LLVM 23.0.0git
ScalarEvolutionExpressions.h
Go to the documentation of this file.
1//===- llvm/Analysis/ScalarEvolutionExpressions.h - SCEV Exprs --*- 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// This file defines the classes used to represent and build scalar expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ANALYSIS_SCALAREVOLUTIONEXPRESSIONS_H
14#define LLVM_ANALYSIS_SCALAREVOLUTIONEXPRESSIONS_H
15
16#include "llvm/ADT/DenseMap.h"
20#include "llvm/IR/Constants.h"
21#include "llvm/IR/ValueHandle.h"
25#include <cassert>
26#include <cstddef>
27
28namespace llvm {
29
30class APInt;
31class Constant;
32class ConstantInt;
33class ConstantRange;
34class Loop;
35class Type;
36class Value;
37
60
61/// This class represents a constant integer value.
62class SCEVConstant : public SCEV {
63 friend class ScalarEvolution;
64
65 ConstantInt *V;
66
67 SCEVConstant(const FoldingSetNodeIDRef ID, ConstantInt *v)
68 : SCEV(ID, scConstant, 1), V(v) {}
69
70public:
71 ConstantInt *getValue() const { return V; }
72 const APInt &getAPInt() const { return getValue()->getValue(); }
73
74 Type *getType() const { return V->getType(); }
75
76 /// Methods for support type inquiry through isa, cast, and dyn_cast:
77 static bool classof(const SCEV *S) { return S->getSCEVType() == scConstant; }
78};
79
80/// This class represents the value of vscale, as used when defining the length
81/// of a scalable vector or returned by the llvm.vscale() intrinsic.
82class SCEVVScale : public SCEV {
83 friend class ScalarEvolution;
84
85 SCEVVScale(const FoldingSetNodeIDRef ID, Type *ty)
86 : SCEV(ID, scVScale, 0), Ty(ty) {}
87
88 Type *Ty;
89
90public:
91 Type *getType() const { return Ty; }
92
93 /// Methods for support type inquiry through isa, cast, and dyn_cast:
94 static bool classof(const SCEV *S) { return S->getSCEVType() == scVScale; }
95};
96
97inline unsigned short computeExpressionSize(ArrayRef<const SCEV *> Args) {
98 APInt Size(16, 1);
99 for (const auto *Arg : Args)
100 Size = Size.uadd_sat(APInt(16, Arg->getExpressionSize()));
101 return (unsigned short)Size.getZExtValue();
102}
103
104/// This is the base class for unary cast operator classes.
105class SCEVCastExpr : public SCEV {
106protected:
107 const SCEV *Op;
109
111 const SCEV *op, Type *ty);
112
113public:
114 const SCEV *getOperand() const { return Op; }
115 const SCEV *getOperand(unsigned i) const {
116 assert(i == 0 && "Operand index out of range!");
117 return Op;
118 }
120 size_t getNumOperands() const { return 1; }
121 Type *getType() const { return Ty; }
122
123 /// Methods for support type inquiry through isa, cast, and dyn_cast:
124 static bool classof(const SCEV *S) {
125 return S->getSCEVType() == scPtrToAddr || S->getSCEVType() == scPtrToInt ||
126 S->getSCEVType() == scTruncate || S->getSCEVType() == scZeroExtend ||
128 }
129};
130
131/// This class represents a cast from a pointer to a pointer-sized integer
132/// value.
133class SCEVPtrToIntExpr : public SCEVCastExpr {
134 friend class ScalarEvolution;
135
136 SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, Type *ITy);
137
138public:
139 /// Methods for support type inquiry through isa, cast, and dyn_cast:
140 static bool classof(const SCEV *S) { return S->getSCEVType() == scPtrToInt; }
141};
142
143/// This class represents a cast from a pointer to a pointer-sized integer
144/// value, without capturing the provenance of the pointer.
145class SCEVPtrToAddrExpr : public SCEVCastExpr {
146 friend class ScalarEvolution;
147
148 SCEVPtrToAddrExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, Type *ITy);
149
150public:
151 /// Methods for support type inquiry through isa, cast, and dyn_cast:
152 static bool classof(const SCEV *S) { return S->getSCEVType() == scPtrToAddr; }
153};
154
155/// This is the base class for unary integral cast operator classes.
157protected:
159 const SCEV *op, Type *ty);
160
161public:
162 /// Methods for support type inquiry through isa, cast, and dyn_cast:
163 static bool classof(const SCEV *S) {
164 return S->getSCEVType() == scTruncate || S->getSCEVType() == scZeroExtend ||
166 }
167};
168
169/// This class represents a truncation of an integer value to a
170/// smaller integer value.
171class SCEVTruncateExpr : public SCEVIntegralCastExpr {
172 friend class ScalarEvolution;
173
174 SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, Type *ty);
175
176public:
177 /// Methods for support type inquiry through isa, cast, and dyn_cast:
178 static bool classof(const SCEV *S) { return S->getSCEVType() == scTruncate; }
179};
180
181/// This class represents a zero extension of a small integer value
182/// to a larger integer value.
183class SCEVZeroExtendExpr : public SCEVIntegralCastExpr {
184 friend class ScalarEvolution;
185
186 SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, const SCEV *op, Type *ty);
187
188public:
189 /// Methods for support type inquiry through isa, cast, and dyn_cast:
190 static bool classof(const SCEV *S) {
191 return S->getSCEVType() == scZeroExtend;
192 }
193};
194
195/// This class represents a sign extension of a small integer value
196/// to a larger integer value.
197class SCEVSignExtendExpr : public SCEVIntegralCastExpr {
198 friend class ScalarEvolution;
199
200 SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, const SCEV *op, Type *ty);
201
202public:
203 /// Methods for support type inquiry through isa, cast, and dyn_cast:
204 static bool classof(const SCEV *S) {
205 return S->getSCEVType() == scSignExtend;
206 }
207};
208
209/// This node is a base class providing common functionality for
210/// n'ary operators.
211class SCEVNAryExpr : public SCEV {
212protected:
213 // Since SCEVs are immutable, ScalarEvolution allocates operand
214 // arrays with its SCEVAllocator, so this class just needs a simple
215 // pointer rather than a more elaborate vector-like data structure.
216 // This also avoids the need for a non-trivial destructor.
217 const SCEV *const *Operands;
219
221 const SCEV *const *O, size_t N)
223 NumOperands(N) {}
224
225public:
226 size_t getNumOperands() const { return NumOperands; }
227
228 const SCEV *getOperand(unsigned i) const {
229 assert(i < NumOperands && "Operand index out of range!");
230 return Operands[i];
231 }
232
236
238 return (NoWrapFlags)(SubclassData & Mask);
239 }
240
241 bool hasNoUnsignedWrap() const {
243 }
244
245 bool hasNoSignedWrap() const {
247 }
248
249 bool hasNoSelfWrap() const { return getNoWrapFlags(FlagNW) != FlagAnyWrap; }
250
251 /// Methods for support type inquiry through isa, cast, and dyn_cast:
252 static bool classof(const SCEV *S) {
253 return S->getSCEVType() == scAddExpr || S->getSCEVType() == scMulExpr ||
254 S->getSCEVType() == scSMaxExpr || S->getSCEVType() == scUMaxExpr ||
255 S->getSCEVType() == scSMinExpr || S->getSCEVType() == scUMinExpr ||
258 }
259};
260
261/// This node is the base class for n'ary commutative operators.
263protected:
265 const SCEV *const *O, size_t N)
266 : SCEVNAryExpr(ID, T, O, N) {}
267
268public:
269 /// Methods for support type inquiry through isa, cast, and dyn_cast:
270 static bool classof(const SCEV *S) {
271 return S->getSCEVType() == scAddExpr || S->getSCEVType() == scMulExpr ||
272 S->getSCEVType() == scSMaxExpr || S->getSCEVType() == scUMaxExpr ||
273 S->getSCEVType() == scSMinExpr || S->getSCEVType() == scUMinExpr;
274 }
275
276 /// Set flags for a non-recurrence without clearing previously set flags.
277 void setNoWrapFlags(NoWrapFlags Flags) { SubclassData |= Flags; }
278};
279
280/// This node represents an addition of some number of SCEVs.
281class SCEVAddExpr : public SCEVCommutativeExpr {
282 friend class ScalarEvolution;
283
284 Type *Ty;
285
286 SCEVAddExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
288 auto *FirstPointerTypedOp = find_if(operands(), [](const SCEV *Op) {
289 return Op->getType()->isPointerTy();
290 });
291 if (FirstPointerTypedOp != operands().end())
292 Ty = (*FirstPointerTypedOp)->getType();
293 else
294 Ty = getOperand(0)->getType();
295 }
296
297public:
298 Type *getType() const { return Ty; }
299
300 /// Methods for support type inquiry through isa, cast, and dyn_cast:
301 static bool classof(const SCEV *S) { return S->getSCEVType() == scAddExpr; }
302};
303
304/// This node represents multiplication of some number of SCEVs.
305class SCEVMulExpr : public SCEVCommutativeExpr {
306 friend class ScalarEvolution;
307
308 SCEVMulExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
310
311public:
312 Type *getType() const { return getOperand(0)->getType(); }
313
314 /// Methods for support type inquiry through isa, cast, and dyn_cast:
315 static bool classof(const SCEV *S) { return S->getSCEVType() == scMulExpr; }
316};
317
318/// This class represents a binary unsigned division operation.
319class SCEVUDivExpr : public SCEV {
320 friend class ScalarEvolution;
321
322 std::array<const SCEV *, 2> Operands;
323
324 SCEVUDivExpr(const FoldingSetNodeIDRef ID, const SCEV *lhs, const SCEV *rhs)
325 : SCEV(ID, scUDivExpr, computeExpressionSize({lhs, rhs})) {
326 Operands[0] = lhs;
327 Operands[1] = rhs;
328 }
329
330public:
331 const SCEV *getLHS() const { return Operands[0]; }
332 const SCEV *getRHS() const { return Operands[1]; }
333 size_t getNumOperands() const { return 2; }
334 const SCEV *getOperand(unsigned i) const {
335 assert((i == 0 || i == 1) && "Operand index out of range!");
336 return i == 0 ? getLHS() : getRHS();
337 }
338
339 ArrayRef<const SCEV *> operands() const { return Operands; }
340
341 Type *getType() const {
342 // In most cases the types of LHS and RHS will be the same, but in some
343 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
344 // depend on the type for correctness, but handling types carefully can
345 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
346 // a pointer type than the RHS, so use the RHS' type here.
347 return getRHS()->getType();
348 }
349
350 /// Methods for support type inquiry through isa, cast, and dyn_cast:
351 static bool classof(const SCEV *S) { return S->getSCEVType() == scUDivExpr; }
352};
353
354/// This node represents a polynomial recurrence on the trip count
355/// of the specified loop. This is the primary focus of the
356/// ScalarEvolution framework; all the other SCEV subclasses are
357/// mostly just supporting infrastructure to allow SCEVAddRecExpr
358/// expressions to be created and analyzed.
359///
360/// All operands of an AddRec are required to be loop invariant.
361///
362class SCEVAddRecExpr : public SCEVNAryExpr {
363 friend class ScalarEvolution;
364
365 const Loop *L;
366
367 SCEVAddRecExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N,
368 const Loop *l)
369 : SCEVNAryExpr(ID, scAddRecExpr, O, N), L(l) {}
370
371public:
372 Type *getType() const { return getStart()->getType(); }
373 const SCEV *getStart() const { return Operands[0]; }
374 const Loop *getLoop() const { return L; }
375
376 /// Constructs and returns the recurrence indicating how much this
377 /// expression steps by. If this is a polynomial of degree N, it
378 /// returns a chrec of degree N-1. We cannot determine whether
379 /// the step recurrence has self-wraparound.
381 if (isAffine())
382 return getOperand(1);
383 return SE.getAddRecExpr(
386 }
387
388 /// Return true if this represents an expression A + B*x where A
389 /// and B are loop invariant values.
390 bool isAffine() const {
391 // We know that the start value is invariant. This expression is thus
392 // affine iff the step is also invariant.
393 return getNumOperands() == 2;
394 }
395
396 /// Return true if this represents an expression A + B*x + C*x^2
397 /// where A, B and C are loop invariant values. This corresponds
398 /// to an addrec of the form {L,+,M,+,N}
399 bool isQuadratic() const { return getNumOperands() == 3; }
400
401 /// Set flags for a recurrence without clearing any previously set flags.
402 /// For AddRec, either NUW or NSW implies NW. Keep track of this fact here
403 /// to make it easier to propagate flags.
405 if (Flags & (FlagNUW | FlagNSW))
406 Flags = ScalarEvolution::setFlags(Flags, FlagNW);
407 SubclassData |= Flags;
408 }
409
410 /// Return the value of this chain of recurrences at the specified
411 /// iteration number.
412 LLVM_ABI const SCEV *evaluateAtIteration(const SCEV *It,
413 ScalarEvolution &SE) const;
414
415 /// Return the value of this chain of recurrences at the specified iteration
416 /// number. Takes an explicit list of operands to represent an AddRec.
417 LLVM_ABI static const SCEV *
419 ScalarEvolution &SE);
420
421 /// Return the number of iterations of this loop that produce
422 /// values in the specified constant range. Another way of
423 /// looking at this is that it returns the first iteration number
424 /// where the value is not in the condition, thus computing the
425 /// exit count. If the iteration count can't be computed, an
426 /// instance of SCEVCouldNotCompute is returned.
428 ScalarEvolution &SE) const;
429
430 /// Return an expression representing the value of this expression
431 /// one iteration of the loop ahead.
433
434 /// Methods for support type inquiry through isa, cast, and dyn_cast:
435 static bool classof(const SCEV *S) {
436 return S->getSCEVType() == scAddRecExpr;
437 }
438};
439
440/// This node is the base class min/max selections.
442 friend class ScalarEvolution;
443
444 static bool isMinMaxType(enum SCEVTypes T) {
445 return T == scSMaxExpr || T == scUMaxExpr || T == scSMinExpr ||
446 T == scUMinExpr;
447 }
448
449protected:
450 /// Note: Constructing subclasses via this constructor is allowed
452 const SCEV *const *O, size_t N)
453 : SCEVCommutativeExpr(ID, T, O, N) {
454 assert(isMinMaxType(T));
455 // Min and max never overflow
457 }
458
459public:
460 Type *getType() const { return getOperand(0)->getType(); }
461
462 static bool classof(const SCEV *S) { return isMinMaxType(S->getSCEVType()); }
463
464 static enum SCEVTypes negate(enum SCEVTypes T) {
465 switch (T) {
466 case scSMaxExpr:
467 return scSMinExpr;
468 case scSMinExpr:
469 return scSMaxExpr;
470 case scUMaxExpr:
471 return scUMinExpr;
472 case scUMinExpr:
473 return scUMaxExpr;
474 default:
475 llvm_unreachable("Not a min or max SCEV type!");
476 }
477 }
478};
479
480/// This class represents a signed maximum selection.
481class SCEVSMaxExpr : public SCEVMinMaxExpr {
482 friend class ScalarEvolution;
483
484 SCEVSMaxExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
485 : SCEVMinMaxExpr(ID, scSMaxExpr, O, N) {}
486
487public:
488 /// Methods for support type inquiry through isa, cast, and dyn_cast:
489 static bool classof(const SCEV *S) { return S->getSCEVType() == scSMaxExpr; }
490};
491
492/// This class represents an unsigned maximum selection.
493class SCEVUMaxExpr : public SCEVMinMaxExpr {
494 friend class ScalarEvolution;
495
496 SCEVUMaxExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
497 : SCEVMinMaxExpr(ID, scUMaxExpr, O, N) {}
498
499public:
500 /// Methods for support type inquiry through isa, cast, and dyn_cast:
501 static bool classof(const SCEV *S) { return S->getSCEVType() == scUMaxExpr; }
502};
503
504/// This class represents a signed minimum selection.
505class SCEVSMinExpr : public SCEVMinMaxExpr {
506 friend class ScalarEvolution;
507
508 SCEVSMinExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
509 : SCEVMinMaxExpr(ID, scSMinExpr, O, N) {}
510
511public:
512 /// Methods for support type inquiry through isa, cast, and dyn_cast:
513 static bool classof(const SCEV *S) { return S->getSCEVType() == scSMinExpr; }
514};
515
516/// This class represents an unsigned minimum selection.
517class SCEVUMinExpr : public SCEVMinMaxExpr {
518 friend class ScalarEvolution;
519
520 SCEVUMinExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
521 : SCEVMinMaxExpr(ID, scUMinExpr, O, N) {}
522
523public:
524 /// Methods for support type inquiry through isa, cast, and dyn_cast:
525 static bool classof(const SCEV *S) { return S->getSCEVType() == scUMinExpr; }
526};
527
528/// This node is the base class for sequential/in-order min/max selections.
529/// Note that their fundamental difference from SCEVMinMaxExpr's is that they
530/// are early-returning upon reaching saturation point.
531/// I.e. given `0 umin_seq poison`, the result will be `0`, while the result of
532/// `0 umin poison` is `poison`. When returning early, later expressions are not
533/// executed, so `0 umin_seq (%x u/ 0)` does not result in undefined behavior.
535 friend class ScalarEvolution;
536
537 static bool isSequentialMinMaxType(enum SCEVTypes T) {
538 return T == scSequentialUMinExpr;
539 }
540
541 /// Set flags for a non-recurrence without clearing previously set flags.
542 void setNoWrapFlags(NoWrapFlags Flags) { SubclassData |= Flags; }
543
544protected:
545 /// Note: Constructing subclasses via this constructor is allowed
547 const SCEV *const *O, size_t N)
548 : SCEVNAryExpr(ID, T, O, N) {
549 assert(isSequentialMinMaxType(T));
550 // Min and max never overflow
551 setNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW));
552 }
553
554public:
555 Type *getType() const { return getOperand(0)->getType(); }
556
558 assert(isSequentialMinMaxType(Ty));
559 switch (Ty) {
561 return scUMinExpr;
562 default:
563 llvm_unreachable("Not a sequential min/max type.");
564 }
565 }
566
570
571 static bool classof(const SCEV *S) {
572 return isSequentialMinMaxType(S->getSCEVType());
573 }
574};
575
576/// This class represents a sequential/in-order unsigned minimum selection.
577class SCEVSequentialUMinExpr : public SCEVSequentialMinMaxExpr {
578 friend class ScalarEvolution;
579
580 SCEVSequentialUMinExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O,
581 size_t N)
583
584public:
585 /// Methods for support type inquiry through isa, cast, and dyn_cast:
586 static bool classof(const SCEV *S) {
587 return S->getSCEVType() == scSequentialUMinExpr;
588 }
589};
590
591/// This means that we are dealing with an entirely unknown SCEV
592/// value, and only represent it as its LLVM Value. This is the
593/// "bottom" value for the analysis.
594class LLVM_ABI SCEVUnknown final : public SCEV, private CallbackVH {
595 friend class ScalarEvolution;
596
597 /// The parent ScalarEvolution value. This is used to update the
598 /// parent's maps when the value associated with a SCEVUnknown is
599 /// deleted or RAUW'd.
600 ScalarEvolution *SE;
601
602 /// The next pointer in the linked list of all SCEVUnknown
603 /// instances owned by a ScalarEvolution.
604 SCEVUnknown *Next;
605
606 SCEVUnknown(const FoldingSetNodeIDRef ID, Value *V, ScalarEvolution *se,
607 SCEVUnknown *next)
608 : SCEV(ID, scUnknown, 1), CallbackVH(V), SE(se), Next(next) {}
609
610 // Implement CallbackVH.
611 void deleted() override;
612 void allUsesReplacedWith(Value *New) override;
613
614public:
615 Value *getValue() const { return getValPtr(); }
616
617 Type *getType() const { return getValPtr()->getType(); }
618
619 /// Methods for support type inquiry through isa, cast, and dyn_cast:
620 static bool classof(const SCEV *S) { return S->getSCEVType() == scUnknown; }
621};
622
623/// This class defines a simple visitor class that may be used for
624/// various SCEV analysis purposes.
625template <typename SC, typename RetVal = void> struct SCEVVisitor {
626 RetVal visit(const SCEV *S) {
627 switch (S->getSCEVType()) {
628 case scConstant:
629 return ((SC *)this)->visitConstant((const SCEVConstant *)S);
630 case scVScale:
631 return ((SC *)this)->visitVScale((const SCEVVScale *)S);
632 case scPtrToAddr:
633 return ((SC *)this)->visitPtrToAddrExpr((const SCEVPtrToAddrExpr *)S);
634 case scPtrToInt:
635 return ((SC *)this)->visitPtrToIntExpr((const SCEVPtrToIntExpr *)S);
636 case scTruncate:
637 return ((SC *)this)->visitTruncateExpr((const SCEVTruncateExpr *)S);
638 case scZeroExtend:
639 return ((SC *)this)->visitZeroExtendExpr((const SCEVZeroExtendExpr *)S);
640 case scSignExtend:
641 return ((SC *)this)->visitSignExtendExpr((const SCEVSignExtendExpr *)S);
642 case scAddExpr:
643 return ((SC *)this)->visitAddExpr((const SCEVAddExpr *)S);
644 case scMulExpr:
645 return ((SC *)this)->visitMulExpr((const SCEVMulExpr *)S);
646 case scUDivExpr:
647 return ((SC *)this)->visitUDivExpr((const SCEVUDivExpr *)S);
648 case scAddRecExpr:
649 return ((SC *)this)->visitAddRecExpr((const SCEVAddRecExpr *)S);
650 case scSMaxExpr:
651 return ((SC *)this)->visitSMaxExpr((const SCEVSMaxExpr *)S);
652 case scUMaxExpr:
653 return ((SC *)this)->visitUMaxExpr((const SCEVUMaxExpr *)S);
654 case scSMinExpr:
655 return ((SC *)this)->visitSMinExpr((const SCEVSMinExpr *)S);
656 case scUMinExpr:
657 return ((SC *)this)->visitUMinExpr((const SCEVUMinExpr *)S);
659 return ((SC *)this)
660 ->visitSequentialUMinExpr((const SCEVSequentialUMinExpr *)S);
661 case scUnknown:
662 return ((SC *)this)->visitUnknown((const SCEVUnknown *)S);
664 return ((SC *)this)->visitCouldNotCompute((const SCEVCouldNotCompute *)S);
665 }
666 llvm_unreachable("Unknown SCEV kind!");
667 }
668
670 llvm_unreachable("Invalid use of SCEVCouldNotCompute!");
671 }
672};
673
674/// Visit all nodes in the expression tree using worklist traversal.
675///
676/// Visitor implements:
677/// // return true to follow this node.
678/// bool follow(const SCEV *S);
679/// // return true to terminate the search.
680/// bool isDone();
681template <typename SV> class SCEVTraversal {
682 SV &Visitor;
685
686 void push(const SCEV *S) {
687 if (Visited.insert(S).second && Visitor.follow(S))
688 Worklist.push_back(S);
689 }
690
691public:
692 SCEVTraversal(SV &V) : Visitor(V) {}
693
694 void visitAll(const SCEV *Root) {
695 push(Root);
696 while (!Worklist.empty() && !Visitor.isDone()) {
697 const SCEV *S = Worklist.pop_back_val();
698
699 switch (S->getSCEVType()) {
700 case scConstant:
701 case scVScale:
702 case scUnknown:
703 continue;
704 case scPtrToAddr:
705 case scPtrToInt:
706 case scTruncate:
707 case scZeroExtend:
708 case scSignExtend:
709 case scAddExpr:
710 case scMulExpr:
711 case scUDivExpr:
712 case scSMaxExpr:
713 case scUMaxExpr:
714 case scSMinExpr:
715 case scUMinExpr:
717 case scAddRecExpr:
718 for (const auto *Op : S->operands()) {
719 push(Op);
720 if (Visitor.isDone())
721 break;
722 }
723 continue;
725 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
726 }
727 llvm_unreachable("Unknown SCEV kind!");
728 }
729 }
730};
731
732/// Use SCEVTraversal to visit all nodes in the given expression tree.
733template <typename SV> void visitAll(const SCEV *Root, SV &Visitor) {
734 SCEVTraversal<SV> T(Visitor);
735 T.visitAll(Root);
736}
737
738/// Return true if any node in \p Root satisfies the predicate \p Pred.
739template <typename PredTy>
740bool SCEVExprContains(const SCEV *Root, PredTy Pred) {
741 struct FindClosure {
742 bool Found = false;
743 PredTy Pred;
744
745 FindClosure(PredTy Pred) : Pred(Pred) {}
746
747 bool follow(const SCEV *S) {
748 if (!Pred(S))
749 return true;
750
751 Found = true;
752 return false;
753 }
754
755 bool isDone() const { return Found; }
756 };
757
758 FindClosure FC(Pred);
759 visitAll(Root, FC);
760 return FC.Found;
761}
762
763/// This visitor recursively visits a SCEV expression and re-writes it.
764/// The result from each visit is cached, so it will return the same
765/// SCEV for the same input.
766template <typename SC>
767class SCEVRewriteVisitor : public SCEVVisitor<SC, const SCEV *> {
768protected:
770 // Memoize the result of each visit so that we only compute once for
771 // the same input SCEV. This is to avoid redundant computations when
772 // a SCEV is referenced by multiple SCEVs. Without memoization, this
773 // visit algorithm would have exponential time complexity in the worst
774 // case, causing the compiler to hang on certain tests.
776
777public:
779
780 const SCEV *visit(const SCEV *S) {
781 auto It = RewriteResults.find(S);
782 if (It != RewriteResults.end())
783 return It->second;
784 auto *Visited = SCEVVisitor<SC, const SCEV *>::visit(S);
785 auto Result = RewriteResults.try_emplace(S, Visited);
786 assert(Result.second && "Should insert a new entry");
787 return Result.first->second;
788 }
789
791
792 const SCEV *visitVScale(const SCEVVScale *VScale) { return VScale; }
793
795 const SCEV *Operand = ((SC *)this)->visit(Expr->getOperand());
796 return Operand == Expr->getOperand() ? Expr : SE.getPtrToAddrExpr(Operand);
797 }
798
800 const SCEV *Operand = ((SC *)this)->visit(Expr->getOperand());
801 return Operand == Expr->getOperand()
802 ? Expr
803 : SE.getPtrToIntExpr(Operand, Expr->getType());
804 }
805
807 const SCEV *Operand = ((SC *)this)->visit(Expr->getOperand());
808 return Operand == Expr->getOperand()
809 ? Expr
810 : SE.getTruncateExpr(Operand, Expr->getType());
811 }
812
814 const SCEV *Operand = ((SC *)this)->visit(Expr->getOperand());
815 return Operand == Expr->getOperand()
816 ? Expr
817 : SE.getZeroExtendExpr(Operand, Expr->getType());
818 }
819
821 const SCEV *Operand = ((SC *)this)->visit(Expr->getOperand());
822 return Operand == Expr->getOperand()
823 ? Expr
824 : SE.getSignExtendExpr(Operand, Expr->getType());
825 }
826
827 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
829 bool Changed = false;
830 for (const auto *Op : Expr->operands()) {
831 Operands.push_back(((SC *)this)->visit(Op));
832 Changed |= Op != Operands.back();
833 }
834 return !Changed ? Expr : SE.getAddExpr(Operands);
835 }
836
837 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
839 bool Changed = false;
840 for (const auto *Op : Expr->operands()) {
841 Operands.push_back(((SC *)this)->visit(Op));
842 Changed |= Op != Operands.back();
843 }
844 return !Changed ? Expr : SE.getMulExpr(Operands);
845 }
846
847 const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) {
848 auto *LHS = ((SC *)this)->visit(Expr->getLHS());
849 auto *RHS = ((SC *)this)->visit(Expr->getRHS());
850 bool Changed = LHS != Expr->getLHS() || RHS != Expr->getRHS();
851 return !Changed ? Expr : SE.getUDivExpr(LHS, RHS);
852 }
853
854 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
856 bool Changed = false;
857 for (const auto *Op : Expr->operands()) {
858 Operands.push_back(((SC *)this)->visit(Op));
859 Changed |= Op != Operands.back();
860 }
861 return !Changed ? Expr
862 : SE.getAddRecExpr(Operands, Expr->getLoop(),
863 Expr->getNoWrapFlags());
864 }
865
866 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
868 bool Changed = false;
869 for (const auto *Op : Expr->operands()) {
870 Operands.push_back(((SC *)this)->visit(Op));
871 Changed |= Op != Operands.back();
872 }
873 return !Changed ? Expr : SE.getSMaxExpr(Operands);
874 }
875
876 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) {
878 bool Changed = false;
879 for (const auto *Op : Expr->operands()) {
880 Operands.push_back(((SC *)this)->visit(Op));
881 Changed |= Op != Operands.back();
882 }
883 return !Changed ? Expr : SE.getUMaxExpr(Operands);
884 }
885
886 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
888 bool Changed = false;
889 for (const auto *Op : Expr->operands()) {
890 Operands.push_back(((SC *)this)->visit(Op));
891 Changed |= Op != Operands.back();
892 }
893 return !Changed ? Expr : SE.getSMinExpr(Operands);
894 }
895
896 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
898 bool Changed = false;
899 for (const auto *Op : Expr->operands()) {
900 Operands.push_back(((SC *)this)->visit(Op));
901 Changed |= Op != Operands.back();
902 }
903 return !Changed ? Expr : SE.getUMinExpr(Operands);
904 }
905
908 bool Changed = false;
909 for (const auto *Op : Expr->operands()) {
910 Operands.push_back(((SC *)this)->visit(Op));
911 Changed |= Op != Operands.back();
912 }
913 return !Changed ? Expr : SE.getUMinExpr(Operands, /*Sequential=*/true);
914 }
915
916 const SCEV *visitUnknown(const SCEVUnknown *Expr) { return Expr; }
917
919 return Expr;
920 }
921};
922
925
926/// The SCEVParameterRewriter takes a scalar evolution expression and updates
927/// the SCEVUnknown components following the Map (Value -> SCEV).
928class SCEVParameterRewriter : public SCEVRewriteVisitor<SCEVParameterRewriter> {
929public:
930 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
931 ValueToSCEVMapTy &Map) {
933 return Rewriter.visit(Scev);
934 }
935
938
939 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
940 auto I = Map.find(Expr->getValue());
941 if (I == Map.end())
942 return Expr;
943 return I->second;
944 }
945
946private:
947 ValueToSCEVMapTy &Map;
948};
949
951
952/// The SCEVLoopAddRecRewriter takes a scalar evolution expression and applies
953/// the Map (Loop -> SCEV) to all AddRecExprs.
955 : public SCEVRewriteVisitor<SCEVLoopAddRecRewriter> {
956public:
959
960 static const SCEV *rewrite(const SCEV *Scev, LoopToScevMapT &Map,
963 return Rewriter.visit(Scev);
964 }
965
966 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
968 for (const SCEV *Op : Expr->operands())
969 Operands.push_back(visit(Op));
970
971 const Loop *L = Expr->getLoop();
972 auto It = Map.find(L);
973 if (It == Map.end())
974 return SE.getAddRecExpr(Operands, L, Expr->getNoWrapFlags());
975
976 return SCEVAddRecExpr::evaluateAtIteration(Operands, It->second, SE);
977 }
978
979private:
980 LoopToScevMapT &Map;
981};
982
983} // end namespace llvm
984
985#endif // LLVM_ANALYSIS_SCALAREVOLUTIONEXPRESSIONS_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:213
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
#define op(i)
#define I(x, y, z)
Definition MD5.cpp:57
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
Virtual Register Rewriter
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
CallbackVH(const CallbackVH &)=default
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
This class represents a range of values.
This is an important base class in LLVM.
Definition Constant.h:43
FoldingSetNodeIDRef - This class describes a reference to an interned FoldingSetNodeID,...
Definition FoldingSet.h:172
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
This node represents an addition of some number of SCEVs.
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
This node represents a polynomial recurrence on the trip count of the specified loop.
LLVM_ABI const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
void setNoWrapFlags(NoWrapFlags Flags)
Set flags for a recurrence without clearing any previously set flags.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
bool isQuadratic() const
Return true if this represents an expression A + B*x + C*x^2 where A, B and C are loop invariant valu...
LLVM_ABI const SCEV * getNumIterationsInRange(const ConstantRange &Range, ScalarEvolution &SE) const
Return the number of iterations of this loop that produce values in the specified constant range.
LLVM_ABI const SCEVAddRecExpr * getPostIncExpr(ScalarEvolution &SE) const
Return an expression representing the value of this expression one iteration of the loop ahead.
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
const SCEV * getOperand(unsigned i) const
ArrayRef< const SCEV * > operands() const
const SCEV * getOperand() const
LLVM_ABI SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, const SCEV *op, Type *ty)
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
void setNoWrapFlags(NoWrapFlags Flags)
Set flags for a non-recurrence without clearing previously set flags.
SCEVCommutativeExpr(const FoldingSetNodeIDRef ID, enum SCEVTypes T, const SCEV *const *O, size_t N)
This class represents a constant integer value.
ConstantInt * getValue() const
const APInt & getAPInt() const
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
LLVM_ABI SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, const SCEV *op, Type *ty)
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
static const SCEV * rewrite(const SCEV *Scev, LoopToScevMapT &Map, ScalarEvolution &SE)
const SCEV * visitAddRecExpr(const SCEVAddRecExpr *Expr)
SCEVLoopAddRecRewriter(ScalarEvolution &SE, LoopToScevMapT &M)
static enum SCEVTypes negate(enum SCEVTypes T)
SCEVMinMaxExpr(const FoldingSetNodeIDRef ID, enum SCEVTypes T, const SCEV *const *O, size_t N)
Note: Constructing subclasses via this constructor is allowed.
static bool classof(const SCEV *S)
This node represents multiplication of some number of SCEVs.
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
SCEVNAryExpr(const FoldingSetNodeIDRef ID, enum SCEVTypes T, const SCEV *const *O, size_t N)
const SCEV * getOperand(unsigned i) const
ArrayRef< const SCEV * > operands() const
const SCEV * visitUnknown(const SCEVUnknown *Expr)
static const SCEV * rewrite(const SCEV *Scev, ScalarEvolution &SE, ValueToSCEVMapTy &Map)
SCEVParameterRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M)
This class represents a cast from a pointer to a pointer-sized integer value, without capturing the p...
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
This class represents a cast from a pointer to a pointer-sized integer value.
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
const SCEV * visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr)
const SCEV * visitSignExtendExpr(const SCEVSignExtendExpr *Expr)
const SCEV * visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr)
const SCEV * visit(const SCEV *S)
const SCEV * visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr)
const SCEV * visitUnknown(const SCEVUnknown *Expr)
const SCEV * visitSMinExpr(const SCEVSMinExpr *Expr)
const SCEV * visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr)
const SCEV * visitAddExpr(const SCEVAddExpr *Expr)
const SCEV * visitUMinExpr(const SCEVUMinExpr *Expr)
const SCEV * visitMulExpr(const SCEVMulExpr *Expr)
SmallDenseMap< const SCEV *, const SCEV * > RewriteResults
const SCEV * visitTruncateExpr(const SCEVTruncateExpr *Expr)
const SCEV * visitUMaxExpr(const SCEVUMaxExpr *Expr)
const SCEV * visitSMaxExpr(const SCEVSMaxExpr *Expr)
const SCEV * visitUDivExpr(const SCEVUDivExpr *Expr)
const SCEV * visitCouldNotCompute(const SCEVCouldNotCompute *Expr)
const SCEV * visitVScale(const SCEVVScale *VScale)
const SCEV * visitAddRecExpr(const SCEVAddRecExpr *Expr)
const SCEV * visitConstant(const SCEVConstant *Constant)
This class represents a signed maximum selection.
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
This class represents a signed minimum selection.
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
SCEVSequentialMinMaxExpr(const FoldingSetNodeIDRef ID, enum SCEVTypes T, const SCEV *const *O, size_t N)
Note: Constructing subclasses via this constructor is allowed.
static SCEVTypes getEquivalentNonSequentialSCEVType(SCEVTypes Ty)
This class represents a sequential/in-order unsigned minimum selection.
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
This class represents a sign extension of a small integer value to a larger integer value.
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
Visit all nodes in the expression tree using worklist traversal.
void visitAll(const SCEV *Root)
This class represents a truncation of an integer value to a smaller integer value.
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
This class represents a binary unsigned division operation.
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
ArrayRef< const SCEV * > operands() const
const SCEV * getOperand(unsigned i) const
This class represents an unsigned maximum selection.
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
This class represents an unsigned minimum selection.
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
This class represents the value of vscale, as used when defining the length of a scalable vector or r...
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
This class represents a zero extension of a small integer value to a larger integer value.
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
This class represents an analyzed expression in the program.
LLVM_ABI ArrayRef< const SCEV * > operands() const
Return operands of this SCEV expression.
SCEV(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, unsigned short ExpressionSize)
SCEVTypes getSCEVType() const
unsigned short SubclassData
This field is initialized to zero and may be used in subclasses to store miscellaneous information.
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
NoWrapFlags
NoWrapFlags are bitfield indices into SubclassData.
The main scalar evolution driver.
LLVM_ABI const SCEV * getAddRecExpr(const SCEV *Start, const SCEV *Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags)
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
Value * getValPtr() const
LLVM Value Representation.
Definition Value.h:75
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
DenseMap< const Value *, const SCEV * > ValueToSCEVMapTy
DenseMap< const Loop *, const SCEV * > LoopToScevMapT
unsigned short computeExpressionSize(ArrayRef< const SCEV * > Args)
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1770
DenseMap< const Value *, Value * > ValueToValueMap
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
#define N
An object of this class is returned by queries that could not be answered.
This class defines a simple visitor class that may be used for various SCEV analysis purposes.
RetVal visit(const SCEV *S)
RetVal visitCouldNotCompute(const SCEVCouldNotCompute *S)