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");
387aeb41b3SRoman Lebedev STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
390d2a0b44SSanjay Patel STATISTIC(NumScalarBO, "Number of scalar binops formed");
40ed67f5e7SSanjay Patel STATISTIC(NumScalarCmp, "Number of scalar compares formed");
41a17f03bdSSanjay Patel 
4225c6544fSSanjay Patel static cl::opt<bool> DisableVectorCombine(
4325c6544fSSanjay Patel     "disable-vector-combine", cl::init(false), cl::Hidden,
4425c6544fSSanjay Patel     cl::desc("Disable all vector combine transforms"));
4525c6544fSSanjay Patel 
46a69158c1SSanjay Patel static cl::opt<bool> DisableBinopExtractShuffle(
47a69158c1SSanjay Patel     "disable-binop-extract-shuffle", cl::init(false), cl::Hidden,
48a69158c1SSanjay Patel     cl::desc("Disable binop extract to shuffle transforms"));
49a69158c1SSanjay Patel 
506bdd531aSSanjay Patel class VectorCombine {
516bdd531aSSanjay Patel public:
526bdd531aSSanjay Patel   VectorCombine(Function &F, const TargetTransformInfo &TTI,
536bdd531aSSanjay Patel                 const DominatorTree &DT)
54de65b356SSanjay Patel       : F(F), Builder(F.getContext()), TTI(TTI), DT(DT) {}
556bdd531aSSanjay Patel 
566bdd531aSSanjay Patel   bool run();
576bdd531aSSanjay Patel 
586bdd531aSSanjay Patel private:
596bdd531aSSanjay Patel   Function &F;
60de65b356SSanjay Patel   IRBuilder<> Builder;
616bdd531aSSanjay Patel   const TargetTransformInfo &TTI;
626bdd531aSSanjay Patel   const DominatorTree &DT;
636bdd531aSSanjay Patel 
646bdd531aSSanjay Patel   bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
656bdd531aSSanjay Patel                              unsigned Opcode,
666bdd531aSSanjay Patel                              ExtractElementInst *&ConvertToShuffle,
676bdd531aSSanjay Patel                              unsigned PreferredExtractIndex);
68de65b356SSanjay Patel   void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
69de65b356SSanjay Patel                      Instruction &I);
70de65b356SSanjay Patel   void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
71de65b356SSanjay Patel                        Instruction &I);
726bdd531aSSanjay Patel   bool foldExtractExtract(Instruction &I);
736bdd531aSSanjay Patel   bool foldBitcastShuf(Instruction &I);
746bdd531aSSanjay Patel   bool scalarizeBinopOrCmp(Instruction &I);
756bdd531aSSanjay Patel };
76a69158c1SSanjay Patel 
7798c2f4eeSSanjay Patel static void replaceValue(Value &Old, Value &New) {
7898c2f4eeSSanjay Patel   Old.replaceAllUsesWith(&New);
7998c2f4eeSSanjay Patel   New.takeName(&Old);
8098c2f4eeSSanjay Patel }
8198c2f4eeSSanjay Patel 
82a69158c1SSanjay Patel /// Compare the relative costs of 2 extracts followed by scalar operation vs.
83a69158c1SSanjay Patel /// vector operation(s) followed by extract. Return true if the existing
84a69158c1SSanjay Patel /// instructions are cheaper than a vector alternative. Otherwise, return false
85a69158c1SSanjay Patel /// and if one of the extracts should be transformed to a shufflevector, set
86a69158c1SSanjay Patel /// \p ConvertToShuffle to that extract instruction.
876bdd531aSSanjay Patel bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0,
886bdd531aSSanjay Patel                                           ExtractElementInst *Ext1,
896bdd531aSSanjay Patel                                           unsigned Opcode,
90216a37bbSSanjay Patel                                           ExtractElementInst *&ConvertToShuffle,
91ce97ce3aSSanjay Patel                                           unsigned PreferredExtractIndex) {
924fa63fd4SAustin Kerbow   assert(isa<ConstantInt>(Ext0->getOperand(1)) &&
93a69158c1SSanjay Patel          isa<ConstantInt>(Ext1->getOperand(1)) &&
94a69158c1SSanjay Patel          "Expected constant extract indexes");
9534e34855SSanjay Patel   Type *ScalarTy = Ext0->getType();
96e3056ae9SSam Parker   auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType());
9734e34855SSanjay Patel   int ScalarOpCost, VectorOpCost;
9834e34855SSanjay Patel 
9934e34855SSanjay Patel   // Get cost estimates for scalar and vector versions of the operation.
10034e34855SSanjay Patel   bool IsBinOp = Instruction::isBinaryOp(Opcode);
10134e34855SSanjay Patel   if (IsBinOp) {
10234e34855SSanjay Patel     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
10334e34855SSanjay Patel     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
10434e34855SSanjay Patel   } else {
10534e34855SSanjay Patel     assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
10634e34855SSanjay Patel            "Expected a compare");
10734e34855SSanjay Patel     ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy,
10834e34855SSanjay Patel                                           CmpInst::makeCmpResultType(ScalarTy));
10934e34855SSanjay Patel     VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy,
11034e34855SSanjay Patel                                           CmpInst::makeCmpResultType(VecTy));
11134e34855SSanjay Patel   }
11234e34855SSanjay Patel 
113a69158c1SSanjay Patel   // Get cost estimates for the extract elements. These costs will factor into
11434e34855SSanjay Patel   // both sequences.
115a69158c1SSanjay Patel   unsigned Ext0Index = cast<ConstantInt>(Ext0->getOperand(1))->getZExtValue();
116a69158c1SSanjay Patel   unsigned Ext1Index = cast<ConstantInt>(Ext1->getOperand(1))->getZExtValue();
117a69158c1SSanjay Patel 
1186bdd531aSSanjay Patel   int Extract0Cost =
1196bdd531aSSanjay Patel       TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext0Index);
1206bdd531aSSanjay Patel   int Extract1Cost =
1216bdd531aSSanjay Patel       TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext1Index);
122a69158c1SSanjay Patel 
123a69158c1SSanjay Patel   // A more expensive extract will always be replaced by a splat shuffle.
124a69158c1SSanjay Patel   // For example, if Ext0 is more expensive:
125a69158c1SSanjay Patel   // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
126a69158c1SSanjay Patel   // extelt (opcode (splat V0, Ext0), V1), Ext1
127a69158c1SSanjay Patel   // TODO: Evaluate whether that always results in lowest cost. Alternatively,
128a69158c1SSanjay Patel   //       check the cost of creating a broadcast shuffle and shuffling both
129a69158c1SSanjay Patel   //       operands to element 0.
130a69158c1SSanjay Patel   int CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
13134e34855SSanjay Patel 
13234e34855SSanjay Patel   // Extra uses of the extracts mean that we include those costs in the
13334e34855SSanjay Patel   // vector total because those instructions will not be eliminated.
134e9c79a7aSSanjay Patel   int OldCost, NewCost;
135a69158c1SSanjay Patel   if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) {
136a69158c1SSanjay Patel     // Handle a special case. If the 2 extracts are identical, adjust the
13734e34855SSanjay Patel     // formulas to account for that. The extra use charge allows for either the
13834e34855SSanjay Patel     // CSE'd pattern or an unoptimized form with identical values:
13934e34855SSanjay Patel     // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
14034e34855SSanjay Patel     bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
14134e34855SSanjay Patel                                   : !Ext0->hasOneUse() || !Ext1->hasOneUse();
142a69158c1SSanjay Patel     OldCost = CheapExtractCost + ScalarOpCost;
143a69158c1SSanjay Patel     NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
14434e34855SSanjay Patel   } else {
14534e34855SSanjay Patel     // Handle the general case. Each extract is actually a different value:
146a69158c1SSanjay Patel     // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
147a69158c1SSanjay Patel     OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
148a69158c1SSanjay Patel     NewCost = VectorOpCost + CheapExtractCost +
149a69158c1SSanjay Patel               !Ext0->hasOneUse() * Extract0Cost +
150a69158c1SSanjay Patel               !Ext1->hasOneUse() * Extract1Cost;
15134e34855SSanjay Patel   }
152a69158c1SSanjay Patel 
153a69158c1SSanjay Patel   if (Ext0Index == Ext1Index) {
154a69158c1SSanjay Patel     // If the extract indexes are identical, no shuffle is needed.
155a69158c1SSanjay Patel     ConvertToShuffle = nullptr;
156a69158c1SSanjay Patel   } else {
157a69158c1SSanjay Patel     if (IsBinOp && DisableBinopExtractShuffle)
158a69158c1SSanjay Patel       return true;
159a69158c1SSanjay Patel 
160a69158c1SSanjay Patel     // If we are extracting from 2 different indexes, then one operand must be
161a69158c1SSanjay Patel     // shuffled before performing the vector operation. The shuffle mask is
162a69158c1SSanjay Patel     // undefined except for 1 lane that is being translated to the remaining
163a69158c1SSanjay Patel     // extraction lane. Therefore, it is a splat shuffle. Ex:
164a69158c1SSanjay Patel     // ShufMask = { undef, undef, 0, undef }
165a69158c1SSanjay Patel     // TODO: The cost model has an option for a "broadcast" shuffle
166a69158c1SSanjay Patel     //       (splat-from-element-0), but no option for a more general splat.
167a69158c1SSanjay Patel     NewCost +=
168a69158c1SSanjay Patel         TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
169a69158c1SSanjay Patel 
170ce97ce3aSSanjay Patel     // The more expensive extract will be replaced by a shuffle. If the costs
171ce97ce3aSSanjay Patel     // are equal and there is a preferred extract index, shuffle the opposite
172ce97ce3aSSanjay Patel     // operand. Otherwise, replace the extract with the higher index.
173a69158c1SSanjay Patel     if (Extract0Cost > Extract1Cost)
174a69158c1SSanjay Patel       ConvertToShuffle = Ext0;
175a69158c1SSanjay Patel     else if (Extract1Cost > Extract0Cost)
176a69158c1SSanjay Patel       ConvertToShuffle = Ext1;
177ce97ce3aSSanjay Patel     else if (PreferredExtractIndex == Ext0Index)
178ce97ce3aSSanjay Patel       ConvertToShuffle = Ext1;
179ce97ce3aSSanjay Patel     else if (PreferredExtractIndex == Ext1Index)
180ce97ce3aSSanjay Patel       ConvertToShuffle = Ext0;
181a69158c1SSanjay Patel     else
182a69158c1SSanjay Patel       ConvertToShuffle = Ext0Index > Ext1Index ? Ext0 : Ext1;
183a69158c1SSanjay Patel   }
184a69158c1SSanjay Patel 
18510ea01d8SSanjay Patel   // Aggressively form a vector op if the cost is equal because the transform
18610ea01d8SSanjay Patel   // may enable further optimization.
18710ea01d8SSanjay Patel   // Codegen can reverse this transform (scalarize) if it was not profitable.
18810ea01d8SSanjay Patel   return OldCost < NewCost;
18934e34855SSanjay Patel }
19034e34855SSanjay Patel 
191*9934cc54SSanjay Patel /// Create a shuffle that translates (shifts) 1 element from the input vector
192*9934cc54SSanjay Patel /// to a new element location.
193*9934cc54SSanjay Patel static Value *createShiftShuffle(Value *Vec, unsigned OldIndex,
194*9934cc54SSanjay Patel                                  unsigned NewIndex, IRBuilder<> &Builder) {
195*9934cc54SSanjay Patel   // The shuffle mask is undefined except for 1 lane that is being translated
196*9934cc54SSanjay Patel   // to the new element index. Example for OldIndex == 2 and NewIndex == 0:
197*9934cc54SSanjay Patel   // ShufMask = { 2, undef, undef, undef }
198*9934cc54SSanjay Patel   auto *VecTy = cast<FixedVectorType>(Vec->getType());
199*9934cc54SSanjay Patel   SmallVector<int, 32> ShufMask(VecTy->getNumElements(), -1);
200*9934cc54SSanjay Patel   ShufMask[NewIndex] = OldIndex;
201*9934cc54SSanjay Patel   Value *Undef = UndefValue::get(VecTy);
202*9934cc54SSanjay Patel   return Builder.CreateShuffleVector(Vec, Undef, ShufMask, "shift");
203*9934cc54SSanjay Patel }
204*9934cc54SSanjay Patel 
205216a37bbSSanjay Patel /// Given an extract element instruction with constant index operand, shuffle
206216a37bbSSanjay Patel /// the source vector (shift the scalar element) to a NewIndex for extraction.
207216a37bbSSanjay Patel /// Return null if the input can be constant folded, so that we are not creating
208216a37bbSSanjay Patel /// unnecessary instructions.
209*9934cc54SSanjay Patel static ExtractElementInst *translateExtract(ExtractElementInst *ExtElt,
210*9934cc54SSanjay Patel                                             unsigned NewIndex,
211*9934cc54SSanjay Patel                                             IRBuilder<> &Builder) {
212216a37bbSSanjay Patel   // If the extract can be constant-folded, this code is unsimplified. Defer
213216a37bbSSanjay Patel   // to other passes to handle that.
214216a37bbSSanjay Patel   Value *X = ExtElt->getVectorOperand();
215216a37bbSSanjay Patel   Value *C = ExtElt->getIndexOperand();
216de65b356SSanjay Patel   assert(isa<ConstantInt>(C) && "Expected a constant index operand");
217216a37bbSSanjay Patel   if (isa<Constant>(X))
218216a37bbSSanjay Patel     return nullptr;
219216a37bbSSanjay Patel 
220*9934cc54SSanjay Patel   Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(),
221*9934cc54SSanjay Patel                                    NewIndex, Builder);
222216a37bbSSanjay Patel   return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex));
223216a37bbSSanjay Patel }
224216a37bbSSanjay Patel 
225fc445589SSanjay Patel /// Try to reduce extract element costs by converting scalar compares to vector
226fc445589SSanjay Patel /// compares followed by extract.
227e9c79a7aSSanjay Patel /// cmp (ext0 V0, C), (ext1 V1, C)
228de65b356SSanjay Patel void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0,
229de65b356SSanjay Patel                                   ExtractElementInst *Ext1, Instruction &I) {
230fc445589SSanjay Patel   assert(isa<CmpInst>(&I) && "Expected a compare");
231216a37bbSSanjay Patel   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
232216a37bbSSanjay Patel              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
233216a37bbSSanjay Patel          "Expected matching constant extract indexes");
234a17f03bdSSanjay Patel 
235a17f03bdSSanjay Patel   // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C
236a17f03bdSSanjay Patel   ++NumVecCmp;
237fc445589SSanjay Patel   CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
238216a37bbSSanjay Patel   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
23946a285adSSanjay Patel   Value *VecCmp = Builder.CreateCmp(Pred, V0, V1);
240216a37bbSSanjay Patel   Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand());
24198c2f4eeSSanjay Patel   replaceValue(I, *NewExt);
242a17f03bdSSanjay Patel }
243a17f03bdSSanjay Patel 
24419b62b79SSanjay Patel /// Try to reduce extract element costs by converting scalar binops to vector
24519b62b79SSanjay Patel /// binops followed by extract.
246e9c79a7aSSanjay Patel /// bo (ext0 V0, C), (ext1 V1, C)
247de65b356SSanjay Patel void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0,
248de65b356SSanjay Patel                                     ExtractElementInst *Ext1, Instruction &I) {
249fc445589SSanjay Patel   assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
250216a37bbSSanjay Patel   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
251216a37bbSSanjay Patel              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
252216a37bbSSanjay Patel          "Expected matching constant extract indexes");
25319b62b79SSanjay Patel 
25434e34855SSanjay Patel   // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C
25519b62b79SSanjay Patel   ++NumVecBO;
256216a37bbSSanjay Patel   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
257e9c79a7aSSanjay Patel   Value *VecBO =
25834e34855SSanjay Patel       Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1);
259e9c79a7aSSanjay Patel 
26019b62b79SSanjay Patel   // All IR flags are safe to back-propagate because any potential poison
26119b62b79SSanjay Patel   // created in unused vector elements is discarded by the extract.
262e9c79a7aSSanjay Patel   if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
26319b62b79SSanjay Patel     VecBOInst->copyIRFlags(&I);
264e9c79a7aSSanjay Patel 
265216a37bbSSanjay Patel   Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand());
26698c2f4eeSSanjay Patel   replaceValue(I, *NewExt);
26719b62b79SSanjay Patel }
26819b62b79SSanjay Patel 
269fc445589SSanjay Patel /// Match an instruction with extracted vector operands.
2706bdd531aSSanjay Patel bool VectorCombine::foldExtractExtract(Instruction &I) {
271e9c79a7aSSanjay Patel   // It is not safe to transform things like div, urem, etc. because we may
272e9c79a7aSSanjay Patel   // create undefined behavior when executing those on unknown vector elements.
273e9c79a7aSSanjay Patel   if (!isSafeToSpeculativelyExecute(&I))
274e9c79a7aSSanjay Patel     return false;
275e9c79a7aSSanjay Patel 
276216a37bbSSanjay Patel   Instruction *I0, *I1;
277fc445589SSanjay Patel   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
278216a37bbSSanjay Patel   if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) &&
279216a37bbSSanjay Patel       !match(&I, m_BinOp(m_Instruction(I0), m_Instruction(I1))))
280fc445589SSanjay Patel     return false;
281fc445589SSanjay Patel 
282fc445589SSanjay Patel   Value *V0, *V1;
283fc445589SSanjay Patel   uint64_t C0, C1;
284216a37bbSSanjay Patel   if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
285216a37bbSSanjay Patel       !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) ||
286fc445589SSanjay Patel       V0->getType() != V1->getType())
287fc445589SSanjay Patel     return false;
288fc445589SSanjay Patel 
289ce97ce3aSSanjay Patel   // If the scalar value 'I' is going to be re-inserted into a vector, then try
290ce97ce3aSSanjay Patel   // to create an extract to that same element. The extract/insert can be
291ce97ce3aSSanjay Patel   // reduced to a "select shuffle".
292ce97ce3aSSanjay Patel   // TODO: If we add a larger pattern match that starts from an insert, this
293ce97ce3aSSanjay Patel   //       probably becomes unnecessary.
294216a37bbSSanjay Patel   auto *Ext0 = cast<ExtractElementInst>(I0);
295216a37bbSSanjay Patel   auto *Ext1 = cast<ExtractElementInst>(I1);
296ce97ce3aSSanjay Patel   uint64_t InsertIndex = std::numeric_limits<uint64_t>::max();
297ce97ce3aSSanjay Patel   if (I.hasOneUse())
2987eed772aSSanjay Patel     match(I.user_back(),
2997eed772aSSanjay Patel           m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
300ce97ce3aSSanjay Patel 
301216a37bbSSanjay Patel   ExtractElementInst *ExtractToChange;
3026bdd531aSSanjay Patel   if (isExtractExtractCheap(Ext0, Ext1, I.getOpcode(), ExtractToChange,
303ce97ce3aSSanjay Patel                             InsertIndex))
304fc445589SSanjay Patel     return false;
305e9c79a7aSSanjay Patel 
306216a37bbSSanjay Patel   if (ExtractToChange) {
307216a37bbSSanjay Patel     unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0;
308216a37bbSSanjay Patel     ExtractElementInst *NewExtract =
309*9934cc54SSanjay Patel         translateExtract(ExtractToChange, CheapExtractIdx, Builder);
310216a37bbSSanjay Patel     if (!NewExtract)
3116d864097SSanjay Patel       return false;
312216a37bbSSanjay Patel     if (ExtractToChange == Ext0)
313216a37bbSSanjay Patel       Ext0 = NewExtract;
314a69158c1SSanjay Patel     else
315216a37bbSSanjay Patel       Ext1 = NewExtract;
316a69158c1SSanjay Patel   }
317e9c79a7aSSanjay Patel 
318e9c79a7aSSanjay Patel   if (Pred != CmpInst::BAD_ICMP_PREDICATE)
319039ff29eSSanjay Patel     foldExtExtCmp(Ext0, Ext1, I);
320e9c79a7aSSanjay Patel   else
321039ff29eSSanjay Patel     foldExtExtBinop(Ext0, Ext1, I);
322e9c79a7aSSanjay Patel 
323e9c79a7aSSanjay Patel   return true;
324fc445589SSanjay Patel }
325fc445589SSanjay Patel 
326bef6e67eSSanjay Patel /// If this is a bitcast of a shuffle, try to bitcast the source vector to the
327bef6e67eSSanjay Patel /// destination type followed by shuffle. This can enable further transforms by
328bef6e67eSSanjay Patel /// moving bitcasts or shuffles together.
3296bdd531aSSanjay Patel bool VectorCombine::foldBitcastShuf(Instruction &I) {
330b6050ca1SSanjay Patel   Value *V;
331b6050ca1SSanjay Patel   ArrayRef<int> Mask;
3327eed772aSSanjay Patel   if (!match(&I, m_BitCast(
3337eed772aSSanjay Patel                      m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))))))
334b6050ca1SSanjay Patel     return false;
335b6050ca1SSanjay Patel 
336bef6e67eSSanjay Patel   // Disallow non-vector casts and length-changing shuffles.
337bef6e67eSSanjay Patel   // TODO: We could allow any shuffle.
3383297e9b7SChristopher Tetreault   auto *DestTy = dyn_cast<VectorType>(I.getType());
3393297e9b7SChristopher Tetreault   auto *SrcTy = cast<VectorType>(V->getType());
3403297e9b7SChristopher Tetreault   if (!DestTy || I.getOperand(0)->getType() != SrcTy)
341b6050ca1SSanjay Patel     return false;
342b6050ca1SSanjay Patel 
343b6050ca1SSanjay Patel   // The new shuffle must not cost more than the old shuffle. The bitcast is
344b6050ca1SSanjay Patel   // moved ahead of the shuffle, so assume that it has the same cost as before.
345b6050ca1SSanjay Patel   if (TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, DestTy) >
346b6050ca1SSanjay Patel       TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, SrcTy))
347b6050ca1SSanjay Patel     return false;
348b6050ca1SSanjay Patel 
349bef6e67eSSanjay Patel   unsigned DestNumElts = DestTy->getNumElements();
350bef6e67eSSanjay Patel   unsigned SrcNumElts = SrcTy->getNumElements();
351b6050ca1SSanjay Patel   SmallVector<int, 16> NewMask;
352bef6e67eSSanjay Patel   if (SrcNumElts <= DestNumElts) {
353bef6e67eSSanjay Patel     // The bitcast is from wide to narrow/equal elements. The shuffle mask can
354bef6e67eSSanjay Patel     // always be expanded to the equivalent form choosing narrower elements.
355b6050ca1SSanjay Patel     assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask");
356b6050ca1SSanjay Patel     unsigned ScaleFactor = DestNumElts / SrcNumElts;
3571318ddbcSSanjay Patel     narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
358bef6e67eSSanjay Patel   } else {
359bef6e67eSSanjay Patel     // The bitcast is from narrow elements to wide elements. The shuffle mask
360bef6e67eSSanjay Patel     // must choose consecutive elements to allow casting first.
361bef6e67eSSanjay Patel     assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask");
362bef6e67eSSanjay Patel     unsigned ScaleFactor = SrcNumElts / DestNumElts;
363bef6e67eSSanjay Patel     if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
364bef6e67eSSanjay Patel       return false;
365bef6e67eSSanjay Patel   }
366bef6e67eSSanjay Patel   // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC'
3677aeb41b3SRoman Lebedev   ++NumShufOfBitcast;
368bef6e67eSSanjay Patel   Value *CastV = Builder.CreateBitCast(V, DestTy);
3697eed772aSSanjay Patel   Value *Shuf =
3707eed772aSSanjay Patel       Builder.CreateShuffleVector(CastV, UndefValue::get(DestTy), NewMask);
37198c2f4eeSSanjay Patel   replaceValue(I, *Shuf);
372b6050ca1SSanjay Patel   return true;
373b6050ca1SSanjay Patel }
374b6050ca1SSanjay Patel 
375ed67f5e7SSanjay Patel /// Match a vector binop or compare instruction with at least one inserted
376ed67f5e7SSanjay Patel /// scalar operand and convert to scalar binop/cmp followed by insertelement.
3776bdd531aSSanjay Patel bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) {
378ed67f5e7SSanjay Patel   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
3795dc4e7c2SSimon Pilgrim   Value *Ins0, *Ins1;
380ed67f5e7SSanjay Patel   if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) &&
381ed67f5e7SSanjay Patel       !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1))))
382ed67f5e7SSanjay Patel     return false;
383ed67f5e7SSanjay Patel 
384ed67f5e7SSanjay Patel   // Do not convert the vector condition of a vector select into a scalar
385ed67f5e7SSanjay Patel   // condition. That may cause problems for codegen because of differences in
386ed67f5e7SSanjay Patel   // boolean formats and register-file transfers.
387ed67f5e7SSanjay Patel   // TODO: Can we account for that in the cost model?
388ed67f5e7SSanjay Patel   bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE;
389ed67f5e7SSanjay Patel   if (IsCmp)
390ed67f5e7SSanjay Patel     for (User *U : I.users())
391ed67f5e7SSanjay Patel       if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
3920d2a0b44SSanjay Patel         return false;
3930d2a0b44SSanjay Patel 
3945dc4e7c2SSimon Pilgrim   // Match against one or both scalar values being inserted into constant
3955dc4e7c2SSimon Pilgrim   // vectors:
396ed67f5e7SSanjay Patel   // vec_op VecC0, (inselt VecC1, V1, Index)
397ed67f5e7SSanjay Patel   // vec_op (inselt VecC0, V0, Index), VecC1
398ed67f5e7SSanjay Patel   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index)
3990d2a0b44SSanjay Patel   // TODO: Deal with mismatched index constants and variable indexes?
4005dc4e7c2SSimon Pilgrim   Constant *VecC0 = nullptr, *VecC1 = nullptr;
4015dc4e7c2SSimon Pilgrim   Value *V0 = nullptr, *V1 = nullptr;
4025dc4e7c2SSimon Pilgrim   uint64_t Index0 = 0, Index1 = 0;
4037eed772aSSanjay Patel   if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
4045dc4e7c2SSimon Pilgrim                                m_ConstantInt(Index0))) &&
4055dc4e7c2SSimon Pilgrim       !match(Ins0, m_Constant(VecC0)))
4065dc4e7c2SSimon Pilgrim     return false;
4075dc4e7c2SSimon Pilgrim   if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
4085dc4e7c2SSimon Pilgrim                                m_ConstantInt(Index1))) &&
4095dc4e7c2SSimon Pilgrim       !match(Ins1, m_Constant(VecC1)))
4100d2a0b44SSanjay Patel     return false;
4110d2a0b44SSanjay Patel 
4125dc4e7c2SSimon Pilgrim   bool IsConst0 = !V0;
4135dc4e7c2SSimon Pilgrim   bool IsConst1 = !V1;
4145dc4e7c2SSimon Pilgrim   if (IsConst0 && IsConst1)
4155dc4e7c2SSimon Pilgrim     return false;
4165dc4e7c2SSimon Pilgrim   if (!IsConst0 && !IsConst1 && Index0 != Index1)
4175dc4e7c2SSimon Pilgrim     return false;
4185dc4e7c2SSimon Pilgrim 
4195dc4e7c2SSimon Pilgrim   // Bail for single insertion if it is a load.
4205dc4e7c2SSimon Pilgrim   // TODO: Handle this once getVectorInstrCost can cost for load/stores.
4215dc4e7c2SSimon Pilgrim   auto *I0 = dyn_cast_or_null<Instruction>(V0);
4225dc4e7c2SSimon Pilgrim   auto *I1 = dyn_cast_or_null<Instruction>(V1);
4235dc4e7c2SSimon Pilgrim   if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
4245dc4e7c2SSimon Pilgrim       (IsConst1 && I0 && I0->mayReadFromMemory()))
4255dc4e7c2SSimon Pilgrim     return false;
4265dc4e7c2SSimon Pilgrim 
4275dc4e7c2SSimon Pilgrim   uint64_t Index = IsConst0 ? Index1 : Index0;
4285dc4e7c2SSimon Pilgrim   Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType();
4290d2a0b44SSanjay Patel   Type *VecTy = I.getType();
4305dc4e7c2SSimon Pilgrim   assert(VecTy->isVectorTy() &&
4315dc4e7c2SSimon Pilgrim          (IsConst0 || IsConst1 || V0->getType() == V1->getType()) &&
432741e20f3SSanjay Patel          (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
433741e20f3SSanjay Patel           ScalarTy->isPointerTy()) &&
434741e20f3SSanjay Patel          "Unexpected types for insert element into binop or cmp");
4350d2a0b44SSanjay Patel 
436ed67f5e7SSanjay Patel   unsigned Opcode = I.getOpcode();
437ed67f5e7SSanjay Patel   int ScalarOpCost, VectorOpCost;
438ed67f5e7SSanjay Patel   if (IsCmp) {
439ed67f5e7SSanjay Patel     ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy);
440ed67f5e7SSanjay Patel     VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy);
441ed67f5e7SSanjay Patel   } else {
442ed67f5e7SSanjay Patel     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
443ed67f5e7SSanjay Patel     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
444ed67f5e7SSanjay Patel   }
4450d2a0b44SSanjay Patel 
4460d2a0b44SSanjay Patel   // Get cost estimate for the insert element. This cost will factor into
4470d2a0b44SSanjay Patel   // both sequences.
4480d2a0b44SSanjay Patel   int InsertCost =
4490d2a0b44SSanjay Patel       TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, Index);
4505dc4e7c2SSimon Pilgrim   int OldCost = (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) +
4515dc4e7c2SSimon Pilgrim                 VectorOpCost;
4525f730b64SSanjay Patel   int NewCost = ScalarOpCost + InsertCost +
4535dc4e7c2SSimon Pilgrim                 (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) +
4545dc4e7c2SSimon Pilgrim                 (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost);
4550d2a0b44SSanjay Patel 
4560d2a0b44SSanjay Patel   // We want to scalarize unless the vector variant actually has lower cost.
4570d2a0b44SSanjay Patel   if (OldCost < NewCost)
4580d2a0b44SSanjay Patel     return false;
4590d2a0b44SSanjay Patel 
460ed67f5e7SSanjay Patel   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
461ed67f5e7SSanjay Patel   // inselt NewVecC, (scalar_op V0, V1), Index
462ed67f5e7SSanjay Patel   if (IsCmp)
463ed67f5e7SSanjay Patel     ++NumScalarCmp;
464ed67f5e7SSanjay Patel   else
4650d2a0b44SSanjay Patel     ++NumScalarBO;
4665dc4e7c2SSimon Pilgrim 
4675dc4e7c2SSimon Pilgrim   // For constant cases, extract the scalar element, this should constant fold.
4685dc4e7c2SSimon Pilgrim   if (IsConst0)
4695dc4e7c2SSimon Pilgrim     V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index));
4705dc4e7c2SSimon Pilgrim   if (IsConst1)
4715dc4e7c2SSimon Pilgrim     V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index));
4725dc4e7c2SSimon Pilgrim 
473ed67f5e7SSanjay Patel   Value *Scalar =
47446a285adSSanjay Patel       IsCmp ? Builder.CreateCmp(Pred, V0, V1)
475ed67f5e7SSanjay Patel             : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1);
476ed67f5e7SSanjay Patel 
477ed67f5e7SSanjay Patel   Scalar->setName(I.getName() + ".scalar");
4780d2a0b44SSanjay Patel 
4790d2a0b44SSanjay Patel   // All IR flags are safe to back-propagate. There is no potential for extra
4800d2a0b44SSanjay Patel   // poison to be created by the scalar instruction.
4810d2a0b44SSanjay Patel   if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
4820d2a0b44SSanjay Patel     ScalarInst->copyIRFlags(&I);
4830d2a0b44SSanjay Patel 
4840d2a0b44SSanjay Patel   // Fold the vector constants in the original vectors into a new base vector.
485ed67f5e7SSanjay Patel   Constant *NewVecC = IsCmp ? ConstantExpr::getCompare(Pred, VecC0, VecC1)
486ed67f5e7SSanjay Patel                             : ConstantExpr::get(Opcode, VecC0, VecC1);
4870d2a0b44SSanjay Patel   Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
48898c2f4eeSSanjay Patel   replaceValue(I, *Insert);
4890d2a0b44SSanjay Patel   return true;
4900d2a0b44SSanjay Patel }
4910d2a0b44SSanjay Patel 
492a17f03bdSSanjay Patel /// This is the entry point for all transforms. Pass manager differences are
493a17f03bdSSanjay Patel /// handled in the callers of this function.
4946bdd531aSSanjay Patel bool VectorCombine::run() {
49525c6544fSSanjay Patel   if (DisableVectorCombine)
49625c6544fSSanjay Patel     return false;
49725c6544fSSanjay Patel 
498a17f03bdSSanjay Patel   bool MadeChange = false;
499a17f03bdSSanjay Patel   for (BasicBlock &BB : F) {
500a17f03bdSSanjay Patel     // Ignore unreachable basic blocks.
501a17f03bdSSanjay Patel     if (!DT.isReachableFromEntry(&BB))
502a17f03bdSSanjay Patel       continue;
503a17f03bdSSanjay Patel     // Do not delete instructions under here and invalidate the iterator.
50481e9ede3SSanjay Patel     // Walk the block forwards to enable simple iterative chains of transforms.
505a17f03bdSSanjay Patel     // TODO: It could be more efficient to remove dead instructions
506a17f03bdSSanjay Patel     //       iteratively in this loop rather than waiting until the end.
50781e9ede3SSanjay Patel     for (Instruction &I : BB) {
508fc3cc8a4SSanjay Patel       if (isa<DbgInfoIntrinsic>(I))
509fc3cc8a4SSanjay Patel         continue;
510de65b356SSanjay Patel       Builder.SetInsertPoint(&I);
5116bdd531aSSanjay Patel       MadeChange |= foldExtractExtract(I);
5126bdd531aSSanjay Patel       MadeChange |= foldBitcastShuf(I);
5136bdd531aSSanjay Patel       MadeChange |= scalarizeBinopOrCmp(I);
514a17f03bdSSanjay Patel     }
515fc3cc8a4SSanjay Patel   }
516a17f03bdSSanjay Patel 
517a17f03bdSSanjay Patel   // We're done with transforms, so remove dead instructions.
518a17f03bdSSanjay Patel   if (MadeChange)
519a17f03bdSSanjay Patel     for (BasicBlock &BB : F)
520a17f03bdSSanjay Patel       SimplifyInstructionsInBlock(&BB);
521a17f03bdSSanjay Patel 
522a17f03bdSSanjay Patel   return MadeChange;
523a17f03bdSSanjay Patel }
524a17f03bdSSanjay Patel 
525a17f03bdSSanjay Patel // Pass manager boilerplate below here.
526a17f03bdSSanjay Patel 
527a17f03bdSSanjay Patel namespace {
528a17f03bdSSanjay Patel class VectorCombineLegacyPass : public FunctionPass {
529a17f03bdSSanjay Patel public:
530a17f03bdSSanjay Patel   static char ID;
531a17f03bdSSanjay Patel   VectorCombineLegacyPass() : FunctionPass(ID) {
532a17f03bdSSanjay Patel     initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry());
533a17f03bdSSanjay Patel   }
534a17f03bdSSanjay Patel 
535a17f03bdSSanjay Patel   void getAnalysisUsage(AnalysisUsage &AU) const override {
536a17f03bdSSanjay Patel     AU.addRequired<DominatorTreeWrapperPass>();
537a17f03bdSSanjay Patel     AU.addRequired<TargetTransformInfoWrapperPass>();
538a17f03bdSSanjay Patel     AU.setPreservesCFG();
539a17f03bdSSanjay Patel     AU.addPreserved<DominatorTreeWrapperPass>();
540a17f03bdSSanjay Patel     AU.addPreserved<GlobalsAAWrapperPass>();
541024098aeSSanjay Patel     AU.addPreserved<AAResultsWrapperPass>();
542024098aeSSanjay Patel     AU.addPreserved<BasicAAWrapperPass>();
543a17f03bdSSanjay Patel     FunctionPass::getAnalysisUsage(AU);
544a17f03bdSSanjay Patel   }
545a17f03bdSSanjay Patel 
546a17f03bdSSanjay Patel   bool runOnFunction(Function &F) override {
547a17f03bdSSanjay Patel     if (skipFunction(F))
548a17f03bdSSanjay Patel       return false;
549a17f03bdSSanjay Patel     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
550a17f03bdSSanjay Patel     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5516bdd531aSSanjay Patel     VectorCombine Combiner(F, TTI, DT);
5526bdd531aSSanjay Patel     return Combiner.run();
553a17f03bdSSanjay Patel   }
554a17f03bdSSanjay Patel };
555a17f03bdSSanjay Patel } // namespace
556a17f03bdSSanjay Patel 
557a17f03bdSSanjay Patel char VectorCombineLegacyPass::ID = 0;
558a17f03bdSSanjay Patel INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine",
559a17f03bdSSanjay Patel                       "Optimize scalar/vector ops", false,
560a17f03bdSSanjay Patel                       false)
561a17f03bdSSanjay Patel INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
562a17f03bdSSanjay Patel INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine",
563a17f03bdSSanjay Patel                     "Optimize scalar/vector ops", false, false)
564a17f03bdSSanjay Patel Pass *llvm::createVectorCombinePass() {
565a17f03bdSSanjay Patel   return new VectorCombineLegacyPass();
566a17f03bdSSanjay Patel }
567a17f03bdSSanjay Patel 
568a17f03bdSSanjay Patel PreservedAnalyses VectorCombinePass::run(Function &F,
569a17f03bdSSanjay Patel                                          FunctionAnalysisManager &FAM) {
570a17f03bdSSanjay Patel   TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
571a17f03bdSSanjay Patel   DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
5726bdd531aSSanjay Patel   VectorCombine Combiner(F, TTI, DT);
5736bdd531aSSanjay Patel   if (!Combiner.run())
574a17f03bdSSanjay Patel     return PreservedAnalyses::all();
575a17f03bdSSanjay Patel   PreservedAnalyses PA;
576a17f03bdSSanjay Patel   PA.preserveSet<CFGAnalyses>();
577a17f03bdSSanjay Patel   PA.preserve<GlobalsAA>();
578024098aeSSanjay Patel   PA.preserve<AAManager>();
579024098aeSSanjay Patel   PA.preserve<BasicAA>();
580a17f03bdSSanjay Patel   return PA;
581a17f03bdSSanjay Patel }
582