Fix include guards so they exactly match file names.
[oota-llvm.git] / include / llvm / Analysis / ScalarEvolutionExpander.h
1 //===---- llvm/Analysis/ScalarEvolutionExpander.h - SCEV Exprs --*- C++ -*-===//
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 defines the classes used to generate code from scalar expressions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ANALYSIS_SCALAREVOLUTIONEXPANDER_H
15 #define LLVM_ANALYSIS_SCALAREVOLUTIONEXPANDER_H
16
17 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
18 #include "llvm/Analysis/ScalarEvolutionNormalization.h"
19 #include "llvm/IR/IRBuilder.h"
20 #include "llvm/Support/TargetFolder.h"
21 #include "llvm/Support/ValueHandle.h"
22 #include <set>
23
24 namespace llvm {
25   class TargetTransformInfo;
26
27   /// Return true if the given expression is safe to expand in the sense that
28   /// all materialized values are safe to speculate.
29   bool isSafeToExpand(const SCEV *S);
30
31   /// SCEVExpander - This class uses information about analyze scalars to
32   /// rewrite expressions in canonical form.
33   ///
34   /// Clients should create an instance of this class when rewriting is needed,
35   /// and destroy it when finished to allow the release of the associated
36   /// memory.
37   class SCEVExpander : public SCEVVisitor<SCEVExpander, Value*> {
38     ScalarEvolution &SE;
39
40     // New instructions receive a name to identifies them with the current pass.
41     const char* IVName;
42
43     std::map<std::pair<const SCEV *, Instruction *>, AssertingVH<Value> >
44       InsertedExpressions;
45     std::set<AssertingVH<Value> > InsertedValues;
46     std::set<AssertingVH<Value> > InsertedPostIncValues;
47
48     /// RelevantLoops - A memoization of the "relevant" loop for a given SCEV.
49     DenseMap<const SCEV *, const Loop *> RelevantLoops;
50
51     /// PostIncLoops - Addrecs referring to any of the given loops are expanded
52     /// in post-inc mode. For example, expanding {1,+,1}<L> in post-inc mode
53     /// returns the add instruction that adds one to the phi for {0,+,1}<L>,
54     /// as opposed to a new phi starting at 1. This is only supported in
55     /// non-canonical mode.
56     PostIncLoopSet PostIncLoops;
57
58     /// IVIncInsertPos - When this is non-null, addrecs expanded in the
59     /// loop it indicates should be inserted with increments at
60     /// IVIncInsertPos.
61     const Loop *IVIncInsertLoop;
62
63     /// IVIncInsertPos - When expanding addrecs in the IVIncInsertLoop loop,
64     /// insert the IV increment at this position.
65     Instruction *IVIncInsertPos;
66
67     /// Phis that complete an IV chain. Reuse
68     std::set<AssertingVH<PHINode> > ChainedPhis;
69
70     /// CanonicalMode - When true, expressions are expanded in "canonical"
71     /// form. In particular, addrecs are expanded as arithmetic based on
72     /// a canonical induction variable. When false, expression are expanded
73     /// in a more literal form.
74     bool CanonicalMode;
75
76     /// When invoked from LSR, the expander is in "strength reduction" mode. The
77     /// only difference is that phi's are only reused if they are already in
78     /// "expanded" form.
79     bool LSRMode;
80
81     typedef IRBuilder<true, TargetFolder> BuilderType;
82     BuilderType Builder;
83
84 #ifndef NDEBUG
85     const char *DebugType;
86 #endif
87
88     friend struct SCEVVisitor<SCEVExpander, Value*>;
89
90   public:
91     /// SCEVExpander - Construct a SCEVExpander in "canonical" mode.
92     explicit SCEVExpander(ScalarEvolution &se, const char *name)
93       : SE(se), IVName(name), IVIncInsertLoop(0), IVIncInsertPos(0),
94         CanonicalMode(true), LSRMode(false),
95         Builder(se.getContext(), TargetFolder(se.TD)) {
96 #ifndef NDEBUG
97       DebugType = "";
98 #endif
99     }
100
101 #ifndef NDEBUG
102     void setDebugType(const char* s) { DebugType = s; }
103 #endif
104
105     /// clear - Erase the contents of the InsertedExpressions map so that users
106     /// trying to expand the same expression into multiple BasicBlocks or
107     /// different places within the same BasicBlock can do so.
108     void clear() {
109       InsertedExpressions.clear();
110       InsertedValues.clear();
111       InsertedPostIncValues.clear();
112       ChainedPhis.clear();
113     }
114
115     /// getOrInsertCanonicalInductionVariable - This method returns the
116     /// canonical induction variable of the specified type for the specified
117     /// loop (inserting one if there is none).  A canonical induction variable
118     /// starts at zero and steps by one on each iteration.
119     PHINode *getOrInsertCanonicalInductionVariable(const Loop *L, Type *Ty);
120
121     /// getIVIncOperand - Return the induction variable increment's IV operand.
122     Instruction *getIVIncOperand(Instruction *IncV, Instruction *InsertPos,
123                                  bool allowScale);
124
125     /// hoistIVInc - Utility for hoisting an IV increment.
126     bool hoistIVInc(Instruction *IncV, Instruction *InsertPos);
127
128     /// replaceCongruentIVs - replace congruent phis with their most canonical
129     /// representative. Return the number of phis eliminated.
130     unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT,
131                                  SmallVectorImpl<WeakVH> &DeadInsts,
132                                  const TargetTransformInfo *TTI = NULL);
133
134     /// expandCodeFor - Insert code to directly compute the specified SCEV
135     /// expression into the program.  The inserted code is inserted into the
136     /// specified block.
137     Value *expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I);
138
139     /// setIVIncInsertPos - Set the current IV increment loop and position.
140     void setIVIncInsertPos(const Loop *L, Instruction *Pos) {
141       assert(!CanonicalMode &&
142              "IV increment positions are not supported in CanonicalMode");
143       IVIncInsertLoop = L;
144       IVIncInsertPos = Pos;
145     }
146
147     /// setPostInc - Enable post-inc expansion for addrecs referring to the
148     /// given loops. Post-inc expansion is only supported in non-canonical
149     /// mode.
150     void setPostInc(const PostIncLoopSet &L) {
151       assert(!CanonicalMode &&
152              "Post-inc expansion is not supported in CanonicalMode");
153       PostIncLoops = L;
154     }
155
156     /// clearPostInc - Disable all post-inc expansion.
157     void clearPostInc() {
158       PostIncLoops.clear();
159
160       // When we change the post-inc loop set, cached expansions may no
161       // longer be valid.
162       InsertedPostIncValues.clear();
163     }
164
165     /// disableCanonicalMode - Disable the behavior of expanding expressions in
166     /// canonical form rather than in a more literal form. Non-canonical mode
167     /// is useful for late optimization passes.
168     void disableCanonicalMode() { CanonicalMode = false; }
169
170     void enableLSRMode() { LSRMode = true; }
171
172     /// clearInsertPoint - Clear the current insertion point. This is useful
173     /// if the instruction that had been serving as the insertion point may
174     /// have been deleted.
175     void clearInsertPoint() {
176       Builder.ClearInsertionPoint();
177     }
178
179     /// isInsertedInstruction - Return true if the specified instruction was
180     /// inserted by the code rewriter.  If so, the client should not modify the
181     /// instruction.
182     bool isInsertedInstruction(Instruction *I) const {
183       return InsertedValues.count(I) || InsertedPostIncValues.count(I);
184     }
185
186     void setChainedPhi(PHINode *PN) { ChainedPhis.insert(PN); }
187
188   private:
189     LLVMContext &getContext() const { return SE.getContext(); }
190
191     /// InsertBinop - Insert the specified binary operator, doing a small amount
192     /// of work to avoid inserting an obviously redundant operation.
193     Value *InsertBinop(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS);
194
195     /// ReuseOrCreateCast - Arange for there to be a cast of V to Ty at IP,
196     /// reusing an existing cast if a suitable one exists, moving an existing
197     /// cast if a suitable one exists but isn't in the right place, or
198     /// or creating a new one.
199     Value *ReuseOrCreateCast(Value *V, Type *Ty,
200                              Instruction::CastOps Op,
201                              BasicBlock::iterator IP);
202
203     /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
204     /// which must be possible with a noop cast, doing what we can to
205     /// share the casts.
206     Value *InsertNoopCastOfTo(Value *V, Type *Ty);
207
208     /// expandAddToGEP - Expand a SCEVAddExpr with a pointer type into a GEP
209     /// instead of using ptrtoint+arithmetic+inttoptr.
210     Value *expandAddToGEP(const SCEV *const *op_begin,
211                           const SCEV *const *op_end,
212                           PointerType *PTy, Type *Ty, Value *V);
213
214     Value *expand(const SCEV *S);
215
216     /// expandCodeFor - Insert code to directly compute the specified SCEV
217     /// expression into the program.  The inserted code is inserted into the
218     /// SCEVExpander's current insertion point. If a type is specified, the
219     /// result will be expanded to have that type, with a cast if necessary.
220     Value *expandCodeFor(const SCEV *SH, Type *Ty = 0);
221
222     /// getRelevantLoop - Determine the most "relevant" loop for the given SCEV.
223     const Loop *getRelevantLoop(const SCEV *);
224
225     Value *visitConstant(const SCEVConstant *S) {
226       return S->getValue();
227     }
228
229     Value *visitTruncateExpr(const SCEVTruncateExpr *S);
230
231     Value *visitZeroExtendExpr(const SCEVZeroExtendExpr *S);
232
233     Value *visitSignExtendExpr(const SCEVSignExtendExpr *S);
234
235     Value *visitAddExpr(const SCEVAddExpr *S);
236
237     Value *visitMulExpr(const SCEVMulExpr *S);
238
239     Value *visitUDivExpr(const SCEVUDivExpr *S);
240
241     Value *visitAddRecExpr(const SCEVAddRecExpr *S);
242
243     Value *visitSMaxExpr(const SCEVSMaxExpr *S);
244
245     Value *visitUMaxExpr(const SCEVUMaxExpr *S);
246
247     Value *visitUnknown(const SCEVUnknown *S) {
248       return S->getValue();
249     }
250
251     void rememberInstruction(Value *I);
252
253     void restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I);
254
255     bool isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV, const Loop *L);
256
257     bool isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV, const Loop *L);
258
259     Value *expandAddRecExprLiterally(const SCEVAddRecExpr *);
260     PHINode *getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
261                                        const Loop *L,
262                                        Type *ExpandTy,
263                                        Type *IntTy);
264     Value *expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
265                        Type *ExpandTy, Type *IntTy, bool useSubtract);
266   };
267 }
268
269 #endif