1 //===----------- VectorUtils.cpp - Vectorizer utility functions -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines vectorizer utilities.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/Analysis/VectorUtils.h"
14 #include "llvm/ADT/EquivalenceClasses.h"
15 #include "llvm/Analysis/DemandedBits.h"
16 #include "llvm/Analysis/LoopInfo.h"
17 #include "llvm/Analysis/LoopIterator.h"
18 #include "llvm/Analysis/ScalarEvolution.h"
19 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/GetElementPtrTypeIterator.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/PatternMatch.h"
26 #include "llvm/IR/Value.h"
27 #include "llvm/Support/CommandLine.h"
28
29 #define DEBUG_TYPE "vectorutils"
30
31 using namespace llvm;
32 using namespace llvm::PatternMatch;
33
34 /// Maximum factor for an interleaved memory access.
35 static cl::opt<unsigned> MaxInterleaveGroupFactor(
36 "max-interleave-group-factor", cl::Hidden,
37 cl::desc("Maximum factor for an interleaved access group (default = 8)"),
38 cl::init(8));
39
40 /// Return true if all of the intrinsic's arguments and return type are scalars
41 /// for the scalar form of the intrinsic, and vectors for the vector form of the
42 /// intrinsic (except operands that are marked as always being scalar by
43 /// hasVectorInstrinsicScalarOpd).
isTriviallyVectorizable(Intrinsic::ID ID)44 bool llvm::isTriviallyVectorizable(Intrinsic::ID ID) {
45 switch (ID) {
46 case Intrinsic::abs: // Begin integer bit-manipulation.
47 case Intrinsic::bswap:
48 case Intrinsic::bitreverse:
49 case Intrinsic::ctpop:
50 case Intrinsic::ctlz:
51 case Intrinsic::cttz:
52 case Intrinsic::fshl:
53 case Intrinsic::fshr:
54 case Intrinsic::smax:
55 case Intrinsic::smin:
56 case Intrinsic::umax:
57 case Intrinsic::umin:
58 case Intrinsic::sadd_sat:
59 case Intrinsic::ssub_sat:
60 case Intrinsic::uadd_sat:
61 case Intrinsic::usub_sat:
62 case Intrinsic::smul_fix:
63 case Intrinsic::smul_fix_sat:
64 case Intrinsic::umul_fix:
65 case Intrinsic::umul_fix_sat:
66 case Intrinsic::sqrt: // Begin floating-point.
67 case Intrinsic::sin:
68 case Intrinsic::cos:
69 case Intrinsic::exp:
70 case Intrinsic::exp2:
71 case Intrinsic::log:
72 case Intrinsic::log10:
73 case Intrinsic::log2:
74 case Intrinsic::fabs:
75 case Intrinsic::minnum:
76 case Intrinsic::maxnum:
77 case Intrinsic::minimum:
78 case Intrinsic::maximum:
79 case Intrinsic::copysign:
80 case Intrinsic::floor:
81 case Intrinsic::ceil:
82 case Intrinsic::trunc:
83 case Intrinsic::rint:
84 case Intrinsic::nearbyint:
85 case Intrinsic::round:
86 case Intrinsic::roundeven:
87 case Intrinsic::pow:
88 case Intrinsic::fma:
89 case Intrinsic::fmuladd:
90 case Intrinsic::powi:
91 case Intrinsic::canonicalize:
92 return true;
93 default:
94 return false;
95 }
96 }
97
98 /// Identifies if the vector form of the intrinsic has a scalar operand.
hasVectorInstrinsicScalarOpd(Intrinsic::ID ID,unsigned ScalarOpdIdx)99 bool llvm::hasVectorInstrinsicScalarOpd(Intrinsic::ID ID,
100 unsigned ScalarOpdIdx) {
101 switch (ID) {
102 case Intrinsic::abs:
103 case Intrinsic::ctlz:
104 case Intrinsic::cttz:
105 case Intrinsic::powi:
106 return (ScalarOpdIdx == 1);
107 case Intrinsic::smul_fix:
108 case Intrinsic::smul_fix_sat:
109 case Intrinsic::umul_fix:
110 case Intrinsic::umul_fix_sat:
111 return (ScalarOpdIdx == 2);
112 default:
113 return false;
114 }
115 }
116
117 /// Returns intrinsic ID for call.
118 /// For the input call instruction it finds mapping intrinsic and returns
119 /// its ID, in case it does not found it return not_intrinsic.
getVectorIntrinsicIDForCall(const CallInst * CI,const TargetLibraryInfo * TLI)120 Intrinsic::ID llvm::getVectorIntrinsicIDForCall(const CallInst *CI,
121 const TargetLibraryInfo *TLI) {
122 Intrinsic::ID ID = getIntrinsicForCallSite(*CI, TLI);
123 if (ID == Intrinsic::not_intrinsic)
124 return Intrinsic::not_intrinsic;
125
126 if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
127 ID == Intrinsic::lifetime_end || ID == Intrinsic::assume ||
128 ID == Intrinsic::sideeffect || ID == Intrinsic::pseudoprobe)
129 return ID;
130 return Intrinsic::not_intrinsic;
131 }
132
133 /// Find the operand of the GEP that should be checked for consecutive
134 /// stores. This ignores trailing indices that have no effect on the final
135 /// pointer.
getGEPInductionOperand(const GetElementPtrInst * Gep)136 unsigned llvm::getGEPInductionOperand(const GetElementPtrInst *Gep) {
137 const DataLayout &DL = Gep->getModule()->getDataLayout();
138 unsigned LastOperand = Gep->getNumOperands() - 1;
139 TypeSize GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType());
140
141 // Walk backwards and try to peel off zeros.
142 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
143 // Find the type we're currently indexing into.
144 gep_type_iterator GEPTI = gep_type_begin(Gep);
145 std::advance(GEPTI, LastOperand - 2);
146
147 // If it's a type with the same allocation size as the result of the GEP we
148 // can peel off the zero index.
149 if (DL.getTypeAllocSize(GEPTI.getIndexedType()) != GEPAllocSize)
150 break;
151 --LastOperand;
152 }
153
154 return LastOperand;
155 }
156
157 /// If the argument is a GEP, then returns the operand identified by
158 /// getGEPInductionOperand. However, if there is some other non-loop-invariant
159 /// operand, it returns that instead.
stripGetElementPtr(Value * Ptr,ScalarEvolution * SE,Loop * Lp)160 Value *llvm::stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
161 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
162 if (!GEP)
163 return Ptr;
164
165 unsigned InductionOperand = getGEPInductionOperand(GEP);
166
167 // Check that all of the gep indices are uniform except for our induction
168 // operand.
169 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
170 if (i != InductionOperand &&
171 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
172 return Ptr;
173 return GEP->getOperand(InductionOperand);
174 }
175
176 /// If a value has only one user that is a CastInst, return it.
getUniqueCastUse(Value * Ptr,Loop * Lp,Type * Ty)177 Value *llvm::getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
178 Value *UniqueCast = nullptr;
179 for (User *U : Ptr->users()) {
180 CastInst *CI = dyn_cast<CastInst>(U);
181 if (CI && CI->getType() == Ty) {
182 if (!UniqueCast)
183 UniqueCast = CI;
184 else
185 return nullptr;
186 }
187 }
188 return UniqueCast;
189 }
190
191 /// Get the stride of a pointer access in a loop. Looks for symbolic
192 /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
getStrideFromPointer(Value * Ptr,ScalarEvolution * SE,Loop * Lp)193 Value *llvm::getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
194 auto *PtrTy = dyn_cast<PointerType>(Ptr->getType());
195 if (!PtrTy || PtrTy->isAggregateType())
196 return nullptr;
197
198 // Try to remove a gep instruction to make the pointer (actually index at this
199 // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the
200 // pointer, otherwise, we are analyzing the index.
201 Value *OrigPtr = Ptr;
202
203 // The size of the pointer access.
204 int64_t PtrAccessSize = 1;
205
206 Ptr = stripGetElementPtr(Ptr, SE, Lp);
207 const SCEV *V = SE->getSCEV(Ptr);
208
209 if (Ptr != OrigPtr)
210 // Strip off casts.
211 while (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(V))
212 V = C->getOperand();
213
214 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
215 if (!S)
216 return nullptr;
217
218 V = S->getStepRecurrence(*SE);
219 if (!V)
220 return nullptr;
221
222 // Strip off the size of access multiplication if we are still analyzing the
223 // pointer.
224 if (OrigPtr == Ptr) {
225 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
226 if (M->getOperand(0)->getSCEVType() != scConstant)
227 return nullptr;
228
229 const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt();
230
231 // Huge step value - give up.
232 if (APStepVal.getBitWidth() > 64)
233 return nullptr;
234
235 int64_t StepVal = APStepVal.getSExtValue();
236 if (PtrAccessSize != StepVal)
237 return nullptr;
238 V = M->getOperand(1);
239 }
240 }
241
242 // Strip off casts.
243 Type *StripedOffRecurrenceCast = nullptr;
244 if (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(V)) {
245 StripedOffRecurrenceCast = C->getType();
246 V = C->getOperand();
247 }
248
249 // Look for the loop invariant symbolic value.
250 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
251 if (!U)
252 return nullptr;
253
254 Value *Stride = U->getValue();
255 if (!Lp->isLoopInvariant(Stride))
256 return nullptr;
257
258 // If we have stripped off the recurrence cast we have to make sure that we
259 // return the value that is used in this loop so that we can replace it later.
260 if (StripedOffRecurrenceCast)
261 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
262
263 return Stride;
264 }
265
266 /// Given a vector and an element number, see if the scalar value is
267 /// already around as a register, for example if it were inserted then extracted
268 /// from the vector.
findScalarElement(Value * V,unsigned EltNo)269 Value *llvm::findScalarElement(Value *V, unsigned EltNo) {
270 assert(V->getType()->isVectorTy() && "Not looking at a vector?");
271 VectorType *VTy = cast<VectorType>(V->getType());
272 // For fixed-length vector, return undef for out of range access.
273 if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
274 unsigned Width = FVTy->getNumElements();
275 if (EltNo >= Width)
276 return UndefValue::get(FVTy->getElementType());
277 }
278
279 if (Constant *C = dyn_cast<Constant>(V))
280 return C->getAggregateElement(EltNo);
281
282 if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
283 // If this is an insert to a variable element, we don't know what it is.
284 if (!isa<ConstantInt>(III->getOperand(2)))
285 return nullptr;
286 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
287
288 // If this is an insert to the element we are looking for, return the
289 // inserted value.
290 if (EltNo == IIElt)
291 return III->getOperand(1);
292
293 // Guard against infinite loop on malformed, unreachable IR.
294 if (III == III->getOperand(0))
295 return nullptr;
296
297 // Otherwise, the insertelement doesn't modify the value, recurse on its
298 // vector input.
299 return findScalarElement(III->getOperand(0), EltNo);
300 }
301
302 ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V);
303 // Restrict the following transformation to fixed-length vector.
304 if (SVI && isa<FixedVectorType>(SVI->getType())) {
305 unsigned LHSWidth =
306 cast<FixedVectorType>(SVI->getOperand(0)->getType())->getNumElements();
307 int InEl = SVI->getMaskValue(EltNo);
308 if (InEl < 0)
309 return UndefValue::get(VTy->getElementType());
310 if (InEl < (int)LHSWidth)
311 return findScalarElement(SVI->getOperand(0), InEl);
312 return findScalarElement(SVI->getOperand(1), InEl - LHSWidth);
313 }
314
315 // Extract a value from a vector add operation with a constant zero.
316 // TODO: Use getBinOpIdentity() to generalize this.
317 Value *Val; Constant *C;
318 if (match(V, m_Add(m_Value(Val), m_Constant(C))))
319 if (Constant *Elt = C->getAggregateElement(EltNo))
320 if (Elt->isNullValue())
321 return findScalarElement(Val, EltNo);
322
323 // Otherwise, we don't know.
324 return nullptr;
325 }
326
getSplatIndex(ArrayRef<int> Mask)327 int llvm::getSplatIndex(ArrayRef<int> Mask) {
328 int SplatIndex = -1;
329 for (int M : Mask) {
330 // Ignore invalid (undefined) mask elements.
331 if (M < 0)
332 continue;
333
334 // There can be only 1 non-negative mask element value if this is a splat.
335 if (SplatIndex != -1 && SplatIndex != M)
336 return -1;
337
338 // Initialize the splat index to the 1st non-negative mask element.
339 SplatIndex = M;
340 }
341 assert((SplatIndex == -1 || SplatIndex >= 0) && "Negative index?");
342 return SplatIndex;
343 }
344
345 /// Get splat value if the input is a splat vector or return nullptr.
346 /// This function is not fully general. It checks only 2 cases:
347 /// the input value is (1) a splat constant vector or (2) a sequence
348 /// of instructions that broadcasts a scalar at element 0.
getSplatValue(const Value * V)349 Value *llvm::getSplatValue(const Value *V) {
350 if (isa<VectorType>(V->getType()))
351 if (auto *C = dyn_cast<Constant>(V))
352 return C->getSplatValue();
353
354 // shuf (inselt ?, Splat, 0), ?, <0, undef, 0, ...>
355 Value *Splat;
356 if (match(V,
357 m_Shuffle(m_InsertElt(m_Value(), m_Value(Splat), m_ZeroInt()),
358 m_Value(), m_ZeroMask())))
359 return Splat;
360
361 return nullptr;
362 }
363
isSplatValue(const Value * V,int Index,unsigned Depth)364 bool llvm::isSplatValue(const Value *V, int Index, unsigned Depth) {
365 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
366
367 if (isa<VectorType>(V->getType())) {
368 if (isa<UndefValue>(V))
369 return true;
370 // FIXME: We can allow undefs, but if Index was specified, we may want to
371 // check that the constant is defined at that index.
372 if (auto *C = dyn_cast<Constant>(V))
373 return C->getSplatValue() != nullptr;
374 }
375
376 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(V)) {
377 // FIXME: We can safely allow undefs here. If Index was specified, we will
378 // check that the mask elt is defined at the required index.
379 if (!is_splat(Shuf->getShuffleMask()))
380 return false;
381
382 // Match any index.
383 if (Index == -1)
384 return true;
385
386 // Match a specific element. The mask should be defined at and match the
387 // specified index.
388 return Shuf->getMaskValue(Index) == Index;
389 }
390
391 // The remaining tests are all recursive, so bail out if we hit the limit.
392 if (Depth++ == MaxAnalysisRecursionDepth)
393 return false;
394
395 // If both operands of a binop are splats, the result is a splat.
396 Value *X, *Y, *Z;
397 if (match(V, m_BinOp(m_Value(X), m_Value(Y))))
398 return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth);
399
400 // If all operands of a select are splats, the result is a splat.
401 if (match(V, m_Select(m_Value(X), m_Value(Y), m_Value(Z))))
402 return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth) &&
403 isSplatValue(Z, Index, Depth);
404
405 // TODO: Add support for unary ops (fneg), casts, intrinsics (overflow ops).
406
407 return false;
408 }
409
narrowShuffleMaskElts(int Scale,ArrayRef<int> Mask,SmallVectorImpl<int> & ScaledMask)410 void llvm::narrowShuffleMaskElts(int Scale, ArrayRef<int> Mask,
411 SmallVectorImpl<int> &ScaledMask) {
412 assert(Scale > 0 && "Unexpected scaling factor");
413
414 // Fast-path: if no scaling, then it is just a copy.
415 if (Scale == 1) {
416 ScaledMask.assign(Mask.begin(), Mask.end());
417 return;
418 }
419
420 ScaledMask.clear();
421 for (int MaskElt : Mask) {
422 if (MaskElt >= 0) {
423 assert(((uint64_t)Scale * MaskElt + (Scale - 1)) <= INT32_MAX &&
424 "Overflowed 32-bits");
425 }
426 for (int SliceElt = 0; SliceElt != Scale; ++SliceElt)
427 ScaledMask.push_back(MaskElt < 0 ? MaskElt : Scale * MaskElt + SliceElt);
428 }
429 }
430
widenShuffleMaskElts(int Scale,ArrayRef<int> Mask,SmallVectorImpl<int> & ScaledMask)431 bool llvm::widenShuffleMaskElts(int Scale, ArrayRef<int> Mask,
432 SmallVectorImpl<int> &ScaledMask) {
433 assert(Scale > 0 && "Unexpected scaling factor");
434
435 // Fast-path: if no scaling, then it is just a copy.
436 if (Scale == 1) {
437 ScaledMask.assign(Mask.begin(), Mask.end());
438 return true;
439 }
440
441 // We must map the original elements down evenly to a type with less elements.
442 int NumElts = Mask.size();
443 if (NumElts % Scale != 0)
444 return false;
445
446 ScaledMask.clear();
447 ScaledMask.reserve(NumElts / Scale);
448
449 // Step through the input mask by splitting into Scale-sized slices.
450 do {
451 ArrayRef<int> MaskSlice = Mask.take_front(Scale);
452 assert((int)MaskSlice.size() == Scale && "Expected Scale-sized slice.");
453
454 // The first element of the slice determines how we evaluate this slice.
455 int SliceFront = MaskSlice.front();
456 if (SliceFront < 0) {
457 // Negative values (undef or other "sentinel" values) must be equal across
458 // the entire slice.
459 if (!is_splat(MaskSlice))
460 return false;
461 ScaledMask.push_back(SliceFront);
462 } else {
463 // A positive mask element must be cleanly divisible.
464 if (SliceFront % Scale != 0)
465 return false;
466 // Elements of the slice must be consecutive.
467 for (int i = 1; i < Scale; ++i)
468 if (MaskSlice[i] != SliceFront + i)
469 return false;
470 ScaledMask.push_back(SliceFront / Scale);
471 }
472 Mask = Mask.drop_front(Scale);
473 } while (!Mask.empty());
474
475 assert((int)ScaledMask.size() * Scale == NumElts && "Unexpected scaled mask");
476
477 // All elements of the original mask can be scaled down to map to the elements
478 // of a mask with wider elements.
479 return true;
480 }
481
482 MapVector<Instruction *, uint64_t>
computeMinimumValueSizes(ArrayRef<BasicBlock * > Blocks,DemandedBits & DB,const TargetTransformInfo * TTI)483 llvm::computeMinimumValueSizes(ArrayRef<BasicBlock *> Blocks, DemandedBits &DB,
484 const TargetTransformInfo *TTI) {
485
486 // DemandedBits will give us every value's live-out bits. But we want
487 // to ensure no extra casts would need to be inserted, so every DAG
488 // of connected values must have the same minimum bitwidth.
489 EquivalenceClasses<Value *> ECs;
490 SmallVector<Value *, 16> Worklist;
491 SmallPtrSet<Value *, 4> Roots;
492 SmallPtrSet<Value *, 16> Visited;
493 DenseMap<Value *, uint64_t> DBits;
494 SmallPtrSet<Instruction *, 4> InstructionSet;
495 MapVector<Instruction *, uint64_t> MinBWs;
496
497 // Determine the roots. We work bottom-up, from truncs or icmps.
498 bool SeenExtFromIllegalType = false;
499 for (auto *BB : Blocks)
500 for (auto &I : *BB) {
501 InstructionSet.insert(&I);
502
503 if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) &&
504 !TTI->isTypeLegal(I.getOperand(0)->getType()))
505 SeenExtFromIllegalType = true;
506
507 // Only deal with non-vector integers up to 64-bits wide.
508 if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) &&
509 !I.getType()->isVectorTy() &&
510 I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) {
511 // Don't make work for ourselves. If we know the loaded type is legal,
512 // don't add it to the worklist.
513 if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType()))
514 continue;
515
516 Worklist.push_back(&I);
517 Roots.insert(&I);
518 }
519 }
520 // Early exit.
521 if (Worklist.empty() || (TTI && !SeenExtFromIllegalType))
522 return MinBWs;
523
524 // Now proceed breadth-first, unioning values together.
525 while (!Worklist.empty()) {
526 Value *Val = Worklist.pop_back_val();
527 Value *Leader = ECs.getOrInsertLeaderValue(Val);
528
529 if (Visited.count(Val))
530 continue;
531 Visited.insert(Val);
532
533 // Non-instructions terminate a chain successfully.
534 if (!isa<Instruction>(Val))
535 continue;
536 Instruction *I = cast<Instruction>(Val);
537
538 // If we encounter a type that is larger than 64 bits, we can't represent
539 // it so bail out.
540 if (DB.getDemandedBits(I).getBitWidth() > 64)
541 return MapVector<Instruction *, uint64_t>();
542
543 uint64_t V = DB.getDemandedBits(I).getZExtValue();
544 DBits[Leader] |= V;
545 DBits[I] = V;
546
547 // Casts, loads and instructions outside of our range terminate a chain
548 // successfully.
549 if (isa<SExtInst>(I) || isa<ZExtInst>(I) || isa<LoadInst>(I) ||
550 !InstructionSet.count(I))
551 continue;
552
553 // Unsafe casts terminate a chain unsuccessfully. We can't do anything
554 // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to
555 // transform anything that relies on them.
556 if (isa<BitCastInst>(I) || isa<PtrToIntInst>(I) || isa<IntToPtrInst>(I) ||
557 !I->getType()->isIntegerTy()) {
558 DBits[Leader] |= ~0ULL;
559 continue;
560 }
561
562 // We don't modify the types of PHIs. Reductions will already have been
563 // truncated if possible, and inductions' sizes will have been chosen by
564 // indvars.
565 if (isa<PHINode>(I))
566 continue;
567
568 if (DBits[Leader] == ~0ULL)
569 // All bits demanded, no point continuing.
570 continue;
571
572 for (Value *O : cast<User>(I)->operands()) {
573 ECs.unionSets(Leader, O);
574 Worklist.push_back(O);
575 }
576 }
577
578 // Now we've discovered all values, walk them to see if there are
579 // any users we didn't see. If there are, we can't optimize that
580 // chain.
581 for (auto &I : DBits)
582 for (auto *U : I.first->users())
583 if (U->getType()->isIntegerTy() && DBits.count(U) == 0)
584 DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL;
585
586 for (auto I = ECs.begin(), E = ECs.end(); I != E; ++I) {
587 uint64_t LeaderDemandedBits = 0;
588 for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI)
589 LeaderDemandedBits |= DBits[*MI];
590
591 uint64_t MinBW = (sizeof(LeaderDemandedBits) * 8) -
592 llvm::countLeadingZeros(LeaderDemandedBits);
593 // Round up to a power of 2
594 if (!isPowerOf2_64((uint64_t)MinBW))
595 MinBW = NextPowerOf2(MinBW);
596
597 // We don't modify the types of PHIs. Reductions will already have been
598 // truncated if possible, and inductions' sizes will have been chosen by
599 // indvars.
600 // If we are required to shrink a PHI, abandon this entire equivalence class.
601 bool Abort = false;
602 for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI)
603 if (isa<PHINode>(*MI) && MinBW < (*MI)->getType()->getScalarSizeInBits()) {
604 Abort = true;
605 break;
606 }
607 if (Abort)
608 continue;
609
610 for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI) {
611 if (!isa<Instruction>(*MI))
612 continue;
613 Type *Ty = (*MI)->getType();
614 if (Roots.count(*MI))
615 Ty = cast<Instruction>(*MI)->getOperand(0)->getType();
616 if (MinBW < Ty->getScalarSizeInBits())
617 MinBWs[cast<Instruction>(*MI)] = MinBW;
618 }
619 }
620
621 return MinBWs;
622 }
623
624 /// Add all access groups in @p AccGroups to @p List.
625 template <typename ListT>
addToAccessGroupList(ListT & List,MDNode * AccGroups)626 static void addToAccessGroupList(ListT &List, MDNode *AccGroups) {
627 // Interpret an access group as a list containing itself.
628 if (AccGroups->getNumOperands() == 0) {
629 assert(isValidAsAccessGroup(AccGroups) && "Node must be an access group");
630 List.insert(AccGroups);
631 return;
632 }
633
634 for (auto &AccGroupListOp : AccGroups->operands()) {
635 auto *Item = cast<MDNode>(AccGroupListOp.get());
636 assert(isValidAsAccessGroup(Item) && "List item must be an access group");
637 List.insert(Item);
638 }
639 }
640
uniteAccessGroups(MDNode * AccGroups1,MDNode * AccGroups2)641 MDNode *llvm::uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2) {
642 if (!AccGroups1)
643 return AccGroups2;
644 if (!AccGroups2)
645 return AccGroups1;
646 if (AccGroups1 == AccGroups2)
647 return AccGroups1;
648
649 SmallSetVector<Metadata *, 4> Union;
650 addToAccessGroupList(Union, AccGroups1);
651 addToAccessGroupList(Union, AccGroups2);
652
653 if (Union.size() == 0)
654 return nullptr;
655 if (Union.size() == 1)
656 return cast<MDNode>(Union.front());
657
658 LLVMContext &Ctx = AccGroups1->getContext();
659 return MDNode::get(Ctx, Union.getArrayRef());
660 }
661
intersectAccessGroups(const Instruction * Inst1,const Instruction * Inst2)662 MDNode *llvm::intersectAccessGroups(const Instruction *Inst1,
663 const Instruction *Inst2) {
664 bool MayAccessMem1 = Inst1->mayReadOrWriteMemory();
665 bool MayAccessMem2 = Inst2->mayReadOrWriteMemory();
666
667 if (!MayAccessMem1 && !MayAccessMem2)
668 return nullptr;
669 if (!MayAccessMem1)
670 return Inst2->getMetadata(LLVMContext::MD_access_group);
671 if (!MayAccessMem2)
672 return Inst1->getMetadata(LLVMContext::MD_access_group);
673
674 MDNode *MD1 = Inst1->getMetadata(LLVMContext::MD_access_group);
675 MDNode *MD2 = Inst2->getMetadata(LLVMContext::MD_access_group);
676 if (!MD1 || !MD2)
677 return nullptr;
678 if (MD1 == MD2)
679 return MD1;
680
681 // Use set for scalable 'contains' check.
682 SmallPtrSet<Metadata *, 4> AccGroupSet2;
683 addToAccessGroupList(AccGroupSet2, MD2);
684
685 SmallVector<Metadata *, 4> Intersection;
686 if (MD1->getNumOperands() == 0) {
687 assert(isValidAsAccessGroup(MD1) && "Node must be an access group");
688 if (AccGroupSet2.count(MD1))
689 Intersection.push_back(MD1);
690 } else {
691 for (const MDOperand &Node : MD1->operands()) {
692 auto *Item = cast<MDNode>(Node.get());
693 assert(isValidAsAccessGroup(Item) && "List item must be an access group");
694 if (AccGroupSet2.count(Item))
695 Intersection.push_back(Item);
696 }
697 }
698
699 if (Intersection.size() == 0)
700 return nullptr;
701 if (Intersection.size() == 1)
702 return cast<MDNode>(Intersection.front());
703
704 LLVMContext &Ctx = Inst1->getContext();
705 return MDNode::get(Ctx, Intersection);
706 }
707
708 /// \returns \p I after propagating metadata from \p VL.
propagateMetadata(Instruction * Inst,ArrayRef<Value * > VL)709 Instruction *llvm::propagateMetadata(Instruction *Inst, ArrayRef<Value *> VL) {
710 Instruction *I0 = cast<Instruction>(VL[0]);
711 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
712 I0->getAllMetadataOtherThanDebugLoc(Metadata);
713
714 for (auto Kind : {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
715 LLVMContext::MD_noalias, LLVMContext::MD_fpmath,
716 LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load,
717 LLVMContext::MD_access_group}) {
718 MDNode *MD = I0->getMetadata(Kind);
719
720 for (int J = 1, E = VL.size(); MD && J != E; ++J) {
721 const Instruction *IJ = cast<Instruction>(VL[J]);
722 MDNode *IMD = IJ->getMetadata(Kind);
723 switch (Kind) {
724 case LLVMContext::MD_tbaa:
725 MD = MDNode::getMostGenericTBAA(MD, IMD);
726 break;
727 case LLVMContext::MD_alias_scope:
728 MD = MDNode::getMostGenericAliasScope(MD, IMD);
729 break;
730 case LLVMContext::MD_fpmath:
731 MD = MDNode::getMostGenericFPMath(MD, IMD);
732 break;
733 case LLVMContext::MD_noalias:
734 case LLVMContext::MD_nontemporal:
735 case LLVMContext::MD_invariant_load:
736 MD = MDNode::intersect(MD, IMD);
737 break;
738 case LLVMContext::MD_access_group:
739 MD = intersectAccessGroups(Inst, IJ);
740 break;
741 default:
742 llvm_unreachable("unhandled metadata");
743 }
744 }
745
746 Inst->setMetadata(Kind, MD);
747 }
748
749 return Inst;
750 }
751
752 Constant *
createBitMaskForGaps(IRBuilderBase & Builder,unsigned VF,const InterleaveGroup<Instruction> & Group)753 llvm::createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF,
754 const InterleaveGroup<Instruction> &Group) {
755 // All 1's means mask is not needed.
756 if (Group.getNumMembers() == Group.getFactor())
757 return nullptr;
758
759 // TODO: support reversed access.
760 assert(!Group.isReverse() && "Reversed group not supported.");
761
762 SmallVector<Constant *, 16> Mask;
763 for (unsigned i = 0; i < VF; i++)
764 for (unsigned j = 0; j < Group.getFactor(); ++j) {
765 unsigned HasMember = Group.getMember(j) ? 1 : 0;
766 Mask.push_back(Builder.getInt1(HasMember));
767 }
768
769 return ConstantVector::get(Mask);
770 }
771
772 llvm::SmallVector<int, 16>
createReplicatedMask(unsigned ReplicationFactor,unsigned VF)773 llvm::createReplicatedMask(unsigned ReplicationFactor, unsigned VF) {
774 SmallVector<int, 16> MaskVec;
775 for (unsigned i = 0; i < VF; i++)
776 for (unsigned j = 0; j < ReplicationFactor; j++)
777 MaskVec.push_back(i);
778
779 return MaskVec;
780 }
781
createInterleaveMask(unsigned VF,unsigned NumVecs)782 llvm::SmallVector<int, 16> llvm::createInterleaveMask(unsigned VF,
783 unsigned NumVecs) {
784 SmallVector<int, 16> Mask;
785 for (unsigned i = 0; i < VF; i++)
786 for (unsigned j = 0; j < NumVecs; j++)
787 Mask.push_back(j * VF + i);
788
789 return Mask;
790 }
791
792 llvm::SmallVector<int, 16>
createStrideMask(unsigned Start,unsigned Stride,unsigned VF)793 llvm::createStrideMask(unsigned Start, unsigned Stride, unsigned VF) {
794 SmallVector<int, 16> Mask;
795 for (unsigned i = 0; i < VF; i++)
796 Mask.push_back(Start + i * Stride);
797
798 return Mask;
799 }
800
createSequentialMask(unsigned Start,unsigned NumInts,unsigned NumUndefs)801 llvm::SmallVector<int, 16> llvm::createSequentialMask(unsigned Start,
802 unsigned NumInts,
803 unsigned NumUndefs) {
804 SmallVector<int, 16> Mask;
805 for (unsigned i = 0; i < NumInts; i++)
806 Mask.push_back(Start + i);
807
808 for (unsigned i = 0; i < NumUndefs; i++)
809 Mask.push_back(-1);
810
811 return Mask;
812 }
813
814 /// A helper function for concatenating vectors. This function concatenates two
815 /// vectors having the same element type. If the second vector has fewer
816 /// elements than the first, it is padded with undefs.
concatenateTwoVectors(IRBuilderBase & Builder,Value * V1,Value * V2)817 static Value *concatenateTwoVectors(IRBuilderBase &Builder, Value *V1,
818 Value *V2) {
819 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
820 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
821 assert(VecTy1 && VecTy2 &&
822 VecTy1->getScalarType() == VecTy2->getScalarType() &&
823 "Expect two vectors with the same element type");
824
825 unsigned NumElts1 = cast<FixedVectorType>(VecTy1)->getNumElements();
826 unsigned NumElts2 = cast<FixedVectorType>(VecTy2)->getNumElements();
827 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
828
829 if (NumElts1 > NumElts2) {
830 // Extend with UNDEFs.
831 V2 = Builder.CreateShuffleVector(
832 V2, UndefValue::get(VecTy2),
833 createSequentialMask(0, NumElts2, NumElts1 - NumElts2));
834 }
835
836 return Builder.CreateShuffleVector(
837 V1, V2, createSequentialMask(0, NumElts1 + NumElts2, 0));
838 }
839
concatenateVectors(IRBuilderBase & Builder,ArrayRef<Value * > Vecs)840 Value *llvm::concatenateVectors(IRBuilderBase &Builder,
841 ArrayRef<Value *> Vecs) {
842 unsigned NumVecs = Vecs.size();
843 assert(NumVecs > 1 && "Should be at least two vectors");
844
845 SmallVector<Value *, 8> ResList;
846 ResList.append(Vecs.begin(), Vecs.end());
847 do {
848 SmallVector<Value *, 8> TmpList;
849 for (unsigned i = 0; i < NumVecs - 1; i += 2) {
850 Value *V0 = ResList[i], *V1 = ResList[i + 1];
851 assert((V0->getType() == V1->getType() || i == NumVecs - 2) &&
852 "Only the last vector may have a different type");
853
854 TmpList.push_back(concatenateTwoVectors(Builder, V0, V1));
855 }
856
857 // Push the last vector if the total number of vectors is odd.
858 if (NumVecs % 2 != 0)
859 TmpList.push_back(ResList[NumVecs - 1]);
860
861 ResList = TmpList;
862 NumVecs = ResList.size();
863 } while (NumVecs > 1);
864
865 return ResList[0];
866 }
867
maskIsAllZeroOrUndef(Value * Mask)868 bool llvm::maskIsAllZeroOrUndef(Value *Mask) {
869 assert(isa<VectorType>(Mask->getType()) &&
870 isa<IntegerType>(Mask->getType()->getScalarType()) &&
871 cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
872 1 &&
873 "Mask must be a vector of i1");
874
875 auto *ConstMask = dyn_cast<Constant>(Mask);
876 if (!ConstMask)
877 return false;
878 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
879 return true;
880 if (isa<ScalableVectorType>(ConstMask->getType()))
881 return false;
882 for (unsigned
883 I = 0,
884 E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
885 I != E; ++I) {
886 if (auto *MaskElt = ConstMask->getAggregateElement(I))
887 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
888 continue;
889 return false;
890 }
891 return true;
892 }
893
894
maskIsAllOneOrUndef(Value * Mask)895 bool llvm::maskIsAllOneOrUndef(Value *Mask) {
896 assert(isa<VectorType>(Mask->getType()) &&
897 isa<IntegerType>(Mask->getType()->getScalarType()) &&
898 cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
899 1 &&
900 "Mask must be a vector of i1");
901
902 auto *ConstMask = dyn_cast<Constant>(Mask);
903 if (!ConstMask)
904 return false;
905 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
906 return true;
907 if (isa<ScalableVectorType>(ConstMask->getType()))
908 return false;
909 for (unsigned
910 I = 0,
911 E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
912 I != E; ++I) {
913 if (auto *MaskElt = ConstMask->getAggregateElement(I))
914 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
915 continue;
916 return false;
917 }
918 return true;
919 }
920
921 /// TODO: This is a lot like known bits, but for
922 /// vectors. Is there something we can common this with?
possiblyDemandedEltsInMask(Value * Mask)923 APInt llvm::possiblyDemandedEltsInMask(Value *Mask) {
924 assert(isa<FixedVectorType>(Mask->getType()) &&
925 isa<IntegerType>(Mask->getType()->getScalarType()) &&
926 cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
927 1 &&
928 "Mask must be a fixed width vector of i1");
929
930 const unsigned VWidth =
931 cast<FixedVectorType>(Mask->getType())->getNumElements();
932 APInt DemandedElts = APInt::getAllOnesValue(VWidth);
933 if (auto *CV = dyn_cast<ConstantVector>(Mask))
934 for (unsigned i = 0; i < VWidth; i++)
935 if (CV->getAggregateElement(i)->isNullValue())
936 DemandedElts.clearBit(i);
937 return DemandedElts;
938 }
939
isStrided(int Stride)940 bool InterleavedAccessInfo::isStrided(int Stride) {
941 unsigned Factor = std::abs(Stride);
942 return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
943 }
944
collectConstStrideAccesses(MapVector<Instruction *,StrideDescriptor> & AccessStrideInfo,const ValueToValueMap & Strides)945 void InterleavedAccessInfo::collectConstStrideAccesses(
946 MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
947 const ValueToValueMap &Strides) {
948 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
949
950 // Since it's desired that the load/store instructions be maintained in
951 // "program order" for the interleaved access analysis, we have to visit the
952 // blocks in the loop in reverse postorder (i.e., in a topological order).
953 // Such an ordering will ensure that any load/store that may be executed
954 // before a second load/store will precede the second load/store in
955 // AccessStrideInfo.
956 LoopBlocksDFS DFS(TheLoop);
957 DFS.perform(LI);
958 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
959 for (auto &I : *BB) {
960 auto *LI = dyn_cast<LoadInst>(&I);
961 auto *SI = dyn_cast<StoreInst>(&I);
962 if (!LI && !SI)
963 continue;
964
965 Value *Ptr = getLoadStorePointerOperand(&I);
966 // We don't check wrapping here because we don't know yet if Ptr will be
967 // part of a full group or a group with gaps. Checking wrapping for all
968 // pointers (even those that end up in groups with no gaps) will be overly
969 // conservative. For full groups, wrapping should be ok since if we would
970 // wrap around the address space we would do a memory access at nullptr
971 // even without the transformation. The wrapping checks are therefore
972 // deferred until after we've formed the interleaved groups.
973 int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides,
974 /*Assume=*/true, /*ShouldCheckWrap=*/false);
975
976 const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
977 PointerType *PtrTy = cast<PointerType>(Ptr->getType());
978 uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
979 AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size,
980 getLoadStoreAlignment(&I));
981 }
982 }
983
984 // Analyze interleaved accesses and collect them into interleaved load and
985 // store groups.
986 //
987 // When generating code for an interleaved load group, we effectively hoist all
988 // loads in the group to the location of the first load in program order. When
989 // generating code for an interleaved store group, we sink all stores to the
990 // location of the last store. This code motion can change the order of load
991 // and store instructions and may break dependences.
992 //
993 // The code generation strategy mentioned above ensures that we won't violate
994 // any write-after-read (WAR) dependences.
995 //
996 // E.g., for the WAR dependence: a = A[i]; // (1)
997 // A[i] = b; // (2)
998 //
999 // The store group of (2) is always inserted at or below (2), and the load
1000 // group of (1) is always inserted at or above (1). Thus, the instructions will
1001 // never be reordered. All other dependences are checked to ensure the
1002 // correctness of the instruction reordering.
1003 //
1004 // The algorithm visits all memory accesses in the loop in bottom-up program
1005 // order. Program order is established by traversing the blocks in the loop in
1006 // reverse postorder when collecting the accesses.
1007 //
1008 // We visit the memory accesses in bottom-up order because it can simplify the
1009 // construction of store groups in the presence of write-after-write (WAW)
1010 // dependences.
1011 //
1012 // E.g., for the WAW dependence: A[i] = a; // (1)
1013 // A[i] = b; // (2)
1014 // A[i + 1] = c; // (3)
1015 //
1016 // We will first create a store group with (3) and (2). (1) can't be added to
1017 // this group because it and (2) are dependent. However, (1) can be grouped
1018 // with other accesses that may precede it in program order. Note that a
1019 // bottom-up order does not imply that WAW dependences should not be checked.
analyzeInterleaving(bool EnablePredicatedInterleavedMemAccesses)1020 void InterleavedAccessInfo::analyzeInterleaving(
1021 bool EnablePredicatedInterleavedMemAccesses) {
1022 LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
1023 const ValueToValueMap &Strides = LAI->getSymbolicStrides();
1024
1025 // Holds all accesses with a constant stride.
1026 MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
1027 collectConstStrideAccesses(AccessStrideInfo, Strides);
1028
1029 if (AccessStrideInfo.empty())
1030 return;
1031
1032 // Collect the dependences in the loop.
1033 collectDependences();
1034
1035 // Holds all interleaved store groups temporarily.
1036 SmallSetVector<InterleaveGroup<Instruction> *, 4> StoreGroups;
1037 // Holds all interleaved load groups temporarily.
1038 SmallSetVector<InterleaveGroup<Instruction> *, 4> LoadGroups;
1039
1040 // Search in bottom-up program order for pairs of accesses (A and B) that can
1041 // form interleaved load or store groups. In the algorithm below, access A
1042 // precedes access B in program order. We initialize a group for B in the
1043 // outer loop of the algorithm, and then in the inner loop, we attempt to
1044 // insert each A into B's group if:
1045 //
1046 // 1. A and B have the same stride,
1047 // 2. A and B have the same memory object size, and
1048 // 3. A belongs in B's group according to its distance from B.
1049 //
1050 // Special care is taken to ensure group formation will not break any
1051 // dependences.
1052 for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
1053 BI != E; ++BI) {
1054 Instruction *B = BI->first;
1055 StrideDescriptor DesB = BI->second;
1056
1057 // Initialize a group for B if it has an allowable stride. Even if we don't
1058 // create a group for B, we continue with the bottom-up algorithm to ensure
1059 // we don't break any of B's dependences.
1060 InterleaveGroup<Instruction> *Group = nullptr;
1061 if (isStrided(DesB.Stride) &&
1062 (!isPredicated(B->getParent()) || EnablePredicatedInterleavedMemAccesses)) {
1063 Group = getInterleaveGroup(B);
1064 if (!Group) {
1065 LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
1066 << '\n');
1067 Group = createInterleaveGroup(B, DesB.Stride, DesB.Alignment);
1068 }
1069 if (B->mayWriteToMemory())
1070 StoreGroups.insert(Group);
1071 else
1072 LoadGroups.insert(Group);
1073 }
1074
1075 for (auto AI = std::next(BI); AI != E; ++AI) {
1076 Instruction *A = AI->first;
1077 StrideDescriptor DesA = AI->second;
1078
1079 // Our code motion strategy implies that we can't have dependences
1080 // between accesses in an interleaved group and other accesses located
1081 // between the first and last member of the group. Note that this also
1082 // means that a group can't have more than one member at a given offset.
1083 // The accesses in a group can have dependences with other accesses, but
1084 // we must ensure we don't extend the boundaries of the group such that
1085 // we encompass those dependent accesses.
1086 //
1087 // For example, assume we have the sequence of accesses shown below in a
1088 // stride-2 loop:
1089 //
1090 // (1, 2) is a group | A[i] = a; // (1)
1091 // | A[i-1] = b; // (2) |
1092 // A[i-3] = c; // (3)
1093 // A[i] = d; // (4) | (2, 4) is not a group
1094 //
1095 // Because accesses (2) and (3) are dependent, we can group (2) with (1)
1096 // but not with (4). If we did, the dependent access (3) would be within
1097 // the boundaries of the (2, 4) group.
1098 if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
1099 // If a dependence exists and A is already in a group, we know that A
1100 // must be a store since A precedes B and WAR dependences are allowed.
1101 // Thus, A would be sunk below B. We release A's group to prevent this
1102 // illegal code motion. A will then be free to form another group with
1103 // instructions that precede it.
1104 if (isInterleaved(A)) {
1105 InterleaveGroup<Instruction> *StoreGroup = getInterleaveGroup(A);
1106
1107 LLVM_DEBUG(dbgs() << "LV: Invalidated store group due to "
1108 "dependence between " << *A << " and "<< *B << '\n');
1109
1110 StoreGroups.remove(StoreGroup);
1111 releaseGroup(StoreGroup);
1112 }
1113
1114 // If a dependence exists and A is not already in a group (or it was
1115 // and we just released it), B might be hoisted above A (if B is a
1116 // load) or another store might be sunk below A (if B is a store). In
1117 // either case, we can't add additional instructions to B's group. B
1118 // will only form a group with instructions that it precedes.
1119 break;
1120 }
1121
1122 // At this point, we've checked for illegal code motion. If either A or B
1123 // isn't strided, there's nothing left to do.
1124 if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
1125 continue;
1126
1127 // Ignore A if it's already in a group or isn't the same kind of memory
1128 // operation as B.
1129 // Note that mayReadFromMemory() isn't mutually exclusive to
1130 // mayWriteToMemory in the case of atomic loads. We shouldn't see those
1131 // here, canVectorizeMemory() should have returned false - except for the
1132 // case we asked for optimization remarks.
1133 if (isInterleaved(A) ||
1134 (A->mayReadFromMemory() != B->mayReadFromMemory()) ||
1135 (A->mayWriteToMemory() != B->mayWriteToMemory()))
1136 continue;
1137
1138 // Check rules 1 and 2. Ignore A if its stride or size is different from
1139 // that of B.
1140 if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
1141 continue;
1142
1143 // Ignore A if the memory object of A and B don't belong to the same
1144 // address space
1145 if (getLoadStoreAddressSpace(A) != getLoadStoreAddressSpace(B))
1146 continue;
1147
1148 // Calculate the distance from A to B.
1149 const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
1150 PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
1151 if (!DistToB)
1152 continue;
1153 int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
1154
1155 // Check rule 3. Ignore A if its distance to B is not a multiple of the
1156 // size.
1157 if (DistanceToB % static_cast<int64_t>(DesB.Size))
1158 continue;
1159
1160 // All members of a predicated interleave-group must have the same predicate,
1161 // and currently must reside in the same BB.
1162 BasicBlock *BlockA = A->getParent();
1163 BasicBlock *BlockB = B->getParent();
1164 if ((isPredicated(BlockA) || isPredicated(BlockB)) &&
1165 (!EnablePredicatedInterleavedMemAccesses || BlockA != BlockB))
1166 continue;
1167
1168 // The index of A is the index of B plus A's distance to B in multiples
1169 // of the size.
1170 int IndexA =
1171 Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
1172
1173 // Try to insert A into B's group.
1174 if (Group->insertMember(A, IndexA, DesA.Alignment)) {
1175 LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
1176 << " into the interleave group with" << *B
1177 << '\n');
1178 InterleaveGroupMap[A] = Group;
1179
1180 // Set the first load in program order as the insert position.
1181 if (A->mayReadFromMemory())
1182 Group->setInsertPos(A);
1183 }
1184 } // Iteration over A accesses.
1185 } // Iteration over B accesses.
1186
1187 // Remove interleaved store groups with gaps.
1188 for (auto *Group : StoreGroups)
1189 if (Group->getNumMembers() != Group->getFactor()) {
1190 LLVM_DEBUG(
1191 dbgs() << "LV: Invalidate candidate interleaved store group due "
1192 "to gaps.\n");
1193 releaseGroup(Group);
1194 }
1195 // Remove interleaved groups with gaps (currently only loads) whose memory
1196 // accesses may wrap around. We have to revisit the getPtrStride analysis,
1197 // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
1198 // not check wrapping (see documentation there).
1199 // FORNOW we use Assume=false;
1200 // TODO: Change to Assume=true but making sure we don't exceed the threshold
1201 // of runtime SCEV assumptions checks (thereby potentially failing to
1202 // vectorize altogether).
1203 // Additional optional optimizations:
1204 // TODO: If we are peeling the loop and we know that the first pointer doesn't
1205 // wrap then we can deduce that all pointers in the group don't wrap.
1206 // This means that we can forcefully peel the loop in order to only have to
1207 // check the first pointer for no-wrap. When we'll change to use Assume=true
1208 // we'll only need at most one runtime check per interleaved group.
1209 for (auto *Group : LoadGroups) {
1210 // Case 1: A full group. Can Skip the checks; For full groups, if the wide
1211 // load would wrap around the address space we would do a memory access at
1212 // nullptr even without the transformation.
1213 if (Group->getNumMembers() == Group->getFactor())
1214 continue;
1215
1216 // Case 2: If first and last members of the group don't wrap this implies
1217 // that all the pointers in the group don't wrap.
1218 // So we check only group member 0 (which is always guaranteed to exist),
1219 // and group member Factor - 1; If the latter doesn't exist we rely on
1220 // peeling (if it is a non-reversed accsess -- see Case 3).
1221 Value *FirstMemberPtr = getLoadStorePointerOperand(Group->getMember(0));
1222 if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false,
1223 /*ShouldCheckWrap=*/true)) {
1224 LLVM_DEBUG(
1225 dbgs() << "LV: Invalidate candidate interleaved group due to "
1226 "first group member potentially pointer-wrapping.\n");
1227 releaseGroup(Group);
1228 continue;
1229 }
1230 Instruction *LastMember = Group->getMember(Group->getFactor() - 1);
1231 if (LastMember) {
1232 Value *LastMemberPtr = getLoadStorePointerOperand(LastMember);
1233 if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false,
1234 /*ShouldCheckWrap=*/true)) {
1235 LLVM_DEBUG(
1236 dbgs() << "LV: Invalidate candidate interleaved group due to "
1237 "last group member potentially pointer-wrapping.\n");
1238 releaseGroup(Group);
1239 }
1240 } else {
1241 // Case 3: A non-reversed interleaved load group with gaps: We need
1242 // to execute at least one scalar epilogue iteration. This will ensure
1243 // we don't speculatively access memory out-of-bounds. We only need
1244 // to look for a member at index factor - 1, since every group must have
1245 // a member at index zero.
1246 if (Group->isReverse()) {
1247 LLVM_DEBUG(
1248 dbgs() << "LV: Invalidate candidate interleaved group due to "
1249 "a reverse access with gaps.\n");
1250 releaseGroup(Group);
1251 continue;
1252 }
1253 LLVM_DEBUG(
1254 dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
1255 RequiresScalarEpilogue = true;
1256 }
1257 }
1258 }
1259
invalidateGroupsRequiringScalarEpilogue()1260 void InterleavedAccessInfo::invalidateGroupsRequiringScalarEpilogue() {
1261 // If no group had triggered the requirement to create an epilogue loop,
1262 // there is nothing to do.
1263 if (!requiresScalarEpilogue())
1264 return;
1265
1266 bool ReleasedGroup = false;
1267 // Release groups requiring scalar epilogues. Note that this also removes them
1268 // from InterleaveGroups.
1269 for (auto *Group : make_early_inc_range(InterleaveGroups)) {
1270 if (!Group->requiresScalarEpilogue())
1271 continue;
1272 LLVM_DEBUG(
1273 dbgs()
1274 << "LV: Invalidate candidate interleaved group due to gaps that "
1275 "require a scalar epilogue (not allowed under optsize) and cannot "
1276 "be masked (not enabled). \n");
1277 releaseGroup(Group);
1278 ReleasedGroup = true;
1279 }
1280 assert(ReleasedGroup && "At least one group must be invalidated, as a "
1281 "scalar epilogue was required");
1282 (void)ReleasedGroup;
1283 RequiresScalarEpilogue = false;
1284 }
1285
1286 template <typename InstT>
addMetadata(InstT * NewInst) const1287 void InterleaveGroup<InstT>::addMetadata(InstT *NewInst) const {
1288 llvm_unreachable("addMetadata can only be used for Instruction");
1289 }
1290
1291 namespace llvm {
1292 template <>
addMetadata(Instruction * NewInst) const1293 void InterleaveGroup<Instruction>::addMetadata(Instruction *NewInst) const {
1294 SmallVector<Value *, 4> VL;
1295 std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
1296 [](std::pair<int, Instruction *> p) { return p.second; });
1297 propagateMetadata(NewInst, VL);
1298 }
1299 }
1300
mangleTLIVectorName(StringRef VectorName,StringRef ScalarName,unsigned numArgs,unsigned VF)1301 std::string VFABI::mangleTLIVectorName(StringRef VectorName,
1302 StringRef ScalarName, unsigned numArgs,
1303 unsigned VF) {
1304 SmallString<256> Buffer;
1305 llvm::raw_svector_ostream Out(Buffer);
1306 Out << "_ZGV" << VFABI::_LLVM_ << "N" << VF;
1307 for (unsigned I = 0; I < numArgs; ++I)
1308 Out << "v";
1309 Out << "_" << ScalarName << "(" << VectorName << ")";
1310 return std::string(Out.str());
1311 }
1312
getVectorVariantNames(const CallInst & CI,SmallVectorImpl<std::string> & VariantMappings)1313 void VFABI::getVectorVariantNames(
1314 const CallInst &CI, SmallVectorImpl<std::string> &VariantMappings) {
1315 const StringRef S =
1316 CI.getAttribute(AttributeList::FunctionIndex, VFABI::MappingsAttrName)
1317 .getValueAsString();
1318 if (S.empty())
1319 return;
1320
1321 SmallVector<StringRef, 8> ListAttr;
1322 S.split(ListAttr, ",");
1323
1324 for (auto &S : SetVector<StringRef>(ListAttr.begin(), ListAttr.end())) {
1325 #ifndef NDEBUG
1326 LLVM_DEBUG(dbgs() << "VFABI: adding mapping '" << S << "'\n");
1327 Optional<VFInfo> Info = VFABI::tryDemangleForVFABI(S, *(CI.getModule()));
1328 assert(Info.hasValue() && "Invalid name for a VFABI variant.");
1329 assert(CI.getModule()->getFunction(Info.getValue().VectorName) &&
1330 "Vector function is missing.");
1331 #endif
1332 VariantMappings.push_back(std::string(S));
1333 }
1334 }
1335
hasValidParameterList() const1336 bool VFShape::hasValidParameterList() const {
1337 for (unsigned Pos = 0, NumParams = Parameters.size(); Pos < NumParams;
1338 ++Pos) {
1339 assert(Parameters[Pos].ParamPos == Pos && "Broken parameter list.");
1340
1341 switch (Parameters[Pos].ParamKind) {
1342 default: // Nothing to check.
1343 break;
1344 case VFParamKind::OMP_Linear:
1345 case VFParamKind::OMP_LinearRef:
1346 case VFParamKind::OMP_LinearVal:
1347 case VFParamKind::OMP_LinearUVal:
1348 // Compile time linear steps must be non-zero.
1349 if (Parameters[Pos].LinearStepOrPos == 0)
1350 return false;
1351 break;
1352 case VFParamKind::OMP_LinearPos:
1353 case VFParamKind::OMP_LinearRefPos:
1354 case VFParamKind::OMP_LinearValPos:
1355 case VFParamKind::OMP_LinearUValPos:
1356 // The runtime linear step must be referring to some other
1357 // parameters in the signature.
1358 if (Parameters[Pos].LinearStepOrPos >= int(NumParams))
1359 return false;
1360 // The linear step parameter must be marked as uniform.
1361 if (Parameters[Parameters[Pos].LinearStepOrPos].ParamKind !=
1362 VFParamKind::OMP_Uniform)
1363 return false;
1364 // The linear step parameter can't point at itself.
1365 if (Parameters[Pos].LinearStepOrPos == int(Pos))
1366 return false;
1367 break;
1368 case VFParamKind::GlobalPredicate:
1369 // The global predicate must be the unique. Can be placed anywhere in the
1370 // signature.
1371 for (unsigned NextPos = Pos + 1; NextPos < NumParams; ++NextPos)
1372 if (Parameters[NextPos].ParamKind == VFParamKind::GlobalPredicate)
1373 return false;
1374 break;
1375 }
1376 }
1377 return true;
1378 }
1379