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