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