LLVM 20.0.0git
VPlanAnalysis.cpp
Go to the documentation of this file.
1//===- VPlanAnalysis.cpp - Various Analyses working on VPlan ----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "VPlanAnalysis.h"
10#include "VPlan.h"
11#include "VPlanCFG.h"
12#include "VPlanDominatorTree.h"
13#include "llvm/ADT/TypeSwitch.h"
15#include "llvm/IR/Instruction.h"
18
19using namespace llvm;
20
21#define DEBUG_TYPE "vplan"
22
23Type *VPTypeAnalysis::inferScalarTypeForRecipe(const VPBlendRecipe *R) {
24 Type *ResTy = inferScalarType(R->getIncomingValue(0));
25 for (unsigned I = 1, E = R->getNumIncomingValues(); I != E; ++I) {
26 VPValue *Inc = R->getIncomingValue(I);
27 assert(inferScalarType(Inc) == ResTy &&
28 "different types inferred for different incoming values");
29 CachedTypes[Inc] = ResTy;
30 }
31 return ResTy;
32}
33
34Type *VPTypeAnalysis::inferScalarTypeForRecipe(const VPInstruction *R) {
35 // Set the result type from the first operand, check if the types for all
36 // other operands match and cache them.
37 auto SetResultTyFromOp = [this, R]() {
38 Type *ResTy = inferScalarType(R->getOperand(0));
39 for (unsigned Op = 1; Op != R->getNumOperands(); ++Op) {
40 VPValue *OtherV = R->getOperand(Op);
41 assert(inferScalarType(OtherV) == ResTy &&
42 "different types inferred for different operands");
43 CachedTypes[OtherV] = ResTy;
44 }
45 return ResTy;
46 };
47
48 unsigned Opcode = R->getOpcode();
50 return SetResultTyFromOp();
51
52 switch (Opcode) {
53 case Instruction::Select: {
54 Type *ResTy = inferScalarType(R->getOperand(1));
55 VPValue *OtherV = R->getOperand(2);
56 assert(inferScalarType(OtherV) == ResTy &&
57 "different types inferred for different operands");
58 CachedTypes[OtherV] = ResTy;
59 return ResTy;
60 }
61 case Instruction::ICmp:
63 return inferScalarType(R->getOperand(1));
65 return Type::getIntNTy(Ctx, 32);
68 return SetResultTyFromOp();
70 Type *BaseTy = inferScalarType(R->getOperand(0));
71 if (auto *VecTy = dyn_cast<VectorType>(BaseTy))
72 return VecTy->getElementType();
73 return BaseTy;
74 }
76 return IntegerType::get(Ctx, 1);
78 // Return the type based on the pointer argument (i.e. first operand).
79 return inferScalarType(R->getOperand(0));
82 return Type::getVoidTy(Ctx);
83 default:
84 break;
85 }
86 // Type inference not implemented for opcode.
88 dbgs() << "LV: Found unhandled opcode for: ";
89 R->getVPSingleValue()->dump();
90 });
91 llvm_unreachable("Unhandled opcode!");
92}
93
94Type *VPTypeAnalysis::inferScalarTypeForRecipe(const VPWidenRecipe *R) {
95 unsigned Opcode = R->getOpcode();
96 if (Instruction::isBinaryOp(Opcode) || Instruction::isShift(Opcode) ||
98 Type *ResTy = inferScalarType(R->getOperand(0));
99 assert(ResTy == inferScalarType(R->getOperand(1)) &&
100 "types for both operands must match for binary op");
101 CachedTypes[R->getOperand(1)] = ResTy;
102 return ResTy;
103 }
104
105 switch (Opcode) {
106 case Instruction::ICmp:
107 case Instruction::FCmp:
108 return IntegerType::get(Ctx, 1);
109 case Instruction::FNeg:
110 case Instruction::Freeze:
111 return inferScalarType(R->getOperand(0));
112 default:
113 break;
114 }
115
116 // Type inference not implemented for opcode.
117 LLVM_DEBUG({
118 dbgs() << "LV: Found unhandled opcode for: ";
119 R->getVPSingleValue()->dump();
120 });
121 llvm_unreachable("Unhandled opcode!");
122}
123
124Type *VPTypeAnalysis::inferScalarTypeForRecipe(const VPWidenCallRecipe *R) {
125 auto &CI = *cast<CallInst>(R->getUnderlyingInstr());
126 return CI.getType();
127}
128
129Type *VPTypeAnalysis::inferScalarTypeForRecipe(const VPWidenMemoryRecipe *R) {
130 assert((isa<VPWidenLoadRecipe, VPWidenLoadEVLRecipe>(R)) &&
131 "Store recipes should not define any values");
132 return cast<LoadInst>(&R->getIngredient())->getType();
133}
134
135Type *VPTypeAnalysis::inferScalarTypeForRecipe(const VPWidenSelectRecipe *R) {
136 Type *ResTy = inferScalarType(R->getOperand(1));
137 VPValue *OtherV = R->getOperand(2);
138 assert(inferScalarType(OtherV) == ResTy &&
139 "different types inferred for different operands");
140 CachedTypes[OtherV] = ResTy;
141 return ResTy;
142}
143
144Type *VPTypeAnalysis::inferScalarTypeForRecipe(const VPReplicateRecipe *R) {
145 unsigned Opcode = R->getUnderlyingInstr()->getOpcode();
146
147 if (Instruction::isBinaryOp(Opcode) || Instruction::isShift(Opcode) ||
149 Type *ResTy = inferScalarType(R->getOperand(0));
150 assert(ResTy == inferScalarType(R->getOperand(1)) &&
151 "inferred types for operands of binary op don't match");
152 CachedTypes[R->getOperand(1)] = ResTy;
153 return ResTy;
154 }
155
156 if (Instruction::isCast(Opcode))
157 return R->getUnderlyingInstr()->getType();
158
159 switch (Opcode) {
160 case Instruction::Call: {
161 unsigned CallIdx = R->getNumOperands() - (R->isPredicated() ? 2 : 1);
162 return cast<Function>(R->getOperand(CallIdx)->getLiveInIRValue())
163 ->getReturnType();
164 }
165 case Instruction::Select: {
166 Type *ResTy = inferScalarType(R->getOperand(1));
167 assert(ResTy == inferScalarType(R->getOperand(2)) &&
168 "inferred types for operands of select op don't match");
169 CachedTypes[R->getOperand(2)] = ResTy;
170 return ResTy;
171 }
172 case Instruction::ICmp:
173 case Instruction::FCmp:
174 return IntegerType::get(Ctx, 1);
175 case Instruction::Alloca:
176 case Instruction::ExtractValue:
177 return R->getUnderlyingInstr()->getType();
178 case Instruction::Freeze:
179 case Instruction::FNeg:
180 case Instruction::GetElementPtr:
181 return inferScalarType(R->getOperand(0));
182 case Instruction::Load:
183 return cast<LoadInst>(R->getUnderlyingInstr())->getType();
184 case Instruction::Store:
185 // FIXME: VPReplicateRecipes with store opcodes still define a result
186 // VPValue, so we need to handle them here. Remove the code here once this
187 // is modeled accurately in VPlan.
188 return Type::getVoidTy(Ctx);
189 default:
190 break;
191 }
192 // Type inference not implemented for opcode.
193 LLVM_DEBUG({
194 dbgs() << "LV: Found unhandled opcode for: ";
195 R->getVPSingleValue()->dump();
196 });
197 llvm_unreachable("Unhandled opcode");
198}
199
201 if (Type *CachedTy = CachedTypes.lookup(V))
202 return CachedTy;
203
204 if (V->isLiveIn()) {
205 if (auto *IRValue = V->getLiveInIRValue())
206 return IRValue->getType();
207 // All VPValues without any underlying IR value (like the vector trip count
208 // or the backedge-taken count) have the same type as the canonical IV.
209 return CanonicalIVTy;
210 }
211
212 Type *ResultTy =
213 TypeSwitch<const VPRecipeBase *, Type *>(V->getDefiningRecipe())
217 VPScalarPHIRecipe>([this](const auto *R) {
218 // Handle header phi recipes, except VPWidenIntOrFpInduction
219 // which needs special handling due it being possibly truncated.
220 // TODO: consider inferring/caching type of siblings, e.g.,
221 // backedge value, here and in cases below.
222 return inferScalarType(R->getStartValue());
223 })
224 .Case<VPWidenIntOrFpInductionRecipe, VPDerivedIVRecipe>(
225 [](const auto *R) { return R->getScalarType(); })
229 [this](const VPRecipeBase *R) {
230 return inferScalarType(R->getOperand(0));
231 })
235 [this](const auto *R) { return inferScalarTypeForRecipe(R); })
236 .Case<VPWidenIntrinsicRecipe>([](const VPWidenIntrinsicRecipe *R) {
237 return R->getResultType();
238 })
239 .Case<VPInterleaveRecipe>([V](const VPInterleaveRecipe *R) {
240 // TODO: Use info from interleave group.
241 return V->getUnderlyingValue()->getType();
242 })
243 .Case<VPWidenCastRecipe>(
244 [](const VPWidenCastRecipe *R) { return R->getResultType(); })
245 .Case<VPScalarCastRecipe>(
246 [](const VPScalarCastRecipe *R) { return R->getResultType(); })
247 .Case<VPExpandSCEVRecipe>([](const VPExpandSCEVRecipe *R) {
248 return R->getSCEV()->getType();
249 })
250 .Case<VPReductionRecipe>([this](const auto *R) {
251 return inferScalarType(R->getChainOp());
252 });
253
254 assert(ResultTy && "could not infer type for the given VPValue");
255 CachedTypes[V] = ResultTy;
256 return ResultTy;
257}
258
260 VPlan &Plan, DenseSet<VPRecipeBase *> &EphRecipes) {
261 // First, collect seed recipes which are operands of assumes.
263 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
265 for (VPRecipeBase &R : *VPBB) {
266 auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
267 if (!RepR || !match(RepR->getUnderlyingInstr(),
268 PatternMatch::m_Intrinsic<Intrinsic::assume>()))
269 continue;
270 Worklist.push_back(RepR);
271 EphRecipes.insert(RepR);
272 }
273 }
274
275 // Process operands of candidates in worklist and add them to the set of
276 // ephemeral recipes, if they don't have side-effects and are only used by
277 // other ephemeral recipes.
278 while (!Worklist.empty()) {
279 VPRecipeBase *Cur = Worklist.pop_back_val();
280 for (VPValue *Op : Cur->operands()) {
281 auto *OpR = Op->getDefiningRecipe();
282 if (!OpR || OpR->mayHaveSideEffects() || EphRecipes.contains(OpR))
283 continue;
284 if (any_of(Op->users(), [EphRecipes](VPUser *U) {
285 auto *UR = dyn_cast<VPRecipeBase>(U);
286 return !UR || !EphRecipes.contains(UR);
287 }))
288 continue;
289 EphRecipes.insert(OpR);
290 Worklist.push_back(OpR);
291 }
292 }
293}
294
295template void DomTreeBuilder::Calculate<DominatorTreeBase<VPBlockBase, false>>(
297
299 const VPRecipeBase *B) {
300 if (A == B)
301 return false;
302
303 auto LocalComesBefore = [](const VPRecipeBase *A, const VPRecipeBase *B) {
304 for (auto &R : *A->getParent()) {
305 if (&R == A)
306 return true;
307 if (&R == B)
308 return false;
309 }
310 llvm_unreachable("recipe not found");
311 };
312 const VPBlockBase *ParentA = A->getParent();
313 const VPBlockBase *ParentB = B->getParent();
314 if (ParentA == ParentB)
315 return LocalComesBefore(A, B);
316
317#ifndef NDEBUG
318 auto GetReplicateRegion = [](VPRecipeBase *R) -> VPRegionBlock * {
319 auto *Region = dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
320 if (Region && Region->isReplicator()) {
321 assert(Region->getNumSuccessors() == 1 &&
322 Region->getNumPredecessors() == 1 && "Expected SESE region!");
323 assert(R->getParent()->size() == 1 &&
324 "A recipe in an original replicator region must be the only "
325 "recipe in its block");
326 return Region;
327 }
328 return nullptr;
329 };
330 assert(!GetReplicateRegion(const_cast<VPRecipeBase *>(A)) &&
331 "No replicate regions expected at this point");
332 assert(!GetReplicateRegion(const_cast<VPRecipeBase *>(B)) &&
333 "No replicate regions expected at this point");
334#endif
335 return Base::properlyDominates(ParentA, ParentB);
336}
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DEBUG(...)
Definition: Debug.h:106
Generic dominator tree construction - this file provides routines to construct immediate dominator in...
#define I(x, y, z)
Definition: MD5.cpp:58
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file implements the TypeSwitch template, which mimics a switch() statement whose cases are type ...
This file implements dominator tree analysis for a single level of a VPlan's H-CFG.
This file contains the declarations of the Vectorization Plan base classes:
This class represents an Operation in the Expression.
Implements a dense probed hash-table based set.
Definition: DenseSet.h:278
Core dominator tree base class.
bool properlyDominates(const DomTreeNodeBase< VPBlockBase > *A, const DomTreeNodeBase< VPBlockBase > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
bool isCast() const
Definition: Instruction.h:283
bool isBinaryOp() const
Definition: Instruction.h:279
bool isBitwiseLogicOp() const
Return true if this is and/or/xor.
Definition: Instruction.h:333
bool isShift() const
Definition: Instruction.h:282
bool isUnaryOp() const
Definition: Instruction.h:278
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:311
bool empty() const
Definition: SmallVector.h:81
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
This class implements a switch-like dispatch statement for a value of 'T' using dyn_cast functionalit...
Definition: TypeSwitch.h:87
TypeSwitch< T, ResultT > & Case(CallableT &&caseFn)
Add a case on the given type.
Definition: TypeSwitch.h:96
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
static Type * getVoidTy(LLVMContext &C)
A recipe for generating the active lane mask for the vector loop that is used to predicate the vector...
Definition: VPlan.h:3228
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition: VPlan.h:3470
A recipe for vectorizing a phi-node as a sequence of mask-based select instructions.
Definition: VPlan.h:2425
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition: VPlan.h:396
Canonical scalar induction phi of the vector loop.
Definition: VPlan.h:3162
bool properlyDominates(const VPRecipeBase *A, const VPRecipeBase *B)
Returns true if A properly dominates B.
A recipe for generating the phi node for the current index of elements, adjusted in accordance with E...
Definition: VPlan.h:3263
Recipe to expand a SCEV expression.
Definition: VPlan.h:3123
This is a concrete Recipe that models a single VPlan-level instruction.
Definition: VPlan.h:1197
@ FirstOrderRecurrenceSplice
Definition: VPlan.h:1203
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Definition: VPlan.h:2492
VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when control converges back from ...
Definition: VPlan.h:2838
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition: VPlan.h:720
A recipe for handling reduction phis.
Definition: VPlan.h:2366
A recipe to represent inloop reduction operations, performing a reduction on a vector operand into a ...
Definition: VPlan.h:2587
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition: VPlan.h:3657
const VPBlockBase * getEntry() const
Definition: VPlan.h:3696
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition: VPlan.h:2706
A recipe to compute the pointers for widened memory accesses of IndexTy in reverse order.
Definition: VPlan.h:1900
VPScalarCastRecipe is a recipe to create scalar cast instructions.
Definition: VPlan.h:1581
A recipe for handling phi nodes of integer and floating-point inductions, producing their scalar valu...
Definition: VPlan.h:3413
Recipe to generate a scalar PHI.
Definition: VPlan.h:2250
Type * inferScalarType(const VPValue *V)
Infer the type of V. Returns the scalar type of V.
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition: VPlanValue.h:200
operand_range operands()
Definition: VPlanValue.h:257
A recipe to compute the pointers for widened memory accesses of IndexTy.
Definition: VPlan.h:1953
A recipe for widening Call instructions using library calls.
Definition: VPlan.h:1716
A Recipe for widening the canonical induction variable of the vector loop.
Definition: VPlan.h:3308
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition: VPlan.h:1529
A recipe for widening operations with vector-predication intrinsics with explicit vector length (EVL)...
Definition: VPlan.h:1482
A recipe for handling GEP instructions.
Definition: VPlan.h:1851
A recipe for widening vector intrinsics.
Definition: VPlan.h:1627
A common base class for widening memory operations.
Definition: VPlan.h:2879
A recipe for handling phis that are widened in the vector loop.
Definition: VPlan.h:2289
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Definition: VPlan.h:1431
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition: VPlan.h:3761
VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition: VPlan.cpp:1084
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:213
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition: DenseSet.h:193
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
iterator_range< df_iterator< VPBlockDeepTraversalWrapper< VPBlockBase * > > > vp_depth_first_deep(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order while traversing t...
Definition: VPlanCFG.h:226
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1746
void collectEphemeralRecipesForVPlan(VPlan &Plan, DenseSet< VPRecipeBase * > &EphRecipes)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
DWARFExpression::Operation Op
A recipe for handling first-order recurrence phis.
Definition: VPlan.h:2334
A recipe for widening select instructions.
Definition: VPlan.h:1813