1 //===------- VectorCombine.cpp - Optimize partial 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 optimizes scalar/vector interactions using target cost models. The
10 // transforms implemented here may not fit in traditional loop-based or SLP
11 // vectorization passes.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Vectorize/VectorCombine.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/BasicAliasAnalysis.h"
18 #include "llvm/Analysis/GlobalsModRef.h"
19 #include "llvm/Analysis/Loads.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/Analysis/VectorUtils.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/InitializePasses.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "llvm/Transforms/Vectorize.h"
32 
33 using namespace llvm;
34 using namespace llvm::PatternMatch;
35 
36 #define DEBUG_TYPE "vector-combine"
37 STATISTIC(NumVecLoad, "Number of vector loads formed");
38 STATISTIC(NumVecCmp, "Number of vector compares formed");
39 STATISTIC(NumVecBO, "Number of vector binops formed");
40 STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed");
41 STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
42 STATISTIC(NumScalarBO, "Number of scalar binops formed");
43 STATISTIC(NumScalarCmp, "Number of scalar compares formed");
44 
45 static cl::opt<bool> DisableVectorCombine(
46     "disable-vector-combine", cl::init(false), cl::Hidden,
47     cl::desc("Disable all vector combine transforms"));
48 
49 static cl::opt<bool> DisableBinopExtractShuffle(
50     "disable-binop-extract-shuffle", cl::init(false), cl::Hidden,
51     cl::desc("Disable binop extract to shuffle transforms"));
52 
53 static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max();
54 
55 namespace {
56 class VectorCombine {
57 public:
58   VectorCombine(Function &F, const TargetTransformInfo &TTI,
59                 const DominatorTree &DT)
60       : F(F), Builder(F.getContext()), TTI(TTI), DT(DT) {}
61 
62   bool run();
63 
64 private:
65   Function &F;
66   IRBuilder<> Builder;
67   const TargetTransformInfo &TTI;
68   const DominatorTree &DT;
69 
70   bool vectorizeLoadInsert(Instruction &I);
71   ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0,
72                                         ExtractElementInst *Ext1,
73                                         unsigned PreferredExtractIndex) const;
74   bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
75                              unsigned Opcode,
76                              ExtractElementInst *&ConvertToShuffle,
77                              unsigned PreferredExtractIndex);
78   void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
79                      Instruction &I);
80   void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
81                        Instruction &I);
82   bool foldExtractExtract(Instruction &I);
83   bool foldBitcastShuf(Instruction &I);
84   bool scalarizeBinopOrCmp(Instruction &I);
85   bool foldExtractedCmps(Instruction &I);
86 };
87 } // namespace
88 
89 static void replaceValue(Value &Old, Value &New) {
90   Old.replaceAllUsesWith(&New);
91   New.takeName(&Old);
92 }
93 
94 bool VectorCombine::vectorizeLoadInsert(Instruction &I) {
95   // Match insert into fixed vector of scalar value.
96   auto *Ty = dyn_cast<FixedVectorType>(I.getType());
97   Value *Scalar;
98   if (!Ty || !match(&I, m_InsertElt(m_Undef(), m_Value(Scalar), m_ZeroInt())) ||
99       !Scalar->hasOneUse())
100     return false;
101 
102   // Optionally match an extract from another vector.
103   Value *X;
104   bool HasExtract = match(Scalar, m_ExtractElt(m_Value(X), m_ZeroInt()));
105   if (!HasExtract)
106     X = Scalar;
107 
108   // Match source value as load of scalar or vector.
109   // Do not vectorize scalar load (widening) if atomic/volatile or under
110   // asan/hwasan/memtag/tsan. The widened load may load data from dirty regions
111   // or create data races non-existent in the source.
112   auto *Load = dyn_cast<LoadInst>(X);
113   if (!Load || !Load->isSimple() || !Load->hasOneUse() ||
114       Load->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag) ||
115       mustSuppressSpeculation(*Load))
116     return false;
117 
118   // TODO: Extend this to match GEP with constant offsets.
119   const DataLayout &DL = I.getModule()->getDataLayout();
120   Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
121   assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
122 
123   // If original AS != Load's AS, we can't bitcast the original pointer and have
124   // to use Load's operand instead. Ideally we would want to strip pointer casts
125   // without changing AS, but there's no API to do that ATM.
126   unsigned AS = Load->getPointerAddressSpace();
127   if (AS != SrcPtr->getType()->getPointerAddressSpace())
128     SrcPtr = Load->getPointerOperand();
129 
130   Type *ScalarTy = Scalar->getType();
131   uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
132   unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
133   if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0)
134     return false;
135 
136   // Check safety of replacing the scalar load with a larger vector load.
137   // We use minimal alignment (maximum flexibility) because we only care about
138   // the dereferenceable region. When calculating cost and creating a new op,
139   // we may use a larger value based on alignment attributes.
140   unsigned MinVecNumElts = MinVectorSize / ScalarSize;
141   auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts, false);
142   if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), DL, Load, &DT))
143     return false;
144 
145   // Original pattern: insertelt undef, load [free casts of] PtrOp, 0
146   Align Alignment = Load->getAlign();
147   Type *LoadTy = Load->getType();
148   int OldCost = TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS);
149   APInt DemandedElts = APInt::getOneBitSet(MinVecNumElts, 0);
150   OldCost += TTI.getScalarizationOverhead(MinVecTy, DemandedElts,
151                                           /* Insert */ true, HasExtract);
152 
153   // New pattern: load VecPtr
154   int NewCost = TTI.getMemoryOpCost(Instruction::Load, MinVecTy, Alignment, AS);
155 
156   // We can aggressively convert to the vector form because the backend can
157   // invert this transform if it does not result in a performance win.
158   if (OldCost < NewCost)
159     return false;
160 
161   // It is safe and potentially profitable to load a vector directly:
162   // inselt undef, load Scalar, 0 --> load VecPtr
163   IRBuilder<> Builder(Load);
164   Value *CastedPtr = Builder.CreateBitCast(SrcPtr, MinVecTy->getPointerTo(AS));
165   Value *VecLd = Builder.CreateAlignedLoad(MinVecTy, CastedPtr, Alignment);
166 
167   // Set everything but element 0 to undef to prevent poison from propagating
168   // from the extra loaded memory. This will also optionally shrink/grow the
169   // vector from the loaded size to the output size.
170   // We assume this operation has no cost in codegen.
171   // Note that we could use freeze to avoid poison problems, but then we might
172   // still need a shuffle to change the vector size.
173   unsigned OutputNumElts = Ty->getNumElements();
174   SmallVector<int, 16> Mask(OutputNumElts, UndefMaskElem);
175   Mask[0] = 0;
176   VecLd = Builder.CreateShuffleVector(VecLd, Mask);
177 
178   replaceValue(I, *VecLd);
179   ++NumVecLoad;
180   return true;
181 }
182 
183 /// Determine which, if any, of the inputs should be replaced by a shuffle
184 /// followed by extract from a different index.
185 ExtractElementInst *VectorCombine::getShuffleExtract(
186     ExtractElementInst *Ext0, ExtractElementInst *Ext1,
187     unsigned PreferredExtractIndex = InvalidIndex) const {
188   assert(isa<ConstantInt>(Ext0->getIndexOperand()) &&
189          isa<ConstantInt>(Ext1->getIndexOperand()) &&
190          "Expected constant extract indexes");
191 
192   unsigned Index0 = cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue();
193   unsigned Index1 = cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue();
194 
195   // If the extract indexes are identical, no shuffle is needed.
196   if (Index0 == Index1)
197     return nullptr;
198 
199   Type *VecTy = Ext0->getVectorOperand()->getType();
200   assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types");
201   int Cost0 = TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
202   int Cost1 = TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
203 
204   // We are extracting from 2 different indexes, so one operand must be shuffled
205   // before performing a vector operation and/or extract. The more expensive
206   // extract will be replaced by a shuffle.
207   if (Cost0 > Cost1)
208     return Ext0;
209   if (Cost1 > Cost0)
210     return Ext1;
211 
212   // If the costs are equal and there is a preferred extract index, shuffle the
213   // opposite operand.
214   if (PreferredExtractIndex == Index0)
215     return Ext1;
216   if (PreferredExtractIndex == Index1)
217     return Ext0;
218 
219   // Otherwise, replace the extract with the higher index.
220   return Index0 > Index1 ? Ext0 : Ext1;
221 }
222 
223 /// Compare the relative costs of 2 extracts followed by scalar operation vs.
224 /// vector operation(s) followed by extract. Return true if the existing
225 /// instructions are cheaper than a vector alternative. Otherwise, return false
226 /// and if one of the extracts should be transformed to a shufflevector, set
227 /// \p ConvertToShuffle to that extract instruction.
228 bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0,
229                                           ExtractElementInst *Ext1,
230                                           unsigned Opcode,
231                                           ExtractElementInst *&ConvertToShuffle,
232                                           unsigned PreferredExtractIndex) {
233   assert(isa<ConstantInt>(Ext0->getOperand(1)) &&
234          isa<ConstantInt>(Ext1->getOperand(1)) &&
235          "Expected constant extract indexes");
236   Type *ScalarTy = Ext0->getType();
237   auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType());
238   int ScalarOpCost, VectorOpCost;
239 
240   // Get cost estimates for scalar and vector versions of the operation.
241   bool IsBinOp = Instruction::isBinaryOp(Opcode);
242   if (IsBinOp) {
243     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
244     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
245   } else {
246     assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
247            "Expected a compare");
248     ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy,
249                                           CmpInst::makeCmpResultType(ScalarTy));
250     VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy,
251                                           CmpInst::makeCmpResultType(VecTy));
252   }
253 
254   // Get cost estimates for the extract elements. These costs will factor into
255   // both sequences.
256   unsigned Ext0Index = cast<ConstantInt>(Ext0->getOperand(1))->getZExtValue();
257   unsigned Ext1Index = cast<ConstantInt>(Ext1->getOperand(1))->getZExtValue();
258 
259   int Extract0Cost =
260       TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext0Index);
261   int Extract1Cost =
262       TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext1Index);
263 
264   // A more expensive extract will always be replaced by a splat shuffle.
265   // For example, if Ext0 is more expensive:
266   // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
267   // extelt (opcode (splat V0, Ext0), V1), Ext1
268   // TODO: Evaluate whether that always results in lowest cost. Alternatively,
269   //       check the cost of creating a broadcast shuffle and shuffling both
270   //       operands to element 0.
271   int CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
272 
273   // Extra uses of the extracts mean that we include those costs in the
274   // vector total because those instructions will not be eliminated.
275   int OldCost, NewCost;
276   if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) {
277     // Handle a special case. If the 2 extracts are identical, adjust the
278     // formulas to account for that. The extra use charge allows for either the
279     // CSE'd pattern or an unoptimized form with identical values:
280     // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
281     bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
282                                   : !Ext0->hasOneUse() || !Ext1->hasOneUse();
283     OldCost = CheapExtractCost + ScalarOpCost;
284     NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
285   } else {
286     // Handle the general case. Each extract is actually a different value:
287     // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
288     OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
289     NewCost = VectorOpCost + CheapExtractCost +
290               !Ext0->hasOneUse() * Extract0Cost +
291               !Ext1->hasOneUse() * Extract1Cost;
292   }
293 
294   ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex);
295   if (ConvertToShuffle) {
296     if (IsBinOp && DisableBinopExtractShuffle)
297       return true;
298 
299     // If we are extracting from 2 different indexes, then one operand must be
300     // shuffled before performing the vector operation. The shuffle mask is
301     // undefined except for 1 lane that is being translated to the remaining
302     // extraction lane. Therefore, it is a splat shuffle. Ex:
303     // ShufMask = { undef, undef, 0, undef }
304     // TODO: The cost model has an option for a "broadcast" shuffle
305     //       (splat-from-element-0), but no option for a more general splat.
306     NewCost +=
307         TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
308   }
309 
310   // Aggressively form a vector op if the cost is equal because the transform
311   // may enable further optimization.
312   // Codegen can reverse this transform (scalarize) if it was not profitable.
313   return OldCost < NewCost;
314 }
315 
316 /// Create a shuffle that translates (shifts) 1 element from the input vector
317 /// to a new element location.
318 static Value *createShiftShuffle(Value *Vec, unsigned OldIndex,
319                                  unsigned NewIndex, IRBuilder<> &Builder) {
320   // The shuffle mask is undefined except for 1 lane that is being translated
321   // to the new element index. Example for OldIndex == 2 and NewIndex == 0:
322   // ShufMask = { 2, undef, undef, undef }
323   auto *VecTy = cast<FixedVectorType>(Vec->getType());
324   SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem);
325   ShufMask[NewIndex] = OldIndex;
326   return Builder.CreateShuffleVector(Vec, ShufMask, "shift");
327 }
328 
329 /// Given an extract element instruction with constant index operand, shuffle
330 /// the source vector (shift the scalar element) to a NewIndex for extraction.
331 /// Return null if the input can be constant folded, so that we are not creating
332 /// unnecessary instructions.
333 static ExtractElementInst *translateExtract(ExtractElementInst *ExtElt,
334                                             unsigned NewIndex,
335                                             IRBuilder<> &Builder) {
336   // If the extract can be constant-folded, this code is unsimplified. Defer
337   // to other passes to handle that.
338   Value *X = ExtElt->getVectorOperand();
339   Value *C = ExtElt->getIndexOperand();
340   assert(isa<ConstantInt>(C) && "Expected a constant index operand");
341   if (isa<Constant>(X))
342     return nullptr;
343 
344   Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(),
345                                    NewIndex, Builder);
346   return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex));
347 }
348 
349 /// Try to reduce extract element costs by converting scalar compares to vector
350 /// compares followed by extract.
351 /// cmp (ext0 V0, C), (ext1 V1, C)
352 void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0,
353                                   ExtractElementInst *Ext1, Instruction &I) {
354   assert(isa<CmpInst>(&I) && "Expected a compare");
355   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
356              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
357          "Expected matching constant extract indexes");
358 
359   // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C
360   ++NumVecCmp;
361   CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
362   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
363   Value *VecCmp = Builder.CreateCmp(Pred, V0, V1);
364   Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand());
365   replaceValue(I, *NewExt);
366 }
367 
368 /// Try to reduce extract element costs by converting scalar binops to vector
369 /// binops followed by extract.
370 /// bo (ext0 V0, C), (ext1 V1, C)
371 void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0,
372                                     ExtractElementInst *Ext1, Instruction &I) {
373   assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
374   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
375              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
376          "Expected matching constant extract indexes");
377 
378   // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C
379   ++NumVecBO;
380   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
381   Value *VecBO =
382       Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1);
383 
384   // All IR flags are safe to back-propagate because any potential poison
385   // created in unused vector elements is discarded by the extract.
386   if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
387     VecBOInst->copyIRFlags(&I);
388 
389   Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand());
390   replaceValue(I, *NewExt);
391 }
392 
393 /// Match an instruction with extracted vector operands.
394 bool VectorCombine::foldExtractExtract(Instruction &I) {
395   // It is not safe to transform things like div, urem, etc. because we may
396   // create undefined behavior when executing those on unknown vector elements.
397   if (!isSafeToSpeculativelyExecute(&I))
398     return false;
399 
400   Instruction *I0, *I1;
401   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
402   if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) &&
403       !match(&I, m_BinOp(m_Instruction(I0), m_Instruction(I1))))
404     return false;
405 
406   Value *V0, *V1;
407   uint64_t C0, C1;
408   if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
409       !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) ||
410       V0->getType() != V1->getType())
411     return false;
412 
413   // If the scalar value 'I' is going to be re-inserted into a vector, then try
414   // to create an extract to that same element. The extract/insert can be
415   // reduced to a "select shuffle".
416   // TODO: If we add a larger pattern match that starts from an insert, this
417   //       probably becomes unnecessary.
418   auto *Ext0 = cast<ExtractElementInst>(I0);
419   auto *Ext1 = cast<ExtractElementInst>(I1);
420   uint64_t InsertIndex = InvalidIndex;
421   if (I.hasOneUse())
422     match(I.user_back(),
423           m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
424 
425   ExtractElementInst *ExtractToChange;
426   if (isExtractExtractCheap(Ext0, Ext1, I.getOpcode(), ExtractToChange,
427                             InsertIndex))
428     return false;
429 
430   if (ExtractToChange) {
431     unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0;
432     ExtractElementInst *NewExtract =
433         translateExtract(ExtractToChange, CheapExtractIdx, Builder);
434     if (!NewExtract)
435       return false;
436     if (ExtractToChange == Ext0)
437       Ext0 = NewExtract;
438     else
439       Ext1 = NewExtract;
440   }
441 
442   if (Pred != CmpInst::BAD_ICMP_PREDICATE)
443     foldExtExtCmp(Ext0, Ext1, I);
444   else
445     foldExtExtBinop(Ext0, Ext1, I);
446 
447   return true;
448 }
449 
450 /// If this is a bitcast of a shuffle, try to bitcast the source vector to the
451 /// destination type followed by shuffle. This can enable further transforms by
452 /// moving bitcasts or shuffles together.
453 bool VectorCombine::foldBitcastShuf(Instruction &I) {
454   Value *V;
455   ArrayRef<int> Mask;
456   if (!match(&I, m_BitCast(
457                      m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))))))
458     return false;
459 
460   // 1) Do not fold bitcast shuffle for scalable type. First, shuffle cost for
461   // scalable type is unknown; Second, we cannot reason if the narrowed shuffle
462   // mask for scalable type is a splat or not.
463   // 2) Disallow non-vector casts and length-changing shuffles.
464   // TODO: We could allow any shuffle.
465   auto *DestTy = dyn_cast<FixedVectorType>(I.getType());
466   auto *SrcTy = dyn_cast<FixedVectorType>(V->getType());
467   if (!SrcTy || !DestTy || I.getOperand(0)->getType() != SrcTy)
468     return false;
469 
470   // The new shuffle must not cost more than the old shuffle. The bitcast is
471   // moved ahead of the shuffle, so assume that it has the same cost as before.
472   if (TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, DestTy) >
473       TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, SrcTy))
474     return false;
475 
476   unsigned DestNumElts = DestTy->getNumElements();
477   unsigned SrcNumElts = SrcTy->getNumElements();
478   SmallVector<int, 16> NewMask;
479   if (SrcNumElts <= DestNumElts) {
480     // The bitcast is from wide to narrow/equal elements. The shuffle mask can
481     // always be expanded to the equivalent form choosing narrower elements.
482     assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask");
483     unsigned ScaleFactor = DestNumElts / SrcNumElts;
484     narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
485   } else {
486     // The bitcast is from narrow elements to wide elements. The shuffle mask
487     // must choose consecutive elements to allow casting first.
488     assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask");
489     unsigned ScaleFactor = SrcNumElts / DestNumElts;
490     if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
491       return false;
492   }
493   // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC'
494   ++NumShufOfBitcast;
495   Value *CastV = Builder.CreateBitCast(V, DestTy);
496   Value *Shuf = Builder.CreateShuffleVector(CastV, NewMask);
497   replaceValue(I, *Shuf);
498   return true;
499 }
500 
501 /// Match a vector binop or compare instruction with at least one inserted
502 /// scalar operand and convert to scalar binop/cmp followed by insertelement.
503 bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) {
504   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
505   Value *Ins0, *Ins1;
506   if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) &&
507       !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1))))
508     return false;
509 
510   // Do not convert the vector condition of a vector select into a scalar
511   // condition. That may cause problems for codegen because of differences in
512   // boolean formats and register-file transfers.
513   // TODO: Can we account for that in the cost model?
514   bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE;
515   if (IsCmp)
516     for (User *U : I.users())
517       if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
518         return false;
519 
520   // Match against one or both scalar values being inserted into constant
521   // vectors:
522   // vec_op VecC0, (inselt VecC1, V1, Index)
523   // vec_op (inselt VecC0, V0, Index), VecC1
524   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index)
525   // TODO: Deal with mismatched index constants and variable indexes?
526   Constant *VecC0 = nullptr, *VecC1 = nullptr;
527   Value *V0 = nullptr, *V1 = nullptr;
528   uint64_t Index0 = 0, Index1 = 0;
529   if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
530                                m_ConstantInt(Index0))) &&
531       !match(Ins0, m_Constant(VecC0)))
532     return false;
533   if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
534                                m_ConstantInt(Index1))) &&
535       !match(Ins1, m_Constant(VecC1)))
536     return false;
537 
538   bool IsConst0 = !V0;
539   bool IsConst1 = !V1;
540   if (IsConst0 && IsConst1)
541     return false;
542   if (!IsConst0 && !IsConst1 && Index0 != Index1)
543     return false;
544 
545   // Bail for single insertion if it is a load.
546   // TODO: Handle this once getVectorInstrCost can cost for load/stores.
547   auto *I0 = dyn_cast_or_null<Instruction>(V0);
548   auto *I1 = dyn_cast_or_null<Instruction>(V1);
549   if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
550       (IsConst1 && I0 && I0->mayReadFromMemory()))
551     return false;
552 
553   uint64_t Index = IsConst0 ? Index1 : Index0;
554   Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType();
555   Type *VecTy = I.getType();
556   assert(VecTy->isVectorTy() &&
557          (IsConst0 || IsConst1 || V0->getType() == V1->getType()) &&
558          (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
559           ScalarTy->isPointerTy()) &&
560          "Unexpected types for insert element into binop or cmp");
561 
562   unsigned Opcode = I.getOpcode();
563   int ScalarOpCost, VectorOpCost;
564   if (IsCmp) {
565     ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy);
566     VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy);
567   } else {
568     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
569     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
570   }
571 
572   // Get cost estimate for the insert element. This cost will factor into
573   // both sequences.
574   int InsertCost =
575       TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, Index);
576   int OldCost = (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) +
577                 VectorOpCost;
578   int NewCost = ScalarOpCost + InsertCost +
579                 (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) +
580                 (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost);
581 
582   // We want to scalarize unless the vector variant actually has lower cost.
583   if (OldCost < NewCost)
584     return false;
585 
586   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
587   // inselt NewVecC, (scalar_op V0, V1), Index
588   if (IsCmp)
589     ++NumScalarCmp;
590   else
591     ++NumScalarBO;
592 
593   // For constant cases, extract the scalar element, this should constant fold.
594   if (IsConst0)
595     V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index));
596   if (IsConst1)
597     V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index));
598 
599   Value *Scalar =
600       IsCmp ? Builder.CreateCmp(Pred, V0, V1)
601             : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1);
602 
603   Scalar->setName(I.getName() + ".scalar");
604 
605   // All IR flags are safe to back-propagate. There is no potential for extra
606   // poison to be created by the scalar instruction.
607   if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
608     ScalarInst->copyIRFlags(&I);
609 
610   // Fold the vector constants in the original vectors into a new base vector.
611   Constant *NewVecC = IsCmp ? ConstantExpr::getCompare(Pred, VecC0, VecC1)
612                             : ConstantExpr::get(Opcode, VecC0, VecC1);
613   Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
614   replaceValue(I, *Insert);
615   return true;
616 }
617 
618 /// Try to combine a scalar binop + 2 scalar compares of extracted elements of
619 /// a vector into vector operations followed by extract. Note: The SLP pass
620 /// may miss this pattern because of implementation problems.
621 bool VectorCombine::foldExtractedCmps(Instruction &I) {
622   // We are looking for a scalar binop of booleans.
623   // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1)
624   if (!I.isBinaryOp() || !I.getType()->isIntegerTy(1))
625     return false;
626 
627   // The compare predicates should match, and each compare should have a
628   // constant operand.
629   // TODO: Relax the one-use constraints.
630   Value *B0 = I.getOperand(0), *B1 = I.getOperand(1);
631   Instruction *I0, *I1;
632   Constant *C0, *C1;
633   CmpInst::Predicate P0, P1;
634   if (!match(B0, m_OneUse(m_Cmp(P0, m_Instruction(I0), m_Constant(C0)))) ||
635       !match(B1, m_OneUse(m_Cmp(P1, m_Instruction(I1), m_Constant(C1)))) ||
636       P0 != P1)
637     return false;
638 
639   // The compare operands must be extracts of the same vector with constant
640   // extract indexes.
641   // TODO: Relax the one-use constraints.
642   Value *X;
643   uint64_t Index0, Index1;
644   if (!match(I0, m_OneUse(m_ExtractElt(m_Value(X), m_ConstantInt(Index0)))) ||
645       !match(I1, m_OneUse(m_ExtractElt(m_Specific(X), m_ConstantInt(Index1)))))
646     return false;
647 
648   auto *Ext0 = cast<ExtractElementInst>(I0);
649   auto *Ext1 = cast<ExtractElementInst>(I1);
650   ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1);
651   if (!ConvertToShuf)
652     return false;
653 
654   // The original scalar pattern is:
655   // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1)
656   CmpInst::Predicate Pred = P0;
657   unsigned CmpOpcode = CmpInst::isFPPredicate(Pred) ? Instruction::FCmp
658                                                     : Instruction::ICmp;
659   auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
660   if (!VecTy)
661     return false;
662 
663   int OldCost = TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
664   OldCost += TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
665   OldCost += TTI.getCmpSelInstrCost(CmpOpcode, I0->getType()) * 2;
666   OldCost += TTI.getArithmeticInstrCost(I.getOpcode(), I.getType());
667 
668   // The proposed vector pattern is:
669   // vcmp = cmp Pred X, VecC
670   // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0
671   int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0;
672   int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1;
673   auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType()));
674   int NewCost = TTI.getCmpSelInstrCost(CmpOpcode, X->getType());
675   NewCost +=
676       TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, CmpTy);
677   NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy);
678   NewCost += TTI.getVectorInstrCost(Ext0->getOpcode(), CmpTy, CheapIndex);
679 
680   // Aggressively form vector ops if the cost is equal because the transform
681   // may enable further optimization.
682   // Codegen can reverse this transform (scalarize) if it was not profitable.
683   if (OldCost < NewCost)
684     return false;
685 
686   // Create a vector constant from the 2 scalar constants.
687   SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(),
688                                    UndefValue::get(VecTy->getElementType()));
689   CmpC[Index0] = C0;
690   CmpC[Index1] = C1;
691   Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC));
692 
693   Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder);
694   Value *VecLogic = Builder.CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
695                                         VCmp, Shuf);
696   Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex);
697   replaceValue(I, *NewExt);
698   ++NumVecCmpBO;
699   return true;
700 }
701 
702 /// This is the entry point for all transforms. Pass manager differences are
703 /// handled in the callers of this function.
704 bool VectorCombine::run() {
705   if (DisableVectorCombine)
706     return false;
707 
708   // Don't attempt vectorization if the target does not support vectors.
709   if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true)))
710     return false;
711 
712   bool MadeChange = false;
713   for (BasicBlock &BB : F) {
714     // Ignore unreachable basic blocks.
715     if (!DT.isReachableFromEntry(&BB))
716       continue;
717     // Do not delete instructions under here and invalidate the iterator.
718     // Walk the block forwards to enable simple iterative chains of transforms.
719     // TODO: It could be more efficient to remove dead instructions
720     //       iteratively in this loop rather than waiting until the end.
721     for (Instruction &I : BB) {
722       if (isa<DbgInfoIntrinsic>(I))
723         continue;
724       Builder.SetInsertPoint(&I);
725       MadeChange |= vectorizeLoadInsert(I);
726       MadeChange |= foldExtractExtract(I);
727       MadeChange |= foldBitcastShuf(I);
728       MadeChange |= scalarizeBinopOrCmp(I);
729       MadeChange |= foldExtractedCmps(I);
730     }
731   }
732 
733   // We're done with transforms, so remove dead instructions.
734   if (MadeChange)
735     for (BasicBlock &BB : F)
736       SimplifyInstructionsInBlock(&BB);
737 
738   return MadeChange;
739 }
740 
741 // Pass manager boilerplate below here.
742 
743 namespace {
744 class VectorCombineLegacyPass : public FunctionPass {
745 public:
746   static char ID;
747   VectorCombineLegacyPass() : FunctionPass(ID) {
748     initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry());
749   }
750 
751   void getAnalysisUsage(AnalysisUsage &AU) const override {
752     AU.addRequired<DominatorTreeWrapperPass>();
753     AU.addRequired<TargetTransformInfoWrapperPass>();
754     AU.setPreservesCFG();
755     AU.addPreserved<DominatorTreeWrapperPass>();
756     AU.addPreserved<GlobalsAAWrapperPass>();
757     AU.addPreserved<AAResultsWrapperPass>();
758     AU.addPreserved<BasicAAWrapperPass>();
759     FunctionPass::getAnalysisUsage(AU);
760   }
761 
762   bool runOnFunction(Function &F) override {
763     if (skipFunction(F))
764       return false;
765     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
766     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
767     VectorCombine Combiner(F, TTI, DT);
768     return Combiner.run();
769   }
770 };
771 } // namespace
772 
773 char VectorCombineLegacyPass::ID = 0;
774 INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine",
775                       "Optimize scalar/vector ops", false,
776                       false)
777 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
778 INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine",
779                     "Optimize scalar/vector ops", false, false)
780 Pass *llvm::createVectorCombinePass() {
781   return new VectorCombineLegacyPass();
782 }
783 
784 PreservedAnalyses VectorCombinePass::run(Function &F,
785                                          FunctionAnalysisManager &FAM) {
786   TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
787   DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
788   VectorCombine Combiner(F, TTI, DT);
789   if (!Combiner.run())
790     return PreservedAnalyses::all();
791   PreservedAnalyses PA;
792   PA.preserveSet<CFGAnalyses>();
793   PA.preserve<GlobalsAA>();
794   PA.preserve<AAManager>();
795   PA.preserve<BasicAA>();
796   return PA;
797 }
798