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 #include "induction_var_range.h"
18 
19 #include <limits>
20 
21 namespace art {
22 
23 /** Returns true if 64-bit constant fits in 32-bit constant. */
CanLongValueFitIntoInt(int64_t c)24 static bool CanLongValueFitIntoInt(int64_t c) {
25   return std::numeric_limits<int32_t>::min() <= c && c <= std::numeric_limits<int32_t>::max();
26 }
27 
28 /** Returns true if 32-bit addition can be done safely. */
IsSafeAdd(int32_t c1,int32_t c2)29 static bool IsSafeAdd(int32_t c1, int32_t c2) {
30   return CanLongValueFitIntoInt(static_cast<int64_t>(c1) + static_cast<int64_t>(c2));
31 }
32 
33 /** Returns true if 32-bit subtraction can be done safely. */
IsSafeSub(int32_t c1,int32_t c2)34 static bool IsSafeSub(int32_t c1, int32_t c2) {
35   return CanLongValueFitIntoInt(static_cast<int64_t>(c1) - static_cast<int64_t>(c2));
36 }
37 
38 /** Returns true if 32-bit multiplication can be done safely. */
IsSafeMul(int32_t c1,int32_t c2)39 static bool IsSafeMul(int32_t c1, int32_t c2) {
40   return CanLongValueFitIntoInt(static_cast<int64_t>(c1) * static_cast<int64_t>(c2));
41 }
42 
43 /** Returns true if 32-bit division can be done safely. */
IsSafeDiv(int32_t c1,int32_t c2)44 static bool IsSafeDiv(int32_t c1, int32_t c2) {
45   return c2 != 0 && CanLongValueFitIntoInt(static_cast<int64_t>(c1) / static_cast<int64_t>(c2));
46 }
47 
48 /** Computes a * b for a,b > 0 (at least until first overflow happens). */
SafeMul(int64_t a,int64_t b,bool * overflow)49 static int64_t SafeMul(int64_t a, int64_t b, /*out*/ bool* overflow) {
50   if (a > 0 && b > 0 && a > (std::numeric_limits<int64_t>::max() / b)) {
51     *overflow = true;
52   }
53   return a * b;
54 }
55 
56 /** Returns b^e for b,e > 0. Sets overflow if arithmetic wrap-around occurred. */
IntPow(int64_t b,int64_t e,bool * overflow)57 static int64_t IntPow(int64_t b, int64_t e, /*out*/ bool* overflow) {
58   DCHECK_LT(0, b);
59   DCHECK_LT(0, e);
60   int64_t pow = 1;
61   while (e) {
62     if (e & 1) {
63       pow = SafeMul(pow, b, overflow);
64     }
65     e >>= 1;
66     if (e) {
67       b = SafeMul(b, b, overflow);
68     }
69   }
70   return pow;
71 }
72 
73 /** Hunts "under the hood" for a suitable instruction at the hint. */
IsMaxAtHint(HInstruction * instruction,HInstruction * hint,HInstruction ** suitable)74 static bool IsMaxAtHint(
75     HInstruction* instruction, HInstruction* hint, /*out*/HInstruction** suitable) {
76   if (instruction->IsMin()) {
77     // For MIN(x, y), return most suitable x or y as maximum.
78     return IsMaxAtHint(instruction->InputAt(0), hint, suitable) ||
79            IsMaxAtHint(instruction->InputAt(1), hint, suitable);
80   } else {
81     *suitable = instruction;
82     return HuntForDeclaration(instruction) == hint;
83   }
84 }
85 
86 /** Post-analysis simplification of a minimum value that makes the bound more useful to clients. */
SimplifyMin(InductionVarRange::Value v)87 static InductionVarRange::Value SimplifyMin(InductionVarRange::Value v) {
88   if (v.is_known && v.a_constant == 1 && v.b_constant <= 0) {
89     // If a == 1,  instruction >= 0 and b <= 0, just return the constant b.
90     // No arithmetic wrap-around can occur.
91     if (IsGEZero(v.instruction)) {
92       return InductionVarRange::Value(v.b_constant);
93     }
94   }
95   return v;
96 }
97 
98 /** Post-analysis simplification of a maximum value that makes the bound more useful to clients. */
SimplifyMax(InductionVarRange::Value v,HInstruction * hint)99 static InductionVarRange::Value SimplifyMax(InductionVarRange::Value v, HInstruction* hint) {
100   if (v.is_known && v.a_constant >= 1) {
101     // An upper bound a * (length / a) + b, where a >= 1, can be conservatively rewritten as
102     // length + b because length >= 0 is true.
103     int64_t value;
104     if (v.instruction->IsDiv() &&
105         v.instruction->InputAt(0)->IsArrayLength() &&
106         IsInt64AndGet(v.instruction->InputAt(1), &value) && v.a_constant == value) {
107       return InductionVarRange::Value(v.instruction->InputAt(0), 1, v.b_constant);
108     }
109     // If a == 1, the most suitable one suffices as maximum value.
110     HInstruction* suitable = nullptr;
111     if (v.a_constant == 1 && IsMaxAtHint(v.instruction, hint, &suitable)) {
112       return InductionVarRange::Value(suitable, 1, v.b_constant);
113     }
114   }
115   return v;
116 }
117 
118 /** Tests for a constant value. */
IsConstantValue(InductionVarRange::Value v)119 static bool IsConstantValue(InductionVarRange::Value v) {
120   return v.is_known && v.a_constant == 0;
121 }
122 
123 /** Corrects a value for type to account for arithmetic wrap-around in lower precision. */
CorrectForType(InductionVarRange::Value v,DataType::Type type)124 static InductionVarRange::Value CorrectForType(InductionVarRange::Value v, DataType::Type type) {
125   switch (type) {
126     case DataType::Type::kUint8:
127     case DataType::Type::kInt8:
128     case DataType::Type::kUint16:
129     case DataType::Type::kInt16: {
130       // Constants within range only.
131       // TODO: maybe some room for improvement, like allowing widening conversions
132       int32_t min = DataType::MinValueOfIntegralType(type);
133       int32_t max = DataType::MaxValueOfIntegralType(type);
134       return (IsConstantValue(v) && min <= v.b_constant && v.b_constant <= max)
135           ? v
136           : InductionVarRange::Value();
137     }
138     default:
139       return v;
140   }
141 }
142 
143 /** Inserts an instruction. */
Insert(HBasicBlock * block,HInstruction * instruction)144 static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
145   DCHECK(block != nullptr);
146   DCHECK(block->GetLastInstruction() != nullptr) << block->GetBlockId();
147   DCHECK(instruction != nullptr);
148   block->InsertInstructionBefore(instruction, block->GetLastInstruction());
149   return instruction;
150 }
151 
152 /** Obtains loop's control instruction. */
GetLoopControl(HLoopInformation * loop)153 static HInstruction* GetLoopControl(HLoopInformation* loop) {
154   DCHECK(loop != nullptr);
155   return loop->GetHeader()->GetLastInstruction();
156 }
157 
158 //
159 // Public class methods.
160 //
161 
InductionVarRange(HInductionVarAnalysis * induction_analysis)162 InductionVarRange::InductionVarRange(HInductionVarAnalysis* induction_analysis)
163     : induction_analysis_(induction_analysis),
164       chase_hint_(nullptr) {
165   DCHECK(induction_analysis != nullptr);
166 }
167 
GetInductionRange(HInstruction * context,HInstruction * instruction,HInstruction * chase_hint,Value * min_val,Value * max_val,bool * needs_finite_test)168 bool InductionVarRange::GetInductionRange(HInstruction* context,
169                                           HInstruction* instruction,
170                                           HInstruction* chase_hint,
171                                           /*out*/Value* min_val,
172                                           /*out*/Value* max_val,
173                                           /*out*/bool* needs_finite_test) {
174   HLoopInformation* loop = nullptr;
175   HInductionVarAnalysis::InductionInfo* info = nullptr;
176   HInductionVarAnalysis::InductionInfo* trip = nullptr;
177   if (!HasInductionInfo(context, instruction, &loop, &info, &trip)) {
178     return false;
179   }
180   // Type int or lower (this is not too restrictive since intended clients, like
181   // bounds check elimination, will have truncated higher precision induction
182   // at their use point already).
183   switch (info->type) {
184     case DataType::Type::kUint8:
185     case DataType::Type::kInt8:
186     case DataType::Type::kUint16:
187     case DataType::Type::kInt16:
188     case DataType::Type::kInt32:
189       break;
190     default:
191       return false;
192   }
193   // Find range.
194   chase_hint_ = chase_hint;
195   bool in_body = context->GetBlock() != loop->GetHeader();
196   int64_t stride_value = 0;
197   *min_val = SimplifyMin(GetVal(info, trip, in_body, /* is_min= */ true));
198   *max_val = SimplifyMax(GetVal(info, trip, in_body, /* is_min= */ false), chase_hint);
199   *needs_finite_test = NeedsTripCount(info, &stride_value) && IsUnsafeTripCount(trip);
200   chase_hint_ = nullptr;
201   // Retry chasing constants for wrap-around (merge sensitive).
202   if (!min_val->is_known && info->induction_class == HInductionVarAnalysis::kWrapAround) {
203     *min_val = SimplifyMin(GetVal(info, trip, in_body, /* is_min= */ true));
204   }
205   return true;
206 }
207 
CanGenerateRange(HInstruction * context,HInstruction * instruction,bool * needs_finite_test,bool * needs_taken_test)208 bool InductionVarRange::CanGenerateRange(HInstruction* context,
209                                          HInstruction* instruction,
210                                          /*out*/bool* needs_finite_test,
211                                          /*out*/bool* needs_taken_test) {
212   bool is_last_value = false;
213   int64_t stride_value = 0;
214   return GenerateRangeOrLastValue(context,
215                                   instruction,
216                                   is_last_value,
217                                   nullptr,
218                                   nullptr,
219                                   nullptr,
220                                   nullptr,
221                                   nullptr,  // nothing generated yet
222                                   &stride_value,
223                                   needs_finite_test,
224                                   needs_taken_test)
225       && (stride_value == -1 ||
226           stride_value == 0 ||
227           stride_value == 1);  // avoid arithmetic wrap-around anomalies.
228 }
229 
GenerateRange(HInstruction * context,HInstruction * instruction,HGraph * graph,HBasicBlock * block,HInstruction ** lower,HInstruction ** upper)230 void InductionVarRange::GenerateRange(HInstruction* context,
231                                       HInstruction* instruction,
232                                       HGraph* graph,
233                                       HBasicBlock* block,
234                                       /*out*/HInstruction** lower,
235                                       /*out*/HInstruction** upper) {
236   bool is_last_value = false;
237   int64_t stride_value = 0;
238   bool b1, b2;  // unused
239   if (!GenerateRangeOrLastValue(context,
240                                 instruction,
241                                 is_last_value,
242                                 graph,
243                                 block,
244                                 lower,
245                                 upper,
246                                 nullptr,
247                                 &stride_value,
248                                 &b1,
249                                 &b2)) {
250     LOG(FATAL) << "Failed precondition: CanGenerateRange()";
251   }
252 }
253 
GenerateTakenTest(HInstruction * context,HGraph * graph,HBasicBlock * block)254 HInstruction* InductionVarRange::GenerateTakenTest(HInstruction* context,
255                                                    HGraph* graph,
256                                                    HBasicBlock* block) {
257   HInstruction* taken_test = nullptr;
258   bool is_last_value = false;
259   int64_t stride_value = 0;
260   bool b1, b2;  // unused
261   if (!GenerateRangeOrLastValue(context,
262                                 context,
263                                 is_last_value,
264                                 graph,
265                                 block,
266                                 nullptr,
267                                 nullptr,
268                                 &taken_test,
269                                 &stride_value,
270                                 &b1,
271                                 &b2)) {
272     LOG(FATAL) << "Failed precondition: CanGenerateRange()";
273   }
274   return taken_test;
275 }
276 
CanGenerateLastValue(HInstruction * instruction)277 bool InductionVarRange::CanGenerateLastValue(HInstruction* instruction) {
278   bool is_last_value = true;
279   int64_t stride_value = 0;
280   bool needs_finite_test = false;
281   bool needs_taken_test = false;
282   return GenerateRangeOrLastValue(instruction,
283                                   instruction,
284                                   is_last_value,
285                                   nullptr,
286                                   nullptr,
287                                   nullptr,
288                                   nullptr,
289                                   nullptr,  // nothing generated yet
290                                   &stride_value,
291                                   &needs_finite_test,
292                                   &needs_taken_test)
293       && !needs_finite_test && !needs_taken_test;
294 }
295 
GenerateLastValue(HInstruction * instruction,HGraph * graph,HBasicBlock * block)296 HInstruction* InductionVarRange::GenerateLastValue(HInstruction* instruction,
297                                                    HGraph* graph,
298                                                    HBasicBlock* block) {
299   HInstruction* last_value = nullptr;
300   bool is_last_value = true;
301   int64_t stride_value = 0;
302   bool b1, b2;  // unused
303   if (!GenerateRangeOrLastValue(instruction,
304                                 instruction,
305                                 is_last_value,
306                                 graph,
307                                 block,
308                                 &last_value,
309                                 &last_value,
310                                 nullptr,
311                                 &stride_value,
312                                 &b1,
313                                 &b2)) {
314     LOG(FATAL) << "Failed precondition: CanGenerateLastValue()";
315   }
316   return last_value;
317 }
318 
Replace(HInstruction * instruction,HInstruction * fetch,HInstruction * replacement)319 void InductionVarRange::Replace(HInstruction* instruction,
320                                 HInstruction* fetch,
321                                 HInstruction* replacement) {
322   for (HLoopInformation* lp = instruction->GetBlock()->GetLoopInformation();  // closest enveloping loop
323        lp != nullptr;
324        lp = lp->GetPreHeader()->GetLoopInformation()) {
325     // Update instruction's information.
326     ReplaceInduction(induction_analysis_->LookupInfo(lp, instruction), fetch, replacement);
327     // Update loop's trip-count information.
328     ReplaceInduction(induction_analysis_->LookupInfo(lp, GetLoopControl(lp)), fetch, replacement);
329   }
330 }
331 
IsFinite(HLoopInformation * loop,int64_t * trip_count) const332 bool InductionVarRange::IsFinite(HLoopInformation* loop, /*out*/ int64_t* trip_count) const {
333   bool is_constant_unused = false;
334   return CheckForFiniteAndConstantProps(loop, &is_constant_unused, trip_count);
335 }
336 
HasKnownTripCount(HLoopInformation * loop,int64_t * trip_count) const337 bool InductionVarRange::HasKnownTripCount(HLoopInformation* loop,
338                                           /*out*/ int64_t* trip_count) const {
339   bool is_constant = false;
340   CheckForFiniteAndConstantProps(loop, &is_constant, trip_count);
341   return is_constant;
342 }
343 
IsUnitStride(HInstruction * context,HInstruction * instruction,HGraph * graph,HInstruction ** offset) const344 bool InductionVarRange::IsUnitStride(HInstruction* context,
345                                      HInstruction* instruction,
346                                      HGraph* graph,
347                                      /*out*/ HInstruction** offset) const {
348   HLoopInformation* loop = nullptr;
349   HInductionVarAnalysis::InductionInfo* info = nullptr;
350   HInductionVarAnalysis::InductionInfo* trip = nullptr;
351   if (HasInductionInfo(context, instruction, &loop, &info, &trip)) {
352     if (info->induction_class == HInductionVarAnalysis::kLinear &&
353         !HInductionVarAnalysis::IsNarrowingLinear(info)) {
354       int64_t stride_value = 0;
355       if (IsConstant(info->op_a, kExact, &stride_value) && stride_value == 1) {
356         int64_t off_value = 0;
357         if (IsConstant(info->op_b, kExact, &off_value)) {
358           *offset = graph->GetConstant(info->op_b->type, off_value);
359         } else if (info->op_b->operation == HInductionVarAnalysis::kFetch) {
360           *offset = info->op_b->fetch;
361         } else {
362           return false;
363         }
364         return true;
365       }
366     }
367   }
368   return false;
369 }
370 
GenerateTripCount(HLoopInformation * loop,HGraph * graph,HBasicBlock * block)371 HInstruction* InductionVarRange::GenerateTripCount(HLoopInformation* loop,
372                                                    HGraph* graph,
373                                                    HBasicBlock* block) {
374   HInductionVarAnalysis::InductionInfo *trip =
375       induction_analysis_->LookupInfo(loop, GetLoopControl(loop));
376   if (trip != nullptr && !IsUnsafeTripCount(trip)) {
377     HInstruction* taken_test = nullptr;
378     HInstruction* trip_expr = nullptr;
379     if (IsBodyTripCount(trip)) {
380       if (!GenerateCode(trip->op_b, nullptr, graph, block, &taken_test, false, false)) {
381         return nullptr;
382       }
383     }
384     if (GenerateCode(trip->op_a, nullptr, graph, block, &trip_expr, false, false)) {
385       if (taken_test != nullptr) {
386         HInstruction* zero = graph->GetConstant(trip->type, 0);
387         ArenaAllocator* allocator = graph->GetAllocator();
388         trip_expr = Insert(block, new (allocator) HSelect(taken_test, trip_expr, zero, kNoDexPc));
389       }
390       return trip_expr;
391     }
392   }
393   return nullptr;
394 }
395 
396 //
397 // Private class methods.
398 //
399 
CheckForFiniteAndConstantProps(HLoopInformation * loop,bool * is_constant,int64_t * trip_count) const400 bool InductionVarRange::CheckForFiniteAndConstantProps(HLoopInformation* loop,
401                                                        /*out*/ bool* is_constant,
402                                                        /*out*/ int64_t* trip_count) const {
403   HInductionVarAnalysis::InductionInfo *trip =
404       induction_analysis_->LookupInfo(loop, GetLoopControl(loop));
405   if (trip != nullptr && !IsUnsafeTripCount(trip)) {
406     *is_constant = IsConstant(trip->op_a, kExact, trip_count);
407     return true;
408   }
409   return false;
410 }
411 
IsConstant(HInductionVarAnalysis::InductionInfo * info,ConstantRequest request,int64_t * value) const412 bool InductionVarRange::IsConstant(HInductionVarAnalysis::InductionInfo* info,
413                                    ConstantRequest request,
414                                    /*out*/ int64_t* value) const {
415   if (info != nullptr) {
416     // A direct 32-bit or 64-bit constant fetch. This immediately satisfies
417     // any of the three requests (kExact, kAtMost, and KAtLeast).
418     if (info->induction_class == HInductionVarAnalysis::kInvariant &&
419         info->operation == HInductionVarAnalysis::kFetch) {
420       if (IsInt64AndGet(info->fetch, value)) {
421         return true;
422       }
423     }
424     // Try range analysis on the invariant, only accept a proper range
425     // to avoid arithmetic wrap-around anomalies.
426     Value min_val = GetVal(info, nullptr, /* in_body= */ true, /* is_min= */ true);
427     Value max_val = GetVal(info, nullptr, /* in_body= */ true, /* is_min= */ false);
428     if (IsConstantValue(min_val) &&
429         IsConstantValue(max_val) && min_val.b_constant <= max_val.b_constant) {
430       if ((request == kExact && min_val.b_constant == max_val.b_constant) || request == kAtMost) {
431         *value = max_val.b_constant;
432         return true;
433       } else if (request == kAtLeast) {
434         *value = min_val.b_constant;
435         return true;
436       }
437     }
438   }
439   return false;
440 }
441 
HasInductionInfo(HInstruction * context,HInstruction * instruction,HLoopInformation ** loop,HInductionVarAnalysis::InductionInfo ** info,HInductionVarAnalysis::InductionInfo ** trip) const442 bool InductionVarRange::HasInductionInfo(
443     HInstruction* context,
444     HInstruction* instruction,
445     /*out*/ HLoopInformation** loop,
446     /*out*/ HInductionVarAnalysis::InductionInfo** info,
447     /*out*/ HInductionVarAnalysis::InductionInfo** trip) const {
448   DCHECK(context != nullptr);
449   DCHECK(context->GetBlock() != nullptr);
450   HLoopInformation* lp = context->GetBlock()->GetLoopInformation();  // closest enveloping loop
451   if (lp != nullptr) {
452     HInductionVarAnalysis::InductionInfo* i = induction_analysis_->LookupInfo(lp, instruction);
453     if (i != nullptr) {
454       *loop = lp;
455       *info = i;
456       *trip = induction_analysis_->LookupInfo(lp, GetLoopControl(lp));
457       return true;
458     }
459   }
460   return false;
461 }
462 
IsWellBehavedTripCount(HInductionVarAnalysis::InductionInfo * trip) const463 bool InductionVarRange::IsWellBehavedTripCount(HInductionVarAnalysis::InductionInfo* trip) const {
464   if (trip != nullptr) {
465     // Both bounds that define a trip-count are well-behaved if they either are not defined
466     // in any loop, or are contained in a proper interval. This allows finding the min/max
467     // of an expression by chasing outward.
468     InductionVarRange range(induction_analysis_);
469     HInductionVarAnalysis::InductionInfo* lower = trip->op_b->op_a;
470     HInductionVarAnalysis::InductionInfo* upper = trip->op_b->op_b;
471     int64_t not_used = 0;
472     return (!HasFetchInLoop(lower) || range.IsConstant(lower, kAtLeast, &not_used)) &&
473            (!HasFetchInLoop(upper) || range.IsConstant(upper, kAtLeast, &not_used));
474   }
475   return true;
476 }
477 
HasFetchInLoop(HInductionVarAnalysis::InductionInfo * info) const478 bool InductionVarRange::HasFetchInLoop(HInductionVarAnalysis::InductionInfo* info) const {
479   if (info != nullptr) {
480     if (info->induction_class == HInductionVarAnalysis::kInvariant &&
481         info->operation == HInductionVarAnalysis::kFetch) {
482       return info->fetch->GetBlock()->GetLoopInformation() != nullptr;
483     }
484     return HasFetchInLoop(info->op_a) || HasFetchInLoop(info->op_b);
485   }
486   return false;
487 }
488 
NeedsTripCount(HInductionVarAnalysis::InductionInfo * info,int64_t * stride_value) const489 bool InductionVarRange::NeedsTripCount(HInductionVarAnalysis::InductionInfo* info,
490                                        int64_t* stride_value) const {
491   if (info != nullptr) {
492     if (info->induction_class == HInductionVarAnalysis::kLinear) {
493       return IsConstant(info->op_a, kExact, stride_value);
494     } else if (info->induction_class == HInductionVarAnalysis::kPolynomial) {
495       return NeedsTripCount(info->op_a, stride_value);
496     } else if (info->induction_class == HInductionVarAnalysis::kWrapAround) {
497       return NeedsTripCount(info->op_b, stride_value);
498     }
499   }
500   return false;
501 }
502 
IsBodyTripCount(HInductionVarAnalysis::InductionInfo * trip) const503 bool InductionVarRange::IsBodyTripCount(HInductionVarAnalysis::InductionInfo* trip) const {
504   if (trip != nullptr) {
505     if (trip->induction_class == HInductionVarAnalysis::kInvariant) {
506       return trip->operation == HInductionVarAnalysis::kTripCountInBody ||
507              trip->operation == HInductionVarAnalysis::kTripCountInBodyUnsafe;
508     }
509   }
510   return false;
511 }
512 
IsUnsafeTripCount(HInductionVarAnalysis::InductionInfo * trip) const513 bool InductionVarRange::IsUnsafeTripCount(HInductionVarAnalysis::InductionInfo* trip) const {
514   if (trip != nullptr) {
515     if (trip->induction_class == HInductionVarAnalysis::kInvariant) {
516       return trip->operation == HInductionVarAnalysis::kTripCountInBodyUnsafe ||
517              trip->operation == HInductionVarAnalysis::kTripCountInLoopUnsafe;
518     }
519   }
520   return false;
521 }
522 
GetLinear(HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,bool in_body,bool is_min) const523 InductionVarRange::Value InductionVarRange::GetLinear(HInductionVarAnalysis::InductionInfo* info,
524                                                       HInductionVarAnalysis::InductionInfo* trip,
525                                                       bool in_body,
526                                                       bool is_min) const {
527   DCHECK(info != nullptr);
528   DCHECK_EQ(info->induction_class, HInductionVarAnalysis::kLinear);
529   // Detect common situation where an offset inside the trip-count cancels out during range
530   // analysis (finding max a * (TC - 1) + OFFSET for a == 1 and TC = UPPER - OFFSET or finding
531   // min a * (TC - 1) + OFFSET for a == -1 and TC = OFFSET - UPPER) to avoid losing information
532   // with intermediate results that only incorporate single instructions.
533   if (trip != nullptr) {
534     HInductionVarAnalysis::InductionInfo* trip_expr = trip->op_a;
535     if (trip_expr->type == info->type && trip_expr->operation == HInductionVarAnalysis::kSub) {
536       int64_t stride_value = 0;
537       if (IsConstant(info->op_a, kExact, &stride_value)) {
538         if (!is_min && stride_value == 1) {
539           // Test original trip's negative operand (trip_expr->op_b) against offset of induction.
540           if (HInductionVarAnalysis::InductionEqual(trip_expr->op_b, info->op_b)) {
541             // Analyze cancelled trip with just the positive operand (trip_expr->op_a).
542             HInductionVarAnalysis::InductionInfo cancelled_trip(
543                 trip->induction_class,
544                 trip->operation,
545                 trip_expr->op_a,
546                 trip->op_b,
547                 nullptr,
548                 trip->type);
549             return GetVal(&cancelled_trip, trip, in_body, is_min);
550           }
551         } else if (is_min && stride_value == -1) {
552           // Test original trip's positive operand (trip_expr->op_a) against offset of induction.
553           if (HInductionVarAnalysis::InductionEqual(trip_expr->op_a, info->op_b)) {
554             // Analyze cancelled trip with just the negative operand (trip_expr->op_b).
555             HInductionVarAnalysis::InductionInfo neg(
556                 HInductionVarAnalysis::kInvariant,
557                 HInductionVarAnalysis::kNeg,
558                 nullptr,
559                 trip_expr->op_b,
560                 nullptr,
561                 trip->type);
562             HInductionVarAnalysis::InductionInfo cancelled_trip(
563                 trip->induction_class, trip->operation, &neg, trip->op_b, nullptr, trip->type);
564             return SubValue(Value(0), GetVal(&cancelled_trip, trip, in_body, !is_min));
565           }
566         }
567       }
568     }
569   }
570   // General rule of linear induction a * i + b, for normalized 0 <= i < TC.
571   return AddValue(GetMul(info->op_a, trip, trip, in_body, is_min),
572                   GetVal(info->op_b, trip, in_body, is_min));
573 }
574 
GetPolynomial(HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,bool in_body,bool is_min) const575 InductionVarRange::Value InductionVarRange::GetPolynomial(HInductionVarAnalysis::InductionInfo* info,
576                                                           HInductionVarAnalysis::InductionInfo* trip,
577                                                           bool in_body,
578                                                           bool is_min) const {
579   DCHECK(info != nullptr);
580   DCHECK_EQ(info->induction_class, HInductionVarAnalysis::kPolynomial);
581   int64_t a = 0;
582   int64_t b = 0;
583   if (IsConstant(info->op_a->op_a, kExact, &a) && CanLongValueFitIntoInt(a) && a >= 0 &&
584       IsConstant(info->op_a->op_b, kExact, &b) && CanLongValueFitIntoInt(b) && b >= 0) {
585     // Evaluate bounds on sum_i=0^m-1(a * i + b) + c with a,b >= 0 for
586     // maximum index value m as a * (m * (m-1)) / 2 + b * m + c.
587     Value c = GetVal(info->op_b, trip, in_body, is_min);
588     if (is_min) {
589       return c;
590     } else {
591       Value m = GetVal(trip, trip, in_body, is_min);
592       Value t = DivValue(MulValue(m, SubValue(m, Value(1))), Value(2));
593       Value x = MulValue(Value(a), t);
594       Value y = MulValue(Value(b), m);
595       return AddValue(AddValue(x, y), c);
596     }
597   }
598   return Value();
599 }
600 
GetGeometric(HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,bool in_body,bool is_min) const601 InductionVarRange::Value InductionVarRange::GetGeometric(HInductionVarAnalysis::InductionInfo* info,
602                                                          HInductionVarAnalysis::InductionInfo* trip,
603                                                          bool in_body,
604                                                          bool is_min) const {
605   DCHECK(info != nullptr);
606   DCHECK_EQ(info->induction_class, HInductionVarAnalysis::kGeometric);
607   int64_t a = 0;
608   int64_t f = 0;
609   if (IsConstant(info->op_a, kExact, &a) &&
610       CanLongValueFitIntoInt(a) &&
611       IsInt64AndGet(info->fetch, &f) && f >= 1) {
612     // Conservative bounds on a * f^-i + b with f >= 1 can be computed without
613     // trip count. Other forms would require a much more elaborate evaluation.
614     const bool is_min_a = a >= 0 ? is_min : !is_min;
615     if (info->operation == HInductionVarAnalysis::kDiv) {
616       Value b = GetVal(info->op_b, trip, in_body, is_min);
617       return is_min_a ? b : AddValue(Value(a), b);
618     }
619   }
620   return Value();
621 }
622 
GetFetch(HInstruction * instruction,HInductionVarAnalysis::InductionInfo * trip,bool in_body,bool is_min) const623 InductionVarRange::Value InductionVarRange::GetFetch(HInstruction* instruction,
624                                                      HInductionVarAnalysis::InductionInfo* trip,
625                                                      bool in_body,
626                                                      bool is_min) const {
627   // Special case when chasing constants: single instruction that denotes trip count in the
628   // loop-body is minimal 1 and maximal, with safe trip-count, max int,
629   if (chase_hint_ == nullptr && in_body && trip != nullptr && instruction == trip->op_a->fetch) {
630     if (is_min) {
631       return Value(1);
632     } else if (!instruction->IsConstant() && !IsUnsafeTripCount(trip)) {
633       return Value(std::numeric_limits<int32_t>::max());
634     }
635   }
636   // Unless at a constant or hint, chase the instruction a bit deeper into the HIR tree, so that
637   // it becomes more likely range analysis will compare the same instructions as terminal nodes.
638   int64_t value;
639   if (IsInt64AndGet(instruction, &value) && CanLongValueFitIntoInt(value)) {
640     // Proper constant reveals best information.
641     return Value(static_cast<int32_t>(value));
642   } else if (instruction == chase_hint_) {
643     // At hint, fetch is represented by itself.
644     return Value(instruction, 1, 0);
645   } else if (instruction->IsAdd()) {
646     // Incorporate suitable constants in the chased value.
647     if (IsInt64AndGet(instruction->InputAt(0), &value) && CanLongValueFitIntoInt(value)) {
648       return AddValue(Value(static_cast<int32_t>(value)),
649                       GetFetch(instruction->InputAt(1), trip, in_body, is_min));
650     } else if (IsInt64AndGet(instruction->InputAt(1), &value) && CanLongValueFitIntoInt(value)) {
651       return AddValue(GetFetch(instruction->InputAt(0), trip, in_body, is_min),
652                       Value(static_cast<int32_t>(value)));
653     }
654   } else if (instruction->IsSub()) {
655     // Incorporate suitable constants in the chased value.
656     if (IsInt64AndGet(instruction->InputAt(0), &value) && CanLongValueFitIntoInt(value)) {
657       return SubValue(Value(static_cast<int32_t>(value)),
658                       GetFetch(instruction->InputAt(1), trip, in_body, !is_min));
659     } else if (IsInt64AndGet(instruction->InputAt(1), &value) && CanLongValueFitIntoInt(value)) {
660       return SubValue(GetFetch(instruction->InputAt(0), trip, in_body, is_min),
661                       Value(static_cast<int32_t>(value)));
662     }
663   } else if (instruction->IsArrayLength()) {
664     // Exploit length properties when chasing constants or chase into a new array declaration.
665     if (chase_hint_ == nullptr) {
666       return is_min ? Value(0) : Value(std::numeric_limits<int32_t>::max());
667     } else if (instruction->InputAt(0)->IsNewArray()) {
668       return GetFetch(instruction->InputAt(0)->AsNewArray()->GetLength(), trip, in_body, is_min);
669     }
670   } else if (instruction->IsTypeConversion()) {
671     // Since analysis is 32-bit (or narrower), chase beyond widening along the path.
672     // For example, this discovers the length in: for (long i = 0; i < a.length; i++);
673     if (instruction->AsTypeConversion()->GetInputType() == DataType::Type::kInt32 &&
674         instruction->AsTypeConversion()->GetResultType() == DataType::Type::kInt64) {
675       return GetFetch(instruction->InputAt(0), trip, in_body, is_min);
676     }
677   }
678   // Chase an invariant fetch that is defined by an outer loop if the trip-count used
679   // so far is well-behaved in both bounds and the next trip-count is safe.
680   // Example:
681   //   for (int i = 0; i <= 100; i++)  // safe
682   //     for (int j = 0; j <= i; j++)  // well-behaved
683   //       j is in range [0, i  ] (if i is chase hint)
684   //         or in range [0, 100] (otherwise)
685   HLoopInformation* next_loop = nullptr;
686   HInductionVarAnalysis::InductionInfo* next_info = nullptr;
687   HInductionVarAnalysis::InductionInfo* next_trip = nullptr;
688   bool next_in_body = true;  // inner loop is always in body of outer loop
689   if (HasInductionInfo(instruction, instruction, &next_loop, &next_info, &next_trip) &&
690       IsWellBehavedTripCount(trip) &&
691       !IsUnsafeTripCount(next_trip)) {
692     return GetVal(next_info, next_trip, next_in_body, is_min);
693   }
694   // Fetch is represented by itself.
695   return Value(instruction, 1, 0);
696 }
697 
GetVal(HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,bool in_body,bool is_min) const698 InductionVarRange::Value InductionVarRange::GetVal(HInductionVarAnalysis::InductionInfo* info,
699                                                    HInductionVarAnalysis::InductionInfo* trip,
700                                                    bool in_body,
701                                                    bool is_min) const {
702   if (info != nullptr) {
703     switch (info->induction_class) {
704       case HInductionVarAnalysis::kInvariant:
705         // Invariants.
706         switch (info->operation) {
707           case HInductionVarAnalysis::kAdd:
708             return AddValue(GetVal(info->op_a, trip, in_body, is_min),
709                             GetVal(info->op_b, trip, in_body, is_min));
710           case HInductionVarAnalysis::kSub:  // second reversed!
711             return SubValue(GetVal(info->op_a, trip, in_body, is_min),
712                             GetVal(info->op_b, trip, in_body, !is_min));
713           case HInductionVarAnalysis::kNeg:  // second reversed!
714             return SubValue(Value(0),
715                             GetVal(info->op_b, trip, in_body, !is_min));
716           case HInductionVarAnalysis::kMul:
717             return GetMul(info->op_a, info->op_b, trip, in_body, is_min);
718           case HInductionVarAnalysis::kDiv:
719             return GetDiv(info->op_a, info->op_b, trip, in_body, is_min);
720           case HInductionVarAnalysis::kRem:
721             return GetRem(info->op_a, info->op_b);
722           case HInductionVarAnalysis::kXor:
723             return GetXor(info->op_a, info->op_b);
724           case HInductionVarAnalysis::kFetch:
725             return GetFetch(info->fetch, trip, in_body, is_min);
726           case HInductionVarAnalysis::kTripCountInLoop:
727           case HInductionVarAnalysis::kTripCountInLoopUnsafe:
728             if (!in_body && !is_min) {  // one extra!
729               return GetVal(info->op_a, trip, in_body, is_min);
730             }
731             FALLTHROUGH_INTENDED;
732           case HInductionVarAnalysis::kTripCountInBody:
733           case HInductionVarAnalysis::kTripCountInBodyUnsafe:
734             if (is_min) {
735               return Value(0);
736             } else if (in_body) {
737               return SubValue(GetVal(info->op_a, trip, in_body, is_min), Value(1));
738             }
739             break;
740           default:
741             break;
742         }
743         break;
744       case HInductionVarAnalysis::kLinear:
745         return CorrectForType(GetLinear(info, trip, in_body, is_min), info->type);
746       case HInductionVarAnalysis::kPolynomial:
747         return GetPolynomial(info, trip, in_body, is_min);
748       case HInductionVarAnalysis::kGeometric:
749         return GetGeometric(info, trip, in_body, is_min);
750       case HInductionVarAnalysis::kWrapAround:
751       case HInductionVarAnalysis::kPeriodic:
752         return MergeVal(GetVal(info->op_a, trip, in_body, is_min),
753                         GetVal(info->op_b, trip, in_body, is_min), is_min);
754     }
755   }
756   return Value();
757 }
758 
GetMul(HInductionVarAnalysis::InductionInfo * info1,HInductionVarAnalysis::InductionInfo * info2,HInductionVarAnalysis::InductionInfo * trip,bool in_body,bool is_min) const759 InductionVarRange::Value InductionVarRange::GetMul(HInductionVarAnalysis::InductionInfo* info1,
760                                                    HInductionVarAnalysis::InductionInfo* info2,
761                                                    HInductionVarAnalysis::InductionInfo* trip,
762                                                    bool in_body,
763                                                    bool is_min) const {
764   // Constant times range.
765   int64_t value = 0;
766   if (IsConstant(info1, kExact, &value)) {
767     return MulRangeAndConstant(value, info2, trip, in_body, is_min);
768   } else if (IsConstant(info2, kExact, &value)) {
769     return MulRangeAndConstant(value, info1, trip, in_body, is_min);
770   }
771   // Interval ranges.
772   Value v1_min = GetVal(info1, trip, in_body, /* is_min= */ true);
773   Value v1_max = GetVal(info1, trip, in_body, /* is_min= */ false);
774   Value v2_min = GetVal(info2, trip, in_body, /* is_min= */ true);
775   Value v2_max = GetVal(info2, trip, in_body, /* is_min= */ false);
776   // Positive range vs. positive or negative range.
777   if (IsConstantValue(v1_min) && v1_min.b_constant >= 0) {
778     if (IsConstantValue(v2_min) && v2_min.b_constant >= 0) {
779       return is_min ? MulValue(v1_min, v2_min) : MulValue(v1_max, v2_max);
780     } else if (IsConstantValue(v2_max) && v2_max.b_constant <= 0) {
781       return is_min ? MulValue(v1_max, v2_min) : MulValue(v1_min, v2_max);
782     }
783   }
784   // Negative range vs. positive or negative range.
785   if (IsConstantValue(v1_max) && v1_max.b_constant <= 0) {
786     if (IsConstantValue(v2_min) && v2_min.b_constant >= 0) {
787       return is_min ? MulValue(v1_min, v2_max) : MulValue(v1_max, v2_min);
788     } else if (IsConstantValue(v2_max) && v2_max.b_constant <= 0) {
789       return is_min ? MulValue(v1_max, v2_max) : MulValue(v1_min, v2_min);
790     }
791   }
792   return Value();
793 }
794 
GetDiv(HInductionVarAnalysis::InductionInfo * info1,HInductionVarAnalysis::InductionInfo * info2,HInductionVarAnalysis::InductionInfo * trip,bool in_body,bool is_min) const795 InductionVarRange::Value InductionVarRange::GetDiv(HInductionVarAnalysis::InductionInfo* info1,
796                                                    HInductionVarAnalysis::InductionInfo* info2,
797                                                    HInductionVarAnalysis::InductionInfo* trip,
798                                                    bool in_body,
799                                                    bool is_min) const {
800   // Range divided by constant.
801   int64_t value = 0;
802   if (IsConstant(info2, kExact, &value)) {
803     return DivRangeAndConstant(value, info1, trip, in_body, is_min);
804   }
805   // Interval ranges.
806   Value v1_min = GetVal(info1, trip, in_body, /* is_min= */ true);
807   Value v1_max = GetVal(info1, trip, in_body, /* is_min= */ false);
808   Value v2_min = GetVal(info2, trip, in_body, /* is_min= */ true);
809   Value v2_max = GetVal(info2, trip, in_body, /* is_min= */ false);
810   // Positive range vs. positive or negative range.
811   if (IsConstantValue(v1_min) && v1_min.b_constant >= 0) {
812     if (IsConstantValue(v2_min) && v2_min.b_constant >= 0) {
813       return is_min ? DivValue(v1_min, v2_max) : DivValue(v1_max, v2_min);
814     } else if (IsConstantValue(v2_max) && v2_max.b_constant <= 0) {
815       return is_min ? DivValue(v1_max, v2_max) : DivValue(v1_min, v2_min);
816     }
817   }
818   // Negative range vs. positive or negative range.
819   if (IsConstantValue(v1_max) && v1_max.b_constant <= 0) {
820     if (IsConstantValue(v2_min) && v2_min.b_constant >= 0) {
821       return is_min ? DivValue(v1_min, v2_min) : DivValue(v1_max, v2_max);
822     } else if (IsConstantValue(v2_max) && v2_max.b_constant <= 0) {
823       return is_min ? DivValue(v1_max, v2_min) : DivValue(v1_min, v2_max);
824     }
825   }
826   return Value();
827 }
828 
GetRem(HInductionVarAnalysis::InductionInfo * info1,HInductionVarAnalysis::InductionInfo * info2) const829 InductionVarRange::Value InductionVarRange::GetRem(
830     HInductionVarAnalysis::InductionInfo* info1,
831     HInductionVarAnalysis::InductionInfo* info2) const {
832   int64_t v1 = 0;
833   int64_t v2 = 0;
834   // Only accept exact values.
835   if (IsConstant(info1, kExact, &v1) && IsConstant(info2, kExact, &v2) && v2 != 0) {
836     int64_t value = v1 % v2;
837     if (CanLongValueFitIntoInt(value)) {
838       return Value(static_cast<int32_t>(value));
839     }
840   }
841   return Value();
842 }
843 
GetXor(HInductionVarAnalysis::InductionInfo * info1,HInductionVarAnalysis::InductionInfo * info2) const844 InductionVarRange::Value InductionVarRange::GetXor(
845     HInductionVarAnalysis::InductionInfo* info1,
846     HInductionVarAnalysis::InductionInfo* info2) const {
847   int64_t v1 = 0;
848   int64_t v2 = 0;
849   // Only accept exact values.
850   if (IsConstant(info1, kExact, &v1) && IsConstant(info2, kExact, &v2)) {
851     int64_t value = v1 ^ v2;
852     if (CanLongValueFitIntoInt(value)) {
853       return Value(static_cast<int32_t>(value));
854     }
855   }
856   return Value();
857 }
858 
MulRangeAndConstant(int64_t value,HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,bool in_body,bool is_min) const859 InductionVarRange::Value InductionVarRange::MulRangeAndConstant(
860     int64_t value,
861     HInductionVarAnalysis::InductionInfo* info,
862     HInductionVarAnalysis::InductionInfo* trip,
863     bool in_body,
864     bool is_min) const {
865   if (CanLongValueFitIntoInt(value)) {
866     Value c(static_cast<int32_t>(value));
867     return MulValue(GetVal(info, trip, in_body, is_min == value >= 0), c);
868   }
869   return Value();
870 }
871 
DivRangeAndConstant(int64_t value,HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,bool in_body,bool is_min) const872 InductionVarRange::Value InductionVarRange::DivRangeAndConstant(
873     int64_t value,
874     HInductionVarAnalysis::InductionInfo* info,
875     HInductionVarAnalysis::InductionInfo* trip,
876     bool in_body,
877     bool is_min) const {
878   if (CanLongValueFitIntoInt(value)) {
879     Value c(static_cast<int32_t>(value));
880     return DivValue(GetVal(info, trip, in_body, is_min == value >= 0), c);
881   }
882   return Value();
883 }
884 
AddValue(Value v1,Value v2) const885 InductionVarRange::Value InductionVarRange::AddValue(Value v1, Value v2) const {
886   if (v1.is_known && v2.is_known && IsSafeAdd(v1.b_constant, v2.b_constant)) {
887     int32_t b = v1.b_constant + v2.b_constant;
888     if (v1.a_constant == 0) {
889       return Value(v2.instruction, v2.a_constant, b);
890     } else if (v2.a_constant == 0) {
891       return Value(v1.instruction, v1.a_constant, b);
892     } else if (v1.instruction == v2.instruction && IsSafeAdd(v1.a_constant, v2.a_constant)) {
893       return Value(v1.instruction, v1.a_constant + v2.a_constant, b);
894     }
895   }
896   return Value();
897 }
898 
SubValue(Value v1,Value v2) const899 InductionVarRange::Value InductionVarRange::SubValue(Value v1, Value v2) const {
900   if (v1.is_known && v2.is_known && IsSafeSub(v1.b_constant, v2.b_constant)) {
901     int32_t b = v1.b_constant - v2.b_constant;
902     if (v1.a_constant == 0 && IsSafeSub(0, v2.a_constant)) {
903       return Value(v2.instruction, -v2.a_constant, b);
904     } else if (v2.a_constant == 0) {
905       return Value(v1.instruction, v1.a_constant, b);
906     } else if (v1.instruction == v2.instruction && IsSafeSub(v1.a_constant, v2.a_constant)) {
907       return Value(v1.instruction, v1.a_constant - v2.a_constant, b);
908     }
909   }
910   return Value();
911 }
912 
MulValue(Value v1,Value v2) const913 InductionVarRange::Value InductionVarRange::MulValue(Value v1, Value v2) const {
914   if (v1.is_known && v2.is_known) {
915     if (v1.a_constant == 0) {
916       if (IsSafeMul(v1.b_constant, v2.a_constant) && IsSafeMul(v1.b_constant, v2.b_constant)) {
917         return Value(v2.instruction, v1.b_constant * v2.a_constant, v1.b_constant * v2.b_constant);
918       }
919     } else if (v2.a_constant == 0) {
920       if (IsSafeMul(v1.a_constant, v2.b_constant) && IsSafeMul(v1.b_constant, v2.b_constant)) {
921         return Value(v1.instruction, v1.a_constant * v2.b_constant, v1.b_constant * v2.b_constant);
922       }
923     }
924   }
925   return Value();
926 }
927 
DivValue(Value v1,Value v2) const928 InductionVarRange::Value InductionVarRange::DivValue(Value v1, Value v2) const {
929   if (v1.is_known && v2.is_known && v1.a_constant == 0 && v2.a_constant == 0) {
930     if (IsSafeDiv(v1.b_constant, v2.b_constant)) {
931       return Value(v1.b_constant / v2.b_constant);
932     }
933   }
934   return Value();
935 }
936 
MergeVal(Value v1,Value v2,bool is_min) const937 InductionVarRange::Value InductionVarRange::MergeVal(Value v1, Value v2, bool is_min) const {
938   if (v1.is_known && v2.is_known) {
939     if (v1.instruction == v2.instruction && v1.a_constant == v2.a_constant) {
940       return Value(v1.instruction, v1.a_constant,
941                    is_min ? std::min(v1.b_constant, v2.b_constant)
942                           : std::max(v1.b_constant, v2.b_constant));
943     }
944   }
945   return Value();
946 }
947 
GenerateRangeOrLastValue(HInstruction * context,HInstruction * instruction,bool is_last_value,HGraph * graph,HBasicBlock * block,HInstruction ** lower,HInstruction ** upper,HInstruction ** taken_test,int64_t * stride_value,bool * needs_finite_test,bool * needs_taken_test) const948 bool InductionVarRange::GenerateRangeOrLastValue(HInstruction* context,
949                                                  HInstruction* instruction,
950                                                  bool is_last_value,
951                                                  HGraph* graph,
952                                                  HBasicBlock* block,
953                                                  /*out*/HInstruction** lower,
954                                                  /*out*/HInstruction** upper,
955                                                  /*out*/HInstruction** taken_test,
956                                                  /*out*/int64_t* stride_value,
957                                                  /*out*/bool* needs_finite_test,
958                                                  /*out*/bool* needs_taken_test) const {
959   HLoopInformation* loop = nullptr;
960   HInductionVarAnalysis::InductionInfo* info = nullptr;
961   HInductionVarAnalysis::InductionInfo* trip = nullptr;
962   if (!HasInductionInfo(context, instruction, &loop, &info, &trip) || trip == nullptr) {
963     return false;  // codegen needs all information, including tripcount
964   }
965   // Determine what tests are needed. A finite test is needed if the evaluation code uses the
966   // trip-count and the loop maybe unsafe (because in such cases, the index could "overshoot"
967   // the computed range). A taken test is needed for any unknown trip-count, even if evaluation
968   // code does not use the trip-count explicitly (since there could be an implicit relation
969   // between e.g. an invariant subscript and a not-taken condition).
970   bool in_body = context->GetBlock() != loop->GetHeader();
971   *stride_value = 0;
972   *needs_finite_test = NeedsTripCount(info, stride_value) && IsUnsafeTripCount(trip);
973   *needs_taken_test = IsBodyTripCount(trip);
974   // Handle last value request.
975   if (is_last_value) {
976     DCHECK(!in_body);
977     switch (info->induction_class) {
978       case HInductionVarAnalysis::kLinear:
979         if (*stride_value > 0) {
980           lower = nullptr;
981         } else {
982           upper = nullptr;
983         }
984         break;
985       case HInductionVarAnalysis::kPolynomial:
986         return GenerateLastValuePolynomial(info, trip, graph, block, lower);
987       case HInductionVarAnalysis::kGeometric:
988         return GenerateLastValueGeometric(info, trip, graph, block, lower);
989       case HInductionVarAnalysis::kWrapAround:
990         return GenerateLastValueWrapAround(info, trip, graph, block, lower);
991       case HInductionVarAnalysis::kPeriodic:
992         return GenerateLastValuePeriodic(info, trip, graph, block, lower, needs_taken_test);
993       default:
994         return false;
995     }
996   }
997   // Code generation for taken test: generate the code when requested or otherwise analyze
998   // if code generation is feasible when taken test is needed.
999   if (taken_test != nullptr) {
1000     return GenerateCode(trip->op_b, nullptr, graph, block, taken_test, in_body, /* is_min= */ false);
1001   } else if (*needs_taken_test) {
1002     if (!GenerateCode(
1003         trip->op_b, nullptr, nullptr, nullptr, nullptr, in_body, /* is_min= */ false)) {
1004       return false;
1005     }
1006   }
1007   // Code generation for lower and upper.
1008   return
1009       // Success on lower if invariant (not set), or code can be generated.
1010       ((info->induction_class == HInductionVarAnalysis::kInvariant) ||
1011           GenerateCode(info, trip, graph, block, lower, in_body, /* is_min= */ true)) &&
1012       // And success on upper.
1013       GenerateCode(info, trip, graph, block, upper, in_body, /* is_min= */ false);
1014 }
1015 
GenerateLastValuePolynomial(HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,HGraph * graph,HBasicBlock * block,HInstruction ** result) const1016 bool InductionVarRange::GenerateLastValuePolynomial(HInductionVarAnalysis::InductionInfo* info,
1017                                                     HInductionVarAnalysis::InductionInfo* trip,
1018                                                     HGraph* graph,
1019                                                     HBasicBlock* block,
1020                                                     /*out*/HInstruction** result) const {
1021   DCHECK(info != nullptr);
1022   DCHECK_EQ(info->induction_class, HInductionVarAnalysis::kPolynomial);
1023   // Detect known coefficients and trip count (always taken).
1024   int64_t a = 0;
1025   int64_t b = 0;
1026   int64_t m = 0;
1027   if (IsConstant(info->op_a->op_a, kExact, &a) &&
1028       IsConstant(info->op_a->op_b, kExact, &b) &&
1029       IsConstant(trip->op_a, kExact, &m) && m >= 1) {
1030     // Evaluate bounds on sum_i=0^m-1(a * i + b) + c for known
1031     // maximum index value m as a * (m * (m-1)) / 2 + b * m + c.
1032     HInstruction* c = nullptr;
1033     if (GenerateCode(info->op_b, nullptr, graph, block, graph ? &c : nullptr, false, false)) {
1034       if (graph != nullptr) {
1035         DataType::Type type = info->type;
1036         int64_t sum = a * ((m * (m - 1)) / 2) + b * m;
1037         if (type != DataType::Type::kInt64) {
1038           sum = static_cast<int32_t>(sum);  // okay to truncate
1039         }
1040         *result =
1041             Insert(block, new (graph->GetAllocator()) HAdd(type, graph->GetConstant(type, sum), c));
1042       }
1043       return true;
1044     }
1045   }
1046   return false;
1047 }
1048 
GenerateLastValueGeometric(HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,HGraph * graph,HBasicBlock * block,HInstruction ** result) const1049 bool InductionVarRange::GenerateLastValueGeometric(HInductionVarAnalysis::InductionInfo* info,
1050                                                    HInductionVarAnalysis::InductionInfo* trip,
1051                                                    HGraph* graph,
1052                                                    HBasicBlock* block,
1053                                                    /*out*/HInstruction** result) const {
1054   DCHECK(info != nullptr);
1055   DCHECK_EQ(info->induction_class, HInductionVarAnalysis::kGeometric);
1056   // Detect known base and trip count (always taken).
1057   int64_t f = 0;
1058   int64_t m = 0;
1059   if (IsInt64AndGet(info->fetch, &f) && f >= 1 && IsConstant(trip->op_a, kExact, &m) && m >= 1) {
1060     HInstruction* opa = nullptr;
1061     HInstruction* opb = nullptr;
1062     if (GenerateCode(info->op_a, nullptr, graph, block, &opa, false, false) &&
1063         GenerateCode(info->op_b, nullptr, graph, block, &opb, false, false)) {
1064       if (graph != nullptr) {
1065         DataType::Type type = info->type;
1066         // Compute f ^ m for known maximum index value m.
1067         bool overflow = false;
1068         int64_t fpow = IntPow(f, m, &overflow);
1069         if (info->operation == HInductionVarAnalysis::kDiv) {
1070           // For division, any overflow truncates to zero.
1071           if (overflow || (type != DataType::Type::kInt64 && !CanLongValueFitIntoInt(fpow))) {
1072             fpow = 0;
1073           }
1074         } else if (type != DataType::Type::kInt64) {
1075           // For multiplication, okay to truncate to required precision.
1076           DCHECK(info->operation == HInductionVarAnalysis::kMul);
1077           fpow = static_cast<int32_t>(fpow);
1078         }
1079         // Generate code.
1080         if (fpow == 0) {
1081           // Special case: repeated mul/div always yields zero.
1082           *result = graph->GetConstant(type, 0);
1083         } else {
1084           // Last value: a * f ^ m + b or a * f ^ -m + b.
1085           HInstruction* e = nullptr;
1086           ArenaAllocator* allocator = graph->GetAllocator();
1087           if (info->operation == HInductionVarAnalysis::kMul) {
1088             e = new (allocator) HMul(type, opa, graph->GetConstant(type, fpow));
1089           } else {
1090             e = new (allocator) HDiv(type, opa, graph->GetConstant(type, fpow), kNoDexPc);
1091           }
1092           *result = Insert(block, new (allocator) HAdd(type, Insert(block, e), opb));
1093         }
1094       }
1095       return true;
1096     }
1097   }
1098   return false;
1099 }
1100 
GenerateLastValueWrapAround(HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,HGraph * graph,HBasicBlock * block,HInstruction ** result) const1101 bool InductionVarRange::GenerateLastValueWrapAround(HInductionVarAnalysis::InductionInfo* info,
1102                                                     HInductionVarAnalysis::InductionInfo* trip,
1103                                                     HGraph* graph,
1104                                                     HBasicBlock* block,
1105                                                     /*out*/HInstruction** result) const {
1106   DCHECK(info != nullptr);
1107   DCHECK_EQ(info->induction_class, HInductionVarAnalysis::kWrapAround);
1108   // Count depth.
1109   int32_t depth = 0;
1110   for (; info->induction_class == HInductionVarAnalysis::kWrapAround;
1111        info = info->op_b, ++depth) {}
1112   // Handle wrap(x, wrap(.., y)) if trip count reaches an invariant at end.
1113   // TODO: generalize, but be careful to adjust the terminal.
1114   int64_t m = 0;
1115   if (info->induction_class == HInductionVarAnalysis::kInvariant &&
1116       IsConstant(trip->op_a, kExact, &m) && m >= depth) {
1117     return GenerateCode(info, nullptr, graph, block, result, false, false);
1118   }
1119   return false;
1120 }
1121 
GenerateLastValuePeriodic(HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,HGraph * graph,HBasicBlock * block,HInstruction ** result,bool * needs_taken_test) const1122 bool InductionVarRange::GenerateLastValuePeriodic(HInductionVarAnalysis::InductionInfo* info,
1123                                                   HInductionVarAnalysis::InductionInfo* trip,
1124                                                   HGraph* graph,
1125                                                   HBasicBlock* block,
1126                                                   /*out*/HInstruction** result,
1127                                                   /*out*/bool* needs_taken_test) const {
1128   DCHECK(info != nullptr);
1129   DCHECK_EQ(info->induction_class, HInductionVarAnalysis::kPeriodic);
1130   // Count period and detect all-invariants.
1131   int64_t period = 1;
1132   bool all_invariants = true;
1133   HInductionVarAnalysis::InductionInfo* p = info;
1134   for (; p->induction_class == HInductionVarAnalysis::kPeriodic; p = p->op_b, ++period) {
1135     DCHECK_EQ(p->op_a->induction_class, HInductionVarAnalysis::kInvariant);
1136     if (p->op_a->operation != HInductionVarAnalysis::kFetch) {
1137       all_invariants = false;
1138     }
1139   }
1140   DCHECK_EQ(p->induction_class, HInductionVarAnalysis::kInvariant);
1141   if (p->operation != HInductionVarAnalysis::kFetch) {
1142     all_invariants = false;
1143   }
1144   // Don't rely on FP arithmetic to be precise, unless the full period
1145   // consist of pre-computed expressions only.
1146   if (info->type == DataType::Type::kFloat32 || info->type == DataType::Type::kFloat64) {
1147     if (!all_invariants) {
1148       return false;
1149     }
1150   }
1151   // Handle any periodic(x, periodic(.., y)) for known maximum index value m.
1152   int64_t m = 0;
1153   if (IsConstant(trip->op_a, kExact, &m) && m >= 1) {
1154     int64_t li = m % period;
1155     for (int64_t i = 0; i < li; info = info->op_b, i++) {}
1156     if (info->induction_class == HInductionVarAnalysis::kPeriodic) {
1157       info = info->op_a;
1158     }
1159     return GenerateCode(info, nullptr, graph, block, result, false, false);
1160   }
1161   // Handle periodic(x, y) using even/odd-select on trip count. Enter trip count expression
1162   // directly to obtain the maximum index value t even if taken test is needed.
1163   HInstruction* x = nullptr;
1164   HInstruction* y = nullptr;
1165   HInstruction* t = nullptr;
1166   if (period == 2 &&
1167       GenerateCode(info->op_a, nullptr, graph, block, graph ? &x : nullptr, false, false) &&
1168       GenerateCode(info->op_b, nullptr, graph, block, graph ? &y : nullptr, false, false) &&
1169       GenerateCode(trip->op_a, nullptr, graph, block, graph ? &t : nullptr, false, false)) {
1170     // During actual code generation (graph != nullptr), generate is_even ? x : y.
1171     if (graph != nullptr) {
1172       DataType::Type type = trip->type;
1173       ArenaAllocator* allocator = graph->GetAllocator();
1174       HInstruction* msk =
1175           Insert(block, new (allocator) HAnd(type, t, graph->GetConstant(type, 1)));
1176       HInstruction* is_even =
1177           Insert(block, new (allocator) HEqual(msk, graph->GetConstant(type, 0), kNoDexPc));
1178       *result = Insert(block, new (graph->GetAllocator()) HSelect(is_even, x, y, kNoDexPc));
1179     }
1180     // Guard select with taken test if needed.
1181     if (*needs_taken_test) {
1182       HInstruction* is_taken = nullptr;
1183       if (GenerateCode(trip->op_b, nullptr, graph, block, graph ? &is_taken : nullptr, false, false)) {
1184         if (graph != nullptr) {
1185           ArenaAllocator* allocator = graph->GetAllocator();
1186           *result = Insert(block, new (allocator) HSelect(is_taken, *result, x, kNoDexPc));
1187         }
1188         *needs_taken_test = false;  // taken care of
1189       } else {
1190         return false;
1191       }
1192     }
1193     return true;
1194   }
1195   return false;
1196 }
1197 
GenerateCode(HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,HGraph * graph,HBasicBlock * block,HInstruction ** result,bool in_body,bool is_min) const1198 bool InductionVarRange::GenerateCode(HInductionVarAnalysis::InductionInfo* info,
1199                                      HInductionVarAnalysis::InductionInfo* trip,
1200                                      HGraph* graph,  // when set, code is generated
1201                                      HBasicBlock* block,
1202                                      /*out*/HInstruction** result,
1203                                      bool in_body,
1204                                      bool is_min) const {
1205   if (info != nullptr) {
1206     // If during codegen, the result is not needed (nullptr), simply return success.
1207     if (graph != nullptr && result == nullptr) {
1208       return true;
1209     }
1210     // Handle current operation.
1211     DataType::Type type = info->type;
1212     HInstruction* opa = nullptr;
1213     HInstruction* opb = nullptr;
1214     switch (info->induction_class) {
1215       case HInductionVarAnalysis::kInvariant:
1216         // Invariants (note that since invariants only have other invariants as
1217         // sub expressions, viz. no induction, there is no need to adjust is_min).
1218         switch (info->operation) {
1219           case HInductionVarAnalysis::kAdd:
1220           case HInductionVarAnalysis::kSub:
1221           case HInductionVarAnalysis::kMul:
1222           case HInductionVarAnalysis::kDiv:
1223           case HInductionVarAnalysis::kRem:
1224           case HInductionVarAnalysis::kXor:
1225           case HInductionVarAnalysis::kLT:
1226           case HInductionVarAnalysis::kLE:
1227           case HInductionVarAnalysis::kGT:
1228           case HInductionVarAnalysis::kGE:
1229             if (GenerateCode(info->op_a, trip, graph, block, &opa, in_body, is_min) &&
1230                 GenerateCode(info->op_b, trip, graph, block, &opb, in_body, is_min)) {
1231               if (graph != nullptr) {
1232                 HInstruction* operation = nullptr;
1233                 switch (info->operation) {
1234                   case HInductionVarAnalysis::kAdd:
1235                     operation = new (graph->GetAllocator()) HAdd(type, opa, opb); break;
1236                   case HInductionVarAnalysis::kSub:
1237                     operation = new (graph->GetAllocator()) HSub(type, opa, opb); break;
1238                   case HInductionVarAnalysis::kMul:
1239                     operation = new (graph->GetAllocator()) HMul(type, opa, opb, kNoDexPc); break;
1240                   case HInductionVarAnalysis::kDiv:
1241                     operation = new (graph->GetAllocator()) HDiv(type, opa, opb, kNoDexPc); break;
1242                   case HInductionVarAnalysis::kRem:
1243                     operation = new (graph->GetAllocator()) HRem(type, opa, opb, kNoDexPc); break;
1244                   case HInductionVarAnalysis::kXor:
1245                     operation = new (graph->GetAllocator()) HXor(type, opa, opb); break;
1246                   case HInductionVarAnalysis::kLT:
1247                     operation = new (graph->GetAllocator()) HLessThan(opa, opb); break;
1248                   case HInductionVarAnalysis::kLE:
1249                     operation = new (graph->GetAllocator()) HLessThanOrEqual(opa, opb); break;
1250                   case HInductionVarAnalysis::kGT:
1251                     operation = new (graph->GetAllocator()) HGreaterThan(opa, opb); break;
1252                   case HInductionVarAnalysis::kGE:
1253                     operation = new (graph->GetAllocator()) HGreaterThanOrEqual(opa, opb); break;
1254                   default:
1255                     LOG(FATAL) << "unknown operation";
1256                 }
1257                 *result = Insert(block, operation);
1258               }
1259               return true;
1260             }
1261             break;
1262           case HInductionVarAnalysis::kNeg:
1263             if (GenerateCode(info->op_b, trip, graph, block, &opb, in_body, !is_min)) {
1264               if (graph != nullptr) {
1265                 *result = Insert(block, new (graph->GetAllocator()) HNeg(type, opb));
1266               }
1267               return true;
1268             }
1269             break;
1270           case HInductionVarAnalysis::kFetch:
1271             if (graph != nullptr) {
1272               *result = info->fetch;  // already in HIR
1273             }
1274             return true;
1275           case HInductionVarAnalysis::kTripCountInLoop:
1276           case HInductionVarAnalysis::kTripCountInLoopUnsafe:
1277             if (!in_body && !is_min) {  // one extra!
1278               return GenerateCode(info->op_a, trip, graph, block, result, in_body, is_min);
1279             }
1280             FALLTHROUGH_INTENDED;
1281           case HInductionVarAnalysis::kTripCountInBody:
1282           case HInductionVarAnalysis::kTripCountInBodyUnsafe:
1283             if (is_min) {
1284               if (graph != nullptr) {
1285                 *result = graph->GetConstant(type, 0);
1286               }
1287               return true;
1288             } else if (in_body) {
1289               if (GenerateCode(info->op_a, trip, graph, block, &opb, in_body, is_min)) {
1290                 if (graph != nullptr) {
1291                   ArenaAllocator* allocator = graph->GetAllocator();
1292                   *result =
1293                       Insert(block, new (allocator) HSub(type, opb, graph->GetConstant(type, 1)));
1294                 }
1295                 return true;
1296               }
1297             }
1298             break;
1299           case HInductionVarAnalysis::kNop:
1300             LOG(FATAL) << "unexpected invariant nop";
1301         }  // switch invariant operation
1302         break;
1303       case HInductionVarAnalysis::kLinear: {
1304         // Linear induction a * i + b, for normalized 0 <= i < TC. For ranges, this should
1305         // be restricted to a unit stride to avoid arithmetic wrap-around situations that
1306         // are harder to guard against. For a last value, requesting min/max based on any
1307         // known stride yields right value. Always avoid any narrowing linear induction or
1308         // any type mismatch between the linear induction and the trip count expression.
1309         // TODO: careful runtime type conversions could generalize this latter restriction.
1310         if (!HInductionVarAnalysis::IsNarrowingLinear(info) && trip->type == type) {
1311           int64_t stride_value = 0;
1312           if (IsConstant(info->op_a, kExact, &stride_value) &&
1313               CanLongValueFitIntoInt(stride_value)) {
1314             const bool is_min_a = stride_value >= 0 ? is_min : !is_min;
1315             if (GenerateCode(trip,       trip, graph, block, &opa, in_body, is_min_a) &&
1316                 GenerateCode(info->op_b, trip, graph, block, &opb, in_body, is_min)) {
1317               if (graph != nullptr) {
1318                 ArenaAllocator* allocator = graph->GetAllocator();
1319                 HInstruction* oper;
1320                 if (stride_value == 1) {
1321                   oper = new (allocator) HAdd(type, opa, opb);
1322                 } else if (stride_value == -1) {
1323                   oper = new (graph->GetAllocator()) HSub(type, opb, opa);
1324                 } else {
1325                   HInstruction* mul =
1326                       new (allocator) HMul(type, graph->GetConstant(type, stride_value), opa);
1327                   oper = new (allocator) HAdd(type, Insert(block, mul), opb);
1328                 }
1329                 *result = Insert(block, oper);
1330               }
1331               return true;
1332             }
1333           }
1334         }
1335         break;
1336       }
1337       case HInductionVarAnalysis::kPolynomial:
1338       case HInductionVarAnalysis::kGeometric:
1339         break;
1340       case HInductionVarAnalysis::kWrapAround:
1341       case HInductionVarAnalysis::kPeriodic: {
1342         // Wrap-around and periodic inductions are restricted to constants only, so that extreme
1343         // values are easy to test at runtime without complications of arithmetic wrap-around.
1344         Value extreme = GetVal(info, trip, in_body, is_min);
1345         if (IsConstantValue(extreme)) {
1346           if (graph != nullptr) {
1347             *result = graph->GetConstant(type, extreme.b_constant);
1348           }
1349           return true;
1350         }
1351         break;
1352       }
1353     }  // switch induction class
1354   }
1355   return false;
1356 }
1357 
ReplaceInduction(HInductionVarAnalysis::InductionInfo * info,HInstruction * fetch,HInstruction * replacement)1358 void InductionVarRange::ReplaceInduction(HInductionVarAnalysis::InductionInfo* info,
1359                                          HInstruction* fetch,
1360                                          HInstruction* replacement) {
1361   if (info != nullptr) {
1362     if (info->induction_class == HInductionVarAnalysis::kInvariant &&
1363         info->operation == HInductionVarAnalysis::kFetch &&
1364         info->fetch == fetch) {
1365       info->fetch = replacement;
1366     }
1367     ReplaceInduction(info->op_a, fetch, replacement);
1368     ReplaceInduction(info->op_b, fetch, replacement);
1369   }
1370 }
1371 
1372 }  // namespace art
1373