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