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"
17575e2affSFlorian Hahn #include "llvm/Analysis/AssumptionCache.h"
185006e551SSimon Pilgrim #include "llvm/Analysis/BasicAliasAnalysis.h"
19a17f03bdSSanjay Patel #include "llvm/Analysis/GlobalsModRef.h"
2043bdac29SSanjay Patel #include "llvm/Analysis/Loads.h"
21a17f03bdSSanjay Patel #include "llvm/Analysis/TargetTransformInfo.h"
2219b62b79SSanjay Patel #include "llvm/Analysis/ValueTracking.h"
23b6050ca1SSanjay Patel #include "llvm/Analysis/VectorUtils.h"
24a17f03bdSSanjay Patel #include "llvm/IR/Dominators.h"
25a17f03bdSSanjay Patel #include "llvm/IR/Function.h"
26a17f03bdSSanjay Patel #include "llvm/IR/IRBuilder.h"
27a17f03bdSSanjay Patel #include "llvm/IR/PatternMatch.h"
28a17f03bdSSanjay Patel #include "llvm/InitializePasses.h"
29a17f03bdSSanjay Patel #include "llvm/Pass.h"
3025c6544fSSanjay Patel #include "llvm/Support/CommandLine.h"
31a17f03bdSSanjay Patel #include "llvm/Transforms/Utils/Local.h"
325006e551SSimon Pilgrim #include "llvm/Transforms/Vectorize.h"
33a17f03bdSSanjay Patel 
34300870a9SFlorian Hahn #define DEBUG_TYPE "vector-combine"
35300870a9SFlorian Hahn #include "llvm/Transforms/Utils/InstructionWorklist.h"
36300870a9SFlorian Hahn 
37a17f03bdSSanjay Patel using namespace llvm;
38a17f03bdSSanjay Patel using namespace llvm::PatternMatch;
39a17f03bdSSanjay Patel 
4043bdac29SSanjay Patel STATISTIC(NumVecLoad, "Number of vector loads formed");
41a17f03bdSSanjay Patel STATISTIC(NumVecCmp, "Number of vector compares formed");
4219b62b79SSanjay Patel STATISTIC(NumVecBO, "Number of vector binops formed");
43b6315aeeSSanjay Patel STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed");
447aeb41b3SRoman Lebedev STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
450d2a0b44SSanjay Patel STATISTIC(NumScalarBO, "Number of scalar binops formed");
46ed67f5e7SSanjay Patel STATISTIC(NumScalarCmp, "Number of scalar compares formed");
47a17f03bdSSanjay Patel 
4825c6544fSSanjay Patel static cl::opt<bool> DisableVectorCombine(
4925c6544fSSanjay Patel     "disable-vector-combine", cl::init(false), cl::Hidden,
5025c6544fSSanjay Patel     cl::desc("Disable all vector combine transforms"));
5125c6544fSSanjay Patel 
52a69158c1SSanjay Patel static cl::opt<bool> DisableBinopExtractShuffle(
53a69158c1SSanjay Patel     "disable-binop-extract-shuffle", cl::init(false), cl::Hidden,
54a69158c1SSanjay Patel     cl::desc("Disable binop extract to shuffle transforms"));
55a69158c1SSanjay Patel 
562db4979cSQiu Chaofan static cl::opt<unsigned> MaxInstrsToScan(
572db4979cSQiu Chaofan     "vector-combine-max-scan-instrs", cl::init(30), cl::Hidden,
582db4979cSQiu Chaofan     cl::desc("Max number of instructions to scan for vector combining."));
592db4979cSQiu Chaofan 
60a0f96741SSanjay Patel static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max();
61a0f96741SSanjay Patel 
62b4447054SBenjamin Kramer namespace {
636bdd531aSSanjay Patel class VectorCombine {
646bdd531aSSanjay Patel public:
VectorCombine(Function & F,const TargetTransformInfo & TTI,const DominatorTree & DT,AAResults & AA,AssumptionCache & AC,bool ScalarizationOnly)656bdd531aSSanjay Patel   VectorCombine(Function &F, const TargetTransformInfo &TTI,
664a1d63d7SFlorian Hahn                 const DominatorTree &DT, AAResults &AA, AssumptionCache &AC,
674a1d63d7SFlorian Hahn                 bool ScalarizationOnly)
684a1d63d7SFlorian Hahn       : F(F), Builder(F.getContext()), TTI(TTI), DT(DT), AA(AA), AC(AC),
694a1d63d7SFlorian Hahn         ScalarizationOnly(ScalarizationOnly) {}
706bdd531aSSanjay Patel 
716bdd531aSSanjay Patel   bool run();
726bdd531aSSanjay Patel 
736bdd531aSSanjay Patel private:
746bdd531aSSanjay Patel   Function &F;
75de65b356SSanjay Patel   IRBuilder<> Builder;
766bdd531aSSanjay Patel   const TargetTransformInfo &TTI;
776bdd531aSSanjay Patel   const DominatorTree &DT;
782db4979cSQiu Chaofan   AAResults &AA;
79575e2affSFlorian Hahn   AssumptionCache &AC;
804a1d63d7SFlorian Hahn 
814a1d63d7SFlorian Hahn   /// If true only perform scalarization combines and do not introduce new
824a1d63d7SFlorian Hahn   /// vector operations.
834a1d63d7SFlorian Hahn   bool ScalarizationOnly;
844a1d63d7SFlorian Hahn 
85300870a9SFlorian Hahn   InstructionWorklist Worklist;
866bdd531aSSanjay Patel 
8743bdac29SSanjay Patel   bool vectorizeLoadInsert(Instruction &I);
883b95d834SSanjay Patel   ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0,
893b95d834SSanjay Patel                                         ExtractElementInst *Ext1,
903b95d834SSanjay Patel                                         unsigned PreferredExtractIndex) const;
916bdd531aSSanjay Patel   bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
920dcd2b40SSimon Pilgrim                              const Instruction &I,
936bdd531aSSanjay Patel                              ExtractElementInst *&ConvertToShuffle,
946bdd531aSSanjay Patel                              unsigned PreferredExtractIndex);
95de65b356SSanjay Patel   void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
96de65b356SSanjay Patel                      Instruction &I);
97de65b356SSanjay Patel   void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
98de65b356SSanjay Patel                        Instruction &I);
996bdd531aSSanjay Patel   bool foldExtractExtract(Instruction &I);
1006bdd531aSSanjay Patel   bool foldBitcastShuf(Instruction &I);
1016bdd531aSSanjay Patel   bool scalarizeBinopOrCmp(Instruction &I);
102b6315aeeSSanjay Patel   bool foldExtractedCmps(Instruction &I);
1032db4979cSQiu Chaofan   bool foldSingleElementStore(Instruction &I);
1044e8c28b6SFlorian Hahn   bool scalarizeLoadExtract(Instruction &I);
10566d22b4dSSanjay Patel   bool foldShuffleOfBinops(Instruction &I);
106ded8187eSDavid Green   bool foldShuffleFromReductions(Instruction &I);
1076f9e1ea0SDavid Green   bool foldSelectShuffle(Instruction &I, bool FromReduction = false);
108a69158c1SSanjay Patel 
replaceValue(Value & Old,Value & New)109300870a9SFlorian Hahn   void replaceValue(Value &Old, Value &New) {
11098c2f4eeSSanjay Patel     Old.replaceAllUsesWith(&New);
111300870a9SFlorian Hahn     if (auto *NewI = dyn_cast<Instruction>(&New)) {
112ded8187eSDavid Green       New.takeName(&Old);
113300870a9SFlorian Hahn       Worklist.pushUsersToWorkList(*NewI);
114300870a9SFlorian Hahn       Worklist.pushValue(NewI);
11598c2f4eeSSanjay Patel     }
116300870a9SFlorian Hahn     Worklist.pushValue(&Old);
117300870a9SFlorian Hahn   }
118300870a9SFlorian Hahn 
eraseInstruction(Instruction & I)119300870a9SFlorian Hahn   void eraseInstruction(Instruction &I) {
120300870a9SFlorian Hahn     for (Value *Op : I.operands())
121300870a9SFlorian Hahn       Worklist.pushValue(Op);
122300870a9SFlorian Hahn     Worklist.remove(&I);
123300870a9SFlorian Hahn     I.eraseFromParent();
124300870a9SFlorian Hahn   }
125300870a9SFlorian Hahn };
126300870a9SFlorian Hahn } // namespace
12798c2f4eeSSanjay Patel 
vectorizeLoadInsert(Instruction & I)12843bdac29SSanjay Patel bool VectorCombine::vectorizeLoadInsert(Instruction &I) {
129b2ef2640SSanjay Patel   // Match insert into fixed vector of scalar value.
13047aaa99cSSanjay Patel   // TODO: Handle non-zero insert index.
131ddd9575dSSanjay Patel   auto *Ty = dyn_cast<FixedVectorType>(I.getType());
13243bdac29SSanjay Patel   Value *Scalar;
13348a23bccSSanjay Patel   if (!Ty || !match(&I, m_InsertElt(m_Undef(), m_Value(Scalar), m_ZeroInt())) ||
13448a23bccSSanjay Patel       !Scalar->hasOneUse())
13543bdac29SSanjay Patel     return false;
136ddd9575dSSanjay Patel 
137b2ef2640SSanjay Patel   // Optionally match an extract from another vector.
138b2ef2640SSanjay Patel   Value *X;
139b2ef2640SSanjay Patel   bool HasExtract = match(Scalar, m_ExtractElt(m_Value(X), m_ZeroInt()));
140b2ef2640SSanjay Patel   if (!HasExtract)
141b2ef2640SSanjay Patel     X = Scalar;
142b2ef2640SSanjay Patel 
143b2ef2640SSanjay Patel   // Match source value as load of scalar or vector.
1444452cc40SFangrui Song   // Do not vectorize scalar load (widening) if atomic/volatile or under
1454452cc40SFangrui Song   // asan/hwasan/memtag/tsan. The widened load may load data from dirty regions
1464452cc40SFangrui Song   // or create data races non-existent in the source.
147b2ef2640SSanjay Patel   auto *Load = dyn_cast<LoadInst>(X);
148b2ef2640SSanjay Patel   if (!Load || !Load->isSimple() || !Load->hasOneUse() ||
1494452cc40SFangrui Song       Load->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag) ||
1504452cc40SFangrui Song       mustSuppressSpeculation(*Load))
15143bdac29SSanjay Patel     return false;
15243bdac29SSanjay Patel 
15312b684aeSSanjay Patel   const DataLayout &DL = I.getModule()->getDataLayout();
15412b684aeSSanjay Patel   Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
15512b684aeSSanjay Patel   assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
156c36c0fabSArtem Belevich 
15712b684aeSSanjay Patel   unsigned AS = Load->getPointerAddressSpace();
15843bdac29SSanjay Patel 
15947aaa99cSSanjay Patel   // We are potentially transforming byte-sized (8-bit) memory accesses, so make
16047aaa99cSSanjay Patel   // sure we have all of our type-based constraints in place for this target.
161ddd9575dSSanjay Patel   Type *ScalarTy = Scalar->getType();
16243bdac29SSanjay Patel   uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
163ddd9575dSSanjay Patel   unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
16447aaa99cSSanjay Patel   if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0 ||
16547aaa99cSSanjay Patel       ScalarSize % 8 != 0)
16643bdac29SSanjay Patel     return false;
16743bdac29SSanjay Patel 
16843bdac29SSanjay Patel   // Check safety of replacing the scalar load with a larger vector load.
169aaaf0ec7SSanjay Patel   // We use minimal alignment (maximum flexibility) because we only care about
170aaaf0ec7SSanjay Patel   // the dereferenceable region. When calculating cost and creating a new op,
171aaaf0ec7SSanjay Patel   // we may use a larger value based on alignment attributes.
1728fb05593SSanjay Patel   unsigned MinVecNumElts = MinVectorSize / ScalarSize;
1738fb05593SSanjay Patel   auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts, false);
17447aaa99cSSanjay Patel   unsigned OffsetEltIndex = 0;
17547aaa99cSSanjay Patel   Align Alignment = Load->getAlign();
17647aaa99cSSanjay Patel   if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), DL, Load, &DT)) {
17747aaa99cSSanjay Patel     // It is not safe to load directly from the pointer, but we can still peek
17847aaa99cSSanjay Patel     // through gep offsets and check if it safe to load from a base address with
17947aaa99cSSanjay Patel     // updated alignment. If it is, we can shuffle the element(s) into place
18047aaa99cSSanjay Patel     // after loading.
18147aaa99cSSanjay Patel     unsigned OffsetBitWidth = DL.getIndexTypeSizeInBits(SrcPtr->getType());
18247aaa99cSSanjay Patel     APInt Offset(OffsetBitWidth, 0);
18347aaa99cSSanjay Patel     SrcPtr = SrcPtr->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
18447aaa99cSSanjay Patel 
18547aaa99cSSanjay Patel     // We want to shuffle the result down from a high element of a vector, so
18647aaa99cSSanjay Patel     // the offset must be positive.
18747aaa99cSSanjay Patel     if (Offset.isNegative())
18847aaa99cSSanjay Patel       return false;
18947aaa99cSSanjay Patel 
19047aaa99cSSanjay Patel     // The offset must be a multiple of the scalar element to shuffle cleanly
19147aaa99cSSanjay Patel     // in the element's size.
19247aaa99cSSanjay Patel     uint64_t ScalarSizeInBytes = ScalarSize / 8;
19347aaa99cSSanjay Patel     if (Offset.urem(ScalarSizeInBytes) != 0)
19447aaa99cSSanjay Patel       return false;
19547aaa99cSSanjay Patel 
19647aaa99cSSanjay Patel     // If we load MinVecNumElts, will our target element still be loaded?
19747aaa99cSSanjay Patel     OffsetEltIndex = Offset.udiv(ScalarSizeInBytes).getZExtValue();
19847aaa99cSSanjay Patel     if (OffsetEltIndex >= MinVecNumElts)
19947aaa99cSSanjay Patel       return false;
20047aaa99cSSanjay Patel 
201aaaf0ec7SSanjay Patel     if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), DL, Load, &DT))
20243bdac29SSanjay Patel       return false;
20343bdac29SSanjay Patel 
20447aaa99cSSanjay Patel     // Update alignment with offset value. Note that the offset could be negated
20547aaa99cSSanjay Patel     // to more accurately represent "(new) SrcPtr - Offset = (old) SrcPtr", but
20647aaa99cSSanjay Patel     // negation does not change the result of the alignment calculation.
20747aaa99cSSanjay Patel     Alignment = commonAlignment(Alignment, Offset.getZExtValue());
20847aaa99cSSanjay Patel   }
20947aaa99cSSanjay Patel 
210b2ef2640SSanjay Patel   // Original pattern: insertelt undef, load [free casts of] PtrOp, 0
21138ebc1a1SSanjay Patel   // Use the greater of the alignment on the load or its source pointer.
21247aaa99cSSanjay Patel   Alignment = std::max(SrcPtr->getPointerAlignment(DL), Alignment);
213b2ef2640SSanjay Patel   Type *LoadTy = Load->getType();
21436710c38SCaroline Concatto   InstructionCost OldCost =
21536710c38SCaroline Concatto       TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS);
2168fb05593SSanjay Patel   APInt DemandedElts = APInt::getOneBitSet(MinVecNumElts, 0);
217b2ef2640SSanjay Patel   OldCost += TTI.getScalarizationOverhead(MinVecTy, DemandedElts,
218b2ef2640SSanjay Patel                                           /* Insert */ true, HasExtract);
21943bdac29SSanjay Patel 
22043bdac29SSanjay Patel   // New pattern: load VecPtr
22136710c38SCaroline Concatto   InstructionCost NewCost =
22236710c38SCaroline Concatto       TTI.getMemoryOpCost(Instruction::Load, MinVecTy, Alignment, AS);
22347aaa99cSSanjay Patel   // Optionally, we are shuffling the loaded vector element(s) into place.
224e2935dcfSDavid Green   // For the mask set everything but element 0 to undef to prevent poison from
225e2935dcfSDavid Green   // propagating from the extra loaded memory. This will also optionally
226e2935dcfSDavid Green   // shrink/grow the vector from the loaded size to the output size.
227e2935dcfSDavid Green   // We assume this operation has no cost in codegen if there was no offset.
228e2935dcfSDavid Green   // Note that we could use freeze to avoid poison problems, but then we might
229e2935dcfSDavid Green   // still need a shuffle to change the vector size.
230e2935dcfSDavid Green   unsigned OutputNumElts = Ty->getNumElements();
231e2935dcfSDavid Green   SmallVector<int, 16> Mask(OutputNumElts, UndefMaskElem);
232e2935dcfSDavid Green   assert(OffsetEltIndex < MinVecNumElts && "Address offset too big");
233e2935dcfSDavid Green   Mask[0] = OffsetEltIndex;
23447aaa99cSSanjay Patel   if (OffsetEltIndex)
235e2935dcfSDavid Green     NewCost += TTI.getShuffleCost(TTI::SK_PermuteSingleSrc, MinVecTy, Mask);
23643bdac29SSanjay Patel 
23743bdac29SSanjay Patel   // We can aggressively convert to the vector form because the backend can
23843bdac29SSanjay Patel   // invert this transform if it does not result in a performance win.
23936710c38SCaroline Concatto   if (OldCost < NewCost || !NewCost.isValid())
24043bdac29SSanjay Patel     return false;
24143bdac29SSanjay Patel 
24243bdac29SSanjay Patel   // It is safe and potentially profitable to load a vector directly:
24343bdac29SSanjay Patel   // inselt undef, load Scalar, 0 --> load VecPtr
24443bdac29SSanjay Patel   IRBuilder<> Builder(Load);
2452e44b787SFraser Cormack   Value *CastedPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
2462e44b787SFraser Cormack       SrcPtr, MinVecTy->getPointerTo(AS));
2478fb05593SSanjay Patel   Value *VecLd = Builder.CreateAlignedLoad(MinVecTy, CastedPtr, Alignment);
2481e6b240dSSanjay Patel   VecLd = Builder.CreateShuffleVector(VecLd, Mask);
249d399f870SSanjay Patel 
25043bdac29SSanjay Patel   replaceValue(I, *VecLd);
25143bdac29SSanjay Patel   ++NumVecLoad;
25243bdac29SSanjay Patel   return true;
25343bdac29SSanjay Patel }
25443bdac29SSanjay Patel 
2553b95d834SSanjay Patel /// Determine which, if any, of the inputs should be replaced by a shuffle
2563b95d834SSanjay Patel /// followed by extract from a different index.
getShuffleExtract(ExtractElementInst * Ext0,ExtractElementInst * Ext1,unsigned PreferredExtractIndex=InvalidIndex) const2573b95d834SSanjay Patel ExtractElementInst *VectorCombine::getShuffleExtract(
2583b95d834SSanjay Patel     ExtractElementInst *Ext0, ExtractElementInst *Ext1,
2593b95d834SSanjay Patel     unsigned PreferredExtractIndex = InvalidIndex) const {
26034f97a37SSimon Pilgrim   auto *Index0C = dyn_cast<ConstantInt>(Ext0->getIndexOperand());
26134f97a37SSimon Pilgrim   auto *Index1C = dyn_cast<ConstantInt>(Ext1->getIndexOperand());
26234f97a37SSimon Pilgrim   assert(Index0C && Index1C && "Expected constant extract indexes");
2633b95d834SSanjay Patel 
26434f97a37SSimon Pilgrim   unsigned Index0 = Index0C->getZExtValue();
26534f97a37SSimon Pilgrim   unsigned Index1 = Index1C->getZExtValue();
2663b95d834SSanjay Patel 
2673b95d834SSanjay Patel   // If the extract indexes are identical, no shuffle is needed.
2683b95d834SSanjay Patel   if (Index0 == Index1)
2693b95d834SSanjay Patel     return nullptr;
2703b95d834SSanjay Patel 
2713b95d834SSanjay Patel   Type *VecTy = Ext0->getVectorOperand()->getType();
2723b95d834SSanjay Patel   assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types");
27336710c38SCaroline Concatto   InstructionCost Cost0 =
27436710c38SCaroline Concatto       TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
27536710c38SCaroline Concatto   InstructionCost Cost1 =
27636710c38SCaroline Concatto       TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
27736710c38SCaroline Concatto 
27836710c38SCaroline Concatto   // If both costs are invalid no shuffle is needed
27936710c38SCaroline Concatto   if (!Cost0.isValid() && !Cost1.isValid())
28036710c38SCaroline Concatto     return nullptr;
2813b95d834SSanjay Patel 
2823b95d834SSanjay Patel   // We are extracting from 2 different indexes, so one operand must be shuffled
2833b95d834SSanjay Patel   // before performing a vector operation and/or extract. The more expensive
2843b95d834SSanjay Patel   // extract will be replaced by a shuffle.
2853b95d834SSanjay Patel   if (Cost0 > Cost1)
2863b95d834SSanjay Patel     return Ext0;
2873b95d834SSanjay Patel   if (Cost1 > Cost0)
2883b95d834SSanjay Patel     return Ext1;
2893b95d834SSanjay Patel 
2903b95d834SSanjay Patel   // If the costs are equal and there is a preferred extract index, shuffle the
2913b95d834SSanjay Patel   // opposite operand.
2923b95d834SSanjay Patel   if (PreferredExtractIndex == Index0)
2933b95d834SSanjay Patel     return Ext1;
2943b95d834SSanjay Patel   if (PreferredExtractIndex == Index1)
2953b95d834SSanjay Patel     return Ext0;
2963b95d834SSanjay Patel 
2973b95d834SSanjay Patel   // Otherwise, replace the extract with the higher index.
2983b95d834SSanjay Patel   return Index0 > Index1 ? Ext0 : Ext1;
2993b95d834SSanjay Patel }
3003b95d834SSanjay Patel 
301a69158c1SSanjay Patel /// Compare the relative costs of 2 extracts followed by scalar operation vs.
302a69158c1SSanjay Patel /// vector operation(s) followed by extract. Return true if the existing
303a69158c1SSanjay Patel /// instructions are cheaper than a vector alternative. Otherwise, return false
304a69158c1SSanjay Patel /// and if one of the extracts should be transformed to a shufflevector, set
305a69158c1SSanjay Patel /// \p ConvertToShuffle to that extract instruction.
isExtractExtractCheap(ExtractElementInst * Ext0,ExtractElementInst * Ext1,const Instruction & I,ExtractElementInst * & ConvertToShuffle,unsigned PreferredExtractIndex)3066bdd531aSSanjay Patel bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0,
3076bdd531aSSanjay Patel                                           ExtractElementInst *Ext1,
3080dcd2b40SSimon Pilgrim                                           const Instruction &I,
309216a37bbSSanjay Patel                                           ExtractElementInst *&ConvertToShuffle,
310ce97ce3aSSanjay Patel                                           unsigned PreferredExtractIndex) {
31134f97a37SSimon Pilgrim   auto *Ext0IndexC = dyn_cast<ConstantInt>(Ext0->getOperand(1));
31234f97a37SSimon Pilgrim   auto *Ext1IndexC = dyn_cast<ConstantInt>(Ext1->getOperand(1));
31334f97a37SSimon Pilgrim   assert(Ext0IndexC && Ext1IndexC && "Expected constant extract indexes");
31434f97a37SSimon Pilgrim 
3150dcd2b40SSimon Pilgrim   unsigned Opcode = I.getOpcode();
31634e34855SSanjay Patel   Type *ScalarTy = Ext0->getType();
317e3056ae9SSam Parker   auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType());
31836710c38SCaroline Concatto   InstructionCost ScalarOpCost, VectorOpCost;
31934e34855SSanjay Patel 
32034e34855SSanjay Patel   // Get cost estimates for scalar and vector versions of the operation.
32134e34855SSanjay Patel   bool IsBinOp = Instruction::isBinaryOp(Opcode);
32234e34855SSanjay Patel   if (IsBinOp) {
32334e34855SSanjay Patel     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
32434e34855SSanjay Patel     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
32534e34855SSanjay Patel   } else {
32634e34855SSanjay Patel     assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
32734e34855SSanjay Patel            "Expected a compare");
3280dcd2b40SSimon Pilgrim     CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
3290dcd2b40SSimon Pilgrim     ScalarOpCost = TTI.getCmpSelInstrCost(
3300dcd2b40SSimon Pilgrim         Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred);
3310dcd2b40SSimon Pilgrim     VectorOpCost = TTI.getCmpSelInstrCost(
3320dcd2b40SSimon Pilgrim         Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred);
33334e34855SSanjay Patel   }
33434e34855SSanjay Patel 
335a69158c1SSanjay Patel   // Get cost estimates for the extract elements. These costs will factor into
33634e34855SSanjay Patel   // both sequences.
33734f97a37SSimon Pilgrim   unsigned Ext0Index = Ext0IndexC->getZExtValue();
33834f97a37SSimon Pilgrim   unsigned Ext1Index = Ext1IndexC->getZExtValue();
339a69158c1SSanjay Patel 
34036710c38SCaroline Concatto   InstructionCost Extract0Cost =
3416bdd531aSSanjay Patel       TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext0Index);
34236710c38SCaroline Concatto   InstructionCost Extract1Cost =
3436bdd531aSSanjay Patel       TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext1Index);
344a69158c1SSanjay Patel 
345a69158c1SSanjay Patel   // A more expensive extract will always be replaced by a splat shuffle.
346a69158c1SSanjay Patel   // For example, if Ext0 is more expensive:
347a69158c1SSanjay Patel   // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
348a69158c1SSanjay Patel   // extelt (opcode (splat V0, Ext0), V1), Ext1
349a69158c1SSanjay Patel   // TODO: Evaluate whether that always results in lowest cost. Alternatively,
350a69158c1SSanjay Patel   //       check the cost of creating a broadcast shuffle and shuffling both
351a69158c1SSanjay Patel   //       operands to element 0.
35236710c38SCaroline Concatto   InstructionCost CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
35334e34855SSanjay Patel 
35434e34855SSanjay Patel   // Extra uses of the extracts mean that we include those costs in the
35534e34855SSanjay Patel   // vector total because those instructions will not be eliminated.
35636710c38SCaroline Concatto   InstructionCost OldCost, NewCost;
357a69158c1SSanjay Patel   if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) {
358a69158c1SSanjay Patel     // Handle a special case. If the 2 extracts are identical, adjust the
35934e34855SSanjay Patel     // formulas to account for that. The extra use charge allows for either the
36034e34855SSanjay Patel     // CSE'd pattern or an unoptimized form with identical values:
36134e34855SSanjay Patel     // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
36234e34855SSanjay Patel     bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
36334e34855SSanjay Patel                                   : !Ext0->hasOneUse() || !Ext1->hasOneUse();
364a69158c1SSanjay Patel     OldCost = CheapExtractCost + ScalarOpCost;
365a69158c1SSanjay Patel     NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
36634e34855SSanjay Patel   } else {
36734e34855SSanjay Patel     // Handle the general case. Each extract is actually a different value:
368a69158c1SSanjay Patel     // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
369a69158c1SSanjay Patel     OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
370a69158c1SSanjay Patel     NewCost = VectorOpCost + CheapExtractCost +
371a69158c1SSanjay Patel               !Ext0->hasOneUse() * Extract0Cost +
372a69158c1SSanjay Patel               !Ext1->hasOneUse() * Extract1Cost;
37334e34855SSanjay Patel   }
374a69158c1SSanjay Patel 
3753b95d834SSanjay Patel   ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex);
3763b95d834SSanjay Patel   if (ConvertToShuffle) {
377a69158c1SSanjay Patel     if (IsBinOp && DisableBinopExtractShuffle)
378a69158c1SSanjay Patel       return true;
379a69158c1SSanjay Patel 
380a69158c1SSanjay Patel     // If we are extracting from 2 different indexes, then one operand must be
381a69158c1SSanjay Patel     // shuffled before performing the vector operation. The shuffle mask is
382a69158c1SSanjay Patel     // undefined except for 1 lane that is being translated to the remaining
383a69158c1SSanjay Patel     // extraction lane. Therefore, it is a splat shuffle. Ex:
384a69158c1SSanjay Patel     // ShufMask = { undef, undef, 0, undef }
385a69158c1SSanjay Patel     // TODO: The cost model has an option for a "broadcast" shuffle
386a69158c1SSanjay Patel     //       (splat-from-element-0), but no option for a more general splat.
387a69158c1SSanjay Patel     NewCost +=
388a69158c1SSanjay Patel         TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
389a69158c1SSanjay Patel   }
390a69158c1SSanjay Patel 
39110ea01d8SSanjay Patel   // Aggressively form a vector op if the cost is equal because the transform
39210ea01d8SSanjay Patel   // may enable further optimization.
39310ea01d8SSanjay Patel   // Codegen can reverse this transform (scalarize) if it was not profitable.
39410ea01d8SSanjay Patel   return OldCost < NewCost;
39534e34855SSanjay Patel }
39634e34855SSanjay Patel 
3979934cc54SSanjay Patel /// Create a shuffle that translates (shifts) 1 element from the input vector
3989934cc54SSanjay Patel /// to a new element location.
createShiftShuffle(Value * Vec,unsigned OldIndex,unsigned NewIndex,IRBuilder<> & Builder)3999934cc54SSanjay Patel static Value *createShiftShuffle(Value *Vec, unsigned OldIndex,
4009934cc54SSanjay Patel                                  unsigned NewIndex, IRBuilder<> &Builder) {
4019934cc54SSanjay Patel   // The shuffle mask is undefined except for 1 lane that is being translated
4029934cc54SSanjay Patel   // to the new element index. Example for OldIndex == 2 and NewIndex == 0:
4039934cc54SSanjay Patel   // ShufMask = { 2, undef, undef, undef }
4049934cc54SSanjay Patel   auto *VecTy = cast<FixedVectorType>(Vec->getType());
40554143e2bSSanjay Patel   SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem);
4069934cc54SSanjay Patel   ShufMask[NewIndex] = OldIndex;
4071e6b240dSSanjay Patel   return Builder.CreateShuffleVector(Vec, ShufMask, "shift");
4089934cc54SSanjay Patel }
4099934cc54SSanjay Patel 
410216a37bbSSanjay Patel /// Given an extract element instruction with constant index operand, shuffle
411216a37bbSSanjay Patel /// the source vector (shift the scalar element) to a NewIndex for extraction.
412216a37bbSSanjay Patel /// Return null if the input can be constant folded, so that we are not creating
413216a37bbSSanjay Patel /// unnecessary instructions.
translateExtract(ExtractElementInst * ExtElt,unsigned NewIndex,IRBuilder<> & Builder)4149934cc54SSanjay Patel static ExtractElementInst *translateExtract(ExtractElementInst *ExtElt,
4159934cc54SSanjay Patel                                             unsigned NewIndex,
4169934cc54SSanjay Patel                                             IRBuilder<> &Builder) {
417519d7876SSander de Smalen   // Shufflevectors can only be created for fixed-width vectors.
418519d7876SSander de Smalen   if (!isa<FixedVectorType>(ExtElt->getOperand(0)->getType()))
419519d7876SSander de Smalen     return nullptr;
420519d7876SSander de Smalen 
421216a37bbSSanjay Patel   // If the extract can be constant-folded, this code is unsimplified. Defer
422216a37bbSSanjay Patel   // to other passes to handle that.
423216a37bbSSanjay Patel   Value *X = ExtElt->getVectorOperand();
424216a37bbSSanjay Patel   Value *C = ExtElt->getIndexOperand();
425de65b356SSanjay Patel   assert(isa<ConstantInt>(C) && "Expected a constant index operand");
426216a37bbSSanjay Patel   if (isa<Constant>(X))
427216a37bbSSanjay Patel     return nullptr;
428216a37bbSSanjay Patel 
4299934cc54SSanjay Patel   Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(),
4309934cc54SSanjay Patel                                    NewIndex, Builder);
431216a37bbSSanjay Patel   return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex));
432216a37bbSSanjay Patel }
433216a37bbSSanjay Patel 
434fc445589SSanjay Patel /// Try to reduce extract element costs by converting scalar compares to vector
435fc445589SSanjay Patel /// compares followed by extract.
436e9c79a7aSSanjay Patel /// cmp (ext0 V0, C), (ext1 V1, C)
foldExtExtCmp(ExtractElementInst * Ext0,ExtractElementInst * Ext1,Instruction & I)437de65b356SSanjay Patel void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0,
438de65b356SSanjay Patel                                   ExtractElementInst *Ext1, Instruction &I) {
439fc445589SSanjay Patel   assert(isa<CmpInst>(&I) && "Expected a compare");
440216a37bbSSanjay Patel   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
441216a37bbSSanjay Patel              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
442216a37bbSSanjay Patel          "Expected matching constant extract indexes");
443a17f03bdSSanjay Patel 
444a17f03bdSSanjay Patel   // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C
445a17f03bdSSanjay Patel   ++NumVecCmp;
446fc445589SSanjay Patel   CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
447216a37bbSSanjay Patel   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
44846a285adSSanjay Patel   Value *VecCmp = Builder.CreateCmp(Pred, V0, V1);
449216a37bbSSanjay Patel   Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand());
45098c2f4eeSSanjay Patel   replaceValue(I, *NewExt);
451a17f03bdSSanjay Patel }
452a17f03bdSSanjay Patel 
45319b62b79SSanjay Patel /// Try to reduce extract element costs by converting scalar binops to vector
45419b62b79SSanjay Patel /// binops followed by extract.
455e9c79a7aSSanjay Patel /// bo (ext0 V0, C), (ext1 V1, C)
foldExtExtBinop(ExtractElementInst * Ext0,ExtractElementInst * Ext1,Instruction & I)456de65b356SSanjay Patel void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0,
457de65b356SSanjay Patel                                     ExtractElementInst *Ext1, Instruction &I) {
458fc445589SSanjay Patel   assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
459216a37bbSSanjay Patel   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
460216a37bbSSanjay Patel              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
461216a37bbSSanjay Patel          "Expected matching constant extract indexes");
46219b62b79SSanjay Patel 
46334e34855SSanjay Patel   // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C
46419b62b79SSanjay Patel   ++NumVecBO;
465216a37bbSSanjay Patel   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
466e9c79a7aSSanjay Patel   Value *VecBO =
46734e34855SSanjay Patel       Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1);
468e9c79a7aSSanjay Patel 
46919b62b79SSanjay Patel   // All IR flags are safe to back-propagate because any potential poison
47019b62b79SSanjay Patel   // created in unused vector elements is discarded by the extract.
471e9c79a7aSSanjay Patel   if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
47219b62b79SSanjay Patel     VecBOInst->copyIRFlags(&I);
473e9c79a7aSSanjay Patel 
474216a37bbSSanjay Patel   Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand());
47598c2f4eeSSanjay Patel   replaceValue(I, *NewExt);
47619b62b79SSanjay Patel }
47719b62b79SSanjay Patel 
478fc445589SSanjay Patel /// Match an instruction with extracted vector operands.
foldExtractExtract(Instruction & I)4796bdd531aSSanjay Patel bool VectorCombine::foldExtractExtract(Instruction &I) {
480e9c79a7aSSanjay Patel   // It is not safe to transform things like div, urem, etc. because we may
481e9c79a7aSSanjay Patel   // create undefined behavior when executing those on unknown vector elements.
482e9c79a7aSSanjay Patel   if (!isSafeToSpeculativelyExecute(&I))
483e9c79a7aSSanjay Patel     return false;
484e9c79a7aSSanjay Patel 
485216a37bbSSanjay Patel   Instruction *I0, *I1;
486fc445589SSanjay Patel   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
487216a37bbSSanjay Patel   if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) &&
488216a37bbSSanjay Patel       !match(&I, m_BinOp(m_Instruction(I0), m_Instruction(I1))))
489fc445589SSanjay Patel     return false;
490fc445589SSanjay Patel 
491fc445589SSanjay Patel   Value *V0, *V1;
492fc445589SSanjay Patel   uint64_t C0, C1;
493216a37bbSSanjay Patel   if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
494216a37bbSSanjay Patel       !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) ||
495fc445589SSanjay Patel       V0->getType() != V1->getType())
496fc445589SSanjay Patel     return false;
497fc445589SSanjay Patel 
498ce97ce3aSSanjay Patel   // If the scalar value 'I' is going to be re-inserted into a vector, then try
499ce97ce3aSSanjay Patel   // to create an extract to that same element. The extract/insert can be
500ce97ce3aSSanjay Patel   // reduced to a "select shuffle".
501ce97ce3aSSanjay Patel   // TODO: If we add a larger pattern match that starts from an insert, this
502ce97ce3aSSanjay Patel   //       probably becomes unnecessary.
503216a37bbSSanjay Patel   auto *Ext0 = cast<ExtractElementInst>(I0);
504216a37bbSSanjay Patel   auto *Ext1 = cast<ExtractElementInst>(I1);
505a0f96741SSanjay Patel   uint64_t InsertIndex = InvalidIndex;
506ce97ce3aSSanjay Patel   if (I.hasOneUse())
5077eed772aSSanjay Patel     match(I.user_back(),
5087eed772aSSanjay Patel           m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
509ce97ce3aSSanjay Patel 
510216a37bbSSanjay Patel   ExtractElementInst *ExtractToChange;
5110dcd2b40SSimon Pilgrim   if (isExtractExtractCheap(Ext0, Ext1, I, ExtractToChange, InsertIndex))
512fc445589SSanjay Patel     return false;
513e9c79a7aSSanjay Patel 
514216a37bbSSanjay Patel   if (ExtractToChange) {
515216a37bbSSanjay Patel     unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0;
516216a37bbSSanjay Patel     ExtractElementInst *NewExtract =
5179934cc54SSanjay Patel         translateExtract(ExtractToChange, CheapExtractIdx, Builder);
518216a37bbSSanjay Patel     if (!NewExtract)
5196d864097SSanjay Patel       return false;
520216a37bbSSanjay Patel     if (ExtractToChange == Ext0)
521216a37bbSSanjay Patel       Ext0 = NewExtract;
522a69158c1SSanjay Patel     else
523216a37bbSSanjay Patel       Ext1 = NewExtract;
524a69158c1SSanjay Patel   }
525e9c79a7aSSanjay Patel 
526e9c79a7aSSanjay Patel   if (Pred != CmpInst::BAD_ICMP_PREDICATE)
527039ff29eSSanjay Patel     foldExtExtCmp(Ext0, Ext1, I);
528e9c79a7aSSanjay Patel   else
529039ff29eSSanjay Patel     foldExtExtBinop(Ext0, Ext1, I);
530e9c79a7aSSanjay Patel 
531300870a9SFlorian Hahn   Worklist.push(Ext0);
532300870a9SFlorian Hahn   Worklist.push(Ext1);
533e9c79a7aSSanjay Patel   return true;
534fc445589SSanjay Patel }
535fc445589SSanjay Patel 
536bef6e67eSSanjay Patel /// If this is a bitcast of a shuffle, try to bitcast the source vector to the
537bef6e67eSSanjay Patel /// destination type followed by shuffle. This can enable further transforms by
538bef6e67eSSanjay Patel /// moving bitcasts or shuffles together.
foldBitcastShuf(Instruction & I)5396bdd531aSSanjay Patel bool VectorCombine::foldBitcastShuf(Instruction &I) {
540b6050ca1SSanjay Patel   Value *V;
541b6050ca1SSanjay Patel   ArrayRef<int> Mask;
5427eed772aSSanjay Patel   if (!match(&I, m_BitCast(
5437eed772aSSanjay Patel                      m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))))))
544b6050ca1SSanjay Patel     return false;
545b6050ca1SSanjay Patel 
546b4f04d71SHuihui Zhang   // 1) Do not fold bitcast shuffle for scalable type. First, shuffle cost for
547b4f04d71SHuihui Zhang   // scalable type is unknown; Second, we cannot reason if the narrowed shuffle
548b4f04d71SHuihui Zhang   // mask for scalable type is a splat or not.
549b4f04d71SHuihui Zhang   // 2) Disallow non-vector casts and length-changing shuffles.
550bef6e67eSSanjay Patel   // TODO: We could allow any shuffle.
551b4f04d71SHuihui Zhang   auto *DestTy = dyn_cast<FixedVectorType>(I.getType());
552b4f04d71SHuihui Zhang   auto *SrcTy = dyn_cast<FixedVectorType>(V->getType());
553b4f04d71SHuihui Zhang   if (!SrcTy || !DestTy || I.getOperand(0)->getType() != SrcTy)
554b6050ca1SSanjay Patel     return false;
555b6050ca1SSanjay Patel 
556b4f04d71SHuihui Zhang   unsigned DestNumElts = DestTy->getNumElements();
557b4f04d71SHuihui Zhang   unsigned SrcNumElts = SrcTy->getNumElements();
558b6050ca1SSanjay Patel   SmallVector<int, 16> NewMask;
559bef6e67eSSanjay Patel   if (SrcNumElts <= DestNumElts) {
560bef6e67eSSanjay Patel     // The bitcast is from wide to narrow/equal elements. The shuffle mask can
561bef6e67eSSanjay Patel     // always be expanded to the equivalent form choosing narrower elements.
562b6050ca1SSanjay Patel     assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask");
563b6050ca1SSanjay Patel     unsigned ScaleFactor = DestNumElts / SrcNumElts;
5641318ddbcSSanjay Patel     narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
565bef6e67eSSanjay Patel   } else {
566bef6e67eSSanjay Patel     // The bitcast is from narrow elements to wide elements. The shuffle mask
567bef6e67eSSanjay Patel     // must choose consecutive elements to allow casting first.
568bef6e67eSSanjay Patel     assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask");
569bef6e67eSSanjay Patel     unsigned ScaleFactor = SrcNumElts / DestNumElts;
570bef6e67eSSanjay Patel     if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
571bef6e67eSSanjay Patel       return false;
572bef6e67eSSanjay Patel   }
573e2935dcfSDavid Green 
574e2935dcfSDavid Green   // The new shuffle must not cost more than the old shuffle. The bitcast is
575e2935dcfSDavid Green   // moved ahead of the shuffle, so assume that it has the same cost as before.
576e2935dcfSDavid Green   InstructionCost DestCost = TTI.getShuffleCost(
577e2935dcfSDavid Green       TargetTransformInfo::SK_PermuteSingleSrc, DestTy, NewMask);
578e2935dcfSDavid Green   InstructionCost SrcCost =
579e2935dcfSDavid Green       TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, SrcTy, Mask);
580e2935dcfSDavid Green   if (DestCost > SrcCost || !DestCost.isValid())
581e2935dcfSDavid Green     return false;
582e2935dcfSDavid Green 
583bef6e67eSSanjay Patel   // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC'
5847aeb41b3SRoman Lebedev   ++NumShufOfBitcast;
585bef6e67eSSanjay Patel   Value *CastV = Builder.CreateBitCast(V, DestTy);
5861e6b240dSSanjay Patel   Value *Shuf = Builder.CreateShuffleVector(CastV, NewMask);
58798c2f4eeSSanjay Patel   replaceValue(I, *Shuf);
588b6050ca1SSanjay Patel   return true;
589b6050ca1SSanjay Patel }
590b6050ca1SSanjay Patel 
591ed67f5e7SSanjay Patel /// Match a vector binop or compare instruction with at least one inserted
592ed67f5e7SSanjay Patel /// scalar operand and convert to scalar binop/cmp followed by insertelement.
scalarizeBinopOrCmp(Instruction & I)5936bdd531aSSanjay Patel bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) {
594ed67f5e7SSanjay Patel   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
5955dc4e7c2SSimon Pilgrim   Value *Ins0, *Ins1;
596ed67f5e7SSanjay Patel   if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) &&
597ed67f5e7SSanjay Patel       !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1))))
598ed67f5e7SSanjay Patel     return false;
599ed67f5e7SSanjay Patel 
600ed67f5e7SSanjay Patel   // Do not convert the vector condition of a vector select into a scalar
601ed67f5e7SSanjay Patel   // condition. That may cause problems for codegen because of differences in
602ed67f5e7SSanjay Patel   // boolean formats and register-file transfers.
603ed67f5e7SSanjay Patel   // TODO: Can we account for that in the cost model?
604ed67f5e7SSanjay Patel   bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE;
605ed67f5e7SSanjay Patel   if (IsCmp)
606ed67f5e7SSanjay Patel     for (User *U : I.users())
607ed67f5e7SSanjay Patel       if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
6080d2a0b44SSanjay Patel         return false;
6090d2a0b44SSanjay Patel 
6105dc4e7c2SSimon Pilgrim   // Match against one or both scalar values being inserted into constant
6115dc4e7c2SSimon Pilgrim   // vectors:
612ed67f5e7SSanjay Patel   // vec_op VecC0, (inselt VecC1, V1, Index)
613ed67f5e7SSanjay Patel   // vec_op (inselt VecC0, V0, Index), VecC1
614ed67f5e7SSanjay Patel   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index)
6150d2a0b44SSanjay Patel   // TODO: Deal with mismatched index constants and variable indexes?
6165dc4e7c2SSimon Pilgrim   Constant *VecC0 = nullptr, *VecC1 = nullptr;
6175dc4e7c2SSimon Pilgrim   Value *V0 = nullptr, *V1 = nullptr;
6185dc4e7c2SSimon Pilgrim   uint64_t Index0 = 0, Index1 = 0;
6197eed772aSSanjay Patel   if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
6205dc4e7c2SSimon Pilgrim                                m_ConstantInt(Index0))) &&
6215dc4e7c2SSimon Pilgrim       !match(Ins0, m_Constant(VecC0)))
6225dc4e7c2SSimon Pilgrim     return false;
6235dc4e7c2SSimon Pilgrim   if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
6245dc4e7c2SSimon Pilgrim                                m_ConstantInt(Index1))) &&
6255dc4e7c2SSimon Pilgrim       !match(Ins1, m_Constant(VecC1)))
6260d2a0b44SSanjay Patel     return false;
6270d2a0b44SSanjay Patel 
6285dc4e7c2SSimon Pilgrim   bool IsConst0 = !V0;
6295dc4e7c2SSimon Pilgrim   bool IsConst1 = !V1;
6305dc4e7c2SSimon Pilgrim   if (IsConst0 && IsConst1)
6315dc4e7c2SSimon Pilgrim     return false;
6325dc4e7c2SSimon Pilgrim   if (!IsConst0 && !IsConst1 && Index0 != Index1)
6335dc4e7c2SSimon Pilgrim     return false;
6345dc4e7c2SSimon Pilgrim 
6355dc4e7c2SSimon Pilgrim   // Bail for single insertion if it is a load.
6365dc4e7c2SSimon Pilgrim   // TODO: Handle this once getVectorInstrCost can cost for load/stores.
6375dc4e7c2SSimon Pilgrim   auto *I0 = dyn_cast_or_null<Instruction>(V0);
6385dc4e7c2SSimon Pilgrim   auto *I1 = dyn_cast_or_null<Instruction>(V1);
6395dc4e7c2SSimon Pilgrim   if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
6405dc4e7c2SSimon Pilgrim       (IsConst1 && I0 && I0->mayReadFromMemory()))
6415dc4e7c2SSimon Pilgrim     return false;
6425dc4e7c2SSimon Pilgrim 
6435dc4e7c2SSimon Pilgrim   uint64_t Index = IsConst0 ? Index1 : Index0;
6445dc4e7c2SSimon Pilgrim   Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType();
6450d2a0b44SSanjay Patel   Type *VecTy = I.getType();
6465dc4e7c2SSimon Pilgrim   assert(VecTy->isVectorTy() &&
6475dc4e7c2SSimon Pilgrim          (IsConst0 || IsConst1 || V0->getType() == V1->getType()) &&
648741e20f3SSanjay Patel          (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
649741e20f3SSanjay Patel           ScalarTy->isPointerTy()) &&
650741e20f3SSanjay Patel          "Unexpected types for insert element into binop or cmp");
6510d2a0b44SSanjay Patel 
652ed67f5e7SSanjay Patel   unsigned Opcode = I.getOpcode();
65336710c38SCaroline Concatto   InstructionCost ScalarOpCost, VectorOpCost;
654ed67f5e7SSanjay Patel   if (IsCmp) {
6550dcd2b40SSimon Pilgrim     CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
6560dcd2b40SSimon Pilgrim     ScalarOpCost = TTI.getCmpSelInstrCost(
6570dcd2b40SSimon Pilgrim         Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred);
6580dcd2b40SSimon Pilgrim     VectorOpCost = TTI.getCmpSelInstrCost(
6590dcd2b40SSimon Pilgrim         Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred);
660ed67f5e7SSanjay Patel   } else {
661ed67f5e7SSanjay Patel     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
662ed67f5e7SSanjay Patel     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
663ed67f5e7SSanjay Patel   }
6640d2a0b44SSanjay Patel 
6650d2a0b44SSanjay Patel   // Get cost estimate for the insert element. This cost will factor into
6660d2a0b44SSanjay Patel   // both sequences.
66736710c38SCaroline Concatto   InstructionCost InsertCost =
6680d2a0b44SSanjay Patel       TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, Index);
66936710c38SCaroline Concatto   InstructionCost OldCost =
67036710c38SCaroline Concatto       (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) + VectorOpCost;
67136710c38SCaroline Concatto   InstructionCost NewCost = ScalarOpCost + InsertCost +
6725dc4e7c2SSimon Pilgrim                             (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) +
6735dc4e7c2SSimon Pilgrim                             (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost);
6740d2a0b44SSanjay Patel 
6750d2a0b44SSanjay Patel   // We want to scalarize unless the vector variant actually has lower cost.
67636710c38SCaroline Concatto   if (OldCost < NewCost || !NewCost.isValid())
6770d2a0b44SSanjay Patel     return false;
6780d2a0b44SSanjay Patel 
679ed67f5e7SSanjay Patel   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
680ed67f5e7SSanjay Patel   // inselt NewVecC, (scalar_op V0, V1), Index
681ed67f5e7SSanjay Patel   if (IsCmp)
682ed67f5e7SSanjay Patel     ++NumScalarCmp;
683ed67f5e7SSanjay Patel   else
6840d2a0b44SSanjay Patel     ++NumScalarBO;
6855dc4e7c2SSimon Pilgrim 
6865dc4e7c2SSimon Pilgrim   // For constant cases, extract the scalar element, this should constant fold.
6875dc4e7c2SSimon Pilgrim   if (IsConst0)
6885dc4e7c2SSimon Pilgrim     V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index));
6895dc4e7c2SSimon Pilgrim   if (IsConst1)
6905dc4e7c2SSimon Pilgrim     V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index));
6915dc4e7c2SSimon Pilgrim 
692ed67f5e7SSanjay Patel   Value *Scalar =
69346a285adSSanjay Patel       IsCmp ? Builder.CreateCmp(Pred, V0, V1)
694ed67f5e7SSanjay Patel             : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1);
695ed67f5e7SSanjay Patel 
696ed67f5e7SSanjay Patel   Scalar->setName(I.getName() + ".scalar");
6970d2a0b44SSanjay Patel 
6980d2a0b44SSanjay Patel   // All IR flags are safe to back-propagate. There is no potential for extra
6990d2a0b44SSanjay Patel   // poison to be created by the scalar instruction.
7000d2a0b44SSanjay Patel   if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
7010d2a0b44SSanjay Patel     ScalarInst->copyIRFlags(&I);
7020d2a0b44SSanjay Patel 
7030d2a0b44SSanjay Patel   // Fold the vector constants in the original vectors into a new base vector.
704bdba8278SNikita Popov   Value *NewVecC =
705bdba8278SNikita Popov       IsCmp ? Builder.CreateCmp(Pred, VecC0, VecC1)
706bdba8278SNikita Popov             : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, VecC0, VecC1);
7070d2a0b44SSanjay Patel   Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
70898c2f4eeSSanjay Patel   replaceValue(I, *Insert);
7090d2a0b44SSanjay Patel   return true;
7100d2a0b44SSanjay Patel }
7110d2a0b44SSanjay Patel 
712b6315aeeSSanjay Patel /// Try to combine a scalar binop + 2 scalar compares of extracted elements of
713b6315aeeSSanjay Patel /// a vector into vector operations followed by extract. Note: The SLP pass
714b6315aeeSSanjay Patel /// may miss this pattern because of implementation problems.
foldExtractedCmps(Instruction & I)715b6315aeeSSanjay Patel bool VectorCombine::foldExtractedCmps(Instruction &I) {
716b6315aeeSSanjay Patel   // We are looking for a scalar binop of booleans.
717b6315aeeSSanjay Patel   // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1)
718b6315aeeSSanjay Patel   if (!I.isBinaryOp() || !I.getType()->isIntegerTy(1))
719b6315aeeSSanjay Patel     return false;
720b6315aeeSSanjay Patel 
721b6315aeeSSanjay Patel   // The compare predicates should match, and each compare should have a
722b6315aeeSSanjay Patel   // constant operand.
723b6315aeeSSanjay Patel   // TODO: Relax the one-use constraints.
724b6315aeeSSanjay Patel   Value *B0 = I.getOperand(0), *B1 = I.getOperand(1);
725b6315aeeSSanjay Patel   Instruction *I0, *I1;
726b6315aeeSSanjay Patel   Constant *C0, *C1;
727b6315aeeSSanjay Patel   CmpInst::Predicate P0, P1;
728b6315aeeSSanjay Patel   if (!match(B0, m_OneUse(m_Cmp(P0, m_Instruction(I0), m_Constant(C0)))) ||
729b6315aeeSSanjay Patel       !match(B1, m_OneUse(m_Cmp(P1, m_Instruction(I1), m_Constant(C1)))) ||
730b6315aeeSSanjay Patel       P0 != P1)
731b6315aeeSSanjay Patel     return false;
732b6315aeeSSanjay Patel 
733b6315aeeSSanjay Patel   // The compare operands must be extracts of the same vector with constant
734b6315aeeSSanjay Patel   // extract indexes.
735b6315aeeSSanjay Patel   // TODO: Relax the one-use constraints.
736b6315aeeSSanjay Patel   Value *X;
737b6315aeeSSanjay Patel   uint64_t Index0, Index1;
738b6315aeeSSanjay Patel   if (!match(I0, m_OneUse(m_ExtractElt(m_Value(X), m_ConstantInt(Index0)))) ||
739b6315aeeSSanjay Patel       !match(I1, m_OneUse(m_ExtractElt(m_Specific(X), m_ConstantInt(Index1)))))
740b6315aeeSSanjay Patel     return false;
741b6315aeeSSanjay Patel 
742b6315aeeSSanjay Patel   auto *Ext0 = cast<ExtractElementInst>(I0);
743b6315aeeSSanjay Patel   auto *Ext1 = cast<ExtractElementInst>(I1);
744b6315aeeSSanjay Patel   ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1);
745b6315aeeSSanjay Patel   if (!ConvertToShuf)
746b6315aeeSSanjay Patel     return false;
747b6315aeeSSanjay Patel 
748b6315aeeSSanjay Patel   // The original scalar pattern is:
749b6315aeeSSanjay Patel   // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1)
750b6315aeeSSanjay Patel   CmpInst::Predicate Pred = P0;
751b6315aeeSSanjay Patel   unsigned CmpOpcode = CmpInst::isFPPredicate(Pred) ? Instruction::FCmp
752b6315aeeSSanjay Patel                                                     : Instruction::ICmp;
753b6315aeeSSanjay Patel   auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
754b6315aeeSSanjay Patel   if (!VecTy)
755b6315aeeSSanjay Patel     return false;
756b6315aeeSSanjay Patel 
75736710c38SCaroline Concatto   InstructionCost OldCost =
75836710c38SCaroline Concatto       TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
759b6315aeeSSanjay Patel   OldCost += TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
7600dcd2b40SSimon Pilgrim   OldCost +=
7610dcd2b40SSimon Pilgrim       TTI.getCmpSelInstrCost(CmpOpcode, I0->getType(),
7620dcd2b40SSimon Pilgrim                              CmpInst::makeCmpResultType(I0->getType()), Pred) *
7630dcd2b40SSimon Pilgrim       2;
764b6315aeeSSanjay Patel   OldCost += TTI.getArithmeticInstrCost(I.getOpcode(), I.getType());
765b6315aeeSSanjay Patel 
766b6315aeeSSanjay Patel   // The proposed vector pattern is:
767b6315aeeSSanjay Patel   // vcmp = cmp Pred X, VecC
768b6315aeeSSanjay Patel   // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0
769b6315aeeSSanjay Patel   int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0;
770b6315aeeSSanjay Patel   int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1;
771b6315aeeSSanjay Patel   auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType()));
7720dcd2b40SSimon Pilgrim   InstructionCost NewCost = TTI.getCmpSelInstrCost(
7730dcd2b40SSimon Pilgrim       CmpOpcode, X->getType(), CmpInst::makeCmpResultType(X->getType()), Pred);
774e2935dcfSDavid Green   SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem);
775e2935dcfSDavid Green   ShufMask[CheapIndex] = ExpensiveIndex;
776e2935dcfSDavid Green   NewCost += TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, CmpTy,
777e2935dcfSDavid Green                                 ShufMask);
778b6315aeeSSanjay Patel   NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy);
779b6315aeeSSanjay Patel   NewCost += TTI.getVectorInstrCost(Ext0->getOpcode(), CmpTy, CheapIndex);
780b6315aeeSSanjay Patel 
781b6315aeeSSanjay Patel   // Aggressively form vector ops if the cost is equal because the transform
782b6315aeeSSanjay Patel   // may enable further optimization.
783b6315aeeSSanjay Patel   // Codegen can reverse this transform (scalarize) if it was not profitable.
78436710c38SCaroline Concatto   if (OldCost < NewCost || !NewCost.isValid())
785b6315aeeSSanjay Patel     return false;
786b6315aeeSSanjay Patel 
787b6315aeeSSanjay Patel   // Create a vector constant from the 2 scalar constants.
788b6315aeeSSanjay Patel   SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(),
789b6315aeeSSanjay Patel                                    UndefValue::get(VecTy->getElementType()));
790b6315aeeSSanjay Patel   CmpC[Index0] = C0;
791b6315aeeSSanjay Patel   CmpC[Index1] = C1;
792b6315aeeSSanjay Patel   Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC));
793b6315aeeSSanjay Patel 
794b6315aeeSSanjay Patel   Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder);
795b6315aeeSSanjay Patel   Value *VecLogic = Builder.CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
796b6315aeeSSanjay Patel                                         VCmp, Shuf);
797b6315aeeSSanjay Patel   Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex);
798b6315aeeSSanjay Patel   replaceValue(I, *NewExt);
799b6315aeeSSanjay Patel   ++NumVecCmpBO;
800b6315aeeSSanjay Patel   return true;
801b6315aeeSSanjay Patel }
802b6315aeeSSanjay Patel 
8032db4979cSQiu Chaofan // Check if memory loc modified between two instrs in the same BB
isMemModifiedBetween(BasicBlock::iterator Begin,BasicBlock::iterator End,const MemoryLocation & Loc,AAResults & AA)8042db4979cSQiu Chaofan static bool isMemModifiedBetween(BasicBlock::iterator Begin,
8052db4979cSQiu Chaofan                                  BasicBlock::iterator End,
8062db4979cSQiu Chaofan                                  const MemoryLocation &Loc, AAResults &AA) {
8072db4979cSQiu Chaofan   unsigned NumScanned = 0;
8082db4979cSQiu Chaofan   return std::any_of(Begin, End, [&](const Instruction &Instr) {
8092db4979cSQiu Chaofan     return isModSet(AA.getModRefInfo(&Instr, Loc)) ||
8102db4979cSQiu Chaofan            ++NumScanned > MaxInstrsToScan;
8112db4979cSQiu Chaofan   });
8122db4979cSQiu Chaofan }
8132db4979cSQiu Chaofan 
814c24fc37eSFlorian Hahn /// Helper class to indicate whether a vector index can be safely scalarized and
815c24fc37eSFlorian Hahn /// if a freeze needs to be inserted.
816c24fc37eSFlorian Hahn class ScalarizationResult {
817c24fc37eSFlorian Hahn   enum class StatusTy { Unsafe, Safe, SafeWithFreeze };
818c24fc37eSFlorian Hahn 
819c24fc37eSFlorian Hahn   StatusTy Status;
820c24fc37eSFlorian Hahn   Value *ToFreeze;
821c24fc37eSFlorian Hahn 
ScalarizationResult(StatusTy Status,Value * ToFreeze=nullptr)822c24fc37eSFlorian Hahn   ScalarizationResult(StatusTy Status, Value *ToFreeze = nullptr)
823c24fc37eSFlorian Hahn       : Status(Status), ToFreeze(ToFreeze) {}
824c24fc37eSFlorian Hahn 
825c24fc37eSFlorian Hahn public:
826c24fc37eSFlorian Hahn   ScalarizationResult(const ScalarizationResult &Other) = default;
~ScalarizationResult()827c24fc37eSFlorian Hahn   ~ScalarizationResult() {
828c24fc37eSFlorian Hahn     assert(!ToFreeze && "freeze() not called with ToFreeze being set");
829c24fc37eSFlorian Hahn   }
830c24fc37eSFlorian Hahn 
unsafe()831c24fc37eSFlorian Hahn   static ScalarizationResult unsafe() { return {StatusTy::Unsafe}; }
safe()832c24fc37eSFlorian Hahn   static ScalarizationResult safe() { return {StatusTy::Safe}; }
safeWithFreeze(Value * ToFreeze)833c24fc37eSFlorian Hahn   static ScalarizationResult safeWithFreeze(Value *ToFreeze) {
834c24fc37eSFlorian Hahn     return {StatusTy::SafeWithFreeze, ToFreeze};
835c24fc37eSFlorian Hahn   }
836c24fc37eSFlorian Hahn 
837c24fc37eSFlorian Hahn   /// Returns true if the index can be scalarize without requiring a freeze.
isSafe() const838c24fc37eSFlorian Hahn   bool isSafe() const { return Status == StatusTy::Safe; }
839c24fc37eSFlorian Hahn   /// Returns true if the index cannot be scalarized.
isUnsafe() const840c24fc37eSFlorian Hahn   bool isUnsafe() const { return Status == StatusTy::Unsafe; }
841c24fc37eSFlorian Hahn   /// Returns true if the index can be scalarize, but requires inserting a
842c24fc37eSFlorian Hahn   /// freeze.
isSafeWithFreeze() const843c24fc37eSFlorian Hahn   bool isSafeWithFreeze() const { return Status == StatusTy::SafeWithFreeze; }
844c24fc37eSFlorian Hahn 
845e2f6290eSFlorian Hahn   /// Reset the state of Unsafe and clear ToFreze if set.
discard()846e2f6290eSFlorian Hahn   void discard() {
847e2f6290eSFlorian Hahn     ToFreeze = nullptr;
848e2f6290eSFlorian Hahn     Status = StatusTy::Unsafe;
849e2f6290eSFlorian Hahn   }
850e2f6290eSFlorian Hahn 
851c24fc37eSFlorian Hahn   /// Freeze the ToFreeze and update the use in \p User to use it.
freeze(IRBuilder<> & Builder,Instruction & UserI)852c24fc37eSFlorian Hahn   void freeze(IRBuilder<> &Builder, Instruction &UserI) {
853c24fc37eSFlorian Hahn     assert(isSafeWithFreeze() &&
854c24fc37eSFlorian Hahn            "should only be used when freezing is required");
855c24fc37eSFlorian Hahn     assert(is_contained(ToFreeze->users(), &UserI) &&
856c24fc37eSFlorian Hahn            "UserI must be a user of ToFreeze");
857c24fc37eSFlorian Hahn     IRBuilder<>::InsertPointGuard Guard(Builder);
858c24fc37eSFlorian Hahn     Builder.SetInsertPoint(cast<Instruction>(&UserI));
859c24fc37eSFlorian Hahn     Value *Frozen =
860c24fc37eSFlorian Hahn         Builder.CreateFreeze(ToFreeze, ToFreeze->getName() + ".frozen");
861c24fc37eSFlorian Hahn     for (Use &U : make_early_inc_range((UserI.operands())))
862c24fc37eSFlorian Hahn       if (U.get() == ToFreeze)
863c24fc37eSFlorian Hahn         U.set(Frozen);
864c24fc37eSFlorian Hahn 
865c24fc37eSFlorian Hahn     ToFreeze = nullptr;
866c24fc37eSFlorian Hahn   }
867c24fc37eSFlorian Hahn };
868c24fc37eSFlorian Hahn 
8694e8c28b6SFlorian Hahn /// Check if it is legal to scalarize a memory access to \p VecTy at index \p
8704e8c28b6SFlorian Hahn /// Idx. \p Idx must access a valid vector element.
canScalarizeAccess(FixedVectorType * VecTy,Value * Idx,Instruction * CtxI,AssumptionCache & AC,const DominatorTree & DT)871c24fc37eSFlorian Hahn static ScalarizationResult canScalarizeAccess(FixedVectorType *VecTy,
872c24fc37eSFlorian Hahn                                               Value *Idx, Instruction *CtxI,
8735131037eSFlorian Hahn                                               AssumptionCache &AC,
8745131037eSFlorian Hahn                                               const DominatorTree &DT) {
875c24fc37eSFlorian Hahn   if (auto *C = dyn_cast<ConstantInt>(Idx)) {
876c24fc37eSFlorian Hahn     if (C->getValue().ult(VecTy->getNumElements()))
877c24fc37eSFlorian Hahn       return ScalarizationResult::safe();
878c24fc37eSFlorian Hahn     return ScalarizationResult::unsafe();
879c24fc37eSFlorian Hahn   }
880575e2affSFlorian Hahn 
881c24fc37eSFlorian Hahn   unsigned IntWidth = Idx->getType()->getScalarSizeInBits();
882c24fc37eSFlorian Hahn   APInt Zero(IntWidth, 0);
883c24fc37eSFlorian Hahn   APInt MaxElts(IntWidth, VecTy->getNumElements());
884575e2affSFlorian Hahn   ConstantRange ValidIndices(Zero, MaxElts);
885c24fc37eSFlorian Hahn   ConstantRange IdxRange(IntWidth, true);
886c24fc37eSFlorian Hahn 
887c24fc37eSFlorian Hahn   if (isGuaranteedNotToBePoison(Idx, &AC)) {
8880edf9995SSanjay Patel     if (ValidIndices.contains(computeConstantRange(Idx, /* ForSigned */ false,
8890edf9995SSanjay Patel                                                    true, &AC, CtxI, &DT)))
890c24fc37eSFlorian Hahn       return ScalarizationResult::safe();
891c24fc37eSFlorian Hahn     return ScalarizationResult::unsafe();
892c24fc37eSFlorian Hahn   }
893c24fc37eSFlorian Hahn 
894c24fc37eSFlorian Hahn   // If the index may be poison, check if we can insert a freeze before the
895c24fc37eSFlorian Hahn   // range of the index is restricted.
896c24fc37eSFlorian Hahn   Value *IdxBase;
897c24fc37eSFlorian Hahn   ConstantInt *CI;
898c24fc37eSFlorian Hahn   if (match(Idx, m_And(m_Value(IdxBase), m_ConstantInt(CI)))) {
899c24fc37eSFlorian Hahn     IdxRange = IdxRange.binaryAnd(CI->getValue());
900c24fc37eSFlorian Hahn   } else if (match(Idx, m_URem(m_Value(IdxBase), m_ConstantInt(CI)))) {
901c24fc37eSFlorian Hahn     IdxRange = IdxRange.urem(CI->getValue());
902c24fc37eSFlorian Hahn   }
903c24fc37eSFlorian Hahn 
904c24fc37eSFlorian Hahn   if (ValidIndices.contains(IdxRange))
905c24fc37eSFlorian Hahn     return ScalarizationResult::safeWithFreeze(IdxBase);
906c24fc37eSFlorian Hahn   return ScalarizationResult::unsafe();
9074e8c28b6SFlorian Hahn }
9084e8c28b6SFlorian Hahn 
909abc0e012SRoman Lebedev /// The memory operation on a vector of \p ScalarType had alignment of
910abc0e012SRoman Lebedev /// \p VectorAlignment. Compute the maximal, but conservatively correct,
911abc0e012SRoman Lebedev /// alignment that will be valid for the memory operation on a single scalar
912abc0e012SRoman Lebedev /// element of the same type with index \p Idx.
computeAlignmentAfterScalarization(Align VectorAlignment,Type * ScalarType,Value * Idx,const DataLayout & DL)913abc0e012SRoman Lebedev static Align computeAlignmentAfterScalarization(Align VectorAlignment,
914abc0e012SRoman Lebedev                                                 Type *ScalarType, Value *Idx,
915abc0e012SRoman Lebedev                                                 const DataLayout &DL) {
916abc0e012SRoman Lebedev   if (auto *C = dyn_cast<ConstantInt>(Idx))
917abc0e012SRoman Lebedev     return commonAlignment(VectorAlignment,
918abc0e012SRoman Lebedev                            C->getZExtValue() * DL.getTypeStoreSize(ScalarType));
919abc0e012SRoman Lebedev   return commonAlignment(VectorAlignment, DL.getTypeStoreSize(ScalarType));
920abc0e012SRoman Lebedev }
921abc0e012SRoman Lebedev 
9222db4979cSQiu Chaofan // Combine patterns like:
9232db4979cSQiu Chaofan //   %0 = load <4 x i32>, <4 x i32>* %a
9242db4979cSQiu Chaofan //   %1 = insertelement <4 x i32> %0, i32 %b, i32 1
9252db4979cSQiu Chaofan //   store <4 x i32> %1, <4 x i32>* %a
9262db4979cSQiu Chaofan // to:
9272db4979cSQiu Chaofan //   %0 = bitcast <4 x i32>* %a to i32*
9282db4979cSQiu Chaofan //   %1 = getelementptr inbounds i32, i32* %0, i64 0, i64 1
9292db4979cSQiu Chaofan //   store i32 %b, i32* %1
foldSingleElementStore(Instruction & I)9302db4979cSQiu Chaofan bool VectorCombine::foldSingleElementStore(Instruction &I) {
9312db4979cSQiu Chaofan   StoreInst *SI = dyn_cast<StoreInst>(&I);
9326d2df181SQiu Chaofan   if (!SI || !SI->isSimple() ||
9336d2df181SQiu Chaofan       !isa<FixedVectorType>(SI->getValueOperand()->getType()))
9342db4979cSQiu Chaofan     return false;
9352db4979cSQiu Chaofan 
9362db4979cSQiu Chaofan   // TODO: Combine more complicated patterns (multiple insert) by referencing
9372db4979cSQiu Chaofan   // TargetTransformInfo.
9382db4979cSQiu Chaofan   Instruction *Source;
9396d2df181SQiu Chaofan   Value *NewElement;
940575e2affSFlorian Hahn   Value *Idx;
9412db4979cSQiu Chaofan   if (!match(SI->getValueOperand(),
9422db4979cSQiu Chaofan              m_InsertElt(m_Instruction(Source), m_Value(NewElement),
943575e2affSFlorian Hahn                          m_Value(Idx))))
9442db4979cSQiu Chaofan     return false;
9452db4979cSQiu Chaofan 
9462db4979cSQiu Chaofan   if (auto *Load = dyn_cast<LoadInst>(Source)) {
9476d2df181SQiu Chaofan     auto VecTy = cast<FixedVectorType>(SI->getValueOperand()->getType());
9482db4979cSQiu Chaofan     const DataLayout &DL = I.getModule()->getDataLayout();
9492db4979cSQiu Chaofan     Value *SrcAddr = Load->getPointerOperand()->stripPointerCasts();
9506d2df181SQiu Chaofan     // Don't optimize for atomic/volatile load or store. Ensure memory is not
9516d2df181SQiu Chaofan     // modified between, vector type matches store size, and index is inbounds.
9522db4979cSQiu Chaofan     if (!Load->isSimple() || Load->getParent() != SI->getParent() ||
9532db4979cSQiu Chaofan         !DL.typeSizeEqualsStoreSize(Load->getType()) ||
954c24fc37eSFlorian Hahn         SrcAddr != SI->getPointerOperand()->stripPointerCasts())
955c24fc37eSFlorian Hahn       return false;
956c24fc37eSFlorian Hahn 
9575131037eSFlorian Hahn     auto ScalarizableIdx = canScalarizeAccess(VecTy, Idx, Load, AC, DT);
958c24fc37eSFlorian Hahn     if (ScalarizableIdx.isUnsafe() ||
9592db4979cSQiu Chaofan         isMemModifiedBetween(Load->getIterator(), SI->getIterator(),
9602db4979cSQiu Chaofan                              MemoryLocation::get(SI), AA))
9612db4979cSQiu Chaofan       return false;
9622db4979cSQiu Chaofan 
963c24fc37eSFlorian Hahn     if (ScalarizableIdx.isSafeWithFreeze())
964c24fc37eSFlorian Hahn       ScalarizableIdx.freeze(Builder, *cast<Instruction>(Idx));
965a213f735SNikita Popov     Value *GEP = Builder.CreateInBoundsGEP(
966a213f735SNikita Popov         SI->getValueOperand()->getType(), SI->getPointerOperand(),
967a213f735SNikita Popov         {ConstantInt::get(Idx->getType(), 0), Idx});
9682db4979cSQiu Chaofan     StoreInst *NSI = Builder.CreateStore(NewElement, GEP);
9692db4979cSQiu Chaofan     NSI->copyMetadata(*SI);
970abc0e012SRoman Lebedev     Align ScalarOpAlignment = computeAlignmentAfterScalarization(
971abc0e012SRoman Lebedev         std::max(SI->getAlign(), Load->getAlign()), NewElement->getType(), Idx,
972abc0e012SRoman Lebedev         DL);
973abc0e012SRoman Lebedev     NSI->setAlignment(ScalarOpAlignment);
9742db4979cSQiu Chaofan     replaceValue(I, *NSI);
975300870a9SFlorian Hahn     eraseInstruction(I);
9762db4979cSQiu Chaofan     return true;
9772db4979cSQiu Chaofan   }
9782db4979cSQiu Chaofan 
9792db4979cSQiu Chaofan   return false;
9802db4979cSQiu Chaofan }
9812db4979cSQiu Chaofan 
9824e8c28b6SFlorian Hahn /// Try to scalarize vector loads feeding extractelement instructions.
scalarizeLoadExtract(Instruction & I)9834e8c28b6SFlorian Hahn bool VectorCombine::scalarizeLoadExtract(Instruction &I) {
9844e8c28b6SFlorian Hahn   Value *Ptr;
985300870a9SFlorian Hahn   if (!match(&I, m_Load(m_Value(Ptr))))
9864e8c28b6SFlorian Hahn     return false;
9874e8c28b6SFlorian Hahn 
988300870a9SFlorian Hahn   auto *LI = cast<LoadInst>(&I);
9894e8c28b6SFlorian Hahn   const DataLayout &DL = I.getModule()->getDataLayout();
9904e8c28b6SFlorian Hahn   if (LI->isVolatile() || !DL.typeSizeEqualsStoreSize(LI->getType()))
9914e8c28b6SFlorian Hahn     return false;
9924e8c28b6SFlorian Hahn 
9934e8c28b6SFlorian Hahn   auto *FixedVT = dyn_cast<FixedVectorType>(LI->getType());
9944e8c28b6SFlorian Hahn   if (!FixedVT)
9954e8c28b6SFlorian Hahn     return false;
9964e8c28b6SFlorian Hahn 
9975a81a603SArthur Eubanks   InstructionCost OriginalCost =
9985a81a603SArthur Eubanks       TTI.getMemoryOpCost(Instruction::Load, LI->getType(), LI->getAlign(),
9994e8c28b6SFlorian Hahn                           LI->getPointerAddressSpace());
10004e8c28b6SFlorian Hahn   InstructionCost ScalarizedCost = 0;
10014e8c28b6SFlorian Hahn 
10024e8c28b6SFlorian Hahn   Instruction *LastCheckedInst = LI;
10034e8c28b6SFlorian Hahn   unsigned NumInstChecked = 0;
10044e8c28b6SFlorian Hahn   // Check if all users of the load are extracts with no memory modifications
10054e8c28b6SFlorian Hahn   // between the load and the extract. Compute the cost of both the original
10064e8c28b6SFlorian Hahn   // code and the scalarized version.
10074e8c28b6SFlorian Hahn   for (User *U : LI->users()) {
10084e8c28b6SFlorian Hahn     auto *UI = dyn_cast<ExtractElementInst>(U);
10094e8c28b6SFlorian Hahn     if (!UI || UI->getParent() != LI->getParent())
10104e8c28b6SFlorian Hahn       return false;
10114e8c28b6SFlorian Hahn 
101296ca0349SFlorian Hahn     if (!isGuaranteedNotToBePoison(UI->getOperand(1), &AC, LI, &DT))
101396ca0349SFlorian Hahn       return false;
101496ca0349SFlorian Hahn 
10154e8c28b6SFlorian Hahn     // Check if any instruction between the load and the extract may modify
10164e8c28b6SFlorian Hahn     // memory.
10174e8c28b6SFlorian Hahn     if (LastCheckedInst->comesBefore(UI)) {
10184e8c28b6SFlorian Hahn       for (Instruction &I :
10194e8c28b6SFlorian Hahn            make_range(std::next(LI->getIterator()), UI->getIterator())) {
10204e8c28b6SFlorian Hahn         // Bail out if we reached the check limit or the instruction may write
10214e8c28b6SFlorian Hahn         // to memory.
10224e8c28b6SFlorian Hahn         if (NumInstChecked == MaxInstrsToScan || I.mayWriteToMemory())
10234e8c28b6SFlorian Hahn           return false;
10244e8c28b6SFlorian Hahn         NumInstChecked++;
10254e8c28b6SFlorian Hahn       }
1026c141d158SFlorian Hahn       LastCheckedInst = UI;
10274e8c28b6SFlorian Hahn     }
10284e8c28b6SFlorian Hahn 
10295131037eSFlorian Hahn     auto ScalarIdx = canScalarizeAccess(FixedVT, UI->getOperand(1), &I, AC, DT);
1030c24fc37eSFlorian Hahn     if (!ScalarIdx.isSafe()) {
1031c24fc37eSFlorian Hahn       // TODO: Freeze index if it is safe to do so.
1032e2f6290eSFlorian Hahn       ScalarIdx.discard();
1033007f268cSFlorian Hahn       return false;
1034c24fc37eSFlorian Hahn     }
1035007f268cSFlorian Hahn 
10364e8c28b6SFlorian Hahn     auto *Index = dyn_cast<ConstantInt>(UI->getOperand(1));
10374e8c28b6SFlorian Hahn     OriginalCost +=
10384e8c28b6SFlorian Hahn         TTI.getVectorInstrCost(Instruction::ExtractElement, LI->getType(),
10394e8c28b6SFlorian Hahn                                Index ? Index->getZExtValue() : -1);
10404e8c28b6SFlorian Hahn     ScalarizedCost +=
10414e8c28b6SFlorian Hahn         TTI.getMemoryOpCost(Instruction::Load, FixedVT->getElementType(),
10424e8c28b6SFlorian Hahn                             Align(1), LI->getPointerAddressSpace());
10434e8c28b6SFlorian Hahn     ScalarizedCost += TTI.getAddressComputationCost(FixedVT->getElementType());
10444e8c28b6SFlorian Hahn   }
10454e8c28b6SFlorian Hahn 
10464e8c28b6SFlorian Hahn   if (ScalarizedCost >= OriginalCost)
10474e8c28b6SFlorian Hahn     return false;
10484e8c28b6SFlorian Hahn 
10494e8c28b6SFlorian Hahn   // Replace extracts with narrow scalar loads.
10504e8c28b6SFlorian Hahn   for (User *U : LI->users()) {
10514e8c28b6SFlorian Hahn     auto *EI = cast<ExtractElementInst>(U);
10524e8c28b6SFlorian Hahn     Builder.SetInsertPoint(EI);
1053d4c070d8SFlorian Hahn 
1054d4c070d8SFlorian Hahn     Value *Idx = EI->getOperand(1);
1055d4c070d8SFlorian Hahn     Value *GEP =
1056d4c070d8SFlorian Hahn         Builder.CreateInBoundsGEP(FixedVT, Ptr, {Builder.getInt32(0), Idx});
10574e8c28b6SFlorian Hahn     auto *NewLoad = cast<LoadInst>(Builder.CreateLoad(
10584e8c28b6SFlorian Hahn         FixedVT->getElementType(), GEP, EI->getName() + ".scalar"));
10594e8c28b6SFlorian Hahn 
106020542b47SRoman Lebedev     Align ScalarOpAlignment = computeAlignmentAfterScalarization(
106120542b47SRoman Lebedev         LI->getAlign(), FixedVT->getElementType(), Idx, DL);
106220542b47SRoman Lebedev     NewLoad->setAlignment(ScalarOpAlignment);
106320542b47SRoman Lebedev 
10644e8c28b6SFlorian Hahn     replaceValue(*EI, *NewLoad);
10654e8c28b6SFlorian Hahn   }
10664e8c28b6SFlorian Hahn 
10674e8c28b6SFlorian Hahn   return true;
10684e8c28b6SFlorian Hahn }
10694e8c28b6SFlorian Hahn 
107066d22b4dSSanjay Patel /// Try to convert "shuffle (binop), (binop)" with a shared binop operand into
107166d22b4dSSanjay Patel /// "binop (shuffle), (shuffle)".
foldShuffleOfBinops(Instruction & I)107266d22b4dSSanjay Patel bool VectorCombine::foldShuffleOfBinops(Instruction &I) {
107366d22b4dSSanjay Patel   auto *VecTy = dyn_cast<FixedVectorType>(I.getType());
107466d22b4dSSanjay Patel   if (!VecTy)
107566d22b4dSSanjay Patel     return false;
107666d22b4dSSanjay Patel 
107766d22b4dSSanjay Patel   BinaryOperator *B0, *B1;
107866d22b4dSSanjay Patel   ArrayRef<int> Mask;
107966d22b4dSSanjay Patel   if (!match(&I, m_Shuffle(m_OneUse(m_BinOp(B0)), m_OneUse(m_BinOp(B1)),
108066d22b4dSSanjay Patel                            m_Mask(Mask))) ||
108166d22b4dSSanjay Patel       B0->getOpcode() != B1->getOpcode() || B0->getType() != VecTy)
108266d22b4dSSanjay Patel     return false;
108366d22b4dSSanjay Patel 
108466d22b4dSSanjay Patel   // Try to replace a binop with a shuffle if the shuffle is not costly.
108566d22b4dSSanjay Patel   // The new shuffle will choose from a single, common operand, so it may be
108666d22b4dSSanjay Patel   // cheaper than the existing two-operand shuffle.
108766d22b4dSSanjay Patel   SmallVector<int> UnaryMask = createUnaryMask(Mask, Mask.size());
108866d22b4dSSanjay Patel   Instruction::BinaryOps Opcode = B0->getOpcode();
108966d22b4dSSanjay Patel   InstructionCost BinopCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
109066d22b4dSSanjay Patel   InstructionCost ShufCost = TTI.getShuffleCost(
109166d22b4dSSanjay Patel       TargetTransformInfo::SK_PermuteSingleSrc, VecTy, UnaryMask);
109266d22b4dSSanjay Patel   if (ShufCost > BinopCost)
109366d22b4dSSanjay Patel     return false;
109466d22b4dSSanjay Patel 
109566d22b4dSSanjay Patel   // If we have something like "add X, Y" and "add Z, X", swap ops to match.
109666d22b4dSSanjay Patel   Value *X = B0->getOperand(0), *Y = B0->getOperand(1);
109766d22b4dSSanjay Patel   Value *Z = B1->getOperand(0), *W = B1->getOperand(1);
109866d22b4dSSanjay Patel   if (BinaryOperator::isCommutative(Opcode) && X != Z && Y != W)
109966d22b4dSSanjay Patel     std::swap(X, Y);
110066d22b4dSSanjay Patel 
110166d22b4dSSanjay Patel   Value *Shuf0, *Shuf1;
110266d22b4dSSanjay Patel   if (X == Z) {
110366d22b4dSSanjay Patel     // shuf (bo X, Y), (bo X, W) --> bo (shuf X), (shuf Y, W)
110466d22b4dSSanjay Patel     Shuf0 = Builder.CreateShuffleVector(X, UnaryMask);
110566d22b4dSSanjay Patel     Shuf1 = Builder.CreateShuffleVector(Y, W, Mask);
110666d22b4dSSanjay Patel   } else if (Y == W) {
110766d22b4dSSanjay Patel     // shuf (bo X, Y), (bo Z, Y) --> bo (shuf X, Z), (shuf Y)
110866d22b4dSSanjay Patel     Shuf0 = Builder.CreateShuffleVector(X, Z, Mask);
110966d22b4dSSanjay Patel     Shuf1 = Builder.CreateShuffleVector(Y, UnaryMask);
111066d22b4dSSanjay Patel   } else {
111166d22b4dSSanjay Patel     return false;
111266d22b4dSSanjay Patel   }
111366d22b4dSSanjay Patel 
111466d22b4dSSanjay Patel   Value *NewBO = Builder.CreateBinOp(Opcode, Shuf0, Shuf1);
111566d22b4dSSanjay Patel   // Intersect flags from the old binops.
111666d22b4dSSanjay Patel   if (auto *NewInst = dyn_cast<Instruction>(NewBO)) {
111766d22b4dSSanjay Patel     NewInst->copyIRFlags(B0);
111866d22b4dSSanjay Patel     NewInst->andIRFlags(B1);
111966d22b4dSSanjay Patel   }
112066d22b4dSSanjay Patel   replaceValue(I, *NewBO);
112166d22b4dSSanjay Patel   return true;
112266d22b4dSSanjay Patel }
112366d22b4dSSanjay Patel 
1124ded8187eSDavid Green /// Given a commutative reduction, the order of the input lanes does not alter
1125ded8187eSDavid Green /// the results. We can use this to remove certain shuffles feeding the
1126ded8187eSDavid Green /// reduction, removing the need to shuffle at all.
foldShuffleFromReductions(Instruction & I)1127ded8187eSDavid Green bool VectorCombine::foldShuffleFromReductions(Instruction &I) {
1128ded8187eSDavid Green   auto *II = dyn_cast<IntrinsicInst>(&I);
1129ded8187eSDavid Green   if (!II)
1130ded8187eSDavid Green     return false;
1131ded8187eSDavid Green   switch (II->getIntrinsicID()) {
1132ded8187eSDavid Green   case Intrinsic::vector_reduce_add:
1133ded8187eSDavid Green   case Intrinsic::vector_reduce_mul:
1134ded8187eSDavid Green   case Intrinsic::vector_reduce_and:
1135ded8187eSDavid Green   case Intrinsic::vector_reduce_or:
1136ded8187eSDavid Green   case Intrinsic::vector_reduce_xor:
1137ded8187eSDavid Green   case Intrinsic::vector_reduce_smin:
1138ded8187eSDavid Green   case Intrinsic::vector_reduce_smax:
1139ded8187eSDavid Green   case Intrinsic::vector_reduce_umin:
1140ded8187eSDavid Green   case Intrinsic::vector_reduce_umax:
1141ded8187eSDavid Green     break;
1142ded8187eSDavid Green   default:
1143ded8187eSDavid Green     return false;
1144ded8187eSDavid Green   }
1145ded8187eSDavid Green 
1146ded8187eSDavid Green   // Find all the inputs when looking through operations that do not alter the
1147ded8187eSDavid Green   // lane order (binops, for example). Currently we look for a single shuffle,
1148ded8187eSDavid Green   // and can ignore splat values.
1149ded8187eSDavid Green   std::queue<Value *> Worklist;
1150ded8187eSDavid Green   SmallPtrSet<Value *, 4> Visited;
1151ded8187eSDavid Green   ShuffleVectorInst *Shuffle = nullptr;
1152ded8187eSDavid Green   if (auto *Op = dyn_cast<Instruction>(I.getOperand(0)))
1153ded8187eSDavid Green     Worklist.push(Op);
1154ded8187eSDavid Green 
1155ded8187eSDavid Green   while (!Worklist.empty()) {
1156ded8187eSDavid Green     Value *CV = Worklist.front();
1157ded8187eSDavid Green     Worklist.pop();
1158ded8187eSDavid Green     if (Visited.contains(CV))
1159ded8187eSDavid Green       continue;
1160ded8187eSDavid Green 
1161ded8187eSDavid Green     // Splats don't change the order, so can be safely ignored.
1162ded8187eSDavid Green     if (isSplatValue(CV))
1163ded8187eSDavid Green       continue;
1164ded8187eSDavid Green 
1165ded8187eSDavid Green     Visited.insert(CV);
1166ded8187eSDavid Green 
1167ded8187eSDavid Green     if (auto *CI = dyn_cast<Instruction>(CV)) {
1168ded8187eSDavid Green       if (CI->isBinaryOp()) {
1169ded8187eSDavid Green         for (auto *Op : CI->operand_values())
1170ded8187eSDavid Green           Worklist.push(Op);
1171ded8187eSDavid Green         continue;
1172ded8187eSDavid Green       } else if (auto *SV = dyn_cast<ShuffleVectorInst>(CI)) {
1173ded8187eSDavid Green         if (Shuffle && Shuffle != SV)
1174ded8187eSDavid Green           return false;
1175ded8187eSDavid Green         Shuffle = SV;
1176ded8187eSDavid Green         continue;
1177ded8187eSDavid Green       }
1178ded8187eSDavid Green     }
1179ded8187eSDavid Green 
1180ded8187eSDavid Green     // Anything else is currently an unknown node.
1181ded8187eSDavid Green     return false;
1182ded8187eSDavid Green   }
1183ded8187eSDavid Green 
1184ded8187eSDavid Green   if (!Shuffle)
1185ded8187eSDavid Green     return false;
1186ded8187eSDavid Green 
1187ded8187eSDavid Green   // Check all uses of the binary ops and shuffles are also included in the
1188ded8187eSDavid Green   // lane-invariant operations (Visited should be the list of lanewise
1189ded8187eSDavid Green   // instructions, including the shuffle that we found).
1190ded8187eSDavid Green   for (auto *V : Visited)
1191ded8187eSDavid Green     for (auto *U : V->users())
1192ded8187eSDavid Green       if (!Visited.contains(U) && U != &I)
1193ded8187eSDavid Green         return false;
1194ded8187eSDavid Green 
1195ded8187eSDavid Green   FixedVectorType *VecType =
1196ded8187eSDavid Green       dyn_cast<FixedVectorType>(II->getOperand(0)->getType());
1197ded8187eSDavid Green   if (!VecType)
1198ded8187eSDavid Green     return false;
1199ded8187eSDavid Green   FixedVectorType *ShuffleInputType =
1200ded8187eSDavid Green       dyn_cast<FixedVectorType>(Shuffle->getOperand(0)->getType());
1201ded8187eSDavid Green   if (!ShuffleInputType)
1202ded8187eSDavid Green     return false;
1203ded8187eSDavid Green   int NumInputElts = ShuffleInputType->getNumElements();
1204ded8187eSDavid Green 
1205ded8187eSDavid Green   // Find the mask from sorting the lanes into order. This is most likely to
1206ded8187eSDavid Green   // become a identity or concat mask. Undef elements are pushed to the end.
1207ded8187eSDavid Green   SmallVector<int> ConcatMask;
1208ded8187eSDavid Green   Shuffle->getShuffleMask(ConcatMask);
12097047c479SDavid Green   sort(ConcatMask, [](int X, int Y) { return (unsigned)X < (unsigned)Y; });
1210ded8187eSDavid Green   bool UsesSecondVec =
1211ded8187eSDavid Green       any_of(ConcatMask, [&](int M) { return M >= NumInputElts; });
1212ded8187eSDavid Green   InstructionCost OldCost = TTI.getShuffleCost(
1213ded8187eSDavid Green       UsesSecondVec ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc, VecType,
1214ded8187eSDavid Green       Shuffle->getShuffleMask());
1215ded8187eSDavid Green   InstructionCost NewCost = TTI.getShuffleCost(
1216ded8187eSDavid Green       UsesSecondVec ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc, VecType,
1217ded8187eSDavid Green       ConcatMask);
1218ded8187eSDavid Green 
1219ded8187eSDavid Green   LLVM_DEBUG(dbgs() << "Found a reduction feeding from a shuffle: " << *Shuffle
1220ded8187eSDavid Green                     << "\n");
1221ded8187eSDavid Green   LLVM_DEBUG(dbgs() << "  OldCost: " << OldCost << " vs NewCost: " << NewCost
1222ded8187eSDavid Green                     << "\n");
1223ded8187eSDavid Green   if (NewCost < OldCost) {
1224ded8187eSDavid Green     Builder.SetInsertPoint(Shuffle);
1225ded8187eSDavid Green     Value *NewShuffle = Builder.CreateShuffleVector(
1226ded8187eSDavid Green         Shuffle->getOperand(0), Shuffle->getOperand(1), ConcatMask);
1227ded8187eSDavid Green     LLVM_DEBUG(dbgs() << "Created new shuffle: " << *NewShuffle << "\n");
1228ded8187eSDavid Green     replaceValue(*Shuffle, *NewShuffle);
1229ded8187eSDavid Green   }
1230ded8187eSDavid Green 
12316f9e1ea0SDavid Green   // See if we can re-use foldSelectShuffle, getting it to reduce the size of
12326f9e1ea0SDavid Green   // the shuffle into a nicer order, as it can ignore the order of the shuffles.
12336f9e1ea0SDavid Green   return foldSelectShuffle(*Shuffle, true);
1234ded8187eSDavid Green }
1235ded8187eSDavid Green 
1236100cb9a2SDavid Green /// This method looks for groups of shuffles acting on binops, of the form:
1237100cb9a2SDavid Green ///  %x = shuffle ...
1238100cb9a2SDavid Green ///  %y = shuffle ...
1239100cb9a2SDavid Green ///  %a = binop %x, %y
1240100cb9a2SDavid Green ///  %b = binop %x, %y
1241100cb9a2SDavid Green ///  shuffle %a, %b, selectmask
1242100cb9a2SDavid Green /// We may, especially if the shuffle is wider than legal, be able to convert
1243100cb9a2SDavid Green /// the shuffle to a form where only parts of a and b need to be computed. On
1244100cb9a2SDavid Green /// architectures with no obvious "select" shuffle, this can reduce the total
1245100cb9a2SDavid Green /// number of operations if the target reports them as cheaper.
foldSelectShuffle(Instruction & I,bool FromReduction)12466f9e1ea0SDavid Green bool VectorCombine::foldSelectShuffle(Instruction &I, bool FromReduction) {
1247100cb9a2SDavid Green   auto *SVI = dyn_cast<ShuffleVectorInst>(&I);
1248100cb9a2SDavid Green   auto *VT = dyn_cast<FixedVectorType>(I.getType());
1249100cb9a2SDavid Green   if (!SVI || !VT)
1250100cb9a2SDavid Green     return false;
1251100cb9a2SDavid Green   auto *Op0 = dyn_cast<Instruction>(SVI->getOperand(0));
1252100cb9a2SDavid Green   auto *Op1 = dyn_cast<Instruction>(SVI->getOperand(1));
1253100cb9a2SDavid Green   if (!Op0 || !Op1 || Op0 == Op1 || !Op0->isBinaryOp() || !Op1->isBinaryOp() ||
1254100cb9a2SDavid Green       VT != Op0->getType())
1255100cb9a2SDavid Green     return false;
12565493f8fcSDavid Green   auto *SVI0A = dyn_cast<Instruction>(Op0->getOperand(0));
12575493f8fcSDavid Green   auto *SVI0B = dyn_cast<Instruction>(Op0->getOperand(1));
12585493f8fcSDavid Green   auto *SVI1A = dyn_cast<Instruction>(Op1->getOperand(0));
12595493f8fcSDavid Green   auto *SVI1B = dyn_cast<Instruction>(Op1->getOperand(1));
12605493f8fcSDavid Green   SmallPtrSet<Instruction *, 4> InputShuffles({SVI0A, SVI0B, SVI1A, SVI1B});
1261100cb9a2SDavid Green   auto checkSVNonOpUses = [&](Instruction *I) {
1262100cb9a2SDavid Green     if (!I || I->getOperand(0)->getType() != VT)
1263100cb9a2SDavid Green       return true;
12645493f8fcSDavid Green     return any_of(I->users(), [&](User *U) {
12655493f8fcSDavid Green       return U != Op0 && U != Op1 &&
12665493f8fcSDavid Green              !(isa<ShuffleVectorInst>(U) &&
12675493f8fcSDavid Green                (InputShuffles.contains(cast<Instruction>(U)) ||
12685493f8fcSDavid Green                 isInstructionTriviallyDead(cast<Instruction>(U))));
12695493f8fcSDavid Green     });
1270100cb9a2SDavid Green   };
1271100cb9a2SDavid Green   if (checkSVNonOpUses(SVI0A) || checkSVNonOpUses(SVI0B) ||
1272100cb9a2SDavid Green       checkSVNonOpUses(SVI1A) || checkSVNonOpUses(SVI1B))
1273100cb9a2SDavid Green     return false;
1274100cb9a2SDavid Green 
1275100cb9a2SDavid Green   // Collect all the uses that are shuffles that we can transform together. We
1276100cb9a2SDavid Green   // may not have a single shuffle, but a group that can all be transformed
1277100cb9a2SDavid Green   // together profitably.
1278100cb9a2SDavid Green   SmallVector<ShuffleVectorInst *> Shuffles;
1279100cb9a2SDavid Green   auto collectShuffles = [&](Instruction *I) {
1280100cb9a2SDavid Green     for (auto *U : I->users()) {
1281100cb9a2SDavid Green       auto *SV = dyn_cast<ShuffleVectorInst>(U);
1282100cb9a2SDavid Green       if (!SV || SV->getType() != VT)
1283100cb9a2SDavid Green         return false;
12845493f8fcSDavid Green       if ((SV->getOperand(0) != Op0 && SV->getOperand(0) != Op1) ||
12855493f8fcSDavid Green           (SV->getOperand(1) != Op0 && SV->getOperand(1) != Op1))
12865493f8fcSDavid Green         return false;
1287c399b3a6SKazu Hirata       if (!llvm::is_contained(Shuffles, SV))
1288100cb9a2SDavid Green         Shuffles.push_back(SV);
1289100cb9a2SDavid Green     }
1290100cb9a2SDavid Green     return true;
1291100cb9a2SDavid Green   };
1292100cb9a2SDavid Green   if (!collectShuffles(Op0) || !collectShuffles(Op1))
1293100cb9a2SDavid Green     return false;
12946f9e1ea0SDavid Green   // From a reduction, we need to be processing a single shuffle, otherwise the
12956f9e1ea0SDavid Green   // other uses will not be lane-invariant.
12966f9e1ea0SDavid Green   if (FromReduction && Shuffles.size() > 1)
12976f9e1ea0SDavid Green     return false;
1298100cb9a2SDavid Green 
12995493f8fcSDavid Green   // Add any shuffle uses for the shuffles we have found, to include them in our
13005493f8fcSDavid Green   // cost calculations.
13015493f8fcSDavid Green   if (!FromReduction) {
13025493f8fcSDavid Green     for (ShuffleVectorInst *SV : Shuffles) {
13035493f8fcSDavid Green       for (auto U : SV->users()) {
13045493f8fcSDavid Green         ShuffleVectorInst *SSV = dyn_cast<ShuffleVectorInst>(U);
1305*4b7913c3SDavid Green         if (SSV && isa<UndefValue>(SSV->getOperand(1)) && SSV->getType() == VT)
13065493f8fcSDavid Green           Shuffles.push_back(SSV);
13075493f8fcSDavid Green       }
13085493f8fcSDavid Green     }
13095493f8fcSDavid Green   }
13105493f8fcSDavid Green 
1311100cb9a2SDavid Green   // For each of the output shuffles, we try to sort all the first vector
1312100cb9a2SDavid Green   // elements to the beginning, followed by the second array elements at the
1313100cb9a2SDavid Green   // end. If the binops are legalized to smaller vectors, this may reduce total
1314100cb9a2SDavid Green   // number of binops. We compute the ReconstructMask mask needed to convert
1315100cb9a2SDavid Green   // back to the original lane order.
13165493f8fcSDavid Green   SmallVector<std::pair<int, int>> V1, V2;
13175493f8fcSDavid Green   SmallVector<SmallVector<int>> OrigReconstructMasks;
1318100cb9a2SDavid Green   int MaxV1Elt = 0, MaxV2Elt = 0;
1319100cb9a2SDavid Green   unsigned NumElts = VT->getNumElements();
1320100cb9a2SDavid Green   for (ShuffleVectorInst *SVN : Shuffles) {
1321100cb9a2SDavid Green     SmallVector<int> Mask;
1322100cb9a2SDavid Green     SVN->getShuffleMask(Mask);
1323100cb9a2SDavid Green 
1324100cb9a2SDavid Green     // Check the operands are the same as the original, or reversed (in which
1325100cb9a2SDavid Green     // case we need to commute the mask).
1326100cb9a2SDavid Green     Value *SVOp0 = SVN->getOperand(0);
1327100cb9a2SDavid Green     Value *SVOp1 = SVN->getOperand(1);
13285493f8fcSDavid Green     if (isa<UndefValue>(SVOp1)) {
13295493f8fcSDavid Green       auto *SSV = cast<ShuffleVectorInst>(SVOp0);
13305493f8fcSDavid Green       SVOp0 = SSV->getOperand(0);
13315493f8fcSDavid Green       SVOp1 = SSV->getOperand(1);
13325493f8fcSDavid Green       for (unsigned I = 0, E = Mask.size(); I != E; I++) {
13335493f8fcSDavid Green         if (Mask[I] >= static_cast<int>(SSV->getShuffleMask().size()))
13345493f8fcSDavid Green           return false;
13355493f8fcSDavid Green         Mask[I] = Mask[I] < 0 ? Mask[I] : SSV->getMaskValue(Mask[I]);
13365493f8fcSDavid Green       }
13375493f8fcSDavid Green     }
1338100cb9a2SDavid Green     if (SVOp0 == Op1 && SVOp1 == Op0) {
1339100cb9a2SDavid Green       std::swap(SVOp0, SVOp1);
1340100cb9a2SDavid Green       ShuffleVectorInst::commuteShuffleMask(Mask, NumElts);
1341100cb9a2SDavid Green     }
1342100cb9a2SDavid Green     if (SVOp0 != Op0 || SVOp1 != Op1)
1343100cb9a2SDavid Green       return false;
1344100cb9a2SDavid Green 
1345100cb9a2SDavid Green     // Calculate the reconstruction mask for this shuffle, as the mask needed to
1346100cb9a2SDavid Green     // take the packed values from Op0/Op1 and reconstructing to the original
1347100cb9a2SDavid Green     // order.
1348100cb9a2SDavid Green     SmallVector<int> ReconstructMask;
1349100cb9a2SDavid Green     for (unsigned I = 0; I < Mask.size(); I++) {
1350100cb9a2SDavid Green       if (Mask[I] < 0) {
1351100cb9a2SDavid Green         ReconstructMask.push_back(-1);
1352100cb9a2SDavid Green       } else if (Mask[I] < static_cast<int>(NumElts)) {
1353100cb9a2SDavid Green         MaxV1Elt = std::max(MaxV1Elt, Mask[I]);
13545493f8fcSDavid Green         auto It = find_if(V1, [&](const std::pair<int, int> &A) {
13555493f8fcSDavid Green           return Mask[I] == A.first;
13565493f8fcSDavid Green         });
1357100cb9a2SDavid Green         if (It != V1.end())
1358100cb9a2SDavid Green           ReconstructMask.push_back(It - V1.begin());
1359100cb9a2SDavid Green         else {
1360100cb9a2SDavid Green           ReconstructMask.push_back(V1.size());
13615493f8fcSDavid Green           V1.emplace_back(Mask[I], V1.size());
1362100cb9a2SDavid Green         }
1363100cb9a2SDavid Green       } else {
1364100cb9a2SDavid Green         MaxV2Elt = std::max<int>(MaxV2Elt, Mask[I] - NumElts);
13655493f8fcSDavid Green         auto It = find_if(V2, [&](const std::pair<int, int> &A) {
13665493f8fcSDavid Green           return Mask[I] - static_cast<int>(NumElts) == A.first;
13675493f8fcSDavid Green         });
1368100cb9a2SDavid Green         if (It != V2.end())
1369100cb9a2SDavid Green           ReconstructMask.push_back(NumElts + It - V2.begin());
1370100cb9a2SDavid Green         else {
1371100cb9a2SDavid Green           ReconstructMask.push_back(NumElts + V2.size());
13725493f8fcSDavid Green           V2.emplace_back(Mask[I] - NumElts, NumElts + V2.size());
1373100cb9a2SDavid Green         }
1374100cb9a2SDavid Green       }
1375100cb9a2SDavid Green     }
1376100cb9a2SDavid Green 
13776f9e1ea0SDavid Green     // For reductions, we know that the lane ordering out doesn't alter the
13786f9e1ea0SDavid Green     // result. In-order can help simplify the shuffle away.
13796f9e1ea0SDavid Green     if (FromReduction)
13806f9e1ea0SDavid Green       sort(ReconstructMask);
13815493f8fcSDavid Green     OrigReconstructMasks.push_back(std::move(ReconstructMask));
1382100cb9a2SDavid Green   }
1383100cb9a2SDavid Green 
1384100cb9a2SDavid Green   // If the Maximum element used from V1 and V2 are not larger than the new
1385100cb9a2SDavid Green   // vectors, the vectors are already packes and performing the optimization
1386100cb9a2SDavid Green   // again will likely not help any further. This also prevents us from getting
1387100cb9a2SDavid Green   // stuck in a cycle in case the costs do not also rule it out.
1388100cb9a2SDavid Green   if (V1.empty() || V2.empty() ||
1389100cb9a2SDavid Green       (MaxV1Elt == static_cast<int>(V1.size()) - 1 &&
1390100cb9a2SDavid Green        MaxV2Elt == static_cast<int>(V2.size()) - 1))
1391100cb9a2SDavid Green     return false;
1392100cb9a2SDavid Green 
13935493f8fcSDavid Green   // GetBaseMaskValue takes one of the inputs, which may either be a shuffle, a
13945493f8fcSDavid Green   // shuffle of another shuffle, or not a shuffle (that is treated like a
13955493f8fcSDavid Green   // identity shuffle).
13965493f8fcSDavid Green   auto GetBaseMaskValue = [&](Instruction *I, int M) {
13975493f8fcSDavid Green     auto *SV = dyn_cast<ShuffleVectorInst>(I);
13985493f8fcSDavid Green     if (!SV)
13995493f8fcSDavid Green       return M;
14005493f8fcSDavid Green     if (isa<UndefValue>(SV->getOperand(1)))
14015493f8fcSDavid Green       if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0)))
14025493f8fcSDavid Green         if (InputShuffles.contains(SSV))
14035493f8fcSDavid Green           return SSV->getMaskValue(SV->getMaskValue(M));
14045493f8fcSDavid Green     return SV->getMaskValue(M);
14055493f8fcSDavid Green   };
14065493f8fcSDavid Green 
14075493f8fcSDavid Green   // Attempt to sort the inputs my ascending mask values to make simpler input
14085493f8fcSDavid Green   // shuffles and push complex shuffles down to the uses. We sort on the first
14095493f8fcSDavid Green   // of the two input shuffle orders, to try and get at least one input into a
14105493f8fcSDavid Green   // nice order.
14115493f8fcSDavid Green   auto SortBase = [&](Instruction *A, std::pair<int, int> X,
14125493f8fcSDavid Green                       std::pair<int, int> Y) {
14135493f8fcSDavid Green     int MXA = GetBaseMaskValue(A, X.first);
14145493f8fcSDavid Green     int MYA = GetBaseMaskValue(A, Y.first);
14155493f8fcSDavid Green     return MXA < MYA;
14165493f8fcSDavid Green   };
14175493f8fcSDavid Green   stable_sort(V1, [&](std::pair<int, int> A, std::pair<int, int> B) {
14185493f8fcSDavid Green     return SortBase(SVI0A, A, B);
14195493f8fcSDavid Green   });
14205493f8fcSDavid Green   stable_sort(V2, [&](std::pair<int, int> A, std::pair<int, int> B) {
14215493f8fcSDavid Green     return SortBase(SVI1A, A, B);
14225493f8fcSDavid Green   });
14235493f8fcSDavid Green   // Calculate our ReconstructMasks from the OrigReconstructMasks and the
14245493f8fcSDavid Green   // modified order of the input shuffles.
14255493f8fcSDavid Green   SmallVector<SmallVector<int>> ReconstructMasks;
14265493f8fcSDavid Green   for (auto Mask : OrigReconstructMasks) {
14275493f8fcSDavid Green     SmallVector<int> ReconstructMask;
14285493f8fcSDavid Green     for (int M : Mask) {
14295493f8fcSDavid Green       auto FindIndex = [](const SmallVector<std::pair<int, int>> &V, int M) {
14305493f8fcSDavid Green         auto It = find_if(V, [M](auto A) { return A.second == M; });
14315493f8fcSDavid Green         assert(It != V.end() && "Expected all entries in Mask");
14325493f8fcSDavid Green         return std::distance(V.begin(), It);
14335493f8fcSDavid Green       };
14345493f8fcSDavid Green       if (M < 0)
14355493f8fcSDavid Green         ReconstructMask.push_back(-1);
14365493f8fcSDavid Green       else if (M < static_cast<int>(NumElts)) {
14375493f8fcSDavid Green         ReconstructMask.push_back(FindIndex(V1, M));
14385493f8fcSDavid Green       } else {
14395493f8fcSDavid Green         ReconstructMask.push_back(NumElts + FindIndex(V2, M));
14405493f8fcSDavid Green       }
14415493f8fcSDavid Green     }
14425493f8fcSDavid Green     ReconstructMasks.push_back(std::move(ReconstructMask));
14435493f8fcSDavid Green   }
14445493f8fcSDavid Green 
1445100cb9a2SDavid Green   // Calculate the masks needed for the new input shuffles, which get padded
1446100cb9a2SDavid Green   // with undef
1447100cb9a2SDavid Green   SmallVector<int> V1A, V1B, V2A, V2B;
1448100cb9a2SDavid Green   for (unsigned I = 0; I < V1.size(); I++) {
14495493f8fcSDavid Green     V1A.push_back(GetBaseMaskValue(SVI0A, V1[I].first));
14505493f8fcSDavid Green     V1B.push_back(GetBaseMaskValue(SVI0B, V1[I].first));
1451100cb9a2SDavid Green   }
1452100cb9a2SDavid Green   for (unsigned I = 0; I < V2.size(); I++) {
14535493f8fcSDavid Green     V2A.push_back(GetBaseMaskValue(SVI1A, V2[I].first));
14545493f8fcSDavid Green     V2B.push_back(GetBaseMaskValue(SVI1B, V2[I].first));
1455100cb9a2SDavid Green   }
1456100cb9a2SDavid Green   while (V1A.size() < NumElts) {
1457100cb9a2SDavid Green     V1A.push_back(UndefMaskElem);
1458100cb9a2SDavid Green     V1B.push_back(UndefMaskElem);
1459100cb9a2SDavid Green   }
1460100cb9a2SDavid Green   while (V2A.size() < NumElts) {
1461100cb9a2SDavid Green     V2A.push_back(UndefMaskElem);
1462100cb9a2SDavid Green     V2B.push_back(UndefMaskElem);
1463100cb9a2SDavid Green   }
1464100cb9a2SDavid Green 
14655493f8fcSDavid Green   auto AddShuffleCost = [&](InstructionCost C, Instruction *I) {
14665493f8fcSDavid Green     auto *SV = dyn_cast<ShuffleVectorInst>(I);
14675493f8fcSDavid Green     if (!SV)
14685493f8fcSDavid Green       return C;
14695493f8fcSDavid Green     return C + TTI.getShuffleCost(isa<UndefValue>(SV->getOperand(1))
14705493f8fcSDavid Green                                       ? TTI::SK_PermuteSingleSrc
14715493f8fcSDavid Green                                       : TTI::SK_PermuteTwoSrc,
14725493f8fcSDavid Green                                   VT, SV->getShuffleMask());
1473100cb9a2SDavid Green   };
1474100cb9a2SDavid Green   auto AddShuffleMaskCost = [&](InstructionCost C, ArrayRef<int> Mask) {
1475100cb9a2SDavid Green     return C + TTI.getShuffleCost(TTI::SK_PermuteTwoSrc, VT, Mask);
1476100cb9a2SDavid Green   };
1477100cb9a2SDavid Green 
1478100cb9a2SDavid Green   // Get the costs of the shuffles + binops before and after with the new
1479100cb9a2SDavid Green   // shuffle masks.
1480100cb9a2SDavid Green   InstructionCost CostBefore =
1481100cb9a2SDavid Green       TTI.getArithmeticInstrCost(Op0->getOpcode(), VT) +
1482100cb9a2SDavid Green       TTI.getArithmeticInstrCost(Op1->getOpcode(), VT);
1483100cb9a2SDavid Green   CostBefore += std::accumulate(Shuffles.begin(), Shuffles.end(),
1484100cb9a2SDavid Green                                 InstructionCost(0), AddShuffleCost);
1485100cb9a2SDavid Green   CostBefore += std::accumulate(InputShuffles.begin(), InputShuffles.end(),
1486100cb9a2SDavid Green                                 InstructionCost(0), AddShuffleCost);
1487100cb9a2SDavid Green 
1488100cb9a2SDavid Green   // The new binops will be unused for lanes past the used shuffle lengths.
1489100cb9a2SDavid Green   // These types attempt to get the correct cost for that from the target.
1490100cb9a2SDavid Green   FixedVectorType *Op0SmallVT =
1491100cb9a2SDavid Green       FixedVectorType::get(VT->getScalarType(), V1.size());
1492100cb9a2SDavid Green   FixedVectorType *Op1SmallVT =
1493100cb9a2SDavid Green       FixedVectorType::get(VT->getScalarType(), V2.size());
1494100cb9a2SDavid Green   InstructionCost CostAfter =
1495100cb9a2SDavid Green       TTI.getArithmeticInstrCost(Op0->getOpcode(), Op0SmallVT) +
1496100cb9a2SDavid Green       TTI.getArithmeticInstrCost(Op1->getOpcode(), Op1SmallVT);
1497100cb9a2SDavid Green   CostAfter += std::accumulate(ReconstructMasks.begin(), ReconstructMasks.end(),
1498100cb9a2SDavid Green                                InstructionCost(0), AddShuffleMaskCost);
1499100cb9a2SDavid Green   std::set<SmallVector<int>> OutputShuffleMasks({V1A, V1B, V2A, V2B});
1500100cb9a2SDavid Green   CostAfter +=
1501100cb9a2SDavid Green       std::accumulate(OutputShuffleMasks.begin(), OutputShuffleMasks.end(),
1502100cb9a2SDavid Green                       InstructionCost(0), AddShuffleMaskCost);
1503100cb9a2SDavid Green 
15045493f8fcSDavid Green   LLVM_DEBUG(dbgs() << "Found a binop select shuffle pattern: " << I << "\n");
15055493f8fcSDavid Green   LLVM_DEBUG(dbgs() << "  CostBefore: " << CostBefore
15065493f8fcSDavid Green                     << " vs CostAfter: " << CostAfter << "\n");
1507100cb9a2SDavid Green   if (CostBefore <= CostAfter)
1508100cb9a2SDavid Green     return false;
1509100cb9a2SDavid Green 
1510100cb9a2SDavid Green   // The cost model has passed, create the new instructions.
15115493f8fcSDavid Green   auto GetShuffleOperand = [&](Instruction *I, unsigned Op) -> Value * {
15125493f8fcSDavid Green     auto *SV = dyn_cast<ShuffleVectorInst>(I);
15135493f8fcSDavid Green     if (!SV)
15145493f8fcSDavid Green       return I;
15155493f8fcSDavid Green     if (isa<UndefValue>(SV->getOperand(1)))
15165493f8fcSDavid Green       if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0)))
15175493f8fcSDavid Green         if (InputShuffles.contains(SSV))
15185493f8fcSDavid Green           return SSV->getOperand(Op);
15195493f8fcSDavid Green     return SV->getOperand(Op);
15205493f8fcSDavid Green   };
15215493f8fcSDavid Green   Builder.SetInsertPoint(SVI0A->getNextNode());
15225493f8fcSDavid Green   Value *NSV0A = Builder.CreateShuffleVector(GetShuffleOperand(SVI0A, 0),
15235493f8fcSDavid Green                                              GetShuffleOperand(SVI0A, 1), V1A);
15245493f8fcSDavid Green   Builder.SetInsertPoint(SVI0B->getNextNode());
15255493f8fcSDavid Green   Value *NSV0B = Builder.CreateShuffleVector(GetShuffleOperand(SVI0B, 0),
15265493f8fcSDavid Green                                              GetShuffleOperand(SVI0B, 1), V1B);
15275493f8fcSDavid Green   Builder.SetInsertPoint(SVI1A->getNextNode());
15285493f8fcSDavid Green   Value *NSV1A = Builder.CreateShuffleVector(GetShuffleOperand(SVI1A, 0),
15295493f8fcSDavid Green                                              GetShuffleOperand(SVI1A, 1), V2A);
15305493f8fcSDavid Green   Builder.SetInsertPoint(SVI1B->getNextNode());
15315493f8fcSDavid Green   Value *NSV1B = Builder.CreateShuffleVector(GetShuffleOperand(SVI1B, 0),
15325493f8fcSDavid Green                                              GetShuffleOperand(SVI1B, 1), V2B);
1533100cb9a2SDavid Green   Builder.SetInsertPoint(Op0);
1534100cb9a2SDavid Green   Value *NOp0 = Builder.CreateBinOp((Instruction::BinaryOps)Op0->getOpcode(),
1535100cb9a2SDavid Green                                     NSV0A, NSV0B);
1536100cb9a2SDavid Green   if (auto *I = dyn_cast<Instruction>(NOp0))
1537100cb9a2SDavid Green     I->copyIRFlags(Op0, true);
1538100cb9a2SDavid Green   Builder.SetInsertPoint(Op1);
1539100cb9a2SDavid Green   Value *NOp1 = Builder.CreateBinOp((Instruction::BinaryOps)Op1->getOpcode(),
1540100cb9a2SDavid Green                                     NSV1A, NSV1B);
1541100cb9a2SDavid Green   if (auto *I = dyn_cast<Instruction>(NOp1))
1542100cb9a2SDavid Green     I->copyIRFlags(Op1, true);
1543100cb9a2SDavid Green 
1544100cb9a2SDavid Green   for (int S = 0, E = ReconstructMasks.size(); S != E; S++) {
1545100cb9a2SDavid Green     Builder.SetInsertPoint(Shuffles[S]);
1546100cb9a2SDavid Green     Value *NSV = Builder.CreateShuffleVector(NOp0, NOp1, ReconstructMasks[S]);
1547100cb9a2SDavid Green     replaceValue(*Shuffles[S], *NSV);
1548100cb9a2SDavid Green   }
1549100cb9a2SDavid Green 
1550100cb9a2SDavid Green   Worklist.pushValue(NSV0A);
1551100cb9a2SDavid Green   Worklist.pushValue(NSV0B);
1552100cb9a2SDavid Green   Worklist.pushValue(NSV1A);
1553100cb9a2SDavid Green   Worklist.pushValue(NSV1B);
1554100cb9a2SDavid Green   for (auto *S : Shuffles)
1555100cb9a2SDavid Green     Worklist.add(S);
1556100cb9a2SDavid Green   return true;
1557100cb9a2SDavid Green }
1558100cb9a2SDavid Green 
1559a17f03bdSSanjay Patel /// This is the entry point for all transforms. Pass manager differences are
1560a17f03bdSSanjay Patel /// handled in the callers of this function.
run()15616bdd531aSSanjay Patel bool VectorCombine::run() {
156225c6544fSSanjay Patel   if (DisableVectorCombine)
156325c6544fSSanjay Patel     return false;
156425c6544fSSanjay Patel 
1565cc892fd9SSanjay Patel   // Don't attempt vectorization if the target does not support vectors.
1566cc892fd9SSanjay Patel   if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true)))
1567cc892fd9SSanjay Patel     return false;
1568cc892fd9SSanjay Patel 
1569a17f03bdSSanjay Patel   bool MadeChange = false;
1570300870a9SFlorian Hahn   auto FoldInst = [this, &MadeChange](Instruction &I) {
1571de65b356SSanjay Patel     Builder.SetInsertPoint(&I);
15724a1d63d7SFlorian Hahn     if (!ScalarizationOnly) {
157343bdac29SSanjay Patel       MadeChange |= vectorizeLoadInsert(I);
15746bdd531aSSanjay Patel       MadeChange |= foldExtractExtract(I);
15756bdd531aSSanjay Patel       MadeChange |= foldBitcastShuf(I);
1576b6315aeeSSanjay Patel       MadeChange |= foldExtractedCmps(I);
157766d22b4dSSanjay Patel       MadeChange |= foldShuffleOfBinops(I);
1578ded8187eSDavid Green       MadeChange |= foldShuffleFromReductions(I);
1579100cb9a2SDavid Green       MadeChange |= foldSelectShuffle(I);
15804a1d63d7SFlorian Hahn     }
15814a1d63d7SFlorian Hahn     MadeChange |= scalarizeBinopOrCmp(I);
15824e8c28b6SFlorian Hahn     MadeChange |= scalarizeLoadExtract(I);
15832db4979cSQiu Chaofan     MadeChange |= foldSingleElementStore(I);
1584300870a9SFlorian Hahn   };
1585300870a9SFlorian Hahn   for (BasicBlock &BB : F) {
1586300870a9SFlorian Hahn     // Ignore unreachable basic blocks.
1587300870a9SFlorian Hahn     if (!DT.isReachableFromEntry(&BB))
1588300870a9SFlorian Hahn       continue;
1589300870a9SFlorian Hahn     // Use early increment range so that we can erase instructions in loop.
1590300870a9SFlorian Hahn     for (Instruction &I : make_early_inc_range(BB)) {
1591098a0d8fSHongtao Yu       if (I.isDebugOrPseudoInst())
1592300870a9SFlorian Hahn         continue;
1593300870a9SFlorian Hahn       FoldInst(I);
1594a17f03bdSSanjay Patel     }
1595fc3cc8a4SSanjay Patel   }
1596a17f03bdSSanjay Patel 
1597300870a9SFlorian Hahn   while (!Worklist.isEmpty()) {
1598300870a9SFlorian Hahn     Instruction *I = Worklist.removeOne();
1599300870a9SFlorian Hahn     if (!I)
1600300870a9SFlorian Hahn       continue;
1601300870a9SFlorian Hahn 
1602300870a9SFlorian Hahn     if (isInstructionTriviallyDead(I)) {
1603300870a9SFlorian Hahn       eraseInstruction(*I);
1604300870a9SFlorian Hahn       continue;
1605300870a9SFlorian Hahn     }
1606300870a9SFlorian Hahn 
1607300870a9SFlorian Hahn     FoldInst(*I);
1608300870a9SFlorian Hahn   }
1609a17f03bdSSanjay Patel 
1610a17f03bdSSanjay Patel   return MadeChange;
1611a17f03bdSSanjay Patel }
1612a17f03bdSSanjay Patel 
1613a17f03bdSSanjay Patel // Pass manager boilerplate below here.
1614a17f03bdSSanjay Patel 
1615a17f03bdSSanjay Patel namespace {
1616a17f03bdSSanjay Patel class VectorCombineLegacyPass : public FunctionPass {
1617a17f03bdSSanjay Patel public:
1618a17f03bdSSanjay Patel   static char ID;
VectorCombineLegacyPass()1619a17f03bdSSanjay Patel   VectorCombineLegacyPass() : FunctionPass(ID) {
1620a17f03bdSSanjay Patel     initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry());
1621a17f03bdSSanjay Patel   }
1622a17f03bdSSanjay Patel 
getAnalysisUsage(AnalysisUsage & AU) const1623a17f03bdSSanjay Patel   void getAnalysisUsage(AnalysisUsage &AU) const override {
1624575e2affSFlorian Hahn     AU.addRequired<AssumptionCacheTracker>();
1625a17f03bdSSanjay Patel     AU.addRequired<DominatorTreeWrapperPass>();
1626a17f03bdSSanjay Patel     AU.addRequired<TargetTransformInfoWrapperPass>();
16272db4979cSQiu Chaofan     AU.addRequired<AAResultsWrapperPass>();
1628a17f03bdSSanjay Patel     AU.setPreservesCFG();
1629a17f03bdSSanjay Patel     AU.addPreserved<DominatorTreeWrapperPass>();
1630a17f03bdSSanjay Patel     AU.addPreserved<GlobalsAAWrapperPass>();
1631024098aeSSanjay Patel     AU.addPreserved<AAResultsWrapperPass>();
1632024098aeSSanjay Patel     AU.addPreserved<BasicAAWrapperPass>();
1633a17f03bdSSanjay Patel     FunctionPass::getAnalysisUsage(AU);
1634a17f03bdSSanjay Patel   }
1635a17f03bdSSanjay Patel 
runOnFunction(Function & F)1636a17f03bdSSanjay Patel   bool runOnFunction(Function &F) override {
1637a17f03bdSSanjay Patel     if (skipFunction(F))
1638a17f03bdSSanjay Patel       return false;
1639575e2affSFlorian Hahn     auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1640a17f03bdSSanjay Patel     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1641a17f03bdSSanjay Patel     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
16422db4979cSQiu Chaofan     auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
16434a1d63d7SFlorian Hahn     VectorCombine Combiner(F, TTI, DT, AA, AC, false);
16446bdd531aSSanjay Patel     return Combiner.run();
1645a17f03bdSSanjay Patel   }
1646a17f03bdSSanjay Patel };
1647a17f03bdSSanjay Patel } // namespace
1648a17f03bdSSanjay Patel 
1649a17f03bdSSanjay Patel char VectorCombineLegacyPass::ID = 0;
1650a17f03bdSSanjay Patel INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine",
1651a17f03bdSSanjay Patel                       "Optimize scalar/vector ops", false,
1652a17f03bdSSanjay Patel                       false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)1653575e2affSFlorian Hahn INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1654a17f03bdSSanjay Patel INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1655a17f03bdSSanjay Patel INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine",
1656a17f03bdSSanjay Patel                     "Optimize scalar/vector ops", false, false)
1657a17f03bdSSanjay Patel Pass *llvm::createVectorCombinePass() {
1658a17f03bdSSanjay Patel   return new VectorCombineLegacyPass();
1659a17f03bdSSanjay Patel }
1660a17f03bdSSanjay Patel 
run(Function & F,FunctionAnalysisManager & FAM)1661a17f03bdSSanjay Patel PreservedAnalyses VectorCombinePass::run(Function &F,
1662a17f03bdSSanjay Patel                                          FunctionAnalysisManager &FAM) {
1663575e2affSFlorian Hahn   auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1664a17f03bdSSanjay Patel   TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
1665a17f03bdSSanjay Patel   DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
16662db4979cSQiu Chaofan   AAResults &AA = FAM.getResult<AAManager>(F);
16674a1d63d7SFlorian Hahn   VectorCombine Combiner(F, TTI, DT, AA, AC, ScalarizationOnly);
16686bdd531aSSanjay Patel   if (!Combiner.run())
1669a17f03bdSSanjay Patel     return PreservedAnalyses::all();
1670a17f03bdSSanjay Patel   PreservedAnalyses PA;
1671a17f03bdSSanjay Patel   PA.preserveSet<CFGAnalyses>();
1672a17f03bdSSanjay Patel   return PA;
1673a17f03bdSSanjay Patel }
1674