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/TargetTransformInfo.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/Analysis/VectorUtils.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/PatternMatch.h"
26 #include "llvm/InitializePasses.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/Transforms/Vectorize.h"
31 
32 using namespace llvm;
33 using namespace llvm::PatternMatch;
34 
35 #define DEBUG_TYPE "vector-combine"
36 STATISTIC(NumVecCmp, "Number of vector compares formed");
37 STATISTIC(NumVecBO, "Number of vector binops formed");
38 STATISTIC(NumScalarBO, "Number of scalar binops formed");
39 
40 static cl::opt<bool> DisableVectorCombine(
41     "disable-vector-combine", cl::init(false), cl::Hidden,
42     cl::desc("Disable all vector combine transforms"));
43 
44 static cl::opt<bool> DisableBinopExtractShuffle(
45     "disable-binop-extract-shuffle", cl::init(false), cl::Hidden,
46     cl::desc("Disable binop extract to shuffle transforms"));
47 
48 
49 /// Compare the relative costs of 2 extracts followed by scalar operation vs.
50 /// vector operation(s) followed by extract. Return true if the existing
51 /// instructions are cheaper than a vector alternative. Otherwise, return false
52 /// and if one of the extracts should be transformed to a shufflevector, set
53 /// \p ConvertToShuffle to that extract instruction.
54 static bool isExtractExtractCheap(Instruction *Ext0, Instruction *Ext1,
55                                   unsigned Opcode,
56                                   const TargetTransformInfo &TTI,
57                                   Instruction *&ConvertToShuffle,
58                                   unsigned PreferredExtractIndex) {
59   assert(isa<ConstantInt>(Ext0->getOperand(1)) &&
60          isa<ConstantInt>(Ext1->getOperand(1)) &&
61          "Expected constant extract indexes");
62   Type *ScalarTy = Ext0->getType();
63   auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType());
64   int ScalarOpCost, VectorOpCost;
65 
66   // Get cost estimates for scalar and vector versions of the operation.
67   bool IsBinOp = Instruction::isBinaryOp(Opcode);
68   if (IsBinOp) {
69     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
70     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
71   } else {
72     assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
73            "Expected a compare");
74     ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy,
75                                           CmpInst::makeCmpResultType(ScalarTy));
76     VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy,
77                                           CmpInst::makeCmpResultType(VecTy));
78   }
79 
80   // Get cost estimates for the extract elements. These costs will factor into
81   // both sequences.
82   unsigned Ext0Index = cast<ConstantInt>(Ext0->getOperand(1))->getZExtValue();
83   unsigned Ext1Index = cast<ConstantInt>(Ext1->getOperand(1))->getZExtValue();
84 
85   int Extract0Cost = TTI.getVectorInstrCost(Instruction::ExtractElement,
86                                             VecTy, Ext0Index);
87   int Extract1Cost = TTI.getVectorInstrCost(Instruction::ExtractElement,
88                                             VecTy, Ext1Index);
89 
90   // A more expensive extract will always be replaced by a splat shuffle.
91   // For example, if Ext0 is more expensive:
92   // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
93   // extelt (opcode (splat V0, Ext0), V1), Ext1
94   // TODO: Evaluate whether that always results in lowest cost. Alternatively,
95   //       check the cost of creating a broadcast shuffle and shuffling both
96   //       operands to element 0.
97   int CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
98 
99   // Extra uses of the extracts mean that we include those costs in the
100   // vector total because those instructions will not be eliminated.
101   int OldCost, NewCost;
102   if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) {
103     // Handle a special case. If the 2 extracts are identical, adjust the
104     // formulas to account for that. The extra use charge allows for either the
105     // CSE'd pattern or an unoptimized form with identical values:
106     // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
107     bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
108                                   : !Ext0->hasOneUse() || !Ext1->hasOneUse();
109     OldCost = CheapExtractCost + ScalarOpCost;
110     NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
111   } else {
112     // Handle the general case. Each extract is actually a different value:
113     // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
114     OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
115     NewCost = VectorOpCost + CheapExtractCost +
116               !Ext0->hasOneUse() * Extract0Cost +
117               !Ext1->hasOneUse() * Extract1Cost;
118   }
119 
120   if (Ext0Index == Ext1Index) {
121     // If the extract indexes are identical, no shuffle is needed.
122     ConvertToShuffle = nullptr;
123   } else {
124     if (IsBinOp && DisableBinopExtractShuffle)
125       return true;
126 
127     // If we are extracting from 2 different indexes, then one operand must be
128     // shuffled before performing the vector operation. The shuffle mask is
129     // undefined except for 1 lane that is being translated to the remaining
130     // extraction lane. Therefore, it is a splat shuffle. Ex:
131     // ShufMask = { undef, undef, 0, undef }
132     // TODO: The cost model has an option for a "broadcast" shuffle
133     //       (splat-from-element-0), but no option for a more general splat.
134     NewCost +=
135         TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
136 
137     // The more expensive extract will be replaced by a shuffle. If the costs
138     // are equal and there is a preferred extract index, shuffle the opposite
139     // operand. Otherwise, replace the extract with the higher index.
140     if (Extract0Cost > Extract1Cost)
141       ConvertToShuffle = Ext0;
142     else if (Extract1Cost > Extract0Cost)
143       ConvertToShuffle = Ext1;
144     else if (PreferredExtractIndex == Ext0Index)
145       ConvertToShuffle = Ext1;
146     else if (PreferredExtractIndex == Ext1Index)
147       ConvertToShuffle = Ext0;
148     else
149       ConvertToShuffle = Ext0Index > Ext1Index ? Ext0 : Ext1;
150   }
151 
152   // Aggressively form a vector op if the cost is equal because the transform
153   // may enable further optimization.
154   // Codegen can reverse this transform (scalarize) if it was not profitable.
155   return OldCost < NewCost;
156 }
157 
158 /// Try to reduce extract element costs by converting scalar compares to vector
159 /// compares followed by extract.
160 /// cmp (ext0 V0, C), (ext1 V1, C)
161 static void foldExtExtCmp(Instruction *Ext0, Instruction *Ext1,
162                           Instruction &I, const TargetTransformInfo &TTI) {
163   assert(isa<CmpInst>(&I) && "Expected a compare");
164 
165   // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C
166   ++NumVecCmp;
167   IRBuilder<> Builder(&I);
168   CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
169   Value *V0 = Ext0->getOperand(0), *V1 = Ext1->getOperand(0);
170   Value *VecCmp =
171       Ext0->getType()->isFloatingPointTy() ? Builder.CreateFCmp(Pred, V0, V1)
172                                            : Builder.CreateICmp(Pred, V0, V1);
173   Value *Extract = Builder.CreateExtractElement(VecCmp, Ext0->getOperand(1));
174   I.replaceAllUsesWith(Extract);
175 }
176 
177 /// Try to reduce extract element costs by converting scalar binops to vector
178 /// binops followed by extract.
179 /// bo (ext0 V0, C), (ext1 V1, C)
180 static void foldExtExtBinop(Instruction *Ext0, Instruction *Ext1,
181                             Instruction &I, const TargetTransformInfo &TTI) {
182   assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
183 
184   // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C
185   ++NumVecBO;
186   IRBuilder<> Builder(&I);
187   Value *V0 = Ext0->getOperand(0), *V1 = Ext1->getOperand(0);
188   Value *VecBO =
189       Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1);
190 
191   // All IR flags are safe to back-propagate because any potential poison
192   // created in unused vector elements is discarded by the extract.
193   if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
194     VecBOInst->copyIRFlags(&I);
195 
196   Value *Extract = Builder.CreateExtractElement(VecBO, Ext0->getOperand(1));
197   I.replaceAllUsesWith(Extract);
198 }
199 
200 /// Match an instruction with extracted vector operands.
201 static bool foldExtractExtract(Instruction &I, const TargetTransformInfo &TTI) {
202   // It is not safe to transform things like div, urem, etc. because we may
203   // create undefined behavior when executing those on unknown vector elements.
204   if (!isSafeToSpeculativelyExecute(&I))
205     return false;
206 
207   Instruction *Ext0, *Ext1;
208   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
209   if (!match(&I, m_Cmp(Pred, m_Instruction(Ext0), m_Instruction(Ext1))) &&
210       !match(&I, m_BinOp(m_Instruction(Ext0), m_Instruction(Ext1))))
211     return false;
212 
213   Value *V0, *V1;
214   uint64_t C0, C1;
215   if (!match(Ext0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
216       !match(Ext1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) ||
217       V0->getType() != V1->getType())
218     return false;
219 
220   // If the scalar value 'I' is going to be re-inserted into a vector, then try
221   // to create an extract to that same element. The extract/insert can be
222   // reduced to a "select shuffle".
223   // TODO: If we add a larger pattern match that starts from an insert, this
224   //       probably becomes unnecessary.
225   uint64_t InsertIndex = std::numeric_limits<uint64_t>::max();
226   if (I.hasOneUse())
227     match(I.user_back(),
228           m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
229 
230   Instruction *ConvertToShuffle;
231   if (isExtractExtractCheap(Ext0, Ext1, I.getOpcode(), TTI, ConvertToShuffle,
232                             InsertIndex))
233     return false;
234 
235   if (ConvertToShuffle) {
236     // The shuffle mask is undefined except for 1 lane that is being translated
237     // to the cheap extraction lane. Example:
238     // ShufMask = { 2, undef, undef, undef }
239     uint64_t SplatIndex = ConvertToShuffle == Ext0 ? C0 : C1;
240     uint64_t CheapExtIndex = ConvertToShuffle == Ext0 ? C1 : C0;
241     auto *VecTy = cast<VectorType>(V0->getType());
242     SmallVector<int, 32> ShufMask(VecTy->getNumElements(), -1);
243     ShufMask[CheapExtIndex] = SplatIndex;
244     IRBuilder<> Builder(ConvertToShuffle);
245 
246     // extelt X, C --> extelt (splat X), C'
247     Value *Shuf = Builder.CreateShuffleVector(ConvertToShuffle->getOperand(0),
248                                               UndefValue::get(VecTy), ShufMask);
249     Value *NewExt = Builder.CreateExtractElement(Shuf, CheapExtIndex);
250     if (ConvertToShuffle == Ext0)
251       Ext0 = cast<Instruction>(NewExt);
252     else
253       Ext1 = cast<Instruction>(NewExt);
254   }
255 
256   if (Pred != CmpInst::BAD_ICMP_PREDICATE)
257     foldExtExtCmp(Ext0, Ext1, I, TTI);
258   else
259     foldExtExtBinop(Ext0, Ext1, I, TTI);
260 
261   return true;
262 }
263 
264 /// If this is a bitcast of a shuffle, try to bitcast the source vector to the
265 /// destination type followed by shuffle. This can enable further transforms by
266 /// moving bitcasts or shuffles together.
267 static bool foldBitcastShuf(Instruction &I, const TargetTransformInfo &TTI) {
268   Value *V;
269   ArrayRef<int> Mask;
270   if (!match(&I, m_BitCast(
271                      m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))))))
272     return false;
273 
274   // Disallow non-vector casts and length-changing shuffles.
275   // TODO: We could allow any shuffle.
276   auto *DestTy = dyn_cast<VectorType>(I.getType());
277   auto *SrcTy = cast<VectorType>(V->getType());
278   if (!DestTy || I.getOperand(0)->getType() != SrcTy)
279     return false;
280 
281   // The new shuffle must not cost more than the old shuffle. The bitcast is
282   // moved ahead of the shuffle, so assume that it has the same cost as before.
283   if (TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, DestTy) >
284       TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, SrcTy))
285     return false;
286 
287   unsigned DestNumElts = DestTy->getNumElements();
288   unsigned SrcNumElts = SrcTy->getNumElements();
289   SmallVector<int, 16> NewMask;
290   if (SrcNumElts <= DestNumElts) {
291     // The bitcast is from wide to narrow/equal elements. The shuffle mask can
292     // always be expanded to the equivalent form choosing narrower elements.
293     assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask");
294     unsigned ScaleFactor = DestNumElts / SrcNumElts;
295     narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
296   } else {
297     // The bitcast is from narrow elements to wide elements. The shuffle mask
298     // must choose consecutive elements to allow casting first.
299     assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask");
300     unsigned ScaleFactor = SrcNumElts / DestNumElts;
301     if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
302       return false;
303   }
304   // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC'
305   IRBuilder<> Builder(&I);
306   Value *CastV = Builder.CreateBitCast(V, DestTy);
307   Value *Shuf =
308       Builder.CreateShuffleVector(CastV, UndefValue::get(DestTy), NewMask);
309   I.replaceAllUsesWith(Shuf);
310   return true;
311 }
312 
313 /// Match a vector binop instruction with inserted scalar operands and convert
314 /// to scalar binop followed by insertelement.
315 static bool scalarizeBinop(Instruction &I, const TargetTransformInfo &TTI) {
316   Instruction *Ins0, *Ins1;
317   if (!match(&I, m_BinOp(m_Instruction(Ins0), m_Instruction(Ins1))))
318     return false;
319 
320   // TODO: Deal with mismatched index constants and variable indexes?
321   Constant *VecC0, *VecC1;
322   Value *V0, *V1;
323   uint64_t Index;
324   if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
325                                m_ConstantInt(Index))) ||
326       !match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
327                                m_SpecificInt(Index))))
328     return false;
329 
330   Type *ScalarTy = V0->getType();
331   Type *VecTy = I.getType();
332   assert(VecTy->isVectorTy() && ScalarTy == V1->getType() &&
333          (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy()) &&
334          "Unexpected types for insert into binop");
335 
336   Instruction::BinaryOps Opcode = cast<BinaryOperator>(&I)->getOpcode();
337   int ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
338   int VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
339 
340   // Get cost estimate for the insert element. This cost will factor into
341   // both sequences.
342   int InsertCost =
343       TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, Index);
344   int OldCost = InsertCost + InsertCost + VectorOpCost;
345   int NewCost = ScalarOpCost + InsertCost +
346                 !Ins0->hasOneUse() * InsertCost +
347                 !Ins1->hasOneUse() * InsertCost;
348 
349   // We want to scalarize unless the vector variant actually has lower cost.
350   if (OldCost < NewCost)
351     return false;
352 
353   // vec_bo (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
354   // inselt NewVecC, (scalar_bo V0, V1), Index
355   ++NumScalarBO;
356   IRBuilder<> Builder(&I);
357   Value *Scalar = Builder.CreateBinOp(Opcode, V0, V1, I.getName() + ".scalar");
358 
359   // All IR flags are safe to back-propagate. There is no potential for extra
360   // poison to be created by the scalar instruction.
361   if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
362     ScalarInst->copyIRFlags(&I);
363 
364   // Fold the vector constants in the original vectors into a new base vector.
365   Constant *NewVecC = ConstantExpr::get(Opcode, VecC0, VecC1);
366   Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
367   I.replaceAllUsesWith(Insert);
368   Insert->takeName(&I);
369   return true;
370 }
371 
372 /// This is the entry point for all transforms. Pass manager differences are
373 /// handled in the callers of this function.
374 static bool runImpl(Function &F, const TargetTransformInfo &TTI,
375                     const DominatorTree &DT) {
376   if (DisableVectorCombine)
377     return false;
378 
379   bool MadeChange = false;
380   for (BasicBlock &BB : F) {
381     // Ignore unreachable basic blocks.
382     if (!DT.isReachableFromEntry(&BB))
383       continue;
384     // Do not delete instructions under here and invalidate the iterator.
385     // Walk the block forwards to enable simple iterative chains of transforms.
386     // TODO: It could be more efficient to remove dead instructions
387     //       iteratively in this loop rather than waiting until the end.
388     for (Instruction &I : BB) {
389       if (isa<DbgInfoIntrinsic>(I))
390         continue;
391       MadeChange |= foldExtractExtract(I, TTI);
392       MadeChange |= foldBitcastShuf(I, TTI);
393       MadeChange |= scalarizeBinop(I, TTI);
394     }
395   }
396 
397   // We're done with transforms, so remove dead instructions.
398   if (MadeChange)
399     for (BasicBlock &BB : F)
400       SimplifyInstructionsInBlock(&BB);
401 
402   return MadeChange;
403 }
404 
405 // Pass manager boilerplate below here.
406 
407 namespace {
408 class VectorCombineLegacyPass : public FunctionPass {
409 public:
410   static char ID;
411   VectorCombineLegacyPass() : FunctionPass(ID) {
412     initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry());
413   }
414 
415   void getAnalysisUsage(AnalysisUsage &AU) const override {
416     AU.addRequired<DominatorTreeWrapperPass>();
417     AU.addRequired<TargetTransformInfoWrapperPass>();
418     AU.setPreservesCFG();
419     AU.addPreserved<DominatorTreeWrapperPass>();
420     AU.addPreserved<GlobalsAAWrapperPass>();
421     AU.addPreserved<AAResultsWrapperPass>();
422     AU.addPreserved<BasicAAWrapperPass>();
423     FunctionPass::getAnalysisUsage(AU);
424   }
425 
426   bool runOnFunction(Function &F) override {
427     if (skipFunction(F))
428       return false;
429     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
430     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
431     return runImpl(F, TTI, DT);
432   }
433 };
434 } // namespace
435 
436 char VectorCombineLegacyPass::ID = 0;
437 INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine",
438                       "Optimize scalar/vector ops", false,
439                       false)
440 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
441 INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine",
442                     "Optimize scalar/vector ops", false, false)
443 Pass *llvm::createVectorCombinePass() {
444   return new VectorCombineLegacyPass();
445 }
446 
447 PreservedAnalyses VectorCombinePass::run(Function &F,
448                                          FunctionAnalysisManager &FAM) {
449   TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
450   DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
451   if (!runImpl(F, TTI, DT))
452     return PreservedAnalyses::all();
453   PreservedAnalyses PA;
454   PA.preserveSet<CFGAnalyses>();
455   PA.preserve<GlobalsAA>();
456   PA.preserve<AAManager>();
457   PA.preserve<BasicAA>();
458   return PA;
459 }
460