Index: lib/Transforms/Vectorize/SLPVectorizer.cpp =================================================================== --- lib/Transforms/Vectorize/SLPVectorizer.cpp +++ lib/Transforms/Vectorize/SLPVectorizer.cpp @@ -662,13 +662,9 @@ /// Vectorize a single entry in the tree, starting in \p VL. Value *vectorizeTree(ArrayRef VL); - /// \returns the pointer to the vectorized value if \p VL is already - /// vectorized, or NULL. They may happen in cycles. - Value *alreadyVectorized(ArrayRef VL, Value *OpValue) const; - /// \returns the scalarization cost for this type. Scalarization in this /// context means the creation of vectors from a group of scalars. - int getGatherCost(Type *Ty); + int getGatherCost(Type *Ty, const DenseSet &ShuffledIndices); /// \returns the scalarization cost for this list of values. Assuming that /// this subtree gets vectorized, we may need to extract the values from the @@ -697,13 +693,24 @@ void reorderInputsAccordingToOpcode(unsigned Opcode, ArrayRef VL, SmallVectorImpl &Left, SmallVectorImpl &Right); + + /// Kind of the tree entry. + enum TreeEntryKind { + TEK_Vectorize, /// Entry must be vectorized. + TEK_Gather, /// Entry is the set of gather scalars. + TEK_EEShuffle, /// Entry is the shuffle of the ExtractElementInstructions. + }; struct TreeEntry { TreeEntry(std::vector &Container) : Container(Container) {} /// \returns true if the scalars in VL are equal to this entry. bool isSame(ArrayRef VL) const { - assert(VL.size() == Scalars.size() && "Invalid size"); - return std::equal(VL.begin(), VL.end(), Scalars.begin()); + if (VL.size() == Scalars.size()) + return std::equal(VL.begin(), VL.end(), Scalars.begin()); + assert(VL.size() == ReuseShuffleIndices.size() && "Invalid size"); + return std::equal( + VL.begin(), VL.end(), ReuseShuffleIndices.begin(), + [this](Value *V, unsigned Idx) { return V == Scalars[Idx]; }); } /// A vector of scalars. @@ -712,8 +719,12 @@ /// The Scalars are vectorized into this value. It is initialized to Null. Value *VectorizedValue = nullptr; - /// Do we need to gather this sequence ? - bool NeedToGather = false; + /// What should be done with the tree entry: vectorization, gathering or + /// shuffling of ExtractElement|InsertElements. + TreeEntryKind VectorizationKind = TEK_Vectorize; + + /// Does this sequence require some shuffling? + SmallVector ReuseShuffleIndices; /// Points back to the VectorizableTree. /// @@ -729,26 +740,27 @@ }; /// Create a new VectorizableTree entry. - TreeEntry *newTreeEntry(ArrayRef VL, bool Vectorized, - int &UserTreeIdx) { + void newTreeEntry(ArrayRef VL, TreeEntryKind Kind, int &UserTreeIdx, + ArrayRef ReuseShuffleIndices = None) { VectorizableTree.emplace_back(VectorizableTree); int idx = VectorizableTree.size() - 1; TreeEntry *Last = &VectorizableTree[idx]; Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end()); - Last->NeedToGather = !Vectorized; - if (Vectorized) { + Last->VectorizationKind = Kind; + Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(), + ReuseShuffleIndices.end()); + if (Kind == TEK_Vectorize) { for (int i = 0, e = VL.size(); i != e; ++i) { assert(!getTreeEntry(VL[i]) && "Scalar already in tree!"); ScalarToTreeEntry[VL[i]] = idx; } - } else { + } else if (Kind == TEK_Gather) { MustGather.insert(VL.begin(), VL.end()); } if (UserTreeIdx >= 0) Last->UserTreeIndices.push_back(UserTreeIdx); UserTreeIdx = idx; - return Last; } /// -- Vectorization State -- @@ -762,13 +774,6 @@ return nullptr; } - const TreeEntry *getTreeEntry(Value *V) const { - auto I = ScalarToTreeEntry.find(V); - if (I != ScalarToTreeEntry.end()) - return &VectorizableTree[I->second]; - return nullptr; - } - /// Maps a specific scalar to its tree entry. SmallDenseMap ScalarToTreeEntry; @@ -1309,7 +1314,7 @@ static std::string getNodeAttributes(const TreeEntry *Entry, const BoUpSLP *) { - if (Entry->NeedToGather) + if (Entry->VectorizationKind != BoUpSLP::TEK_Vectorize) return "color=red"; return ""; } @@ -1337,7 +1342,7 @@ TreeEntry *Entry = &EIdx; // No need to handle users of gathered values. - if (Entry->NeedToGather) + if (Entry->VectorizationKind != TEK_Vectorize) continue; // For each lane: @@ -1368,7 +1373,7 @@ !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) { DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U << ".\n"); - assert(!UseEntry->NeedToGather && "Bad state"); + assert(UseEntry->VectorizationKind == TEK_Vectorize && "Bad state"); continue; } } @@ -1392,28 +1397,28 @@ InstructionsState S = getSameOpcode(VL); if (Depth == RecursionMaxDepth) { DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n"); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx); return; } // Don't handle vectors. if (S.OpValue->getType()->isVectorTy()) { DEBUG(dbgs() << "SLP: Gathering due to vector type.\n"); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx); return; } if (StoreInst *SI = dyn_cast(S.OpValue)) if (SI->getValueOperand()->getType()->isVectorTy()) { DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n"); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx); return; } // If all of the operands are identical or constant we have a simple solution. if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.Opcode) { DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n"); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx); return; } @@ -1425,7 +1430,7 @@ if (EphValues.count(VL[i])) { DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] << ") is ephemeral.\n"); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx); return; } } @@ -1436,7 +1441,7 @@ DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n"); if (E->Scalars[i] != VL[i]) { DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n"); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx); return; } } @@ -1455,7 +1460,7 @@ if (getTreeEntry(I)) { DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] << ") is already in tree.\n"); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx); return; } } @@ -1465,7 +1470,7 @@ for (unsigned i = 0, e = VL.size(); i != e; ++i) { if (MustGather.count(VL[i])) { DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n"); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx); return; } } @@ -1479,18 +1484,31 @@ // Don't go into unreachable blocks. They may contain instructions with // dependency cycles which confuse the final scheduling. DEBUG(dbgs() << "SLP: bundle in unreachable block.\n"); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx); return; } // Check that every instruction appears once in this bundle. - for (unsigned i = 0, e = VL.size(); i < e; ++i) - for (unsigned j = i + 1; j < e; ++j) - if (VL[i] == VL[j]) { - DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n"); - newTreeEntry(VL, false, UserTreeIdx); - return; - } + SmallVector ReuseShuffleIndicies; + SmallVector UniqueValues; + DenseMap UniquePositions; + for (Value *V : VL) { + auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); + ReuseShuffleIndicies.emplace_back(Res.first->second); + if (Res.second) + UniqueValues.emplace_back(V); + } + if (UniqueValues.size() == VL.size()) { + ReuseShuffleIndicies.clear(); + } else { + DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n"); + if (UniqueValues.size() <= 1 || !llvm::isPowerOf2_32(UniqueValues.size())) { + DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n"); + newTreeEntry(VL, TEK_Gather, UserTreeIdx); + return; + } + VL = UniqueValues; + } auto &BSRef = BlocksSchedules[BB]; if (!BSRef) @@ -1498,12 +1516,12 @@ BlockScheduling &BS = *BSRef.get(); - if (!BS.tryScheduleBundle(VL, this, S.OpValue)) { + if (!BS.tryScheduleBundle(VL, this, VL0)) { DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n"); assert((!BS.getScheduleData(VL0) || !BS.getScheduleData(VL0)->isPartOfBundle()) && "tryScheduleBundle should cancelScheduling on failure"); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx, ReuseShuffleIndicies); return; } DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n"); @@ -1522,12 +1540,12 @@ if (Term) { DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n"); BS.cancelScheduling(VL, VL0); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx, ReuseShuffleIndicies); return; } } - newTreeEntry(VL, true, UserTreeIdx); + newTreeEntry(VL, TEK_Vectorize, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n"); for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { @@ -1543,17 +1561,22 @@ } case Instruction::ExtractValue: case Instruction::ExtractElement: { - bool Reuse = canReuseExtract(VL, VL0); - if (Reuse) { - DEBUG(dbgs() << "SLP: Reusing extract sequence.\n"); + TreeEntryKind Kind = TEK_Gather; + if (canReuseExtract(VL, VL0)) { + DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n"); ++NumOpsWantToKeepOrder[S.Opcode]; + Kind = TEK_Vectorize; } else { - SmallVector ReverseVL(VL.rbegin(), VL.rend()); - if (canReuseExtract(ReverseVL, VL0)) + if (canReuseExtract(llvm::to_vector<4>(llvm::reverse(VL)), VL0)) { --NumOpsWantToKeepOrder[S.Opcode]; + } else if (ShuffleOrOp == Instruction::ExtractElement && + isShuffle(VL).hasValue()) { + ++NumOpsWantToKeepOrder[S.Opcode]; + Kind = TEK_EEShuffle; + } BS.cancelScheduling(VL, VL0); } - newTreeEntry(VL, Reuse, UserTreeIdx); + newTreeEntry(VL, Kind, UserTreeIdx, ReuseShuffleIndicies); return; } case Instruction::Load: { @@ -1568,7 +1591,7 @@ if (DL->getTypeSizeInBits(ScalarTy) != DL->getTypeAllocSizeInBits(ScalarTy)) { BS.cancelScheduling(VL, VL0); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n"); return; } @@ -1579,7 +1602,7 @@ LoadInst *L = cast(VL[i]); if (!L->isSimple()) { BS.cancelScheduling(VL, VL0); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n"); return; } @@ -1601,7 +1624,7 @@ if (Consecutive) { ++NumOpsWantToKeepOrder[S.Opcode]; - newTreeEntry(VL, true, UserTreeIdx); + newTreeEntry(VL, TEK_Vectorize, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: added a vector of loads.\n"); return; } @@ -1616,7 +1639,7 @@ } BS.cancelScheduling(VL, VL0); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx, ReuseShuffleIndicies); if (ReverseConsecutive) { --NumOpsWantToKeepOrder[S.Opcode]; @@ -1643,12 +1666,12 @@ Type *Ty = cast(VL[i])->getOperand(0)->getType(); if (Ty != SrcTy || !isValidElementType(Ty)) { BS.cancelScheduling(VL, VL0); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n"); return; } } - newTreeEntry(VL, true, UserTreeIdx); + newTreeEntry(VL, TEK_Vectorize, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: added a vector of casts.\n"); for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { @@ -1671,13 +1694,13 @@ if (Cmp->getPredicate() != P0 || Cmp->getOperand(0)->getType() != ComparedTy) { BS.cancelScheduling(VL, VL0); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n"); return; } } - newTreeEntry(VL, true, UserTreeIdx); + newTreeEntry(VL, TEK_Vectorize, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: added a vector of compares.\n"); for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { @@ -1709,7 +1732,7 @@ case Instruction::And: case Instruction::Or: case Instruction::Xor: - newTreeEntry(VL, true, UserTreeIdx); + newTreeEntry(VL, TEK_Vectorize, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: added a vector of bin op.\n"); // Sort operands of the instructions so that each side is more likely to @@ -1738,7 +1761,7 @@ if (cast(VL[j])->getNumOperands() != 2) { DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n"); BS.cancelScheduling(VL, VL0); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx, ReuseShuffleIndicies); return; } } @@ -1751,7 +1774,7 @@ if (Ty0 != CurTy) { DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n"); BS.cancelScheduling(VL, VL0); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx, ReuseShuffleIndicies); return; } } @@ -1763,12 +1786,12 @@ DEBUG( dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n"); BS.cancelScheduling(VL, VL0); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx, ReuseShuffleIndicies); return; } } - newTreeEntry(VL, true, UserTreeIdx); + newTreeEntry(VL, TEK_Vectorize, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: added a vector of GEPs.\n"); for (unsigned i = 0, e = 2; i < e; ++i) { ValueList Operands; @@ -1785,12 +1808,12 @@ for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) { BS.cancelScheduling(VL, VL0); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: Non-consecutive store.\n"); return; } - newTreeEntry(VL, true, UserTreeIdx); + newTreeEntry(VL, TEK_Vectorize, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: added a vector of stores.\n"); ValueList Operands; @@ -1808,7 +1831,7 @@ Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); if (!isTriviallyVectorizable(ID)) { BS.cancelScheduling(VL, VL0); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: Non-vectorizable call.\n"); return; } @@ -1822,7 +1845,7 @@ getVectorIntrinsicIDForCall(CI2, TLI) != ID || !CI->hasIdenticalOperandBundleSchema(*CI2)) { BS.cancelScheduling(VL, VL0); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i] << "\n"); return; @@ -1833,7 +1856,7 @@ Value *A1J = CI2->getArgOperand(1); if (A1I != A1J) { BS.cancelScheduling(VL, VL0); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI << " argument "<< A1I<<"!=" << A1J << "\n"); @@ -1846,14 +1869,14 @@ CI->op_begin() + CI->getBundleOperandsEndIndex(), CI2->op_begin() + CI2->getBundleOperandsStartIndex())) { BS.cancelScheduling(VL, VL0); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" << *CI << "!=" << *VL[i] << '\n'); return; } } - newTreeEntry(VL, true, UserTreeIdx); + newTreeEntry(VL, TEK_Vectorize, UserTreeIdx, ReuseShuffleIndicies); for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) { ValueList Operands; // Prepare the operand vector. @@ -1870,11 +1893,11 @@ // then do not vectorize this instruction. if (!S.IsAltShuffle) { BS.cancelScheduling(VL, VL0); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n"); return; } - newTreeEntry(VL, true, UserTreeIdx); + newTreeEntry(VL, TEK_Vectorize, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n"); // Reorder operands if reordering would enable vectorization. @@ -1898,7 +1921,7 @@ default: BS.cancelScheduling(VL, VL0); - newTreeEntry(VL, false, UserTreeIdx); + newTreeEntry(VL, TEK_Gather, UserTreeIdx, ReuseShuffleIndicies); DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n"); return; } @@ -1991,36 +2014,28 @@ VecTy = VectorType::get( IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size()); - if (E->NeedToGather) { + unsigned ReuseShuffleNumbers = E->ReuseShuffleIndices.size(); + bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); + int ReuseShuffleCost = 0; + if (NeedToShuffleReuses) { + ReuseShuffleCost = + TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy); + } + if (E->VectorizationKind == TEK_Gather) { if (allConstant(VL)) return 0; if (isSplat(VL)) { - return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0); - } - if (getSameOpcode(VL).Opcode == Instruction::ExtractElement) { - Optional ShuffleKind = isShuffle(VL); - if (ShuffleKind.hasValue()) { - int Cost = TTI->getShuffleCost(ShuffleKind.getValue(), VecTy); - for (auto *V : VL) { - // If all users of instruction are going to be vectorized and this - // instruction itself is not going to be vectorized, consider this - // instruction as dead and remove its cost from the final cost of the - // vectorized tree. - if (areAllUsersVectorized(cast(V)) && - !ScalarToTreeEntry.count(V)) { - auto *IO = cast( - cast(V)->getIndexOperand()); - Cost -= TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, - IO->getZExtValue()); - } - } - return Cost; - } + return ReuseShuffleCost + + TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0); } return getGatherCost(E->Scalars); } InstructionsState S = getSameOpcode(VL); assert(S.Opcode && allSameType(VL) && allSameBlock(VL) && "Invalid VL"); + assert((E->VectorizationKind == TEK_Vectorize || + (E->VectorizationKind == TEK_EEShuffle && + S.Opcode == Instruction::ExtractElement)) && + "Must be vectorization entry or ExtractElementInst shuffle."); Instruction *VL0 = cast(S.OpValue); unsigned ShuffleOrOp = S.IsAltShuffle ? (unsigned) Instruction::ShuffleVector : S.Opcode; @@ -2030,8 +2045,55 @@ case Instruction::ExtractValue: case Instruction::ExtractElement: - if (canReuseExtract(VL, S.OpValue)) { - int DeadCost = 0; + if (NeedToShuffleReuses) { + unsigned Idx = 0; + for (unsigned I : E->ReuseShuffleIndices) { + if (ShuffleOrOp == Instruction::ExtractElement) { + auto *IO = cast( + cast(VL[I])->getIndexOperand()); + Idx = IO->getZExtValue(); + ReuseShuffleCost -= TTI->getVectorInstrCost( + Instruction::ExtractElement, VecTy, Idx); + } else { + ReuseShuffleCost -= TTI->getVectorInstrCost( + Instruction::ExtractElement, VecTy, Idx); + ++Idx; + } + } + Idx = ReuseShuffleNumbers; + for (Value *V : VL) { + if (ShuffleOrOp == Instruction::ExtractElement) { + auto *IO = cast( + cast(V)->getIndexOperand()); + Idx = IO->getZExtValue(); + } else { + --Idx; + } + ReuseShuffleCost += + TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, Idx); + } + } + if (E->VectorizationKind == TEK_EEShuffle) { + Optional ShuffleKind = isShuffle(VL); + assert(ShuffleKind.hasValue() && "Must be shuffle of extractelements"); + int Cost = TTI->getShuffleCost(ShuffleKind.getValue(), VecTy); + for (auto *V : VL) { + // If all users of instruction are going to be vectorized and this + // instruction itself is not going to be vectorized, consider this + // instruction as dead and remove its cost from the final cost of + // the vectorized tree. + if (areAllUsersVectorized(cast(V)) && + !ScalarToTreeEntry.count(V)) { + auto *IO = cast( + cast(V)->getIndexOperand()); + Cost -= TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, + IO->getZExtValue()); + } + } + return ReuseShuffleCost + Cost; + } + if (E->VectorizationKind == TEK_Vectorize) { + int DeadCost = ReuseShuffleCost; for (unsigned i = 0, e = VL.size(); i < e; ++i) { Instruction *E = cast(VL[i]); // If all users are going to be vectorized, instruction can be @@ -2039,12 +2101,12 @@ // The same, if have only one user, it will be vectorized for sure. if (areAllUsersVectorized(E)) // Take credit for instruction that will become dead. - DeadCost += + DeadCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i); } - return -DeadCost; + return DeadCost; } - return getGatherCost(VecTy); + return ReuseShuffleCost + getGatherCost(VL); case Instruction::ZExt: case Instruction::SExt: @@ -2059,6 +2121,11 @@ case Instruction::FPTrunc: case Instruction::BitCast: { Type *SrcTy = VL0->getOperand(0)->getType(); + if (NeedToShuffleReuses) { + ReuseShuffleCost -= + (ReuseShuffleNumbers - VL.size()) * + TTI->getCastInstrCost(S.Opcode, ScalarTy, SrcTy, VL0); + } // Calculate the cost of this instruction. int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(), @@ -2066,17 +2133,22 @@ VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size()); int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy, VL0); - return VecCost - ScalarCost; + return ReuseShuffleCost + VecCost - ScalarCost; } case Instruction::FCmp: case Instruction::ICmp: case Instruction::Select: { // Calculate the cost of this instruction. + if (NeedToShuffleReuses) { + ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * + TTI->getCmpSelInstrCost(S.Opcode, ScalarTy, + Builder.getInt1Ty(), VL0); + } VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size()); int ScalarCost = VecTy->getNumElements() * TTI->getCmpSelInstrCost(S.Opcode, ScalarTy, Builder.getInt1Ty(), VL0); int VecCost = TTI->getCmpSelInstrCost(S.Opcode, VecTy, MaskTy, VL0); - return VecCost - ScalarCost; + return ReuseShuffleCost + VecCost - ScalarCost; } case Instruction::Add: case Instruction::FAdd: @@ -2134,13 +2206,19 @@ Op2VP = TargetTransformInfo::OP_PowerOf2; SmallVector Operands(VL0->operand_values()); + if (NeedToShuffleReuses) { + ReuseShuffleCost -= + (ReuseShuffleNumbers - VL.size()) * + TTI->getArithmeticInstrCost(S.Opcode, ScalarTy, Op1VK, Op2VK, Op1VP, + Op2VP, Operands); + } int ScalarCost = VecTy->getNumElements() * TTI->getArithmeticInstrCost(S.Opcode, ScalarTy, Op1VK, Op2VK, Op1VP, Op2VP, Operands); int VecCost = TTI->getArithmeticInstrCost(S.Opcode, VecTy, Op1VK, Op2VK, Op1VP, Op2VP, Operands); - return VecCost - ScalarCost; + return ReuseShuffleCost + VecCost - ScalarCost; } case Instruction::GetElementPtr: { TargetTransformInfo::OperandValueKind Op1VK = @@ -2148,31 +2226,46 @@ TargetTransformInfo::OperandValueKind Op2VK = TargetTransformInfo::OK_UniformConstantValue; + if (NeedToShuffleReuses) { + ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * + TTI->getArithmeticInstrCost(Instruction::Add, + ScalarTy, Op1VK, Op2VK); + } int ScalarCost = VecTy->getNumElements() * TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK); int VecCost = TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK); - return VecCost - ScalarCost; + return ReuseShuffleCost + VecCost - ScalarCost; } case Instruction::Load: { // Cost of wide load - cost of scalar loads. unsigned alignment = dyn_cast(VL0)->getAlignment(); + if (NeedToShuffleReuses) { + ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * + TTI->getMemoryOpCost(Instruction::Load, ScalarTy, + alignment, 0, VL0); + } int ScalarLdCost = VecTy->getNumElements() * TTI->getMemoryOpCost(Instruction::Load, ScalarTy, alignment, 0, VL0); int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, alignment, 0, VL0); - return VecLdCost - ScalarLdCost; + return ReuseShuffleCost + VecLdCost - ScalarLdCost; } case Instruction::Store: { // We know that we can merge the stores. Calculate the cost. unsigned alignment = dyn_cast(VL0)->getAlignment(); + if (NeedToShuffleReuses) { + ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * + TTI->getMemoryOpCost(Instruction::Store, ScalarTy, + alignment, 0, VL0); + } int ScalarStCost = VecTy->getNumElements() * TTI->getMemoryOpCost(Instruction::Store, ScalarTy, alignment, 0, VL0); int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, alignment, 0, VL0); - return VecStCost - ScalarStCost; + return ReuseShuffleCost + VecStCost - ScalarStCost; } case Instruction::Call: { CallInst *CI = cast(VL0); @@ -2187,6 +2280,11 @@ if (auto *FPMO = dyn_cast(CI)) FMF = FPMO->getFastMathFlags(); + if (NeedToShuffleReuses) { + ReuseShuffleCost -= + (ReuseShuffleNumbers - VL.size()) * + TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF); + } int ScalarCallCost = VecTy->getNumElements() * TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF); @@ -2198,7 +2296,7 @@ << " (" << VecCallCost << "-" << ScalarCallCost << ")" << " for " << *CI << "\n"); - return VecCallCost - ScalarCallCost; + return ReuseShuffleCost + VecCallCost - ScalarCallCost; } case Instruction::ShuffleVector: { TargetTransformInfo::OperandValueKind Op1VK = @@ -2206,6 +2304,22 @@ TargetTransformInfo::OperandValueKind Op2VK = TargetTransformInfo::OK_AnyValue; int ScalarCost = 0; + if (NeedToShuffleReuses) { + for (unsigned Idx : E->ReuseShuffleIndices) { + Instruction *I = cast(VL[Idx]); + if (!I) + continue; + ReuseShuffleCost -= TTI->getArithmeticInstrCost( + I->getOpcode(), ScalarTy, Op1VK, Op2VK); + } + for (Value *V : VL) { + Instruction *I = cast(V); + if (!I) + continue; + ReuseShuffleCost += TTI->getArithmeticInstrCost( + I->getOpcode(), ScalarTy, Op1VK, Op2VK); + } + } int VecCost = 0; for (Value *i : VL) { Instruction *I = cast(i); @@ -2224,7 +2338,7 @@ TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK); VecCost += TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0); - return VecCost - ScalarCost; + return ReuseShuffleCost + VecCost - ScalarCost; } default: llvm_unreachable("Unknown instruction"); @@ -2236,20 +2350,23 @@ VectorizableTree.size() << " is fully vectorizable .\n"); // We only handle trees of heights 1 and 2. - if (VectorizableTree.size() == 1 && !VectorizableTree[0].NeedToGather) + if (VectorizableTree.size() == 1 && + VectorizableTree[0].VectorizationKind == TEK_Vectorize) return true; if (VectorizableTree.size() != 2) return false; // Handle splat and all-constants stores. - if (!VectorizableTree[0].NeedToGather && + if (VectorizableTree[0].VectorizationKind == TEK_Vectorize && (allConstant(VectorizableTree[1].Scalars) || isSplat(VectorizableTree[1].Scalars))) return true; // Gathering cost would be too much for tiny trees. - if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather) + if ((VectorizableTree[0].VectorizationKind != TEK_Vectorize || + VectorizableTree[1].VectorizationKind != TEK_Vectorize) && + VectorizableTree[0].Scalars.size() < 4) return false; return true; @@ -2400,10 +2517,14 @@ return Cost; } -int BoUpSLP::getGatherCost(Type *Ty) { +int BoUpSLP::getGatherCost(Type *Ty, + const DenseSet &ShuffledIndices) { int Cost = 0; for (unsigned i = 0, e = cast(Ty)->getNumElements(); i < e; ++i) - Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i); + if (!ShuffledIndices.count(i)) + Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i); + if (!ShuffledIndices.empty()) + Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty); return Cost; } @@ -2414,7 +2535,17 @@ ScalarTy = SI->getValueOperand()->getType(); VectorType *VecTy = VectorType::get(ScalarTy, VL.size()); // Find the cost of inserting/extracting values from the vector. - return getGatherCost(VecTy); + // Check if the same elements are inserted several times and count them as + // shuffle candidates. + DenseSet ShuffledElements; + DenseSet UniqueElements; + // Iterate in reverse order to consider insert elements with the high cost. + for (unsigned I = VL.size(); I > 0; --I) { + unsigned Idx = I - 1; + if (!UniqueElements.insert(VL[Idx]).second) + ShuffledElements.insert(Idx); + } + return getGatherCost(VecTy, ShuffledElements); } // Reorder commutative operations in alternate shuffle if the resulting vectors @@ -2728,14 +2859,6 @@ return Vec; } -Value *BoUpSLP::alreadyVectorized(ArrayRef VL, Value *OpValue) const { - if (const TreeEntry *En = getTreeEntry(OpValue)) { - if (En->isSame(VL) && En->VectorizedValue) - return En->VectorizedValue; - } - return nullptr; -} - Value *BoUpSLP::vectorizeTree(ArrayRef VL) { InstructionsState S = getSameOpcode(VL); if (S.Opcode) { @@ -2748,9 +2871,38 @@ Type *ScalarTy = S.OpValue->getType(); if (StoreInst *SI = dyn_cast(S.OpValue)) ScalarTy = SI->getValueOperand()->getType(); + + // Check that every instruction appears once in this bundle. + SmallVector ReuseShuffleIndicies; + SmallVector UniqueValues; + if (VL.size() > 2) { + DenseMap UniquePositions; + for (Value *V : VL) { + auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); + ReuseShuffleIndicies.emplace_back(Res.first->second); + if (Res.second || isa(V)) + UniqueValues.emplace_back(V); + } + // Do not shuffle single element or if number of unique values is not power + // of 2. + if (UniqueValues.size() == VL.size() || UniqueValues.size() <= 1 || + !llvm::isPowerOf2_32(UniqueValues.size())) + ReuseShuffleIndicies.clear(); + else + VL = UniqueValues; + } VectorType *VecTy = VectorType::get(ScalarTy, VL.size()); - return Gather(VL, VecTy); + Value *V = Gather(VL, VecTy); + if (!ReuseShuffleIndicies.empty()) { + V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), + ReuseShuffleIndicies, "shuffle"); + if (auto *I = dyn_cast(V)) { + GatherSeq.insert(I); + CSEBlocks.insert(I->getParent()); + } + } + return V; } Value *BoUpSLP::vectorizeTree(TreeEntry *E) { @@ -2768,12 +2920,26 @@ ScalarTy = SI->getValueOperand()->getType(); VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size()); - if (E->NeedToGather) { + bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); + + if (E->VectorizationKind == TEK_Gather) { setInsertPointAfterBundle(E->Scalars, VL0); auto *V = Gather(E->Scalars, VecTy); + if (NeedToShuffleReuses) { + V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), + E->ReuseShuffleIndices, "shuffle"); + if (auto *I = dyn_cast(V)) { + GatherSeq.insert(I); + CSEBlocks.insert(I->getParent()); + } + } E->VectorizedValue = V; return V; } + assert((E->VectorizationKind == TEK_Vectorize || + (E->VectorizationKind == TEK_EEShuffle && + S.Opcode == Instruction::ExtractElement)) && + "Must be vectorization entry or ExtractElementInst shuffle."); unsigned ShuffleOrOp = S.IsAltShuffle ? (unsigned) Instruction::ShuffleVector : S.Opcode; @@ -2810,34 +2976,52 @@ assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && "Invalid number of incoming values"); - return NewPhi; + if (NeedToShuffleReuses) { + E->VectorizedValue = Builder.CreateShuffleVector( + NewPhi, UndefValue::get(VecTy), E->ReuseShuffleIndices, "shuffle"); + } + return E->VectorizedValue; } case Instruction::ExtractElement: { - if (canReuseExtract(E->Scalars, VL0)) { - Value *V = VL0->getOperand(0); - E->VectorizedValue = V; - return V; + Value *V; + if (E->VectorizationKind == TEK_Vectorize) { + V = VL0->getOperand(0); + } else { + assert(E->VectorizationKind == TEK_EEShuffle && + "Only shuffle is expected."); + setInsertPointAfterBundle(E->Scalars, VL0); + V = Gather(E->Scalars, VecTy); + } + if (NeedToShuffleReuses) { + V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), + E->ReuseShuffleIndices, "shuffle"); + if (E->VectorizationKind != TEK_Vectorize) { + if (auto *I = dyn_cast(V)) { + GatherSeq.insert(I); + CSEBlocks.insert(I->getParent()); + } + } } - setInsertPointAfterBundle(E->Scalars, VL0); - auto *V = Gather(E->Scalars, VecTy); E->VectorizedValue = V; return V; } case Instruction::ExtractValue: { - if (canReuseExtract(E->Scalars, VL0)) { - LoadInst *LI = cast(VL0->getOperand(0)); - Builder.SetInsertPoint(LI); - PointerType *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace()); - Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy); - LoadInst *V = Builder.CreateAlignedLoad(Ptr, LI->getAlignment()); - E->VectorizedValue = V; - return propagateMetadata(V, E->Scalars); + assert(E->VectorizationKind == TEK_Vectorize && + "Unable to reuse extractvalues"); + LoadInst *LI = cast(VL0->getOperand(0)); + Builder.SetInsertPoint(LI); + PointerType *PtrTy = + PointerType::get(VecTy, LI->getPointerAddressSpace()); + Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy); + LoadInst *V = Builder.CreateAlignedLoad(Ptr, LI->getAlignment()); + Value *NewV = propagateMetadata(V, E->Scalars); + if (NeedToShuffleReuses) { + NewV = Builder.CreateShuffleVector(NewV, UndefValue::get(VecTy), + E->ReuseShuffleIndices, "shuffle"); } - setInsertPointAfterBundle(E->Scalars, VL0); - auto *V = Gather(E->Scalars, VecTy); - E->VectorizedValue = V; - return V; + E->VectorizedValue = NewV; + return NewV; } case Instruction::ZExt: case Instruction::SExt: @@ -2859,11 +3043,17 @@ Value *InVec = vectorizeTree(INVL); - if (Value *V = alreadyVectorized(E->Scalars, VL0)) - return V; + if (E->VectorizedValue) { + DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); + return E->VectorizedValue; + } CastInst *CI = dyn_cast(VL0); Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy); + if (NeedToShuffleReuses) { + V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), + E->ReuseShuffleIndices, "shuffle"); + } E->VectorizedValue = V; ++NumVectorInstructions; return V; @@ -2881,8 +3071,10 @@ Value *L = vectorizeTree(LHSV); Value *R = vectorizeTree(RHSV); - if (Value *V = alreadyVectorized(E->Scalars, VL0)) - return V; + if (E->VectorizedValue) { + DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); + return E->VectorizedValue; + } CmpInst::Predicate P0 = cast(VL0)->getPredicate(); Value *V; @@ -2891,8 +3083,12 @@ else V = Builder.CreateICmp(P0, L, R); + propagateIRFlags(V, E->Scalars, VL0); + if (NeedToShuffleReuses) { + V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), + E->ReuseShuffleIndices, "shuffle"); + } E->VectorizedValue = V; - propagateIRFlags(E->VectorizedValue, E->Scalars, VL0); ++NumVectorInstructions; return V; } @@ -2910,10 +3106,16 @@ Value *True = vectorizeTree(TrueVec); Value *False = vectorizeTree(FalseVec); - if (Value *V = alreadyVectorized(E->Scalars, VL0)) - return V; + if (E->VectorizedValue) { + DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); + return E->VectorizedValue; + } Value *V = Builder.CreateSelect(Cond, True, False); + if (NeedToShuffleReuses) { + V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), + E->ReuseShuffleIndices, "shuffle"); + } E->VectorizedValue = V; ++NumVectorInstructions; return V; @@ -2952,18 +3154,24 @@ Value *LHS = vectorizeTree(LHSVL); Value *RHS = vectorizeTree(RHSVL); - if (Value *V = alreadyVectorized(E->Scalars, VL0)) - return V; + if (E->VectorizedValue) { + DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); + return E->VectorizedValue; + } Value *V = Builder.CreateBinOp( static_cast(S.Opcode), LHS, RHS); + propagateIRFlags(V, E->Scalars, VL0); + if (auto *I = dyn_cast(V)) + V = propagateMetadata(I, E->Scalars); + + if (NeedToShuffleReuses) { + V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), + E->ReuseShuffleIndices, "shuffle"); + } E->VectorizedValue = V; - propagateIRFlags(E->VectorizedValue, E->Scalars, VL0); ++NumVectorInstructions; - if (Instruction *I = dyn_cast(V)) - return propagateMetadata(I, E->Scalars); - return V; } case Instruction::Load: { @@ -2991,9 +3199,14 @@ Alignment = DL->getABITypeAlignment(ScalarLoadTy); } LI->setAlignment(Alignment); - E->VectorizedValue = LI; + Value *V = propagateMetadata(LI, E->Scalars); + if (NeedToShuffleReuses) { + V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), + E->ReuseShuffleIndices, "shuffle"); + } + E->VectorizedValue = V; ++NumVectorInstructions; - return propagateMetadata(LI, E->Scalars); + return V; } case Instruction::Store: { StoreInst *SI = cast(VL0); @@ -3021,9 +3234,14 @@ Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType()); S->setAlignment(Alignment); - E->VectorizedValue = S; + Value *V = propagateMetadata(S, E->Scalars); + if (NeedToShuffleReuses) { + V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), + E->ReuseShuffleIndices, "shuffle"); + } + E->VectorizedValue = V; ++NumVectorInstructions; - return propagateMetadata(S, E->Scalars); + return V; } case Instruction::GetElementPtr: { setInsertPointAfterBundle(E->Scalars, VL0); @@ -3047,12 +3265,16 @@ Value *V = Builder.CreateGEP( cast(VL0)->getSourceElementType(), Op0, OpVecs); + if (Instruction *I = dyn_cast(V)) + V = propagateMetadata(I, E->Scalars); + + if (NeedToShuffleReuses) { + V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), + E->ReuseShuffleIndices, "shuffle"); + } E->VectorizedValue = V; ++NumVectorInstructions; - if (Instruction *I = dyn_cast(V)) - return propagateMetadata(I, E->Scalars); - return V; } case Instruction::Call: { @@ -3099,8 +3321,12 @@ if (ScalarArg && getTreeEntry(ScalarArg)) ExternalUses.push_back(ExternalUser(ScalarArg, cast(V), 0)); + propagateIRFlags(V, E->Scalars, VL0); + if (NeedToShuffleReuses) { + V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), + E->ReuseShuffleIndices, "shuffle"); + } E->VectorizedValue = V; - propagateIRFlags(E->VectorizedValue, E->Scalars, VL0); ++NumVectorInstructions; return V; } @@ -3114,8 +3340,10 @@ Value *LHS = vectorizeTree(LHSVL); Value *RHS = vectorizeTree(RHSVL); - if (Value *V = alreadyVectorized(E->Scalars, VL0)) - return V; + if (E->VectorizedValue) { + DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); + return E->VectorizedValue; + } // Create a vector of LHS op1 RHS Value *V0 = Builder.CreateBinOp( @@ -3147,10 +3375,14 @@ propagateIRFlags(V1, OddScalars); Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask); + if (Instruction *I = dyn_cast(V)) + V = propagateMetadata(I, E->Scalars); + if (NeedToShuffleReuses) { + V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), + E->ReuseShuffleIndices, "shuffle"); + } E->VectorizedValue = V; ++NumVectorInstructions; - if (Instruction *I = dyn_cast(V)) - return propagateMetadata(I, E->Scalars); return V; } @@ -3212,7 +3444,8 @@ continue; TreeEntry *E = getTreeEntry(Scalar); assert(E && "Invalid scalar"); - assert(!E->NeedToGather && "Extracting from a gather list"); + assert(E->VectorizationKind == TEK_Vectorize && + "Extracting from a gather list"); Value *Vec = E->VectorizedValue; assert(Vec && "Can't find vectorizable value"); @@ -3283,7 +3516,7 @@ TreeEntry *Entry = &EIdx; // No need to handle users of gathered values. - if (Entry->NeedToGather) + if (Entry->VectorizationKind != TEK_Vectorize) continue; assert(Entry->VectorizedValue && "Can't find vectorizable value"); @@ -3320,14 +3553,12 @@ DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size() << " gather sequences instructions.\n"); // LICM InsertElementInst sequences. - for (Instruction *it : GatherSeq) { - InsertElementInst *Insert = dyn_cast(it); - - if (!Insert) + for (Instruction *I : GatherSeq) { + if (!isa(I) && !isa(I)) continue; // Check if this block is inside a loop. - Loop *L = LI->getLoopFor(Insert->getParent()); + Loop *L = LI->getLoopFor(I->getParent()); if (!L) continue; @@ -3339,15 +3570,15 @@ // If the vector or the element that we insert into it are // instructions that are defined in this basic block then we can't // hoist this instruction. - Instruction *CurrVec = dyn_cast(Insert->getOperand(0)); - Instruction *NewElem = dyn_cast(Insert->getOperand(1)); - if (CurrVec && L->contains(CurrVec)) + auto *Op0 = dyn_cast(I->getOperand(0)); + auto *Op1 = dyn_cast(I->getOperand(1)); + if (Op0 && L->contains(Op0)) continue; - if (NewElem && L->contains(NewElem)) + if (Op1 && L->contains(Op1)) continue; // We can hoist this instruction. Move it to the pre-header. - Insert->moveBefore(PreHeader->getTerminator()); + I->moveBefore(PreHeader->getTerminator()); } // Make a list of all reachable blocks in our CSE queue. Index: test/Transforms/SLPVectorizer/X86/PR32086.ll =================================================================== --- test/Transforms/SLPVectorizer/X86/PR32086.ll +++ test/Transforms/SLPVectorizer/X86/PR32086.ll @@ -4,15 +4,14 @@ define void @i64_simplified(i64* noalias %st, i64* noalias %ld) { ; CHECK-LABEL: @i64_simplified( ; CHECK-NEXT: [[ARRAYIDX1:%.*]] = getelementptr inbounds i64, i64* [[LD:%.*]], i64 1 -; CHECK-NEXT: [[T0:%.*]] = load i64, i64* [[LD]], align 8 -; CHECK-NEXT: [[T1:%.*]] = load i64, i64* [[ARRAYIDX1]], align 8 +; CHECK-NEXT: [[TMP1:%.*]] = bitcast i64* [[LD]] to <2 x i64>* +; CHECK-NEXT: [[TMP2:%.*]] = load <2 x i64>, <2 x i64>* [[TMP1]], align 8 +; CHECK-NEXT: [[SHUFFLE:%.*]] = shufflevector <2 x i64> [[TMP2]], <2 x i64> undef, <4 x i32> ; CHECK-NEXT: [[ARRAYIDX3:%.*]] = getelementptr inbounds i64, i64* [[ST:%.*]], i64 1 ; CHECK-NEXT: [[ARRAYIDX4:%.*]] = getelementptr inbounds i64, i64* [[ST]], i64 2 ; CHECK-NEXT: [[ARRAYIDX5:%.*]] = getelementptr inbounds i64, i64* [[ST]], i64 3 -; CHECK-NEXT: store i64 [[T0]], i64* [[ST]], align 8 -; CHECK-NEXT: store i64 [[T1]], i64* [[ARRAYIDX3]], align 8 -; CHECK-NEXT: store i64 [[T0]], i64* [[ARRAYIDX4]], align 8 -; CHECK-NEXT: store i64 [[T1]], i64* [[ARRAYIDX5]], align 8 +; CHECK-NEXT: [[TMP3:%.*]] = bitcast i64* [[ST]] to <4 x i64>* +; CHECK-NEXT: store <4 x i64> [[SHUFFLE]], <4 x i64>* [[TMP3]], align 8 ; CHECK-NEXT: ret void ; %arrayidx1 = getelementptr inbounds i64, i64* %ld, i64 1 @@ -39,10 +38,11 @@ ; CHECK-NEXT: [[ARRAYIDX3:%.*]] = getelementptr inbounds i64, i64* [[ST:%.*]], i64 1 ; CHECK-NEXT: [[ARRAYIDX4:%.*]] = getelementptr inbounds i64, i64* [[ST]], i64 2 ; CHECK-NEXT: [[ARRAYIDX5:%.*]] = getelementptr inbounds i64, i64* [[ST]], i64 3 -; CHECK-NEXT: store i64 [[T1]], i64* [[ST]], align 8 -; CHECK-NEXT: store i64 [[T0]], i64* [[ARRAYIDX3]], align 8 -; CHECK-NEXT: store i64 [[T1]], i64* [[ARRAYIDX4]], align 8 -; CHECK-NEXT: store i64 [[T0]], i64* [[ARRAYIDX5]], align 8 +; CHECK-NEXT: [[TMP1:%.*]] = insertelement <2 x i64> undef, i64 [[T1]], i32 0 +; CHECK-NEXT: [[TMP2:%.*]] = insertelement <2 x i64> [[TMP1]], i64 [[T0]], i32 1 +; CHECK-NEXT: [[SHUFFLE:%.*]] = shufflevector <2 x i64> [[TMP2]], <2 x i64> undef, <4 x i32> +; CHECK-NEXT: [[TMP3:%.*]] = bitcast i64* [[ST]] to <4 x i64>* +; CHECK-NEXT: store <4 x i64> [[SHUFFLE]], <4 x i64>* [[TMP3]], align 8 ; CHECK-NEXT: ret void ; %arrayidx1 = getelementptr inbounds i64, i64* %ld, i64 1 Index: test/Transforms/SLPVectorizer/X86/blending-shuffle.ll =================================================================== --- test/Transforms/SLPVectorizer/X86/blending-shuffle.ll +++ test/Transforms/SLPVectorizer/X86/blending-shuffle.ll @@ -137,17 +137,19 @@ define i8 @k_bb(<4 x i8> %x) { ; CHECK-LABEL: @k_bb( +; CHECK-NEXT: [[X0:%.*]] = extractelement <4 x i8> [[X:%.*]], i32 0 ; CHECK-NEXT: br label [[BB1:%.*]] ; CHECK: bb1: -; CHECK-NEXT: [[TMP1:%.*]] = mul <4 x i8> [[X:%.*]], [[X]] -; CHECK-NEXT: [[TMP2:%.*]] = shufflevector <4 x i8> [[TMP1]], <4 x i8> undef, <2 x i32> -; CHECK-NEXT: [[TMP3:%.*]] = mul <4 x i8> [[X]], [[X]] -; CHECK-NEXT: [[TMP4:%.*]] = shufflevector <4 x i8> [[TMP3]], <4 x i8> undef, <2 x i32> -; CHECK-NEXT: [[TMP5:%.*]] = add <2 x i8> [[TMP2]], [[TMP4]] -; CHECK-NEXT: [[TMP6:%.*]] = extractelement <2 x i8> [[TMP5]], i32 0 -; CHECK-NEXT: [[TMP7:%.*]] = extractelement <2 x i8> [[TMP5]], i32 1 -; CHECK-NEXT: [[TMP8:%.*]] = sdiv i8 [[TMP6]], [[TMP7]] -; CHECK-NEXT: ret i8 [[TMP8]] +; CHECK-NEXT: [[X3:%.*]] = extractelement <4 x i8> [[X]], i32 3 +; CHECK-NEXT: [[X0X0:%.*]] = mul i8 [[X0]], [[X0]] +; CHECK-NEXT: [[X3X3:%.*]] = mul i8 [[X3]], [[X3]] +; CHECK-NEXT: [[TMP1:%.*]] = mul <4 x i8> [[X]], [[X]] +; CHECK-NEXT: [[TMP2:%.*]] = add i8 [[X0X0]], [[X3X3]] +; CHECK-NEXT: [[TMP3:%.*]] = extractelement <4 x i8> [[TMP1]], i32 1 +; CHECK-NEXT: [[TMP4:%.*]] = extractelement <4 x i8> [[TMP1]], i32 2 +; CHECK-NEXT: [[TMP5:%.*]] = add i8 [[TMP3]], [[TMP4]] +; CHECK-NEXT: [[TMP6:%.*]] = sdiv i8 [[TMP2]], [[TMP5]] +; CHECK-NEXT: ret i8 [[TMP6]] ; %x0 = extractelement <4 x i8> %x, i32 0 br label %bb1 Index: test/Transforms/SLPVectorizer/X86/hoist.ll =================================================================== --- test/Transforms/SLPVectorizer/X86/hoist.ll +++ test/Transforms/SLPVectorizer/X86/hoist.ll @@ -16,19 +16,18 @@ define i32 @foo(i32* nocapture %A, i32 %n, i32 %k) { ; CHECK-LABEL: @foo( ; CHECK-NEXT: entry: -; CHECK-NEXT: [[TMP0:%.*]] = insertelement <4 x i32> undef, i32 [[N:%.*]], i32 0 -; CHECK-NEXT: [[TMP1:%.*]] = insertelement <4 x i32> [[TMP0]], i32 [[K:%.*]], i32 1 -; CHECK-NEXT: [[TMP2:%.*]] = insertelement <4 x i32> [[TMP1]], i32 [[N]], i32 2 -; CHECK-NEXT: [[TMP3:%.*]] = insertelement <4 x i32> [[TMP2]], i32 [[K]], i32 3 +; CHECK-NEXT: [[TMP0:%.*]] = insertelement <2 x i32> undef, i32 [[N:%.*]], i32 0 +; CHECK-NEXT: [[TMP1:%.*]] = insertelement <2 x i32> [[TMP0]], i32 [[K:%.*]], i32 1 +; CHECK-NEXT: [[SHUFFLE:%.*]] = shufflevector <2 x i32> [[TMP1]], <2 x i32> undef, <4 x i32> ; CHECK-NEXT: br label [[FOR_BODY:%.*]] ; CHECK: for.body: ; CHECK-NEXT: [[I_024:%.*]] = phi i32 [ 0, [[ENTRY:%.*]] ], [ [[ADD10:%.*]], [[FOR_BODY]] ] ; CHECK-NEXT: [[ARRAYIDX:%.*]] = getelementptr inbounds i32, i32* [[A:%.*]], i32 [[I_024]] -; CHECK-NEXT: [[TMP4:%.*]] = bitcast i32* [[ARRAYIDX]] to <4 x i32>* -; CHECK-NEXT: [[TMP5:%.*]] = load <4 x i32>, <4 x i32>* [[TMP4]], align 4 -; CHECK-NEXT: [[TMP6:%.*]] = add nsw <4 x i32> [[TMP3]], [[TMP5]] -; CHECK-NEXT: [[TMP7:%.*]] = bitcast i32* [[ARRAYIDX]] to <4 x i32>* -; CHECK-NEXT: store <4 x i32> [[TMP6]], <4 x i32>* [[TMP7]], align 4 +; CHECK-NEXT: [[TMP2:%.*]] = bitcast i32* [[ARRAYIDX]] to <4 x i32>* +; CHECK-NEXT: [[TMP3:%.*]] = load <4 x i32>, <4 x i32>* [[TMP2]], align 4 +; CHECK-NEXT: [[TMP4:%.*]] = add nsw <4 x i32> [[SHUFFLE]], [[TMP3]] +; CHECK-NEXT: [[TMP5:%.*]] = bitcast i32* [[ARRAYIDX]] to <4 x i32>* +; CHECK-NEXT: store <4 x i32> [[TMP4]], <4 x i32>* [[TMP5]], align 4 ; CHECK-NEXT: [[ADD10]] = add nsw i32 [[I_024]], 4 ; CHECK-NEXT: [[CMP:%.*]] = icmp slt i32 [[ADD10]], 10000 ; CHECK-NEXT: br i1 [[CMP]], label [[FOR_BODY]], label [[FOR_END:%.*]]