1 //===----- LoadStoreVectorizer.cpp - GPU Load & Store Vectorizer ----------===//
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 //===----------------------------------------------------------------------===//
11 
12 #include "llvm/ADT/MapVector.h"
13 #include "llvm/ADT/PostOrderIterator.h"
14 #include "llvm/ADT/SetVector.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/Analysis/OrderedBasicBlock.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/Analysis/VectorUtils.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/IR/Value.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Transforms/Utils/Local.h"
35 #include "llvm/Transforms/Vectorize.h"
36 
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "load-store-vectorizer"
40 STATISTIC(NumVectorInstructions, "Number of vector accesses generated");
41 STATISTIC(NumScalarsVectorized, "Number of scalar accesses vectorized");
42 
43 namespace {
44 
45 // FIXME: Assuming stack alignment of 4 is always good enough
46 static const unsigned StackAdjustedAlignment = 4;
47 typedef SmallVector<Instruction *, 8> InstrList;
48 typedef MapVector<Value *, InstrList> InstrListMap;
49 
50 class Vectorizer {
51   Function &F;
52   AliasAnalysis &AA;
53   DominatorTree &DT;
54   ScalarEvolution &SE;
55   TargetTransformInfo &TTI;
56   const DataLayout &DL;
57   IRBuilder<> Builder;
58 
59 public:
60   Vectorizer(Function &F, AliasAnalysis &AA, DominatorTree &DT,
61              ScalarEvolution &SE, TargetTransformInfo &TTI)
62       : F(F), AA(AA), DT(DT), SE(SE), TTI(TTI),
63         DL(F.getParent()->getDataLayout()), Builder(SE.getContext()) {}
64 
65   bool run();
66 
67 private:
68   Value *getPointerOperand(Value *I);
69 
70   unsigned getPointerAddressSpace(Value *I);
71 
72   unsigned getAlignment(LoadInst *LI) const {
73     unsigned Align = LI->getAlignment();
74     if (Align != 0)
75       return Align;
76 
77     return DL.getABITypeAlignment(LI->getType());
78   }
79 
80   unsigned getAlignment(StoreInst *SI) const {
81     unsigned Align = SI->getAlignment();
82     if (Align != 0)
83       return Align;
84 
85     return DL.getABITypeAlignment(SI->getValueOperand()->getType());
86   }
87 
88   bool isConsecutiveAccess(Value *A, Value *B);
89 
90   /// After vectorization, reorder the instructions that I depends on
91   /// (the instructions defining its operands), to ensure they dominate I.
92   void reorder(Instruction *I);
93 
94   /// Returns the first and the last instructions in Chain.
95   std::pair<BasicBlock::iterator, BasicBlock::iterator>
96   getBoundaryInstrs(ArrayRef<Instruction *> Chain);
97 
98   /// Erases the original instructions after vectorizing.
99   void eraseInstructions(ArrayRef<Instruction *> Chain);
100 
101   /// "Legalize" the vector type that would be produced by combining \p
102   /// ElementSizeBits elements in \p Chain. Break into two pieces such that the
103   /// total size of each piece is 1, 2 or a multiple of 4 bytes. \p Chain is
104   /// expected to have more than 4 elements.
105   std::pair<ArrayRef<Instruction *>, ArrayRef<Instruction *>>
106   splitOddVectorElts(ArrayRef<Instruction *> Chain, unsigned ElementSizeBits);
107 
108   /// Finds the largest prefix of Chain that's vectorizable, checking for
109   /// intervening instructions which may affect the memory accessed by the
110   /// instructions within Chain.
111   ///
112   /// The elements of \p Chain must be all loads or all stores and must be in
113   /// address order.
114   ArrayRef<Instruction *> getVectorizablePrefix(ArrayRef<Instruction *> Chain);
115 
116   /// Collects load and store instructions to vectorize.
117   std::pair<InstrListMap, InstrListMap> collectInstructions(BasicBlock *BB);
118 
119   /// Processes the collected instructions, the \p Map. The values of \p Map
120   /// should be all loads or all stores.
121   bool vectorizeChains(InstrListMap &Map);
122 
123   /// Finds the load/stores to consecutive memory addresses and vectorizes them.
124   bool vectorizeInstructions(ArrayRef<Instruction *> Instrs);
125 
126   /// Vectorizes the load instructions in Chain.
127   bool
128   vectorizeLoadChain(ArrayRef<Instruction *> Chain,
129                      SmallPtrSet<Instruction *, 16> *InstructionsProcessed);
130 
131   /// Vectorizes the store instructions in Chain.
132   bool
133   vectorizeStoreChain(ArrayRef<Instruction *> Chain,
134                       SmallPtrSet<Instruction *, 16> *InstructionsProcessed);
135 
136   /// Check if this load/store access is misaligned accesses.
137   bool accessIsMisaligned(unsigned SzInBytes, unsigned AddressSpace,
138                           unsigned Alignment);
139 };
140 
141 class LoadStoreVectorizer : public FunctionPass {
142 public:
143   static char ID;
144 
145   LoadStoreVectorizer() : FunctionPass(ID) {
146     initializeLoadStoreVectorizerPass(*PassRegistry::getPassRegistry());
147   }
148 
149   bool runOnFunction(Function &F) override;
150 
151   StringRef getPassName() const override {
152     return "GPU Load and Store Vectorizer";
153   }
154 
155   void getAnalysisUsage(AnalysisUsage &AU) const override {
156     AU.addRequired<AAResultsWrapperPass>();
157     AU.addRequired<ScalarEvolutionWrapperPass>();
158     AU.addRequired<DominatorTreeWrapperPass>();
159     AU.addRequired<TargetTransformInfoWrapperPass>();
160     AU.setPreservesCFG();
161   }
162 };
163 }
164 
165 INITIALIZE_PASS_BEGIN(LoadStoreVectorizer, DEBUG_TYPE,
166                       "Vectorize load and Store instructions", false, false)
167 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
168 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
169 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
170 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
171 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
172 INITIALIZE_PASS_END(LoadStoreVectorizer, DEBUG_TYPE,
173                     "Vectorize load and store instructions", false, false)
174 
175 char LoadStoreVectorizer::ID = 0;
176 
177 Pass *llvm::createLoadStoreVectorizerPass() {
178   return new LoadStoreVectorizer();
179 }
180 
181 // The real propagateMetadata expects a SmallVector<Value*>, but we deal in
182 // vectors of Instructions.
183 static void propagateMetadata(Instruction *I, ArrayRef<Instruction *> IL) {
184   SmallVector<Value *, 8> VL(IL.begin(), IL.end());
185   propagateMetadata(I, VL);
186 }
187 
188 bool LoadStoreVectorizer::runOnFunction(Function &F) {
189   // Don't vectorize when the attribute NoImplicitFloat is used.
190   if (skipFunction(F) || F.hasFnAttribute(Attribute::NoImplicitFloat))
191     return false;
192 
193   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
194   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
195   ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
196   TargetTransformInfo &TTI =
197       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
198 
199   Vectorizer V(F, AA, DT, SE, TTI);
200   return V.run();
201 }
202 
203 // Vectorizer Implementation
204 bool Vectorizer::run() {
205   bool Changed = false;
206 
207   // Scan the blocks in the function in post order.
208   for (BasicBlock *BB : post_order(&F)) {
209     InstrListMap LoadRefs, StoreRefs;
210     std::tie(LoadRefs, StoreRefs) = collectInstructions(BB);
211     Changed |= vectorizeChains(LoadRefs);
212     Changed |= vectorizeChains(StoreRefs);
213   }
214 
215   return Changed;
216 }
217 
218 Value *Vectorizer::getPointerOperand(Value *I) {
219   if (LoadInst *LI = dyn_cast<LoadInst>(I))
220     return LI->getPointerOperand();
221   if (StoreInst *SI = dyn_cast<StoreInst>(I))
222     return SI->getPointerOperand();
223   return nullptr;
224 }
225 
226 unsigned Vectorizer::getPointerAddressSpace(Value *I) {
227   if (LoadInst *L = dyn_cast<LoadInst>(I))
228     return L->getPointerAddressSpace();
229   if (StoreInst *S = dyn_cast<StoreInst>(I))
230     return S->getPointerAddressSpace();
231   return -1;
232 }
233 
234 // FIXME: Merge with llvm::isConsecutiveAccess
235 bool Vectorizer::isConsecutiveAccess(Value *A, Value *B) {
236   Value *PtrA = getPointerOperand(A);
237   Value *PtrB = getPointerOperand(B);
238   unsigned ASA = getPointerAddressSpace(A);
239   unsigned ASB = getPointerAddressSpace(B);
240 
241   // Check that the address spaces match and that the pointers are valid.
242   if (!PtrA || !PtrB || (ASA != ASB))
243     return false;
244 
245   // Make sure that A and B are different pointers of the same size type.
246   unsigned PtrBitWidth = DL.getPointerSizeInBits(ASA);
247   Type *PtrATy = PtrA->getType()->getPointerElementType();
248   Type *PtrBTy = PtrB->getType()->getPointerElementType();
249   if (PtrA == PtrB ||
250       DL.getTypeStoreSize(PtrATy) != DL.getTypeStoreSize(PtrBTy) ||
251       DL.getTypeStoreSize(PtrATy->getScalarType()) !=
252           DL.getTypeStoreSize(PtrBTy->getScalarType()))
253     return false;
254 
255   APInt Size(PtrBitWidth, DL.getTypeStoreSize(PtrATy));
256 
257   APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
258   PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
259   PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
260 
261   APInt OffsetDelta = OffsetB - OffsetA;
262 
263   // Check if they are based on the same pointer. That makes the offsets
264   // sufficient.
265   if (PtrA == PtrB)
266     return OffsetDelta == Size;
267 
268   // Compute the necessary base pointer delta to have the necessary final delta
269   // equal to the size.
270   APInt BaseDelta = Size - OffsetDelta;
271 
272   // Compute the distance with SCEV between the base pointers.
273   const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
274   const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
275   const SCEV *C = SE.getConstant(BaseDelta);
276   const SCEV *X = SE.getAddExpr(PtrSCEVA, C);
277   if (X == PtrSCEVB)
278     return true;
279 
280   // Sometimes even this doesn't work, because SCEV can't always see through
281   // patterns that look like (gep (ext (add (shl X, C1), C2))). Try checking
282   // things the hard way.
283 
284   // Look through GEPs after checking they're the same except for the last
285   // index.
286   GetElementPtrInst *GEPA = dyn_cast<GetElementPtrInst>(getPointerOperand(A));
287   GetElementPtrInst *GEPB = dyn_cast<GetElementPtrInst>(getPointerOperand(B));
288   if (!GEPA || !GEPB || GEPA->getNumOperands() != GEPB->getNumOperands())
289     return false;
290   unsigned FinalIndex = GEPA->getNumOperands() - 1;
291   for (unsigned i = 0; i < FinalIndex; i++)
292     if (GEPA->getOperand(i) != GEPB->getOperand(i))
293       return false;
294 
295   Instruction *OpA = dyn_cast<Instruction>(GEPA->getOperand(FinalIndex));
296   Instruction *OpB = dyn_cast<Instruction>(GEPB->getOperand(FinalIndex));
297   if (!OpA || !OpB || OpA->getOpcode() != OpB->getOpcode() ||
298       OpA->getType() != OpB->getType())
299     return false;
300 
301   // Only look through a ZExt/SExt.
302   if (!isa<SExtInst>(OpA) && !isa<ZExtInst>(OpA))
303     return false;
304 
305   bool Signed = isa<SExtInst>(OpA);
306 
307   OpA = dyn_cast<Instruction>(OpA->getOperand(0));
308   OpB = dyn_cast<Instruction>(OpB->getOperand(0));
309   if (!OpA || !OpB || OpA->getType() != OpB->getType())
310     return false;
311 
312   // Now we need to prove that adding 1 to OpA won't overflow.
313   bool Safe = false;
314   // First attempt: if OpB is an add with NSW/NUW, and OpB is 1 added to OpA,
315   // we're okay.
316   if (OpB->getOpcode() == Instruction::Add &&
317       isa<ConstantInt>(OpB->getOperand(1)) &&
318       cast<ConstantInt>(OpB->getOperand(1))->getSExtValue() > 0) {
319     if (Signed)
320       Safe = cast<BinaryOperator>(OpB)->hasNoSignedWrap();
321     else
322       Safe = cast<BinaryOperator>(OpB)->hasNoUnsignedWrap();
323   }
324 
325   unsigned BitWidth = OpA->getType()->getScalarSizeInBits();
326 
327   // Second attempt:
328   // If any bits are known to be zero other than the sign bit in OpA, we can
329   // add 1 to it while guaranteeing no overflow of any sort.
330   if (!Safe) {
331     APInt KnownZero(BitWidth, 0);
332     APInt KnownOne(BitWidth, 0);
333     computeKnownBits(OpA, KnownZero, KnownOne, DL, 0, nullptr, OpA, &DT);
334     KnownZero &= ~APInt::getHighBitsSet(BitWidth, 1);
335     if (KnownZero != 0)
336       Safe = true;
337   }
338 
339   if (!Safe)
340     return false;
341 
342   const SCEV *OffsetSCEVA = SE.getSCEV(OpA);
343   const SCEV *OffsetSCEVB = SE.getSCEV(OpB);
344   const SCEV *One = SE.getConstant(APInt(BitWidth, 1));
345   const SCEV *X2 = SE.getAddExpr(OffsetSCEVA, One);
346   return X2 == OffsetSCEVB;
347 }
348 
349 void Vectorizer::reorder(Instruction *I) {
350   OrderedBasicBlock OBB(I->getParent());
351   SmallPtrSet<Instruction *, 16> InstructionsToMove;
352   SmallVector<Instruction *, 16> Worklist;
353 
354   Worklist.push_back(I);
355   while (!Worklist.empty()) {
356     Instruction *IW = Worklist.pop_back_val();
357     int NumOperands = IW->getNumOperands();
358     for (int i = 0; i < NumOperands; i++) {
359       Instruction *IM = dyn_cast<Instruction>(IW->getOperand(i));
360       if (!IM || IM->getOpcode() == Instruction::PHI)
361         continue;
362 
363       // If IM is in another BB, no need to move it, because this pass only
364       // vectorizes instructions within one BB.
365       if (IM->getParent() != I->getParent())
366         continue;
367 
368       if (!OBB.dominates(IM, I)) {
369         InstructionsToMove.insert(IM);
370         Worklist.push_back(IM);
371       }
372     }
373   }
374 
375   // All instructions to move should follow I. Start from I, not from begin().
376   for (auto BBI = I->getIterator(), E = I->getParent()->end(); BBI != E;
377        ++BBI) {
378     if (!InstructionsToMove.count(&*BBI))
379       continue;
380     Instruction *IM = &*BBI;
381     --BBI;
382     IM->removeFromParent();
383     IM->insertBefore(I);
384   }
385 }
386 
387 std::pair<BasicBlock::iterator, BasicBlock::iterator>
388 Vectorizer::getBoundaryInstrs(ArrayRef<Instruction *> Chain) {
389   Instruction *C0 = Chain[0];
390   BasicBlock::iterator FirstInstr = C0->getIterator();
391   BasicBlock::iterator LastInstr = C0->getIterator();
392 
393   BasicBlock *BB = C0->getParent();
394   unsigned NumFound = 0;
395   for (Instruction &I : *BB) {
396     if (!is_contained(Chain, &I))
397       continue;
398 
399     ++NumFound;
400     if (NumFound == 1) {
401       FirstInstr = I.getIterator();
402     }
403     if (NumFound == Chain.size()) {
404       LastInstr = I.getIterator();
405       break;
406     }
407   }
408 
409   // Range is [first, last).
410   return std::make_pair(FirstInstr, ++LastInstr);
411 }
412 
413 void Vectorizer::eraseInstructions(ArrayRef<Instruction *> Chain) {
414   SmallVector<Instruction *, 16> Instrs;
415   for (Instruction *I : Chain) {
416     Value *PtrOperand = getPointerOperand(I);
417     assert(PtrOperand && "Instruction must have a pointer operand.");
418     Instrs.push_back(I);
419     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(PtrOperand))
420       Instrs.push_back(GEP);
421   }
422 
423   // Erase instructions.
424   for (Instruction *I : Instrs)
425     if (I->use_empty())
426       I->eraseFromParent();
427 }
428 
429 std::pair<ArrayRef<Instruction *>, ArrayRef<Instruction *>>
430 Vectorizer::splitOddVectorElts(ArrayRef<Instruction *> Chain,
431                                unsigned ElementSizeBits) {
432   unsigned ElementSizeBytes = ElementSizeBits / 8;
433   unsigned SizeBytes = ElementSizeBytes * Chain.size();
434   unsigned NumLeft = (SizeBytes - (SizeBytes % 4)) / ElementSizeBytes;
435   if (NumLeft == Chain.size())
436     --NumLeft;
437   else if (NumLeft == 0)
438     NumLeft = 1;
439   return std::make_pair(Chain.slice(0, NumLeft), Chain.slice(NumLeft));
440 }
441 
442 ArrayRef<Instruction *>
443 Vectorizer::getVectorizablePrefix(ArrayRef<Instruction *> Chain) {
444   // These are in BB order, unlike Chain, which is in address order.
445   SmallVector<Instruction *, 16> MemoryInstrs;
446   SmallVector<Instruction *, 16> ChainInstrs;
447 
448   bool IsLoadChain = isa<LoadInst>(Chain[0]);
449   DEBUG({
450     for (Instruction *I : Chain) {
451       if (IsLoadChain)
452         assert(isa<LoadInst>(I) &&
453                "All elements of Chain must be loads, or all must be stores.");
454       else
455         assert(isa<StoreInst>(I) &&
456                "All elements of Chain must be loads, or all must be stores.");
457     }
458   });
459 
460   for (Instruction &I : make_range(getBoundaryInstrs(Chain))) {
461     if (isa<LoadInst>(I) || isa<StoreInst>(I)) {
462       if (!is_contained(Chain, &I))
463         MemoryInstrs.push_back(&I);
464       else
465         ChainInstrs.push_back(&I);
466     } else if (IsLoadChain && (I.mayWriteToMemory() || I.mayThrow())) {
467       DEBUG(dbgs() << "LSV: Found may-write/throw operation: " << I << '\n');
468       break;
469     } else if (!IsLoadChain && (I.mayReadOrWriteMemory() || I.mayThrow())) {
470       DEBUG(dbgs() << "LSV: Found may-read/write/throw operation: " << I
471                    << '\n');
472       break;
473     }
474   }
475 
476   OrderedBasicBlock OBB(Chain[0]->getParent());
477 
478   // Loop until we find an instruction in ChainInstrs that we can't vectorize.
479   unsigned ChainInstrIdx = 0;
480   for (unsigned E = ChainInstrs.size(); ChainInstrIdx < E; ++ChainInstrIdx) {
481     Instruction *ChainInstr = ChainInstrs[ChainInstrIdx];
482     bool AliasFound = false;
483     for (Instruction *MemInstr : MemoryInstrs) {
484       if (isa<LoadInst>(MemInstr) && isa<LoadInst>(ChainInstr))
485         continue;
486 
487       // We can ignore the alias as long as the load comes before the store,
488       // because that means we won't be moving the load past the store to
489       // vectorize it (the vectorized load is inserted at the location of the
490       // first load in the chain).
491       if (isa<StoreInst>(MemInstr) && isa<LoadInst>(ChainInstr) &&
492           OBB.dominates(ChainInstr, MemInstr))
493         continue;
494 
495       // Same case, but in reverse.
496       if (isa<LoadInst>(MemInstr) && isa<StoreInst>(ChainInstr) &&
497           OBB.dominates(MemInstr, ChainInstr))
498         continue;
499 
500       if (!AA.isNoAlias(MemoryLocation::get(MemInstr),
501                         MemoryLocation::get(ChainInstr))) {
502         DEBUG({
503           dbgs() << "LSV: Found alias:\n"
504                     "  Aliasing instruction and pointer:\n"
505                  << "  " << *MemInstr << '\n'
506                  << "  " << *getPointerOperand(MemInstr) << '\n'
507                  << "  Aliased instruction and pointer:\n"
508                  << "  " << *ChainInstr << '\n'
509                  << "  " << *getPointerOperand(ChainInstr) << '\n';
510         });
511         AliasFound = true;
512         break;
513       }
514     }
515     if (AliasFound)
516       break;
517   }
518 
519   // Find the largest prefix of Chain whose elements are all in
520   // ChainInstrs[0, ChainInstrIdx).  This is the largest vectorizable prefix of
521   // Chain.  (Recall that Chain is in address order, but ChainInstrs is in BB
522   // order.)
523   SmallPtrSet<Instruction *, 8> VectorizableChainInstrs(
524       ChainInstrs.begin(), ChainInstrs.begin() + ChainInstrIdx);
525   unsigned ChainIdx = 0;
526   for (unsigned ChainLen = Chain.size(); ChainIdx < ChainLen; ++ChainIdx) {
527     if (!VectorizableChainInstrs.count(Chain[ChainIdx]))
528       break;
529   }
530   return Chain.slice(0, ChainIdx);
531 }
532 
533 std::pair<InstrListMap, InstrListMap>
534 Vectorizer::collectInstructions(BasicBlock *BB) {
535   InstrListMap LoadRefs;
536   InstrListMap StoreRefs;
537 
538   for (Instruction &I : *BB) {
539     if (!I.mayReadOrWriteMemory())
540       continue;
541 
542     if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
543       if (!LI->isSimple())
544         continue;
545 
546       // Skip if it's not legal.
547       if (!TTI.isLegalToVectorizeLoad(LI))
548         continue;
549 
550       Type *Ty = LI->getType();
551       if (!VectorType::isValidElementType(Ty->getScalarType()))
552         continue;
553 
554       // Skip weird non-byte sizes. They probably aren't worth the effort of
555       // handling correctly.
556       unsigned TySize = DL.getTypeSizeInBits(Ty);
557       if (TySize < 8)
558         continue;
559 
560       Value *Ptr = LI->getPointerOperand();
561       unsigned AS = Ptr->getType()->getPointerAddressSpace();
562       unsigned VecRegSize = TTI.getLoadStoreVecRegBitWidth(AS);
563 
564       // No point in looking at these if they're too big to vectorize.
565       if (TySize > VecRegSize / 2)
566         continue;
567 
568       // Make sure all the users of a vector are constant-index extracts.
569       if (isa<VectorType>(Ty) && !all_of(LI->users(), [LI](const User *U) {
570             const ExtractElementInst *EEI = dyn_cast<ExtractElementInst>(U);
571             return EEI && isa<ConstantInt>(EEI->getOperand(1));
572           }))
573         continue;
574 
575       // Save the load locations.
576       Value *ObjPtr = GetUnderlyingObject(Ptr, DL);
577       LoadRefs[ObjPtr].push_back(LI);
578 
579     } else if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
580       if (!SI->isSimple())
581         continue;
582 
583       // Skip if it's not legal.
584       if (!TTI.isLegalToVectorizeStore(SI))
585         continue;
586 
587       Type *Ty = SI->getValueOperand()->getType();
588       if (!VectorType::isValidElementType(Ty->getScalarType()))
589         continue;
590 
591       // Skip weird non-byte sizes. They probably aren't worth the effort of
592       // handling correctly.
593       unsigned TySize = DL.getTypeSizeInBits(Ty);
594       if (TySize < 8)
595         continue;
596 
597       Value *Ptr = SI->getPointerOperand();
598       unsigned AS = Ptr->getType()->getPointerAddressSpace();
599       unsigned VecRegSize = TTI.getLoadStoreVecRegBitWidth(AS);
600       if (TySize > VecRegSize / 2)
601         continue;
602 
603       if (isa<VectorType>(Ty) && !all_of(SI->users(), [SI](const User *U) {
604             const ExtractElementInst *EEI = dyn_cast<ExtractElementInst>(U);
605             return EEI && isa<ConstantInt>(EEI->getOperand(1));
606           }))
607         continue;
608 
609       // Save store location.
610       Value *ObjPtr = GetUnderlyingObject(Ptr, DL);
611       StoreRefs[ObjPtr].push_back(SI);
612     }
613   }
614 
615   return {LoadRefs, StoreRefs};
616 }
617 
618 bool Vectorizer::vectorizeChains(InstrListMap &Map) {
619   bool Changed = false;
620 
621   for (const std::pair<Value *, InstrList> &Chain : Map) {
622     unsigned Size = Chain.second.size();
623     if (Size < 2)
624       continue;
625 
626     DEBUG(dbgs() << "LSV: Analyzing a chain of length " << Size << ".\n");
627 
628     // Process the stores in chunks of 64.
629     for (unsigned CI = 0, CE = Size; CI < CE; CI += 64) {
630       unsigned Len = std::min<unsigned>(CE - CI, 64);
631       ArrayRef<Instruction *> Chunk(&Chain.second[CI], Len);
632       Changed |= vectorizeInstructions(Chunk);
633     }
634   }
635 
636   return Changed;
637 }
638 
639 bool Vectorizer::vectorizeInstructions(ArrayRef<Instruction *> Instrs) {
640   DEBUG(dbgs() << "LSV: Vectorizing " << Instrs.size() << " instructions.\n");
641   SmallVector<int, 16> Heads, Tails;
642   int ConsecutiveChain[64];
643 
644   // Do a quadratic search on all of the given stores and find all of the pairs
645   // of stores that follow each other.
646   for (int i = 0, e = Instrs.size(); i < e; ++i) {
647     ConsecutiveChain[i] = -1;
648     for (int j = e - 1; j >= 0; --j) {
649       if (i == j)
650         continue;
651 
652       if (isConsecutiveAccess(Instrs[i], Instrs[j])) {
653         if (ConsecutiveChain[i] != -1) {
654           int CurDistance = std::abs(ConsecutiveChain[i] - i);
655           int NewDistance = std::abs(ConsecutiveChain[i] - j);
656           if (j < i || NewDistance > CurDistance)
657             continue; // Should not insert.
658         }
659 
660         Tails.push_back(j);
661         Heads.push_back(i);
662         ConsecutiveChain[i] = j;
663       }
664     }
665   }
666 
667   bool Changed = false;
668   SmallPtrSet<Instruction *, 16> InstructionsProcessed;
669 
670   for (int Head : Heads) {
671     if (InstructionsProcessed.count(Instrs[Head]))
672       continue;
673     bool LongerChainExists = false;
674     for (unsigned TIt = 0; TIt < Tails.size(); TIt++)
675       if (Head == Tails[TIt] &&
676           !InstructionsProcessed.count(Instrs[Heads[TIt]])) {
677         LongerChainExists = true;
678         break;
679       }
680     if (LongerChainExists)
681       continue;
682 
683     // We found an instr that starts a chain. Now follow the chain and try to
684     // vectorize it.
685     SmallVector<Instruction *, 16> Operands;
686     int I = Head;
687     while (I != -1 && (is_contained(Tails, I) || is_contained(Heads, I))) {
688       if (InstructionsProcessed.count(Instrs[I]))
689         break;
690 
691       Operands.push_back(Instrs[I]);
692       I = ConsecutiveChain[I];
693     }
694 
695     bool Vectorized = false;
696     if (isa<LoadInst>(*Operands.begin()))
697       Vectorized = vectorizeLoadChain(Operands, &InstructionsProcessed);
698     else
699       Vectorized = vectorizeStoreChain(Operands, &InstructionsProcessed);
700 
701     Changed |= Vectorized;
702   }
703 
704   return Changed;
705 }
706 
707 bool Vectorizer::vectorizeStoreChain(
708     ArrayRef<Instruction *> Chain,
709     SmallPtrSet<Instruction *, 16> *InstructionsProcessed) {
710   StoreInst *S0 = cast<StoreInst>(Chain[0]);
711 
712   // If the vector has an int element, default to int for the whole load.
713   Type *StoreTy;
714   for (Instruction *I : Chain) {
715     StoreTy = cast<StoreInst>(I)->getValueOperand()->getType();
716     if (StoreTy->isIntOrIntVectorTy())
717       break;
718 
719     if (StoreTy->isPtrOrPtrVectorTy()) {
720       StoreTy = Type::getIntNTy(F.getParent()->getContext(),
721                                 DL.getTypeSizeInBits(StoreTy));
722       break;
723     }
724   }
725 
726   unsigned Sz = DL.getTypeSizeInBits(StoreTy);
727   unsigned AS = S0->getPointerAddressSpace();
728   unsigned VecRegSize = TTI.getLoadStoreVecRegBitWidth(AS);
729   unsigned VF = VecRegSize / Sz;
730   unsigned ChainSize = Chain.size();
731   unsigned Alignment = getAlignment(S0);
732 
733   if (!isPowerOf2_32(Sz) || VF < 2 || ChainSize < 2) {
734     InstructionsProcessed->insert(Chain.begin(), Chain.end());
735     return false;
736   }
737 
738   ArrayRef<Instruction *> NewChain = getVectorizablePrefix(Chain);
739   if (NewChain.empty()) {
740     // No vectorization possible.
741     InstructionsProcessed->insert(Chain.begin(), Chain.end());
742     return false;
743   }
744   if (NewChain.size() == 1) {
745     // Failed after the first instruction. Discard it and try the smaller chain.
746     InstructionsProcessed->insert(NewChain.front());
747     return false;
748   }
749 
750   // Update Chain to the valid vectorizable subchain.
751   Chain = NewChain;
752   ChainSize = Chain.size();
753 
754   // Check if it's legal to vectorize this chain. If not, split the chain and
755   // try again.
756   unsigned EltSzInBytes = Sz / 8;
757   unsigned SzInBytes = EltSzInBytes * ChainSize;
758   if (!TTI.isLegalToVectorizeStoreChain(SzInBytes, Alignment, AS)) {
759     auto Chains = splitOddVectorElts(Chain, Sz);
760     return vectorizeStoreChain(Chains.first, InstructionsProcessed) |
761            vectorizeStoreChain(Chains.second, InstructionsProcessed);
762   }
763 
764   VectorType *VecTy;
765   VectorType *VecStoreTy = dyn_cast<VectorType>(StoreTy);
766   if (VecStoreTy)
767     VecTy = VectorType::get(StoreTy->getScalarType(),
768                             Chain.size() * VecStoreTy->getNumElements());
769   else
770     VecTy = VectorType::get(StoreTy, Chain.size());
771 
772   // If it's more than the max vector size or the target has a better
773   // vector factor, break it into two pieces.
774   unsigned TargetVF = TTI.getStoreVectorFactor(VF, Sz, SzInBytes, VecTy);
775   if (ChainSize > VF || (VF != TargetVF && TargetVF < ChainSize)) {
776     DEBUG(dbgs() << "LSV: Chain doesn't match with the vector factor."
777                     " Creating two separate arrays.\n");
778     return vectorizeStoreChain(Chain.slice(0, TargetVF),
779                                InstructionsProcessed) |
780            vectorizeStoreChain(Chain.slice(TargetVF), InstructionsProcessed);
781   }
782 
783   DEBUG({
784     dbgs() << "LSV: Stores to vectorize:\n";
785     for (Instruction *I : Chain)
786       dbgs() << "  " << *I << "\n";
787   });
788 
789   // We won't try again to vectorize the elements of the chain, regardless of
790   // whether we succeed below.
791   InstructionsProcessed->insert(Chain.begin(), Chain.end());
792 
793   // If the store is going to be misaligned, don't vectorize it.
794   if (accessIsMisaligned(SzInBytes, AS, Alignment)) {
795     if (S0->getPointerAddressSpace() != 0)
796       return false;
797 
798     unsigned NewAlign = getOrEnforceKnownAlignment(S0->getPointerOperand(),
799                                                    StackAdjustedAlignment,
800                                                    DL, S0, nullptr, &DT);
801     if (NewAlign < StackAdjustedAlignment)
802       return false;
803   }
804 
805   BasicBlock::iterator First, Last;
806   std::tie(First, Last) = getBoundaryInstrs(Chain);
807   Builder.SetInsertPoint(&*Last);
808 
809   Value *Vec = UndefValue::get(VecTy);
810 
811   if (VecStoreTy) {
812     unsigned VecWidth = VecStoreTy->getNumElements();
813     for (unsigned I = 0, E = Chain.size(); I != E; ++I) {
814       StoreInst *Store = cast<StoreInst>(Chain[I]);
815       for (unsigned J = 0, NE = VecStoreTy->getNumElements(); J != NE; ++J) {
816         unsigned NewIdx = J + I * VecWidth;
817         Value *Extract = Builder.CreateExtractElement(Store->getValueOperand(),
818                                                       Builder.getInt32(J));
819         if (Extract->getType() != StoreTy->getScalarType())
820           Extract = Builder.CreateBitCast(Extract, StoreTy->getScalarType());
821 
822         Value *Insert =
823             Builder.CreateInsertElement(Vec, Extract, Builder.getInt32(NewIdx));
824         Vec = Insert;
825       }
826     }
827   } else {
828     for (unsigned I = 0, E = Chain.size(); I != E; ++I) {
829       StoreInst *Store = cast<StoreInst>(Chain[I]);
830       Value *Extract = Store->getValueOperand();
831       if (Extract->getType() != StoreTy->getScalarType())
832         Extract =
833             Builder.CreateBitOrPointerCast(Extract, StoreTy->getScalarType());
834 
835       Value *Insert =
836           Builder.CreateInsertElement(Vec, Extract, Builder.getInt32(I));
837       Vec = Insert;
838     }
839   }
840 
841   // This cast is safe because Builder.CreateStore() always creates a bona fide
842   // StoreInst.
843   StoreInst *SI = cast<StoreInst>(
844       Builder.CreateStore(Vec, Builder.CreateBitCast(S0->getPointerOperand(),
845                                                      VecTy->getPointerTo(AS))));
846   propagateMetadata(SI, Chain);
847   SI->setAlignment(Alignment);
848 
849   eraseInstructions(Chain);
850   ++NumVectorInstructions;
851   NumScalarsVectorized += Chain.size();
852   return true;
853 }
854 
855 bool Vectorizer::vectorizeLoadChain(
856     ArrayRef<Instruction *> Chain,
857     SmallPtrSet<Instruction *, 16> *InstructionsProcessed) {
858   LoadInst *L0 = cast<LoadInst>(Chain[0]);
859 
860   // If the vector has an int element, default to int for the whole load.
861   Type *LoadTy;
862   for (const auto &V : Chain) {
863     LoadTy = cast<LoadInst>(V)->getType();
864     if (LoadTy->isIntOrIntVectorTy())
865       break;
866 
867     if (LoadTy->isPtrOrPtrVectorTy()) {
868       LoadTy = Type::getIntNTy(F.getParent()->getContext(),
869                                DL.getTypeSizeInBits(LoadTy));
870       break;
871     }
872   }
873 
874   unsigned Sz = DL.getTypeSizeInBits(LoadTy);
875   unsigned AS = L0->getPointerAddressSpace();
876   unsigned VecRegSize = TTI.getLoadStoreVecRegBitWidth(AS);
877   unsigned VF = VecRegSize / Sz;
878   unsigned ChainSize = Chain.size();
879   unsigned Alignment = getAlignment(L0);
880 
881   if (!isPowerOf2_32(Sz) || VF < 2 || ChainSize < 2) {
882     InstructionsProcessed->insert(Chain.begin(), Chain.end());
883     return false;
884   }
885 
886   ArrayRef<Instruction *> NewChain = getVectorizablePrefix(Chain);
887   if (NewChain.empty()) {
888     // No vectorization possible.
889     InstructionsProcessed->insert(Chain.begin(), Chain.end());
890     return false;
891   }
892   if (NewChain.size() == 1) {
893     // Failed after the first instruction. Discard it and try the smaller chain.
894     InstructionsProcessed->insert(NewChain.front());
895     return false;
896   }
897 
898   // Update Chain to the valid vectorizable subchain.
899   Chain = NewChain;
900   ChainSize = Chain.size();
901 
902   // Check if it's legal to vectorize this chain. If not, split the chain and
903   // try again.
904   unsigned EltSzInBytes = Sz / 8;
905   unsigned SzInBytes = EltSzInBytes * ChainSize;
906   if (!TTI.isLegalToVectorizeLoadChain(SzInBytes, Alignment, AS)) {
907     auto Chains = splitOddVectorElts(Chain, Sz);
908     return vectorizeLoadChain(Chains.first, InstructionsProcessed) |
909            vectorizeLoadChain(Chains.second, InstructionsProcessed);
910   }
911 
912   VectorType *VecTy;
913   VectorType *VecLoadTy = dyn_cast<VectorType>(LoadTy);
914   if (VecLoadTy)
915     VecTy = VectorType::get(LoadTy->getScalarType(),
916                             Chain.size() * VecLoadTy->getNumElements());
917   else
918     VecTy = VectorType::get(LoadTy, Chain.size());
919 
920   // If it's more than the max vector size or the target has a better
921   // vector factor, break it into two pieces.
922   unsigned TargetVF = TTI.getLoadVectorFactor(VF, Sz, SzInBytes, VecTy);
923   if (ChainSize > VF || (VF != TargetVF && TargetVF < ChainSize)) {
924     DEBUG(dbgs() << "LSV: Chain doesn't match with the vector factor."
925                     " Creating two separate arrays.\n");
926     return vectorizeLoadChain(Chain.slice(0, TargetVF), InstructionsProcessed) |
927            vectorizeLoadChain(Chain.slice(TargetVF), InstructionsProcessed);
928   }
929 
930   // We won't try again to vectorize the elements of the chain, regardless of
931   // whether we succeed below.
932   InstructionsProcessed->insert(Chain.begin(), Chain.end());
933 
934   // If the load is going to be misaligned, don't vectorize it.
935   if (accessIsMisaligned(SzInBytes, AS, Alignment)) {
936     if (L0->getPointerAddressSpace() != 0)
937       return false;
938 
939     unsigned NewAlign = getOrEnforceKnownAlignment(L0->getPointerOperand(),
940                                                    StackAdjustedAlignment,
941                                                    DL, L0, nullptr, &DT);
942     if (NewAlign < StackAdjustedAlignment)
943       return false;
944 
945     Alignment = NewAlign;
946   }
947 
948   DEBUG({
949     dbgs() << "LSV: Loads to vectorize:\n";
950     for (Instruction *I : Chain)
951       I->dump();
952   });
953 
954   // getVectorizablePrefix already computed getBoundaryInstrs.  The value of
955   // Last may have changed since then, but the value of First won't have.  If it
956   // matters, we could compute getBoundaryInstrs only once and reuse it here.
957   BasicBlock::iterator First, Last;
958   std::tie(First, Last) = getBoundaryInstrs(Chain);
959   Builder.SetInsertPoint(&*First);
960 
961   Value *Bitcast =
962       Builder.CreateBitCast(L0->getPointerOperand(), VecTy->getPointerTo(AS));
963   // This cast is safe because Builder.CreateLoad always creates a bona fide
964   // LoadInst.
965   LoadInst *LI = cast<LoadInst>(Builder.CreateLoad(Bitcast));
966   propagateMetadata(LI, Chain);
967   LI->setAlignment(Alignment);
968 
969   if (VecLoadTy) {
970     SmallVector<Instruction *, 16> InstrsToErase;
971 
972     unsigned VecWidth = VecLoadTy->getNumElements();
973     for (unsigned I = 0, E = Chain.size(); I != E; ++I) {
974       for (auto Use : Chain[I]->users()) {
975         // All users of vector loads are ExtractElement instructions with
976         // constant indices, otherwise we would have bailed before now.
977         Instruction *UI = cast<Instruction>(Use);
978         unsigned Idx = cast<ConstantInt>(UI->getOperand(1))->getZExtValue();
979         unsigned NewIdx = Idx + I * VecWidth;
980         Value *V = Builder.CreateExtractElement(LI, Builder.getInt32(NewIdx),
981                                                 UI->getName());
982         if (V->getType() != UI->getType())
983           V = Builder.CreateBitCast(V, UI->getType());
984 
985         // Replace the old instruction.
986         UI->replaceAllUsesWith(V);
987         InstrsToErase.push_back(UI);
988       }
989     }
990 
991     // Bitcast might not be an Instruction, if the value being loaded is a
992     // constant.  In that case, no need to reorder anything.
993     if (Instruction *BitcastInst = dyn_cast<Instruction>(Bitcast))
994       reorder(BitcastInst);
995 
996     for (auto I : InstrsToErase)
997       I->eraseFromParent();
998   } else {
999     for (unsigned I = 0, E = Chain.size(); I != E; ++I) {
1000       Value *CV = Chain[I];
1001       Value *V =
1002           Builder.CreateExtractElement(LI, Builder.getInt32(I), CV->getName());
1003       if (V->getType() != CV->getType()) {
1004         V = Builder.CreateBitOrPointerCast(V, CV->getType());
1005       }
1006 
1007       // Replace the old instruction.
1008       CV->replaceAllUsesWith(V);
1009     }
1010 
1011     if (Instruction *BitcastInst = dyn_cast<Instruction>(Bitcast))
1012       reorder(BitcastInst);
1013   }
1014 
1015   eraseInstructions(Chain);
1016 
1017   ++NumVectorInstructions;
1018   NumScalarsVectorized += Chain.size();
1019   return true;
1020 }
1021 
1022 bool Vectorizer::accessIsMisaligned(unsigned SzInBytes, unsigned AddressSpace,
1023                                     unsigned Alignment) {
1024   if (Alignment % SzInBytes == 0)
1025     return false;
1026 
1027   bool Fast = false;
1028   bool Allows = TTI.allowsMisalignedMemoryAccesses(F.getParent()->getContext(),
1029                                                    SzInBytes * 8, AddressSpace,
1030                                                    Alignment, &Fast);
1031   DEBUG(dbgs() << "LSV: Target said misaligned is allowed? " << Allows
1032                << " and fast? " << Fast << "\n";);
1033   return !Allows || !Fast;
1034 }
1035