1a17f03bdSSanjay Patel //===------- VectorCombine.cpp - Optimize partial vector operations -------===// 2a17f03bdSSanjay Patel // 3a17f03bdSSanjay Patel // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4a17f03bdSSanjay Patel // See https://llvm.org/LICENSE.txt for license information. 5a17f03bdSSanjay Patel // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6a17f03bdSSanjay Patel // 7a17f03bdSSanjay Patel //===----------------------------------------------------------------------===// 8a17f03bdSSanjay Patel // 9a17f03bdSSanjay Patel // This pass optimizes scalar/vector interactions using target cost models. The 10a17f03bdSSanjay Patel // transforms implemented here may not fit in traditional loop-based or SLP 11a17f03bdSSanjay Patel // vectorization passes. 12a17f03bdSSanjay Patel // 13a17f03bdSSanjay Patel //===----------------------------------------------------------------------===// 14a17f03bdSSanjay Patel 15a17f03bdSSanjay Patel #include "llvm/Transforms/Vectorize/VectorCombine.h" 16a17f03bdSSanjay Patel #include "llvm/ADT/Statistic.h" 175006e551SSimon Pilgrim #include "llvm/Analysis/BasicAliasAnalysis.h" 18a17f03bdSSanjay Patel #include "llvm/Analysis/GlobalsModRef.h" 19a17f03bdSSanjay Patel #include "llvm/Analysis/TargetTransformInfo.h" 2019b62b79SSanjay Patel #include "llvm/Analysis/ValueTracking.h" 21b6050ca1SSanjay Patel #include "llvm/Analysis/VectorUtils.h" 22a17f03bdSSanjay Patel #include "llvm/IR/Dominators.h" 23a17f03bdSSanjay Patel #include "llvm/IR/Function.h" 24a17f03bdSSanjay Patel #include "llvm/IR/IRBuilder.h" 25a17f03bdSSanjay Patel #include "llvm/IR/PatternMatch.h" 26a17f03bdSSanjay Patel #include "llvm/InitializePasses.h" 27a17f03bdSSanjay Patel #include "llvm/Pass.h" 2825c6544fSSanjay Patel #include "llvm/Support/CommandLine.h" 29a17f03bdSSanjay Patel #include "llvm/Transforms/Utils/Local.h" 305006e551SSimon Pilgrim #include "llvm/Transforms/Vectorize.h" 31a17f03bdSSanjay Patel 32a17f03bdSSanjay Patel using namespace llvm; 33a17f03bdSSanjay Patel using namespace llvm::PatternMatch; 34a17f03bdSSanjay Patel 35a17f03bdSSanjay Patel #define DEBUG_TYPE "vector-combine" 36a17f03bdSSanjay Patel STATISTIC(NumVecCmp, "Number of vector compares formed"); 3719b62b79SSanjay Patel STATISTIC(NumVecBO, "Number of vector binops formed"); 38*b6315aeeSSanjay Patel STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed"); 397aeb41b3SRoman Lebedev STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast"); 400d2a0b44SSanjay Patel STATISTIC(NumScalarBO, "Number of scalar binops formed"); 41ed67f5e7SSanjay Patel STATISTIC(NumScalarCmp, "Number of scalar compares formed"); 42a17f03bdSSanjay Patel 4325c6544fSSanjay Patel static cl::opt<bool> DisableVectorCombine( 4425c6544fSSanjay Patel "disable-vector-combine", cl::init(false), cl::Hidden, 4525c6544fSSanjay Patel cl::desc("Disable all vector combine transforms")); 4625c6544fSSanjay Patel 47a69158c1SSanjay Patel static cl::opt<bool> DisableBinopExtractShuffle( 48a69158c1SSanjay Patel "disable-binop-extract-shuffle", cl::init(false), cl::Hidden, 49a69158c1SSanjay Patel cl::desc("Disable binop extract to shuffle transforms")); 50a69158c1SSanjay Patel 51a0f96741SSanjay Patel static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max(); 52a0f96741SSanjay Patel 536bdd531aSSanjay Patel class VectorCombine { 546bdd531aSSanjay Patel public: 556bdd531aSSanjay Patel VectorCombine(Function &F, const TargetTransformInfo &TTI, 566bdd531aSSanjay Patel const DominatorTree &DT) 57de65b356SSanjay Patel : F(F), Builder(F.getContext()), TTI(TTI), DT(DT) {} 586bdd531aSSanjay Patel 596bdd531aSSanjay Patel bool run(); 606bdd531aSSanjay Patel 616bdd531aSSanjay Patel private: 626bdd531aSSanjay Patel Function &F; 63de65b356SSanjay Patel IRBuilder<> Builder; 646bdd531aSSanjay Patel const TargetTransformInfo &TTI; 656bdd531aSSanjay Patel const DominatorTree &DT; 666bdd531aSSanjay Patel 673b95d834SSanjay Patel ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0, 683b95d834SSanjay Patel ExtractElementInst *Ext1, 693b95d834SSanjay Patel unsigned PreferredExtractIndex) const; 706bdd531aSSanjay Patel bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1, 716bdd531aSSanjay Patel unsigned Opcode, 726bdd531aSSanjay Patel ExtractElementInst *&ConvertToShuffle, 736bdd531aSSanjay Patel unsigned PreferredExtractIndex); 74de65b356SSanjay Patel void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1, 75de65b356SSanjay Patel Instruction &I); 76de65b356SSanjay Patel void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1, 77de65b356SSanjay Patel Instruction &I); 786bdd531aSSanjay Patel bool foldExtractExtract(Instruction &I); 796bdd531aSSanjay Patel bool foldBitcastShuf(Instruction &I); 806bdd531aSSanjay Patel bool scalarizeBinopOrCmp(Instruction &I); 81*b6315aeeSSanjay Patel bool foldExtractedCmps(Instruction &I); 826bdd531aSSanjay Patel }; 83a69158c1SSanjay Patel 8498c2f4eeSSanjay Patel static void replaceValue(Value &Old, Value &New) { 8598c2f4eeSSanjay Patel Old.replaceAllUsesWith(&New); 8698c2f4eeSSanjay Patel New.takeName(&Old); 8798c2f4eeSSanjay Patel } 8898c2f4eeSSanjay Patel 893b95d834SSanjay Patel /// Determine which, if any, of the inputs should be replaced by a shuffle 903b95d834SSanjay Patel /// followed by extract from a different index. 913b95d834SSanjay Patel ExtractElementInst *VectorCombine::getShuffleExtract( 923b95d834SSanjay Patel ExtractElementInst *Ext0, ExtractElementInst *Ext1, 933b95d834SSanjay Patel unsigned PreferredExtractIndex = InvalidIndex) const { 943b95d834SSanjay Patel assert(isa<ConstantInt>(Ext0->getIndexOperand()) && 953b95d834SSanjay Patel isa<ConstantInt>(Ext1->getIndexOperand()) && 963b95d834SSanjay Patel "Expected constant extract indexes"); 973b95d834SSanjay Patel 983b95d834SSanjay Patel unsigned Index0 = cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue(); 993b95d834SSanjay Patel unsigned Index1 = cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue(); 1003b95d834SSanjay Patel 1013b95d834SSanjay Patel // If the extract indexes are identical, no shuffle is needed. 1023b95d834SSanjay Patel if (Index0 == Index1) 1033b95d834SSanjay Patel return nullptr; 1043b95d834SSanjay Patel 1053b95d834SSanjay Patel Type *VecTy = Ext0->getVectorOperand()->getType(); 1063b95d834SSanjay Patel assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types"); 1073b95d834SSanjay Patel int Cost0 = TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0); 1083b95d834SSanjay Patel int Cost1 = TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1); 1093b95d834SSanjay Patel 1103b95d834SSanjay Patel // We are extracting from 2 different indexes, so one operand must be shuffled 1113b95d834SSanjay Patel // before performing a vector operation and/or extract. The more expensive 1123b95d834SSanjay Patel // extract will be replaced by a shuffle. 1133b95d834SSanjay Patel if (Cost0 > Cost1) 1143b95d834SSanjay Patel return Ext0; 1153b95d834SSanjay Patel if (Cost1 > Cost0) 1163b95d834SSanjay Patel return Ext1; 1173b95d834SSanjay Patel 1183b95d834SSanjay Patel // If the costs are equal and there is a preferred extract index, shuffle the 1193b95d834SSanjay Patel // opposite operand. 1203b95d834SSanjay Patel if (PreferredExtractIndex == Index0) 1213b95d834SSanjay Patel return Ext1; 1223b95d834SSanjay Patel if (PreferredExtractIndex == Index1) 1233b95d834SSanjay Patel return Ext0; 1243b95d834SSanjay Patel 1253b95d834SSanjay Patel // Otherwise, replace the extract with the higher index. 1263b95d834SSanjay Patel return Index0 > Index1 ? Ext0 : Ext1; 1273b95d834SSanjay Patel } 1283b95d834SSanjay Patel 129a69158c1SSanjay Patel /// Compare the relative costs of 2 extracts followed by scalar operation vs. 130a69158c1SSanjay Patel /// vector operation(s) followed by extract. Return true if the existing 131a69158c1SSanjay Patel /// instructions are cheaper than a vector alternative. Otherwise, return false 132a69158c1SSanjay Patel /// and if one of the extracts should be transformed to a shufflevector, set 133a69158c1SSanjay Patel /// \p ConvertToShuffle to that extract instruction. 1346bdd531aSSanjay Patel bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0, 1356bdd531aSSanjay Patel ExtractElementInst *Ext1, 1366bdd531aSSanjay Patel unsigned Opcode, 137216a37bbSSanjay Patel ExtractElementInst *&ConvertToShuffle, 138ce97ce3aSSanjay Patel unsigned PreferredExtractIndex) { 1394fa63fd4SAustin Kerbow assert(isa<ConstantInt>(Ext0->getOperand(1)) && 140a69158c1SSanjay Patel isa<ConstantInt>(Ext1->getOperand(1)) && 141a69158c1SSanjay Patel "Expected constant extract indexes"); 14234e34855SSanjay Patel Type *ScalarTy = Ext0->getType(); 143e3056ae9SSam Parker auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType()); 14434e34855SSanjay Patel int ScalarOpCost, VectorOpCost; 14534e34855SSanjay Patel 14634e34855SSanjay Patel // Get cost estimates for scalar and vector versions of the operation. 14734e34855SSanjay Patel bool IsBinOp = Instruction::isBinaryOp(Opcode); 14834e34855SSanjay Patel if (IsBinOp) { 14934e34855SSanjay Patel ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy); 15034e34855SSanjay Patel VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy); 15134e34855SSanjay Patel } else { 15234e34855SSanjay Patel assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) && 15334e34855SSanjay Patel "Expected a compare"); 15434e34855SSanjay Patel ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy, 15534e34855SSanjay Patel CmpInst::makeCmpResultType(ScalarTy)); 15634e34855SSanjay Patel VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy, 15734e34855SSanjay Patel CmpInst::makeCmpResultType(VecTy)); 15834e34855SSanjay Patel } 15934e34855SSanjay Patel 160a69158c1SSanjay Patel // Get cost estimates for the extract elements. These costs will factor into 16134e34855SSanjay Patel // both sequences. 162a69158c1SSanjay Patel unsigned Ext0Index = cast<ConstantInt>(Ext0->getOperand(1))->getZExtValue(); 163a69158c1SSanjay Patel unsigned Ext1Index = cast<ConstantInt>(Ext1->getOperand(1))->getZExtValue(); 164a69158c1SSanjay Patel 1656bdd531aSSanjay Patel int Extract0Cost = 1666bdd531aSSanjay Patel TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext0Index); 1676bdd531aSSanjay Patel int Extract1Cost = 1686bdd531aSSanjay Patel TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext1Index); 169a69158c1SSanjay Patel 170a69158c1SSanjay Patel // A more expensive extract will always be replaced by a splat shuffle. 171a69158c1SSanjay Patel // For example, if Ext0 is more expensive: 172a69158c1SSanjay Patel // opcode (extelt V0, Ext0), (ext V1, Ext1) --> 173a69158c1SSanjay Patel // extelt (opcode (splat V0, Ext0), V1), Ext1 174a69158c1SSanjay Patel // TODO: Evaluate whether that always results in lowest cost. Alternatively, 175a69158c1SSanjay Patel // check the cost of creating a broadcast shuffle and shuffling both 176a69158c1SSanjay Patel // operands to element 0. 177a69158c1SSanjay Patel int CheapExtractCost = std::min(Extract0Cost, Extract1Cost); 17834e34855SSanjay Patel 17934e34855SSanjay Patel // Extra uses of the extracts mean that we include those costs in the 18034e34855SSanjay Patel // vector total because those instructions will not be eliminated. 181e9c79a7aSSanjay Patel int OldCost, NewCost; 182a69158c1SSanjay Patel if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) { 183a69158c1SSanjay Patel // Handle a special case. If the 2 extracts are identical, adjust the 18434e34855SSanjay Patel // formulas to account for that. The extra use charge allows for either the 18534e34855SSanjay Patel // CSE'd pattern or an unoptimized form with identical values: 18634e34855SSanjay Patel // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C 18734e34855SSanjay Patel bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2) 18834e34855SSanjay Patel : !Ext0->hasOneUse() || !Ext1->hasOneUse(); 189a69158c1SSanjay Patel OldCost = CheapExtractCost + ScalarOpCost; 190a69158c1SSanjay Patel NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost; 19134e34855SSanjay Patel } else { 19234e34855SSanjay Patel // Handle the general case. Each extract is actually a different value: 193a69158c1SSanjay Patel // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C 194a69158c1SSanjay Patel OldCost = Extract0Cost + Extract1Cost + ScalarOpCost; 195a69158c1SSanjay Patel NewCost = VectorOpCost + CheapExtractCost + 196a69158c1SSanjay Patel !Ext0->hasOneUse() * Extract0Cost + 197a69158c1SSanjay Patel !Ext1->hasOneUse() * Extract1Cost; 19834e34855SSanjay Patel } 199a69158c1SSanjay Patel 2003b95d834SSanjay Patel ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex); 2013b95d834SSanjay Patel if (ConvertToShuffle) { 202a69158c1SSanjay Patel if (IsBinOp && DisableBinopExtractShuffle) 203a69158c1SSanjay Patel return true; 204a69158c1SSanjay Patel 205a69158c1SSanjay Patel // If we are extracting from 2 different indexes, then one operand must be 206a69158c1SSanjay Patel // shuffled before performing the vector operation. The shuffle mask is 207a69158c1SSanjay Patel // undefined except for 1 lane that is being translated to the remaining 208a69158c1SSanjay Patel // extraction lane. Therefore, it is a splat shuffle. Ex: 209a69158c1SSanjay Patel // ShufMask = { undef, undef, 0, undef } 210a69158c1SSanjay Patel // TODO: The cost model has an option for a "broadcast" shuffle 211a69158c1SSanjay Patel // (splat-from-element-0), but no option for a more general splat. 212a69158c1SSanjay Patel NewCost += 213a69158c1SSanjay Patel TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy); 214a69158c1SSanjay Patel } 215a69158c1SSanjay Patel 21610ea01d8SSanjay Patel // Aggressively form a vector op if the cost is equal because the transform 21710ea01d8SSanjay Patel // may enable further optimization. 21810ea01d8SSanjay Patel // Codegen can reverse this transform (scalarize) if it was not profitable. 21910ea01d8SSanjay Patel return OldCost < NewCost; 22034e34855SSanjay Patel } 22134e34855SSanjay Patel 2229934cc54SSanjay Patel /// Create a shuffle that translates (shifts) 1 element from the input vector 2239934cc54SSanjay Patel /// to a new element location. 2249934cc54SSanjay Patel static Value *createShiftShuffle(Value *Vec, unsigned OldIndex, 2259934cc54SSanjay Patel unsigned NewIndex, IRBuilder<> &Builder) { 2269934cc54SSanjay Patel // The shuffle mask is undefined except for 1 lane that is being translated 2279934cc54SSanjay Patel // to the new element index. Example for OldIndex == 2 and NewIndex == 0: 2289934cc54SSanjay Patel // ShufMask = { 2, undef, undef, undef } 2299934cc54SSanjay Patel auto *VecTy = cast<FixedVectorType>(Vec->getType()); 23054143e2bSSanjay Patel SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem); 2319934cc54SSanjay Patel ShufMask[NewIndex] = OldIndex; 2329934cc54SSanjay Patel Value *Undef = UndefValue::get(VecTy); 2339934cc54SSanjay Patel return Builder.CreateShuffleVector(Vec, Undef, ShufMask, "shift"); 2349934cc54SSanjay Patel } 2359934cc54SSanjay Patel 236216a37bbSSanjay Patel /// Given an extract element instruction with constant index operand, shuffle 237216a37bbSSanjay Patel /// the source vector (shift the scalar element) to a NewIndex for extraction. 238216a37bbSSanjay Patel /// Return null if the input can be constant folded, so that we are not creating 239216a37bbSSanjay Patel /// unnecessary instructions. 2409934cc54SSanjay Patel static ExtractElementInst *translateExtract(ExtractElementInst *ExtElt, 2419934cc54SSanjay Patel unsigned NewIndex, 2429934cc54SSanjay Patel IRBuilder<> &Builder) { 243216a37bbSSanjay Patel // If the extract can be constant-folded, this code is unsimplified. Defer 244216a37bbSSanjay Patel // to other passes to handle that. 245216a37bbSSanjay Patel Value *X = ExtElt->getVectorOperand(); 246216a37bbSSanjay Patel Value *C = ExtElt->getIndexOperand(); 247de65b356SSanjay Patel assert(isa<ConstantInt>(C) && "Expected a constant index operand"); 248216a37bbSSanjay Patel if (isa<Constant>(X)) 249216a37bbSSanjay Patel return nullptr; 250216a37bbSSanjay Patel 2519934cc54SSanjay Patel Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(), 2529934cc54SSanjay Patel NewIndex, Builder); 253216a37bbSSanjay Patel return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex)); 254216a37bbSSanjay Patel } 255216a37bbSSanjay Patel 256fc445589SSanjay Patel /// Try to reduce extract element costs by converting scalar compares to vector 257fc445589SSanjay Patel /// compares followed by extract. 258e9c79a7aSSanjay Patel /// cmp (ext0 V0, C), (ext1 V1, C) 259de65b356SSanjay Patel void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0, 260de65b356SSanjay Patel ExtractElementInst *Ext1, Instruction &I) { 261fc445589SSanjay Patel assert(isa<CmpInst>(&I) && "Expected a compare"); 262216a37bbSSanjay Patel assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() == 263216a37bbSSanjay Patel cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() && 264216a37bbSSanjay Patel "Expected matching constant extract indexes"); 265a17f03bdSSanjay Patel 266a17f03bdSSanjay Patel // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C 267a17f03bdSSanjay Patel ++NumVecCmp; 268fc445589SSanjay Patel CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate(); 269216a37bbSSanjay Patel Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand(); 27046a285adSSanjay Patel Value *VecCmp = Builder.CreateCmp(Pred, V0, V1); 271216a37bbSSanjay Patel Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand()); 27298c2f4eeSSanjay Patel replaceValue(I, *NewExt); 273a17f03bdSSanjay Patel } 274a17f03bdSSanjay Patel 27519b62b79SSanjay Patel /// Try to reduce extract element costs by converting scalar binops to vector 27619b62b79SSanjay Patel /// binops followed by extract. 277e9c79a7aSSanjay Patel /// bo (ext0 V0, C), (ext1 V1, C) 278de65b356SSanjay Patel void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0, 279de65b356SSanjay Patel ExtractElementInst *Ext1, Instruction &I) { 280fc445589SSanjay Patel assert(isa<BinaryOperator>(&I) && "Expected a binary operator"); 281216a37bbSSanjay Patel assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() == 282216a37bbSSanjay Patel cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() && 283216a37bbSSanjay Patel "Expected matching constant extract indexes"); 28419b62b79SSanjay Patel 28534e34855SSanjay Patel // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C 28619b62b79SSanjay Patel ++NumVecBO; 287216a37bbSSanjay Patel Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand(); 288e9c79a7aSSanjay Patel Value *VecBO = 28934e34855SSanjay Patel Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1); 290e9c79a7aSSanjay Patel 29119b62b79SSanjay Patel // All IR flags are safe to back-propagate because any potential poison 29219b62b79SSanjay Patel // created in unused vector elements is discarded by the extract. 293e9c79a7aSSanjay Patel if (auto *VecBOInst = dyn_cast<Instruction>(VecBO)) 29419b62b79SSanjay Patel VecBOInst->copyIRFlags(&I); 295e9c79a7aSSanjay Patel 296216a37bbSSanjay Patel Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand()); 29798c2f4eeSSanjay Patel replaceValue(I, *NewExt); 29819b62b79SSanjay Patel } 29919b62b79SSanjay Patel 300fc445589SSanjay Patel /// Match an instruction with extracted vector operands. 3016bdd531aSSanjay Patel bool VectorCombine::foldExtractExtract(Instruction &I) { 302e9c79a7aSSanjay Patel // It is not safe to transform things like div, urem, etc. because we may 303e9c79a7aSSanjay Patel // create undefined behavior when executing those on unknown vector elements. 304e9c79a7aSSanjay Patel if (!isSafeToSpeculativelyExecute(&I)) 305e9c79a7aSSanjay Patel return false; 306e9c79a7aSSanjay Patel 307216a37bbSSanjay Patel Instruction *I0, *I1; 308fc445589SSanjay Patel CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE; 309216a37bbSSanjay Patel if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) && 310216a37bbSSanjay Patel !match(&I, m_BinOp(m_Instruction(I0), m_Instruction(I1)))) 311fc445589SSanjay Patel return false; 312fc445589SSanjay Patel 313fc445589SSanjay Patel Value *V0, *V1; 314fc445589SSanjay Patel uint64_t C0, C1; 315216a37bbSSanjay Patel if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) || 316216a37bbSSanjay Patel !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) || 317fc445589SSanjay Patel V0->getType() != V1->getType()) 318fc445589SSanjay Patel return false; 319fc445589SSanjay Patel 320ce97ce3aSSanjay Patel // If the scalar value 'I' is going to be re-inserted into a vector, then try 321ce97ce3aSSanjay Patel // to create an extract to that same element. The extract/insert can be 322ce97ce3aSSanjay Patel // reduced to a "select shuffle". 323ce97ce3aSSanjay Patel // TODO: If we add a larger pattern match that starts from an insert, this 324ce97ce3aSSanjay Patel // probably becomes unnecessary. 325216a37bbSSanjay Patel auto *Ext0 = cast<ExtractElementInst>(I0); 326216a37bbSSanjay Patel auto *Ext1 = cast<ExtractElementInst>(I1); 327a0f96741SSanjay Patel uint64_t InsertIndex = InvalidIndex; 328ce97ce3aSSanjay Patel if (I.hasOneUse()) 3297eed772aSSanjay Patel match(I.user_back(), 3307eed772aSSanjay Patel m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex))); 331ce97ce3aSSanjay Patel 332216a37bbSSanjay Patel ExtractElementInst *ExtractToChange; 3336bdd531aSSanjay Patel if (isExtractExtractCheap(Ext0, Ext1, I.getOpcode(), ExtractToChange, 334ce97ce3aSSanjay Patel InsertIndex)) 335fc445589SSanjay Patel return false; 336e9c79a7aSSanjay Patel 337216a37bbSSanjay Patel if (ExtractToChange) { 338216a37bbSSanjay Patel unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0; 339216a37bbSSanjay Patel ExtractElementInst *NewExtract = 3409934cc54SSanjay Patel translateExtract(ExtractToChange, CheapExtractIdx, Builder); 341216a37bbSSanjay Patel if (!NewExtract) 3426d864097SSanjay Patel return false; 343216a37bbSSanjay Patel if (ExtractToChange == Ext0) 344216a37bbSSanjay Patel Ext0 = NewExtract; 345a69158c1SSanjay Patel else 346216a37bbSSanjay Patel Ext1 = NewExtract; 347a69158c1SSanjay Patel } 348e9c79a7aSSanjay Patel 349e9c79a7aSSanjay Patel if (Pred != CmpInst::BAD_ICMP_PREDICATE) 350039ff29eSSanjay Patel foldExtExtCmp(Ext0, Ext1, I); 351e9c79a7aSSanjay Patel else 352039ff29eSSanjay Patel foldExtExtBinop(Ext0, Ext1, I); 353e9c79a7aSSanjay Patel 354e9c79a7aSSanjay Patel return true; 355fc445589SSanjay Patel } 356fc445589SSanjay Patel 357bef6e67eSSanjay Patel /// If this is a bitcast of a shuffle, try to bitcast the source vector to the 358bef6e67eSSanjay Patel /// destination type followed by shuffle. This can enable further transforms by 359bef6e67eSSanjay Patel /// moving bitcasts or shuffles together. 3606bdd531aSSanjay Patel bool VectorCombine::foldBitcastShuf(Instruction &I) { 361b6050ca1SSanjay Patel Value *V; 362b6050ca1SSanjay Patel ArrayRef<int> Mask; 3637eed772aSSanjay Patel if (!match(&I, m_BitCast( 3647eed772aSSanjay Patel m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask)))))) 365b6050ca1SSanjay Patel return false; 366b6050ca1SSanjay Patel 367bef6e67eSSanjay Patel // Disallow non-vector casts and length-changing shuffles. 368bef6e67eSSanjay Patel // TODO: We could allow any shuffle. 3693297e9b7SChristopher Tetreault auto *DestTy = dyn_cast<VectorType>(I.getType()); 3703297e9b7SChristopher Tetreault auto *SrcTy = cast<VectorType>(V->getType()); 3713297e9b7SChristopher Tetreault if (!DestTy || I.getOperand(0)->getType() != SrcTy) 372b6050ca1SSanjay Patel return false; 373b6050ca1SSanjay Patel 374b6050ca1SSanjay Patel // The new shuffle must not cost more than the old shuffle. The bitcast is 375b6050ca1SSanjay Patel // moved ahead of the shuffle, so assume that it has the same cost as before. 376b6050ca1SSanjay Patel if (TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, DestTy) > 377b6050ca1SSanjay Patel TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, SrcTy)) 378b6050ca1SSanjay Patel return false; 379b6050ca1SSanjay Patel 380bef6e67eSSanjay Patel unsigned DestNumElts = DestTy->getNumElements(); 381bef6e67eSSanjay Patel unsigned SrcNumElts = SrcTy->getNumElements(); 382b6050ca1SSanjay Patel SmallVector<int, 16> NewMask; 383bef6e67eSSanjay Patel if (SrcNumElts <= DestNumElts) { 384bef6e67eSSanjay Patel // The bitcast is from wide to narrow/equal elements. The shuffle mask can 385bef6e67eSSanjay Patel // always be expanded to the equivalent form choosing narrower elements. 386b6050ca1SSanjay Patel assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask"); 387b6050ca1SSanjay Patel unsigned ScaleFactor = DestNumElts / SrcNumElts; 3881318ddbcSSanjay Patel narrowShuffleMaskElts(ScaleFactor, Mask, NewMask); 389bef6e67eSSanjay Patel } else { 390bef6e67eSSanjay Patel // The bitcast is from narrow elements to wide elements. The shuffle mask 391bef6e67eSSanjay Patel // must choose consecutive elements to allow casting first. 392bef6e67eSSanjay Patel assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask"); 393bef6e67eSSanjay Patel unsigned ScaleFactor = SrcNumElts / DestNumElts; 394bef6e67eSSanjay Patel if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask)) 395bef6e67eSSanjay Patel return false; 396bef6e67eSSanjay Patel } 397bef6e67eSSanjay Patel // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC' 3987aeb41b3SRoman Lebedev ++NumShufOfBitcast; 399bef6e67eSSanjay Patel Value *CastV = Builder.CreateBitCast(V, DestTy); 4007eed772aSSanjay Patel Value *Shuf = 4017eed772aSSanjay Patel Builder.CreateShuffleVector(CastV, UndefValue::get(DestTy), NewMask); 40298c2f4eeSSanjay Patel replaceValue(I, *Shuf); 403b6050ca1SSanjay Patel return true; 404b6050ca1SSanjay Patel } 405b6050ca1SSanjay Patel 406ed67f5e7SSanjay Patel /// Match a vector binop or compare instruction with at least one inserted 407ed67f5e7SSanjay Patel /// scalar operand and convert to scalar binop/cmp followed by insertelement. 4086bdd531aSSanjay Patel bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) { 409ed67f5e7SSanjay Patel CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE; 4105dc4e7c2SSimon Pilgrim Value *Ins0, *Ins1; 411ed67f5e7SSanjay Patel if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) && 412ed67f5e7SSanjay Patel !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1)))) 413ed67f5e7SSanjay Patel return false; 414ed67f5e7SSanjay Patel 415ed67f5e7SSanjay Patel // Do not convert the vector condition of a vector select into a scalar 416ed67f5e7SSanjay Patel // condition. That may cause problems for codegen because of differences in 417ed67f5e7SSanjay Patel // boolean formats and register-file transfers. 418ed67f5e7SSanjay Patel // TODO: Can we account for that in the cost model? 419ed67f5e7SSanjay Patel bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE; 420ed67f5e7SSanjay Patel if (IsCmp) 421ed67f5e7SSanjay Patel for (User *U : I.users()) 422ed67f5e7SSanjay Patel if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value()))) 4230d2a0b44SSanjay Patel return false; 4240d2a0b44SSanjay Patel 4255dc4e7c2SSimon Pilgrim // Match against one or both scalar values being inserted into constant 4265dc4e7c2SSimon Pilgrim // vectors: 427ed67f5e7SSanjay Patel // vec_op VecC0, (inselt VecC1, V1, Index) 428ed67f5e7SSanjay Patel // vec_op (inselt VecC0, V0, Index), VecC1 429ed67f5e7SSanjay Patel // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) 4300d2a0b44SSanjay Patel // TODO: Deal with mismatched index constants and variable indexes? 4315dc4e7c2SSimon Pilgrim Constant *VecC0 = nullptr, *VecC1 = nullptr; 4325dc4e7c2SSimon Pilgrim Value *V0 = nullptr, *V1 = nullptr; 4335dc4e7c2SSimon Pilgrim uint64_t Index0 = 0, Index1 = 0; 4347eed772aSSanjay Patel if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0), 4355dc4e7c2SSimon Pilgrim m_ConstantInt(Index0))) && 4365dc4e7c2SSimon Pilgrim !match(Ins0, m_Constant(VecC0))) 4375dc4e7c2SSimon Pilgrim return false; 4385dc4e7c2SSimon Pilgrim if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1), 4395dc4e7c2SSimon Pilgrim m_ConstantInt(Index1))) && 4405dc4e7c2SSimon Pilgrim !match(Ins1, m_Constant(VecC1))) 4410d2a0b44SSanjay Patel return false; 4420d2a0b44SSanjay Patel 4435dc4e7c2SSimon Pilgrim bool IsConst0 = !V0; 4445dc4e7c2SSimon Pilgrim bool IsConst1 = !V1; 4455dc4e7c2SSimon Pilgrim if (IsConst0 && IsConst1) 4465dc4e7c2SSimon Pilgrim return false; 4475dc4e7c2SSimon Pilgrim if (!IsConst0 && !IsConst1 && Index0 != Index1) 4485dc4e7c2SSimon Pilgrim return false; 4495dc4e7c2SSimon Pilgrim 4505dc4e7c2SSimon Pilgrim // Bail for single insertion if it is a load. 4515dc4e7c2SSimon Pilgrim // TODO: Handle this once getVectorInstrCost can cost for load/stores. 4525dc4e7c2SSimon Pilgrim auto *I0 = dyn_cast_or_null<Instruction>(V0); 4535dc4e7c2SSimon Pilgrim auto *I1 = dyn_cast_or_null<Instruction>(V1); 4545dc4e7c2SSimon Pilgrim if ((IsConst0 && I1 && I1->mayReadFromMemory()) || 4555dc4e7c2SSimon Pilgrim (IsConst1 && I0 && I0->mayReadFromMemory())) 4565dc4e7c2SSimon Pilgrim return false; 4575dc4e7c2SSimon Pilgrim 4585dc4e7c2SSimon Pilgrim uint64_t Index = IsConst0 ? Index1 : Index0; 4595dc4e7c2SSimon Pilgrim Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType(); 4600d2a0b44SSanjay Patel Type *VecTy = I.getType(); 4615dc4e7c2SSimon Pilgrim assert(VecTy->isVectorTy() && 4625dc4e7c2SSimon Pilgrim (IsConst0 || IsConst1 || V0->getType() == V1->getType()) && 463741e20f3SSanjay Patel (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() || 464741e20f3SSanjay Patel ScalarTy->isPointerTy()) && 465741e20f3SSanjay Patel "Unexpected types for insert element into binop or cmp"); 4660d2a0b44SSanjay Patel 467ed67f5e7SSanjay Patel unsigned Opcode = I.getOpcode(); 468ed67f5e7SSanjay Patel int ScalarOpCost, VectorOpCost; 469ed67f5e7SSanjay Patel if (IsCmp) { 470ed67f5e7SSanjay Patel ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy); 471ed67f5e7SSanjay Patel VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy); 472ed67f5e7SSanjay Patel } else { 473ed67f5e7SSanjay Patel ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy); 474ed67f5e7SSanjay Patel VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy); 475ed67f5e7SSanjay Patel } 4760d2a0b44SSanjay Patel 4770d2a0b44SSanjay Patel // Get cost estimate for the insert element. This cost will factor into 4780d2a0b44SSanjay Patel // both sequences. 4790d2a0b44SSanjay Patel int InsertCost = 4800d2a0b44SSanjay Patel TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, Index); 4815dc4e7c2SSimon Pilgrim int OldCost = (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) + 4825dc4e7c2SSimon Pilgrim VectorOpCost; 4835f730b64SSanjay Patel int NewCost = ScalarOpCost + InsertCost + 4845dc4e7c2SSimon Pilgrim (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) + 4855dc4e7c2SSimon Pilgrim (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost); 4860d2a0b44SSanjay Patel 4870d2a0b44SSanjay Patel // We want to scalarize unless the vector variant actually has lower cost. 4880d2a0b44SSanjay Patel if (OldCost < NewCost) 4890d2a0b44SSanjay Patel return false; 4900d2a0b44SSanjay Patel 491ed67f5e7SSanjay Patel // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) --> 492ed67f5e7SSanjay Patel // inselt NewVecC, (scalar_op V0, V1), Index 493ed67f5e7SSanjay Patel if (IsCmp) 494ed67f5e7SSanjay Patel ++NumScalarCmp; 495ed67f5e7SSanjay Patel else 4960d2a0b44SSanjay Patel ++NumScalarBO; 4975dc4e7c2SSimon Pilgrim 4985dc4e7c2SSimon Pilgrim // For constant cases, extract the scalar element, this should constant fold. 4995dc4e7c2SSimon Pilgrim if (IsConst0) 5005dc4e7c2SSimon Pilgrim V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index)); 5015dc4e7c2SSimon Pilgrim if (IsConst1) 5025dc4e7c2SSimon Pilgrim V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index)); 5035dc4e7c2SSimon Pilgrim 504ed67f5e7SSanjay Patel Value *Scalar = 50546a285adSSanjay Patel IsCmp ? Builder.CreateCmp(Pred, V0, V1) 506ed67f5e7SSanjay Patel : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1); 507ed67f5e7SSanjay Patel 508ed67f5e7SSanjay Patel Scalar->setName(I.getName() + ".scalar"); 5090d2a0b44SSanjay Patel 5100d2a0b44SSanjay Patel // All IR flags are safe to back-propagate. There is no potential for extra 5110d2a0b44SSanjay Patel // poison to be created by the scalar instruction. 5120d2a0b44SSanjay Patel if (auto *ScalarInst = dyn_cast<Instruction>(Scalar)) 5130d2a0b44SSanjay Patel ScalarInst->copyIRFlags(&I); 5140d2a0b44SSanjay Patel 5150d2a0b44SSanjay Patel // Fold the vector constants in the original vectors into a new base vector. 516ed67f5e7SSanjay Patel Constant *NewVecC = IsCmp ? ConstantExpr::getCompare(Pred, VecC0, VecC1) 517ed67f5e7SSanjay Patel : ConstantExpr::get(Opcode, VecC0, VecC1); 5180d2a0b44SSanjay Patel Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index); 51998c2f4eeSSanjay Patel replaceValue(I, *Insert); 5200d2a0b44SSanjay Patel return true; 5210d2a0b44SSanjay Patel } 5220d2a0b44SSanjay Patel 523*b6315aeeSSanjay Patel /// Try to combine a scalar binop + 2 scalar compares of extracted elements of 524*b6315aeeSSanjay Patel /// a vector into vector operations followed by extract. Note: The SLP pass 525*b6315aeeSSanjay Patel /// may miss this pattern because of implementation problems. 526*b6315aeeSSanjay Patel bool VectorCombine::foldExtractedCmps(Instruction &I) { 527*b6315aeeSSanjay Patel // We are looking for a scalar binop of booleans. 528*b6315aeeSSanjay Patel // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1) 529*b6315aeeSSanjay Patel if (!I.isBinaryOp() || !I.getType()->isIntegerTy(1)) 530*b6315aeeSSanjay Patel return false; 531*b6315aeeSSanjay Patel 532*b6315aeeSSanjay Patel // The compare predicates should match, and each compare should have a 533*b6315aeeSSanjay Patel // constant operand. 534*b6315aeeSSanjay Patel // TODO: Relax the one-use constraints. 535*b6315aeeSSanjay Patel Value *B0 = I.getOperand(0), *B1 = I.getOperand(1); 536*b6315aeeSSanjay Patel Instruction *I0, *I1; 537*b6315aeeSSanjay Patel Constant *C0, *C1; 538*b6315aeeSSanjay Patel CmpInst::Predicate P0, P1; 539*b6315aeeSSanjay Patel if (!match(B0, m_OneUse(m_Cmp(P0, m_Instruction(I0), m_Constant(C0)))) || 540*b6315aeeSSanjay Patel !match(B1, m_OneUse(m_Cmp(P1, m_Instruction(I1), m_Constant(C1)))) || 541*b6315aeeSSanjay Patel P0 != P1) 542*b6315aeeSSanjay Patel return false; 543*b6315aeeSSanjay Patel 544*b6315aeeSSanjay Patel // The compare operands must be extracts of the same vector with constant 545*b6315aeeSSanjay Patel // extract indexes. 546*b6315aeeSSanjay Patel // TODO: Relax the one-use constraints. 547*b6315aeeSSanjay Patel Value *X; 548*b6315aeeSSanjay Patel uint64_t Index0, Index1; 549*b6315aeeSSanjay Patel if (!match(I0, m_OneUse(m_ExtractElt(m_Value(X), m_ConstantInt(Index0)))) || 550*b6315aeeSSanjay Patel !match(I1, m_OneUse(m_ExtractElt(m_Specific(X), m_ConstantInt(Index1))))) 551*b6315aeeSSanjay Patel return false; 552*b6315aeeSSanjay Patel 553*b6315aeeSSanjay Patel auto *Ext0 = cast<ExtractElementInst>(I0); 554*b6315aeeSSanjay Patel auto *Ext1 = cast<ExtractElementInst>(I1); 555*b6315aeeSSanjay Patel ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1); 556*b6315aeeSSanjay Patel if (!ConvertToShuf) 557*b6315aeeSSanjay Patel return false; 558*b6315aeeSSanjay Patel 559*b6315aeeSSanjay Patel // The original scalar pattern is: 560*b6315aeeSSanjay Patel // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1) 561*b6315aeeSSanjay Patel CmpInst::Predicate Pred = P0; 562*b6315aeeSSanjay Patel unsigned CmpOpcode = CmpInst::isFPPredicate(Pred) ? Instruction::FCmp 563*b6315aeeSSanjay Patel : Instruction::ICmp; 564*b6315aeeSSanjay Patel auto *VecTy = dyn_cast<FixedVectorType>(X->getType()); 565*b6315aeeSSanjay Patel if (!VecTy) 566*b6315aeeSSanjay Patel return false; 567*b6315aeeSSanjay Patel 568*b6315aeeSSanjay Patel int OldCost = TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0); 569*b6315aeeSSanjay Patel OldCost += TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1); 570*b6315aeeSSanjay Patel OldCost += TTI.getCmpSelInstrCost(CmpOpcode, I0->getType()) * 2; 571*b6315aeeSSanjay Patel OldCost += TTI.getArithmeticInstrCost(I.getOpcode(), I.getType()); 572*b6315aeeSSanjay Patel 573*b6315aeeSSanjay Patel // The proposed vector pattern is: 574*b6315aeeSSanjay Patel // vcmp = cmp Pred X, VecC 575*b6315aeeSSanjay Patel // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0 576*b6315aeeSSanjay Patel int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0; 577*b6315aeeSSanjay Patel int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1; 578*b6315aeeSSanjay Patel auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType())); 579*b6315aeeSSanjay Patel int NewCost = TTI.getCmpSelInstrCost(CmpOpcode, X->getType()); 580*b6315aeeSSanjay Patel NewCost += 581*b6315aeeSSanjay Patel TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, CmpTy); 582*b6315aeeSSanjay Patel NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy); 583*b6315aeeSSanjay Patel NewCost += TTI.getVectorInstrCost(Ext0->getOpcode(), CmpTy, CheapIndex); 584*b6315aeeSSanjay Patel 585*b6315aeeSSanjay Patel // Aggressively form vector ops if the cost is equal because the transform 586*b6315aeeSSanjay Patel // may enable further optimization. 587*b6315aeeSSanjay Patel // Codegen can reverse this transform (scalarize) if it was not profitable. 588*b6315aeeSSanjay Patel if (OldCost < NewCost) 589*b6315aeeSSanjay Patel return false; 590*b6315aeeSSanjay Patel 591*b6315aeeSSanjay Patel // Create a vector constant from the 2 scalar constants. 592*b6315aeeSSanjay Patel SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(), 593*b6315aeeSSanjay Patel UndefValue::get(VecTy->getElementType())); 594*b6315aeeSSanjay Patel CmpC[Index0] = C0; 595*b6315aeeSSanjay Patel CmpC[Index1] = C1; 596*b6315aeeSSanjay Patel Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC)); 597*b6315aeeSSanjay Patel 598*b6315aeeSSanjay Patel Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder); 599*b6315aeeSSanjay Patel Value *VecLogic = Builder.CreateBinOp(cast<BinaryOperator>(I).getOpcode(), 600*b6315aeeSSanjay Patel VCmp, Shuf); 601*b6315aeeSSanjay Patel Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex); 602*b6315aeeSSanjay Patel replaceValue(I, *NewExt); 603*b6315aeeSSanjay Patel ++NumVecCmpBO; 604*b6315aeeSSanjay Patel return true; 605*b6315aeeSSanjay Patel } 606*b6315aeeSSanjay Patel 607a17f03bdSSanjay Patel /// This is the entry point for all transforms. Pass manager differences are 608a17f03bdSSanjay Patel /// handled in the callers of this function. 6096bdd531aSSanjay Patel bool VectorCombine::run() { 61025c6544fSSanjay Patel if (DisableVectorCombine) 61125c6544fSSanjay Patel return false; 61225c6544fSSanjay Patel 613a17f03bdSSanjay Patel bool MadeChange = false; 614a17f03bdSSanjay Patel for (BasicBlock &BB : F) { 615a17f03bdSSanjay Patel // Ignore unreachable basic blocks. 616a17f03bdSSanjay Patel if (!DT.isReachableFromEntry(&BB)) 617a17f03bdSSanjay Patel continue; 618a17f03bdSSanjay Patel // Do not delete instructions under here and invalidate the iterator. 61981e9ede3SSanjay Patel // Walk the block forwards to enable simple iterative chains of transforms. 620a17f03bdSSanjay Patel // TODO: It could be more efficient to remove dead instructions 621a17f03bdSSanjay Patel // iteratively in this loop rather than waiting until the end. 62281e9ede3SSanjay Patel for (Instruction &I : BB) { 623fc3cc8a4SSanjay Patel if (isa<DbgInfoIntrinsic>(I)) 624fc3cc8a4SSanjay Patel continue; 625de65b356SSanjay Patel Builder.SetInsertPoint(&I); 6266bdd531aSSanjay Patel MadeChange |= foldExtractExtract(I); 6276bdd531aSSanjay Patel MadeChange |= foldBitcastShuf(I); 6286bdd531aSSanjay Patel MadeChange |= scalarizeBinopOrCmp(I); 629*b6315aeeSSanjay Patel MadeChange |= foldExtractedCmps(I); 630a17f03bdSSanjay Patel } 631fc3cc8a4SSanjay Patel } 632a17f03bdSSanjay Patel 633a17f03bdSSanjay Patel // We're done with transforms, so remove dead instructions. 634a17f03bdSSanjay Patel if (MadeChange) 635a17f03bdSSanjay Patel for (BasicBlock &BB : F) 636a17f03bdSSanjay Patel SimplifyInstructionsInBlock(&BB); 637a17f03bdSSanjay Patel 638a17f03bdSSanjay Patel return MadeChange; 639a17f03bdSSanjay Patel } 640a17f03bdSSanjay Patel 641a17f03bdSSanjay Patel // Pass manager boilerplate below here. 642a17f03bdSSanjay Patel 643a17f03bdSSanjay Patel namespace { 644a17f03bdSSanjay Patel class VectorCombineLegacyPass : public FunctionPass { 645a17f03bdSSanjay Patel public: 646a17f03bdSSanjay Patel static char ID; 647a17f03bdSSanjay Patel VectorCombineLegacyPass() : FunctionPass(ID) { 648a17f03bdSSanjay Patel initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry()); 649a17f03bdSSanjay Patel } 650a17f03bdSSanjay Patel 651a17f03bdSSanjay Patel void getAnalysisUsage(AnalysisUsage &AU) const override { 652a17f03bdSSanjay Patel AU.addRequired<DominatorTreeWrapperPass>(); 653a17f03bdSSanjay Patel AU.addRequired<TargetTransformInfoWrapperPass>(); 654a17f03bdSSanjay Patel AU.setPreservesCFG(); 655a17f03bdSSanjay Patel AU.addPreserved<DominatorTreeWrapperPass>(); 656a17f03bdSSanjay Patel AU.addPreserved<GlobalsAAWrapperPass>(); 657024098aeSSanjay Patel AU.addPreserved<AAResultsWrapperPass>(); 658024098aeSSanjay Patel AU.addPreserved<BasicAAWrapperPass>(); 659a17f03bdSSanjay Patel FunctionPass::getAnalysisUsage(AU); 660a17f03bdSSanjay Patel } 661a17f03bdSSanjay Patel 662a17f03bdSSanjay Patel bool runOnFunction(Function &F) override { 663a17f03bdSSanjay Patel if (skipFunction(F)) 664a17f03bdSSanjay Patel return false; 665a17f03bdSSanjay Patel auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 666a17f03bdSSanjay Patel auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 6676bdd531aSSanjay Patel VectorCombine Combiner(F, TTI, DT); 6686bdd531aSSanjay Patel return Combiner.run(); 669a17f03bdSSanjay Patel } 670a17f03bdSSanjay Patel }; 671a17f03bdSSanjay Patel } // namespace 672a17f03bdSSanjay Patel 673a17f03bdSSanjay Patel char VectorCombineLegacyPass::ID = 0; 674a17f03bdSSanjay Patel INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine", 675a17f03bdSSanjay Patel "Optimize scalar/vector ops", false, 676a17f03bdSSanjay Patel false) 677a17f03bdSSanjay Patel INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 678a17f03bdSSanjay Patel INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine", 679a17f03bdSSanjay Patel "Optimize scalar/vector ops", false, false) 680a17f03bdSSanjay Patel Pass *llvm::createVectorCombinePass() { 681a17f03bdSSanjay Patel return new VectorCombineLegacyPass(); 682a17f03bdSSanjay Patel } 683a17f03bdSSanjay Patel 684a17f03bdSSanjay Patel PreservedAnalyses VectorCombinePass::run(Function &F, 685a17f03bdSSanjay Patel FunctionAnalysisManager &FAM) { 686a17f03bdSSanjay Patel TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F); 687a17f03bdSSanjay Patel DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F); 6886bdd531aSSanjay Patel VectorCombine Combiner(F, TTI, DT); 6896bdd531aSSanjay Patel if (!Combiner.run()) 690a17f03bdSSanjay Patel return PreservedAnalyses::all(); 691a17f03bdSSanjay Patel PreservedAnalyses PA; 692a17f03bdSSanjay Patel PA.preserveSet<CFGAnalyses>(); 693a17f03bdSSanjay Patel PA.preserve<GlobalsAA>(); 694024098aeSSanjay Patel PA.preserve<AAManager>(); 695024098aeSSanjay Patel PA.preserve<BasicAA>(); 696a17f03bdSSanjay Patel return PA; 697a17f03bdSSanjay Patel } 698