[Scalarizer] Fix potential for stale data in Scattered across invocations
[oota-llvm.git] / lib / Transforms / Scalar / Scalarizer.cpp
1 //===--- Scalarizer.cpp - Scalarize vector operations ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass converts vector operations into scalar operations, in order
11 // to expose optimization opportunities on the individual scalar operations.
12 // It is mainly intended for targets that do not have vector units, but it
13 // may also be useful for revectorizing code to different vector widths.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/IR/IRBuilder.h"
19 #include "llvm/IR/InstVisitor.h"
20 #include "llvm/Pass.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
24
25 using namespace llvm;
26
27 #define DEBUG_TYPE "scalarizer"
28
29 namespace {
30 // Used to store the scattered form of a vector.
31 typedef SmallVector<Value *, 8> ValueVector;
32
33 // Used to map a vector Value to its scattered form.  We use std::map
34 // because we want iterators to persist across insertion and because the
35 // values are relatively large.
36 typedef std::map<Value *, ValueVector> ScatterMap;
37
38 // Lists Instructions that have been replaced with scalar implementations,
39 // along with a pointer to their scattered forms.
40 typedef SmallVector<std::pair<Instruction *, ValueVector *>, 16> GatherList;
41
42 // Provides a very limited vector-like interface for lazily accessing one
43 // component of a scattered vector or vector pointer.
44 class Scatterer {
45 public:
46   Scatterer() {}
47
48   // Scatter V into Size components.  If new instructions are needed,
49   // insert them before BBI in BB.  If Cache is nonnull, use it to cache
50   // the results.
51   Scatterer(BasicBlock *bb, BasicBlock::iterator bbi, Value *v,
52             ValueVector *cachePtr = nullptr);
53
54   // Return component I, creating a new Value for it if necessary.
55   Value *operator[](unsigned I);
56
57   // Return the number of components.
58   unsigned size() const { return Size; }
59
60 private:
61   BasicBlock *BB;
62   BasicBlock::iterator BBI;
63   Value *V;
64   ValueVector *CachePtr;
65   PointerType *PtrTy;
66   ValueVector Tmp;
67   unsigned Size;
68 };
69
70 // FCmpSpliiter(FCI)(Builder, X, Y, Name) uses Builder to create an FCmp
71 // called Name that compares X and Y in the same way as FCI.
72 struct FCmpSplitter {
73   FCmpSplitter(FCmpInst &fci) : FCI(fci) {}
74   Value *operator()(IRBuilder<> &Builder, Value *Op0, Value *Op1,
75                     const Twine &Name) const {
76     return Builder.CreateFCmp(FCI.getPredicate(), Op0, Op1, Name);
77   }
78   FCmpInst &FCI;
79 };
80
81 // ICmpSpliiter(ICI)(Builder, X, Y, Name) uses Builder to create an ICmp
82 // called Name that compares X and Y in the same way as ICI.
83 struct ICmpSplitter {
84   ICmpSplitter(ICmpInst &ici) : ICI(ici) {}
85   Value *operator()(IRBuilder<> &Builder, Value *Op0, Value *Op1,
86                     const Twine &Name) const {
87     return Builder.CreateICmp(ICI.getPredicate(), Op0, Op1, Name);
88   }
89   ICmpInst &ICI;
90 };
91
92 // BinarySpliiter(BO)(Builder, X, Y, Name) uses Builder to create
93 // a binary operator like BO called Name with operands X and Y.
94 struct BinarySplitter {
95   BinarySplitter(BinaryOperator &bo) : BO(bo) {}
96   Value *operator()(IRBuilder<> &Builder, Value *Op0, Value *Op1,
97                     const Twine &Name) const {
98     return Builder.CreateBinOp(BO.getOpcode(), Op0, Op1, Name);
99   }
100   BinaryOperator &BO;
101 };
102
103 // Information about a load or store that we're scalarizing.
104 struct VectorLayout {
105   VectorLayout() : VecTy(nullptr), ElemTy(nullptr), VecAlign(0), ElemSize(0) {}
106
107   // Return the alignment of element I.
108   uint64_t getElemAlign(unsigned I) {
109     return MinAlign(VecAlign, I * ElemSize);
110   }
111
112   // The type of the vector.
113   VectorType *VecTy;
114
115   // The type of each element.
116   Type *ElemTy;
117
118   // The alignment of the vector.
119   uint64_t VecAlign;
120
121   // The size of each element.
122   uint64_t ElemSize;
123 };
124
125 class Scalarizer : public FunctionPass,
126                    public InstVisitor<Scalarizer, bool> {
127 public:
128   static char ID;
129
130   Scalarizer() :
131     FunctionPass(ID) {
132     initializeScalarizerPass(*PassRegistry::getPassRegistry());
133   }
134
135   bool doInitialization(Module &M) override;
136   bool runOnFunction(Function &F) override;
137
138   // InstVisitor methods.  They return true if the instruction was scalarized,
139   // false if nothing changed.
140   bool visitInstruction(Instruction &) { return false; }
141   bool visitSelectInst(SelectInst &SI);
142   bool visitICmpInst(ICmpInst &);
143   bool visitFCmpInst(FCmpInst &);
144   bool visitBinaryOperator(BinaryOperator &);
145   bool visitGetElementPtrInst(GetElementPtrInst &);
146   bool visitCastInst(CastInst &);
147   bool visitBitCastInst(BitCastInst &);
148   bool visitShuffleVectorInst(ShuffleVectorInst &);
149   bool visitPHINode(PHINode &);
150   bool visitLoadInst(LoadInst &);
151   bool visitStoreInst(StoreInst &);
152
153   static void registerOptions() {
154     // This is disabled by default because having separate loads and stores
155     // makes it more likely that the -combiner-alias-analysis limits will be
156     // reached.
157     OptionRegistry::registerOption<bool, Scalarizer,
158                                  &Scalarizer::ScalarizeLoadStore>(
159         "scalarize-load-store",
160         "Allow the scalarizer pass to scalarize loads and store", false);
161   }
162
163 private:
164   Scatterer scatter(Instruction *, Value *);
165   void gather(Instruction *, const ValueVector &);
166   bool canTransferMetadata(unsigned Kind);
167   void transferMetadata(Instruction *, const ValueVector &);
168   bool getVectorLayout(Type *, unsigned, VectorLayout &, const DataLayout &);
169   bool finish();
170
171   template<typename T> bool splitBinary(Instruction &, const T &);
172
173   ScatterMap Scattered;
174   GatherList Gathered;
175   unsigned ParallelLoopAccessMDKind;
176   bool ScalarizeLoadStore;
177 };
178
179 char Scalarizer::ID = 0;
180 } // end anonymous namespace
181
182 INITIALIZE_PASS_WITH_OPTIONS(Scalarizer, "scalarizer",
183                              "Scalarize vector operations", false, false)
184
185 Scatterer::Scatterer(BasicBlock *bb, BasicBlock::iterator bbi, Value *v,
186                      ValueVector *cachePtr)
187   : BB(bb), BBI(bbi), V(v), CachePtr(cachePtr) {
188   Type *Ty = V->getType();
189   PtrTy = dyn_cast<PointerType>(Ty);
190   if (PtrTy)
191     Ty = PtrTy->getElementType();
192   Size = Ty->getVectorNumElements();
193   if (!CachePtr)
194     Tmp.resize(Size, nullptr);
195   else if (CachePtr->empty())
196     CachePtr->resize(Size, nullptr);
197   else
198     assert(Size == CachePtr->size() && "Inconsistent vector sizes");
199 }
200
201 // Return component I, creating a new Value for it if necessary.
202 Value *Scatterer::operator[](unsigned I) {
203   ValueVector &CV = (CachePtr ? *CachePtr : Tmp);
204   // Try to reuse a previous value.
205   if (CV[I])
206     return CV[I];
207   IRBuilder<> Builder(BB, BBI);
208   if (PtrTy) {
209     if (!CV[0]) {
210       Type *Ty =
211         PointerType::get(PtrTy->getElementType()->getVectorElementType(),
212                          PtrTy->getAddressSpace());
213       CV[0] = Builder.CreateBitCast(V, Ty, V->getName() + ".i0");
214     }
215     if (I != 0)
216       CV[I] = Builder.CreateConstGEP1_32(nullptr, CV[0], I,
217                                          V->getName() + ".i" + Twine(I));
218   } else {
219     // Search through a chain of InsertElementInsts looking for element I.
220     // Record other elements in the cache.  The new V is still suitable
221     // for all uncached indices.
222     for (;;) {
223       InsertElementInst *Insert = dyn_cast<InsertElementInst>(V);
224       if (!Insert)
225         break;
226       ConstantInt *Idx = dyn_cast<ConstantInt>(Insert->getOperand(2));
227       if (!Idx)
228         break;
229       unsigned J = Idx->getZExtValue();
230       CV[J] = Insert->getOperand(1);
231       V = Insert->getOperand(0);
232       if (I == J)
233         return CV[J];
234     }
235     CV[I] = Builder.CreateExtractElement(V, Builder.getInt32(I),
236                                          V->getName() + ".i" + Twine(I));
237   }
238   return CV[I];
239 }
240
241 bool Scalarizer::doInitialization(Module &M) {
242   ParallelLoopAccessMDKind =
243       M.getContext().getMDKindID("llvm.mem.parallel_loop_access");
244   ScalarizeLoadStore =
245       M.getContext().getOption<bool, Scalarizer, &Scalarizer::ScalarizeLoadStore>();
246   return false;
247 }
248
249 bool Scalarizer::runOnFunction(Function &F) {
250   assert(Gathered.empty() && Scattered.empty());
251   for (Function::iterator BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
252     BasicBlock *BB = BBI;
253     for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
254       Instruction *I = II;
255       bool Done = visit(I);
256       ++II;
257       if (Done && I->getType()->isVoidTy())
258         I->eraseFromParent();
259     }
260   }
261   return finish();
262 }
263
264 // Return a scattered form of V that can be accessed by Point.  V must be a
265 // vector or a pointer to a vector.
266 Scatterer Scalarizer::scatter(Instruction *Point, Value *V) {
267   if (Argument *VArg = dyn_cast<Argument>(V)) {
268     // Put the scattered form of arguments in the entry block,
269     // so that it can be used everywhere.
270     Function *F = VArg->getParent();
271     BasicBlock *BB = &F->getEntryBlock();
272     return Scatterer(BB, BB->begin(), V, &Scattered[V]);
273   }
274   if (Instruction *VOp = dyn_cast<Instruction>(V)) {
275     // Put the scattered form of an instruction directly after the
276     // instruction.
277     BasicBlock *BB = VOp->getParent();
278     return Scatterer(BB, std::next(BasicBlock::iterator(VOp)),
279                      V, &Scattered[V]);
280   }
281   // In the fallback case, just put the scattered before Point and
282   // keep the result local to Point.
283   return Scatterer(Point->getParent(), Point, V);
284 }
285
286 // Replace Op with the gathered form of the components in CV.  Defer the
287 // deletion of Op and creation of the gathered form to the end of the pass,
288 // so that we can avoid creating the gathered form if all uses of Op are
289 // replaced with uses of CV.
290 void Scalarizer::gather(Instruction *Op, const ValueVector &CV) {
291   // Since we're not deleting Op yet, stub out its operands, so that it
292   // doesn't make anything live unnecessarily.
293   for (unsigned I = 0, E = Op->getNumOperands(); I != E; ++I)
294     Op->setOperand(I, UndefValue::get(Op->getOperand(I)->getType()));
295
296   transferMetadata(Op, CV);
297
298   // If we already have a scattered form of Op (created from ExtractElements
299   // of Op itself), replace them with the new form.
300   ValueVector &SV = Scattered[Op];
301   if (!SV.empty()) {
302     for (unsigned I = 0, E = SV.size(); I != E; ++I) {
303       Instruction *Old = cast<Instruction>(SV[I]);
304       CV[I]->takeName(Old);
305       Old->replaceAllUsesWith(CV[I]);
306       Old->eraseFromParent();
307     }
308   }
309   SV = CV;
310   Gathered.push_back(GatherList::value_type(Op, &SV));
311 }
312
313 // Return true if it is safe to transfer the given metadata tag from
314 // vector to scalar instructions.
315 bool Scalarizer::canTransferMetadata(unsigned Tag) {
316   return (Tag == LLVMContext::MD_tbaa
317           || Tag == LLVMContext::MD_fpmath
318           || Tag == LLVMContext::MD_tbaa_struct
319           || Tag == LLVMContext::MD_invariant_load
320           || Tag == LLVMContext::MD_alias_scope
321           || Tag == LLVMContext::MD_noalias
322           || Tag == ParallelLoopAccessMDKind);
323 }
324
325 // Transfer metadata from Op to the instructions in CV if it is known
326 // to be safe to do so.
327 void Scalarizer::transferMetadata(Instruction *Op, const ValueVector &CV) {
328   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
329   Op->getAllMetadataOtherThanDebugLoc(MDs);
330   for (unsigned I = 0, E = CV.size(); I != E; ++I) {
331     if (Instruction *New = dyn_cast<Instruction>(CV[I])) {
332       for (SmallVectorImpl<std::pair<unsigned, MDNode *>>::iterator
333                MI = MDs.begin(),
334                ME = MDs.end();
335            MI != ME; ++MI)
336         if (canTransferMetadata(MI->first))
337           New->setMetadata(MI->first, MI->second);
338       New->setDebugLoc(Op->getDebugLoc());
339     }
340   }
341 }
342
343 // Try to fill in Layout from Ty, returning true on success.  Alignment is
344 // the alignment of the vector, or 0 if the ABI default should be used.
345 bool Scalarizer::getVectorLayout(Type *Ty, unsigned Alignment,
346                                  VectorLayout &Layout, const DataLayout &DL) {
347   // Make sure we're dealing with a vector.
348   Layout.VecTy = dyn_cast<VectorType>(Ty);
349   if (!Layout.VecTy)
350     return false;
351
352   // Check that we're dealing with full-byte elements.
353   Layout.ElemTy = Layout.VecTy->getElementType();
354   if (DL.getTypeSizeInBits(Layout.ElemTy) !=
355       DL.getTypeStoreSizeInBits(Layout.ElemTy))
356     return false;
357
358   if (Alignment)
359     Layout.VecAlign = Alignment;
360   else
361     Layout.VecAlign = DL.getABITypeAlignment(Layout.VecTy);
362   Layout.ElemSize = DL.getTypeStoreSize(Layout.ElemTy);
363   return true;
364 }
365
366 // Scalarize two-operand instruction I, using Split(Builder, X, Y, Name)
367 // to create an instruction like I with operands X and Y and name Name.
368 template<typename Splitter>
369 bool Scalarizer::splitBinary(Instruction &I, const Splitter &Split) {
370   VectorType *VT = dyn_cast<VectorType>(I.getType());
371   if (!VT)
372     return false;
373
374   unsigned NumElems = VT->getNumElements();
375   IRBuilder<> Builder(I.getParent(), &I);
376   Scatterer Op0 = scatter(&I, I.getOperand(0));
377   Scatterer Op1 = scatter(&I, I.getOperand(1));
378   assert(Op0.size() == NumElems && "Mismatched binary operation");
379   assert(Op1.size() == NumElems && "Mismatched binary operation");
380   ValueVector Res;
381   Res.resize(NumElems);
382   for (unsigned Elem = 0; Elem < NumElems; ++Elem)
383     Res[Elem] = Split(Builder, Op0[Elem], Op1[Elem],
384                       I.getName() + ".i" + Twine(Elem));
385   gather(&I, Res);
386   return true;
387 }
388
389 bool Scalarizer::visitSelectInst(SelectInst &SI) {
390   VectorType *VT = dyn_cast<VectorType>(SI.getType());
391   if (!VT)
392     return false;
393
394   unsigned NumElems = VT->getNumElements();
395   IRBuilder<> Builder(SI.getParent(), &SI);
396   Scatterer Op1 = scatter(&SI, SI.getOperand(1));
397   Scatterer Op2 = scatter(&SI, SI.getOperand(2));
398   assert(Op1.size() == NumElems && "Mismatched select");
399   assert(Op2.size() == NumElems && "Mismatched select");
400   ValueVector Res;
401   Res.resize(NumElems);
402
403   if (SI.getOperand(0)->getType()->isVectorTy()) {
404     Scatterer Op0 = scatter(&SI, SI.getOperand(0));
405     assert(Op0.size() == NumElems && "Mismatched select");
406     for (unsigned I = 0; I < NumElems; ++I)
407       Res[I] = Builder.CreateSelect(Op0[I], Op1[I], Op2[I],
408                                     SI.getName() + ".i" + Twine(I));
409   } else {
410     Value *Op0 = SI.getOperand(0);
411     for (unsigned I = 0; I < NumElems; ++I)
412       Res[I] = Builder.CreateSelect(Op0, Op1[I], Op2[I],
413                                     SI.getName() + ".i" + Twine(I));
414   }
415   gather(&SI, Res);
416   return true;
417 }
418
419 bool Scalarizer::visitICmpInst(ICmpInst &ICI) {
420   return splitBinary(ICI, ICmpSplitter(ICI));
421 }
422
423 bool Scalarizer::visitFCmpInst(FCmpInst &FCI) {
424   return splitBinary(FCI, FCmpSplitter(FCI));
425 }
426
427 bool Scalarizer::visitBinaryOperator(BinaryOperator &BO) {
428   return splitBinary(BO, BinarySplitter(BO));
429 }
430
431 bool Scalarizer::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
432   VectorType *VT = dyn_cast<VectorType>(GEPI.getType());
433   if (!VT)
434     return false;
435
436   IRBuilder<> Builder(GEPI.getParent(), &GEPI);
437   unsigned NumElems = VT->getNumElements();
438   unsigned NumIndices = GEPI.getNumIndices();
439
440   Scatterer Base = scatter(&GEPI, GEPI.getOperand(0));
441
442   SmallVector<Scatterer, 8> Ops;
443   Ops.resize(NumIndices);
444   for (unsigned I = 0; I < NumIndices; ++I)
445     Ops[I] = scatter(&GEPI, GEPI.getOperand(I + 1));
446
447   ValueVector Res;
448   Res.resize(NumElems);
449   for (unsigned I = 0; I < NumElems; ++I) {
450     SmallVector<Value *, 8> Indices;
451     Indices.resize(NumIndices);
452     for (unsigned J = 0; J < NumIndices; ++J)
453       Indices[J] = Ops[J][I];
454     Res[I] = Builder.CreateGEP(GEPI.getSourceElementType(), Base[I], Indices,
455                                GEPI.getName() + ".i" + Twine(I));
456     if (GEPI.isInBounds())
457       if (GetElementPtrInst *NewGEPI = dyn_cast<GetElementPtrInst>(Res[I]))
458         NewGEPI->setIsInBounds();
459   }
460   gather(&GEPI, Res);
461   return true;
462 }
463
464 bool Scalarizer::visitCastInst(CastInst &CI) {
465   VectorType *VT = dyn_cast<VectorType>(CI.getDestTy());
466   if (!VT)
467     return false;
468
469   unsigned NumElems = VT->getNumElements();
470   IRBuilder<> Builder(CI.getParent(), &CI);
471   Scatterer Op0 = scatter(&CI, CI.getOperand(0));
472   assert(Op0.size() == NumElems && "Mismatched cast");
473   ValueVector Res;
474   Res.resize(NumElems);
475   for (unsigned I = 0; I < NumElems; ++I)
476     Res[I] = Builder.CreateCast(CI.getOpcode(), Op0[I], VT->getElementType(),
477                                 CI.getName() + ".i" + Twine(I));
478   gather(&CI, Res);
479   return true;
480 }
481
482 bool Scalarizer::visitBitCastInst(BitCastInst &BCI) {
483   VectorType *DstVT = dyn_cast<VectorType>(BCI.getDestTy());
484   VectorType *SrcVT = dyn_cast<VectorType>(BCI.getSrcTy());
485   if (!DstVT || !SrcVT)
486     return false;
487
488   unsigned DstNumElems = DstVT->getNumElements();
489   unsigned SrcNumElems = SrcVT->getNumElements();
490   IRBuilder<> Builder(BCI.getParent(), &BCI);
491   Scatterer Op0 = scatter(&BCI, BCI.getOperand(0));
492   ValueVector Res;
493   Res.resize(DstNumElems);
494
495   if (DstNumElems == SrcNumElems) {
496     for (unsigned I = 0; I < DstNumElems; ++I)
497       Res[I] = Builder.CreateBitCast(Op0[I], DstVT->getElementType(),
498                                      BCI.getName() + ".i" + Twine(I));
499   } else if (DstNumElems > SrcNumElems) {
500     // <M x t1> -> <N*M x t2>.  Convert each t1 to <N x t2> and copy the
501     // individual elements to the destination.
502     unsigned FanOut = DstNumElems / SrcNumElems;
503     Type *MidTy = VectorType::get(DstVT->getElementType(), FanOut);
504     unsigned ResI = 0;
505     for (unsigned Op0I = 0; Op0I < SrcNumElems; ++Op0I) {
506       Value *V = Op0[Op0I];
507       Instruction *VI;
508       // Look through any existing bitcasts before converting to <N x t2>.
509       // In the best case, the resulting conversion might be a no-op.
510       while ((VI = dyn_cast<Instruction>(V)) &&
511              VI->getOpcode() == Instruction::BitCast)
512         V = VI->getOperand(0);
513       V = Builder.CreateBitCast(V, MidTy, V->getName() + ".cast");
514       Scatterer Mid = scatter(&BCI, V);
515       for (unsigned MidI = 0; MidI < FanOut; ++MidI)
516         Res[ResI++] = Mid[MidI];
517     }
518   } else {
519     // <N*M x t1> -> <M x t2>.  Convert each group of <N x t1> into a t2.
520     unsigned FanIn = SrcNumElems / DstNumElems;
521     Type *MidTy = VectorType::get(SrcVT->getElementType(), FanIn);
522     unsigned Op0I = 0;
523     for (unsigned ResI = 0; ResI < DstNumElems; ++ResI) {
524       Value *V = UndefValue::get(MidTy);
525       for (unsigned MidI = 0; MidI < FanIn; ++MidI)
526         V = Builder.CreateInsertElement(V, Op0[Op0I++], Builder.getInt32(MidI),
527                                         BCI.getName() + ".i" + Twine(ResI)
528                                         + ".upto" + Twine(MidI));
529       Res[ResI] = Builder.CreateBitCast(V, DstVT->getElementType(),
530                                         BCI.getName() + ".i" + Twine(ResI));
531     }
532   }
533   gather(&BCI, Res);
534   return true;
535 }
536
537 bool Scalarizer::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
538   VectorType *VT = dyn_cast<VectorType>(SVI.getType());
539   if (!VT)
540     return false;
541
542   unsigned NumElems = VT->getNumElements();
543   Scatterer Op0 = scatter(&SVI, SVI.getOperand(0));
544   Scatterer Op1 = scatter(&SVI, SVI.getOperand(1));
545   ValueVector Res;
546   Res.resize(NumElems);
547
548   for (unsigned I = 0; I < NumElems; ++I) {
549     int Selector = SVI.getMaskValue(I);
550     if (Selector < 0)
551       Res[I] = UndefValue::get(VT->getElementType());
552     else if (unsigned(Selector) < Op0.size())
553       Res[I] = Op0[Selector];
554     else
555       Res[I] = Op1[Selector - Op0.size()];
556   }
557   gather(&SVI, Res);
558   return true;
559 }
560
561 bool Scalarizer::visitPHINode(PHINode &PHI) {
562   VectorType *VT = dyn_cast<VectorType>(PHI.getType());
563   if (!VT)
564     return false;
565
566   unsigned NumElems = VT->getNumElements();
567   IRBuilder<> Builder(PHI.getParent(), &PHI);
568   ValueVector Res;
569   Res.resize(NumElems);
570
571   unsigned NumOps = PHI.getNumOperands();
572   for (unsigned I = 0; I < NumElems; ++I)
573     Res[I] = Builder.CreatePHI(VT->getElementType(), NumOps,
574                                PHI.getName() + ".i" + Twine(I));
575
576   for (unsigned I = 0; I < NumOps; ++I) {
577     Scatterer Op = scatter(&PHI, PHI.getIncomingValue(I));
578     BasicBlock *IncomingBlock = PHI.getIncomingBlock(I);
579     for (unsigned J = 0; J < NumElems; ++J)
580       cast<PHINode>(Res[J])->addIncoming(Op[J], IncomingBlock);
581   }
582   gather(&PHI, Res);
583   return true;
584 }
585
586 bool Scalarizer::visitLoadInst(LoadInst &LI) {
587   if (!ScalarizeLoadStore)
588     return false;
589   if (!LI.isSimple())
590     return false;
591
592   VectorLayout Layout;
593   if (!getVectorLayout(LI.getType(), LI.getAlignment(), Layout,
594                        LI.getModule()->getDataLayout()))
595     return false;
596
597   unsigned NumElems = Layout.VecTy->getNumElements();
598   IRBuilder<> Builder(LI.getParent(), &LI);
599   Scatterer Ptr = scatter(&LI, LI.getPointerOperand());
600   ValueVector Res;
601   Res.resize(NumElems);
602
603   for (unsigned I = 0; I < NumElems; ++I)
604     Res[I] = Builder.CreateAlignedLoad(Ptr[I], Layout.getElemAlign(I),
605                                        LI.getName() + ".i" + Twine(I));
606   gather(&LI, Res);
607   return true;
608 }
609
610 bool Scalarizer::visitStoreInst(StoreInst &SI) {
611   if (!ScalarizeLoadStore)
612     return false;
613   if (!SI.isSimple())
614     return false;
615
616   VectorLayout Layout;
617   Value *FullValue = SI.getValueOperand();
618   if (!getVectorLayout(FullValue->getType(), SI.getAlignment(), Layout,
619                        SI.getModule()->getDataLayout()))
620     return false;
621
622   unsigned NumElems = Layout.VecTy->getNumElements();
623   IRBuilder<> Builder(SI.getParent(), &SI);
624   Scatterer Ptr = scatter(&SI, SI.getPointerOperand());
625   Scatterer Val = scatter(&SI, FullValue);
626
627   ValueVector Stores;
628   Stores.resize(NumElems);
629   for (unsigned I = 0; I < NumElems; ++I) {
630     unsigned Align = Layout.getElemAlign(I);
631     Stores[I] = Builder.CreateAlignedStore(Val[I], Ptr[I], Align);
632   }
633   transferMetadata(&SI, Stores);
634   return true;
635 }
636
637 // Delete the instructions that we scalarized.  If a full vector result
638 // is still needed, recreate it using InsertElements.
639 bool Scalarizer::finish() {
640   // The presence of data in Gathered or Scattered indicates changes
641   // made to the Function.
642   if (Gathered.empty() && Scattered.empty())
643     return false;
644   for (GatherList::iterator GMI = Gathered.begin(), GME = Gathered.end();
645        GMI != GME; ++GMI) {
646     Instruction *Op = GMI->first;
647     ValueVector &CV = *GMI->second;
648     if (!Op->use_empty()) {
649       // The value is still needed, so recreate it using a series of
650       // InsertElements.
651       Type *Ty = Op->getType();
652       Value *Res = UndefValue::get(Ty);
653       BasicBlock *BB = Op->getParent();
654       unsigned Count = Ty->getVectorNumElements();
655       IRBuilder<> Builder(BB, Op);
656       if (isa<PHINode>(Op))
657         Builder.SetInsertPoint(BB, BB->getFirstInsertionPt());
658       for (unsigned I = 0; I < Count; ++I)
659         Res = Builder.CreateInsertElement(Res, CV[I], Builder.getInt32(I),
660                                           Op->getName() + ".upto" + Twine(I));
661       Res->takeName(Op);
662       Op->replaceAllUsesWith(Res);
663     }
664     Op->eraseFromParent();
665   }
666   Gathered.clear();
667   Scattered.clear();
668   return true;
669 }
670
671 FunctionPass *llvm::createScalarizerPass() {
672   return new Scalarizer();
673 }