LLVM 24.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 "VectorizeOptions.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/ScopeExit.h"
22#include "llvm/ADT/Statistic.h"
27#include "llvm/Analysis/Loads.h"
32#include "llvm/IR/Dominators.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/IRBuilder.h"
42#include <numeric>
43#include <optional>
44#include <queue>
45#include <set>
46
47#define DEBUG_TYPE "vector-combine"
49
50using namespace llvm;
51using namespace llvm::PatternMatch;
52
53STATISTIC(NumVecLoad, "Number of vector loads formed");
54STATISTIC(NumVecCmp, "Number of vector compares formed");
55STATISTIC(NumVecBO, "Number of vector binops formed");
56STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed");
57STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
58STATISTIC(NumScalarOps, "Number of scalar unary + binary ops formed");
59STATISTIC(NumScalarCmp, "Number of scalar compares formed");
60STATISTIC(NumScalarIntrinsic, "Number of scalar intrinsic calls formed");
61
62static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max();
63
64namespace {
65class VectorCombine {
66public:
67 VectorCombine(const VectorizeOptions &Opts, Function &F,
68 const TargetTransformInfo &TTI, const DominatorTree &DT,
70 TTI::TargetCostKind CostKind, bool TryEarlyFoldsOnly)
71 : Opts(Opts), F(F),
72 Builder(*F.getParent(), InstSimplifyFolder(*DL),
74 // Automatically add newly created instructions
75 // into the deferred queue.
76 Worklist.add(I);
77 })),
78 TTI(TTI), DT(DT), AA(AA), DL(DL), CostKind(CostKind),
79 SQ(*DL, /*TLI=*/nullptr, &DT, &AC),
80 TryEarlyFoldsOnly(TryEarlyFoldsOnly) {}
81
82 bool run();
83
84private:
85 const VectorizeOptions &Opts;
86 Function &F;
87 IRBuilder<InstSimplifyFolder, IRBuilderCallbackInserter> Builder;
88 const TargetTransformInfo &TTI;
89 const DominatorTree &DT;
90 AAResults &AA;
91 const DataLayout *DL;
92 TTI::TargetCostKind CostKind;
93 const SimplifyQuery SQ;
94
95 /// If true, only perform beneficial early IR transforms. Do not introduce new
96 /// vector operations.
97 bool TryEarlyFoldsOnly;
98
99 InstructionWorklist Worklist;
100
101 /// Next instruction to iterate. It will be updated when it is erased by
102 /// RecursivelyDeleteTriviallyDeadInstructions.
103 Instruction *NextInst;
104
105 // TODO: Direct calls from the top-level "run" loop use a plain "Instruction"
106 // parameter. That should be updated to specific sub-classes because the
107 // run loop was changed to dispatch on opcode.
108 bool vectorizeLoadInsert(Instruction &I);
109 bool widenSubvectorLoad(Instruction &I);
110 ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0,
111 ExtractElementInst *Ext1,
112 unsigned PreferredExtractIndex) const;
113 bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
114 const Instruction &I,
115 ExtractElementInst *&ConvertToShuffle,
116 unsigned PreferredExtractIndex);
117 Value *foldExtExtCmp(Value *V0, Value *V1, Value *ExtIndex, Instruction &I);
118 Value *foldExtExtBinop(Value *V0, Value *V1, Value *ExtIndex, Instruction &I);
119 bool foldExtractExtract(Instruction &I);
120 bool foldInsExtFNeg(Instruction &I);
121 bool foldInsExtBinop(Instruction &I);
122 bool foldInsExtVectorToShuffle(Instruction &I);
123 bool foldInsertScalarPartsToShuffle(Instruction &I);
124 bool foldBitOpOfCastops(Instruction &I);
125 bool foldBitOpOfCastConstant(Instruction &I);
126 bool foldBitcastShuffle(Instruction &I);
127 bool scalarizeOpOrCmp(Instruction &I);
128 bool foldExtractedCmps(Instruction &I);
129 bool foldSelectsFromBitcast(Instruction &I);
130 bool foldBinopOfReductions(Instruction &I);
131 bool foldInsertElementsToStores(Instruction &I);
132 bool scalarizeLoad(Instruction &I);
133 bool scalarizeLoadExtract(LoadInst *LI, VectorType *VecTy, Value *Ptr);
134 bool scalarizeLoadBitcast(LoadInst *LI, VectorType *VecTy, Value *Ptr);
135 bool scalarizeExtExtract(Instruction &I);
136 bool foldConcatOfBoolMasks(Instruction &I);
137 bool foldPermuteOfBinops(Instruction &I);
138 bool foldShuffleOfBinops(Instruction &I);
139 bool foldShuffleOfSelects(Instruction &I);
140 bool foldShuffleOfCastops(Instruction &I);
141 bool foldShuffleOfShuffles(Instruction &I);
142 bool foldShuffleOfAdjacentLoads(Instruction &I);
143 bool foldPermuteOfIntrinsic(Instruction &I);
144 bool foldShufflesOfLengthChangingShuffles(Instruction &I);
145 bool foldShuffleOfIntrinsics(Instruction &I);
146 bool foldShuffleToIdentity(Instruction &I);
147 bool foldShuffleFromReductions(Instruction &I);
148 bool foldShuffleChainsToReduce(Instruction &I);
149 bool foldCastFromReductions(Instruction &I);
150 bool foldSignBitReductionCmp(Instruction &I);
151 bool foldReductionZeroTest(Instruction &I);
152 bool foldICmpEqZeroVectorReduce(Instruction &I);
153 bool foldEquivalentReductionCmp(Instruction &I);
154 bool foldReduceAddCmpZero(Instruction &I);
155 bool foldSelectShuffle(Instruction &I, bool FromReduction = false);
156 bool foldInterleaveIntrinsics(Instruction &I);
157 bool foldDeinterleaveIntrinsics(Instruction &I);
158 bool foldBitcastOfVPLoad(Instruction &I);
159 bool foldBitOrderReverseAndSwap(Instruction &I);
160 bool shrinkType(Instruction &I);
161 bool shrinkLoadForShuffles(Instruction &I);
162 bool shrinkPhiOfShuffles(Instruction &I);
163 bool foldInterleaveOfDeinterleaveChains(Instruction &I);
164
165 void replaceValue(Instruction &Old, Value &New, bool Erase = true) {
166 LLVM_DEBUG(dbgs() << "VC: Replacing: " << Old << '\n');
167 LLVM_DEBUG(dbgs() << " With: " << New << '\n');
168 Old.replaceAllUsesWith(&New);
169 if (auto *NewI = dyn_cast<Instruction>(&New)) {
170 New.takeName(&Old);
171 Worklist.pushUsersToWorkList(*NewI);
172 Worklist.pushValue(NewI);
173 }
174 if (Erase && isInstructionTriviallyDead(&Old)) {
175 eraseInstruction(Old);
176 } else {
177 Worklist.push(&Old);
178 }
179 }
180
181 void eraseInstruction(Instruction &I) {
182 LLVM_DEBUG(dbgs() << "VC: Erasing: " << I << '\n');
183 SmallVector<Value *> Ops(I.operands());
184 Worklist.remove(&I);
185 I.eraseFromParent();
186
187 // Push remaining users of the operands and then the operand itself - allows
188 // further folds that were hindered by OneUse limits.
189 SmallPtrSet<Value *, 4> Visited;
190 for (Value *Op : Ops) {
191 if (!Visited.contains(Op)) {
192 if (auto *OpI = dyn_cast<Instruction>(Op)) {
194 OpI, nullptr, nullptr, [&](Value *V) {
195 if (auto *I = dyn_cast<Instruction>(V)) {
196 LLVM_DEBUG(dbgs() << "VC: Erased: " << *I << '\n');
197 Worklist.remove(I);
198 if (I == NextInst)
199 NextInst = NextInst->getNextNode();
200 Visited.insert(I);
201 }
202 }))
203 continue;
204 Worklist.pushUsersToWorkList(*OpI);
205 Worklist.pushValue(OpI);
206 }
207 }
208 }
209 }
210};
211} // namespace
212
213/// Return the source operand of a potentially bitcasted value. If there is no
214/// bitcast, return the input value itself.
216 while (auto *BitCast = dyn_cast<BitCastInst>(V))
217 V = BitCast->getOperand(0);
218 return V;
219}
220
221/// Helper to peek through bitcasts to the same value.
222static bool isEquivBitcast(Value *X, Value *Y) {
223 return X->getType() == Y->getType() &&
225}
226
228 // Do not widen load if atomic/volatile or under asan/hwasan/memtag/tsan.
229 // The widened load may load data from dirty regions or create data races
230 // non-existent in the source.
231 if (!Load || !Load->isSimple() || !Load->hasOneUse() ||
232 Load->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag) ||
234 return false;
235
236 // We are potentially transforming byte-sized (8-bit) memory accesses, so make
237 // sure we have all of our type-based constraints in place for this target.
238 Type *ScalarTy = Load->getType()->getScalarType();
239 uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
240 unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
241 if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0 ||
242 ScalarSize % 8 != 0)
243 return false;
244
245 return true;
246}
247
248bool VectorCombine::vectorizeLoadInsert(Instruction &I) {
249 // Match insert into fixed vector of scalar value.
250 // TODO: Handle non-zero insert index.
251 Value *Scalar;
252 if (!match(&I,
254 return false;
255
256 // Optionally match an extract from another vector.
257 Value *X;
258 bool HasExtract = match(Scalar, m_ExtractElt(m_Value(X), m_ZeroInt()));
259 if (!HasExtract)
260 X = Scalar;
261
262 auto *Load = dyn_cast<LoadInst>(X);
263 if (!canWidenLoad(Load, TTI))
264 return false;
265
266 Type *ScalarTy = Scalar->getType();
267 uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
268 unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
269
270 // Check safety of replacing the scalar load with a larger vector load.
271 // We use minimal alignment (maximum flexibility) because we only care about
272 // the dereferenceable region. When calculating cost and creating a new op,
273 // we may use a larger value based on alignment attributes.
274 Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
275 assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
276
277 unsigned MinVecNumElts = MinVectorSize / ScalarSize;
278 auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts, false);
279 unsigned OffsetEltIndex = 0;
280 Align Alignment = Load->getAlign();
281 // Ignore frees because the existing load proves that the object has not been
282 // freed. Allocations cannot shrink, so this is sufficient.
283 if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1),
285 /*IgnoreFree=*/true)) {
286 // It is not safe to load directly from the pointer, but we can still peek
287 // through gep offsets and check if it safe to load from a base address with
288 // updated alignment. If it is, we can shuffle the element(s) into place
289 // after loading.
290 unsigned OffsetBitWidth = DL->getIndexTypeSizeInBits(SrcPtr->getType());
291 APInt Offset(OffsetBitWidth, 0);
293
294 // We want to shuffle the result down from a high element of a vector, so
295 // the offset must be positive.
296 if (Offset.isNegative())
297 return false;
298
299 // The offset must be a multiple of the scalar element to shuffle cleanly
300 // in the element's size.
301 uint64_t ScalarSizeInBytes = ScalarSize / 8;
302 if (Offset.urem(ScalarSizeInBytes) != 0)
303 return false;
304
305 // If we load MinVecNumElts, will our target element still be loaded?
306 APInt OffsetEltIndexAP = Offset.udiv(ScalarSizeInBytes);
307 if (OffsetEltIndexAP.uge(MinVecNumElts))
308 return false;
309 OffsetEltIndex = OffsetEltIndexAP.getZExtValue();
310
311 if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1),
313 /*IgnoreFree=*/true))
314 return false;
315
316 // Update alignment with offset value. Note that the offset could be negated
317 // to more accurately represent "(new) SrcPtr - Offset = (old) SrcPtr", but
318 // negation does not change the result of the alignment calculation.
319 Alignment = commonAlignment(Alignment, Offset.getZExtValue());
320 }
321
322 // Original pattern: insertelt undef, load [free casts of] PtrOp, 0
323 // Use the greater of the alignment on the load or its source pointer.
324 Alignment = std::max(SrcPtr->getPointerAlignment(*DL), Alignment);
325 Type *LoadTy = Load->getType();
326 unsigned AS = Load->getPointerAddressSpace();
327 InstructionCost OldCost =
328 TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS, CostKind);
329 APInt DemandedElts = APInt::getOneBitSet(MinVecNumElts, 0);
330 OldCost +=
331 TTI.getScalarizationOverhead(MinVecTy, DemandedElts,
332 /* Insert */ true, HasExtract, CostKind);
333
334 // New pattern: load VecPtr
335 InstructionCost NewCost =
336 TTI.getMemoryOpCost(Instruction::Load, MinVecTy, Alignment, AS, CostKind);
337 // Optionally, we are shuffling the loaded vector element(s) into place.
338 // For the mask set everything but element 0 to undef to prevent poison from
339 // propagating from the extra loaded memory. This will also optionally
340 // shrink/grow the vector from the loaded size to the output size.
341 // We assume this operation has no cost in codegen if there was no offset.
342 // Note that we could use freeze to avoid poison problems, but then we might
343 // still need a shuffle to change the vector size.
344 auto *Ty = cast<FixedVectorType>(I.getType());
345 unsigned OutputNumElts = Ty->getNumElements();
346 SmallVector<int, 16> Mask(OutputNumElts, PoisonMaskElem);
347 assert(OffsetEltIndex < MinVecNumElts && "Address offset too big");
348 Mask[0] = OffsetEltIndex;
349 if (OffsetEltIndex)
350 NewCost += TTI.getShuffleCost(TTI::SK_PermuteSingleSrc, Ty, MinVecTy,
351 CostKind, Mask);
352
353 // We can aggressively convert to the vector form because the backend can
354 // invert this transform if it does not result in a performance win.
355 if (OldCost < NewCost || !NewCost.isValid())
356 return false;
357
358 // It is safe and potentially profitable to load a vector directly:
359 // inselt undef, load Scalar, 0 --> load VecPtr
360 Builder.SetInsertPoint(Load);
361 Value *CastedPtr =
362 Builder.CreatePointerBitCastOrAddrSpaceCast(SrcPtr, Builder.getPtrTy(AS));
363 Value *VecLd = Builder.CreateAlignedLoad(MinVecTy, CastedPtr, Alignment);
364 VecLd = Builder.CreateShuffleVector(VecLd, Mask);
365
366 replaceValue(I, *VecLd);
367 ++NumVecLoad;
368 return true;
369}
370
371/// If we are loading a vector and then inserting it into a larger vector with
372/// undefined elements, try to load the larger vector and eliminate the insert.
373/// This removes a shuffle in IR and may allow combining of other loaded values.
374bool VectorCombine::widenSubvectorLoad(Instruction &I) {
375 // Match subvector insert of fixed vector.
376 auto *Shuf = cast<ShuffleVectorInst>(&I);
377 if (!Shuf->isIdentityWithPadding())
378 return false;
379
380 // Allow a non-canonical shuffle mask that is choosing elements from op1.
381 unsigned NumOpElts =
382 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
383 unsigned OpIndex = any_of(Shuf->getShuffleMask(), [&NumOpElts](int M) {
384 return M >= (int)(NumOpElts);
385 });
386
387 auto *Load = dyn_cast<LoadInst>(Shuf->getOperand(OpIndex));
388 if (!canWidenLoad(Load, TTI))
389 return false;
390
391 // We use minimal alignment (maximum flexibility) because we only care about
392 // the dereferenceable region. When calculating cost and creating a new op,
393 // we may use a larger value based on alignment attributes.
394 auto *Ty = cast<FixedVectorType>(I.getType());
395 Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
396 assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
397 Align Alignment = Load->getAlign();
398 // Ignore frees because the existing load proves that the object has not been
399 // freed. Allocations cannot shrink, so this is sufficient.
400 if (!isSafeToLoadUnconditionally(SrcPtr, Ty, Align(1),
402 /*IgnoreFree=*/true))
403 return false;
404
405 Alignment = std::max(SrcPtr->getPointerAlignment(*DL), Alignment);
406 Type *LoadTy = Load->getType();
407 unsigned AS = Load->getPointerAddressSpace();
408
409 // Original pattern: insert_subvector (load PtrOp)
410 // This conservatively assumes that the cost of a subvector insert into an
411 // undef value is 0. We could add that cost if the cost model accurately
412 // reflects the real cost of that operation.
413 InstructionCost OldCost =
414 TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS, CostKind);
415
416 // New pattern: load PtrOp
417 InstructionCost NewCost =
418 TTI.getMemoryOpCost(Instruction::Load, Ty, Alignment, AS, CostKind);
419
420 // We can aggressively convert to the vector form because the backend can
421 // invert this transform if it does not result in a performance win.
422 if (OldCost < NewCost || !NewCost.isValid())
423 return false;
424
425 Builder.SetInsertPoint(Load);
426 Value *CastedPtr =
427 Builder.CreatePointerBitCastOrAddrSpaceCast(SrcPtr, Builder.getPtrTy(AS));
428 Value *VecLd = Builder.CreateAlignedLoad(Ty, CastedPtr, Alignment);
429 replaceValue(I, *VecLd);
430 ++NumVecLoad;
431 return true;
432}
433
434/// Determine which, if any, of the inputs should be replaced by a shuffle
435/// followed by extract from a different index.
436ExtractElementInst *VectorCombine::getShuffleExtract(
437 ExtractElementInst *Ext0, ExtractElementInst *Ext1,
438 unsigned PreferredExtractIndex = InvalidIndex) const {
439 auto *Index0C = dyn_cast<ConstantInt>(Ext0->getIndexOperand());
440 auto *Index1C = dyn_cast<ConstantInt>(Ext1->getIndexOperand());
441 assert(Index0C && Index1C && "Expected constant extract indexes");
442
443 unsigned Index0 = Index0C->getZExtValue();
444 unsigned Index1 = Index1C->getZExtValue();
445
446 // If the extract indexes are identical, no shuffle is needed.
447 if (Index0 == Index1)
448 return nullptr;
449
450 Type *VecTy = Ext0->getVectorOperand()->getType();
451 assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types");
452 InstructionCost Cost0 =
453 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Index0);
454 InstructionCost Cost1 =
455 TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Index1);
456
457 // If both costs are invalid no shuffle is needed
458 if (!Cost0.isValid() && !Cost1.isValid())
459 return nullptr;
460
461 // We are extracting from 2 different indexes, so one operand must be shuffled
462 // before performing a vector operation and/or extract. The more expensive
463 // extract will be replaced by a shuffle.
464 if (Cost0 > Cost1)
465 return Ext0;
466 if (Cost1 > Cost0)
467 return Ext1;
468
469 // If the costs are equal and there is a preferred extract index, shuffle the
470 // opposite operand.
471 if (PreferredExtractIndex == Index0)
472 return Ext1;
473 if (PreferredExtractIndex == Index1)
474 return Ext0;
475
476 // Otherwise, replace the extract with the higher index.
477 return Index0 > Index1 ? Ext0 : Ext1;
478}
479
480/// Compare the relative costs of 2 extracts followed by scalar operation vs.
481/// vector operation(s) followed by extract. Return true if the existing
482/// instructions are cheaper than a vector alternative. Otherwise, return false
483/// and if one of the extracts should be transformed to a shufflevector, set
484/// \p ConvertToShuffle to that extract instruction.
485bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0,
486 ExtractElementInst *Ext1,
487 const Instruction &I,
488 ExtractElementInst *&ConvertToShuffle,
489 unsigned PreferredExtractIndex) {
490 auto *Ext0IndexC = dyn_cast<ConstantInt>(Ext0->getIndexOperand());
491 auto *Ext1IndexC = dyn_cast<ConstantInt>(Ext1->getIndexOperand());
492 assert(Ext0IndexC && Ext1IndexC && "Expected constant extract indexes");
493
494 unsigned Opcode = I.getOpcode();
495 Value *Ext0Src = Ext0->getVectorOperand();
496 Value *Ext1Src = Ext1->getVectorOperand();
497 Type *ScalarTy = Ext0->getType();
498 auto *VecTy = cast<VectorType>(Ext0Src->getType());
499 InstructionCost ScalarOpCost, VectorOpCost;
500
501 // Get cost estimates for scalar and vector versions of the operation.
502 bool IsBinOp = Instruction::isBinaryOp(Opcode);
503 if (IsBinOp) {
504 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy, CostKind);
505 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy, CostKind);
506 } else {
507 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
508 "Expected a compare");
509 CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
510 ScalarOpCost = TTI.getCmpSelInstrCost(
511 Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred, CostKind);
512 VectorOpCost = TTI.getCmpSelInstrCost(
513 Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred, CostKind);
514 }
515
516 // Get cost estimates for the extract elements. These costs will factor into
517 // both sequences.
518 unsigned Ext0Index = Ext0IndexC->getZExtValue();
519 unsigned Ext1Index = Ext1IndexC->getZExtValue();
520
521 InstructionCost Extract0Cost =
522 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Ext0Index);
523 InstructionCost Extract1Cost =
524 TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Ext1Index);
525
526 // A more expensive extract will always be replaced by a splat shuffle.
527 // For example, if Ext0 is more expensive:
528 // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
529 // extelt (opcode (splat V0, Ext0), V1), Ext1
530 // TODO: Evaluate whether that always results in lowest cost. Alternatively,
531 // check the cost of creating a broadcast shuffle and shuffling both
532 // operands to element 0.
533 unsigned BestExtIndex = Extract0Cost > Extract1Cost ? Ext0Index : Ext1Index;
534 unsigned BestInsIndex = Extract0Cost > Extract1Cost ? Ext1Index : Ext0Index;
535 InstructionCost CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
536
537 // Extra uses of the extracts mean that we include those costs in the
538 // vector total because those instructions will not be eliminated.
539 InstructionCost OldCost, NewCost;
540 if (Ext0Src == Ext1Src && Ext0Index == Ext1Index) {
541 // Handle a special case. If the 2 extracts are identical, adjust the
542 // formulas to account for that. The extra use charge allows for either the
543 // CSE'd pattern or an unoptimized form with identical values:
544 // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
545 bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
546 : !Ext0->hasOneUse() || !Ext1->hasOneUse();
547 OldCost = CheapExtractCost + ScalarOpCost;
548 NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
549 } else {
550 // Handle the general case. Each extract is actually a different value:
551 // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
552 OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
553 NewCost = VectorOpCost + CheapExtractCost +
554 !Ext0->hasOneUse() * Extract0Cost +
555 !Ext1->hasOneUse() * Extract1Cost;
556 }
557
558 ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex);
559 if (ConvertToShuffle) {
560 if (IsBinOp && Opts.disable_binop_extract_shuffle)
561 return true;
562
563 // If we are extracting from 2 different indexes, then one operand must be
564 // shuffled before performing the vector operation. The shuffle mask is
565 // poison except for 1 lane that is being translated to the remaining
566 // extraction lane. Therefore, it is a splat shuffle. Ex:
567 // ShufMask = { poison, poison, 0, poison }
568 // TODO: The cost model has an option for a "broadcast" shuffle
569 // (splat-from-element-0), but no option for a more general splat.
570 if (auto *FixedVecTy = dyn_cast<FixedVectorType>(VecTy)) {
571 SmallVector<int> ShuffleMask(FixedVecTy->getNumElements(),
573 ShuffleMask[BestInsIndex] = BestExtIndex;
575 VecTy, VecTy, CostKind, ShuffleMask, 0,
576 nullptr, {ConvertToShuffle});
577 } else {
579 VecTy, VecTy, CostKind, {}, 0, nullptr,
580 {ConvertToShuffle});
581 }
582 }
583
584 LLVM_DEBUG(dbgs() << "Found a binop of extractions: " << I << "\n OldCost: "
585 << OldCost << " vs NewCost: " << NewCost << "\n");
586
587 // Aggressively form a vector op if the cost is equal because the transform
588 // may enable further optimization.
589 // Codegen can reverse this transform (scalarize) if it was not profitable.
590 return OldCost < NewCost;
591}
592
593/// Create a shuffle that translates (shifts) 1 element from the input vector
594/// to a new element location.
595static Value *createShiftShuffle(Value *Vec, unsigned OldIndex,
596 unsigned NewIndex, IRBuilderBase &Builder) {
597 // The shuffle mask is poison except for 1 lane that is being translated
598 // to the new element index. Example for OldIndex == 2 and NewIndex == 0:
599 // ShufMask = { 2, poison, poison, poison }
600 auto *VecTy = cast<FixedVectorType>(Vec->getType());
601 SmallVector<int, 32> ShufMask(VecTy->getNumElements(), PoisonMaskElem);
602 ShufMask[NewIndex] = OldIndex;
603 return Builder.CreateShuffleVector(Vec, ShufMask, "shift");
604}
605
606/// Given an extract element instruction with constant index operand, shuffle
607/// the source vector (shift the scalar element) to a NewIndex for extraction.
608/// Return null if the input can be constant folded, so that we are not creating
609/// unnecessary instructions.
610static Value *translateExtract(ExtractElementInst *ExtElt, unsigned NewIndex,
611 IRBuilderBase &Builder) {
612 // Shufflevectors can only be created for fixed-width vectors.
613 Value *X = ExtElt->getVectorOperand();
614 if (!isa<FixedVectorType>(X->getType()))
615 return nullptr;
616
617 // If the extract can be constant-folded, this code is unsimplified. Defer
618 // to other passes to handle that.
619 Value *C = ExtElt->getIndexOperand();
620 assert(isa<ConstantInt>(C) && "Expected a constant index operand");
621 if (isa<Constant>(X))
622 return nullptr;
623
624 Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(),
625 NewIndex, Builder);
626 return Shuf;
627}
628
629/// Try to reduce extract element costs by converting scalar compares to vector
630/// compares followed by extract.
631/// cmp (ext0 V0, ExtIndex), (ext1 V1, ExtIndex)
632Value *VectorCombine::foldExtExtCmp(Value *V0, Value *V1, Value *ExtIndex,
633 Instruction &I) {
634 assert(isa<CmpInst>(&I) && "Expected a compare");
635
636 // cmp Pred (extelt V0, ExtIndex), (extelt V1, ExtIndex)
637 // --> extelt (cmp Pred V0, V1), ExtIndex
638 ++NumVecCmp;
639 CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
640 Value *VecCmp = Builder.CreateCmp(Pred, V0, V1);
641 return Builder.CreateExtractElement(VecCmp, ExtIndex, "foldExtExtCmp");
642}
643
644/// Try to reduce extract element costs by converting scalar binops to vector
645/// binops followed by extract.
646/// bo (ext0 V0, ExtIndex), (ext1 V1, ExtIndex)
647Value *VectorCombine::foldExtExtBinop(Value *V0, Value *V1, Value *ExtIndex,
648 Instruction &I) {
649 assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
650
651 // bo (extelt V0, ExtIndex), (extelt V1, ExtIndex)
652 // --> extelt (bo V0, V1), ExtIndex
653 ++NumVecBO;
654 Value *VecBO = Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0,
655 V1, "foldExtExtBinop");
656
657 // All IR flags are safe to back-propagate because any potential poison
658 // created in unused vector elements is discarded by the extract.
659 if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
660 VecBOInst->copyIRFlags(&I);
661
662 return Builder.CreateExtractElement(VecBO, ExtIndex, "foldExtExtBinop");
663}
664
665/// Match an instruction with extracted vector operands.
666bool VectorCombine::foldExtractExtract(Instruction &I) {
667 // It is not safe to transform things like div, urem, etc. because we may
668 // create undefined behavior when executing those on unknown vector elements.
670 return false;
671
672 Instruction *I0, *I1;
673 CmpPredicate Pred = CmpInst::BAD_ICMP_PREDICATE;
674 if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) &&
676 return false;
677
678 Value *V0, *V1;
679 uint64_t C0, C1;
680 if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
682 V0->getType() != V1->getType())
683 return false;
684
685 // For fixed-width vectors, reject out-of-bounds extract indexes
686 if (auto *FixedVecTy = dyn_cast<FixedVectorType>(V0->getType())) {
687 unsigned NumElts = FixedVecTy->getNumElements();
688 if (C0 >= NumElts || C1 >= NumElts)
689 return false;
690 }
691
692 // If the scalar value 'I' is going to be re-inserted into a vector, then try
693 // to create an extract to that same element. The extract/insert can be
694 // reduced to a "select shuffle".
695 // TODO: If we add a larger pattern match that starts from an insert, this
696 // probably becomes unnecessary.
697 auto *Ext0 = cast<ExtractElementInst>(I0);
698 auto *Ext1 = cast<ExtractElementInst>(I1);
699 uint64_t InsertIndex = InvalidIndex;
700 if (I.hasOneUse())
701 match(I.user_back(),
702 m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
703
704 ExtractElementInst *ExtractToChange;
705 if (isExtractExtractCheap(Ext0, Ext1, I, ExtractToChange, InsertIndex))
706 return false;
707
708 Value *ExtOp0 = Ext0->getVectorOperand();
709 Value *ExtOp1 = Ext1->getVectorOperand();
710
711 if (ExtractToChange) {
712 unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0;
713 Value *NewExtOp =
714 translateExtract(ExtractToChange, CheapExtractIdx, Builder);
715 if (!NewExtOp)
716 return false;
717 if (ExtractToChange == Ext0)
718 ExtOp0 = NewExtOp;
719 else
720 ExtOp1 = NewExtOp;
721 }
722
723 Value *ExtIndex = ExtractToChange == Ext0 ? Ext1->getIndexOperand()
724 : Ext0->getIndexOperand();
726 ? foldExtExtCmp(ExtOp0, ExtOp1, ExtIndex, I)
727 : foldExtExtBinop(ExtOp0, ExtOp1, ExtIndex, I);
728 replaceValue(I, *NewExt);
729 return true;
730}
731
732/// Try to replace an extract + scalar fneg + insert with a vector fneg +
733/// shuffle.
734bool VectorCombine::foldInsExtFNeg(Instruction &I) {
735 // Match an insert (op (extract)) pattern.
736 Value *DstVec;
737 uint64_t ExtIdx, InsIdx;
738 Instruction *FNeg;
739 if (!match(&I, m_InsertElt(m_Value(DstVec), m_OneUse(m_Instruction(FNeg)),
740 m_ConstantInt(InsIdx))))
741 return false;
742
743 // Note: This handles the canonical fneg instruction and "fsub -0.0, X".
744 Value *SrcVec;
745 Instruction *Extract;
746 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
748 m_Instruction(Extract),
749 m_ExtractElt(m_Value(SrcVec), m_ConstantInt(ExtIdx))))))
750 return false;
751
752 auto *DstVecTy = cast<FixedVectorType>(DstVec->getType());
753 auto *DstVecScalarTy = DstVecTy->getScalarType();
754 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcVec->getType());
755 if (!SrcVecTy || DstVecScalarTy != SrcVecTy->getScalarType())
756 return false;
757
758 // Ignore if insert/extract index is out of bounds or destination vector has
759 // one element
760 unsigned NumDstElts = DstVecTy->getNumElements();
761 unsigned NumSrcElts = SrcVecTy->getNumElements();
762 if (ExtIdx > NumSrcElts || InsIdx >= NumDstElts || NumDstElts == 1)
763 return false;
764
765 // We are inserting the negated element into the same lane that we extracted
766 // from. This is equivalent to a select-shuffle that chooses all but the
767 // negated element from the destination vector.
768 SmallVector<int> Mask(NumDstElts);
769 std::iota(Mask.begin(), Mask.end(), 0);
770 Mask[InsIdx] = (ExtIdx % NumDstElts) + NumDstElts;
771 InstructionCost OldCost =
772 TTI.getArithmeticInstrCost(Instruction::FNeg, DstVecScalarTy, CostKind) +
773 TTI.getVectorInstrCost(I, DstVecTy, CostKind, InsIdx);
774
775 // If the extract has one use, it will be eliminated, so count it in the
776 // original cost. If it has more than one use, ignore the cost because it will
777 // be the same before/after.
778 if (Extract->hasOneUse())
779 OldCost += TTI.getVectorInstrCost(*Extract, SrcVecTy, CostKind, ExtIdx);
780
781 InstructionCost NewCost =
782 TTI.getArithmeticInstrCost(Instruction::FNeg, SrcVecTy, CostKind) +
784 DstVecTy, CostKind, Mask);
785
786 bool NeedLenChg = SrcVecTy->getNumElements() != NumDstElts;
787 // If the lengths of the two vectors are not equal,
788 // we need to add a length-change vector. Add this cost.
789 SmallVector<int> SrcMask;
790 if (NeedLenChg) {
791 SrcMask.assign(NumDstElts, PoisonMaskElem);
792 SrcMask[ExtIdx % NumDstElts] = ExtIdx;
794 DstVecTy, SrcVecTy, CostKind, SrcMask);
795 }
796
797 LLVM_DEBUG(dbgs() << "Found an insertion of (extract)fneg : " << I
798 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
799 << "\n");
800 if (NewCost > OldCost)
801 return false;
802
803 Value *NewShuf, *LenChgShuf = nullptr;
804 // insertelt DstVec, (fneg (extractelt SrcVec, Index)), Index
805 Value *VecFNeg = Builder.CreateFNegFMF(SrcVec, FNeg);
806 if (NeedLenChg) {
807 // shuffle DstVec, (shuffle (fneg SrcVec), poison, SrcMask), Mask
808 LenChgShuf = Builder.CreateShuffleVector(VecFNeg, SrcMask);
809 NewShuf = Builder.CreateShuffleVector(DstVec, LenChgShuf, Mask);
810 } else {
811 // shuffle DstVec, (fneg SrcVec), Mask
812 NewShuf = Builder.CreateShuffleVector(DstVec, VecFNeg, Mask);
813 }
814
815 replaceValue(I, *NewShuf);
816 return true;
817}
818
819/// Try to fold insert(binop(x,y),binop(a,b),idx)
820/// --> binop(insert(x,a,idx),insert(y,b,idx))
821bool VectorCombine::foldInsExtBinop(Instruction &I) {
822 BinaryOperator *VecBinOp, *SclBinOp;
824 if (!match(&I,
825 m_InsertElt(m_OneUse(m_BinOp(VecBinOp)),
826 m_OneUse(m_BinOp(SclBinOp)), m_ConstantInt(Index))))
827 return false;
828
829 // TODO: Add support for addlike etc.
830 Instruction::BinaryOps BinOpcode = VecBinOp->getOpcode();
831 if (BinOpcode != SclBinOp->getOpcode())
832 return false;
833
834 auto *ResultTy = dyn_cast<FixedVectorType>(I.getType());
835 if (!ResultTy)
836 return false;
837
838 // TODO: Attempt to detect m_ExtractElt for scalar operands and convert to
839 // shuffle?
840
841 InstructionCost OldCost = TTI.getInstructionCost(&I, CostKind) +
842 TTI.getInstructionCost(VecBinOp, CostKind) +
843 TTI.getInstructionCost(SclBinOp, CostKind);
844 InstructionCost NewCost =
845 TTI.getArithmeticInstrCost(BinOpcode, ResultTy, CostKind) +
846 TTI.getVectorInstrCost(Instruction::InsertElement, ResultTy, CostKind,
847 Index, VecBinOp->getOperand(0),
848 SclBinOp->getOperand(0)) +
849 TTI.getVectorInstrCost(Instruction::InsertElement, ResultTy, CostKind,
850 Index, VecBinOp->getOperand(1),
851 SclBinOp->getOperand(1));
852
853 LLVM_DEBUG(dbgs() << "Found an insertion of two binops: " << I
854 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
855 << "\n");
856 if (NewCost > OldCost)
857 return false;
858
859 Value *NewIns0 = Builder.CreateInsertElement(VecBinOp->getOperand(0),
860 SclBinOp->getOperand(0), Index);
861 Value *NewIns1 = Builder.CreateInsertElement(VecBinOp->getOperand(1),
862 SclBinOp->getOperand(1), Index);
863 Value *NewBO = Builder.CreateBinOp(BinOpcode, NewIns0, NewIns1);
864
865 // Intersect flags from the old binops.
866 if (auto *NewInst = dyn_cast<Instruction>(NewBO)) {
867 NewInst->copyIRFlags(VecBinOp);
868 NewInst->andIRFlags(SclBinOp);
869 }
870
871 replaceValue(I, *NewBO);
872 return true;
873}
874
875/// Match: bitop(castop(x), castop(y)) -> castop(bitop(x, y))
876/// Supports: bitcast, trunc, sext, zext
877bool VectorCombine::foldBitOpOfCastops(Instruction &I) {
878 // Check if this is a bitwise logic operation
879 auto *BinOp = dyn_cast<BinaryOperator>(&I);
880 if (!BinOp || !BinOp->isBitwiseLogicOp())
881 return false;
882
883 // Get the cast instructions
884 auto *LHSCast = dyn_cast<CastInst>(BinOp->getOperand(0));
885 auto *RHSCast = dyn_cast<CastInst>(BinOp->getOperand(1));
886 if (!LHSCast || !RHSCast) {
887 LLVM_DEBUG(dbgs() << " One or both operands are not cast instructions\n");
888 return false;
889 }
890
891 // Both casts must be the same type
892 Instruction::CastOps CastOpcode = LHSCast->getOpcode();
893 if (CastOpcode != RHSCast->getOpcode())
894 return false;
895
896 // Only handle supported cast operations
897 switch (CastOpcode) {
898 case Instruction::BitCast:
899 case Instruction::Trunc:
900 case Instruction::SExt:
901 case Instruction::ZExt:
902 break;
903 default:
904 return false;
905 }
906
907 Value *LHSSrc = LHSCast->getOperand(0);
908 Value *RHSSrc = RHSCast->getOperand(0);
909
910 // Source types must match
911 if (LHSSrc->getType() != RHSSrc->getType())
912 return false;
913
914 auto *SrcTy = LHSSrc->getType();
915 auto *DstTy = I.getType();
916 // Bitcasts can handle scalar/vector mixes, such as i16 -> <16 x i1>.
917 // Other casts only handle vector types with integer elements.
918 if (CastOpcode != Instruction::BitCast &&
919 (!isa<FixedVectorType>(SrcTy) || !isa<FixedVectorType>(DstTy)))
920 return false;
921
922 // Only integer scalar/vector values are legal for bitwise logic operations.
923 if (!SrcTy->getScalarType()->isIntegerTy() ||
924 !DstTy->getScalarType()->isIntegerTy())
925 return false;
926
927 // Cost Check :
928 // OldCost = bitlogic + 2*casts
929 // NewCost = bitlogic + cast
930
931 // Calculate specific costs for each cast with instruction context
933 CastOpcode, DstTy, SrcTy, TTI::CastContextHint::None, CostKind, LHSCast);
935 CastOpcode, DstTy, SrcTy, TTI::CastContextHint::None, CostKind, RHSCast);
936
937 InstructionCost OldCost =
938 TTI.getArithmeticInstrCost(BinOp->getOpcode(), DstTy, CostKind) +
939 LHSCastCost + RHSCastCost;
940
941 // For new cost, we can't provide an instruction (it doesn't exist yet)
942 InstructionCost GenericCastCost = TTI.getCastInstrCost(
943 CastOpcode, DstTy, SrcTy, TTI::CastContextHint::None, CostKind);
944
945 InstructionCost NewCost =
946 TTI.getArithmeticInstrCost(BinOp->getOpcode(), SrcTy, CostKind) +
947 GenericCastCost;
948
949 // Account for multi-use casts using specific costs
950 if (!LHSCast->hasOneUse())
951 NewCost += LHSCastCost;
952 if (!RHSCast->hasOneUse())
953 NewCost += RHSCastCost;
954
955 LLVM_DEBUG(dbgs() << "foldBitOpOfCastops: OldCost=" << OldCost
956 << " NewCost=" << NewCost << "\n");
957
958 if (NewCost > OldCost)
959 return false;
960
961 // Create the operation on the source type
962 Value *NewOp = Builder.CreateBinOp(BinOp->getOpcode(), LHSSrc, RHSSrc,
963 BinOp->getName() + ".inner");
964 if (auto *NewBinOp = dyn_cast<BinaryOperator>(NewOp))
965 NewBinOp->copyIRFlags(BinOp);
966
967 // Create the cast operation directly to ensure we get a new instruction
968 Instruction *NewCast = CastInst::Create(CastOpcode, NewOp, I.getType());
969
970 // Preserve cast instruction flags
971 NewCast->copyIRFlags(LHSCast);
972 NewCast->andIRFlags(RHSCast);
973
974 // Insert the new instruction
975 Value *Result = Builder.Insert(NewCast);
976
977 replaceValue(I, *Result);
978 return true;
979}
980
981/// Match:
982// bitop(castop(x), C) ->
983// bitop(castop(x), castop(InvC)) ->
984// castop(bitop(x, InvC))
985// Supports: bitcast
986bool VectorCombine::foldBitOpOfCastConstant(Instruction &I) {
988 Constant *C;
989
990 // Check if this is a bitwise logic operation
992 return false;
993
994 // Get the cast instructions
995 auto *LHSCast = dyn_cast<CastInst>(LHS);
996 if (!LHSCast)
997 return false;
998
999 Instruction::CastOps CastOpcode = LHSCast->getOpcode();
1000
1001 // Only handle supported cast operations
1002 switch (CastOpcode) {
1003 case Instruction::BitCast:
1004 case Instruction::ZExt:
1005 case Instruction::SExt:
1006 case Instruction::Trunc:
1007 break;
1008 default:
1009 return false;
1010 }
1011
1012 Value *LHSSrc = LHSCast->getOperand(0);
1013
1014 auto *SrcTy = LHSSrc->getType();
1015 auto *DstTy = I.getType();
1016 // Bitcasts can handle scalar/vector mixes, such as i16 -> <16 x i1>.
1017 // Other casts only handle vector types with integer elements.
1018 if (CastOpcode != Instruction::BitCast &&
1019 (!isa<FixedVectorType>(SrcTy) || !isa<FixedVectorType>(DstTy)))
1020 return false;
1021
1022 // Only integer scalar/vector values are legal for bitwise logic operations.
1023 if (!SrcTy->getScalarType()->isIntegerTy() ||
1024 !DstTy->getScalarType()->isIntegerTy())
1025 return false;
1026
1027 // Find the constant InvC, such that castop(InvC) equals to C.
1028 PreservedCastFlags RHSFlags;
1029 Constant *InvC = getLosslessInvCast(C, SrcTy, CastOpcode, *DL, &RHSFlags);
1030 if (!InvC)
1031 return false;
1032
1033 // Cost Check :
1034 // OldCost = bitlogic + cast
1035 // NewCost = bitlogic + cast
1036
1037 // Calculate specific costs for each cast with instruction context
1038 InstructionCost LHSCastCost = TTI.getCastInstrCost(
1039 CastOpcode, DstTy, SrcTy, TTI::CastContextHint::None, CostKind, LHSCast);
1040
1041 InstructionCost OldCost =
1042 TTI.getArithmeticInstrCost(I.getOpcode(), DstTy, CostKind) + LHSCastCost;
1043
1044 // For new cost, we can't provide an instruction (it doesn't exist yet)
1045 InstructionCost GenericCastCost = TTI.getCastInstrCost(
1046 CastOpcode, DstTy, SrcTy, TTI::CastContextHint::None, CostKind);
1047
1048 InstructionCost NewCost =
1049 TTI.getArithmeticInstrCost(I.getOpcode(), SrcTy, CostKind) +
1050 GenericCastCost;
1051
1052 // Account for multi-use casts using specific costs
1053 if (!LHSCast->hasOneUse())
1054 NewCost += LHSCastCost;
1055
1056 LLVM_DEBUG(dbgs() << "foldBitOpOfCastConstant: OldCost=" << OldCost
1057 << " NewCost=" << NewCost << "\n");
1058
1059 if (NewCost > OldCost)
1060 return false;
1061
1062 // Create the operation on the source type
1063 Value *NewOp = Builder.CreateBinOp((Instruction::BinaryOps)I.getOpcode(),
1064 LHSSrc, InvC, I.getName() + ".inner");
1065 if (auto *NewBinOp = dyn_cast<BinaryOperator>(NewOp))
1066 NewBinOp->copyIRFlags(&I);
1067
1068 // Create the cast operation directly to ensure we get a new instruction
1069 Instruction *NewCast = CastInst::Create(CastOpcode, NewOp, I.getType());
1070
1071 // Preserve cast instruction flags
1072 if (RHSFlags.NNeg)
1073 NewCast->setNonNeg();
1074 if (RHSFlags.NUW)
1075 NewCast->setHasNoUnsignedWrap();
1076 if (RHSFlags.NSW)
1077 NewCast->setHasNoSignedWrap();
1078
1079 NewCast->andIRFlags(LHSCast);
1080
1081 // Insert the new instruction
1082 Value *Result = Builder.Insert(NewCast);
1083
1084 replaceValue(I, *Result);
1085 return true;
1086}
1087
1088/// If this is a bitcast of a shuffle, try to bitcast the source vector to the
1089/// destination type followed by shuffle. This can enable further transforms by
1090/// moving bitcasts or shuffles together.
1091bool VectorCombine::foldBitcastShuffle(Instruction &I) {
1092 Value *V0, *V1;
1093 ArrayRef<int> Mask;
1094 if (!match(&I, m_BitCast(m_OneUse(
1095 m_Shuffle(m_Value(V0), m_Value(V1), m_Mask(Mask))))))
1096 return false;
1097
1098 // 1) Do not fold bitcast shuffle for scalable type. First, shuffle cost for
1099 // scalable type is unknown; Second, we cannot reason if the narrowed shuffle
1100 // mask for scalable type is a splat or not.
1101 // 2) Disallow non-vector casts.
1102 // TODO: We could allow any shuffle.
1103 auto *DestTy = dyn_cast<FixedVectorType>(I.getType());
1104 auto *SrcTy = dyn_cast<FixedVectorType>(V0->getType());
1105 if (!DestTy || !SrcTy)
1106 return false;
1107
1108 unsigned DestEltSize = DestTy->getScalarSizeInBits();
1109 unsigned SrcEltSize = SrcTy->getScalarSizeInBits();
1110 if (SrcTy->getPrimitiveSizeInBits() % DestEltSize != 0)
1111 return false;
1112
1113 bool IsUnary = isa<UndefValue>(V1);
1114
1115 // For binary shuffles, only fold bitcast(shuffle(X,Y))
1116 // if it won't increase the number of bitcasts.
1117 if (!IsUnary) {
1120 if (!(BCTy0 && BCTy0->getElementType() == DestTy->getElementType()) &&
1121 !(BCTy1 && BCTy1->getElementType() == DestTy->getElementType()))
1122 return false;
1123 }
1124
1125 SmallVector<int, 16> NewMask;
1126 if (DestEltSize <= SrcEltSize) {
1127 // The bitcast is from wide to narrow/equal elements. The shuffle mask can
1128 // always be expanded to the equivalent form choosing narrower elements.
1129 if (SrcEltSize % DestEltSize != 0)
1130 return false;
1131 unsigned ScaleFactor = SrcEltSize / DestEltSize;
1132 narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
1133 } else {
1134 // The bitcast is from narrow elements to wide elements. The shuffle mask
1135 // must choose consecutive elements to allow casting first.
1136 if (DestEltSize % SrcEltSize != 0)
1137 return false;
1138 unsigned ScaleFactor = DestEltSize / SrcEltSize;
1139 if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
1140 return false;
1141 }
1142
1143 // Bitcast the shuffle src - keep its original width but using the destination
1144 // scalar type.
1145 unsigned NumSrcElts = SrcTy->getPrimitiveSizeInBits() / DestEltSize;
1146 auto *NewShuffleTy =
1147 FixedVectorType::get(DestTy->getScalarType(), NumSrcElts);
1148 auto *OldShuffleTy =
1149 FixedVectorType::get(SrcTy->getScalarType(), Mask.size());
1150 unsigned NumOps = IsUnary ? 1 : 2;
1151
1152 // The new shuffle must not cost more than the old shuffle.
1156
1157 InstructionCost NewCost =
1158 TTI.getShuffleCost(SK, DestTy, NewShuffleTy, CostKind, NewMask) +
1159 (NumOps * TTI.getCastInstrCost(Instruction::BitCast, NewShuffleTy, SrcTy,
1160 TargetTransformInfo::CastContextHint::None,
1161 CostKind));
1162 InstructionCost OldCost =
1163 TTI.getShuffleCost(SK, OldShuffleTy, SrcTy, CostKind, Mask) +
1164 TTI.getCastInstrCost(Instruction::BitCast, DestTy, OldShuffleTy,
1165 TargetTransformInfo::CastContextHint::None,
1166 CostKind);
1167
1168 LLVM_DEBUG(dbgs() << "Found a bitcasted shuffle: " << I << "\n OldCost: "
1169 << OldCost << " vs NewCost: " << NewCost << "\n");
1170
1171 if (NewCost > OldCost || !NewCost.isValid())
1172 return false;
1173
1174 // bitcast (shuf V0, V1, MaskC) --> shuf (bitcast V0), (bitcast V1), MaskC'
1175 ++NumShufOfBitcast;
1176 Value *CastV0 = Builder.CreateBitCast(peekThroughBitcasts(V0), NewShuffleTy);
1177 Value *CastV1 = Builder.CreateBitCast(peekThroughBitcasts(V1), NewShuffleTy);
1178 Value *Shuf = Builder.CreateShuffleVector(CastV0, CastV1, NewMask);
1179 replaceValue(I, *Shuf);
1180 return true;
1181}
1182
1183/// Match a vector op/compare/intrinsic with at least one
1184/// inserted scalar operand and convert to scalar op/cmp/intrinsic followed
1185/// by insertelement.
1186bool VectorCombine::scalarizeOpOrCmp(Instruction &I) {
1187 auto *UO = dyn_cast<UnaryOperator>(&I);
1188 auto *BO = dyn_cast<BinaryOperator>(&I);
1189 auto *CI = dyn_cast<CmpInst>(&I);
1190 auto *II = dyn_cast<IntrinsicInst>(&I);
1191 if (!UO && !BO && !CI && !II)
1192 return false;
1193
1194 // TODO: Allow intrinsics with different argument types
1195 if (II) {
1196 if (!isTriviallyVectorizable(II->getIntrinsicID()))
1197 return false;
1198 for (auto [Idx, Arg] : enumerate(II->args()))
1199 if (Arg->getType() != II->getType() &&
1200 !isVectorIntrinsicWithScalarOpAtArg(II->getIntrinsicID(), Idx, &TTI))
1201 return false;
1202 }
1203
1204 // Do not convert the vector condition of a vector select into a scalar
1205 // condition. That may cause problems for codegen because of differences in
1206 // boolean formats and register-file transfers.
1207 // TODO: Can we account for that in the cost model?
1208 if (CI)
1209 for (User *U : I.users())
1210 if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
1211 return false;
1212
1213 // Match constant vectors or scalars being inserted into constant vectors:
1214 // vec_op [VecC0 | (inselt VecC0, V0, Index)], ...
1215 SmallVector<Value *> VecCs, ScalarOps;
1216 std::optional<uint64_t> Index;
1217
1218 auto Ops = II ? II->args() : I.operands();
1219 for (auto [OpNum, Op] : enumerate(Ops)) {
1220 Constant *VecC;
1221 Value *V;
1222 uint64_t InsIdx = 0;
1223 if (match(Op.get(), m_InsertElt(m_Constant(VecC), m_Value(V),
1224 m_ConstantInt(InsIdx)))) {
1225 // Bail if any inserts are out of bounds.
1226 VectorType *OpTy = cast<VectorType>(Op->getType());
1227 if (OpTy->getElementCount().getKnownMinValue() <= InsIdx)
1228 return false;
1229 // All inserts must have the same index.
1230 // TODO: Deal with mismatched index constants and variable indexes?
1231 if (!Index)
1232 Index = InsIdx;
1233 else if (InsIdx != *Index)
1234 return false;
1235 VecCs.push_back(VecC);
1236 ScalarOps.push_back(V);
1237 } else if (II && isVectorIntrinsicWithScalarOpAtArg(II->getIntrinsicID(),
1238 OpNum, &TTI)) {
1239 VecCs.push_back(Op.get());
1240 ScalarOps.push_back(Op.get());
1241 } else if (match(Op.get(), m_Constant(VecC))) {
1242 VecCs.push_back(VecC);
1243 ScalarOps.push_back(nullptr);
1244 } else {
1245 return false;
1246 }
1247 }
1248
1249 // Bail if all operands are constant.
1250 if (!Index.has_value())
1251 return false;
1252
1253 VectorType *VecTy = cast<VectorType>(I.getType());
1254 Type *ScalarTy = VecTy->getScalarType();
1255 assert(VecTy->isVectorTy() &&
1256 (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
1257 ScalarTy->isPointerTy()) &&
1258 "Unexpected types for insert element into binop or cmp");
1259
1260 unsigned Opcode = I.getOpcode();
1261 InstructionCost ScalarOpCost, VectorOpCost;
1262 if (CI) {
1263 CmpInst::Predicate Pred = CI->getPredicate();
1264 ScalarOpCost = TTI.getCmpSelInstrCost(
1265 Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred, CostKind);
1266 VectorOpCost = TTI.getCmpSelInstrCost(
1267 Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred, CostKind);
1268 } else if (UO || BO) {
1269 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy, CostKind);
1270 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy, CostKind);
1271 } else {
1272 IntrinsicCostAttributes ScalarICA(
1273 II->getIntrinsicID(), ScalarTy,
1274 SmallVector<Type *>(II->arg_size(), ScalarTy));
1275 ScalarOpCost = TTI.getIntrinsicInstrCost(ScalarICA, CostKind);
1276 IntrinsicCostAttributes VectorICA(
1277 II->getIntrinsicID(), VecTy,
1278 SmallVector<Type *>(II->arg_size(), VecTy));
1279 VectorOpCost = TTI.getIntrinsicInstrCost(VectorICA, CostKind);
1280 }
1281
1282 // Fold the vector constants in the original vectors into a new base vector to
1283 // get more accurate cost modelling.
1284 Value *NewVecC = nullptr;
1285 if (CI)
1286 NewVecC = simplifyCmpInst(CI->getPredicate(), VecCs[0], VecCs[1], SQ);
1287 else if (UO)
1288 NewVecC =
1289 simplifyUnOp(UO->getOpcode(), VecCs[0], UO->getFastMathFlags(), SQ);
1290 else if (BO)
1291 NewVecC = simplifyBinOp(BO->getOpcode(), VecCs[0], VecCs[1], SQ);
1292 else if (II)
1293 NewVecC = simplifyCall(II, II->getCalledOperand(), VecCs, SQ);
1294
1295 if (!NewVecC)
1296 return false;
1297
1298 // Get cost estimate for the insert element. This cost will factor into
1299 // both sequences.
1300 InstructionCost OldCost = VectorOpCost;
1301 InstructionCost NewCost =
1302 ScalarOpCost + TTI.getVectorInstrCost(Instruction::InsertElement, VecTy,
1303 CostKind, *Index, NewVecC);
1304
1305 for (auto [Idx, Op, VecC, Scalar] : enumerate(Ops, VecCs, ScalarOps)) {
1306 if (!Scalar || (II && isVectorIntrinsicWithScalarOpAtArg(
1307 II->getIntrinsicID(), Idx, &TTI)))
1308 continue;
1310 Instruction::InsertElement, VecTy, CostKind, *Index, VecC, Scalar);
1311 OldCost += InsertCost;
1312 NewCost += !Op->hasOneUse() * InsertCost;
1313 }
1314
1315 // We want to scalarize unless the vector variant actually has lower cost.
1316 if (OldCost < NewCost || !NewCost.isValid())
1317 return false;
1318
1319 // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
1320 // inselt NewVecC, (scalar_op V0, V1), Index
1321 if (CI)
1322 ++NumScalarCmp;
1323 else if (UO || BO)
1324 ++NumScalarOps;
1325 else
1326 ++NumScalarIntrinsic;
1327
1328 // For constant cases, extract the scalar element, this should constant fold.
1329 for (auto [OpIdx, Scalar, VecC] : enumerate(ScalarOps, VecCs))
1330 if (!Scalar)
1331 ScalarOps[OpIdx] = ConstantExpr::getExtractElement(
1332 cast<Constant>(VecC), Builder.getInt64(*Index));
1333
1334 Value *Scalar;
1335 // We need to pass the flags during the creation of instructions. Constant
1336 // folding might remove the instructions, so post setting the flags might
1337 // pollute the later instructions.
1338 if (CI) {
1339 if (FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I)) {
1340 Scalar = Builder.CreateFCmpFMF(CI->getPredicate(), ScalarOps[0],
1341 ScalarOps[1], FPMO->getFastMathFlags(),
1342 CI->getName() + ".scalar");
1343 } else {
1344 Scalar = Builder.CreateICmp(CI->getPredicate(), ScalarOps[0],
1345 ScalarOps[1], CI->getName() + ".scalar");
1346 }
1347 } else if (UO) {
1348 Scalar = Builder.CreateUnOpFMF(UO->getOpcode(), ScalarOps[0], UO,
1349 UO->getName() + ".scalar");
1350 } else if (BO) {
1351 if (OverflowingBinaryOperator *OBO =
1353 Scalar = Builder.CreateNoWrapBinOp(
1354 BO->getOpcode(), ScalarOps[0], ScalarOps[1], OBO->hasNoUnsignedWrap(),
1355 OBO->hasNoSignedWrap(), BO->getName() + ".scalar");
1356 } else if (PossiblyDisjointInst *PDI = dyn_cast<PossiblyDisjointInst>(&I)) {
1357 Scalar = Builder.CreateOr(ScalarOps[0], ScalarOps[1],
1358 BO->getName() + ".scalar", PDI->isDisjoint());
1359 } else if (PossiblyExactOperator *PEO =
1361 Scalar =
1362 Builder.CreateExactBinOp(BO->getOpcode(), ScalarOps[0], ScalarOps[1],
1363 PEO->isExact(), BO->getName() + ".scalar");
1364 } else if (FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I)) {
1365 Scalar = Builder.CreateBinOpFMF(BO->getOpcode(), ScalarOps[0],
1366 ScalarOps[1], FPMO->getFastMathFlags(),
1367 BO->getName() + ".scalar");
1368 } else {
1369 Scalar = Builder.CreateBinOp(BO->getOpcode(), ScalarOps[0], ScalarOps[1],
1370 BO->getName() + ".scalar");
1371 }
1372 } else {
1373 FastMathFlags FMF;
1374 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
1375 FMF = FPMO->getFastMathFlags();
1376 Scalar = Builder.CreateIntrinsic(ScalarTy, II->getIntrinsicID(), ScalarOps,
1377 FMF, II->getName() + ".scalar");
1378 }
1379
1380 Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, *Index);
1381 replaceValue(I, *Insert);
1382 return true;
1383}
1384
1385/// Try to combine a scalar binop + 2 scalar compares of extracted elements of
1386/// a vector into vector operations followed by extract. Note: The SLP pass
1387/// may miss this pattern because of implementation problems.
1388bool VectorCombine::foldExtractedCmps(Instruction &I) {
1389 auto *BI = dyn_cast<BinaryOperator>(&I);
1390
1391 // We are looking for a scalar binop of booleans.
1392 // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1)
1393 if (!BI || !I.getType()->isIntegerTy(1))
1394 return false;
1395
1396 // The compare predicates should match, and each compare should have a
1397 // constant operand.
1398 Value *B0 = I.getOperand(0), *B1 = I.getOperand(1);
1399 Instruction *I0, *I1;
1400 Constant *C0, *C1;
1401 CmpPredicate P0, P1;
1402 if (!match(B0, m_Cmp(P0, m_Instruction(I0), m_Constant(C0))) ||
1403 !match(B1, m_Cmp(P1, m_Instruction(I1), m_Constant(C1))))
1404 return false;
1405
1406 auto MatchingPred = CmpPredicate::getMatching(P0, P1);
1407 if (!MatchingPred)
1408 return false;
1409
1410 // The compare operands must be extracts of the same vector with constant
1411 // extract indexes.
1412 Value *X;
1413 uint64_t Index0, Index1;
1414 if (!match(I0, m_ExtractElt(m_Value(X), m_ConstantInt(Index0))) ||
1415 !match(I1, m_ExtractElt(m_Specific(X), m_ConstantInt(Index1))))
1416 return false;
1417
1418 auto *Ext0 = cast<ExtractElementInst>(I0);
1419 auto *Ext1 = cast<ExtractElementInst>(I1);
1420 ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1, CostKind);
1421 if (!ConvertToShuf)
1422 return false;
1423 assert((ConvertToShuf == Ext0 || ConvertToShuf == Ext1) &&
1424 "Unknown ExtractElementInst");
1425
1426 // The original scalar pattern is:
1427 // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1)
1428 CmpInst::Predicate Pred = *MatchingPred;
1429 unsigned CmpOpcode =
1430 CmpInst::isFPPredicate(Pred) ? Instruction::FCmp : Instruction::ICmp;
1431 auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
1432 if (!VecTy)
1433 return false;
1434
1435 if (Index0 >= VecTy->getNumElements() || Index1 >= VecTy->getNumElements())
1436 return false;
1437
1438 InstructionCost Ext0Cost =
1439 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Index0);
1440 InstructionCost Ext1Cost =
1441 TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Index1);
1443 CmpOpcode, I0->getType(), CmpInst::makeCmpResultType(I0->getType()), Pred,
1444 CostKind);
1445
1446 InstructionCost OldCost =
1447 Ext0Cost + Ext1Cost + CmpCost * 2 +
1448 TTI.getArithmeticInstrCost(I.getOpcode(), I.getType(), CostKind);
1449
1450 // The proposed vector pattern is:
1451 // vcmp = cmp Pred X, VecC
1452 // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0
1453 int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0;
1454 int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1;
1457 CmpOpcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred, CostKind);
1458 SmallVector<int, 32> ShufMask(VecTy->getNumElements(), PoisonMaskElem);
1459 ShufMask[CheapIndex] = ExpensiveIndex;
1461 CmpTy, CostKind, ShufMask);
1462 NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy, CostKind);
1463 NewCost += TTI.getVectorInstrCost(*Ext0, CmpTy, CostKind, CheapIndex);
1464 NewCost += Ext0->hasOneUse() ? 0 : Ext0Cost;
1465 NewCost += Ext1->hasOneUse() ? 0 : Ext1Cost;
1466
1467 // Aggressively form vector ops if the cost is equal because the transform
1468 // may enable further optimization.
1469 // Codegen can reverse this transform (scalarize) if it was not profitable.
1470 if (OldCost < NewCost || !NewCost.isValid())
1471 return false;
1472
1473 // Create a vector constant from the 2 scalar constants.
1474 SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(),
1475 PoisonValue::get(VecTy->getElementType()));
1476 CmpC[Index0] = C0;
1477 CmpC[Index1] = C1;
1478 Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC));
1479 Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder);
1480 Value *LHS = ConvertToShuf == Ext0 ? Shuf : VCmp;
1481 Value *RHS = ConvertToShuf == Ext0 ? VCmp : Shuf;
1482 Value *VecLogic = Builder.CreateBinOp(BI->getOpcode(), LHS, RHS);
1483 Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex);
1484 replaceValue(I, *NewExt);
1485 ++NumVecCmpBO;
1486 return true;
1487}
1488
1489/// Try to fold scalar selects that select between extracted elements and zero
1490/// into extracting from a vector select. This is rooted at the bitcast.
1491///
1492/// This pattern arises when a vector is bitcast to a smaller element type,
1493/// elements are extracted, and then conditionally selected with zero:
1494///
1495/// %bc = bitcast <4 x i32> %src to <16 x i8>
1496/// %e0 = extractelement <16 x i8> %bc, i32 0
1497/// %s0 = select i1 %cond, i8 %e0, i8 0
1498/// %e1 = extractelement <16 x i8> %bc, i32 1
1499/// %s1 = select i1 %cond, i8 %e1, i8 0
1500/// ...
1501///
1502/// Transforms to:
1503/// %sel = select i1 %cond, <4 x i32> %src, <4 x i32> zeroinitializer
1504/// %bc = bitcast <4 x i32> %sel to <16 x i8>
1505/// %e0 = extractelement <16 x i8> %bc, i32 0
1506/// %e1 = extractelement <16 x i8> %bc, i32 1
1507/// ...
1508///
1509/// This is profitable because vector select on wider types produces fewer
1510/// select/cndmask instructions than scalar selects on each element.
1511bool VectorCombine::foldSelectsFromBitcast(Instruction &I) {
1512 auto *BC = dyn_cast<BitCastInst>(&I);
1513 if (!BC)
1514 return false;
1515
1516 FixedVectorType *SrcVecTy = dyn_cast<FixedVectorType>(BC->getSrcTy());
1517 FixedVectorType *DstVecTy = dyn_cast<FixedVectorType>(BC->getDestTy());
1518 if (!SrcVecTy || !DstVecTy)
1519 return false;
1520
1521 // Source must be 32-bit or 64-bit elements, destination must be smaller
1522 // integer elements. Zero in all these types is all-bits-zero.
1523 Type *SrcEltTy = SrcVecTy->getElementType();
1524 Type *DstEltTy = DstVecTy->getElementType();
1525 unsigned SrcEltBits = SrcEltTy->getPrimitiveSizeInBits();
1526 unsigned DstEltBits = DstEltTy->getPrimitiveSizeInBits();
1527
1528 if (SrcEltBits != 32 && SrcEltBits != 64)
1529 return false;
1530
1531 if (!DstEltTy->isIntegerTy() || DstEltBits >= SrcEltBits)
1532 return false;
1533
1534 // Check profitability using TTI before collecting users.
1535 Type *CondTy = CmpInst::makeCmpResultType(DstEltTy);
1536 Type *VecCondTy = CmpInst::makeCmpResultType(SrcVecTy);
1537
1538 InstructionCost ScalarSelCost =
1539 TTI.getCmpSelInstrCost(Instruction::Select, DstEltTy, CondTy,
1540 CmpInst::BAD_ICMP_PREDICATE, CostKind);
1541 InstructionCost VecSelCost =
1542 TTI.getCmpSelInstrCost(Instruction::Select, SrcVecTy, VecCondTy,
1543 CmpInst::BAD_ICMP_PREDICATE, CostKind);
1544
1545 // We need at least this many selects for vectorization to be profitable.
1546 // VecSelCost < ScalarSelCost * NumSelects => NumSelects > VecSelCost /
1547 // ScalarSelCost
1548 if (!ScalarSelCost.isValid() || ScalarSelCost == 0)
1549 return false;
1550
1551 unsigned MinSelects = (VecSelCost.getValue() / ScalarSelCost.getValue()) + 1;
1552
1553 // Quick check: if bitcast doesn't have enough users, bail early.
1554 if (!BC->hasNUsesOrMore(MinSelects))
1555 return false;
1556
1557 // Collect all select users that match the pattern, grouped by condition.
1558 // Pattern: select i1 %cond, (extractelement %bc, idx), 0
1559 DenseMap<Value *, SmallVector<SelectInst *, 8>> CondToSelects;
1560
1561 for (User *U : BC->users()) {
1562 auto *Ext = dyn_cast<ExtractElementInst>(U);
1563 if (!Ext)
1564 continue;
1565
1566 for (User *ExtUser : Ext->users()) {
1567 Value *Cond;
1568 // Match: select i1 %cond, %ext, 0
1569 if (match(ExtUser, m_Select(m_Value(Cond), m_Specific(Ext), m_Zero())) &&
1570 Cond->getType()->isIntegerTy(1))
1571 CondToSelects[Cond].push_back(cast<SelectInst>(ExtUser));
1572 }
1573 }
1574
1575 if (CondToSelects.empty())
1576 return false;
1577
1578 bool MadeChange = false;
1579 Value *SrcVec = BC->getOperand(0);
1580
1581 // Process each group of selects with the same condition.
1582 for (auto [Cond, Selects] : CondToSelects) {
1583 // Only profitable if vector select cost < total scalar select cost.
1584 if (Selects.size() < MinSelects) {
1585 LLVM_DEBUG(dbgs() << "VectorCombine: foldSelectsFromBitcast not "
1586 << "profitable (VecCost=" << VecSelCost
1587 << ", ScalarCost=" << ScalarSelCost
1588 << ", NumSelects=" << Selects.size() << ")\n");
1589 continue;
1590 }
1591
1592 // Create the vector select and bitcast once for this condition.
1593 auto InsertPt = std::next(BC->getIterator());
1594
1595 if (auto *CondInst = dyn_cast<Instruction>(Cond))
1596 if (DT.dominates(BC, CondInst))
1597 InsertPt = std::next(CondInst->getIterator());
1598
1599 Builder.SetInsertPoint(InsertPt);
1600 Value *VecSel =
1601 Builder.CreateSelect(Cond, SrcVec, Constant::getNullValue(SrcVecTy));
1602 Value *NewBC = Builder.CreateBitCast(VecSel, DstVecTy);
1603
1604 // Replace each scalar select with an extract from the new bitcast.
1605 for (SelectInst *Sel : Selects) {
1606 auto *Ext = cast<ExtractElementInst>(Sel->getTrueValue());
1607 Value *Idx = Ext->getIndexOperand();
1608
1609 Builder.SetInsertPoint(Sel);
1610 Value *NewExt = Builder.CreateExtractElement(NewBC, Idx);
1611 replaceValue(*Sel, *NewExt);
1612 MadeChange = true;
1613 }
1614
1615 LLVM_DEBUG(dbgs() << "VectorCombine: folded " << Selects.size()
1616 << " selects into vector select\n");
1617 }
1618
1619 return MadeChange;
1620}
1621
1623 TTI::TargetCostKind CostKind,
1624 const TargetTransformInfo &TTI,
1625 InstructionCost &CostBeforeReduction,
1626 InstructionCost &CostAfterReduction) {
1627 Instruction *Op0, *Op1;
1628 auto *RedOp = dyn_cast<Instruction>(II.getOperand(0));
1629 auto *VecRedTy = cast<VectorType>(II.getOperand(0)->getType());
1630 unsigned ReductionOpc =
1631 getArithmeticReductionInstruction(II.getIntrinsicID());
1632 if (RedOp && match(RedOp, m_ZExtOrSExt(m_Value()))) {
1633 bool IsUnsigned = isa<ZExtInst>(RedOp);
1634 auto *ExtType = cast<VectorType>(RedOp->getOperand(0)->getType());
1635
1636 CostBeforeReduction =
1637 TTI.getCastInstrCost(RedOp->getOpcode(), VecRedTy, ExtType,
1638 TTI::CastContextHint::None, CostKind, RedOp);
1639 CostAfterReduction =
1640 TTI.getExtendedReductionCost(ReductionOpc, IsUnsigned, II.getType(),
1641 ExtType, FastMathFlags(), CostKind);
1642 return;
1643 }
1644 if (RedOp && II.getIntrinsicID() == Intrinsic::vector_reduce_add &&
1645 match(RedOp,
1647 match(Op0, m_ZExtOrSExt(m_Value())) &&
1648 Op0->getOpcode() == Op1->getOpcode() &&
1649 Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
1650 (Op0->getOpcode() == RedOp->getOpcode() || Op0 == Op1)) {
1651 // Matched reduce.add(ext(mul(ext(A), ext(B)))
1652 bool IsUnsigned = isa<ZExtInst>(Op0);
1653 auto *ExtType = cast<VectorType>(Op0->getOperand(0)->getType());
1654 VectorType *MulType = VectorType::get(Op0->getType(), VecRedTy);
1655
1656 InstructionCost ExtCost =
1657 TTI.getCastInstrCost(Op0->getOpcode(), MulType, ExtType,
1658 TTI::CastContextHint::None, CostKind, Op0);
1659 InstructionCost MulCost =
1660 TTI.getArithmeticInstrCost(Instruction::Mul, MulType, CostKind);
1661 InstructionCost Ext2Cost =
1662 TTI.getCastInstrCost(RedOp->getOpcode(), VecRedTy, MulType,
1663 TTI::CastContextHint::None, CostKind, RedOp);
1664
1665 CostBeforeReduction = ExtCost * 2 + MulCost + Ext2Cost;
1666 CostAfterReduction = TTI.getMulAccReductionCost(
1667 IsUnsigned, ReductionOpc, II.getType(), ExtType, CostKind);
1668 return;
1669 }
1670 CostAfterReduction = TTI.getArithmeticReductionCost(ReductionOpc, VecRedTy,
1671 std::nullopt, CostKind);
1672}
1673
1674bool VectorCombine::foldBinopOfReductions(Instruction &I) {
1675 Instruction::BinaryOps BinOpOpc = cast<BinaryOperator>(&I)->getOpcode();
1676 Intrinsic::ID ReductionIID = getReductionForBinop(BinOpOpc);
1677 if (BinOpOpc == Instruction::Sub)
1678 ReductionIID = Intrinsic::vector_reduce_add;
1679 if (ReductionIID == Intrinsic::not_intrinsic)
1680 return false;
1681 // FP reductions have a start-value operand that this fold doesn't handle.
1682 if (ReductionIID == Intrinsic::vector_reduce_fadd ||
1683 ReductionIID == Intrinsic::vector_reduce_fmul)
1684 return false;
1685
1686 auto checkIntrinsicAndGetItsArgument = [](Value *V,
1687 Intrinsic::ID IID) -> Value * {
1688 auto *II = dyn_cast<IntrinsicInst>(V);
1689 if (!II)
1690 return nullptr;
1691 if (II->getIntrinsicID() == IID && II->hasOneUse())
1692 return II->getArgOperand(0);
1693 return nullptr;
1694 };
1695
1696 Value *V0 = checkIntrinsicAndGetItsArgument(I.getOperand(0), ReductionIID);
1697 if (!V0)
1698 return false;
1699 Value *V1 = checkIntrinsicAndGetItsArgument(I.getOperand(1), ReductionIID);
1700 if (!V1)
1701 return false;
1702
1703 auto *VTy = cast<VectorType>(V0->getType());
1704 if (V1->getType() != VTy)
1705 return false;
1706 const auto &II0 = *cast<IntrinsicInst>(I.getOperand(0));
1707 const auto &II1 = *cast<IntrinsicInst>(I.getOperand(1));
1708 unsigned ReductionOpc =
1709 getArithmeticReductionInstruction(II0.getIntrinsicID());
1710
1711 InstructionCost OldCost = 0;
1712 InstructionCost NewCost = 0;
1713 InstructionCost CostOfRedOperand0 = 0;
1714 InstructionCost CostOfRed0 = 0;
1715 InstructionCost CostOfRedOperand1 = 0;
1716 InstructionCost CostOfRed1 = 0;
1717 analyzeCostOfVecReduction(II0, CostKind, TTI, CostOfRedOperand0, CostOfRed0);
1718 analyzeCostOfVecReduction(II1, CostKind, TTI, CostOfRedOperand1, CostOfRed1);
1719 OldCost = CostOfRed0 + CostOfRed1 + TTI.getInstructionCost(&I, CostKind);
1720 NewCost =
1721 CostOfRedOperand0 + CostOfRedOperand1 +
1722 TTI.getArithmeticInstrCost(BinOpOpc, VTy, CostKind) +
1723 TTI.getArithmeticReductionCost(ReductionOpc, VTy, std::nullopt, CostKind);
1724 if (NewCost >= OldCost || !NewCost.isValid())
1725 return false;
1726
1727 LLVM_DEBUG(dbgs() << "Found two mergeable reductions: " << I
1728 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
1729 << "\n");
1730 Value *VectorBO;
1731 if (BinOpOpc == Instruction::Or)
1732 VectorBO = Builder.CreateOr(V0, V1, "",
1733 cast<PossiblyDisjointInst>(I).isDisjoint());
1734 else
1735 VectorBO = Builder.CreateBinOp(BinOpOpc, V0, V1);
1736
1737 Value *Rdx = Builder.CreateIntrinsic(ReductionIID, {VTy}, {VectorBO});
1738 replaceValue(I, *Rdx);
1739 return true;
1740}
1741
1742// Check if memory is modified, freed, or synchronized between two instrs in
1743// the same BB.
1744static bool isMemModifiedBetween(const VectorizeOptions &Opts,
1747 const MemoryLocation &Loc, AAResults &AA) {
1748 unsigned NumScanned = 0;
1749 if (std::any_of(Begin, End, [&](const Instruction &Instr) {
1750 return isModSet(AA.getModRefInfo(&Instr, Loc)) ||
1751 ++NumScanned > Opts.vector_combine_max_scan_instrs;
1752 }))
1753 return true;
1754
1755 // willNotFreeBetween expects instructions rather than iterators. An empty
1756 // range cannot free or synchronize, so avoid dereferencing its end.
1757 return Begin != End && !willNotFreeBetween(&*Begin, &*End);
1758}
1759
1760namespace {
1761/// Helper class to indicate whether a vector index can be safely scalarized and
1762/// if a freeze needs to be inserted.
1763class ScalarizationResult {
1764 enum class StatusTy { Unsafe, Safe, SafeWithFreeze };
1765
1766 StatusTy Status;
1767 Value *ToFreeze;
1768
1769 ScalarizationResult(StatusTy Status, Value *ToFreeze = nullptr)
1770 : Status(Status), ToFreeze(ToFreeze) {}
1771
1772public:
1773 ScalarizationResult(const ScalarizationResult &Other) = default;
1774 ~ScalarizationResult() {
1775 assert(!ToFreeze && "freeze() not called with ToFreeze being set");
1776 }
1777
1778 static ScalarizationResult unsafe() { return {StatusTy::Unsafe}; }
1779 static ScalarizationResult safe() { return {StatusTy::Safe}; }
1780 static ScalarizationResult safeWithFreeze(Value *ToFreeze) {
1781 return {StatusTy::SafeWithFreeze, ToFreeze};
1782 }
1783
1784 /// Returns true if the index can be scalarize without requiring a freeze.
1785 bool isSafe() const { return Status == StatusTy::Safe; }
1786 /// Returns true if the index cannot be scalarized.
1787 bool isUnsafe() const { return Status == StatusTy::Unsafe; }
1788 /// Returns true if the index can be scalarize, but requires inserting a
1789 /// freeze.
1790 bool isSafeWithFreeze() const { return Status == StatusTy::SafeWithFreeze; }
1791
1792 /// Reset the state of Unsafe and clear ToFreze if set.
1793 void discard() {
1794 ToFreeze = nullptr;
1795 Status = StatusTy::Unsafe;
1796 }
1797
1798 /// Freeze the ToFreeze and update the use in \p User to use it.
1799 void freeze(IRBuilderBase &Builder, Instruction &UserI) {
1800 assert(isSafeWithFreeze() &&
1801 "should only be used when freezing is required");
1802 assert(is_contained(ToFreeze->users(), &UserI) &&
1803 "UserI must be a user of ToFreeze");
1804 IRBuilder<>::InsertPointGuard Guard(Builder);
1805 Builder.SetInsertPoint(cast<Instruction>(&UserI));
1806 Value *Frozen =
1807 Builder.CreateFreeze(ToFreeze, ToFreeze->getName() + ".frozen");
1808 for (Use &U : make_early_inc_range((UserI.operands())))
1809 if (U.get() == ToFreeze)
1810 U.set(Frozen);
1811
1812 ToFreeze = nullptr;
1813 }
1814};
1815} // namespace
1816
1817/// Check if it is legal to scalarize a memory access to \p VecTy at index \p
1818/// Idx. \p Idx must access a valid vector element.
1819static ScalarizationResult canScalarizeAccess(VectorType *VecTy, Value *Idx,
1820 const SimplifyQuery &SQ) {
1821 // We do checks for both fixed vector types and scalable vector types.
1822 // This is the number of elements of fixed vector types,
1823 // or the minimum number of elements of scalable vector types.
1824 uint64_t NumElements = VecTy->getElementCount().getKnownMinValue();
1825 unsigned IntWidth = Idx->getType()->getScalarSizeInBits();
1826
1827 if (auto *C = dyn_cast<ConstantInt>(Idx)) {
1828 if (C->getValue().ult(NumElements))
1829 return ScalarizationResult::safe();
1830 return ScalarizationResult::unsafe();
1831 }
1832
1833 // Always unsafe if the index type can't handle all inbound values.
1834 if (!llvm::isUIntN(IntWidth, NumElements))
1835 return ScalarizationResult::unsafe();
1836
1837 APInt Zero(IntWidth, 0);
1838 APInt MaxElts(IntWidth, NumElements);
1839 ConstantRange ValidIndices(Zero, MaxElts);
1840 ConstantRange IdxRange(IntWidth, true);
1841
1842 if (isGuaranteedNotToBePoison(Idx, SQ.AC, SQ.CtxI, SQ.DT)) {
1843 if (ValidIndices.contains(
1844 computeConstantRange(Idx, /*ForSigned=*/false, SQ)))
1845 return ScalarizationResult::safe();
1846 return ScalarizationResult::unsafe();
1847 }
1848
1849 // If the index may be poison, check if we can insert a freeze before the
1850 // range of the index is restricted.
1851 Value *IdxBase;
1852 ConstantInt *CI;
1853 if (match(Idx, m_And(m_Value(IdxBase), m_ConstantInt(CI)))) {
1854 IdxRange = IdxRange.binaryAnd(CI->getValue());
1855 } else if (match(Idx, m_URem(m_Value(IdxBase), m_ConstantInt(CI)))) {
1856 IdxRange = IdxRange.urem(CI->getValue());
1857 }
1858
1859 if (ValidIndices.contains(IdxRange))
1860 return ScalarizationResult::safeWithFreeze(IdxBase);
1861 return ScalarizationResult::unsafe();
1862}
1863
1864/// Return the GEP index type if the unsigned vector index \p Idx can be
1865/// represented by an inbounds GEP. A null result means that the maximum byte
1866/// offset cannot be represented by the pointer's signed GEP index type.
1867///
1868/// unsigned lane range
1869/// |
1870/// v
1871/// MaxByteOffset = MaxLane * element store size
1872/// |
1873/// +-- unavailable or outside signed GEP range --> reject
1874/// |
1875/// v
1876/// valid range --> use the pointer's GEP index type
1878 Type *PtrTy,
1879 const DataLayout &DL) {
1880 auto *GEPIndexTy = cast<IntegerType>(DL.getIndexType(PtrTy));
1881 unsigned GEPBits = GEPIndexTy->getBitWidth();
1882 uint64_t NumElements = VecTy->getElementCount().getKnownMinValue();
1883
1884 uint64_t MaxLane = NumElements - 1;
1885 if (auto *C = dyn_cast<ConstantInt>(Idx)) {
1886 if (C->getValue().uge(NumElements))
1887 return nullptr;
1888 MaxLane = C->getZExtValue();
1889 }
1890
1891 Type *ElemTy = VecTy->getElementType();
1892 if (!DL.typeSizeEqualsStoreSize(ElemTy))
1893 return nullptr;
1894
1895 TypeSize ElemStride = DL.getTypeStoreSize(ElemTy);
1896 if (ElemStride.isScalable())
1897 return nullptr;
1898
1899 // Compare both values in a common width:
1900 //
1901 // MaxLane (uint64_t) * ElemStride (uint64_t) signed_max(GEPBits)
1902 // | |
1903 // v v
1904 // ByteOffset (up to 128 bits) sext to WideBits
1905 // \ /
1906 // +------------ ugt ------------+
1907 // |
1908 // greater -> reject
1909 //
1910 // WideBits = max(GEPBits, 128) prevents the multiplication from wrapping
1911 // and preserves the GEP limit during the comparison.
1912 unsigned WideBits = std::max(GEPBits, 128u);
1913 APInt MaxLaneValue(WideBits, MaxLane);
1914 APInt ByteOffset = MaxLaneValue;
1915 ByteOffset *= APInt(WideBits, ElemStride.getFixedValue());
1916 APInt MaxGEPOffset = APInt::getSignedMaxValue(GEPBits).sext(WideBits);
1917 // Reject offsets outside the GEP's positive signed range. Compare as
1918 // unsigned because the full 128-bit product may set its sign bit.
1919 if (ByteOffset.ugt(MaxGEPOffset))
1920 return nullptr;
1921
1922 return GEPIndexTy;
1923}
1924
1925/// Materialize an index for a scalarized GEP after profitability is known.
1926/// Vector element indices are unsigned, but GEP sign-extends narrow integer
1927/// indices. Widen a narrow index explicitly so its unsigned value is retained.
1929 IRBuilderBase &Builder) {
1930 unsigned SrcBits = Idx->getType()->getIntegerBitWidth();
1931 unsigned DstBits = GEPIndexTy->getBitWidth();
1932 if (SrcBits >= DstBits)
1933 return Idx;
1934
1935 return Builder.CreateZExt(Idx, GEPIndexTy, Idx->getName() + ".gepidx");
1936}
1937
1938/// The memory operation on a vector of \p ScalarType had alignment of
1939/// \p VectorAlignment. Compute the maximal, but conservatively correct,
1940/// alignment that will be valid for the memory operation on a single scalar
1941/// element of the same type with index \p Idx.
1943 Type *ScalarType, Value *Idx,
1944 const DataLayout &DL) {
1945 if (auto *C = dyn_cast<ConstantInt>(Idx))
1946 return commonAlignment(VectorAlignment,
1947 C->getZExtValue() * DL.getTypeStoreSize(ScalarType));
1948 return commonAlignment(VectorAlignment, DL.getTypeStoreSize(ScalarType));
1949}
1950
1951/// Fold a vector store fed by a single-use insertelement chain into scalar
1952/// stores.
1953///
1954/// Before:
1955///
1956/// %p --> vector load --> insert %x, lane 1 --> insert %y, lane 3
1957/// |
1958/// v
1959/// vector store to %p
1960///
1961/// Vector lanes: [ 0 ] [ 1 ] [ 2 ] [ 3 ]
1962/// Stored value: [ old | x | old | y ] (one vector store)
1963///
1964/// After:
1965///
1966/// +--> GEP(%p, lane 1) --> store %x
1967/// %p -------------+
1968/// +--> GEP(%p, lane 3) --> store %y
1969///
1970/// Vector lanes: [ 0 ] [ 1 ] [ 2 ] [ 3 ]
1971/// Scalar stores: x y
1972/// store@1 store@3
1973///
1974/// Step 1. Gate:
1975/// target supports vector-element GEP addressing
1976///
1977/// Step 2. Trace:
1978/// vector store <-- insertelement <-- ... <-- insertelement <-- load
1979///
1980/// Steps 3-5. Validate:
1981/// reject unprofitable full overwrites; require simple accesses, a
1982/// common address/block, no memory write in between, and scalarizable
1983/// indices.
1984bool VectorCombine::foldInsertElementsToStores(Instruction &I) {
1985 // Step 1: The target must support addressing a vector element with a GEP.
1987 return false;
1988
1989 auto *SI = cast<StoreInst>(&I);
1990 if (!SI->isSimple() || !isa<VectorType>(SI->getValueOperand()->getType()))
1991 return false;
1992
1993 // Step 2: Collect a single-use insertelement chain, starting at the vector
1994 // store and walking back to the candidate load.
1995 Value *Source = SI->getValueOperand();
1996 SmallVector<std::pair<Value *, Value *>, 4> InsertElements;
1997 Value *Base = Source;
1998 while (auto *Insert = dyn_cast<InsertElementInst>(Base)) {
1999 if (!Insert->hasOneUse())
2000 break;
2001 Value *InsertVal = Insert->getOperand(1);
2002 Value *Idx = Insert->getOperand(2);
2003 InsertElements.push_back({InsertVal, Idx});
2004 Base = Insert->getOperand(0);
2005 }
2006
2007 if (InsertElements.empty())
2008 return false;
2009
2010 // The backwards walk collected the inserts in reverse program order. Restore
2011 // it now so later scalar stores preserve writes to duplicate/equal indices.
2012 std::reverse(InsertElements.begin(), InsertElements.end());
2013 auto *Load = dyn_cast<LoadInst>(Base);
2014 if (!Load)
2015 return false;
2016 auto *VecTy = cast<VectorType>(SI->getValueOperand()->getType());
2017
2018 // Step 3: Avoid replacing a complete overwrite with scalar stores when every
2019 // lane receives the same value; keeping the vector operation is preferable.
2020 if (auto *FVT = dyn_cast<FixedVectorType>(VecTy)) {
2021 if (InsertElements.size() == FVT->getNumElements()) {
2022 Value *FirstVal = InsertElements.front().first;
2023 if (all_of(InsertElements,
2024 [FirstVal](const auto &Elt) { return Elt.first == FirstVal; }))
2025 return false;
2026 }
2027 }
2028 Value *SrcAddr = Load->getPointerOperand()->stripPointerCasts();
2029 // Step 4: Establish the load/store update is legal: both accesses are simple,
2030 // have the same base address and block, have scalar elements whose type size
2031 // equals their store size, and no intervening operation modifies the updated
2032 // memory.
2033 if (!Load->isSimple() || Load->getParent() != SI->getParent() ||
2034 !DL->typeSizeEqualsStoreSize(Load->getType()->getScalarType()) ||
2035 SrcAddr != SI->getPointerOperand()->stripPointerCasts())
2036 return false;
2037
2038 if (isMemModifiedBetween(Opts, Load->getIterator(), SI->getIterator(),
2039 MemoryLocation::get(SI), AA))
2040 return false;
2041
2042 // Step 5: Validate every index before changing IR. A safe-with-freeze result
2043 // is recorded by ScalarizationResult, so discard it until profitability is
2044 // known; otherwise a rejected candidate could leave a freeze behind.
2045 for (auto [InsertVal, Idx] : InsertElements) {
2046 auto ScalarizableIdx =
2047 canScalarizeAccess(VecTy, Idx, SQ.getWithInstruction(&I));
2048 if (ScalarizableIdx.isUnsafe())
2049 return false;
2050
2051 auto GEPIndex =
2052 getScalarizedGEPIndexInfo(VecTy, Idx, SI->getPointerOperandType(), *DL);
2053 if (!GEPIndex) {
2054 ScalarizableIdx.discard();
2055 return false;
2056 }
2057
2058 // We are only checking legality here. Do not mutate IR before the
2059 // profitability check, but also do not leave a pending ToFreeze behind.
2060 ScalarizableIdx.discard();
2061 }
2062
2064 Instruction::Store, SI->getValueOperand()->getType(), SI->getAlign(),
2065 SI->getPointerAddressSpace(), CostKind);
2066
2067 if (Load->hasOneUse())
2068 OldCost += TTI.getMemoryOpCost(Instruction::Load, Load->getType(),
2069 Load->getAlign(),
2070 Load->getPointerAddressSpace(), CostKind);
2071
2072 for (auto [InsertVal, Idx] : InsertElements) {
2073 int Index = -1;
2074 if (auto *CIdx = dyn_cast<ConstantInt>(Idx))
2075 Index = CIdx->getZExtValue();
2076
2077 OldCost += TTI.getVectorInstrCost(Instruction::InsertElement, VecTy,
2078 CostKind, Index);
2079 }
2080
2081 InstructionCost NewCost = 0;
2082 // This transform replaces insertelement operations on a single vector with
2083 // GEPs and scalar stores, so assume constant-index GEP offsets stay within
2084 // addressing-mode ranges that getGEPCost considers TCC_Free. Cost only GEPs
2085 // with dynamic indices.
2086 for (auto [InsertVal, Idx] : InsertElements) {
2087 if (isa<ConstantInt>(Idx))
2088 continue;
2089 const Value *GEPIndices[] = {ConstantInt::get(Idx->getType(), 0), Idx};
2090 NewCost += TTI.getGEPCost(VecTy, SI->getPointerOperand(), GEPIndices,
2091 CostKind, InsertVal->getType());
2092 }
2093
2094 for (auto [InsertVal, Idx] : InsertElements) {
2095 Align ScalarOpAlignment = computeAlignmentAfterScalarization(
2096 std::max(SI->getAlign(), Load->getAlign()), InsertVal->getType(), Idx,
2097 *DL);
2098
2099 NewCost += TTI.getMemoryOpCost(Instruction::Store, InsertVal->getType(),
2100 ScalarOpAlignment,
2101 SI->getPointerAddressSpace(), CostKind);
2102 }
2103
2104 LLVM_DEBUG(dbgs() << "Found an insert-elements vector store scalarization "
2105 "candidate: "
2106 << I << "\n"
2107 << " NumInserts: " << InsertElements.size() << "\n"
2108 << " OldCost: " << OldCost << " vs NewCost: " << NewCost
2109 << "\n");
2110
2111 if (OldCost <= NewCost)
2112 return false;
2113
2114 for (auto [InsertVal, Idx] : InsertElements) {
2115 auto ScalarizableIdx =
2116 canScalarizeAccess(VecTy, Idx, SQ.getWithInstruction(&I));
2117 assert(!ScalarizableIdx.isUnsafe() && "already checked above");
2118
2119 if (ScalarizableIdx.isSafeWithFreeze())
2120 ScalarizableIdx.freeze(Builder, *cast<Instruction>(Idx));
2121 }
2122
2123 Worklist.push(Load);
2124 StoreInst *LastStore = nullptr;
2125 for (auto [InsertVal, Idx] : InsertElements) {
2126 auto ScalarizableIdx =
2127 canScalarizeAccess(VecTy, Idx, SQ.getWithInstruction(&I));
2128 if (ScalarizableIdx.isUnsafe())
2129 return false;
2130
2131 IntegerType *GEPIndexTy =
2132 getScalarizedGEPIndexInfo(VecTy, Idx, SI->getPointerOperandType(), *DL);
2133
2134 Value *GEPIdx = materializeScalarizedGEPIndex(Idx, GEPIndexTy, Builder);
2135 Value *GEP = Builder.CreateInBoundsGEP(
2136 SI->getValueOperand()->getType(), SI->getPointerOperand(),
2137 {ConstantInt::get(GEPIdx->getType(), 0), GEPIdx});
2138
2139 LastStore = Builder.CreateStore(InsertVal, GEP);
2140 LastStore->copyMetadata(*SI);
2141
2142 // The new GEP may change the pointer operand, so !invariant.group cannot
2143 // be transferred to the scalar store.
2144 LastStore->setMetadata(LLVMContext::MD_invariant_group, nullptr);
2145 Align ScalarOpAlignment = computeAlignmentAfterScalarization(
2146 std::max(SI->getAlign(), Load->getAlign()), InsertVal->getType(), Idx,
2147 *DL);
2148 LastStore->setAlignment(ScalarOpAlignment);
2149 }
2150
2151 replaceValue(I, *LastStore);
2153 return true;
2154}
2155
2156/// Try to scalarize vector loads feeding extractelement or bitcast
2157/// instructions.
2158bool VectorCombine::scalarizeLoad(Instruction &I) {
2159 Value *Ptr;
2160 if (!match(&I, m_Load(m_Value(Ptr))))
2161 return false;
2162
2163 auto *LI = cast<LoadInst>(&I);
2164 auto *VecTy = cast<VectorType>(LI->getType());
2165
2166 // The isSimple() check could be isUnordered(), but for now we cowardly
2167 // refuse to handle even unordered atomics.
2168 if (!LI->isSimple() || !DL->typeSizeEqualsStoreSize(VecTy->getScalarType()))
2169 return false;
2170
2171 bool AllExtracts = true;
2172 bool AllBitcasts = true;
2173 Instruction *LastCheckedInst = LI;
2174 unsigned NumInstChecked = 0;
2175
2176 // Check what type of users we have (must either all be extracts or
2177 // bitcasts) and ensure no memory modifications between the load and
2178 // its users.
2179 for (Instruction *UI : LI->users()) {
2180 if (UI->getParent() != LI->getParent())
2181 return false;
2182
2183 // If any user is waiting to be erased, then bail out as this will
2184 // distort the cost calculation and possibly lead to infinite loops.
2185 if (UI->use_empty())
2186 return false;
2187
2188 if (!isa<ExtractElementInst>(UI))
2189 AllExtracts = false;
2190 if (!isa<BitCastInst>(UI))
2191 AllBitcasts = false;
2192
2193 // Check if any instruction between the load and the user may modify memory.
2194 if (LastCheckedInst->comesBefore(UI)) {
2195 for (Instruction &I :
2196 make_range(std::next(LI->getIterator()), UI->getIterator())) {
2197 // Bail out if we reached the check limit or the instruction may write
2198 // to memory.
2199 if (NumInstChecked == Opts.vector_combine_max_scan_instrs ||
2200 I.mayWriteToMemory())
2201 return false;
2202 NumInstChecked++;
2203 }
2204 LastCheckedInst = UI;
2205 }
2206 }
2207
2208 if (AllExtracts)
2209 return scalarizeLoadExtract(LI, VecTy, Ptr);
2210 if (AllBitcasts)
2211 return scalarizeLoadBitcast(LI, VecTy, Ptr);
2212 return false;
2213}
2214
2215/// Try to scalarize vector loads feeding extractelement instructions.
2216bool VectorCombine::scalarizeLoadExtract(LoadInst *LI, VectorType *VecTy,
2217 Value *Ptr) {
2219 return false;
2220
2221 DenseMap<ExtractElementInst *, ScalarizationResult> NeedFreeze;
2222 DenseMap<ExtractElementInst *, IntegerType *> GEPIndexInfos;
2223 llvm::scope_exit FailureGuard([&]() {
2224 // If the transform is aborted, discard the ScalarizationResults.
2225 for (auto &Pair : NeedFreeze)
2226 Pair.second.discard();
2227 });
2228
2229 InstructionCost OriginalCost =
2230 TTI.getMemoryOpCost(Instruction::Load, VecTy, LI->getAlign(),
2231 LI->getPointerAddressSpace(), CostKind);
2232 InstructionCost ScalarizedCost = 0;
2233
2234 for (User *U : LI->users()) {
2235 auto *UI = cast<ExtractElementInst>(U);
2236
2237 auto ScalarIdx = canScalarizeAccess(VecTy, UI->getIndexOperand(),
2238 SQ.getWithInstruction(LI));
2239 if (ScalarIdx.isUnsafe())
2240 return false;
2241
2242 IntegerType *GEPIndex = getScalarizedGEPIndexInfo(
2243 VecTy, UI->getIndexOperand(), LI->getPointerOperandType(), *DL);
2244 if (!GEPIndex) {
2245 ScalarIdx.discard();
2246 return false;
2247 }
2248
2249 GEPIndexInfos.try_emplace(UI, GEPIndex);
2250
2251 if (ScalarIdx.isSafeWithFreeze()) {
2252 NeedFreeze.try_emplace(UI, ScalarIdx);
2253 ScalarIdx.discard();
2254 }
2255
2256 auto *Index = dyn_cast<ConstantInt>(UI->getIndexOperand());
2257 OriginalCost +=
2258 TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, CostKind,
2259 Index ? Index->getZExtValue() : -1);
2260 ScalarizedCost +=
2261 TTI.getMemoryOpCost(Instruction::Load, VecTy->getElementType(),
2262 Align(1), LI->getPointerAddressSpace(), CostKind);
2263 ScalarizedCost += TTI.getAddressComputationCost(LI->getPointerOperandType(),
2264 nullptr, nullptr, CostKind);
2265 if (!Index && UI->getIndexOperand()->getType()->getIntegerBitWidth() <
2266 GEPIndex->getBitWidth())
2267 ScalarizedCost += TTI.getCastInstrCost(
2268 Instruction::ZExt, GEPIndex, UI->getIndexOperand()->getType(),
2269 TTI::CastContextHint::None, CostKind);
2270 }
2271
2272 LLVM_DEBUG(dbgs() << "Found all extractions of a vector load: " << *LI
2273 << "\n LoadExtractCost: " << OriginalCost
2274 << " vs ScalarizedCost: " << ScalarizedCost << "\n");
2275
2276 if (ScalarizedCost > OriginalCost)
2277 return false;
2278 if (ScalarizedCost == OriginalCost && !LI->hasOneUse())
2279 return false;
2280
2281 // Ensure we add the load back to the worklist BEFORE its users so they can
2282 // erased in the correct order.
2283 Worklist.push(LI);
2284
2285 Type *ElemType = VecTy->getElementType();
2286
2287 // Replace extracts with narrow scalar loads.
2288 for (User *U : LI->users()) {
2289 auto *EI = cast<ExtractElementInst>(U);
2290 Value *Idx = EI->getIndexOperand();
2291
2292 // Insert 'freeze' for poison indexes.
2293 if (auto It = NeedFreeze.find(EI); It != NeedFreeze.end())
2294 It->second.freeze(Builder, *cast<Instruction>(Idx));
2295
2296 Builder.SetInsertPoint(EI);
2297 auto It = GEPIndexInfos.find(EI);
2298 assert(It != GEPIndexInfos.end() &&
2299 "Missing scalarized GEP index information");
2300 Value *GEPIdx = materializeScalarizedGEPIndex(Idx, It->second, Builder);
2301 Value *GEP = Builder.CreateInBoundsGEP(
2302 VecTy, Ptr, {ConstantInt::get(GEPIdx->getType(), 0), GEPIdx});
2303 auto *NewLoad = cast<LoadInst>(
2304 Builder.CreateLoad(ElemType, GEP, EI->getName() + ".scalar"));
2305
2306 Align ScalarOpAlignment =
2307 computeAlignmentAfterScalarization(LI->getAlign(), ElemType, Idx, *DL);
2308 NewLoad->setAlignment(ScalarOpAlignment);
2309 NewLoad->copyMetadata(*LI,
2310 {LLVMContext::MD_mmra, LLVMContext::MD_nontemporal,
2311 LLVMContext::MD_mem_cache_hint});
2312
2313 if (auto *ConstIdx = dyn_cast<ConstantInt>(Idx)) {
2314 size_t Offset = ConstIdx->getZExtValue() * DL->getTypeStoreSize(ElemType);
2315 AAMDNodes OldAAMD = LI->getAAMetadata();
2316 NewLoad->setAAMetadata(OldAAMD.adjustForAccess(Offset, ElemType, *DL));
2317 }
2318
2319 replaceValue(*EI, *NewLoad, false);
2320 }
2321
2322 FailureGuard.release();
2323 return true;
2324}
2325
2326/// Try to scalarize vector loads feeding bitcast instructions.
2327bool VectorCombine::scalarizeLoadBitcast(LoadInst *LI, VectorType *VecTy,
2328 Value *Ptr) {
2329 InstructionCost OriginalCost =
2330 TTI.getMemoryOpCost(Instruction::Load, VecTy, LI->getAlign(),
2331 LI->getPointerAddressSpace(), CostKind);
2332
2333 if (!isa<FixedVectorType>(VecTy))
2334 return false;
2335
2336 Type *TargetScalarType = nullptr;
2337 unsigned VecBitWidth = DL->getTypeSizeInBits(VecTy);
2338
2339 for (User *U : LI->users()) {
2340 auto *BC = cast<BitCastInst>(U);
2341
2342 Type *DestTy = BC->getDestTy();
2343 if (!DestTy->isIntegerTy() && !DestTy->isFloatingPointTy())
2344 return false;
2345
2346 unsigned DestBitWidth = DL->getTypeSizeInBits(DestTy);
2347 if (DestBitWidth != VecBitWidth)
2348 return false;
2349
2350 // All bitcasts must target the same scalar type.
2351 if (!TargetScalarType)
2352 TargetScalarType = DestTy;
2353 else if (TargetScalarType != DestTy)
2354 return false;
2355
2356 OriginalCost +=
2357 TTI.getCastInstrCost(Instruction::BitCast, TargetScalarType, VecTy,
2358 TTI.getCastContextHint(BC), CostKind, BC);
2359 }
2360
2361 if (!TargetScalarType)
2362 return false;
2363
2364 assert(!LI->user_empty() && "Unexpected load without bitcast users");
2365 InstructionCost ScalarizedCost =
2366 TTI.getMemoryOpCost(Instruction::Load, TargetScalarType, LI->getAlign(),
2367 LI->getPointerAddressSpace(), CostKind);
2368
2369 LLVM_DEBUG(dbgs() << "Found vector load feeding only bitcasts: " << *LI
2370 << "\n OriginalCost: " << OriginalCost
2371 << " vs ScalarizedCost: " << ScalarizedCost << "\n");
2372
2373 if (ScalarizedCost >= OriginalCost)
2374 return false;
2375
2376 // Ensure we add the load back to the worklist BEFORE its users so they can
2377 // erased in the correct order.
2378 Worklist.push(LI);
2379
2380 Builder.SetInsertPoint(LI);
2381 auto *ScalarLoad =
2382 Builder.CreateLoad(TargetScalarType, Ptr, LI->getName() + ".scalar");
2383 ScalarLoad->setAlignment(LI->getAlign());
2384 ScalarLoad->copyMetadata(*LI);
2385
2386 // Replace all bitcast users with the scalar load.
2387 for (User *U : LI->users()) {
2388 auto *BC = cast<BitCastInst>(U);
2389 replaceValue(*BC, *ScalarLoad, false);
2390 }
2391
2392 return true;
2393}
2394
2395bool VectorCombine::scalarizeExtExtract(Instruction &I) {
2397 return false;
2398 auto *Ext = dyn_cast<ZExtInst>(&I);
2399 if (!Ext)
2400 return false;
2401
2402 // Try to convert a vector zext feeding only extracts to a set of scalar
2403 // (Src << ExtIdx *Size) & (Size -1)
2404 // if profitable .
2405 auto *SrcTy = dyn_cast<FixedVectorType>(Ext->getOperand(0)->getType());
2406 if (!SrcTy)
2407 return false;
2408 auto *DstTy = cast<FixedVectorType>(Ext->getType());
2409
2410 Type *ScalarDstTy = DstTy->getElementType();
2411 if (DL->getTypeSizeInBits(SrcTy) != DL->getTypeSizeInBits(ScalarDstTy))
2412 return false;
2413
2414 InstructionCost VectorCost =
2415 TTI.getCastInstrCost(Instruction::ZExt, DstTy, SrcTy,
2416 TTI::CastContextHint::None, CostKind, Ext);
2417 unsigned ExtCnt = 0;
2418 bool ExtLane0 = false;
2419 for (Instruction *U : Ext->users()) {
2420 uint64_t Idx;
2421 if (!match(U, m_ExtractElt(m_Value(), m_ConstantInt(Idx))))
2422 return false;
2423 // An out-of-bounds extractelement produces poison; bail out rather
2424 // than computing a shift amount that overflows the packed type.
2425 if (Idx >= SrcTy->getNumElements())
2426 return false;
2427 if (U->use_empty())
2428 continue;
2429 ExtCnt += 1;
2430 ExtLane0 |= !Idx;
2431 VectorCost += TTI.getVectorInstrCost(Instruction::ExtractElement, DstTy,
2432 CostKind, Idx, U);
2433 }
2434
2435 InstructionCost ScalarCost =
2436 ExtCnt * TTI.getArithmeticInstrCost(
2437 Instruction::And, ScalarDstTy, CostKind,
2440 (ExtCnt - ExtLane0) *
2442 Instruction::LShr, ScalarDstTy, CostKind,
2445 if (ScalarCost > VectorCost)
2446 return false;
2447
2448 Value *ScalarV = Ext->getOperand(0);
2449 if (!isGuaranteedNotToBePoison(ScalarV, SQ.AC, dyn_cast<Instruction>(ScalarV),
2450 SQ.DT)) {
2451 // Check wether all lanes are extracted, all extracts trigger UB
2452 // on poison, and the last extract (and hence all previous ones)
2453 // are guaranteed to execute if Ext executes. If so, we do not
2454 // need to insert a freeze.
2455 SmallDenseSet<ConstantInt *, 8> ExtractedLanes;
2456 bool AllExtractsTriggerUB = true;
2457 ExtractElementInst *LastExtract = nullptr;
2458 BasicBlock *ExtBB = Ext->getParent();
2459 for (User *U : Ext->users()) {
2460 auto *Extract = cast<ExtractElementInst>(U);
2461 if (Extract->getParent() != ExtBB || !programUndefinedIfPoison(Extract)) {
2462 AllExtractsTriggerUB = false;
2463 break;
2464 }
2465 ExtractedLanes.insert(cast<ConstantInt>(Extract->getIndexOperand()));
2466 if (!LastExtract || LastExtract->comesBefore(Extract))
2467 LastExtract = Extract;
2468 }
2469 if (ExtractedLanes.size() != DstTy->getNumElements() ||
2470 !AllExtractsTriggerUB ||
2472 LastExtract->getIterator()))
2473 ScalarV = Builder.CreateFreeze(ScalarV);
2474 }
2475 ScalarV = Builder.CreateBitCast(
2476 ScalarV,
2477 IntegerType::get(SrcTy->getContext(), DL->getTypeSizeInBits(SrcTy)));
2478 uint64_t SrcEltSizeInBits = DL->getTypeSizeInBits(SrcTy->getElementType());
2479 uint64_t TotalBits = DL->getTypeSizeInBits(SrcTy);
2480 APInt EltBitMask = APInt::getLowBitsSet(TotalBits, SrcEltSizeInBits);
2481 Type *PackedTy = IntegerType::get(SrcTy->getContext(), TotalBits);
2482 Value *Mask = ConstantInt::get(PackedTy, EltBitMask);
2483 for (User *U : Ext->users()) {
2484 auto *Extract = cast<ExtractElementInst>(U);
2485 uint64_t Idx =
2486 cast<ConstantInt>(Extract->getIndexOperand())->getZExtValue();
2487 uint64_t ShiftAmt =
2488 DL->isBigEndian()
2489 ? (TotalBits - SrcEltSizeInBits - Idx * SrcEltSizeInBits)
2490 : (Idx * SrcEltSizeInBits);
2491 Value *LShr = Builder.CreateLShr(ScalarV, ShiftAmt);
2492 Value *And = Builder.CreateAnd(LShr, Mask);
2493 U->replaceAllUsesWith(And);
2494 }
2495 return true;
2496}
2497
2498/// Try to fold "(or (zext (bitcast X)), (shl (zext (bitcast Y)), C))"
2499/// to "(bitcast (concat X, Y))"
2500/// where X/Y are bitcasted from i1 mask vectors.
2501bool VectorCombine::foldConcatOfBoolMasks(Instruction &I) {
2502 Type *Ty = I.getType();
2503 if (!Ty->isIntegerTy())
2504 return false;
2505
2506 // TODO: Add big endian test coverage
2507 if (DL->isBigEndian())
2508 return false;
2509
2510 // Restrict to disjoint cases so the mask vectors aren't overlapping.
2511 Instruction *X, *Y;
2513 return false;
2514
2515 // Allow both sources to contain shl, to handle more generic pattern:
2516 // "(or (shl (zext (bitcast X)), C1), (shl (zext (bitcast Y)), C2))"
2517 Value *SrcX;
2518 uint64_t ShAmtX = 0;
2519 if (!match(X, m_OneUse(m_ZExt(m_OneUse(m_BitCast(m_Value(SrcX)))))) &&
2520 !match(X, m_OneUse(
2522 m_ConstantInt(ShAmtX)))))
2523 return false;
2524
2525 Value *SrcY;
2526 uint64_t ShAmtY = 0;
2527 if (!match(Y, m_OneUse(m_ZExt(m_OneUse(m_BitCast(m_Value(SrcY)))))) &&
2528 !match(Y, m_OneUse(
2530 m_ConstantInt(ShAmtY)))))
2531 return false;
2532
2533 // Canonicalize larger shift to the RHS.
2534 if (ShAmtX > ShAmtY) {
2535 std::swap(X, Y);
2536 std::swap(SrcX, SrcY);
2537 std::swap(ShAmtX, ShAmtY);
2538 }
2539
2540 // Ensure both sources are matching vXi1 bool mask types, and that the shift
2541 // difference is the mask width so they can be easily concatenated together.
2542 uint64_t ShAmtDiff = ShAmtY - ShAmtX;
2543 unsigned NumSHL = (ShAmtX > 0) + (ShAmtY > 0);
2544 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
2545 auto *MaskTy = dyn_cast<FixedVectorType>(SrcX->getType());
2546 if (!MaskTy || SrcX->getType() != SrcY->getType() ||
2547 !MaskTy->getElementType()->isIntegerTy(1) ||
2548 MaskTy->getNumElements() != ShAmtDiff ||
2549 MaskTy->getNumElements() > (BitWidth / 2))
2550 return false;
2551
2552 auto *ConcatTy = FixedVectorType::getDoubleElementsVectorType(MaskTy);
2553 auto *ConcatIntTy =
2554 Type::getIntNTy(Ty->getContext(), ConcatTy->getNumElements());
2555 auto *MaskIntTy = Type::getIntNTy(Ty->getContext(), ShAmtDiff);
2556
2557 SmallVector<int, 32> ConcatMask(ConcatTy->getNumElements());
2558 std::iota(ConcatMask.begin(), ConcatMask.end(), 0);
2559
2560 // TODO: Is it worth supporting multi use cases?
2561 InstructionCost OldCost = 0;
2562 OldCost += TTI.getArithmeticInstrCost(Instruction::Or, Ty, CostKind);
2563 OldCost +=
2564 NumSHL * TTI.getArithmeticInstrCost(Instruction::Shl, Ty, CostKind);
2565 OldCost += 2 * TTI.getCastInstrCost(Instruction::ZExt, Ty, MaskIntTy,
2566 TTI::CastContextHint::None, CostKind);
2567 OldCost += 2 * TTI.getCastInstrCost(Instruction::BitCast, MaskIntTy, MaskTy,
2568 TTI::CastContextHint::None, CostKind);
2569
2570 InstructionCost NewCost = 0;
2572 MaskTy, CostKind, ConcatMask);
2573 NewCost += TTI.getCastInstrCost(Instruction::BitCast, ConcatIntTy, ConcatTy,
2574 TTI::CastContextHint::None, CostKind);
2575 if (Ty != ConcatIntTy)
2576 NewCost += TTI.getCastInstrCost(Instruction::ZExt, Ty, ConcatIntTy,
2577 TTI::CastContextHint::None, CostKind);
2578 if (ShAmtX > 0)
2579 NewCost += TTI.getArithmeticInstrCost(Instruction::Shl, Ty, CostKind);
2580
2581 LLVM_DEBUG(dbgs() << "Found a concatenation of bitcasted bool masks: " << I
2582 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
2583 << "\n");
2584
2585 if (NewCost > OldCost)
2586 return false;
2587
2588 // Build bool mask concatenation, bitcast back to scalar integer, and perform
2589 // any residual zero-extension or shifting.
2590 Value *Concat = Builder.CreateShuffleVector(SrcX, SrcY, ConcatMask);
2591
2592 Value *Result = Builder.CreateBitCast(Concat, ConcatIntTy);
2593
2594 if (Ty != ConcatIntTy) {
2595 Result = Builder.CreateZExt(Result, Ty);
2596 }
2597
2598 if (ShAmtX > 0) {
2599 Result = Builder.CreateShl(Result, ShAmtX);
2600 }
2601
2602 replaceValue(I, *Result);
2603 return true;
2604}
2605
2606/// Try to convert "shuffle (binop (shuffle, shuffle)), undef"
2607/// --> "binop (shuffle), (shuffle)".
2608bool VectorCombine::foldPermuteOfBinops(Instruction &I) {
2609 BinaryOperator *BinOp;
2610 ArrayRef<int> OuterMask;
2611 if (!match(&I, m_Shuffle(m_BinOp(BinOp), m_Undef(), m_Mask(OuterMask))))
2612 return false;
2613
2614 // Don't introduce poison into div/rem.
2615 if (BinOp->isIntDivRem() && llvm::is_contained(OuterMask, PoisonMaskElem))
2616 return false;
2617
2618 Value *Op00, *Op01, *Op10, *Op11;
2619 ArrayRef<int> Mask0, Mask1;
2620 bool Match0 = match(BinOp->getOperand(0),
2621 m_Shuffle(m_Value(Op00), m_Value(Op01), m_Mask(Mask0)));
2622 bool Match1 = match(BinOp->getOperand(1),
2623 m_Shuffle(m_Value(Op10), m_Value(Op11), m_Mask(Mask1)));
2624 if (!Match0 && !Match1)
2625 return false;
2626
2627 Op00 = Match0 ? Op00 : BinOp->getOperand(0);
2628 Op01 = Match0 ? Op01 : BinOp->getOperand(0);
2629 Op10 = Match1 ? Op10 : BinOp->getOperand(1);
2630 Op11 = Match1 ? Op11 : BinOp->getOperand(1);
2631
2632 Instruction::BinaryOps Opcode = BinOp->getOpcode();
2633 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
2634 auto *BinOpTy = dyn_cast<FixedVectorType>(BinOp->getType());
2635 auto *Op0Ty = dyn_cast<FixedVectorType>(Op00->getType());
2636 auto *Op1Ty = dyn_cast<FixedVectorType>(Op10->getType());
2637 if (!ShuffleDstTy || !BinOpTy || !Op0Ty || !Op1Ty)
2638 return false;
2639
2640 unsigned NumSrcElts = BinOpTy->getNumElements();
2641
2642 // Don't accept shuffles that reference the second operand in
2643 // div/rem or if its an undef arg.
2644 if ((BinOp->isIntDivRem() || !isa<PoisonValue>(I.getOperand(1))) &&
2645 any_of(OuterMask, [NumSrcElts](int M) { return M >= (int)NumSrcElts; }))
2646 return false;
2647
2648 // Merge outer / inner (or identity if no match) shuffles.
2649 SmallVector<int> NewMask0, NewMask1;
2650 for (int M : OuterMask) {
2651 if (M < 0 || M >= (int)NumSrcElts) {
2652 NewMask0.push_back(PoisonMaskElem);
2653 NewMask1.push_back(PoisonMaskElem);
2654 } else {
2655 NewMask0.push_back(Match0 ? Mask0[M] : M);
2656 NewMask1.push_back(Match1 ? Mask1[M] : M);
2657 }
2658 }
2659
2660 unsigned NumOpElts = Op0Ty->getNumElements();
2661 bool IsIdentity0 = ShuffleDstTy == Op0Ty &&
2662 all_of(NewMask0, [NumOpElts](int M) { return M < (int)NumOpElts; }) &&
2663 ShuffleVectorInst::isIdentityMask(NewMask0, NumOpElts);
2664 bool IsIdentity1 = ShuffleDstTy == Op1Ty &&
2665 all_of(NewMask1, [NumOpElts](int M) { return M < (int)NumOpElts; }) &&
2666 ShuffleVectorInst::isIdentityMask(NewMask1, NumOpElts);
2667
2668 InstructionCost NewCost = 0;
2669 // Try to merge shuffles across the binop if the new shuffles are not costly.
2670 InstructionCost BinOpCost =
2671 TTI.getArithmeticInstrCost(Opcode, BinOpTy, CostKind);
2672 InstructionCost OldCost =
2674 ShuffleDstTy, BinOpTy, CostKind, OuterMask,
2675 0, nullptr, {BinOp}, &I);
2676 if (!BinOp->hasOneUse())
2677 NewCost += BinOpCost;
2678
2679 if (Match0) {
2681 TargetTransformInfo::SK_PermuteTwoSrc, BinOpTy, Op0Ty, CostKind, Mask0,
2682 0, nullptr, {Op00, Op01}, cast<Instruction>(BinOp->getOperand(0)));
2683 OldCost += Shuf0Cost;
2684 if (!BinOp->hasOneUse() || !BinOp->getOperand(0)->hasOneUse())
2685 NewCost += Shuf0Cost;
2686 }
2687 if (Match1) {
2689 TargetTransformInfo::SK_PermuteTwoSrc, BinOpTy, Op1Ty, CostKind, Mask1,
2690 0, nullptr, {Op10, Op11}, cast<Instruction>(BinOp->getOperand(1)));
2691 OldCost += Shuf1Cost;
2692 if (!BinOp->hasOneUse() || !BinOp->getOperand(1)->hasOneUse())
2693 NewCost += Shuf1Cost;
2694 }
2695
2696 NewCost += TTI.getArithmeticInstrCost(Opcode, ShuffleDstTy, CostKind);
2697
2698 if (!IsIdentity0)
2699 NewCost +=
2701 Op0Ty, CostKind, NewMask0, 0, nullptr, {Op00, Op01});
2702 if (!IsIdentity1)
2703 NewCost +=
2705 Op1Ty, CostKind, NewMask1, 0, nullptr, {Op10, Op11});
2706
2707 LLVM_DEBUG(dbgs() << "Found a shuffle feeding a shuffled binop: " << I
2708 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
2709 << "\n");
2710
2711 // If costs are equal, still fold as we reduce instruction count.
2712 if (NewCost > OldCost)
2713 return false;
2714
2715 Value *LHS =
2716 IsIdentity0 ? Op00 : Builder.CreateShuffleVector(Op00, Op01, NewMask0);
2717 Value *RHS =
2718 IsIdentity1 ? Op10 : Builder.CreateShuffleVector(Op10, Op11, NewMask1);
2719 Value *NewBO = Builder.CreateBinOp(Opcode, LHS, RHS);
2720
2721 // Intersect flags from the old binops.
2722 if (auto *NewInst = dyn_cast<Instruction>(NewBO))
2723 NewInst->copyIRFlags(BinOp);
2724
2725 replaceValue(I, *NewBO);
2726 return true;
2727}
2728
2729/// Try to convert "shuffle (binop), (binop)" into "binop (shuffle), (shuffle)".
2730/// Try to convert "shuffle (cmpop), (cmpop)" into "cmpop (shuffle), (shuffle)".
2731bool VectorCombine::foldShuffleOfBinops(Instruction &I) {
2732 ArrayRef<int> OldMask;
2733 Instruction *LHS, *RHS;
2735 m_Mask(OldMask))))
2736 return false;
2737
2738 // TODO: Add support for addlike etc.
2739 if (LHS->getOpcode() != RHS->getOpcode())
2740 return false;
2741
2742 Value *X, *Y, *Z, *W;
2743 bool IsCommutative = false;
2744 CmpPredicate PredLHS = CmpInst::BAD_ICMP_PREDICATE;
2745 CmpPredicate PredRHS = CmpInst::BAD_ICMP_PREDICATE;
2746 if (match(LHS, m_BinOp(m_Value(X), m_Value(Y))) &&
2747 match(RHS, m_BinOp(m_Value(Z), m_Value(W)))) {
2748 auto *BO = cast<BinaryOperator>(LHS);
2749 // Don't introduce poison into div/rem.
2750 if (llvm::is_contained(OldMask, PoisonMaskElem) && BO->isIntDivRem())
2751 return false;
2752 IsCommutative = BinaryOperator::isCommutative(BO->getOpcode());
2753 } else if (match(LHS, m_Cmp(PredLHS, m_Value(X), m_Value(Y))) &&
2754 match(RHS, m_Cmp(PredRHS, m_Value(Z), m_Value(W))) &&
2755 (CmpInst::Predicate)PredLHS == (CmpInst::Predicate)PredRHS) {
2756 IsCommutative = cast<CmpInst>(LHS)->isCommutative();
2757 } else
2758 return false;
2759
2760 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
2761 auto *BinResTy = dyn_cast<FixedVectorType>(LHS->getType());
2762 auto *BinOpTy = dyn_cast<FixedVectorType>(X->getType());
2763 if (!ShuffleDstTy || !BinResTy || !BinOpTy || X->getType() != Z->getType())
2764 return false;
2765
2766 bool SameBinOp = LHS == RHS;
2767 unsigned NumSrcElts = BinOpTy->getNumElements();
2768
2769 // If we have something like "add X, Y" and "add Z, X", swap ops to match.
2770 if (IsCommutative && X != Z && Y != W && (X == W || Y == Z))
2771 std::swap(X, Y);
2772
2773 auto ConvertToUnary = [NumSrcElts](int &M) {
2774 if (M >= (int)NumSrcElts)
2775 M -= NumSrcElts;
2776 };
2777
2778 SmallVector<int> NewMask0(OldMask);
2780 TTI::OperandValueInfo Op0Info = TTI.commonOperandInfo(X, Z);
2781 if (X == Z) {
2782 llvm::for_each(NewMask0, ConvertToUnary);
2784 Z = PoisonValue::get(BinOpTy);
2785 }
2786
2787 SmallVector<int> NewMask1(OldMask);
2789 TTI::OperandValueInfo Op1Info = TTI.commonOperandInfo(Y, W);
2790 if (Y == W) {
2791 llvm::for_each(NewMask1, ConvertToUnary);
2793 W = PoisonValue::get(BinOpTy);
2794 }
2795
2796 // Try to replace a binop with a shuffle if the shuffle is not costly.
2797 // When SameBinOp, only count the binop cost once.
2798 InstructionCost LHSCost = TTI.getInstructionCost(LHS, CostKind);
2799 InstructionCost RHSCost = TTI.getInstructionCost(RHS, CostKind);
2800
2801 InstructionCost OldCost = LHSCost;
2802 if (!SameBinOp) {
2803 OldCost += RHSCost;
2804 }
2806 ShuffleDstTy, BinResTy, CostKind, OldMask, 0,
2807 nullptr, {LHS, RHS}, &I);
2808
2809 // Handle shuffle(binop(shuffle(x),y),binop(z,shuffle(w))) style patterns
2810 // where one use shuffles have gotten split across the binop/cmp. These
2811 // often allow a major reduction in total cost that wouldn't happen as
2812 // individual folds.
2813 auto MergeInner = [&](Value *&Op, int Offset, MutableArrayRef<int> Mask,
2814 TTI::TargetCostKind CostKind,
2815 Instruction *BinOp) -> bool {
2816 Value *InnerOp;
2817 ArrayRef<int> InnerMask;
2818 if (match(Op, m_OneUse(m_Shuffle(m_Value(InnerOp), m_Undef(),
2819 m_Mask(InnerMask)))) &&
2820 InnerOp->getType() == Op->getType() &&
2821 all_of(InnerMask,
2822 [NumSrcElts](int M) { return M < (int)NumSrcElts; })) {
2823 for (int &M : Mask)
2824 if (Offset <= M && M < (int)(Offset + NumSrcElts)) {
2825 M = InnerMask[M - Offset];
2826 M = 0 <= M ? M + Offset : M;
2827 }
2828 // Op is only removed if the binop using it is removed too.
2829 bool Removed = BinOp->hasOneUser();
2830 if (Removed)
2831 OldCost += TTI.getInstructionCost(cast<Instruction>(Op), CostKind);
2832 Op = InnerOp;
2833 return Removed;
2834 }
2835 return false;
2836 };
2837 bool ReducedInstCount = false;
2838 ReducedInstCount |= MergeInner(X, 0, NewMask0, CostKind, LHS);
2839 ReducedInstCount |= MergeInner(Y, 0, NewMask1, CostKind, LHS);
2840 ReducedInstCount |= MergeInner(Z, NumSrcElts, NewMask0, CostKind, RHS);
2841 ReducedInstCount |= MergeInner(W, NumSrcElts, NewMask1, CostKind, RHS);
2842 bool SingleSrcBinOp = (X == Y) && (Z == W) && (NewMask0 == NewMask1);
2843 // SingleSrcBinOp only reduces instruction count if we also eliminate the
2844 // original binop(s). If binops have multiple uses, they won't be eliminated.
2845 ReducedInstCount |= SingleSrcBinOp && LHS->hasOneUser() && RHS->hasOneUser();
2846
2847 // For concat shuffles of i1 vectors where both binops are one-use, the
2848 // transform keeps the same instruction count but canonicalises to a single
2849 // wider binop, enabling downstream folds (e.g. NOT(XOR(concat(a,b),
2850 // concat(c,d))) -> XNOR(concat(a,b),concat(c,d)) on AVX-512 mask regs).
2851 // Restrict to BinaryOperator (not CmpInst) since narrow comparisons may
2852 // be cheaper than wide ones on some targets (e.g. AVX-512 vpcmpeq).
2853 ReducedInstCount |= cast<ShuffleVectorInst>(&I)->isConcat() &&
2854 I.getType()->getScalarType()->isIntegerTy(1) &&
2856 RHS->hasOneUser();
2857
2858 auto *ShuffleCmpTy =
2859 FixedVectorType::get(BinOpTy->getElementType(), ShuffleDstTy);
2861 SK0, ShuffleCmpTy, BinOpTy, CostKind, NewMask0, 0, nullptr, {X, Z});
2862 if (!SingleSrcBinOp)
2863 NewCost += TTI.getShuffleCost(SK1, ShuffleCmpTy, BinOpTy, CostKind,
2864 NewMask1, 0, nullptr, {Y, W});
2865
2866 if (PredLHS == CmpInst::BAD_ICMP_PREDICATE) {
2867 NewCost += TTI.getArithmeticInstrCost(LHS->getOpcode(), ShuffleDstTy,
2868 CostKind, Op0Info, Op1Info);
2869 } else {
2870 NewCost +=
2871 TTI.getCmpSelInstrCost(LHS->getOpcode(), ShuffleCmpTy, ShuffleDstTy,
2872 PredLHS, CostKind, Op0Info, Op1Info);
2873 }
2874 // If LHS/RHS have other uses, we need to account for the cost of keeping
2875 // the original instructions. When SameBinOp, only add the cost once.
2876 if (!LHS->hasOneUser())
2877 NewCost += LHSCost;
2878 if (!SameBinOp && !RHS->hasOneUser())
2879 NewCost += RHSCost;
2880
2881 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two binops: " << I
2882 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
2883 << "\n");
2884
2885 // If either shuffle will constant fold away, then fold for the same cost as
2886 // we will reduce the instruction count.
2887 ReducedInstCount |= (isa<Constant>(X) && isa<Constant>(Z)) ||
2888 (isa<Constant>(Y) && isa<Constant>(W));
2889 if (ReducedInstCount ? (NewCost > OldCost) : (NewCost >= OldCost))
2890 return false;
2891
2892 Value *Shuf0 = Builder.CreateShuffleVector(X, Z, NewMask0);
2893 Value *Shuf1 =
2894 SingleSrcBinOp ? Shuf0 : Builder.CreateShuffleVector(Y, W, NewMask1);
2895 Value *NewBO = PredLHS == CmpInst::BAD_ICMP_PREDICATE
2896 ? Builder.CreateBinOp(
2897 cast<BinaryOperator>(LHS)->getOpcode(), Shuf0, Shuf1)
2898 : Builder.CreateCmp(PredLHS, Shuf0, Shuf1);
2899
2900 // Intersect flags from the old binops.
2901 if (auto *NewInst = dyn_cast<Instruction>(NewBO)) {
2902 NewInst->copyIRFlags(LHS);
2903 NewInst->andIRFlags(RHS);
2904 }
2905
2906 replaceValue(I, *NewBO);
2907 return true;
2908}
2909
2910/// Try to convert,
2911/// (shuffle(select(c1,t1,f1)), (select(c2,t2,f2)), m) into
2912/// (select (shuffle c1,c2,m), (shuffle t1,t2,m), (shuffle f1,f2,m))
2913bool VectorCombine::foldShuffleOfSelects(Instruction &I) {
2914 ArrayRef<int> Mask;
2915 Value *C1, *T1, *F1, *C2, *T2, *F2;
2917 m_Select(m_Value(C2), m_Value(T2), m_Value(F2)),
2918 m_Mask(Mask))))
2919 return false;
2920
2921 auto *Sel1 = cast<Instruction>(I.getOperand(0));
2922 auto *Sel2 = cast<Instruction>(I.getOperand(1));
2923
2924 auto *C1VecTy = dyn_cast<FixedVectorType>(C1->getType());
2925 auto *C2VecTy = dyn_cast<FixedVectorType>(C2->getType());
2926 if (!C1VecTy || !C2VecTy || C1VecTy != C2VecTy)
2927 return false;
2928
2929 auto *SI0FOp = dyn_cast<FPMathOperator>(I.getOperand(0));
2930 auto *SI1FOp = dyn_cast<FPMathOperator>(I.getOperand(1));
2931 // SelectInsts must have the same FMF.
2932 if (((SI0FOp == nullptr) != (SI1FOp == nullptr)) ||
2933 ((SI0FOp != nullptr) &&
2934 (SI0FOp->getFastMathFlags() != SI1FOp->getFastMathFlags())))
2935 return false;
2936
2937 auto *SrcVecTy = cast<FixedVectorType>(T1->getType());
2938 auto *DstVecTy = cast<FixedVectorType>(I.getType());
2940 auto SelOp = Instruction::Select;
2941
2943 SelOp, SrcVecTy, C1VecTy, CmpInst::BAD_ICMP_PREDICATE, CostKind);
2945 SelOp, SrcVecTy, C2VecTy, CmpInst::BAD_ICMP_PREDICATE, CostKind);
2946
2947 InstructionCost OldCost =
2948 CostSel1 + CostSel2 +
2949 TTI.getShuffleCost(SK, DstVecTy, SrcVecTy, CostKind, Mask, 0, nullptr,
2950 {I.getOperand(0), I.getOperand(1)}, &I);
2951
2953 SK, FixedVectorType::get(C1VecTy->getScalarType(), Mask.size()), C1VecTy,
2954 CostKind, Mask, 0, nullptr, {C1, C2});
2955 NewCost += TTI.getShuffleCost(SK, DstVecTy, SrcVecTy, CostKind, Mask, 0,
2956 nullptr, {T1, T2});
2957 NewCost += TTI.getShuffleCost(SK, DstVecTy, SrcVecTy, CostKind, Mask, 0,
2958 nullptr, {F1, F2});
2959 auto *C1C2ShuffledVecTy = FixedVectorType::get(
2960 Type::getInt1Ty(I.getContext()), DstVecTy->getNumElements());
2961 NewCost += TTI.getCmpSelInstrCost(SelOp, DstVecTy, C1C2ShuffledVecTy,
2962 CmpInst::BAD_ICMP_PREDICATE, CostKind);
2963
2964 if (!Sel1->hasOneUse())
2965 NewCost += CostSel1;
2966 if (!Sel2->hasOneUse())
2967 NewCost += CostSel2;
2968
2969 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two selects: " << I
2970 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
2971 << "\n");
2972 if (NewCost > OldCost)
2973 return false;
2974
2975 Value *ShuffleCmp = Builder.CreateShuffleVector(C1, C2, Mask);
2976 Value *ShuffleTrue = Builder.CreateShuffleVector(T1, T2, Mask);
2977 Value *ShuffleFalse = Builder.CreateShuffleVector(F1, F2, Mask);
2978 Value *NewSel;
2979 // We presuppose that the SelectInsts have the same FMF.
2980 if (SI0FOp)
2981 NewSel = Builder.CreateSelectFMF(ShuffleCmp, ShuffleTrue, ShuffleFalse,
2982 SI0FOp->getFastMathFlags());
2983 else
2984 NewSel = Builder.CreateSelect(ShuffleCmp, ShuffleTrue, ShuffleFalse);
2985
2986 replaceValue(I, *NewSel);
2987 return true;
2988}
2989
2990/// Try to convert "shuffle (castop), (castop)" with a shared castop operand
2991/// into "castop (shuffle)".
2992bool VectorCombine::foldShuffleOfCastops(Instruction &I) {
2993 Value *V0, *V1;
2994 ArrayRef<int> OldMask;
2995 if (!match(&I, m_Shuffle(m_Value(V0), m_Value(V1), m_Mask(OldMask))))
2996 return false;
2997
2998 // Check whether this is a binary shuffle.
2999 bool IsBinaryShuffle = !isa<UndefValue>(V1);
3000
3001 auto *C0 = dyn_cast<CastInst>(V0);
3002 auto *C1 = dyn_cast<CastInst>(V1);
3003 if (!C0 || (IsBinaryShuffle && !C1))
3004 return false;
3005
3006 Instruction::CastOps Opcode = C0->getOpcode();
3007
3008 // If this is allowed, foldShuffleOfCastops can get stuck in a loop
3009 // with foldBitcastOfShuffle. Reject in favor of foldBitcastOfShuffle.
3010 if (!IsBinaryShuffle && Opcode == Instruction::BitCast)
3011 return false;
3012
3013 if (IsBinaryShuffle) {
3014 if (C0->getSrcTy() != C1->getSrcTy())
3015 return false;
3016 // Handle shuffle(zext_nneg(x), sext(y)) -> sext(shuffle(x,y)) folds.
3017 if (Opcode != C1->getOpcode()) {
3019 Opcode = Instruction::SExt;
3020 else
3021 return false;
3022 }
3023 }
3024
3025 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
3026 auto *CastDstTy = dyn_cast<FixedVectorType>(C0->getDestTy());
3027 auto *CastSrcTy = dyn_cast<FixedVectorType>(C0->getSrcTy());
3028 if (!ShuffleDstTy || !CastDstTy || !CastSrcTy)
3029 return false;
3030
3031 unsigned NumSrcElts = CastSrcTy->getNumElements();
3032 unsigned NumDstElts = CastDstTy->getNumElements();
3033 assert((NumDstElts == NumSrcElts || Opcode == Instruction::BitCast) &&
3034 "Only bitcasts expected to alter src/dst element counts");
3035
3036 // Check for bitcasting of unscalable vector types.
3037 // e.g. <32 x i40> -> <40 x i32>
3038 if (NumDstElts != NumSrcElts && (NumSrcElts % NumDstElts) != 0 &&
3039 (NumDstElts % NumSrcElts) != 0)
3040 return false;
3041
3042 SmallVector<int, 16> NewMask;
3043 if (NumSrcElts >= NumDstElts) {
3044 // The bitcast is from wide to narrow/equal elements. The shuffle mask can
3045 // always be expanded to the equivalent form choosing narrower elements.
3046 assert(NumSrcElts % NumDstElts == 0 && "Unexpected shuffle mask");
3047 unsigned ScaleFactor = NumSrcElts / NumDstElts;
3048 narrowShuffleMaskElts(ScaleFactor, OldMask, NewMask);
3049 } else {
3050 // The bitcast is from narrow elements to wide elements. The shuffle mask
3051 // must choose consecutive elements to allow casting first.
3052 assert(NumDstElts % NumSrcElts == 0 && "Unexpected shuffle mask");
3053 unsigned ScaleFactor = NumDstElts / NumSrcElts;
3054 if (!widenShuffleMaskElts(ScaleFactor, OldMask, NewMask))
3055 return false;
3056 }
3057
3058 auto *NewShuffleDstTy =
3059 FixedVectorType::get(CastSrcTy->getScalarType(), NewMask.size());
3060
3061 // Try to replace a castop with a shuffle if the shuffle is not costly.
3062 InstructionCost CostC0 =
3063 TTI.getCastInstrCost(C0->getOpcode(), CastDstTy, CastSrcTy,
3064 TTI::CastContextHint::None, CostKind, C0);
3065
3067 if (IsBinaryShuffle)
3069 else
3071
3072 InstructionCost OldCost = CostC0;
3073 OldCost += TTI.getShuffleCost(ShuffleKind, ShuffleDstTy, CastDstTy, CostKind,
3074 OldMask, 0, nullptr, {}, &I);
3075
3076 InstructionCost NewCost = TTI.getShuffleCost(ShuffleKind, NewShuffleDstTy,
3077 CastSrcTy, CostKind, NewMask);
3078 NewCost += TTI.getCastInstrCost(Opcode, ShuffleDstTy, NewShuffleDstTy,
3079 TTI::CastContextHint::None, CostKind);
3080 if (!C0->hasOneUse())
3081 NewCost += CostC0;
3082 if (IsBinaryShuffle) {
3083 InstructionCost CostC1 =
3084 TTI.getCastInstrCost(C1->getOpcode(), CastDstTy, CastSrcTy,
3085 TTI::CastContextHint::None, CostKind, C1);
3086 OldCost += CostC1;
3087 if (!C1->hasOneUse())
3088 NewCost += CostC1;
3089 }
3090
3091 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two casts: " << I
3092 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
3093 << "\n");
3094 if (NewCost > OldCost)
3095 return false;
3096
3097 Value *Shuf;
3098 if (IsBinaryShuffle)
3099 Shuf = Builder.CreateShuffleVector(C0->getOperand(0), C1->getOperand(0),
3100 NewMask);
3101 else
3102 Shuf = Builder.CreateShuffleVector(C0->getOperand(0), NewMask);
3103
3104 Value *Cast = Builder.CreateCast(Opcode, Shuf, ShuffleDstTy);
3105
3106 // Intersect flags from the old casts.
3107 if (auto *NewInst = dyn_cast<Instruction>(Cast)) {
3108 NewInst->copyIRFlags(C0);
3109 if (IsBinaryShuffle)
3110 NewInst->andIRFlags(C1);
3111 }
3112
3113 replaceValue(I, *Cast);
3114 return true;
3115}
3116
3117/// Try to convert any of:
3118/// "shuffle (shuffle x, y), (shuffle y, x)"
3119/// "shuffle (shuffle x, undef), (shuffle y, undef)"
3120/// "shuffle (shuffle x, undef), y"
3121/// "shuffle x, (shuffle y, undef)"
3122/// into "shuffle x, y".
3123bool VectorCombine::foldShuffleOfShuffles(Instruction &I) {
3124 ArrayRef<int> OuterMask;
3125 Value *OuterV0, *OuterV1;
3126 if (!match(&I,
3127 m_Shuffle(m_Value(OuterV0), m_Value(OuterV1), m_Mask(OuterMask))))
3128 return false;
3129
3130 ArrayRef<int> InnerMask0, InnerMask1;
3131 Value *X0, *X1, *Y0, *Y1;
3132 bool Match0 =
3133 match(OuterV0, m_Shuffle(m_Value(X0), m_Value(Y0), m_Mask(InnerMask0)));
3134 bool Match1 =
3135 match(OuterV1, m_Shuffle(m_Value(X1), m_Value(Y1), m_Mask(InnerMask1)));
3136 if (!Match0 && !Match1)
3137 return false;
3138
3139 // If the outer shuffle is a permute, then create a fake inner all-poison
3140 // shuffle. This is easier than accounting for length-changing shuffles below.
3141 SmallVector<int, 16> PoisonMask1;
3142 if (!Match1 && isa<PoisonValue>(OuterV1)) {
3143 X1 = X0;
3144 Y1 = Y0;
3145 PoisonMask1.append(InnerMask0.size(), PoisonMaskElem);
3146 InnerMask1 = PoisonMask1;
3147 Match1 = true; // fake match
3148 }
3149
3150 X0 = Match0 ? X0 : OuterV0;
3151 Y0 = Match0 ? Y0 : OuterV0;
3152 X1 = Match1 ? X1 : OuterV1;
3153 Y1 = Match1 ? Y1 : OuterV1;
3154 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
3155 auto *ShuffleSrcTy = dyn_cast<FixedVectorType>(X0->getType());
3156 auto *ShuffleImmTy = dyn_cast<FixedVectorType>(OuterV0->getType());
3157 if (!ShuffleDstTy || !ShuffleSrcTy || !ShuffleImmTy ||
3158 X0->getType() != X1->getType())
3159 return false;
3160
3161 unsigned NumSrcElts = ShuffleSrcTy->getNumElements();
3162 unsigned NumImmElts = ShuffleImmTy->getNumElements();
3163
3164 // Attempt to merge shuffles, matching upto 2 source operands.
3165 // Replace index to a poison arg with PoisonMaskElem.
3166 // Bail if either inner masks reference an undef arg.
3167 SmallVector<int, 16> NewMask(OuterMask);
3168 Value *NewX = nullptr, *NewY = nullptr;
3169 for (int &M : NewMask) {
3170 Value *Src = nullptr;
3171 if (0 <= M && M < (int)NumImmElts) {
3172 Src = OuterV0;
3173 if (Match0) {
3174 M = InnerMask0[M];
3175 Src = M >= (int)NumSrcElts ? Y0 : X0;
3176 M = M >= (int)NumSrcElts ? (M - NumSrcElts) : M;
3177 }
3178 } else if (M >= (int)NumImmElts) {
3179 Src = OuterV1;
3180 M -= NumImmElts;
3181 if (Match1) {
3182 M = InnerMask1[M];
3183 Src = M >= (int)NumSrcElts ? Y1 : X1;
3184 M = M >= (int)NumSrcElts ? (M - NumSrcElts) : M;
3185 }
3186 }
3187 if (Src && M != PoisonMaskElem) {
3188 assert(0 <= M && M < (int)NumSrcElts && "Unexpected shuffle mask index");
3189 if (isa<UndefValue>(Src)) {
3190 // We've referenced an undef element - if its poison, update the shuffle
3191 // mask, else bail.
3192 if (!isa<PoisonValue>(Src))
3193 return false;
3194 M = PoisonMaskElem;
3195 continue;
3196 }
3197 if (!NewX || NewX == Src) {
3198 NewX = Src;
3199 continue;
3200 }
3201 if (!NewY || NewY == Src) {
3202 M += NumSrcElts;
3203 NewY = Src;
3204 continue;
3205 }
3206 return false;
3207 }
3208 }
3209
3210 if (!NewX) {
3211 replaceValue(I, *PoisonValue::get(ShuffleDstTy));
3212 return true;
3213 }
3214
3215 if (!NewY)
3216 NewY = PoisonValue::get(ShuffleSrcTy);
3217
3218 // Have we folded to an Identity shuffle?
3219 if (ShuffleVectorInst::isIdentityMask(NewMask, NumSrcElts)) {
3220 replaceValue(I, *NewX);
3221 return true;
3222 }
3223
3224 // Try to merge the shuffles if the new shuffle is not costly.
3225 InstructionCost InnerCost0 = 0;
3226 if (Match0)
3227 InnerCost0 = TTI.getInstructionCost(cast<User>(OuterV0), CostKind);
3228
3229 InstructionCost InnerCost1 = 0;
3230 if (Match1)
3231 InnerCost1 = TTI.getInstructionCost(cast<User>(OuterV1), CostKind);
3232
3233 InstructionCost OuterCost = TTI.getInstructionCost(&I, CostKind);
3234
3235 InstructionCost OldCost = InnerCost0 + InnerCost1 + OuterCost;
3236
3237 bool IsUnary = all_of(NewMask, [&](int M) { return M < (int)NumSrcElts; });
3241 InstructionCost NewCost =
3242 TTI.getShuffleCost(SK, ShuffleDstTy, ShuffleSrcTy, CostKind, NewMask, 0,
3243 nullptr, {NewX, NewY});
3244 if (!OuterV0->hasOneUse())
3245 NewCost += InnerCost0;
3246 if (!OuterV1->hasOneUse())
3247 NewCost += InnerCost1;
3248
3249 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two shuffles: " << I
3250 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
3251 << "\n");
3252 if (NewCost > OldCost)
3253 return false;
3254
3255 Value *Shuf = Builder.CreateShuffleVector(NewX, NewY, NewMask);
3256 replaceValue(I, *Shuf);
3257 return true;
3258}
3259
3260/// Try to convert a chain of length-preserving shuffles that are fed by
3261/// length-changing shuffles from the same source, e.g. a chain of length 3:
3262///
3263/// "shuffle (shuffle (shuffle x, (shuffle y, undef)),
3264/// (shuffle y, undef)),
3265// (shuffle y, undef)"
3266///
3267/// into a single shuffle fed by a length-changing shuffle:
3268///
3269/// "shuffle x, (shuffle y, undef)"
3270///
3271/// Such chains arise e.g. from folding extract/insert sequences.
3272bool VectorCombine::foldShufflesOfLengthChangingShuffles(Instruction &I) {
3273 FixedVectorType *TrunkType = dyn_cast<FixedVectorType>(I.getType());
3274 if (!TrunkType)
3275 return false;
3276
3277 unsigned ChainLength = 0;
3278 SmallVector<int> Mask;
3279 SmallVector<int> YMask;
3280 InstructionCost OldCost = 0;
3281 InstructionCost NewCost = 0;
3282 Value *Trunk = &I;
3283 unsigned NumTrunkElts = TrunkType->getNumElements();
3284 Value *Y = nullptr;
3285
3286 for (;;) {
3287 // Match the current trunk against (commutations of) the pattern
3288 // "shuffle trunk', (shuffle y, undef)"
3289 ArrayRef<int> OuterMask;
3290 Value *OuterV0, *OuterV1;
3291 if (ChainLength != 0 && !Trunk->hasOneUse())
3292 break;
3293 if (!match(Trunk, m_Shuffle(m_Value(OuterV0), m_Value(OuterV1),
3294 m_Mask(OuterMask))))
3295 break;
3296 if (OuterV0->getType() != TrunkType) {
3297 // This shuffle is not length-preserving, so it cannot be part of the
3298 // chain.
3299 break;
3300 }
3301
3302 ArrayRef<int> InnerMask0, InnerMask1;
3303 Value *A0, *A1, *B0, *B1;
3304 bool Match0 =
3305 match(OuterV0, m_Shuffle(m_Value(A0), m_Value(B0), m_Mask(InnerMask0)));
3306 bool Match1 =
3307 match(OuterV1, m_Shuffle(m_Value(A1), m_Value(B1), m_Mask(InnerMask1)));
3308 bool Match0Leaf = Match0 && A0->getType() != I.getType();
3309 bool Match1Leaf = Match1 && A1->getType() != I.getType();
3310 if (Match0Leaf == Match1Leaf) {
3311 // Only handle the case of exactly one leaf in each step. The "two leaves"
3312 // case is handled by foldShuffleOfShuffles.
3313 break;
3314 }
3315
3316 SmallVector<int> CommutedOuterMask;
3317 if (Match0Leaf) {
3318 std::swap(OuterV0, OuterV1);
3319 std::swap(InnerMask0, InnerMask1);
3320 std::swap(A0, A1);
3321 std::swap(B0, B1);
3322 llvm::append_range(CommutedOuterMask, OuterMask);
3323 for (int &M : CommutedOuterMask) {
3324 if (M == PoisonMaskElem)
3325 continue;
3326 if (M < (int)NumTrunkElts)
3327 M += NumTrunkElts;
3328 else
3329 M -= NumTrunkElts;
3330 }
3331 OuterMask = CommutedOuterMask;
3332 }
3333 if (!OuterV1->hasOneUse())
3334 break;
3335
3336 if (!isa<UndefValue>(A1)) {
3337 if (!Y)
3338 Y = A1;
3339 else if (Y != A1)
3340 break;
3341 }
3342 if (!isa<UndefValue>(B1)) {
3343 if (!Y)
3344 Y = B1;
3345 else if (Y != B1)
3346 break;
3347 }
3348
3349 auto *YType = cast<FixedVectorType>(A1->getType());
3350 int NumLeafElts = YType->getNumElements();
3351 SmallVector<int> LocalYMask(InnerMask1);
3352 for (int &M : LocalYMask) {
3353 if (M >= NumLeafElts)
3354 M -= NumLeafElts;
3355 }
3356
3357 InstructionCost LocalOldCost =
3358 TTI.getInstructionCost(cast<User>(Trunk), CostKind) +
3359 TTI.getInstructionCost(cast<User>(OuterV1), CostKind);
3360
3361 // Handle the initial (start of chain) case.
3362 if (!ChainLength) {
3363 Mask.assign(OuterMask);
3364 YMask.assign(LocalYMask);
3365 OldCost = NewCost = LocalOldCost;
3366 Trunk = OuterV0;
3367 ChainLength++;
3368 continue;
3369 }
3370
3371 // For the non-root case, first attempt to combine masks.
3372 SmallVector<int> NewYMask(YMask);
3373 bool Valid = true;
3374 for (auto [CombinedM, LeafM] : llvm::zip(NewYMask, LocalYMask)) {
3375 if (LeafM == -1 || CombinedM == LeafM)
3376 continue;
3377 if (CombinedM == -1) {
3378 CombinedM = LeafM;
3379 } else {
3380 Valid = false;
3381 break;
3382 }
3383 }
3384 if (!Valid)
3385 break;
3386
3387 SmallVector<int> NewMask;
3388 NewMask.reserve(NumTrunkElts);
3389 for (int M : Mask) {
3390 if (M < 0 || M >= static_cast<int>(NumTrunkElts))
3391 NewMask.push_back(M);
3392 else
3393 NewMask.push_back(OuterMask[M]);
3394 }
3395
3396 // Break the chain if adding this new step complicates the shuffles such
3397 // that it would increase the new cost by more than the old cost of this
3398 // step.
3399 InstructionCost LocalNewCost =
3401 YType, CostKind, NewYMask) +
3403 TrunkType, CostKind, NewMask);
3404
3405 if (LocalNewCost >= NewCost && LocalOldCost < LocalNewCost - NewCost)
3406 break;
3407
3408 LLVM_DEBUG({
3409 if (ChainLength == 1) {
3410 dbgs() << "Found chain of shuffles fed by length-changing shuffles: "
3411 << I << '\n';
3412 }
3413 dbgs() << " next chain link: " << *Trunk << '\n'
3414 << " old cost: " << (OldCost + LocalOldCost)
3415 << " new cost: " << LocalNewCost << '\n';
3416 });
3417
3418 Mask = NewMask;
3419 YMask = NewYMask;
3420 OldCost += LocalOldCost;
3421 NewCost = LocalNewCost;
3422 Trunk = OuterV0;
3423 ChainLength++;
3424 }
3425 if (ChainLength <= 1)
3426 return false;
3427
3428 // Bail out if all leaves were poison.
3429 if (!Y)
3430 return false;
3431
3432 if (llvm::all_of(Mask, [&](int M) {
3433 return M < 0 || M >= static_cast<int>(NumTrunkElts);
3434 })) {
3435 // Produce a canonical simplified form if all elements are sourced from Y.
3436 for (int &M : Mask) {
3437 if (M >= static_cast<int>(NumTrunkElts))
3438 M = YMask[M - NumTrunkElts];
3439 }
3440 Value *Root =
3441 Builder.CreateShuffleVector(Y, PoisonValue::get(Y->getType()), Mask);
3442 replaceValue(I, *Root);
3443 return true;
3444 }
3445
3446 Value *Leaf =
3447 Builder.CreateShuffleVector(Y, PoisonValue::get(Y->getType()), YMask);
3448 Value *Root = Builder.CreateShuffleVector(Trunk, Leaf, Mask);
3449 replaceValue(I, *Root);
3450 return true;
3451}
3452
3453/// Try to convert
3454/// "shuffle (intrinsic), (intrinsic)" into "intrinsic (shuffle), (shuffle)".
3455bool VectorCombine::foldShuffleOfIntrinsics(Instruction &I) {
3456 Value *V0, *V1;
3457 ArrayRef<int> OldMask;
3458 if (!match(&I, m_Shuffle(m_Value(V0), m_Value(V1), m_Mask(OldMask))))
3459 return false;
3460
3461 auto *II0 = dyn_cast<IntrinsicInst>(V0);
3462 auto *II1 = dyn_cast<IntrinsicInst>(V1);
3463 if (!II0 || !II1)
3464 return false;
3465
3466 Intrinsic::ID IID = II0->getIntrinsicID();
3467 if (IID != II1->getIntrinsicID())
3468 return false;
3469 InstructionCost CostII0 =
3470 TTI.getIntrinsicInstrCost(IntrinsicCostAttributes(IID, *II0), CostKind);
3471 InstructionCost CostII1 =
3472 TTI.getIntrinsicInstrCost(IntrinsicCostAttributes(IID, *II1), CostKind);
3473
3474 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
3475 auto *II0Ty = dyn_cast<FixedVectorType>(II0->getType());
3476 if (!ShuffleDstTy || !II0Ty)
3477 return false;
3478
3479 if (!isTriviallyVectorizable(IID))
3480 return false;
3481
3482 for (unsigned Idx = 0, E = II0->arg_size(); Idx != E; ++Idx) {
3483 Value *Arg0 = II0->getArgOperand(Idx);
3484 Value *Arg1 = II1->getArgOperand(Idx);
3485 if (isVectorIntrinsicWithScalarOpAtArg(IID, Idx, &TTI)) {
3486 // Scalar operands must be identical.
3487 if (Arg0 != Arg1)
3488 return false;
3489 } else if (Arg0->getType() != Arg1->getType()) {
3490 // The corresponding vector operands are shuffled together, so they must
3491 // share the same type. For intrinsics overloaded on their operand type
3492 // (e.g. llvm.fptosi.sat), two calls can produce the same result type
3493 // from different operand types; shuffling those would be invalid.
3494 return false;
3495 }
3496 }
3497
3498 InstructionCost OldCost =
3499 CostII0 + CostII1 +
3501 II0Ty, CostKind, OldMask, 0, nullptr, {II0, II1}, &I);
3502
3503 SmallVector<Type *> NewArgsTy;
3504 InstructionCost NewCost = 0;
3505 SmallDenseSet<std::pair<Value *, Value *>> SeenOperandPairs;
3506 for (unsigned Idx = 0, E = II0->arg_size(); Idx != E; ++Idx) {
3507 if (isVectorIntrinsicWithScalarOpAtArg(IID, Idx, &TTI)) {
3508 NewArgsTy.push_back(II0->getArgOperand(Idx)->getType());
3509 } else {
3510 auto *VecTy = cast<FixedVectorType>(II0->getArgOperand(Idx)->getType());
3511 auto *ArgTy = FixedVectorType::get(VecTy->getElementType(),
3512 ShuffleDstTy->getNumElements());
3513 NewArgsTy.push_back(ArgTy);
3514 std::pair<Value *, Value *> OperandPair =
3515 std::make_pair(II0->getArgOperand(Idx), II1->getArgOperand(Idx));
3516 if (!SeenOperandPairs.insert(OperandPair).second) {
3517 // We've already computed the cost for this operand pair.
3518 continue;
3519 }
3520 NewCost += TTI.getShuffleCost(
3521 TargetTransformInfo::SK_PermuteTwoSrc, ArgTy, VecTy, CostKind,
3522 OldMask, 0, nullptr,
3523 {II0->getArgOperand(Idx), II1->getArgOperand(Idx)});
3524 }
3525 }
3526 IntrinsicCostAttributes NewAttr(IID, ShuffleDstTy, NewArgsTy);
3527
3528 NewCost += TTI.getIntrinsicInstrCost(NewAttr, CostKind);
3529 if (!II0->hasOneUse())
3530 NewCost += CostII0;
3531 if (II1 != II0 && !II1->hasOneUse())
3532 NewCost += CostII1;
3533
3534 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two intrinsics: " << I
3535 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
3536 << "\n");
3537
3538 if (NewCost > OldCost)
3539 return false;
3540
3541 SmallVector<Value *> NewArgs;
3542 SmallDenseMap<std::pair<Value *, Value *>, Value *> ShuffleCache;
3543 for (unsigned Idx = 0, E = II0->arg_size(); Idx != E; ++Idx) {
3544 if (isVectorIntrinsicWithScalarOpAtArg(IID, Idx, &TTI)) {
3545 NewArgs.push_back(II0->getArgOperand(Idx));
3546 } else {
3547 std::pair<Value *, Value *> OperandPair =
3548 std::make_pair(II0->getArgOperand(Idx), II1->getArgOperand(Idx));
3549 auto It = ShuffleCache.find(OperandPair);
3550 if (It != ShuffleCache.end()) {
3551 // Reuse previously created shuffle for this operand pair.
3552 NewArgs.push_back(It->second);
3553 continue;
3554 }
3555 Value *Shuf = Builder.CreateShuffleVector(
3556 II0->getArgOperand(Idx), II1->getArgOperand(Idx), OldMask);
3557 ShuffleCache[OperandPair] = Shuf;
3558 NewArgs.push_back(Shuf);
3559 }
3560 }
3561 Value *NewIntrinsic = Builder.CreateIntrinsic(ShuffleDstTy, IID, NewArgs);
3562
3563 // Intersect flags from the old intrinsics.
3564 if (auto *NewInst = dyn_cast<Instruction>(NewIntrinsic)) {
3565 NewInst->copyIRFlags(II0);
3566 NewInst->andIRFlags(II1);
3567 }
3568
3569 replaceValue(I, *NewIntrinsic);
3570 return true;
3571}
3572
3573/// Try to convert
3574/// "shuffle (intrinsic), (poison/undef)" into "intrinsic (shuffle)".
3575bool VectorCombine::foldPermuteOfIntrinsic(Instruction &I) {
3576 Value *V0;
3577 ArrayRef<int> Mask;
3578 if (!match(&I, m_Shuffle(m_Value(V0), m_Undef(), m_Mask(Mask))))
3579 return false;
3580
3581 auto *II0 = dyn_cast<IntrinsicInst>(V0);
3582 if (!II0)
3583 return false;
3584
3585 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
3586 auto *IntrinsicSrcTy = dyn_cast<FixedVectorType>(II0->getType());
3587 if (!ShuffleDstTy || !IntrinsicSrcTy)
3588 return false;
3589
3590 // Validate it's a pure permute, mask should only reference the first vector
3591 unsigned NumSrcElts = IntrinsicSrcTy->getNumElements();
3592 if (any_of(Mask, [NumSrcElts](int M) { return M >= (int)NumSrcElts; }))
3593 return false;
3594
3595 Intrinsic::ID IID = II0->getIntrinsicID();
3596 if (!isTriviallyVectorizable(IID))
3597 return false;
3598
3599 // Cost analysis
3601 TTI.getIntrinsicInstrCost(IntrinsicCostAttributes(IID, *II0), CostKind);
3602 InstructionCost OldCost =
3605 IntrinsicSrcTy, CostKind, Mask, 0, nullptr, {V0}, &I);
3606
3607 SmallVector<Type *> NewArgsTy;
3608 InstructionCost NewCost = 0;
3609 for (unsigned I = 0, E = II0->arg_size(); I != E; ++I) {
3611 NewArgsTy.push_back(II0->getArgOperand(I)->getType());
3612 } else {
3613 auto *VecTy = cast<FixedVectorType>(II0->getArgOperand(I)->getType());
3614 auto *ArgTy = FixedVectorType::get(VecTy->getElementType(),
3615 ShuffleDstTy->getNumElements());
3616 NewArgsTy.push_back(ArgTy);
3618 ArgTy, VecTy, CostKind, Mask, 0, nullptr,
3619 {II0->getArgOperand(I)});
3620 }
3621 }
3622 IntrinsicCostAttributes NewAttr(IID, ShuffleDstTy, NewArgsTy);
3623 NewCost += TTI.getIntrinsicInstrCost(NewAttr, CostKind);
3624
3625 // If the intrinsic has multiple uses, we need to account for the cost of
3626 // keeping the original intrinsic around.
3627 if (!II0->hasOneUse())
3628 NewCost += IntrinsicCost;
3629
3630 LLVM_DEBUG(dbgs() << "Found a permute of intrinsic: " << I << "\n OldCost: "
3631 << OldCost << " vs NewCost: " << NewCost << "\n");
3632
3633 if (NewCost > OldCost)
3634 return false;
3635
3636 // Transform
3637 SmallVector<Value *> NewArgs;
3638 for (unsigned I = 0, E = II0->arg_size(); I != E; ++I) {
3640 NewArgs.push_back(II0->getArgOperand(I));
3641 } else {
3642 Value *Shuf = Builder.CreateShuffleVector(II0->getArgOperand(I), Mask);
3643 NewArgs.push_back(Shuf);
3644 }
3645 }
3646
3647 Value *NewIntrinsic = Builder.CreateIntrinsic(ShuffleDstTy, IID, NewArgs);
3648
3649 if (auto *NewInst = dyn_cast<Instruction>(NewIntrinsic))
3650 NewInst->copyIRFlags(II0);
3651
3652 replaceValue(I, *NewIntrinsic);
3653 return true;
3654}
3655
3656using InstLane = std::pair<Value *, int>;
3657
3659 while (auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
3660 unsigned NumElts =
3661 cast<FixedVectorType>(SV->getOperand(0)->getType())->getNumElements();
3662 int M = SV->getMaskValue(Lane);
3663 if (M < 0)
3664 return {nullptr, PoisonMaskElem};
3665 if (static_cast<unsigned>(M) < NumElts) {
3666 V = SV->getOperand(0);
3667 Lane = M;
3668 } else {
3669 V = SV->getOperand(1);
3670 Lane = M - NumElts;
3671 }
3672 }
3673 return InstLane{V, Lane};
3674}
3675
3679 for (InstLane IL : Item) {
3680 auto [U, Lane] = IL;
3681 InstLane OpLane =
3682 U ? lookThroughShuffles(cast<Instruction>(U)->getOperand(Op), Lane)
3683 : InstLane{nullptr, PoisonMaskElem};
3684 NItem.emplace_back(OpLane);
3685 }
3686 return NItem;
3687}
3688
3689/// Detect concat of multiple values into a vector
3691 const TargetTransformInfo &TTI) {
3692 auto *Ty = cast<FixedVectorType>(Item.front().first->getType());
3693 unsigned NumElts = Ty->getNumElements();
3694 if (Item.size() == NumElts || NumElts == 1 || Item.size() % NumElts != 0)
3695 return false;
3696
3697 // Check that the concat is free, usually meaning that the type will be split
3698 // during legalization.
3699 SmallVector<int, 16> ConcatMask(NumElts * 2);
3700 std::iota(ConcatMask.begin(), ConcatMask.end(), 0);
3701 if (TTI.getShuffleCost(TTI::SK_PermuteTwoSrc,
3702 FixedVectorType::get(Ty->getScalarType(), NumElts * 2),
3703 Ty, CostKind, ConcatMask) != 0)
3704 return false;
3705
3706 unsigned NumSlices = Item.size() / NumElts;
3707 // Currently we generate a tree of shuffles for the concats, which limits us
3708 // to a power2.
3709 if (!isPowerOf2_32(NumSlices))
3710 return false;
3711 for (unsigned Slice = 0; Slice < NumSlices; ++Slice) {
3712 Value *SliceV = Item[Slice * NumElts].first;
3713 if (!SliceV || SliceV->getType() != Ty)
3714 return false;
3715 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
3716 auto [V, Lane] = Item[Slice * NumElts + Elt];
3717 if (Lane != static_cast<int>(Elt) || SliceV != V)
3718 return false;
3719 }
3720 }
3721 return true;
3722}
3723
3724static Value *
3726 const DenseSet<std::pair<Value *, Use *>> &IdentityLeafs,
3727 const DenseSet<std::pair<Value *, Use *>> &SplatLeafs,
3728 const DenseSet<std::pair<Value *, Use *>> &ConcatLeafs,
3729 IRBuilderBase &Builder, InstructionWorklist &WorkList,
3730 const TargetTransformInfo *TTI) {
3731 auto [FrontV, FrontLane] = Item.front();
3732
3733 if (IdentityLeafs.contains(std::make_pair(FrontV, From))) {
3734 return FrontV;
3735 }
3736 if (SplatLeafs.contains(std::make_pair(FrontV, From))) {
3737 SmallVector<int, 16> Mask(Item.size(), FrontLane);
3738 return Builder.CreateShuffleVector(FrontV, Mask);
3739 }
3740 if (ConcatLeafs.contains(std::make_pair(FrontV, From))) {
3741 unsigned NumElts =
3742 cast<FixedVectorType>(FrontV->getType())->getNumElements();
3743 SmallVector<Value *> Values(Item.size() / NumElts, nullptr);
3744 for (size_t S = 0; S < Values.size(); ++S)
3745 Values[S] = Item[S * NumElts].first;
3746
3747 while (Values.size() > 1) {
3748 NumElts *= 2;
3749 SmallVector<int, 16> Mask(NumElts, 0);
3750 std::iota(Mask.begin(), Mask.end(), 0);
3751 SmallVector<Value *> NewValues(Values.size() / 2, nullptr);
3752 for (unsigned S = 0; S < NewValues.size(); ++S)
3753 NewValues[S] =
3754 Builder.CreateShuffleVector(Values[S * 2], Values[S * 2 + 1], Mask);
3755 Values = NewValues;
3756 }
3757 return Values[0];
3758 }
3759
3760 auto *I = cast<Instruction>(FrontV);
3761
3762 // Handle vector bitcasts that change element count. We cannot use
3763 // generateInstLaneVectorFromOperand for these because the lane indices
3764 // don't map 1:1 through the bitcast.
3765 if (auto *BitCast = dyn_cast<BitCastInst>(I)) {
3766 auto *BCDstTy = dyn_cast<FixedVectorType>(BitCast->getDestTy());
3767 auto *BCSrcTy = dyn_cast<FixedVectorType>(BitCast->getSrcTy());
3768 if (BCDstTy && BCSrcTy &&
3769 BCDstTy->getElementCount() != BCSrcTy->getElementCount()) {
3770 unsigned DstElts = BCDstTy->getNumElements();
3771 unsigned SrcElts = BCSrcTy->getNumElements();
3772 SmallVector<InstLane> NewItem;
3773 if (DstElts > SrcElts) {
3774 // Widening: compress operand Item.
3775 unsigned R = DstElts / SrcElts;
3776 if (Item.size() % R != 0)
3777 return nullptr;
3778 for (unsigned Idx = 0, E = Item.size(); Idx < E; Idx += R) {
3779 auto [V, Lane] = Item[Idx];
3780 if (!V) {
3781 NewItem.push_back({nullptr, PoisonMaskElem});
3782 continue;
3783 }
3784 NewItem.push_back(
3785 lookThroughShuffles(cast<Operator>(V)->getOperand(0), Lane / R));
3786 }
3787 } else {
3788 // Narrowing: expand operand Item.
3789 unsigned R = SrcElts / DstElts;
3790 for (auto [V, Lane] : Item) {
3791 if (!V) {
3792 NewItem.append(R, {nullptr, PoisonMaskElem});
3793 continue;
3794 }
3795 Value *Op = cast<Operator>(V)->getOperand(0);
3796 for (unsigned J = 0; J < R; ++J)
3797 NewItem.push_back(lookThroughShuffles(Op, Lane * R + J));
3798 }
3799 }
3800 Value *Op = generateNewInstTree(NewItem, &BitCast->getOperandUse(0),
3801 IdentityLeafs, SplatLeafs, ConcatLeafs,
3802 Builder, WorkList, TTI);
3803 return Builder.CreateBitCast(
3804 Op, FixedVectorType::get(BCDstTy->getScalarType(), Item.size()));
3805 }
3806 }
3807 auto *II = dyn_cast<IntrinsicInst>(I);
3808 unsigned NumOps = I->getNumOperands() - (II ? 1 : 0);
3810 for (unsigned Idx = 0; Idx < NumOps; Idx++) {
3811 if (II &&
3812 isVectorIntrinsicWithScalarOpAtArg(II->getIntrinsicID(), Idx, TTI)) {
3813 Ops[Idx] = II->getOperand(Idx);
3814 continue;
3815 }
3816 Ops[Idx] = generateNewInstTree(
3817 generateInstLaneVectorFromOperand(Item, Idx), &I->getOperandUse(Idx),
3818 IdentityLeafs, SplatLeafs, ConcatLeafs, Builder, WorkList, TTI);
3819 // Don't re-queue the operand of a bitcast we just regenerated. Doing so
3820 // lets foldBitcastShuffle sink the bitcast back into a shuffle(bitcast),
3821 // which foldShuffleToIdentity then re-matches as the same superfluous
3822 // identity - an infinite loop between the two folds.
3823 // TODO: we should fix algorithms in foldBitcastShuffle and
3824 // foldShuffleToIdentity instead of workaround the problem in worklist.
3825 if (isa<BitCastInst>(I) && isa<Instruction>(Ops[Idx]))
3826 WorkList.remove(cast<Instruction>(Ops[Idx]));
3827 }
3828
3829 SmallVector<Value *, 8> ValueList;
3830 for (const auto &Lane : Item)
3831 if (Lane.first)
3832 ValueList.push_back(Lane.first);
3833
3834 Type *DstTy =
3835 FixedVectorType::get(I->getType()->getScalarType(), Item.size());
3836 if (auto *BI = dyn_cast<BinaryOperator>(I)) {
3837 auto *Value = Builder.CreateBinOp((Instruction::BinaryOps)BI->getOpcode(),
3838 Ops[0], Ops[1]);
3839 propagateIRFlags(Value, ValueList);
3840 return Value;
3841 }
3842 if (auto *CI = dyn_cast<CmpInst>(I)) {
3843 auto *Value = Builder.CreateCmp(CI->getPredicate(), Ops[0], Ops[1]);
3844 propagateIRFlags(Value, ValueList);
3845 return Value;
3846 }
3847 if (auto *SI = dyn_cast<SelectInst>(I)) {
3848 auto *Value = Builder.CreateSelect(Ops[0], Ops[1], Ops[2], "", SI);
3849 propagateIRFlags(Value, ValueList);
3850 return Value;
3851 }
3852 if (auto *CI = dyn_cast<CastInst>(I)) {
3853 auto *Value = Builder.CreateCast(CI->getOpcode(), Ops[0], DstTy);
3854 propagateIRFlags(Value, ValueList);
3855 return Value;
3856 }
3857 if (II) {
3858 auto *Value = Builder.CreateIntrinsic(DstTy, II->getIntrinsicID(), Ops);
3859 propagateIRFlags(Value, ValueList);
3860 return Value;
3861 }
3862 assert(isa<UnaryInstruction>(I) && "Unexpected instruction type in Generate");
3863 auto *Value =
3864 Builder.CreateUnOp((Instruction::UnaryOps)I->getOpcode(), Ops[0]);
3865 propagateIRFlags(Value, ValueList);
3866 return Value;
3867}
3868
3869// Starting from a shuffle, look up through operands tracking the shuffled index
3870// of each lane. If we can simplify away the shuffles to identities then
3871// do so.
3872bool VectorCombine::foldShuffleToIdentity(Instruction &I) {
3873 auto *Ty = dyn_cast<FixedVectorType>(I.getType());
3874 if (!Ty || I.use_empty())
3875 return false;
3876
3877 SmallVector<InstLane> Start(Ty->getNumElements());
3878 for (unsigned M = 0, E = Ty->getNumElements(); M < E; ++M)
3879 Start[M] = lookThroughShuffles(&I, M);
3880
3882 Candidates.push_back(std::make_pair(Start, &*I.use_begin()));
3883 DenseSet<std::pair<Value *, Use *>> IdentityLeafs, SplatLeafs, ConcatLeafs;
3884 unsigned NumVisited = 0;
3885 bool TraversedElCountChangingBitcast = false;
3886
3887 while (!Candidates.empty()) {
3888 if (++NumVisited > Opts.vector_combine_max_scan_instrs)
3889 return false;
3890
3891 auto ItemFrom = Candidates.pop_back_val();
3892 auto Item = ItemFrom.first;
3893 auto From = ItemFrom.second;
3894 auto [FrontV, FrontLane] = Item.front();
3895
3896 // If we found an undef first lane then bail out to keep things simple.
3897 if (!FrontV)
3898 return false;
3899
3900 // Look for an identity value.
3901 if (FrontLane == 0 &&
3902 cast<FixedVectorType>(FrontV->getType())->getNumElements() ==
3903 Item.size() &&
3904 all_of(drop_begin(enumerate(Item)), [Item](const auto &E) {
3905 Value *FrontV = Item.front().first;
3906 return !E.value().first || (isEquivBitcast(E.value().first, FrontV) &&
3907 E.value().second == (int)E.index());
3908 })) {
3909 IdentityLeafs.insert(std::make_pair(FrontV, From));
3910 continue;
3911 }
3912 // Look for constants, for the moment only supporting constant splats.
3913 if (auto *C = dyn_cast<Constant>(FrontV);
3914 C && C->getSplatValue() &&
3915 all_of(drop_begin(Item), [Item](InstLane &IL) {
3916 Value *FrontV = Item.front().first;
3917 Value *V = IL.first;
3918 return !V || (isa<Constant>(V) &&
3919 cast<Constant>(V)->getSplatValue() ==
3920 cast<Constant>(FrontV)->getSplatValue());
3921 })) {
3922 SplatLeafs.insert(std::make_pair(FrontV, From));
3923 continue;
3924 }
3925 // Look for a splat value.
3926 if (all_of(drop_begin(Item), [Item](InstLane &IL) {
3927 auto [FrontV, FrontLane] = Item.front();
3928 auto [V, Lane] = IL;
3929 return !V || (V == FrontV && Lane == FrontLane);
3930 })) {
3931 SplatLeafs.insert(std::make_pair(FrontV, From));
3932 continue;
3933 }
3934
3935 // We need each element to be the same type of value, and check that each
3936 // element has a single use.
3937 auto CheckLaneIsEquivalentToFirst = [Item](InstLane IL) {
3938 Value *FrontV = Item.front().first;
3939 if (!IL.first)
3940 return true;
3941 Value *V = IL.first;
3942 if (auto *I = dyn_cast<Instruction>(V); I && !I->hasOneUser())
3943 return false;
3944 if (V->getValueID() != FrontV->getValueID())
3945 return false;
3946 if (auto *CI = dyn_cast<CmpInst>(V))
3947 if (CI->getPredicate() != cast<CmpInst>(FrontV)->getPredicate())
3948 return false;
3949 if (auto *CI = dyn_cast<CastInst>(V))
3950 if (CI->getSrcTy()->getScalarType() !=
3951 cast<CastInst>(FrontV)->getSrcTy()->getScalarType())
3952 return false;
3953 if (auto *SI = dyn_cast<SelectInst>(V))
3954 if (!isa<VectorType>(SI->getOperand(0)->getType()) ||
3955 SI->getOperand(0)->getType() !=
3956 cast<SelectInst>(FrontV)->getOperand(0)->getType())
3957 return false;
3959 return false;
3960 auto *II = dyn_cast<IntrinsicInst>(V);
3961 return !II || (isa<IntrinsicInst>(FrontV) &&
3962 II->getIntrinsicID() ==
3963 cast<IntrinsicInst>(FrontV)->getIntrinsicID() &&
3964 !II->hasOperandBundles());
3965 };
3966 if (all_of(drop_begin(Item), CheckLaneIsEquivalentToFirst)) {
3967 // Check the operator is one that we support.
3968 if (isa<BinaryOperator, CmpInst>(FrontV)) {
3969 // We exclude div/rem in case they hit UB from poison lanes.
3970 if (auto *BO = dyn_cast<BinaryOperator>(FrontV);
3971 BO && BO->isIntDivRem())
3972 return false;
3974 &cast<Instruction>(FrontV)->getOperandUse(0));
3976 &cast<Instruction>(FrontV)->getOperandUse(1));
3977 continue;
3978 } else if (isa<UnaryOperator, TruncInst, ZExtInst, SExtInst, FPToSIInst,
3979 FPToUIInst, SIToFPInst, UIToFPInst>(FrontV)) {
3981 &cast<Instruction>(FrontV)->getOperandUse(0));
3982 continue;
3983 } else if (auto *BitCast = dyn_cast<BitCastInst>(FrontV)) {
3984 auto *BCDstTy = dyn_cast<FixedVectorType>(BitCast->getDestTy());
3985 auto *BCSrcTy = dyn_cast<FixedVectorType>(BitCast->getSrcTy());
3986 if (BCDstTy && BCSrcTy) {
3987 ElementCount DstEC = BCDstTy->getElementCount();
3988 ElementCount SrcEC = BCSrcTy->getElementCount();
3989 if (DstEC == SrcEC) {
3990 // Same element count - simple pass-through.
3992 &BitCast->getOperandUse(0));
3993 continue;
3994 }
3995 unsigned DstElts = DstEC.getFixedValue();
3996 unsigned SrcElts = SrcEC.getFixedValue();
3997 if (DstElts > SrcElts && DstElts % SrcElts == 0) {
3998 // Widening bitcast (e.g. <2 x i32> -> <4 x i16>). Compress
3999 // consecutive groups of R destination lanes into one source
4000 // lane.
4001 unsigned R = DstElts / SrcElts;
4003 bool Valid = Item.size() % R == 0;
4004 for (unsigned Idx = 0, E = Item.size(); Valid && Idx < E;
4005 Idx += R) {
4006 auto [V0, L0] = Item[Idx];
4007 if (!V0) {
4008 if (any_of(ArrayRef(Item).slice(Idx + 1, R - 1),
4009 [](InstLane IL) { return IL.first != nullptr; })) {
4010 Valid = false;
4011 break;
4012 }
4013 NItem.push_back({nullptr, PoisonMaskElem});
4014 continue;
4015 }
4016 if (L0 % R != 0) {
4017 Valid = false;
4018 break;
4019 }
4020 for (unsigned J = 1; J < R; ++J) {
4021 auto [VJ, LJ] = Item[Idx + J];
4022 if (!VJ || VJ != V0 || LJ != L0 + (int)J) {
4023 Valid = false;
4024 break;
4025 }
4026 }
4027 if (!Valid)
4028 break;
4030 cast<Operator>(V0)->getOperand(0), L0 / R));
4031 }
4032 if (Valid) {
4033 TraversedElCountChangingBitcast = true;
4034 Candidates.emplace_back(NItem, &BitCast->getOperandUse(0));
4035 continue;
4036 }
4037 } else if (SrcElts > DstElts && SrcElts % DstElts == 0) {
4038 // Narrowing bitcast (e.g. <4 x i16> -> <2 x i32>). Expand
4039 // each destination lane into R source lanes.
4040 unsigned R = SrcElts / DstElts;
4042 for (auto [V, Lane] : Item) {
4043 if (!V) {
4044 NItem.append(R, {nullptr, PoisonMaskElem});
4045 continue;
4046 }
4047 Value *Op = cast<Operator>(V)->getOperand(0);
4048 for (unsigned J = 0; J < R; ++J)
4049 NItem.push_back(lookThroughShuffles(Op, Lane * R + J));
4050 }
4051 TraversedElCountChangingBitcast = true;
4052 Candidates.emplace_back(NItem, &BitCast->getOperandUse(0));
4053 continue;
4054 }
4055 }
4056 } else if (auto *Sel = dyn_cast<SelectInst>(FrontV)) {
4058 &Sel->getOperandUse(0));
4060 &Sel->getOperandUse(1));
4062 &Sel->getOperandUse(2));
4063 continue;
4064 } else if (auto *II = dyn_cast<IntrinsicInst>(FrontV);
4065 II && isTriviallyVectorizable(II->getIntrinsicID()) &&
4066 !II->hasOperandBundles()) {
4067 for (unsigned Op = 0, E = II->getNumOperands() - 1; Op < E; Op++) {
4068 if (isVectorIntrinsicWithScalarOpAtArg(II->getIntrinsicID(), Op,
4069 &TTI)) {
4070 if (!all_of(drop_begin(Item), [Item, Op](InstLane &IL) {
4071 Value *FrontV = Item.front().first;
4072 Value *V = IL.first;
4073 return !V || (cast<Instruction>(V)->getOperand(Op) ==
4074 cast<Instruction>(FrontV)->getOperand(Op));
4075 }))
4076 return false;
4077 continue;
4078 }
4079 Candidates.emplace_back(
4081 &cast<Instruction>(FrontV)->getOperandUse(Op));
4082 }
4083 continue;
4084 }
4085 }
4086
4087 if (isFreeConcat(Item, CostKind, TTI)) {
4088 ConcatLeafs.insert(std::make_pair(FrontV, From));
4089 continue;
4090 }
4091
4092 return false;
4093 }
4094
4095 if (NumVisited <= 1)
4096 return false;
4097
4098 // If the only non-leaf node traversed was a single bitcast that changes
4099 // element count, the fold would just commute the bitcast and shuffle.
4100 // foldBitcastShuffle does the reverse transform, causing an infinite loop.
4101 if (NumVisited == 2 && TraversedElCountChangingBitcast)
4102 return false;
4103
4104 LLVM_DEBUG(dbgs() << "Found a superfluous identity shuffle: " << I << "\n");
4105
4106 // If we got this far, we know the shuffles are superfluous and can be
4107 // removed. Scan through again and generate the new tree of instructions.
4108 Builder.SetInsertPoint(&I);
4109 Value *V =
4110 generateNewInstTree(Start, &*I.use_begin(), IdentityLeafs, SplatLeafs,
4111 ConcatLeafs, Builder, Worklist, &TTI);
4112 replaceValue(I, *V);
4113 return true;
4114}
4115
4116/// Given a commutative reduction, the order of the input lanes does not alter
4117/// the results. We can use this to remove certain shuffles feeding the
4118/// reduction, removing the need to shuffle at all.
4119bool VectorCombine::foldShuffleFromReductions(Instruction &I) {
4120 auto *II = dyn_cast<IntrinsicInst>(&I);
4121 if (!II)
4122 return false;
4123 switch (II->getIntrinsicID()) {
4124 case Intrinsic::vector_reduce_add:
4125 case Intrinsic::vector_reduce_mul:
4126 case Intrinsic::vector_reduce_and:
4127 case Intrinsic::vector_reduce_or:
4128 case Intrinsic::vector_reduce_xor:
4129 case Intrinsic::vector_reduce_smin:
4130 case Intrinsic::vector_reduce_smax:
4131 case Intrinsic::vector_reduce_umin:
4132 case Intrinsic::vector_reduce_umax:
4133 break;
4134 default:
4135 return false;
4136 }
4137
4138 // Find all the inputs when looking through operations that do not alter the
4139 // lane order (binops, for example). Currently we look for a single shuffle,
4140 // and can ignore splat values.
4141 std::queue<Value *> Worklist;
4142 SmallPtrSet<Value *, 4> Visited;
4143 ShuffleVectorInst *Shuffle = nullptr;
4144 if (auto *Op = dyn_cast<Instruction>(I.getOperand(0)))
4145 Worklist.push(Op);
4146
4147 while (!Worklist.empty()) {
4148 Value *CV = Worklist.front();
4149 Worklist.pop();
4150 if (Visited.contains(CV))
4151 continue;
4152
4153 // Splats don't change the order, so can be safely ignored.
4154 if (isSplatValue(CV))
4155 continue;
4156
4157 Visited.insert(CV);
4158
4159 if (auto *CI = dyn_cast<Instruction>(CV)) {
4160 if (CI->isBinaryOp()) {
4161 for (auto *Op : CI->operand_values())
4162 Worklist.push(Op);
4163 continue;
4164 } else if (auto *SV = dyn_cast<ShuffleVectorInst>(CI)) {
4165 if (Shuffle && Shuffle != SV)
4166 return false;
4167 Shuffle = SV;
4168 continue;
4169 }
4170 }
4171
4172 // Anything else is currently an unknown node.
4173 return false;
4174 }
4175
4176 if (!Shuffle)
4177 return false;
4178
4179 // Check all uses of the binary ops and shuffles are also included in the
4180 // lane-invariant operations (Visited should be the list of lanewise
4181 // instructions, including the shuffle that we found).
4182 for (auto *V : Visited)
4183 for (auto *U : V->users())
4184 if (!Visited.contains(U) && U != &I)
4185 return false;
4186
4187 FixedVectorType *VecType =
4188 dyn_cast<FixedVectorType>(II->getOperand(0)->getType());
4189 if (!VecType)
4190 return false;
4191 FixedVectorType *ShuffleInputType =
4193 if (!ShuffleInputType)
4194 return false;
4195 unsigned NumInputElts = ShuffleInputType->getNumElements();
4196
4197 // Find the mask from sorting the lanes into order. This is most likely to
4198 // become a identity or concat mask. Undef elements are pushed to the end.
4199 SmallVector<int> ConcatMask;
4200 Shuffle->getShuffleMask(ConcatMask);
4201 sort(ConcatMask, [](int X, int Y) { return (unsigned)X < (unsigned)Y; });
4202 bool UsesSecondVec =
4203 any_of(ConcatMask, [&](int M) { return M >= (int)NumInputElts; });
4204
4206 UsesSecondVec ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc, VecType,
4207 ShuffleInputType, CostKind, Shuffle->getShuffleMask());
4209 UsesSecondVec ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc, VecType,
4210 ShuffleInputType, CostKind, ConcatMask);
4211
4212 LLVM_DEBUG(dbgs() << "Found a reduction feeding from a shuffle: " << *Shuffle
4213 << "\n");
4214 LLVM_DEBUG(dbgs() << " OldCost: " << OldCost << " vs NewCost: " << NewCost
4215 << "\n");
4216 bool MadeChanges = false;
4217 if (NewCost < OldCost) {
4218 Builder.SetInsertPoint(Shuffle);
4219 Value *NewShuffle = Builder.CreateShuffleVector(
4220 Shuffle->getOperand(0), Shuffle->getOperand(1), ConcatMask);
4221 LLVM_DEBUG(dbgs() << "Created new shuffle: " << *NewShuffle << "\n");
4222 replaceValue(*Shuffle, *NewShuffle);
4223 return true;
4224 }
4225
4226 // See if we can re-use foldSelectShuffle, getting it to reduce the size of
4227 // the shuffle into a nicer order, as it can ignore the order of the shuffles.
4228 MadeChanges |= foldSelectShuffle(*Shuffle, true);
4229 return MadeChanges;
4230}
4231
4232/// Try to fold a chain of shuffles and ops feeding extractelement(..., 0)
4233/// into llvm.vector.reduce.*, by tracking which lanes contribute to the
4234/// extracted lane and reducing the widest vector whose lanes each contribute
4235/// once.
4236///
4237/// For example:
4238///
4239/// %lo = shufflevector <4 x i32> %a, poison, <2 x i32> <i32 0, i32 1>
4240/// %hi = shufflevector <4 x i32> %a, poison, <2 x i32> <i32 2, i32 3>
4241/// %s = add <2 x i32> %lo, %hi
4242/// %sh = shufflevector <2 x i32> %s, poison, <2 x i32> <i32 1, i32 poison>
4243/// %r = add <2 x i32> %s, %sh
4244/// %e = extractelement <2 x i32> %r, i64 0
4245///
4246/// transforms to:
4247///
4248/// %e = call i32 @llvm.vector.reduce.add.v4i32(<4 x i32> %a)
4249bool VectorCombine::foldShuffleChainsToReduce(Instruction &I) {
4250 Value *VecOpEE;
4251 if (!match(&I, m_ExtractElt(m_Value(VecOpEE), m_Zero())))
4252 return false;
4253
4254 auto *FVT = dyn_cast<FixedVectorType>(VecOpEE->getType());
4255 if (!FVT)
4256 return false;
4257
4258 if (FVT->getNumElements() < 2)
4259 return false;
4260
4261 std::optional<Instruction::BinaryOps> CommonBinOp;
4262 std::optional<Intrinsic::ID> CommonCallOp;
4263
4264 if (auto *BO = dyn_cast<BinaryOperator>(VecOpEE)) {
4265 if (!getReductionForBinop(BO->getOpcode()))
4266 return false;
4267 CommonBinOp = BO->getOpcode();
4268 } else if (auto *MMI = dyn_cast<MinMaxIntrinsic>(VecOpEE)) {
4269 CommonCallOp = MMI->getIntrinsicID();
4270 } else {
4271 return false;
4272 }
4273
4274 // For floating-point reductions, track FMF intersection across all binops.
4275 FastMathFlags CommonFMF;
4276 bool IsFloatReduction = false;
4277
4278 // A chain node is one we walk through, either a matching-opcode binop/min-max
4279 // or a single-source shuffle. Anything else is a leaf source.
4280 auto IsChainNode = [&](Value *V) {
4281 if (auto *BO = dyn_cast<BinaryOperator>(V))
4282 return CommonBinOp && BO->getOpcode() == *CommonBinOp;
4283 if (auto *MMI = dyn_cast<MinMaxIntrinsic>(V))
4284 return CommonCallOp && MMI->getIntrinsicID() == *CommonCallOp;
4285 if (auto *SVI = dyn_cast<ShuffleVectorInst>(V))
4286 return isa<PoisonValue>(SVI->getOperand(1));
4287 return false;
4288 };
4289
4290 // Collect the chain, building Nodes in postorder. Bail if the chain is empty
4291 // or exceeds MaxChainNodes.
4292 constexpr unsigned MaxChainNodes = 32;
4293 SmallSetVector<Value *, 16> Nodes;
4294 SmallSetVector<Value *, 4> Sources;
4295 unsigned NumVisited = 0;
4296 auto AddSource = [&](Value *V) {
4297 if (!isa<FixedVectorType>(V->getType()))
4298 return false;
4299 Sources.insert(V);
4300 return true;
4301 };
4302 auto Walk = [&](Value *V, auto &&Walk) -> bool {
4303 if (Nodes.contains(V) || Sources.contains(V))
4304 return true;
4305 if (++NumVisited > MaxChainNodes)
4306 return false;
4307 if (!IsChainNode(V))
4308 return AddSource(V);
4309 // Chain shuffles always have poison as op1, so only op0 matters.
4310 auto *U = cast<Instruction>(V);
4311 unsigned NumOps = isa<ShuffleVectorInst>(U) ? 1 : 2;
4312 for (unsigned I = 0; I != NumOps; ++I)
4313 if (!Walk(U->getOperand(I), Walk))
4314 return false;
4315 if (isa<ShuffleVectorInst>(U) || Nodes.contains(U->getOperand(0)) ||
4316 Nodes.contains(U->getOperand(1))) {
4317 Nodes.insert(V);
4318 return true;
4319 }
4320 // Both operands are leaves so treat this binop as a source rather than
4321 // walking into it.
4322 return AddSource(V);
4323 };
4324 if (!Walk(VecOpEE, Walk) || Nodes.empty())
4325 return false;
4326
4327 bool IsIdempotent =
4328 CommonCallOp || (CommonBinOp && Instruction::isIdempotent(*CommonBinOp));
4329
4330 // For FP reductions, require reassoc on every binop and collect FMF.
4331 for (Value *V : Nodes) {
4332 auto *BinOp = dyn_cast<BinaryOperator>(V);
4333 if (!BinOp || !BinOp->getType()->isFPOrFPVectorTy())
4334 continue;
4335 if (!BinOp->hasAllowReassoc())
4336 return false;
4337 if (!IsFloatReduction) {
4338 CommonFMF = BinOp->getFastMathFlags();
4339 IsFloatReduction = true;
4340 } else {
4341 CommonFMF &= BinOp->getFastMathFlags();
4342 }
4343 }
4344
4345 // Top-down demanded elements. For each chain value, track which lanes feed
4346 // the extracted lane 0 and which feed it more than once. Reverse postorder
4347 // visits every use before its value. A binop forwards its demand to both
4348 // operands and a shuffle follows its mask back to the source lane.
4349 struct Demand {
4350 APInt Lanes;
4351 APInt Duplicates;
4352 };
4353 DenseMap<Value *, Demand> Demands;
4354 auto DemandOf = [&](Value *V) -> Demand & {
4355 unsigned N = cast<FixedVectorType>(V->getType())->getNumElements();
4356 Demand &D = Demands[V];
4357 if (D.Lanes.getBitWidth() != N)
4358 D.Lanes = D.Duplicates = APInt::getZero(N);
4359 return D;
4360 };
4361 DemandOf(VecOpEE).Lanes.setBit(0);
4362 for (Value *V : reverse(Nodes)) {
4363 Demand DV = Demands.lookup(V);
4364 if (DV.Lanes.isZero())
4365 continue;
4366 if (auto *SVI = dyn_cast<ShuffleVectorInst>(V)) {
4367 ArrayRef<int> Mask = SVI->getShuffleMask();
4368 Demand &DS = DemandOf(SVI->getOperand(0));
4369 for (unsigned I = 0, E = Mask.size(); I != E; ++I) {
4370 // Skip lanes that are undemanded or map to poison.
4371 if (!DV.Lanes[I] || Mask[I] < 0 ||
4372 (unsigned)Mask[I] >= DS.Lanes.getBitWidth())
4373 continue;
4374 if (DS.Lanes[Mask[I]] || DV.Duplicates[I])
4375 DS.Duplicates.setBit(Mask[I]);
4376 DS.Lanes.setBit(Mask[I]);
4377 }
4378 } else {
4379 auto *U = cast<User>(V);
4380 for (Value *Op : {U->getOperand(0), U->getOperand(1)}) {
4381 Demand &DOp = DemandOf(Op);
4382 // Lanes demanded through more than one path accumulate in Duplicates.
4383 DOp.Duplicates |= DV.Duplicates | (DOp.Lanes & DV.Lanes);
4384 DOp.Lanes |= DV.Lanes;
4385 }
4386 }
4387 }
4388
4389 // Reducing V replaces the entire chain, so every contribution to the result
4390 // must flow through V. Reject if anything above V reads outside the chain.
4391 auto CoversChain = [&](Value *V) {
4392 SmallVector<Value *, 8> Worklist(1, VecOpEE);
4393 SmallPtrSet<Value *, 8> Seen;
4394 Seen.insert(VecOpEE);
4395 while (!Worklist.empty()) {
4396 auto *U = cast<Instruction>(Worklist.pop_back_val());
4397 unsigned NumOps = isa<ShuffleVectorInst>(U) ? 1 : 2;
4398 for (unsigned I = 0; I != NumOps; ++I) {
4399 Value *Op = U->getOperand(I);
4400 if (Op == V || !Seen.insert(Op).second)
4401 continue;
4402 if (!Nodes.contains(Op))
4403 return false;
4404 Worklist.push_back(Op);
4405 }
4406 }
4407 return true;
4408 };
4409
4410 // Reduce a single cleanly demanded source if there is one, otherwise the
4411 // deepest intermediate that covers the chain.
4412 struct ReductionCut {
4413 Value *Src;
4414 APInt Elts;
4415 };
4416 std::optional<ReductionCut> Cut;
4417 for (Value *S : Sources) {
4418 auto It = Demands.find(S);
4419 if (It == Demands.end() || It->second.Lanes.isZero())
4420 continue;
4421 if (!IsIdempotent && !It->second.Duplicates.isZero()) {
4422 Cut.reset();
4423 break;
4424 }
4425 if (!Cut) {
4426 Cut = ReductionCut{S, It->second.Lanes};
4427 continue;
4428 }
4429 if (!isEquivBitcast(Cut->Src, S)) {
4430 Cut.reset();
4431 break;
4432 }
4433 if (!IsIdempotent && !(Cut->Elts & It->second.Lanes).isZero()) {
4434 Cut.reset();
4435 break;
4436 }
4437 Cut->Elts |= It->second.Lanes;
4438 }
4439 if (!Cut) {
4440 for (Value *V : Nodes) {
4442 continue;
4443 auto It = Demands.find(V);
4444 if (It == Demands.end() || !It->second.Lanes.isAllOnes())
4445 continue;
4446 if (!IsIdempotent && !It->second.Duplicates.isZero())
4447 continue;
4448 if (!CoversChain(V))
4449 continue;
4450 Cut = ReductionCut{V, It->second.Lanes};
4451 break;
4452 }
4453 }
4454 // Reducing one lane is just an extract and can refold forever.
4455 if (!Cut || Cut->Elts.popcount() < 2)
4456 return false;
4457
4458 Intrinsic::ID ReducedOp =
4459 (CommonCallOp ? getMinMaxReductionIntrinsicID(*CommonCallOp)
4460 : getReductionForBinop(*CommonBinOp));
4461 if (!ReducedOp)
4462 return false;
4463
4464 InstructionCost OrigCost = 0;
4465 for (Value *V : Nodes)
4466 OrigCost += TTI.getInstructionCost(cast<Instruction>(V), CostKind);
4467
4468 auto *SrcVT = cast<FixedVectorType>(Cut->Src->getType());
4469 bool IsPartialReduction = !Cut->Elts.isAllOnes();
4470 FixedVectorType *ReduceVecTy =
4471 IsPartialReduction
4472 ? FixedVectorType::get(FVT->getElementType(), Cut->Elts.popcount())
4473 : SrcVT;
4474
4475 SmallVector<int> ExtractMask;
4476 InstructionCost NewCost = 0;
4477 if (IsPartialReduction) {
4478 for (unsigned I = 0, E = Cut->Elts.getBitWidth(); I != E; ++I)
4479 if (Cut->Elts[I])
4480 ExtractMask.push_back(I);
4481 unsigned SubIdx = 0, SubLen;
4482 auto SK = Cut->Elts.isShiftedMask(SubIdx, SubLen)
4485 NewCost += TTI.getShuffleCost(SK, ReduceVecTy, SrcVT, CostKind, ExtractMask,
4486 SubIdx, ReduceVecTy);
4487 }
4488
4489 IntrinsicCostAttributes ICA(
4490 ReducedOp, ReduceVecTy->getElementType(),
4491 IsFloatReduction
4492 ? SmallVector<Type *, 2>{ReduceVecTy->getElementType(), ReduceVecTy}
4493 : SmallVector<Type *, 2>{ReduceVecTy},
4494 IsFloatReduction ? CommonFMF : FastMathFlags());
4495 NewCost += TTI.getIntrinsicInstrCost(ICA, CostKind);
4496
4497 LLVM_DEBUG(dbgs() << "Found reduction shuffle chain: " << I << "\n OldCost : "
4498 << OrigCost << " vs NewCost: " << NewCost << "\n");
4499
4500 if (!OrigCost.isValid() || !NewCost.isValid())
4501 return false;
4502
4503 if (VecOpEE->hasOneUse() ? (NewCost > OrigCost) : (NewCost >= OrigCost))
4504 return false;
4505
4506 Value *ReduceInput = Cut->Src;
4507 if (IsPartialReduction)
4508 ReduceInput = Builder.CreateShuffleVector(Cut->Src, ExtractMask);
4509
4510 Value *ReducedResult;
4511 if (IsFloatReduction) {
4513 *CommonBinOp, ReduceVecTy->getElementType(), /*AllowRHSConstant=*/false,
4514 CommonFMF.noSignedZeros());
4515 ReducedResult = Builder.CreateIntrinsic(ReducedOp, {ReduceVecTy},
4516 {Identity, ReduceInput}, CommonFMF);
4517 } else {
4518 ReducedResult =
4519 Builder.CreateIntrinsic(ReducedOp, {ReduceVecTy}, {ReduceInput});
4520 }
4521 replaceValue(I, *ReducedResult);
4522
4523 return true;
4524}
4525
4526/// Determine if its more efficient to fold:
4527/// reduce(trunc(x)) -> trunc(reduce(x)).
4528/// reduce(sext(x)) -> sext(reduce(x)).
4529/// reduce(zext(x)) -> zext(reduce(x)).
4530bool VectorCombine::foldCastFromReductions(Instruction &I) {
4531 auto *II = dyn_cast<IntrinsicInst>(&I);
4532 if (!II)
4533 return false;
4534
4535 bool TruncOnly = false;
4536 Intrinsic::ID IID = II->getIntrinsicID();
4537 switch (IID) {
4538 case Intrinsic::vector_reduce_add:
4539 case Intrinsic::vector_reduce_mul:
4540 TruncOnly = true;
4541 break;
4542 case Intrinsic::vector_reduce_and:
4543 case Intrinsic::vector_reduce_or:
4544 case Intrinsic::vector_reduce_xor:
4545 break;
4546 default:
4547 return false;
4548 }
4549
4550 unsigned ReductionOpc = getArithmeticReductionInstruction(IID);
4551 Value *ReductionSrc = I.getOperand(0);
4552
4553 Value *Src;
4554 if (!match(ReductionSrc, m_OneUse(m_Trunc(m_Value(Src)))) &&
4555 (TruncOnly || !match(ReductionSrc, m_OneUse(m_ZExtOrSExt(m_Value(Src))))))
4556 return false;
4557
4558 auto CastOpc =
4559 (Instruction::CastOps)cast<Instruction>(ReductionSrc)->getOpcode();
4560
4561 auto *SrcTy = cast<VectorType>(Src->getType());
4562 auto *ReductionSrcTy = cast<VectorType>(ReductionSrc->getType());
4563 Type *ResultTy = I.getType();
4564
4566 ReductionOpc, ReductionSrcTy, std::nullopt, CostKind);
4567 OldCost += TTI.getCastInstrCost(CastOpc, ReductionSrcTy, SrcTy,
4569 cast<CastInst>(ReductionSrc));
4570 InstructionCost NewCost =
4571 TTI.getArithmeticReductionCost(ReductionOpc, SrcTy, std::nullopt,
4572 CostKind) +
4573 TTI.getCastInstrCost(CastOpc, ResultTy, ReductionSrcTy->getScalarType(),
4574 TTI::CastContextHint::None, CostKind);
4575
4576 if (OldCost <= NewCost || !NewCost.isValid())
4577 return false;
4578
4579 Value *NewReduction = Builder.CreateIntrinsic(SrcTy->getScalarType(),
4580 II->getIntrinsicID(), {Src});
4581 Value *NewCast = Builder.CreateCast(CastOpc, NewReduction, ResultTy);
4582 replaceValue(I, *NewCast);
4583 return true;
4584}
4585
4586/// Fold:
4587/// icmp pred (reduce.{add,or,and,umax,umin}(signbit_extract(x))), C
4588/// into:
4589/// icmp sgt/slt (reduce.{or,umax,and,umin}(x)), -1/0
4590///
4591/// Sign-bit reductions produce values with known semantics:
4592/// - reduce.{or,umax}: 0 if no element is negative, 1 if any is
4593/// - reduce.{and,umin}: 1 if all elements are negative, 0 if any isn't
4594/// - reduce.add: count of negative elements (0 to NumElts)
4595///
4596/// Both lshr and ashr are supported:
4597/// - lshr produces 0 or 1, so reduce.add range is [0, N]
4598/// - ashr produces 0 or -1, so reduce.add range is [-N, 0]
4599///
4600/// The fold generalizes to multiple source vectors combined with the same
4601/// operation as the reduction. For example:
4602/// reduce.or(or(shr A, shr B)) conceptually extends the vector
4603/// For reduce.add, this changes the count to M*N where M is the number of
4604/// source vectors.
4605///
4606/// We transform to a direct sign check on the original vector using
4607/// reduce.{or,umax} or reduce.{and,umin}.
4608///
4609/// In spirit, it's similar to foldSignBitCheck in InstCombine.
4610bool VectorCombine::foldSignBitReductionCmp(Instruction &I) {
4611 CmpPredicate Pred;
4612 IntrinsicInst *ReduceOp;
4613 const APInt *CmpVal;
4614 if (!match(&I,
4615 m_ICmp(Pred, m_OneUse(m_AnyIntrinsic(ReduceOp)), m_APInt(CmpVal))))
4616 return false;
4617
4618 Intrinsic::ID OrigIID = ReduceOp->getIntrinsicID();
4619 switch (OrigIID) {
4620 case Intrinsic::vector_reduce_or:
4621 case Intrinsic::vector_reduce_umax:
4622 case Intrinsic::vector_reduce_and:
4623 case Intrinsic::vector_reduce_umin:
4624 case Intrinsic::vector_reduce_add:
4625 break;
4626 default:
4627 return false;
4628 }
4629
4630 Value *ReductionSrc = ReduceOp->getArgOperand(0);
4631 auto *VecTy = dyn_cast<FixedVectorType>(ReductionSrc->getType());
4632 if (!VecTy)
4633 return false;
4634
4635 unsigned BitWidth = VecTy->getScalarSizeInBits();
4636 if (BitWidth == 1)
4637 return false;
4638
4639 unsigned NumElts = VecTy->getNumElements();
4640
4641 // Determine the expected tree opcode for multi-vector patterns.
4642 // The tree opcode must match the reduction's underlying operation.
4643 //
4644 // TODO: for pairs of equivalent operators, we should match both,
4645 // not only the most common.
4646 Instruction::BinaryOps TreeOpcode;
4647 switch (OrigIID) {
4648 case Intrinsic::vector_reduce_or:
4649 case Intrinsic::vector_reduce_umax:
4650 TreeOpcode = Instruction::Or;
4651 break;
4652 case Intrinsic::vector_reduce_and:
4653 case Intrinsic::vector_reduce_umin:
4654 TreeOpcode = Instruction::And;
4655 break;
4656 case Intrinsic::vector_reduce_add:
4657 TreeOpcode = Instruction::Add;
4658 break;
4659 default:
4660 llvm_unreachable("Unexpected intrinsic");
4661 }
4662
4663 // Collect sign-bit extraction leaves from an associative tree of TreeOpcode.
4664 // The tree conceptually extends the vector being reduced.
4665 SmallVector<Value *, 8> Worklist;
4666 SmallVector<Value *, 8> Sources; // Original vectors (X in shr X, BW-1)
4667 Worklist.push_back(ReductionSrc);
4668 std::optional<bool> IsAShr;
4669 constexpr unsigned MaxSources = 8;
4670
4671 // Calculate old cost: all shifts + tree ops + reduction
4672 InstructionCost OldCost = TTI.getInstructionCost(ReduceOp, CostKind);
4673
4674 while (!Worklist.empty() && Worklist.size() <= MaxSources &&
4675 Sources.size() <= MaxSources) {
4676 Value *V = Worklist.pop_back_val();
4677
4678 // Try to match sign-bit extraction: shr X, (bitwidth-1)
4679 Value *X;
4681 auto *Shr = cast<Instruction>(V);
4682
4683 // All shifts must be the same type (all lshr or all ashr)
4684 bool ThisIsAShr = Shr->getOpcode() == Instruction::AShr;
4685 if (!IsAShr)
4686 IsAShr = ThisIsAShr;
4687 else if (*IsAShr != ThisIsAShr)
4688 return false;
4689
4690 Sources.push_back(X);
4691
4692 // As part of the fold, we remove all of the shifts, so we need to keep
4693 // track of their costs.
4694 OldCost += TTI.getInstructionCost(Shr, CostKind);
4695
4696 continue;
4697 }
4698
4699 // Try to extend through a tree node of the expected opcode
4700 Value *A, *B;
4701 if (!match(V, m_OneUse(m_BinOp(TreeOpcode, m_Value(A), m_Value(B)))))
4702 return false;
4703
4704 // We are potentially replacing these operations as well, so we add them
4705 // to the costs.
4706 OldCost += TTI.getInstructionCost(cast<Instruction>(V), CostKind);
4707
4708 Worklist.push_back(A);
4709 Worklist.push_back(B);
4710 }
4711
4712 // Must have at least one source and not exceed limit
4713 if (Sources.empty() || Sources.size() > MaxSources ||
4714 Worklist.size() > MaxSources || !IsAShr)
4715 return false;
4716
4717 unsigned NumSources = Sources.size();
4718
4719 // For reduce.add, the total count must fit as a signed integer.
4720 // Range is [0, M*N] for lshr or [-M*N, 0] for ashr.
4721 if (OrigIID == Intrinsic::vector_reduce_add &&
4722 !isIntN(BitWidth, NumSources * NumElts))
4723 return false;
4724
4725 // Compute the boundary value when all elements are negative:
4726 // - Per-element contribution: 1 for lshr, -1 for ashr
4727 // - For add: M*N (total elements across all sources); for others: just 1
4728 unsigned Count =
4729 (OrigIID == Intrinsic::vector_reduce_add) ? NumSources * NumElts : 1;
4730 APInt NegativeVal(CmpVal->getBitWidth(), Count);
4731 if (*IsAShr)
4732 NegativeVal.negate();
4733
4734 // Range is [min(0, AllNegVal), max(0, AllNegVal)]
4735 APInt Zero = APInt::getZero(CmpVal->getBitWidth());
4736 APInt RangeLow = APIntOps::smin(Zero, NegativeVal);
4737 APInt RangeHigh = APIntOps::smax(Zero, NegativeVal);
4738
4739 // Determine comparison semantics:
4740 // - IsEq: true for equality test, false for inequality
4741 // - TestsNegative: true if testing against AllNegVal, false for zero
4742 //
4743 // In addition to EQ/NE against 0 or AllNegVal, we support inequalities
4744 // that fold to boundary tests given the narrow value range:
4745 // < RangeHigh -> != RangeHigh
4746 // > RangeHigh-1 -> == RangeHigh
4747 // > RangeLow -> != RangeLow
4748 // < RangeLow+1 -> == RangeLow
4749 //
4750 // For inequalities, we work with signed predicates only. Unsigned predicates
4751 // are canonicalized to signed when the range is non-negative (where they are
4752 // equivalent). When the range includes negative values, unsigned predicates
4753 // would have different semantics due to wrap-around, so we reject them.
4754 if (!ICmpInst::isEquality(Pred) && !ICmpInst::isSigned(Pred)) {
4755 if (RangeLow.isNegative())
4756 return false;
4758 }
4759
4760 bool IsEq;
4761 bool TestsNegative;
4763 if (CmpVal->isZero()) {
4764 TestsNegative = false;
4765 } else if (*CmpVal == NegativeVal) {
4766 TestsNegative = true;
4767 } else {
4768 return false;
4769 }
4770 IsEq = Pred == ICmpInst::ICMP_EQ;
4771 } else if (Pred == ICmpInst::ICMP_SLT && *CmpVal == RangeHigh) {
4772 IsEq = false;
4773 TestsNegative = (RangeHigh == NegativeVal);
4774 } else if (Pred == ICmpInst::ICMP_SGT && *CmpVal == RangeHigh - 1) {
4775 IsEq = true;
4776 TestsNegative = (RangeHigh == NegativeVal);
4777 } else if (Pred == ICmpInst::ICMP_SGT && *CmpVal == RangeLow) {
4778 IsEq = false;
4779 TestsNegative = (RangeLow == NegativeVal);
4780 } else if (Pred == ICmpInst::ICMP_SLT && *CmpVal == RangeLow + 1) {
4781 IsEq = true;
4782 TestsNegative = (RangeLow == NegativeVal);
4783 } else {
4784 return false;
4785 }
4786
4787 // For this fold we support four types of checks:
4788 //
4789 // 1. All lanes are negative - AllNeg
4790 // 2. All lanes are non-negative - AllNonNeg
4791 // 3. At least one negative lane - AnyNeg
4792 // 4. At least one non-negative lane - AnyNonNeg
4793 //
4794 // For each case, we can generate the following code:
4795 //
4796 // 1. AllNeg - reduce.and/umin(X) < 0
4797 // 2. AllNonNeg - reduce.or/umax(X) > -1
4798 // 3. AnyNeg - reduce.or/umax(X) < 0
4799 // 4. AnyNonNeg - reduce.and/umin(X) > -1
4800 //
4801 // The table below shows the aggregation of all supported cases
4802 // using these four cases.
4803 //
4804 // Reduction | == 0 | != 0 | == MAX | != MAX
4805 // ------------+-----------+-----------+-----------+-----------
4806 // or/umax | AllNonNeg | AnyNeg | AnyNeg | AllNonNeg
4807 // and/umin | AnyNonNeg | AllNeg | AllNeg | AnyNonNeg
4808 // add | AllNonNeg | AnyNeg | AllNeg | AnyNonNeg
4809 //
4810 // NOTE: MAX = 1 for or/and/umax/umin, and the vector size N for add
4811 //
4812 // For easier codegen and check inversion, we use the following encoding:
4813 //
4814 // 1. Bit-3 === requires or/umax (1) or and/umin (0) check
4815 // 2. Bit-2 === checks < 0 (1) or > -1 (0)
4816 // 3. Bit-1 === universal (1) or existential (0) check
4817 //
4818 // AnyNeg = 0b110: uses or/umax, checks negative, any-check
4819 // AllNonNeg = 0b101: uses or/umax, checks non-neg, all-check
4820 // AnyNonNeg = 0b000: uses and/umin, checks non-neg, any-check
4821 // AllNeg = 0b011: uses and/umin, checks negative, all-check
4822 //
4823 // XOR with 0b011 inverts the check (swaps all/any and neg/non-neg).
4824 //
4825 enum CheckKind : unsigned {
4826 AnyNonNeg = 0b000,
4827 AllNeg = 0b011,
4828 AllNonNeg = 0b101,
4829 AnyNeg = 0b110,
4830 };
4831 // Return true if we fold this check into or/umax and false for and/umin
4832 auto RequiresOr = [](CheckKind C) -> bool { return C & 0b100; };
4833 // Return true if we should check if result is negative and false otherwise
4834 auto IsNegativeCheck = [](CheckKind C) -> bool { return C & 0b010; };
4835 // Logically invert the check
4836 auto Invert = [](CheckKind C) { return CheckKind(C ^ 0b011); };
4837
4838 CheckKind Base;
4839 switch (OrigIID) {
4840 case Intrinsic::vector_reduce_or:
4841 case Intrinsic::vector_reduce_umax:
4842 Base = TestsNegative ? AnyNeg : AllNonNeg;
4843 break;
4844 case Intrinsic::vector_reduce_and:
4845 case Intrinsic::vector_reduce_umin:
4846 Base = TestsNegative ? AllNeg : AnyNonNeg;
4847 break;
4848 case Intrinsic::vector_reduce_add:
4849 Base = TestsNegative ? AllNeg : AllNonNeg;
4850 break;
4851 default:
4852 llvm_unreachable("Unexpected intrinsic");
4853 }
4854
4855 CheckKind Check = IsEq ? Base : Invert(Base);
4856
4857 auto PickCheaper = [&](Intrinsic::ID Arith, Intrinsic::ID MinMax) {
4858 InstructionCost ArithCost =
4860 VecTy, std::nullopt, CostKind);
4861 InstructionCost MinMaxCost =
4863 FastMathFlags(), CostKind);
4864 return ArithCost <= MinMaxCost ? std::make_pair(Arith, ArithCost)
4865 : std::make_pair(MinMax, MinMaxCost);
4866 };
4867
4868 // Choose output reduction based on encoding's MSB
4869 auto [NewIID, NewCost] = RequiresOr(Check)
4870 ? PickCheaper(Intrinsic::vector_reduce_or,
4871 Intrinsic::vector_reduce_umax)
4872 : PickCheaper(Intrinsic::vector_reduce_and,
4873 Intrinsic::vector_reduce_umin);
4874
4875 // Add cost of combining multiple sources with or/and
4876 if (NumSources > 1) {
4877 unsigned CombineOpc =
4878 RequiresOr(Check) ? Instruction::Or : Instruction::And;
4879 NewCost += TTI.getArithmeticInstrCost(CombineOpc, VecTy, CostKind) *
4880 (NumSources - 1);
4881 }
4882
4883 LLVM_DEBUG(dbgs() << "Found sign-bit reduction cmp: " << I << "\n OldCost: "
4884 << OldCost << " vs NewCost: " << NewCost << "\n");
4885
4886 if (NewCost > OldCost)
4887 return false;
4888
4889 // Generate the combined input and reduction
4890 Builder.SetInsertPoint(&I);
4891 Type *ScalarTy = VecTy->getScalarType();
4892
4893 Value *Input;
4894 if (NumSources == 1) {
4895 Input = Sources[0];
4896 } else {
4897 // Combine sources with or/and based on check type
4898 Input = RequiresOr(Check) ? Builder.CreateOr(Sources)
4899 : Builder.CreateAnd(Sources);
4900 }
4901
4902 Value *NewReduce = Builder.CreateIntrinsic(ScalarTy, NewIID, {Input});
4903 Value *NewCmp = IsNegativeCheck(Check) ? Builder.CreateIsNeg(NewReduce)
4904 : Builder.CreateIsNotNeg(NewReduce);
4905 replaceValue(I, *NewCmp);
4906 return true;
4907}
4908
4909/// Fold a zero test of reduce.or or reduce.umax into a boolean reduction.
4910///
4911/// Vectorization may produce IR that compares the result of a scalar reduction
4912/// with zero. Depending on the target, lowering a reduction and a scalar
4913/// comparison separately can cost more than reducing lane-wise comparison
4914/// results. This fold creates the latter form only when it is not costlier.
4915///
4916/// Before:
4917/// %r = call iT @llvm.vector.reduce.or.vNiT(<N x iT> %x)
4918/// %cmp = icmp ne iT %r, 0
4919///
4920/// After:
4921/// %lane.cmp = icmp ne <N x iT> %x, zeroinitializer
4922/// %cmp = call i1 @llvm.vector.reduce.or.vNi1(<N x i1> %lane.cmp)
4923///
4924/// `reduce.or` and `reduce.umax` are non-zero when at least one lane is
4925/// non-zero. Therefore, `icmp ne` uses the existential `reduce.or` test.
4926/// Conversely, `icmp eq` must check that every lane is zero, so it uses the
4927/// universal `reduce.and` test.
4928///
4929/// Before:
4930/// %r = call iT @llvm.vector.reduce.umax.vNiT(<N x iT> %x)
4931/// %cmp = icmp eq iT %r, 0
4932///
4933/// After:
4934/// %lane.cmp = icmp eq <N x iT> %x, zeroinitializer
4935/// %cmp = call i1 @llvm.vector.reduce.and.vNi1(<N x i1> %lane.cmp)
4936bool VectorCombine::foldReductionZeroTest(Instruction &I) {
4937 CmpPredicate Pred;
4938 Value *Op;
4939
4940 if (!match(&I, m_c_ICmp(Pred, m_Value(Op), m_Zero())) ||
4942 return false;
4943
4944 auto *II = dyn_cast<IntrinsicInst>(Op);
4945 if (!II || !II->hasOneUse())
4946 return false;
4947
4948 auto ReduceID = II->getIntrinsicID();
4949 if (ReduceID != Intrinsic::vector_reduce_or &&
4950 ReduceID != Intrinsic::vector_reduce_umax)
4951 return false;
4952
4953 Value *Vec = II->getArgOperand(0);
4954 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
4955 if (!VecTy || !VecTy->getElementType()->isIntegerTy())
4956 return false;
4957
4958 // Map the scalar zero test to an any-lane or all-lane boolean reduction.
4959 Intrinsic::ID NewIID = (Pred == ICmpInst::ICMP_NE)
4960 ? Intrinsic::vector_reduce_or
4961 : Intrinsic::vector_reduce_and;
4962
4963 // This is not an unconditional canonicalization: compare the cost of the
4964 // original scalar reduction and compare with the vector compare and i1
4965 // reduction replacement for both reduce.or and reduce.umax.
4966 InstructionCost OldCost = TTI.getInstructionCost(II, CostKind) +
4967 TTI.getInstructionCost(&I, CostKind);
4968
4969 auto *CmpTy = cast<VectorType>(CmpInst::makeCmpResultType(VecTy));
4970 InstructionCost NewCost =
4971 TTI.getCmpSelInstrCost(Instruction::ICmp, VecTy, CmpTy, Pred, CostKind);
4973 getArithmeticReductionInstruction(NewIID), CmpTy, std::nullopt, CostKind);
4974
4975 LLVM_DEBUG(dbgs() << "Found a reduction zero test: " << I << "\n OldCost: "
4976 << OldCost << " vs NewCost: " << NewCost << "\n");
4977
4978 if (!OldCost.isValid() || !NewCost.isValid() || NewCost > OldCost)
4979 return false;
4980
4981 Builder.SetInsertPoint(&I);
4982 Value *NewCmp = Builder.CreateICmp(Pred, Vec, Constant::getNullValue(VecTy));
4983 Value *NewReduce = Builder.CreateIntrinsic(NewIID, {CmpTy}, {NewCmp});
4984 replaceValue(I, *NewReduce);
4985 return true;
4986}
4987
4988/// vector.reduce.OP f(X_i) == 0 -> vector.reduce.OP X_i == 0
4989///
4990/// We can prove it for cases when:
4991///
4992/// 1. OP X_i == 0 <=> \forall i \in [1, N] X_i == 0
4993/// 1'. OP X_i == 0 <=> \exists j \in [1, N] X_j == 0
4994/// 2. f(x) == 0 <=> x == 0
4995///
4996/// From 1 and 2 (or 1' and 2), we can infer that
4997///
4998/// OP f(X_i) == 0 <=> OP X_i == 0.
4999///
5000/// (1)
5001/// OP f(X_i) == 0 <=> \forall i \in [1, N] f(X_i) == 0
5002/// (2)
5003/// <=> \forall i \in [1, N] X_i == 0
5004/// (1)
5005/// <=> OP(X_i) == 0
5006///
5007/// For some of the OP's and f's, we need to have domain constraints on X
5008/// to ensure properties 1 (or 1') and 2.
5009bool VectorCombine::foldICmpEqZeroVectorReduce(Instruction &I) {
5010 CmpPredicate Pred;
5011 Value *Op;
5012 if (!match(&I, m_ICmp(Pred, m_Value(Op), m_Zero())) ||
5014 return false;
5015
5016 auto *II = dyn_cast<IntrinsicInst>(Op);
5017 if (!II)
5018 return false;
5019
5020 switch (II->getIntrinsicID()) {
5021 case Intrinsic::vector_reduce_add:
5022 case Intrinsic::vector_reduce_or:
5023 case Intrinsic::vector_reduce_umin:
5024 case Intrinsic::vector_reduce_umax:
5025 case Intrinsic::vector_reduce_smin:
5026 case Intrinsic::vector_reduce_smax:
5027 break;
5028 default:
5029 return false;
5030 }
5031
5032 Value *InnerOp = II->getArgOperand(0);
5033
5034 // TODO: fixed vector type might be too restrictive
5035 if (!II->hasOneUse() || !isa<FixedVectorType>(InnerOp->getType()))
5036 return false;
5037
5038 Value *X = nullptr;
5039
5040 // Check for zero-preserving operations where f(x) = 0 <=> x = 0
5041 //
5042 // 1. f(x) = shl nuw x, y for arbitrary y
5043 // 2. f(x) = mul nuw x, c for defined c != 0
5044 // 3. f(x) = zext x
5045 // 4. f(x) = sext x
5046 // 5. f(x) = neg x
5047 //
5048 if (!(match(InnerOp, m_NUWShl(m_Value(X), m_Value())) || // Case 1
5049 match(InnerOp, m_NUWMul(m_Value(X), m_NonZeroInt())) || // Case 2
5050 match(InnerOp, m_ZExt(m_Value(X))) || // Case 3
5051 match(InnerOp, m_SExt(m_Value(X))) || // Case 4
5052 match(InnerOp, m_Neg(m_Value(X))) // Case 5
5053 ))
5054 return false;
5055
5056 SimplifyQuery S = SQ.getWithInstruction(&I);
5057 auto *XTy = cast<FixedVectorType>(X->getType());
5058
5059 // Check for domain constraints for all supported reductions.
5060 //
5061 // a. OR X_i - has property 1 for every X
5062 // b. UMAX X_i - has property 1 for every X
5063 // c. UMIN X_i - has property 1' for every X
5064 // d. SMAX X_i - has property 1 for X >= 0
5065 // e. SMIN X_i - has property 1' for X >= 0
5066 // f. ADD X_i - has property 1 for X >= 0 && ADD X_i doesn't sign wrap
5067 //
5068 // In order for the proof to work, we need 1 (or 1') to be true for both
5069 // OP f(X_i) and OP X_i and that's why below we check constraints twice.
5070 //
5071 // NOTE: ADD X_i holds property 1 for a mirror case as well, i.e. when
5072 // X <= 0 && ADD X_i doesn't sign wrap. However, due to the nature
5073 // of known bits, we can't reasonably hold knowledge of "either 0
5074 // or negative".
5075 switch (II->getIntrinsicID()) {
5076 case Intrinsic::vector_reduce_add: {
5077 // We need to check that both X_i and f(X_i) have enough leading
5078 // zeros to not overflow.
5079 KnownBits KnownX = computeKnownBits(X, S);
5080 KnownBits KnownFX = computeKnownBits(InnerOp, S);
5081 unsigned NumElems = XTy->getNumElements();
5082 // Adding N elements loses at most ceil(log2(N)) leading bits.
5083 unsigned LostBits = Log2_32_Ceil(NumElems);
5084 unsigned LeadingZerosX = KnownX.countMinLeadingZeros();
5085 unsigned LeadingZerosFX = KnownFX.countMinLeadingZeros();
5086 // Need at least one leading zero left after summation to ensure no overflow
5087 if (LeadingZerosX <= LostBits || LeadingZerosFX <= LostBits)
5088 return false;
5089
5090 // We are not checking whether X or f(X) are positive explicitly because
5091 // we implicitly checked for it when we checked if both cases have enough
5092 // leading zeros to not wrap addition.
5093 break;
5094 }
5095 case Intrinsic::vector_reduce_smin:
5096 case Intrinsic::vector_reduce_smax:
5097 // Check whether X >= 0 and f(X) >= 0
5098 if (!isKnownNonNegative(InnerOp, S) || !isKnownNonNegative(X, S))
5099 return false;
5100
5101 break;
5102 default:
5103 break;
5104 };
5105
5106 LLVM_DEBUG(dbgs() << "Found a reduction to 0 comparison with removable op: "
5107 << *II << "\n");
5108
5109 // For zext/sext, check if the transform is profitable using cost model.
5110 // For other operations (shl, mul, neg), we're removing an instruction
5111 // while keeping the same reduction type, so it's always profitable.
5112 if (isa<ZExtInst>(InnerOp) || isa<SExtInst>(InnerOp)) {
5113 auto *FXTy = cast<FixedVectorType>(InnerOp->getType());
5114 Intrinsic::ID IID = II->getIntrinsicID();
5115
5117 cast<CastInst>(InnerOp)->getOpcode(), FXTy, XTy,
5118 TTI::CastContextHint::None, CostKind, cast<CastInst>(InnerOp));
5119
5120 InstructionCost OldReduceCost, NewReduceCost;
5121 switch (IID) {
5122 case Intrinsic::vector_reduce_add:
5123 case Intrinsic::vector_reduce_or:
5124 OldReduceCost = TTI.getArithmeticReductionCost(
5125 getArithmeticReductionInstruction(IID), FXTy, std::nullopt, CostKind);
5126 NewReduceCost = TTI.getArithmeticReductionCost(
5127 getArithmeticReductionInstruction(IID), XTy, std::nullopt, CostKind);
5128 break;
5129 case Intrinsic::vector_reduce_umin:
5130 case Intrinsic::vector_reduce_umax:
5131 case Intrinsic::vector_reduce_smin:
5132 case Intrinsic::vector_reduce_smax:
5133 OldReduceCost = TTI.getMinMaxReductionCost(
5134 getMinMaxReductionIntrinsicOp(IID), FXTy, FastMathFlags(), CostKind);
5135 NewReduceCost = TTI.getMinMaxReductionCost(
5136 getMinMaxReductionIntrinsicOp(IID), XTy, FastMathFlags(), CostKind);
5137 break;
5138 default:
5139 llvm_unreachable("Unexpected reduction");
5140 }
5141
5142 InstructionCost OldCost = OldReduceCost + ExtCost;
5143 InstructionCost NewCost =
5144 NewReduceCost + (InnerOp->hasOneUse() ? 0 : ExtCost);
5145
5146 LLVM_DEBUG(dbgs() << "Found a removable extension before reduction: "
5147 << *InnerOp << "\n OldCost: " << OldCost
5148 << " vs NewCost: " << NewCost << "\n");
5149
5150 // We consider transformation to still be potentially beneficial even
5151 // when the costs are the same because we might remove a use from f(X)
5152 // and unlock other optimizations. Equal costs would just mean that we
5153 // didn't make it worse in the worst case.
5154 if (NewCost > OldCost)
5155 return false;
5156 }
5157
5158 // Since we support zext and sext as f, we might change the scalar type
5159 // of the intrinsic.
5160 Type *Ty = XTy->getScalarType();
5161 Value *NewReduce = Builder.CreateIntrinsic(Ty, II->getIntrinsicID(), {X});
5162 Value *NewCmp =
5163 Builder.CreateICmp(Pred, NewReduce, ConstantInt::getNullValue(Ty));
5164 replaceValue(I, *NewCmp);
5165 return true;
5166}
5167
5168/// Fold comparisons of reduce.or/reduce.and with reduce.umax/reduce.umin
5169/// based on cost, preserving the comparison semantics.
5170///
5171/// We use two fundamental properties for each pair:
5172///
5173/// 1. or(X) == 0 <=> umax(X) == 0
5174/// 2. or(X) == 1 <=> umax(X) == 1
5175/// 3. sign(or(X)) == sign(umax(X))
5176///
5177/// 1. and(X) == -1 <=> umin(X) == -1
5178/// 2. and(X) == -2 <=> umin(X) == -2
5179/// 3. sign(and(X)) == sign(umin(X))
5180///
5181/// From these we can infer the following transformations:
5182/// a. or(X) ==/!= 0 <-> umax(X) ==/!= 0
5183/// b. or(X) s< 0 <-> umax(X) s< 0
5184/// c. or(X) s> -1 <-> umax(X) s> -1
5185/// d. or(X) s< 1 <-> umax(X) s< 1
5186/// e. or(X) ==/!= 1 <-> umax(X) ==/!= 1
5187/// f. or(X) s< 2 <-> umax(X) s< 2
5188/// g. and(X) ==/!= -1 <-> umin(X) ==/!= -1
5189/// h. and(X) s< 0 <-> umin(X) s< 0
5190/// i. and(X) s> -1 <-> umin(X) s> -1
5191/// j. and(X) s> -2 <-> umin(X) s> -2
5192/// k. and(X) ==/!= -2 <-> umin(X) ==/!= -2
5193/// l. and(X) s> -3 <-> umin(X) s> -3
5194///
5195bool VectorCombine::foldEquivalentReductionCmp(Instruction &I) {
5196 CmpPredicate Pred;
5197 Value *ReduceOp;
5198 const APInt *CmpVal;
5199 if (!match(&I, m_ICmp(Pred, m_Value(ReduceOp), m_APInt(CmpVal))))
5200 return false;
5201
5202 auto *II = dyn_cast<IntrinsicInst>(ReduceOp);
5203 if (!II || !II->hasOneUse())
5204 return false;
5205
5206 const auto IsValidOrUmaxCmp = [&]() {
5207 // or === umax for i1
5208 if (CmpVal->getBitWidth() == 1)
5209 return true;
5210
5211 // Cases a and e
5212 bool IsEquality =
5213 (CmpVal->isZero() || CmpVal->isOne()) && ICmpInst::isEquality(Pred);
5214 // Case c
5215 bool IsPositive = CmpVal->isAllOnes() && Pred == ICmpInst::ICMP_SGT;
5216 // Cases b, d, and f
5217 bool IsNegative = (CmpVal->isZero() || CmpVal->isOne() || *CmpVal == 2) &&
5218 Pred == ICmpInst::ICMP_SLT;
5219 return IsEquality || IsPositive || IsNegative;
5220 };
5221
5222 const auto IsValidAndUminCmp = [&]() {
5223 // and === umin for i1
5224 if (CmpVal->getBitWidth() == 1)
5225 return true;
5226
5227 const auto LeadingOnes = CmpVal->countl_one();
5228
5229 // Cases g and k
5230 bool IsEquality =
5231 (CmpVal->isAllOnes() || LeadingOnes + 1 == CmpVal->getBitWidth()) &&
5233 // Case h
5234 bool IsNegative = CmpVal->isZero() && Pred == ICmpInst::ICMP_SLT;
5235 // Cases i, j, and l
5236 bool IsPositive =
5237 // if the number has at least N - 2 leading ones
5238 // and the two LSBs are:
5239 // - 1 x 1 -> -1
5240 // - 1 x 0 -> -2
5241 // - 0 x 1 -> -3
5242 LeadingOnes + 2 >= CmpVal->getBitWidth() &&
5243 ((*CmpVal)[0] || (*CmpVal)[1]) && Pred == ICmpInst::ICMP_SGT;
5244 return IsEquality || IsNegative || IsPositive;
5245 };
5246
5247 Intrinsic::ID OriginalIID = II->getIntrinsicID();
5248 Intrinsic::ID AlternativeIID;
5249
5250 // Check if this is a valid comparison pattern and determine the alternate
5251 // reduction intrinsic.
5252 switch (OriginalIID) {
5253 case Intrinsic::vector_reduce_or:
5254 if (!IsValidOrUmaxCmp())
5255 return false;
5256 AlternativeIID = Intrinsic::vector_reduce_umax;
5257 break;
5258 case Intrinsic::vector_reduce_umax:
5259 if (!IsValidOrUmaxCmp())
5260 return false;
5261 AlternativeIID = Intrinsic::vector_reduce_or;
5262 break;
5263 case Intrinsic::vector_reduce_and:
5264 if (!IsValidAndUminCmp())
5265 return false;
5266 AlternativeIID = Intrinsic::vector_reduce_umin;
5267 break;
5268 case Intrinsic::vector_reduce_umin:
5269 if (!IsValidAndUminCmp())
5270 return false;
5271 AlternativeIID = Intrinsic::vector_reduce_and;
5272 break;
5273 default:
5274 return false;
5275 }
5276
5277 Value *X = II->getArgOperand(0);
5278 auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
5279 if (!VecTy)
5280 return false;
5281
5282 const auto GetReductionCost = [&](Intrinsic::ID IID) -> InstructionCost {
5283 unsigned ReductionOpc = getArithmeticReductionInstruction(IID);
5284 if (ReductionOpc != Instruction::ICmp)
5285 return TTI.getArithmeticReductionCost(ReductionOpc, VecTy, std::nullopt,
5286 CostKind);
5288 FastMathFlags(), CostKind);
5289 };
5290
5291 InstructionCost OrigCost = GetReductionCost(OriginalIID);
5292 InstructionCost AltCost = GetReductionCost(AlternativeIID);
5293
5294 LLVM_DEBUG(dbgs() << "Found equivalent reduction cmp: " << I
5295 << "\n OrigCost: " << OrigCost
5296 << " vs AltCost: " << AltCost << "\n");
5297
5298 if (AltCost >= OrigCost)
5299 return false;
5300
5301 Builder.SetInsertPoint(&I);
5302 Type *ScalarTy = VecTy->getScalarType();
5303 Value *NewReduce = Builder.CreateIntrinsic(ScalarTy, AlternativeIID, {X});
5304 Value *NewCmp =
5305 Builder.CreateICmp(Pred, NewReduce, ConstantInt::get(ScalarTy, *CmpVal));
5306
5307 replaceValue(I, *NewCmp);
5308 return true;
5309}
5310
5311/// Used by foldReduceAddCmpZero to check if we can prove that a value is
5312/// non-positive.
5313/// KnownBits cannot see sext <? x i1> as non-positive: each top bit equals a
5314/// single unknown input bit, which a per-bit lattice cannot track. The fold's
5315/// target shape is popcount-style sums of <N x i1> valid/invalid masks (e.g.
5316/// ray-intersection hits) tested for any-hit.
5317/// Previous attempts to approximate the known bits of such expressions were
5318/// using a fully recursive value tracking approach to infer a constant range
5319/// but ultimately turned to be too expensive in compile time.
5320static bool isKnownNonPositive(const Value *V, const SimplifyQuery &SQ,
5321 unsigned Depth = 0) {
5322 constexpr unsigned MaxLocalDepth = 2;
5323 if (Depth > MaxLocalDepth)
5324 return false;
5325
5326 auto NumSignBits = [&](const Value *X) {
5327 return ComputeNumSignBits(X, SQ.DL, SQ.AC, SQ.CtxI, SQ.DT);
5328 };
5329 if (NumSignBits(V) == V->getType()->getScalarSizeInBits())
5330 return true;
5331
5332 Value *A, *B;
5333 if (match(V, m_Add(m_Value(A), m_Value(B))))
5334 return NumSignBits(A) >= 2 && NumSignBits(B) >= 2 &&
5335 isKnownNonPositive(A, SQ, Depth + 1) &&
5336 isKnownNonPositive(B, SQ, Depth + 1);
5337
5338 return computeKnownBits(V, SQ).isNonPositive();
5339}
5340
5341/// Fold (icmp pred (reduce.add X), 0) to (icmp pred' (reduce.or X), 0) when X
5342/// has lanes known to all be non-negative or all non-positive, so that
5343/// sum == 0 iff every lane is 0. Falls back to reduce.umax if reduce.or is
5344/// more expensive on the target.
5345bool VectorCombine::foldReduceAddCmpZero(Instruction &I) {
5346 CmpPredicate Pred;
5347 Value *Vec;
5348 if (!match(&I, m_ICmp(Pred,
5350 m_Value(Vec))),
5351 m_Zero())))
5352 return false;
5353
5354 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
5355 if (!VecTy || VecTy->getNumElements() < 2)
5356 return false;
5357
5358 SimplifyQuery Q = SQ.getWithInstruction(&I);
5359 bool IsNonNegative = isKnownNonNegative(Vec, Q);
5360 bool IsNonPositive = !IsNonNegative && isKnownNonPositive(Vec, Q);
5361 if (!IsNonNegative && !IsNonPositive)
5362 return false;
5363
5364 // Summing NumElts lanes can consume up to log2(NumElts) sign bits. Require
5365 // strictly more headroom than that so the sum cannot wrap to zero.
5366 unsigned NumElts = VecTy->getNumElements();
5367 unsigned NumSignBits = ComputeNumSignBits(Vec, *DL, SQ.AC, &I, &DT);
5368 if (Log2_32(NumElts) >= NumSignBits)
5369 return false;
5370
5371 ICmpInst::Predicate NewPred;
5372 switch (Pred) {
5373 case ICmpInst::ICMP_EQ:
5374 case ICmpInst::ICMP_ULE:
5375 case ICmpInst::ICMP_SLE:
5376 case ICmpInst::ICMP_SGE:
5377 NewPred = ICmpInst::ICMP_EQ;
5378 break;
5379 case ICmpInst::ICMP_NE:
5380 case ICmpInst::ICMP_UGT:
5381 case ICmpInst::ICMP_SGT:
5382 case ICmpInst::ICMP_SLT:
5383 NewPred = ICmpInst::ICMP_NE;
5384 break;
5385 default:
5386 return false;
5387 }
5388
5389 // SGT and SLE on a non-positive tree, and SLT and SGE on a non-negative
5390 // tree, are tautologies (always true or always false). Leave those to
5391 // InstCombine rather than mapping them here. Remaining signed inequalities
5392 // also need one extra sign bit so the sum cannot flip sign.
5393 if (!IsNonNegative &&
5394 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE))
5395 return false;
5396 if (!IsNonPositive &&
5397 (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE))
5398 return false;
5399 if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE ||
5400 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) &&
5401 Log2_32(NumElts) >= NumSignBits - 1)
5402 return false;
5403
5405 Instruction::Add, VecTy, std::nullopt, CostKind);
5407 Instruction::Or, VecTy, std::nullopt, CostKind);
5409 Intrinsic::umax, VecTy, FastMathFlags(), CostKind);
5410 if (!OrCost.isValid() && !UmaxCost.isValid())
5411 return false;
5412 bool UseOr = OrCost.isValid() && (!UmaxCost.isValid() || OrCost <= UmaxCost);
5413 InstructionCost AltCost = UseOr ? OrCost : UmaxCost;
5414 if (AltCost > OrigCost)
5415 return false;
5416
5417 Builder.SetInsertPoint(&I);
5418 Value *NewReduce = UseOr ? Builder.CreateOrReduce(Vec)
5419 : Builder.CreateIntrinsic(
5420 Intrinsic::vector_reduce_umax, {VecTy}, {Vec});
5421 Value *NewCmp = Builder.CreateICmp(
5422 NewPred, NewReduce, ConstantInt::getNullValue(VecTy->getScalarType()));
5423 replaceValue(I, *NewCmp);
5424 return true;
5425}
5426
5427/// Returns true if this ShuffleVectorInst eventually feeds into a
5428/// vector reduction intrinsic (e.g., vector_reduce_add) by only following
5429/// chains of shuffles and binary operators (in any combination/order).
5430/// The search does not go deeper than the given Depth.
5432 constexpr unsigned MaxVisited = 32;
5435 bool FoundReduction = false;
5436
5437 WorkList.push_back(SVI);
5438 while (!WorkList.empty()) {
5439 Instruction *I = WorkList.pop_back_val();
5440 for (Instruction *UI : I->users()) {
5441 if (!UI || !Visited.insert(UI).second)
5442 continue;
5443 if (Visited.size() > MaxVisited)
5444 return false;
5445 if (auto *II = dyn_cast<IntrinsicInst>(UI)) {
5446 // More than one reduction reached
5447 if (FoundReduction)
5448 return false;
5449 switch (II->getIntrinsicID()) {
5450 case Intrinsic::vector_reduce_add:
5451 case Intrinsic::vector_reduce_mul:
5452 case Intrinsic::vector_reduce_and:
5453 case Intrinsic::vector_reduce_or:
5454 case Intrinsic::vector_reduce_xor:
5455 case Intrinsic::vector_reduce_smin:
5456 case Intrinsic::vector_reduce_smax:
5457 case Intrinsic::vector_reduce_umin:
5458 case Intrinsic::vector_reduce_umax:
5459 FoundReduction = true;
5460 continue;
5461 default:
5462 return false;
5463 }
5464 }
5465
5467 return false;
5468
5469 WorkList.emplace_back(UI);
5470 }
5471 }
5472 return FoundReduction;
5473}
5474
5475/// This method looks for groups of shuffles acting on binops, of the form:
5476/// %x = shuffle ...
5477/// %y = shuffle ...
5478/// %a = binop %x, %y
5479/// %b = binop %x, %y
5480/// shuffle %a, %b, selectmask
5481/// We may, especially if the shuffle is wider than legal, be able to convert
5482/// the shuffle to a form where only parts of a and b need to be computed. On
5483/// architectures with no obvious "select" shuffle, this can reduce the total
5484/// number of operations if the target reports them as cheaper.
5485bool VectorCombine::foldSelectShuffle(Instruction &I, bool FromReduction) {
5486 auto *SVI = cast<ShuffleVectorInst>(&I);
5487 auto *VT = cast<FixedVectorType>(I.getType());
5488 auto *Op0 = dyn_cast<Instruction>(SVI->getOperand(0));
5489 auto *Op1 = dyn_cast<Instruction>(SVI->getOperand(1));
5490 if (!Op0 || !Op1 || Op0 == Op1 || !Op0->isBinaryOp() || !Op1->isBinaryOp() ||
5491 VT != Op0->getType())
5492 return false;
5493
5494 auto *SVI0A = dyn_cast<Instruction>(Op0->getOperand(0));
5495 auto *SVI0B = dyn_cast<Instruction>(Op0->getOperand(1));
5496 auto *SVI1A = dyn_cast<Instruction>(Op1->getOperand(0));
5497 auto *SVI1B = dyn_cast<Instruction>(Op1->getOperand(1));
5498 SmallPtrSet<Instruction *, 4> InputShuffles({SVI0A, SVI0B, SVI1A, SVI1B});
5499 auto checkSVNonOpUses = [&](Instruction *I) {
5500 if (!I || I->getOperand(0)->getType() != VT)
5501 return true;
5502 return any_of(I->users(), [&](User *U) {
5503 return U != Op0 && U != Op1 &&
5504 !(isa<ShuffleVectorInst>(U) &&
5505 (InputShuffles.contains(cast<Instruction>(U)) ||
5506 isInstructionTriviallyDead(cast<Instruction>(U))));
5507 });
5508 };
5509 if (checkSVNonOpUses(SVI0A) || checkSVNonOpUses(SVI0B) ||
5510 checkSVNonOpUses(SVI1A) || checkSVNonOpUses(SVI1B))
5511 return false;
5512
5513 // Collect all the uses that are shuffles that we can transform together. We
5514 // may not have a single shuffle, but a group that can all be transformed
5515 // together profitably.
5517 auto collectShuffles = [&](Instruction *I) {
5518 for (auto *U : I->users()) {
5520 if (!SV || SV->getType() != VT)
5521 return false;
5522 if ((SV->getOperand(0) != Op0 && SV->getOperand(0) != Op1) ||
5523 (SV->getOperand(1) != Op0 && SV->getOperand(1) != Op1))
5524 return false;
5525 if (!llvm::is_contained(Shuffles, SV))
5526 Shuffles.push_back(SV);
5527 }
5528 return true;
5529 };
5530 if (!collectShuffles(Op0) || !collectShuffles(Op1))
5531 return false;
5532 // From a reduction, we need to be processing a single shuffle, otherwise the
5533 // other uses will not be lane-invariant.
5534 if (FromReduction && Shuffles.size() > 1)
5535 return false;
5536
5537 // Add any shuffle uses for the shuffles we have found, to include them in our
5538 // cost calculations.
5539 if (!FromReduction) {
5540 for (size_t Idx = 0, E = Shuffles.size(); Idx != E; ++Idx) {
5541 for (auto *U : Shuffles[Idx]->users()) {
5542 ShuffleVectorInst *SSV = dyn_cast<ShuffleVectorInst>(U);
5543 if (SSV && isa<UndefValue>(SSV->getOperand(1)) && SSV->getType() == VT)
5544 Shuffles.push_back(SSV);
5545 }
5546 }
5547 }
5548
5549 // For each of the output shuffles, we try to sort all the first vector
5550 // elements to the beginning, followed by the second array elements at the
5551 // end. If the binops are legalized to smaller vectors, this may reduce total
5552 // number of binops. We compute the ReconstructMask mask needed to convert
5553 // back to the original lane order.
5555 SmallVector<SmallVector<int>> OrigReconstructMasks;
5556 int MaxV1Elt = 0, MaxV2Elt = 0;
5557 unsigned NumElts = VT->getNumElements();
5558 for (ShuffleVectorInst *SVN : Shuffles) {
5559 SmallVector<int> Mask;
5560 SVN->getShuffleMask(Mask);
5561
5562 // Check the operands are the same as the original, or reversed (in which
5563 // case we need to commute the mask).
5564 Value *SVOp0 = SVN->getOperand(0);
5565 Value *SVOp1 = SVN->getOperand(1);
5566 if (isa<UndefValue>(SVOp1)) {
5567 auto *SSV = cast<ShuffleVectorInst>(SVOp0);
5568 SVOp0 = SSV->getOperand(0);
5569 SVOp1 = SSV->getOperand(1);
5570 for (int &Elem : Mask) {
5571 if (Elem >= static_cast<int>(SSV->getShuffleMask().size()))
5572 return false;
5573 Elem = Elem < 0 ? Elem : SSV->getMaskValue(Elem);
5574 }
5575 }
5576 if (SVOp0 == Op1 && SVOp1 == Op0) {
5577 std::swap(SVOp0, SVOp1);
5579 }
5580 if (SVOp0 != Op0 || SVOp1 != Op1)
5581 return false;
5582
5583 // Calculate the reconstruction mask for this shuffle, as the mask needed to
5584 // take the packed values from Op0/Op1 and reconstructing to the original
5585 // order.
5586 SmallVector<int> ReconstructMask;
5587 for (unsigned I = 0; I < Mask.size(); I++) {
5588 if (Mask[I] < 0) {
5589 ReconstructMask.push_back(-1);
5590 } else if (Mask[I] < static_cast<int>(NumElts)) {
5591 MaxV1Elt = std::max(MaxV1Elt, Mask[I]);
5592 auto It = find_if(V1, [&](const std::pair<int, int> &A) {
5593 return Mask[I] == A.first;
5594 });
5595 if (It != V1.end())
5596 ReconstructMask.push_back(It - V1.begin());
5597 else {
5598 ReconstructMask.push_back(V1.size());
5599 V1.emplace_back(Mask[I], V1.size());
5600 }
5601 } else {
5602 MaxV2Elt = std::max<int>(MaxV2Elt, Mask[I] - NumElts);
5603 auto It = find_if(V2, [&](const std::pair<int, int> &A) {
5604 return Mask[I] - static_cast<int>(NumElts) == A.first;
5605 });
5606 if (It != V2.end())
5607 ReconstructMask.push_back(NumElts + It - V2.begin());
5608 else {
5609 ReconstructMask.push_back(NumElts + V2.size());
5610 V2.emplace_back(Mask[I] - NumElts, NumElts + V2.size());
5611 }
5612 }
5613 }
5614
5615 // For reductions, we know that the lane ordering out doesn't alter the
5616 // result. In-order can help simplify the shuffle away.
5617 if (FromReduction)
5618 sort(ReconstructMask);
5619 OrigReconstructMasks.push_back(std::move(ReconstructMask));
5620 }
5621
5622 // If the Maximum element used from V1 and V2 are not larger than the new
5623 // vectors, the vectors are already packes and performing the optimization
5624 // again will likely not help any further. This also prevents us from getting
5625 // stuck in a cycle in case the costs do not also rule it out.
5626 if (V1.empty() || V2.empty() ||
5627 (MaxV1Elt == static_cast<int>(V1.size()) - 1 &&
5628 MaxV2Elt == static_cast<int>(V2.size()) - 1))
5629 return false;
5630
5631 // GetBaseMaskValue takes one of the inputs, which may either be a shuffle, a
5632 // shuffle of another shuffle, or not a shuffle (that is treated like a
5633 // identity shuffle).
5634 auto GetBaseMaskValue = [&](Instruction *I, int M) {
5636 if (!SV)
5637 return M;
5638 if (isa<UndefValue>(SV->getOperand(1)))
5639 if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0)))
5640 if (InputShuffles.contains(SSV))
5641 return SSV->getMaskValue(SV->getMaskValue(M));
5642 return SV->getMaskValue(M);
5643 };
5644
5645 // Attempt to sort the inputs my ascending mask values to make simpler input
5646 // shuffles and push complex shuffles down to the uses. We sort on the first
5647 // of the two input shuffle orders, to try and get at least one input into a
5648 // nice order.
5649 auto SortBase = [&](Instruction *A, std::pair<int, int> X,
5650 std::pair<int, int> Y) {
5651 int MXA = GetBaseMaskValue(A, X.first);
5652 int MYA = GetBaseMaskValue(A, Y.first);
5653 return MXA < MYA;
5654 };
5655 stable_sort(V1, [&](std::pair<int, int> A, std::pair<int, int> B) {
5656 return SortBase(SVI0A, A, B);
5657 });
5658 stable_sort(V2, [&](std::pair<int, int> A, std::pair<int, int> B) {
5659 return SortBase(SVI1A, A, B);
5660 });
5661 // Calculate our ReconstructMasks from the OrigReconstructMasks and the
5662 // modified order of the input shuffles.
5663 SmallVector<SmallVector<int>> ReconstructMasks;
5664 for (const auto &Mask : OrigReconstructMasks) {
5665 SmallVector<int> ReconstructMask;
5666 for (int M : Mask) {
5667 auto FindIndex = [](const SmallVector<std::pair<int, int>> &V, int M) {
5668 auto It = find_if(V, [M](auto A) { return A.second == M; });
5669 assert(It != V.end() && "Expected all entries in Mask");
5670 return std::distance(V.begin(), It);
5671 };
5672 if (M < 0)
5673 ReconstructMask.push_back(-1);
5674 else if (M < static_cast<int>(NumElts)) {
5675 ReconstructMask.push_back(FindIndex(V1, M));
5676 } else {
5677 ReconstructMask.push_back(NumElts + FindIndex(V2, M));
5678 }
5679 }
5680 ReconstructMasks.push_back(std::move(ReconstructMask));
5681 }
5682
5683 // Calculate the masks needed for the new input shuffles, which get padded
5684 // with undef
5685 SmallVector<int> V1A, V1B, V2A, V2B;
5686 for (unsigned I = 0; I < V1.size(); I++) {
5687 V1A.push_back(GetBaseMaskValue(SVI0A, V1[I].first));
5688 V1B.push_back(GetBaseMaskValue(SVI0B, V1[I].first));
5689 }
5690 for (unsigned I = 0; I < V2.size(); I++) {
5691 V2A.push_back(GetBaseMaskValue(SVI1A, V2[I].first));
5692 V2B.push_back(GetBaseMaskValue(SVI1B, V2[I].first));
5693 }
5694 while (V1A.size() < NumElts) {
5697 }
5698 while (V2A.size() < NumElts) {
5701 }
5702
5703 auto AddShuffleCost = [&](InstructionCost C, Instruction *I) {
5705 if (!SV)
5706 return C;
5707 return C + TTI.getShuffleCost(isa<UndefValue>(SV->getOperand(1))
5710 VT, VT, CostKind, SV->getShuffleMask());
5711 };
5712 auto AddShuffleMaskCost = [&](InstructionCost C, ArrayRef<int> Mask) {
5713 return C +
5714 TTI.getShuffleCost(TTI::SK_PermuteTwoSrc, VT, VT, CostKind, Mask);
5715 };
5716
5717 unsigned ElementSize = VT->getElementType()->getPrimitiveSizeInBits();
5718 unsigned MaxVectorSize =
5720 unsigned MaxElementsInVector = MaxVectorSize / ElementSize;
5721 if (MaxElementsInVector == 0)
5722 return false;
5723 // When there are multiple shufflevector operations on the same input,
5724 // especially when the vector length is larger than the register size,
5725 // identical shuffle patterns may occur across different groups of elements.
5726 // To avoid overestimating the cost by counting these repeated shuffles more
5727 // than once, we only account for unique shuffle patterns. This adjustment
5728 // prevents inflated costs in the cost model for wide vectors split into
5729 // several register-sized groups.
5730 std::set<SmallVector<int, 4>> UniqueShuffles;
5731 auto AddShuffleMaskAdjustedCost = [&](InstructionCost C, ArrayRef<int> Mask) {
5732 // Compute the cost for performing the shuffle over the full vector.
5733 auto ShuffleCost =
5734 TTI.getShuffleCost(TTI::SK_PermuteTwoSrc, VT, VT, CostKind, Mask);
5735 unsigned NumFullVectors = Mask.size() / MaxElementsInVector;
5736 if (NumFullVectors < 2)
5737 return C + ShuffleCost;
5738 SmallVector<int, 4> SubShuffle(MaxElementsInVector);
5739 unsigned NumUniqueGroups = 0;
5740 unsigned NumGroups = Mask.size() / MaxElementsInVector;
5741 // For each group of MaxElementsInVector contiguous elements,
5742 // collect their shuffle pattern and insert into the set of unique patterns.
5743 for (unsigned I = 0; I < NumFullVectors; ++I) {
5744 for (unsigned J = 0; J < MaxElementsInVector; ++J)
5745 SubShuffle[J] = Mask[MaxElementsInVector * I + J];
5746 if (UniqueShuffles.insert(SubShuffle).second)
5747 NumUniqueGroups += 1;
5748 }
5749 return C + ShuffleCost * NumUniqueGroups / NumGroups;
5750 };
5751 auto AddShuffleAdjustedCost = [&](InstructionCost C, Instruction *I) {
5753 if (!SV)
5754 return C;
5755 SmallVector<int, 16> Mask;
5756 SV->getShuffleMask(Mask);
5757 return AddShuffleMaskAdjustedCost(C, Mask);
5758 };
5759 // Check that input consists of ShuffleVectors applied to the same input
5760 auto AllShufflesHaveSameOperands =
5761 [](SmallPtrSetImpl<Instruction *> &InputShuffles) {
5762 if (InputShuffles.size() < 2)
5763 return false;
5764 ShuffleVectorInst *FirstSV =
5765 dyn_cast<ShuffleVectorInst>(*InputShuffles.begin());
5766 if (!FirstSV)
5767 return false;
5768
5769 Value *In0 = FirstSV->getOperand(0), *In1 = FirstSV->getOperand(1);
5770 return std::all_of(
5771 std::next(InputShuffles.begin()), InputShuffles.end(),
5772 [&](Instruction *I) {
5773 ShuffleVectorInst *SV = dyn_cast<ShuffleVectorInst>(I);
5774 return SV && SV->getOperand(0) == In0 && SV->getOperand(1) == In1;
5775 });
5776 };
5777
5778 // Get the costs of the shuffles + binops before and after with the new
5779 // shuffle masks.
5780 InstructionCost CostBefore =
5781 TTI.getArithmeticInstrCost(Op0->getOpcode(), VT, CostKind) +
5782 TTI.getArithmeticInstrCost(Op1->getOpcode(), VT, CostKind);
5783 CostBefore += std::accumulate(Shuffles.begin(), Shuffles.end(),
5784 InstructionCost(0), AddShuffleCost);
5785 if (AllShufflesHaveSameOperands(InputShuffles)) {
5786 UniqueShuffles.clear();
5787 CostBefore += std::accumulate(InputShuffles.begin(), InputShuffles.end(),
5788 InstructionCost(0), AddShuffleAdjustedCost);
5789 } else {
5790 CostBefore += std::accumulate(InputShuffles.begin(), InputShuffles.end(),
5791 InstructionCost(0), AddShuffleCost);
5792 }
5793
5794 // The new binops will be unused for lanes past the used shuffle lengths.
5795 // These types attempt to get the correct cost for that from the target.
5796 FixedVectorType *Op0SmallVT =
5797 FixedVectorType::get(VT->getScalarType(), V1.size());
5798 FixedVectorType *Op1SmallVT =
5799 FixedVectorType::get(VT->getScalarType(), V2.size());
5800 InstructionCost CostAfter =
5801 TTI.getArithmeticInstrCost(Op0->getOpcode(), Op0SmallVT, CostKind) +
5802 TTI.getArithmeticInstrCost(Op1->getOpcode(), Op1SmallVT, CostKind);
5803 UniqueShuffles.clear();
5804 CostAfter += std::accumulate(ReconstructMasks.begin(), ReconstructMasks.end(),
5805 InstructionCost(0), AddShuffleMaskAdjustedCost);
5806 std::set<SmallVector<int>> OutputShuffleMasks({V1A, V1B, V2A, V2B});
5807 CostAfter +=
5808 std::accumulate(OutputShuffleMasks.begin(), OutputShuffleMasks.end(),
5809 InstructionCost(0), AddShuffleMaskCost);
5810
5811 LLVM_DEBUG(dbgs() << "Found a binop select shuffle pattern: " << I << "\n");
5812 LLVM_DEBUG(dbgs() << " CostBefore: " << CostBefore
5813 << " vs CostAfter: " << CostAfter << "\n");
5814 if (CostBefore < CostAfter ||
5815 (CostBefore == CostAfter && !feedsIntoVectorReduction(SVI)))
5816 return false;
5817
5818 // The cost model has passed, create the new instructions.
5819 auto GetShuffleOperand = [&](Instruction *I, unsigned Op) -> Value * {
5821 if (!SV)
5822 return I;
5823 if (isa<UndefValue>(SV->getOperand(1)))
5824 if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0)))
5825 if (InputShuffles.contains(SSV))
5826 return SSV->getOperand(Op);
5827 return SV->getOperand(Op);
5828 };
5829 Builder.SetInsertPoint(*SVI0A->getInsertionPointAfterDef());
5830 Value *NSV0A = Builder.CreateShuffleVector(GetShuffleOperand(SVI0A, 0),
5831 GetShuffleOperand(SVI0A, 1), V1A);
5832 Builder.SetInsertPoint(*SVI0B->getInsertionPointAfterDef());
5833 Value *NSV0B = Builder.CreateShuffleVector(GetShuffleOperand(SVI0B, 0),
5834 GetShuffleOperand(SVI0B, 1), V1B);
5835 Builder.SetInsertPoint(*SVI1A->getInsertionPointAfterDef());
5836 Value *NSV1A = Builder.CreateShuffleVector(GetShuffleOperand(SVI1A, 0),
5837 GetShuffleOperand(SVI1A, 1), V2A);
5838 Builder.SetInsertPoint(*SVI1B->getInsertionPointAfterDef());
5839 Value *NSV1B = Builder.CreateShuffleVector(GetShuffleOperand(SVI1B, 0),
5840 GetShuffleOperand(SVI1B, 1), V2B);
5841 Builder.SetInsertPoint(Op0);
5842 Value *NOp0 = Builder.CreateBinOp((Instruction::BinaryOps)Op0->getOpcode(),
5843 NSV0A, NSV0B);
5844 if (auto *I = dyn_cast<Instruction>(NOp0))
5845 I->copyIRFlags(Op0, true);
5846 Builder.SetInsertPoint(Op1);
5847 Value *NOp1 = Builder.CreateBinOp((Instruction::BinaryOps)Op1->getOpcode(),
5848 NSV1A, NSV1B);
5849 if (auto *I = dyn_cast<Instruction>(NOp1))
5850 I->copyIRFlags(Op1, true);
5851
5852 for (int S = 0, E = ReconstructMasks.size(); S != E; S++) {
5853 Builder.SetInsertPoint(Shuffles[S]);
5854 Value *NSV = Builder.CreateShuffleVector(NOp0, NOp1, ReconstructMasks[S]);
5855 replaceValue(*Shuffles[S], *NSV, false);
5856 }
5857
5858 return true;
5859}
5860
5861/// Check if instruction depends on ZExt and this ZExt can be moved after the
5862/// instruction. Move ZExt if it is profitable. For example:
5863/// logic(zext(x),y) -> zext(logic(x,trunc(y)))
5864/// lshr((zext(x),y) -> zext(lshr(x,trunc(y)))
5865/// Cost model calculations takes into account if zext(x) has other users and
5866/// whether it can be propagated through them too.
5867bool VectorCombine::shrinkType(Instruction &I) {
5868 Value *ZExted, *OtherOperand;
5869 if (!match(&I, m_c_BitwiseLogic(m_ZExt(m_Value(ZExted)),
5870 m_Value(OtherOperand))) &&
5871 !match(&I, m_LShr(m_ZExt(m_Value(ZExted)), m_Value(OtherOperand))))
5872 return false;
5873
5874 Value *ZExtOperand = I.getOperand(I.getOperand(0) == OtherOperand ? 1 : 0);
5875
5876 auto *BigTy = cast<FixedVectorType>(I.getType());
5877 auto *SmallTy = cast<FixedVectorType>(ZExted->getType());
5878 unsigned BW = SmallTy->getElementType()->getPrimitiveSizeInBits();
5879
5880 if (I.getOpcode() == Instruction::LShr) {
5881 // Check that the shift amount is less than the number of bits in the
5882 // smaller type. Otherwise, the smaller lshr will return a poison value.
5883 KnownBits ShAmtKB = computeKnownBits(I.getOperand(1), *DL);
5884 if (ShAmtKB.getMaxValue().uge(BW))
5885 return false;
5886 } else {
5887 // Check that the expression overall uses at most the same number of bits as
5888 // ZExted
5889 KnownBits KB = computeKnownBits(&I, *DL);
5890 if (KB.countMaxActiveBits() > BW)
5891 return false;
5892 }
5893
5894 // Calculate costs of leaving current IR as it is and moving ZExt operation
5895 // later, along with adding truncates if needed
5897 Instruction::ZExt, BigTy, SmallTy,
5898 TargetTransformInfo::CastContextHint::None, CostKind);
5899 InstructionCost CurrentCost = ZExtCost;
5900 InstructionCost ShrinkCost = 0;
5901
5902 // Calculate total cost and check that we can propagate through all ZExt users
5903 for (User *U : ZExtOperand->users()) {
5904 auto *UI = cast<Instruction>(U);
5905 if (UI == &I) {
5906 CurrentCost +=
5907 TTI.getArithmeticInstrCost(UI->getOpcode(), BigTy, CostKind);
5908 ShrinkCost +=
5909 TTI.getArithmeticInstrCost(UI->getOpcode(), SmallTy, CostKind);
5910 ShrinkCost += ZExtCost;
5911 continue;
5912 }
5913
5914 if (!Instruction::isBinaryOp(UI->getOpcode()))
5915 return false;
5916
5917 // Check if we can propagate ZExt through its other users
5918 KnownBits KB = computeKnownBits(UI, *DL);
5919 if (KB.countMaxActiveBits() > BW)
5920 return false;
5921
5922 CurrentCost += TTI.getArithmeticInstrCost(UI->getOpcode(), BigTy, CostKind);
5923 ShrinkCost +=
5924 TTI.getArithmeticInstrCost(UI->getOpcode(), SmallTy, CostKind);
5925 ShrinkCost += ZExtCost;
5926 }
5927
5928 // If the other instruction operand is not a constant, we'll need to
5929 // generate a truncate instruction. So we have to adjust cost
5930 if (!isa<Constant>(OtherOperand))
5931 ShrinkCost += TTI.getCastInstrCost(
5932 Instruction::Trunc, SmallTy, BigTy,
5933 TargetTransformInfo::CastContextHint::None, CostKind);
5934
5935 // If the cost of shrinking types and leaving the IR is the same, we'll lean
5936 // towards modifying the IR because shrinking opens opportunities for other
5937 // shrinking optimisations.
5938 if (ShrinkCost > CurrentCost)
5939 return false;
5940
5941 Builder.SetInsertPoint(&I);
5942 Value *Op0 = ZExted;
5943 Value *Op1 = Builder.CreateTrunc(OtherOperand, SmallTy);
5944 // Keep the order of operands the same
5945 if (I.getOperand(0) == OtherOperand)
5946 std::swap(Op0, Op1);
5947 Value *NewBinOp =
5948 Builder.CreateBinOp((Instruction::BinaryOps)I.getOpcode(), Op0, Op1);
5949 if (auto *NewBinOpI = dyn_cast<Instruction>(NewBinOp)) {
5950 NewBinOpI->copyIRFlags(&I);
5951 NewBinOpI->copyMetadata(I);
5952 }
5953 Value *NewZExtr = Builder.CreateZExt(NewBinOp, BigTy);
5954 replaceValue(I, *NewZExtr);
5955 return true;
5956}
5957
5958/// insert (DstVec, (extract SrcVec, ExtIdx), InsIdx) -->
5959/// shuffle (DstVec, SrcVec, Mask)
5960bool VectorCombine::foldInsExtVectorToShuffle(Instruction &I) {
5961 Value *DstVec, *SrcVec;
5962 uint64_t ExtIdx, InsIdx;
5963 if (!match(&I,
5964 m_InsertElt(m_Value(DstVec),
5965 m_ExtractElt(m_Value(SrcVec), m_ConstantInt(ExtIdx)),
5966 m_ConstantInt(InsIdx))))
5967 return false;
5968
5969 auto *DstVecTy = dyn_cast<FixedVectorType>(I.getType());
5970 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcVec->getType());
5971 // We can try combining vectors with different element sizes.
5972 if (!DstVecTy || !SrcVecTy ||
5973 SrcVecTy->getElementType() != DstVecTy->getElementType())
5974 return false;
5975
5976 unsigned NumDstElts = DstVecTy->getNumElements();
5977 unsigned NumSrcElts = SrcVecTy->getNumElements();
5978 if (InsIdx >= NumDstElts || ExtIdx >= NumSrcElts || NumDstElts == 1)
5979 return false;
5980
5981 // Insertion into poison is a cheaper single operand shuffle.
5983 SmallVector<int> Mask(NumDstElts, PoisonMaskElem);
5984
5985 bool NeedExpOrNarrow = NumSrcElts != NumDstElts;
5986 bool NeedDstSrcSwap = isa<PoisonValue>(DstVec) && !isa<UndefValue>(SrcVec);
5987 if (NeedDstSrcSwap) {
5989 Mask[InsIdx] = ExtIdx % NumDstElts;
5990 std::swap(DstVec, SrcVec);
5991 } else {
5993 std::iota(Mask.begin(), Mask.end(), 0);
5994 Mask[InsIdx] = (ExtIdx % NumDstElts) + NumDstElts;
5995 }
5996
5997 // Cost
5998 auto *Ins = cast<InsertElementInst>(&I);
5999 auto *Ext = cast<ExtractElementInst>(I.getOperand(1));
6000 InstructionCost InsCost =
6001 TTI.getVectorInstrCost(*Ins, DstVecTy, CostKind, InsIdx);
6002 InstructionCost ExtCost =
6003 TTI.getVectorInstrCost(*Ext, DstVecTy, CostKind, ExtIdx);
6004 InstructionCost OldCost = ExtCost + InsCost;
6005
6006 InstructionCost NewCost = 0;
6007 SmallVector<int> ExtToVecMask;
6008 if (!NeedExpOrNarrow) {
6009 // Ignore 'free' identity insertion shuffle.
6010 // TODO: getShuffleCost should return TCC_Free for Identity shuffles.
6011 if (!ShuffleVectorInst::isIdentityMask(Mask, NumSrcElts))
6012 NewCost += TTI.getShuffleCost(SK, DstVecTy, DstVecTy, CostKind, Mask, 0,
6013 nullptr, {DstVec, SrcVec});
6014 } else {
6015 // When creating a length-changing-vector, always try to keep the relevant
6016 // element in an equivalent position, so that bulk shuffles are more likely
6017 // to be useful.
6018 ExtToVecMask.assign(NumDstElts, PoisonMaskElem);
6019 ExtToVecMask[ExtIdx % NumDstElts] = ExtIdx;
6020 // Add cost for expanding or narrowing
6022 DstVecTy, SrcVecTy, CostKind, ExtToVecMask);
6023 NewCost += TTI.getShuffleCost(SK, DstVecTy, DstVecTy, CostKind, Mask);
6024 }
6025
6026 if (!Ext->hasOneUse())
6027 NewCost += ExtCost;
6028
6029 LLVM_DEBUG(dbgs() << "Found a insert/extract shuffle-like pair: " << I
6030 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
6031 << "\n");
6032
6033 if (OldCost < NewCost)
6034 return false;
6035
6036 if (NeedExpOrNarrow) {
6037 if (!NeedDstSrcSwap)
6038 SrcVec = Builder.CreateShuffleVector(SrcVec, ExtToVecMask);
6039 else
6040 DstVec = Builder.CreateShuffleVector(DstVec, ExtToVecMask);
6041 }
6042
6043 // Canonicalize undef param to RHS to help further folds.
6044 if (isa<UndefValue>(DstVec) && !isa<UndefValue>(SrcVec)) {
6045 ShuffleVectorInst::commuteShuffleMask(Mask, NumDstElts);
6046 std::swap(DstVec, SrcVec);
6047 }
6048
6049 Value *Shuf = Builder.CreateShuffleVector(DstVec, SrcVec, Mask);
6050 replaceValue(I, *Shuf);
6051
6052 return true;
6053}
6054
6055/// Try to replace a chain of insertelements of parts of the same scalar with a
6056/// bitcast and a shuffle (little endian):
6057/// insert (insert poison, (trunc (lshr X, 32)), 0), (trunc X), 1 -->
6058/// shuffle (bitcast X to <2 x i32>), poison, <1, 0>
6059bool VectorCombine::foldInsertScalarPartsToShuffle(Instruction &I) {
6060 auto *VecTy = dyn_cast<FixedVectorType>(I.getType());
6061 if (!VecTy)
6062 return false;
6063
6064 // Start from the last insertelement of the chain.
6065 if (I.hasOneUse() && isa<InsertElementInst>(I.user_back()))
6066 return false;
6067
6068 Type *EltTy = VecTy->getElementType();
6069 if ((!EltTy->isIntegerTy() && !EltTy->isIEEELikeFPTy()) ||
6070 !DL->typeSizeEqualsStoreSize(EltTy))
6071 return false;
6072 unsigned EltBits = EltTy->getPrimitiveSizeInBits();
6073 unsigned NumElts = VecTy->getNumElements();
6074
6075 Value *Src = nullptr;
6076 unsigned NumSrcElts = 0;
6077 SmallVector<int> Mask(NumElts, PoisonMaskElem);
6078 APInt DemandedElts = APInt::getZero(NumElts);
6079 InstructionCost OldCost = 0;
6080 Value *Vec = &I;
6081 while (auto *Ins = dyn_cast<InsertElementInst>(Vec)) {
6082 if (Ins != &I && !Ins->hasOneUse())
6083 return false;
6084 uint64_t Idx;
6085 if (!match(Ins->getOperand(2), m_ConstantInt(Idx)) || Idx >= NumElts)
6086 return false;
6087 Vec = Ins->getOperand(0);
6088 // A later insert to the same element overrides this one.
6089 if (DemandedElts[Idx])
6090 continue;
6091 DemandedElts.setBit(Idx);
6092
6093 // Match (bitcast (trunc (lshr X, ShAmt))), the bitcast and shift being
6094 // optional.
6095 Value *Elt = Ins->getOperand(1);
6096 Value *Trunc = Elt;
6098 Value *X;
6099 if (!match(Trunc, m_Trunc(m_Value(X))) || !X->getType()->isIntegerTy() ||
6100 Trunc->getType()->getPrimitiveSizeInBits() != EltBits)
6101 return false;
6102 Value *Shift = nullptr;
6103 uint64_t ShAmt = 0;
6104 if (match(X, m_LShr(m_Value(), m_ConstantInt(ShAmt)))) {
6105 Shift = X;
6106 X = cast<Instruction>(Shift)->getOperand(0);
6107 }
6108
6109 if (!Src) {
6110 unsigned SrcBits = X->getType()->getIntegerBitWidth();
6111 if (SrcBits % EltBits)
6112 return false;
6113 Src = X;
6114 NumSrcElts = SrcBits / EltBits;
6115 } else if (X != Src) {
6116 return false;
6117 }
6118 uint64_t Part = ShAmt / EltBits;
6119 if (ShAmt % EltBits || Part >= NumSrcElts)
6120 return false;
6121 Mask[Idx] = DL->isBigEndian() ? NumSrcElts - 1 - Part : Part;
6122
6123 // The scalar ops die with the chain if it is their only user.
6124 for (Value *V : {Elt == Trunc ? nullptr : Elt, Trunc, Shift}) {
6125 if (!V)
6126 continue;
6127 if (!V->hasOneUse())
6128 break;
6129 OldCost += TTI.getInstructionCost(cast<Instruction>(V), CostKind);
6130 }
6131 }
6132 // Elements that are not inserted become poison, so the base must be poison
6133 // unless every element is inserted.
6134 if (!Src || (!isa<PoisonValue>(Vec) && !DemandedElts.isAllOnes()))
6135 return false;
6136 // Inserting a single part is a scalar insert or a splat, whose canonical
6137 // insertelement (+ splat shuffle) form is better left alone.
6138 if (all_equal(
6139 make_filter_range(Mask, [](int M) { return M != PoisonMaskElem; })))
6140 return false;
6141
6142 OldCost += TTI.getScalarizationOverhead(VecTy, DemandedElts, /*Insert=*/true,
6143 /*Extract=*/false, CostKind);
6144
6145 auto *SrcVecTy = FixedVectorType::get(EltTy, NumSrcElts);
6146 InstructionCost NewCost =
6147 TTI.getCastInstrCost(Instruction::BitCast, SrcVecTy, Src->getType(),
6148 TTI::CastContextHint::None, CostKind);
6149 bool IsIdentity = NumSrcElts == NumElts &&
6150 ShuffleVectorInst::isIdentityMask(Mask, NumSrcElts);
6151 if (!IsIdentity)
6152 NewCost += TTI.getShuffleCost(TTI::SK_PermuteSingleSrc, VecTy, SrcVecTy,
6153 CostKind, Mask);
6154
6155 LLVM_DEBUG(dbgs() << "Found an insertelement chain of scalar parts: " << I
6156 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
6157 << "\n");
6158 if (!OldCost.isValid() || !NewCost.isValid() || NewCost >= OldCost)
6159 return false;
6160
6161 Value *Cast = Builder.CreateBitCast(Src, SrcVecTy);
6162 Value *Shuf = IsIdentity ? Cast : Builder.CreateShuffleVector(Cast, Mask);
6163 replaceValue(I, *Shuf);
6164 return true;
6165}
6166
6167/// Return the number of data operands of \p Inst.
6168static unsigned getNumDataOperands(const Instruction *Inst) {
6169 if (auto *CB = dyn_cast<CallBase>(Inst))
6170 return CB->arg_size(); // Exclude callee operand and bundles.
6171 return Inst->getNumOperands();
6172}
6173
6174/// Return true if \p Inst is an elementwise operation that can be rebuilt at a
6175/// wider element count.
6177 auto *ResultTy = dyn_cast<VectorType>(Inst->getType());
6178 if (!ResultTy || !isSafeToSpeculativelyExecute(Inst))
6179 return false;
6180
6181 if (auto *II = dyn_cast<IntrinsicInst>(Inst)) {
6182 if (II->hasOperandBundles() ||
6183 !isTriviallyVectorizable(II->getIntrinsicID()))
6184 return false;
6186 FreezeInst>(Inst)) {
6187 return false;
6188 }
6189
6190 // Reject operations that change the element-count.
6191 // E.g., bitcast <vscale x 4 x i16> %v to <vscale x 8 x i8>
6192 for (unsigned Op = 0, E = getNumDataOperands(Inst); Op != E; ++Op) {
6193 auto *OperandTy = dyn_cast<VectorType>(Inst->getOperand(Op)->getType());
6194 if (OperandTy &&
6195 OperandTy->getElementCount() != ResultTy->getElementCount())
6196 return false;
6197 }
6198
6199 return true;
6200}
6201
6202/// Return the common splat value of \p Values.
6204 auto GetSplatOrScalar = [](Value *V) {
6205 return isa<VectorType>(V->getType()) ? getSplatValue(V) : V;
6206 };
6207
6208 Value *CommonValue = GetSplatOrScalar(Values.front());
6209 if (!CommonValue)
6210 return nullptr;
6211 for (Value *V : Values.drop_front())
6212 if (GetSplatOrScalar(V) != CommonValue)
6213 return nullptr;
6214 return CommonValue;
6215}
6216
6217/// Return the common deinterleave intrinsic if \p Members are its extracts in
6218/// field order.
6220 IntrinsicInst *Deinterleave = nullptr;
6221 for (const auto &[Index, Member] : enumerate(Members)) {
6222 auto *Extract = dyn_cast<ExtractValueInst>(Member);
6223 if (!Extract || Extract->getNumIndices() != 1 ||
6224 *Extract->idx_begin() != Index)
6225 return nullptr;
6226
6227 auto *Current = dyn_cast<IntrinsicInst>(Extract->getAggregateOperand());
6228 if (!Current || (Deinterleave && Current != Deinterleave))
6229 return nullptr;
6230 Deinterleave = Current;
6231 }
6232 unsigned Factor = Members.size();
6233 if (Deinterleave->hasOperandBundles() ||
6234 getDeinterleaveIntrinsicFactor(Deinterleave->getIntrinsicID()) !=
6235 Factor ||
6236 !Deinterleave->hasNUndroppableUses(Factor))
6237 return nullptr;
6238 return Deinterleave;
6239}
6240
6241/// Return the operand at \p OperandIndex of each \p Members.
6243 unsigned OperandIndex) {
6245 for (Value *Member : Members)
6246 Operands.push_back(cast<Instruction>(Member)->getOperand(OperandIndex));
6247 return Operands;
6248}
6249
6250/// Check whether the tree of elementwise operations each feeding \p Members
6251/// can be rebuilt at the interleaved width.
6253 const VectorizeOptions &Opts, ArrayRef<Value *> Members,
6254 DenseSet<Value *> &Visited, SmallPtrSetImpl<User *> &UndroppableUsers) {
6255 unsigned Factor = Members.size();
6256 if (getCommonDeinterleavedSource(Members))
6257 return true;
6258
6259 if (all_of(Members, [&](Value *V) { return Visited.count(V); }))
6260 return true;
6261
6262 if (Visited.size() + Factor > Opts.vector_combine_max_scan_instrs)
6263 return false;
6264
6265 auto addUndroppableUsers = [&](Value *V) {
6266 for (User *U : V->users()) {
6267 if (U->isDroppable())
6268 continue;
6269 UndroppableUsers.insert(U);
6270 }
6271 };
6272
6273 auto *FirstInst = dyn_cast<Instruction>(Members.front());
6274 if (!FirstInst || !isSupportedElementwise(FirstInst))
6275 return false;
6276 if (Visited.insert(FirstInst).second && !FirstInst->getSingleUndroppableUse())
6277 addUndroppableUsers(FirstInst);
6278
6279 for (Value *Member : Members.drop_front()) {
6280 auto *Inst = dyn_cast<Instruction>(Member);
6281 if (!Inst ||
6282 !FirstInst->isSameOperationAs(Inst, Instruction::CompareCallTargets))
6283 return false;
6284 if (Visited.insert(Inst).second && !Inst->getSingleUndroppableUse())
6285 addUndroppableUsers(Inst);
6286 }
6287
6288 // Scalars operands should be equal among all members.
6289 // Vector operands should be a common splat value or can be widened.
6290 for (unsigned Op = 0, E = getNumDataOperands(FirstInst); Op != E; ++Op) {
6294 UndroppableUsers))
6295 return false;
6296 }
6297 return true;
6298}
6299
6301 ArrayRef<Value *> NewOperands,
6302 VectorType *WideResultTy,
6303 IRBuilderBase &Builder) {
6304 if (isa<BinaryOperator, UnaryOperator>(NarrowInst))
6305 return Builder.CreateNAryOp(NarrowInst->getOpcode(), NewOperands);
6306 if (auto *Cast = dyn_cast<CastInst>(NarrowInst))
6307 return Builder.CreateCast(Cast->getOpcode(), NewOperands[0], WideResultTy);
6308 if (auto *Cmp = dyn_cast<CmpInst>(NarrowInst))
6309 return Builder.CreateCmp(Cmp->getPredicate(), NewOperands[0],
6310 NewOperands[1]);
6311 if (isa<SelectInst>(NarrowInst))
6312 return Builder.CreateSelect(
6313 NewOperands[0], NewOperands[1], NewOperands[2], /*Name=*/"",
6314 ProfcheckDisableMetadataFixes ? nullptr : NarrowInst);
6315 if (isa<FreezeInst>(NarrowInst))
6316 return Builder.CreateFreeze(NewOperands[0]);
6317 if (auto *II = dyn_cast<IntrinsicInst>(NarrowInst))
6318 return Builder.CreateIntrinsic(WideResultTy, II->getIntrinsicID(),
6319 NewOperands);
6320 llvm_unreachable("Unsupported instruction");
6321}
6322
6324 const SmallVector<Value *, 8> &Members, ElementCount WideEC,
6325 IRBuilderBase &Builder,
6326 DenseMap<SmallVector<Value *, 8>, Value *> &WideValueCache) {
6327 if (Value *WideValue = WideValueCache.lookup(Members))
6328 return WideValue;
6329
6330 if (auto *Deinterleave = getCommonDeinterleavedSource(Members)) {
6331 Value *Source = Deinterleave->getArgOperand(0);
6332 assert(cast<VectorType>(Source->getType())->getElementCount() == WideEC &&
6333 "deinterleave source must have the interleaved element count");
6334 WideValueCache[Members] = Source;
6335 return Source;
6336 }
6337
6338 auto *NarrowInst = cast<Instruction>(Members.front());
6339 unsigned NumOperands = getNumDataOperands(NarrowInst);
6340 SmallVector<Value *, 4> NewOperands;
6341 NewOperands.reserve(NumOperands);
6342 for (unsigned Op = 0; Op != NumOperands; ++Op) {
6344 Value *NewOperand = nullptr;
6345 if ((NewOperand = getCommonSplatValue(Operands))) {
6346 if (isa<VectorType>(Operands.front()->getType())) {
6347 Builder.SetCurrentDebugLocation(NarrowInst->getDebugLoc());
6348 NewOperand = Builder.CreateVectorSplat(WideEC, NewOperand);
6349 } else {
6350 assert(all_equal(Operands) && "expected all operands to be equal");
6351 }
6352 } else {
6353 NewOperand = widenDeinterleavedOperations(Operands, WideEC, Builder,
6354 WideValueCache);
6355 }
6356 NewOperands.push_back(NewOperand);
6357 }
6358
6359 Builder.SetCurrentDebugLocation(NarrowInst->getDebugLoc());
6360 auto *WideResultTy =
6361 VectorType::get(NarrowInst->getType()->getScalarType(), WideEC);
6362 Value *NewValue =
6363 createWideInstruction(NarrowInst, NewOperands, WideResultTy, Builder);
6364 if (auto *NewInst = dyn_cast<Instruction>(NewValue)) {
6365 propagateIRFlags(NewInst, Members);
6366 propagateMetadata(NewInst, Members);
6367 }
6368 WideValueCache[Members] = NewValue;
6369 return NewValue;
6370}
6371
6372/// Fold away vector.deinterleave/interleave intrinsics with matching trees of
6373/// elementwise operations between them.
6374///
6375/// For example:
6376/// ```
6377/// %d = call { <2 x i16>, <2 x i16> } @deinterleave2.v4i16(<4 x i16> %v)
6378/// %f0 = extractvalue { <2 x i16>, <2 x i16> } %d, 0
6379/// %f1 = extractvalue { <2 x i16>, <2 x i16> } %d, 1
6380///
6381/// %u0 = add <2 x i16> %f0, splat (i16 3)
6382/// %u1 = add <2 x i16> %f1, splat (i16 3)
6383///
6384/// %r = call <4 x i16> @interleave2.v4i16(<2 x i16> %u0, <2 x i16> %u1)
6385/// ```
6386/// Folds to:
6387/// ```
6388/// %r = add <4 x i16> %v, splat (i16 3)
6389/// ```
6390/// And with two sources:
6391/// ```
6392/// %da = call { <2 x i16>, <2 x i16> } @deinterleave2.v4i16(<4 x i16> %a)
6393/// %a0 = extractvalue { <2 x i16>, <2 x i16> } %da, 0
6394/// %a1 = extractvalue { <2 x i16>, <2 x i16> } %da, 1
6395/// %db = call { <2 x i16>, <2 x i16> } @deinterleave2.v4i16(<4 x i16> %b)
6396/// %b0 = extractvalue { <2 x i16>, <2 x i16> } %db, 0
6397/// %b1 = extractvalue { <2 x i16>, <2 x i16> } %db, 1
6398///
6399/// %m0 = mul <2 x i16> %a0, %b0
6400/// %m1 = mul <2 x i16> %a1, %b1
6401///
6402/// %r = call <4 x i16> @interleave2.v4i16(<2 x i16> %m0, <2 x i16> %m1)
6403/// ```
6404/// Folds to:
6405/// ```
6406/// %r = mul <4 x i16> %a, %b
6407/// ```
6408bool VectorCombine::foldInterleaveOfDeinterleaveChains(Instruction &I) {
6409 auto *Interleave = dyn_cast<IntrinsicInst>(&I);
6410 if (!Interleave)
6411 return false;
6412
6413 unsigned Factor = getInterleaveIntrinsicFactor(Interleave->getIntrinsicID());
6414 if (!Factor || Interleave->hasOperandBundles())
6415 return false;
6416
6417 SmallVector<Value *, 8> RootMembers(Interleave->args());
6418 SmallPtrSet<User *, 4> UndroppableUsers;
6419 DenseSet<Value *> Visited;
6420 if (!canWidenDeinterleavedOperations(Opts, RootMembers, Visited,
6421 UndroppableUsers))
6422 return false;
6423 // Every users should be in the tree.
6424 if (!set_is_subset(UndroppableUsers, Visited))
6425 return false;
6426
6427 ElementCount WideEC = cast<VectorType>(I.getType())->getElementCount();
6428 Builder.SetInsertPoint(Interleave);
6429 // Mapping from members to the new wide value. This avoids emitting redundant
6430 // instructions when a new operand value has more than one use.
6431 DenseMap<SmallVector<Value *, 8>, Value *> WideValueCache;
6432 Value *WideValue = widenDeinterleavedOperations(RootMembers, WideEC, Builder,
6433 WideValueCache);
6434 assert(WideValue->getType() == Interleave->getType());
6435 replaceValue(*Interleave, *WideValue);
6436 return true;
6437}
6438
6439/// If we're interleaving 2 constant splats, for instance `<vscale x 8 x i32>
6440/// <splat of 666>` and `<vscale x 8 x i32> <splat of 777>`, we can create a
6441/// larger splat `<vscale x 8 x i64> <splat of ((777 << 32) | 666)>` first
6442/// before casting it back into `<vscale x 16 x i32>`.
6443bool VectorCombine::foldInterleaveIntrinsics(Instruction &I) {
6444 if (foldInterleaveOfDeinterleaveChains(I))
6445 return true;
6446
6447 const APInt *SplatVal0, *SplatVal1;
6449 m_APInt(SplatVal0), m_APInt(SplatVal1))))
6450 return false;
6451
6452 LLVM_DEBUG(dbgs() << "VC: Folding interleave2 with two splats: " << I
6453 << "\n");
6454
6455 auto *VTy =
6456 cast<VectorType>(cast<IntrinsicInst>(I).getArgOperand(0)->getType());
6457 auto *ExtVTy = VectorType::getExtendedElementVectorType(VTy);
6458 unsigned Width = VTy->getElementType()->getIntegerBitWidth();
6459
6460 // Just in case the cost of interleave2 intrinsic and bitcast are both
6461 // invalid, in which case we want to bail out, we use <= rather
6462 // than < here. Even they both have valid and equal costs, it's probably
6463 // not a good idea to emit a high-cost constant splat.
6464 if (TTI.getInstructionCost(&I, CostKind) <=
6465 TTI.getCastInstrCost(Instruction::BitCast, I.getType(), ExtVTy,
6466 TTI::CastContextHint::None, CostKind)) {
6467 LLVM_DEBUG(dbgs() << "VC: The cost to cast from " << *ExtVTy << " to "
6468 << *I.getType() << " is too high.\n");
6469 return false;
6470 }
6471
6472 // The bitcast puts element 0 of the narrow vector in the low half of each
6473 // wide element on little-endian targets, and in the high half on big-endian
6474 // targets.
6475 const APInt &LowHalf = DL->isLittleEndian() ? *SplatVal0 : *SplatVal1;
6476 const APInt &HighHalf = DL->isLittleEndian() ? *SplatVal1 : *SplatVal0;
6477 APInt NewSplatVal = HighHalf.zext(Width * 2);
6478 NewSplatVal <<= Width;
6479 NewSplatVal |= LowHalf.zext(Width * 2);
6480 auto *NewSplat = ConstantVector::getSplat(
6481 ExtVTy->getElementCount(), ConstantInt::get(F.getContext(), NewSplatVal));
6482
6483 Builder.SetInsertPoint(&I);
6484 replaceValue(I, *Builder.CreateBitCast(NewSplat, I.getType()));
6485 return true;
6486}
6487
6488/// Given this sequence:
6489/// ```
6490/// %d = llvm.vector.deinterleave2 <vscale x 16 x i32> %v
6491/// %f0 = extractvalue { <vscale x 8 x i32>, <vscale x 8 x i32> } %d, 0
6492/// %f1 = extractvalue { <vscale x 8 x i32>, <vscale x 8 x i32> } %d, 1
6493///
6494/// %low0 = and <vscale x 8 x i32> %f0, splat (i32 65535)
6495/// %low1 = shl <vscale x 8 x i32> %f1, splat (i32 16)
6496/// %merge0 = or disjoint <vscale x 8 x i32> %low0, %low1
6497///
6498/// %high0 = and <vscale x 8 x i32> %f1, splat (i32 -65536)
6499/// %high1 = lshr <vscale x 8 x i32> %f0, splat (i32 16)
6500/// %merge1 = or disjoint <vscale x 8 x i32> %high0, %high1
6501/// ```
6502/// It is actually just de-interleaving a 16-bit vector with double the
6503/// vector length. More generally speaking, it's de-interleaving on a vector
6504/// with half the element width as the original vector.
6505///
6506/// Therefore, we can turn it into:
6507/// ```
6508/// %narrow.v = bitcast <vscale x 16 x i32> %v to <vscale x 32 x i16>
6509/// %d = llvm.vector.deinterleave2 <vscale x 32 x i16> %narrow.v
6510/// %f0 = extractvalue { <vscale x 16 x i16>, <vscale x 16 x i16> } %d, 0
6511/// %f1 = extractvalue { <vscale x 16 x i16>, <vscale x 16 x i16> } %d, 1
6512///
6513/// %merge0 = bitcast <vscale x 16 x i16> %f0 to <vscale x 8 x i32>
6514/// %merge1 = bitcast <vscale x 16 x i16> %f1 to <vscale x 8 x i32>
6515/// ```
6516bool VectorCombine::foldDeinterleaveIntrinsics(Instruction &I) {
6517 using namespace PatternMatch;
6518 Value *DeinterleavedVal;
6519 if (!match(&I, m_Deinterleave2(m_Value(DeinterleavedVal))))
6520 return false;
6521
6522 VectorType *VecTy = cast<VectorType>(DeinterleavedVal->getType());
6523 IntegerType *ElementTy = dyn_cast<IntegerType>(VecTy->getElementType());
6524 if (!ElementTy)
6525 return false;
6526 unsigned ElementWidth = ElementTy->getBitWidth();
6527 if (ElementWidth < 2 || !isPowerOf2_32(ElementWidth))
6528 return false;
6529 unsigned HalfElementWidth = ElementWidth / 2;
6530
6531 if (!I.hasNUses(2))
6532 return false;
6533 std::array<ExtractValueInst *, 2> OrigFields{};
6534 for (User *Usr : I.users()) {
6535 auto *E = dyn_cast<ExtractValueInst>(Usr);
6536 // The deinterleave result can only be used by extractions.
6537 if (!E || E->getNumIndices() != 1)
6538 return false;
6539 unsigned Idx = *E->idx_begin();
6540 // A single field cannot be extracted more than once.
6541 if (Idx >= 2 || OrigFields[Idx] || !E->hasNUses(2))
6542 return false;
6543 OrigFields[Idx] = E;
6544 }
6545
6546 if (DL->isBigEndian())
6547 std::swap(OrigFields[0], OrigFields[1]);
6548
6549 // Find the merge instruction (i.e. OR) first.
6550 SmallVector<Instruction *, 2> MergeInsts;
6551 for (auto *FieldUsr : OrigFields[0]->users()) {
6552 if (!FieldUsr->hasOneUse() || !isa<Instruction>(FieldUsr->user_back()))
6553 return false;
6554 MergeInsts.push_back(FieldUsr->user_back());
6555 }
6556 assert(MergeInsts.size() == 2);
6557
6558 // Pattern match bottom-up from the merge instructions.
6559 auto MatchMerge = [&](void) -> bool {
6560 APInt LoMask = APInt::getLowBitsSet(ElementWidth, HalfElementWidth);
6561 APInt HiMask = APInt::getHighBitsSet(ElementWidth, HalfElementWidth);
6562 return match(MergeInsts[0],
6563 m_c_Or(m_And(m_Specific(OrigFields[0]), m_SpecificInt(LoMask)),
6564 m_Shl(m_Specific(OrigFields[1]),
6565 m_SpecificInt(HalfElementWidth)))) &&
6566 match(MergeInsts[1],
6567 m_c_Or(m_And(m_Specific(OrigFields[1]), m_SpecificInt(HiMask)),
6568 m_LShr(m_Specific(OrigFields[0]),
6569 m_SpecificInt(HalfElementWidth))));
6570 };
6571 if (!MatchMerge()) {
6572 std::swap(MergeInsts[0], MergeInsts[1]);
6573 if (!MatchMerge())
6574 return false;
6575 }
6576
6577 // Profitability check.
6578 InstructionCost OldCost =
6579 TTI.getInstructionCost(MergeInsts[0], CostKind) +
6580 TTI.getInstructionCost(cast<Instruction>(MergeInsts[0]->getOperand(0)),
6581 CostKind) +
6582 TTI.getInstructionCost(cast<Instruction>(MergeInsts[0]->getOperand(1)),
6583 CostKind);
6584 // There are two fields (assuming SHL has the same cost as LSHR).
6585 OldCost *= 2;
6586
6587 auto *NewFieldTy = VecTy->getWithNewBitWidth(HalfElementWidth);
6588 auto *NewVecTy =
6589 VectorType::getDoubleElementsVectorType(cast<VectorType>(NewFieldTy));
6590 InstructionCost NewCost =
6591 TTI.getCastInstrCost(Instruction::BitCast, VecTy, NewVecTy,
6592 TTI::CastContextHint::None, CostKind) +
6593 TTI.getCastInstrCost(Instruction::BitCast, NewFieldTy,
6594 MergeInsts[0]->getType(), TTI::CastContextHint::None,
6595 CostKind) *
6596 2;
6597 if (OldCost <= NewCost || !NewCost.isValid()) {
6598 LLVM_DEBUG(
6599 dbgs() << "VC: New deinterleave2 sequence cost (" << NewCost << ")"
6600 << " is higher than that of the old one (" << OldCost << ")\n");
6601 return false;
6602 }
6603
6604 // Do the replacement.
6605 Builder.SetInsertPoint(&I);
6606 Value *NewVecCast = Builder.CreateBitCast(DeinterleavedVal, NewVecTy);
6607 Value *NewDeinterleave = Builder.CreateIntrinsic(
6608 Intrinsic::vector_deinterleave2, {NewVecTy}, {NewVecCast});
6609 for (auto [Idx, MergeInst] : enumerate(MergeInsts)) {
6610 if (DL->isBigEndian())
6611 Idx ^= 1;
6612 Value *NewField = Builder.CreateExtractValue(NewDeinterleave, Idx);
6613 NewField = Builder.CreateBitCast(NewField, MergeInst->getType());
6614 replaceValue(*MergeInst, *NewField);
6615 }
6616
6617 return true;
6618}
6619
6620bool VectorCombine::foldBitcastOfVPLoad(Instruction &I) {
6621 const DataLayout &DL = I.getDataLayout();
6622 auto *Cast = dyn_cast<CastInst>(&I);
6623 if (!Cast || !Cast->isNoopCast(DL) || !isa<VectorType>(Cast->getDestTy()))
6624 return false;
6625
6626 // Fold away bit casts of the loaded value by loading the desired type,
6627 // if the mask is all-ones.
6628 Value *EVL;
6629 auto *II = dyn_cast<VPIntrinsic>(I.getOperand(0));
6631 m_Value(), m_AllOnes(), m_Value(EVL)))))
6632 return false;
6633
6634 VectorType *OrigVecTy = cast<VectorType>(II->getType());
6635 Align OrigAlign =
6636 DL.getValueOrABITypeAlignment(II->getPointerAlignment(), OrigVecTy);
6637 ElementCount OrigVecCnt = OrigVecTy->getElementCount();
6638 VectorType *NewVecTy = cast<VectorType>(Cast->getDestTy());
6639 ElementCount NewVecCnt = NewVecTy->getElementCount();
6640
6641 // Right now we only support cases where the NewVec is longer, because for
6642 // cases where it's shorter, we have to be sure that EVL can be exactly
6643 // divided, otherwise it might yield incorrect results or even page faults
6644 // (if we round-up during the division).
6645 if (!(OrigVecCnt.isScalable() == NewVecCnt.isScalable() &&
6646 NewVecCnt.hasKnownScalarFactor(OrigVecCnt)))
6647 return false;
6648
6649 InstructionCost OldCost =
6650 TTI.getMemIntrinsicInstrCost({Intrinsic::vp_load, OrigVecTy,
6651 II->getMemoryPointerParam(), false,
6652 OrigAlign},
6653 CostKind) +
6654 TTI.getCastInstrCost(Instruction::BitCast, Cast->getType(), OrigVecTy,
6655 TTI::CastContextHint::None, CostKind);
6657 {Intrinsic::vp_load, NewVecTy, II->getMemoryPointerParam(), false,
6658 OrigAlign},
6659 CostKind);
6660 LLVM_DEBUG(dbgs() << "foldBitcastOfVPLoad: OldCost=" << OldCost
6661 << " NewCost=" << NewCost << "\n");
6662 if (NewCost > OldCost || !NewCost.isValid())
6663 return false;
6664
6665 Builder.SetInsertPoint(II);
6666 unsigned Factor = NewVecCnt.getKnownScalarFactor(OrigVecCnt);
6667 Value *NewEVL = Builder.CreateNUWMul(EVL, Builder.getInt32(Factor));
6668 Value *NewMask = Builder.CreateVectorSplat(NewVecCnt, Builder.getTrue());
6669 CallInst *NewVP = Builder.CreateIntrinsicWithoutFolding(
6670 NewVecTy, Intrinsic::vp_load,
6671 {II->getMemoryPointerParam(), NewMask, NewEVL});
6672 // Preserve the original alignment.
6673 NewVP->addParamAttrs(
6674 0, AttrBuilder(II->getContext()).addAlignmentAttr(OrigAlign));
6675 replaceValue(*Cast, *NewVP);
6676 return true;
6677}
6678/// Fold the following cases into a single byte-level bit-reverse operation
6679/// and accepts bswap and bitreverse intrinsics:
6680/// bswap(bitreverse(x)) --> bitcast(bitreverse(bitcast(x)))
6681/// bitreverse(bswap(x)) <--> bitcast(bitreverse(bitcast(x)))
6682/// The direction of the fold is cost-model driven.
6683/// Also supports:
6684/// bitcast(bitreverse(bitcast(x))) --> bitreverse(fshl(x))
6685bool VectorCombine::foldBitOrderReverseAndSwap(Instruction &I) {
6686 Value *X;
6687
6689 Type *Ty = X->getType();
6690 Type *VecTy = I.getOperand(0)->getType();
6691 // Detect the case when bitreversing every octet in X individually. Then we
6692 // can use bswap to reorder the octets before doing a single bitreverse.
6693 bool CanUseBswap =
6694 Ty->isIntegerTy() && Ty == I.getType() && isa<FixedVectorType>(VecTy) &&
6695 cast<FixedVectorType>(VecTy)->getElementType()->isIntegerTy(8) &&
6696 Ty->getIntegerBitWidth() % 16 == 0;
6697 // Detect the case when bitreversing upper and lower half of X
6698 // individually. Then we can use fshl as a rotate operation, to swap the
6699 // halves before doing a single bitreverse.
6700 bool CanUseFshl =
6701 Ty->isIntegerTy() && Ty == I.getType() && isa<FixedVectorType>(VecTy) &&
6702 cast<FixedVectorType>(VecTy)->getElementType()->isIntegerTy() &&
6703 cast<FixedVectorType>(VecTy)->getNumElements() == 2;
6704 if (CanUseBswap || CanUseFshl) {
6705 auto *InnerCall = dyn_cast<Instruction>(I.getOperand(0));
6706 if (!InnerCall)
6707 return false;
6708 auto *InnerBitCast = dyn_cast<BitCastInst>(InnerCall->getOperand(0));
6709 if (!InnerBitCast)
6710 return false;
6711 Constant *HalfBW = ConstantInt::get(Ty, Ty->getIntegerBitWidth() / 2);
6712 InstructionCost OldCost = TTI.getInstructionCost(InnerBitCast, CostKind) +
6713 TTI.getInstructionCost(InnerCall, CostKind) +
6714 TTI.getInstructionCost(&I, CostKind);
6715 IntrinsicCostAttributes ICABSwap(Intrinsic::bswap, Ty, {Ty});
6716 IntrinsicCostAttributes ICABFshl(Intrinsic::fshl, Ty, {X, X, HalfBW},
6717 {Ty, Ty, Ty});
6718 IntrinsicCostAttributes ICABRev(Intrinsic::bitreverse, Ty, {Ty});
6719 InstructionCost NewCost =
6720 TTI.getIntrinsicInstrCost(CanUseBswap ? ICABSwap : ICABFshl,
6721 CostKind) +
6722 TTI.getIntrinsicInstrCost(ICABRev, CostKind);
6723 if (!InnerCall->hasOneUse())
6724 NewCost += TTI.getInstructionCost(InnerCall, CostKind) +
6725 TTI.getInstructionCost(InnerBitCast, CostKind);
6726 else if (!InnerBitCast->hasOneUse())
6727 NewCost += TTI.getInstructionCost(InnerBitCast, CostKind);
6728 LLVM_DEBUG(dbgs() << "Found bitreverse vector roundtrip: " << I
6729 << "\n OldCost: " << OldCost
6730 << " vs NewCost: " << NewCost << "\n");
6731 if (NewCost.isValid() && NewCost < OldCost) {
6732 Builder.SetInsertPoint(&I);
6733 Value *Swap =
6734 CanUseBswap
6735 ? Builder.CreateUnaryIntrinsic(Intrinsic::bswap, X)
6736 : Builder.CreateIntrinsic(Ty, Intrinsic::fshl, {X, X, HalfBW});
6737 Value *BRev = Builder.CreateUnaryIntrinsic(Intrinsic::bitreverse, Swap);
6738 replaceValue(I, *BRev);
6739 return true;
6740 }
6741 }
6742 }
6743
6744 if (!match(&I, m_BitReverse(m_BSwap(m_Value(X)))) &&
6746 return false;
6747 Type *Ty = I.getType();
6748 Type *I8Ty = Builder.getInt8Ty();
6749 TypeSize ElementSize = DL->getTypeStoreSize(Ty);
6750 ElementCount NewVecCnt = ElementCount::get(ElementSize.getKnownMinValue(),
6751 ElementSize.isScalable());
6752 Type *NewVecTy = VectorType::get(I8Ty, NewVecCnt);
6753 auto *II = cast<IntrinsicInst>(&I);
6754 auto *InnerII = cast<IntrinsicInst>(II->getArgOperand(0));
6755 // OldCost = cost of bitreverse/bswap + cost of bswap/bitreverse
6756 InstructionCost OldCost = TTI.getInstructionCost(II, CostKind) +
6757 TTI.getInstructionCost(InnerII, CostKind);
6758 // NewCost = cost of bitcast to byte vector +
6759 // cost of bitreverse/bswap on byte vector +
6760 // cost of bitcast back to original type
6761 InstructionCost CastToVecCost = TTI.getCastInstrCost(
6762 Instruction::BitCast, NewVecTy, Ty, TTI::CastContextHint::None, CostKind);
6763 InstructionCost CastToOrigCost = TTI.getCastInstrCost(
6764 Instruction::BitCast, Ty, NewVecTy, TTI::CastContextHint::None, CostKind);
6765 IntrinsicCostAttributes ICANew(Intrinsic::bitreverse, NewVecTy, {NewVecTy});
6766 InstructionCost NewIntrinsicCost =
6767 TTI.getIntrinsicInstrCost(ICANew, CostKind);
6768 InstructionCost NewCost = CastToVecCost + NewIntrinsicCost + CastToOrigCost;
6769 if (!InnerII->hasOneUse())
6770 NewCost += TTI.getInstructionCost(InnerII, CostKind);
6771 LLVM_DEBUG(dbgs() << "Found bitorder reverse and swap: " << I
6772 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
6773 << "\n");
6774 if (!NewCost.isValid() || NewCost >= OldCost)
6775 return false;
6776 // Perform transform: bitcast(arg, <N x i8>), bitreverse, bitcast back
6777 Builder.SetInsertPoint(II);
6778 Value *CastToVec = Builder.CreateBitCast(X, NewVecTy);
6779 Value *NewCall =
6780 Builder.CreateUnaryIntrinsic(Intrinsic::bitreverse, CastToVec);
6781 Value *CastToOrig = Builder.CreateBitCast(NewCall, Ty);
6782 replaceValue(I, *CastToOrig);
6783 return true;
6784}
6785
6786/// Given the maximum shuffle index and load vector type, compute the number of
6787/// elements for the shrunk load, rounding up to the next full vector register
6788/// boundary to avoid scalar remainders that legalize poorly.
6789static unsigned getAlignedNumElements(unsigned MaxIdx, FixedVectorType *LoadTy,
6790 const TargetTransformInfo &TTI,
6791 const DataLayout &DL) {
6792 unsigned RawNumElements = MaxIdx + 1u;
6793 Type *ElemTy = LoadTy->getElementType();
6794 // Skip alignment for illegal element types.
6795 if (!TTI.isTypeLegal(ElemTy))
6796 return RawNumElements;
6797
6798 TypeSize ElemSize = DL.getTypeSizeInBits(ElemTy);
6799 if (ElemSize.isScalable() || ElemSize.isZero())
6800 return RawNumElements;
6801
6804 if (RegSize.isScalable() || RegSize.isZero())
6805 return RawNumElements;
6806
6807 unsigned ElemsPerReg = RegSize.getFixedValue() / ElemSize.getFixedValue();
6808 // If the load already fits in a register, keep the exact size.
6809 // Otherwise round up to the next full register boundary.
6810 if (ElemsPerReg == 0 || RawNumElements <= ElemsPerReg)
6811 return RawNumElements;
6812
6813 return alignTo(RawNumElements, ElemsPerReg);
6814}
6815
6816// Attempt to shrink loads that are only used by shufflevector instructions.
6817bool VectorCombine::shrinkLoadForShuffles(Instruction &I) {
6818 auto *OldLoad = dyn_cast<LoadInst>(&I);
6819 if (!OldLoad || !OldLoad->isSimple())
6820 return false;
6821
6822 auto *OldLoadTy = dyn_cast<FixedVectorType>(OldLoad->getType());
6823 if (!OldLoadTy)
6824 return false;
6825
6826 unsigned const OldNumElements = OldLoadTy->getNumElements();
6827
6828 // Search all uses of load. If all uses are shufflevector instructions, and
6829 // the second operands are all poison values, find the minimum and maximum
6830 // indices of the vector elements referenced by all shuffle masks.
6831 // Otherwise return `std::nullopt`.
6832 using IndexRange = std::pair<int, int>;
6833 auto GetIndexRangeInShuffles = [&]() -> std::optional<IndexRange> {
6834 IndexRange OutputRange = IndexRange(OldNumElements, -1);
6835 for (Instruction *Shuffle : I.users()) {
6836 // Ensure all uses match the required pattern.
6837 ArrayRef<int> Mask;
6838
6839 if (!match(Shuffle,
6840 m_Shuffle(m_Specific(OldLoad), m_Undef(), m_Mask(Mask))))
6841 return std::nullopt;
6842
6843 // Ignore shufflevector instructions that have no uses.
6844 if (Shuffle->use_empty())
6845 continue;
6846
6847 // Find the min and max indices used by the shufflevector instruction.
6848 for (int Index : Mask) {
6849 if (Index >= 0 && Index < static_cast<int>(OldNumElements)) {
6850 OutputRange.first = std::min(Index, OutputRange.first);
6851 OutputRange.second = std::max(Index, OutputRange.second);
6852 }
6853 }
6854 }
6855
6856 if (OutputRange.second < OutputRange.first)
6857 return std::nullopt;
6858
6859 return OutputRange;
6860 };
6861
6862 // Get the range of vector elements used by shufflevector instructions.
6863 if (std::optional<IndexRange> Indices = GetIndexRangeInShuffles()) {
6864 unsigned const NewNumElements =
6865 getAlignedNumElements(Indices->second, OldLoadTy, TTI, *DL);
6866
6867 // If the range of vector elements is smaller than the full load, attempt
6868 // to create a smaller load.
6869 if (NewNumElements < OldNumElements) {
6870 Builder.SetInsertPoint(&I);
6871 Builder.SetCurrentDebugLocation(I.getDebugLoc());
6872
6873 // Calculate costs of old and new ops.
6874 Type *ElemTy = OldLoadTy->getElementType();
6875 FixedVectorType *NewLoadTy = FixedVectorType::get(ElemTy, NewNumElements);
6876 Value *PtrOp = OldLoad->getPointerOperand();
6877
6879 Instruction::Load, OldLoad->getType(), OldLoad->getAlign(),
6880 OldLoad->getPointerAddressSpace(), CostKind);
6881 InstructionCost NewCost =
6882 TTI.getMemoryOpCost(Instruction::Load, NewLoadTy, OldLoad->getAlign(),
6883 OldLoad->getPointerAddressSpace(), CostKind);
6884
6885 using UseEntry = std::pair<ShuffleVectorInst *, std::vector<int>>;
6887 unsigned const MaxIndex = NewNumElements * 2u;
6888
6889 for (Instruction *U : I.users()) {
6890 auto *Shuffle = cast<ShuffleVectorInst>(U);
6891
6892 // Ignore shufflevector instructions that have no uses.
6893 if (Shuffle->use_empty())
6894 continue;
6895
6896 ArrayRef<int> OldMask = Shuffle->getShuffleMask();
6897
6898 // Create entry for new use.
6899 NewUses.push_back({Shuffle, OldMask});
6900
6901 // Validate mask indices.
6902 for (int Index : OldMask) {
6903 if (Index >= static_cast<int>(MaxIndex))
6904 return false;
6905 }
6906
6907 // Update costs.
6908 OldCost +=
6910 OldLoadTy, CostKind, OldMask);
6911 NewCost +=
6913 NewLoadTy, CostKind, OldMask);
6914 }
6915
6916 LLVM_DEBUG(
6917 dbgs() << "Found a load used only by shufflevector instructions: "
6918 << I << "\n OldCost: " << OldCost
6919 << " vs NewCost: " << NewCost << "\n");
6920
6921 if (OldCost < NewCost || !NewCost.isValid())
6922 return false;
6923
6924 // Create new load of smaller vector.
6925 auto *NewLoad = cast<LoadInst>(
6926 Builder.CreateAlignedLoad(NewLoadTy, PtrOp, OldLoad->getAlign()));
6927 NewLoad->copyMetadata(I);
6928
6929 // Replace all uses.
6930 for (UseEntry &Use : NewUses) {
6931 ShuffleVectorInst *Shuffle = Use.first;
6932 std::vector<int> &NewMask = Use.second;
6933
6934 Builder.SetInsertPoint(Shuffle);
6935 Builder.SetCurrentDebugLocation(Shuffle->getDebugLoc());
6936 Value *NewShuffle = Builder.CreateShuffleVector(
6937 NewLoad, PoisonValue::get(NewLoadTy), NewMask);
6938
6939 replaceValue(*Shuffle, *NewShuffle, false);
6940 }
6941
6942 return true;
6943 }
6944 }
6945 return false;
6946}
6947
6948// Attempt to combine two adjacent fixed-length vector loads, that only feed
6949// shufflevector instructions, into a single wider load, rewriting every such
6950// shuffle so that operand 0 is the wide load and operand 1 is poison.
6951// clang-format off
6952// e.g.
6953// %loadA = load <16 x i8>, ptr %a
6954// %gep = getelementptr inbounds <16 x i8>, ptr %a, i64 1
6955// %loadB = load <16 x i8>, ptr %gep
6956// %shuffle0 = shufflevector <16 x i8> %loadA, <16 x i8> %loadB,
6957// <32 x i8> <...>
6958// %shuffle1 = shufflevector <16 x i8> %loadA, <16 x i8> %loadB,
6959// <32 x i8> <...>
6960//
6961// The fold would transform this to:
6962// %loadAB = load <32 x i8>, ptr %a
6963// %shuffle0 = shufflevector <32 x i8> %loadAB, <32 x i8> poison,
6964// <32 x i8> <...>
6965// %shuffle1 = shufflevector <32 x i8> %loadAB, <32 x i8> poison,
6966// <32 x i8> <...>
6967//
6968// clang-format on
6969// Matching this pattern in codegen becomes difficult and hence, we prefer doing
6970// this here.
6971bool VectorCombine::foldShuffleOfAdjacentLoads(Instruction &I) {
6972 auto *SV = cast<ShuffleVectorInst>(&I);
6973
6974 // The two operands must be distinct loads of the same fixed vector type.
6975 auto *Load0 = dyn_cast<LoadInst>(SV->getOperand(0));
6976 auto *Load1 = dyn_cast<LoadInst>(SV->getOperand(1));
6977 if (!Load0 || !Load1 || Load0 == Load1 || !Load0->isSimple() ||
6978 !Load1->isSimple())
6979 return false;
6980
6981 // Confirm both loads are of fixed vector type.
6982 auto *LoadTy = dyn_cast<FixedVectorType>(Load0->getType());
6983 if (!LoadTy)
6984 return false;
6985
6986 // We restrict to loads occurring in the same BB for now.
6987 if (Load0->getParent() != Load1->getParent())
6988 return false;
6989
6990 if (Load0->getPointerAddressSpace() != Load1->getPointerAddressSpace())
6991 return false;
6992
6993 // Check that the original load type has no padding bits otherwise the wide
6994 // load would be incorrect.
6995 if (DL->getTypeSizeInBits(LoadTy) != 8 * DL->getTypeStoreSize(LoadTy))
6996 return false;
6997
6998 const unsigned NumElts = LoadTy->getNumElements();
6999 // Avoid overflow/wraparound issues.
7000 if (NumElts > INT_MAX / 2)
7001 return false;
7002
7003 // Determine which load is at the lower address and confirm the two loads are
7004 // exactly contiguous: both pointers must strip to the same base, and their
7005 // constant offsets from it must differ by exactly the store size of LoadTy.
7006 unsigned AS = Load0->getPointerAddressSpace();
7007 unsigned IdxWidth = DL->getIndexSizeInBits(AS);
7008 APInt Offset0(IdxWidth, 0), Offset1(IdxWidth, 0);
7009 const Value *Base0 =
7010 Load0->getPointerOperand()->stripAndAccumulateConstantOffsets(
7011 *DL, Offset0, /*AllowNonInbounds=*/true);
7012 const Value *Base1 =
7013 Load1->getPointerOperand()->stripAndAccumulateConstantOffsets(
7014 *DL, Offset1, /*AllowNonInbounds=*/true);
7015 // Offsets accumulated across an addrspacecast are not comparable.
7016 if (Base0 != Base1 || Base0->getType()->getPointerAddressSpace() != AS)
7017 return false;
7018
7019 int64_t LoadSize = DL->getTypeStoreSize(LoadTy).getFixedValue();
7020 std::optional<int64_t> Dist = (Offset1 - Offset0).trySExtValue();
7021 LoadInst *LowLoad, *HighLoad;
7022 if (Dist == LoadSize) {
7023 LowLoad = Load0;
7024 HighLoad = Load1;
7025 } else if (Dist == -LoadSize) {
7026 LowLoad = Load1;
7027 HighLoad = Load0;
7028 } else {
7029 return false;
7030 }
7031
7032 // 1. Check all users of both loads are shuffles.
7033 // 2. Check that both loads feed exactly the same set of shuffles.
7034 SmallPtrSet<ShuffleVectorInst *, 4> Shuffles;
7035 if (!std::is_permutation(LowLoad->user_begin(), LowLoad->user_end(),
7036 HighLoad->user_begin(), HighLoad->user_end()) ||
7037 !all_of(LowLoad->users(), [&Shuffles](User *U) {
7038 if (auto *SVI = dyn_cast<ShuffleVectorInst>(U)) {
7039 Shuffles.insert(SVI);
7040 return true;
7041 }
7042 return false;
7043 }))
7044 return false;
7045
7046 // The value loaded by either load must not be clobbered in between the loads.
7047 auto *WideTy = FixedVectorType::get(LoadTy->getElementType(), NumElts * 2);
7048 LoadInst *FirstLoad = LowLoad, *LastLoad = HighLoad;
7049 if (HighLoad->comesBefore(LowLoad))
7050 std::swap(FirstLoad, LastLoad);
7051 MemoryLocation FirstLoc = MemoryLocation::get(FirstLoad);
7052 if (isMemModifiedBetween(Opts, std::next(FirstLoad->getIterator()),
7053 LastLoad->getIterator(), FirstLoc, AA))
7054 return false;
7055
7056 // case 1: wide load = LowLoad + HighLoad ,
7057 // shuffle 0th operand = LowLoad
7058 // shuffle 1st operand = HighLoad
7059 // Implication with this is shuffle mask for the wide load remains unchanged
7060 // case 2: wide load = LowLoad + HighLoad ,
7061 // shuffle 0th operand = HighLoad
7062 // shuffle 1st operand = LowLoad
7063 // Implication with this is shuffle mask for the wide load changes
7064 auto RemapMask = [&](ShuffleVectorInst *SV, SmallVectorImpl<int> &NewMask) {
7065 Value *SVOp0 = SV->getOperand(0);
7066 assert(((SVOp0 == LowLoad && SV->getOperand(1) == HighLoad) ||
7067 (SVOp0 == HighLoad && SV->getOperand(1) == LowLoad)) &&
7068 "Shuffle operands must be exactly {LowLoad, HighLoad} or {HighLoad, "
7069 "LowLoad}");
7070 SV->getShuffleMask(NewMask);
7071 if (SVOp0 == HighLoad)
7072 ShuffleVectorInst::commuteShuffleMask(NewMask, NumElts);
7073 };
7074
7075 // Cost model checks
7076 Value *Poison = PoisonValue::get(WideTy);
7077 InstructionCost OldCost =
7078 TTI.getMemoryOpCost(Instruction::Load, LoadTy, LowLoad->getAlign(),
7079 LowLoad->getPointerAddressSpace(), CostKind);
7080 OldCost +=
7081 TTI.getMemoryOpCost(Instruction::Load, LoadTy, HighLoad->getAlign(),
7082 HighLoad->getPointerAddressSpace(), CostKind);
7083 InstructionCost NewCost =
7084 TTI.getMemoryOpCost(Instruction::Load, WideTy, LowLoad->getAlign(),
7085 LowLoad->getPointerAddressSpace(), CostKind);
7086 for (ShuffleVectorInst *SV : Shuffles) {
7087 OldCost += TTI.getShuffleCost(TTI::SK_PermuteTwoSrc, SV->getType(), LoadTy,
7088 CostKind, SV->getShuffleMask());
7089 SmallVector<int, 32> NewMask;
7090 RemapMask(SV, NewMask);
7091 // LoadSz = initial load size
7092 // WideSz = 2 * LoadSz
7093 // MaxMaskSize = WideSz * 2
7094 // Check if MaxMaskSize fits within an integer range.
7095 if (!ShuffleVectorInst::isValidOperands(Poison, Poison, NewMask))
7096 return false;
7097 NewCost += TTI.getShuffleCost(TTI::SK_PermuteSingleSrc, SV->getType(),
7098 WideTy, CostKind, NewMask);
7099 }
7100
7101 LLVM_DEBUG(dbgs() << "Found adjacent loads feeding shuffles: " << *LowLoad
7102 << ", " << *HighLoad << "\n OldCost: " << OldCost
7103 << " vs NewCost: " << NewCost << "\n");
7104
7105 if (!NewCost.isValid() || NewCost > OldCost)
7106 return false;
7107
7108 // Insert the wide load at whichever original load comes last, so that both
7109 // halves of the contiguous range are known to be dereferenceable there.
7110 LoadInst *InsertPt = LastLoad;
7111
7112 // Build the wide load at the insertion point using the low load's pointer and
7113 // alignment, intersecting alias metadata from both original loads.
7114 Builder.SetInsertPoint(InsertPt);
7115 Builder.SetCurrentDebugLocation(InsertPt->getDebugLoc());
7116 LoadInst *WideLoad = Builder.CreateAlignedLoad(
7117 WideTy, LowLoad->getPointerOperand(), LowLoad->getAlign());
7118
7119 // Set the metadata on the wide load. copyMetadataForLoad seeds it from
7120 // LowLoad, then combineMetadataForCSE intersects every known kind against
7121 // HighLoad (taking the most-generic value where applicable, keeping facts
7122 // only where both loads agree, and dropping unknown metadata), so nothing is
7123 // asserted over the combined load unless justified by both halves.
7124 copyMetadataForLoad(*WideLoad, *LowLoad);
7125 combineMetadataForCSE(WideLoad, HighLoad, /*DoesKMove=*/true);
7126
7127 for (ShuffleVectorInst *SV : Shuffles) {
7128 SmallVector<int, 32> NewMask;
7129 RemapMask(SV, NewMask);
7130
7131 Builder.SetInsertPoint(SV);
7132 Builder.SetCurrentDebugLocation(SV->getDebugLoc());
7133 Value *NewShuf = Builder.CreateShuffleVector(WideLoad, Poison, NewMask);
7134 // We do not want to erase shuffles immediately because they may invalidate
7135 // the NextInst pointer in the caller's BB traversal.
7136 replaceValue(*SV, *NewShuf, /*Erase=*/false);
7137 }
7138 return true;
7139}
7140
7141// Attempt to narrow a phi of shufflevector instructions where the two incoming
7142// values have the same operands but different masks. If the two shuffle masks
7143// are offsets of one another we can use one branch to rotate the incoming
7144// vector and perform one larger shuffle after the phi.
7145bool VectorCombine::shrinkPhiOfShuffles(Instruction &I) {
7146 auto *Phi = dyn_cast<PHINode>(&I);
7147 if (!Phi || Phi->getNumIncomingValues() != 2u)
7148 return false;
7149
7150 Value *Op = nullptr;
7151 ArrayRef<int> Mask0;
7152 ArrayRef<int> Mask1;
7153
7154 if (!match(Phi->getOperand(0u),
7155 m_OneUse(m_Shuffle(m_Value(Op), m_Poison(), m_Mask(Mask0)))) ||
7156 !match(Phi->getOperand(1u),
7157 m_OneUse(m_Shuffle(m_Specific(Op), m_Poison(), m_Mask(Mask1)))))
7158 return false;
7159
7160 auto *Shuf = cast<ShuffleVectorInst>(Phi->getOperand(0u));
7161
7162 // Ensure result vectors are wider than the argument vector.
7163 auto *InputVT = cast<FixedVectorType>(Op->getType());
7164 auto *ResultVT = cast<FixedVectorType>(Shuf->getType());
7165 auto const InputNumElements = InputVT->getNumElements();
7166
7167 if (InputNumElements >= ResultVT->getNumElements())
7168 return false;
7169
7170 // Take the difference of the two shuffle masks at each index. Ignore poison
7171 // values at the same index in both masks.
7172 SmallVector<int, 16> NewMask;
7173 NewMask.reserve(Mask0.size());
7174
7175 auto IsPoison = [InputNumElements](int M) {
7176 return M < 0 || (unsigned)M >= InputNumElements;
7177 };
7178
7179 for (auto [M0, M1] : zip(Mask0, Mask1)) {
7180 bool P0 = IsPoison(M0);
7181 bool P1 = IsPoison(M1);
7182 if (!P0 && !P1)
7183 NewMask.push_back(M0 - M1);
7184 else if (P0 && P1)
7185 continue;
7186 else
7187 return false;
7188 }
7189
7190 // Ensure all elements of the new mask are equal. If the difference between
7191 // the incoming mask elements is the same, the two must be constant offsets
7192 // of one another.
7193 if (NewMask.empty() || !all_equal(NewMask))
7194 return false;
7195
7196 // Create new mask using difference of the two incoming masks.
7197 int MaskOffset = NewMask[0u];
7198 unsigned Index = (InputNumElements + MaskOffset) % InputNumElements;
7199 NewMask.clear();
7200
7201 for (unsigned I = 0u; I < InputNumElements; ++I) {
7202 NewMask.push_back(Index);
7203 Index = (Index + 1u) % InputNumElements;
7204 }
7205
7206 // Calculate costs for worst cases and compare.
7207 auto const Kind = TTI::SK_PermuteSingleSrc;
7208 auto OldCost =
7209 std::max(TTI.getShuffleCost(Kind, ResultVT, InputVT, CostKind, Mask0),
7210 TTI.getShuffleCost(Kind, ResultVT, InputVT, CostKind, Mask1));
7211 auto NewCost = TTI.getShuffleCost(Kind, InputVT, InputVT, CostKind, NewMask) +
7212 TTI.getShuffleCost(Kind, ResultVT, InputVT, CostKind, Mask1);
7213
7214 LLVM_DEBUG(dbgs() << "Found a phi of mergeable shuffles: " << I
7215 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
7216 << "\n");
7217
7218 if (NewCost > OldCost)
7219 return false;
7220
7221 // Create new shuffles and narrowed phi.
7222 Builder.SetInsertPoint(Shuf);
7223 Builder.SetCurrentDebugLocation(Shuf->getDebugLoc());
7224 auto *PoisonVal = PoisonValue::get(InputVT);
7225 auto *NewShuf0 = Builder.CreateShuffleVector(Op, PoisonVal, NewMask);
7226
7227 Builder.SetInsertPoint(Phi);
7228 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
7229 auto *NewPhi = Builder.CreatePHI(NewShuf0->getType(), 2u);
7230 NewPhi->addIncoming(NewShuf0, Phi->getIncomingBlock(0u));
7231 NewPhi->addIncoming(Op, Phi->getIncomingBlock(1u));
7232
7233 Builder.SetInsertPoint(*NewPhi->getInsertionPointAfterDef());
7234 PoisonVal = PoisonValue::get(NewPhi->getType());
7235 auto *NewShuf1 = Builder.CreateShuffleVector(NewPhi, PoisonVal, Mask1);
7236
7237 replaceValue(*Phi, *NewShuf1);
7238 return true;
7239}
7240
7241/// This is the entry point for all transforms. Pass manager differences are
7242/// handled in the callers of this function.
7243bool VectorCombine::run() {
7244 if (Opts.disable_vector_combine)
7245 return false;
7246
7247 // Don't attempt vectorization if the target does not support vectors.
7248 if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true)))
7249 return false;
7250
7251 LLVM_DEBUG(dbgs() << "\n\nVECTORCOMBINE on " << F.getName() << "\n");
7252
7253 auto FoldInst = [this](Instruction &I) {
7254 Builder.SetInsertPoint(&I);
7255 bool IsVectorType = isa<VectorType>(I.getType());
7256 bool IsFixedVectorType = isa<FixedVectorType>(I.getType());
7257 auto Opcode = I.getOpcode();
7258
7259 LLVM_DEBUG(dbgs() << "VC: Visiting: " << I << '\n');
7260
7261 // These folds should be beneficial regardless of when this pass is run
7262 // in the optimization pipeline.
7263 // The type checking is for run-time efficiency. We can avoid wasting time
7264 // dispatching to folding functions if there's no chance of matching.
7265 if (IsFixedVectorType) {
7266 switch (Opcode) {
7267 case Instruction::InsertElement:
7268 if (vectorizeLoadInsert(I))
7269 return true;
7270 break;
7271 case Instruction::ShuffleVector:
7272 if (widenSubvectorLoad(I))
7273 return true;
7274 break;
7275 default:
7276 break;
7277 }
7278 }
7279
7280 // This transform works with scalable and fixed vectors
7281 // TODO: Identify and allow other scalable transforms
7282 if (IsVectorType) {
7283 if (scalarizeOpOrCmp(I))
7284 return true;
7285 if (scalarizeLoad(I))
7286 return true;
7287 if (scalarizeExtExtract(I))
7288 return true;
7289 if (foldInterleaveIntrinsics(I))
7290 return true;
7291 if (foldBitcastOfVPLoad(I))
7292 return true;
7293 }
7294
7295 if (foldDeinterleaveIntrinsics(I))
7296 return true;
7297
7298 if (Opcode == Instruction::Store)
7299 if (foldInsertElementsToStores(I))
7300 return true;
7301
7302 // If this is an early pipeline invocation of this pass, we are done.
7303 if (TryEarlyFoldsOnly)
7304 return false;
7305
7306 if (Opcode == Instruction::Call)
7307 if (foldBitOrderReverseAndSwap(I))
7308 return true;
7309 if (Opcode == Instruction::BitCast)
7310 if (foldBitOrderReverseAndSwap(I))
7311 return true;
7312
7313 // Otherwise, try folds that improve codegen but may interfere with
7314 // early IR canonicalizations.
7315 // The type checking is for run-time efficiency. We can avoid wasting time
7316 // dispatching to folding functions if there's no chance of matching.
7317 if (IsFixedVectorType) {
7318 switch (Opcode) {
7319 case Instruction::InsertElement:
7320 if (foldInsExtFNeg(I))
7321 return true;
7322 if (foldInsExtBinop(I))
7323 return true;
7324 if (foldInsExtVectorToShuffle(I))
7325 return true;
7326 if (foldInsertScalarPartsToShuffle(I))
7327 return true;
7328 break;
7329 case Instruction::ShuffleVector:
7330 if (foldPermuteOfBinops(I))
7331 return true;
7332 if (foldShuffleOfBinops(I))
7333 return true;
7334 if (foldShuffleOfSelects(I))
7335 return true;
7336 if (foldShuffleOfCastops(I))
7337 return true;
7338 if (foldShuffleOfShuffles(I))
7339 return true;
7340 if (foldShuffleOfAdjacentLoads(I))
7341 return true;
7342 if (foldPermuteOfIntrinsic(I))
7343 return true;
7344 if (foldShufflesOfLengthChangingShuffles(I))
7345 return true;
7346 if (foldShuffleOfIntrinsics(I))
7347 return true;
7348 if (foldSelectShuffle(I))
7349 return true;
7350 if (foldShuffleToIdentity(I))
7351 return true;
7352 break;
7353 case Instruction::Load:
7354 if (shrinkLoadForShuffles(I))
7355 return true;
7356 break;
7357 case Instruction::BitCast:
7358 if (foldBitcastShuffle(I))
7359 return true;
7360 if (foldSelectsFromBitcast(I))
7361 return true;
7362 break;
7363 case Instruction::And:
7364 case Instruction::Or:
7365 case Instruction::Xor:
7366 if (foldBitOpOfCastops(I))
7367 return true;
7368 if (foldBitOpOfCastConstant(I))
7369 return true;
7370 break;
7371 case Instruction::PHI:
7372 if (shrinkPhiOfShuffles(I))
7373 return true;
7374 break;
7375 default:
7376 if (shrinkType(I))
7377 return true;
7378 break;
7379 }
7380 } else {
7381 switch (Opcode) {
7382 case Instruction::Call:
7383 if (foldShuffleFromReductions(I))
7384 return true;
7385 if (foldCastFromReductions(I))
7386 return true;
7387 break;
7388 case Instruction::ExtractElement:
7389 if (foldShuffleChainsToReduce(I))
7390 return true;
7391 break;
7392 case Instruction::ICmp:
7393 if (foldSignBitReductionCmp(I))
7394 return true;
7395 if (foldICmpEqZeroVectorReduce(I))
7396 return true;
7397 if (foldReductionZeroTest(I))
7398 return true;
7399 if (foldEquivalentReductionCmp(I))
7400 return true;
7401 if (foldReduceAddCmpZero(I))
7402 return true;
7403 [[fallthrough]];
7404 case Instruction::FCmp:
7405 if (foldExtractExtract(I))
7406 return true;
7407 break;
7408 case Instruction::Or:
7409 if (foldConcatOfBoolMasks(I))
7410 return true;
7411 [[fallthrough]];
7412 default:
7413 if (Instruction::isBinaryOp(Opcode)) {
7414 if (foldExtractExtract(I))
7415 return true;
7416 if (foldExtractedCmps(I))
7417 return true;
7418 if (foldBinopOfReductions(I))
7419 return true;
7420 }
7421 break;
7422 }
7423 }
7424 return false;
7425 };
7426
7427 bool MadeChange = false;
7428 for (BasicBlock &BB : F) {
7429 // Ignore unreachable basic blocks.
7430 if (!DT.isReachableFromEntry(&BB))
7431 continue;
7432 // Use early increment range so that we can erase instructions in loop.
7433 // make_early_inc_range is not applicable here, as the next iterator may
7434 // be invalidated by RecursivelyDeleteTriviallyDeadInstructions.
7435 // We manually maintain the next instruction and update it when it is about
7436 // to be deleted.
7437 Instruction *I = &BB.front();
7438 while (I) {
7439 NextInst = I->getNextNode();
7440 MadeChange |= FoldInst(*I);
7441 I = NextInst;
7442 }
7443 }
7444
7445 NextInst = nullptr;
7446
7447 while (!Worklist.isEmpty()) {
7448 // Push deferred instructions in reverse order, so that they'll end up
7449 // popped from the worklist in-order.
7450 while (Instruction *I = Worklist.popDeferred()) {
7453 continue;
7454 }
7455
7456 Worklist.push(I);
7457 }
7458
7459 Instruction *I = Worklist.removeOne();
7460 if (!I)
7461 continue;
7462
7465 continue;
7466 }
7467
7468 MadeChange |= FoldInst(*I);
7469 }
7470
7471 return MadeChange;
7472}
7473
7475 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
7476 static_cast<PassInfoMixin<VectorCombinePass> *>(this)->printPipeline(
7477 OS, MapClassName2PassName);
7478 if (TryEarlyFoldsOnly)
7479 OS << "<early-folds-only>";
7480}
7481
7484 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
7486 DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
7487 AAResults &AA = FAM.getResult<AAManager>(F);
7488 const DataLayout *DL = &F.getDataLayout();
7489 TTI::TargetCostKind CostKind =
7491 VectorCombine Combiner(getVectorizeOptions(F), F, TTI, DT, AA, AC, DL,
7492 CostKind, TryEarlyFoldsOnly);
7493 if (!Combiner.run())
7494 return PreservedAnalyses::all();
7497 return PA;
7498}
SDValue Pred
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
This is the interface for LLVM's primary stateless and local alias analysis.
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseMap class.
#define Check(C,...)
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
iv users
Definition IVUsers.cpp:48
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static void eraseInstruction(Instruction &I, const LICMDependencies &Deps)
Definition LICM.cpp:1183
SmallVector< MachineOperand, 4 > Cond
if(!TBB||Cond.size()< 1) return false
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T1
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
This file contains the declarations for profiling metadata utility functions.
int64_t C1
int64_t C0
SI Fold Operands
This file contains some templates that are useful if you are working with the STL at all.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines generic set operations that may be used on set's of different types,...
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
static bool isEquivBitcast(Value *X, Value *Y)
Helper to peek through bitcasts to the same value.
static SmallVector< Value *, 8 > getInstrOperandsAtIdx(ArrayRef< Value * > Members, unsigned OperandIndex)
Return the operand at OperandIndex of each Members.
static bool isFreeConcat(ArrayRef< InstLane > Item, TTI::TargetCostKind CostKind, const TargetTransformInfo &TTI)
Detect concat of multiple values into a vector.
static void analyzeCostOfVecReduction(const IntrinsicInst &II, TTI::TargetCostKind CostKind, const TargetTransformInfo &TTI, InstructionCost &CostBeforeReduction, InstructionCost &CostAfterReduction)
static Value * generateNewInstTree(ArrayRef< InstLane > Item, Use *From, const DenseSet< std::pair< Value *, Use * > > &IdentityLeafs, const DenseSet< std::pair< Value *, Use * > > &SplatLeafs, const DenseSet< std::pair< Value *, Use * > > &ConcatLeafs, IRBuilderBase &Builder, InstructionWorklist &WorkList, const TargetTransformInfo *TTI)
static SmallVector< InstLane > generateInstLaneVectorFromOperand(ArrayRef< InstLane > Item, int Op)
static Value * createShiftShuffle(Value *Vec, unsigned OldIndex, unsigned NewIndex, IRBuilderBase &Builder)
Create a shuffle that translates (shifts) 1 element from the input vector to a new element location.
std::pair< Value *, int > InstLane
static Value * createWideInstruction(Instruction *NarrowInst, ArrayRef< Value * > NewOperands, VectorType *WideResultTy, IRBuilderBase &Builder)
static unsigned getNumDataOperands(const Instruction *Inst)
Return the number of data operands of Inst.
static bool isKnownNonPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Used by foldReduceAddCmpZero to check if we can prove that a value is non-positive.
static bool isSupportedElementwise(Instruction *Inst)
Return true if Inst is an elementwise operation that can be rebuilt at a wider element count.
static Value * materializeScalarizedGEPIndex(Value *Idx, IntegerType *GEPIndexTy, IRBuilderBase &Builder)
Materialize an index for a scalarized GEP after profitability is known.
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 bool feedsIntoVectorReduction(ShuffleVectorInst *SVI)
Returns true if this ShuffleVectorInst eventually feeds into a vector reduction intrinsic (e....
static bool canWidenLoad(LoadInst *Load, const TargetTransformInfo &TTI)
static const unsigned InvalidIndex
static Value * getCommonSplatValue(ArrayRef< Value * > Values)
Return the common splat value of Values.
static IntegerType * getScalarizedGEPIndexInfo(VectorType *VecTy, Value *Idx, Type *PtrTy, const DataLayout &DL)
Return the GEP index type if the unsigned vector index Idx can be represented by an inbounds GEP.
static Value * translateExtract(ExtractElementInst *ExtElt, unsigned NewIndex, IRBuilderBase &Builder)
Given an extract element instruction with constant index operand, shuffle the source vector (shift th...
static ScalarizationResult canScalarizeAccess(VectorType *VecTy, Value *Idx, const SimplifyQuery &SQ)
Check if it is legal to scalarize a memory access to VecTy at index Idx.
static bool canWidenDeinterleavedOperations(const VectorizeOptions &Opts, ArrayRef< Value * > Members, DenseSet< Value * > &Visited, SmallPtrSetImpl< User * > &UndroppableUsers)
Check whether the tree of elementwise operations each feeding Members can be rebuilt at the interleav...
static unsigned getAlignedNumElements(unsigned MaxIdx, FixedVectorType *LoadTy, const TargetTransformInfo &TTI, const DataLayout &DL)
Given the maximum shuffle index and load vector type, compute the number of elements for the shrunk l...
static InstLane lookThroughShuffles(Value *V, int Lane)
static IntrinsicInst * getCommonDeinterleavedSource(ArrayRef< Value * > Members)
Return the common deinterleave intrinsic if Members are its extracts in field order.
static bool isMemModifiedBetween(const VectorizeOptions &Opts, BasicBlock::iterator Begin, BasicBlock::iterator End, const MemoryLocation &Loc, AAResults &AA)
static Value * widenDeinterleavedOperations(const SmallVector< Value *, 8 > &Members, ElementCount WideEC, IRBuilderBase &Builder, DenseMap< SmallVector< Value *, 8 >, Value * > &WideValueCache)
static constexpr int Concat[]
Value * RHS
Value * LHS
A manager for alias analyses.
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
unsigned countl_one() const
Count the number of leading one bits.
Definition APInt.h:1635
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition ArrayRef.h:194
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Value * getArgOperand(unsigned i) const
void addParamAttrs(unsigned ArgNo, const AttrBuilder &B)
Adds attributes to the indicated argument.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
bool isFPPredicate() const
Definition InstrTypes.h:845
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
Combiner implementation.
Definition Combiner.h:33
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
This class represents a range of values.
LLVM_ABI ConstantRange urem(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned remainder operation of...
LLVM_ABI 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...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:312
This instruction extracts a single (scalar) element from a VectorType value.
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
static FixedVectorType * getDoubleElementsVectorType(FixedVectorType *VTy)
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
This class represents a freeze function that returns random concrete value if an operand is either a ...
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
bool isEquality() const
Return true if this predicate is either EQ or NE.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
LLVM_ABI CallInst * CreateIntrinsicWithoutFolding(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={})
Create a call to intrinsic ID with Args, mangled using OverloadTypes.
Value * CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1471
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2748
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2736
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition IRBuilder.h:1940
Value * CreateNoWrapBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, bool IsNUW, bool IsNSW, const Twine &Name="")
Definition IRBuilder.h:1750
LLVM_ABI Value * CreateSelectFMF(Value *C, Value *True, Value *False, FMFSource FMFSource, const Twine &Name="", Instruction *MDFrom=nullptr)
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2795
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition IRBuilder.h:451
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition IRBuilder.h:2814
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:229
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1534
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Definition IRBuilder.h:2360
Value * CreateIsNotNeg(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg > -1.
Definition IRBuilder.h:2852
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition IRBuilder.h:2021
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", bool HasSameSign=false)
Definition IRBuilder.h:2568
Value * CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2385
Value * CreateFCmpFMF(CmpInst::Predicate P, Value *LHS, Value *RHS, FMFSource FMFSource, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2589
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:476
LLVM_ABI Value * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:471
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2595
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition IRBuilder.h:2626
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition IRBuilder.h:148
Value * CreateBinOpFMF(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, FMFSource FMFSource, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1739
Value * CreateIsNeg(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg < 0.
Definition IRBuilder.h:2847
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2319
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:1913
Value * CreateUnOpFMF(Instruction::UnaryOps Opc, Value *V, FMFSource FMFSource, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1866
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1513
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2197
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition IRBuilder.h:2770
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1572
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1931
Value * CreateExactBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, bool IsExact, const Twine &Name="")
Definition IRBuilder.h:1762
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition IRBuilder.h:2183
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:571
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1733
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
Value * CreateFNegFMF(Value *V, FMFSource FMFSource, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1846
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1594
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition IRBuilder.h:518
LLVM_ABI Value * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *Op, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
Definition IRBuilder.h:74
InstSimplifyFolder - Use InstructionSimplify to fold operations to existing values.
CostType getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
InstructionWorklist - This is the worklist management logic for InstCombine and other simplification ...
void push(Instruction *I)
Push the instruction onto the worklist stack.
void remove(Instruction *I)
Remove I from the worklist if it exists.
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction.
bool isBinaryOp() const
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
user_iterator user_begin()
@ CompareCallTargets
Check for equivalence by comparing call targets.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
user_iterator user_end()
bool isIdempotent() const
Return true if the instruction is idempotent:
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI bool hasAllowReassoc() const LLVM_READONLY
Determine whether the allow-reassociation flag is set.
bool isIntDivRem() const
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
void setAlignment(Align Align)
Value * getPointerOperand()
Type * getPointerOperandType() const
Align getAlign() const
Return the alignment of the access that is being performed.
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
This class represents the LLVM 'select' instruction.
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
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.
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
VectorType * getType() const
Overload to return most specific vector type.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
static LLVM_ABI bool isIdentityMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector without lane crossin...
static void commuteShuffleMask(MutableArrayRef< int > Mask, unsigned InVecNumElts)
Change values in a shuffle permute mask assuming the two vector operands of length InVecNumElts have ...
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
void setAlignment(Align Align)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
static LLVM_ABI CastContextHint getCastContextHint(const Instruction *I)
Calculates a CastContextHint from I.
LLVM_ABI InstructionCost getGEPCost(Type *PointeeType, const Value *Ptr, ArrayRef< const Value * > Operands, TargetCostKind CostKind, Type *AccessType=nullptr) const
Estimate the cost of a GEP operation when lowered.
LLVM_ABI TypeSize getRegisterBitWidth(RegisterKind K) const
LLVM_ABI InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, OperandValueInfo OpdInfo={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
static LLVM_ABI OperandValueInfo commonOperandInfo(const Value *X, const Value *Y)
Collect common data between two OperandValueInfo inputs.
LLVM_ABI bool allowVectorElementIndexingUsingGEP() const
Returns true if GEP should not be used to index into vectors for this target.
LLVM_ABI InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
LLVM_ABI InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index=-1, const Value *Op0=nullptr, const Value *Op1=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
LLVM_ABI InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind, OperandValueInfo Op1Info={OK_AnyValue, OP_None}, OperandValueInfo Op2Info={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
LLVM_ABI InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, TTI::TargetCostKind CostKind, ArrayRef< int > Mask={}, int Index=0, VectorType *SubTp=nullptr, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
LLVM_ABI InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const
LLVM_ABI unsigned getRegisterClassForType(bool Vector, Type *Ty=nullptr) const
LLVM_ABI InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const
Calculate the cost of vector reduction intrinsics.
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_CodeSize
Instruction code size.
LLVM_ABI InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr, ArrayRef< const Value * > Scalars={}) const
This is an approximation of reciprocal throughput of a math/logic op.
LLVM_ABI InstructionCost getMemIntrinsicInstrCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const
LLVM_ABI InstructionCost getMinMaxReductionCost(Intrinsic::ID IID, VectorType *Ty, FastMathFlags FMF, TTI::TargetCostKind CostKind) const
LLVM_ABI unsigned getMinVectorRegisterBitWidth() const
LLVM_ABI InstructionCost getAddressComputationCost(Type *PtrTy, ScalarEvolution *SE, const SCEV *Ptr, TTI::TargetCostKind CostKind) const
LLVM_ABI unsigned getNumberOfRegisters(unsigned ClassID) const
LLVM_ABI InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
LLVM_ABI InstructionCost getScalarizationOverhead(VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind, bool ForPoisonSrc=true, ArrayRef< Value * > VL={}, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
Estimate the overhead of scalarizing an instruction.
ShuffleKind
The various kinds of shuffle patterns for vector queries.
@ SK_PermuteSingleSrc
Shuffle elements of single source vector with any shuffle mask.
@ SK_PermuteTwoSrc
Merge elements from two source vectors into one with any shuffle mask.
@ SK_ExtractSubvector
ExtractSubvector Index indicates start offset.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
bool isIEEELikeFPTy() const
Return true if this is a well-behaved IEEE-like type, which has a IEEE compatible layout,...
Definition Type.h:172
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
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:729
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
Definition Value.cpp:158
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:985
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:545
LLVM_ABI bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition Value.cpp:142
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:707
bool use_empty() const
Definition Value.h:348
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
bool user_empty() const
Definition Value.h:391
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Type * getElementType() const
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
size_type size() const
Definition DenseSet.h:85
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:188
constexpr bool hasKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns true if there exists a value X where RHS*X will result in a value whose quantity matches our ...
Definition TypeSize.h:266
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr ScalarTy getKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns a value X where RHS*X will result in a value whose quantity matches our own.
Definition TypeSize.h:274
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
constexpr bool isZero() const
Definition TypeSize.h:154
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2274
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2279
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_and< Ty... > m_CombineAnd(const Ty &...Ps)
Combine pattern matchers matching all of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_BSwap(const Opnd0 &Op0)
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
auto m_BitReverse(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
auto m_Poison()
Match an arbitrary poison constant.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
DisjointOr_match< LHS, RHS > m_DisjointOr(const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
cst_pred_ty< is_non_zero_int > m_NonZeroInt()
Match a non-zero integer or a vector with all non-zero elements.
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
auto m_AnyIntrinsic()
Matches any intrinsic call and ignore it.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinOpPred_match< LHS, RHS, is_bitwiselogic_op, true > m_c_BitwiseLogic(const LHS &L, const RHS &R)
Matches bitwise logic operations in either order.
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".
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_Deinterleave2(const Opnd &Op)
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_Undef()
Match an arbitrary undef constant.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
@ Valid
The data is already valid.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
void stable_sort(R &&Range)
Definition STLExtras.h:2132
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
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:1748
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:522
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI Value * simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q)
Given operand for a UnaryOperator, fold the result or return null.
scope_exit(Callable) -> scope_exit< Callable >
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI void copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source)
Copy the metadata from the source instruction to the destination (the replacement for the source inst...
Definition Local.cpp:3194
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
LLVM_ABI unsigned getArithmeticReductionInstruction(Intrinsic::ID RdxID)
Returns the arithmetic instruction opcode used when expanding a reduction.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI Value * simplifyCall(CallBase *Call, Value *Callee, ArrayRef< Value * > Args, const SimplifyQuery &Q)
Given a callsite, callee, and arguments, fold the result or return null.
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:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
Definition Loads.cpp:453
LLVM_ABI 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...
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI Instruction * propagateMetadata(Instruction *I, ArrayRef< Value * > VL)
Propagate metadata that can be preserved after vectorization from VL to I, retaining only information...
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
unsigned M1(unsigned Val)
Definition VE.h:394
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:1762
LLVM_ABI 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:408
LLVM_ABI 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...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI unsigned getDeinterleaveIntrinsicFactor(Intrinsic::ID ID)
Returns the corresponding factor of llvm.vector.deinterleaveN intrinsics.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
LLVM_ABI unsigned getInterleaveIntrinsicFactor(Intrinsic::ID ID)
Returns the corresponding factor of llvm.vector.interleaveN intrinsics.
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:552
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI void propagateIRFlags(Value *I, ArrayRef< Value * > VL, Value *OpValue=nullptr, bool IncludeWrapFlags=true)
Get the intersection (logical and) of all of the potential IR flags of each scalar operation (VL) tha...
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
constexpr int PoisonMaskElem
LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
Definition Local.cpp:3185
@ Other
Any other memory.
Definition ModRef.h:68
TargetTransformInfo TTI
LLVM_ABI bool isSafeToLoadUnconditionally(Value *V, Align Alignment, const APInt &Size, const SimplifyQuery &SQ, bool IgnoreFree=false)
Return true if we know that executing a load from this value cannot trap.
Definition Loads.cpp:457
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
LLVM_ABI 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...
LLVM_ABI Intrinsic::ID getReductionForBinop(Instruction::BinaryOps Opc)
Returns the reduction intrinsic id corresponding to the binary operation.
@ And
Bitwise or logical AND of integers.
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
unsigned M0(unsigned Val)
Definition VE.h:393
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
constexpr unsigned BitWidth
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
LLVM_ABI Constant * getLosslessInvCast(Constant *C, Type *InvCastTo, unsigned CastOp, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
Try to cast C to InvC losslessly, satisfying CastOp(InvC) equals C, or CastOp(InvC) is a refined valu...
const VectorizeOptions & getVectorizeOptions(const LLVMContext &C)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
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:1788
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
LLVM_ABI Value * simplifyCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a CmpInst, fold the result or return null.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicID(Intrinsic::ID IID)
Returns the llvm.vector.reduce min/max intrinsic that corresponds to the intrinsic op.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
LLVM_ABI AAMDNodes adjustForAccess(unsigned AccessSize)
Create a new AAMDNode for accessing AccessSize bytes of this AAMDNode.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
unsigned countMaxActiveBits() const
Returns the maximum number of bits needed to represent all possible unsigned values with these known ...
Definition KnownBits.h:310
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
const DataLayout & DL
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const Instruction * CtxI