xref: /llvm-project/llvm/lib/Analysis/ScalarEvolutionNormalization.cpp (revision e3a15e832cd1f62a51a734a0d083d51db4127494)
1 //===- ScalarEvolutionNormalization.cpp - See below -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements utilities for working with "normalized" expressions.
11 // See the comments at the top of ScalarEvolutionNormalization.h for details.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Analysis/LoopInfo.h"
16 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
17 #include "llvm/Analysis/ScalarEvolutionNormalization.h"
18 using namespace llvm;
19 
20 namespace {
21 
22 /// TransformKind - Different types of transformations that
23 /// TransformForPostIncUse can do.
24 enum TransformKind {
25   /// Normalize - Normalize according to the given loops.
26   Normalize,
27   /// Denormalize - Perform the inverse transform on the expression with the
28   /// given loop set.
29   Denormalize
30 };
31 
32 /// Hold the state used during post-inc expression transformation, including a
33 /// map of transformed expressions.
34 class PostIncTransform {
35   TransformKind Kind;
36   Optional<NormalizePredTy> Pred;
37   const PostIncLoopSet &Loops;
38   ScalarEvolution &SE;
39 
40   DenseMap<const SCEV*, const SCEV*> Transformed;
41 
42 public:
43   PostIncTransform(TransformKind kind, Optional<NormalizePredTy> Pred,
44                    const PostIncLoopSet &loops, ScalarEvolution &se)
45       : Kind(kind), Pred(Pred), Loops(loops), SE(se) {}
46 
47   const SCEV *TransformSubExpr(const SCEV *S);
48 
49 protected:
50   const SCEV *TransformImpl(const SCEV *S);
51 };
52 
53 } // namespace
54 
55 /// Implement post-inc transformation for all valid expression types.
56 const SCEV *PostIncTransform::TransformImpl(const SCEV *S) {
57   if (const SCEVCastExpr *X = dyn_cast<SCEVCastExpr>(S)) {
58     const SCEV *O = X->getOperand();
59     const SCEV *N = TransformSubExpr(O);
60     if (O != N)
61       switch (S->getSCEVType()) {
62       case scZeroExtend: return SE.getZeroExtendExpr(N, S->getType());
63       case scSignExtend: return SE.getSignExtendExpr(N, S->getType());
64       case scTruncate: return SE.getTruncateExpr(N, S->getType());
65       default: llvm_unreachable("Unexpected SCEVCastExpr kind!");
66       }
67     return S;
68   }
69 
70   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
71     // An addrec. This is the interesting part.
72     SmallVector<const SCEV *, 8> Operands;
73     const Loop *L = AR->getLoop();
74 
75     transform(AR->operands(), std::back_inserter(Operands),
76               [&](const SCEV *Op) { return TransformSubExpr(Op); });
77 
78     // Conservatively use AnyWrap until/unless we need FlagNW.
79     const SCEV *Result = SE.getAddRecExpr(Operands, L, SCEV::FlagAnyWrap);
80     switch (Kind) {
81     case Normalize:
82       // We want to normalize step expression, because otherwise we might not be
83       // able to denormalize to the original expression.
84       //
85       // Here is an example what will happen if we don't normalize step:
86       //  ORIGINAL ISE:
87       //    {(100 /u {1,+,1}<%bb16>),+,(100 /u {1,+,1}<%bb16>)}<%bb25>
88       //  NORMALIZED ISE:
89       //    {((-1 * (100 /u {1,+,1}<%bb16>)) + (100 /u {0,+,1}<%bb16>)),+,
90       //     (100 /u {0,+,1}<%bb16>)}<%bb25>
91       //  DENORMALIZED BACK ISE:
92       //    {((2 * (100 /u {1,+,1}<%bb16>)) + (-1 * (100 /u {2,+,1}<%bb16>))),+,
93       //     (100 /u {1,+,1}<%bb16>)}<%bb25>
94       //  Note that the initial value changes after normalization +
95       //  denormalization, which isn't correct.
96       if ((Pred && (*Pred)(AR)) || (!Pred && Loops.count(L))) {
97         const SCEV *TransformedStep =
98             TransformSubExpr(AR->getStepRecurrence(SE));
99         Result = SE.getMinusSCEV(Result, TransformedStep);
100       }
101 #if 0
102       // See the comment on the assert above.
103       assert(S == TransformSubExpr(Result, User, OperandValToReplace) &&
104              "SCEV normalization is not invertible!");
105 #endif
106       break;
107     case Denormalize:
108       // Here we want to normalize step expressions for the same reasons, as
109       // stated above.
110       if (Loops.count(L)) {
111         const SCEV *TransformedStep =
112             TransformSubExpr(AR->getStepRecurrence(SE));
113         Result = SE.getAddExpr(Result, TransformedStep);
114       }
115       break;
116     }
117     return Result;
118   }
119 
120   if (const SCEVNAryExpr *X = dyn_cast<SCEVNAryExpr>(S)) {
121     SmallVector<const SCEV *, 8> Operands;
122     bool Changed = false;
123     // Transform each operand.
124     for (SCEVNAryExpr::op_iterator I = X->op_begin(), E = X->op_end();
125          I != E; ++I) {
126       const SCEV *O = *I;
127       const SCEV *N = TransformSubExpr(O);
128       Changed |= N != O;
129       Operands.push_back(N);
130     }
131     // If any operand actually changed, return a transformed result.
132     if (Changed)
133       switch (S->getSCEVType()) {
134       case scAddExpr: return SE.getAddExpr(Operands);
135       case scMulExpr: return SE.getMulExpr(Operands);
136       case scSMaxExpr: return SE.getSMaxExpr(Operands);
137       case scUMaxExpr: return SE.getUMaxExpr(Operands);
138       default: llvm_unreachable("Unexpected SCEVNAryExpr kind!");
139       }
140     return S;
141   }
142 
143   if (const SCEVUDivExpr *X = dyn_cast<SCEVUDivExpr>(S)) {
144     const SCEV *LO = X->getLHS();
145     const SCEV *RO = X->getRHS();
146     const SCEV *LN = TransformSubExpr(LO);
147     const SCEV *RN = TransformSubExpr(RO);
148     if (LO != LN || RO != RN)
149       return SE.getUDivExpr(LN, RN);
150     return S;
151   }
152 
153   llvm_unreachable("Unexpected SCEV kind!");
154 }
155 
156 /// Manage recursive transformation across an expression DAG. Revisiting
157 /// expressions would lead to exponential recursion.
158 const SCEV *PostIncTransform::TransformSubExpr(const SCEV *S) {
159   if (isa<SCEVConstant>(S) || isa<SCEVUnknown>(S))
160     return S;
161 
162   const SCEV *Result = Transformed.lookup(S);
163   if (Result)
164     return Result;
165 
166   Result = TransformImpl(S);
167   Transformed[S] = Result;
168   return Result;
169 }
170 
171 /// Top level driver for transforming an expression DAG into its requested
172 /// post-inc form (either "Normalized" or "Denormalized").
173 static const SCEV *TransformForPostIncUse(TransformKind Kind, const SCEV *S,
174                                           Optional<NormalizePredTy> Pred,
175                                           const PostIncLoopSet &Loops,
176                                           ScalarEvolution &SE) {
177   PostIncTransform Transform(Kind, Pred, Loops, SE);
178   return Transform.TransformSubExpr(S);
179 }
180 
181 const SCEV *llvm::normalizeForPostIncUse(const SCEV *S,
182                                          const PostIncLoopSet &Loops,
183                                          ScalarEvolution &SE) {
184   return TransformForPostIncUse(Normalize, S, None, Loops, SE);
185 }
186 
187 const SCEV *llvm::normalizeForPostIncUseIf(const SCEV *S, NormalizePredTy Pred,
188                                            ScalarEvolution &SE) {
189   PostIncLoopSet Empty;
190   return TransformForPostIncUse(Normalize, S, Pred, Empty, SE);
191 }
192 
193 const SCEV *llvm::denormalizeForPostIncUse(const SCEV *S,
194                                            const PostIncLoopSet &Loops,
195                                            ScalarEvolution &SE) {
196   return TransformForPostIncUse(Denormalize, S, None, Loops, SE);
197 }
198