1 //===----------- VectorUtils.cpp - Vectorizer utility functions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines vectorizer utilities.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/VectorUtils.h"
15 #include "llvm/ADT/EquivalenceClasses.h"
16 #include "llvm/Analysis/DemandedBits.h"
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/Analysis/LoopIterator.h"
19 #include "llvm/Analysis/ScalarEvolution.h"
20 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/GetElementPtrTypeIterator.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/IR/Value.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 /// Identify if the intrinsic is trivially vectorizable.
41 /// This method returns true if the intrinsic's argument types are all
42 /// scalars for the scalar form of the intrinsic and all vectors for
43 /// the vector form of the intrinsic.
44 bool llvm::isTriviallyVectorizable(Intrinsic::ID ID) {
45   switch (ID) {
46   case Intrinsic::sqrt:
47   case Intrinsic::sin:
48   case Intrinsic::cos:
49   case Intrinsic::exp:
50   case Intrinsic::exp2:
51   case Intrinsic::log:
52   case Intrinsic::log10:
53   case Intrinsic::log2:
54   case Intrinsic::fabs:
55   case Intrinsic::minnum:
56   case Intrinsic::maxnum:
57   case Intrinsic::copysign:
58   case Intrinsic::floor:
59   case Intrinsic::ceil:
60   case Intrinsic::trunc:
61   case Intrinsic::rint:
62   case Intrinsic::nearbyint:
63   case Intrinsic::round:
64   case Intrinsic::bswap:
65   case Intrinsic::bitreverse:
66   case Intrinsic::ctpop:
67   case Intrinsic::pow:
68   case Intrinsic::fma:
69   case Intrinsic::fmuladd:
70   case Intrinsic::ctlz:
71   case Intrinsic::cttz:
72   case Intrinsic::powi:
73   case Intrinsic::canonicalize:
74     return true;
75   default:
76     return false;
77   }
78 }
79 
80 /// Identifies if the intrinsic has a scalar operand. It check for
81 /// ctlz,cttz and powi special intrinsics whose argument is scalar.
82 bool llvm::hasVectorInstrinsicScalarOpd(Intrinsic::ID ID,
83                                         unsigned ScalarOpdIdx) {
84   switch (ID) {
85   case Intrinsic::ctlz:
86   case Intrinsic::cttz:
87   case Intrinsic::powi:
88     return (ScalarOpdIdx == 1);
89   default:
90     return false;
91   }
92 }
93 
94 /// Returns intrinsic ID for call.
95 /// For the input call instruction it finds mapping intrinsic and returns
96 /// its ID, in case it does not found it return not_intrinsic.
97 Intrinsic::ID llvm::getVectorIntrinsicIDForCall(const CallInst *CI,
98                                                 const TargetLibraryInfo *TLI) {
99   Intrinsic::ID ID = getIntrinsicForCallSite(CI, TLI);
100   if (ID == Intrinsic::not_intrinsic)
101     return Intrinsic::not_intrinsic;
102 
103   if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
104       ID == Intrinsic::lifetime_end || ID == Intrinsic::assume ||
105       ID == Intrinsic::sideeffect)
106     return ID;
107   return Intrinsic::not_intrinsic;
108 }
109 
110 /// Find the operand of the GEP that should be checked for consecutive
111 /// stores. This ignores trailing indices that have no effect on the final
112 /// pointer.
113 unsigned llvm::getGEPInductionOperand(const GetElementPtrInst *Gep) {
114   const DataLayout &DL = Gep->getModule()->getDataLayout();
115   unsigned LastOperand = Gep->getNumOperands() - 1;
116   unsigned GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType());
117 
118   // Walk backwards and try to peel off zeros.
119   while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
120     // Find the type we're currently indexing into.
121     gep_type_iterator GEPTI = gep_type_begin(Gep);
122     std::advance(GEPTI, LastOperand - 2);
123 
124     // If it's a type with the same allocation size as the result of the GEP we
125     // can peel off the zero index.
126     if (DL.getTypeAllocSize(GEPTI.getIndexedType()) != GEPAllocSize)
127       break;
128     --LastOperand;
129   }
130 
131   return LastOperand;
132 }
133 
134 /// If the argument is a GEP, then returns the operand identified by
135 /// getGEPInductionOperand. However, if there is some other non-loop-invariant
136 /// operand, it returns that instead.
137 Value *llvm::stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
138   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
139   if (!GEP)
140     return Ptr;
141 
142   unsigned InductionOperand = getGEPInductionOperand(GEP);
143 
144   // Check that all of the gep indices are uniform except for our induction
145   // operand.
146   for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
147     if (i != InductionOperand &&
148         !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
149       return Ptr;
150   return GEP->getOperand(InductionOperand);
151 }
152 
153 /// If a value has only one user that is a CastInst, return it.
154 Value *llvm::getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
155   Value *UniqueCast = nullptr;
156   for (User *U : Ptr->users()) {
157     CastInst *CI = dyn_cast<CastInst>(U);
158     if (CI && CI->getType() == Ty) {
159       if (!UniqueCast)
160         UniqueCast = CI;
161       else
162         return nullptr;
163     }
164   }
165   return UniqueCast;
166 }
167 
168 /// Get the stride of a pointer access in a loop. Looks for symbolic
169 /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
170 Value *llvm::getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
171   auto *PtrTy = dyn_cast<PointerType>(Ptr->getType());
172   if (!PtrTy || PtrTy->isAggregateType())
173     return nullptr;
174 
175   // Try to remove a gep instruction to make the pointer (actually index at this
176   // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the
177   // pointer, otherwise, we are analyzing the index.
178   Value *OrigPtr = Ptr;
179 
180   // The size of the pointer access.
181   int64_t PtrAccessSize = 1;
182 
183   Ptr = stripGetElementPtr(Ptr, SE, Lp);
184   const SCEV *V = SE->getSCEV(Ptr);
185 
186   if (Ptr != OrigPtr)
187     // Strip off casts.
188     while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
189       V = C->getOperand();
190 
191   const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
192   if (!S)
193     return nullptr;
194 
195   V = S->getStepRecurrence(*SE);
196   if (!V)
197     return nullptr;
198 
199   // Strip off the size of access multiplication if we are still analyzing the
200   // pointer.
201   if (OrigPtr == Ptr) {
202     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
203       if (M->getOperand(0)->getSCEVType() != scConstant)
204         return nullptr;
205 
206       const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt();
207 
208       // Huge step value - give up.
209       if (APStepVal.getBitWidth() > 64)
210         return nullptr;
211 
212       int64_t StepVal = APStepVal.getSExtValue();
213       if (PtrAccessSize != StepVal)
214         return nullptr;
215       V = M->getOperand(1);
216     }
217   }
218 
219   // Strip off casts.
220   Type *StripedOffRecurrenceCast = nullptr;
221   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
222     StripedOffRecurrenceCast = C->getType();
223     V = C->getOperand();
224   }
225 
226   // Look for the loop invariant symbolic value.
227   const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
228   if (!U)
229     return nullptr;
230 
231   Value *Stride = U->getValue();
232   if (!Lp->isLoopInvariant(Stride))
233     return nullptr;
234 
235   // If we have stripped off the recurrence cast we have to make sure that we
236   // return the value that is used in this loop so that we can replace it later.
237   if (StripedOffRecurrenceCast)
238     Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
239 
240   return Stride;
241 }
242 
243 /// Given a vector and an element number, see if the scalar value is
244 /// already around as a register, for example if it were inserted then extracted
245 /// from the vector.
246 Value *llvm::findScalarElement(Value *V, unsigned EltNo) {
247   assert(V->getType()->isVectorTy() && "Not looking at a vector?");
248   VectorType *VTy = cast<VectorType>(V->getType());
249   unsigned Width = VTy->getNumElements();
250   if (EltNo >= Width)  // Out of range access.
251     return UndefValue::get(VTy->getElementType());
252 
253   if (Constant *C = dyn_cast<Constant>(V))
254     return C->getAggregateElement(EltNo);
255 
256   if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
257     // If this is an insert to a variable element, we don't know what it is.
258     if (!isa<ConstantInt>(III->getOperand(2)))
259       return nullptr;
260     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
261 
262     // If this is an insert to the element we are looking for, return the
263     // inserted value.
264     if (EltNo == IIElt)
265       return III->getOperand(1);
266 
267     // Otherwise, the insertelement doesn't modify the value, recurse on its
268     // vector input.
269     return findScalarElement(III->getOperand(0), EltNo);
270   }
271 
272   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
273     unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements();
274     int InEl = SVI->getMaskValue(EltNo);
275     if (InEl < 0)
276       return UndefValue::get(VTy->getElementType());
277     if (InEl < (int)LHSWidth)
278       return findScalarElement(SVI->getOperand(0), InEl);
279     return findScalarElement(SVI->getOperand(1), InEl - LHSWidth);
280   }
281 
282   // Extract a value from a vector add operation with a constant zero.
283   Value *Val = nullptr; Constant *Con = nullptr;
284   if (match(V, m_Add(m_Value(Val), m_Constant(Con))))
285     if (Constant *Elt = Con->getAggregateElement(EltNo))
286       if (Elt->isNullValue())
287         return findScalarElement(Val, EltNo);
288 
289   // Otherwise, we don't know.
290   return nullptr;
291 }
292 
293 /// Get splat value if the input is a splat vector or return nullptr.
294 /// This function is not fully general. It checks only 2 cases:
295 /// the input value is (1) a splat constants vector or (2) a sequence
296 /// of instructions that broadcast a single value into a vector.
297 ///
298 const llvm::Value *llvm::getSplatValue(const Value *V) {
299 
300   if (auto *C = dyn_cast<Constant>(V))
301     if (isa<VectorType>(V->getType()))
302       return C->getSplatValue();
303 
304   auto *ShuffleInst = dyn_cast<ShuffleVectorInst>(V);
305   if (!ShuffleInst)
306     return nullptr;
307   // All-zero (or undef) shuffle mask elements.
308   for (int MaskElt : ShuffleInst->getShuffleMask())
309     if (MaskElt != 0 && MaskElt != -1)
310       return nullptr;
311   // The first shuffle source is 'insertelement' with index 0.
312   auto *InsertEltInst =
313     dyn_cast<InsertElementInst>(ShuffleInst->getOperand(0));
314   if (!InsertEltInst || !isa<ConstantInt>(InsertEltInst->getOperand(2)) ||
315       !cast<ConstantInt>(InsertEltInst->getOperand(2))->isZero())
316     return nullptr;
317 
318   return InsertEltInst->getOperand(1);
319 }
320 
321 MapVector<Instruction *, uint64_t>
322 llvm::computeMinimumValueSizes(ArrayRef<BasicBlock *> Blocks, DemandedBits &DB,
323                                const TargetTransformInfo *TTI) {
324 
325   // DemandedBits will give us every value's live-out bits. But we want
326   // to ensure no extra casts would need to be inserted, so every DAG
327   // of connected values must have the same minimum bitwidth.
328   EquivalenceClasses<Value *> ECs;
329   SmallVector<Value *, 16> Worklist;
330   SmallPtrSet<Value *, 4> Roots;
331   SmallPtrSet<Value *, 16> Visited;
332   DenseMap<Value *, uint64_t> DBits;
333   SmallPtrSet<Instruction *, 4> InstructionSet;
334   MapVector<Instruction *, uint64_t> MinBWs;
335 
336   // Determine the roots. We work bottom-up, from truncs or icmps.
337   bool SeenExtFromIllegalType = false;
338   for (auto *BB : Blocks)
339     for (auto &I : *BB) {
340       InstructionSet.insert(&I);
341 
342       if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) &&
343           !TTI->isTypeLegal(I.getOperand(0)->getType()))
344         SeenExtFromIllegalType = true;
345 
346       // Only deal with non-vector integers up to 64-bits wide.
347       if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) &&
348           !I.getType()->isVectorTy() &&
349           I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) {
350         // Don't make work for ourselves. If we know the loaded type is legal,
351         // don't add it to the worklist.
352         if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType()))
353           continue;
354 
355         Worklist.push_back(&I);
356         Roots.insert(&I);
357       }
358     }
359   // Early exit.
360   if (Worklist.empty() || (TTI && !SeenExtFromIllegalType))
361     return MinBWs;
362 
363   // Now proceed breadth-first, unioning values together.
364   while (!Worklist.empty()) {
365     Value *Val = Worklist.pop_back_val();
366     Value *Leader = ECs.getOrInsertLeaderValue(Val);
367 
368     if (Visited.count(Val))
369       continue;
370     Visited.insert(Val);
371 
372     // Non-instructions terminate a chain successfully.
373     if (!isa<Instruction>(Val))
374       continue;
375     Instruction *I = cast<Instruction>(Val);
376 
377     // If we encounter a type that is larger than 64 bits, we can't represent
378     // it so bail out.
379     if (DB.getDemandedBits(I).getBitWidth() > 64)
380       return MapVector<Instruction *, uint64_t>();
381 
382     uint64_t V = DB.getDemandedBits(I).getZExtValue();
383     DBits[Leader] |= V;
384     DBits[I] = V;
385 
386     // Casts, loads and instructions outside of our range terminate a chain
387     // successfully.
388     if (isa<SExtInst>(I) || isa<ZExtInst>(I) || isa<LoadInst>(I) ||
389         !InstructionSet.count(I))
390       continue;
391 
392     // Unsafe casts terminate a chain unsuccessfully. We can't do anything
393     // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to
394     // transform anything that relies on them.
395     if (isa<BitCastInst>(I) || isa<PtrToIntInst>(I) || isa<IntToPtrInst>(I) ||
396         !I->getType()->isIntegerTy()) {
397       DBits[Leader] |= ~0ULL;
398       continue;
399     }
400 
401     // We don't modify the types of PHIs. Reductions will already have been
402     // truncated if possible, and inductions' sizes will have been chosen by
403     // indvars.
404     if (isa<PHINode>(I))
405       continue;
406 
407     if (DBits[Leader] == ~0ULL)
408       // All bits demanded, no point continuing.
409       continue;
410 
411     for (Value *O : cast<User>(I)->operands()) {
412       ECs.unionSets(Leader, O);
413       Worklist.push_back(O);
414     }
415   }
416 
417   // Now we've discovered all values, walk them to see if there are
418   // any users we didn't see. If there are, we can't optimize that
419   // chain.
420   for (auto &I : DBits)
421     for (auto *U : I.first->users())
422       if (U->getType()->isIntegerTy() && DBits.count(U) == 0)
423         DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL;
424 
425   for (auto I = ECs.begin(), E = ECs.end(); I != E; ++I) {
426     uint64_t LeaderDemandedBits = 0;
427     for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI)
428       LeaderDemandedBits |= DBits[*MI];
429 
430     uint64_t MinBW = (sizeof(LeaderDemandedBits) * 8) -
431                      llvm::countLeadingZeros(LeaderDemandedBits);
432     // Round up to a power of 2
433     if (!isPowerOf2_64((uint64_t)MinBW))
434       MinBW = NextPowerOf2(MinBW);
435 
436     // We don't modify the types of PHIs. Reductions will already have been
437     // truncated if possible, and inductions' sizes will have been chosen by
438     // indvars.
439     // If we are required to shrink a PHI, abandon this entire equivalence class.
440     bool Abort = false;
441     for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI)
442       if (isa<PHINode>(*MI) && MinBW < (*MI)->getType()->getScalarSizeInBits()) {
443         Abort = true;
444         break;
445       }
446     if (Abort)
447       continue;
448 
449     for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI) {
450       if (!isa<Instruction>(*MI))
451         continue;
452       Type *Ty = (*MI)->getType();
453       if (Roots.count(*MI))
454         Ty = cast<Instruction>(*MI)->getOperand(0)->getType();
455       if (MinBW < Ty->getScalarSizeInBits())
456         MinBWs[cast<Instruction>(*MI)] = MinBW;
457     }
458   }
459 
460   return MinBWs;
461 }
462 
463 /// \returns \p I after propagating metadata from \p VL.
464 Instruction *llvm::propagateMetadata(Instruction *Inst, ArrayRef<Value *> VL) {
465   Instruction *I0 = cast<Instruction>(VL[0]);
466   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
467   I0->getAllMetadataOtherThanDebugLoc(Metadata);
468 
469   for (auto Kind :
470        {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
471         LLVMContext::MD_noalias, LLVMContext::MD_fpmath,
472         LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load}) {
473     MDNode *MD = I0->getMetadata(Kind);
474 
475     for (int J = 1, E = VL.size(); MD && J != E; ++J) {
476       const Instruction *IJ = cast<Instruction>(VL[J]);
477       MDNode *IMD = IJ->getMetadata(Kind);
478       switch (Kind) {
479       case LLVMContext::MD_tbaa:
480         MD = MDNode::getMostGenericTBAA(MD, IMD);
481         break;
482       case LLVMContext::MD_alias_scope:
483         MD = MDNode::getMostGenericAliasScope(MD, IMD);
484         break;
485       case LLVMContext::MD_fpmath:
486         MD = MDNode::getMostGenericFPMath(MD, IMD);
487         break;
488       case LLVMContext::MD_noalias:
489       case LLVMContext::MD_nontemporal:
490       case LLVMContext::MD_invariant_load:
491         MD = MDNode::intersect(MD, IMD);
492         break;
493       default:
494         llvm_unreachable("unhandled metadata");
495       }
496     }
497 
498     Inst->setMetadata(Kind, MD);
499   }
500 
501   return Inst;
502 }
503 
504 Constant *llvm::createInterleaveMask(IRBuilder<> &Builder, unsigned VF,
505                                      unsigned NumVecs) {
506   SmallVector<Constant *, 16> Mask;
507   for (unsigned i = 0; i < VF; i++)
508     for (unsigned j = 0; j < NumVecs; j++)
509       Mask.push_back(Builder.getInt32(j * VF + i));
510 
511   return ConstantVector::get(Mask);
512 }
513 
514 Constant *llvm::createStrideMask(IRBuilder<> &Builder, unsigned Start,
515                                  unsigned Stride, unsigned VF) {
516   SmallVector<Constant *, 16> Mask;
517   for (unsigned i = 0; i < VF; i++)
518     Mask.push_back(Builder.getInt32(Start + i * Stride));
519 
520   return ConstantVector::get(Mask);
521 }
522 
523 Constant *llvm::createSequentialMask(IRBuilder<> &Builder, unsigned Start,
524                                      unsigned NumInts, unsigned NumUndefs) {
525   SmallVector<Constant *, 16> Mask;
526   for (unsigned i = 0; i < NumInts; i++)
527     Mask.push_back(Builder.getInt32(Start + i));
528 
529   Constant *Undef = UndefValue::get(Builder.getInt32Ty());
530   for (unsigned i = 0; i < NumUndefs; i++)
531     Mask.push_back(Undef);
532 
533   return ConstantVector::get(Mask);
534 }
535 
536 /// A helper function for concatenating vectors. This function concatenates two
537 /// vectors having the same element type. If the second vector has fewer
538 /// elements than the first, it is padded with undefs.
539 static Value *concatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
540                                     Value *V2) {
541   VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
542   VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
543   assert(VecTy1 && VecTy2 &&
544          VecTy1->getScalarType() == VecTy2->getScalarType() &&
545          "Expect two vectors with the same element type");
546 
547   unsigned NumElts1 = VecTy1->getNumElements();
548   unsigned NumElts2 = VecTy2->getNumElements();
549   assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
550 
551   if (NumElts1 > NumElts2) {
552     // Extend with UNDEFs.
553     Constant *ExtMask =
554         createSequentialMask(Builder, 0, NumElts2, NumElts1 - NumElts2);
555     V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
556   }
557 
558   Constant *Mask = createSequentialMask(Builder, 0, NumElts1 + NumElts2, 0);
559   return Builder.CreateShuffleVector(V1, V2, Mask);
560 }
561 
562 Value *llvm::concatenateVectors(IRBuilder<> &Builder, ArrayRef<Value *> Vecs) {
563   unsigned NumVecs = Vecs.size();
564   assert(NumVecs > 1 && "Should be at least two vectors");
565 
566   SmallVector<Value *, 8> ResList;
567   ResList.append(Vecs.begin(), Vecs.end());
568   do {
569     SmallVector<Value *, 8> TmpList;
570     for (unsigned i = 0; i < NumVecs - 1; i += 2) {
571       Value *V0 = ResList[i], *V1 = ResList[i + 1];
572       assert((V0->getType() == V1->getType() || i == NumVecs - 2) &&
573              "Only the last vector may have a different type");
574 
575       TmpList.push_back(concatenateTwoVectors(Builder, V0, V1));
576     }
577 
578     // Push the last vector if the total number of vectors is odd.
579     if (NumVecs % 2 != 0)
580       TmpList.push_back(ResList[NumVecs - 1]);
581 
582     ResList = TmpList;
583     NumVecs = ResList.size();
584   } while (NumVecs > 1);
585 
586   return ResList[0];
587 }
588 
589 bool InterleavedAccessInfo::isStrided(int Stride) {
590   unsigned Factor = std::abs(Stride);
591   return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
592 }
593 
594 void InterleavedAccessInfo::collectConstStrideAccesses(
595     MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
596     const ValueToValueMap &Strides) {
597   auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
598 
599   // Since it's desired that the load/store instructions be maintained in
600   // "program order" for the interleaved access analysis, we have to visit the
601   // blocks in the loop in reverse postorder (i.e., in a topological order).
602   // Such an ordering will ensure that any load/store that may be executed
603   // before a second load/store will precede the second load/store in
604   // AccessStrideInfo.
605   LoopBlocksDFS DFS(TheLoop);
606   DFS.perform(LI);
607   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
608     for (auto &I : *BB) {
609       auto *LI = dyn_cast<LoadInst>(&I);
610       auto *SI = dyn_cast<StoreInst>(&I);
611       if (!LI && !SI)
612         continue;
613 
614       Value *Ptr = getLoadStorePointerOperand(&I);
615       // We don't check wrapping here because we don't know yet if Ptr will be
616       // part of a full group or a group with gaps. Checking wrapping for all
617       // pointers (even those that end up in groups with no gaps) will be overly
618       // conservative. For full groups, wrapping should be ok since if we would
619       // wrap around the address space we would do a memory access at nullptr
620       // even without the transformation. The wrapping checks are therefore
621       // deferred until after we've formed the interleaved groups.
622       int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides,
623                                     /*Assume=*/true, /*ShouldCheckWrap=*/false);
624 
625       const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
626       PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
627       uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
628 
629       // An alignment of 0 means target ABI alignment.
630       unsigned Align = getLoadStoreAlignment(&I);
631       if (!Align)
632         Align = DL.getABITypeAlignment(PtrTy->getElementType());
633 
634       AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align);
635     }
636 }
637 
638 // Analyze interleaved accesses and collect them into interleaved load and
639 // store groups.
640 //
641 // When generating code for an interleaved load group, we effectively hoist all
642 // loads in the group to the location of the first load in program order. When
643 // generating code for an interleaved store group, we sink all stores to the
644 // location of the last store. This code motion can change the order of load
645 // and store instructions and may break dependences.
646 //
647 // The code generation strategy mentioned above ensures that we won't violate
648 // any write-after-read (WAR) dependences.
649 //
650 // E.g., for the WAR dependence:  a = A[i];      // (1)
651 //                                A[i] = b;      // (2)
652 //
653 // The store group of (2) is always inserted at or below (2), and the load
654 // group of (1) is always inserted at or above (1). Thus, the instructions will
655 // never be reordered. All other dependences are checked to ensure the
656 // correctness of the instruction reordering.
657 //
658 // The algorithm visits all memory accesses in the loop in bottom-up program
659 // order. Program order is established by traversing the blocks in the loop in
660 // reverse postorder when collecting the accesses.
661 //
662 // We visit the memory accesses in bottom-up order because it can simplify the
663 // construction of store groups in the presence of write-after-write (WAW)
664 // dependences.
665 //
666 // E.g., for the WAW dependence:  A[i] = a;      // (1)
667 //                                A[i] = b;      // (2)
668 //                                A[i + 1] = c;  // (3)
669 //
670 // We will first create a store group with (3) and (2). (1) can't be added to
671 // this group because it and (2) are dependent. However, (1) can be grouped
672 // with other accesses that may precede it in program order. Note that a
673 // bottom-up order does not imply that WAW dependences should not be checked.
674 void InterleavedAccessInfo::analyzeInterleaving() {
675   LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
676   const ValueToValueMap &Strides = LAI->getSymbolicStrides();
677 
678   // Holds all accesses with a constant stride.
679   MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
680   collectConstStrideAccesses(AccessStrideInfo, Strides);
681 
682   if (AccessStrideInfo.empty())
683     return;
684 
685   // Collect the dependences in the loop.
686   collectDependences();
687 
688   // Holds all interleaved store groups temporarily.
689   SmallSetVector<InterleaveGroup *, 4> StoreGroups;
690   // Holds all interleaved load groups temporarily.
691   SmallSetVector<InterleaveGroup *, 4> LoadGroups;
692 
693   // Search in bottom-up program order for pairs of accesses (A and B) that can
694   // form interleaved load or store groups. In the algorithm below, access A
695   // precedes access B in program order. We initialize a group for B in the
696   // outer loop of the algorithm, and then in the inner loop, we attempt to
697   // insert each A into B's group if:
698   //
699   //  1. A and B have the same stride,
700   //  2. A and B have the same memory object size, and
701   //  3. A belongs in B's group according to its distance from B.
702   //
703   // Special care is taken to ensure group formation will not break any
704   // dependences.
705   for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
706        BI != E; ++BI) {
707     Instruction *B = BI->first;
708     StrideDescriptor DesB = BI->second;
709 
710     // Initialize a group for B if it has an allowable stride. Even if we don't
711     // create a group for B, we continue with the bottom-up algorithm to ensure
712     // we don't break any of B's dependences.
713     InterleaveGroup *Group = nullptr;
714     if (isStrided(DesB.Stride)) {
715       Group = getInterleaveGroup(B);
716       if (!Group) {
717         LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
718                           << '\n');
719         Group = createInterleaveGroup(B, DesB.Stride, DesB.Align);
720       }
721       if (B->mayWriteToMemory())
722         StoreGroups.insert(Group);
723       else
724         LoadGroups.insert(Group);
725     }
726 
727     for (auto AI = std::next(BI); AI != E; ++AI) {
728       Instruction *A = AI->first;
729       StrideDescriptor DesA = AI->second;
730 
731       // Our code motion strategy implies that we can't have dependences
732       // between accesses in an interleaved group and other accesses located
733       // between the first and last member of the group. Note that this also
734       // means that a group can't have more than one member at a given offset.
735       // The accesses in a group can have dependences with other accesses, but
736       // we must ensure we don't extend the boundaries of the group such that
737       // we encompass those dependent accesses.
738       //
739       // For example, assume we have the sequence of accesses shown below in a
740       // stride-2 loop:
741       //
742       //  (1, 2) is a group | A[i]   = a;  // (1)
743       //                    | A[i-1] = b;  // (2) |
744       //                      A[i-3] = c;  // (3)
745       //                      A[i]   = d;  // (4) | (2, 4) is not a group
746       //
747       // Because accesses (2) and (3) are dependent, we can group (2) with (1)
748       // but not with (4). If we did, the dependent access (3) would be within
749       // the boundaries of the (2, 4) group.
750       if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
751         // If a dependence exists and A is already in a group, we know that A
752         // must be a store since A precedes B and WAR dependences are allowed.
753         // Thus, A would be sunk below B. We release A's group to prevent this
754         // illegal code motion. A will then be free to form another group with
755         // instructions that precede it.
756         if (isInterleaved(A)) {
757           InterleaveGroup *StoreGroup = getInterleaveGroup(A);
758           StoreGroups.remove(StoreGroup);
759           releaseGroup(StoreGroup);
760         }
761 
762         // If a dependence exists and A is not already in a group (or it was
763         // and we just released it), B might be hoisted above A (if B is a
764         // load) or another store might be sunk below A (if B is a store). In
765         // either case, we can't add additional instructions to B's group. B
766         // will only form a group with instructions that it precedes.
767         break;
768       }
769 
770       // At this point, we've checked for illegal code motion. If either A or B
771       // isn't strided, there's nothing left to do.
772       if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
773         continue;
774 
775       // Ignore A if it's already in a group or isn't the same kind of memory
776       // operation as B.
777       // Note that mayReadFromMemory() isn't mutually exclusive to
778       // mayWriteToMemory in the case of atomic loads. We shouldn't see those
779       // here, canVectorizeMemory() should have returned false - except for the
780       // case we asked for optimization remarks.
781       if (isInterleaved(A) ||
782           (A->mayReadFromMemory() != B->mayReadFromMemory()) ||
783           (A->mayWriteToMemory() != B->mayWriteToMemory()))
784         continue;
785 
786       // Check rules 1 and 2. Ignore A if its stride or size is different from
787       // that of B.
788       if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
789         continue;
790 
791       // Ignore A if the memory object of A and B don't belong to the same
792       // address space
793       if (getLoadStoreAddressSpace(A) != getLoadStoreAddressSpace(B))
794         continue;
795 
796       // Calculate the distance from A to B.
797       const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
798           PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
799       if (!DistToB)
800         continue;
801       int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
802 
803       // Check rule 3. Ignore A if its distance to B is not a multiple of the
804       // size.
805       if (DistanceToB % static_cast<int64_t>(DesB.Size))
806         continue;
807 
808       // Ignore A if either A or B is in a predicated block. Although we
809       // currently prevent group formation for predicated accesses, we may be
810       // able to relax this limitation in the future once we handle more
811       // complicated blocks.
812       if (isPredicated(A->getParent()) || isPredicated(B->getParent()))
813         continue;
814 
815       // The index of A is the index of B plus A's distance to B in multiples
816       // of the size.
817       int IndexA =
818           Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
819 
820       // Try to insert A into B's group.
821       if (Group->insertMember(A, IndexA, DesA.Align)) {
822         LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
823                           << "    into the interleave group with" << *B
824                           << '\n');
825         InterleaveGroupMap[A] = Group;
826 
827         // Set the first load in program order as the insert position.
828         if (A->mayReadFromMemory())
829           Group->setInsertPos(A);
830       }
831     } // Iteration over A accesses.
832   }   // Iteration over B accesses.
833 
834   // Remove interleaved store groups with gaps.
835   for (InterleaveGroup *Group : StoreGroups)
836     if (Group->getNumMembers() != Group->getFactor()) {
837       LLVM_DEBUG(
838           dbgs() << "LV: Invalidate candidate interleaved store group due "
839                     "to gaps.\n");
840       releaseGroup(Group);
841     }
842   // Remove interleaved groups with gaps (currently only loads) whose memory
843   // accesses may wrap around. We have to revisit the getPtrStride analysis,
844   // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
845   // not check wrapping (see documentation there).
846   // FORNOW we use Assume=false;
847   // TODO: Change to Assume=true but making sure we don't exceed the threshold
848   // of runtime SCEV assumptions checks (thereby potentially failing to
849   // vectorize altogether).
850   // Additional optional optimizations:
851   // TODO: If we are peeling the loop and we know that the first pointer doesn't
852   // wrap then we can deduce that all pointers in the group don't wrap.
853   // This means that we can forcefully peel the loop in order to only have to
854   // check the first pointer for no-wrap. When we'll change to use Assume=true
855   // we'll only need at most one runtime check per interleaved group.
856   for (InterleaveGroup *Group : LoadGroups) {
857     // Case 1: A full group. Can Skip the checks; For full groups, if the wide
858     // load would wrap around the address space we would do a memory access at
859     // nullptr even without the transformation.
860     if (Group->getNumMembers() == Group->getFactor())
861       continue;
862 
863     // Case 2: If first and last members of the group don't wrap this implies
864     // that all the pointers in the group don't wrap.
865     // So we check only group member 0 (which is always guaranteed to exist),
866     // and group member Factor - 1; If the latter doesn't exist we rely on
867     // peeling (if it is a non-reveresed accsess -- see Case 3).
868     Value *FirstMemberPtr = getLoadStorePointerOperand(Group->getMember(0));
869     if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false,
870                       /*ShouldCheckWrap=*/true)) {
871       LLVM_DEBUG(
872           dbgs() << "LV: Invalidate candidate interleaved group due to "
873                     "first group member potentially pointer-wrapping.\n");
874       releaseGroup(Group);
875       continue;
876     }
877     Instruction *LastMember = Group->getMember(Group->getFactor() - 1);
878     if (LastMember) {
879       Value *LastMemberPtr = getLoadStorePointerOperand(LastMember);
880       if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false,
881                         /*ShouldCheckWrap=*/true)) {
882         LLVM_DEBUG(
883             dbgs() << "LV: Invalidate candidate interleaved group due to "
884                       "last group member potentially pointer-wrapping.\n");
885         releaseGroup(Group);
886       }
887     } else {
888       // Case 3: A non-reversed interleaved load group with gaps: We need
889       // to execute at least one scalar epilogue iteration. This will ensure
890       // we don't speculatively access memory out-of-bounds. We only need
891       // to look for a member at index factor - 1, since every group must have
892       // a member at index zero.
893       if (Group->isReverse()) {
894         LLVM_DEBUG(
895             dbgs() << "LV: Invalidate candidate interleaved group due to "
896                       "a reverse access with gaps.\n");
897         releaseGroup(Group);
898         continue;
899       }
900       LLVM_DEBUG(
901           dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
902       RequiresScalarEpilogue = true;
903     }
904   }
905 }
906