1//===- VPlanUtils.h - VPlan-related utilities -------------------*- 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#ifndef LLVM_TRANSFORMS_VECTORIZE_VPLANUTILS_H
10#define LLVM_TRANSFORMS_VECTORIZE_VPLANUTILS_H
11
12#include "VPlan.h"
13#include "llvm/Support/BlockFrequency.h"
14#include "llvm/Support/BranchProbability.h"
15#include "llvm/Support/Compiler.h"
16
17namespace llvm {
18class DominatorTree;
19class MemoryLocation;
20class ScalarEvolution;
21class SCEV;
22class SCEVNAryExpr;
23class PredicatedScalarEvolution;
24} // namespace llvm
25
26namespace llvm {
27
28namespace vputils {
29/// Returns true if only the first lane of \p Def is used.
30bool onlyFirstLaneUsed(const VPValue *Def);
31
32/// Returns true if only the first part of \p Def is used.
33bool onlyFirstPartUsed(const VPValue *Def);
34
35/// Returns true if only scalar values of \p Def are used by all users.
36bool onlyScalarValuesUsed(const VPValue *Def);
37
38/// Get or create a VPValue that corresponds to the expansion of \p Expr. If \p
39/// Expr is a SCEVConstant or SCEVUnknown, return a VPValue wrapping the live-in
40/// value. Otherwise return a VPExpandSCEVRecipe to expand \p Expr. If \p Plan's
41/// pre-header already contains a recipe expanding \p Expr, return it. If not,
42/// create a new one.
43VPValue *getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr);
44
45/// Return the SCEV expression for \p V. Returns SCEVCouldNotCompute if no
46/// SCEV expression could be constructed.
47LLVM_ABI_FOR_TEST const SCEV *
48getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE,
49 const Loop *L = nullptr);
50
51/// If the pointer operand \p Addr of a memory access is an affine AddRec
52/// w.r.t. \p L with a constant stride, return the stride in units of
53/// \p AccessTy. Otherwise return std::nullopt.
54std::optional<int64_t> getConstantStride(VPValue *Addr, Type *AccessTy,
55 PredicatedScalarEvolution &PSE,
56 const Loop *L);
57
58/// Returns true if \p Addr is an address SCEV that can be passed to
59/// TTI::getAddressComputationCost, i.e. the address SCEV is loop invariant, an
60/// affine AddRec (i.e. induction ), or an add expression of such operands or a
61/// sign-extended AddRec.
62bool isAddressSCEVForCost(const SCEV *Addr, ScalarEvolution &SE, const Loop *L);
63
64/// Returns true if \p VPV is a single scalar, either because it produces the
65/// same value for all lanes or only has its first lane used.
66bool isSingleScalar(const VPValue *VPV);
67
68/// Checks if \p V is uniform across all VF lanes and UF parts. It is considered
69/// as such if it is either loop invariant (defined outside the vector region)
70/// or its operands are known to be uniform across all VFs and UFs (e.g.
71/// VPDerivedIV or the canonical IV).
72LLVM_ABI_FOR_TEST bool isUniformAcrossVFsAndUFs(const VPValue *V);
73
74/// Return true if \p V is elementwise, i.e. none of the lanes are permuted.
75bool isElementwise(const VPValue *V);
76
77/// Returns true if \p R produces scalar values for all VF lanes.
78bool doesGeneratePerAllLanes(const VPRecipeBase *R);
79
80/// Returns the header block of the first, top-level loop, or null if none
81/// exist.
82VPBasicBlock *getFirstLoopHeader(VPlan &Plan, VPDominatorTree &VPDT);
83
84/// Get the VF scaling factor applied to the recipe's output, if the recipe has
85/// one.
86unsigned getVFScaleFactor(VPRecipeBase *R);
87
88/// Return true if we do not know how to (mechanically) hoist or sink \p R.
89/// When sinking, passing \p Sinking = true ensures that assumes aren't sunk.
90/// Returns true for recipes that access memory.
91bool cannotHoistOrSinkRecipe(const VPRecipeBase &R, bool Sinking = false);
92
93/// Return the intrinsic ID underlying a call.
94template <typename Ty> Intrinsic::ID getIntrinsicID(const Ty *R) {
95 if (const auto *Intr = dyn_cast<VPWidenIntrinsicRecipe>(R))
96 return Intr->getVectorIntrinsicID();
97 if (const auto *Call = dyn_cast<VPWidenCallRecipe>(R))
98 return Call->getCalledScalarFunction()->getIntrinsicID();
99
100 auto GetCalleeIntrinsic = [&](VPValue *CalleeOp) -> Intrinsic::ID {
101 if (!isa<VPIRValue>(Val: CalleeOp))
102 return Intrinsic::not_intrinsic;
103 auto *F = cast<Function>(Val: CalleeOp->getLiveInIRValue());
104 return F->getIntrinsicID();
105 };
106 if (const auto *Rep = dyn_cast<VPReplicateRecipe>(R))
107 if (Rep->getOpcode() == Instruction::Call)
108 // The callee is the last operand, excluding the mask if predicated.
109 return GetCalleeIntrinsic(
110 Rep->getOperand(Rep->getNumOperandsWithoutMask() - 1));
111 if (const auto *VPI = dyn_cast<VPInstruction>(R)) {
112 if (VPI->getOpcode() == Instruction::Call)
113 // The callee is the last operand, excluding the mask if masked.
114 return GetCalleeIntrinsic(
115 VPI->getOperand(VPI->getNumOperandsWithoutMask() - 1));
116 if (VPI->getOpcode() == VPInstruction::Intrinsic) {
117 return cast<VPConstantInt>(VPI->getLastOperand())->getZExtValue();
118 }
119 }
120 return Intrinsic::not_intrinsic;
121}
122
123/// Return the instruction opcode for the recipe defining \p V or 0 for
124/// unsupported recipes and VPValues not defined by a recipe.
125unsigned getOpcode(const VPValue *V);
126
127/// Get the instruction opcode or intrinsic ID for the recipe defining \p V.
128/// Returns an optional pair, where the first element indicates whether it is an
129/// intrinsic ID.
130std::optional<std::pair<bool, unsigned>>
131getOpcodeOrIntrinsicID(const VPValue *V);
132
133/// Return a MemoryLocation for \p R with noalias metadata populated from
134/// \p R, if the recipe is supported and std::nullopt otherwise. The pointer of
135/// the location is conservatively set to nullptr.
136std::optional<MemoryLocation> getMemoryLocation(const VPRecipeBase &R);
137
138/// Extracts and returns NoWrap flags from \p PhiR and fast-math flags from \p
139/// ID.
140VPIRFlags getFlagsForInduction(const InductionDescriptor &ID,
141 const VPPhi *PhiR);
142
143/// Search \p Start's users for a recipe satisfying \p Pred, looking through
144/// recipes with definitions.
145template <typename PredT>
146inline VPRecipeBase *findRecipe(VPValue *Start, PredT Pred) {
147 SetVector<VPValue *> Worklist;
148 Worklist.insert(X: Start);
149 for (unsigned I = 0; I != Worklist.size(); ++I) {
150 VPValue *Cur = Worklist[I];
151 auto *R = Cur->getDefiningRecipe();
152 if (!R)
153 continue;
154 if (Pred(R))
155 return R;
156 for (VPUser *U : Cur->users()) {
157 for (VPValue *V : cast<VPRecipeBase>(Val: U)->definedValues())
158 Worklist.insert(X: V);
159 }
160 }
161 return nullptr;
162}
163
164/// Find the canonical IV increment of \p Plan's vector loop region. Returns
165/// nullptr if not found.
166VPInstruction *findCanonicalIVIncrement(VPlan &Plan);
167
168/// Returns the GEP nowrap flags for \p Ptr, looking through pointer casts
169/// mirroring Value::stripPointerCasts.
170GEPNoWrapFlags getGEPFlagsForPtr(VPValue *Ptr);
171
172/// Returns true if \p V is used as part of the address of another load or
173/// store.
174bool isUsedByLoadStoreAddress(const VPValue *V);
175
176/// Find the ComputeReductionResult recipe for \p PhiR, looking through selects
177/// inserted for predicated reductions or tail folding.
178VPInstruction *findComputeReductionResult(VPReductionPHIRecipe *PhiR);
179
180/// Finds the incoming alias-mask within the vector preheader.
181VPValue *findIncomingAliasMask(const VPlan &Plan);
182
183/// Returns the (early exiting block, exit block) pairs of \p Plan, i.e. all
184/// edges to an exit block that do not come from \p MiddleVPBB.
185SmallVector<std::pair<VPBasicBlock *, VPIRBasicBlock *>>
186getEarlyExits(const VPlan &Plan, const VPBlockBase *MiddleVPBB);
187
188/// Create a scalar-iv-steps recipe over \p Plan's canonical IV for an
189/// induction of \p Kind with \p InductionOpcode / \p FPBinOp, start value \p
190/// StartV and step \p Step, truncated to \p ResultTy, inserting recipes via \p
191/// Builder.
192VPScalarIVStepsRecipe *
193createScalarIVSteps(VPlan &Plan, InductionDescriptor::InductionKind Kind,
194 Instruction::BinaryOps InductionOpcode,
195 FPMathOperator *FPBinOp, Type *ResultTy, VPValue *StartV,
196 VPValue *Step, DebugLoc DL, VPBuilder &Builder,
197 const VPIRFlags::WrapFlagsTy &Flags = {});
198
199/// Scalarize a VPWidenPointerInductionRecipe by replacing it with a PtrAdd
200/// (IndStart, ScalarIVSteps (0, Step)). This is used when the recipe only
201/// generates scalar values.
202VPValue *scalarizeVPWidenPointerInduction(VPWidenPointerInductionRecipe *PtrIV,
203 VPlan &Plan, VPBuilder &Builder);
204
205/// Returns true if \p R is dead, i.e. none of its defined values are used and
206/// it has no side effects (with the exception of conditional assumes, which are
207/// considered dead as their conditions may be flattened).
208bool isDeadRecipe(VPRecipeBase &R);
209
210/// Recursively delete \p V and any of its operands that become dead.
211void recursivelyDeleteDeadRecipes(VPValue *V);
212
213/// Collect all users of \p V, looking through recipes that define other values.
214SmallVector<VPUser *> collectUsersRecursively(VPValue *V);
215
216/// Try to fold \p R using InstSimplifyFolder. Will succeed and return a
217/// non-nullptr VPValue for a handled opcode or intrinsic ID if corresponding \p
218/// Operands are foldable live-ins.
219VPIRValue *tryToFoldLiveIns(VPSingleDefRecipe &R, ArrayRef<VPValue *> Operands,
220 const DataLayout &DL);
221
222/// Insert phis to reconstruct SSA for a single value starting from \p VPBB. \p
223/// Defs is a map of definitions at specific blocks. Returns the
224/// reconstructed value at VPBB. Use if the CFG has been modified such that a
225/// def no longer dominates all its uses. Every block leading to VPBB must be
226/// reachable from the entry and the plan must be plain-CFG (not contain any
227/// regions).
228LLVM_ABI_FOR_TEST VPValue *
229reconstructSSA(VPBasicBlock *VPBB, DenseMap<VPBasicBlock *, VPValue *> &Defs);
230
231/// Returns \p Freq as a BranchProbability, relative to the full mass.
232BranchProbability getExecutionProbability(BlockFrequency Freq);
233
234/// Computes for each block in \p Blocks, which must be in reverse post-order,
235/// the frequency with which it executes relative to the first (header) block,
236/// and whether that frequency was composed using any estimated branch weights.
237/// The frequency of a block is the sum over its incoming edges, or std::nullopt
238/// if any edge on a path reaching it lacks branch weights. Edges to blocks
239/// outside \p Blocks are ignored.
240DenseMap<const VPBasicBlock *, std::optional<VPExecutionFrequency>>
241computeExecutionFrequencies(ArrayRef<VPBasicBlock *> Blocks);
242
243namespace detail {
244
245/// Template-independent implementation for pullOutPermutations.
246void pullOutPermutationsImpl(
247 VPlan &Plan, function_ref<VPValue *(VPValue *Op)> Perm,
248 function_ref<VPSingleDefRecipe *(VPSingleDefRecipe *X)> Build);
249} // namespace detail
250
251/// Removes the permutation pattern \p Perm from any elementwise operations
252/// in the plan, by constructing a new permutation via \p Build.
253/// e.g. binop(perm(x), perm(y)) -> perm(binop(x,y)).
254template <typename Match_t, typename Builder>
255void pullOutPermutations(VPlan &Plan, Match_t Perm, Builder Build) {
256 // Convert matcher to function returing the matched VPValue.
257 auto MatchPerm = [&Perm](VPValue *Op) -> VPValue * {
258 VPValue *X;
259 return match(Op, Perm(X)) ? X : nullptr;
260 };
261 detail::pullOutPermutationsImpl(Plan, Perm: MatchPerm, Build);
262}
263
264} // namespace vputils
265
266/// Lightweight SCEV-to-VPlan expander. Converts SCEV expressions into
267/// VPInstructions and live-ins. SCEVAddRecExprs are wrapped in a
268/// VPExpandSCEVRecipe to be expanded to IR later.
269class VPSCEVExpander {
270 VPBuilder &Builder;
271 ScalarEvolution &SE;
272 DebugLoc DL;
273
274 /// When true, nested SCEVUDivExprs are expanded so that they cannot divide by
275 /// zero, matching SCEVExpander's SafeUDivMode.
276 bool SafeUDivMode = false;
277
278 /// Try to find a loop-invariant IR value in the plan's entry block whose
279 /// SCEV matches \p S. Returns the corresponding live-in VPValue, or nullptr
280 /// if none is found.
281 VPValue *tryToReuseIRValue(const SCEV *S);
282
283 /// Expand pointer-typed \p S as a ptradd of its pointer base and offset.
284 VPValue *expandAsPtrAdd(const SCEVNAryExpr *S);
285
286public:
287 VPSCEVExpander(VPBuilder &Builder, ScalarEvolution &SE, DebugLoc DL)
288 : Builder(Builder), SE(SE), DL(DL) {}
289
290 /// Expand \p S into recipes and live-ins using the builder.
291 VPValue *expand(const SCEV *S);
292};
293//===----------------------------------------------------------------------===//
294// Utilities for modifying predecessors and successors of VPlan blocks.
295//===----------------------------------------------------------------------===//
296
297/// Class that provides utilities for VPBlockBases in VPlan.
298class VPBlockUtils {
299public:
300 VPBlockUtils() = delete;
301
302 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
303 /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
304 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. \p BlockPtr's
305 /// successors are moved from \p BlockPtr to \p NewBlock. \p NewBlock must
306 /// have neither successors nor predecessors.
307 static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
308 assert(!NewBlock->hasSuccessors() && !NewBlock->hasPredecessors() &&
309 "Can't insert new block with predecessors or successors.");
310 NewBlock->setParent(BlockPtr->getParent());
311 transferSuccessors(Old: BlockPtr, New: NewBlock);
312 connectBlocks(From: BlockPtr, To: NewBlock);
313 }
314
315 /// Insert disconnected block \p NewBlock before \p Blockptr. First
316 /// disconnects all predecessors of \p BlockPtr and connects them to \p
317 /// NewBlock. Add \p NewBlock as predecessor of \p BlockPtr and \p BlockPtr as
318 /// successor of \p NewBlock.
319 static void insertBlockBefore(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
320 assert(!NewBlock->hasSuccessors() && !NewBlock->hasPredecessors() &&
321 "Can't insert new block with predecessors or successors.");
322 NewBlock->setParent(BlockPtr->getParent());
323 for (VPBlockBase *Pred : to_vector(Range: BlockPtr->predecessors()))
324 replaceSuccessor(From: Pred, OldSucc: BlockPtr, NewSucc: NewBlock);
325 connectBlocks(From: NewBlock, To: BlockPtr);
326 }
327
328 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
329 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
330 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
331 /// parent to \p IfTrue and \p IfFalse. \p BlockPtr must have no successors
332 /// and \p IfTrue and \p IfFalse must have neither successors nor
333 /// predecessors.
334 static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
335 VPBlockBase *BlockPtr) {
336 assert(!IfTrue->hasSuccessors() && "Can't insert IfTrue with successors.");
337 assert(!IfFalse->hasSuccessors() &&
338 "Can't insert IfFalse with successors.");
339 BlockPtr->setTwoSuccessors(IfTrue, IfFalse);
340 IfTrue->setPredecessors({BlockPtr});
341 IfFalse->setPredecessors({BlockPtr});
342 IfTrue->setParent(BlockPtr->getParent());
343 IfFalse->setParent(BlockPtr->getParent());
344 }
345
346 /// Connect VPBlockBases \p From and \p To bi-directionally. If \p PredIdx is
347 /// -1, append \p From to the predecessors of \p To, otherwise set \p To's
348 /// predecessor at \p PredIdx to \p From. If \p SuccIdx is -1, append \p To to
349 /// the successors of \p From, otherwise set \p From's successor at \p SuccIdx
350 /// to \p To. Both VPBlockBases must have the same parent, which can be null.
351 /// Both VPBlockBases can be already connected to other VPBlockBases.
352 static void connectBlocks(VPBlockBase *From, VPBlockBase *To,
353 unsigned PredIdx = -1u, unsigned SuccIdx = -1u) {
354 assert((From->getParent() == To->getParent()) &&
355 "Can't connect two block with different parents");
356
357 if (SuccIdx == -1u)
358 From->appendSuccessor(Successor: To);
359 else
360 From->getSuccessors()[SuccIdx] = To;
361
362 if (PredIdx == -1u)
363 To->appendPredecessor(Predecessor: From);
364 else
365 To->getPredecessors()[PredIdx] = From;
366 }
367
368 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
369 /// from the successors of \p From and \p From from the predecessors of \p To.
370 static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
371 assert(To && "Successor to disconnect is null.");
372 From->removeSuccessor(Successor: To);
373 To->removePredecessor(Predecessor: From);
374 }
375
376 /// Redirect the edge from \p From to \p OldSucc to \p NewSucc, keeping \p
377 /// From's successor order. \p From is removed from \p OldSucc's predecessors
378 /// and appended to \p NewSucc's.
379 static void replaceSuccessor(VPBlockBase *From, VPBlockBase *OldSucc,
380 VPBlockBase *NewSucc) {
381 From->replaceSuccessor(Old: OldSucc, New: NewSucc);
382 OldSucc->removePredecessor(Predecessor: From);
383 NewSucc->appendPredecessor(Predecessor: From);
384 }
385
386 /// Reassociate all the blocks connected to \p Old so that they now point to
387 /// \p New.
388 static void reassociateBlocks(VPBlockBase *Old, VPBlockBase *New) {
389 auto Preds = to_vector(Range&: Old->getPredecessors());
390 auto Succs = to_vector(Range&: Old->getSuccessors());
391 for (auto *Pred : Preds)
392 Pred->replaceSuccessor(Old, New);
393 for (auto *Succ : Succs)
394 Succ->replacePredecessor(Old, New);
395 New->setPredecessors(Old->getPredecessors());
396 New->setSuccessors(Old->getSuccessors());
397 Old->clearPredecessors();
398 Old->clearSuccessors();
399 }
400
401 /// Transfer successors from \p Old to \p New. \p New must have no successors.
402 static void transferSuccessors(VPBlockBase *Old, VPBlockBase *New) {
403 for (auto *Succ : Old->getSuccessors())
404 Succ->replacePredecessor(Old, New);
405 New->setSuccessors(Old->getSuccessors());
406 Old->clearSuccessors();
407 }
408
409 /// Clone the CFG for all nodes reachable from \p Entry, including cloning
410 /// the blocks and their recipes. Operands of cloned recipes will NOT be
411 /// updated. Remapping of operands must be done separately. Returns a pair
412 /// with the new entry and exiting blocks of the cloned region. If \p Entry
413 /// isn't part of a region, return nullptr for the exiting block.
414 static std::pair<VPBlockBase *, VPBlockBase *> cloneFrom(VPBlockBase *Entry);
415
416 /// Return an iterator range over \p Range which only includes \p BlockTy
417 /// blocks. The accesses are casted to \p BlockTy.
418 template <typename BlockTy, typename T> static auto blocksOnly(T &&Range) {
419 return make_isa_range<BlockTy>(std::forward<T>(Range));
420 }
421
422 /// Return an iterator range over \p Range with each block cast to \p
423 /// BlockTy. Unlike blocksOnly, all blocks in \p Range must be of type
424 /// \p BlockTy.
425 template <typename BlockTy, typename T> static auto blocksAs(T &&Range) {
426 // Create BaseTy with correct const-ness based on BlockTy.
427 using BaseTy = std::conditional_t<std::is_const<BlockTy>::value,
428 const VPBlockBase, VPBlockBase>;
429 return map_range(
430 Range, [](BaseTy *Block) -> BlockTy * { return cast<BlockTy>(Block); });
431 }
432
433 /// Returns the blocks between \p FirstBB and \p LastBB, where FirstBB
434 /// to LastBB forms a single-sucessor chain.
435 static SmallVector<VPBasicBlock *>
436 blocksInSingleSuccessorChainBetween(VPBasicBlock *FirstBB,
437 VPBasicBlock *LastBB);
438
439 /// Inserts \p BlockPtr on the edge between \p From and \p To. That is, update
440 /// \p From's successor to \p To to point to \p BlockPtr and \p To's
441 /// predecessor from \p From to \p BlockPtr. \p From and \p To are added to \p
442 /// BlockPtr's predecessors and successors respectively. There must be a
443 /// single edge between \p From and \p To.
444 static void insertOnEdge(VPBlockBase *From, VPBlockBase *To,
445 VPBlockBase *BlockPtr) {
446 unsigned SuccIdx = From->getIndexForSuccessor(Succ: To);
447 unsigned PredIx = To->getIndexForPredecessor(Pred: From);
448 VPBlockUtils::connectBlocks(From, To: BlockPtr, PredIdx: -1, SuccIdx);
449 VPBlockUtils::connectBlocks(From: BlockPtr, To, PredIdx: PredIx, SuccIdx: -1);
450 }
451
452 /// Returns true if \p VPB is a loop header, based on regions or \p VPDT in
453 /// their absence.
454 static bool isHeader(const VPBlockBase *VPB, const VPDominatorTree &VPDT);
455
456 /// Returns true if \p VPB is a loop latch, using isHeader().
457 static bool isLatch(const VPBlockBase *VPB, const VPDominatorTree &VPDT);
458
459 /// Returns the header and latch of the outermost loop of \p Plan in plain
460 /// CFG form (before regions are formed).
461 static std::pair<VPBasicBlock *, VPBasicBlock *>
462 getPlainCFGHeaderAndLatch(const VPlan &Plan);
463
464 /// Returns the middle block of \p Plan in plain CFG form (before regions
465 /// are formed).
466 static VPBasicBlock *getPlainCFGMiddleBlock(const VPlan &Plan);
467};
468
469} // namespace llvm
470
471#endif
472