1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ART_COMPILER_OPTIMIZING_INDUCTION_VAR_RANGE_H_
18 #define ART_COMPILER_OPTIMIZING_INDUCTION_VAR_RANGE_H_
19 
20 #include "induction_var_analysis.h"
21 
22 namespace art {
23 
24 /**
25  * This class implements range analysis on expressions within loops. It takes the results
26  * of induction variable analysis in the constructor and provides a public API to obtain
27  * a conservative lower and upper bound value or last value on each instruction in the HIR.
28  * The public API also provides a few general-purpose utility methods related to induction.
29  *
30  * The range analysis is done with a combination of symbolic and partial integral evaluation
31  * of expressions. The analysis avoids complications with wrap-around arithmetic on the integral
32  * parts but all clients should be aware that wrap-around may occur on any of the symbolic parts.
33  * For example, given a known range for [0,100] for i, the evaluation yields range [-100,100]
34  * for expression -2*i+100, which is exact, and range [x,x+100] for expression i+x, which may
35  * wrap-around anywhere in the range depending on the actual value of x.
36  */
37 class InductionVarRange {
38  public:
39   /*
40    * A value that can be represented as "a * instruction + b" for 32-bit constants, where
41    * Value() denotes an unknown lower and upper bound. Although range analysis could yield
42    * more complex values, the format is sufficiently powerful to represent useful cases
43    * and feeds directly into optimizations like bounds check elimination.
44    */
45   struct Value {
ValueValue46     Value() : instruction(nullptr), a_constant(0), b_constant(0), is_known(false) {}
ValueValue47     Value(HInstruction* i, int32_t a, int32_t b)
48         : instruction(a != 0 ? i : nullptr), a_constant(a), b_constant(b), is_known(true) {}
ValueValue49     explicit Value(int32_t b) : Value(nullptr, 0, b) {}
50     // Representation as: a_constant x instruction + b_constant.
51     HInstruction* instruction;
52     int32_t a_constant;
53     int32_t b_constant;
54     // If true, represented by prior fields. Otherwise unknown value.
55     bool is_known;
56   };
57 
58   explicit InductionVarRange(HInductionVarAnalysis* induction);
59 
60   /**
61    * Given a context denoted by the first instruction, returns a possibly conservative lower
62    * and upper bound on the instruction's value in the output parameters min_val and max_val,
63    * respectively. The need_finite_test flag denotes if an additional finite-test is needed
64    * to protect the range evaluation inside its loop. The parameter chase_hint defines an
65    * instruction at which chasing may stop. Returns false on failure.
66    */
67   bool GetInductionRange(HInstruction* context,
68                          HInstruction* instruction,
69                          HInstruction* chase_hint,
70                          /*out*/ Value* min_val,
71                          /*out*/ Value* max_val,
72                          /*out*/ bool* needs_finite_test);
73 
74   /**
75    * Returns true if range analysis is able to generate code for the lower and upper
76    * bound expressions on the instruction in the given context. The need_finite_test
77    * and need_taken test flags denote if an additional finite-test and/or taken-test
78    * are needed to protect the range evaluation inside its loop.
79    */
80   bool CanGenerateRange(HInstruction* context,
81                         HInstruction* instruction,
82                         /*out*/ bool* needs_finite_test,
83                         /*out*/ bool* needs_taken_test);
84 
85   /**
86    * Generates the actual code in the HIR for the lower and upper bound expressions on the
87    * instruction in the given context. Code for the lower and upper bound expression are
88    * generated in given block and graph and are returned in the output parameters lower and
89    * upper, respectively. For a loop invariant, lower is not set.
90    *
91    * For example, given expression x+i with range [0, 5] for i, calling this method
92    * will generate the following sequence:
93    *
94    * block:
95    *   lower: add x, 0
96    *   upper: add x, 5
97    *
98    * Precondition: CanGenerateRange() returns true.
99    */
100   void GenerateRange(HInstruction* context,
101                      HInstruction* instruction,
102                      HGraph* graph,
103                      HBasicBlock* block,
104                      /*out*/ HInstruction** lower,
105                      /*out*/ HInstruction** upper);
106 
107   /**
108    * Generates explicit taken-test for the loop in the given context. Code is generated in
109    * given block and graph. Returns generated taken-test.
110    *
111    * Precondition: CanGenerateRange() returns true and needs_taken_test is set.
112    */
113   HInstruction* GenerateTakenTest(HInstruction* context, HGraph* graph, HBasicBlock* block);
114 
115   /**
116    * Returns true if induction analysis is able to generate code for last value of
117    * the given instruction inside the closest enveloping loop.
118    */
119   bool CanGenerateLastValue(HInstruction* instruction);
120 
121   /**
122    * Generates last value of the given instruction in the closest enveloping loop.
123    * Code is generated in given block and graph. Returns generated last value.
124    *
125    * Precondition: CanGenerateLastValue() returns true.
126    */
127   HInstruction* GenerateLastValue(HInstruction* instruction, HGraph* graph, HBasicBlock* block);
128 
129   /**
130    * Updates all matching fetches with the given replacement in all induction information
131    * that is associated with the given instruction.
132    */
133   void Replace(HInstruction* instruction, HInstruction* fetch, HInstruction* replacement);
134 
135   /**
136    * Incrementally updates induction information for just the given loop.
137    */
ReVisit(HLoopInformation * loop)138   void ReVisit(HLoopInformation* loop) {
139     induction_analysis_->induction_.erase(loop);
140     for (HInstructionIterator it(loop->GetHeader()->GetPhis()); !it.Done(); it.Advance()) {
141       induction_analysis_->cycles_.erase(it.Current()->AsPhi());
142     }
143     induction_analysis_->VisitLoop(loop);
144   }
145 
146   /**
147    * Lookup an interesting cycle associated with an entry phi.
148    */
LookupCycle(HPhi * phi)149   ArenaSet<HInstruction*>* LookupCycle(HPhi* phi) const {
150     return induction_analysis_->LookupCycle(phi);
151   }
152 
153   /**
154    * Checks if the given phi instruction has been classified as anything by
155    * induction variable analysis. Returns false for anything that cannot be
156    * classified statically, such as reductions or other complex cycles.
157    */
IsClassified(HPhi * phi)158   bool IsClassified(HPhi* phi) const {
159     HLoopInformation* lp = phi->GetBlock()->GetLoopInformation();  // closest enveloping loop
160     return (lp != nullptr) && (induction_analysis_->LookupInfo(lp, phi) != nullptr);
161   }
162 
163   /**
164    * Checks if header logic of a loop terminates. If trip count is known sets 'trip_count' to its
165    * value.
166    */
167   bool IsFinite(HLoopInformation* loop, /*out*/ int64_t* trip_count) const;
168 
169   /**
170    * Checks if a trip count is known for the loop and sets 'trip_count' to its value in this case.
171    */
172   bool HasKnownTripCount(HLoopInformation* loop, /*out*/ int64_t* trip_count) const;
173 
174   /**
175    * Checks if the given instruction is a unit stride induction inside the closest enveloping
176    * loop of the context that is defined by the first parameter (e.g. pass an array reference
177    * as context and the index as instruction to make sure the stride is tested against the
178    * loop that envelops the reference the closest). Returns invariant offset on success.
179    */
180   bool IsUnitStride(HInstruction* context,
181                     HInstruction* instruction,
182                     HGraph* graph,
183                     /*out*/ HInstruction** offset) const;
184 
185   /**
186    * Generates the trip count expression for the given loop. Code is generated in given block
187    * and graph. The expression is guarded by a taken test if needed. Returns the trip count
188    * expression on success or null otherwise.
189    */
190   HInstruction* GenerateTripCount(HLoopInformation* loop, HGraph* graph, HBasicBlock* block);
191 
192  private:
193   /*
194    * Enum used in IsConstant() request.
195    */
196   enum ConstantRequest {
197     kExact,
198     kAtMost,
199     kAtLeast
200   };
201 
202   /**
203    * Checks if header logic of a loop terminates. If trip count is known (constant) sets
204    * 'is_constant' to true and 'trip_count' to the trip count value.
205    */
206   bool CheckForFiniteAndConstantProps(HLoopInformation* loop,
207                                       /*out*/ bool* is_constant,
208                                       /*out*/ int64_t* trip_count) const;
209 
210   /**
211    * Returns true if exact or upper/lower bound on the given induction
212    * information is known as a 64-bit constant, which is returned in value.
213    */
214   bool IsConstant(HInductionVarAnalysis::InductionInfo* info,
215                   ConstantRequest request,
216                   /*out*/ int64_t* value) const;
217 
218   /** Returns whether induction information can be obtained. */
219   bool HasInductionInfo(HInstruction* context,
220                         HInstruction* instruction,
221                         /*out*/ HLoopInformation** loop,
222                         /*out*/ HInductionVarAnalysis::InductionInfo** info,
223                         /*out*/ HInductionVarAnalysis::InductionInfo** trip) const;
224 
225   bool HasFetchInLoop(HInductionVarAnalysis::InductionInfo* info) const;
226   bool NeedsTripCount(HInductionVarAnalysis::InductionInfo* info,
227                       /*out*/ int64_t* stride_value) const;
228   bool IsBodyTripCount(HInductionVarAnalysis::InductionInfo* trip) const;
229   bool IsUnsafeTripCount(HInductionVarAnalysis::InductionInfo* trip) const;
230   bool IsWellBehavedTripCount(HInductionVarAnalysis::InductionInfo* trip) const;
231 
232   Value GetLinear(HInductionVarAnalysis::InductionInfo* info,
233                   HInductionVarAnalysis::InductionInfo* trip,
234                   bool in_body,
235                   bool is_min) const;
236   Value GetPolynomial(HInductionVarAnalysis::InductionInfo* info,
237                       HInductionVarAnalysis::InductionInfo* trip,
238                       bool in_body,
239                       bool is_min) const;
240   Value GetGeometric(HInductionVarAnalysis::InductionInfo* info,
241                      HInductionVarAnalysis::InductionInfo* trip,
242                      bool in_body,
243                      bool is_min) const;
244   Value GetFetch(HInstruction* instruction,
245                  HInductionVarAnalysis::InductionInfo* trip,
246                  bool in_body,
247                  bool is_min) const;
248   Value GetVal(HInductionVarAnalysis::InductionInfo* info,
249                HInductionVarAnalysis::InductionInfo* trip,
250                bool in_body,
251                bool is_min) const;
252   Value GetMul(HInductionVarAnalysis::InductionInfo* info1,
253                HInductionVarAnalysis::InductionInfo* info2,
254                HInductionVarAnalysis::InductionInfo* trip,
255                bool in_body,
256                bool is_min) const;
257   Value GetDiv(HInductionVarAnalysis::InductionInfo* info1,
258                HInductionVarAnalysis::InductionInfo* info2,
259                HInductionVarAnalysis::InductionInfo* trip,
260                bool in_body,
261                bool is_min) const;
262   Value GetRem(HInductionVarAnalysis::InductionInfo* info1,
263                HInductionVarAnalysis::InductionInfo* info2) const;
264   Value GetXor(HInductionVarAnalysis::InductionInfo* info1,
265                HInductionVarAnalysis::InductionInfo* info2) const;
266 
267   Value MulRangeAndConstant(int64_t value,
268                             HInductionVarAnalysis::InductionInfo* info,
269                             HInductionVarAnalysis::InductionInfo* trip,
270                             bool in_body,
271                             bool is_min) const;
272   Value DivRangeAndConstant(int64_t value,
273                             HInductionVarAnalysis::InductionInfo* info,
274                             HInductionVarAnalysis::InductionInfo* trip,
275                             bool in_body,
276                             bool is_min) const;
277 
278   Value AddValue(Value v1, Value v2) const;
279   Value SubValue(Value v1, Value v2) const;
280   Value MulValue(Value v1, Value v2) const;
281   Value DivValue(Value v1, Value v2) const;
282   Value MergeVal(Value v1, Value v2, bool is_min) const;
283 
284   /**
285    * Generates code for lower/upper/taken-test or last value in the HIR. Returns true on
286    * success. With values nullptr, the method can be used to determine if code generation
287    * would be successful without generating actual code yet.
288    */
289   bool GenerateRangeOrLastValue(HInstruction* context,
290                                 HInstruction* instruction,
291                                 bool is_last_val,
292                                 HGraph* graph,
293                                 HBasicBlock* block,
294                                 /*out*/ HInstruction** lower,
295                                 /*out*/ HInstruction** upper,
296                                 /*out*/ HInstruction** taken_test,
297                                 /*out*/ int64_t* stride_value,
298                                 /*out*/ bool* needs_finite_test,
299                                 /*out*/ bool* needs_taken_test) const;
300 
301   bool GenerateLastValuePolynomial(HInductionVarAnalysis::InductionInfo* info,
302                                    HInductionVarAnalysis::InductionInfo* trip,
303                                    HGraph* graph,
304                                    HBasicBlock* block,
305                                    /*out*/HInstruction** result) const;
306 
307   bool GenerateLastValueGeometric(HInductionVarAnalysis::InductionInfo* info,
308                                   HInductionVarAnalysis::InductionInfo* trip,
309                                   HGraph* graph,
310                                   HBasicBlock* block,
311                                   /*out*/HInstruction** result) const;
312 
313   bool GenerateLastValueWrapAround(HInductionVarAnalysis::InductionInfo* info,
314                                    HInductionVarAnalysis::InductionInfo* trip,
315                                    HGraph* graph,
316                                    HBasicBlock* block,
317                                    /*out*/HInstruction** result) const;
318 
319   bool GenerateLastValuePeriodic(HInductionVarAnalysis::InductionInfo* info,
320                                  HInductionVarAnalysis::InductionInfo* trip,
321                                  HGraph* graph,
322                                  HBasicBlock* block,
323                                  /*out*/HInstruction** result,
324                                  /*out*/ bool* needs_taken_test) const;
325 
326   bool GenerateCode(HInductionVarAnalysis::InductionInfo* info,
327                     HInductionVarAnalysis::InductionInfo* trip,
328                     HGraph* graph,
329                     HBasicBlock* block,
330                     /*out*/ HInstruction** result,
331                     bool in_body,
332                     bool is_min) const;
333 
334   void ReplaceInduction(HInductionVarAnalysis::InductionInfo* info,
335                         HInstruction* fetch,
336                         HInstruction* replacement);
337 
338   /** Results of prior induction variable analysis. */
339   HInductionVarAnalysis* induction_analysis_;
340 
341   /** Instruction at which chasing may stop. */
342   HInstruction* chase_hint_;
343 
344   friend class HInductionVarAnalysis;
345   friend class InductionVarRangeTest;
346 
347   DISALLOW_COPY_AND_ASSIGN(InductionVarRange);
348 };
349 
350 }  // namespace art
351 
352 #endif  // ART_COMPILER_OPTIMIZING_INDUCTION_VAR_RANGE_H_
353