1a17f03bdSSanjay Patel //===------- VectorCombine.cpp - Optimize partial vector operations -------===//
2a17f03bdSSanjay Patel //
3a17f03bdSSanjay Patel // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4a17f03bdSSanjay Patel // See https://llvm.org/LICENSE.txt for license information.
5a17f03bdSSanjay Patel // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6a17f03bdSSanjay Patel //
7a17f03bdSSanjay Patel //===----------------------------------------------------------------------===//
8a17f03bdSSanjay Patel //
9a17f03bdSSanjay Patel // This pass optimizes scalar/vector interactions using target cost models. The
10a17f03bdSSanjay Patel // transforms implemented here may not fit in traditional loop-based or SLP
11a17f03bdSSanjay Patel // vectorization passes.
12a17f03bdSSanjay Patel //
13a17f03bdSSanjay Patel //===----------------------------------------------------------------------===//
14a17f03bdSSanjay Patel 
15a17f03bdSSanjay Patel #include "llvm/Transforms/Vectorize/VectorCombine.h"
16a17f03bdSSanjay Patel #include "llvm/ADT/Statistic.h"
175006e551SSimon Pilgrim #include "llvm/Analysis/BasicAliasAnalysis.h"
18a17f03bdSSanjay Patel #include "llvm/Analysis/GlobalsModRef.h"
19a17f03bdSSanjay Patel #include "llvm/Analysis/TargetTransformInfo.h"
2019b62b79SSanjay Patel #include "llvm/Analysis/ValueTracking.h"
21b6050ca1SSanjay Patel #include "llvm/Analysis/VectorUtils.h"
22a17f03bdSSanjay Patel #include "llvm/IR/Dominators.h"
23a17f03bdSSanjay Patel #include "llvm/IR/Function.h"
24a17f03bdSSanjay Patel #include "llvm/IR/IRBuilder.h"
25a17f03bdSSanjay Patel #include "llvm/IR/PatternMatch.h"
26a17f03bdSSanjay Patel #include "llvm/InitializePasses.h"
27a17f03bdSSanjay Patel #include "llvm/Pass.h"
2825c6544fSSanjay Patel #include "llvm/Support/CommandLine.h"
29a17f03bdSSanjay Patel #include "llvm/Transforms/Utils/Local.h"
305006e551SSimon Pilgrim #include "llvm/Transforms/Vectorize.h"
31a17f03bdSSanjay Patel 
32a17f03bdSSanjay Patel using namespace llvm;
33a17f03bdSSanjay Patel using namespace llvm::PatternMatch;
34a17f03bdSSanjay Patel 
35a17f03bdSSanjay Patel #define DEBUG_TYPE "vector-combine"
36a17f03bdSSanjay Patel STATISTIC(NumVecCmp, "Number of vector compares formed");
3719b62b79SSanjay Patel STATISTIC(NumVecBO, "Number of vector binops formed");
38*7aeb41b3SRoman Lebedev STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
390d2a0b44SSanjay Patel STATISTIC(NumScalarBO, "Number of scalar binops formed");
40a17f03bdSSanjay Patel 
4125c6544fSSanjay Patel static cl::opt<bool> DisableVectorCombine(
4225c6544fSSanjay Patel     "disable-vector-combine", cl::init(false), cl::Hidden,
4325c6544fSSanjay Patel     cl::desc("Disable all vector combine transforms"));
4425c6544fSSanjay Patel 
45a69158c1SSanjay Patel static cl::opt<bool> DisableBinopExtractShuffle(
46a69158c1SSanjay Patel     "disable-binop-extract-shuffle", cl::init(false), cl::Hidden,
47a69158c1SSanjay Patel     cl::desc("Disable binop extract to shuffle transforms"));
48a69158c1SSanjay Patel 
49a69158c1SSanjay Patel 
50a69158c1SSanjay Patel /// Compare the relative costs of 2 extracts followed by scalar operation vs.
51a69158c1SSanjay Patel /// vector operation(s) followed by extract. Return true if the existing
52a69158c1SSanjay Patel /// instructions are cheaper than a vector alternative. Otherwise, return false
53a69158c1SSanjay Patel /// and if one of the extracts should be transformed to a shufflevector, set
54a69158c1SSanjay Patel /// \p ConvertToShuffle to that extract instruction.
5534e34855SSanjay Patel static bool isExtractExtractCheap(Instruction *Ext0, Instruction *Ext1,
5634e34855SSanjay Patel                                   unsigned Opcode,
57a69158c1SSanjay Patel                                   const TargetTransformInfo &TTI,
58ce97ce3aSSanjay Patel                                   Instruction *&ConvertToShuffle,
59ce97ce3aSSanjay Patel                                   unsigned PreferredExtractIndex) {
604fa63fd4SAustin Kerbow   assert(isa<ConstantInt>(Ext0->getOperand(1)) &&
61a69158c1SSanjay Patel          isa<ConstantInt>(Ext1->getOperand(1)) &&
62a69158c1SSanjay Patel          "Expected constant extract indexes");
6334e34855SSanjay Patel   Type *ScalarTy = Ext0->getType();
64e3056ae9SSam Parker   auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType());
6534e34855SSanjay Patel   int ScalarOpCost, VectorOpCost;
6634e34855SSanjay Patel 
6734e34855SSanjay Patel   // Get cost estimates for scalar and vector versions of the operation.
6834e34855SSanjay Patel   bool IsBinOp = Instruction::isBinaryOp(Opcode);
6934e34855SSanjay Patel   if (IsBinOp) {
7034e34855SSanjay Patel     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
7134e34855SSanjay Patel     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
7234e34855SSanjay Patel   } else {
7334e34855SSanjay Patel     assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
7434e34855SSanjay Patel            "Expected a compare");
7534e34855SSanjay Patel     ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy,
7634e34855SSanjay Patel                                           CmpInst::makeCmpResultType(ScalarTy));
7734e34855SSanjay Patel     VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy,
7834e34855SSanjay Patel                                           CmpInst::makeCmpResultType(VecTy));
7934e34855SSanjay Patel   }
8034e34855SSanjay Patel 
81a69158c1SSanjay Patel   // Get cost estimates for the extract elements. These costs will factor into
8234e34855SSanjay Patel   // both sequences.
83a69158c1SSanjay Patel   unsigned Ext0Index = cast<ConstantInt>(Ext0->getOperand(1))->getZExtValue();
84a69158c1SSanjay Patel   unsigned Ext1Index = cast<ConstantInt>(Ext1->getOperand(1))->getZExtValue();
85a69158c1SSanjay Patel 
86a69158c1SSanjay Patel   int Extract0Cost = TTI.getVectorInstrCost(Instruction::ExtractElement,
87a69158c1SSanjay Patel                                             VecTy, Ext0Index);
88a69158c1SSanjay Patel   int Extract1Cost = TTI.getVectorInstrCost(Instruction::ExtractElement,
89a69158c1SSanjay Patel                                             VecTy, Ext1Index);
90a69158c1SSanjay Patel 
91a69158c1SSanjay Patel   // A more expensive extract will always be replaced by a splat shuffle.
92a69158c1SSanjay Patel   // For example, if Ext0 is more expensive:
93a69158c1SSanjay Patel   // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
94a69158c1SSanjay Patel   // extelt (opcode (splat V0, Ext0), V1), Ext1
95a69158c1SSanjay Patel   // TODO: Evaluate whether that always results in lowest cost. Alternatively,
96a69158c1SSanjay Patel   //       check the cost of creating a broadcast shuffle and shuffling both
97a69158c1SSanjay Patel   //       operands to element 0.
98a69158c1SSanjay Patel   int CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
9934e34855SSanjay Patel 
10034e34855SSanjay Patel   // Extra uses of the extracts mean that we include those costs in the
10134e34855SSanjay Patel   // vector total because those instructions will not be eliminated.
102e9c79a7aSSanjay Patel   int OldCost, NewCost;
103a69158c1SSanjay Patel   if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) {
104a69158c1SSanjay Patel     // Handle a special case. If the 2 extracts are identical, adjust the
10534e34855SSanjay Patel     // formulas to account for that. The extra use charge allows for either the
10634e34855SSanjay Patel     // CSE'd pattern or an unoptimized form with identical values:
10734e34855SSanjay Patel     // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
10834e34855SSanjay Patel     bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
10934e34855SSanjay Patel                                   : !Ext0->hasOneUse() || !Ext1->hasOneUse();
110a69158c1SSanjay Patel     OldCost = CheapExtractCost + ScalarOpCost;
111a69158c1SSanjay Patel     NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
11234e34855SSanjay Patel   } else {
11334e34855SSanjay Patel     // Handle the general case. Each extract is actually a different value:
114a69158c1SSanjay Patel     // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
115a69158c1SSanjay Patel     OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
116a69158c1SSanjay Patel     NewCost = VectorOpCost + CheapExtractCost +
117a69158c1SSanjay Patel               !Ext0->hasOneUse() * Extract0Cost +
118a69158c1SSanjay Patel               !Ext1->hasOneUse() * Extract1Cost;
11934e34855SSanjay Patel   }
120a69158c1SSanjay Patel 
121a69158c1SSanjay Patel   if (Ext0Index == Ext1Index) {
122a69158c1SSanjay Patel     // If the extract indexes are identical, no shuffle is needed.
123a69158c1SSanjay Patel     ConvertToShuffle = nullptr;
124a69158c1SSanjay Patel   } else {
125a69158c1SSanjay Patel     if (IsBinOp && DisableBinopExtractShuffle)
126a69158c1SSanjay Patel       return true;
127a69158c1SSanjay Patel 
128a69158c1SSanjay Patel     // If we are extracting from 2 different indexes, then one operand must be
129a69158c1SSanjay Patel     // shuffled before performing the vector operation. The shuffle mask is
130a69158c1SSanjay Patel     // undefined except for 1 lane that is being translated to the remaining
131a69158c1SSanjay Patel     // extraction lane. Therefore, it is a splat shuffle. Ex:
132a69158c1SSanjay Patel     // ShufMask = { undef, undef, 0, undef }
133a69158c1SSanjay Patel     // TODO: The cost model has an option for a "broadcast" shuffle
134a69158c1SSanjay Patel     //       (splat-from-element-0), but no option for a more general splat.
135a69158c1SSanjay Patel     NewCost +=
136a69158c1SSanjay Patel         TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
137a69158c1SSanjay Patel 
138ce97ce3aSSanjay Patel     // The more expensive extract will be replaced by a shuffle. If the costs
139ce97ce3aSSanjay Patel     // are equal and there is a preferred extract index, shuffle the opposite
140ce97ce3aSSanjay Patel     // operand. Otherwise, replace the extract with the higher index.
141a69158c1SSanjay Patel     if (Extract0Cost > Extract1Cost)
142a69158c1SSanjay Patel       ConvertToShuffle = Ext0;
143a69158c1SSanjay Patel     else if (Extract1Cost > Extract0Cost)
144a69158c1SSanjay Patel       ConvertToShuffle = Ext1;
145ce97ce3aSSanjay Patel     else if (PreferredExtractIndex == Ext0Index)
146ce97ce3aSSanjay Patel       ConvertToShuffle = Ext1;
147ce97ce3aSSanjay Patel     else if (PreferredExtractIndex == Ext1Index)
148ce97ce3aSSanjay Patel       ConvertToShuffle = Ext0;
149a69158c1SSanjay Patel     else
150a69158c1SSanjay Patel       ConvertToShuffle = Ext0Index > Ext1Index ? Ext0 : Ext1;
151a69158c1SSanjay Patel   }
152a69158c1SSanjay Patel 
15310ea01d8SSanjay Patel   // Aggressively form a vector op if the cost is equal because the transform
15410ea01d8SSanjay Patel   // may enable further optimization.
15510ea01d8SSanjay Patel   // Codegen can reverse this transform (scalarize) if it was not profitable.
15610ea01d8SSanjay Patel   return OldCost < NewCost;
15734e34855SSanjay Patel }
15834e34855SSanjay Patel 
159fc445589SSanjay Patel /// Try to reduce extract element costs by converting scalar compares to vector
160fc445589SSanjay Patel /// compares followed by extract.
161e9c79a7aSSanjay Patel /// cmp (ext0 V0, C), (ext1 V1, C)
162e9c79a7aSSanjay Patel static void foldExtExtCmp(Instruction *Ext0, Instruction *Ext1,
163039ff29eSSanjay Patel                           Instruction &I) {
164fc445589SSanjay Patel   assert(isa<CmpInst>(&I) && "Expected a compare");
165a17f03bdSSanjay Patel 
166a17f03bdSSanjay Patel   // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C
167a17f03bdSSanjay Patel   ++NumVecCmp;
168a17f03bdSSanjay Patel   IRBuilder<> Builder(&I);
169fc445589SSanjay Patel   CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
170e9c79a7aSSanjay Patel   Value *V0 = Ext0->getOperand(0), *V1 = Ext1->getOperand(0);
17134e34855SSanjay Patel   Value *VecCmp =
17234e34855SSanjay Patel       Ext0->getType()->isFloatingPointTy() ? Builder.CreateFCmp(Pred, V0, V1)
173a17f03bdSSanjay Patel                                            : Builder.CreateICmp(Pred, V0, V1);
174fc445589SSanjay Patel   Value *Extract = Builder.CreateExtractElement(VecCmp, Ext0->getOperand(1));
175fc445589SSanjay Patel   I.replaceAllUsesWith(Extract);
176a17f03bdSSanjay Patel }
177a17f03bdSSanjay Patel 
17819b62b79SSanjay Patel /// Try to reduce extract element costs by converting scalar binops to vector
17919b62b79SSanjay Patel /// binops followed by extract.
180e9c79a7aSSanjay Patel /// bo (ext0 V0, C), (ext1 V1, C)
181e9c79a7aSSanjay Patel static void foldExtExtBinop(Instruction *Ext0, Instruction *Ext1,
182039ff29eSSanjay Patel                             Instruction &I) {
183fc445589SSanjay Patel   assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
18419b62b79SSanjay Patel 
18534e34855SSanjay Patel   // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C
18619b62b79SSanjay Patel   ++NumVecBO;
18719b62b79SSanjay Patel   IRBuilder<> Builder(&I);
188e9c79a7aSSanjay Patel   Value *V0 = Ext0->getOperand(0), *V1 = Ext1->getOperand(0);
189e9c79a7aSSanjay Patel   Value *VecBO =
19034e34855SSanjay Patel       Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1);
191e9c79a7aSSanjay Patel 
19219b62b79SSanjay Patel   // All IR flags are safe to back-propagate because any potential poison
19319b62b79SSanjay Patel   // created in unused vector elements is discarded by the extract.
194e9c79a7aSSanjay Patel   if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
19519b62b79SSanjay Patel     VecBOInst->copyIRFlags(&I);
196e9c79a7aSSanjay Patel 
197e9c79a7aSSanjay Patel   Value *Extract = Builder.CreateExtractElement(VecBO, Ext0->getOperand(1));
19819b62b79SSanjay Patel   I.replaceAllUsesWith(Extract);
19919b62b79SSanjay Patel }
20019b62b79SSanjay Patel 
201fc445589SSanjay Patel /// Match an instruction with extracted vector operands.
202fc445589SSanjay Patel static bool foldExtractExtract(Instruction &I, const TargetTransformInfo &TTI) {
203e9c79a7aSSanjay Patel   // It is not safe to transform things like div, urem, etc. because we may
204e9c79a7aSSanjay Patel   // create undefined behavior when executing those on unknown vector elements.
205e9c79a7aSSanjay Patel   if (!isSafeToSpeculativelyExecute(&I))
206e9c79a7aSSanjay Patel     return false;
207e9c79a7aSSanjay Patel 
208fc445589SSanjay Patel   Instruction *Ext0, *Ext1;
209fc445589SSanjay Patel   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
210fc445589SSanjay Patel   if (!match(&I, m_Cmp(Pred, m_Instruction(Ext0), m_Instruction(Ext1))) &&
211fc445589SSanjay Patel       !match(&I, m_BinOp(m_Instruction(Ext0), m_Instruction(Ext1))))
212fc445589SSanjay Patel     return false;
213fc445589SSanjay Patel 
214fc445589SSanjay Patel   Value *V0, *V1;
215fc445589SSanjay Patel   uint64_t C0, C1;
2167eed772aSSanjay Patel   if (!match(Ext0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
2177eed772aSSanjay Patel       !match(Ext1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) ||
218fc445589SSanjay Patel       V0->getType() != V1->getType())
219fc445589SSanjay Patel     return false;
220fc445589SSanjay Patel 
221ce97ce3aSSanjay Patel   // If the scalar value 'I' is going to be re-inserted into a vector, then try
222ce97ce3aSSanjay Patel   // to create an extract to that same element. The extract/insert can be
223ce97ce3aSSanjay Patel   // reduced to a "select shuffle".
224ce97ce3aSSanjay Patel   // TODO: If we add a larger pattern match that starts from an insert, this
225ce97ce3aSSanjay Patel   //       probably becomes unnecessary.
226ce97ce3aSSanjay Patel   uint64_t InsertIndex = std::numeric_limits<uint64_t>::max();
227ce97ce3aSSanjay Patel   if (I.hasOneUse())
2287eed772aSSanjay Patel     match(I.user_back(),
2297eed772aSSanjay Patel           m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
230ce97ce3aSSanjay Patel 
231a69158c1SSanjay Patel   Instruction *ConvertToShuffle;
232ce97ce3aSSanjay Patel   if (isExtractExtractCheap(Ext0, Ext1, I.getOpcode(), TTI, ConvertToShuffle,
233ce97ce3aSSanjay Patel                             InsertIndex))
234fc445589SSanjay Patel     return false;
235e9c79a7aSSanjay Patel 
236a69158c1SSanjay Patel   if (ConvertToShuffle) {
237a69158c1SSanjay Patel     // The shuffle mask is undefined except for 1 lane that is being translated
238a69158c1SSanjay Patel     // to the cheap extraction lane. Example:
239a69158c1SSanjay Patel     // ShufMask = { 2, undef, undef, undef }
240a69158c1SSanjay Patel     uint64_t SplatIndex = ConvertToShuffle == Ext0 ? C0 : C1;
241a69158c1SSanjay Patel     uint64_t CheapExtIndex = ConvertToShuffle == Ext0 ? C1 : C0;
2423297e9b7SChristopher Tetreault     auto *VecTy = cast<VectorType>(V0->getType());
2436f64dacaSBenjamin Kramer     SmallVector<int, 32> ShufMask(VecTy->getNumElements(), -1);
2446f64dacaSBenjamin Kramer     ShufMask[CheapExtIndex] = SplatIndex;
245a69158c1SSanjay Patel     IRBuilder<> Builder(ConvertToShuffle);
246a69158c1SSanjay Patel 
247a69158c1SSanjay Patel     // extelt X, C --> extelt (splat X), C'
248a69158c1SSanjay Patel     Value *Shuf = Builder.CreateShuffleVector(ConvertToShuffle->getOperand(0),
2496f64dacaSBenjamin Kramer                                               UndefValue::get(VecTy), ShufMask);
250a69158c1SSanjay Patel     Value *NewExt = Builder.CreateExtractElement(Shuf, CheapExtIndex);
251a69158c1SSanjay Patel     if (ConvertToShuffle == Ext0)
252a69158c1SSanjay Patel       Ext0 = cast<Instruction>(NewExt);
253a69158c1SSanjay Patel     else
254a69158c1SSanjay Patel       Ext1 = cast<Instruction>(NewExt);
255a69158c1SSanjay Patel   }
256e9c79a7aSSanjay Patel 
257e9c79a7aSSanjay Patel   if (Pred != CmpInst::BAD_ICMP_PREDICATE)
258039ff29eSSanjay Patel     foldExtExtCmp(Ext0, Ext1, I);
259e9c79a7aSSanjay Patel   else
260039ff29eSSanjay Patel     foldExtExtBinop(Ext0, Ext1, I);
261e9c79a7aSSanjay Patel 
262e9c79a7aSSanjay Patel   return true;
263fc445589SSanjay Patel }
264fc445589SSanjay Patel 
265bef6e67eSSanjay Patel /// If this is a bitcast of a shuffle, try to bitcast the source vector to the
266bef6e67eSSanjay Patel /// destination type followed by shuffle. This can enable further transforms by
267bef6e67eSSanjay Patel /// moving bitcasts or shuffles together.
268b6050ca1SSanjay Patel static bool foldBitcastShuf(Instruction &I, const TargetTransformInfo &TTI) {
269b6050ca1SSanjay Patel   Value *V;
270b6050ca1SSanjay Patel   ArrayRef<int> Mask;
2717eed772aSSanjay Patel   if (!match(&I, m_BitCast(
2727eed772aSSanjay Patel                      m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))))))
273b6050ca1SSanjay Patel     return false;
274b6050ca1SSanjay Patel 
275bef6e67eSSanjay Patel   // Disallow non-vector casts and length-changing shuffles.
276bef6e67eSSanjay Patel   // TODO: We could allow any shuffle.
2773297e9b7SChristopher Tetreault   auto *DestTy = dyn_cast<VectorType>(I.getType());
2783297e9b7SChristopher Tetreault   auto *SrcTy = cast<VectorType>(V->getType());
2793297e9b7SChristopher Tetreault   if (!DestTy || I.getOperand(0)->getType() != SrcTy)
280b6050ca1SSanjay Patel     return false;
281b6050ca1SSanjay Patel 
282b6050ca1SSanjay Patel   // The new shuffle must not cost more than the old shuffle. The bitcast is
283b6050ca1SSanjay Patel   // moved ahead of the shuffle, so assume that it has the same cost as before.
284b6050ca1SSanjay Patel   if (TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, DestTy) >
285b6050ca1SSanjay Patel       TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, SrcTy))
286b6050ca1SSanjay Patel     return false;
287b6050ca1SSanjay Patel 
288bef6e67eSSanjay Patel   unsigned DestNumElts = DestTy->getNumElements();
289bef6e67eSSanjay Patel   unsigned SrcNumElts = SrcTy->getNumElements();
290b6050ca1SSanjay Patel   SmallVector<int, 16> NewMask;
291bef6e67eSSanjay Patel   if (SrcNumElts <= DestNumElts) {
292bef6e67eSSanjay Patel     // The bitcast is from wide to narrow/equal elements. The shuffle mask can
293bef6e67eSSanjay Patel     // always be expanded to the equivalent form choosing narrower elements.
294b6050ca1SSanjay Patel     assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask");
295b6050ca1SSanjay Patel     unsigned ScaleFactor = DestNumElts / SrcNumElts;
2961318ddbcSSanjay Patel     narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
297bef6e67eSSanjay Patel   } else {
298bef6e67eSSanjay Patel     // The bitcast is from narrow elements to wide elements. The shuffle mask
299bef6e67eSSanjay Patel     // must choose consecutive elements to allow casting first.
300bef6e67eSSanjay Patel     assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask");
301bef6e67eSSanjay Patel     unsigned ScaleFactor = SrcNumElts / DestNumElts;
302bef6e67eSSanjay Patel     if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
303bef6e67eSSanjay Patel       return false;
304bef6e67eSSanjay Patel   }
305bef6e67eSSanjay Patel   // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC'
306*7aeb41b3SRoman Lebedev   ++NumShufOfBitcast;
307bef6e67eSSanjay Patel   IRBuilder<> Builder(&I);
308bef6e67eSSanjay Patel   Value *CastV = Builder.CreateBitCast(V, DestTy);
3097eed772aSSanjay Patel   Value *Shuf =
3107eed772aSSanjay Patel       Builder.CreateShuffleVector(CastV, UndefValue::get(DestTy), NewMask);
311b6050ca1SSanjay Patel   I.replaceAllUsesWith(Shuf);
312b6050ca1SSanjay Patel   return true;
313b6050ca1SSanjay Patel }
314b6050ca1SSanjay Patel 
3150d2a0b44SSanjay Patel /// Match a vector binop instruction with inserted scalar operands and convert
3160d2a0b44SSanjay Patel /// to scalar binop followed by insertelement.
3170d2a0b44SSanjay Patel static bool scalarizeBinop(Instruction &I, const TargetTransformInfo &TTI) {
3185dc4e7c2SSimon Pilgrim   Value *Ins0, *Ins1;
3195dc4e7c2SSimon Pilgrim   if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))))
3200d2a0b44SSanjay Patel     return false;
3210d2a0b44SSanjay Patel 
3225dc4e7c2SSimon Pilgrim   // Match against one or both scalar values being inserted into constant
3235dc4e7c2SSimon Pilgrim   // vectors:
3245dc4e7c2SSimon Pilgrim   // vec_bo VecC0, (inselt VecC1, V1, Index)
3255dc4e7c2SSimon Pilgrim   // vec_bo (inselt VecC0, V0, Index), VecC1
3265dc4e7c2SSimon Pilgrim   // vec_bo (inselt VecC0, V0, Index), (inselt VecC1, V1, Index)
3270d2a0b44SSanjay Patel   // TODO: Deal with mismatched index constants and variable indexes?
3285dc4e7c2SSimon Pilgrim   Constant *VecC0 = nullptr, *VecC1 = nullptr;
3295dc4e7c2SSimon Pilgrim   Value *V0 = nullptr, *V1 = nullptr;
3305dc4e7c2SSimon Pilgrim   uint64_t Index0 = 0, Index1 = 0;
3317eed772aSSanjay Patel   if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
3325dc4e7c2SSimon Pilgrim                                m_ConstantInt(Index0))) &&
3335dc4e7c2SSimon Pilgrim       !match(Ins0, m_Constant(VecC0)))
3345dc4e7c2SSimon Pilgrim     return false;
3355dc4e7c2SSimon Pilgrim   if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
3365dc4e7c2SSimon Pilgrim                                m_ConstantInt(Index1))) &&
3375dc4e7c2SSimon Pilgrim       !match(Ins1, m_Constant(VecC1)))
3380d2a0b44SSanjay Patel     return false;
3390d2a0b44SSanjay Patel 
3405dc4e7c2SSimon Pilgrim   bool IsConst0 = !V0;
3415dc4e7c2SSimon Pilgrim   bool IsConst1 = !V1;
3425dc4e7c2SSimon Pilgrim   if (IsConst0 && IsConst1)
3435dc4e7c2SSimon Pilgrim     return false;
3445dc4e7c2SSimon Pilgrim   if (!IsConst0 && !IsConst1 && Index0 != Index1)
3455dc4e7c2SSimon Pilgrim     return false;
3465dc4e7c2SSimon Pilgrim 
3475dc4e7c2SSimon Pilgrim   // Bail for single insertion if it is a load.
3485dc4e7c2SSimon Pilgrim   // TODO: Handle this once getVectorInstrCost can cost for load/stores.
3495dc4e7c2SSimon Pilgrim   auto *I0 = dyn_cast_or_null<Instruction>(V0);
3505dc4e7c2SSimon Pilgrim   auto *I1 = dyn_cast_or_null<Instruction>(V1);
3515dc4e7c2SSimon Pilgrim   if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
3525dc4e7c2SSimon Pilgrim       (IsConst1 && I0 && I0->mayReadFromMemory()))
3535dc4e7c2SSimon Pilgrim     return false;
3545dc4e7c2SSimon Pilgrim 
3555dc4e7c2SSimon Pilgrim   uint64_t Index = IsConst0 ? Index1 : Index0;
3565dc4e7c2SSimon Pilgrim   Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType();
3570d2a0b44SSanjay Patel   Type *VecTy = I.getType();
3585dc4e7c2SSimon Pilgrim   assert(VecTy->isVectorTy() &&
3595dc4e7c2SSimon Pilgrim          (IsConst0 || IsConst1 || V0->getType() == V1->getType()) &&
3600d2a0b44SSanjay Patel          (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy()) &&
3610d2a0b44SSanjay Patel          "Unexpected types for insert into binop");
3620d2a0b44SSanjay Patel 
3630d2a0b44SSanjay Patel   Instruction::BinaryOps Opcode = cast<BinaryOperator>(&I)->getOpcode();
3640d2a0b44SSanjay Patel   int ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
3650d2a0b44SSanjay Patel   int VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
3660d2a0b44SSanjay Patel 
3670d2a0b44SSanjay Patel   // Get cost estimate for the insert element. This cost will factor into
3680d2a0b44SSanjay Patel   // both sequences.
3690d2a0b44SSanjay Patel   int InsertCost =
3700d2a0b44SSanjay Patel       TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, Index);
3715dc4e7c2SSimon Pilgrim   int OldCost = (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) +
3725dc4e7c2SSimon Pilgrim                 VectorOpCost;
3735f730b64SSanjay Patel   int NewCost = ScalarOpCost + InsertCost +
3745dc4e7c2SSimon Pilgrim                 (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) +
3755dc4e7c2SSimon Pilgrim                 (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost);
3760d2a0b44SSanjay Patel 
3770d2a0b44SSanjay Patel   // We want to scalarize unless the vector variant actually has lower cost.
3780d2a0b44SSanjay Patel   if (OldCost < NewCost)
3790d2a0b44SSanjay Patel     return false;
3800d2a0b44SSanjay Patel 
3810d2a0b44SSanjay Patel   // vec_bo (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
3820d2a0b44SSanjay Patel   // inselt NewVecC, (scalar_bo V0, V1), Index
3830d2a0b44SSanjay Patel   ++NumScalarBO;
3840d2a0b44SSanjay Patel   IRBuilder<> Builder(&I);
3855dc4e7c2SSimon Pilgrim 
3865dc4e7c2SSimon Pilgrim   // For constant cases, extract the scalar element, this should constant fold.
3875dc4e7c2SSimon Pilgrim   if (IsConst0)
3885dc4e7c2SSimon Pilgrim     V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index));
3895dc4e7c2SSimon Pilgrim   if (IsConst1)
3905dc4e7c2SSimon Pilgrim     V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index));
3915dc4e7c2SSimon Pilgrim 
3920d2a0b44SSanjay Patel   Value *Scalar = Builder.CreateBinOp(Opcode, V0, V1, I.getName() + ".scalar");
3930d2a0b44SSanjay Patel 
3940d2a0b44SSanjay Patel   // All IR flags are safe to back-propagate. There is no potential for extra
3950d2a0b44SSanjay Patel   // poison to be created by the scalar instruction.
3960d2a0b44SSanjay Patel   if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
3970d2a0b44SSanjay Patel     ScalarInst->copyIRFlags(&I);
3980d2a0b44SSanjay Patel 
3990d2a0b44SSanjay Patel   // Fold the vector constants in the original vectors into a new base vector.
4000d2a0b44SSanjay Patel   Constant *NewVecC = ConstantExpr::get(Opcode, VecC0, VecC1);
4010d2a0b44SSanjay Patel   Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
4020d2a0b44SSanjay Patel   I.replaceAllUsesWith(Insert);
4030d2a0b44SSanjay Patel   Insert->takeName(&I);
4040d2a0b44SSanjay Patel   return true;
4050d2a0b44SSanjay Patel }
4060d2a0b44SSanjay Patel 
407a17f03bdSSanjay Patel /// This is the entry point for all transforms. Pass manager differences are
408a17f03bdSSanjay Patel /// handled in the callers of this function.
409a17f03bdSSanjay Patel static bool runImpl(Function &F, const TargetTransformInfo &TTI,
410a17f03bdSSanjay Patel                     const DominatorTree &DT) {
41125c6544fSSanjay Patel   if (DisableVectorCombine)
41225c6544fSSanjay Patel     return false;
41325c6544fSSanjay Patel 
414a17f03bdSSanjay Patel   bool MadeChange = false;
415a17f03bdSSanjay Patel   for (BasicBlock &BB : F) {
416a17f03bdSSanjay Patel     // Ignore unreachable basic blocks.
417a17f03bdSSanjay Patel     if (!DT.isReachableFromEntry(&BB))
418a17f03bdSSanjay Patel       continue;
419a17f03bdSSanjay Patel     // Do not delete instructions under here and invalidate the iterator.
42081e9ede3SSanjay Patel     // Walk the block forwards to enable simple iterative chains of transforms.
421a17f03bdSSanjay Patel     // TODO: It could be more efficient to remove dead instructions
422a17f03bdSSanjay Patel     //       iteratively in this loop rather than waiting until the end.
42381e9ede3SSanjay Patel     for (Instruction &I : BB) {
424fc3cc8a4SSanjay Patel       if (isa<DbgInfoIntrinsic>(I))
425fc3cc8a4SSanjay Patel         continue;
426fc445589SSanjay Patel       MadeChange |= foldExtractExtract(I, TTI);
427b6050ca1SSanjay Patel       MadeChange |= foldBitcastShuf(I, TTI);
4280d2a0b44SSanjay Patel       MadeChange |= scalarizeBinop(I, TTI);
429a17f03bdSSanjay Patel     }
430fc3cc8a4SSanjay Patel   }
431a17f03bdSSanjay Patel 
432a17f03bdSSanjay Patel   // We're done with transforms, so remove dead instructions.
433a17f03bdSSanjay Patel   if (MadeChange)
434a17f03bdSSanjay Patel     for (BasicBlock &BB : F)
435a17f03bdSSanjay Patel       SimplifyInstructionsInBlock(&BB);
436a17f03bdSSanjay Patel 
437a17f03bdSSanjay Patel   return MadeChange;
438a17f03bdSSanjay Patel }
439a17f03bdSSanjay Patel 
440a17f03bdSSanjay Patel // Pass manager boilerplate below here.
441a17f03bdSSanjay Patel 
442a17f03bdSSanjay Patel namespace {
443a17f03bdSSanjay Patel class VectorCombineLegacyPass : public FunctionPass {
444a17f03bdSSanjay Patel public:
445a17f03bdSSanjay Patel   static char ID;
446a17f03bdSSanjay Patel   VectorCombineLegacyPass() : FunctionPass(ID) {
447a17f03bdSSanjay Patel     initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry());
448a17f03bdSSanjay Patel   }
449a17f03bdSSanjay Patel 
450a17f03bdSSanjay Patel   void getAnalysisUsage(AnalysisUsage &AU) const override {
451a17f03bdSSanjay Patel     AU.addRequired<DominatorTreeWrapperPass>();
452a17f03bdSSanjay Patel     AU.addRequired<TargetTransformInfoWrapperPass>();
453a17f03bdSSanjay Patel     AU.setPreservesCFG();
454a17f03bdSSanjay Patel     AU.addPreserved<DominatorTreeWrapperPass>();
455a17f03bdSSanjay Patel     AU.addPreserved<GlobalsAAWrapperPass>();
456024098aeSSanjay Patel     AU.addPreserved<AAResultsWrapperPass>();
457024098aeSSanjay Patel     AU.addPreserved<BasicAAWrapperPass>();
458a17f03bdSSanjay Patel     FunctionPass::getAnalysisUsage(AU);
459a17f03bdSSanjay Patel   }
460a17f03bdSSanjay Patel 
461a17f03bdSSanjay Patel   bool runOnFunction(Function &F) override {
462a17f03bdSSanjay Patel     if (skipFunction(F))
463a17f03bdSSanjay Patel       return false;
464a17f03bdSSanjay Patel     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
465a17f03bdSSanjay Patel     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
466a17f03bdSSanjay Patel     return runImpl(F, TTI, DT);
467a17f03bdSSanjay Patel   }
468a17f03bdSSanjay Patel };
469a17f03bdSSanjay Patel } // namespace
470a17f03bdSSanjay Patel 
471a17f03bdSSanjay Patel char VectorCombineLegacyPass::ID = 0;
472a17f03bdSSanjay Patel INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine",
473a17f03bdSSanjay Patel                       "Optimize scalar/vector ops", false,
474a17f03bdSSanjay Patel                       false)
475a17f03bdSSanjay Patel INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
476a17f03bdSSanjay Patel INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine",
477a17f03bdSSanjay Patel                     "Optimize scalar/vector ops", false, false)
478a17f03bdSSanjay Patel Pass *llvm::createVectorCombinePass() {
479a17f03bdSSanjay Patel   return new VectorCombineLegacyPass();
480a17f03bdSSanjay Patel }
481a17f03bdSSanjay Patel 
482a17f03bdSSanjay Patel PreservedAnalyses VectorCombinePass::run(Function &F,
483a17f03bdSSanjay Patel                                          FunctionAnalysisManager &FAM) {
484a17f03bdSSanjay Patel   TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
485a17f03bdSSanjay Patel   DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
486a17f03bdSSanjay Patel   if (!runImpl(F, TTI, DT))
487a17f03bdSSanjay Patel     return PreservedAnalyses::all();
488a17f03bdSSanjay Patel   PreservedAnalyses PA;
489a17f03bdSSanjay Patel   PA.preserveSet<CFGAnalyses>();
490a17f03bdSSanjay Patel   PA.preserve<GlobalsAA>();
491024098aeSSanjay Patel   PA.preserve<AAManager>();
492024098aeSSanjay Patel   PA.preserve<BasicAA>();
493a17f03bdSSanjay Patel   return PA;
494a17f03bdSSanjay Patel }
495