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"
1943bdac29SSanjay Patel #include "llvm/Analysis/Loads.h"
20a17f03bdSSanjay Patel #include "llvm/Analysis/TargetTransformInfo.h"
2119b62b79SSanjay Patel #include "llvm/Analysis/ValueTracking.h"
22b6050ca1SSanjay Patel #include "llvm/Analysis/VectorUtils.h"
23a17f03bdSSanjay Patel #include "llvm/IR/Dominators.h"
24a17f03bdSSanjay Patel #include "llvm/IR/Function.h"
25a17f03bdSSanjay Patel #include "llvm/IR/IRBuilder.h"
26a17f03bdSSanjay Patel #include "llvm/IR/PatternMatch.h"
27a17f03bdSSanjay Patel #include "llvm/InitializePasses.h"
28a17f03bdSSanjay Patel #include "llvm/Pass.h"
2925c6544fSSanjay Patel #include "llvm/Support/CommandLine.h"
30a17f03bdSSanjay Patel #include "llvm/Transforms/Utils/Local.h"
315006e551SSimon Pilgrim #include "llvm/Transforms/Vectorize.h"
32a17f03bdSSanjay Patel 
33a17f03bdSSanjay Patel using namespace llvm;
34a17f03bdSSanjay Patel using namespace llvm::PatternMatch;
35a17f03bdSSanjay Patel 
36a17f03bdSSanjay Patel #define DEBUG_TYPE "vector-combine"
3743bdac29SSanjay Patel STATISTIC(NumVecLoad, "Number of vector loads formed");
38a17f03bdSSanjay Patel STATISTIC(NumVecCmp, "Number of vector compares formed");
3919b62b79SSanjay Patel STATISTIC(NumVecBO, "Number of vector binops formed");
40b6315aeeSSanjay Patel STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed");
417aeb41b3SRoman Lebedev STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
420d2a0b44SSanjay Patel STATISTIC(NumScalarBO, "Number of scalar binops formed");
43ed67f5e7SSanjay Patel STATISTIC(NumScalarCmp, "Number of scalar compares formed");
44a17f03bdSSanjay Patel 
4525c6544fSSanjay Patel static cl::opt<bool> DisableVectorCombine(
4625c6544fSSanjay Patel     "disable-vector-combine", cl::init(false), cl::Hidden,
4725c6544fSSanjay Patel     cl::desc("Disable all vector combine transforms"));
4825c6544fSSanjay Patel 
49a69158c1SSanjay Patel static cl::opt<bool> DisableBinopExtractShuffle(
50a69158c1SSanjay Patel     "disable-binop-extract-shuffle", cl::init(false), cl::Hidden,
51a69158c1SSanjay Patel     cl::desc("Disable binop extract to shuffle transforms"));
52a69158c1SSanjay Patel 
53a0f96741SSanjay Patel static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max();
54a0f96741SSanjay Patel 
55b4447054SBenjamin Kramer namespace {
566bdd531aSSanjay Patel class VectorCombine {
576bdd531aSSanjay Patel public:
586bdd531aSSanjay Patel   VectorCombine(Function &F, const TargetTransformInfo &TTI,
596bdd531aSSanjay Patel                 const DominatorTree &DT)
60de65b356SSanjay Patel       : F(F), Builder(F.getContext()), TTI(TTI), DT(DT) {}
616bdd531aSSanjay Patel 
626bdd531aSSanjay Patel   bool run();
636bdd531aSSanjay Patel 
646bdd531aSSanjay Patel private:
656bdd531aSSanjay Patel   Function &F;
66de65b356SSanjay Patel   IRBuilder<> Builder;
676bdd531aSSanjay Patel   const TargetTransformInfo &TTI;
686bdd531aSSanjay Patel   const DominatorTree &DT;
696bdd531aSSanjay Patel 
7043bdac29SSanjay Patel   bool vectorizeLoadInsert(Instruction &I);
713b95d834SSanjay Patel   ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0,
723b95d834SSanjay Patel                                         ExtractElementInst *Ext1,
733b95d834SSanjay Patel                                         unsigned PreferredExtractIndex) const;
746bdd531aSSanjay Patel   bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
756bdd531aSSanjay Patel                              unsigned Opcode,
766bdd531aSSanjay Patel                              ExtractElementInst *&ConvertToShuffle,
776bdd531aSSanjay Patel                              unsigned PreferredExtractIndex);
78de65b356SSanjay Patel   void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
79de65b356SSanjay Patel                      Instruction &I);
80de65b356SSanjay Patel   void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
81de65b356SSanjay Patel                        Instruction &I);
826bdd531aSSanjay Patel   bool foldExtractExtract(Instruction &I);
836bdd531aSSanjay Patel   bool foldBitcastShuf(Instruction &I);
846bdd531aSSanjay Patel   bool scalarizeBinopOrCmp(Instruction &I);
85b6315aeeSSanjay Patel   bool foldExtractedCmps(Instruction &I);
866bdd531aSSanjay Patel };
87b4447054SBenjamin Kramer } // namespace
88a69158c1SSanjay Patel 
8998c2f4eeSSanjay Patel static void replaceValue(Value &Old, Value &New) {
9098c2f4eeSSanjay Patel   Old.replaceAllUsesWith(&New);
9198c2f4eeSSanjay Patel   New.takeName(&Old);
9298c2f4eeSSanjay Patel }
9398c2f4eeSSanjay Patel 
9443bdac29SSanjay Patel bool VectorCombine::vectorizeLoadInsert(Instruction &I) {
95*b2ef2640SSanjay Patel   // Match insert into fixed vector of scalar value.
96ddd9575dSSanjay Patel   auto *Ty = dyn_cast<FixedVectorType>(I.getType());
9743bdac29SSanjay Patel   Value *Scalar;
9848a23bccSSanjay Patel   if (!Ty || !match(&I, m_InsertElt(m_Undef(), m_Value(Scalar), m_ZeroInt())) ||
9948a23bccSSanjay Patel       !Scalar->hasOneUse())
10043bdac29SSanjay Patel     return false;
101ddd9575dSSanjay Patel 
102*b2ef2640SSanjay Patel   // Optionally match an extract from another vector.
103*b2ef2640SSanjay Patel   Value *X;
104*b2ef2640SSanjay Patel   bool HasExtract = match(Scalar, m_ExtractElt(m_Value(X), m_ZeroInt()));
105*b2ef2640SSanjay Patel   if (!HasExtract)
106*b2ef2640SSanjay Patel     X = Scalar;
107*b2ef2640SSanjay Patel 
108*b2ef2640SSanjay Patel   // Match source value as load of scalar or vector.
1094452cc40SFangrui Song   // Do not vectorize scalar load (widening) if atomic/volatile or under
1104452cc40SFangrui Song   // asan/hwasan/memtag/tsan. The widened load may load data from dirty regions
1114452cc40SFangrui Song   // or create data races non-existent in the source.
112*b2ef2640SSanjay Patel   auto *Load = dyn_cast<LoadInst>(X);
113*b2ef2640SSanjay Patel   if (!Load || !Load->isSimple() || !Load->hasOneUse() ||
1144452cc40SFangrui Song       Load->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag) ||
1154452cc40SFangrui Song       mustSuppressSpeculation(*Load))
11643bdac29SSanjay Patel     return false;
11743bdac29SSanjay Patel 
11843bdac29SSanjay Patel   // TODO: Extend this to match GEP with constant offsets.
11943bdac29SSanjay Patel   Value *PtrOp = Load->getPointerOperand()->stripPointerCasts();
12043bdac29SSanjay Patel   assert(isa<PointerType>(PtrOp->getType()) && "Expected a pointer type");
121c36c0fabSArtem Belevich   unsigned AS = Load->getPointerAddressSpace();
122c36c0fabSArtem Belevich 
123c36c0fabSArtem Belevich   // If original AS != Load's AS, we can't bitcast the original pointer and have
124c36c0fabSArtem Belevich   // to use Load's operand instead. Ideally we would want to strip pointer casts
125c36c0fabSArtem Belevich   // without changing AS, but there's no API to do that ATM.
126c36c0fabSArtem Belevich   if (AS != PtrOp->getType()->getPointerAddressSpace())
127c36c0fabSArtem Belevich     PtrOp = Load->getPointerOperand();
12843bdac29SSanjay Patel 
129ddd9575dSSanjay Patel   Type *ScalarTy = Scalar->getType();
13043bdac29SSanjay Patel   uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
131ddd9575dSSanjay Patel   unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
1328fb05593SSanjay Patel   if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0)
13343bdac29SSanjay Patel     return false;
13443bdac29SSanjay Patel 
13543bdac29SSanjay Patel   // Check safety of replacing the scalar load with a larger vector load.
1368fb05593SSanjay Patel   unsigned MinVecNumElts = MinVectorSize / ScalarSize;
1378fb05593SSanjay Patel   auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts, false);
13843bdac29SSanjay Patel   Align Alignment = Load->getAlign();
13943bdac29SSanjay Patel   const DataLayout &DL = I.getModule()->getDataLayout();
1408fb05593SSanjay Patel   if (!isSafeToLoadUnconditionally(PtrOp, MinVecTy, Alignment, DL, Load, &DT))
14143bdac29SSanjay Patel     return false;
14243bdac29SSanjay Patel 
14311446b02SBjorn Pettersson 
144*b2ef2640SSanjay Patel   // Original pattern: insertelt undef, load [free casts of] PtrOp, 0
145*b2ef2640SSanjay Patel   Type *LoadTy = Load->getType();
146*b2ef2640SSanjay Patel   int OldCost = TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS);
1478fb05593SSanjay Patel   APInt DemandedElts = APInt::getOneBitSet(MinVecNumElts, 0);
148*b2ef2640SSanjay Patel   OldCost += TTI.getScalarizationOverhead(MinVecTy, DemandedElts,
149*b2ef2640SSanjay Patel                                           /* Insert */ true, HasExtract);
15043bdac29SSanjay Patel 
15143bdac29SSanjay Patel   // New pattern: load VecPtr
1528fb05593SSanjay Patel   int NewCost = TTI.getMemoryOpCost(Instruction::Load, MinVecTy, Alignment, AS);
15343bdac29SSanjay Patel 
15443bdac29SSanjay Patel   // We can aggressively convert to the vector form because the backend can
15543bdac29SSanjay Patel   // invert this transform if it does not result in a performance win.
15643bdac29SSanjay Patel   if (OldCost < NewCost)
15743bdac29SSanjay Patel     return false;
15843bdac29SSanjay Patel 
15943bdac29SSanjay Patel   // It is safe and potentially profitable to load a vector directly:
16043bdac29SSanjay Patel   // inselt undef, load Scalar, 0 --> load VecPtr
16143bdac29SSanjay Patel   IRBuilder<> Builder(Load);
1628fb05593SSanjay Patel   Value *CastedPtr = Builder.CreateBitCast(PtrOp, MinVecTy->getPointerTo(AS));
1638fb05593SSanjay Patel   Value *VecLd = Builder.CreateAlignedLoad(MinVecTy, CastedPtr, Alignment);
1648fb05593SSanjay Patel 
1658fb05593SSanjay Patel   // If the insert type does not match the target's minimum vector type,
1668fb05593SSanjay Patel   // use an identity shuffle to shrink/grow the vector.
1678fb05593SSanjay Patel   if (Ty != MinVecTy) {
1688fb05593SSanjay Patel     unsigned OutputNumElts = Ty->getNumElements();
1698fb05593SSanjay Patel     SmallVector<int, 16> Mask(OutputNumElts, UndefMaskElem);
1708fb05593SSanjay Patel     for (unsigned i = 0; i < OutputNumElts && i < MinVecNumElts; ++i)
1718fb05593SSanjay Patel       Mask[i] = i;
1721e6b240dSSanjay Patel     VecLd = Builder.CreateShuffleVector(VecLd, Mask);
1738fb05593SSanjay Patel   }
17443bdac29SSanjay Patel   replaceValue(I, *VecLd);
17543bdac29SSanjay Patel   ++NumVecLoad;
17643bdac29SSanjay Patel   return true;
17743bdac29SSanjay Patel }
17843bdac29SSanjay Patel 
1793b95d834SSanjay Patel /// Determine which, if any, of the inputs should be replaced by a shuffle
1803b95d834SSanjay Patel /// followed by extract from a different index.
1813b95d834SSanjay Patel ExtractElementInst *VectorCombine::getShuffleExtract(
1823b95d834SSanjay Patel     ExtractElementInst *Ext0, ExtractElementInst *Ext1,
1833b95d834SSanjay Patel     unsigned PreferredExtractIndex = InvalidIndex) const {
1843b95d834SSanjay Patel   assert(isa<ConstantInt>(Ext0->getIndexOperand()) &&
1853b95d834SSanjay Patel          isa<ConstantInt>(Ext1->getIndexOperand()) &&
1863b95d834SSanjay Patel          "Expected constant extract indexes");
1873b95d834SSanjay Patel 
1883b95d834SSanjay Patel   unsigned Index0 = cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue();
1893b95d834SSanjay Patel   unsigned Index1 = cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue();
1903b95d834SSanjay Patel 
1913b95d834SSanjay Patel   // If the extract indexes are identical, no shuffle is needed.
1923b95d834SSanjay Patel   if (Index0 == Index1)
1933b95d834SSanjay Patel     return nullptr;
1943b95d834SSanjay Patel 
1953b95d834SSanjay Patel   Type *VecTy = Ext0->getVectorOperand()->getType();
1963b95d834SSanjay Patel   assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types");
1973b95d834SSanjay Patel   int Cost0 = TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
1983b95d834SSanjay Patel   int Cost1 = TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
1993b95d834SSanjay Patel 
2003b95d834SSanjay Patel   // We are extracting from 2 different indexes, so one operand must be shuffled
2013b95d834SSanjay Patel   // before performing a vector operation and/or extract. The more expensive
2023b95d834SSanjay Patel   // extract will be replaced by a shuffle.
2033b95d834SSanjay Patel   if (Cost0 > Cost1)
2043b95d834SSanjay Patel     return Ext0;
2053b95d834SSanjay Patel   if (Cost1 > Cost0)
2063b95d834SSanjay Patel     return Ext1;
2073b95d834SSanjay Patel 
2083b95d834SSanjay Patel   // If the costs are equal and there is a preferred extract index, shuffle the
2093b95d834SSanjay Patel   // opposite operand.
2103b95d834SSanjay Patel   if (PreferredExtractIndex == Index0)
2113b95d834SSanjay Patel     return Ext1;
2123b95d834SSanjay Patel   if (PreferredExtractIndex == Index1)
2133b95d834SSanjay Patel     return Ext0;
2143b95d834SSanjay Patel 
2153b95d834SSanjay Patel   // Otherwise, replace the extract with the higher index.
2163b95d834SSanjay Patel   return Index0 > Index1 ? Ext0 : Ext1;
2173b95d834SSanjay Patel }
2183b95d834SSanjay Patel 
219a69158c1SSanjay Patel /// Compare the relative costs of 2 extracts followed by scalar operation vs.
220a69158c1SSanjay Patel /// vector operation(s) followed by extract. Return true if the existing
221a69158c1SSanjay Patel /// instructions are cheaper than a vector alternative. Otherwise, return false
222a69158c1SSanjay Patel /// and if one of the extracts should be transformed to a shufflevector, set
223a69158c1SSanjay Patel /// \p ConvertToShuffle to that extract instruction.
2246bdd531aSSanjay Patel bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0,
2256bdd531aSSanjay Patel                                           ExtractElementInst *Ext1,
2266bdd531aSSanjay Patel                                           unsigned Opcode,
227216a37bbSSanjay Patel                                           ExtractElementInst *&ConvertToShuffle,
228ce97ce3aSSanjay Patel                                           unsigned PreferredExtractIndex) {
2294fa63fd4SAustin Kerbow   assert(isa<ConstantInt>(Ext0->getOperand(1)) &&
230a69158c1SSanjay Patel          isa<ConstantInt>(Ext1->getOperand(1)) &&
231a69158c1SSanjay Patel          "Expected constant extract indexes");
23234e34855SSanjay Patel   Type *ScalarTy = Ext0->getType();
233e3056ae9SSam Parker   auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType());
23434e34855SSanjay Patel   int ScalarOpCost, VectorOpCost;
23534e34855SSanjay Patel 
23634e34855SSanjay Patel   // Get cost estimates for scalar and vector versions of the operation.
23734e34855SSanjay Patel   bool IsBinOp = Instruction::isBinaryOp(Opcode);
23834e34855SSanjay Patel   if (IsBinOp) {
23934e34855SSanjay Patel     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
24034e34855SSanjay Patel     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
24134e34855SSanjay Patel   } else {
24234e34855SSanjay Patel     assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
24334e34855SSanjay Patel            "Expected a compare");
24434e34855SSanjay Patel     ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy,
24534e34855SSanjay Patel                                           CmpInst::makeCmpResultType(ScalarTy));
24634e34855SSanjay Patel     VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy,
24734e34855SSanjay Patel                                           CmpInst::makeCmpResultType(VecTy));
24834e34855SSanjay Patel   }
24934e34855SSanjay Patel 
250a69158c1SSanjay Patel   // Get cost estimates for the extract elements. These costs will factor into
25134e34855SSanjay Patel   // both sequences.
252a69158c1SSanjay Patel   unsigned Ext0Index = cast<ConstantInt>(Ext0->getOperand(1))->getZExtValue();
253a69158c1SSanjay Patel   unsigned Ext1Index = cast<ConstantInt>(Ext1->getOperand(1))->getZExtValue();
254a69158c1SSanjay Patel 
2556bdd531aSSanjay Patel   int Extract0Cost =
2566bdd531aSSanjay Patel       TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext0Index);
2576bdd531aSSanjay Patel   int Extract1Cost =
2586bdd531aSSanjay Patel       TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext1Index);
259a69158c1SSanjay Patel 
260a69158c1SSanjay Patel   // A more expensive extract will always be replaced by a splat shuffle.
261a69158c1SSanjay Patel   // For example, if Ext0 is more expensive:
262a69158c1SSanjay Patel   // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
263a69158c1SSanjay Patel   // extelt (opcode (splat V0, Ext0), V1), Ext1
264a69158c1SSanjay Patel   // TODO: Evaluate whether that always results in lowest cost. Alternatively,
265a69158c1SSanjay Patel   //       check the cost of creating a broadcast shuffle and shuffling both
266a69158c1SSanjay Patel   //       operands to element 0.
267a69158c1SSanjay Patel   int CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
26834e34855SSanjay Patel 
26934e34855SSanjay Patel   // Extra uses of the extracts mean that we include those costs in the
27034e34855SSanjay Patel   // vector total because those instructions will not be eliminated.
271e9c79a7aSSanjay Patel   int OldCost, NewCost;
272a69158c1SSanjay Patel   if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) {
273a69158c1SSanjay Patel     // Handle a special case. If the 2 extracts are identical, adjust the
27434e34855SSanjay Patel     // formulas to account for that. The extra use charge allows for either the
27534e34855SSanjay Patel     // CSE'd pattern or an unoptimized form with identical values:
27634e34855SSanjay Patel     // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
27734e34855SSanjay Patel     bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
27834e34855SSanjay Patel                                   : !Ext0->hasOneUse() || !Ext1->hasOneUse();
279a69158c1SSanjay Patel     OldCost = CheapExtractCost + ScalarOpCost;
280a69158c1SSanjay Patel     NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
28134e34855SSanjay Patel   } else {
28234e34855SSanjay Patel     // Handle the general case. Each extract is actually a different value:
283a69158c1SSanjay Patel     // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
284a69158c1SSanjay Patel     OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
285a69158c1SSanjay Patel     NewCost = VectorOpCost + CheapExtractCost +
286a69158c1SSanjay Patel               !Ext0->hasOneUse() * Extract0Cost +
287a69158c1SSanjay Patel               !Ext1->hasOneUse() * Extract1Cost;
28834e34855SSanjay Patel   }
289a69158c1SSanjay Patel 
2903b95d834SSanjay Patel   ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex);
2913b95d834SSanjay Patel   if (ConvertToShuffle) {
292a69158c1SSanjay Patel     if (IsBinOp && DisableBinopExtractShuffle)
293a69158c1SSanjay Patel       return true;
294a69158c1SSanjay Patel 
295a69158c1SSanjay Patel     // If we are extracting from 2 different indexes, then one operand must be
296a69158c1SSanjay Patel     // shuffled before performing the vector operation. The shuffle mask is
297a69158c1SSanjay Patel     // undefined except for 1 lane that is being translated to the remaining
298a69158c1SSanjay Patel     // extraction lane. Therefore, it is a splat shuffle. Ex:
299a69158c1SSanjay Patel     // ShufMask = { undef, undef, 0, undef }
300a69158c1SSanjay Patel     // TODO: The cost model has an option for a "broadcast" shuffle
301a69158c1SSanjay Patel     //       (splat-from-element-0), but no option for a more general splat.
302a69158c1SSanjay Patel     NewCost +=
303a69158c1SSanjay Patel         TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
304a69158c1SSanjay Patel   }
305a69158c1SSanjay Patel 
30610ea01d8SSanjay Patel   // Aggressively form a vector op if the cost is equal because the transform
30710ea01d8SSanjay Patel   // may enable further optimization.
30810ea01d8SSanjay Patel   // Codegen can reverse this transform (scalarize) if it was not profitable.
30910ea01d8SSanjay Patel   return OldCost < NewCost;
31034e34855SSanjay Patel }
31134e34855SSanjay Patel 
3129934cc54SSanjay Patel /// Create a shuffle that translates (shifts) 1 element from the input vector
3139934cc54SSanjay Patel /// to a new element location.
3149934cc54SSanjay Patel static Value *createShiftShuffle(Value *Vec, unsigned OldIndex,
3159934cc54SSanjay Patel                                  unsigned NewIndex, IRBuilder<> &Builder) {
3169934cc54SSanjay Patel   // The shuffle mask is undefined except for 1 lane that is being translated
3179934cc54SSanjay Patel   // to the new element index. Example for OldIndex == 2 and NewIndex == 0:
3189934cc54SSanjay Patel   // ShufMask = { 2, undef, undef, undef }
3199934cc54SSanjay Patel   auto *VecTy = cast<FixedVectorType>(Vec->getType());
32054143e2bSSanjay Patel   SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem);
3219934cc54SSanjay Patel   ShufMask[NewIndex] = OldIndex;
3221e6b240dSSanjay Patel   return Builder.CreateShuffleVector(Vec, ShufMask, "shift");
3239934cc54SSanjay Patel }
3249934cc54SSanjay Patel 
325216a37bbSSanjay Patel /// Given an extract element instruction with constant index operand, shuffle
326216a37bbSSanjay Patel /// the source vector (shift the scalar element) to a NewIndex for extraction.
327216a37bbSSanjay Patel /// Return null if the input can be constant folded, so that we are not creating
328216a37bbSSanjay Patel /// unnecessary instructions.
3299934cc54SSanjay Patel static ExtractElementInst *translateExtract(ExtractElementInst *ExtElt,
3309934cc54SSanjay Patel                                             unsigned NewIndex,
3319934cc54SSanjay Patel                                             IRBuilder<> &Builder) {
332216a37bbSSanjay Patel   // If the extract can be constant-folded, this code is unsimplified. Defer
333216a37bbSSanjay Patel   // to other passes to handle that.
334216a37bbSSanjay Patel   Value *X = ExtElt->getVectorOperand();
335216a37bbSSanjay Patel   Value *C = ExtElt->getIndexOperand();
336de65b356SSanjay Patel   assert(isa<ConstantInt>(C) && "Expected a constant index operand");
337216a37bbSSanjay Patel   if (isa<Constant>(X))
338216a37bbSSanjay Patel     return nullptr;
339216a37bbSSanjay Patel 
3409934cc54SSanjay Patel   Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(),
3419934cc54SSanjay Patel                                    NewIndex, Builder);
342216a37bbSSanjay Patel   return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex));
343216a37bbSSanjay Patel }
344216a37bbSSanjay Patel 
345fc445589SSanjay Patel /// Try to reduce extract element costs by converting scalar compares to vector
346fc445589SSanjay Patel /// compares followed by extract.
347e9c79a7aSSanjay Patel /// cmp (ext0 V0, C), (ext1 V1, C)
348de65b356SSanjay Patel void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0,
349de65b356SSanjay Patel                                   ExtractElementInst *Ext1, Instruction &I) {
350fc445589SSanjay Patel   assert(isa<CmpInst>(&I) && "Expected a compare");
351216a37bbSSanjay Patel   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
352216a37bbSSanjay Patel              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
353216a37bbSSanjay Patel          "Expected matching constant extract indexes");
354a17f03bdSSanjay Patel 
355a17f03bdSSanjay Patel   // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C
356a17f03bdSSanjay Patel   ++NumVecCmp;
357fc445589SSanjay Patel   CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
358216a37bbSSanjay Patel   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
35946a285adSSanjay Patel   Value *VecCmp = Builder.CreateCmp(Pred, V0, V1);
360216a37bbSSanjay Patel   Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand());
36198c2f4eeSSanjay Patel   replaceValue(I, *NewExt);
362a17f03bdSSanjay Patel }
363a17f03bdSSanjay Patel 
36419b62b79SSanjay Patel /// Try to reduce extract element costs by converting scalar binops to vector
36519b62b79SSanjay Patel /// binops followed by extract.
366e9c79a7aSSanjay Patel /// bo (ext0 V0, C), (ext1 V1, C)
367de65b356SSanjay Patel void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0,
368de65b356SSanjay Patel                                     ExtractElementInst *Ext1, Instruction &I) {
369fc445589SSanjay Patel   assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
370216a37bbSSanjay Patel   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
371216a37bbSSanjay Patel              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
372216a37bbSSanjay Patel          "Expected matching constant extract indexes");
37319b62b79SSanjay Patel 
37434e34855SSanjay Patel   // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C
37519b62b79SSanjay Patel   ++NumVecBO;
376216a37bbSSanjay Patel   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
377e9c79a7aSSanjay Patel   Value *VecBO =
37834e34855SSanjay Patel       Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1);
379e9c79a7aSSanjay Patel 
38019b62b79SSanjay Patel   // All IR flags are safe to back-propagate because any potential poison
38119b62b79SSanjay Patel   // created in unused vector elements is discarded by the extract.
382e9c79a7aSSanjay Patel   if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
38319b62b79SSanjay Patel     VecBOInst->copyIRFlags(&I);
384e9c79a7aSSanjay Patel 
385216a37bbSSanjay Patel   Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand());
38698c2f4eeSSanjay Patel   replaceValue(I, *NewExt);
38719b62b79SSanjay Patel }
38819b62b79SSanjay Patel 
389fc445589SSanjay Patel /// Match an instruction with extracted vector operands.
3906bdd531aSSanjay Patel bool VectorCombine::foldExtractExtract(Instruction &I) {
391e9c79a7aSSanjay Patel   // It is not safe to transform things like div, urem, etc. because we may
392e9c79a7aSSanjay Patel   // create undefined behavior when executing those on unknown vector elements.
393e9c79a7aSSanjay Patel   if (!isSafeToSpeculativelyExecute(&I))
394e9c79a7aSSanjay Patel     return false;
395e9c79a7aSSanjay Patel 
396216a37bbSSanjay Patel   Instruction *I0, *I1;
397fc445589SSanjay Patel   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
398216a37bbSSanjay Patel   if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) &&
399216a37bbSSanjay Patel       !match(&I, m_BinOp(m_Instruction(I0), m_Instruction(I1))))
400fc445589SSanjay Patel     return false;
401fc445589SSanjay Patel 
402fc445589SSanjay Patel   Value *V0, *V1;
403fc445589SSanjay Patel   uint64_t C0, C1;
404216a37bbSSanjay Patel   if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
405216a37bbSSanjay Patel       !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) ||
406fc445589SSanjay Patel       V0->getType() != V1->getType())
407fc445589SSanjay Patel     return false;
408fc445589SSanjay Patel 
409ce97ce3aSSanjay Patel   // If the scalar value 'I' is going to be re-inserted into a vector, then try
410ce97ce3aSSanjay Patel   // to create an extract to that same element. The extract/insert can be
411ce97ce3aSSanjay Patel   // reduced to a "select shuffle".
412ce97ce3aSSanjay Patel   // TODO: If we add a larger pattern match that starts from an insert, this
413ce97ce3aSSanjay Patel   //       probably becomes unnecessary.
414216a37bbSSanjay Patel   auto *Ext0 = cast<ExtractElementInst>(I0);
415216a37bbSSanjay Patel   auto *Ext1 = cast<ExtractElementInst>(I1);
416a0f96741SSanjay Patel   uint64_t InsertIndex = InvalidIndex;
417ce97ce3aSSanjay Patel   if (I.hasOneUse())
4187eed772aSSanjay Patel     match(I.user_back(),
4197eed772aSSanjay Patel           m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
420ce97ce3aSSanjay Patel 
421216a37bbSSanjay Patel   ExtractElementInst *ExtractToChange;
4226bdd531aSSanjay Patel   if (isExtractExtractCheap(Ext0, Ext1, I.getOpcode(), ExtractToChange,
423ce97ce3aSSanjay Patel                             InsertIndex))
424fc445589SSanjay Patel     return false;
425e9c79a7aSSanjay Patel 
426216a37bbSSanjay Patel   if (ExtractToChange) {
427216a37bbSSanjay Patel     unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0;
428216a37bbSSanjay Patel     ExtractElementInst *NewExtract =
4299934cc54SSanjay Patel         translateExtract(ExtractToChange, CheapExtractIdx, Builder);
430216a37bbSSanjay Patel     if (!NewExtract)
4316d864097SSanjay Patel       return false;
432216a37bbSSanjay Patel     if (ExtractToChange == Ext0)
433216a37bbSSanjay Patel       Ext0 = NewExtract;
434a69158c1SSanjay Patel     else
435216a37bbSSanjay Patel       Ext1 = NewExtract;
436a69158c1SSanjay Patel   }
437e9c79a7aSSanjay Patel 
438e9c79a7aSSanjay Patel   if (Pred != CmpInst::BAD_ICMP_PREDICATE)
439039ff29eSSanjay Patel     foldExtExtCmp(Ext0, Ext1, I);
440e9c79a7aSSanjay Patel   else
441039ff29eSSanjay Patel     foldExtExtBinop(Ext0, Ext1, I);
442e9c79a7aSSanjay Patel 
443e9c79a7aSSanjay Patel   return true;
444fc445589SSanjay Patel }
445fc445589SSanjay Patel 
446bef6e67eSSanjay Patel /// If this is a bitcast of a shuffle, try to bitcast the source vector to the
447bef6e67eSSanjay Patel /// destination type followed by shuffle. This can enable further transforms by
448bef6e67eSSanjay Patel /// moving bitcasts or shuffles together.
4496bdd531aSSanjay Patel bool VectorCombine::foldBitcastShuf(Instruction &I) {
450b6050ca1SSanjay Patel   Value *V;
451b6050ca1SSanjay Patel   ArrayRef<int> Mask;
4527eed772aSSanjay Patel   if (!match(&I, m_BitCast(
4537eed772aSSanjay Patel                      m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))))))
454b6050ca1SSanjay Patel     return false;
455b6050ca1SSanjay Patel 
456b4f04d71SHuihui Zhang   // 1) Do not fold bitcast shuffle for scalable type. First, shuffle cost for
457b4f04d71SHuihui Zhang   // scalable type is unknown; Second, we cannot reason if the narrowed shuffle
458b4f04d71SHuihui Zhang   // mask for scalable type is a splat or not.
459b4f04d71SHuihui Zhang   // 2) Disallow non-vector casts and length-changing shuffles.
460bef6e67eSSanjay Patel   // TODO: We could allow any shuffle.
461b4f04d71SHuihui Zhang   auto *DestTy = dyn_cast<FixedVectorType>(I.getType());
462b4f04d71SHuihui Zhang   auto *SrcTy = dyn_cast<FixedVectorType>(V->getType());
463b4f04d71SHuihui Zhang   if (!SrcTy || !DestTy || I.getOperand(0)->getType() != SrcTy)
464b6050ca1SSanjay Patel     return false;
465b6050ca1SSanjay Patel 
466b6050ca1SSanjay Patel   // The new shuffle must not cost more than the old shuffle. The bitcast is
467b6050ca1SSanjay Patel   // moved ahead of the shuffle, so assume that it has the same cost as before.
468b6050ca1SSanjay Patel   if (TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, DestTy) >
469b6050ca1SSanjay Patel       TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, SrcTy))
470b6050ca1SSanjay Patel     return false;
471b6050ca1SSanjay Patel 
472b4f04d71SHuihui Zhang   unsigned DestNumElts = DestTy->getNumElements();
473b4f04d71SHuihui Zhang   unsigned SrcNumElts = SrcTy->getNumElements();
474b6050ca1SSanjay Patel   SmallVector<int, 16> NewMask;
475bef6e67eSSanjay Patel   if (SrcNumElts <= DestNumElts) {
476bef6e67eSSanjay Patel     // The bitcast is from wide to narrow/equal elements. The shuffle mask can
477bef6e67eSSanjay Patel     // always be expanded to the equivalent form choosing narrower elements.
478b6050ca1SSanjay Patel     assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask");
479b6050ca1SSanjay Patel     unsigned ScaleFactor = DestNumElts / SrcNumElts;
4801318ddbcSSanjay Patel     narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
481bef6e67eSSanjay Patel   } else {
482bef6e67eSSanjay Patel     // The bitcast is from narrow elements to wide elements. The shuffle mask
483bef6e67eSSanjay Patel     // must choose consecutive elements to allow casting first.
484bef6e67eSSanjay Patel     assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask");
485bef6e67eSSanjay Patel     unsigned ScaleFactor = SrcNumElts / DestNumElts;
486bef6e67eSSanjay Patel     if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
487bef6e67eSSanjay Patel       return false;
488bef6e67eSSanjay Patel   }
489bef6e67eSSanjay Patel   // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC'
4907aeb41b3SRoman Lebedev   ++NumShufOfBitcast;
491bef6e67eSSanjay Patel   Value *CastV = Builder.CreateBitCast(V, DestTy);
4921e6b240dSSanjay Patel   Value *Shuf = Builder.CreateShuffleVector(CastV, NewMask);
49398c2f4eeSSanjay Patel   replaceValue(I, *Shuf);
494b6050ca1SSanjay Patel   return true;
495b6050ca1SSanjay Patel }
496b6050ca1SSanjay Patel 
497ed67f5e7SSanjay Patel /// Match a vector binop or compare instruction with at least one inserted
498ed67f5e7SSanjay Patel /// scalar operand and convert to scalar binop/cmp followed by insertelement.
4996bdd531aSSanjay Patel bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) {
500ed67f5e7SSanjay Patel   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
5015dc4e7c2SSimon Pilgrim   Value *Ins0, *Ins1;
502ed67f5e7SSanjay Patel   if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) &&
503ed67f5e7SSanjay Patel       !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1))))
504ed67f5e7SSanjay Patel     return false;
505ed67f5e7SSanjay Patel 
506ed67f5e7SSanjay Patel   // Do not convert the vector condition of a vector select into a scalar
507ed67f5e7SSanjay Patel   // condition. That may cause problems for codegen because of differences in
508ed67f5e7SSanjay Patel   // boolean formats and register-file transfers.
509ed67f5e7SSanjay Patel   // TODO: Can we account for that in the cost model?
510ed67f5e7SSanjay Patel   bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE;
511ed67f5e7SSanjay Patel   if (IsCmp)
512ed67f5e7SSanjay Patel     for (User *U : I.users())
513ed67f5e7SSanjay Patel       if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
5140d2a0b44SSanjay Patel         return false;
5150d2a0b44SSanjay Patel 
5165dc4e7c2SSimon Pilgrim   // Match against one or both scalar values being inserted into constant
5175dc4e7c2SSimon Pilgrim   // vectors:
518ed67f5e7SSanjay Patel   // vec_op VecC0, (inselt VecC1, V1, Index)
519ed67f5e7SSanjay Patel   // vec_op (inselt VecC0, V0, Index), VecC1
520ed67f5e7SSanjay Patel   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index)
5210d2a0b44SSanjay Patel   // TODO: Deal with mismatched index constants and variable indexes?
5225dc4e7c2SSimon Pilgrim   Constant *VecC0 = nullptr, *VecC1 = nullptr;
5235dc4e7c2SSimon Pilgrim   Value *V0 = nullptr, *V1 = nullptr;
5245dc4e7c2SSimon Pilgrim   uint64_t Index0 = 0, Index1 = 0;
5257eed772aSSanjay Patel   if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
5265dc4e7c2SSimon Pilgrim                                m_ConstantInt(Index0))) &&
5275dc4e7c2SSimon Pilgrim       !match(Ins0, m_Constant(VecC0)))
5285dc4e7c2SSimon Pilgrim     return false;
5295dc4e7c2SSimon Pilgrim   if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
5305dc4e7c2SSimon Pilgrim                                m_ConstantInt(Index1))) &&
5315dc4e7c2SSimon Pilgrim       !match(Ins1, m_Constant(VecC1)))
5320d2a0b44SSanjay Patel     return false;
5330d2a0b44SSanjay Patel 
5345dc4e7c2SSimon Pilgrim   bool IsConst0 = !V0;
5355dc4e7c2SSimon Pilgrim   bool IsConst1 = !V1;
5365dc4e7c2SSimon Pilgrim   if (IsConst0 && IsConst1)
5375dc4e7c2SSimon Pilgrim     return false;
5385dc4e7c2SSimon Pilgrim   if (!IsConst0 && !IsConst1 && Index0 != Index1)
5395dc4e7c2SSimon Pilgrim     return false;
5405dc4e7c2SSimon Pilgrim 
5415dc4e7c2SSimon Pilgrim   // Bail for single insertion if it is a load.
5425dc4e7c2SSimon Pilgrim   // TODO: Handle this once getVectorInstrCost can cost for load/stores.
5435dc4e7c2SSimon Pilgrim   auto *I0 = dyn_cast_or_null<Instruction>(V0);
5445dc4e7c2SSimon Pilgrim   auto *I1 = dyn_cast_or_null<Instruction>(V1);
5455dc4e7c2SSimon Pilgrim   if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
5465dc4e7c2SSimon Pilgrim       (IsConst1 && I0 && I0->mayReadFromMemory()))
5475dc4e7c2SSimon Pilgrim     return false;
5485dc4e7c2SSimon Pilgrim 
5495dc4e7c2SSimon Pilgrim   uint64_t Index = IsConst0 ? Index1 : Index0;
5505dc4e7c2SSimon Pilgrim   Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType();
5510d2a0b44SSanjay Patel   Type *VecTy = I.getType();
5525dc4e7c2SSimon Pilgrim   assert(VecTy->isVectorTy() &&
5535dc4e7c2SSimon Pilgrim          (IsConst0 || IsConst1 || V0->getType() == V1->getType()) &&
554741e20f3SSanjay Patel          (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
555741e20f3SSanjay Patel           ScalarTy->isPointerTy()) &&
556741e20f3SSanjay Patel          "Unexpected types for insert element into binop or cmp");
5570d2a0b44SSanjay Patel 
558ed67f5e7SSanjay Patel   unsigned Opcode = I.getOpcode();
559ed67f5e7SSanjay Patel   int ScalarOpCost, VectorOpCost;
560ed67f5e7SSanjay Patel   if (IsCmp) {
561ed67f5e7SSanjay Patel     ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy);
562ed67f5e7SSanjay Patel     VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy);
563ed67f5e7SSanjay Patel   } else {
564ed67f5e7SSanjay Patel     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
565ed67f5e7SSanjay Patel     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
566ed67f5e7SSanjay Patel   }
5670d2a0b44SSanjay Patel 
5680d2a0b44SSanjay Patel   // Get cost estimate for the insert element. This cost will factor into
5690d2a0b44SSanjay Patel   // both sequences.
5700d2a0b44SSanjay Patel   int InsertCost =
5710d2a0b44SSanjay Patel       TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, Index);
5725dc4e7c2SSimon Pilgrim   int OldCost = (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) +
5735dc4e7c2SSimon Pilgrim                 VectorOpCost;
5745f730b64SSanjay Patel   int NewCost = ScalarOpCost + InsertCost +
5755dc4e7c2SSimon Pilgrim                 (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) +
5765dc4e7c2SSimon Pilgrim                 (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost);
5770d2a0b44SSanjay Patel 
5780d2a0b44SSanjay Patel   // We want to scalarize unless the vector variant actually has lower cost.
5790d2a0b44SSanjay Patel   if (OldCost < NewCost)
5800d2a0b44SSanjay Patel     return false;
5810d2a0b44SSanjay Patel 
582ed67f5e7SSanjay Patel   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
583ed67f5e7SSanjay Patel   // inselt NewVecC, (scalar_op V0, V1), Index
584ed67f5e7SSanjay Patel   if (IsCmp)
585ed67f5e7SSanjay Patel     ++NumScalarCmp;
586ed67f5e7SSanjay Patel   else
5870d2a0b44SSanjay Patel     ++NumScalarBO;
5885dc4e7c2SSimon Pilgrim 
5895dc4e7c2SSimon Pilgrim   // For constant cases, extract the scalar element, this should constant fold.
5905dc4e7c2SSimon Pilgrim   if (IsConst0)
5915dc4e7c2SSimon Pilgrim     V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index));
5925dc4e7c2SSimon Pilgrim   if (IsConst1)
5935dc4e7c2SSimon Pilgrim     V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index));
5945dc4e7c2SSimon Pilgrim 
595ed67f5e7SSanjay Patel   Value *Scalar =
59646a285adSSanjay Patel       IsCmp ? Builder.CreateCmp(Pred, V0, V1)
597ed67f5e7SSanjay Patel             : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1);
598ed67f5e7SSanjay Patel 
599ed67f5e7SSanjay Patel   Scalar->setName(I.getName() + ".scalar");
6000d2a0b44SSanjay Patel 
6010d2a0b44SSanjay Patel   // All IR flags are safe to back-propagate. There is no potential for extra
6020d2a0b44SSanjay Patel   // poison to be created by the scalar instruction.
6030d2a0b44SSanjay Patel   if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
6040d2a0b44SSanjay Patel     ScalarInst->copyIRFlags(&I);
6050d2a0b44SSanjay Patel 
6060d2a0b44SSanjay Patel   // Fold the vector constants in the original vectors into a new base vector.
607ed67f5e7SSanjay Patel   Constant *NewVecC = IsCmp ? ConstantExpr::getCompare(Pred, VecC0, VecC1)
608ed67f5e7SSanjay Patel                             : ConstantExpr::get(Opcode, VecC0, VecC1);
6090d2a0b44SSanjay Patel   Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
61098c2f4eeSSanjay Patel   replaceValue(I, *Insert);
6110d2a0b44SSanjay Patel   return true;
6120d2a0b44SSanjay Patel }
6130d2a0b44SSanjay Patel 
614b6315aeeSSanjay Patel /// Try to combine a scalar binop + 2 scalar compares of extracted elements of
615b6315aeeSSanjay Patel /// a vector into vector operations followed by extract. Note: The SLP pass
616b6315aeeSSanjay Patel /// may miss this pattern because of implementation problems.
617b6315aeeSSanjay Patel bool VectorCombine::foldExtractedCmps(Instruction &I) {
618b6315aeeSSanjay Patel   // We are looking for a scalar binop of booleans.
619b6315aeeSSanjay Patel   // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1)
620b6315aeeSSanjay Patel   if (!I.isBinaryOp() || !I.getType()->isIntegerTy(1))
621b6315aeeSSanjay Patel     return false;
622b6315aeeSSanjay Patel 
623b6315aeeSSanjay Patel   // The compare predicates should match, and each compare should have a
624b6315aeeSSanjay Patel   // constant operand.
625b6315aeeSSanjay Patel   // TODO: Relax the one-use constraints.
626b6315aeeSSanjay Patel   Value *B0 = I.getOperand(0), *B1 = I.getOperand(1);
627b6315aeeSSanjay Patel   Instruction *I0, *I1;
628b6315aeeSSanjay Patel   Constant *C0, *C1;
629b6315aeeSSanjay Patel   CmpInst::Predicate P0, P1;
630b6315aeeSSanjay Patel   if (!match(B0, m_OneUse(m_Cmp(P0, m_Instruction(I0), m_Constant(C0)))) ||
631b6315aeeSSanjay Patel       !match(B1, m_OneUse(m_Cmp(P1, m_Instruction(I1), m_Constant(C1)))) ||
632b6315aeeSSanjay Patel       P0 != P1)
633b6315aeeSSanjay Patel     return false;
634b6315aeeSSanjay Patel 
635b6315aeeSSanjay Patel   // The compare operands must be extracts of the same vector with constant
636b6315aeeSSanjay Patel   // extract indexes.
637b6315aeeSSanjay Patel   // TODO: Relax the one-use constraints.
638b6315aeeSSanjay Patel   Value *X;
639b6315aeeSSanjay Patel   uint64_t Index0, Index1;
640b6315aeeSSanjay Patel   if (!match(I0, m_OneUse(m_ExtractElt(m_Value(X), m_ConstantInt(Index0)))) ||
641b6315aeeSSanjay Patel       !match(I1, m_OneUse(m_ExtractElt(m_Specific(X), m_ConstantInt(Index1)))))
642b6315aeeSSanjay Patel     return false;
643b6315aeeSSanjay Patel 
644b6315aeeSSanjay Patel   auto *Ext0 = cast<ExtractElementInst>(I0);
645b6315aeeSSanjay Patel   auto *Ext1 = cast<ExtractElementInst>(I1);
646b6315aeeSSanjay Patel   ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1);
647b6315aeeSSanjay Patel   if (!ConvertToShuf)
648b6315aeeSSanjay Patel     return false;
649b6315aeeSSanjay Patel 
650b6315aeeSSanjay Patel   // The original scalar pattern is:
651b6315aeeSSanjay Patel   // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1)
652b6315aeeSSanjay Patel   CmpInst::Predicate Pred = P0;
653b6315aeeSSanjay Patel   unsigned CmpOpcode = CmpInst::isFPPredicate(Pred) ? Instruction::FCmp
654b6315aeeSSanjay Patel                                                     : Instruction::ICmp;
655b6315aeeSSanjay Patel   auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
656b6315aeeSSanjay Patel   if (!VecTy)
657b6315aeeSSanjay Patel     return false;
658b6315aeeSSanjay Patel 
659b6315aeeSSanjay Patel   int OldCost = TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
660b6315aeeSSanjay Patel   OldCost += TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
661b6315aeeSSanjay Patel   OldCost += TTI.getCmpSelInstrCost(CmpOpcode, I0->getType()) * 2;
662b6315aeeSSanjay Patel   OldCost += TTI.getArithmeticInstrCost(I.getOpcode(), I.getType());
663b6315aeeSSanjay Patel 
664b6315aeeSSanjay Patel   // The proposed vector pattern is:
665b6315aeeSSanjay Patel   // vcmp = cmp Pred X, VecC
666b6315aeeSSanjay Patel   // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0
667b6315aeeSSanjay Patel   int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0;
668b6315aeeSSanjay Patel   int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1;
669b6315aeeSSanjay Patel   auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType()));
670b6315aeeSSanjay Patel   int NewCost = TTI.getCmpSelInstrCost(CmpOpcode, X->getType());
671b6315aeeSSanjay Patel   NewCost +=
672b6315aeeSSanjay Patel       TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, CmpTy);
673b6315aeeSSanjay Patel   NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy);
674b6315aeeSSanjay Patel   NewCost += TTI.getVectorInstrCost(Ext0->getOpcode(), CmpTy, CheapIndex);
675b6315aeeSSanjay Patel 
676b6315aeeSSanjay Patel   // Aggressively form vector ops if the cost is equal because the transform
677b6315aeeSSanjay Patel   // may enable further optimization.
678b6315aeeSSanjay Patel   // Codegen can reverse this transform (scalarize) if it was not profitable.
679b6315aeeSSanjay Patel   if (OldCost < NewCost)
680b6315aeeSSanjay Patel     return false;
681b6315aeeSSanjay Patel 
682b6315aeeSSanjay Patel   // Create a vector constant from the 2 scalar constants.
683b6315aeeSSanjay Patel   SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(),
684b6315aeeSSanjay Patel                                    UndefValue::get(VecTy->getElementType()));
685b6315aeeSSanjay Patel   CmpC[Index0] = C0;
686b6315aeeSSanjay Patel   CmpC[Index1] = C1;
687b6315aeeSSanjay Patel   Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC));
688b6315aeeSSanjay Patel 
689b6315aeeSSanjay Patel   Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder);
690b6315aeeSSanjay Patel   Value *VecLogic = Builder.CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
691b6315aeeSSanjay Patel                                         VCmp, Shuf);
692b6315aeeSSanjay Patel   Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex);
693b6315aeeSSanjay Patel   replaceValue(I, *NewExt);
694b6315aeeSSanjay Patel   ++NumVecCmpBO;
695b6315aeeSSanjay Patel   return true;
696b6315aeeSSanjay Patel }
697b6315aeeSSanjay Patel 
698a17f03bdSSanjay Patel /// This is the entry point for all transforms. Pass manager differences are
699a17f03bdSSanjay Patel /// handled in the callers of this function.
7006bdd531aSSanjay Patel bool VectorCombine::run() {
70125c6544fSSanjay Patel   if (DisableVectorCombine)
70225c6544fSSanjay Patel     return false;
70325c6544fSSanjay Patel 
704cc892fd9SSanjay Patel   // Don't attempt vectorization if the target does not support vectors.
705cc892fd9SSanjay Patel   if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true)))
706cc892fd9SSanjay Patel     return false;
707cc892fd9SSanjay Patel 
708a17f03bdSSanjay Patel   bool MadeChange = false;
709a17f03bdSSanjay Patel   for (BasicBlock &BB : F) {
710a17f03bdSSanjay Patel     // Ignore unreachable basic blocks.
711a17f03bdSSanjay Patel     if (!DT.isReachableFromEntry(&BB))
712a17f03bdSSanjay Patel       continue;
713a17f03bdSSanjay Patel     // Do not delete instructions under here and invalidate the iterator.
71481e9ede3SSanjay Patel     // Walk the block forwards to enable simple iterative chains of transforms.
715a17f03bdSSanjay Patel     // TODO: It could be more efficient to remove dead instructions
716a17f03bdSSanjay Patel     //       iteratively in this loop rather than waiting until the end.
71781e9ede3SSanjay Patel     for (Instruction &I : BB) {
718fc3cc8a4SSanjay Patel       if (isa<DbgInfoIntrinsic>(I))
719fc3cc8a4SSanjay Patel         continue;
720de65b356SSanjay Patel       Builder.SetInsertPoint(&I);
72143bdac29SSanjay Patel       MadeChange |= vectorizeLoadInsert(I);
7226bdd531aSSanjay Patel       MadeChange |= foldExtractExtract(I);
7236bdd531aSSanjay Patel       MadeChange |= foldBitcastShuf(I);
7246bdd531aSSanjay Patel       MadeChange |= scalarizeBinopOrCmp(I);
725b6315aeeSSanjay Patel       MadeChange |= foldExtractedCmps(I);
726a17f03bdSSanjay Patel     }
727fc3cc8a4SSanjay Patel   }
728a17f03bdSSanjay Patel 
729a17f03bdSSanjay Patel   // We're done with transforms, so remove dead instructions.
730a17f03bdSSanjay Patel   if (MadeChange)
731a17f03bdSSanjay Patel     for (BasicBlock &BB : F)
732a17f03bdSSanjay Patel       SimplifyInstructionsInBlock(&BB);
733a17f03bdSSanjay Patel 
734a17f03bdSSanjay Patel   return MadeChange;
735a17f03bdSSanjay Patel }
736a17f03bdSSanjay Patel 
737a17f03bdSSanjay Patel // Pass manager boilerplate below here.
738a17f03bdSSanjay Patel 
739a17f03bdSSanjay Patel namespace {
740a17f03bdSSanjay Patel class VectorCombineLegacyPass : public FunctionPass {
741a17f03bdSSanjay Patel public:
742a17f03bdSSanjay Patel   static char ID;
743a17f03bdSSanjay Patel   VectorCombineLegacyPass() : FunctionPass(ID) {
744a17f03bdSSanjay Patel     initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry());
745a17f03bdSSanjay Patel   }
746a17f03bdSSanjay Patel 
747a17f03bdSSanjay Patel   void getAnalysisUsage(AnalysisUsage &AU) const override {
748a17f03bdSSanjay Patel     AU.addRequired<DominatorTreeWrapperPass>();
749a17f03bdSSanjay Patel     AU.addRequired<TargetTransformInfoWrapperPass>();
750a17f03bdSSanjay Patel     AU.setPreservesCFG();
751a17f03bdSSanjay Patel     AU.addPreserved<DominatorTreeWrapperPass>();
752a17f03bdSSanjay Patel     AU.addPreserved<GlobalsAAWrapperPass>();
753024098aeSSanjay Patel     AU.addPreserved<AAResultsWrapperPass>();
754024098aeSSanjay Patel     AU.addPreserved<BasicAAWrapperPass>();
755a17f03bdSSanjay Patel     FunctionPass::getAnalysisUsage(AU);
756a17f03bdSSanjay Patel   }
757a17f03bdSSanjay Patel 
758a17f03bdSSanjay Patel   bool runOnFunction(Function &F) override {
759a17f03bdSSanjay Patel     if (skipFunction(F))
760a17f03bdSSanjay Patel       return false;
761a17f03bdSSanjay Patel     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
762a17f03bdSSanjay Patel     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
7636bdd531aSSanjay Patel     VectorCombine Combiner(F, TTI, DT);
7646bdd531aSSanjay Patel     return Combiner.run();
765a17f03bdSSanjay Patel   }
766a17f03bdSSanjay Patel };
767a17f03bdSSanjay Patel } // namespace
768a17f03bdSSanjay Patel 
769a17f03bdSSanjay Patel char VectorCombineLegacyPass::ID = 0;
770a17f03bdSSanjay Patel INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine",
771a17f03bdSSanjay Patel                       "Optimize scalar/vector ops", false,
772a17f03bdSSanjay Patel                       false)
773a17f03bdSSanjay Patel INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
774a17f03bdSSanjay Patel INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine",
775a17f03bdSSanjay Patel                     "Optimize scalar/vector ops", false, false)
776a17f03bdSSanjay Patel Pass *llvm::createVectorCombinePass() {
777a17f03bdSSanjay Patel   return new VectorCombineLegacyPass();
778a17f03bdSSanjay Patel }
779a17f03bdSSanjay Patel 
780a17f03bdSSanjay Patel PreservedAnalyses VectorCombinePass::run(Function &F,
781a17f03bdSSanjay Patel                                          FunctionAnalysisManager &FAM) {
782a17f03bdSSanjay Patel   TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
783a17f03bdSSanjay Patel   DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
7846bdd531aSSanjay Patel   VectorCombine Combiner(F, TTI, DT);
7856bdd531aSSanjay Patel   if (!Combiner.run())
786a17f03bdSSanjay Patel     return PreservedAnalyses::all();
787a17f03bdSSanjay Patel   PreservedAnalyses PA;
788a17f03bdSSanjay Patel   PA.preserveSet<CFGAnalyses>();
789a17f03bdSSanjay Patel   PA.preserve<GlobalsAA>();
790024098aeSSanjay Patel   PA.preserve<AAManager>();
791024098aeSSanjay Patel   PA.preserve<BasicAA>();
792a17f03bdSSanjay Patel   return PA;
793a17f03bdSSanjay Patel }
794