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