xref: /src/contrib/llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1044eb2f6SDimitry Andric //===- VPlan.cpp - Vectorizer Plan ----------------------------------------===//
2044eb2f6SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6044eb2f6SDimitry Andric //
7044eb2f6SDimitry Andric //===----------------------------------------------------------------------===//
8044eb2f6SDimitry Andric ///
9044eb2f6SDimitry Andric /// \file
10044eb2f6SDimitry Andric /// This is the LLVM vectorization plan. It represents a candidate for
11044eb2f6SDimitry Andric /// vectorization, allowing to plan and optimize how to vectorize a given loop
12044eb2f6SDimitry Andric /// before generating LLVM-IR.
13044eb2f6SDimitry Andric /// The vectorizer uses vectorization plans to estimate the costs of potential
14044eb2f6SDimitry Andric /// candidates and if profitable to execute the desired plan, generating vector
15044eb2f6SDimitry Andric /// LLVM-IR code.
16044eb2f6SDimitry Andric ///
17044eb2f6SDimitry Andric //===----------------------------------------------------------------------===//
18044eb2f6SDimitry Andric 
19044eb2f6SDimitry Andric #include "VPlan.h"
20ac9a064cSDimitry Andric #include "LoopVectorizationPlanner.h"
21e3b55780SDimitry Andric #include "VPlanCFG.h"
22b7eb8e35SDimitry Andric #include "VPlanDominatorTree.h"
23ac9a064cSDimitry Andric #include "VPlanPatternMatch.h"
24044eb2f6SDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
25b60736ecSDimitry Andric #include "llvm/ADT/STLExtras.h"
26044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
277fa27ce4SDimitry Andric #include "llvm/ADT/StringExtras.h"
28044eb2f6SDimitry Andric #include "llvm/ADT/Twine.h"
29ac9a064cSDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
30044eb2f6SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
31044eb2f6SDimitry Andric #include "llvm/IR/BasicBlock.h"
32044eb2f6SDimitry Andric #include "llvm/IR/CFG.h"
33145449b1SDimitry Andric #include "llvm/IR/IRBuilder.h"
34044eb2f6SDimitry Andric #include "llvm/IR/Instruction.h"
35044eb2f6SDimitry Andric #include "llvm/IR/Instructions.h"
36044eb2f6SDimitry Andric #include "llvm/IR/Type.h"
37044eb2f6SDimitry Andric #include "llvm/IR/Value.h"
38044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
39706b4fc4SDimitry Andric #include "llvm/Support/CommandLine.h"
40044eb2f6SDimitry Andric #include "llvm/Support/Debug.h"
41b7eb8e35SDimitry Andric #include "llvm/Support/GenericDomTreeConstruction.h"
42044eb2f6SDimitry Andric #include "llvm/Support/GraphWriter.h"
43044eb2f6SDimitry Andric #include "llvm/Support/raw_ostream.h"
44044eb2f6SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45145449b1SDimitry Andric #include "llvm/Transforms/Utils/LoopVersioning.h"
46145449b1SDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
47044eb2f6SDimitry Andric #include <cassert>
48044eb2f6SDimitry Andric #include <string>
49044eb2f6SDimitry Andric #include <vector>
50044eb2f6SDimitry Andric 
51044eb2f6SDimitry Andric using namespace llvm;
52ac9a064cSDimitry Andric using namespace llvm::VPlanPatternMatch;
537fa27ce4SDimitry Andric 
547fa27ce4SDimitry Andric namespace llvm {
55d8e91e46SDimitry Andric extern cl::opt<bool> EnableVPlanNativePath;
567fa27ce4SDimitry Andric }
57044eb2f6SDimitry Andric 
58044eb2f6SDimitry Andric #define DEBUG_TYPE "vplan"
59044eb2f6SDimitry Andric 
60344a3780SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
operator <<(raw_ostream & OS,const VPValue & V)61044eb2f6SDimitry Andric raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) {
62cfca06d7SDimitry Andric   const VPInstruction *Instr = dyn_cast<VPInstruction>(&V);
63cfca06d7SDimitry Andric   VPSlotTracker SlotTracker(
64cfca06d7SDimitry Andric       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
65cfca06d7SDimitry Andric   V.print(OS, SlotTracker);
66044eb2f6SDimitry Andric   return OS;
67044eb2f6SDimitry Andric }
68344a3780SDimitry Andric #endif
69344a3780SDimitry Andric 
getAsRuntimeExpr(IRBuilderBase & Builder,const ElementCount & VF) const70145449b1SDimitry Andric Value *VPLane::getAsRuntimeExpr(IRBuilderBase &Builder,
71344a3780SDimitry Andric                                 const ElementCount &VF) const {
72344a3780SDimitry Andric   switch (LaneKind) {
73344a3780SDimitry Andric   case VPLane::Kind::ScalableLast:
74344a3780SDimitry Andric     // Lane = RuntimeVF - VF.getKnownMinValue() + Lane
75344a3780SDimitry Andric     return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF),
76344a3780SDimitry Andric                              Builder.getInt32(VF.getKnownMinValue() - Lane));
77344a3780SDimitry Andric   case VPLane::Kind::First:
78344a3780SDimitry Andric     return Builder.getInt32(Lane);
79344a3780SDimitry Andric   }
80344a3780SDimitry Andric   llvm_unreachable("Unknown lane kind");
81344a3780SDimitry Andric }
82044eb2f6SDimitry Andric 
VPValue(const unsigned char SC,Value * UV,VPDef * Def)83b60736ecSDimitry Andric VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def)
84b60736ecSDimitry Andric     : SubclassID(SC), UnderlyingVal(UV), Def(Def) {
85b60736ecSDimitry Andric   if (Def)
86b60736ecSDimitry Andric     Def->addDefinedValue(this);
87b60736ecSDimitry Andric }
88b60736ecSDimitry Andric 
~VPValue()89b60736ecSDimitry Andric VPValue::~VPValue() {
90b60736ecSDimitry Andric   assert(Users.empty() && "trying to delete a VPValue with remaining users");
91b60736ecSDimitry Andric   if (Def)
92b60736ecSDimitry Andric     Def->removeDefinedValue(this);
93b60736ecSDimitry Andric }
94b60736ecSDimitry Andric 
95344a3780SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
print(raw_ostream & OS,VPSlotTracker & SlotTracker) const96cfca06d7SDimitry Andric void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const {
97b60736ecSDimitry Andric   if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def))
98b60736ecSDimitry Andric     R->print(OS, "", SlotTracker);
99cfca06d7SDimitry Andric   else
100cfca06d7SDimitry Andric     printAsOperand(OS, SlotTracker);
101cfca06d7SDimitry Andric }
102cfca06d7SDimitry Andric 
dump() const103b60736ecSDimitry Andric void VPValue::dump() const {
104b60736ecSDimitry Andric   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def);
105b60736ecSDimitry Andric   VPSlotTracker SlotTracker(
106b60736ecSDimitry Andric       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
107b60736ecSDimitry Andric   print(dbgs(), SlotTracker);
108b60736ecSDimitry Andric   dbgs() << "\n";
109b60736ecSDimitry Andric }
110b60736ecSDimitry Andric 
dump() const111b60736ecSDimitry Andric void VPDef::dump() const {
112b60736ecSDimitry Andric   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this);
113b60736ecSDimitry Andric   VPSlotTracker SlotTracker(
114b60736ecSDimitry Andric       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
115b60736ecSDimitry Andric   print(dbgs(), "", SlotTracker);
116b60736ecSDimitry Andric   dbgs() << "\n";
117b60736ecSDimitry Andric }
118344a3780SDimitry Andric #endif
119b60736ecSDimitry Andric 
getDefiningRecipe()120e3b55780SDimitry Andric VPRecipeBase *VPValue::getDefiningRecipe() {
121e3b55780SDimitry Andric   return cast_or_null<VPRecipeBase>(Def);
122e3b55780SDimitry Andric }
123e3b55780SDimitry Andric 
getDefiningRecipe() const124e3b55780SDimitry Andric const VPRecipeBase *VPValue::getDefiningRecipe() const {
125e3b55780SDimitry Andric   return cast_or_null<VPRecipeBase>(Def);
126e3b55780SDimitry Andric }
127e3b55780SDimitry Andric 
128cfca06d7SDimitry Andric // Get the top-most entry block of \p Start. This is the entry block of the
129cfca06d7SDimitry Andric // containing VPlan. This function is templated to support both const and non-const blocks
getPlanEntry(T * Start)130cfca06d7SDimitry Andric template <typename T> static T *getPlanEntry(T *Start) {
131cfca06d7SDimitry Andric   T *Next = Start;
132cfca06d7SDimitry Andric   T *Current = Start;
133cfca06d7SDimitry Andric   while ((Next = Next->getParent()))
134cfca06d7SDimitry Andric     Current = Next;
135cfca06d7SDimitry Andric 
136cfca06d7SDimitry Andric   SmallSetVector<T *, 8> WorkList;
137cfca06d7SDimitry Andric   WorkList.insert(Current);
138cfca06d7SDimitry Andric 
139cfca06d7SDimitry Andric   for (unsigned i = 0; i < WorkList.size(); i++) {
140cfca06d7SDimitry Andric     T *Current = WorkList[i];
141cfca06d7SDimitry Andric     if (Current->getNumPredecessors() == 0)
142cfca06d7SDimitry Andric       return Current;
143cfca06d7SDimitry Andric     auto &Predecessors = Current->getPredecessors();
144cfca06d7SDimitry Andric     WorkList.insert(Predecessors.begin(), Predecessors.end());
145cfca06d7SDimitry Andric   }
146cfca06d7SDimitry Andric 
147cfca06d7SDimitry Andric   llvm_unreachable("VPlan without any entry node without predecessors");
148cfca06d7SDimitry Andric }
149cfca06d7SDimitry Andric 
getPlan()150cfca06d7SDimitry Andric VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; }
151cfca06d7SDimitry Andric 
getPlan() const152cfca06d7SDimitry Andric const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; }
153cfca06d7SDimitry Andric 
154044eb2f6SDimitry Andric /// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
getEntryBasicBlock() const155044eb2f6SDimitry Andric const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const {
156044eb2f6SDimitry Andric   const VPBlockBase *Block = this;
157044eb2f6SDimitry Andric   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
158044eb2f6SDimitry Andric     Block = Region->getEntry();
159044eb2f6SDimitry Andric   return cast<VPBasicBlock>(Block);
160044eb2f6SDimitry Andric }
161044eb2f6SDimitry Andric 
getEntryBasicBlock()162044eb2f6SDimitry Andric VPBasicBlock *VPBlockBase::getEntryBasicBlock() {
163044eb2f6SDimitry Andric   VPBlockBase *Block = this;
164044eb2f6SDimitry Andric   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
165044eb2f6SDimitry Andric     Block = Region->getEntry();
166044eb2f6SDimitry Andric   return cast<VPBasicBlock>(Block);
167044eb2f6SDimitry Andric }
168044eb2f6SDimitry Andric 
setPlan(VPlan * ParentPlan)169cfca06d7SDimitry Andric void VPBlockBase::setPlan(VPlan *ParentPlan) {
1707fa27ce4SDimitry Andric   assert(
1717fa27ce4SDimitry Andric       (ParentPlan->getEntry() == this || ParentPlan->getPreheader() == this) &&
1727fa27ce4SDimitry Andric       "Can only set plan on its entry or preheader block.");
173cfca06d7SDimitry Andric   Plan = ParentPlan;
174cfca06d7SDimitry Andric }
175cfca06d7SDimitry Andric 
176044eb2f6SDimitry Andric /// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
getExitingBasicBlock() const177145449b1SDimitry Andric const VPBasicBlock *VPBlockBase::getExitingBasicBlock() const {
178044eb2f6SDimitry Andric   const VPBlockBase *Block = this;
179044eb2f6SDimitry Andric   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
180145449b1SDimitry Andric     Block = Region->getExiting();
181044eb2f6SDimitry Andric   return cast<VPBasicBlock>(Block);
182044eb2f6SDimitry Andric }
183044eb2f6SDimitry Andric 
getExitingBasicBlock()184145449b1SDimitry Andric VPBasicBlock *VPBlockBase::getExitingBasicBlock() {
185044eb2f6SDimitry Andric   VPBlockBase *Block = this;
186044eb2f6SDimitry Andric   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
187145449b1SDimitry Andric     Block = Region->getExiting();
188044eb2f6SDimitry Andric   return cast<VPBasicBlock>(Block);
189044eb2f6SDimitry Andric }
190044eb2f6SDimitry Andric 
getEnclosingBlockWithSuccessors()191044eb2f6SDimitry Andric VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {
192044eb2f6SDimitry Andric   if (!Successors.empty() || !Parent)
193044eb2f6SDimitry Andric     return this;
194145449b1SDimitry Andric   assert(Parent->getExiting() == this &&
195145449b1SDimitry Andric          "Block w/o successors not the exiting block of its parent.");
196044eb2f6SDimitry Andric   return Parent->getEnclosingBlockWithSuccessors();
197044eb2f6SDimitry Andric }
198044eb2f6SDimitry Andric 
getEnclosingBlockWithPredecessors()199044eb2f6SDimitry Andric VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() {
200044eb2f6SDimitry Andric   if (!Predecessors.empty() || !Parent)
201044eb2f6SDimitry Andric     return this;
202044eb2f6SDimitry Andric   assert(Parent->getEntry() == this &&
203044eb2f6SDimitry Andric          "Block w/o predecessors not the entry of its parent.");
204044eb2f6SDimitry Andric   return Parent->getEnclosingBlockWithPredecessors();
205044eb2f6SDimitry Andric }
206044eb2f6SDimitry Andric 
deleteCFG(VPBlockBase * Entry)207044eb2f6SDimitry Andric void VPBlockBase::deleteCFG(VPBlockBase *Entry) {
208e3b55780SDimitry Andric   for (VPBlockBase *Block : to_vector(vp_depth_first_shallow(Entry)))
209044eb2f6SDimitry Andric     delete Block;
210044eb2f6SDimitry Andric }
211044eb2f6SDimitry Andric 
getFirstNonPhi()212b60736ecSDimitry Andric VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() {
213b60736ecSDimitry Andric   iterator It = begin();
214344a3780SDimitry Andric   while (It != end() && It->isPhi())
215b60736ecSDimitry Andric     It++;
216b60736ecSDimitry Andric   return It;
217b60736ecSDimitry Andric }
218b60736ecSDimitry Andric 
VPTransformState(ElementCount VF,unsigned UF,LoopInfo * LI,DominatorTree * DT,IRBuilderBase & Builder,InnerLoopVectorizer * ILV,VPlan * Plan,LLVMContext & Ctx)219ac9a064cSDimitry Andric VPTransformState::VPTransformState(ElementCount VF, unsigned UF, LoopInfo *LI,
220ac9a064cSDimitry Andric                                    DominatorTree *DT, IRBuilderBase &Builder,
221ac9a064cSDimitry Andric                                    InnerLoopVectorizer *ILV, VPlan *Plan,
222ac9a064cSDimitry Andric                                    LLVMContext &Ctx)
223ac9a064cSDimitry Andric     : VF(VF), UF(UF), CFG(DT), LI(LI), Builder(Builder), ILV(ILV), Plan(Plan),
224ac9a064cSDimitry Andric       LVer(nullptr),
225ac9a064cSDimitry Andric       TypeAnalysis(Plan->getCanonicalIV()->getScalarType(), Ctx) {}
226ac9a064cSDimitry Andric 
get(VPValue * Def,const VPIteration & Instance)227b60736ecSDimitry Andric Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) {
2287fa27ce4SDimitry Andric   if (Def->isLiveIn())
229b60736ecSDimitry Andric     return Def->getLiveInIRValue();
230b60736ecSDimitry Andric 
231344a3780SDimitry Andric   if (hasScalarValue(Def, Instance)) {
232344a3780SDimitry Andric     return Data
233344a3780SDimitry Andric         .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)];
234344a3780SDimitry Andric   }
235ac9a064cSDimitry Andric   if (!Instance.Lane.isFirstLane() &&
236ac9a064cSDimitry Andric       vputils::isUniformAfterVectorization(Def) &&
237ac9a064cSDimitry Andric       hasScalarValue(Def, {Instance.Part, VPLane::getFirstLane()})) {
238ac9a064cSDimitry Andric     return Data.PerPartScalars[Def][Instance.Part][0];
239ac9a064cSDimitry Andric   }
240b60736ecSDimitry Andric 
241344a3780SDimitry Andric   assert(hasVectorValue(Def, Instance.Part));
242b60736ecSDimitry Andric   auto *VecPart = Data.PerPartOutput[Def][Instance.Part];
243b60736ecSDimitry Andric   if (!VecPart->getType()->isVectorTy()) {
244344a3780SDimitry Andric     assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar");
245b60736ecSDimitry Andric     return VecPart;
246b60736ecSDimitry Andric   }
247b60736ecSDimitry Andric   // TODO: Cache created scalar values.
248344a3780SDimitry Andric   Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF);
249344a3780SDimitry Andric   auto *Extract = Builder.CreateExtractElement(VecPart, Lane);
250344a3780SDimitry Andric   // set(Def, Extract, Instance);
251344a3780SDimitry Andric   return Extract;
252b60736ecSDimitry Andric }
253b1c73532SDimitry Andric 
get(VPValue * Def,unsigned Part,bool NeedsScalar)254ac9a064cSDimitry Andric Value *VPTransformState::get(VPValue *Def, unsigned Part, bool NeedsScalar) {
255ac9a064cSDimitry Andric   if (NeedsScalar) {
256ac9a064cSDimitry Andric     assert((VF.isScalar() || Def->isLiveIn() || hasVectorValue(Def, Part) ||
257ac9a064cSDimitry Andric             !vputils::onlyFirstLaneUsed(Def) ||
258ac9a064cSDimitry Andric             (hasScalarValue(Def, VPIteration(Part, 0)) &&
259ac9a064cSDimitry Andric              Data.PerPartScalars[Def][Part].size() == 1)) &&
260ac9a064cSDimitry Andric            "Trying to access a single scalar per part but has multiple scalars "
261ac9a064cSDimitry Andric            "per part.");
262ac9a064cSDimitry Andric     return get(Def, VPIteration(Part, 0));
263ac9a064cSDimitry Andric   }
264ac9a064cSDimitry Andric 
265b1c73532SDimitry Andric   // If Values have been set for this Def return the one relevant for \p Part.
266b1c73532SDimitry Andric   if (hasVectorValue(Def, Part))
267b1c73532SDimitry Andric     return Data.PerPartOutput[Def][Part];
268b1c73532SDimitry Andric 
269b1c73532SDimitry Andric   auto GetBroadcastInstrs = [this, Def](Value *V) {
270b1c73532SDimitry Andric     bool SafeToHoist = Def->isDefinedOutsideVectorRegions();
271b1c73532SDimitry Andric     if (VF.isScalar())
272b1c73532SDimitry Andric       return V;
273b1c73532SDimitry Andric     // Place the code for broadcasting invariant variables in the new preheader.
274b1c73532SDimitry Andric     IRBuilder<>::InsertPointGuard Guard(Builder);
275b1c73532SDimitry Andric     if (SafeToHoist) {
276b1c73532SDimitry Andric       BasicBlock *LoopVectorPreHeader = CFG.VPBB2IRBB[cast<VPBasicBlock>(
277b1c73532SDimitry Andric           Plan->getVectorLoopRegion()->getSinglePredecessor())];
278b1c73532SDimitry Andric       if (LoopVectorPreHeader)
279b1c73532SDimitry Andric         Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
280b1c73532SDimitry Andric     }
281b1c73532SDimitry Andric 
282b1c73532SDimitry Andric     // Place the code for broadcasting invariant variables in the new preheader.
283b1c73532SDimitry Andric     // Broadcast the scalar into all locations in the vector.
284b1c73532SDimitry Andric     Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
285b1c73532SDimitry Andric 
286b1c73532SDimitry Andric     return Shuf;
287b1c73532SDimitry Andric   };
288b1c73532SDimitry Andric 
289b1c73532SDimitry Andric   if (!hasScalarValue(Def, {Part, 0})) {
290b1c73532SDimitry Andric     assert(Def->isLiveIn() && "expected a live-in");
291b1c73532SDimitry Andric     if (Part != 0)
292b1c73532SDimitry Andric       return get(Def, 0);
293b1c73532SDimitry Andric     Value *IRV = Def->getLiveInIRValue();
294b1c73532SDimitry Andric     Value *B = GetBroadcastInstrs(IRV);
295b1c73532SDimitry Andric     set(Def, B, Part);
296b1c73532SDimitry Andric     return B;
297b1c73532SDimitry Andric   }
298b1c73532SDimitry Andric 
299b1c73532SDimitry Andric   Value *ScalarValue = get(Def, {Part, 0});
300b1c73532SDimitry Andric   // If we aren't vectorizing, we can just copy the scalar map values over
301b1c73532SDimitry Andric   // to the vector map.
302b1c73532SDimitry Andric   if (VF.isScalar()) {
303b1c73532SDimitry Andric     set(Def, ScalarValue, Part);
304b1c73532SDimitry Andric     return ScalarValue;
305b1c73532SDimitry Andric   }
306b1c73532SDimitry Andric 
307b1c73532SDimitry Andric   bool IsUniform = vputils::isUniformAfterVectorization(Def);
308b1c73532SDimitry Andric 
309b1c73532SDimitry Andric   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
310b1c73532SDimitry Andric   // Check if there is a scalar value for the selected lane.
311b1c73532SDimitry Andric   if (!hasScalarValue(Def, {Part, LastLane})) {
312b1c73532SDimitry Andric     // At the moment, VPWidenIntOrFpInductionRecipes, VPScalarIVStepsRecipes and
313b1c73532SDimitry Andric     // VPExpandSCEVRecipes can also be uniform.
314b1c73532SDimitry Andric     assert((isa<VPWidenIntOrFpInductionRecipe>(Def->getDefiningRecipe()) ||
315b1c73532SDimitry Andric             isa<VPScalarIVStepsRecipe>(Def->getDefiningRecipe()) ||
316b1c73532SDimitry Andric             isa<VPExpandSCEVRecipe>(Def->getDefiningRecipe())) &&
317b1c73532SDimitry Andric            "unexpected recipe found to be invariant");
318b1c73532SDimitry Andric     IsUniform = true;
319b1c73532SDimitry Andric     LastLane = 0;
320b1c73532SDimitry Andric   }
321b1c73532SDimitry Andric 
322b1c73532SDimitry Andric   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
323b1c73532SDimitry Andric   // Set the insert point after the last scalarized instruction or after the
324b1c73532SDimitry Andric   // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
325b1c73532SDimitry Andric   // will directly follow the scalar definitions.
326b1c73532SDimitry Andric   auto OldIP = Builder.saveIP();
327b1c73532SDimitry Andric   auto NewIP =
328b1c73532SDimitry Andric       isa<PHINode>(LastInst)
329b1c73532SDimitry Andric           ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
330b1c73532SDimitry Andric           : std::next(BasicBlock::iterator(LastInst));
331b1c73532SDimitry Andric   Builder.SetInsertPoint(&*NewIP);
332b1c73532SDimitry Andric 
333b1c73532SDimitry Andric   // However, if we are vectorizing, we need to construct the vector values.
334b1c73532SDimitry Andric   // If the value is known to be uniform after vectorization, we can just
335b1c73532SDimitry Andric   // broadcast the scalar value corresponding to lane zero for each unroll
336b1c73532SDimitry Andric   // iteration. Otherwise, we construct the vector values using
337b1c73532SDimitry Andric   // insertelement instructions. Since the resulting vectors are stored in
338b1c73532SDimitry Andric   // State, we will only generate the insertelements once.
339b1c73532SDimitry Andric   Value *VectorValue = nullptr;
340b1c73532SDimitry Andric   if (IsUniform) {
341b1c73532SDimitry Andric     VectorValue = GetBroadcastInstrs(ScalarValue);
342b1c73532SDimitry Andric     set(Def, VectorValue, Part);
343b1c73532SDimitry Andric   } else {
344b1c73532SDimitry Andric     // Initialize packing with insertelements to start from undef.
345b1c73532SDimitry Andric     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
346b1c73532SDimitry Andric     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
347b1c73532SDimitry Andric     set(Def, Undef, Part);
348b1c73532SDimitry Andric     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
349b1c73532SDimitry Andric       packScalarIntoVectorValue(Def, {Part, Lane});
350b1c73532SDimitry Andric     VectorValue = get(Def, Part);
351b1c73532SDimitry Andric   }
352b1c73532SDimitry Andric   Builder.restoreIP(OldIP);
353b1c73532SDimitry Andric   return VectorValue;
354b1c73532SDimitry Andric }
355b1c73532SDimitry Andric 
getPreheaderBBFor(VPRecipeBase * R)356145449b1SDimitry Andric BasicBlock *VPTransformState::CFGState::getPreheaderBBFor(VPRecipeBase *R) {
357145449b1SDimitry Andric   VPRegionBlock *LoopRegion = R->getParent()->getEnclosingLoopRegion();
358145449b1SDimitry Andric   return VPBB2IRBB[LoopRegion->getPreheaderVPBB()];
359145449b1SDimitry Andric }
360145449b1SDimitry Andric 
addNewMetadata(Instruction * To,const Instruction * Orig)361145449b1SDimitry Andric void VPTransformState::addNewMetadata(Instruction *To,
362145449b1SDimitry Andric                                       const Instruction *Orig) {
363145449b1SDimitry Andric   // If the loop was versioned with memchecks, add the corresponding no-alias
364145449b1SDimitry Andric   // metadata.
365145449b1SDimitry Andric   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
366145449b1SDimitry Andric     LVer->annotateInstWithNoAlias(To, Orig);
367145449b1SDimitry Andric }
368145449b1SDimitry Andric 
addMetadata(Value * To,Instruction * From)369ac9a064cSDimitry Andric void VPTransformState::addMetadata(Value *To, Instruction *From) {
3707fa27ce4SDimitry Andric   // No source instruction to transfer metadata from?
3717fa27ce4SDimitry Andric   if (!From)
3727fa27ce4SDimitry Andric     return;
3737fa27ce4SDimitry Andric 
374ac9a064cSDimitry Andric   if (Instruction *ToI = dyn_cast<Instruction>(To)) {
375ac9a064cSDimitry Andric     propagateMetadata(ToI, From);
376ac9a064cSDimitry Andric     addNewMetadata(ToI, From);
377145449b1SDimitry Andric   }
378145449b1SDimitry Andric }
379145449b1SDimitry Andric 
setDebugLocFrom(DebugLoc DL)380b1c73532SDimitry Andric void VPTransformState::setDebugLocFrom(DebugLoc DL) {
381b1c73532SDimitry Andric   const DILocation *DIL = DL;
382145449b1SDimitry Andric   // When a FSDiscriminator is enabled, we don't need to add the multiply
383145449b1SDimitry Andric   // factors to the discriminators.
384b1c73532SDimitry Andric   if (DIL &&
385b1c73532SDimitry Andric       Builder.GetInsertBlock()
386b1c73532SDimitry Andric           ->getParent()
387b1c73532SDimitry Andric           ->shouldEmitDebugInfoForProfiling() &&
388b1c73532SDimitry Andric       !EnableFSDiscriminator) {
389145449b1SDimitry Andric     // FIXME: For scalable vectors, assume vscale=1.
390145449b1SDimitry Andric     auto NewDIL =
391145449b1SDimitry Andric         DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
392145449b1SDimitry Andric     if (NewDIL)
393145449b1SDimitry Andric       Builder.SetCurrentDebugLocation(*NewDIL);
394145449b1SDimitry Andric     else
395145449b1SDimitry Andric       LLVM_DEBUG(dbgs() << "Failed to create new discriminator: "
396145449b1SDimitry Andric                         << DIL->getFilename() << " Line: " << DIL->getLine());
397145449b1SDimitry Andric   } else
398145449b1SDimitry Andric     Builder.SetCurrentDebugLocation(DIL);
399145449b1SDimitry Andric }
400b60736ecSDimitry Andric 
packScalarIntoVectorValue(VPValue * Def,const VPIteration & Instance)401b1c73532SDimitry Andric void VPTransformState::packScalarIntoVectorValue(VPValue *Def,
402b1c73532SDimitry Andric                                                  const VPIteration &Instance) {
403b1c73532SDimitry Andric   Value *ScalarInst = get(Def, Instance);
404b1c73532SDimitry Andric   Value *VectorValue = get(Def, Instance.Part);
405b1c73532SDimitry Andric   VectorValue = Builder.CreateInsertElement(
406b1c73532SDimitry Andric       VectorValue, ScalarInst, Instance.Lane.getAsRuntimeExpr(Builder, VF));
407b1c73532SDimitry Andric   set(Def, VectorValue, Instance.Part);
408b1c73532SDimitry Andric }
409b1c73532SDimitry Andric 
410044eb2f6SDimitry Andric BasicBlock *
createEmptyBasicBlock(VPTransformState::CFGState & CFG)411044eb2f6SDimitry Andric VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
412044eb2f6SDimitry Andric   // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
413044eb2f6SDimitry Andric   // Pred stands for Predessor. Prev stands for Previous - last visited/created.
414044eb2f6SDimitry Andric   BasicBlock *PrevBB = CFG.PrevBB;
415044eb2f6SDimitry Andric   BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
416145449b1SDimitry Andric                                          PrevBB->getParent(), CFG.ExitBB);
417eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
418044eb2f6SDimitry Andric 
419044eb2f6SDimitry Andric   // Hook up the new basic block to its predecessors.
420044eb2f6SDimitry Andric   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
421145449b1SDimitry Andric     VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock();
422145449b1SDimitry Andric     auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors();
423044eb2f6SDimitry Andric     BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
424d8e91e46SDimitry Andric 
425044eb2f6SDimitry Andric     assert(PredBB && "Predecessor basic-block not found building successor.");
426044eb2f6SDimitry Andric     auto *PredBBTerminator = PredBB->getTerminator();
427eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
428145449b1SDimitry Andric 
429145449b1SDimitry Andric     auto *TermBr = dyn_cast<BranchInst>(PredBBTerminator);
430044eb2f6SDimitry Andric     if (isa<UnreachableInst>(PredBBTerminator)) {
431044eb2f6SDimitry Andric       assert(PredVPSuccessors.size() == 1 &&
432044eb2f6SDimitry Andric              "Predecessor ending w/o branch must have single successor.");
433145449b1SDimitry Andric       DebugLoc DL = PredBBTerminator->getDebugLoc();
434044eb2f6SDimitry Andric       PredBBTerminator->eraseFromParent();
435145449b1SDimitry Andric       auto *Br = BranchInst::Create(NewBB, PredBB);
436145449b1SDimitry Andric       Br->setDebugLoc(DL);
437145449b1SDimitry Andric     } else if (TermBr && !TermBr->isConditional()) {
438145449b1SDimitry Andric       TermBr->setSuccessor(0, NewBB);
439044eb2f6SDimitry Andric     } else {
440145449b1SDimitry Andric       // Set each forward successor here when it is created, excluding
441145449b1SDimitry Andric       // backedges. A backward successor is set when the branch is created.
442044eb2f6SDimitry Andric       unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
443145449b1SDimitry Andric       assert(!TermBr->getSuccessor(idx) &&
444044eb2f6SDimitry Andric              "Trying to reset an existing successor block.");
445145449b1SDimitry Andric       TermBr->setSuccessor(idx, NewBB);
446044eb2f6SDimitry Andric     }
447ac9a064cSDimitry Andric     CFG.DTU.applyUpdates({{DominatorTree::Insert, PredBB, NewBB}});
448044eb2f6SDimitry Andric   }
449044eb2f6SDimitry Andric   return NewBB;
450044eb2f6SDimitry Andric }
451044eb2f6SDimitry Andric 
execute(VPTransformState * State)452ac9a064cSDimitry Andric void VPIRBasicBlock::execute(VPTransformState *State) {
453ac9a064cSDimitry Andric   assert(getHierarchicalSuccessors().size() <= 2 &&
454ac9a064cSDimitry Andric          "VPIRBasicBlock can have at most two successors at the moment!");
455ac9a064cSDimitry Andric   State->Builder.SetInsertPoint(getIRBasicBlock()->getTerminator());
456ac9a064cSDimitry Andric   executeRecipes(State, getIRBasicBlock());
457ac9a064cSDimitry Andric   if (getSingleSuccessor()) {
458ac9a064cSDimitry Andric     assert(isa<UnreachableInst>(getIRBasicBlock()->getTerminator()));
459ac9a064cSDimitry Andric     auto *Br = State->Builder.CreateBr(getIRBasicBlock());
460ac9a064cSDimitry Andric     Br->setOperand(0, nullptr);
461ac9a064cSDimitry Andric     getIRBasicBlock()->getTerminator()->eraseFromParent();
462ac9a064cSDimitry Andric   }
463ac9a064cSDimitry Andric 
464ac9a064cSDimitry Andric   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
465ac9a064cSDimitry Andric     VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock();
466ac9a064cSDimitry Andric     BasicBlock *PredBB = State->CFG.VPBB2IRBB[PredVPBB];
467ac9a064cSDimitry Andric     assert(PredBB && "Predecessor basic-block not found building successor.");
468ac9a064cSDimitry Andric     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
469ac9a064cSDimitry Andric 
470ac9a064cSDimitry Andric     auto *PredBBTerminator = PredBB->getTerminator();
471ac9a064cSDimitry Andric     auto *TermBr = cast<BranchInst>(PredBBTerminator);
472ac9a064cSDimitry Andric     // Set each forward successor here when it is created, excluding
473ac9a064cSDimitry Andric     // backedges. A backward successor is set when the branch is created.
474ac9a064cSDimitry Andric     const auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors();
475ac9a064cSDimitry Andric     unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
476ac9a064cSDimitry Andric     assert(!TermBr->getSuccessor(idx) &&
477ac9a064cSDimitry Andric            "Trying to reset an existing successor block.");
478ac9a064cSDimitry Andric     TermBr->setSuccessor(idx, IRBB);
479ac9a064cSDimitry Andric     State->CFG.DTU.applyUpdates({{DominatorTree::Insert, PredBB, IRBB}});
480ac9a064cSDimitry Andric   }
481ac9a064cSDimitry Andric }
482ac9a064cSDimitry Andric 
execute(VPTransformState * State)483044eb2f6SDimitry Andric void VPBasicBlock::execute(VPTransformState *State) {
484344a3780SDimitry Andric   bool Replica = State->Instance && !State->Instance->isFirstIteration();
485044eb2f6SDimitry Andric   VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
486044eb2f6SDimitry Andric   VPBlockBase *SingleHPred = nullptr;
487044eb2f6SDimitry Andric   BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
488044eb2f6SDimitry Andric 
489145449b1SDimitry Andric   auto IsLoopRegion = [](VPBlockBase *BB) {
490145449b1SDimitry Andric     auto *R = dyn_cast<VPRegionBlock>(BB);
491145449b1SDimitry Andric     return R && !R->isReplicator();
492145449b1SDimitry Andric   };
493145449b1SDimitry Andric 
494ac9a064cSDimitry Andric   // 1. Create an IR basic block.
495ac9a064cSDimitry Andric   if (PrevVPBB && /* A */
496044eb2f6SDimitry Andric       !((SingleHPred = getSingleHierarchicalPredecessor()) &&
497145449b1SDimitry Andric         SingleHPred->getExitingBasicBlock() == PrevVPBB &&
498145449b1SDimitry Andric         PrevVPBB->getSingleHierarchicalSuccessor() &&
499145449b1SDimitry Andric         (SingleHPred->getParent() == getEnclosingLoopRegion() &&
500145449b1SDimitry Andric          !IsLoopRegion(SingleHPred))) &&         /* B */
501044eb2f6SDimitry Andric       !(Replica && getPredecessors().empty())) { /* C */
502145449b1SDimitry Andric     // The last IR basic block is reused, as an optimization, in three cases:
503145449b1SDimitry Andric     // A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null;
504145449b1SDimitry Andric     // B. when the current VPBB has a single (hierarchical) predecessor which
505145449b1SDimitry Andric     //    is PrevVPBB and the latter has a single (hierarchical) successor which
506145449b1SDimitry Andric     //    both are in the same non-replicator region; and
507145449b1SDimitry Andric     // C. when the current VPBB is an entry of a region replica - where PrevVPBB
508145449b1SDimitry Andric     //    is the exiting VPBB of this region from a previous instance, or the
509145449b1SDimitry Andric     //    predecessor of this region.
510145449b1SDimitry Andric 
511044eb2f6SDimitry Andric     NewBB = createEmptyBasicBlock(State->CFG);
512044eb2f6SDimitry Andric     State->Builder.SetInsertPoint(NewBB);
513044eb2f6SDimitry Andric     // Temporarily terminate with unreachable until CFG is rewired.
514044eb2f6SDimitry Andric     UnreachableInst *Terminator = State->Builder.CreateUnreachable();
515145449b1SDimitry Andric     // Register NewBB in its loop. In innermost loops its the same for all
516145449b1SDimitry Andric     // BB's.
517145449b1SDimitry Andric     if (State->CurrentVectorLoop)
518145449b1SDimitry Andric       State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI);
519044eb2f6SDimitry Andric     State->Builder.SetInsertPoint(Terminator);
520044eb2f6SDimitry Andric     State->CFG.PrevBB = NewBB;
521044eb2f6SDimitry Andric   }
522044eb2f6SDimitry Andric 
523044eb2f6SDimitry Andric   // 2. Fill the IR basic block with IR instructions.
524ac9a064cSDimitry Andric   executeRecipes(State, NewBB);
525044eb2f6SDimitry Andric }
526044eb2f6SDimitry Andric 
dropAllReferences(VPValue * NewValue)527b60736ecSDimitry Andric void VPBasicBlock::dropAllReferences(VPValue *NewValue) {
528b60736ecSDimitry Andric   for (VPRecipeBase &R : Recipes) {
529b60736ecSDimitry Andric     for (auto *Def : R.definedValues())
530b60736ecSDimitry Andric       Def->replaceAllUsesWith(NewValue);
531b60736ecSDimitry Andric 
532344a3780SDimitry Andric     for (unsigned I = 0, E = R.getNumOperands(); I != E; I++)
533344a3780SDimitry Andric       R.setOperand(I, NewValue);
534b60736ecSDimitry Andric   }
535b60736ecSDimitry Andric }
536b60736ecSDimitry Andric 
executeRecipes(VPTransformState * State,BasicBlock * BB)537ac9a064cSDimitry Andric void VPBasicBlock::executeRecipes(VPTransformState *State, BasicBlock *BB) {
538ac9a064cSDimitry Andric   LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
539ac9a064cSDimitry Andric                     << " in BB:" << BB->getName() << '\n');
540ac9a064cSDimitry Andric 
541ac9a064cSDimitry Andric   State->CFG.VPBB2IRBB[this] = BB;
542ac9a064cSDimitry Andric   State->CFG.PrevVPBB = this;
543ac9a064cSDimitry Andric 
544ac9a064cSDimitry Andric   for (VPRecipeBase &Recipe : Recipes)
545ac9a064cSDimitry Andric     Recipe.execute(*State);
546ac9a064cSDimitry Andric 
547ac9a064cSDimitry Andric   LLVM_DEBUG(dbgs() << "LV: filled BB:" << *BB);
548ac9a064cSDimitry Andric }
549ac9a064cSDimitry Andric 
splitAt(iterator SplitAt)550344a3780SDimitry Andric VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) {
551344a3780SDimitry Andric   assert((SplitAt == end() || SplitAt->getParent() == this) &&
552344a3780SDimitry Andric          "can only split at a position in the same block");
553344a3780SDimitry Andric 
55477fc4c14SDimitry Andric   SmallVector<VPBlockBase *, 2> Succs(successors());
555344a3780SDimitry Andric   // First, disconnect the current block from its successors.
556344a3780SDimitry Andric   for (VPBlockBase *Succ : Succs)
557344a3780SDimitry Andric     VPBlockUtils::disconnectBlocks(this, Succ);
558344a3780SDimitry Andric 
559344a3780SDimitry Andric   // Create new empty block after the block to split.
560344a3780SDimitry Andric   auto *SplitBlock = new VPBasicBlock(getName() + ".split");
561344a3780SDimitry Andric   VPBlockUtils::insertBlockAfter(SplitBlock, this);
562344a3780SDimitry Andric 
563344a3780SDimitry Andric   // Add successors for block to split to new block.
564344a3780SDimitry Andric   for (VPBlockBase *Succ : Succs)
565344a3780SDimitry Andric     VPBlockUtils::connectBlocks(SplitBlock, Succ);
566344a3780SDimitry Andric 
567344a3780SDimitry Andric   // Finally, move the recipes starting at SplitAt to new block.
568344a3780SDimitry Andric   for (VPRecipeBase &ToMove :
569344a3780SDimitry Andric        make_early_inc_range(make_range(SplitAt, this->end())))
570344a3780SDimitry Andric     ToMove.moveBefore(*SplitBlock, SplitBlock->end());
571344a3780SDimitry Andric 
572344a3780SDimitry Andric   return SplitBlock;
573344a3780SDimitry Andric }
574344a3780SDimitry Andric 
getEnclosingLoopRegion()575145449b1SDimitry Andric VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() {
576145449b1SDimitry Andric   VPRegionBlock *P = getParent();
577145449b1SDimitry Andric   if (P && P->isReplicator()) {
578145449b1SDimitry Andric     P = P->getParent();
579145449b1SDimitry Andric     assert(!cast<VPRegionBlock>(P)->isReplicator() &&
580145449b1SDimitry Andric            "unexpected nested replicate regions");
581145449b1SDimitry Andric   }
582145449b1SDimitry Andric   return P;
583145449b1SDimitry Andric }
584145449b1SDimitry Andric 
hasConditionalTerminator(const VPBasicBlock * VPBB)585145449b1SDimitry Andric static bool hasConditionalTerminator(const VPBasicBlock *VPBB) {
586145449b1SDimitry Andric   if (VPBB->empty()) {
587145449b1SDimitry Andric     assert(
588145449b1SDimitry Andric         VPBB->getNumSuccessors() < 2 &&
589145449b1SDimitry Andric         "block with multiple successors doesn't have a recipe as terminator");
590145449b1SDimitry Andric     return false;
591145449b1SDimitry Andric   }
592145449b1SDimitry Andric 
593145449b1SDimitry Andric   const VPRecipeBase *R = &VPBB->back();
594ac9a064cSDimitry Andric   bool IsCondBranch = isa<VPBranchOnMaskRecipe>(R) ||
595ac9a064cSDimitry Andric                       match(R, m_BranchOnCond(m_VPValue())) ||
596ac9a064cSDimitry Andric                       match(R, m_BranchOnCount(m_VPValue(), m_VPValue()));
597145449b1SDimitry Andric   (void)IsCondBranch;
598145449b1SDimitry Andric 
599ac9a064cSDimitry Andric   if (VPBB->getNumSuccessors() >= 2 ||
600ac9a064cSDimitry Andric       (VPBB->isExiting() && !VPBB->getParent()->isReplicator())) {
601145449b1SDimitry Andric     assert(IsCondBranch && "block with multiple successors not terminated by "
602145449b1SDimitry Andric                            "conditional branch recipe");
603145449b1SDimitry Andric 
604145449b1SDimitry Andric     return true;
605145449b1SDimitry Andric   }
606145449b1SDimitry Andric 
607145449b1SDimitry Andric   assert(
608145449b1SDimitry Andric       !IsCondBranch &&
609145449b1SDimitry Andric       "block with 0 or 1 successors terminated by conditional branch recipe");
610145449b1SDimitry Andric   return false;
611145449b1SDimitry Andric }
612145449b1SDimitry Andric 
getTerminator()613145449b1SDimitry Andric VPRecipeBase *VPBasicBlock::getTerminator() {
614145449b1SDimitry Andric   if (hasConditionalTerminator(this))
615145449b1SDimitry Andric     return &back();
616145449b1SDimitry Andric   return nullptr;
617145449b1SDimitry Andric }
618145449b1SDimitry Andric 
getTerminator() const619145449b1SDimitry Andric const VPRecipeBase *VPBasicBlock::getTerminator() const {
620145449b1SDimitry Andric   if (hasConditionalTerminator(this))
621145449b1SDimitry Andric     return &back();
622145449b1SDimitry Andric   return nullptr;
623145449b1SDimitry Andric }
624145449b1SDimitry Andric 
isExiting() const625145449b1SDimitry Andric bool VPBasicBlock::isExiting() const {
626ac9a064cSDimitry Andric   return getParent() && getParent()->getExitingBasicBlock() == this;
627145449b1SDimitry Andric }
628145449b1SDimitry Andric 
629344a3780SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
printSuccessors(raw_ostream & O,const Twine & Indent) const630344a3780SDimitry Andric void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const {
631344a3780SDimitry Andric   if (getSuccessors().empty()) {
632344a3780SDimitry Andric     O << Indent << "No successors\n";
633344a3780SDimitry Andric   } else {
634344a3780SDimitry Andric     O << Indent << "Successor(s): ";
635344a3780SDimitry Andric     ListSeparator LS;
636344a3780SDimitry Andric     for (auto *Succ : getSuccessors())
637344a3780SDimitry Andric       O << LS << Succ->getName();
638344a3780SDimitry Andric     O << '\n';
639344a3780SDimitry Andric   }
640344a3780SDimitry Andric }
641344a3780SDimitry Andric 
print(raw_ostream & O,const Twine & Indent,VPSlotTracker & SlotTracker) const642344a3780SDimitry Andric void VPBasicBlock::print(raw_ostream &O, const Twine &Indent,
643344a3780SDimitry Andric                          VPSlotTracker &SlotTracker) const {
644344a3780SDimitry Andric   O << Indent << getName() << ":\n";
645344a3780SDimitry Andric 
646344a3780SDimitry Andric   auto RecipeIndent = Indent + "  ";
647344a3780SDimitry Andric   for (const VPRecipeBase &Recipe : *this) {
648344a3780SDimitry Andric     Recipe.print(O, RecipeIndent, SlotTracker);
649344a3780SDimitry Andric     O << '\n';
650344a3780SDimitry Andric   }
651344a3780SDimitry Andric 
652344a3780SDimitry Andric   printSuccessors(O, Indent);
653344a3780SDimitry Andric }
654344a3780SDimitry Andric #endif
655344a3780SDimitry Andric 
656ac9a064cSDimitry Andric static std::pair<VPBlockBase *, VPBlockBase *> cloneFrom(VPBlockBase *Entry);
657ac9a064cSDimitry Andric 
658ac9a064cSDimitry Andric // Clone the CFG for all nodes reachable from \p Entry, this includes cloning
659ac9a064cSDimitry Andric // the blocks and their recipes. Operands of cloned recipes will NOT be updated.
660ac9a064cSDimitry Andric // Remapping of operands must be done separately. Returns a pair with the new
661ac9a064cSDimitry Andric // entry and exiting blocks of the cloned region. If \p Entry isn't part of a
662ac9a064cSDimitry Andric // region, return nullptr for the exiting block.
cloneFrom(VPBlockBase * Entry)663ac9a064cSDimitry Andric static std::pair<VPBlockBase *, VPBlockBase *> cloneFrom(VPBlockBase *Entry) {
664ac9a064cSDimitry Andric   DenseMap<VPBlockBase *, VPBlockBase *> Old2NewVPBlocks;
665ac9a064cSDimitry Andric   VPBlockBase *Exiting = nullptr;
666ac9a064cSDimitry Andric   bool InRegion = Entry->getParent();
667ac9a064cSDimitry Andric   // First, clone blocks reachable from Entry.
668ac9a064cSDimitry Andric   for (VPBlockBase *BB : vp_depth_first_shallow(Entry)) {
669ac9a064cSDimitry Andric     VPBlockBase *NewBB = BB->clone();
670ac9a064cSDimitry Andric     Old2NewVPBlocks[BB] = NewBB;
671ac9a064cSDimitry Andric     if (InRegion && BB->getNumSuccessors() == 0) {
672ac9a064cSDimitry Andric       assert(!Exiting && "Multiple exiting blocks?");
673ac9a064cSDimitry Andric       Exiting = BB;
674ac9a064cSDimitry Andric     }
675ac9a064cSDimitry Andric   }
676ac9a064cSDimitry Andric   assert((!InRegion || Exiting) && "regions must have a single exiting block");
677ac9a064cSDimitry Andric 
678ac9a064cSDimitry Andric   // Second, update the predecessors & successors of the cloned blocks.
679ac9a064cSDimitry Andric   for (VPBlockBase *BB : vp_depth_first_shallow(Entry)) {
680ac9a064cSDimitry Andric     VPBlockBase *NewBB = Old2NewVPBlocks[BB];
681ac9a064cSDimitry Andric     SmallVector<VPBlockBase *> NewPreds;
682ac9a064cSDimitry Andric     for (VPBlockBase *Pred : BB->getPredecessors()) {
683ac9a064cSDimitry Andric       NewPreds.push_back(Old2NewVPBlocks[Pred]);
684ac9a064cSDimitry Andric     }
685ac9a064cSDimitry Andric     NewBB->setPredecessors(NewPreds);
686ac9a064cSDimitry Andric     SmallVector<VPBlockBase *> NewSuccs;
687ac9a064cSDimitry Andric     for (VPBlockBase *Succ : BB->successors()) {
688ac9a064cSDimitry Andric       NewSuccs.push_back(Old2NewVPBlocks[Succ]);
689ac9a064cSDimitry Andric     }
690ac9a064cSDimitry Andric     NewBB->setSuccessors(NewSuccs);
691ac9a064cSDimitry Andric   }
692ac9a064cSDimitry Andric 
693ac9a064cSDimitry Andric #if !defined(NDEBUG)
694ac9a064cSDimitry Andric   // Verify that the order of predecessors and successors matches in the cloned
695ac9a064cSDimitry Andric   // version.
696ac9a064cSDimitry Andric   for (const auto &[OldBB, NewBB] :
697ac9a064cSDimitry Andric        zip(vp_depth_first_shallow(Entry),
698ac9a064cSDimitry Andric            vp_depth_first_shallow(Old2NewVPBlocks[Entry]))) {
699ac9a064cSDimitry Andric     for (const auto &[OldPred, NewPred] :
700ac9a064cSDimitry Andric          zip(OldBB->getPredecessors(), NewBB->getPredecessors()))
701ac9a064cSDimitry Andric       assert(NewPred == Old2NewVPBlocks[OldPred] && "Different predecessors");
702ac9a064cSDimitry Andric 
703ac9a064cSDimitry Andric     for (const auto &[OldSucc, NewSucc] :
704ac9a064cSDimitry Andric          zip(OldBB->successors(), NewBB->successors()))
705ac9a064cSDimitry Andric       assert(NewSucc == Old2NewVPBlocks[OldSucc] && "Different successors");
706ac9a064cSDimitry Andric   }
707ac9a064cSDimitry Andric #endif
708ac9a064cSDimitry Andric 
709ac9a064cSDimitry Andric   return std::make_pair(Old2NewVPBlocks[Entry],
710ac9a064cSDimitry Andric                         Exiting ? Old2NewVPBlocks[Exiting] : nullptr);
711ac9a064cSDimitry Andric }
712ac9a064cSDimitry Andric 
clone()713ac9a064cSDimitry Andric VPRegionBlock *VPRegionBlock::clone() {
714ac9a064cSDimitry Andric   const auto &[NewEntry, NewExiting] = cloneFrom(getEntry());
715ac9a064cSDimitry Andric   auto *NewRegion =
716ac9a064cSDimitry Andric       new VPRegionBlock(NewEntry, NewExiting, getName(), isReplicator());
717ac9a064cSDimitry Andric   for (VPBlockBase *Block : vp_depth_first_shallow(NewEntry))
718ac9a064cSDimitry Andric     Block->setParent(NewRegion);
719ac9a064cSDimitry Andric   return NewRegion;
720ac9a064cSDimitry Andric }
721ac9a064cSDimitry Andric 
dropAllReferences(VPValue * NewValue)722b60736ecSDimitry Andric void VPRegionBlock::dropAllReferences(VPValue *NewValue) {
723e3b55780SDimitry Andric   for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
724b60736ecSDimitry Andric     // Drop all references in VPBasicBlocks and replace all uses with
725b60736ecSDimitry Andric     // DummyValue.
726b60736ecSDimitry Andric     Block->dropAllReferences(NewValue);
727b60736ecSDimitry Andric }
728b60736ecSDimitry Andric 
execute(VPTransformState * State)729044eb2f6SDimitry Andric void VPRegionBlock::execute(VPTransformState *State) {
730e3b55780SDimitry Andric   ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>>
731e3b55780SDimitry Andric       RPOT(Entry);
732044eb2f6SDimitry Andric 
733044eb2f6SDimitry Andric   if (!isReplicator()) {
734145449b1SDimitry Andric     // Create and register the new vector loop.
735145449b1SDimitry Andric     Loop *PrevLoop = State->CurrentVectorLoop;
736145449b1SDimitry Andric     State->CurrentVectorLoop = State->LI->AllocateLoop();
737145449b1SDimitry Andric     BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()];
738145449b1SDimitry Andric     Loop *ParentLoop = State->LI->getLoopFor(VectorPH);
739145449b1SDimitry Andric 
740145449b1SDimitry Andric     // Insert the new loop into the loop nest and register the new basic blocks
741145449b1SDimitry Andric     // before calling any utilities such as SCEV that require valid LoopInfo.
742145449b1SDimitry Andric     if (ParentLoop)
743145449b1SDimitry Andric       ParentLoop->addChildLoop(State->CurrentVectorLoop);
744145449b1SDimitry Andric     else
745145449b1SDimitry Andric       State->LI->addTopLevelLoop(State->CurrentVectorLoop);
746145449b1SDimitry Andric 
747044eb2f6SDimitry Andric     // Visit the VPBlocks connected to "this", starting from it.
748044eb2f6SDimitry Andric     for (VPBlockBase *Block : RPOT) {
749eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
750044eb2f6SDimitry Andric       Block->execute(State);
751044eb2f6SDimitry Andric     }
752145449b1SDimitry Andric 
753145449b1SDimitry Andric     State->CurrentVectorLoop = PrevLoop;
754044eb2f6SDimitry Andric     return;
755044eb2f6SDimitry Andric   }
756044eb2f6SDimitry Andric 
757044eb2f6SDimitry Andric   assert(!State->Instance && "Replicating a Region with non-null instance.");
758044eb2f6SDimitry Andric 
759044eb2f6SDimitry Andric   // Enter replicating mode.
760344a3780SDimitry Andric   State->Instance = VPIteration(0, 0);
761044eb2f6SDimitry Andric 
762044eb2f6SDimitry Andric   for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
763044eb2f6SDimitry Andric     State->Instance->Part = Part;
764b60736ecSDimitry Andric     assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
765b60736ecSDimitry Andric     for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
766b60736ecSDimitry Andric          ++Lane) {
767344a3780SDimitry Andric       State->Instance->Lane = VPLane(Lane, VPLane::Kind::First);
768044eb2f6SDimitry Andric       // Visit the VPBlocks connected to \p this, starting from it.
769044eb2f6SDimitry Andric       for (VPBlockBase *Block : RPOT) {
770eb11fae6SDimitry Andric         LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
771044eb2f6SDimitry Andric         Block->execute(State);
772044eb2f6SDimitry Andric       }
773044eb2f6SDimitry Andric     }
774044eb2f6SDimitry Andric   }
775044eb2f6SDimitry Andric 
776044eb2f6SDimitry Andric   // Exit replicating mode.
777044eb2f6SDimitry Andric   State->Instance.reset();
778044eb2f6SDimitry Andric }
779044eb2f6SDimitry Andric 
cost(ElementCount VF,VPCostContext & Ctx)780ac9a064cSDimitry Andric InstructionCost VPBasicBlock::cost(ElementCount VF, VPCostContext &Ctx) {
781ac9a064cSDimitry Andric   InstructionCost Cost = 0;
782ac9a064cSDimitry Andric   for (VPRecipeBase &R : Recipes)
783ac9a064cSDimitry Andric     Cost += R.cost(VF, Ctx);
784ac9a064cSDimitry Andric   return Cost;
785ac9a064cSDimitry Andric }
786ac9a064cSDimitry Andric 
cost(ElementCount VF,VPCostContext & Ctx)787ac9a064cSDimitry Andric InstructionCost VPRegionBlock::cost(ElementCount VF, VPCostContext &Ctx) {
788ac9a064cSDimitry Andric   if (!isReplicator()) {
789ac9a064cSDimitry Andric     InstructionCost Cost = 0;
790ac9a064cSDimitry Andric     for (VPBlockBase *Block : vp_depth_first_shallow(getEntry()))
791ac9a064cSDimitry Andric       Cost += Block->cost(VF, Ctx);
792ac9a064cSDimitry Andric     InstructionCost BackedgeCost =
793ac9a064cSDimitry Andric         Ctx.TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
794ac9a064cSDimitry Andric     LLVM_DEBUG(dbgs() << "Cost of " << BackedgeCost << " for VF " << VF
795ac9a064cSDimitry Andric                       << ": vector loop backedge\n");
796ac9a064cSDimitry Andric     Cost += BackedgeCost;
797ac9a064cSDimitry Andric     return Cost;
798ac9a064cSDimitry Andric   }
799ac9a064cSDimitry Andric 
800ac9a064cSDimitry Andric   // Compute the cost of a replicate region. Replicating isn't supported for
801ac9a064cSDimitry Andric   // scalable vectors, return an invalid cost for them.
802ac9a064cSDimitry Andric   // TODO: Discard scalable VPlans with replicate recipes earlier after
803ac9a064cSDimitry Andric   // construction.
804ac9a064cSDimitry Andric   if (VF.isScalable())
805ac9a064cSDimitry Andric     return InstructionCost::getInvalid();
806ac9a064cSDimitry Andric 
807ac9a064cSDimitry Andric   // First compute the cost of the conditionally executed recipes, followed by
808ac9a064cSDimitry Andric   // account for the branching cost, except if the mask is a header mask or
809ac9a064cSDimitry Andric   // uniform condition.
810ac9a064cSDimitry Andric   using namespace llvm::VPlanPatternMatch;
811ac9a064cSDimitry Andric   VPBasicBlock *Then = cast<VPBasicBlock>(getEntry()->getSuccessors()[0]);
812ac9a064cSDimitry Andric   InstructionCost ThenCost = Then->cost(VF, Ctx);
813ac9a064cSDimitry Andric 
814ac9a064cSDimitry Andric   // For the scalar case, we may not always execute the original predicated
815ac9a064cSDimitry Andric   // block, Thus, scale the block's cost by the probability of executing it.
816ac9a064cSDimitry Andric   if (VF.isScalar())
817ac9a064cSDimitry Andric     return ThenCost / getReciprocalPredBlockProb();
818ac9a064cSDimitry Andric 
819ac9a064cSDimitry Andric   return ThenCost;
820ac9a064cSDimitry Andric }
821ac9a064cSDimitry Andric 
822344a3780SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
print(raw_ostream & O,const Twine & Indent,VPSlotTracker & SlotTracker) const823344a3780SDimitry Andric void VPRegionBlock::print(raw_ostream &O, const Twine &Indent,
824344a3780SDimitry Andric                           VPSlotTracker &SlotTracker) const {
825344a3780SDimitry Andric   O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {";
826344a3780SDimitry Andric   auto NewIndent = Indent + "  ";
827e3b55780SDimitry Andric   for (auto *BlockBase : vp_depth_first_shallow(Entry)) {
828344a3780SDimitry Andric     O << '\n';
829344a3780SDimitry Andric     BlockBase->print(O, NewIndent, SlotTracker);
830344a3780SDimitry Andric   }
831344a3780SDimitry Andric   O << Indent << "}\n";
832344a3780SDimitry Andric 
833344a3780SDimitry Andric   printSuccessors(O, Indent);
834344a3780SDimitry Andric }
835344a3780SDimitry Andric #endif
836344a3780SDimitry Andric 
~VPlan()837e3b55780SDimitry Andric VPlan::~VPlan() {
8387fa27ce4SDimitry Andric   for (auto &KV : LiveOuts)
8397fa27ce4SDimitry Andric     delete KV.second;
8407fa27ce4SDimitry Andric   LiveOuts.clear();
841e3b55780SDimitry Andric 
842e3b55780SDimitry Andric   if (Entry) {
843e3b55780SDimitry Andric     VPValue DummyValue;
844e3b55780SDimitry Andric     for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
845e3b55780SDimitry Andric       Block->dropAllReferences(&DummyValue);
846e3b55780SDimitry Andric 
847e3b55780SDimitry Andric     VPBlockBase::deleteCFG(Entry);
8487fa27ce4SDimitry Andric 
8497fa27ce4SDimitry Andric     Preheader->dropAllReferences(&DummyValue);
8507fa27ce4SDimitry Andric     delete Preheader;
851e3b55780SDimitry Andric   }
8527fa27ce4SDimitry Andric   for (VPValue *VPV : VPLiveInsToFree)
853e3b55780SDimitry Andric     delete VPV;
854e3b55780SDimitry Andric   if (BackedgeTakenCount)
855e3b55780SDimitry Andric     delete BackedgeTakenCount;
8567fa27ce4SDimitry Andric }
8577fa27ce4SDimitry Andric 
createInitialVPlan(const SCEV * TripCount,ScalarEvolution & SE,bool RequiresScalarEpilogueCheck,bool TailFolded,Loop * TheLoop)858ac9a064cSDimitry Andric VPlanPtr VPlan::createInitialVPlan(const SCEV *TripCount, ScalarEvolution &SE,
859ac9a064cSDimitry Andric                                    bool RequiresScalarEpilogueCheck,
860ac9a064cSDimitry Andric                                    bool TailFolded, Loop *TheLoop) {
861ac9a064cSDimitry Andric   VPIRBasicBlock *Entry = new VPIRBasicBlock(TheLoop->getLoopPreheader());
8627fa27ce4SDimitry Andric   VPBasicBlock *VecPreheader = new VPBasicBlock("vector.ph");
863ac9a064cSDimitry Andric   auto Plan = std::make_unique<VPlan>(Entry, VecPreheader);
8647fa27ce4SDimitry Andric   Plan->TripCount =
8657fa27ce4SDimitry Andric       vputils::getOrCreateVPValueForSCEVExpr(*Plan, TripCount, SE);
866ac9a064cSDimitry Andric   // Create VPRegionBlock, with empty header and latch blocks, to be filled
867ac9a064cSDimitry Andric   // during processing later.
868ac9a064cSDimitry Andric   VPBasicBlock *HeaderVPBB = new VPBasicBlock("vector.body");
869ac9a064cSDimitry Andric   VPBasicBlock *LatchVPBB = new VPBasicBlock("vector.latch");
870ac9a064cSDimitry Andric   VPBlockUtils::insertBlockAfter(LatchVPBB, HeaderVPBB);
871ac9a064cSDimitry Andric   auto *TopRegion = new VPRegionBlock(HeaderVPBB, LatchVPBB, "vector loop",
872ac9a064cSDimitry Andric                                       false /*isReplicator*/);
873ac9a064cSDimitry Andric 
874b1c73532SDimitry Andric   VPBlockUtils::insertBlockAfter(TopRegion, VecPreheader);
875b1c73532SDimitry Andric   VPBasicBlock *MiddleVPBB = new VPBasicBlock("middle.block");
876b1c73532SDimitry Andric   VPBlockUtils::insertBlockAfter(MiddleVPBB, TopRegion);
877ac9a064cSDimitry Andric 
878ac9a064cSDimitry Andric   VPBasicBlock *ScalarPH = new VPBasicBlock("scalar.ph");
879ac9a064cSDimitry Andric   if (!RequiresScalarEpilogueCheck) {
880ac9a064cSDimitry Andric     VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH);
881ac9a064cSDimitry Andric     return Plan;
882ac9a064cSDimitry Andric   }
883ac9a064cSDimitry Andric 
884ac9a064cSDimitry Andric   // If needed, add a check in the middle block to see if we have completed
885ac9a064cSDimitry Andric   // all of the iterations in the first vector loop.  Three cases:
886ac9a064cSDimitry Andric   // 1) If (N - N%VF) == N, then we *don't* need to run the remainder.
887ac9a064cSDimitry Andric   //    Thus if tail is to be folded, we know we don't need to run the
888ac9a064cSDimitry Andric   //    remainder and we can set the condition to true.
889ac9a064cSDimitry Andric   // 2) If we require a scalar epilogue, there is no conditional branch as
890ac9a064cSDimitry Andric   //    we unconditionally branch to the scalar preheader.  Do nothing.
891ac9a064cSDimitry Andric   // 3) Otherwise, construct a runtime check.
892ac9a064cSDimitry Andric   BasicBlock *IRExitBlock = TheLoop->getUniqueExitBlock();
893ac9a064cSDimitry Andric   auto *VPExitBlock = new VPIRBasicBlock(IRExitBlock);
894ac9a064cSDimitry Andric   // The connection order corresponds to the operands of the conditional branch.
895ac9a064cSDimitry Andric   VPBlockUtils::insertBlockAfter(VPExitBlock, MiddleVPBB);
896ac9a064cSDimitry Andric   VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH);
897ac9a064cSDimitry Andric 
898ac9a064cSDimitry Andric   auto *ScalarLatchTerm = TheLoop->getLoopLatch()->getTerminator();
899ac9a064cSDimitry Andric   // Here we use the same DebugLoc as the scalar loop latch terminator instead
900ac9a064cSDimitry Andric   // of the corresponding compare because they may have ended up with
901ac9a064cSDimitry Andric   // different line numbers and we want to avoid awkward line stepping while
902ac9a064cSDimitry Andric   // debugging. Eg. if the compare has got a line number inside the loop.
903ac9a064cSDimitry Andric   VPBuilder Builder(MiddleVPBB);
904ac9a064cSDimitry Andric   VPValue *Cmp =
905ac9a064cSDimitry Andric       TailFolded
906ac9a064cSDimitry Andric           ? Plan->getOrAddLiveIn(ConstantInt::getTrue(
907ac9a064cSDimitry Andric                 IntegerType::getInt1Ty(TripCount->getType()->getContext())))
908ac9a064cSDimitry Andric           : Builder.createICmp(CmpInst::ICMP_EQ, Plan->getTripCount(),
909ac9a064cSDimitry Andric                                &Plan->getVectorTripCount(),
910ac9a064cSDimitry Andric                                ScalarLatchTerm->getDebugLoc(), "cmp.n");
911ac9a064cSDimitry Andric   Builder.createNaryOp(VPInstruction::BranchOnCond, {Cmp},
912ac9a064cSDimitry Andric                        ScalarLatchTerm->getDebugLoc());
9137fa27ce4SDimitry Andric   return Plan;
914e3b55780SDimitry Andric }
915e3b55780SDimitry Andric 
prepareToExecute(Value * TripCountV,Value * VectorTripCountV,Value * CanonicalIVStartValue,VPTransformState & State)9166f8fc217SDimitry Andric void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV,
9176f8fc217SDimitry Andric                              Value *CanonicalIVStartValue,
918b1c73532SDimitry Andric                              VPTransformState &State) {
9196f8fc217SDimitry Andric   // Check if the backedge taken count is needed, and if so build it.
9206f8fc217SDimitry Andric   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
9216f8fc217SDimitry Andric     IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
9226f8fc217SDimitry Andric     auto *TCMO = Builder.CreateSub(TripCountV,
9236f8fc217SDimitry Andric                                    ConstantInt::get(TripCountV->getType(), 1),
9246f8fc217SDimitry Andric                                    "trip.count.minus.1");
925ac9a064cSDimitry Andric     BackedgeTakenCount->setUnderlyingValue(TCMO);
9266f8fc217SDimitry Andric   }
9276f8fc217SDimitry Andric 
928ac9a064cSDimitry Andric   VectorTripCount.setUnderlyingValue(VectorTripCountV);
9296f8fc217SDimitry Andric 
930b1c73532SDimitry Andric   IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
931b1c73532SDimitry Andric   // FIXME: Model VF * UF computation completely in VPlan.
932ac9a064cSDimitry Andric   VFxUF.setUnderlyingValue(
933ac9a064cSDimitry Andric       createStepForVF(Builder, TripCountV->getType(), State.VF, State.UF));
934b1c73532SDimitry Andric 
9356f8fc217SDimitry Andric   // When vectorizing the epilogue loop, the canonical induction start value
9366f8fc217SDimitry Andric   // needs to be changed from zero to the value after the main vector loop.
937e3b55780SDimitry Andric   // FIXME: Improve modeling for canonical IV start values in the epilogue loop.
9386f8fc217SDimitry Andric   if (CanonicalIVStartValue) {
939ac9a064cSDimitry Andric     VPValue *VPV = getOrAddLiveIn(CanonicalIVStartValue);
9406f8fc217SDimitry Andric     auto *IV = getCanonicalIV();
9416f8fc217SDimitry Andric     assert(all_of(IV->users(),
9426f8fc217SDimitry Andric                   [](const VPUser *U) {
943b1c73532SDimitry Andric                     return isa<VPScalarIVStepsRecipe>(U) ||
944ac9a064cSDimitry Andric                            isa<VPScalarCastRecipe>(U) ||
945b1c73532SDimitry Andric                            isa<VPDerivedIVRecipe>(U) ||
946b1c73532SDimitry Andric                            cast<VPInstruction>(U)->getOpcode() ==
947b1c73532SDimitry Andric                                Instruction::Add;
9486f8fc217SDimitry Andric                   }) &&
949b1c73532SDimitry Andric            "the canonical IV should only be used by its increment or "
9507fa27ce4SDimitry Andric            "ScalarIVSteps when resetting the start value");
9516f8fc217SDimitry Andric     IV->setOperand(0, VPV);
9526f8fc217SDimitry Andric   }
9536f8fc217SDimitry Andric }
9546f8fc217SDimitry Andric 
955ac9a064cSDimitry Andric /// Replace \p VPBB with a VPIRBasicBlock wrapping \p IRBB. All recipes from \p
956ac9a064cSDimitry Andric /// VPBB are moved to the newly created VPIRBasicBlock.  VPBB must have a single
957ac9a064cSDimitry Andric /// predecessor, which is rewired to the new VPIRBasicBlock. All successors of
958ac9a064cSDimitry Andric /// VPBB, if any, are rewired to the new VPIRBasicBlock.
replaceVPBBWithIRVPBB(VPBasicBlock * VPBB,BasicBlock * IRBB)959ac9a064cSDimitry Andric static void replaceVPBBWithIRVPBB(VPBasicBlock *VPBB, BasicBlock *IRBB) {
960ac9a064cSDimitry Andric   VPIRBasicBlock *IRMiddleVPBB = new VPIRBasicBlock(IRBB);
961ac9a064cSDimitry Andric   for (auto &R : make_early_inc_range(*VPBB))
962ac9a064cSDimitry Andric     R.moveBefore(*IRMiddleVPBB, IRMiddleVPBB->end());
963ac9a064cSDimitry Andric   VPBlockBase *PredVPBB = VPBB->getSinglePredecessor();
964ac9a064cSDimitry Andric   VPBlockUtils::disconnectBlocks(PredVPBB, VPBB);
965ac9a064cSDimitry Andric   VPBlockUtils::connectBlocks(PredVPBB, IRMiddleVPBB);
966ac9a064cSDimitry Andric   for (auto *Succ : to_vector(VPBB->getSuccessors())) {
967ac9a064cSDimitry Andric     VPBlockUtils::connectBlocks(IRMiddleVPBB, Succ);
968ac9a064cSDimitry Andric     VPBlockUtils::disconnectBlocks(VPBB, Succ);
969ac9a064cSDimitry Andric   }
970ac9a064cSDimitry Andric   delete VPBB;
971ac9a064cSDimitry Andric }
972ac9a064cSDimitry Andric 
973145449b1SDimitry Andric /// Generate the code inside the preheader and body of the vectorized loop.
974145449b1SDimitry Andric /// Assumes a single pre-header basic-block was created for this. Introduce
975145449b1SDimitry Andric /// additional basic-blocks as needed, and fill them all.
execute(VPTransformState * State)976044eb2f6SDimitry Andric void VPlan::execute(VPTransformState *State) {
977145449b1SDimitry Andric   // Initialize CFG state.
978044eb2f6SDimitry Andric   State->CFG.PrevVPBB = nullptr;
979145449b1SDimitry Andric   State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor();
980145449b1SDimitry Andric   BasicBlock *VectorPreHeader = State->CFG.PrevBB;
981145449b1SDimitry Andric   State->Builder.SetInsertPoint(VectorPreHeader->getTerminator());
982044eb2f6SDimitry Andric 
983ac9a064cSDimitry Andric   // Disconnect VectorPreHeader from ExitBB in both the CFG and DT.
984ac9a064cSDimitry Andric   cast<BranchInst>(VectorPreHeader->getTerminator())->setSuccessor(0, nullptr);
985ac9a064cSDimitry Andric   State->CFG.DTU.applyUpdates(
986ac9a064cSDimitry Andric       {{DominatorTree::Delete, VectorPreHeader, State->CFG.ExitBB}});
987ac9a064cSDimitry Andric 
988ac9a064cSDimitry Andric   // Replace regular VPBB's for the middle and scalar preheader blocks with
989ac9a064cSDimitry Andric   // VPIRBasicBlocks wrapping their IR blocks. The IR blocks are created during
990ac9a064cSDimitry Andric   // skeleton creation, so we can only create the VPIRBasicBlocks now during
991ac9a064cSDimitry Andric   // VPlan execution rather than earlier during VPlan construction.
992ac9a064cSDimitry Andric   BasicBlock *MiddleBB = State->CFG.ExitBB;
993ac9a064cSDimitry Andric   VPBasicBlock *MiddleVPBB =
994ac9a064cSDimitry Andric       cast<VPBasicBlock>(getVectorLoopRegion()->getSingleSuccessor());
995ac9a064cSDimitry Andric   // Find the VPBB for the scalar preheader, relying on the current structure
996ac9a064cSDimitry Andric   // when creating the middle block and its successrs: if there's a single
997ac9a064cSDimitry Andric   // predecessor, it must be the scalar preheader. Otherwise, the second
998ac9a064cSDimitry Andric   // successor is the scalar preheader.
999ac9a064cSDimitry Andric   BasicBlock *ScalarPh = MiddleBB->getSingleSuccessor();
1000ac9a064cSDimitry Andric   auto &MiddleSuccs = MiddleVPBB->getSuccessors();
1001ac9a064cSDimitry Andric   assert((MiddleSuccs.size() == 1 || MiddleSuccs.size() == 2) &&
1002ac9a064cSDimitry Andric          "middle block has unexpected successors");
1003ac9a064cSDimitry Andric   VPBasicBlock *ScalarPhVPBB = cast<VPBasicBlock>(
1004ac9a064cSDimitry Andric       MiddleSuccs.size() == 1 ? MiddleSuccs[0] : MiddleSuccs[1]);
1005ac9a064cSDimitry Andric   assert(!isa<VPIRBasicBlock>(ScalarPhVPBB) &&
1006ac9a064cSDimitry Andric          "scalar preheader cannot be wrapped already");
1007ac9a064cSDimitry Andric   replaceVPBBWithIRVPBB(ScalarPhVPBB, ScalarPh);
1008ac9a064cSDimitry Andric   replaceVPBBWithIRVPBB(MiddleVPBB, MiddleBB);
1009ac9a064cSDimitry Andric 
1010ac9a064cSDimitry Andric   // Disconnect the middle block from its single successor (the scalar loop
1011ac9a064cSDimitry Andric   // header) in both the CFG and DT. The branch will be recreated during VPlan
1012ac9a064cSDimitry Andric   // execution.
1013ac9a064cSDimitry Andric   auto *BrInst = new UnreachableInst(MiddleBB->getContext());
1014ac9a064cSDimitry Andric   BrInst->insertBefore(MiddleBB->getTerminator());
1015ac9a064cSDimitry Andric   MiddleBB->getTerminator()->eraseFromParent();
1016ac9a064cSDimitry Andric   State->CFG.DTU.applyUpdates({{DominatorTree::Delete, MiddleBB, ScalarPh}});
1017ac9a064cSDimitry Andric 
1018145449b1SDimitry Andric   // Generate code in the loop pre-header and body.
1019e3b55780SDimitry Andric   for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
1020044eb2f6SDimitry Andric     Block->execute(State);
1021044eb2f6SDimitry Andric 
1022145449b1SDimitry Andric   VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock();
1023145449b1SDimitry Andric   BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB];
1024044eb2f6SDimitry Andric 
10256f8fc217SDimitry Andric   // Fix the latch value of canonical, reduction and first-order recurrences
10266f8fc217SDimitry Andric   // phis in the vector loop.
1027145449b1SDimitry Andric   VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock();
10286f8fc217SDimitry Andric   for (VPRecipeBase &R : Header->phis()) {
10296f8fc217SDimitry Andric     // Skip phi-like recipes that generate their backedege values themselves.
1030145449b1SDimitry Andric     if (isa<VPWidenPHIRecipe>(&R))
10316f8fc217SDimitry Andric       continue;
10326f8fc217SDimitry Andric 
1033145449b1SDimitry Andric     if (isa<VPWidenPointerInductionRecipe>(&R) ||
1034145449b1SDimitry Andric         isa<VPWidenIntOrFpInductionRecipe>(&R)) {
1035145449b1SDimitry Andric       PHINode *Phi = nullptr;
1036145449b1SDimitry Andric       if (isa<VPWidenIntOrFpInductionRecipe>(&R)) {
1037145449b1SDimitry Andric         Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0));
1038145449b1SDimitry Andric       } else {
1039145449b1SDimitry Andric         auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R);
1040ac9a064cSDimitry Andric         assert(!WidenPhi->onlyScalarsGenerated(State->VF.isScalable()) &&
1041ac9a064cSDimitry Andric                "recipe generating only scalars should have been replaced");
1042145449b1SDimitry Andric         auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0));
1043145449b1SDimitry Andric         Phi = cast<PHINode>(GEP->getPointerOperand());
1044145449b1SDimitry Andric       }
1045145449b1SDimitry Andric 
1046145449b1SDimitry Andric       Phi->setIncomingBlock(1, VectorLatchBB);
1047145449b1SDimitry Andric 
1048145449b1SDimitry Andric       // Move the last step to the end of the latch block. This ensures
1049145449b1SDimitry Andric       // consistent placement of all induction updates.
1050145449b1SDimitry Andric       Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1));
1051145449b1SDimitry Andric       Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode());
1052145449b1SDimitry Andric       continue;
1053145449b1SDimitry Andric     }
1054145449b1SDimitry Andric 
10556f8fc217SDimitry Andric     auto *PhiR = cast<VPHeaderPHIRecipe>(&R);
10566f8fc217SDimitry Andric     // For  canonical IV, first-order recurrences and in-order reduction phis,
10576f8fc217SDimitry Andric     // only a single part is generated, which provides the last part from the
10586f8fc217SDimitry Andric     // previous iteration. For non-ordered reductions all UF parts are
10596f8fc217SDimitry Andric     // generated.
1060ac9a064cSDimitry Andric     bool SinglePartNeeded =
1061ac9a064cSDimitry Andric         isa<VPCanonicalIVPHIRecipe>(PhiR) ||
1062ac9a064cSDimitry Andric         isa<VPFirstOrderRecurrencePHIRecipe, VPEVLBasedIVPHIRecipe>(PhiR) ||
10631f917f69SDimitry Andric         (isa<VPReductionPHIRecipe>(PhiR) &&
10641f917f69SDimitry Andric          cast<VPReductionPHIRecipe>(PhiR)->isOrdered());
1065ac9a064cSDimitry Andric     bool NeedsScalar =
1066ac9a064cSDimitry Andric         isa<VPCanonicalIVPHIRecipe, VPEVLBasedIVPHIRecipe>(PhiR) ||
1067ac9a064cSDimitry Andric         (isa<VPReductionPHIRecipe>(PhiR) &&
1068ac9a064cSDimitry Andric          cast<VPReductionPHIRecipe>(PhiR)->isInLoop());
10696f8fc217SDimitry Andric     unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF;
10706f8fc217SDimitry Andric 
10716f8fc217SDimitry Andric     for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
1072ac9a064cSDimitry Andric       Value *Phi = State->get(PhiR, Part, NeedsScalar);
1073ac9a064cSDimitry Andric       Value *Val =
1074ac9a064cSDimitry Andric           State->get(PhiR->getBackedgeValue(),
1075ac9a064cSDimitry Andric                      SinglePartNeeded ? State->UF - 1 : Part, NeedsScalar);
10766f8fc217SDimitry Andric       cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB);
10776f8fc217SDimitry Andric     }
10786f8fc217SDimitry Andric   }
10796f8fc217SDimitry Andric 
1080ac9a064cSDimitry Andric   State->CFG.DTU.flush();
1081ac9a064cSDimitry Andric   assert(State->CFG.DTU.getDomTree().verify(
1082ac9a064cSDimitry Andric              DominatorTree::VerificationLevel::Fast) &&
1083ac9a064cSDimitry Andric          "DT not preserved correctly");
1084145449b1SDimitry Andric }
1085ac9a064cSDimitry Andric 
cost(ElementCount VF,VPCostContext & Ctx)1086ac9a064cSDimitry Andric InstructionCost VPlan::cost(ElementCount VF, VPCostContext &Ctx) {
1087ac9a064cSDimitry Andric   // For now only return the cost of the vector loop region, ignoring any other
1088ac9a064cSDimitry Andric   // blocks, like the preheader or middle blocks.
1089ac9a064cSDimitry Andric   return getVectorLoopRegion()->cost(VF, Ctx);
1090044eb2f6SDimitry Andric }
1091044eb2f6SDimitry Andric 
1092706b4fc4SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
printLiveIns(raw_ostream & O) const1093b1c73532SDimitry Andric void VPlan::printLiveIns(raw_ostream &O) const {
1094344a3780SDimitry Andric   VPSlotTracker SlotTracker(this);
1095344a3780SDimitry Andric 
1096b1c73532SDimitry Andric   if (VFxUF.getNumUsers() > 0) {
1097b1c73532SDimitry Andric     O << "\nLive-in ";
1098b1c73532SDimitry Andric     VFxUF.printAsOperand(O, SlotTracker);
1099b1c73532SDimitry Andric     O << " = VF * UF";
1100b1c73532SDimitry Andric   }
1101c0981da4SDimitry Andric 
11026f8fc217SDimitry Andric   if (VectorTripCount.getNumUsers() > 0) {
11036f8fc217SDimitry Andric     O << "\nLive-in ";
11046f8fc217SDimitry Andric     VectorTripCount.printAsOperand(O, SlotTracker);
11057fa27ce4SDimitry Andric     O << " = vector-trip-count";
11066f8fc217SDimitry Andric   }
11076f8fc217SDimitry Andric 
1108c0981da4SDimitry Andric   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
1109c0981da4SDimitry Andric     O << "\nLive-in ";
1110c0981da4SDimitry Andric     BackedgeTakenCount->printAsOperand(O, SlotTracker);
11117fa27ce4SDimitry Andric     O << " = backedge-taken count";
11127fa27ce4SDimitry Andric   }
11137fa27ce4SDimitry Andric 
11147fa27ce4SDimitry Andric   O << "\n";
11157fa27ce4SDimitry Andric   if (TripCount->isLiveIn())
11167fa27ce4SDimitry Andric     O << "Live-in ";
11177fa27ce4SDimitry Andric   TripCount->printAsOperand(O, SlotTracker);
11187fa27ce4SDimitry Andric   O << " = original trip-count";
11197fa27ce4SDimitry Andric   O << "\n";
1120b1c73532SDimitry Andric }
1121b1c73532SDimitry Andric 
1122b1c73532SDimitry Andric LLVM_DUMP_METHOD
print(raw_ostream & O) const1123b1c73532SDimitry Andric void VPlan::print(raw_ostream &O) const {
1124b1c73532SDimitry Andric   VPSlotTracker SlotTracker(this);
1125b1c73532SDimitry Andric 
1126b1c73532SDimitry Andric   O << "VPlan '" << getName() << "' {";
1127b1c73532SDimitry Andric 
1128b1c73532SDimitry Andric   printLiveIns(O);
11297fa27ce4SDimitry Andric 
11307fa27ce4SDimitry Andric   if (!getPreheader()->empty()) {
11317fa27ce4SDimitry Andric     O << "\n";
11327fa27ce4SDimitry Andric     getPreheader()->print(O, "", SlotTracker);
1133c0981da4SDimitry Andric   }
1134c0981da4SDimitry Andric 
1135e3b55780SDimitry Andric   for (const VPBlockBase *Block : vp_depth_first_shallow(getEntry())) {
1136344a3780SDimitry Andric     O << '\n';
1137344a3780SDimitry Andric     Block->print(O, "", SlotTracker);
1138344a3780SDimitry Andric   }
1139145449b1SDimitry Andric 
1140145449b1SDimitry Andric   if (!LiveOuts.empty())
1141145449b1SDimitry Andric     O << "\n";
1142e3b55780SDimitry Andric   for (const auto &KV : LiveOuts) {
11437fa27ce4SDimitry Andric     KV.second->print(O, SlotTracker);
1144145449b1SDimitry Andric   }
1145145449b1SDimitry Andric 
1146344a3780SDimitry Andric   O << "}\n";
1147344a3780SDimitry Andric }
1148344a3780SDimitry Andric 
getName() const1149e3b55780SDimitry Andric std::string VPlan::getName() const {
1150e3b55780SDimitry Andric   std::string Out;
1151e3b55780SDimitry Andric   raw_string_ostream RSO(Out);
1152e3b55780SDimitry Andric   RSO << Name << " for ";
1153e3b55780SDimitry Andric   if (!VFs.empty()) {
1154e3b55780SDimitry Andric     RSO << "VF={" << VFs[0];
1155e3b55780SDimitry Andric     for (ElementCount VF : drop_begin(VFs))
1156e3b55780SDimitry Andric       RSO << "," << VF;
1157e3b55780SDimitry Andric     RSO << "},";
1158e3b55780SDimitry Andric   }
1159e3b55780SDimitry Andric 
1160e3b55780SDimitry Andric   if (UFs.empty()) {
1161e3b55780SDimitry Andric     RSO << "UF>=1";
1162e3b55780SDimitry Andric   } else {
1163e3b55780SDimitry Andric     RSO << "UF={" << UFs[0];
1164e3b55780SDimitry Andric     for (unsigned UF : drop_begin(UFs))
1165e3b55780SDimitry Andric       RSO << "," << UF;
1166e3b55780SDimitry Andric     RSO << "}";
1167e3b55780SDimitry Andric   }
1168e3b55780SDimitry Andric 
1169e3b55780SDimitry Andric   return Out;
1170e3b55780SDimitry Andric }
1171e3b55780SDimitry Andric 
1172344a3780SDimitry Andric LLVM_DUMP_METHOD
printDOT(raw_ostream & O) const1173344a3780SDimitry Andric void VPlan::printDOT(raw_ostream &O) const {
1174344a3780SDimitry Andric   VPlanPrinter Printer(O, *this);
1175344a3780SDimitry Andric   Printer.dump();
1176344a3780SDimitry Andric }
1177344a3780SDimitry Andric 
1178344a3780SDimitry Andric LLVM_DUMP_METHOD
dump() const1179344a3780SDimitry Andric void VPlan::dump() const { print(dbgs()); }
1180706b4fc4SDimitry Andric #endif
1181706b4fc4SDimitry Andric 
addLiveOut(PHINode * PN,VPValue * V)1182145449b1SDimitry Andric void VPlan::addLiveOut(PHINode *PN, VPValue *V) {
1183145449b1SDimitry Andric   assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists");
1184145449b1SDimitry Andric   LiveOuts.insert({PN, new VPLiveOut(PN, V)});
1185145449b1SDimitry Andric }
1186145449b1SDimitry Andric 
remapOperands(VPBlockBase * Entry,VPBlockBase * NewEntry,DenseMap<VPValue *,VPValue * > & Old2NewVPValues)1187ac9a064cSDimitry Andric static void remapOperands(VPBlockBase *Entry, VPBlockBase *NewEntry,
1188ac9a064cSDimitry Andric                           DenseMap<VPValue *, VPValue *> &Old2NewVPValues) {
1189ac9a064cSDimitry Andric   // Update the operands of all cloned recipes starting at NewEntry. This
1190ac9a064cSDimitry Andric   // traverses all reachable blocks. This is done in two steps, to handle cycles
1191ac9a064cSDimitry Andric   // in PHI recipes.
1192ac9a064cSDimitry Andric   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>>
1193ac9a064cSDimitry Andric       OldDeepRPOT(Entry);
1194ac9a064cSDimitry Andric   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>>
1195ac9a064cSDimitry Andric       NewDeepRPOT(NewEntry);
1196ac9a064cSDimitry Andric   // First, collect all mappings from old to new VPValues defined by cloned
1197ac9a064cSDimitry Andric   // recipes.
1198ac9a064cSDimitry Andric   for (const auto &[OldBB, NewBB] :
1199ac9a064cSDimitry Andric        zip(VPBlockUtils::blocksOnly<VPBasicBlock>(OldDeepRPOT),
1200ac9a064cSDimitry Andric            VPBlockUtils::blocksOnly<VPBasicBlock>(NewDeepRPOT))) {
1201ac9a064cSDimitry Andric     assert(OldBB->getRecipeList().size() == NewBB->getRecipeList().size() &&
1202ac9a064cSDimitry Andric            "blocks must have the same number of recipes");
1203ac9a064cSDimitry Andric     for (const auto &[OldR, NewR] : zip(*OldBB, *NewBB)) {
1204ac9a064cSDimitry Andric       assert(OldR.getNumOperands() == NewR.getNumOperands() &&
1205ac9a064cSDimitry Andric              "recipes must have the same number of operands");
1206ac9a064cSDimitry Andric       assert(OldR.getNumDefinedValues() == NewR.getNumDefinedValues() &&
1207ac9a064cSDimitry Andric              "recipes must define the same number of operands");
1208ac9a064cSDimitry Andric       for (const auto &[OldV, NewV] :
1209ac9a064cSDimitry Andric            zip(OldR.definedValues(), NewR.definedValues()))
1210ac9a064cSDimitry Andric         Old2NewVPValues[OldV] = NewV;
1211044eb2f6SDimitry Andric     }
1212044eb2f6SDimitry Andric   }
1213ac9a064cSDimitry Andric 
1214ac9a064cSDimitry Andric   // Update all operands to use cloned VPValues.
1215ac9a064cSDimitry Andric   for (VPBasicBlock *NewBB :
1216ac9a064cSDimitry Andric        VPBlockUtils::blocksOnly<VPBasicBlock>(NewDeepRPOT)) {
1217ac9a064cSDimitry Andric     for (VPRecipeBase &NewR : *NewBB)
1218ac9a064cSDimitry Andric       for (unsigned I = 0, E = NewR.getNumOperands(); I != E; ++I) {
1219ac9a064cSDimitry Andric         VPValue *NewOp = Old2NewVPValues.lookup(NewR.getOperand(I));
1220ac9a064cSDimitry Andric         NewR.setOperand(I, NewOp);
1221044eb2f6SDimitry Andric       }
1222ac9a064cSDimitry Andric   }
1223ac9a064cSDimitry Andric }
1224ac9a064cSDimitry Andric 
duplicate()1225ac9a064cSDimitry Andric VPlan *VPlan::duplicate() {
1226ac9a064cSDimitry Andric   // Clone blocks.
1227ac9a064cSDimitry Andric   VPBasicBlock *NewPreheader = Preheader->clone();
1228ac9a064cSDimitry Andric   const auto &[NewEntry, __] = cloneFrom(Entry);
1229ac9a064cSDimitry Andric 
1230ac9a064cSDimitry Andric   // Create VPlan, clone live-ins and remap operands in the cloned blocks.
1231ac9a064cSDimitry Andric   auto *NewPlan = new VPlan(NewPreheader, cast<VPBasicBlock>(NewEntry));
1232ac9a064cSDimitry Andric   DenseMap<VPValue *, VPValue *> Old2NewVPValues;
1233ac9a064cSDimitry Andric   for (VPValue *OldLiveIn : VPLiveInsToFree) {
1234ac9a064cSDimitry Andric     Old2NewVPValues[OldLiveIn] =
1235ac9a064cSDimitry Andric         NewPlan->getOrAddLiveIn(OldLiveIn->getLiveInIRValue());
1236ac9a064cSDimitry Andric   }
1237ac9a064cSDimitry Andric   Old2NewVPValues[&VectorTripCount] = &NewPlan->VectorTripCount;
1238ac9a064cSDimitry Andric   Old2NewVPValues[&VFxUF] = &NewPlan->VFxUF;
1239ac9a064cSDimitry Andric   if (BackedgeTakenCount) {
1240ac9a064cSDimitry Andric     NewPlan->BackedgeTakenCount = new VPValue();
1241ac9a064cSDimitry Andric     Old2NewVPValues[BackedgeTakenCount] = NewPlan->BackedgeTakenCount;
1242ac9a064cSDimitry Andric   }
1243ac9a064cSDimitry Andric   assert(TripCount && "trip count must be set");
1244ac9a064cSDimitry Andric   if (TripCount->isLiveIn())
1245ac9a064cSDimitry Andric     Old2NewVPValues[TripCount] =
1246ac9a064cSDimitry Andric         NewPlan->getOrAddLiveIn(TripCount->getLiveInIRValue());
1247ac9a064cSDimitry Andric   // else NewTripCount will be created and inserted into Old2NewVPValues when
1248ac9a064cSDimitry Andric   // TripCount is cloned. In any case NewPlan->TripCount is updated below.
1249ac9a064cSDimitry Andric 
1250ac9a064cSDimitry Andric   remapOperands(Preheader, NewPreheader, Old2NewVPValues);
1251ac9a064cSDimitry Andric   remapOperands(Entry, NewEntry, Old2NewVPValues);
1252ac9a064cSDimitry Andric 
1253ac9a064cSDimitry Andric   // Clone live-outs.
1254ac9a064cSDimitry Andric   for (const auto &[_, LO] : LiveOuts)
1255ac9a064cSDimitry Andric     NewPlan->addLiveOut(LO->getPhi(), Old2NewVPValues[LO->getOperand(0)]);
1256ac9a064cSDimitry Andric 
1257ac9a064cSDimitry Andric   // Initialize remaining fields of cloned VPlan.
1258ac9a064cSDimitry Andric   NewPlan->VFs = VFs;
1259ac9a064cSDimitry Andric   NewPlan->UFs = UFs;
1260ac9a064cSDimitry Andric   // TODO: Adjust names.
1261ac9a064cSDimitry Andric   NewPlan->Name = Name;
1262ac9a064cSDimitry Andric   assert(Old2NewVPValues.contains(TripCount) &&
1263ac9a064cSDimitry Andric          "TripCount must have been added to Old2NewVPValues");
1264ac9a064cSDimitry Andric   NewPlan->TripCount = Old2NewVPValues[TripCount];
1265ac9a064cSDimitry Andric   return NewPlan;
1266044eb2f6SDimitry Andric }
1267044eb2f6SDimitry Andric 
1268344a3780SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1269145449b1SDimitry Andric 
getUID(const VPBlockBase * Block)1270c0981da4SDimitry Andric Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
1271044eb2f6SDimitry Andric   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
1272044eb2f6SDimitry Andric          Twine(getOrCreateBID(Block));
1273044eb2f6SDimitry Andric }
1274044eb2f6SDimitry Andric 
getOrCreateName(const VPBlockBase * Block)1275c0981da4SDimitry Andric Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
1276044eb2f6SDimitry Andric   const std::string &Name = Block->getName();
1277044eb2f6SDimitry Andric   if (!Name.empty())
1278044eb2f6SDimitry Andric     return Name;
1279044eb2f6SDimitry Andric   return "VPB" + Twine(getOrCreateBID(Block));
1280044eb2f6SDimitry Andric }
1281044eb2f6SDimitry Andric 
dump()1282044eb2f6SDimitry Andric void VPlanPrinter::dump() {
1283044eb2f6SDimitry Andric   Depth = 1;
1284044eb2f6SDimitry Andric   bumpIndent(0);
1285044eb2f6SDimitry Andric   OS << "digraph VPlan {\n";
1286044eb2f6SDimitry Andric   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
1287044eb2f6SDimitry Andric   if (!Plan.getName().empty())
1288044eb2f6SDimitry Andric     OS << "\\n" << DOT::EscapeString(Plan.getName());
1289b1c73532SDimitry Andric 
1290b1c73532SDimitry Andric   {
1291b1c73532SDimitry Andric     // Print live-ins.
1292b1c73532SDimitry Andric   std::string Str;
1293b1c73532SDimitry Andric   raw_string_ostream SS(Str);
1294b1c73532SDimitry Andric   Plan.printLiveIns(SS);
1295b1c73532SDimitry Andric   SmallVector<StringRef, 0> Lines;
1296b1c73532SDimitry Andric   StringRef(Str).rtrim('\n').split(Lines, "\n");
1297b1c73532SDimitry Andric   for (auto Line : Lines)
1298b1c73532SDimitry Andric     OS << DOT::EscapeString(Line.str()) << "\\n";
1299044eb2f6SDimitry Andric   }
1300b1c73532SDimitry Andric 
1301044eb2f6SDimitry Andric   OS << "\"]\n";
1302044eb2f6SDimitry Andric   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
1303044eb2f6SDimitry Andric   OS << "edge [fontname=Courier, fontsize=30]\n";
1304044eb2f6SDimitry Andric   OS << "compound=true\n";
1305044eb2f6SDimitry Andric 
13067fa27ce4SDimitry Andric   dumpBlock(Plan.getPreheader());
13077fa27ce4SDimitry Andric 
1308e3b55780SDimitry Andric   for (const VPBlockBase *Block : vp_depth_first_shallow(Plan.getEntry()))
1309044eb2f6SDimitry Andric     dumpBlock(Block);
1310044eb2f6SDimitry Andric 
1311044eb2f6SDimitry Andric   OS << "}\n";
1312044eb2f6SDimitry Andric }
1313044eb2f6SDimitry Andric 
dumpBlock(const VPBlockBase * Block)1314044eb2f6SDimitry Andric void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
1315044eb2f6SDimitry Andric   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
1316044eb2f6SDimitry Andric     dumpBasicBlock(BasicBlock);
1317044eb2f6SDimitry Andric   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1318044eb2f6SDimitry Andric     dumpRegion(Region);
1319044eb2f6SDimitry Andric   else
1320044eb2f6SDimitry Andric     llvm_unreachable("Unsupported kind of VPBlock.");
1321044eb2f6SDimitry Andric }
1322044eb2f6SDimitry Andric 
drawEdge(const VPBlockBase * From,const VPBlockBase * To,bool Hidden,const Twine & Label)1323044eb2f6SDimitry Andric void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
1324044eb2f6SDimitry Andric                             bool Hidden, const Twine &Label) {
1325044eb2f6SDimitry Andric   // Due to "dot" we print an edge between two regions as an edge between the
1326145449b1SDimitry Andric   // exiting basic block and the entry basic of the respective regions.
1327145449b1SDimitry Andric   const VPBlockBase *Tail = From->getExitingBasicBlock();
1328044eb2f6SDimitry Andric   const VPBlockBase *Head = To->getEntryBasicBlock();
1329044eb2f6SDimitry Andric   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
1330044eb2f6SDimitry Andric   OS << " [ label=\"" << Label << '\"';
1331044eb2f6SDimitry Andric   if (Tail != From)
1332044eb2f6SDimitry Andric     OS << " ltail=" << getUID(From);
1333044eb2f6SDimitry Andric   if (Head != To)
1334044eb2f6SDimitry Andric     OS << " lhead=" << getUID(To);
1335044eb2f6SDimitry Andric   if (Hidden)
1336044eb2f6SDimitry Andric     OS << "; splines=none";
1337044eb2f6SDimitry Andric   OS << "]\n";
1338044eb2f6SDimitry Andric }
1339044eb2f6SDimitry Andric 
dumpEdges(const VPBlockBase * Block)1340044eb2f6SDimitry Andric void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
1341044eb2f6SDimitry Andric   auto &Successors = Block->getSuccessors();
1342044eb2f6SDimitry Andric   if (Successors.size() == 1)
1343044eb2f6SDimitry Andric     drawEdge(Block, Successors.front(), false, "");
1344044eb2f6SDimitry Andric   else if (Successors.size() == 2) {
1345044eb2f6SDimitry Andric     drawEdge(Block, Successors.front(), false, "T");
1346044eb2f6SDimitry Andric     drawEdge(Block, Successors.back(), false, "F");
1347044eb2f6SDimitry Andric   } else {
1348044eb2f6SDimitry Andric     unsigned SuccessorNumber = 0;
1349044eb2f6SDimitry Andric     for (auto *Successor : Successors)
1350044eb2f6SDimitry Andric       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
1351044eb2f6SDimitry Andric   }
1352044eb2f6SDimitry Andric }
1353044eb2f6SDimitry Andric 
dumpBasicBlock(const VPBasicBlock * BasicBlock)1354044eb2f6SDimitry Andric void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
1355344a3780SDimitry Andric   // Implement dot-formatted dump by performing plain-text dump into the
1356344a3780SDimitry Andric   // temporary storage followed by some post-processing.
1357044eb2f6SDimitry Andric   OS << Indent << getUID(BasicBlock) << " [label =\n";
1358044eb2f6SDimitry Andric   bumpIndent(1);
1359344a3780SDimitry Andric   std::string Str;
1360344a3780SDimitry Andric   raw_string_ostream SS(Str);
1361344a3780SDimitry Andric   // Use no indentation as we need to wrap the lines into quotes ourselves.
1362344a3780SDimitry Andric   BasicBlock->print(SS, "", SlotTracker);
1363e6d15924SDimitry Andric 
1364344a3780SDimitry Andric   // We need to process each line of the output separately, so split
1365344a3780SDimitry Andric   // single-string plain-text dump.
1366344a3780SDimitry Andric   SmallVector<StringRef, 0> Lines;
1367344a3780SDimitry Andric   StringRef(Str).rtrim('\n').split(Lines, "\n");
1368e6d15924SDimitry Andric 
1369344a3780SDimitry Andric   auto EmitLine = [&](StringRef Line, StringRef Suffix) {
1370344a3780SDimitry Andric     OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;
1371344a3780SDimitry Andric   };
1372eb11fae6SDimitry Andric 
1373344a3780SDimitry Andric   // Don't need the "+" after the last line.
1374344a3780SDimitry Andric   for (auto Line : make_range(Lines.begin(), Lines.end() - 1))
1375344a3780SDimitry Andric     EmitLine(Line, " +\n");
1376344a3780SDimitry Andric   EmitLine(Lines.back(), "\n");
1377eb11fae6SDimitry Andric 
1378344a3780SDimitry Andric   bumpIndent(-1);
1379344a3780SDimitry Andric   OS << Indent << "]\n";
1380344a3780SDimitry Andric 
1381044eb2f6SDimitry Andric   dumpEdges(BasicBlock);
1382044eb2f6SDimitry Andric }
1383044eb2f6SDimitry Andric 
dumpRegion(const VPRegionBlock * Region)1384044eb2f6SDimitry Andric void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
1385044eb2f6SDimitry Andric   OS << Indent << "subgraph " << getUID(Region) << " {\n";
1386044eb2f6SDimitry Andric   bumpIndent(1);
1387044eb2f6SDimitry Andric   OS << Indent << "fontname=Courier\n"
1388044eb2f6SDimitry Andric      << Indent << "label=\""
1389044eb2f6SDimitry Andric      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
1390044eb2f6SDimitry Andric      << DOT::EscapeString(Region->getName()) << "\"\n";
1391044eb2f6SDimitry Andric   // Dump the blocks of the region.
1392044eb2f6SDimitry Andric   assert(Region->getEntry() && "Region contains no inner blocks.");
1393e3b55780SDimitry Andric   for (const VPBlockBase *Block : vp_depth_first_shallow(Region->getEntry()))
1394044eb2f6SDimitry Andric     dumpBlock(Block);
1395044eb2f6SDimitry Andric   bumpIndent(-1);
1396044eb2f6SDimitry Andric   OS << Indent << "}\n";
1397044eb2f6SDimitry Andric   dumpEdges(Region);
1398044eb2f6SDimitry Andric }
1399044eb2f6SDimitry Andric 
print(raw_ostream & O) const1400344a3780SDimitry Andric void VPlanIngredient::print(raw_ostream &O) const {
1401044eb2f6SDimitry Andric   if (auto *Inst = dyn_cast<Instruction>(V)) {
1402044eb2f6SDimitry Andric     if (!Inst->getType()->isVoidTy()) {
1403344a3780SDimitry Andric       Inst->printAsOperand(O, false);
1404344a3780SDimitry Andric       O << " = ";
1405044eb2f6SDimitry Andric     }
1406344a3780SDimitry Andric     O << Inst->getOpcodeName() << " ";
1407044eb2f6SDimitry Andric     unsigned E = Inst->getNumOperands();
1408044eb2f6SDimitry Andric     if (E > 0) {
1409344a3780SDimitry Andric       Inst->getOperand(0)->printAsOperand(O, false);
1410044eb2f6SDimitry Andric       for (unsigned I = 1; I < E; ++I)
1411344a3780SDimitry Andric         Inst->getOperand(I)->printAsOperand(O << ", ", false);
1412044eb2f6SDimitry Andric     }
1413044eb2f6SDimitry Andric   } else // !Inst
1414344a3780SDimitry Andric     V->printAsOperand(O, false);
1415044eb2f6SDimitry Andric }
1416044eb2f6SDimitry Andric 
1417344a3780SDimitry Andric #endif
1418b7eb8e35SDimitry Andric 
1419b7eb8e35SDimitry Andric template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
1420d8e91e46SDimitry Andric 
replaceAllUsesWith(VPValue * New)1421d8e91e46SDimitry Andric void VPValue::replaceAllUsesWith(VPValue *New) {
14224df029ccSDimitry Andric   replaceUsesWithIf(New, [](VPUser &, unsigned) { return true; });
1423d8e91e46SDimitry Andric }
1424d8e91e46SDimitry Andric 
replaceUsesWithIf(VPValue * New,llvm::function_ref<bool (VPUser & U,unsigned Idx)> ShouldReplace)1425b1c73532SDimitry Andric void VPValue::replaceUsesWithIf(
1426b1c73532SDimitry Andric     VPValue *New,
1427b1c73532SDimitry Andric     llvm::function_ref<bool(VPUser &U, unsigned Idx)> ShouldReplace) {
14284df029ccSDimitry Andric   // Note that this early exit is required for correctness; the implementation
14294df029ccSDimitry Andric   // below relies on the number of users for this VPValue to decrease, which
14304df029ccSDimitry Andric   // isn't the case if this == New.
1431312c0ed1SDimitry Andric   if (this == New)
1432312c0ed1SDimitry Andric     return;
14334df029ccSDimitry Andric 
1434b1c73532SDimitry Andric   for (unsigned J = 0; J < getNumUsers();) {
1435b1c73532SDimitry Andric     VPUser *User = Users[J];
1436312c0ed1SDimitry Andric     bool RemovedUser = false;
1437b1c73532SDimitry Andric     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) {
1438b1c73532SDimitry Andric       if (User->getOperand(I) != this || !ShouldReplace(*User, I))
1439b1c73532SDimitry Andric         continue;
1440b1c73532SDimitry Andric 
1441312c0ed1SDimitry Andric       RemovedUser = true;
1442b1c73532SDimitry Andric       User->setOperand(I, New);
1443b1c73532SDimitry Andric     }
1444b1c73532SDimitry Andric     // If a user got removed after updating the current user, the next user to
1445b1c73532SDimitry Andric     // update will be moved to the current position, so we only need to
1446b1c73532SDimitry Andric     // increment the index if the number of users did not change.
1447312c0ed1SDimitry Andric     if (!RemovedUser)
1448b1c73532SDimitry Andric       J++;
1449b1c73532SDimitry Andric   }
1450b1c73532SDimitry Andric }
1451b1c73532SDimitry Andric 
1452344a3780SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
printAsOperand(raw_ostream & OS,VPSlotTracker & Tracker) const1453cfca06d7SDimitry Andric void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
1454ac9a064cSDimitry Andric   OS << Tracker.getOrCreateName(this);
1455cfca06d7SDimitry Andric }
1456cfca06d7SDimitry Andric 
printOperands(raw_ostream & O,VPSlotTracker & SlotTracker) const1457b60736ecSDimitry Andric void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
1458b60736ecSDimitry Andric   interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {
1459b60736ecSDimitry Andric     Op->printAsOperand(O, SlotTracker);
1460b60736ecSDimitry Andric   });
1461b60736ecSDimitry Andric }
1462344a3780SDimitry Andric #endif
1463b60736ecSDimitry Andric 
visitRegion(VPRegionBlock * Region,Old2NewTy & Old2New,InterleavedAccessInfo & IAI)1464d8e91e46SDimitry Andric void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
1465d8e91e46SDimitry Andric                                           Old2NewTy &Old2New,
1466d8e91e46SDimitry Andric                                           InterleavedAccessInfo &IAI) {
1467e3b55780SDimitry Andric   ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>>
1468e3b55780SDimitry Andric       RPOT(Region->getEntry());
1469d8e91e46SDimitry Andric   for (VPBlockBase *Base : RPOT) {
1470d8e91e46SDimitry Andric     visitBlock(Base, Old2New, IAI);
1471d8e91e46SDimitry Andric   }
1472d8e91e46SDimitry Andric }
1473d8e91e46SDimitry Andric 
visitBlock(VPBlockBase * Block,Old2NewTy & Old2New,InterleavedAccessInfo & IAI)1474d8e91e46SDimitry Andric void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1475d8e91e46SDimitry Andric                                          InterleavedAccessInfo &IAI) {
1476d8e91e46SDimitry Andric   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
1477d8e91e46SDimitry Andric     for (VPRecipeBase &VPI : *VPBB) {
1478ac9a064cSDimitry Andric       if (isa<VPWidenPHIRecipe>(&VPI))
1479344a3780SDimitry Andric         continue;
1480d8e91e46SDimitry Andric       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
1481d8e91e46SDimitry Andric       auto *VPInst = cast<VPInstruction>(&VPI);
1482145449b1SDimitry Andric 
1483145449b1SDimitry Andric       auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue());
1484145449b1SDimitry Andric       if (!Inst)
1485145449b1SDimitry Andric         continue;
1486d8e91e46SDimitry Andric       auto *IG = IAI.getInterleaveGroup(Inst);
1487d8e91e46SDimitry Andric       if (!IG)
1488d8e91e46SDimitry Andric         continue;
1489d8e91e46SDimitry Andric 
1490d8e91e46SDimitry Andric       auto NewIGIter = Old2New.find(IG);
1491d8e91e46SDimitry Andric       if (NewIGIter == Old2New.end())
1492d8e91e46SDimitry Andric         Old2New[IG] = new InterleaveGroup<VPInstruction>(
1493cfca06d7SDimitry Andric             IG->getFactor(), IG->isReverse(), IG->getAlign());
1494d8e91e46SDimitry Andric 
1495d8e91e46SDimitry Andric       if (Inst == IG->getInsertPos())
1496d8e91e46SDimitry Andric         Old2New[IG]->setInsertPos(VPInst);
1497d8e91e46SDimitry Andric 
1498d8e91e46SDimitry Andric       InterleaveGroupMap[VPInst] = Old2New[IG];
1499d8e91e46SDimitry Andric       InterleaveGroupMap[VPInst]->insertMember(
1500d8e91e46SDimitry Andric           VPInst, IG->getIndex(Inst),
15011d5ae102SDimitry Andric           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
15021d5ae102SDimitry Andric                                 : IG->getFactor()));
1503d8e91e46SDimitry Andric     }
1504d8e91e46SDimitry Andric   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1505d8e91e46SDimitry Andric     visitRegion(Region, Old2New, IAI);
1506d8e91e46SDimitry Andric   else
1507d8e91e46SDimitry Andric     llvm_unreachable("Unsupported kind of VPBlock.");
1508d8e91e46SDimitry Andric }
1509d8e91e46SDimitry Andric 
VPInterleavedAccessInfo(VPlan & Plan,InterleavedAccessInfo & IAI)1510d8e91e46SDimitry Andric VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1511d8e91e46SDimitry Andric                                                  InterleavedAccessInfo &IAI) {
1512d8e91e46SDimitry Andric   Old2NewTy Old2New;
1513145449b1SDimitry Andric   visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI);
1514d8e91e46SDimitry Andric }
1515cfca06d7SDimitry Andric 
assignName(const VPValue * V)1516ac9a064cSDimitry Andric void VPSlotTracker::assignName(const VPValue *V) {
1517ac9a064cSDimitry Andric   assert(!VPValue2Name.contains(V) && "VPValue already has a name!");
1518ac9a064cSDimitry Andric   auto *UV = V->getUnderlyingValue();
1519ac9a064cSDimitry Andric   if (!UV) {
1520ac9a064cSDimitry Andric     VPValue2Name[V] = (Twine("vp<%") + Twine(NextSlot) + ">").str();
1521ac9a064cSDimitry Andric     NextSlot++;
1522ac9a064cSDimitry Andric     return;
1523cfca06d7SDimitry Andric   }
1524cfca06d7SDimitry Andric 
1525ac9a064cSDimitry Andric   // Use the name of the underlying Value, wrapped in "ir<>", and versioned by
1526ac9a064cSDimitry Andric   // appending ".Number" to the name if there are multiple uses.
1527ac9a064cSDimitry Andric   std::string Name;
1528ac9a064cSDimitry Andric   raw_string_ostream S(Name);
1529ac9a064cSDimitry Andric   UV->printAsOperand(S, false);
1530ac9a064cSDimitry Andric   assert(!Name.empty() && "Name cannot be empty.");
1531ac9a064cSDimitry Andric   std::string BaseName = (Twine("ir<") + Name + Twine(">")).str();
1532ac9a064cSDimitry Andric 
1533ac9a064cSDimitry Andric   // First assign the base name for V.
1534ac9a064cSDimitry Andric   const auto &[A, _] = VPValue2Name.insert({V, BaseName});
1535ac9a064cSDimitry Andric   // Integer or FP constants with different types will result in he same string
1536ac9a064cSDimitry Andric   // due to stripping types.
1537ac9a064cSDimitry Andric   if (V->isLiveIn() && isa<ConstantInt, ConstantFP>(UV))
1538ac9a064cSDimitry Andric     return;
1539ac9a064cSDimitry Andric 
1540ac9a064cSDimitry Andric   // If it is already used by C > 0 other VPValues, increase the version counter
1541ac9a064cSDimitry Andric   // C and use it for V.
1542ac9a064cSDimitry Andric   const auto &[C, UseInserted] = BaseName2Version.insert({BaseName, 0});
1543ac9a064cSDimitry Andric   if (!UseInserted) {
1544ac9a064cSDimitry Andric     C->second++;
1545ac9a064cSDimitry Andric     A->second = (BaseName + Twine(".") + Twine(C->second)).str();
1546ac9a064cSDimitry Andric   }
1547ac9a064cSDimitry Andric }
1548ac9a064cSDimitry Andric 
assignNames(const VPlan & Plan)1549ac9a064cSDimitry Andric void VPSlotTracker::assignNames(const VPlan &Plan) {
1550b1c73532SDimitry Andric   if (Plan.VFxUF.getNumUsers() > 0)
1551ac9a064cSDimitry Andric     assignName(&Plan.VFxUF);
1552ac9a064cSDimitry Andric   assignName(&Plan.VectorTripCount);
1553cfca06d7SDimitry Andric   if (Plan.BackedgeTakenCount)
1554ac9a064cSDimitry Andric     assignName(Plan.BackedgeTakenCount);
1555ac9a064cSDimitry Andric   for (VPValue *LI : Plan.VPLiveInsToFree)
1556ac9a064cSDimitry Andric     assignName(LI);
1557ac9a064cSDimitry Andric   assignNames(Plan.getPreheader());
1558cfca06d7SDimitry Andric 
1559e3b55780SDimitry Andric   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<const VPBlockBase *>>
1560e3b55780SDimitry Andric       RPOT(VPBlockDeepTraversalWrapper<const VPBlockBase *>(Plan.getEntry()));
1561344a3780SDimitry Andric   for (const VPBasicBlock *VPBB :
1562344a3780SDimitry Andric        VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT))
1563ac9a064cSDimitry Andric     assignNames(VPBB);
15647fa27ce4SDimitry Andric }
15657fa27ce4SDimitry Andric 
assignNames(const VPBasicBlock * VPBB)1566ac9a064cSDimitry Andric void VPSlotTracker::assignNames(const VPBasicBlock *VPBB) {
1567344a3780SDimitry Andric   for (const VPRecipeBase &Recipe : *VPBB)
1568344a3780SDimitry Andric     for (VPValue *Def : Recipe.definedValues())
1569ac9a064cSDimitry Andric       assignName(Def);
1570cfca06d7SDimitry Andric }
1571ecbca9f5SDimitry Andric 
getOrCreateName(const VPValue * V) const1572ac9a064cSDimitry Andric std::string VPSlotTracker::getOrCreateName(const VPValue *V) const {
1573ac9a064cSDimitry Andric   std::string Name = VPValue2Name.lookup(V);
1574ac9a064cSDimitry Andric   if (!Name.empty())
1575ac9a064cSDimitry Andric     return Name;
1576ac9a064cSDimitry Andric 
1577ac9a064cSDimitry Andric   // If no name was assigned, no VPlan was provided when creating the slot
1578ac9a064cSDimitry Andric   // tracker or it is not reachable from the provided VPlan. This can happen,
1579ac9a064cSDimitry Andric   // e.g. when trying to print a recipe that has not been inserted into a VPlan
1580ac9a064cSDimitry Andric   // in a debugger.
1581ac9a064cSDimitry Andric   // TODO: Update VPSlotTracker constructor to assign names to recipes &
1582ac9a064cSDimitry Andric   // VPValues not associated with a VPlan, instead of constructing names ad-hoc
1583ac9a064cSDimitry Andric   // here.
1584ac9a064cSDimitry Andric   const VPRecipeBase *DefR = V->getDefiningRecipe();
1585ac9a064cSDimitry Andric   (void)DefR;
1586ac9a064cSDimitry Andric   assert((!DefR || !DefR->getParent() || !DefR->getParent()->getPlan()) &&
1587ac9a064cSDimitry Andric          "VPValue defined by a recipe in a VPlan?");
1588ac9a064cSDimitry Andric 
1589ac9a064cSDimitry Andric   // Use the underlying value's name, if there is one.
1590ac9a064cSDimitry Andric   if (auto *UV = V->getUnderlyingValue()) {
1591ac9a064cSDimitry Andric     std::string Name;
1592ac9a064cSDimitry Andric     raw_string_ostream S(Name);
1593ac9a064cSDimitry Andric     UV->printAsOperand(S, false);
1594ac9a064cSDimitry Andric     return (Twine("ir<") + Name + ">").str();
1595145449b1SDimitry Andric   }
1596145449b1SDimitry Andric 
1597ac9a064cSDimitry Andric   return "<badref>";
1598ac9a064cSDimitry Andric }
1599ac9a064cSDimitry Andric 
onlyFirstLaneUsed(const VPValue * Def)1600ac9a064cSDimitry Andric bool vputils::onlyFirstLaneUsed(const VPValue *Def) {
1601b1c73532SDimitry Andric   return all_of(Def->users(),
1602ac9a064cSDimitry Andric                 [Def](const VPUser *U) { return U->onlyFirstLaneUsed(Def); });
1603ac9a064cSDimitry Andric }
1604ac9a064cSDimitry Andric 
onlyFirstPartUsed(const VPValue * Def)1605ac9a064cSDimitry Andric bool vputils::onlyFirstPartUsed(const VPValue *Def) {
1606ac9a064cSDimitry Andric   return all_of(Def->users(),
1607ac9a064cSDimitry Andric                 [Def](const VPUser *U) { return U->onlyFirstPartUsed(Def); });
1608b1c73532SDimitry Andric }
1609b1c73532SDimitry Andric 
getOrCreateVPValueForSCEVExpr(VPlan & Plan,const SCEV * Expr,ScalarEvolution & SE)1610145449b1SDimitry Andric VPValue *vputils::getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr,
1611145449b1SDimitry Andric                                                 ScalarEvolution &SE) {
16127fa27ce4SDimitry Andric   if (auto *Expanded = Plan.getSCEVExpansion(Expr))
16137fa27ce4SDimitry Andric     return Expanded;
16147fa27ce4SDimitry Andric   VPValue *Expanded = nullptr;
1615145449b1SDimitry Andric   if (auto *E = dyn_cast<SCEVConstant>(Expr))
1616ac9a064cSDimitry Andric     Expanded = Plan.getOrAddLiveIn(E->getValue());
16177fa27ce4SDimitry Andric   else if (auto *E = dyn_cast<SCEVUnknown>(Expr))
1618ac9a064cSDimitry Andric     Expanded = Plan.getOrAddLiveIn(E->getValue());
16197fa27ce4SDimitry Andric   else {
16207fa27ce4SDimitry Andric     Expanded = new VPExpandSCEVRecipe(Expr, SE);
16217fa27ce4SDimitry Andric     Plan.getPreheader()->appendRecipe(Expanded->getDefiningRecipe());
16227fa27ce4SDimitry Andric   }
16237fa27ce4SDimitry Andric   Plan.addSCEVExpansion(Expr, Expanded);
16247fa27ce4SDimitry Andric   return Expanded;
1625ecbca9f5SDimitry Andric }
1626ac9a064cSDimitry Andric 
isHeaderMask(VPValue * V,VPlan & Plan)1627ac9a064cSDimitry Andric bool vputils::isHeaderMask(VPValue *V, VPlan &Plan) {
1628ac9a064cSDimitry Andric   if (isa<VPActiveLaneMaskPHIRecipe>(V))
1629ac9a064cSDimitry Andric     return true;
1630ac9a064cSDimitry Andric 
1631ac9a064cSDimitry Andric   auto IsWideCanonicalIV = [](VPValue *A) {
1632ac9a064cSDimitry Andric     return isa<VPWidenCanonicalIVRecipe>(A) ||
1633ac9a064cSDimitry Andric            (isa<VPWidenIntOrFpInductionRecipe>(A) &&
1634ac9a064cSDimitry Andric             cast<VPWidenIntOrFpInductionRecipe>(A)->isCanonical());
1635ac9a064cSDimitry Andric   };
1636ac9a064cSDimitry Andric 
1637ac9a064cSDimitry Andric   VPValue *A, *B;
1638ac9a064cSDimitry Andric   if (match(V, m_ActiveLaneMask(m_VPValue(A), m_VPValue(B))))
1639ac9a064cSDimitry Andric     return B == Plan.getTripCount() &&
1640ac9a064cSDimitry Andric            (match(A, m_ScalarIVSteps(m_CanonicalIV(), m_SpecificInt(1))) ||
1641ac9a064cSDimitry Andric             IsWideCanonicalIV(A));
1642ac9a064cSDimitry Andric 
1643ac9a064cSDimitry Andric   return match(V, m_Binary<Instruction::ICmp>(m_VPValue(A), m_VPValue(B))) &&
1644ac9a064cSDimitry Andric          IsWideCanonicalIV(A) && B == Plan.getOrCreateBackedgeTakenCount();
1645ac9a064cSDimitry Andric }
1646