1 //===- Scalarizer.cpp - Scalarize vector operations -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass converts vector operations into scalar operations, in order
10 // to expose optimization opportunities on the individual scalar operations.
11 // It is mainly intended for targets that do not have vector units, but it
12 // may also be useful for revectorizing code to different vector widths.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/ADT/PostOrderIterator.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Analysis/VectorUtils.h"
20 #include "llvm/IR/Argument.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/InstVisitor.h"
28 #include "llvm/IR/InstrTypes.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/Options.h"
40 #include "llvm/Transforms/Scalar.h"
41 #include "llvm/Transforms/Scalar/Scalarizer.h"
42 #include <cassert>
43 #include <cstdint>
44 #include <iterator>
45 #include <map>
46 #include <utility>
47 
48 using namespace llvm;
49 
50 #define DEBUG_TYPE "scalarizer"
51 
52 // This is disabled by default because having separate loads and stores
53 // makes it more likely that the -combiner-alias-analysis limits will be
54 // reached.
55 static cl::opt<bool>
56     ScalarizeLoadStore("scalarize-load-store", cl::init(false), cl::Hidden,
57                        cl::desc("Allow the scalarizer pass to scalarize loads and store"));
58 
59 namespace {
60 
61 // Used to store the scattered form of a vector.
62 using ValueVector = SmallVector<Value *, 8>;
63 
64 // Used to map a vector Value to its scattered form.  We use std::map
65 // because we want iterators to persist across insertion and because the
66 // values are relatively large.
67 using ScatterMap = std::map<Value *, ValueVector>;
68 
69 // Lists Instructions that have been replaced with scalar implementations,
70 // along with a pointer to their scattered forms.
71 using GatherList = SmallVector<std::pair<Instruction *, ValueVector *>, 16>;
72 
73 // Provides a very limited vector-like interface for lazily accessing one
74 // component of a scattered vector or vector pointer.
75 class Scatterer {
76 public:
77   Scatterer() = default;
78 
79   // Scatter V into Size components.  If new instructions are needed,
80   // insert them before BBI in BB.  If Cache is nonnull, use it to cache
81   // the results.
82   Scatterer(BasicBlock *bb, BasicBlock::iterator bbi, Value *v,
83             ValueVector *cachePtr = nullptr);
84 
85   // Return component I, creating a new Value for it if necessary.
86   Value *operator[](unsigned I);
87 
88   // Return the number of components.
89   unsigned size() const { return Size; }
90 
91 private:
92   BasicBlock *BB;
93   BasicBlock::iterator BBI;
94   Value *V;
95   ValueVector *CachePtr;
96   PointerType *PtrTy;
97   ValueVector Tmp;
98   unsigned Size;
99 };
100 
101 // FCmpSpliiter(FCI)(Builder, X, Y, Name) uses Builder to create an FCmp
102 // called Name that compares X and Y in the same way as FCI.
103 struct FCmpSplitter {
104   FCmpSplitter(FCmpInst &fci) : FCI(fci) {}
105 
106   Value *operator()(IRBuilder<> &Builder, Value *Op0, Value *Op1,
107                     const Twine &Name) const {
108     return Builder.CreateFCmp(FCI.getPredicate(), Op0, Op1, Name);
109   }
110 
111   FCmpInst &FCI;
112 };
113 
114 // ICmpSpliiter(ICI)(Builder, X, Y, Name) uses Builder to create an ICmp
115 // called Name that compares X and Y in the same way as ICI.
116 struct ICmpSplitter {
117   ICmpSplitter(ICmpInst &ici) : ICI(ici) {}
118 
119   Value *operator()(IRBuilder<> &Builder, Value *Op0, Value *Op1,
120                     const Twine &Name) const {
121     return Builder.CreateICmp(ICI.getPredicate(), Op0, Op1, Name);
122   }
123 
124   ICmpInst &ICI;
125 };
126 
127 // UnarySpliiter(UO)(Builder, X, Name) uses Builder to create
128 // a unary operator like UO called Name with operand X.
129 struct UnarySplitter {
130   UnarySplitter(UnaryOperator &uo) : UO(uo) {}
131 
132   Value *operator()(IRBuilder<> &Builder, Value *Op, const Twine &Name) const {
133     return Builder.CreateUnOp(UO.getOpcode(), Op, Name);
134   }
135 
136   UnaryOperator &UO;
137 };
138 
139 // BinarySpliiter(BO)(Builder, X, Y, Name) uses Builder to create
140 // a binary operator like BO called Name with operands X and Y.
141 struct BinarySplitter {
142   BinarySplitter(BinaryOperator &bo) : BO(bo) {}
143 
144   Value *operator()(IRBuilder<> &Builder, Value *Op0, Value *Op1,
145                     const Twine &Name) const {
146     return Builder.CreateBinOp(BO.getOpcode(), Op0, Op1, Name);
147   }
148 
149   BinaryOperator &BO;
150 };
151 
152 // Information about a load or store that we're scalarizing.
153 struct VectorLayout {
154   VectorLayout() = default;
155 
156   // Return the alignment of element I.
157   uint64_t getElemAlign(unsigned I) {
158     return MinAlign(VecAlign, I * ElemSize);
159   }
160 
161   // The type of the vector.
162   VectorType *VecTy = nullptr;
163 
164   // The type of each element.
165   Type *ElemTy = nullptr;
166 
167   // The alignment of the vector.
168   uint64_t VecAlign = 0;
169 
170   // The size of each element.
171   uint64_t ElemSize = 0;
172 };
173 
174 class ScalarizerVisitor : public InstVisitor<ScalarizerVisitor, bool> {
175 public:
176   ScalarizerVisitor(unsigned ParallelLoopAccessMDKind)
177     : ParallelLoopAccessMDKind(ParallelLoopAccessMDKind) {
178   }
179 
180   bool visit(Function &F);
181 
182   // InstVisitor methods.  They return true if the instruction was scalarized,
183   // false if nothing changed.
184   bool visitInstruction(Instruction &I) { return false; }
185   bool visitSelectInst(SelectInst &SI);
186   bool visitICmpInst(ICmpInst &ICI);
187   bool visitFCmpInst(FCmpInst &FCI);
188   bool visitUnaryOperator(UnaryOperator &UO);
189   bool visitBinaryOperator(BinaryOperator &BO);
190   bool visitGetElementPtrInst(GetElementPtrInst &GEPI);
191   bool visitCastInst(CastInst &CI);
192   bool visitBitCastInst(BitCastInst &BCI);
193   bool visitShuffleVectorInst(ShuffleVectorInst &SVI);
194   bool visitPHINode(PHINode &PHI);
195   bool visitLoadInst(LoadInst &LI);
196   bool visitStoreInst(StoreInst &SI);
197   bool visitCallInst(CallInst &ICI);
198 
199 private:
200   Scatterer scatter(Instruction *Point, Value *V);
201   void gather(Instruction *Op, const ValueVector &CV);
202   bool canTransferMetadata(unsigned Kind);
203   void transferMetadata(Instruction *Op, const ValueVector &CV);
204   bool getVectorLayout(Type *Ty, unsigned Alignment, VectorLayout &Layout,
205                        const DataLayout &DL);
206   bool finish();
207 
208   template<typename T> bool splitUnary(Instruction &, const T &);
209   template<typename T> bool splitBinary(Instruction &, const T &);
210 
211   bool splitCall(CallInst &CI);
212 
213   ScatterMap Scattered;
214   GatherList Gathered;
215 
216   unsigned ParallelLoopAccessMDKind;
217 };
218 
219 class ScalarizerLegacyPass : public FunctionPass {
220 public:
221   static char ID;
222 
223   ScalarizerLegacyPass() : FunctionPass(ID) {
224     initializeScalarizerLegacyPassPass(*PassRegistry::getPassRegistry());
225   }
226 
227   bool runOnFunction(Function &F) override;
228 };
229 
230 } // end anonymous namespace
231 
232 char ScalarizerLegacyPass::ID = 0;
233 INITIALIZE_PASS_BEGIN(ScalarizerLegacyPass, "scalarizer",
234                       "Scalarize vector operations", false, false)
235 INITIALIZE_PASS_END(ScalarizerLegacyPass, "scalarizer",
236                     "Scalarize vector operations", false, false)
237 
238 Scatterer::Scatterer(BasicBlock *bb, BasicBlock::iterator bbi, Value *v,
239                      ValueVector *cachePtr)
240   : BB(bb), BBI(bbi), V(v), CachePtr(cachePtr) {
241   Type *Ty = V->getType();
242   PtrTy = dyn_cast<PointerType>(Ty);
243   if (PtrTy)
244     Ty = PtrTy->getElementType();
245   Size = Ty->getVectorNumElements();
246   if (!CachePtr)
247     Tmp.resize(Size, nullptr);
248   else if (CachePtr->empty())
249     CachePtr->resize(Size, nullptr);
250   else
251     assert(Size == CachePtr->size() && "Inconsistent vector sizes");
252 }
253 
254 // Return component I, creating a new Value for it if necessary.
255 Value *Scatterer::operator[](unsigned I) {
256   ValueVector &CV = (CachePtr ? *CachePtr : Tmp);
257   // Try to reuse a previous value.
258   if (CV[I])
259     return CV[I];
260   IRBuilder<> Builder(BB, BBI);
261   if (PtrTy) {
262     Type *ElTy = PtrTy->getElementType()->getVectorElementType();
263     if (!CV[0]) {
264       Type *NewPtrTy = PointerType::get(ElTy, PtrTy->getAddressSpace());
265       CV[0] = Builder.CreateBitCast(V, NewPtrTy, V->getName() + ".i0");
266     }
267     if (I != 0)
268       CV[I] = Builder.CreateConstGEP1_32(ElTy, CV[0], I,
269                                          V->getName() + ".i" + Twine(I));
270   } else {
271     // Search through a chain of InsertElementInsts looking for element I.
272     // Record other elements in the cache.  The new V is still suitable
273     // for all uncached indices.
274     while (true) {
275       InsertElementInst *Insert = dyn_cast<InsertElementInst>(V);
276       if (!Insert)
277         break;
278       ConstantInt *Idx = dyn_cast<ConstantInt>(Insert->getOperand(2));
279       if (!Idx)
280         break;
281       unsigned J = Idx->getZExtValue();
282       V = Insert->getOperand(0);
283       if (I == J) {
284         CV[J] = Insert->getOperand(1);
285         return CV[J];
286       } else if (!CV[J]) {
287         // Only cache the first entry we find for each index we're not actively
288         // searching for. This prevents us from going too far up the chain and
289         // caching incorrect entries.
290         CV[J] = Insert->getOperand(1);
291       }
292     }
293     CV[I] = Builder.CreateExtractElement(V, Builder.getInt32(I),
294                                          V->getName() + ".i" + Twine(I));
295   }
296   return CV[I];
297 }
298 
299 bool ScalarizerLegacyPass::runOnFunction(Function &F) {
300   if (skipFunction(F))
301     return false;
302 
303   Module &M = *F.getParent();
304   unsigned ParallelLoopAccessMDKind =
305       M.getContext().getMDKindID("llvm.mem.parallel_loop_access");
306   ScalarizerVisitor Impl(ParallelLoopAccessMDKind);
307   return Impl.visit(F);
308 }
309 
310 FunctionPass *llvm::createScalarizerPass() {
311   return new ScalarizerLegacyPass();
312 }
313 
314 bool ScalarizerVisitor::visit(Function &F) {
315   assert(Gathered.empty() && Scattered.empty());
316 
317   // To ensure we replace gathered components correctly we need to do an ordered
318   // traversal of the basic blocks in the function.
319   ReversePostOrderTraversal<BasicBlock *> RPOT(&F.getEntryBlock());
320   for (BasicBlock *BB : RPOT) {
321     for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
322       Instruction *I = &*II;
323       bool Done = InstVisitor::visit(I);
324       ++II;
325       if (Done && I->getType()->isVoidTy())
326         I->eraseFromParent();
327     }
328   }
329   return finish();
330 }
331 
332 // Return a scattered form of V that can be accessed by Point.  V must be a
333 // vector or a pointer to a vector.
334 Scatterer ScalarizerVisitor::scatter(Instruction *Point, Value *V) {
335   if (Argument *VArg = dyn_cast<Argument>(V)) {
336     // Put the scattered form of arguments in the entry block,
337     // so that it can be used everywhere.
338     Function *F = VArg->getParent();
339     BasicBlock *BB = &F->getEntryBlock();
340     return Scatterer(BB, BB->begin(), V, &Scattered[V]);
341   }
342   if (Instruction *VOp = dyn_cast<Instruction>(V)) {
343     // Put the scattered form of an instruction directly after the
344     // instruction.
345     BasicBlock *BB = VOp->getParent();
346     return Scatterer(BB, std::next(BasicBlock::iterator(VOp)),
347                      V, &Scattered[V]);
348   }
349   // In the fallback case, just put the scattered before Point and
350   // keep the result local to Point.
351   return Scatterer(Point->getParent(), Point->getIterator(), V);
352 }
353 
354 // Replace Op with the gathered form of the components in CV.  Defer the
355 // deletion of Op and creation of the gathered form to the end of the pass,
356 // so that we can avoid creating the gathered form if all uses of Op are
357 // replaced with uses of CV.
358 void ScalarizerVisitor::gather(Instruction *Op, const ValueVector &CV) {
359   // Since we're not deleting Op yet, stub out its operands, so that it
360   // doesn't make anything live unnecessarily.
361   for (unsigned I = 0, E = Op->getNumOperands(); I != E; ++I)
362     Op->setOperand(I, UndefValue::get(Op->getOperand(I)->getType()));
363 
364   transferMetadata(Op, CV);
365 
366   // If we already have a scattered form of Op (created from ExtractElements
367   // of Op itself), replace them with the new form.
368   ValueVector &SV = Scattered[Op];
369   if (!SV.empty()) {
370     for (unsigned I = 0, E = SV.size(); I != E; ++I) {
371       Value *V = SV[I];
372       if (V == nullptr)
373         continue;
374 
375       Instruction *Old = cast<Instruction>(V);
376       CV[I]->takeName(Old);
377       Old->replaceAllUsesWith(CV[I]);
378       Old->eraseFromParent();
379     }
380   }
381   SV = CV;
382   Gathered.push_back(GatherList::value_type(Op, &SV));
383 }
384 
385 // Return true if it is safe to transfer the given metadata tag from
386 // vector to scalar instructions.
387 bool ScalarizerVisitor::canTransferMetadata(unsigned Tag) {
388   return (Tag == LLVMContext::MD_tbaa
389           || Tag == LLVMContext::MD_fpmath
390           || Tag == LLVMContext::MD_tbaa_struct
391           || Tag == LLVMContext::MD_invariant_load
392           || Tag == LLVMContext::MD_alias_scope
393           || Tag == LLVMContext::MD_noalias
394           || Tag == ParallelLoopAccessMDKind
395           || Tag == LLVMContext::MD_access_group);
396 }
397 
398 // Transfer metadata from Op to the instructions in CV if it is known
399 // to be safe to do so.
400 void ScalarizerVisitor::transferMetadata(Instruction *Op, const ValueVector &CV) {
401   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
402   Op->getAllMetadataOtherThanDebugLoc(MDs);
403   for (unsigned I = 0, E = CV.size(); I != E; ++I) {
404     if (Instruction *New = dyn_cast<Instruction>(CV[I])) {
405       for (const auto &MD : MDs)
406         if (canTransferMetadata(MD.first))
407           New->setMetadata(MD.first, MD.second);
408       if (Op->getDebugLoc() && !New->getDebugLoc())
409         New->setDebugLoc(Op->getDebugLoc());
410     }
411   }
412 }
413 
414 // Try to fill in Layout from Ty, returning true on success.  Alignment is
415 // the alignment of the vector, or 0 if the ABI default should be used.
416 bool ScalarizerVisitor::getVectorLayout(Type *Ty, unsigned Alignment,
417                                  VectorLayout &Layout, const DataLayout &DL) {
418   // Make sure we're dealing with a vector.
419   Layout.VecTy = dyn_cast<VectorType>(Ty);
420   if (!Layout.VecTy)
421     return false;
422 
423   // Check that we're dealing with full-byte elements.
424   Layout.ElemTy = Layout.VecTy->getElementType();
425   if (!DL.typeSizeEqualsStoreSize(Layout.ElemTy))
426     return false;
427 
428   if (Alignment)
429     Layout.VecAlign = Alignment;
430   else
431     Layout.VecAlign = DL.getABITypeAlignment(Layout.VecTy);
432   Layout.ElemSize = DL.getTypeStoreSize(Layout.ElemTy);
433   return true;
434 }
435 
436 // Scalarize one-operand instruction I, using Split(Builder, X, Name)
437 // to create an instruction like I with operand X and name Name.
438 template<typename Splitter>
439 bool ScalarizerVisitor::splitUnary(Instruction &I, const Splitter &Split) {
440   VectorType *VT = dyn_cast<VectorType>(I.getType());
441   if (!VT)
442     return false;
443 
444   unsigned NumElems = VT->getNumElements();
445   IRBuilder<> Builder(&I);
446   Scatterer Op = scatter(&I, I.getOperand(0));
447   assert(Op.size() == NumElems && "Mismatched unary operation");
448   ValueVector Res;
449   Res.resize(NumElems);
450   for (unsigned Elem = 0; Elem < NumElems; ++Elem)
451     Res[Elem] = Split(Builder, Op[Elem], I.getName() + ".i" + Twine(Elem));
452   gather(&I, Res);
453   return true;
454 }
455 
456 // Scalarize two-operand instruction I, using Split(Builder, X, Y, Name)
457 // to create an instruction like I with operands X and Y and name Name.
458 template<typename Splitter>
459 bool ScalarizerVisitor::splitBinary(Instruction &I, const Splitter &Split) {
460   VectorType *VT = dyn_cast<VectorType>(I.getType());
461   if (!VT)
462     return false;
463 
464   unsigned NumElems = VT->getNumElements();
465   IRBuilder<> Builder(&I);
466   Scatterer Op0 = scatter(&I, I.getOperand(0));
467   Scatterer Op1 = scatter(&I, I.getOperand(1));
468   assert(Op0.size() == NumElems && "Mismatched binary operation");
469   assert(Op1.size() == NumElems && "Mismatched binary operation");
470   ValueVector Res;
471   Res.resize(NumElems);
472   for (unsigned Elem = 0; Elem < NumElems; ++Elem)
473     Res[Elem] = Split(Builder, Op0[Elem], Op1[Elem],
474                       I.getName() + ".i" + Twine(Elem));
475   gather(&I, Res);
476   return true;
477 }
478 
479 static bool isTriviallyScalariable(Intrinsic::ID ID) {
480   return isTriviallyVectorizable(ID);
481 }
482 
483 // All of the current scalarizable intrinsics only have one mangled type.
484 static Function *getScalarIntrinsicDeclaration(Module *M,
485                                                Intrinsic::ID ID,
486                                                VectorType *Ty) {
487   return Intrinsic::getDeclaration(M, ID, { Ty->getScalarType() });
488 }
489 
490 /// If a call to a vector typed intrinsic function, split into a scalar call per
491 /// element if possible for the intrinsic.
492 bool ScalarizerVisitor::splitCall(CallInst &CI) {
493   VectorType *VT = dyn_cast<VectorType>(CI.getType());
494   if (!VT)
495     return false;
496 
497   Function *F = CI.getCalledFunction();
498   if (!F)
499     return false;
500 
501   Intrinsic::ID ID = F->getIntrinsicID();
502   if (ID == Intrinsic::not_intrinsic || !isTriviallyScalariable(ID))
503     return false;
504 
505   unsigned NumElems = VT->getNumElements();
506   unsigned NumArgs = CI.getNumArgOperands();
507 
508   ValueVector ScalarOperands(NumArgs);
509   SmallVector<Scatterer, 8> Scattered(NumArgs);
510 
511   Scattered.resize(NumArgs);
512 
513   // Assumes that any vector type has the same number of elements as the return
514   // vector type, which is true for all current intrinsics.
515   for (unsigned I = 0; I != NumArgs; ++I) {
516     Value *OpI = CI.getOperand(I);
517     if (OpI->getType()->isVectorTy()) {
518       Scattered[I] = scatter(&CI, OpI);
519       assert(Scattered[I].size() == NumElems && "mismatched call operands");
520     } else {
521       ScalarOperands[I] = OpI;
522     }
523   }
524 
525   ValueVector Res(NumElems);
526   ValueVector ScalarCallOps(NumArgs);
527 
528   Function *NewIntrin = getScalarIntrinsicDeclaration(F->getParent(), ID, VT);
529   IRBuilder<> Builder(&CI);
530 
531   // Perform actual scalarization, taking care to preserve any scalar operands.
532   for (unsigned Elem = 0; Elem < NumElems; ++Elem) {
533     ScalarCallOps.clear();
534 
535     for (unsigned J = 0; J != NumArgs; ++J) {
536       if (hasVectorInstrinsicScalarOpd(ID, J))
537         ScalarCallOps.push_back(ScalarOperands[J]);
538       else
539         ScalarCallOps.push_back(Scattered[J][Elem]);
540     }
541 
542     Res[Elem] = Builder.CreateCall(NewIntrin, ScalarCallOps,
543                                    CI.getName() + ".i" + Twine(Elem));
544   }
545 
546   gather(&CI, Res);
547   return true;
548 }
549 
550 bool ScalarizerVisitor::visitSelectInst(SelectInst &SI) {
551   VectorType *VT = dyn_cast<VectorType>(SI.getType());
552   if (!VT)
553     return false;
554 
555   unsigned NumElems = VT->getNumElements();
556   IRBuilder<> Builder(&SI);
557   Scatterer Op1 = scatter(&SI, SI.getOperand(1));
558   Scatterer Op2 = scatter(&SI, SI.getOperand(2));
559   assert(Op1.size() == NumElems && "Mismatched select");
560   assert(Op2.size() == NumElems && "Mismatched select");
561   ValueVector Res;
562   Res.resize(NumElems);
563 
564   if (SI.getOperand(0)->getType()->isVectorTy()) {
565     Scatterer Op0 = scatter(&SI, SI.getOperand(0));
566     assert(Op0.size() == NumElems && "Mismatched select");
567     for (unsigned I = 0; I < NumElems; ++I)
568       Res[I] = Builder.CreateSelect(Op0[I], Op1[I], Op2[I],
569                                     SI.getName() + ".i" + Twine(I));
570   } else {
571     Value *Op0 = SI.getOperand(0);
572     for (unsigned I = 0; I < NumElems; ++I)
573       Res[I] = Builder.CreateSelect(Op0, Op1[I], Op2[I],
574                                     SI.getName() + ".i" + Twine(I));
575   }
576   gather(&SI, Res);
577   return true;
578 }
579 
580 bool ScalarizerVisitor::visitICmpInst(ICmpInst &ICI) {
581   return splitBinary(ICI, ICmpSplitter(ICI));
582 }
583 
584 bool ScalarizerVisitor::visitFCmpInst(FCmpInst &FCI) {
585   return splitBinary(FCI, FCmpSplitter(FCI));
586 }
587 
588 bool ScalarizerVisitor::visitUnaryOperator(UnaryOperator &UO) {
589   return splitUnary(UO, UnarySplitter(UO));
590 }
591 
592 bool ScalarizerVisitor::visitBinaryOperator(BinaryOperator &BO) {
593   return splitBinary(BO, BinarySplitter(BO));
594 }
595 
596 bool ScalarizerVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
597   VectorType *VT = dyn_cast<VectorType>(GEPI.getType());
598   if (!VT)
599     return false;
600 
601   IRBuilder<> Builder(&GEPI);
602   unsigned NumElems = VT->getNumElements();
603   unsigned NumIndices = GEPI.getNumIndices();
604 
605   // The base pointer might be scalar even if it's a vector GEP. In those cases,
606   // splat the pointer into a vector value, and scatter that vector.
607   Value *Op0 = GEPI.getOperand(0);
608   if (!Op0->getType()->isVectorTy())
609     Op0 = Builder.CreateVectorSplat(NumElems, Op0);
610   Scatterer Base = scatter(&GEPI, Op0);
611 
612   SmallVector<Scatterer, 8> Ops;
613   Ops.resize(NumIndices);
614   for (unsigned I = 0; I < NumIndices; ++I) {
615     Value *Op = GEPI.getOperand(I + 1);
616 
617     // The indices might be scalars even if it's a vector GEP. In those cases,
618     // splat the scalar into a vector value, and scatter that vector.
619     if (!Op->getType()->isVectorTy())
620       Op = Builder.CreateVectorSplat(NumElems, Op);
621 
622     Ops[I] = scatter(&GEPI, Op);
623   }
624 
625   ValueVector Res;
626   Res.resize(NumElems);
627   for (unsigned I = 0; I < NumElems; ++I) {
628     SmallVector<Value *, 8> Indices;
629     Indices.resize(NumIndices);
630     for (unsigned J = 0; J < NumIndices; ++J)
631       Indices[J] = Ops[J][I];
632     Res[I] = Builder.CreateGEP(GEPI.getSourceElementType(), Base[I], Indices,
633                                GEPI.getName() + ".i" + Twine(I));
634     if (GEPI.isInBounds())
635       if (GetElementPtrInst *NewGEPI = dyn_cast<GetElementPtrInst>(Res[I]))
636         NewGEPI->setIsInBounds();
637   }
638   gather(&GEPI, Res);
639   return true;
640 }
641 
642 bool ScalarizerVisitor::visitCastInst(CastInst &CI) {
643   VectorType *VT = dyn_cast<VectorType>(CI.getDestTy());
644   if (!VT)
645     return false;
646 
647   unsigned NumElems = VT->getNumElements();
648   IRBuilder<> Builder(&CI);
649   Scatterer Op0 = scatter(&CI, CI.getOperand(0));
650   assert(Op0.size() == NumElems && "Mismatched cast");
651   ValueVector Res;
652   Res.resize(NumElems);
653   for (unsigned I = 0; I < NumElems; ++I)
654     Res[I] = Builder.CreateCast(CI.getOpcode(), Op0[I], VT->getElementType(),
655                                 CI.getName() + ".i" + Twine(I));
656   gather(&CI, Res);
657   return true;
658 }
659 
660 bool ScalarizerVisitor::visitBitCastInst(BitCastInst &BCI) {
661   VectorType *DstVT = dyn_cast<VectorType>(BCI.getDestTy());
662   VectorType *SrcVT = dyn_cast<VectorType>(BCI.getSrcTy());
663   if (!DstVT || !SrcVT)
664     return false;
665 
666   unsigned DstNumElems = DstVT->getNumElements();
667   unsigned SrcNumElems = SrcVT->getNumElements();
668   IRBuilder<> Builder(&BCI);
669   Scatterer Op0 = scatter(&BCI, BCI.getOperand(0));
670   ValueVector Res;
671   Res.resize(DstNumElems);
672 
673   if (DstNumElems == SrcNumElems) {
674     for (unsigned I = 0; I < DstNumElems; ++I)
675       Res[I] = Builder.CreateBitCast(Op0[I], DstVT->getElementType(),
676                                      BCI.getName() + ".i" + Twine(I));
677   } else if (DstNumElems > SrcNumElems) {
678     // <M x t1> -> <N*M x t2>.  Convert each t1 to <N x t2> and copy the
679     // individual elements to the destination.
680     unsigned FanOut = DstNumElems / SrcNumElems;
681     Type *MidTy = VectorType::get(DstVT->getElementType(), FanOut);
682     unsigned ResI = 0;
683     for (unsigned Op0I = 0; Op0I < SrcNumElems; ++Op0I) {
684       Value *V = Op0[Op0I];
685       Instruction *VI;
686       // Look through any existing bitcasts before converting to <N x t2>.
687       // In the best case, the resulting conversion might be a no-op.
688       while ((VI = dyn_cast<Instruction>(V)) &&
689              VI->getOpcode() == Instruction::BitCast)
690         V = VI->getOperand(0);
691       V = Builder.CreateBitCast(V, MidTy, V->getName() + ".cast");
692       Scatterer Mid = scatter(&BCI, V);
693       for (unsigned MidI = 0; MidI < FanOut; ++MidI)
694         Res[ResI++] = Mid[MidI];
695     }
696   } else {
697     // <N*M x t1> -> <M x t2>.  Convert each group of <N x t1> into a t2.
698     unsigned FanIn = SrcNumElems / DstNumElems;
699     Type *MidTy = VectorType::get(SrcVT->getElementType(), FanIn);
700     unsigned Op0I = 0;
701     for (unsigned ResI = 0; ResI < DstNumElems; ++ResI) {
702       Value *V = UndefValue::get(MidTy);
703       for (unsigned MidI = 0; MidI < FanIn; ++MidI)
704         V = Builder.CreateInsertElement(V, Op0[Op0I++], Builder.getInt32(MidI),
705                                         BCI.getName() + ".i" + Twine(ResI)
706                                         + ".upto" + Twine(MidI));
707       Res[ResI] = Builder.CreateBitCast(V, DstVT->getElementType(),
708                                         BCI.getName() + ".i" + Twine(ResI));
709     }
710   }
711   gather(&BCI, Res);
712   return true;
713 }
714 
715 bool ScalarizerVisitor::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
716   VectorType *VT = dyn_cast<VectorType>(SVI.getType());
717   if (!VT)
718     return false;
719 
720   unsigned NumElems = VT->getNumElements();
721   Scatterer Op0 = scatter(&SVI, SVI.getOperand(0));
722   Scatterer Op1 = scatter(&SVI, SVI.getOperand(1));
723   ValueVector Res;
724   Res.resize(NumElems);
725 
726   for (unsigned I = 0; I < NumElems; ++I) {
727     int Selector = SVI.getMaskValue(I);
728     if (Selector < 0)
729       Res[I] = UndefValue::get(VT->getElementType());
730     else if (unsigned(Selector) < Op0.size())
731       Res[I] = Op0[Selector];
732     else
733       Res[I] = Op1[Selector - Op0.size()];
734   }
735   gather(&SVI, Res);
736   return true;
737 }
738 
739 bool ScalarizerVisitor::visitPHINode(PHINode &PHI) {
740   VectorType *VT = dyn_cast<VectorType>(PHI.getType());
741   if (!VT)
742     return false;
743 
744   unsigned NumElems = VT->getNumElements();
745   IRBuilder<> Builder(&PHI);
746   ValueVector Res;
747   Res.resize(NumElems);
748 
749   unsigned NumOps = PHI.getNumOperands();
750   for (unsigned I = 0; I < NumElems; ++I)
751     Res[I] = Builder.CreatePHI(VT->getElementType(), NumOps,
752                                PHI.getName() + ".i" + Twine(I));
753 
754   for (unsigned I = 0; I < NumOps; ++I) {
755     Scatterer Op = scatter(&PHI, PHI.getIncomingValue(I));
756     BasicBlock *IncomingBlock = PHI.getIncomingBlock(I);
757     for (unsigned J = 0; J < NumElems; ++J)
758       cast<PHINode>(Res[J])->addIncoming(Op[J], IncomingBlock);
759   }
760   gather(&PHI, Res);
761   return true;
762 }
763 
764 bool ScalarizerVisitor::visitLoadInst(LoadInst &LI) {
765   if (!ScalarizeLoadStore)
766     return false;
767   if (!LI.isSimple())
768     return false;
769 
770   VectorLayout Layout;
771   if (!getVectorLayout(LI.getType(), LI.getAlignment(), Layout,
772                        LI.getModule()->getDataLayout()))
773     return false;
774 
775   unsigned NumElems = Layout.VecTy->getNumElements();
776   IRBuilder<> Builder(&LI);
777   Scatterer Ptr = scatter(&LI, LI.getPointerOperand());
778   ValueVector Res;
779   Res.resize(NumElems);
780 
781   for (unsigned I = 0; I < NumElems; ++I)
782     Res[I] = Builder.CreateAlignedLoad(Layout.VecTy->getElementType(), Ptr[I],
783                                        Layout.getElemAlign(I),
784                                        LI.getName() + ".i" + Twine(I));
785   gather(&LI, Res);
786   return true;
787 }
788 
789 bool ScalarizerVisitor::visitStoreInst(StoreInst &SI) {
790   if (!ScalarizeLoadStore)
791     return false;
792   if (!SI.isSimple())
793     return false;
794 
795   VectorLayout Layout;
796   Value *FullValue = SI.getValueOperand();
797   if (!getVectorLayout(FullValue->getType(), SI.getAlignment(), Layout,
798                        SI.getModule()->getDataLayout()))
799     return false;
800 
801   unsigned NumElems = Layout.VecTy->getNumElements();
802   IRBuilder<> Builder(&SI);
803   Scatterer Ptr = scatter(&SI, SI.getPointerOperand());
804   Scatterer Val = scatter(&SI, FullValue);
805 
806   ValueVector Stores;
807   Stores.resize(NumElems);
808   for (unsigned I = 0; I < NumElems; ++I) {
809     unsigned Align = Layout.getElemAlign(I);
810     Stores[I] = Builder.CreateAlignedStore(Val[I], Ptr[I], Align);
811   }
812   transferMetadata(&SI, Stores);
813   return true;
814 }
815 
816 bool ScalarizerVisitor::visitCallInst(CallInst &CI) {
817   return splitCall(CI);
818 }
819 
820 // Delete the instructions that we scalarized.  If a full vector result
821 // is still needed, recreate it using InsertElements.
822 bool ScalarizerVisitor::finish() {
823   // The presence of data in Gathered or Scattered indicates changes
824   // made to the Function.
825   if (Gathered.empty() && Scattered.empty())
826     return false;
827   for (const auto &GMI : Gathered) {
828     Instruction *Op = GMI.first;
829     ValueVector &CV = *GMI.second;
830     if (!Op->use_empty()) {
831       // The value is still needed, so recreate it using a series of
832       // InsertElements.
833       Type *Ty = Op->getType();
834       Value *Res = UndefValue::get(Ty);
835       BasicBlock *BB = Op->getParent();
836       unsigned Count = Ty->getVectorNumElements();
837       IRBuilder<> Builder(Op);
838       if (isa<PHINode>(Op))
839         Builder.SetInsertPoint(BB, BB->getFirstInsertionPt());
840       for (unsigned I = 0; I < Count; ++I)
841         Res = Builder.CreateInsertElement(Res, CV[I], Builder.getInt32(I),
842                                           Op->getName() + ".upto" + Twine(I));
843       Res->takeName(Op);
844       Op->replaceAllUsesWith(Res);
845     }
846     Op->eraseFromParent();
847   }
848   Gathered.clear();
849   Scattered.clear();
850   return true;
851 }
852 
853 PreservedAnalyses ScalarizerPass::run(Function &F, FunctionAnalysisManager &AM) {
854   Module &M = *F.getParent();
855   unsigned ParallelLoopAccessMDKind =
856       M.getContext().getMDKindID("llvm.mem.parallel_loop_access");
857   ScalarizerVisitor Impl(ParallelLoopAccessMDKind);
858   bool Changed = Impl.visit(F);
859   return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
860 }
861