LLVM 19.0.0git
VPlan.h
Go to the documentation of this file.
1//===- VPlan.h - Represent A Vectorizer Plan --------------------*- 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/// \file
10/// This file contains the declarations of the Vectorization Plan base classes:
11/// 1. VPBasicBlock and VPRegionBlock that inherit from a common pure virtual
12/// VPBlockBase, together implementing a Hierarchical CFG;
13/// 2. Pure virtual VPRecipeBase serving as the base class for recipes contained
14/// within VPBasicBlocks;
15/// 3. Pure virtual VPSingleDefRecipe serving as a base class for recipes that
16/// also inherit from VPValue.
17/// 4. VPInstruction, a concrete Recipe and VPUser modeling a single planned
18/// instruction;
19/// 5. The VPlan class holding a candidate for vectorization;
20/// 6. The VPlanPrinter class providing a way to print a plan in dot format;
21/// These are documented in docs/VectorizationPlan.rst.
22//
23//===----------------------------------------------------------------------===//
24
25#ifndef LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
26#define LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
27
28#include "VPlanAnalysis.h"
29#include "VPlanValue.h"
30#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/MapVector.h"
35#include "llvm/ADT/Twine.h"
36#include "llvm/ADT/ilist.h"
37#include "llvm/ADT/ilist_node.h"
41#include "llvm/IR/DebugLoc.h"
42#include "llvm/IR/FMF.h"
43#include "llvm/IR/Operator.h"
44#include <algorithm>
45#include <cassert>
46#include <cstddef>
47#include <string>
48
49namespace llvm {
50
51class BasicBlock;
52class DominatorTree;
53class InnerLoopVectorizer;
54class IRBuilderBase;
55class LoopInfo;
56class raw_ostream;
57class RecurrenceDescriptor;
58class SCEV;
59class Type;
60class VPBasicBlock;
61class VPRegionBlock;
62class VPlan;
63class VPReplicateRecipe;
64class VPlanSlp;
65class Value;
66class LoopVersioning;
67
68namespace Intrinsic {
69typedef unsigned ID;
70}
71
72/// Returns a calculation for the total number of elements for a given \p VF.
73/// For fixed width vectors this value is a constant, whereas for scalable
74/// vectors it is an expression determined at runtime.
75Value *getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF);
76
77/// Return a value for Step multiplied by VF.
78Value *createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF,
79 int64_t Step);
80
81const SCEV *createTripCountSCEV(Type *IdxTy, PredicatedScalarEvolution &PSE,
82 Loop *CurLoop = nullptr);
83
84/// A range of powers-of-2 vectorization factors with fixed start and
85/// adjustable end. The range includes start and excludes end, e.g.,:
86/// [1, 16) = {1, 2, 4, 8}
87struct VFRange {
88 // A power of 2.
90
91 // A power of 2. If End <= Start range is empty.
93
94 bool isEmpty() const {
96 }
97
99 : Start(Start), End(End) {
101 "Both Start and End should have the same scalable flag");
103 "Expected Start to be a power of 2");
105 "Expected End to be a power of 2");
106 }
107
108 /// Iterator to iterate over vectorization factors in a VFRange.
110 : public iterator_facade_base<iterator, std::forward_iterator_tag,
111 ElementCount> {
112 ElementCount VF;
113
114 public:
115 iterator(ElementCount VF) : VF(VF) {}
116
117 bool operator==(const iterator &Other) const { return VF == Other.VF; }
118
119 ElementCount operator*() const { return VF; }
120
122 VF *= 2;
123 return *this;
124 }
125 };
126
130 return iterator(End);
131 }
132};
133
134using VPlanPtr = std::unique_ptr<VPlan>;
135
136/// In what follows, the term "input IR" refers to code that is fed into the
137/// vectorizer whereas the term "output IR" refers to code that is generated by
138/// the vectorizer.
139
140/// VPLane provides a way to access lanes in both fixed width and scalable
141/// vectors, where for the latter the lane index sometimes needs calculating
142/// as a runtime expression.
143class VPLane {
144public:
145 /// Kind describes how to interpret Lane.
146 enum class Kind : uint8_t {
147 /// For First, Lane is the index into the first N elements of a
148 /// fixed-vector <N x <ElTy>> or a scalable vector <vscale x N x <ElTy>>.
149 First,
150 /// For ScalableLast, Lane is the offset from the start of the last
151 /// N-element subvector in a scalable vector <vscale x N x <ElTy>>. For
152 /// example, a Lane of 0 corresponds to lane `(vscale - 1) * N`, a Lane of
153 /// 1 corresponds to `((vscale - 1) * N) + 1`, etc.
155 };
156
157private:
158 /// in [0..VF)
159 unsigned Lane;
160
161 /// Indicates how the Lane should be interpreted, as described above.
162 Kind LaneKind;
163
164public:
165 VPLane(unsigned Lane, Kind LaneKind) : Lane(Lane), LaneKind(LaneKind) {}
166
168
170 unsigned LaneOffset = VF.getKnownMinValue() - 1;
171 Kind LaneKind;
172 if (VF.isScalable())
173 // In this case 'LaneOffset' refers to the offset from the start of the
174 // last subvector with VF.getKnownMinValue() elements.
176 else
177 LaneKind = VPLane::Kind::First;
178 return VPLane(LaneOffset, LaneKind);
179 }
180
181 /// Returns a compile-time known value for the lane index and asserts if the
182 /// lane can only be calculated at runtime.
183 unsigned getKnownLane() const {
184 assert(LaneKind == Kind::First);
185 return Lane;
186 }
187
188 /// Returns an expression describing the lane index that can be used at
189 /// runtime.
190 Value *getAsRuntimeExpr(IRBuilderBase &Builder, const ElementCount &VF) const;
191
192 /// Returns the Kind of lane offset.
193 Kind getKind() const { return LaneKind; }
194
195 /// Returns true if this is the first lane of the whole vector.
196 bool isFirstLane() const { return Lane == 0 && LaneKind == Kind::First; }
197
198 /// Maps the lane to a cache index based on \p VF.
199 unsigned mapToCacheIndex(const ElementCount &VF) const {
200 switch (LaneKind) {
202 assert(VF.isScalable() && Lane < VF.getKnownMinValue());
203 return VF.getKnownMinValue() + Lane;
204 default:
205 assert(Lane < VF.getKnownMinValue());
206 return Lane;
207 }
208 }
209
210 /// Returns the maxmimum number of lanes that we are able to consider
211 /// caching for \p VF.
212 static unsigned getNumCachedLanes(const ElementCount &VF) {
213 return VF.getKnownMinValue() * (VF.isScalable() ? 2 : 1);
214 }
215};
216
217/// VPIteration represents a single point in the iteration space of the output
218/// (vectorized and/or unrolled) IR loop.
220 /// in [0..UF)
221 unsigned Part;
222
224
225 VPIteration(unsigned Part, unsigned Lane,
227 : Part(Part), Lane(Lane, Kind) {}
228
229 VPIteration(unsigned Part, const VPLane &Lane) : Part(Part), Lane(Lane) {}
230
231 bool isFirstIteration() const { return Part == 0 && Lane.isFirstLane(); }
232};
233
234/// VPTransformState holds information passed down when "executing" a VPlan,
235/// needed for generating the output IR.
240
241 /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
243 unsigned UF;
244
245 /// Hold the indices to generate specific scalar instructions. Null indicates
246 /// that all instances are to be generated, using either scalar or vector
247 /// instructions.
248 std::optional<VPIteration> Instance;
249
250 struct DataState {
251 /// A type for vectorized values in the new loop. Each value from the
252 /// original loop, when vectorized, is represented by UF vector values in
253 /// the new unrolled loop, where UF is the unroll factor.
255
257
261
262 /// Get the generated vector Value for a given VPValue \p Def and a given \p
263 /// Part if \p IsScalar is false, otherwise return the generated scalar
264 /// for \p Part. \See set.
265 Value *get(VPValue *Def, unsigned Part, bool IsScalar = false);
266
267 /// Get the generated Value for a given VPValue and given Part and Lane.
268 Value *get(VPValue *Def, const VPIteration &Instance);
269
270 bool hasVectorValue(VPValue *Def, unsigned Part) {
271 auto I = Data.PerPartOutput.find(Def);
272 return I != Data.PerPartOutput.end() && Part < I->second.size() &&
273 I->second[Part];
274 }
275
277 auto I = Data.PerPartScalars.find(Def);
278 if (I == Data.PerPartScalars.end())
279 return false;
280 unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF);
281 return Instance.Part < I->second.size() &&
282 CacheIdx < I->second[Instance.Part].size() &&
283 I->second[Instance.Part][CacheIdx];
284 }
285
286 /// Set the generated vector Value for a given VPValue and a given Part, if \p
287 /// IsScalar is false. If \p IsScalar is true, set the scalar in (Part, 0).
288 void set(VPValue *Def, Value *V, unsigned Part, bool IsScalar = false) {
289 if (IsScalar) {
290 set(Def, V, VPIteration(Part, 0));
291 return;
292 }
293 assert((VF.isScalar() || V->getType()->isVectorTy()) &&
294 "scalar values must be stored as (Part, 0)");
295 if (!Data.PerPartOutput.count(Def)) {
297 Data.PerPartOutput[Def] = Entry;
298 }
299 Data.PerPartOutput[Def][Part] = V;
300 }
301
302 /// Reset an existing vector value for \p Def and a given \p Part.
303 void reset(VPValue *Def, Value *V, unsigned Part) {
304 auto Iter = Data.PerPartOutput.find(Def);
305 assert(Iter != Data.PerPartOutput.end() &&
306 "need to overwrite existing value");
307 Iter->second[Part] = V;
308 }
309
310 /// Set the generated scalar \p V for \p Def and the given \p Instance.
311 void set(VPValue *Def, Value *V, const VPIteration &Instance) {
312 auto Iter = Data.PerPartScalars.insert({Def, {}});
313 auto &PerPartVec = Iter.first->second;
314 if (PerPartVec.size() <= Instance.Part)
315 PerPartVec.resize(Instance.Part + 1);
316 auto &Scalars = PerPartVec[Instance.Part];
317 unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF);
318 if (Scalars.size() <= CacheIdx)
319 Scalars.resize(CacheIdx + 1);
320 assert(!Scalars[CacheIdx] && "should overwrite existing value");
321 Scalars[CacheIdx] = V;
322 }
323
324 /// Reset an existing scalar value for \p Def and a given \p Instance.
325 void reset(VPValue *Def, Value *V, const VPIteration &Instance) {
326 auto Iter = Data.PerPartScalars.find(Def);
327 assert(Iter != Data.PerPartScalars.end() &&
328 "need to overwrite existing value");
329 assert(Instance.Part < Iter->second.size() &&
330 "need to overwrite existing value");
331 unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF);
332 assert(CacheIdx < Iter->second[Instance.Part].size() &&
333 "need to overwrite existing value");
334 Iter->second[Instance.Part][CacheIdx] = V;
335 }
336
337 /// Add additional metadata to \p To that was not present on \p Orig.
338 ///
339 /// Currently this is used to add the noalias annotations based on the
340 /// inserted memchecks. Use this for instructions that are *cloned* into the
341 /// vector loop.
342 void addNewMetadata(Instruction *To, const Instruction *Orig);
343
344 /// Add metadata from one instruction to another.
345 ///
346 /// This includes both the original MDs from \p From and additional ones (\see
347 /// addNewMetadata). Use this for *newly created* instructions in the vector
348 /// loop.
349 void addMetadata(Value *To, Instruction *From);
350
351 /// Set the debug location in the builder using the debug location \p DL.
353
354 /// Construct the vector value of a scalarized value \p V one lane at a time.
356
357 /// Hold state information used when constructing the CFG of the output IR,
358 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
359 struct CFGState {
360 /// The previous VPBasicBlock visited. Initially set to null.
362
363 /// The previous IR BasicBlock created or used. Initially set to the new
364 /// header BasicBlock.
365 BasicBlock *PrevBB = nullptr;
366
367 /// The last IR BasicBlock in the output IR. Set to the exit block of the
368 /// vector loop.
369 BasicBlock *ExitBB = nullptr;
370
371 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
372 /// of replication, maps the BasicBlock of the last replica created.
374
375 CFGState() = default;
376
377 /// Returns the BasicBlock* mapped to the pre-header of the loop region
378 /// containing \p R.
381
382 /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
384
385 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
387
388 /// Hold a reference to the IRBuilder used to generate output IR code.
390
391 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
393
394 /// Pointer to the VPlan code is generated for.
396
397 /// The loop object for the current parent region, or nullptr.
399
400 /// LoopVersioning. It's only set up (non-null) if memchecks were
401 /// used.
402 ///
403 /// This is currently only used to add no-alias metadata based on the
404 /// memchecks. The actually versioning is performed manually.
406
407 /// Map SCEVs to their expanded values. Populated when executing
408 /// VPExpandSCEVRecipes.
410
411 /// VPlan-based type analysis.
413};
414
415/// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
416/// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
418 friend class VPBlockUtils;
419
420 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
421
422 /// An optional name for the block.
423 std::string Name;
424
425 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
426 /// it is a topmost VPBlockBase.
427 VPRegionBlock *Parent = nullptr;
428
429 /// List of predecessor blocks.
431
432 /// List of successor blocks.
434
435 /// VPlan containing the block. Can only be set on the entry block of the
436 /// plan.
437 VPlan *Plan = nullptr;
438
439 /// Add \p Successor as the last successor to this block.
440 void appendSuccessor(VPBlockBase *Successor) {
441 assert(Successor && "Cannot add nullptr successor!");
442 Successors.push_back(Successor);
443 }
444
445 /// Add \p Predecessor as the last predecessor to this block.
446 void appendPredecessor(VPBlockBase *Predecessor) {
447 assert(Predecessor && "Cannot add nullptr predecessor!");
448 Predecessors.push_back(Predecessor);
449 }
450
451 /// Remove \p Predecessor from the predecessors of this block.
452 void removePredecessor(VPBlockBase *Predecessor) {
453 auto Pos = find(Predecessors, Predecessor);
454 assert(Pos && "Predecessor does not exist");
455 Predecessors.erase(Pos);
456 }
457
458 /// Remove \p Successor from the successors of this block.
459 void removeSuccessor(VPBlockBase *Successor) {
460 auto Pos = find(Successors, Successor);
461 assert(Pos && "Successor does not exist");
462 Successors.erase(Pos);
463 }
464
465protected:
466 VPBlockBase(const unsigned char SC, const std::string &N)
467 : SubclassID(SC), Name(N) {}
468
469public:
470 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
471 /// that are actually instantiated. Values of this enumeration are kept in the
472 /// SubclassID field of the VPBlockBase objects. They are used for concrete
473 /// type identification.
474 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
475
477
478 virtual ~VPBlockBase() = default;
479
480 const std::string &getName() const { return Name; }
481
482 void setName(const Twine &newName) { Name = newName.str(); }
483
484 /// \return an ID for the concrete type of this object.
485 /// This is used to implement the classof checks. This should not be used
486 /// for any other purpose, as the values may change as LLVM evolves.
487 unsigned getVPBlockID() const { return SubclassID; }
488
489 VPRegionBlock *getParent() { return Parent; }
490 const VPRegionBlock *getParent() const { return Parent; }
491
492 /// \return A pointer to the plan containing the current block.
493 VPlan *getPlan();
494 const VPlan *getPlan() const;
495
496 /// Sets the pointer of the plan containing the block. The block must be the
497 /// entry block into the VPlan.
498 void setPlan(VPlan *ParentPlan);
499
500 void setParent(VPRegionBlock *P) { Parent = P; }
501
502 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
503 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
504 /// VPBlockBase is a VPBasicBlock, it is returned.
505 const VPBasicBlock *getEntryBasicBlock() const;
507
508 /// \return the VPBasicBlock that is the exiting this VPBlockBase,
509 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
510 /// VPBlockBase is a VPBasicBlock, it is returned.
511 const VPBasicBlock *getExitingBasicBlock() const;
513
514 const VPBlocksTy &getSuccessors() const { return Successors; }
515 VPBlocksTy &getSuccessors() { return Successors; }
516
518
519 const VPBlocksTy &getPredecessors() const { return Predecessors; }
520 VPBlocksTy &getPredecessors() { return Predecessors; }
521
522 /// \return the successor of this VPBlockBase if it has a single successor.
523 /// Otherwise return a null pointer.
525 return (Successors.size() == 1 ? *Successors.begin() : nullptr);
526 }
527
528 /// \return the predecessor of this VPBlockBase if it has a single
529 /// predecessor. Otherwise return a null pointer.
531 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
532 }
533
534 size_t getNumSuccessors() const { return Successors.size(); }
535 size_t getNumPredecessors() const { return Predecessors.size(); }
536
537 /// An Enclosing Block of a block B is any block containing B, including B
538 /// itself. \return the closest enclosing block starting from "this", which
539 /// has successors. \return the root enclosing block if all enclosing blocks
540 /// have no successors.
542
543 /// \return the closest enclosing block starting from "this", which has
544 /// predecessors. \return the root enclosing block if all enclosing blocks
545 /// have no predecessors.
547
548 /// \return the successors either attached directly to this VPBlockBase or, if
549 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
550 /// successors of its own, search recursively for the first enclosing
551 /// VPRegionBlock that has successors and return them. If no such
552 /// VPRegionBlock exists, return the (empty) successors of the topmost
553 /// VPBlockBase reached.
556 }
557
558 /// \return the hierarchical successor of this VPBlockBase if it has a single
559 /// hierarchical successor. Otherwise return a null pointer.
562 }
563
564 /// \return the predecessors either attached directly to this VPBlockBase or,
565 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
566 /// predecessors of its own, search recursively for the first enclosing
567 /// VPRegionBlock that has predecessors and return them. If no such
568 /// VPRegionBlock exists, return the (empty) predecessors of the topmost
569 /// VPBlockBase reached.
572 }
573
574 /// \return the hierarchical predecessor of this VPBlockBase if it has a
575 /// single hierarchical predecessor. Otherwise return a null pointer.
578 }
579
580 /// Set a given VPBlockBase \p Successor as the single successor of this
581 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
582 /// This VPBlockBase must have no successors.
584 assert(Successors.empty() && "Setting one successor when others exist.");
585 assert(Successor->getParent() == getParent() &&
586 "connected blocks must have the same parent");
587 appendSuccessor(Successor);
588 }
589
590 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
591 /// successors of this VPBlockBase. This VPBlockBase is not added as
592 /// predecessor of \p IfTrue or \p IfFalse. This VPBlockBase must have no
593 /// successors.
594 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse) {
595 assert(Successors.empty() && "Setting two successors when others exist.");
596 appendSuccessor(IfTrue);
597 appendSuccessor(IfFalse);
598 }
599
600 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
601 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
602 /// as successor of any VPBasicBlock in \p NewPreds.
604 assert(Predecessors.empty() && "Block predecessors already set.");
605 for (auto *Pred : NewPreds)
606 appendPredecessor(Pred);
607 }
608
609 /// Remove all the predecessor of this block.
610 void clearPredecessors() { Predecessors.clear(); }
611
612 /// Remove all the successors of this block.
613 void clearSuccessors() { Successors.clear(); }
614
615 /// The method which generates the output IR that correspond to this
616 /// VPBlockBase, thereby "executing" the VPlan.
617 virtual void execute(VPTransformState *State) = 0;
618
619 /// Delete all blocks reachable from a given VPBlockBase, inclusive.
620 static void deleteCFG(VPBlockBase *Entry);
621
622 /// Return true if it is legal to hoist instructions into this block.
624 // There are currently no constraints that prevent an instruction to be
625 // hoisted into a VPBlockBase.
626 return true;
627 }
628
629 /// Replace all operands of VPUsers in the block with \p NewValue and also
630 /// replaces all uses of VPValues defined in the block with NewValue.
631 virtual void dropAllReferences(VPValue *NewValue) = 0;
632
633#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
634 void printAsOperand(raw_ostream &OS, bool PrintType) const {
635 OS << getName();
636 }
637
638 /// Print plain-text dump of this VPBlockBase to \p O, prefixing all lines
639 /// with \p Indent. \p SlotTracker is used to print unnamed VPValue's using
640 /// consequtive numbers.
641 ///
642 /// Note that the numbering is applied to the whole VPlan, so printing
643 /// individual blocks is consistent with the whole VPlan printing.
644 virtual void print(raw_ostream &O, const Twine &Indent,
645 VPSlotTracker &SlotTracker) const = 0;
646
647 /// Print plain-text dump of this VPlan to \p O.
648 void print(raw_ostream &O) const {
650 print(O, "", SlotTracker);
651 }
652
653 /// Print the successors of this block to \p O, prefixing all lines with \p
654 /// Indent.
655 void printSuccessors(raw_ostream &O, const Twine &Indent) const;
656
657 /// Dump this VPBlockBase to dbgs().
658 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
659#endif
660
661 /// Clone the current block and it's recipes without updating the operands of
662 /// the cloned recipes, including all blocks in the single-entry single-exit
663 /// region for VPRegionBlocks.
664 virtual VPBlockBase *clone() = 0;
665};
666
667/// A value that is used outside the VPlan. The operand of the user needs to be
668/// added to the associated LCSSA phi node.
669class VPLiveOut : public VPUser {
670 PHINode *Phi;
671
672public:
674 : VPUser({Op}, VPUser::VPUserID::LiveOut), Phi(Phi) {}
675
676 static inline bool classof(const VPUser *U) {
677 return U->getVPUserID() == VPUser::VPUserID::LiveOut;
678 }
679
680 /// Fixup the wrapped LCSSA phi node in the unique exit block. This simply
681 /// means we need to add the appropriate incoming value from the middle
682 /// block as exiting edges from the scalar epilogue loop (if present) are
683 /// already in place, and we exit the vector loop exclusively to the middle
684 /// block.
685 void fixPhi(VPlan &Plan, VPTransformState &State);
686
687 /// Returns true if the VPLiveOut uses scalars of operand \p Op.
688 bool usesScalars(const VPValue *Op) const override {
690 "Op must be an operand of the recipe");
691 return true;
692 }
693
694 PHINode *getPhi() const { return Phi; }
695
696#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
697 /// Print the VPLiveOut to \p O.
699#endif
700};
701
702/// VPRecipeBase is a base class modeling a sequence of one or more output IR
703/// instructions. VPRecipeBase owns the VPValues it defines through VPDef
704/// and is responsible for deleting its defined values. Single-value
705/// recipes must inherit from VPSingleDef instead of inheriting from both
706/// VPRecipeBase and VPValue separately.
707class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock>,
708 public VPDef,
709 public VPUser {
710 friend VPBasicBlock;
711 friend class VPBlockUtils;
712
713 /// Each VPRecipe belongs to a single VPBasicBlock.
714 VPBasicBlock *Parent = nullptr;
715
716 /// The debug location for the recipe.
717 DebugLoc DL;
718
719public:
721 DebugLoc DL = {})
723
724 template <typename IterT>
726 DebugLoc DL = {})
728 virtual ~VPRecipeBase() = default;
729
730 /// Clone the current recipe.
731 virtual VPRecipeBase *clone() = 0;
732
733 /// \return the VPBasicBlock which this VPRecipe belongs to.
734 VPBasicBlock *getParent() { return Parent; }
735 const VPBasicBlock *getParent() const { return Parent; }
736
737 /// The method which generates the output IR instructions that correspond to
738 /// this VPRecipe, thereby "executing" the VPlan.
739 virtual void execute(VPTransformState &State) = 0;
740
741 /// Insert an unlinked recipe into a basic block immediately before
742 /// the specified recipe.
743 void insertBefore(VPRecipeBase *InsertPos);
744 /// Insert an unlinked recipe into \p BB immediately before the insertion
745 /// point \p IP;
747
748 /// Insert an unlinked Recipe into a basic block immediately after
749 /// the specified Recipe.
750 void insertAfter(VPRecipeBase *InsertPos);
751
752 /// Unlink this recipe from its current VPBasicBlock and insert it into
753 /// the VPBasicBlock that MovePos lives in, right after MovePos.
754 void moveAfter(VPRecipeBase *MovePos);
755
756 /// Unlink this recipe and insert into BB before I.
757 ///
758 /// \pre I is a valid iterator into BB.
760
761 /// This method unlinks 'this' from the containing basic block, but does not
762 /// delete it.
763 void removeFromParent();
764
765 /// This method unlinks 'this' from the containing basic block and deletes it.
766 ///
767 /// \returns an iterator pointing to the element after the erased one
769
770 /// Method to support type inquiry through isa, cast, and dyn_cast.
771 static inline bool classof(const VPDef *D) {
772 // All VPDefs are also VPRecipeBases.
773 return true;
774 }
775
776 static inline bool classof(const VPUser *U) {
777 return U->getVPUserID() == VPUser::VPUserID::Recipe;
778 }
779
780 /// Returns true if the recipe may have side-effects.
781 bool mayHaveSideEffects() const;
782
783 /// Returns true for PHI-like recipes.
784 bool isPhi() const {
785 return getVPDefID() >= VPFirstPHISC && getVPDefID() <= VPLastPHISC;
786 }
787
788 /// Returns true if the recipe may read from memory.
789 bool mayReadFromMemory() const;
790
791 /// Returns true if the recipe may write to memory.
792 bool mayWriteToMemory() const;
793
794 /// Returns true if the recipe may read from or write to memory.
795 bool mayReadOrWriteMemory() const {
797 }
798
799 /// Returns the debug location of the recipe.
800 DebugLoc getDebugLoc() const { return DL; }
801};
802
803// Helper macro to define common classof implementations for recipes.
804#define VP_CLASSOF_IMPL(VPDefID) \
805 static inline bool classof(const VPDef *D) { \
806 return D->getVPDefID() == VPDefID; \
807 } \
808 static inline bool classof(const VPValue *V) { \
809 auto *R = V->getDefiningRecipe(); \
810 return R && R->getVPDefID() == VPDefID; \
811 } \
812 static inline bool classof(const VPUser *U) { \
813 auto *R = dyn_cast<VPRecipeBase>(U); \
814 return R && R->getVPDefID() == VPDefID; \
815 } \
816 static inline bool classof(const VPRecipeBase *R) { \
817 return R->getVPDefID() == VPDefID; \
818 } \
819 static inline bool classof(const VPSingleDefRecipe *R) { \
820 return R->getVPDefID() == VPDefID; \
821 }
822
823/// VPSingleDef is a base class for recipes for modeling a sequence of one or
824/// more output IR that define a single result VPValue.
825/// Note that VPRecipeBase must be inherited from before VPValue.
826class VPSingleDefRecipe : public VPRecipeBase, public VPValue {
827public:
828 template <typename IterT>
829 VPSingleDefRecipe(const unsigned char SC, IterT Operands, DebugLoc DL = {})
830 : VPRecipeBase(SC, Operands, DL), VPValue(this) {}
831
832 VPSingleDefRecipe(const unsigned char SC, ArrayRef<VPValue *> Operands,
833 DebugLoc DL = {})
834 : VPRecipeBase(SC, Operands, DL), VPValue(this) {}
835
836 template <typename IterT>
837 VPSingleDefRecipe(const unsigned char SC, IterT Operands, Value *UV,
838 DebugLoc DL = {})
839 : VPRecipeBase(SC, Operands, DL), VPValue(this, UV) {}
840
841 static inline bool classof(const VPRecipeBase *R) {
842 switch (R->getVPDefID()) {
843 case VPRecipeBase::VPDerivedIVSC:
844 case VPRecipeBase::VPExpandSCEVSC:
845 case VPRecipeBase::VPInstructionSC:
846 case VPRecipeBase::VPReductionSC:
847 case VPRecipeBase::VPReplicateSC:
848 case VPRecipeBase::VPScalarIVStepsSC:
849 case VPRecipeBase::VPVectorPointerSC:
850 case VPRecipeBase::VPWidenCallSC:
851 case VPRecipeBase::VPWidenCanonicalIVSC:
852 case VPRecipeBase::VPWidenCastSC:
853 case VPRecipeBase::VPWidenGEPSC:
854 case VPRecipeBase::VPWidenSC:
855 case VPRecipeBase::VPWidenSelectSC:
856 case VPRecipeBase::VPBlendSC:
857 case VPRecipeBase::VPPredInstPHISC:
858 case VPRecipeBase::VPCanonicalIVPHISC:
859 case VPRecipeBase::VPActiveLaneMaskPHISC:
860 case VPRecipeBase::VPFirstOrderRecurrencePHISC:
861 case VPRecipeBase::VPWidenPHISC:
862 case VPRecipeBase::VPWidenIntOrFpInductionSC:
863 case VPRecipeBase::VPWidenPointerInductionSC:
864 case VPRecipeBase::VPReductionPHISC:
865 case VPRecipeBase::VPScalarCastSC:
866 return true;
867 case VPRecipeBase::VPInterleaveSC:
868 case VPRecipeBase::VPBranchOnMaskSC:
869 case VPRecipeBase::VPWidenLoadEVLSC:
870 case VPRecipeBase::VPWidenLoadSC:
871 case VPRecipeBase::VPWidenStoreEVLSC:
872 case VPRecipeBase::VPWidenStoreSC:
873 // TODO: Widened stores don't define a value, but widened loads do. Split
874 // the recipes to be able to make widened loads VPSingleDefRecipes.
875 return false;
876 }
877 llvm_unreachable("Unhandled VPDefID");
878 }
879
880 static inline bool classof(const VPUser *U) {
881 auto *R = dyn_cast<VPRecipeBase>(U);
882 return R && classof(R);
883 }
884
885 virtual VPSingleDefRecipe *clone() override = 0;
886
887 /// Returns the underlying instruction.
889 return cast<Instruction>(getUnderlyingValue());
890 }
892 return cast<Instruction>(getUnderlyingValue());
893 }
894};
895
896/// Class to record LLVM IR flag for a recipe along with it.
898 enum class OperationType : unsigned char {
899 Cmp,
900 OverflowingBinOp,
901 DisjointOp,
902 PossiblyExactOp,
903 GEPOp,
904 FPMathOp,
905 NonNegOp,
906 Other
907 };
908
909public:
910 struct WrapFlagsTy {
911 char HasNUW : 1;
912 char HasNSW : 1;
913
915 };
916
918 char IsDisjoint : 1;
920 };
921
922protected:
923 struct GEPFlagsTy {
924 char IsInBounds : 1;
926 };
927
928private:
929 struct ExactFlagsTy {
930 char IsExact : 1;
931 };
932 struct NonNegFlagsTy {
933 char NonNeg : 1;
934 };
935 struct FastMathFlagsTy {
936 char AllowReassoc : 1;
937 char NoNaNs : 1;
938 char NoInfs : 1;
939 char NoSignedZeros : 1;
940 char AllowReciprocal : 1;
941 char AllowContract : 1;
942 char ApproxFunc : 1;
943
944 FastMathFlagsTy(const FastMathFlags &FMF);
945 };
946
947 OperationType OpType;
948
949 union {
953 ExactFlagsTy ExactFlags;
955 NonNegFlagsTy NonNegFlags;
956 FastMathFlagsTy FMFs;
957 unsigned AllFlags;
958 };
959
960protected:
962 OpType = Other.OpType;
963 AllFlags = Other.AllFlags;
964 }
965
966public:
967 template <typename IterT>
968 VPRecipeWithIRFlags(const unsigned char SC, IterT Operands, DebugLoc DL = {})
969 : VPSingleDefRecipe(SC, Operands, DL) {
970 OpType = OperationType::Other;
971 AllFlags = 0;
972 }
973
974 template <typename IterT>
975 VPRecipeWithIRFlags(const unsigned char SC, IterT Operands, Instruction &I)
977 if (auto *Op = dyn_cast<CmpInst>(&I)) {
978 OpType = OperationType::Cmp;
979 CmpPredicate = Op->getPredicate();
980 } else if (auto *Op = dyn_cast<PossiblyDisjointInst>(&I)) {
981 OpType = OperationType::DisjointOp;
982 DisjointFlags.IsDisjoint = Op->isDisjoint();
983 } else if (auto *Op = dyn_cast<OverflowingBinaryOperator>(&I)) {
984 OpType = OperationType::OverflowingBinOp;
985 WrapFlags = {Op->hasNoUnsignedWrap(), Op->hasNoSignedWrap()};
986 } else if (auto *Op = dyn_cast<PossiblyExactOperator>(&I)) {
987 OpType = OperationType::PossiblyExactOp;
988 ExactFlags.IsExact = Op->isExact();
989 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
990 OpType = OperationType::GEPOp;
991 GEPFlags.IsInBounds = GEP->isInBounds();
992 } else if (auto *PNNI = dyn_cast<PossiblyNonNegInst>(&I)) {
993 OpType = OperationType::NonNegOp;
994 NonNegFlags.NonNeg = PNNI->hasNonNeg();
995 } else if (auto *Op = dyn_cast<FPMathOperator>(&I)) {
996 OpType = OperationType::FPMathOp;
997 FMFs = Op->getFastMathFlags();
998 } else {
999 OpType = OperationType::Other;
1000 AllFlags = 0;
1001 }
1002 }
1003
1004 template <typename IterT>
1005 VPRecipeWithIRFlags(const unsigned char SC, IterT Operands,
1006 CmpInst::Predicate Pred, DebugLoc DL = {})
1007 : VPSingleDefRecipe(SC, Operands, DL), OpType(OperationType::Cmp),
1008 CmpPredicate(Pred) {}
1009
1010 template <typename IterT>
1011 VPRecipeWithIRFlags(const unsigned char SC, IterT Operands,
1013 : VPSingleDefRecipe(SC, Operands, DL),
1014 OpType(OperationType::OverflowingBinOp), WrapFlags(WrapFlags) {}
1015
1016 template <typename IterT>
1017 VPRecipeWithIRFlags(const unsigned char SC, IterT Operands,
1018 FastMathFlags FMFs, DebugLoc DL = {})
1019 : VPSingleDefRecipe(SC, Operands, DL), OpType(OperationType::FPMathOp),
1020 FMFs(FMFs) {}
1021
1022 template <typename IterT>
1023 VPRecipeWithIRFlags(const unsigned char SC, IterT Operands,
1025 : VPSingleDefRecipe(SC, Operands, DL), OpType(OperationType::DisjointOp),
1027
1028protected:
1029 template <typename IterT>
1030 VPRecipeWithIRFlags(const unsigned char SC, IterT Operands,
1031 GEPFlagsTy GEPFlags, DebugLoc DL = {})
1032 : VPSingleDefRecipe(SC, Operands, DL), OpType(OperationType::GEPOp),
1033 GEPFlags(GEPFlags) {}
1034
1035public:
1036 static inline bool classof(const VPRecipeBase *R) {
1037 return R->getVPDefID() == VPRecipeBase::VPInstructionSC ||
1038 R->getVPDefID() == VPRecipeBase::VPWidenSC ||
1039 R->getVPDefID() == VPRecipeBase::VPWidenGEPSC ||
1040 R->getVPDefID() == VPRecipeBase::VPWidenCastSC ||
1041 R->getVPDefID() == VPRecipeBase::VPReplicateSC ||
1042 R->getVPDefID() == VPRecipeBase::VPVectorPointerSC;
1043 }
1044
1045 static inline bool classof(const VPUser *U) {
1046 auto *R = dyn_cast<VPRecipeBase>(U);
1047 return R && classof(R);
1048 }
1049
1050 /// Drop all poison-generating flags.
1052 // NOTE: This needs to be kept in-sync with
1053 // Instruction::dropPoisonGeneratingFlags.
1054 switch (OpType) {
1055 case OperationType::OverflowingBinOp:
1056 WrapFlags.HasNUW = false;
1057 WrapFlags.HasNSW = false;
1058 break;
1059 case OperationType::DisjointOp:
1060 DisjointFlags.IsDisjoint = false;
1061 break;
1062 case OperationType::PossiblyExactOp:
1063 ExactFlags.IsExact = false;
1064 break;
1065 case OperationType::GEPOp:
1066 GEPFlags.IsInBounds = false;
1067 break;
1068 case OperationType::FPMathOp:
1069 FMFs.NoNaNs = false;
1070 FMFs.NoInfs = false;
1071 break;
1072 case OperationType::NonNegOp:
1073 NonNegFlags.NonNeg = false;
1074 break;
1075 case OperationType::Cmp:
1076 case OperationType::Other:
1077 break;
1078 }
1079 }
1080
1081 /// Set the IR flags for \p I.
1082 void setFlags(Instruction *I) const {
1083 switch (OpType) {
1084 case OperationType::OverflowingBinOp:
1085 I->setHasNoUnsignedWrap(WrapFlags.HasNUW);
1086 I->setHasNoSignedWrap(WrapFlags.HasNSW);
1087 break;
1088 case OperationType::DisjointOp:
1089 cast<PossiblyDisjointInst>(I)->setIsDisjoint(DisjointFlags.IsDisjoint);
1090 break;
1091 case OperationType::PossiblyExactOp:
1092 I->setIsExact(ExactFlags.IsExact);
1093 break;
1094 case OperationType::GEPOp:
1095 cast<GetElementPtrInst>(I)->setIsInBounds(GEPFlags.IsInBounds);
1096 break;
1097 case OperationType::FPMathOp:
1098 I->setHasAllowReassoc(FMFs.AllowReassoc);
1099 I->setHasNoNaNs(FMFs.NoNaNs);
1100 I->setHasNoInfs(FMFs.NoInfs);
1101 I->setHasNoSignedZeros(FMFs.NoSignedZeros);
1102 I->setHasAllowReciprocal(FMFs.AllowReciprocal);
1103 I->setHasAllowContract(FMFs.AllowContract);
1104 I->setHasApproxFunc(FMFs.ApproxFunc);
1105 break;
1106 case OperationType::NonNegOp:
1107 I->setNonNeg(NonNegFlags.NonNeg);
1108 break;
1109 case OperationType::Cmp:
1110 case OperationType::Other:
1111 break;
1112 }
1113 }
1114
1116 assert(OpType == OperationType::Cmp &&
1117 "recipe doesn't have a compare predicate");
1118 return CmpPredicate;
1119 }
1120
1121 bool isInBounds() const {
1122 assert(OpType == OperationType::GEPOp &&
1123 "recipe doesn't have inbounds flag");
1124 return GEPFlags.IsInBounds;
1125 }
1126
1127 /// Returns true if the recipe has fast-math flags.
1128 bool hasFastMathFlags() const { return OpType == OperationType::FPMathOp; }
1129
1131
1132 bool hasNoUnsignedWrap() const {
1133 assert(OpType == OperationType::OverflowingBinOp &&
1134 "recipe doesn't have a NUW flag");
1135 return WrapFlags.HasNUW;
1136 }
1137
1138 bool hasNoSignedWrap() const {
1139 assert(OpType == OperationType::OverflowingBinOp &&
1140 "recipe doesn't have a NSW flag");
1141 return WrapFlags.HasNSW;
1142 }
1143
1144 bool isDisjoint() const {
1145 assert(OpType == OperationType::DisjointOp &&
1146 "recipe cannot have a disjoing flag");
1148 }
1149
1150#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1151 void printFlags(raw_ostream &O) const;
1152#endif
1153};
1154
1155/// This is a concrete Recipe that models a single VPlan-level instruction.
1156/// While as any Recipe it may generate a sequence of IR instructions when
1157/// executed, these instructions would always form a single-def expression as
1158/// the VPInstruction is also a single def-use vertex.
1160 friend class VPlanSlp;
1161
1162public:
1163 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
1164 enum {
1166 Instruction::OtherOpsEnd + 1, // Combines the incoming and previous
1167 // values of a first-order recurrence.
1174 // Increment the canonical IV separately for each unrolled part.
1179 // Add an offset in bytes (second operand) to a base pointer (first
1180 // operand). Only generates scalar values (either for the first lane only or
1181 // for all lanes, depending on its uses).
1183 };
1184
1185private:
1186 typedef unsigned char OpcodeTy;
1187 OpcodeTy Opcode;
1188
1189 /// An optional name that can be used for the generated IR instruction.
1190 const std::string Name;
1191
1192 /// Returns true if this VPInstruction generates scalar values for all lanes.
1193 /// Most VPInstructions generate a single value per part, either vector or
1194 /// scalar. VPReplicateRecipe takes care of generating multiple (scalar)
1195 /// values per all lanes, stemming from an original ingredient. This method
1196 /// identifies the (rare) cases of VPInstructions that do so as well, w/o an
1197 /// underlying ingredient.
1198 bool doesGeneratePerAllLanes() const;
1199
1200 /// Returns true if we can generate a scalar for the first lane only if
1201 /// needed.
1202 bool canGenerateScalarForFirstLane() const;
1203
1204 /// Utility methods serving execute(): generates a single instance of the
1205 /// modeled instruction for a given part. \returns the generated value for \p
1206 /// Part. In some cases an existing value is returned rather than a generated
1207 /// one.
1208 Value *generatePerPart(VPTransformState &State, unsigned Part);
1209
1210 /// Utility methods serving execute(): generates a scalar single instance of
1211 /// the modeled instruction for a given lane. \returns the scalar generated
1212 /// value for lane \p Lane.
1213 Value *generatePerLane(VPTransformState &State, const VPIteration &Lane);
1214
1215#if !defined(NDEBUG)
1216 /// Return true if the VPInstruction is a floating point math operation, i.e.
1217 /// has fast-math flags.
1218 bool isFPMathOp() const;
1219#endif
1220
1221public:
1223 const Twine &Name = "")
1224 : VPRecipeWithIRFlags(VPDef::VPInstructionSC, Operands, DL),
1225 Opcode(Opcode), Name(Name.str()) {}
1226
1227 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands,
1228 DebugLoc DL = {}, const Twine &Name = "")
1230
1231 VPInstruction(unsigned Opcode, CmpInst::Predicate Pred, VPValue *A,
1232 VPValue *B, DebugLoc DL = {}, const Twine &Name = "");
1233
1234 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands,
1235 WrapFlagsTy WrapFlags, DebugLoc DL = {}, const Twine &Name = "")
1236 : VPRecipeWithIRFlags(VPDef::VPInstructionSC, Operands, WrapFlags, DL),
1237 Opcode(Opcode), Name(Name.str()) {}
1238
1239 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands,
1240 DisjointFlagsTy DisjointFlag, DebugLoc DL = {},
1241 const Twine &Name = "")
1242 : VPRecipeWithIRFlags(VPDef::VPInstructionSC, Operands, DisjointFlag, DL),
1243 Opcode(Opcode), Name(Name.str()) {
1244 assert(Opcode == Instruction::Or && "only OR opcodes can be disjoint");
1245 }
1246
1247 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands,
1248 FastMathFlags FMFs, DebugLoc DL = {}, const Twine &Name = "");
1249
1250 VP_CLASSOF_IMPL(VPDef::VPInstructionSC)
1251
1252 VPInstruction *clone() override {
1254 auto *New = new VPInstruction(Opcode, Operands, getDebugLoc(), Name);
1255 New->transferFlags(*this);
1256 return New;
1257 }
1258
1259 unsigned getOpcode() const { return Opcode; }
1260
1261 /// Generate the instruction.
1262 /// TODO: We currently execute only per-part unless a specific instance is
1263 /// provided.
1264 void execute(VPTransformState &State) override;
1265
1266#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1267 /// Print the VPInstruction to \p O.
1268 void print(raw_ostream &O, const Twine &Indent,
1269 VPSlotTracker &SlotTracker) const override;
1270
1271 /// Print the VPInstruction to dbgs() (for debugging).
1272 LLVM_DUMP_METHOD void dump() const;
1273#endif
1274
1275 /// Return true if this instruction may modify memory.
1276 bool mayWriteToMemory() const {
1277 // TODO: we can use attributes of the called function to rule out memory
1278 // modifications.
1279 return Opcode == Instruction::Store || Opcode == Instruction::Call ||
1280 Opcode == Instruction::Invoke || Opcode == SLPStore;
1281 }
1282
1283 bool hasResult() const {
1284 // CallInst may or may not have a result, depending on the called function.
1285 // Conservatively return calls have results for now.
1286 switch (getOpcode()) {
1287 case Instruction::Ret:
1288 case Instruction::Br:
1289 case Instruction::Store:
1290 case Instruction::Switch:
1291 case Instruction::IndirectBr:
1292 case Instruction::Resume:
1293 case Instruction::CatchRet:
1294 case Instruction::Unreachable:
1295 case Instruction::Fence:
1296 case Instruction::AtomicRMW:
1299 return false;
1300 default:
1301 return true;
1302 }
1303 }
1304
1305 /// Returns true if the recipe only uses the first lane of operand \p Op.
1306 bool onlyFirstLaneUsed(const VPValue *Op) const override;
1307
1308 /// Returns true if the recipe only uses the first part of operand \p Op.
1309 bool onlyFirstPartUsed(const VPValue *Op) const override {
1311 "Op must be an operand of the recipe");
1312 if (getOperand(0) != Op)
1313 return false;
1314 switch (getOpcode()) {
1315 default:
1316 return false;
1319 return true;
1320 };
1321 llvm_unreachable("switch should return");
1322 }
1323};
1324
1325/// VPWidenRecipe is a recipe for producing a copy of vector type its
1326/// ingredient. This recipe covers most of the traditional vectorization cases
1327/// where each ingredient transforms into a vectorized version of itself.
1329 unsigned Opcode;
1330
1331public:
1332 template <typename IterT>
1334 : VPRecipeWithIRFlags(VPDef::VPWidenSC, Operands, I),
1335 Opcode(I.getOpcode()) {}
1336
1337 ~VPWidenRecipe() override = default;
1338
1339 VPWidenRecipe *clone() override {
1340 auto *R = new VPWidenRecipe(*getUnderlyingInstr(), operands());
1341 R->transferFlags(*this);
1342 return R;
1343 }
1344
1345 VP_CLASSOF_IMPL(VPDef::VPWidenSC)
1346
1347 /// Produce widened copies of all Ingredients.
1348 void execute(VPTransformState &State) override;
1349
1350 unsigned getOpcode() const { return Opcode; }
1351
1352#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1353 /// Print the recipe.
1354 void print(raw_ostream &O, const Twine &Indent,
1355 VPSlotTracker &SlotTracker) const override;
1356#endif
1357};
1358
1359/// VPWidenCastRecipe is a recipe to create vector cast instructions.
1361 /// Cast instruction opcode.
1362 Instruction::CastOps Opcode;
1363
1364 /// Result type for the cast.
1365 Type *ResultTy;
1366
1367public:
1369 CastInst &UI)
1370 : VPRecipeWithIRFlags(VPDef::VPWidenCastSC, Op, UI), Opcode(Opcode),
1371 ResultTy(ResultTy) {
1372 assert(UI.getOpcode() == Opcode &&
1373 "opcode of underlying cast doesn't match");
1374 assert(UI.getType() == ResultTy &&
1375 "result type of underlying cast doesn't match");
1376 }
1377
1379 : VPRecipeWithIRFlags(VPDef::VPWidenCastSC, Op), Opcode(Opcode),
1380 ResultTy(ResultTy) {}
1381
1382 ~VPWidenCastRecipe() override = default;
1383
1385 if (auto *UV = getUnderlyingValue())
1386 return new VPWidenCastRecipe(Opcode, getOperand(0), ResultTy,
1387 *cast<CastInst>(UV));
1388
1389 return new VPWidenCastRecipe(Opcode, getOperand(0), ResultTy);
1390 }
1391
1392 VP_CLASSOF_IMPL(VPDef::VPWidenCastSC)
1393
1394 /// Produce widened copies of the cast.
1395 void execute(VPTransformState &State) override;
1396
1397#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1398 /// Print the recipe.
1399 void print(raw_ostream &O, const Twine &Indent,
1400 VPSlotTracker &SlotTracker) const override;
1401#endif
1402
1403 Instruction::CastOps getOpcode() const { return Opcode; }
1404
1405 /// Returns the result type of the cast.
1406 Type *getResultType() const { return ResultTy; }
1407};
1408
1409/// VPScalarCastRecipe is a recipe to create scalar cast instructions.
1411 Instruction::CastOps Opcode;
1412
1413 Type *ResultTy;
1414
1415 Value *generate(VPTransformState &State, unsigned Part);
1416
1417public:
1419 : VPSingleDefRecipe(VPDef::VPScalarCastSC, {Op}), Opcode(Opcode),
1420 ResultTy(ResultTy) {}
1421
1422 ~VPScalarCastRecipe() override = default;
1423
1425 return new VPScalarCastRecipe(Opcode, getOperand(0), ResultTy);
1426 }
1427
1428 VP_CLASSOF_IMPL(VPDef::VPScalarCastSC)
1429
1430 void execute(VPTransformState &State) override;
1431
1432#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1433 void print(raw_ostream &O, const Twine &Indent,
1434 VPSlotTracker &SlotTracker) const override;
1435#endif
1436
1437 /// Returns the result type of the cast.
1438 Type *getResultType() const { return ResultTy; }
1439
1440 bool onlyFirstLaneUsed(const VPValue *Op) const override {
1441 // At the moment, only uniform codegen is implemented.
1443 "Op must be an operand of the recipe");
1444 return true;
1445 }
1446};
1447
1448/// A recipe for widening Call instructions.
1450 /// ID of the vector intrinsic to call when widening the call. If set the
1451 /// Intrinsic::not_intrinsic, a library call will be used instead.
1452 Intrinsic::ID VectorIntrinsicID;
1453 /// If this recipe represents a library call, Variant stores a pointer to
1454 /// the chosen function. There is a 1:1 mapping between a given VF and the
1455 /// chosen vectorized variant, so there will be a different vplan for each
1456 /// VF with a valid variant.
1457 Function *Variant;
1458
1459public:
1460 template <typename IterT>
1462 Intrinsic::ID VectorIntrinsicID, DebugLoc DL = {},
1463 Function *Variant = nullptr)
1464 : VPSingleDefRecipe(VPDef::VPWidenCallSC, CallArguments, UV, DL),
1465 VectorIntrinsicID(VectorIntrinsicID), Variant(Variant) {
1466 assert(
1467 isa<Function>(getOperand(getNumOperands() - 1)->getLiveInIRValue()) &&
1468 "last operand must be the called function");
1469 }
1470
1471 ~VPWidenCallRecipe() override = default;
1472
1475 VectorIntrinsicID, getDebugLoc(), Variant);
1476 }
1477
1478 VP_CLASSOF_IMPL(VPDef::VPWidenCallSC)
1479
1480 /// Produce a widened version of the call instruction.
1481 void execute(VPTransformState &State) override;
1482
1484 return cast<Function>(getOperand(getNumOperands() - 1)->getLiveInIRValue());
1485 }
1486
1488 return make_range(op_begin(), op_begin() + getNumOperands() - 1);
1489 }
1491 return make_range(op_begin(), op_begin() + getNumOperands() - 1);
1492 }
1493
1494#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1495 /// Print the recipe.
1496 void print(raw_ostream &O, const Twine &Indent,
1497 VPSlotTracker &SlotTracker) const override;
1498#endif
1499};
1500
1501/// A recipe for widening select instructions.
1503 template <typename IterT>
1505 : VPSingleDefRecipe(VPDef::VPWidenSelectSC, Operands, &I,
1506 I.getDebugLoc()) {}
1507
1508 ~VPWidenSelectRecipe() override = default;
1509
1511 return new VPWidenSelectRecipe(*cast<SelectInst>(getUnderlyingInstr()),
1512 operands());
1513 }
1514
1515 VP_CLASSOF_IMPL(VPDef::VPWidenSelectSC)
1516
1517 /// Produce a widened version of the select instruction.
1518 void execute(VPTransformState &State) override;
1519
1520#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1521 /// Print the recipe.
1522 void print(raw_ostream &O, const Twine &Indent,
1523 VPSlotTracker &SlotTracker) const override;
1524#endif
1525
1526 VPValue *getCond() const {
1527 return getOperand(0);
1528 }
1529
1530 bool isInvariantCond() const {
1532 }
1533};
1534
1535/// A recipe for handling GEP instructions.
1537 bool isPointerLoopInvariant() const {
1539 }
1540
1541 bool isIndexLoopInvariant(unsigned I) const {
1543 }
1544
1545 bool areAllOperandsInvariant() const {
1546 return all_of(operands(), [](VPValue *Op) {
1547 return Op->isDefinedOutsideVectorRegions();
1548 });
1549 }
1550
1551public:
1552 template <typename IterT>
1554 : VPRecipeWithIRFlags(VPDef::VPWidenGEPSC, Operands, *GEP) {}
1555
1556 ~VPWidenGEPRecipe() override = default;
1557
1559 return new VPWidenGEPRecipe(cast<GetElementPtrInst>(getUnderlyingInstr()),
1560 operands());
1561 }
1562
1563 VP_CLASSOF_IMPL(VPDef::VPWidenGEPSC)
1564
1565 /// Generate the gep nodes.
1566 void execute(VPTransformState &State) override;
1567
1568#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1569 /// Print the recipe.
1570 void print(raw_ostream &O, const Twine &Indent,
1571 VPSlotTracker &SlotTracker) const override;
1572#endif
1573};
1574
1575/// A recipe to compute the pointers for widened memory accesses of IndexTy for
1576/// all parts. If IsReverse is true, compute pointers for accessing the input in
1577/// reverse order per part.
1579 Type *IndexedTy;
1580 bool IsReverse;
1581
1582public:
1583 VPVectorPointerRecipe(VPValue *Ptr, Type *IndexedTy, bool IsReverse,
1584 bool IsInBounds, DebugLoc DL)
1585 : VPRecipeWithIRFlags(VPDef::VPVectorPointerSC, ArrayRef<VPValue *>(Ptr),
1586 GEPFlagsTy(IsInBounds), DL),
1587 IndexedTy(IndexedTy), IsReverse(IsReverse) {}
1588
1589 VP_CLASSOF_IMPL(VPDef::VPVectorPointerSC)
1590
1591 void execute(VPTransformState &State) override;
1592
1593 bool onlyFirstLaneUsed(const VPValue *Op) const override {
1595 "Op must be an operand of the recipe");
1596 return true;
1597 }
1598
1600 return new VPVectorPointerRecipe(getOperand(0), IndexedTy, IsReverse,
1601 isInBounds(), getDebugLoc());
1602 }
1603
1604#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1605 /// Print the recipe.
1606 void print(raw_ostream &O, const Twine &Indent,
1607 VPSlotTracker &SlotTracker) const override;
1608#endif
1609};
1610
1611/// A pure virtual base class for all recipes modeling header phis, including
1612/// phis for first order recurrences, pointer inductions and reductions. The
1613/// start value is the first operand of the recipe and the incoming value from
1614/// the backedge is the second operand.
1615///
1616/// Inductions are modeled using the following sub-classes:
1617/// * VPCanonicalIVPHIRecipe: Canonical scalar induction of the vector loop,
1618/// starting at a specified value (zero for the main vector loop, the resume
1619/// value for the epilogue vector loop) and stepping by 1. The induction
1620/// controls exiting of the vector loop by comparing against the vector trip
1621/// count. Produces a single scalar PHI for the induction value per
1622/// iteration.
1623/// * VPWidenIntOrFpInductionRecipe: Generates vector values for integer and
1624/// floating point inductions with arbitrary start and step values. Produces
1625/// a vector PHI per-part.
1626/// * VPDerivedIVRecipe: Converts the canonical IV value to the corresponding
1627/// value of an IV with different start and step values. Produces a single
1628/// scalar value per iteration
1629/// * VPScalarIVStepsRecipe: Generates scalar values per-lane based on a
1630/// canonical or derived induction.
1631/// * VPWidenPointerInductionRecipe: Generate vector and scalar values for a
1632/// pointer induction. Produces either a vector PHI per-part or scalar values
1633/// per-lane based on the canonical induction.
1635protected:
1636 VPHeaderPHIRecipe(unsigned char VPDefID, Instruction *UnderlyingInstr,
1637 VPValue *Start = nullptr, DebugLoc DL = {})
1638 : VPSingleDefRecipe(VPDefID, ArrayRef<VPValue *>(), UnderlyingInstr, DL) {
1639 if (Start)
1640 addOperand(Start);
1641 }
1642
1643public:
1644 ~VPHeaderPHIRecipe() override = default;
1645
1646 /// Method to support type inquiry through isa, cast, and dyn_cast.
1647 static inline bool classof(const VPRecipeBase *B) {
1648 return B->getVPDefID() >= VPDef::VPFirstHeaderPHISC &&
1649 B->getVPDefID() <= VPDef::VPLastHeaderPHISC;
1650 }
1651 static inline bool classof(const VPValue *V) {
1652 auto *B = V->getDefiningRecipe();
1653 return B && B->getVPDefID() >= VPRecipeBase::VPFirstHeaderPHISC &&
1654 B->getVPDefID() <= VPRecipeBase::VPLastHeaderPHISC;
1655 }
1656
1657 /// Generate the phi nodes.
1658 void execute(VPTransformState &State) override = 0;
1659
1660#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1661 /// Print the recipe.
1662 void print(raw_ostream &O, const Twine &Indent,
1663 VPSlotTracker &SlotTracker) const override = 0;
1664#endif
1665
1666 /// Returns the start value of the phi, if one is set.
1668 return getNumOperands() == 0 ? nullptr : getOperand(0);
1669 }
1671 return getNumOperands() == 0 ? nullptr : getOperand(0);
1672 }
1673
1674 /// Update the start value of the recipe.
1676
1677 /// Returns the incoming value from the loop backedge.
1679 return getOperand(1);
1680 }
1681
1682 /// Returns the backedge value as a recipe. The backedge value is guaranteed
1683 /// to be a recipe.
1686 }
1687};
1688
1689/// A recipe for handling phi nodes of integer and floating-point inductions,
1690/// producing their vector values.
1692 PHINode *IV;
1693 TruncInst *Trunc;
1694 const InductionDescriptor &IndDesc;
1695
1696public:
1698 const InductionDescriptor &IndDesc)
1699 : VPHeaderPHIRecipe(VPDef::VPWidenIntOrFpInductionSC, IV, Start), IV(IV),
1700 Trunc(nullptr), IndDesc(IndDesc) {
1701 addOperand(Step);
1702 }
1703
1705 const InductionDescriptor &IndDesc,
1706 TruncInst *Trunc)
1707 : VPHeaderPHIRecipe(VPDef::VPWidenIntOrFpInductionSC, Trunc, Start),
1708 IV(IV), Trunc(Trunc), IndDesc(IndDesc) {
1709 addOperand(Step);
1710 }
1711
1713
1716 getStepValue(), IndDesc, Trunc);
1717 }
1718
1719 VP_CLASSOF_IMPL(VPDef::VPWidenIntOrFpInductionSC)
1720
1721 /// Generate the vectorized and scalarized versions of the phi node as
1722 /// needed by their users.
1723 void execute(VPTransformState &State) override;
1724
1725#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1726 /// Print the recipe.
1727 void print(raw_ostream &O, const Twine &Indent,
1728 VPSlotTracker &SlotTracker) const override;
1729#endif
1730
1732 // TODO: All operands of base recipe must exist and be at same index in
1733 // derived recipe.
1735 "VPWidenIntOrFpInductionRecipe generates its own backedge value");
1736 }
1737
1739 // TODO: All operands of base recipe must exist and be at same index in
1740 // derived recipe.
1742 "VPWidenIntOrFpInductionRecipe generates its own backedge value");
1743 }
1744
1745 /// Returns the step value of the induction.
1747 const VPValue *getStepValue() const { return getOperand(1); }
1748
1749 /// Returns the first defined value as TruncInst, if it is one or nullptr
1750 /// otherwise.
1751 TruncInst *getTruncInst() { return Trunc; }
1752 const TruncInst *getTruncInst() const { return Trunc; }
1753
1754 PHINode *getPHINode() { return IV; }
1755
1756 /// Returns the induction descriptor for the recipe.
1757 const InductionDescriptor &getInductionDescriptor() const { return IndDesc; }
1758
1759 /// Returns true if the induction is canonical, i.e. starting at 0 and
1760 /// incremented by UF * VF (= the original IV is incremented by 1) and has the
1761 /// same type as the canonical induction.
1762 bool isCanonical() const;
1763
1764 /// Returns the scalar type of the induction.
1766 return Trunc ? Trunc->getType() : IV->getType();
1767 }
1768};
1769
1771 const InductionDescriptor &IndDesc;
1772
1773 bool IsScalarAfterVectorization;
1774
1775public:
1776 /// Create a new VPWidenPointerInductionRecipe for \p Phi with start value \p
1777 /// Start.
1779 const InductionDescriptor &IndDesc,
1780 bool IsScalarAfterVectorization)
1781 : VPHeaderPHIRecipe(VPDef::VPWidenPointerInductionSC, Phi),
1782 IndDesc(IndDesc),
1783 IsScalarAfterVectorization(IsScalarAfterVectorization) {
1784 addOperand(Start);
1785 addOperand(Step);
1786 }
1787
1789
1792 cast<PHINode>(getUnderlyingInstr()), getOperand(0), getOperand(1),
1793 IndDesc, IsScalarAfterVectorization);
1794 }
1795
1796 VP_CLASSOF_IMPL(VPDef::VPWidenPointerInductionSC)
1797
1798 /// Generate vector values for the pointer induction.
1799 void execute(VPTransformState &State) override;
1800
1801 /// Returns true if only scalar values will be generated.
1802 bool onlyScalarsGenerated(bool IsScalable);
1803
1804 /// Returns the induction descriptor for the recipe.
1805 const InductionDescriptor &getInductionDescriptor() const { return IndDesc; }
1806
1807#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1808 /// Print the recipe.
1809 void print(raw_ostream &O, const Twine &Indent,
1810 VPSlotTracker &SlotTracker) const override;
1811#endif
1812};
1813
1814/// A recipe for handling phis that are widened in the vector loop.
1815/// In the VPlan native path, all incoming VPValues & VPBasicBlock pairs are
1816/// managed in the recipe directly.
1818 /// List of incoming blocks. Only used in the VPlan native path.
1819 SmallVector<VPBasicBlock *, 2> IncomingBlocks;
1820
1821public:
1822 /// Create a new VPWidenPHIRecipe for \p Phi with start value \p Start.
1823 VPWidenPHIRecipe(PHINode *Phi, VPValue *Start = nullptr)
1824 : VPSingleDefRecipe(VPDef::VPWidenPHISC, ArrayRef<VPValue *>(), Phi) {
1825 if (Start)
1826 addOperand(Start);
1827 }
1828
1830 llvm_unreachable("cloning not implemented yet");
1831 }
1832
1833 ~VPWidenPHIRecipe() override = default;
1834
1835 VP_CLASSOF_IMPL(VPDef::VPWidenPHISC)
1836
1837 /// Generate the phi/select nodes.
1838 void execute(VPTransformState &State) override;
1839
1840#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1841 /// Print the recipe.
1842 void print(raw_ostream &O, const Twine &Indent,
1843 VPSlotTracker &SlotTracker) const override;
1844#endif
1845
1846 /// Adds a pair (\p IncomingV, \p IncomingBlock) to the phi.
1847 void addIncoming(VPValue *IncomingV, VPBasicBlock *IncomingBlock) {
1848 addOperand(IncomingV);
1849 IncomingBlocks.push_back(IncomingBlock);
1850 }
1851
1852 /// Returns the \p I th incoming VPBasicBlock.
1853 VPBasicBlock *getIncomingBlock(unsigned I) { return IncomingBlocks[I]; }
1854
1855 /// Returns the \p I th incoming VPValue.
1856 VPValue *getIncomingValue(unsigned I) { return getOperand(I); }
1857};
1858
1859/// A recipe for handling first-order recurrence phis. The start value is the
1860/// first operand of the recipe and the incoming value from the backedge is the
1861/// second operand.
1864 : VPHeaderPHIRecipe(VPDef::VPFirstOrderRecurrencePHISC, Phi, &Start) {}
1865
1866 VP_CLASSOF_IMPL(VPDef::VPFirstOrderRecurrencePHISC)
1867
1869 return R->getVPDefID() == VPDef::VPFirstOrderRecurrencePHISC;
1870 }
1871
1874 cast<PHINode>(getUnderlyingInstr()), *getOperand(0));
1875 }
1876
1877 void execute(VPTransformState &State) override;
1878
1879#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1880 /// Print the recipe.
1881 void print(raw_ostream &O, const Twine &Indent,
1882 VPSlotTracker &SlotTracker) const override;
1883#endif
1884};
1885
1886/// A recipe for handling reduction phis. The start value is the first operand
1887/// of the recipe and the incoming value from the backedge is the second
1888/// operand.
1890 /// Descriptor for the reduction.
1891 const RecurrenceDescriptor &RdxDesc;
1892
1893 /// The phi is part of an in-loop reduction.
1894 bool IsInLoop;
1895
1896 /// The phi is part of an ordered reduction. Requires IsInLoop to be true.
1897 bool IsOrdered;
1898
1899public:
1900 /// Create a new VPReductionPHIRecipe for the reduction \p Phi described by \p
1901 /// RdxDesc.
1903 VPValue &Start, bool IsInLoop = false,
1904 bool IsOrdered = false)
1905 : VPHeaderPHIRecipe(VPDef::VPReductionPHISC, Phi, &Start),
1906 RdxDesc(RdxDesc), IsInLoop(IsInLoop), IsOrdered(IsOrdered) {
1907 assert((!IsOrdered || IsInLoop) && "IsOrdered requires IsInLoop");
1908 }
1909
1910 ~VPReductionPHIRecipe() override = default;
1911
1913 auto *R =
1914 new VPReductionPHIRecipe(cast<PHINode>(getUnderlyingInstr()), RdxDesc,
1915 *getOperand(0), IsInLoop, IsOrdered);
1916 R->addOperand(getBackedgeValue());
1917 return R;
1918 }
1919
1920 VP_CLASSOF_IMPL(VPDef::VPReductionPHISC)
1921
1923 return R->getVPDefID() == VPDef::VPReductionPHISC;
1924 }
1925
1926 /// Generate the phi/select nodes.
1927 void execute(VPTransformState &State) override;
1928
1929#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1930 /// Print the recipe.
1931 void print(raw_ostream &O, const Twine &Indent,
1932 VPSlotTracker &SlotTracker) const override;
1933#endif
1934
1936 return RdxDesc;
1937 }
1938
1939 /// Returns true, if the phi is part of an ordered reduction.
1940 bool isOrdered() const { return IsOrdered; }
1941
1942 /// Returns true, if the phi is part of an in-loop reduction.
1943 bool isInLoop() const { return IsInLoop; }
1944};
1945
1946/// A recipe for vectorizing a phi-node as a sequence of mask-based select
1947/// instructions.
1949public:
1950 /// The blend operation is a User of the incoming values and of their
1951 /// respective masks, ordered [I0, I1, M1, I2, M2, ...]. Note that the first
1952 /// incoming value does not have a mask associated.
1954 : VPSingleDefRecipe(VPDef::VPBlendSC, Operands, Phi, Phi->getDebugLoc()) {
1955 assert((Operands.size() + 1) % 2 == 0 &&
1956 "Expected an odd number of operands");
1957 }
1958
1959 VPBlendRecipe *clone() override {
1961 return new VPBlendRecipe(cast<PHINode>(getUnderlyingValue()), Ops);
1962 }
1963
1964 VP_CLASSOF_IMPL(VPDef::VPBlendSC)
1965
1966 /// Return the number of incoming values, taking into account that the first
1967 /// incoming value has no mask.
1968 unsigned getNumIncomingValues() const { return (getNumOperands() + 1) / 2; }
1969
1970 /// Return incoming value number \p Idx.
1971 VPValue *getIncomingValue(unsigned Idx) const {
1972 return Idx == 0 ? getOperand(0) : getOperand(Idx * 2 - 1);
1973 }
1974
1975 /// Return mask number \p Idx.
1976 VPValue *getMask(unsigned Idx) const {
1977 assert(Idx > 0 && "First index has no mask associated.");
1978 return getOperand(Idx * 2);
1979 }
1980
1981 /// Generate the phi/select nodes.
1982 void execute(VPTransformState &State) override;
1983
1984#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1985 /// Print the recipe.
1986 void print(raw_ostream &O, const Twine &Indent,
1987 VPSlotTracker &SlotTracker) const override;
1988#endif
1989
1990 /// Returns true if the recipe only uses the first lane of operand \p Op.
1991 bool onlyFirstLaneUsed(const VPValue *Op) const override {
1993 "Op must be an operand of the recipe");
1994 // Recursing through Blend recipes only, must terminate at header phi's the
1995 // latest.
1996 return all_of(users(),
1997 [this](VPUser *U) { return U->onlyFirstLaneUsed(this); });
1998 }
1999};
2000
2001/// VPInterleaveRecipe is a recipe for transforming an interleave group of load
2002/// or stores into one wide load/store and shuffles. The first operand of a
2003/// VPInterleave recipe is the address, followed by the stored values, followed
2004/// by an optional mask.
2007
2008 /// Indicates if the interleave group is in a conditional block and requires a
2009 /// mask.
2010 bool HasMask = false;
2011
2012 /// Indicates if gaps between members of the group need to be masked out or if
2013 /// unusued gaps can be loaded speculatively.
2014 bool NeedsMaskForGaps = false;
2015
2016public:
2018 ArrayRef<VPValue *> StoredValues, VPValue *Mask,
2019 bool NeedsMaskForGaps)
2020 : VPRecipeBase(VPDef::VPInterleaveSC, {Addr}), IG(IG),
2021 NeedsMaskForGaps(NeedsMaskForGaps) {
2022 for (unsigned i = 0; i < IG->getFactor(); ++i)
2023 if (Instruction *I = IG->getMember(i)) {
2024 if (I->getType()->isVoidTy())
2025 continue;
2026 new VPValue(I, this);
2027 }
2028
2029 for (auto *SV : StoredValues)
2030 addOperand(SV);
2031 if (Mask) {
2032 HasMask = true;
2033 addOperand(Mask);
2034 }
2035 }
2036 ~VPInterleaveRecipe() override = default;
2037
2039 return new VPInterleaveRecipe(IG, getAddr(), getStoredValues(), getMask(),
2040 NeedsMaskForGaps);
2041 }
2042
2043 VP_CLASSOF_IMPL(VPDef::VPInterleaveSC)
2044
2045 /// Return the address accessed by this recipe.
2046 VPValue *getAddr() const {
2047 return getOperand(0); // Address is the 1st, mandatory operand.
2048 }
2049
2050 /// Return the mask used by this recipe. Note that a full mask is represented
2051 /// by a nullptr.
2052 VPValue *getMask() const {
2053 // Mask is optional and therefore the last, currently 2nd operand.
2054 return HasMask ? getOperand(getNumOperands() - 1) : nullptr;
2055 }
2056
2057 /// Return the VPValues stored by this interleave group. If it is a load
2058 /// interleave group, return an empty ArrayRef.
2060 // The first operand is the address, followed by the stored values, followed
2061 // by an optional mask.
2064 }
2065
2066 /// Generate the wide load or store, and shuffles.
2067 void execute(VPTransformState &State) override;
2068
2069#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2070 /// Print the recipe.
2071 void print(raw_ostream &O, const Twine &Indent,
2072 VPSlotTracker &SlotTracker) const override;
2073#endif
2074
2076
2077 /// Returns the number of stored operands of this interleave group. Returns 0
2078 /// for load interleave groups.
2079 unsigned getNumStoreOperands() const {
2080 return getNumOperands() - (HasMask ? 2 : 1);
2081 }
2082
2083 /// The recipe only uses the first lane of the address.
2084 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2086 "Op must be an operand of the recipe");
2087 return Op == getAddr() && !llvm::is_contained(getStoredValues(), Op);
2088 }
2089};
2090
2091/// A recipe to represent inloop reduction operations, performing a reduction on
2092/// a vector operand into a scalar value, and adding the result to a chain.
2093/// The Operands are {ChainOp, VecOp, [Condition]}.
2095 /// The recurrence decriptor for the reduction in question.
2096 const RecurrenceDescriptor &RdxDesc;
2097 bool IsOrdered;
2098
2099public:
2101 VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp,
2102 bool IsOrdered)
2103 : VPSingleDefRecipe(VPDef::VPReductionSC,
2104 ArrayRef<VPValue *>({ChainOp, VecOp}), I),
2105 RdxDesc(R), IsOrdered(IsOrdered) {
2106 if (CondOp)
2107 addOperand(CondOp);
2108 }
2109
2110 ~VPReductionRecipe() override = default;
2111
2113 return new VPReductionRecipe(RdxDesc, getUnderlyingInstr(), getChainOp(),
2114 getVecOp(), getCondOp(), IsOrdered);
2115 }
2116
2117 VP_CLASSOF_IMPL(VPDef::VPReductionSC)
2118
2119 /// Generate the reduction in the loop
2120 void execute(VPTransformState &State) override;
2121
2122#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2123 /// Print the recipe.
2124 void print(raw_ostream &O, const Twine &Indent,
2125 VPSlotTracker &SlotTracker) const override;
2126#endif
2127
2128 /// The VPValue of the scalar Chain being accumulated.
2129 VPValue *getChainOp() const { return getOperand(0); }
2130 /// The VPValue of the vector value to be reduced.
2131 VPValue *getVecOp() const { return getOperand(1); }
2132 /// The VPValue of the condition for the block.
2134 return getNumOperands() > 2 ? getOperand(2) : nullptr;
2135 }
2136};
2137
2138/// VPReplicateRecipe replicates a given instruction producing multiple scalar
2139/// copies of the original scalar type, one per lane, instead of producing a
2140/// single copy of widened type for all lanes. If the instruction is known to be
2141/// uniform only one copy, per lane zero, will be generated.
2143 /// Indicator if only a single replica per lane is needed.
2144 bool IsUniform;
2145
2146 /// Indicator if the replicas are also predicated.
2147 bool IsPredicated;
2148
2149public:
2150 template <typename IterT>
2152 bool IsUniform, VPValue *Mask = nullptr)
2153 : VPRecipeWithIRFlags(VPDef::VPReplicateSC, Operands, *I),
2154 IsUniform(IsUniform), IsPredicated(Mask) {
2155 if (Mask)
2156 addOperand(Mask);
2157 }
2158
2159 ~VPReplicateRecipe() override = default;
2160
2162 auto *Copy =
2163 new VPReplicateRecipe(getUnderlyingInstr(), operands(), IsUniform,
2164 isPredicated() ? getMask() : nullptr);
2165 Copy->transferFlags(*this);
2166 return Copy;
2167 }
2168
2169 VP_CLASSOF_IMPL(VPDef::VPReplicateSC)
2170
2171 /// Generate replicas of the desired Ingredient. Replicas will be generated
2172 /// for all parts and lanes unless a specific part and lane are specified in
2173 /// the \p State.
2174 void execute(VPTransformState &State) override;
2175
2176#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2177 /// Print the recipe.
2178 void print(raw_ostream &O, const Twine &Indent,
2179 VPSlotTracker &SlotTracker) const override;
2180#endif
2181
2182 bool isUniform() const { return IsUniform; }
2183
2184 bool isPredicated() const { return IsPredicated; }
2185
2186 /// Returns true if the recipe only uses the first lane of operand \p Op.
2187 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2189 "Op must be an operand of the recipe");
2190 return isUniform();
2191 }
2192
2193 /// Returns true if the recipe uses scalars of operand \p Op.
2194 bool usesScalars(const VPValue *Op) const override {
2196 "Op must be an operand of the recipe");
2197 return true;
2198 }
2199
2200 /// Returns true if the recipe is used by a widened recipe via an intervening
2201 /// VPPredInstPHIRecipe. In this case, the scalar values should also be packed
2202 /// in a vector.
2203 bool shouldPack() const;
2204
2205 /// Return the mask of a predicated VPReplicateRecipe.
2207 assert(isPredicated() && "Trying to get the mask of a unpredicated recipe");
2208 return getOperand(getNumOperands() - 1);
2209 }
2210
2211 unsigned getOpcode() const { return getUnderlyingInstr()->getOpcode(); }
2212};
2213
2214/// A recipe for generating conditional branches on the bits of a mask.
2216public:
2218 : VPRecipeBase(VPDef::VPBranchOnMaskSC, {}) {
2219 if (BlockInMask) // nullptr means all-one mask.
2220 addOperand(BlockInMask);
2221 }
2222
2224 return new VPBranchOnMaskRecipe(getOperand(0));
2225 }
2226
2227 VP_CLASSOF_IMPL(VPDef::VPBranchOnMaskSC)
2228
2229 /// Generate the extraction of the appropriate bit from the block mask and the
2230 /// conditional branch.
2231 void execute(VPTransformState &State) override;
2232
2233#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2234 /// Print the recipe.
2235 void print(raw_ostream &O, const Twine &Indent,
2236 VPSlotTracker &SlotTracker) const override {
2237 O << Indent << "BRANCH-ON-MASK ";
2238 if (VPValue *Mask = getMask())
2239 Mask->printAsOperand(O, SlotTracker);
2240 else
2241 O << " All-One";
2242 }
2243#endif
2244
2245 /// Return the mask used by this recipe. Note that a full mask is represented
2246 /// by a nullptr.
2247 VPValue *getMask() const {
2248 assert(getNumOperands() <= 1 && "should have either 0 or 1 operands");
2249 // Mask is optional.
2250 return getNumOperands() == 1 ? getOperand(0) : nullptr;
2251 }
2252
2253 /// Returns true if the recipe uses scalars of operand \p Op.
2254 bool usesScalars(const VPValue *Op) const override {
2256 "Op must be an operand of the recipe");
2257 return true;
2258 }
2259};
2260
2261/// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
2262/// control converges back from a Branch-on-Mask. The phi nodes are needed in
2263/// order to merge values that are set under such a branch and feed their uses.
2264/// The phi nodes can be scalar or vector depending on the users of the value.
2265/// This recipe works in concert with VPBranchOnMaskRecipe.
2267public:
2268 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
2269 /// nodes after merging back from a Branch-on-Mask.
2271 : VPSingleDefRecipe(VPDef::VPPredInstPHISC, PredV) {}
2272 ~VPPredInstPHIRecipe() override = default;
2273
2275 return new VPPredInstPHIRecipe(getOperand(0));
2276 }
2277
2278 VP_CLASSOF_IMPL(VPDef::VPPredInstPHISC)
2279
2280 /// Generates phi nodes for live-outs as needed to retain SSA form.
2281 void execute(VPTransformState &State) override;
2282
2283#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2284 /// Print the recipe.
2285 void print(raw_ostream &O, const Twine &Indent,
2286 VPSlotTracker &SlotTracker) const override;
2287#endif
2288
2289 /// Returns true if the recipe uses scalars of operand \p Op.
2290 bool usesScalars(const VPValue *Op) const override {
2292 "Op must be an operand of the recipe");
2293 return true;
2294 }
2295};
2296
2297/// A common base class for widening memory operations. An optional mask can be
2298/// provided as the last operand.
2300protected:
2302
2303 /// Whether the accessed addresses are consecutive.
2305
2306 /// Whether the consecutive accessed addresses are in reverse order.
2308
2309 /// Whether the memory access is masked.
2310 bool IsMasked = false;
2311
2312 void setMask(VPValue *Mask) {
2313 assert(!IsMasked && "cannot re-set mask");
2314 if (!Mask)
2315 return;
2316 addOperand(Mask);
2317 IsMasked = true;
2318 }
2319
2320 VPWidenMemoryRecipe(const char unsigned SC, Instruction &I,
2321 std::initializer_list<VPValue *> Operands,
2322 bool Consecutive, bool Reverse, DebugLoc DL)
2324 Reverse(Reverse) {
2325 assert((Consecutive || !Reverse) && "Reverse implies consecutive");
2326 }
2327
2328public:
2330 llvm_unreachable("cloning not supported");
2331 }
2332
2333 static inline bool classof(const VPRecipeBase *R) {
2334 return R->getVPDefID() == VPRecipeBase::VPWidenLoadSC ||
2335 R->getVPDefID() == VPRecipeBase::VPWidenStoreSC ||
2336 R->getVPDefID() == VPRecipeBase::VPWidenLoadEVLSC ||
2337 R->getVPDefID() == VPRecipeBase::VPWidenStoreEVLSC;
2338 }
2339
2340 static inline bool classof(const VPUser *U) {
2341 auto *R = dyn_cast<VPRecipeBase>(U);
2342 return R && classof(R);
2343 }
2344
2345 /// Return whether the loaded-from / stored-to addresses are consecutive.
2346 bool isConsecutive() const { return Consecutive; }
2347
2348 /// Return whether the consecutive loaded/stored addresses are in reverse
2349 /// order.
2350 bool isReverse() const { return Reverse; }
2351
2352 /// Return the address accessed by this recipe.
2353 VPValue *getAddr() const { return getOperand(0); }
2354
2355 /// Returns true if the recipe is masked.
2356 bool isMasked() const { return IsMasked; }
2357
2358 /// Return the mask used by this recipe. Note that a full mask is represented
2359 /// by a nullptr.
2360 VPValue *getMask() const {
2361 // Mask is optional and therefore the last operand.
2362 return isMasked() ? getOperand(getNumOperands() - 1) : nullptr;
2363 }
2364
2365 /// Generate the wide load/store.
2366 void execute(VPTransformState &State) override {
2367 llvm_unreachable("VPWidenMemoryRecipe should not be instantiated.");
2368 }
2369
2371};
2372
2373/// A recipe for widening load operations, using the address to load from and an
2374/// optional mask.
2375struct VPWidenLoadRecipe final : public VPWidenMemoryRecipe, public VPValue {
2377 bool Consecutive, bool Reverse, DebugLoc DL)
2378 : VPWidenMemoryRecipe(VPDef::VPWidenLoadSC, Load, {Addr}, Consecutive,
2379 Reverse, DL),
2380 VPValue(this, &Load) {
2381 setMask(Mask);
2382 }
2383
2385 return new VPWidenLoadRecipe(cast<LoadInst>(Ingredient), getAddr(),
2387 getDebugLoc());
2388 }
2389
2390 VP_CLASSOF_IMPL(VPDef::VPWidenLoadSC);
2391
2392 /// Generate a wide load or gather.
2393 void execute(VPTransformState &State) override;
2394
2395#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2396 /// Print the recipe.
2397 void print(raw_ostream &O, const Twine &Indent,
2398 VPSlotTracker &SlotTracker) const override;
2399#endif
2400
2401 /// Returns true if the recipe only uses the first lane of operand \p Op.
2402 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2404 "Op must be an operand of the recipe");
2405 // Widened, consecutive loads operations only demand the first lane of
2406 // their address.
2407 return Op == getAddr() && isConsecutive();
2408 }
2409};
2410
2411/// A recipe for widening load operations with vector-predication intrinsics,
2412/// using the address to load from, the explicit vector length and an optional
2413/// mask.
2414struct VPWidenLoadEVLRecipe final : public VPWidenMemoryRecipe, public VPValue {
2416 : VPWidenMemoryRecipe(VPDef::VPWidenLoadEVLSC, L->getIngredient(),
2417 {L->getAddr(), EVL}, L->isConsecutive(),
2418 L->isReverse(), L->getDebugLoc()),
2419 VPValue(this, &getIngredient()) {
2420 setMask(Mask);
2421 }
2422
2423 VP_CLASSOF_IMPL(VPDef::VPWidenLoadEVLSC)
2424
2425 /// Return the EVL operand.
2426 VPValue *getEVL() const { return getOperand(1); }
2427
2428 /// Generate the wide load or gather.
2429 void execute(VPTransformState &State) override;
2430
2431#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2432 /// Print the recipe.
2433 void print(raw_ostream &O, const Twine &Indent,
2434 VPSlotTracker &SlotTracker) const override;
2435#endif
2436
2437 /// Returns true if the recipe only uses the first lane of operand \p Op.
2438 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2440 "Op must be an operand of the recipe");
2441 // Widened loads only demand the first lane of EVL and consecutive loads
2442 // only demand the first lane of their address.
2443 return Op == getEVL() || (Op == getAddr() && isConsecutive());
2444 }
2445};
2446
2447/// A recipe for widening store operations, using the stored value, the address
2448/// to store to and an optional mask.
2451 VPValue *Mask, bool Consecutive, bool Reverse, DebugLoc DL)
2452 : VPWidenMemoryRecipe(VPDef::VPWidenStoreSC, Store, {Addr, StoredVal},
2454 setMask(Mask);
2455 }
2456
2458 return new VPWidenStoreRecipe(cast<StoreInst>(Ingredient), getAddr(),
2460 Reverse, getDebugLoc());
2461 }
2462
2463 VP_CLASSOF_IMPL(VPDef::VPWidenStoreSC);
2464
2465 /// Return the value stored by this recipe.
2466 VPValue *getStoredValue() const { return getOperand(1); }
2467
2468 /// Generate a wide store or scatter.
2469 void execute(VPTransformState &State) override;
2470
2471#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2472 /// Print the recipe.
2473 void print(raw_ostream &O, const Twine &Indent,
2474 VPSlotTracker &SlotTracker) const override;
2475#endif
2476
2477 /// Returns true if the recipe only uses the first lane of operand \p Op.
2478 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2480 "Op must be an operand of the recipe");
2481 // Widened, consecutive stores only demand the first lane of their address,
2482 // unless the same operand is also stored.
2483 return Op == getAddr() && isConsecutive() && Op != getStoredValue();
2484 }
2485};
2486
2487/// A recipe for widening store operations with vector-predication intrinsics,
2488/// using the value to store, the address to store to, the explicit vector
2489/// length and an optional mask.
2492 : VPWidenMemoryRecipe(VPDef::VPWidenStoreEVLSC, S->getIngredient(),
2493 {S->getAddr(), S->getStoredValue(), EVL},
2494 S->isConsecutive(), S->isReverse(),
2495 S->getDebugLoc()) {
2496 setMask(Mask);
2497 }
2498
2499 VP_CLASSOF_IMPL(VPDef::VPWidenStoreEVLSC)
2500
2501 /// Return the address accessed by this recipe.
2502 VPValue *getStoredValue() const { return getOperand(1); }
2503
2504 /// Return the EVL operand.
2505 VPValue *getEVL() const { return getOperand(2); }
2506
2507 /// Generate the wide store or scatter.
2508 void execute(VPTransformState &State) override;
2509
2510#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2511 /// Print the recipe.
2512 void print(raw_ostream &O, const Twine &Indent,
2513 VPSlotTracker &SlotTracker) const override;
2514#endif
2515
2516 /// Returns true if the recipe only uses the first lane of operand \p Op.
2517 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2519 "Op must be an operand of the recipe");
2520 if (Op == getEVL()) {
2521 assert(getStoredValue() != Op && "unexpected store of EVL");
2522 return true;
2523 }
2524 // Widened, consecutive memory operations only demand the first lane of
2525 // their address, unless the same operand is also stored. That latter can
2526 // happen with opaque pointers.
2527 return Op == getAddr() && isConsecutive() && Op != getStoredValue();
2528 }
2529};
2530
2531/// Recipe to expand a SCEV expression.
2533 const SCEV *Expr;
2534 ScalarEvolution &SE;
2535
2536public:
2538 : VPSingleDefRecipe(VPDef::VPExpandSCEVSC, {}), Expr(Expr), SE(SE) {}
2539
2540 ~VPExpandSCEVRecipe() override = default;
2541
2543 return new VPExpandSCEVRecipe(Expr, SE);
2544 }
2545
2546 VP_CLASSOF_IMPL(VPDef::VPExpandSCEVSC)
2547
2548 /// Generate a canonical vector induction variable of the vector loop, with
2549 void execute(VPTransformState &State) override;
2550
2551#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2552 /// Print the recipe.
2553 void print(raw_ostream &O, const Twine &Indent,
2554 VPSlotTracker &SlotTracker) const override;
2555#endif
2556
2557 const SCEV *getSCEV() const { return Expr; }
2558};
2559
2560/// Canonical scalar induction phi of the vector loop. Starting at the specified
2561/// start value (either 0 or the resume value when vectorizing the epilogue
2562/// loop). VPWidenCanonicalIVRecipe represents the vector version of the
2563/// canonical induction variable.
2565public:
2567 : VPHeaderPHIRecipe(VPDef::VPCanonicalIVPHISC, nullptr, StartV, DL) {}
2568
2569 ~VPCanonicalIVPHIRecipe() override = default;
2570
2572 auto *R = new VPCanonicalIVPHIRecipe(getOperand(0), getDebugLoc());
2573 R->addOperand(getBackedgeValue());
2574 return R;
2575 }
2576
2577 VP_CLASSOF_IMPL(VPDef::VPCanonicalIVPHISC)
2578
2580 return D->getVPDefID() == VPDef::VPCanonicalIVPHISC;
2581 }
2582
2583 /// Generate the canonical scalar induction phi of the vector loop.
2584 void execute(VPTransformState &State) override;
2585
2586#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2587 /// Print the recipe.
2588 void print(raw_ostream &O, const Twine &Indent,
2589 VPSlotTracker &SlotTracker) const override;
2590#endif
2591
2592 /// Returns the scalar type of the induction.
2594 return getStartValue()->getLiveInIRValue()->getType();
2595 }
2596
2597 /// Returns true if the recipe only uses the first lane of operand \p Op.
2598 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2600 "Op must be an operand of the recipe");
2601 return true;
2602 }
2603
2604 /// Returns true if the recipe only uses the first part of operand \p Op.
2605 bool onlyFirstPartUsed(const VPValue *Op) const override {
2607 "Op must be an operand of the recipe");
2608 return true;
2609 }
2610
2611 /// Check if the induction described by \p Kind, /p Start and \p Step is
2612 /// canonical, i.e. has the same start and step (of 1) as the canonical IV.
2614 VPValue *Step) const;
2615};
2616
2617/// A recipe for generating the active lane mask for the vector loop that is
2618/// used to predicate the vector operations.
2619/// TODO: It would be good to use the existing VPWidenPHIRecipe instead and
2620/// remove VPActiveLaneMaskPHIRecipe.
2622public:
2624 : VPHeaderPHIRecipe(VPDef::VPActiveLaneMaskPHISC, nullptr, StartMask,
2625 DL) {}
2626
2627 ~VPActiveLaneMaskPHIRecipe() override = default;
2628
2631 }
2632
2633 VP_CLASSOF_IMPL(VPDef::VPActiveLaneMaskPHISC)
2634
2636 return D->getVPDefID() == VPDef::VPActiveLaneMaskPHISC;
2637 }
2638
2639 /// Generate the active lane mask phi of the vector loop.
2640 void execute(VPTransformState &State) override;
2641
2642#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2643 /// Print the recipe.
2644 void print(raw_ostream &O, const Twine &Indent,
2645 VPSlotTracker &SlotTracker) const override;
2646#endif
2647};
2648
2649/// A recipe for generating the phi node for the current index of elements,
2650/// adjusted in accordance with EVL value. It starts at the start value of the
2651/// canonical induction and gets incremented by EVL in each iteration of the
2652/// vector loop.
2654public:
2656 : VPHeaderPHIRecipe(VPDef::VPEVLBasedIVPHISC, nullptr, StartIV, DL) {}
2657
2658 ~VPEVLBasedIVPHIRecipe() override = default;
2659
2661 llvm_unreachable("cloning not implemented yet");
2662 }
2663
2664 VP_CLASSOF_IMPL(VPDef::VPEVLBasedIVPHISC)
2665
2667 return D->getVPDefID() == VPDef::VPEVLBasedIVPHISC;
2668 }
2669
2670 /// Generate phi for handling IV based on EVL over iterations correctly.
2671 /// TODO: investigate if it can share the code with VPCanonicalIVPHIRecipe.
2672 void execute(VPTransformState &State) override;
2673
2674 /// Returns true if the recipe only uses the first lane of operand \p Op.
2675 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2677 "Op must be an operand of the recipe");
2678 return true;
2679 }
2680
2681#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2682 /// Print the recipe.
2683 void print(raw_ostream &O, const Twine &Indent,
2684 VPSlotTracker &SlotTracker) const override;
2685#endif
2686};
2687
2688/// A Recipe for widening the canonical induction variable of the vector loop.
2690public:
2692 : VPSingleDefRecipe(VPDef::VPWidenCanonicalIVSC, {CanonicalIV}) {}
2693
2694 ~VPWidenCanonicalIVRecipe() override = default;
2695
2697 return new VPWidenCanonicalIVRecipe(
2698 cast<VPCanonicalIVPHIRecipe>(getOperand(0)));
2699 }
2700
2701 VP_CLASSOF_IMPL(VPDef::VPWidenCanonicalIVSC)
2702
2703 /// Generate a canonical vector induction variable of the vector loop, with
2704 /// start = {<Part*VF, Part*VF+1, ..., Part*VF+VF-1> for 0 <= Part < UF}, and
2705 /// step = <VF*UF, VF*UF, ..., VF*UF>.
2706 void execute(VPTransformState &State) override;
2707
2708#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2709 /// Print the recipe.
2710 void print(raw_ostream &O, const Twine &Indent,
2711 VPSlotTracker &SlotTracker) const override;
2712#endif
2713};
2714
2715/// A recipe for converting the input value \p IV value to the corresponding
2716/// value of an IV with different start and step values, using Start + IV *
2717/// Step.
2719 /// Kind of the induction.
2721 /// If not nullptr, the floating point induction binary operator. Must be set
2722 /// for floating point inductions.
2723 const FPMathOperator *FPBinOp;
2724
2725public:
2727 VPCanonicalIVPHIRecipe *CanonicalIV, VPValue *Step)
2729 IndDesc.getKind(),
2730 dyn_cast_or_null<FPMathOperator>(IndDesc.getInductionBinOp()),
2731 Start, CanonicalIV, Step) {}
2732
2734 const FPMathOperator *FPBinOp, VPValue *Start, VPValue *IV,
2735 VPValue *Step)
2736 : VPSingleDefRecipe(VPDef::VPDerivedIVSC, {Start, IV, Step}), Kind(Kind),
2737 FPBinOp(FPBinOp) {}
2738
2739 ~VPDerivedIVRecipe() override = default;
2740
2742 return new VPDerivedIVRecipe(Kind, FPBinOp, getStartValue(), getOperand(1),
2743 getStepValue());
2744 }
2745
2746 VP_CLASSOF_IMPL(VPDef::VPDerivedIVSC)
2747
2748 /// Generate the transformed value of the induction at offset StartValue (1.
2749 /// operand) + IV (2. operand) * StepValue (3, operand).
2750 void execute(VPTransformState &State) override;
2751
2752#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2753 /// Print the recipe.
2754 void print(raw_ostream &O, const Twine &Indent,
2755 VPSlotTracker &SlotTracker) const override;
2756#endif
2757
2759 return getStartValue()->getLiveInIRValue()->getType();
2760 }
2761
2762 VPValue *getStartValue() const { return getOperand(0); }
2763 VPValue *getStepValue() const { return getOperand(2); }
2764
2765 /// Returns true if the recipe only uses the first lane of operand \p Op.
2766 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2768 "Op must be an operand of the recipe");
2769 return true;
2770 }
2771};
2772
2773/// A recipe for handling phi nodes of integer and floating-point inductions,
2774/// producing their scalar values.
2776 Instruction::BinaryOps InductionOpcode;
2777
2778public:
2781 : VPRecipeWithIRFlags(VPDef::VPScalarIVStepsSC,
2782 ArrayRef<VPValue *>({IV, Step}), FMFs),
2783 InductionOpcode(Opcode) {}
2784
2786 VPValue *Step)
2788 IV, Step, IndDesc.getInductionOpcode(),
2789 dyn_cast_or_null<FPMathOperator>(IndDesc.getInductionBinOp())
2790 ? IndDesc.getInductionBinOp()->getFastMathFlags()
2791 : FastMathFlags()) {}
2792
2793 ~VPScalarIVStepsRecipe() override = default;
2794
2796 return new VPScalarIVStepsRecipe(
2797 getOperand(0), getOperand(1), InductionOpcode,
2799 }
2800
2801 VP_CLASSOF_IMPL(VPDef::VPScalarIVStepsSC)
2802
2803 /// Generate the scalarized versions of the phi node as needed by their users.
2804 void execute(VPTransformState &State) override;
2805
2806#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2807 /// Print the recipe.
2808 void print(raw_ostream &O, const Twine &Indent,
2809 VPSlotTracker &SlotTracker) const override;
2810#endif
2811
2812 VPValue *getStepValue() const { return getOperand(1); }
2813
2814 /// Returns true if the recipe only uses the first lane of operand \p Op.
2815 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2817 "Op must be an operand of the recipe");
2818 return true;
2819 }
2820};
2821
2822/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
2823/// holds a sequence of zero or more VPRecipe's each representing a sequence of
2824/// output IR instructions. All PHI-like recipes must come before any non-PHI recipes.
2826public:
2828
2829private:
2830 /// The VPRecipes held in the order of output instructions to generate.
2831 RecipeListTy Recipes;
2832
2833public:
2834 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
2835 : VPBlockBase(VPBasicBlockSC, Name.str()) {
2836 if (Recipe)
2837 appendRecipe(Recipe);
2838 }
2839
2840 ~VPBasicBlock() override {
2841 while (!Recipes.empty())
2842 Recipes.pop_back();
2843 }
2844
2845 /// Instruction iterators...
2850
2851 //===--------------------------------------------------------------------===//
2852 /// Recipe iterator methods
2853 ///
2854 inline iterator begin() { return Recipes.begin(); }
2855 inline const_iterator begin() const { return Recipes.begin(); }
2856 inline iterator end() { return Recipes.end(); }
2857 inline const_iterator end() const { return Recipes.end(); }
2858
2859 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
2860 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
2861 inline reverse_iterator rend() { return Recipes.rend(); }
2862 inline const_reverse_iterator rend() const { return Recipes.rend(); }
2863
2864 inline size_t size() const { return Recipes.size(); }
2865 inline bool empty() const { return Recipes.empty(); }
2866 inline const VPRecipeBase &front() const { return Recipes.front(); }
2867 inline VPRecipeBase &front() { return Recipes.front(); }
2868 inline const VPRecipeBase &back() const { return Recipes.back(); }
2869 inline VPRecipeBase &back() { return Recipes.back(); }
2870
2871 /// Returns a reference to the list of recipes.
2872 RecipeListTy &getRecipeList() { return Recipes; }
2873
2874 /// Returns a pointer to a member of the recipe list.
2876 return &VPBasicBlock::Recipes;
2877 }
2878
2879 /// Method to support type inquiry through isa, cast, and dyn_cast.
2880 static inline bool classof(const VPBlockBase *V) {
2881 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
2882 }
2883
2884 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
2885 assert(Recipe && "No recipe to append.");
2886 assert(!Recipe->Parent && "Recipe already in VPlan");
2887 Recipe->Parent = this;
2888 Recipes.insert(InsertPt, Recipe);
2889 }
2890
2891 /// Augment the existing recipes of a VPBasicBlock with an additional
2892 /// \p Recipe as the last recipe.
2893 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
2894
2895 /// The method which generates the output IR instructions that correspond to
2896 /// this VPBasicBlock, thereby "executing" the VPlan.
2897 void execute(VPTransformState *State) override;
2898
2899 /// Return the position of the first non-phi node recipe in the block.
2901
2902 /// Returns an iterator range over the PHI-like recipes in the block.
2904 return make_range(begin(), getFirstNonPhi());
2905 }
2906
2907 void dropAllReferences(VPValue *NewValue) override;
2908
2909 /// Split current block at \p SplitAt by inserting a new block between the
2910 /// current block and its successors and moving all recipes starting at
2911 /// SplitAt to the new block. Returns the new block.
2912 VPBasicBlock *splitAt(iterator SplitAt);
2913
2915
2916#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2917 /// Print this VPBsicBlock to \p O, prefixing all lines with \p Indent. \p
2918 /// SlotTracker is used to print unnamed VPValue's using consequtive numbers.
2919 ///
2920 /// Note that the numbering is applied to the whole VPlan, so printing
2921 /// individual blocks is consistent with the whole VPlan printing.
2922 void print(raw_ostream &O, const Twine &Indent,
2923 VPSlotTracker &SlotTracker) const override;
2924 using VPBlockBase::print; // Get the print(raw_stream &O) version.
2925#endif
2926
2927 /// If the block has multiple successors, return the branch recipe terminating
2928 /// the block. If there are no or only a single successor, return nullptr;
2930 const VPRecipeBase *getTerminator() const;
2931
2932 /// Returns true if the block is exiting it's parent region.
2933 bool isExiting() const;
2934
2935 /// Clone the current block and it's recipes, without updating the operands of
2936 /// the cloned recipes.
2937 VPBasicBlock *clone() override {
2938 auto *NewBlock = new VPBasicBlock(getName());
2939 for (VPRecipeBase &R : *this)
2940 NewBlock->appendRecipe(R.clone());
2941 return NewBlock;
2942 }
2943
2944private:
2945 /// Create an IR BasicBlock to hold the output instructions generated by this
2946 /// VPBasicBlock, and return it. Update the CFGState accordingly.
2947 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
2948};
2949
2950/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
2951/// which form a Single-Entry-Single-Exiting subgraph of the output IR CFG.
2952/// A VPRegionBlock may indicate that its contents are to be replicated several
2953/// times. This is designed to support predicated scalarization, in which a
2954/// scalar if-then code structure needs to be generated VF * UF times. Having
2955/// this replication indicator helps to keep a single model for multiple
2956/// candidate VF's. The actual replication takes place only once the desired VF
2957/// and UF have been determined.
2959 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
2960 VPBlockBase *Entry;
2961
2962 /// Hold the Single Exiting block of the SESE region modelled by the
2963 /// VPRegionBlock.
2964 VPBlockBase *Exiting;
2965
2966 /// An indicator whether this region is to generate multiple replicated
2967 /// instances of output IR corresponding to its VPBlockBases.
2968 bool IsReplicator;
2969
2970public:
2972 const std::string &Name = "", bool IsReplicator = false)
2973 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exiting(Exiting),
2974 IsReplicator(IsReplicator) {
2975 assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
2976 assert(Exiting->getSuccessors().empty() && "Exit block has successors.");
2977 Entry->setParent(this);
2978 Exiting->setParent(this);
2979 }
2980 VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
2981 : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exiting(nullptr),
2982 IsReplicator(IsReplicator) {}
2983
2984 ~VPRegionBlock() override {
2985 if (Entry) {
2986 VPValue DummyValue;
2987 Entry->dropAllReferences(&DummyValue);
2988 deleteCFG(Entry);
2989 }
2990 }
2991
2992 /// Method to support type inquiry through isa, cast, and dyn_cast.
2993 static inline bool classof(const VPBlockBase *V) {
2994 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
2995 }
2996
2997 const VPBlockBase *getEntry() const { return Entry; }
2998 VPBlockBase *getEntry() { return Entry; }
2999
3000 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
3001 /// EntryBlock must have no predecessors.
3002 void setEntry(VPBlockBase *EntryBlock) {
3003 assert(EntryBlock->getPredecessors().empty() &&
3004 "Entry block cannot have predecessors.");
3005 Entry = EntryBlock;
3006 EntryBlock->setParent(this);
3007 }
3008
3009 const VPBlockBase *getExiting() const { return Exiting; }
3010 VPBlockBase *getExiting() { return Exiting; }
3011
3012 /// Set \p ExitingBlock as the exiting VPBlockBase of this VPRegionBlock. \p
3013 /// ExitingBlock must have no successors.
3014 void setExiting(VPBlockBase *ExitingBlock) {
3015 assert(ExitingBlock->getSuccessors().empty() &&
3016 "Exit block cannot have successors.");
3017 Exiting = ExitingBlock;
3018 ExitingBlock->setParent(this);
3019 }
3020
3021 /// Returns the pre-header VPBasicBlock of the loop region.
3023 assert(!isReplicator() && "should only get pre-header of loop regions");
3025 }
3026
3027 /// An indicator whether this region is to generate multiple replicated
3028 /// instances of output IR corresponding to its VPBlockBases.
3029 bool isReplicator() const { return IsReplicator; }
3030
3031 /// The method which generates the output IR instructions that correspond to
3032 /// this VPRegionBlock, thereby "executing" the VPlan.
3033 void execute(VPTransformState *State) override;
3034
3035 void dropAllReferences(VPValue *NewValue) override;
3036
3037#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3038 /// Print this VPRegionBlock to \p O (recursively), prefixing all lines with
3039 /// \p Indent. \p SlotTracker is used to print unnamed VPValue's using
3040 /// consequtive numbers.
3041 ///
3042 /// Note that the numbering is applied to the whole VPlan, so printing
3043 /// individual regions is consistent with the whole VPlan printing.
3044 void print(raw_ostream &O, const Twine &Indent,
3045 VPSlotTracker &SlotTracker) const override;
3046 using VPBlockBase::print; // Get the print(raw_stream &O) version.
3047#endif
3048
3049 /// Clone all blocks in the single-entry single-exit region of the block and
3050 /// their recipes without updating the operands of the cloned recipes.
3051 VPRegionBlock *clone() override;
3052};
3053
3054/// VPlan models a candidate for vectorization, encoding various decisions take
3055/// to produce efficient output IR, including which branches, basic-blocks and
3056/// output IR instructions to generate, and their cost. VPlan holds a
3057/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
3058/// VPBasicBlock.
3059class VPlan {
3060 friend class VPlanPrinter;
3061 friend class VPSlotTracker;
3062
3063 /// Hold the single entry to the Hierarchical CFG of the VPlan, i.e. the
3064 /// preheader of the vector loop.
3065 VPBasicBlock *Entry;
3066
3067 /// VPBasicBlock corresponding to the original preheader. Used to place
3068 /// VPExpandSCEV recipes for expressions used during skeleton creation and the
3069 /// rest of VPlan execution.
3070 VPBasicBlock *Preheader;
3071
3072 /// Holds the VFs applicable to this VPlan.
3074
3075 /// Holds the UFs applicable to this VPlan. If empty, the VPlan is valid for
3076 /// any UF.
3078
3079 /// Holds the name of the VPlan, for printing.
3080 std::string Name;
3081
3082 /// Represents the trip count of the original loop, for folding
3083 /// the tail.
3084 VPValue *TripCount = nullptr;
3085
3086 /// Represents the backedge taken count of the original loop, for folding
3087 /// the tail. It equals TripCount - 1.
3088 VPValue *BackedgeTakenCount = nullptr;
3089
3090 /// Represents the vector trip count.
3091 VPValue VectorTripCount;
3092
3093 /// Represents the loop-invariant VF * UF of the vector loop region.
3094 VPValue VFxUF;
3095
3096 /// Holds a mapping between Values and their corresponding VPValue inside
3097 /// VPlan.
3098 Value2VPValueTy Value2VPValue;
3099
3100 /// Contains all the external definitions created for this VPlan. External
3101 /// definitions are VPValues that hold a pointer to their underlying IR.
3102 SmallVector<VPValue *, 16> VPLiveInsToFree;
3103
3104 /// Values used outside the plan.
3106
3107 /// Mapping from SCEVs to the VPValues representing their expansions.
3108 /// NOTE: This mapping is temporary and will be removed once all users have
3109 /// been modeled in VPlan directly.
3110 DenseMap<const SCEV *, VPValue *> SCEVToExpansion;
3111
3112public:
3113 /// Construct a VPlan with original preheader \p Preheader, trip count \p TC
3114 /// and \p Entry to the plan. At the moment, \p Preheader and \p Entry need to
3115 /// be disconnected, as the bypass blocks between them are not yet modeled in
3116 /// VPlan.
3117 VPlan(VPBasicBlock *Preheader, VPValue *TC, VPBasicBlock *Entry)
3118 : VPlan(Preheader, Entry) {
3119 TripCount = TC;
3120 }
3121
3122 /// Construct a VPlan with original preheader \p Preheader and \p Entry to
3123 /// the plan. At the moment, \p Preheader and \p Entry need to be
3124 /// disconnected, as the bypass blocks between them are not yet modeled in
3125 /// VPlan.
3126 VPlan(VPBasicBlock *Preheader, VPBasicBlock *Entry)
3127 : Entry(Entry), Preheader(Preheader) {
3128 Entry->setPlan(this);
3129 Preheader->setPlan(this);
3130 assert(Preheader->getNumSuccessors() == 0 &&
3131 Preheader->getNumPredecessors() == 0 &&
3132 "preheader must be disconnected");
3133 }
3134
3135 ~VPlan();
3136
3137 /// Create initial VPlan skeleton, having an "entry" VPBasicBlock (wrapping
3138 /// original scalar pre-header) which contains SCEV expansions that need to
3139 /// happen before the CFG is modified; a VPBasicBlock for the vector
3140 /// pre-header, followed by a region for the vector loop, followed by the
3141 /// middle VPBasicBlock.
3142 static VPlanPtr createInitialVPlan(const SCEV *TripCount,
3143 ScalarEvolution &PSE);
3144
3145 /// Prepare the plan for execution, setting up the required live-in values.
3146 void prepareToExecute(Value *TripCount, Value *VectorTripCount,
3147 Value *CanonicalIVStartValue, VPTransformState &State);
3148
3149 /// Generate the IR code for this VPlan.
3150 void execute(VPTransformState *State);
3151
3152 VPBasicBlock *getEntry() { return Entry; }
3153 const VPBasicBlock *getEntry() const { return Entry; }
3154
3155 /// The trip count of the original loop.
3157 assert(TripCount && "trip count needs to be set before accessing it");
3158 return TripCount;
3159 }
3160
3161 /// Resets the trip count for the VPlan. The caller must make sure all uses of
3162 /// the original trip count have been replaced.
3163 void resetTripCount(VPValue *NewTripCount) {
3164 assert(TripCount && NewTripCount && TripCount->getNumUsers() == 0 &&
3165 "TripCount always must be set");
3166 TripCount = NewTripCount;
3167 }
3168
3169 /// The backedge taken count of the original loop.
3171 if (!BackedgeTakenCount)
3172 BackedgeTakenCount = new VPValue();
3173 return BackedgeTakenCount;
3174 }
3175
3176 /// The vector trip count.
3177 VPValue &getVectorTripCount() { return VectorTripCount; }
3178
3179 /// Returns VF * UF of the vector loop region.
3180 VPValue &getVFxUF() { return VFxUF; }
3181
3182 void addVF(ElementCount VF) { VFs.insert(VF); }
3183
3185 assert(hasVF(VF) && "Cannot set VF not already in plan");
3186 VFs.clear();
3187 VFs.insert(VF);
3188 }
3189
3190 bool hasVF(ElementCount VF) { return VFs.count(VF); }
3192 return any_of(VFs, [](ElementCount VF) { return VF.isScalable(); });
3193 }
3194
3195 bool hasScalarVFOnly() const { return VFs.size() == 1 && VFs[0].isScalar(); }
3196
3197 bool hasUF(unsigned UF) const { return UFs.empty() || UFs.contains(UF); }
3198
3199 void setUF(unsigned UF) {
3200 assert(hasUF(UF) && "Cannot set the UF not already in plan");
3201 UFs.clear();
3202 UFs.insert(UF);
3203 }
3204
3205 /// Return a string with the name of the plan and the applicable VFs and UFs.
3206 std::string getName() const;
3207
3208 void setName(const Twine &newName) { Name = newName.str(); }
3209
3210 /// Gets the live-in VPValue for \p V or adds a new live-in (if none exists
3211 /// yet) for \p V.
3213 assert(V && "Trying to get or add the VPValue of a null Value");
3214 if (!Value2VPValue.count(V)) {
3215 VPValue *VPV = new VPValue(V);
3216 VPLiveInsToFree.push_back(VPV);
3217 assert(VPV->isLiveIn() && "VPV must be a live-in.");
3218 assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
3219 Value2VPValue[V] = VPV;
3220 }
3221
3222 assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
3223 assert(Value2VPValue[V]->isLiveIn() &&
3224 "Only live-ins should be in mapping");
3225 return Value2VPValue[V];
3226 }
3227
3228 /// Return the live-in VPValue for \p V, if there is one or nullptr otherwise.
3229 VPValue *getLiveIn(Value *V) const { return Value2VPValue.lookup(V); }
3230
3231#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3232 /// Print the live-ins of this VPlan to \p O.
3233 void printLiveIns(raw_ostream &O) const;
3234
3235 /// Print this VPlan to \p O.
3236 void print(raw_ostream &O) const;
3237
3238 /// Print this VPlan in DOT format to \p O.
3239 void printDOT(raw_ostream &O) const;
3240
3241 /// Dump the plan to stderr (for debugging).
3242 LLVM_DUMP_METHOD void dump() const;
3243#endif
3244
3245 /// Returns the VPRegionBlock of the vector loop.
3247 return cast<VPRegionBlock>(getEntry()->getSingleSuccessor());
3248 }
3250 return cast<VPRegionBlock>(getEntry()->getSingleSuccessor());
3251 }
3252
3253 /// Returns the canonical induction recipe of the vector loop.
3256 if (EntryVPBB->empty()) {
3257 // VPlan native path.
3258 EntryVPBB = cast<VPBasicBlock>(EntryVPBB->getSingleSuccessor());
3259 }
3260 return cast<VPCanonicalIVPHIRecipe>(&*EntryVPBB->begin());
3261 }
3262
3263 void addLiveOut(PHINode *PN, VPValue *V);
3264
3266 delete LiveOuts[PN];
3267 LiveOuts.erase(PN);
3268 }
3269
3271 return LiveOuts;
3272 }
3273
3274 VPValue *getSCEVExpansion(const SCEV *S) const {
3275 return SCEVToExpansion.lookup(S);
3276 }
3277
3278 void addSCEVExpansion(const SCEV *S, VPValue *V) {
3279 assert(!SCEVToExpansion.contains(S) && "SCEV already expanded");
3280 SCEVToExpansion[S] = V;
3281 }
3282
3283 /// \return The block corresponding to the original preheader.
3284 VPBasicBlock *getPreheader() { return Preheader; }
3285 const VPBasicBlock *getPreheader() const { return Preheader; }
3286
3287 /// Clone the current VPlan, update all VPValues of the new VPlan and cloned
3288 /// recipes to refer to the clones, and return it.
3289 VPlan *duplicate();
3290
3291private:
3292 /// Add to the given dominator tree the header block and every new basic block
3293 /// that was created between it and the latch block, inclusive.
3294 static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB,
3295 BasicBlock *LoopLatchBB,
3296 BasicBlock *LoopExitBB);
3297};
3298
3299#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3300/// VPlanPrinter prints a given VPlan to a given output stream. The printing is
3301/// indented and follows the dot format.
3303 raw_ostream &OS;
3304 const VPlan &Plan;
3305 unsigned Depth = 0;
3306 unsigned TabWidth = 2;
3307 std::string Indent;
3308 unsigned BID = 0;
3310
3312
3313 /// Handle indentation.
3314 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
3315
3316 /// Print a given \p Block of the Plan.
3317 void dumpBlock(const VPBlockBase *Block);
3318
3319 /// Print the information related to the CFG edges going out of a given
3320 /// \p Block, followed by printing the successor blocks themselves.
3321 void dumpEdges(const VPBlockBase *Block);
3322
3323 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
3324 /// its successor blocks.
3325 void dumpBasicBlock(const VPBasicBlock *BasicBlock);
3326
3327 /// Print a given \p Region of the Plan.
3328 void dumpRegion(const VPRegionBlock *Region);
3329
3330 unsigned getOrCreateBID(const VPBlockBase *Block) {
3331 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
3332 }
3333
3334 Twine getOrCreateName(const VPBlockBase *Block);
3335
3336 Twine getUID(const VPBlockBase *Block);
3337
3338 /// Print the information related to a CFG edge between two VPBlockBases.
3339 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
3340 const Twine &Label);
3341
3342public:
3344 : OS(O), Plan(P), SlotTracker(&P) {}
3345
3346 LLVM_DUMP_METHOD void dump();
3347};
3348
3350 const Value *V;
3351
3352 VPlanIngredient(const Value *V) : V(V) {}
3353
3354 void print(raw_ostream &O) const;
3355};
3356
3358 I.print(OS);
3359 return OS;
3360}
3361
3363 Plan.print(OS);
3364 return OS;
3365}
3366#endif
3367
3368//===----------------------------------------------------------------------===//
3369// VPlan Utilities
3370//===----------------------------------------------------------------------===//
3371
3372/// Class that provides utilities for VPBlockBases in VPlan.
3374public:
3375 VPBlockUtils() = delete;
3376
3377 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
3378 /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
3379 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. \p BlockPtr's
3380 /// successors are moved from \p BlockPtr to \p NewBlock. \p NewBlock must
3381 /// have neither successors nor predecessors.
3382 static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
3383 assert(NewBlock->getSuccessors().empty() &&
3384 NewBlock->getPredecessors().empty() &&
3385 "Can't insert new block with predecessors or successors.");
3386 NewBlock->setParent(BlockPtr->getParent());
3387 SmallVector<VPBlockBase *> Succs(BlockPtr->successors());
3388 for (VPBlockBase *Succ : Succs) {
3389 disconnectBlocks(BlockPtr, Succ);
3390 connectBlocks(NewBlock, Succ);
3391 }
3392 connectBlocks(BlockPtr, NewBlock);
3393 }
3394
3395 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
3396 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
3397 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
3398 /// parent to \p IfTrue and \p IfFalse. \p BlockPtr must have no successors
3399 /// and \p IfTrue and \p IfFalse must have neither successors nor
3400 /// predecessors.
3401 static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
3402 VPBlockBase *BlockPtr) {
3403 assert(IfTrue->getSuccessors().empty() &&
3404 "Can't insert IfTrue with successors.");
3405 assert(IfFalse->getSuccessors().empty() &&
3406 "Can't insert IfFalse with successors.");
3407 BlockPtr->setTwoSuccessors(IfTrue, IfFalse);
3408 IfTrue->setPredecessors({BlockPtr});
3409 IfFalse->setPredecessors({BlockPtr});
3410 IfTrue->setParent(BlockPtr->getParent());
3411 IfFalse->setParent(BlockPtr->getParent());
3412 }
3413
3414 /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
3415 /// the successors of \p From and \p From to the predecessors of \p To. Both
3416 /// VPBlockBases must have the same parent, which can be null. Both
3417 /// VPBlockBases can be already connected to other VPBlockBases.
3419 assert((From->getParent() == To->getParent()) &&
3420 "Can't connect two block with different parents");
3421 assert(From->getNumSuccessors() < 2 &&
3422 "Blocks can't have more than two successors.");
3423 From->appendSuccessor(To);
3424 To->appendPredecessor(From);
3425 }
3426
3427 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
3428 /// from the successors of \p From and \p From from the predecessors of \p To.
3430 assert(To && "Successor to disconnect is null.");
3431 From->removeSuccessor(To);
3432 To->removePredecessor(From);
3433 }
3434
3435 /// Return an iterator range over \p Range which only includes \p BlockTy
3436 /// blocks. The accesses are casted to \p BlockTy.
3437 template <typename BlockTy, typename T>
3438 static auto blocksOnly(const T &Range) {
3439 // Create BaseTy with correct const-ness based on BlockTy.
3440 using BaseTy = std::conditional_t<std::is_const<BlockTy>::value,
3441 const VPBlockBase, VPBlockBase>;
3442
3443 // We need to first create an iterator range over (const) BlocktTy & instead
3444 // of (const) BlockTy * for filter_range to work properly.
3445 auto Mapped =
3446 map_range(Range, [](BaseTy *Block) -> BaseTy & { return *Block; });
3448 Mapped, [](BaseTy &Block) { return isa<BlockTy>(&Block); });
3449 return map_range(Filter, [](BaseTy &Block) -> BlockTy * {
3450 return cast<BlockTy>(&Block);
3451 });
3452 }
3453};
3454
3457 InterleaveGroupMap;
3458
3459 /// Type for mapping of instruction based interleave groups to VPInstruction
3460 /// interleave groups
3463
3464 /// Recursively \p Region and populate VPlan based interleave groups based on
3465 /// \p IAI.
3466 void visitRegion(VPRegionBlock *Region, Old2NewTy &Old2New,
3468 /// Recursively traverse \p Block and populate VPlan based interleave groups
3469 /// based on \p IAI.
3470 void visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
3472
3473public:
3475
3478 // Avoid releasing a pointer twice.
3479 for (auto &I : InterleaveGroupMap)
3480 DelSet.insert(I.second);
3481 for (auto *Ptr : DelSet)
3482 delete Ptr;
3483 }
3484
3485 /// Get the interleave group that \p Instr belongs to.
3486 ///
3487 /// \returns nullptr if doesn't have such group.
3490 return InterleaveGroupMap.lookup(Instr);
3491 }
3492};
3493
3494/// Class that maps (parts of) an existing VPlan to trees of combined
3495/// VPInstructions.
3497 enum class OpMode { Failed, Load, Opcode };
3498
3499 /// A DenseMapInfo implementation for using SmallVector<VPValue *, 4> as
3500 /// DenseMap keys.
3501 struct BundleDenseMapInfo {
3502 static SmallVector<VPValue *, 4> getEmptyKey() {
3503 return {reinterpret_cast<VPValue *>(-1)};
3504 }
3505
3506 static SmallVector<VPValue *, 4> getTombstoneKey() {
3507 return {reinterpret_cast<VPValue *>(-2)};
3508 }
3509
3510 static unsigned getHashValue(const SmallVector<VPValue *, 4> &V) {
3511 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3512 }
3513
3514 static bool isEqual(const SmallVector<VPValue *, 4> &LHS,
3516 return LHS == RHS;
3517 }
3518 };
3519
3520 /// Mapping of values in the original VPlan to a combined VPInstruction.
3522 BundleToCombined;
3523
3525
3526 /// Basic block to operate on. For now, only instructions in a single BB are
3527 /// considered.
3528 const VPBasicBlock &BB;
3529
3530 /// Indicates whether we managed to combine all visited instructions or not.
3531 bool CompletelySLP = true;
3532
3533 /// Width of the widest combined bundle in bits.
3534 unsigned WidestBundleBits = 0;
3535
3536 using MultiNodeOpTy =
3537 typename std::pair<VPInstruction *, SmallVector<VPValue *, 4>>;
3538
3539 // Input operand bundles for the current multi node. Each multi node operand
3540 // bundle contains values not matching the multi node's opcode. They will
3541 // be reordered in reorderMultiNodeOps, once we completed building a
3542 // multi node.
3543 SmallVector<MultiNodeOpTy, 4> MultiNodeOps;
3544
3545 /// Indicates whether we are building a multi node currently.
3546 bool MultiNodeActive = false;
3547
3548 /// Check if we can vectorize Operands together.
3549 bool areVectorizable(ArrayRef<VPValue *> Operands) const;
3550
3551 /// Add combined instruction \p New for the bundle \p Operands.
3552 void addCombined(ArrayRef<VPValue *> Operands, VPInstruction *New);
3553
3554 /// Indicate we hit a bundle we failed to combine. Returns nullptr for now.
3555 VPInstruction *markFailed();
3556
3557 /// Reorder operands in the multi node to maximize sequential memory access
3558 /// and commutative operations.
3559 SmallVector<MultiNodeOpTy, 4> reorderMultiNodeOps();
3560
3561 /// Choose the best candidate to use for the lane after \p Last. The set of
3562 /// candidates to choose from are values with an opcode matching \p Last's
3563 /// or loads consecutive to \p Last.
3564 std::pair<OpMode, VPValue *> getBest(OpMode Mode, VPValue *Last,
3565 SmallPtrSetImpl<VPValue *> &Candidates,
3567
3568#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3569 /// Print bundle \p Values to dbgs().
3570 void dumpBundle(ArrayRef<VPValue *> Values);
3571#endif
3572
3573public:
3574 VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB) : IAI(IAI), BB(BB) {}
3575
3576 ~VPlanSlp() = default;
3577
3578 /// Tries to build an SLP tree rooted at \p Operands and returns a
3579 /// VPInstruction combining \p Operands, if they can be combined.
3581
3582 /// Return the width of the widest combined bundle in bits.
3583 unsigned getWidestBundleBits() const { return WidestBundleBits; }
3584
3585 /// Return true if all visited instruction can be combined.
3586 bool isCompletelySLP() const { return CompletelySLP; }
3587};
3588
3589namespace vputils {
3590
3591/// Returns true if only the first lane of \p Def is used.
3592bool onlyFirstLaneUsed(const VPValue *Def);
3593
3594/// Returns true if only the first part of \p Def is used.
3595bool onlyFirstPartUsed(const VPValue *Def);
3596
3597/// Get or create a VPValue that corresponds to the expansion of \p Expr. If \p
3598/// Expr is a SCEVConstant or SCEVUnknown, return a VPValue wrapping the live-in
3599/// value. Otherwise return a VPExpandSCEVRecipe to expand \p Expr. If \p Plan's
3600/// pre-header already contains a recipe expanding \p Expr, return it. If not,
3601/// create a new one.
3603 ScalarEvolution &SE);
3604
3605/// Returns true if \p VPV is uniform after vectorization.
3607 // A value defined outside the vector region must be uniform after
3608 // vectorization inside a vector region.
3610 return true;
3611 VPRecipeBase *Def = VPV->getDefiningRecipe();
3612 assert(Def && "Must have definition for value defined inside vector region");
3613 if (auto Rep = dyn_cast<VPReplicateRecipe>(Def))
3614 return Rep->isUniform();
3615 if (auto *GEP = dyn_cast<VPWidenGEPRecipe>(Def))
3616 return all_of(GEP->operands(), isUniformAfterVectorization);
3617 if (auto *VPI = dyn_cast<VPInstruction>(Def))
3618 return VPI->getOpcode() == VPInstruction::ComputeReductionResult;
3619 return false;
3620}
3621} // end namespace vputils
3622
3623} // end namespace llvm
3624
3625#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
aarch64 promote const
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
always inline
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
RelocType Type
Definition: COFFYAML.cpp:391
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:537
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file defines the DenseMap class.
uint64_t Addr
std::string Name
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1291
Flatten the CFG
Hexagon Common GEP
std::pair< BasicBlock *, unsigned > BlockTy
A pair of (basic block, score).
#define I(x, y, z)
Definition: MD5.cpp:58
mir Rename Register Operands
This file implements a map that provides insertion order iteration.
#define P(N)
static cl::opt< RegAllocEvictionAdvisorAnalysis::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Development, "development", "for training")))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file implements the SmallBitVector class.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file contains the declarations of the entities induced by Vectorization Plans,...
#define VP_CLASSOF_IMPL(VPDefID)
Definition: VPlan.h:804
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition: blake3_impl.h:78
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition: ArrayRef.h:195
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:601
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Definition: InstrTypes.h:930
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:993
This class represents an Operation in the Expression.
A debug info location.
Definition: DebugLoc.h:33
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:202
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:151
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition: DenseMap.h:145
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
constexpr bool isScalar() const
Exactly one element.
Definition: TypeSize.h:319
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition: Operator.h:201
Convenience struct for specifying and reasoning about fast-math flags.
Definition: FMF.h:20
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:973
Common base class shared among various IRBuilders.
Definition: IRBuilder.h:94
A struct for saving information about induction variables.
InductionKind
This enum represents the kinds of inductions that we support.
InnerLoopVectorizer vectorizes loops which contain only one basic block to a specified vectorization ...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:252
The group of interleaved loads/stores sharing the same stride and close to each other.
Definition: VectorUtils.h:444
uint32_t getFactor() const
Definition: VectorUtils.h:460
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
Definition: VectorUtils.h:514
Drive the analysis of interleaved memory accesses in the loop.
Definition: VectorUtils.h:586
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
An instruction for reading from memory.
Definition: Instructions.h:184
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:44
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
Definition: MapVector.h:193
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Definition: IVDescriptors.h:71
This class represents an analyzed expression in the program.
The main scalar evolution driver.
This class represents the LLVM 'select' instruction.
size_type size() const
Determine the number of elements in the SetVector.
Definition: SetVector.h:98
void clear()
Completely clear the SetVector.
Definition: SetVector.h:273
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Definition: SetVector.h:264
bool empty() const
Determine if the SetVector is empty or not.
Definition: SetVector.h:93
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:162
bool contains(const key_type &key) const
Check if the SetVector contains the given key.
Definition: SetVector.h:254
This class provides computation of slot numbers for LLVM Assembly writing.
Definition: AsmWriter.cpp:693
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:321
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:342
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
iterator erase(const_iterator CI)
Definition: SmallVector.h:750
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:317
This class represents a truncation of integer types.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
Iterator to iterate over vectorization factors in a VFRange.
Definition: VPlan.h:111
ElementCount operator*() const
Definition: VPlan.h:119
iterator & operator++()
Definition: VPlan.h:121
iterator(ElementCount VF)
Definition: VPlan.h:115
bool operator==(const iterator &Other) const
Definition: VPlan.h:117
A recipe for generating the active lane mask for the vector loop that is used to predicate the vector...
Definition: VPlan.h:2621
void execute(VPTransformState &State) override
Generate the active lane mask phi of the vector loop.
VPActiveLaneMaskPHIRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2629
static bool classof(const VPHeaderPHIRecipe *D)
Definition: VPlan.h:2635
VPActiveLaneMaskPHIRecipe(VPValue *StartMask, DebugLoc DL)
Definition: VPlan.h:2623
~VPActiveLaneMaskPHIRecipe() override=default
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition: VPlan.h:2825
RecipeListTy::const_iterator const_iterator
Definition: VPlan.h:2847
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
Definition: VPlan.h:2893
VPBasicBlock * clone() override
Clone the current block and it's recipes, without updating the operands of the cloned recipes.
Definition: VPlan.h:2937
RecipeListTy::const_reverse_iterator const_reverse_iterator
Definition: VPlan.h:2849
RecipeListTy::iterator iterator
Instruction iterators...
Definition: VPlan.h:2846
void execute(VPTransformState *State) override
The method which generates the output IR instructions that correspond to this VPBasicBlock,...
Definition: VPlan.cpp:443
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition: VPlan.h:2872
iterator end()
Definition: VPlan.h:2856
VPBasicBlock(const Twine &Name="", VPRecipeBase *Recipe=nullptr)
Definition: VPlan.h:2834
iterator begin()
Recipe iterator methods.
Definition: VPlan.h:2854
RecipeListTy::reverse_iterator reverse_iterator
Definition: VPlan.h:2848
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition: VPlan.h:2903
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition: VPlan.cpp:210
~VPBasicBlock() override
Definition: VPlan.h:2840
VPRegionBlock * getEnclosingLoopRegion()
Definition: VPlan.cpp:546
void dropAllReferences(VPValue *NewValue) override
Replace all operands of VPUsers in the block with NewValue and also replaces all uses of VPValues def...
Definition: VPlan.cpp:511
const_reverse_iterator rbegin() const
Definition: VPlan.h:2860
reverse_iterator rend()
Definition: VPlan.h:2861
VPBasicBlock * splitAt(iterator SplitAt)
Split current block at SplitAt by inserting a new block between the current block and its successors ...
Definition: VPlan.cpp:521
VPRecipeBase & back()
Definition: VPlan.h:2869
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print this VPBsicBlock to O, prefixing all lines with Indent.
Definition: VPlan.cpp:613
const VPRecipeBase & front() const
Definition: VPlan.h:2866
const_iterator begin() const
Definition: VPlan.h:2855
VPRecipeBase & front()
Definition: VPlan.h:2867
bool isExiting() const
Returns true if the block is exiting it's parent region.
Definition: VPlan.cpp:596
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition: VPlan.cpp:584
const VPRecipeBase & back() const
Definition: VPlan.h:2868
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition: VPlan.h:2884
bool empty() const
Definition: VPlan.h:2865
const_iterator end() const
Definition: VPlan.h:2857
static bool classof(const VPBlockBase *V)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition: VPlan.h:2880
static RecipeListTy VPBasicBlock::* getSublistAccess(VPRecipeBase *)
Returns a pointer to a member of the recipe list.
Definition: VPlan.h:2875
reverse_iterator rbegin()
Definition: VPlan.h:2859
size_t size() const
Definition: VPlan.h:2864
const_reverse_iterator rend() const
Definition: VPlan.h:2862
A recipe for vectorizing a phi-node as a sequence of mask-based select instructions.
Definition: VPlan.h:1948
VPBlendRecipe(PHINode *Phi, ArrayRef< VPValue * > Operands)
The blend operation is a User of the incoming values and of their respective masks,...
Definition: VPlan.h:1953
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:1991
VPValue * getIncomingValue(unsigned Idx) const
Return incoming value number Idx.
Definition: VPlan.h:1971
VPValue * getMask(unsigned Idx) const
Return mask number Idx.
Definition: VPlan.h:1976
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account that the first incoming value has no mask.
Definition: VPlan.h:1968
VPBlendRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1959
void execute(VPTransformState &State) override
Generate the phi/select nodes.
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition: VPlan.h:417
VPRegionBlock * getParent()
Definition: VPlan.h:489
VPBlocksTy & getPredecessors()
Definition: VPlan.h:520
const VPBasicBlock * getExitingBasicBlock() const
Definition: VPlan.cpp:175
LLVM_DUMP_METHOD void dump() const
Dump this VPBlockBase to dbgs().
Definition: VPlan.h:658
void setName(const Twine &newName)
Definition: VPlan.h:482
size_t getNumSuccessors() const
Definition: VPlan.h:534
iterator_range< VPBlockBase ** > successors()
Definition: VPlan.h:517
virtual void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const =0
Print plain-text dump of this VPBlockBase to O, prefixing all lines with Indent.
void printSuccessors(raw_ostream &O, const Twine &Indent) const
Print the successors of this block to O, prefixing all lines with Indent.
Definition: VPlan.cpp:601
bool isLegalToHoistInto()
Return true if it is legal to hoist instructions into this block.
Definition: VPlan.h:623
virtual ~VPBlockBase()=default
void print(raw_ostream &O) const
Print plain-text dump of this VPlan to O.
Definition: VPlan.h:648
const VPBlocksTy & getHierarchicalPredecessors()
Definition: VPlan.h:570
size_t getNumPredecessors() const
Definition: VPlan.h:535
void setPredecessors(ArrayRef< VPBlockBase * > NewPreds)
Set each VPBasicBlock in NewPreds as predecessor of this VPBlockBase.
Definition: VPlan.h:603
VPBlockBase * getEnclosingBlockWithPredecessors()
Definition: VPlan.cpp:197
const VPBlocksTy & getPredecessors() const
Definition: VPlan.h:519
virtual VPBlockBase * clone()=0
Clone the current block and it's recipes without updating the operands of the cloned recipes,...
static void deleteCFG(VPBlockBase *Entry)
Delete all blocks reachable from a given VPBlockBase, inclusive.
Definition: VPlan.cpp:205
VPlan * getPlan()
Definition: VPlan.cpp:148
void setPlan(VPlan *ParentPlan)
Sets the pointer of the plan containing the block.
Definition: VPlan.cpp:167
const VPRegionBlock * getParent() const
Definition: VPlan.h:490
void printAsOperand(raw_ostream &OS, bool PrintType) const
Definition: VPlan.h:634
const std::string & getName() const
Definition: VPlan.h:480
void clearSuccessors()
Remove all the successors of this block.
Definition: VPlan.h:613
VPBlockBase * getSingleHierarchicalSuccessor()
Definition: VPlan.h:560
void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse)
Set two given VPBlockBases IfTrue and IfFalse to be the two successors of this VPBlockBase.
Definition: VPlan.h:594
VPBlockBase * getSinglePredecessor() const
Definition: VPlan.h:530
virtual void execute(VPTransformState *State)=0
The method which generates the output IR that correspond to this VPBlockBase, thereby "executing" the...
const VPBlocksTy & getHierarchicalSuccessors()
Definition: VPlan.h:554
void clearPredecessors()
Remove all the predecessor of this block.
Definition: VPlan.h:610
enum { VPBasicBlockSC, VPRegionBlockSC } VPBlockTy
An enumeration for keeping track of the concrete subclass of VPBlockBase that are actually instantiat...
Definition: VPlan.h:474
unsigned getVPBlockID() const
Definition: VPlan.h:487
VPBlockBase(const unsigned char SC, const std::string &N)
Definition: VPlan.h:466
VPBlocksTy & getSuccessors()
Definition: VPlan.h:515
VPBlockBase * getEnclosingBlockWithSuccessors()
An Enclosing Block of a block B is any block containing B, including B itself.
Definition: VPlan.cpp:189
const VPBasicBlock * getEntryBasicBlock() const
Definition: VPlan.cpp:153
void setOneSuccessor(VPBlockBase *Successor)
Set a given VPBlockBase Successor as the single successor of this VPBlockBase.
Definition: VPlan.h:583
void setParent(VPRegionBlock *P)
Definition: VPlan.h:500
virtual void dropAllReferences(VPValue *NewValue)=0
Replace all operands of VPUsers in the block with NewValue and also replaces all uses of VPValues def...
VPBlockBase * getSingleHierarchicalPredecessor()
Definition: VPlan.h:576
VPBlockBase * getSingleSuccessor() const
Definition: VPlan.h:524
const VPBlocksTy & getSuccessors() const
Definition: VPlan.h:514
Class that provides utilities for VPBlockBases in VPlan.
Definition: VPlan.h:3373
static auto blocksOnly(const T &Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition: VPlan.h:3438
static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBase NewBlock after BlockPtr.
Definition: VPlan.h:3382
static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBases IfTrue and IfFalse after BlockPtr.
Definition: VPlan.h:3401
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
Definition: VPlan.h:3429
static void connectBlocks(VPBlockBase *From, VPBlockBase *To)
Connect VPBlockBases From and To bi-directionally.
Definition: VPlan.h:3418
A recipe for generating conditional branches on the bits of a mask.
Definition: VPlan.h:2215
VPValue * getMask() const
Return the mask used by this recipe.
Definition: VPlan.h:2247
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Definition: VPlan.h:2235
VPBranchOnMaskRecipe(VPValue *BlockInMask)
Definition: VPlan.h:2217
VPBranchOnMaskRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2223
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe uses scalars of operand Op.
Definition: VPlan.h:2254
void execute(VPTransformState &State) override
Generate the extraction of the appropriate bit from the block mask and the conditional branch.
Canonical scalar induction phi of the vector loop.
Definition: VPlan.h:2564
bool onlyFirstPartUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
Definition: VPlan.h:2605
~VPCanonicalIVPHIRecipe() override=default
static bool classof(const VPHeaderPHIRecipe *D)
Definition: VPlan.h:2579
VPCanonicalIVPHIRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2571
VPCanonicalIVPHIRecipe(VPValue *StartV, DebugLoc DL)
Definition: VPlan.h:2566
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:2598
void execute(VPTransformState &State) override
Generate the canonical scalar induction phi of the vector loop.
Type * getScalarType() const
Returns the scalar type of the induction.
Definition: VPlan.h:2593
bool isCanonical(InductionDescriptor::InductionKind Kind, VPValue *Start, VPValue *Step) const
Check if the induction described by Kind, /p Start and Step is canonical, i.e.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
This class augments a recipe with a set of VPValues defined by the recipe.
Definition: VPlanValue.h:313
unsigned getVPDefID() const
Definition: VPlanValue.h:433
A recipe for converting the input value IV value to the corresponding value of an IV with different s...
Definition: VPlan.h:2718
void execute(VPTransformState &State) override
Generate the transformed value of the induction at offset StartValue (1.
VPDerivedIVRecipe(InductionDescriptor::InductionKind Kind, const FPMathOperator *FPBinOp, VPValue *Start, VPValue *IV, VPValue *Step)
Definition: VPlan.h:2733
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getStepValue() const
Definition: VPlan.h:2763
VPDerivedIVRecipe(const InductionDescriptor &IndDesc, VPValue *Start, VPCanonicalIVPHIRecipe *CanonicalIV, VPValue *Step)
Definition: VPlan.h:2726
Type * getScalarType() const
Definition: VPlan.h:2758
VPDerivedIVRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2741
~VPDerivedIVRecipe() override=default
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:2766
VPValue * getStartValue() const
Definition: VPlan.h:2762
A recipe for generating the phi node for the current index of elements, adjusted in accordance with E...
Definition: VPlan.h:2653
static bool classof(const VPHeaderPHIRecipe *D)
Definition: VPlan.h:2666
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPEVLBasedIVPHIRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2660
~VPEVLBasedIVPHIRecipe() override=default
void execute(VPTransformState &State) override
Generate phi for handling IV based on EVL over iterations correctly.
VPEVLBasedIVPHIRecipe(VPValue *StartIV, DebugLoc DL)
Definition: VPlan.h:2655
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:2675
Recipe to expand a SCEV expression.
Definition: VPlan.h:2532
VPExpandSCEVRecipe(const SCEV *Expr, ScalarEvolution &SE)
Definition: VPlan.h:2537
const SCEV * getSCEV() const
Definition: VPlan.h:2557
void execute(VPTransformState &State) override
Generate a canonical vector induction variable of the vector loop, with.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPExpandSCEVRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2542
~VPExpandSCEVRecipe() override=default
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition: VPlan.h:1634
static bool classof(const VPValue *V)
Definition: VPlan.h:1651
VPHeaderPHIRecipe(unsigned char VPDefID, Instruction *UnderlyingInstr, VPValue *Start=nullptr, DebugLoc DL={})
Definition: VPlan.h:1636
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override=0
Print the recipe.
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition: VPlan.h:1678
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition: VPlan.h:1667
void setStartValue(VPValue *V)
Update the start value of the recipe.
Definition: VPlan.h:1675
VPValue * getStartValue() const
Definition: VPlan.h:1670
static bool classof(const VPRecipeBase *B)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition: VPlan.h:1647
void execute(VPTransformState &State) override=0
Generate the phi nodes.
virtual VPRecipeBase & getBackedgeRecipe()
Returns the backedge value as a recipe.
Definition: VPlan.h:1684
~VPHeaderPHIRecipe() override=default
This is a concrete Recipe that models a single VPlan-level instruction.
Definition: VPlan.h:1159
bool onlyFirstPartUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
Definition: VPlan.h:1309
VPInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands, DebugLoc DL, const Twine &Name="")
Definition: VPlan.h:1222
VPInstruction * clone() override
Clone the current recipe.
Definition: VPlan.h:1252
@ FirstOrderRecurrenceSplice
Definition: VPlan.h:1165
@ CanonicalIVIncrementForPart
Definition: VPlan.h:1175
@ CalculateTripCountMinusVF
Definition: VPlan.h:1173
bool hasResult() const
Definition: VPlan.h:1283
LLVM_DUMP_METHOD void dump() const
Print the VPInstruction to dbgs() (for debugging).
unsigned getOpcode() const
Definition: VPlan.h:1259
VPInstruction(unsigned Opcode, std::initializer_list< VPValue * > Operands, WrapFlagsTy WrapFlags, DebugLoc DL={}, const Twine &Name="")
Definition: VPlan.h:1234
VPInstruction(unsigned Opcode, std::initializer_list< VPValue * > Operands, DebugLoc DL={}, const Twine &Name="")
Definition: VPlan.h:1227
VPInstruction(unsigned Opcode, std::initializer_list< VPValue * > Operands, DisjointFlagsTy DisjointFlag, DebugLoc DL={}, const Twine &Name="")
Definition: VPlan.h:1239
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the VPInstruction to O.
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
Definition: VPlan.h:1276
void execute(VPTransformState &State) override
Generate the instruction.
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Definition: VPlan.h:2005
bool onlyFirstLaneUsed(const VPValue *Op) const override
The recipe only uses the first lane of the address.
Definition: VPlan.h:2084
~VPInterleaveRecipe() override=default
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition: VPlan.h:2046
VPInterleaveRecipe(const InterleaveGroup< Instruction > *IG, VPValue *Addr, ArrayRef< VPValue * > StoredValues, VPValue *Mask, bool NeedsMaskForGaps)
Definition: VPlan.h:2017
VPValue * getMask() const
Return the mask used by this recipe.
Definition: VPlan.h:2052
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPInterleaveRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2038
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition: VPlan.h:2059
const InterleaveGroup< Instruction > * getInterleaveGroup()
Definition: VPlan.h:2075
unsigned getNumStoreOperands() const
Returns the number of stored operands of this interleave group.
Definition: VPlan.h:2079
InterleaveGroup< VPInstruction > * getInterleaveGroup(VPInstruction *Instr) const
Get the interleave group that Instr belongs to.
Definition: VPlan.h:3489
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
Definition: VPlan.h:143
static VPLane getLastLaneForVF(const ElementCount &VF)
Definition: VPlan.h:169
static unsigned getNumCachedLanes(const ElementCount &VF)
Returns the maxmimum number of lanes that we are able to consider caching for VF.
Definition: VPlan.h:212
Value * getAsRuntimeExpr(IRBuilderBase &Builder, const ElementCount &VF) const
Returns an expression describing the lane index that can be used at runtime.
Definition: VPlan.cpp:68
VPLane(unsigned Lane, Kind LaneKind)
Definition: VPlan.h:165
Kind getKind() const
Returns the Kind of lane offset.
Definition: VPlan.h:193
bool isFirstLane() const
Returns true if this is the first lane of the whole vector.
Definition: VPlan.h:196
unsigned getKnownLane() const
Returns a compile-time known value for the lane index and asserts if the lane can only be calculated ...
Definition: VPlan.h:183
static VPLane getFirstLane()
Definition: VPlan.h:167
Kind
Kind describes how to interpret Lane.
Definition: VPlan.h:146
@ ScalableLast
For ScalableLast, Lane is the offset from the start of the last N-element subvector in a scalable vec...
@ First
For First, Lane is the index into the first N elements of a fixed-vector <N x <ElTy>> or a scalable v...
unsigned mapToCacheIndex(const ElementCount &VF) const
Maps the lane to a cache index based on VF.
Definition: VPlan.h:199
A value that is used outside the VPlan.
Definition: VPlan.h:669
VPLiveOut(PHINode *Phi, VPValue *Op)
Definition: VPlan.h:673
static bool classof(const VPUser *U)
Definition: VPlan.h:676
bool usesScalars(const VPValue *Op) const override
Returns true if the VPLiveOut uses scalars of operand Op.
Definition: VPlan.h:688
void print(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the VPLiveOut to O.
PHINode * getPhi() const
Definition: VPlan.h:694
void fixPhi(VPlan &Plan, VPTransformState &State)
Fixup the wrapped LCSSA phi node in the unique exit block.
VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when control converges back from ...
Definition: VPlan.h:2266
~VPPredInstPHIRecipe() override=default
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe uses scalars of operand Op.
Definition: VPlan.h:2290
VPPredInstPHIRecipe(VPValue *PredV)
Construct a VPPredInstPHIRecipe given PredInst whose value needs a phi nodes after merging back from ...
Definition: VPlan.h:2270
void execute(VPTransformState &State) override
Generates phi nodes for live-outs as needed to retain SSA form.
VPPredInstPHIRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2274
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition: VPlan.h:709
bool mayReadFromMemory() const
Returns true if the recipe may read from memory.
bool mayReadOrWriteMemory() const
Returns true if the recipe may read from or write to memory.
Definition: VPlan.h:795
bool mayHaveSideEffects() const
Returns true if the recipe may have side-effects.
bool mayWriteToMemory() const
Returns true if the recipe may write to memory.
virtual ~VPRecipeBase()=default
VPBasicBlock * getParent()
Definition: VPlan.h:734
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition: VPlan.h:800
virtual void execute(VPTransformState &State)=0
The method which generates the output IR instructions that correspond to this VPRecipe,...
void moveBefore(VPBasicBlock &BB, iplist< VPRecipeBase >::iterator I)
Unlink this recipe and insert into BB before I.
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
void insertAfter(VPRecipeBase *InsertPos)
Insert an unlinked Recipe into a basic block immediately after the specified Recipe.
static bool classof(const VPDef *D)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition: VPlan.h:771
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
VPRecipeBase(const unsigned char SC, ArrayRef< VPValue * > Operands, DebugLoc DL={})
Definition: VPlan.h:720
virtual VPRecipeBase * clone()=0
Clone the current recipe.
const VPBasicBlock * getParent() const
Definition: VPlan.h:735
static bool classof(const VPUser *U)
Definition: VPlan.h:776
VPRecipeBase(const unsigned char SC, iterator_range< IterT > Operands, DebugLoc DL={})
Definition: VPlan.h:725
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
bool isPhi() const
Returns true for PHI-like recipes.
Definition: VPlan.h:784
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
Class to record LLVM IR flag for a recipe along with it.
Definition: VPlan.h:897
ExactFlagsTy ExactFlags
Definition: VPlan.h:953
FastMathFlagsTy FMFs
Definition: VPlan.h:956
VPRecipeWithIRFlags(const unsigned char SC, IterT Operands, GEPFlagsTy GEPFlags, DebugLoc DL={})
Definition: VPlan.h:1030
NonNegFlagsTy NonNegFlags
Definition: VPlan.h:955
CmpInst::Predicate CmpPredicate
Definition: VPlan.h:950
VPRecipeWithIRFlags(const unsigned char SC, IterT Operands, CmpInst::Predicate Pred, DebugLoc DL={})
Definition: VPlan.h:1005
void setFlags(Instruction *I) const
Set the IR flags for I.
Definition: VPlan.h:1082
bool isInBounds() const
Definition: VPlan.h:1121
GEPFlagsTy GEPFlags
Definition: VPlan.h:954
static bool classof(const VPRecipeBase *R)
Definition: VPlan.h:1036
VPRecipeWithIRFlags(const unsigned char SC, IterT Operands, FastMathFlags FMFs, DebugLoc DL={})
Definition: VPlan.h:1017
void dropPoisonGeneratingFlags()
Drop all poison-generating flags.
Definition: VPlan.h:1051
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition: VPlan.h:1128
VPRecipeWithIRFlags(const unsigned char SC, IterT Operands, Instruction &I)
Definition: VPlan.h:975
DisjointFlagsTy DisjointFlags
Definition: VPlan.h:952
VPRecipeWithIRFlags(const unsigned char SC, IterT Operands, WrapFlagsTy WrapFlags, DebugLoc DL={})
Definition: VPlan.h:1011
VPRecipeWithIRFlags(const unsigned char SC, IterT Operands, DisjointFlagsTy DisjointFlags, DebugLoc DL={})
Definition: VPlan.h:1023
void transferFlags(VPRecipeWithIRFlags &Other)
Definition: VPlan.h:961
WrapFlagsTy WrapFlags
Definition: VPlan.h:951
bool hasNoUnsignedWrap() const
Definition: VPlan.h:1132
bool isDisjoint() const
Definition: VPlan.h:1144
void printFlags(raw_ostream &O) const
CmpInst::Predicate getPredicate() const
Definition: VPlan.h:1115
bool hasNoSignedWrap() const
Definition: VPlan.h:1138
static bool classof(const VPUser *U)
Definition: VPlan.h:1045
FastMathFlags getFastMathFlags() const
VPRecipeWithIRFlags(const unsigned char SC, IterT Operands, DebugLoc DL={})
Definition: VPlan.h:968
A recipe for handling reduction phis.
Definition: VPlan.h:1889
VPReductionPHIRecipe(PHINode *Phi, const RecurrenceDescriptor &RdxDesc, VPValue &Start, bool IsInLoop=false, bool IsOrdered=false)
Create a new VPReductionPHIRecipe for the reduction Phi described by RdxDesc.
Definition: VPlan.h:1902
bool isOrdered() const
Returns true, if the phi is part of an ordered reduction.
Definition: VPlan.h:1940
VPReductionPHIRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1912
~VPReductionPHIRecipe() override=default
bool isInLoop() const
Returns true, if the phi is part of an in-loop reduction.
Definition: VPlan.h:1943
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
static bool classof(const VPHeaderPHIRecipe *R)
Definition: VPlan.h:1922
const RecurrenceDescriptor & getRecurrenceDescriptor() const
Definition: VPlan.h:1935
A recipe to represent inloop reduction operations, performing a reduction on a vector operand into a ...
Definition: VPlan.h:2094
VPValue * getVecOp() const
The VPValue of the vector value to be reduced.
Definition: VPlan.h:2131
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPReductionRecipe(const RecurrenceDescriptor &R, Instruction *I, VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp, bool IsOrdered)
Definition: VPlan.h:2100
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition: VPlan.h:2133
~VPReductionRecipe() override=default
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition: VPlan.h:2129
VPReductionRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2112
void execute(VPTransformState &State) override
Generate the reduction in the loop.
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition: VPlan.h:2958
VPRegionBlock * clone() override
Clone all blocks in the single-entry single-exit region of the block and their recipes without updati...
Definition: VPlan.cpp:666
const VPBlockBase * getEntry() const
Definition: VPlan.h:2997
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition: VPlan.h:3029
void dropAllReferences(VPValue *NewValue) override
Replace all operands of VPUsers in the block with NewValue and also replaces all uses of VPValues def...
Definition: VPlan.cpp:675
void setExiting(VPBlockBase *ExitingBlock)
Set ExitingBlock as the exiting VPBlockBase of this VPRegionBlock.
Definition: VPlan.h:3014
VPBlockBase * getExiting()
Definition: VPlan.h:3010
void setEntry(VPBlockBase *EntryBlock)
Set EntryBlock as the entry VPBlockBase of this VPRegionBlock.
Definition: VPlan.h:3002
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print this VPRegionBlock to O (recursively), prefixing all lines with Indent.
Definition: VPlan.cpp:734
VPRegionBlock(const std::string &Name="", bool IsReplicator=false)
Definition: VPlan.h:2980
VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exiting, const std::string &Name="", bool IsReplicator=false)
Definition: VPlan.h:2971
void execute(VPTransformState *State) override
The method which generates the output IR instructions that correspond to this VPRegionBlock,...
Definition: VPlan.cpp:682
const VPBlockBase * getExiting() const
Definition: VPlan.h:3009
VPBlockBase * getEntry()
Definition: VPlan.h:2998
VPBasicBlock * getPreheaderVPBB()
Returns the pre-header VPBasicBlock of the loop region.
Definition: VPlan.h:3022
~VPRegionBlock() override
Definition: VPlan.h:2984
static bool classof(const VPBlockBase *V)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition: VPlan.h:2993
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition: VPlan.h:2142
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
~VPReplicateRecipe() override=default
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:2187
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe uses scalars of operand Op.
Definition: VPlan.h:2194
bool isUniform() const
Definition: VPlan.h:2182
bool isPredicated() const
Definition: VPlan.h:2184
VPReplicateRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2161
VPReplicateRecipe(Instruction *I, iterator_range< IterT > Operands, bool IsUniform, VPValue *Mask=nullptr)
Definition: VPlan.h:2151
unsigned getOpcode() const
Definition: VPlan.h:2211
VPValue * getMask()
Return the mask of a predicated VPReplicateRecipe.
Definition: VPlan.h:2206
bool shouldPack() const
Returns true if the recipe is used by a widened recipe via an intervening VPPredInstPHIRecipe.
VPScalarCastRecipe is a recipe to create scalar cast instructions.
Definition: VPlan.h:1410
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Each concrete VPDef prints itself.
~VPScalarCastRecipe() override=default
VPScalarCastRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1424
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Definition: VPlan.h:1440
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Type * getResultType() const
Returns the result type of the cast.
Definition: VPlan.h:1438
VPScalarCastRecipe(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy)
Definition: VPlan.h:1418
A recipe for handling phi nodes of integer and floating-point inductions, producing their scalar valu...
Definition: VPlan.h:2775
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:2815
VPValue * getStepValue() const
Definition: VPlan.h:2812
VPScalarIVStepsRecipe(const InductionDescriptor &IndDesc, VPValue *IV, VPValue *Step)
Definition: VPlan.h:2785
VPScalarIVStepsRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2795
VPScalarIVStepsRecipe(VPValue *IV, VPValue *Step, Instruction::BinaryOps Opcode, FastMathFlags FMFs)
Definition: VPlan.h:2779
~VPScalarIVStepsRecipe() override=default
void execute(VPTransformState &State) override
Generate the scalarized versions of the phi node as needed by their users.
VPSingleDef is a base class for recipes for modeling a sequence of one or more output IR that define ...
Definition: VPlan.h:826
VPSingleDefRecipe(const unsigned char SC, ArrayRef< VPValue * > Operands, DebugLoc DL={})
Definition: VPlan.h:832
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition: VPlan.h:888
static bool classof(const VPRecipeBase *R)
Definition: VPlan.h:841
const Instruction * getUnderlyingInstr() const
Definition: VPlan.h:891
VPSingleDefRecipe(const unsigned char SC, IterT Operands, DebugLoc DL={})
Definition: VPlan.h:829
static bool classof(const VPUser *U)
Definition: VPlan.h:880
VPSingleDefRecipe(const unsigned char SC, IterT Operands, Value *UV, DebugLoc DL={})
Definition: VPlan.h:837
virtual VPSingleDefRecipe * clone() override=0
Clone the current recipe.
This class can be used to assign names to VPValues.
Definition: VPlanValue.h:454
An analysis for type-inference for VPValues.
Definition: VPlanAnalysis.h:36
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition: VPlanValue.h:203
operand_range operands()
Definition: VPlanValue.h:278
void setOperand(unsigned I, VPValue *New)
Definition: VPlanValue.h:258
unsigned getNumOperands() const
Definition: VPlanValue.h:252
operand_iterator op_begin()
Definition: VPlanValue.h:274
VPValue * getOperand(unsigned N) const
Definition: VPlanValue.h:253
VPUser()=delete
void addOperand(VPValue *Operand)
Definition: VPlanValue.h:247
Value * getUnderlyingValue()
Return the underlying Value attached to this VPValue.
Definition: VPlanValue.h:77
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition: VPlan.cpp:118
unsigned getNumUsers() const
Definition: VPlanValue.h:112
Value * getLiveInIRValue()
Returns the underlying IR value, if this VPValue is defined outside the scope of VPlan.
Definition: VPlanValue.h:173
bool isLiveIn() const
Returns true if this VPValue is a live-in, i.e. defined outside the VPlan.
Definition: VPlanValue.h:168
friend class VPRecipeBase
Definition: VPlanValue.h:52
user_range users()
Definition: VPlanValue.h:133
bool isDefinedOutsideVectorRegions() const
Returns true if the VPValue is defined outside any vector regions, i.e.
Definition: VPlanValue.h:187
A recipe to compute the pointers for widened memory accesses of IndexTy for all parts.
Definition: VPlan.h:1578
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
VPVectorPointerRecipe(VPValue *Ptr, Type *IndexedTy, bool IsReverse, bool IsInBounds, DebugLoc DL)
Definition: VPlan.h:1583
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Definition: VPlan.h:1593
VPVectorPointerRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1599
A recipe for widening Call instructions.
Definition: VPlan.h:1449
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
const_operand_range arg_operands() const
Definition: VPlan.h:1490
VPWidenCallRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1473
VPWidenCallRecipe(Value *UV, iterator_range< IterT > CallArguments, Intrinsic::ID VectorIntrinsicID, DebugLoc DL={}, Function *Variant=nullptr)
Definition: VPlan.h:1461
Function * getCalledScalarFunction() const
Definition: VPlan.h:1483
void execute(VPTransformState &State) override
Produce a widened version of the call instruction.
operand_range arg_operands()
Definition: VPlan.h:1487
~VPWidenCallRecipe() override=default
A Recipe for widening the canonical induction variable of the vector loop.
Definition: VPlan.h:2689
void execute(VPTransformState &State) override
Generate a canonical vector induction variable of the vector loop, with start = {<Part*VF,...
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
~VPWidenCanonicalIVRecipe() override=default
VPWidenCanonicalIVRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2696
VPWidenCanonicalIVRecipe(VPCanonicalIVPHIRecipe *CanonicalIV)
Definition: VPlan.h:2691
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition: VPlan.h:1360
VPWidenCastRecipe(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy, CastInst &UI)
Definition: VPlan.h:1368
Instruction::CastOps getOpcode() const
Definition: VPlan.h:1403
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Type * getResultType() const
Returns the result type of the cast.
Definition: VPlan.h:1406
VPWidenCastRecipe(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy)
Definition: VPlan.h:1378
void execute(VPTransformState &State) override
Produce widened copies of the cast.
~VPWidenCastRecipe() override=default
VPWidenCastRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1384
A recipe for handling GEP instructions.
Definition: VPlan.h:1536
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the gep nodes.
VPWidenGEPRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1558
~VPWidenGEPRecipe() override=default
VPWidenGEPRecipe(GetElementPtrInst *GEP, iterator_range< IterT > Operands)
Definition: VPlan.h:1553
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition: VPlan.h:1691
VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step, const InductionDescriptor &IndDesc, TruncInst *Trunc)
Definition: VPlan.h:1704
const TruncInst * getTruncInst() const
Definition: VPlan.h:1752
VPRecipeBase & getBackedgeRecipe() override
Returns the backedge value as a recipe.
Definition: VPlan.h:1738
~VPWidenIntOrFpInductionRecipe() override=default
VPWidenIntOrFpInductionRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1714
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition: VPlan.h:1751
void execute(VPTransformState &State) override
Generate the vectorized and scalarized versions of the phi node as needed by their users.
VPValue * getStepValue()
Returns the step value of the induction.
Definition: VPlan.h:1746
VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step, const InductionDescriptor &IndDesc)
Definition: VPlan.h:1697
const VPValue * getStepValue() const
Definition: VPlan.h:1747
Type * getScalarType() const
Returns the scalar type of the induction.
Definition: VPlan.h:1765
VPValue * getBackedgeValue() override
Returns the incoming value from the loop backedge.
Definition: VPlan.h:1731
bool isCanonical() const
Returns true if the induction is canonical, i.e.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition: VPlan.h:1757
A common base class for widening memory operations.
Definition: VPlan.h:2299
bool IsMasked
Whether the memory access is masked.
Definition: VPlan.h:2310
bool Reverse
Whether the consecutive accessed addresses are in reverse order.
Definition: VPlan.h:2307
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition: VPlan.h:2346
static bool classof(const VPUser *U)
Definition: VPlan.h:2340
void execute(VPTransformState &State) override
Generate the wide load/store.
Definition: VPlan.h:2366
Instruction & Ingredient
Definition: VPlan.h:2301
VPWidenMemoryRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2329
Instruction & getIngredient() const
Definition: VPlan.h:2370
bool Consecutive
Whether the accessed addresses are consecutive.
Definition: VPlan.h:2304
static bool classof(const VPRecipeBase *R)
Definition: VPlan.h:2333
VPWidenMemoryRecipe(const char unsigned SC, Instruction &I, std::initializer_list< VPValue * > Operands, bool Consecutive, bool Reverse, DebugLoc DL)
Definition: VPlan.h:2320
VPValue * getMask() const
Return the mask used by this recipe.
Definition: VPlan.h:2360
bool isMasked() const
Returns true if the recipe is masked.
Definition: VPlan.h:2356
void setMask(VPValue *Mask)
Definition: VPlan.h:2312
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition: VPlan.h:2353
bool isReverse() const
Return whether the consecutive loaded/stored addresses are in reverse order.
Definition: VPlan.h:2350
A recipe for handling phis that are widened in the vector loop.
Definition: VPlan.h:1817
void addIncoming(VPValue *IncomingV, VPBasicBlock *IncomingBlock)
Adds a pair (IncomingV, IncomingBlock) to the phi.
Definition: VPlan.h:1847
VPValue * getIncomingValue(unsigned I)
Returns the I th incoming VPValue.
Definition: VPlan.h:1856
VPWidenPHIRecipe(PHINode *Phi, VPValue *Start=nullptr)
Create a new VPWidenPHIRecipe for Phi with start value Start.
Definition: VPlan.h:1823
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPWidenPHIRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1829
~VPWidenPHIRecipe() override=default
VPBasicBlock * getIncomingBlock(unsigned I)
Returns the I th incoming VPBasicBlock.
Definition: VPlan.h:1853
void execute(VPTransformState &State) override
Generate the phi/select nodes.
VPWidenPointerInductionRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1790
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition: VPlan.h:1805
~VPWidenPointerInductionRecipe() override=default
bool onlyScalarsGenerated(bool IsScalable)
Returns true if only scalar values will be generated.
void execute(VPTransformState &State) override
Generate vector values for the pointer induction.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPWidenPointerInductionRecipe(PHINode *Phi, VPValue *Start, VPValue *Step, const InductionDescriptor &IndDesc, bool IsScalarAfterVectorization)
Create a new VPWidenPointerInductionRecipe for Phi with start value Start.
Definition: VPlan.h:1778
VPWidenRecipe is a recipe for producing a copy of vector type its ingredient.
Definition: VPlan.h:1328
void execute(VPTransformState &State) override
Produce widened copies of all Ingredients.
VPWidenRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1339
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
~VPWidenRecipe() override=default
VPWidenRecipe(Instruction &I, iterator_range< IterT > Operands)
Definition: VPlan.h:1333
unsigned getOpcode() const
Definition: VPlan.h:1350
VPlanPrinter prints a given VPlan to a given output stream.
Definition: VPlan.h:3302
VPlanPrinter(raw_ostream &O, const VPlan &P)
Definition: VPlan.h:3343
LLVM_DUMP_METHOD void dump()
Definition: VPlan.cpp:1131
Class that maps (parts of) an existing VPlan to trees of combined VPInstructions.
Definition: VPlan.h:3496
VPInstruction * buildGraph(ArrayRef< VPValue * > Operands)
Tries to build an SLP tree rooted at Operands and returns a VPInstruction combining Operands,...
Definition: VPlanSLP.cpp:359
bool isCompletelySLP() const
Return true if all visited instruction can be combined.
Definition: VPlan.h:3586
~VPlanSlp()=default
VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB)
Definition: VPlan.h:3574
unsigned getWidestBundleBits() const
Return the width of the widest combined bundle in bits.
Definition: VPlan.h:3583
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition: VPlan.h:3059
void printDOT(raw_ostream &O) const
Print this VPlan in DOT format to O.
Definition: VPlan.cpp:984
std::string getName() const
Return a string with the name of the plan and the applicable VFs and UFs.
Definition: VPlan.cpp:960
void prepareToExecute(Value *TripCount, Value *VectorTripCount, Value *CanonicalIVStartValue, VPTransformState &State)
Prepare the plan for execution, setting up the required live-in values.
Definition: VPlan.cpp:783
bool hasScalableVF()
Definition: VPlan.h:3191
VPBasicBlock * getEntry()
Definition: VPlan.h:3152
VPValue & getVectorTripCount()
The vector trip count.
Definition: VPlan.h:3177
void setName(const Twine &newName)
Definition: VPlan.h:3208
VPValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition: VPlan.h:3180
VPValue * getTripCount() const
The trip count of the original loop.
Definition: VPlan.h:3156
VPValue * getOrCreateBackedgeTakenCount()
The backedge taken count of the original loop.
Definition: VPlan.h:3170
void removeLiveOut(PHINode *PN)
Definition: VPlan.h:3265
void addLiveOut(PHINode *PN, VPValue *V)
Definition: VPlan.cpp:993
const VPBasicBlock * getEntry() const
Definition: VPlan.h:3153
VPlan(VPBasicBlock *Preheader, VPValue *TC, VPBasicBlock *Entry)
Construct a VPlan with original preheader Preheader, trip count TC and Entry to the plan.
Definition: VPlan.h:3117
VPBasicBlock * getPreheader()
Definition: VPlan.h:3284
VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition: VPlan.h:3246
const VPRegionBlock * getVectorLoopRegion() const
Definition: VPlan.h:3249
static VPlanPtr createInitialVPlan(const SCEV *TripCount, ScalarEvolution &PSE)
Create initial VPlan skeleton, having an "entry" VPBasicBlock (wrapping original scalar pre-header) w...
Definition: VPlan.cpp:769
bool hasVF(ElementCount VF)
Definition: VPlan.h:3190
void addSCEVExpansion(const SCEV *S, VPValue *V)
Definition: VPlan.h:3278
bool hasUF(unsigned UF) const
Definition: VPlan.h:3197
void setVF(ElementCount VF)
Definition: VPlan.h:3184
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition: VPlan.h:3163
VPlan(VPBasicBlock *Preheader, VPBasicBlock *Entry)
Construct a VPlan with original preheader Preheader and Entry to the plan.
Definition: VPlan.h:3126
const VPBasicBlock * getPreheader() const
Definition: VPlan.h:3285
VPValue * getOrAddLiveIn(Value *V)
Gets the live-in VPValue for V or adds a new live-in (if none exists yet) for V.
Definition: VPlan.h:3212
LLVM_DUMP_METHOD void dump() const
Dump the plan to stderr (for debugging).
Definition: VPlan.cpp:990
bool hasScalarVFOnly() const
Definition: VPlan.h:3195
void execute(VPTransformState *State)
Generate the IR code for this VPlan.
Definition: VPlan.cpp:825
VPCanonicalIVPHIRecipe * getCanonicalIV()
Returns the canonical induction recipe of the vector loop.
Definition: VPlan.h:3254
const MapVector< PHINode *, VPLiveOut * > & getLiveOuts() const
Definition: VPlan.h:3270
void print(raw_ostream &O) const
Print this VPlan to O.
Definition: VPlan.cpp:934
void addVF(ElementCount VF)
Definition: VPlan.h:3182
VPValue * getLiveIn(Value *V) const
Return the live-in VPValue for V, if there is one or nullptr otherwise.
Definition: VPlan.h:3229
VPValue * getSCEVExpansion(const SCEV *S) const
Definition: VPlan.h:3274
void printLiveIns(raw_ostream &O) const
Print the live-ins of this VPlan to O.
Definition: VPlan.cpp:904
void setUF(unsigned UF)
Definition: VPlan.h:3199
VPlan * duplicate()
Clone the current VPlan, update all VPValues of the new VPlan and cloned recipes to refer to the clon...
Definition: VPlan.cpp:1074
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition: TypeSize.h:171
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition: TypeSize.h:168
An ilist node that can access its parent list.
Definition: ilist_node.h:284
base_list_type::const_reverse_iterator const_reverse_iterator
Definition: ilist.h:125
void pop_back()
Definition: ilist.h:255
base_list_type::reverse_iterator reverse_iterator
Definition: ilist.h:123
base_list_type::const_iterator const_iterator
Definition: ilist.h:122
iterator insert(iterator where, pointer New)
Definition: ilist.h:165
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition: iterator.h:80
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
This file defines classes to implement an intrusive doubly linked list class (i.e.
This file defines the ilist_node class template, which is a convenient base class for creating classe...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
Definition: ISDOpcodes.h:71
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, ScalarEvolution &SE)
Get or create a VPValue that corresponds to the expansion of Expr.
Definition: VPlan.cpp:1459
bool isUniformAfterVectorization(VPValue *VPV)
Returns true if VPV is uniform after vectorization.
Definition: VPlan.h:3606
bool onlyFirstPartUsed(const VPValue *Def)
Returns true if only the first part of Def is used.
Definition: VPlan.cpp:1454
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
Definition: VPlan.cpp:1449
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1742
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1722
bool isEqual(const GCNRPTracker::LiveRegSet &S1, const GCNRPTracker::LiveRegSet &S2)
const SCEV * createTripCountSCEV(Type *IdxTy, PredicatedScalarEvolution &PSE, Loop *OrigLoop)
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition: Error.h:198
Value * getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF)
Return the runtime value for VF.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
auto map_range(ContainerTy &&C, FuncTy F)
Definition: STLExtras.h:377
auto dyn_cast_or_null(const Y &Val)
Definition: Casting.h:759
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:1729
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:275
std::unique_ptr< VPlan > VPlanPtr
Definition: VPlan.h:134
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition: STLExtras.h:572
@ Other
Any other memory.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:293
Value * createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF, int64_t Step)
Return a value for Step multiplied by VF.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1879
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition: Hashing.h:491
#define N
A range of powers-of-2 vectorization factors with fixed start and adjustable end.
Definition: VPlan.h:87
iterator end()
Definition: VPlan.h:128
const ElementCount Start
Definition: VPlan.h:89
ElementCount End
Definition: VPlan.h:92
iterator begin()
Definition: VPlan.h:127
bool isEmpty() const
Definition: VPlan.h:94
VFRange(const ElementCount &Start, const ElementCount &End)
Definition: VPlan.h:98
A recipe for handling first-order recurrence phis.
Definition: VPlan.h:1862
void execute(VPTransformState &State) override
Generate the phi nodes.
VPFirstOrderRecurrencePHIRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1872
VPFirstOrderRecurrencePHIRecipe(PHINode *Phi, VPValue &Start)
Definition: VPlan.h:1863
static bool classof(const VPHeaderPHIRecipe *R)
Definition: VPlan.h:1868
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPIteration represents a single point in the iteration space of the output (vectorized and/or unrolle...
Definition: VPlan.h:219
VPIteration(unsigned Part, const VPLane &Lane)
Definition: VPlan.h:229
unsigned Part
in [0..UF)
Definition: VPlan.h:221
VPLane Lane
Definition: VPlan.h:223
VPIteration(unsigned Part, unsigned Lane, VPLane::Kind Kind=VPLane::Kind::First)
Definition: VPlan.h:225
bool isFirstIteration() const
Definition: VPlan.h:231
WrapFlagsTy(bool HasNUW, bool HasNSW)
Definition: VPlan.h:914
Hold state information used when constructing the CFG of the output IR, traversing the VPBasicBlocks ...
Definition: VPlan.h:359
BasicBlock * PrevBB
The previous IR BasicBlock created or used.
Definition: VPlan.h:365
SmallDenseMap< VPBasicBlock *, BasicBlock * > VPBB2IRBB
A mapping of each VPBasicBlock to the corresponding BasicBlock.
Definition: VPlan.h:373
VPBasicBlock * PrevVPBB
The previous VPBasicBlock visited. Initially set to null.
Definition: VPlan.h:361
BasicBlock * ExitBB
The last IR BasicBlock in the output IR.
Definition: VPlan.h:369
BasicBlock * getPreheaderBBFor(VPRecipeBase *R)
Returns the BasicBlock* mapped to the pre-header of the loop region containing R.
Definition: VPlan.cpp:348
SmallVector< Value *, 2 > PerPartValuesTy
A type for vectorized values in the new loop.
Definition: VPlan.h:254
DenseMap< VPValue *, ScalarsPerPartValuesTy > PerPartScalars
Definition: VPlan.h:259
DenseMap< VPValue *, PerPartValuesTy > PerPartOutput
Definition: VPlan.h:256
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
Definition: VPlan.h:236
Value * get(VPValue *Def, unsigned Part, bool IsScalar=false)
Get the generated vector Value for a given VPValue Def and a given Part if IsScalar is false,...
Definition: VPlan.cpp:247
LoopInfo * LI
Hold a pointer to LoopInfo to register new basic blocks in the loop.
Definition: VPlan.h:383
DenseMap< const SCEV *, Value * > ExpandedSCEVs
Map SCEVs to their expanded values.
Definition: VPlan.h:409
VPTypeAnalysis TypeAnalysis
VPlan-based type analysis.
Definition: VPlan.h:412
struct llvm::VPTransformState::DataState Data
void addMetadata(Value *To, Instruction *From)
Add metadata from one instruction to another.
Definition: VPlan.cpp:361
void reset(VPValue *Def, Value *V, unsigned Part)
Reset an existing vector value for Def and a given Part.
Definition: VPlan.h:303
struct llvm::VPTransformState::CFGState CFG
void reset(VPValue *Def, Value *V, const VPIteration &Instance)
Reset an existing scalar value for Def and a given Instance.
Definition: VPlan.h:325
LoopVersioning * LVer
LoopVersioning.
Definition: VPlan.h:405
void addNewMetadata(Instruction *To, const Instruction *Orig)
Add additional metadata to To that was not present on Orig.
Definition: VPlan.cpp:353
void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance)
Construct the vector value of a scalarized value V one lane at a time.
Definition: VPlan.cpp:393
void set(VPValue *Def, Value *V, const VPIteration &Instance)
Set the generated scalar V for Def and the given Instance.
Definition: VPlan.h:311
void set(VPValue *Def, Value *V, unsigned Part, bool IsScalar=false)
Set the generated vector Value for a given VPValue and a given Part, if IsScalar is false.
Definition: VPlan.h:288
std::optional< VPIteration > Instance
Hold the indices to generate specific scalar instructions.
Definition: VPlan.h:248
IRBuilderBase & Builder
Hold a reference to the IRBuilder used to generate output IR code.
Definition: VPlan.h:389
DominatorTree * DT
Hold a pointer to Dominator Tree to register new basic blocks in the loop.
Definition: VPlan.h:386
bool hasScalarValue(VPValue *Def, VPIteration Instance)
Definition: VPlan.h:276
VPlan * Plan
Pointer to the VPlan code is generated for.
Definition: VPlan.h:395
InnerLoopVectorizer * ILV
Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
Definition: VPlan.h:392
bool hasVectorValue(VPValue *Def, unsigned Part)
Definition: VPlan.h:270
ElementCount VF
The chosen Vectorization and Unroll Factors of the loop being vectorized.
Definition: VPlan.h:242
Loop * CurrentVectorLoop
The loop object for the current parent region, or nullptr.
Definition: VPlan.h:398
void setDebugLocFrom(DebugLoc DL)
Set the debug location in the builder using the debug location DL.
Definition: VPlan.cpp:372
A recipe for widening load operations with vector-predication intrinsics, using the address to load f...
Definition: VPlan.h:2414
void execute(VPTransformState &State) override
Generate the wide load or gather.
VPValue * getEVL() const
Return the EVL operand.
Definition: VPlan.h:2426
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPWidenLoadEVLRecipe(VPWidenLoadRecipe *L, VPValue *EVL, VPValue *Mask)
Definition: VPlan.h:2415
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:2438
A recipe for widening load operations, using the address to load from and an optional mask.
Definition: VPlan.h:2375
VP_CLASSOF_IMPL(VPDef::VPWidenLoadSC)
VPWidenLoadRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask, bool Consecutive, bool Reverse, DebugLoc DL)
Definition: VPlan.h:2376
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:2402
void execute(VPTransformState &State) override
Generate a wide load or gather.
VPWidenLoadRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2384
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
A recipe for widening select instructions.
Definition: VPlan.h:1502
bool isInvariantCond() const
Definition: VPlan.h:1530
VPWidenSelectRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1510
VPWidenSelectRecipe(SelectInst &I, iterator_range< IterT > Operands)
Definition: VPlan.h:1504
VPValue * getCond() const
Definition: VPlan.h:1526
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Produce a widened version of the select instruction.
~VPWidenSelectRecipe() override=default
A recipe for widening store operations with vector-predication intrinsics, using the value to store,...
Definition: VPlan.h:2490
VPValue * getStoredValue() const
Return the address accessed by this recipe.
Definition: VPlan.h:2502
void execute(VPTransformState &State) override
Generate the wide store or scatter.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPWidenStoreEVLRecipe(VPWidenStoreRecipe *S, VPValue *EVL, VPValue *Mask)
Definition: VPlan.h:2491
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:2517
VPValue * getEVL() const
Return the EVL operand.
Definition: VPlan.h:2505
A recipe for widening store operations, using the stored value, the address to store to and an option...
Definition: VPlan.h:2449
void execute(VPTransformState &State) override
Generate a wide store or scatter.
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:2478
VPWidenStoreRecipe(StoreInst &Store, VPValue *Addr, VPValue *StoredVal, VPValue *Mask, bool Consecutive, bool Reverse, DebugLoc DL)
Definition: VPlan.h:2450
VP_CLASSOF_IMPL(VPDef::VPWidenStoreSC)
VPValue * getStoredValue() const
Return the value stored by this recipe.
Definition: VPlan.h:2466
VPWidenStoreRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2457
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPlanIngredient(const Value *V)
Definition: VPlan.h:3352
const Value * V
Definition: VPlan.h:3350
void print(raw_ostream &O) const
Definition: VPlan.cpp:1249