blob: eee6116098c47d73e9b73cc727ca7b8227ce1f59 [file] [log] [blame]
Mingyao Yangf384f882014-10-22 16:08:18 -07001/*
2 * Copyright (C) 2014 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 "bounds_check_elimination.h"
Aart Bikaab5b752015-09-23 11:18:57 -070018
19#include <limits>
20
21#include "base/arena_containers.h"
Aart Bik22af3be2015-09-10 12:50:58 -070022#include "induction_var_range.h"
Aart Bik4a342772015-11-30 10:17:46 -080023#include "side_effects_analysis.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070024#include "nodes.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070025
26namespace art {
27
28class MonotonicValueRange;
29
30/**
31 * A value bound is represented as a pair of value and constant,
32 * e.g. array.length - 1.
33 */
34class ValueBound : public ValueObject {
35 public:
Mingyao Yang0304e182015-01-30 16:41:29 -080036 ValueBound(HInstruction* instruction, int32_t constant) {
Mingyao Yang64197522014-12-05 15:56:23 -080037 if (instruction != nullptr && instruction->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -080038 // Normalize ValueBound with constant instruction.
39 int32_t instr_const = instruction->AsIntConstant()->GetValue();
Mingyao Yang8c8bad82015-02-09 18:13:26 -080040 if (!WouldAddOverflowOrUnderflow(instr_const, constant)) {
Mingyao Yang64197522014-12-05 15:56:23 -080041 instruction_ = nullptr;
42 constant_ = instr_const + constant;
43 return;
44 }
Mingyao Yangf384f882014-10-22 16:08:18 -070045 }
Mingyao Yang64197522014-12-05 15:56:23 -080046 instruction_ = instruction;
47 constant_ = constant;
48 }
49
Mingyao Yang8c8bad82015-02-09 18:13:26 -080050 // Return whether (left + right) overflows or underflows.
51 static bool WouldAddOverflowOrUnderflow(int32_t left, int32_t right) {
52 if (right == 0) {
53 return false;
54 }
Aart Bikaab5b752015-09-23 11:18:57 -070055 if ((right > 0) && (left <= (std::numeric_limits<int32_t>::max() - right))) {
Mingyao Yang8c8bad82015-02-09 18:13:26 -080056 // No overflow.
57 return false;
58 }
Aart Bikaab5b752015-09-23 11:18:57 -070059 if ((right < 0) && (left >= (std::numeric_limits<int32_t>::min() - right))) {
Mingyao Yang8c8bad82015-02-09 18:13:26 -080060 // No underflow.
61 return false;
62 }
63 return true;
64 }
65
Mingyao Yang0304e182015-01-30 16:41:29 -080066 static bool IsAddOrSubAConstant(HInstruction* instruction,
67 HInstruction** left_instruction,
68 int* right_constant) {
69 if (instruction->IsAdd() || instruction->IsSub()) {
70 HBinaryOperation* bin_op = instruction->AsBinaryOperation();
71 HInstruction* left = bin_op->GetLeft();
72 HInstruction* right = bin_op->GetRight();
73 if (right->IsIntConstant()) {
74 *left_instruction = left;
75 int32_t c = right->AsIntConstant()->GetValue();
76 *right_constant = instruction->IsAdd() ? c : -c;
77 return true;
78 }
79 }
80 *left_instruction = nullptr;
81 *right_constant = 0;
82 return false;
83 }
84
Mingyao Yang64197522014-12-05 15:56:23 -080085 // Try to detect useful value bound format from an instruction, e.g.
86 // a constant or array length related value.
87 static ValueBound DetectValueBoundFromValue(HInstruction* instruction, bool* found) {
88 DCHECK(instruction != nullptr);
Mingyao Yangf384f882014-10-22 16:08:18 -070089 if (instruction->IsIntConstant()) {
Mingyao Yang64197522014-12-05 15:56:23 -080090 *found = true;
91 return ValueBound(nullptr, instruction->AsIntConstant()->GetValue());
Mingyao Yangf384f882014-10-22 16:08:18 -070092 }
Mingyao Yang64197522014-12-05 15:56:23 -080093
94 if (instruction->IsArrayLength()) {
95 *found = true;
96 return ValueBound(instruction, 0);
97 }
98 // Try to detect (array.length + c) format.
Mingyao Yang0304e182015-01-30 16:41:29 -080099 HInstruction *left;
100 int32_t right;
101 if (IsAddOrSubAConstant(instruction, &left, &right)) {
102 if (left->IsArrayLength()) {
Mingyao Yang64197522014-12-05 15:56:23 -0800103 *found = true;
Mingyao Yang0304e182015-01-30 16:41:29 -0800104 return ValueBound(left, right);
Mingyao Yang64197522014-12-05 15:56:23 -0800105 }
106 }
107
108 // No useful bound detected.
109 *found = false;
110 return ValueBound::Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700111 }
112
113 HInstruction* GetInstruction() const { return instruction_; }
Mingyao Yang0304e182015-01-30 16:41:29 -0800114 int32_t GetConstant() const { return constant_; }
Mingyao Yangf384f882014-10-22 16:08:18 -0700115
Mingyao Yang0304e182015-01-30 16:41:29 -0800116 bool IsRelatedToArrayLength() const {
117 // Some bounds are created with HNewArray* as the instruction instead
118 // of HArrayLength*. They are treated the same.
119 return (instruction_ != nullptr) &&
120 (instruction_->IsArrayLength() || instruction_->IsNewArray());
Mingyao Yangf384f882014-10-22 16:08:18 -0700121 }
122
123 bool IsConstant() const {
124 return instruction_ == nullptr;
125 }
126
Aart Bikaab5b752015-09-23 11:18:57 -0700127 static ValueBound Min() { return ValueBound(nullptr, std::numeric_limits<int32_t>::min()); }
128 static ValueBound Max() { return ValueBound(nullptr, std::numeric_limits<int32_t>::max()); }
Mingyao Yangf384f882014-10-22 16:08:18 -0700129
130 bool Equals(ValueBound bound) const {
131 return instruction_ == bound.instruction_ && constant_ == bound.constant_;
132 }
133
Aart Bik22af3be2015-09-10 12:50:58 -0700134 /*
135 * Hunt "under the hood" of array lengths (leading to array references),
136 * null checks (also leading to array references), and new arrays
137 * (leading to the actual length). This makes it more likely related
138 * instructions become actually comparable.
139 */
140 static HInstruction* HuntForDeclaration(HInstruction* instruction) {
141 while (instruction->IsArrayLength() ||
142 instruction->IsNullCheck() ||
143 instruction->IsNewArray()) {
144 instruction = instruction->InputAt(0);
Mingyao Yang0304e182015-01-30 16:41:29 -0800145 }
146 return instruction;
147 }
148
149 static bool Equal(HInstruction* instruction1, HInstruction* instruction2) {
150 if (instruction1 == instruction2) {
151 return true;
152 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800153 if (instruction1 == nullptr || instruction2 == nullptr) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700154 return false;
155 }
Aart Bik22af3be2015-09-10 12:50:58 -0700156 instruction1 = HuntForDeclaration(instruction1);
157 instruction2 = HuntForDeclaration(instruction2);
Mingyao Yang0304e182015-01-30 16:41:29 -0800158 return instruction1 == instruction2;
159 }
160
161 // Returns if it's certain this->bound >= `bound`.
162 bool GreaterThanOrEqualTo(ValueBound bound) const {
163 if (Equal(instruction_, bound.instruction_)) {
164 return constant_ >= bound.constant_;
165 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700166 // Not comparable. Just return false.
167 return false;
168 }
169
Mingyao Yang0304e182015-01-30 16:41:29 -0800170 // Returns if it's certain this->bound <= `bound`.
171 bool LessThanOrEqualTo(ValueBound bound) const {
172 if (Equal(instruction_, bound.instruction_)) {
173 return constant_ <= bound.constant_;
Mingyao Yangf384f882014-10-22 16:08:18 -0700174 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700175 // Not comparable. Just return false.
176 return false;
177 }
178
Aart Bik4a342772015-11-30 10:17:46 -0800179 // Returns if it's certain this->bound > `bound`.
180 bool GreaterThan(ValueBound bound) const {
181 if (Equal(instruction_, bound.instruction_)) {
182 return constant_ > bound.constant_;
183 }
184 // Not comparable. Just return false.
185 return false;
186 }
187
188 // Returns if it's certain this->bound < `bound`.
189 bool LessThan(ValueBound bound) const {
190 if (Equal(instruction_, bound.instruction_)) {
191 return constant_ < bound.constant_;
192 }
193 // Not comparable. Just return false.
194 return false;
195 }
196
Mingyao Yangf384f882014-10-22 16:08:18 -0700197 // Try to narrow lower bound. Returns the greatest of the two if possible.
198 // Pick one if they are not comparable.
199 static ValueBound NarrowLowerBound(ValueBound bound1, ValueBound bound2) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800200 if (bound1.GreaterThanOrEqualTo(bound2)) {
201 return bound1;
202 }
203 if (bound2.GreaterThanOrEqualTo(bound1)) {
204 return bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700205 }
206
207 // Not comparable. Just pick one. We may lose some info, but that's ok.
208 // Favor constant as lower bound.
209 return bound1.IsConstant() ? bound1 : bound2;
210 }
211
212 // Try to narrow upper bound. Returns the lowest of the two if possible.
213 // Pick one if they are not comparable.
214 static ValueBound NarrowUpperBound(ValueBound bound1, ValueBound bound2) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800215 if (bound1.LessThanOrEqualTo(bound2)) {
216 return bound1;
217 }
218 if (bound2.LessThanOrEqualTo(bound1)) {
219 return bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700220 }
221
222 // Not comparable. Just pick one. We may lose some info, but that's ok.
223 // Favor array length as upper bound.
Mingyao Yang0304e182015-01-30 16:41:29 -0800224 return bound1.IsRelatedToArrayLength() ? bound1 : bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700225 }
226
Mingyao Yang0304e182015-01-30 16:41:29 -0800227 // Add a constant to a ValueBound.
228 // `overflow` or `underflow` will return whether the resulting bound may
229 // overflow or underflow an int.
230 ValueBound Add(int32_t c, bool* overflow, bool* underflow) const {
231 *overflow = *underflow = false;
Mingyao Yangf384f882014-10-22 16:08:18 -0700232 if (c == 0) {
233 return *this;
234 }
235
Mingyao Yang0304e182015-01-30 16:41:29 -0800236 int32_t new_constant;
Mingyao Yangf384f882014-10-22 16:08:18 -0700237 if (c > 0) {
Aart Bikaab5b752015-09-23 11:18:57 -0700238 if (constant_ > (std::numeric_limits<int32_t>::max() - c)) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800239 *overflow = true;
Mingyao Yang64197522014-12-05 15:56:23 -0800240 return Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700241 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800242
243 new_constant = constant_ + c;
244 // (array.length + non-positive-constant) won't overflow an int.
245 if (IsConstant() || (IsRelatedToArrayLength() && new_constant <= 0)) {
246 return ValueBound(instruction_, new_constant);
247 }
248 // Be conservative.
249 *overflow = true;
250 return Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700251 } else {
Aart Bikaab5b752015-09-23 11:18:57 -0700252 if (constant_ < (std::numeric_limits<int32_t>::min() - c)) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800253 *underflow = true;
254 return Min();
Mingyao Yangf384f882014-10-22 16:08:18 -0700255 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800256
257 new_constant = constant_ + c;
258 // Regardless of the value new_constant, (array.length+new_constant) will
259 // never underflow since array.length is no less than 0.
260 if (IsConstant() || IsRelatedToArrayLength()) {
261 return ValueBound(instruction_, new_constant);
262 }
263 // Be conservative.
264 *underflow = true;
265 return Min();
Mingyao Yangf384f882014-10-22 16:08:18 -0700266 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700267 }
268
269 private:
Mingyao Yangf384f882014-10-22 16:08:18 -0700270 HInstruction* instruction_;
Mingyao Yang0304e182015-01-30 16:41:29 -0800271 int32_t constant_;
Mingyao Yangf384f882014-10-22 16:08:18 -0700272};
273
274/**
275 * Represent a range of lower bound and upper bound, both being inclusive.
276 * Currently a ValueRange may be generated as a result of the following:
277 * comparisons related to array bounds, array bounds check, add/sub on top
Mingyao Yang0304e182015-01-30 16:41:29 -0800278 * of an existing value range, NewArray or a loop phi corresponding to an
Mingyao Yangf384f882014-10-22 16:08:18 -0700279 * incrementing/decrementing array index (MonotonicValueRange).
280 */
Vladimir Marko5233f932015-09-29 19:01:15 +0100281class ValueRange : public ArenaObject<kArenaAllocBoundsCheckElimination> {
Mingyao Yangf384f882014-10-22 16:08:18 -0700282 public:
283 ValueRange(ArenaAllocator* allocator, ValueBound lower, ValueBound upper)
284 : allocator_(allocator), lower_(lower), upper_(upper) {}
285
286 virtual ~ValueRange() {}
287
Mingyao Yang57e04752015-02-09 18:13:26 -0800288 virtual MonotonicValueRange* AsMonotonicValueRange() { return nullptr; }
289 bool IsMonotonicValueRange() {
Mingyao Yangf384f882014-10-22 16:08:18 -0700290 return AsMonotonicValueRange() != nullptr;
291 }
292
293 ArenaAllocator* GetAllocator() const { return allocator_; }
294 ValueBound GetLower() const { return lower_; }
295 ValueBound GetUpper() const { return upper_; }
296
Mingyao Yang3584bce2015-05-19 16:01:59 -0700297 bool IsConstantValueRange() { return lower_.IsConstant() && upper_.IsConstant(); }
298
Mingyao Yangf384f882014-10-22 16:08:18 -0700299 // If it's certain that this value range fits in other_range.
300 virtual bool FitsIn(ValueRange* other_range) const {
301 if (other_range == nullptr) {
302 return true;
303 }
304 DCHECK(!other_range->IsMonotonicValueRange());
Mingyao Yang0304e182015-01-30 16:41:29 -0800305 return lower_.GreaterThanOrEqualTo(other_range->lower_) &&
306 upper_.LessThanOrEqualTo(other_range->upper_);
Mingyao Yangf384f882014-10-22 16:08:18 -0700307 }
308
309 // Returns the intersection of this and range.
310 // If it's not possible to do intersection because some
311 // bounds are not comparable, it's ok to pick either bound.
312 virtual ValueRange* Narrow(ValueRange* range) {
313 if (range == nullptr) {
314 return this;
315 }
316
317 if (range->IsMonotonicValueRange()) {
318 return this;
319 }
320
321 return new (allocator_) ValueRange(
322 allocator_,
323 ValueBound::NarrowLowerBound(lower_, range->lower_),
324 ValueBound::NarrowUpperBound(upper_, range->upper_));
325 }
326
Mingyao Yang0304e182015-01-30 16:41:29 -0800327 // Shift a range by a constant.
328 ValueRange* Add(int32_t constant) const {
329 bool overflow, underflow;
330 ValueBound lower = lower_.Add(constant, &overflow, &underflow);
331 if (underflow) {
332 // Lower bound underflow will wrap around to positive values
333 // and invalidate the upper bound.
334 return nullptr;
Mingyao Yangf384f882014-10-22 16:08:18 -0700335 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800336 ValueBound upper = upper_.Add(constant, &overflow, &underflow);
337 if (overflow) {
338 // Upper bound overflow will wrap around to negative values
339 // and invalidate the lower bound.
340 return nullptr;
Mingyao Yangf384f882014-10-22 16:08:18 -0700341 }
342 return new (allocator_) ValueRange(allocator_, lower, upper);
343 }
344
Mingyao Yangf384f882014-10-22 16:08:18 -0700345 private:
346 ArenaAllocator* const allocator_;
347 const ValueBound lower_; // inclusive
348 const ValueBound upper_; // inclusive
349
350 DISALLOW_COPY_AND_ASSIGN(ValueRange);
351};
352
353/**
354 * A monotonically incrementing/decrementing value range, e.g.
355 * the variable i in "for (int i=0; i<array.length; i++)".
356 * Special care needs to be taken to account for overflow/underflow
357 * of such value ranges.
358 */
359class MonotonicValueRange : public ValueRange {
360 public:
Mingyao Yang64197522014-12-05 15:56:23 -0800361 MonotonicValueRange(ArenaAllocator* allocator,
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700362 HPhi* induction_variable,
Mingyao Yang64197522014-12-05 15:56:23 -0800363 HInstruction* initial,
Mingyao Yang0304e182015-01-30 16:41:29 -0800364 int32_t increment,
Mingyao Yang64197522014-12-05 15:56:23 -0800365 ValueBound bound)
Aart Bikaab5b752015-09-23 11:18:57 -0700366 // To be conservative, give it full range [Min(), Max()] in case it's
Mingyao Yang64197522014-12-05 15:56:23 -0800367 // used as a regular value range, due to possible overflow/underflow.
368 : ValueRange(allocator, ValueBound::Min(), ValueBound::Max()),
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700369 induction_variable_(induction_variable),
Mingyao Yang64197522014-12-05 15:56:23 -0800370 initial_(initial),
371 increment_(increment),
372 bound_(bound) {}
Mingyao Yangf384f882014-10-22 16:08:18 -0700373
374 virtual ~MonotonicValueRange() {}
375
Mingyao Yang57e04752015-02-09 18:13:26 -0800376 int32_t GetIncrement() const { return increment_; }
Mingyao Yang57e04752015-02-09 18:13:26 -0800377 ValueBound GetBound() const { return bound_; }
Mingyao Yang3584bce2015-05-19 16:01:59 -0700378 HBasicBlock* GetLoopHeader() const {
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700379 DCHECK(induction_variable_->GetBlock()->IsLoopHeader());
380 return induction_variable_->GetBlock();
381 }
Mingyao Yang57e04752015-02-09 18:13:26 -0800382
383 MonotonicValueRange* AsMonotonicValueRange() OVERRIDE { return this; }
Mingyao Yangf384f882014-10-22 16:08:18 -0700384
385 // If it's certain that this value range fits in other_range.
386 bool FitsIn(ValueRange* other_range) const OVERRIDE {
387 if (other_range == nullptr) {
388 return true;
389 }
390 DCHECK(!other_range->IsMonotonicValueRange());
391 return false;
392 }
393
394 // Try to narrow this MonotonicValueRange given another range.
395 // Ideally it will return a normal ValueRange. But due to
396 // possible overflow/underflow, that may not be possible.
397 ValueRange* Narrow(ValueRange* range) OVERRIDE {
398 if (range == nullptr) {
399 return this;
400 }
401 DCHECK(!range->IsMonotonicValueRange());
402
403 if (increment_ > 0) {
404 // Monotonically increasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800405 ValueBound lower = ValueBound::NarrowLowerBound(bound_, range->GetLower());
Aart Bikaab5b752015-09-23 11:18:57 -0700406 if (!lower.IsConstant() || lower.GetConstant() == std::numeric_limits<int32_t>::min()) {
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700407 // Lower bound isn't useful. Leave it to deoptimization.
408 return this;
409 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700410
Aart Bikaab5b752015-09-23 11:18:57 -0700411 // We currently conservatively assume max array length is Max().
412 // If we can make assumptions about the max array length, e.g. due to the max heap size,
Mingyao Yangf384f882014-10-22 16:08:18 -0700413 // divided by the element size (such as 4 bytes for each integer array), we can
414 // lower this number and rule out some possible overflows.
Aart Bikaab5b752015-09-23 11:18:57 -0700415 int32_t max_array_len = std::numeric_limits<int32_t>::max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700416
Mingyao Yang0304e182015-01-30 16:41:29 -0800417 // max possible integer value of range's upper value.
Aart Bikaab5b752015-09-23 11:18:57 -0700418 int32_t upper = std::numeric_limits<int32_t>::max();
Mingyao Yang0304e182015-01-30 16:41:29 -0800419 // Try to lower upper.
420 ValueBound upper_bound = range->GetUpper();
421 if (upper_bound.IsConstant()) {
422 upper = upper_bound.GetConstant();
423 } else if (upper_bound.IsRelatedToArrayLength() && upper_bound.GetConstant() <= 0) {
424 // Normal case. e.g. <= array.length - 1.
425 upper = max_array_len + upper_bound.GetConstant();
Mingyao Yangf384f882014-10-22 16:08:18 -0700426 }
427
428 // If we can prove for the last number in sequence of initial_,
429 // initial_ + increment_, initial_ + 2 x increment_, ...
430 // that's <= upper, (last_num_in_sequence + increment_) doesn't trigger overflow,
431 // then this MonoticValueRange is narrowed to a normal value range.
432
433 // Be conservative first, assume last number in the sequence hits upper.
Mingyao Yang0304e182015-01-30 16:41:29 -0800434 int32_t last_num_in_sequence = upper;
Mingyao Yangf384f882014-10-22 16:08:18 -0700435 if (initial_->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800436 int32_t initial_constant = initial_->AsIntConstant()->GetValue();
Mingyao Yangf384f882014-10-22 16:08:18 -0700437 if (upper <= initial_constant) {
438 last_num_in_sequence = upper;
439 } else {
Mingyao Yang0304e182015-01-30 16:41:29 -0800440 // Cast to int64_t for the substraction part to avoid int32_t overflow.
Mingyao Yangf384f882014-10-22 16:08:18 -0700441 last_num_in_sequence = initial_constant +
442 ((int64_t)upper - (int64_t)initial_constant) / increment_ * increment_;
443 }
444 }
Aart Bikaab5b752015-09-23 11:18:57 -0700445 if (last_num_in_sequence <= (std::numeric_limits<int32_t>::max() - increment_)) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700446 // No overflow. The sequence will be stopped by the upper bound test as expected.
447 return new (GetAllocator()) ValueRange(GetAllocator(), lower, range->GetUpper());
448 }
449
450 // There might be overflow. Give up narrowing.
451 return this;
452 } else {
453 DCHECK_NE(increment_, 0);
454 // Monotonically decreasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800455 ValueBound upper = ValueBound::NarrowUpperBound(bound_, range->GetUpper());
Aart Bikaab5b752015-09-23 11:18:57 -0700456 if ((!upper.IsConstant() || upper.GetConstant() == std::numeric_limits<int32_t>::max()) &&
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700457 !upper.IsRelatedToArrayLength()) {
458 // Upper bound isn't useful. Leave it to deoptimization.
459 return this;
460 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700461
462 // Need to take care of underflow. Try to prove underflow won't happen
Mingyao Yang0304e182015-01-30 16:41:29 -0800463 // for common cases.
Mingyao Yangf384f882014-10-22 16:08:18 -0700464 if (range->GetLower().IsConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800465 int32_t constant = range->GetLower().GetConstant();
Aart Bikaab5b752015-09-23 11:18:57 -0700466 if (constant >= (std::numeric_limits<int32_t>::min() - increment_)) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700467 return new (GetAllocator()) ValueRange(GetAllocator(), range->GetLower(), upper);
468 }
469 }
470
Mingyao Yang0304e182015-01-30 16:41:29 -0800471 // For non-constant lower bound, just assume might be underflow. Give up narrowing.
Mingyao Yangf384f882014-10-22 16:08:18 -0700472 return this;
473 }
474 }
475
476 private:
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700477 HPhi* const induction_variable_; // Induction variable for this monotonic value range.
478 HInstruction* const initial_; // Initial value.
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700479 const int32_t increment_; // Increment for each loop iteration.
480 const ValueBound bound_; // Additional value bound info for initial_.
Mingyao Yangf384f882014-10-22 16:08:18 -0700481
482 DISALLOW_COPY_AND_ASSIGN(MonotonicValueRange);
483};
484
485class BCEVisitor : public HGraphVisitor {
486 public:
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700487 // The least number of bounds checks that should be eliminated by triggering
488 // the deoptimization technique.
489 static constexpr size_t kThresholdForAddingDeoptimize = 2;
490
491 // Very large constant index is considered as an anomaly. This is a threshold
492 // beyond which we don't bother to apply the deoptimization technique since
493 // it's likely some AIOOBE will be thrown.
Aart Bikaab5b752015-09-23 11:18:57 -0700494 static constexpr int32_t kMaxConstantForAddingDeoptimize =
495 std::numeric_limits<int32_t>::max() - 1024 * 1024;
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700496
Mingyao Yang3584bce2015-05-19 16:01:59 -0700497 // Added blocks for loop body entry test.
498 bool IsAddedBlock(HBasicBlock* block) const {
499 return block->GetBlockId() >= initial_block_size_;
500 }
501
Aart Bik4a342772015-11-30 10:17:46 -0800502 BCEVisitor(HGraph* graph,
503 const SideEffectsAnalysis& side_effects,
504 HInductionVarAnalysis* induction_analysis)
Aart Bik22af3be2015-09-10 12:50:58 -0700505 : HGraphVisitor(graph),
Vladimir Marko5233f932015-09-29 19:01:15 +0100506 maps_(graph->GetBlocks().size(),
507 ArenaSafeMap<int, ValueRange*>(
508 std::less<int>(),
509 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
510 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
511 first_constant_index_bounds_check_map_(
512 std::less<int>(),
513 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
Aart Bik4a342772015-11-30 10:17:46 -0800514 early_exit_loop_(
515 std::less<uint32_t>(),
516 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
517 taken_test_loop_(
518 std::less<uint32_t>(),
519 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
520 finite_loop_(graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
Aart Bik22af3be2015-09-10 12:50:58 -0700521 need_to_revisit_block_(false),
Aart Bik4a342772015-11-30 10:17:46 -0800522 has_deoptimization_on_constant_subscripts_(false),
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100523 initial_block_size_(graph->GetBlocks().size()),
Aart Bik4a342772015-11-30 10:17:46 -0800524 side_effects_(side_effects),
Aart Bik22af3be2015-09-10 12:50:58 -0700525 induction_range_(induction_analysis) {}
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700526
527 void VisitBasicBlock(HBasicBlock* block) OVERRIDE {
Mingyao Yang3584bce2015-05-19 16:01:59 -0700528 DCHECK(!IsAddedBlock(block));
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700529 first_constant_index_bounds_check_map_.clear();
530 HGraphVisitor::VisitBasicBlock(block);
531 if (need_to_revisit_block_) {
532 AddComparesWithDeoptimization(block);
533 need_to_revisit_block_ = false;
534 first_constant_index_bounds_check_map_.clear();
535 GetValueRangeMap(block)->clear();
536 HGraphVisitor::VisitBasicBlock(block);
537 }
538 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700539
Aart Bik4a342772015-11-30 10:17:46 -0800540 void Finish() {
541 // Preserve SSA structure which may have been broken by adding one or more
542 // new taken-test structures (see TransformLoopForDeoptimizationIfNeeded()).
543 InsertPhiNodes();
544
545 // Clear the loop data structures.
546 early_exit_loop_.clear();
547 taken_test_loop_.clear();
548 finite_loop_.clear();
549 }
550
Mingyao Yangf384f882014-10-22 16:08:18 -0700551 private:
552 // Return the map of proven value ranges at the beginning of a basic block.
553 ArenaSafeMap<int, ValueRange*>* GetValueRangeMap(HBasicBlock* basic_block) {
Mingyao Yang3584bce2015-05-19 16:01:59 -0700554 if (IsAddedBlock(basic_block)) {
555 // Added blocks don't keep value ranges.
556 return nullptr;
557 }
Vladimir Marko5233f932015-09-29 19:01:15 +0100558 uint32_t block_id = basic_block->GetBlockId();
Vladimir Marko5233f932015-09-29 19:01:15 +0100559 return &maps_[block_id];
Mingyao Yangf384f882014-10-22 16:08:18 -0700560 }
561
562 // Traverse up the dominator tree to look for value range info.
563 ValueRange* LookupValueRange(HInstruction* instruction, HBasicBlock* basic_block) {
564 while (basic_block != nullptr) {
565 ArenaSafeMap<int, ValueRange*>* map = GetValueRangeMap(basic_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -0700566 if (map != nullptr) {
567 if (map->find(instruction->GetId()) != map->end()) {
568 return map->Get(instruction->GetId());
569 }
570 } else {
571 DCHECK(IsAddedBlock(basic_block));
Mingyao Yangf384f882014-10-22 16:08:18 -0700572 }
573 basic_block = basic_block->GetDominator();
574 }
575 // Didn't find any.
576 return nullptr;
577 }
578
Mingyao Yang0304e182015-01-30 16:41:29 -0800579 // Narrow the value range of `instruction` at the end of `basic_block` with `range`,
580 // and push the narrowed value range to `successor`.
Mingyao Yangf384f882014-10-22 16:08:18 -0700581 void ApplyRangeFromComparison(HInstruction* instruction, HBasicBlock* basic_block,
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800582 HBasicBlock* successor, ValueRange* range) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700583 ValueRange* existing_range = LookupValueRange(instruction, basic_block);
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800584 if (existing_range == nullptr) {
585 if (range != nullptr) {
586 GetValueRangeMap(successor)->Overwrite(instruction->GetId(), range);
587 }
588 return;
589 }
590 if (existing_range->IsMonotonicValueRange()) {
591 DCHECK(instruction->IsLoopHeaderPhi());
592 // Make sure the comparison is in the loop header so each increment is
593 // checked with a comparison.
594 if (instruction->GetBlock() != basic_block) {
595 return;
596 }
597 }
598 ValueRange* narrowed_range = existing_range->Narrow(range);
Nicolas Geoffraya09ff9c2015-06-24 10:38:27 +0100599 GetValueRangeMap(successor)->Overwrite(instruction->GetId(), narrowed_range);
Mingyao Yangf384f882014-10-22 16:08:18 -0700600 }
601
Mingyao Yang57e04752015-02-09 18:13:26 -0800602 // Special case that we may simultaneously narrow two MonotonicValueRange's to
603 // regular value ranges.
604 void HandleIfBetweenTwoMonotonicValueRanges(HIf* instruction,
605 HInstruction* left,
606 HInstruction* right,
607 IfCondition cond,
608 MonotonicValueRange* left_range,
609 MonotonicValueRange* right_range) {
610 DCHECK(left->IsLoopHeaderPhi());
611 DCHECK(right->IsLoopHeaderPhi());
612 if (instruction->GetBlock() != left->GetBlock()) {
613 // Comparison needs to be in loop header to make sure it's done after each
614 // increment/decrement.
615 return;
616 }
617
618 // Handle common cases which also don't have overflow/underflow concerns.
619 if (left_range->GetIncrement() == 1 &&
620 left_range->GetBound().IsConstant() &&
621 right_range->GetIncrement() == -1 &&
622 right_range->GetBound().IsRelatedToArrayLength() &&
623 right_range->GetBound().GetConstant() < 0) {
Mingyao Yang57e04752015-02-09 18:13:26 -0800624 HBasicBlock* successor = nullptr;
625 int32_t left_compensation = 0;
626 int32_t right_compensation = 0;
627 if (cond == kCondLT) {
628 left_compensation = -1;
629 right_compensation = 1;
630 successor = instruction->IfTrueSuccessor();
631 } else if (cond == kCondLE) {
632 successor = instruction->IfTrueSuccessor();
633 } else if (cond == kCondGT) {
634 successor = instruction->IfFalseSuccessor();
635 } else if (cond == kCondGE) {
636 left_compensation = -1;
637 right_compensation = 1;
638 successor = instruction->IfFalseSuccessor();
639 } else {
640 // We don't handle '=='/'!=' test in case left and right can cross and
641 // miss each other.
642 return;
643 }
644
645 if (successor != nullptr) {
646 bool overflow;
647 bool underflow;
648 ValueRange* new_left_range = new (GetGraph()->GetArena()) ValueRange(
649 GetGraph()->GetArena(),
650 left_range->GetBound(),
651 right_range->GetBound().Add(left_compensation, &overflow, &underflow));
652 if (!overflow && !underflow) {
653 ApplyRangeFromComparison(left, instruction->GetBlock(), successor,
654 new_left_range);
655 }
656
657 ValueRange* new_right_range = new (GetGraph()->GetArena()) ValueRange(
658 GetGraph()->GetArena(),
659 left_range->GetBound().Add(right_compensation, &overflow, &underflow),
660 right_range->GetBound());
661 if (!overflow && !underflow) {
662 ApplyRangeFromComparison(right, instruction->GetBlock(), successor,
663 new_right_range);
664 }
665 }
666 }
667 }
668
Mingyao Yangf384f882014-10-22 16:08:18 -0700669 // Handle "if (left cmp_cond right)".
670 void HandleIf(HIf* instruction, HInstruction* left, HInstruction* right, IfCondition cond) {
671 HBasicBlock* block = instruction->GetBlock();
672
673 HBasicBlock* true_successor = instruction->IfTrueSuccessor();
674 // There should be no critical edge at this point.
Vladimir Marko60584552015-09-03 13:35:12 +0000675 DCHECK_EQ(true_successor->GetPredecessors().size(), 1u);
Mingyao Yangf384f882014-10-22 16:08:18 -0700676
677 HBasicBlock* false_successor = instruction->IfFalseSuccessor();
678 // There should be no critical edge at this point.
Vladimir Marko60584552015-09-03 13:35:12 +0000679 DCHECK_EQ(false_successor->GetPredecessors().size(), 1u);
Mingyao Yangf384f882014-10-22 16:08:18 -0700680
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700681 ValueRange* left_range = LookupValueRange(left, block);
682 MonotonicValueRange* left_monotonic_range = nullptr;
683 if (left_range != nullptr) {
684 left_monotonic_range = left_range->AsMonotonicValueRange();
685 if (left_monotonic_range != nullptr) {
Mingyao Yang3584bce2015-05-19 16:01:59 -0700686 HBasicBlock* loop_head = left_monotonic_range->GetLoopHeader();
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700687 if (instruction->GetBlock() != loop_head) {
688 // For monotonic value range, don't handle `instruction`
689 // if it's not defined in the loop header.
690 return;
691 }
692 }
693 }
694
Mingyao Yang64197522014-12-05 15:56:23 -0800695 bool found;
696 ValueBound bound = ValueBound::DetectValueBoundFromValue(right, &found);
Mingyao Yang0304e182015-01-30 16:41:29 -0800697 // Each comparison can establish a lower bound and an upper bound
698 // for the left hand side.
Mingyao Yangf384f882014-10-22 16:08:18 -0700699 ValueBound lower = bound;
700 ValueBound upper = bound;
701 if (!found) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800702 // No constant or array.length+c format bound found.
Mingyao Yangf384f882014-10-22 16:08:18 -0700703 // For i<j, we can still use j's upper bound as i's upper bound. Same for lower.
Mingyao Yang57e04752015-02-09 18:13:26 -0800704 ValueRange* right_range = LookupValueRange(right, block);
705 if (right_range != nullptr) {
706 if (right_range->IsMonotonicValueRange()) {
Mingyao Yang57e04752015-02-09 18:13:26 -0800707 if (left_range != nullptr && left_range->IsMonotonicValueRange()) {
708 HandleIfBetweenTwoMonotonicValueRanges(instruction, left, right, cond,
709 left_range->AsMonotonicValueRange(),
710 right_range->AsMonotonicValueRange());
711 return;
712 }
713 }
714 lower = right_range->GetLower();
715 upper = right_range->GetUpper();
Mingyao Yangf384f882014-10-22 16:08:18 -0700716 } else {
717 lower = ValueBound::Min();
718 upper = ValueBound::Max();
719 }
720 }
721
Mingyao Yang0304e182015-01-30 16:41:29 -0800722 bool overflow, underflow;
Mingyao Yangf384f882014-10-22 16:08:18 -0700723 if (cond == kCondLT || cond == kCondLE) {
724 if (!upper.Equals(ValueBound::Max())) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800725 int32_t compensation = (cond == kCondLT) ? -1 : 0; // upper bound is inclusive
726 ValueBound new_upper = upper.Add(compensation, &overflow, &underflow);
727 if (overflow || underflow) {
728 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800729 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700730 ValueRange* new_range = new (GetGraph()->GetArena())
731 ValueRange(GetGraph()->GetArena(), ValueBound::Min(), new_upper);
732 ApplyRangeFromComparison(left, block, true_successor, new_range);
733 }
734
735 // array.length as a lower bound isn't considered useful.
Mingyao Yang0304e182015-01-30 16:41:29 -0800736 if (!lower.Equals(ValueBound::Min()) && !lower.IsRelatedToArrayLength()) {
737 int32_t compensation = (cond == kCondLE) ? 1 : 0; // lower bound is inclusive
738 ValueBound new_lower = lower.Add(compensation, &overflow, &underflow);
739 if (overflow || underflow) {
740 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800741 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700742 ValueRange* new_range = new (GetGraph()->GetArena())
743 ValueRange(GetGraph()->GetArena(), new_lower, ValueBound::Max());
744 ApplyRangeFromComparison(left, block, false_successor, new_range);
745 }
746 } else if (cond == kCondGT || cond == kCondGE) {
747 // array.length as a lower bound isn't considered useful.
Mingyao Yang0304e182015-01-30 16:41:29 -0800748 if (!lower.Equals(ValueBound::Min()) && !lower.IsRelatedToArrayLength()) {
749 int32_t compensation = (cond == kCondGT) ? 1 : 0; // lower bound is inclusive
750 ValueBound new_lower = lower.Add(compensation, &overflow, &underflow);
751 if (overflow || underflow) {
752 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800753 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700754 ValueRange* new_range = new (GetGraph()->GetArena())
755 ValueRange(GetGraph()->GetArena(), new_lower, ValueBound::Max());
756 ApplyRangeFromComparison(left, block, true_successor, new_range);
757 }
758
759 if (!upper.Equals(ValueBound::Max())) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800760 int32_t compensation = (cond == kCondGE) ? -1 : 0; // upper bound is inclusive
761 ValueBound new_upper = upper.Add(compensation, &overflow, &underflow);
762 if (overflow || underflow) {
763 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800764 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700765 ValueRange* new_range = new (GetGraph()->GetArena())
766 ValueRange(GetGraph()->GetArena(), ValueBound::Min(), new_upper);
767 ApplyRangeFromComparison(left, block, false_successor, new_range);
768 }
769 }
770 }
771
Aart Bik4a342772015-11-30 10:17:46 -0800772 void VisitBoundsCheck(HBoundsCheck* bounds_check) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700773 HBasicBlock* block = bounds_check->GetBlock();
774 HInstruction* index = bounds_check->InputAt(0);
775 HInstruction* array_length = bounds_check->InputAt(1);
Mingyao Yang3584bce2015-05-19 16:01:59 -0700776 DCHECK(array_length->IsIntConstant() ||
777 array_length->IsArrayLength() ||
778 array_length->IsPhi());
Aart Bik4a342772015-11-30 10:17:46 -0800779 bool try_dynamic_bce = true;
Mingyao Yangf384f882014-10-22 16:08:18 -0700780
Mingyao Yang0304e182015-01-30 16:41:29 -0800781 if (!index->IsIntConstant()) {
Aart Bik4a342772015-11-30 10:17:46 -0800782 // Non-constant subscript.
Aart Bik22af3be2015-09-10 12:50:58 -0700783 ValueBound lower = ValueBound(nullptr, 0); // constant 0
784 ValueBound upper = ValueBound(array_length, -1); // array_length - 1
785 ValueRange array_range(GetGraph()->GetArena(), lower, upper);
Aart Bik4a342772015-11-30 10:17:46 -0800786 // Try range obtained by dominator-based analysis.
Mingyao Yang0304e182015-01-30 16:41:29 -0800787 ValueRange* index_range = LookupValueRange(index, block);
Aart Bik22af3be2015-09-10 12:50:58 -0700788 if (index_range != nullptr && index_range->FitsIn(&array_range)) {
Aart Bik4a342772015-11-30 10:17:46 -0800789 ReplaceInstruction(bounds_check, index);
Aart Bik22af3be2015-09-10 12:50:58 -0700790 return;
791 }
792 // Try range obtained by induction variable analysis.
Aart Bik4a342772015-11-30 10:17:46 -0800793 // Disables dynamic bce if OOB is certain.
794 if (InductionRangeFitsIn(&array_range, bounds_check, index, &try_dynamic_bce)) {
795 ReplaceInstruction(bounds_check, index);
Aart Bik22af3be2015-09-10 12:50:58 -0700796 return;
Mingyao Yangf384f882014-10-22 16:08:18 -0700797 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800798 } else {
Aart Bik4a342772015-11-30 10:17:46 -0800799 // Constant subscript.
Mingyao Yang0304e182015-01-30 16:41:29 -0800800 int32_t constant = index->AsIntConstant()->GetValue();
801 if (constant < 0) {
802 // Will always throw exception.
803 return;
804 }
805 if (array_length->IsIntConstant()) {
806 if (constant < array_length->AsIntConstant()->GetValue()) {
Aart Bik4a342772015-11-30 10:17:46 -0800807 ReplaceInstruction(bounds_check, index);
Mingyao Yang0304e182015-01-30 16:41:29 -0800808 }
809 return;
810 }
811
812 DCHECK(array_length->IsArrayLength());
813 ValueRange* existing_range = LookupValueRange(array_length, block);
814 if (existing_range != nullptr) {
815 ValueBound lower = existing_range->GetLower();
816 DCHECK(lower.IsConstant());
817 if (constant < lower.GetConstant()) {
Aart Bik4a342772015-11-30 10:17:46 -0800818 ReplaceInstruction(bounds_check, index);
Mingyao Yang0304e182015-01-30 16:41:29 -0800819 return;
820 } else {
821 // Existing range isn't strong enough to eliminate the bounds check.
822 // Fall through to update the array_length range with info from this
823 // bounds check.
824 }
825 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700826
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700827 if (first_constant_index_bounds_check_map_.find(array_length->GetId()) ==
828 first_constant_index_bounds_check_map_.end()) {
829 // Remember the first bounds check against array_length of a constant index.
830 // That bounds check instruction has an associated HEnvironment where we
831 // may add an HDeoptimize to eliminate bounds checks of constant indices
832 // against array_length.
833 first_constant_index_bounds_check_map_.Put(array_length->GetId(), bounds_check);
834 } else {
835 // We've seen it at least twice. It's beneficial to introduce a compare with
836 // deoptimization fallback to eliminate the bounds checks.
837 need_to_revisit_block_ = true;
838 }
839
Mingyao Yangf384f882014-10-22 16:08:18 -0700840 // Once we have an array access like 'array[5] = 1', we record array.length >= 6.
Mingyao Yang0304e182015-01-30 16:41:29 -0800841 // We currently don't do it for non-constant index since a valid array[i] can't prove
842 // a valid array[i-1] yet due to the lower bound side.
Aart Bikaab5b752015-09-23 11:18:57 -0700843 if (constant == std::numeric_limits<int32_t>::max()) {
844 // Max() as an index will definitely throw AIOOBE.
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700845 return;
846 }
Mingyao Yang64197522014-12-05 15:56:23 -0800847 ValueBound lower = ValueBound(nullptr, constant + 1);
Mingyao Yangf384f882014-10-22 16:08:18 -0700848 ValueBound upper = ValueBound::Max();
849 ValueRange* range = new (GetGraph()->GetArena())
850 ValueRange(GetGraph()->GetArena(), lower, upper);
Mingyao Yang0304e182015-01-30 16:41:29 -0800851 GetValueRangeMap(block)->Overwrite(array_length->GetId(), range);
Mingyao Yangf384f882014-10-22 16:08:18 -0700852 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700853
Aart Bik4a342772015-11-30 10:17:46 -0800854 // If static analysis fails, and OOB is not certain, try dynamic elimination.
855 if (try_dynamic_bce) {
856 TryDynamicBCE(bounds_check);
857 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700858 }
859
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100860 static bool HasSameInputAtBackEdges(HPhi* phi) {
861 DCHECK(phi->IsLoopHeaderPhi());
862 // Start with input 1. Input 0 is from the incoming block.
863 HInstruction* input1 = phi->InputAt(1);
864 DCHECK(phi->GetBlock()->GetLoopInformation()->IsBackEdge(
Vladimir Markoec7802a2015-10-01 20:57:57 +0100865 *phi->GetBlock()->GetPredecessors()[1]));
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100866 for (size_t i = 2, e = phi->InputCount(); i < e; ++i) {
867 DCHECK(phi->GetBlock()->GetLoopInformation()->IsBackEdge(
Vladimir Markoec7802a2015-10-01 20:57:57 +0100868 *phi->GetBlock()->GetPredecessors()[i]));
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100869 if (input1 != phi->InputAt(i)) {
870 return false;
871 }
872 }
873 return true;
874 }
875
Aart Bik4a342772015-11-30 10:17:46 -0800876 void VisitPhi(HPhi* phi) OVERRIDE {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100877 if (phi->IsLoopHeaderPhi()
878 && (phi->GetType() == Primitive::kPrimInt)
879 && HasSameInputAtBackEdges(phi)) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700880 HInstruction* instruction = phi->InputAt(1);
Mingyao Yang0304e182015-01-30 16:41:29 -0800881 HInstruction *left;
882 int32_t increment;
883 if (ValueBound::IsAddOrSubAConstant(instruction, &left, &increment)) {
884 if (left == phi) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700885 HInstruction* initial_value = phi->InputAt(0);
886 ValueRange* range = nullptr;
Mingyao Yang64197522014-12-05 15:56:23 -0800887 if (increment == 0) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700888 // Add constant 0. It's really a fixed value.
889 range = new (GetGraph()->GetArena()) ValueRange(
890 GetGraph()->GetArena(),
Mingyao Yang64197522014-12-05 15:56:23 -0800891 ValueBound(initial_value, 0),
892 ValueBound(initial_value, 0));
Mingyao Yangf384f882014-10-22 16:08:18 -0700893 } else {
894 // Monotonically increasing/decreasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800895 bool found;
896 ValueBound bound = ValueBound::DetectValueBoundFromValue(
897 initial_value, &found);
898 if (!found) {
899 // No constant or array.length+c bound found.
900 // For i=j, we can still use j's upper bound as i's upper bound.
901 // Same for lower.
902 ValueRange* initial_range = LookupValueRange(initial_value, phi->GetBlock());
903 if (initial_range != nullptr) {
904 bound = increment > 0 ? initial_range->GetLower() :
905 initial_range->GetUpper();
906 } else {
907 bound = increment > 0 ? ValueBound::Min() : ValueBound::Max();
908 }
909 }
910 range = new (GetGraph()->GetArena()) MonotonicValueRange(
Mingyao Yangf384f882014-10-22 16:08:18 -0700911 GetGraph()->GetArena(),
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700912 phi,
Mingyao Yangf384f882014-10-22 16:08:18 -0700913 initial_value,
Mingyao Yang64197522014-12-05 15:56:23 -0800914 increment,
915 bound);
Mingyao Yangf384f882014-10-22 16:08:18 -0700916 }
917 GetValueRangeMap(phi->GetBlock())->Overwrite(phi->GetId(), range);
918 }
919 }
920 }
921 }
922
Aart Bik4a342772015-11-30 10:17:46 -0800923 void VisitIf(HIf* instruction) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700924 if (instruction->InputAt(0)->IsCondition()) {
925 HCondition* cond = instruction->InputAt(0)->AsCondition();
926 IfCondition cmp = cond->GetCondition();
927 if (cmp == kCondGT || cmp == kCondGE ||
928 cmp == kCondLT || cmp == kCondLE) {
929 HInstruction* left = cond->GetLeft();
930 HInstruction* right = cond->GetRight();
931 HandleIf(instruction, left, right, cmp);
932 }
933 }
934 }
935
Aart Bik4a342772015-11-30 10:17:46 -0800936 void VisitAdd(HAdd* add) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700937 HInstruction* right = add->GetRight();
938 if (right->IsIntConstant()) {
939 ValueRange* left_range = LookupValueRange(add->GetLeft(), add->GetBlock());
940 if (left_range == nullptr) {
941 return;
942 }
943 ValueRange* range = left_range->Add(right->AsIntConstant()->GetValue());
944 if (range != nullptr) {
945 GetValueRangeMap(add->GetBlock())->Overwrite(add->GetId(), range);
946 }
947 }
948 }
949
Aart Bik4a342772015-11-30 10:17:46 -0800950 void VisitSub(HSub* sub) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700951 HInstruction* left = sub->GetLeft();
952 HInstruction* right = sub->GetRight();
953 if (right->IsIntConstant()) {
954 ValueRange* left_range = LookupValueRange(left, sub->GetBlock());
955 if (left_range == nullptr) {
956 return;
957 }
958 ValueRange* range = left_range->Add(-right->AsIntConstant()->GetValue());
959 if (range != nullptr) {
960 GetValueRangeMap(sub->GetBlock())->Overwrite(sub->GetId(), range);
961 return;
962 }
963 }
964
965 // Here we are interested in the typical triangular case of nested loops,
966 // such as the inner loop 'for (int j=0; j<array.length-i; j++)' where i
967 // is the index for outer loop. In this case, we know j is bounded by array.length-1.
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800968
969 // Try to handle (array.length - i) or (array.length + c - i) format.
970 HInstruction* left_of_left; // left input of left.
971 int32_t right_const = 0;
972 if (ValueBound::IsAddOrSubAConstant(left, &left_of_left, &right_const)) {
973 left = left_of_left;
974 }
975 // The value of left input of the sub equals (left + right_const).
976
Mingyao Yangf384f882014-10-22 16:08:18 -0700977 if (left->IsArrayLength()) {
978 HInstruction* array_length = left->AsArrayLength();
979 ValueRange* right_range = LookupValueRange(right, sub->GetBlock());
980 if (right_range != nullptr) {
981 ValueBound lower = right_range->GetLower();
982 ValueBound upper = right_range->GetUpper();
Mingyao Yang0304e182015-01-30 16:41:29 -0800983 if (lower.IsConstant() && upper.IsRelatedToArrayLength()) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700984 HInstruction* upper_inst = upper.GetInstruction();
Mingyao Yang0304e182015-01-30 16:41:29 -0800985 // Make sure it's the same array.
986 if (ValueBound::Equal(array_length, upper_inst)) {
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800987 int32_t c0 = right_const;
988 int32_t c1 = lower.GetConstant();
989 int32_t c2 = upper.GetConstant();
990 // (array.length + c0 - v) where v is in [c1, array.length + c2]
991 // gets [c0 - c2, array.length + c0 - c1] as its value range.
992 if (!ValueBound::WouldAddOverflowOrUnderflow(c0, -c2) &&
993 !ValueBound::WouldAddOverflowOrUnderflow(c0, -c1)) {
994 if ((c0 - c1) <= 0) {
995 // array.length + (c0 - c1) won't overflow/underflow.
996 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
997 GetGraph()->GetArena(),
998 ValueBound(nullptr, right_const - upper.GetConstant()),
999 ValueBound(array_length, right_const - lower.GetConstant()));
1000 GetValueRangeMap(sub->GetBlock())->Overwrite(sub->GetId(), range);
1001 }
1002 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001003 }
1004 }
1005 }
1006 }
1007 }
1008
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001009 void FindAndHandlePartialArrayLength(HBinaryOperation* instruction) {
1010 DCHECK(instruction->IsDiv() || instruction->IsShr() || instruction->IsUShr());
1011 HInstruction* right = instruction->GetRight();
1012 int32_t right_const;
1013 if (right->IsIntConstant()) {
1014 right_const = right->AsIntConstant()->GetValue();
1015 // Detect division by two or more.
1016 if ((instruction->IsDiv() && right_const <= 1) ||
1017 (instruction->IsShr() && right_const < 1) ||
1018 (instruction->IsUShr() && right_const < 1)) {
1019 return;
1020 }
1021 } else {
1022 return;
1023 }
1024
1025 // Try to handle array.length/2 or (array.length-1)/2 format.
1026 HInstruction* left = instruction->GetLeft();
1027 HInstruction* left_of_left; // left input of left.
1028 int32_t c = 0;
1029 if (ValueBound::IsAddOrSubAConstant(left, &left_of_left, &c)) {
1030 left = left_of_left;
1031 }
1032 // The value of left input of instruction equals (left + c).
1033
1034 // (array_length + 1) or smaller divided by two or more
Aart Bikaab5b752015-09-23 11:18:57 -07001035 // always generate a value in [Min(), array_length].
1036 // This is true even if array_length is Max().
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001037 if (left->IsArrayLength() && c <= 1) {
1038 if (instruction->IsUShr() && c < 0) {
1039 // Make sure for unsigned shift, left side is not negative.
1040 // e.g. if array_length is 2, ((array_length - 3) >>> 2) is way bigger
1041 // than array_length.
1042 return;
1043 }
1044 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1045 GetGraph()->GetArena(),
Aart Bikaab5b752015-09-23 11:18:57 -07001046 ValueBound(nullptr, std::numeric_limits<int32_t>::min()),
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001047 ValueBound(left, 0));
1048 GetValueRangeMap(instruction->GetBlock())->Overwrite(instruction->GetId(), range);
1049 }
1050 }
1051
Aart Bik4a342772015-11-30 10:17:46 -08001052 void VisitDiv(HDiv* div) OVERRIDE {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001053 FindAndHandlePartialArrayLength(div);
1054 }
1055
Aart Bik4a342772015-11-30 10:17:46 -08001056 void VisitShr(HShr* shr) OVERRIDE {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001057 FindAndHandlePartialArrayLength(shr);
1058 }
1059
Aart Bik4a342772015-11-30 10:17:46 -08001060 void VisitUShr(HUShr* ushr) OVERRIDE {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001061 FindAndHandlePartialArrayLength(ushr);
1062 }
1063
Aart Bik4a342772015-11-30 10:17:46 -08001064 void VisitAnd(HAnd* instruction) OVERRIDE {
Mingyao Yang4559f002015-02-27 14:43:53 -08001065 if (instruction->GetRight()->IsIntConstant()) {
1066 int32_t constant = instruction->GetRight()->AsIntConstant()->GetValue();
1067 if (constant > 0) {
1068 // constant serves as a mask so any number masked with it
1069 // gets a [0, constant] value range.
1070 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1071 GetGraph()->GetArena(),
1072 ValueBound(nullptr, 0),
1073 ValueBound(nullptr, constant));
1074 GetValueRangeMap(instruction->GetBlock())->Overwrite(instruction->GetId(), range);
1075 }
1076 }
1077 }
1078
Aart Bik4a342772015-11-30 10:17:46 -08001079 void VisitNewArray(HNewArray* new_array) OVERRIDE {
Mingyao Yang0304e182015-01-30 16:41:29 -08001080 HInstruction* len = new_array->InputAt(0);
1081 if (!len->IsIntConstant()) {
1082 HInstruction *left;
1083 int32_t right_const;
1084 if (ValueBound::IsAddOrSubAConstant(len, &left, &right_const)) {
1085 // (left + right_const) is used as size to new the array.
1086 // We record "-right_const <= left <= new_array - right_const";
1087 ValueBound lower = ValueBound(nullptr, -right_const);
1088 // We use new_array for the bound instead of new_array.length,
1089 // which isn't available as an instruction yet. new_array will
1090 // be treated the same as new_array.length when it's used in a ValueBound.
1091 ValueBound upper = ValueBound(new_array, -right_const);
1092 ValueRange* range = new (GetGraph()->GetArena())
1093 ValueRange(GetGraph()->GetArena(), lower, upper);
Nicolas Geoffraya09ff9c2015-06-24 10:38:27 +01001094 ValueRange* existing_range = LookupValueRange(left, new_array->GetBlock());
1095 if (existing_range != nullptr) {
1096 range = existing_range->Narrow(range);
1097 }
Mingyao Yang0304e182015-01-30 16:41:29 -08001098 GetValueRangeMap(new_array->GetBlock())->Overwrite(left->GetId(), range);
1099 }
1100 }
1101 }
1102
Aart Bik4a342772015-11-30 10:17:46 -08001103 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE {
1104 if (!deoptimize->InputAt(0)->IsLessThanOrEqual()) {
1105 return;
1106 }
1107 // If this instruction was added by AddCompareWithDeoptimization(), narrow
1108 // the range accordingly in subsequent basic blocks.
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001109 HLessThanOrEqual* less_than_or_equal = deoptimize->InputAt(0)->AsLessThanOrEqual();
1110 HInstruction* instruction = less_than_or_equal->InputAt(0);
1111 if (instruction->IsArrayLength()) {
1112 HInstruction* constant = less_than_or_equal->InputAt(1);
1113 DCHECK(constant->IsIntConstant());
1114 DCHECK(constant->AsIntConstant()->GetValue() <= kMaxConstantForAddingDeoptimize);
1115 ValueBound lower = ValueBound(nullptr, constant->AsIntConstant()->GetValue() + 1);
1116 ValueRange* range = new (GetGraph()->GetArena())
1117 ValueRange(GetGraph()->GetArena(), lower, ValueBound::Max());
1118 GetValueRangeMap(deoptimize->GetBlock())->Overwrite(instruction->GetId(), range);
1119 }
1120 }
1121
Aart Bik4a342772015-11-30 10:17:46 -08001122 /**
1123 * After null/bounds checks are eliminated, some invariant array references
1124 * may be exposed underneath which can be hoisted out of the loop to the
1125 * preheader or, in combination with dynamic bce, the deoptimization block.
1126 *
1127 * for (int i = 0; i < n; i++) {
1128 * <-------+
1129 * for (int j = 0; j < n; j++) |
1130 * a[i][j] = 0; --a[i]--+
1131 * }
1132 *
1133 * Note: this optimization is no longer applied after deoptimization on array references
1134 * with constant subscripts has occurred (see AddCompareWithDeoptimization()), since in
1135 * those cases it would be unsafe to hoist array references across their deoptimization
1136 * instruction inside a loop.
1137 */
1138 void VisitArrayGet(HArrayGet* array_get) OVERRIDE {
1139 if (!has_deoptimization_on_constant_subscripts_ && array_get->IsInLoop()) {
1140 HLoopInformation* loop = array_get->GetBlock()->GetLoopInformation();
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001141 if (loop->IsDefinedOutOfTheLoop(array_get->InputAt(0)) &&
1142 loop->IsDefinedOutOfTheLoop(array_get->InputAt(1))) {
Aart Bik4a342772015-11-30 10:17:46 -08001143 SideEffects loop_effects = side_effects_.GetLoopEffects(loop->GetHeader());
1144 if (!array_get->GetSideEffects().MayDependOn(loop_effects)) {
Aart Bik55b14df2016-01-12 14:12:47 -08001145 HoistToPreHeaderOrDeoptBlock(loop, array_get);
Aart Bik4a342772015-11-30 10:17:46 -08001146 }
1147 }
1148 }
1149 }
1150
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001151 void AddCompareWithDeoptimization(HInstruction* array_length,
1152 HIntConstant* const_instr,
1153 HBasicBlock* block) {
1154 DCHECK(array_length->IsArrayLength());
1155 ValueRange* range = LookupValueRange(array_length, block);
1156 ValueBound lower_bound = range->GetLower();
1157 DCHECK(lower_bound.IsConstant());
1158 DCHECK(const_instr->GetValue() <= kMaxConstantForAddingDeoptimize);
Nicolas Geoffray8d82a0c2015-06-20 23:49:01 +01001159 // Note that the lower bound of the array length may have been refined
1160 // through other instructions (such as `HNewArray(length - 4)`).
1161 DCHECK_LE(const_instr->GetValue() + 1, lower_bound.GetConstant());
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001162
1163 // If array_length is less than lower_const, deoptimize.
1164 HBoundsCheck* bounds_check = first_constant_index_bounds_check_map_.Get(
1165 array_length->GetId())->AsBoundsCheck();
1166 HCondition* cond = new (GetGraph()->GetArena()) HLessThanOrEqual(array_length, const_instr);
1167 HDeoptimize* deoptimize = new (GetGraph()->GetArena())
1168 HDeoptimize(cond, bounds_check->GetDexPc());
1169 block->InsertInstructionBefore(cond, bounds_check);
1170 block->InsertInstructionBefore(deoptimize, bounds_check);
Nicolas Geoffray3dcd58c2015-04-03 11:02:38 +01001171 deoptimize->CopyEnvironmentFrom(bounds_check->GetEnvironment());
Aart Bik4a342772015-11-30 10:17:46 -08001172 // Flag that this kind of deoptimization on array references with constant
1173 // subscripts has occurred to prevent further hoisting of these references.
1174 has_deoptimization_on_constant_subscripts_ = true;
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001175 }
1176
1177 void AddComparesWithDeoptimization(HBasicBlock* block) {
1178 for (ArenaSafeMap<int, HBoundsCheck*>::iterator it =
1179 first_constant_index_bounds_check_map_.begin();
1180 it != first_constant_index_bounds_check_map_.end();
1181 ++it) {
1182 HBoundsCheck* bounds_check = it->second;
Nicolas Geoffray8df886b2015-06-24 14:57:44 +01001183 HInstruction* array_length = bounds_check->InputAt(1);
1184 if (!array_length->IsArrayLength()) {
1185 // Prior deoptimizations may have changed the array length to a phi.
1186 // TODO(mingyao): propagate the range to the phi?
1187 DCHECK(array_length->IsPhi()) << array_length->DebugName();
1188 continue;
1189 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001190 HIntConstant* lower_bound_const_instr = nullptr;
Aart Bikaab5b752015-09-23 11:18:57 -07001191 int32_t lower_bound_const = std::numeric_limits<int32_t>::min();
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001192 size_t counter = 0;
1193 // Count the constant indexing for which bounds checks haven't
1194 // been removed yet.
1195 for (HUseIterator<HInstruction*> it2(array_length->GetUses());
1196 !it2.Done();
1197 it2.Advance()) {
1198 HInstruction* user = it2.Current()->GetUser();
1199 if (user->GetBlock() == block &&
1200 user->IsBoundsCheck() &&
1201 user->AsBoundsCheck()->InputAt(0)->IsIntConstant()) {
1202 DCHECK_EQ(array_length, user->AsBoundsCheck()->InputAt(1));
1203 HIntConstant* const_instr = user->AsBoundsCheck()->InputAt(0)->AsIntConstant();
1204 if (const_instr->GetValue() > lower_bound_const) {
1205 lower_bound_const = const_instr->GetValue();
1206 lower_bound_const_instr = const_instr;
1207 }
1208 counter++;
1209 }
1210 }
1211 if (counter >= kThresholdForAddingDeoptimize &&
1212 lower_bound_const_instr->GetValue() <= kMaxConstantForAddingDeoptimize) {
1213 AddCompareWithDeoptimization(array_length, lower_bound_const_instr, block);
1214 }
1215 }
1216 }
1217
Aart Bik4a342772015-11-30 10:17:46 -08001218 /**
1219 * Returns true if static range analysis based on induction variables can determine the bounds
1220 * check on the given array range is always satisfied with the computed index range. The output
1221 * parameter try_dynamic_bce is set to false if OOB is certain.
1222 */
1223 bool InductionRangeFitsIn(ValueRange* array_range,
1224 HInstruction* context,
1225 HInstruction* index,
1226 bool* try_dynamic_bce) {
1227 InductionVarRange::Value v1;
1228 InductionVarRange::Value v2;
1229 bool needs_finite_test = false;
1230 induction_range_.GetInductionRange(context, index, &v1, &v2, &needs_finite_test);
Aart Bikb738d4f2015-12-03 11:23:35 -08001231 do {
1232 if (v1.is_known && (v1.a_constant == 0 || v1.a_constant == 1) &&
1233 v2.is_known && (v2.a_constant == 0 || v2.a_constant == 1)) {
1234 DCHECK(v1.a_constant == 1 || v1.instruction == nullptr);
1235 DCHECK(v2.a_constant == 1 || v2.instruction == nullptr);
1236 ValueRange index_range(GetGraph()->GetArena(),
1237 ValueBound(v1.instruction, v1.b_constant),
1238 ValueBound(v2.instruction, v2.b_constant));
1239 // If analysis reveals a certain OOB, disable dynamic BCE.
1240 if (index_range.GetLower().LessThan(array_range->GetLower()) ||
1241 index_range.GetUpper().GreaterThan(array_range->GetUpper())) {
1242 *try_dynamic_bce = false;
1243 return false;
1244 }
1245 // Use analysis for static bce only if loop is finite.
1246 if (!needs_finite_test && index_range.FitsIn(array_range)) {
1247 return true;
1248 }
1249 }
1250 } while (induction_range_.RefineOuter(&v1, &v2));
Aart Bik4a342772015-11-30 10:17:46 -08001251 return false;
1252 }
1253
1254 /**
1255 * When the compiler fails to remove a bounds check statically, we try to remove the bounds
1256 * check dynamically by adding runtime tests that trigger a deoptimization in case bounds
1257 * will go out of range (we want to be rather certain of that given the slowdown of
1258 * deoptimization). If no deoptimization occurs, the loop is executed with all corresponding
1259 * bounds checks and related null checks removed.
1260 */
1261 void TryDynamicBCE(HBoundsCheck* instruction) {
1262 HLoopInformation* loop = instruction->GetBlock()->GetLoopInformation();
1263 HInstruction* index = instruction->InputAt(0);
1264 HInstruction* length = instruction->InputAt(1);
1265 // If dynamic bounds check elimination seems profitable and is possible, then proceed.
1266 bool needs_finite_test = false;
1267 bool needs_taken_test = false;
1268 if (DynamicBCESeemsProfitable(loop, instruction->GetBlock()) &&
1269 induction_range_.CanGenerateCode(
1270 instruction, index, &needs_finite_test, &needs_taken_test) &&
1271 CanHandleInfiniteLoop(loop, index, needs_finite_test) &&
1272 CanHandleLength(loop, length, needs_taken_test)) { // do this test last (may code gen)
1273 HInstruction* lower = nullptr;
1274 HInstruction* upper = nullptr;
1275 // Generate the following unsigned comparisons
1276 // if (lower > upper) deoptimize;
1277 // if (upper >= length) deoptimize;
1278 // or, for a non-induction index, just the unsigned comparison on its 'upper' value
1279 // if (upper >= length) deoptimize;
1280 // as runtime test. By restricting dynamic bce to unit strides (with a maximum of 32-bit
1281 // iterations) and by not combining access (e.g. a[i], a[i-3], a[i+5] etc.), these tests
1282 // correctly guard against any possible OOB (including arithmetic wrap-around cases).
Aart Bik55b14df2016-01-12 14:12:47 -08001283 TransformLoopForDeoptimizationIfNeeded(loop, needs_taken_test);
1284 HBasicBlock* block = GetPreHeader(loop, instruction);
Aart Bik4a342772015-11-30 10:17:46 -08001285 induction_range_.GenerateRangeCode(instruction, index, GetGraph(), block, &lower, &upper);
1286 if (lower != nullptr) {
1287 InsertDeopt(loop, block, new (GetGraph()->GetArena()) HAbove(lower, upper));
1288 }
1289 InsertDeopt(loop, block, new (GetGraph()->GetArena()) HAboveOrEqual(upper, length));
1290 ReplaceInstruction(instruction, index);
1291 }
1292 }
1293
1294 /**
1295 * Returns true if heuristics indicate that dynamic bce may be profitable.
1296 */
1297 bool DynamicBCESeemsProfitable(HLoopInformation* loop, HBasicBlock* block) {
1298 if (loop != nullptr) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001299 // The loop preheader of an irreducible loop does not dominate all the blocks in
1300 // the loop. We would need to find the common dominator of all blocks in the loop.
1301 if (loop->IsIrreducible()) {
1302 return false;
1303 }
Aart Bik4a342772015-11-30 10:17:46 -08001304 // A try boundary preheader is hard to handle.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001305 // TODO: remove this restriction.
Aart Bik4a342772015-11-30 10:17:46 -08001306 if (loop->GetPreHeader()->GetLastInstruction()->IsTryBoundary()) {
1307 return false;
1308 }
1309 // Does loop have early-exits? If so, the full range may not be covered by the loop
1310 // at runtime and testing the range may apply deoptimization unnecessarily.
1311 if (IsEarlyExitLoop(loop)) {
1312 return false;
1313 }
1314 // Does the current basic block dominate all back edges? If not,
1315 // don't apply dynamic bce to something that may not be executed.
1316 for (HBasicBlock* back_edge : loop->GetBackEdges()) {
1317 if (!block->Dominates(back_edge)) {
1318 return false;
1319 }
1320 }
1321 // Success!
1322 return true;
1323 }
1324 return false;
1325 }
1326
1327 /**
1328 * Returns true if the loop has early exits, which implies it may not cover
1329 * the full range computed by range analysis based on induction variables.
1330 */
1331 bool IsEarlyExitLoop(HLoopInformation* loop) {
1332 const uint32_t loop_id = loop->GetHeader()->GetBlockId();
1333 // If loop has been analyzed earlier for early-exit, don't repeat the analysis.
1334 auto it = early_exit_loop_.find(loop_id);
1335 if (it != early_exit_loop_.end()) {
1336 return it->second;
1337 }
1338 // First time early-exit analysis for this loop. Since analysis requires scanning
1339 // the full loop-body, results of the analysis is stored for subsequent queries.
1340 HBlocksInLoopReversePostOrderIterator it_loop(*loop);
1341 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
1342 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
1343 if (!loop->Contains(*successor)) {
1344 early_exit_loop_.Put(loop_id, true);
1345 return true;
1346 }
1347 }
1348 }
1349 early_exit_loop_.Put(loop_id, false);
1350 return false;
1351 }
1352
1353 /**
1354 * Returns true if the array length is already loop invariant, or can be made so
1355 * by handling the null check under the hood of the array length operation.
1356 */
1357 bool CanHandleLength(HLoopInformation* loop, HInstruction* length, bool needs_taken_test) {
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001358 if (loop->IsDefinedOutOfTheLoop(length)) {
Aart Bik4a342772015-11-30 10:17:46 -08001359 return true;
1360 } else if (length->IsArrayLength() && length->GetBlock()->GetLoopInformation() == loop) {
1361 if (CanHandleNullCheck(loop, length->InputAt(0), needs_taken_test)) {
Aart Bik55b14df2016-01-12 14:12:47 -08001362 HoistToPreHeaderOrDeoptBlock(loop, length);
Aart Bik4a342772015-11-30 10:17:46 -08001363 return true;
1364 }
1365 }
1366 return false;
1367 }
1368
1369 /**
1370 * Returns true if the null check is already loop invariant, or can be made so
1371 * by generating a deoptimization test.
1372 */
1373 bool CanHandleNullCheck(HLoopInformation* loop, HInstruction* check, bool needs_taken_test) {
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001374 if (loop->IsDefinedOutOfTheLoop(check)) {
Aart Bik4a342772015-11-30 10:17:46 -08001375 return true;
1376 } else if (check->IsNullCheck() && check->GetBlock()->GetLoopInformation() == loop) {
1377 HInstruction* array = check->InputAt(0);
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001378 if (loop->IsDefinedOutOfTheLoop(array)) {
Aart Bik4a342772015-11-30 10:17:46 -08001379 // Generate: if (array == null) deoptimize;
Aart Bik55b14df2016-01-12 14:12:47 -08001380 TransformLoopForDeoptimizationIfNeeded(loop, needs_taken_test);
1381 HBasicBlock* block = GetPreHeader(loop, check);
Aart Bik4a342772015-11-30 10:17:46 -08001382 HInstruction* cond =
1383 new (GetGraph()->GetArena()) HEqual(array, GetGraph()->GetNullConstant());
1384 InsertDeopt(loop, block, cond);
1385 ReplaceInstruction(check, array);
1386 return true;
1387 }
1388 }
1389 return false;
1390 }
1391
1392 /**
1393 * Returns true if compiler can apply dynamic bce to loops that may be infinite
1394 * (e.g. for (int i = 0; i <= U; i++) with U = MAX_INT), which would invalidate
1395 * the range analysis evaluation code by "overshooting" the computed range.
1396 * Since deoptimization would be a bad choice, and there is no other version
1397 * of the loop to use, dynamic bce in such cases is only allowed if other tests
1398 * ensure the loop is finite.
1399 */
1400 bool CanHandleInfiniteLoop(
1401 HLoopInformation* loop, HInstruction* index, bool needs_infinite_test) {
1402 if (needs_infinite_test) {
1403 // If we already forced the loop to be finite, allow directly.
1404 const uint32_t loop_id = loop->GetHeader()->GetBlockId();
1405 if (finite_loop_.find(loop_id) != finite_loop_.end()) {
1406 return true;
1407 }
1408 // Otherwise, allow dynamic bce if the index (which is necessarily an induction at
1409 // this point) is the direct loop index (viz. a[i]), since then the runtime tests
1410 // ensure upper bound cannot cause an infinite loop.
1411 HInstruction* control = loop->GetHeader()->GetLastInstruction();
1412 if (control->IsIf()) {
1413 HInstruction* if_expr = control->AsIf()->InputAt(0);
1414 if (if_expr->IsCondition()) {
1415 HCondition* condition = if_expr->AsCondition();
1416 if (index == condition->InputAt(0) ||
1417 index == condition->InputAt(1)) {
1418 finite_loop_.insert(loop_id);
1419 return true;
1420 }
1421 }
1422 }
1423 return false;
1424 }
1425 return true;
1426 }
1427
Aart Bik55b14df2016-01-12 14:12:47 -08001428 /**
1429 * Returns appropriate preheader for the loop, depending on whether the
1430 * instruction appears in the loop header or proper loop-body.
1431 */
1432 HBasicBlock* GetPreHeader(HLoopInformation* loop, HInstruction* instruction) {
1433 // Use preheader unless there is an earlier generated deoptimization block since
1434 // hoisted expressions may depend on and/or used by the deoptimization tests.
1435 HBasicBlock* header = loop->GetHeader();
1436 const uint32_t loop_id = header->GetBlockId();
1437 auto it = taken_test_loop_.find(loop_id);
1438 if (it != taken_test_loop_.end()) {
1439 HBasicBlock* block = it->second;
1440 // If always taken, keep it that way by returning the original preheader,
1441 // which can be found by following the predecessor of the true-block twice.
1442 if (instruction->GetBlock() == header) {
1443 return block->GetSinglePredecessor()->GetSinglePredecessor();
1444 }
1445 return block;
1446 }
1447 return loop->GetPreHeader();
1448 }
1449
Aart Bik4a342772015-11-30 10:17:46 -08001450 /** Inserts a deoptimization test. */
1451 void InsertDeopt(HLoopInformation* loop, HBasicBlock* block, HInstruction* condition) {
1452 HInstruction* suspend = loop->GetSuspendCheck();
1453 block->InsertInstructionBefore(condition, block->GetLastInstruction());
1454 HDeoptimize* deoptimize =
1455 new (GetGraph()->GetArena()) HDeoptimize(condition, suspend->GetDexPc());
1456 block->InsertInstructionBefore(deoptimize, block->GetLastInstruction());
1457 if (suspend->HasEnvironment()) {
1458 deoptimize->CopyEnvironmentFromWithLoopPhiAdjustment(
1459 suspend->GetEnvironment(), loop->GetHeader());
1460 }
1461 }
1462
1463 /** Hoists instruction out of the loop to preheader or deoptimization block. */
Aart Bik55b14df2016-01-12 14:12:47 -08001464 void HoistToPreHeaderOrDeoptBlock(HLoopInformation* loop, HInstruction* instruction) {
1465 HBasicBlock* block = GetPreHeader(loop, instruction);
Aart Bik4a342772015-11-30 10:17:46 -08001466 DCHECK(!instruction->HasEnvironment());
1467 instruction->MoveBefore(block->GetLastInstruction());
1468 }
1469
1470 /**
Aart Bik55b14df2016-01-12 14:12:47 -08001471 * Adds a new taken-test structure to a loop if needed and not already done.
Aart Bik4a342772015-11-30 10:17:46 -08001472 * The taken-test protects range analysis evaluation code to avoid any
1473 * deoptimization caused by incorrect trip-count evaluation in non-taken loops.
1474 *
Aart Bik4a342772015-11-30 10:17:46 -08001475 * old_preheader
1476 * |
1477 * if_block <- taken-test protects deoptimization block
1478 * / \
1479 * true_block false_block <- deoptimizations/invariants are placed in true_block
1480 * \ /
1481 * new_preheader <- may require phi nodes to preserve SSA structure
1482 * |
1483 * header
1484 *
1485 * For example, this loop:
1486 *
1487 * for (int i = lower; i < upper; i++) {
1488 * array[i] = 0;
1489 * }
1490 *
1491 * will be transformed to:
1492 *
1493 * if (lower < upper) {
1494 * if (array == null) deoptimize;
1495 * array_length = array.length;
1496 * if (lower > upper) deoptimize; // unsigned
1497 * if (upper >= array_length) deoptimize; // unsigned
1498 * } else {
1499 * array_length = 0;
1500 * }
1501 * for (int i = lower; i < upper; i++) {
1502 * // Loop without null check and bounds check, and any array.length replaced with array_length.
1503 * array[i] = 0;
1504 * }
1505 */
Aart Bik55b14df2016-01-12 14:12:47 -08001506 void TransformLoopForDeoptimizationIfNeeded(HLoopInformation* loop, bool needs_taken_test) {
1507 // Not needed (can use preheader) or already done (can reuse)?
Aart Bik4a342772015-11-30 10:17:46 -08001508 const uint32_t loop_id = loop->GetHeader()->GetBlockId();
Aart Bik55b14df2016-01-12 14:12:47 -08001509 if (!needs_taken_test || taken_test_loop_.find(loop_id) != taken_test_loop_.end()) {
1510 return;
Aart Bik4a342772015-11-30 10:17:46 -08001511 }
1512
1513 // Generate top test structure.
1514 HBasicBlock* header = loop->GetHeader();
1515 GetGraph()->TransformLoopHeaderForBCE(header);
1516 HBasicBlock* new_preheader = loop->GetPreHeader();
1517 HBasicBlock* if_block = new_preheader->GetDominator();
1518 HBasicBlock* true_block = if_block->GetSuccessors()[0]; // True successor.
1519 HBasicBlock* false_block = if_block->GetSuccessors()[1]; // False successor.
1520
1521 // Goto instructions.
1522 true_block->AddInstruction(new (GetGraph()->GetArena()) HGoto());
1523 false_block->AddInstruction(new (GetGraph()->GetArena()) HGoto());
1524 new_preheader->AddInstruction(new (GetGraph()->GetArena()) HGoto());
1525
1526 // Insert the taken-test to see if the loop body is entered. If the
1527 // loop isn't entered at all, it jumps around the deoptimization block.
1528 if_block->AddInstruction(new (GetGraph()->GetArena()) HGoto()); // placeholder
1529 HInstruction* condition = nullptr;
1530 induction_range_.GenerateTakenTest(header->GetLastInstruction(),
1531 GetGraph(),
1532 if_block,
1533 &condition);
1534 DCHECK(condition != nullptr);
1535 if_block->RemoveInstruction(if_block->GetLastInstruction());
1536 if_block->AddInstruction(new (GetGraph()->GetArena()) HIf(condition));
1537
1538 taken_test_loop_.Put(loop_id, true_block);
Aart Bik4a342772015-11-30 10:17:46 -08001539 }
1540
1541 /**
1542 * Inserts phi nodes that preserve SSA structure in generated top test structures.
1543 * All uses of instructions in the deoptimization block that reach the loop need
1544 * a phi node in the new loop preheader to fix the dominance relation.
1545 *
1546 * Example:
1547 * if_block
1548 * / \
1549 * x_0 = .. false_block
1550 * \ /
1551 * x_1 = phi(x_0, null) <- synthetic phi
1552 * |
Aart Bik55b14df2016-01-12 14:12:47 -08001553 * new_preheader
Aart Bik4a342772015-11-30 10:17:46 -08001554 */
1555 void InsertPhiNodes() {
1556 // Scan all new deoptimization blocks.
1557 for (auto it1 = taken_test_loop_.begin(); it1 != taken_test_loop_.end(); ++it1) {
1558 HBasicBlock* true_block = it1->second;
1559 HBasicBlock* new_preheader = true_block->GetSingleSuccessor();
1560 // Scan all instructions in a new deoptimization block.
1561 for (HInstructionIterator it(true_block->GetInstructions()); !it.Done(); it.Advance()) {
1562 HInstruction* instruction = it.Current();
1563 Primitive::Type type = instruction->GetType();
1564 HPhi* phi = nullptr;
1565 // Scan all uses of an instruction and replace each later use with a phi node.
1566 for (HUseIterator<HInstruction*> it2(instruction->GetUses());
1567 !it2.Done();
1568 it2.Advance()) {
1569 HInstruction* user = it2.Current()->GetUser();
1570 if (user->GetBlock() != true_block) {
1571 if (phi == nullptr) {
1572 phi = NewPhi(new_preheader, instruction, type);
1573 }
1574 user->ReplaceInput(phi, it2.Current()->GetIndex());
1575 }
1576 }
1577 // Scan all environment uses of an instruction and replace each later use with a phi node.
1578 for (HUseIterator<HEnvironment*> it2(instruction->GetEnvUses());
1579 !it2.Done();
1580 it2.Advance()) {
1581 HEnvironment* user = it2.Current()->GetUser();
1582 if (user->GetHolder()->GetBlock() != true_block) {
1583 if (phi == nullptr) {
1584 phi = NewPhi(new_preheader, instruction, type);
1585 }
1586 user->RemoveAsUserOfInput(it2.Current()->GetIndex());
1587 user->SetRawEnvAt(it2.Current()->GetIndex(), phi);
1588 phi->AddEnvUseAt(user, it2.Current()->GetIndex());
1589 }
1590 }
1591 }
1592 }
1593 }
1594
1595 /**
1596 * Construct a phi(instruction, 0) in the new preheader to fix the dominance relation.
1597 * These are synthetic phi nodes without a virtual register.
1598 */
1599 HPhi* NewPhi(HBasicBlock* new_preheader,
1600 HInstruction* instruction,
1601 Primitive::Type type) {
1602 HGraph* graph = GetGraph();
1603 HInstruction* zero;
1604 switch (type) {
David Brazdil4833f5a2015-12-16 10:37:39 +00001605 case Primitive::kPrimNot: zero = graph->GetNullConstant(); break;
1606 case Primitive::kPrimFloat: zero = graph->GetFloatConstant(0); break;
1607 case Primitive::kPrimDouble: zero = graph->GetDoubleConstant(0); break;
Aart Bik4a342772015-11-30 10:17:46 -08001608 default: zero = graph->GetConstant(type, 0); break;
1609 }
1610 HPhi* phi = new (graph->GetArena())
1611 HPhi(graph->GetArena(), kNoRegNumber, /*number_of_inputs*/ 2, HPhi::ToPhiType(type));
1612 phi->SetRawInputAt(0, instruction);
1613 phi->SetRawInputAt(1, zero);
David Brazdil4833f5a2015-12-16 10:37:39 +00001614 if (type == Primitive::kPrimNot) {
1615 phi->SetReferenceTypeInfo(instruction->GetReferenceTypeInfo());
1616 }
Aart Bik4a342772015-11-30 10:17:46 -08001617 new_preheader->AddPhi(phi);
1618 return phi;
1619 }
1620
1621 /** Helper method to replace an instruction with another instruction. */
1622 static void ReplaceInstruction(HInstruction* instruction, HInstruction* replacement) {
1623 instruction->ReplaceWith(replacement);
1624 instruction->GetBlock()->RemoveInstruction(instruction);
1625 }
1626
1627 // A set of maps, one per basic block, from instruction to range.
Vladimir Marko5233f932015-09-29 19:01:15 +01001628 ArenaVector<ArenaSafeMap<int, ValueRange*>> maps_;
Mingyao Yangf384f882014-10-22 16:08:18 -07001629
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001630 // Map an HArrayLength instruction's id to the first HBoundsCheck instruction in
1631 // a block that checks a constant index against that HArrayLength.
Vladimir Marko5233f932015-09-29 19:01:15 +01001632 ArenaSafeMap<int, HBoundsCheck*> first_constant_index_bounds_check_map_;
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001633
Aart Bik4a342772015-11-30 10:17:46 -08001634 // Early-exit loop bookkeeping.
1635 ArenaSafeMap<uint32_t, bool> early_exit_loop_;
1636
1637 // Taken-test loop bookkeeping.
1638 ArenaSafeMap<uint32_t, HBasicBlock*> taken_test_loop_;
1639
1640 // Finite loop bookkeeping.
1641 ArenaSet<uint32_t> finite_loop_;
1642
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001643 // For the block, there is at least one HArrayLength instruction for which there
1644 // is more than one bounds check instruction with constant indexing. And it's
1645 // beneficial to add a compare instruction that has deoptimization fallback and
1646 // eliminate those bounds checks.
1647 bool need_to_revisit_block_;
1648
Aart Bik4a342772015-11-30 10:17:46 -08001649 // Flag that denotes whether deoptimization has occurred on array references
1650 // with constant subscripts (see AddCompareWithDeoptimization()).
1651 bool has_deoptimization_on_constant_subscripts_;
1652
Mingyao Yang3584bce2015-05-19 16:01:59 -07001653 // Initial number of blocks.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001654 uint32_t initial_block_size_;
Mingyao Yang3584bce2015-05-19 16:01:59 -07001655
Aart Bik4a342772015-11-30 10:17:46 -08001656 // Side effects.
1657 const SideEffectsAnalysis& side_effects_;
1658
Aart Bik22af3be2015-09-10 12:50:58 -07001659 // Range analysis based on induction variables.
1660 InductionVarRange induction_range_;
1661
Mingyao Yangf384f882014-10-22 16:08:18 -07001662 DISALLOW_COPY_AND_ASSIGN(BCEVisitor);
1663};
1664
1665void BoundsCheckElimination::Run() {
Mark Mendell1152c922015-04-24 17:06:35 -04001666 if (!graph_->HasBoundsChecks()) {
Mingyao Yange4335eb2015-03-02 15:14:13 -08001667 return;
1668 }
1669
Mingyao Yangf384f882014-10-22 16:08:18 -07001670 // Reverse post order guarantees a node's dominators are visited first.
1671 // We want to visit in the dominator-based order since if a value is known to
1672 // be bounded by a range at one instruction, it must be true that all uses of
1673 // that value dominated by that instruction fits in that range. Range of that
1674 // value can be narrowed further down in the dominator tree.
Aart Bik4a342772015-11-30 10:17:46 -08001675 BCEVisitor visitor(graph_, side_effects_, induction_analysis_);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001676 HBasicBlock* last_visited_block = nullptr;
1677 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1678 HBasicBlock* current = it.Current();
1679 if (current == last_visited_block) {
1680 // We may insert blocks into the reverse post order list when processing
1681 // a loop header. Don't process it again.
1682 DCHECK(current->IsLoopHeader());
1683 continue;
1684 }
1685 if (visitor.IsAddedBlock(current)) {
1686 // Skip added blocks. Their effects are already taken care of.
1687 continue;
1688 }
1689 visitor.VisitBasicBlock(current);
1690 last_visited_block = current;
1691 }
Aart Bik4a342772015-11-30 10:17:46 -08001692
1693 // Perform cleanup.
1694 visitor.Finish();
Mingyao Yangf384f882014-10-22 16:08:18 -07001695}
1696
1697} // namespace art