blob: 147df1e3e834e30ad939f424b79c4433792b80f8 [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
Vladimir Marko009d1662017-10-10 13:21:15 +010021#include "base/scoped_arena_allocator.h"
22#include "base/scoped_arena_containers.h"
Aart Bik22af3be2015-09-10 12:50:58 -070023#include "induction_var_range.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070024#include "nodes.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070025#include "side_effects_analysis.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070026
27namespace art {
28
29class MonotonicValueRange;
30
31/**
32 * A value bound is represented as a pair of value and constant,
33 * e.g. array.length - 1.
34 */
35class ValueBound : public ValueObject {
36 public:
Mingyao Yang0304e182015-01-30 16:41:29 -080037 ValueBound(HInstruction* instruction, int32_t constant) {
Mingyao Yang64197522014-12-05 15:56:23 -080038 if (instruction != nullptr && instruction->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -080039 // Normalize ValueBound with constant instruction.
40 int32_t instr_const = instruction->AsIntConstant()->GetValue();
Mingyao Yang8c8bad82015-02-09 18:13:26 -080041 if (!WouldAddOverflowOrUnderflow(instr_const, constant)) {
Mingyao Yang64197522014-12-05 15:56:23 -080042 instruction_ = nullptr;
43 constant_ = instr_const + constant;
44 return;
45 }
Mingyao Yangf384f882014-10-22 16:08:18 -070046 }
Mingyao Yang64197522014-12-05 15:56:23 -080047 instruction_ = instruction;
48 constant_ = constant;
49 }
50
Mingyao Yang8c8bad82015-02-09 18:13:26 -080051 // Return whether (left + right) overflows or underflows.
52 static bool WouldAddOverflowOrUnderflow(int32_t left, int32_t right) {
53 if (right == 0) {
54 return false;
55 }
Aart Bikaab5b752015-09-23 11:18:57 -070056 if ((right > 0) && (left <= (std::numeric_limits<int32_t>::max() - right))) {
Mingyao Yang8c8bad82015-02-09 18:13:26 -080057 // No overflow.
58 return false;
59 }
Aart Bikaab5b752015-09-23 11:18:57 -070060 if ((right < 0) && (left >= (std::numeric_limits<int32_t>::min() - right))) {
Mingyao Yang8c8bad82015-02-09 18:13:26 -080061 // No underflow.
62 return false;
63 }
64 return true;
65 }
66
Aart Bik1d239822016-02-09 14:26:34 -080067 // Return true if instruction can be expressed as "left_instruction + right_constant".
Mingyao Yang0304e182015-01-30 16:41:29 -080068 static bool IsAddOrSubAConstant(HInstruction* instruction,
Aart Bik1d239822016-02-09 14:26:34 -080069 /* out */ HInstruction** left_instruction,
70 /* out */ int32_t* right_constant) {
Aart Bikbf3f1cf2016-02-22 16:22:33 -080071 HInstruction* left_so_far = nullptr;
72 int32_t right_so_far = 0;
73 while (instruction->IsAdd() || instruction->IsSub()) {
Mingyao Yang0304e182015-01-30 16:41:29 -080074 HBinaryOperation* bin_op = instruction->AsBinaryOperation();
75 HInstruction* left = bin_op->GetLeft();
76 HInstruction* right = bin_op->GetRight();
77 if (right->IsIntConstant()) {
Aart Bikbf3f1cf2016-02-22 16:22:33 -080078 int32_t v = right->AsIntConstant()->GetValue();
79 int32_t c = instruction->IsAdd() ? v : -v;
80 if (!WouldAddOverflowOrUnderflow(right_so_far, c)) {
81 instruction = left;
82 left_so_far = left;
83 right_so_far += c;
84 continue;
85 }
Mingyao Yang0304e182015-01-30 16:41:29 -080086 }
Aart Bikbf3f1cf2016-02-22 16:22:33 -080087 break;
Mingyao Yang0304e182015-01-30 16:41:29 -080088 }
Aart Bikbf3f1cf2016-02-22 16:22:33 -080089 // Return result: either false and "null+0" or true and "instr+constant".
90 *left_instruction = left_so_far;
91 *right_constant = right_so_far;
92 return left_so_far != nullptr;
Mingyao Yang0304e182015-01-30 16:41:29 -080093 }
94
Aart Bik1d239822016-02-09 14:26:34 -080095 // Expresses any instruction as a value bound.
96 static ValueBound AsValueBound(HInstruction* instruction) {
97 if (instruction->IsIntConstant()) {
98 return ValueBound(nullptr, instruction->AsIntConstant()->GetValue());
99 }
100 HInstruction *left;
101 int32_t right;
102 if (IsAddOrSubAConstant(instruction, &left, &right)) {
103 return ValueBound(left, right);
104 }
105 return ValueBound(instruction, 0);
106 }
107
Mingyao Yang64197522014-12-05 15:56:23 -0800108 // Try to detect useful value bound format from an instruction, e.g.
109 // a constant or array length related value.
Aart Bik1d239822016-02-09 14:26:34 -0800110 static ValueBound DetectValueBoundFromValue(HInstruction* instruction, /* out */ bool* found) {
Mingyao Yang64197522014-12-05 15:56:23 -0800111 DCHECK(instruction != nullptr);
Mingyao Yangf384f882014-10-22 16:08:18 -0700112 if (instruction->IsIntConstant()) {
Mingyao Yang64197522014-12-05 15:56:23 -0800113 *found = true;
114 return ValueBound(nullptr, instruction->AsIntConstant()->GetValue());
Mingyao Yangf384f882014-10-22 16:08:18 -0700115 }
Mingyao Yang64197522014-12-05 15:56:23 -0800116
117 if (instruction->IsArrayLength()) {
118 *found = true;
119 return ValueBound(instruction, 0);
120 }
121 // Try to detect (array.length + c) format.
Mingyao Yang0304e182015-01-30 16:41:29 -0800122 HInstruction *left;
123 int32_t right;
124 if (IsAddOrSubAConstant(instruction, &left, &right)) {
125 if (left->IsArrayLength()) {
Mingyao Yang64197522014-12-05 15:56:23 -0800126 *found = true;
Mingyao Yang0304e182015-01-30 16:41:29 -0800127 return ValueBound(left, right);
Mingyao Yang64197522014-12-05 15:56:23 -0800128 }
129 }
130
131 // No useful bound detected.
132 *found = false;
133 return ValueBound::Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700134 }
135
136 HInstruction* GetInstruction() const { return instruction_; }
Mingyao Yang0304e182015-01-30 16:41:29 -0800137 int32_t GetConstant() const { return constant_; }
Mingyao Yangf384f882014-10-22 16:08:18 -0700138
Mingyao Yang0304e182015-01-30 16:41:29 -0800139 bool IsRelatedToArrayLength() const {
140 // Some bounds are created with HNewArray* as the instruction instead
141 // of HArrayLength*. They are treated the same.
142 return (instruction_ != nullptr) &&
143 (instruction_->IsArrayLength() || instruction_->IsNewArray());
Mingyao Yangf384f882014-10-22 16:08:18 -0700144 }
145
146 bool IsConstant() const {
147 return instruction_ == nullptr;
148 }
149
Aart Bikaab5b752015-09-23 11:18:57 -0700150 static ValueBound Min() { return ValueBound(nullptr, std::numeric_limits<int32_t>::min()); }
151 static ValueBound Max() { return ValueBound(nullptr, std::numeric_limits<int32_t>::max()); }
Mingyao Yangf384f882014-10-22 16:08:18 -0700152
153 bool Equals(ValueBound bound) const {
154 return instruction_ == bound.instruction_ && constant_ == bound.constant_;
155 }
156
Mingyao Yang0304e182015-01-30 16:41:29 -0800157 static bool Equal(HInstruction* instruction1, HInstruction* instruction2) {
158 if (instruction1 == instruction2) {
159 return true;
160 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800161 if (instruction1 == nullptr || instruction2 == nullptr) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700162 return false;
163 }
Aart Bik22af3be2015-09-10 12:50:58 -0700164 instruction1 = HuntForDeclaration(instruction1);
165 instruction2 = HuntForDeclaration(instruction2);
Mingyao Yang0304e182015-01-30 16:41:29 -0800166 return instruction1 == instruction2;
167 }
168
169 // Returns if it's certain this->bound >= `bound`.
170 bool GreaterThanOrEqualTo(ValueBound bound) const {
171 if (Equal(instruction_, bound.instruction_)) {
172 return constant_ >= bound.constant_;
173 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700174 // Not comparable. Just return false.
175 return false;
176 }
177
Mingyao Yang0304e182015-01-30 16:41:29 -0800178 // Returns if it's certain this->bound <= `bound`.
179 bool LessThanOrEqualTo(ValueBound bound) const {
180 if (Equal(instruction_, bound.instruction_)) {
181 return constant_ <= bound.constant_;
Mingyao Yangf384f882014-10-22 16:08:18 -0700182 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700183 // Not comparable. Just return false.
184 return false;
185 }
186
Aart Bik4a342772015-11-30 10:17:46 -0800187 // Returns if it's certain this->bound > `bound`.
188 bool GreaterThan(ValueBound bound) const {
189 if (Equal(instruction_, bound.instruction_)) {
190 return constant_ > bound.constant_;
191 }
192 // Not comparable. Just return false.
193 return false;
194 }
195
196 // Returns if it's certain this->bound < `bound`.
197 bool LessThan(ValueBound bound) const {
198 if (Equal(instruction_, bound.instruction_)) {
199 return constant_ < bound.constant_;
200 }
201 // Not comparable. Just return false.
202 return false;
203 }
204
Mingyao Yangf384f882014-10-22 16:08:18 -0700205 // Try to narrow lower bound. Returns the greatest of the two if possible.
206 // Pick one if they are not comparable.
207 static ValueBound NarrowLowerBound(ValueBound bound1, ValueBound bound2) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800208 if (bound1.GreaterThanOrEqualTo(bound2)) {
209 return bound1;
210 }
211 if (bound2.GreaterThanOrEqualTo(bound1)) {
212 return bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700213 }
214
215 // Not comparable. Just pick one. We may lose some info, but that's ok.
216 // Favor constant as lower bound.
217 return bound1.IsConstant() ? bound1 : bound2;
218 }
219
220 // Try to narrow upper bound. Returns the lowest of the two if possible.
221 // Pick one if they are not comparable.
222 static ValueBound NarrowUpperBound(ValueBound bound1, ValueBound bound2) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800223 if (bound1.LessThanOrEqualTo(bound2)) {
224 return bound1;
225 }
226 if (bound2.LessThanOrEqualTo(bound1)) {
227 return bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700228 }
229
230 // Not comparable. Just pick one. We may lose some info, but that's ok.
231 // Favor array length as upper bound.
Mingyao Yang0304e182015-01-30 16:41:29 -0800232 return bound1.IsRelatedToArrayLength() ? bound1 : bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700233 }
234
Mingyao Yang0304e182015-01-30 16:41:29 -0800235 // Add a constant to a ValueBound.
236 // `overflow` or `underflow` will return whether the resulting bound may
237 // overflow or underflow an int.
Aart Bik1d239822016-02-09 14:26:34 -0800238 ValueBound Add(int32_t c, /* out */ bool* overflow, /* out */ bool* underflow) const {
Mingyao Yang0304e182015-01-30 16:41:29 -0800239 *overflow = *underflow = false;
Mingyao Yangf384f882014-10-22 16:08:18 -0700240 if (c == 0) {
241 return *this;
242 }
243
Mingyao Yang0304e182015-01-30 16:41:29 -0800244 int32_t new_constant;
Mingyao Yangf384f882014-10-22 16:08:18 -0700245 if (c > 0) {
Aart Bikaab5b752015-09-23 11:18:57 -0700246 if (constant_ > (std::numeric_limits<int32_t>::max() - c)) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800247 *overflow = true;
Mingyao Yang64197522014-12-05 15:56:23 -0800248 return Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700249 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800250
251 new_constant = constant_ + c;
252 // (array.length + non-positive-constant) won't overflow an int.
253 if (IsConstant() || (IsRelatedToArrayLength() && new_constant <= 0)) {
254 return ValueBound(instruction_, new_constant);
255 }
256 // Be conservative.
257 *overflow = true;
258 return Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700259 } else {
Aart Bikaab5b752015-09-23 11:18:57 -0700260 if (constant_ < (std::numeric_limits<int32_t>::min() - c)) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800261 *underflow = true;
262 return Min();
Mingyao Yangf384f882014-10-22 16:08:18 -0700263 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800264
265 new_constant = constant_ + c;
266 // Regardless of the value new_constant, (array.length+new_constant) will
267 // never underflow since array.length is no less than 0.
268 if (IsConstant() || IsRelatedToArrayLength()) {
269 return ValueBound(instruction_, new_constant);
270 }
271 // Be conservative.
272 *underflow = true;
273 return Min();
Mingyao Yangf384f882014-10-22 16:08:18 -0700274 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700275 }
276
277 private:
Mingyao Yangf384f882014-10-22 16:08:18 -0700278 HInstruction* instruction_;
Mingyao Yang0304e182015-01-30 16:41:29 -0800279 int32_t constant_;
Mingyao Yangf384f882014-10-22 16:08:18 -0700280};
281
282/**
283 * Represent a range of lower bound and upper bound, both being inclusive.
284 * Currently a ValueRange may be generated as a result of the following:
285 * comparisons related to array bounds, array bounds check, add/sub on top
Mingyao Yang0304e182015-01-30 16:41:29 -0800286 * of an existing value range, NewArray or a loop phi corresponding to an
Mingyao Yangf384f882014-10-22 16:08:18 -0700287 * incrementing/decrementing array index (MonotonicValueRange).
288 */
Vladimir Marko5233f932015-09-29 19:01:15 +0100289class ValueRange : public ArenaObject<kArenaAllocBoundsCheckElimination> {
Mingyao Yangf384f882014-10-22 16:08:18 -0700290 public:
Vladimir Marko009d1662017-10-10 13:21:15 +0100291 ValueRange(ScopedArenaAllocator* allocator, ValueBound lower, ValueBound upper)
Mingyao Yangf384f882014-10-22 16:08:18 -0700292 : allocator_(allocator), lower_(lower), upper_(upper) {}
293
294 virtual ~ValueRange() {}
295
Mingyao Yang57e04752015-02-09 18:13:26 -0800296 virtual MonotonicValueRange* AsMonotonicValueRange() { return nullptr; }
297 bool IsMonotonicValueRange() {
Mingyao Yangf384f882014-10-22 16:08:18 -0700298 return AsMonotonicValueRange() != nullptr;
299 }
300
Vladimir Marko009d1662017-10-10 13:21:15 +0100301 ScopedArenaAllocator* GetAllocator() const { return allocator_; }
Mingyao Yangf384f882014-10-22 16:08:18 -0700302 ValueBound GetLower() const { return lower_; }
303 ValueBound GetUpper() const { return upper_; }
304
Aart Bik98f17362018-01-17 14:36:41 -0800305 bool IsConstantValueRange() const { return lower_.IsConstant() && upper_.IsConstant(); }
Mingyao Yang3584bce2015-05-19 16:01:59 -0700306
Mingyao Yangf384f882014-10-22 16:08:18 -0700307 // If it's certain that this value range fits in other_range.
308 virtual bool FitsIn(ValueRange* other_range) const {
309 if (other_range == nullptr) {
310 return true;
311 }
312 DCHECK(!other_range->IsMonotonicValueRange());
Mingyao Yang0304e182015-01-30 16:41:29 -0800313 return lower_.GreaterThanOrEqualTo(other_range->lower_) &&
314 upper_.LessThanOrEqualTo(other_range->upper_);
Mingyao Yangf384f882014-10-22 16:08:18 -0700315 }
316
317 // Returns the intersection of this and range.
318 // If it's not possible to do intersection because some
319 // bounds are not comparable, it's ok to pick either bound.
320 virtual ValueRange* Narrow(ValueRange* range) {
321 if (range == nullptr) {
322 return this;
323 }
324
325 if (range->IsMonotonicValueRange()) {
326 return this;
327 }
328
329 return new (allocator_) ValueRange(
330 allocator_,
331 ValueBound::NarrowLowerBound(lower_, range->lower_),
332 ValueBound::NarrowUpperBound(upper_, range->upper_));
333 }
334
Mingyao Yang0304e182015-01-30 16:41:29 -0800335 // Shift a range by a constant.
336 ValueRange* Add(int32_t constant) const {
337 bool overflow, underflow;
338 ValueBound lower = lower_.Add(constant, &overflow, &underflow);
339 if (underflow) {
340 // Lower bound underflow will wrap around to positive values
341 // and invalidate the upper bound.
342 return nullptr;
Mingyao Yangf384f882014-10-22 16:08:18 -0700343 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800344 ValueBound upper = upper_.Add(constant, &overflow, &underflow);
345 if (overflow) {
346 // Upper bound overflow will wrap around to negative values
347 // and invalidate the lower bound.
348 return nullptr;
Mingyao Yangf384f882014-10-22 16:08:18 -0700349 }
350 return new (allocator_) ValueRange(allocator_, lower, upper);
351 }
352
Mingyao Yangf384f882014-10-22 16:08:18 -0700353 private:
Vladimir Marko009d1662017-10-10 13:21:15 +0100354 ScopedArenaAllocator* const allocator_;
Mingyao Yangf384f882014-10-22 16:08:18 -0700355 const ValueBound lower_; // inclusive
356 const ValueBound upper_; // inclusive
357
358 DISALLOW_COPY_AND_ASSIGN(ValueRange);
359};
360
361/**
362 * A monotonically incrementing/decrementing value range, e.g.
363 * the variable i in "for (int i=0; i<array.length; i++)".
364 * Special care needs to be taken to account for overflow/underflow
365 * of such value ranges.
366 */
367class MonotonicValueRange : public ValueRange {
368 public:
Vladimir Marko009d1662017-10-10 13:21:15 +0100369 MonotonicValueRange(ScopedArenaAllocator* allocator,
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700370 HPhi* induction_variable,
Mingyao Yang64197522014-12-05 15:56:23 -0800371 HInstruction* initial,
Mingyao Yang0304e182015-01-30 16:41:29 -0800372 int32_t increment,
Mingyao Yang64197522014-12-05 15:56:23 -0800373 ValueBound bound)
Aart Bikaab5b752015-09-23 11:18:57 -0700374 // To be conservative, give it full range [Min(), Max()] in case it's
Mingyao Yang64197522014-12-05 15:56:23 -0800375 // used as a regular value range, due to possible overflow/underflow.
376 : ValueRange(allocator, ValueBound::Min(), ValueBound::Max()),
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700377 induction_variable_(induction_variable),
Mingyao Yang64197522014-12-05 15:56:23 -0800378 initial_(initial),
379 increment_(increment),
380 bound_(bound) {}
Mingyao Yangf384f882014-10-22 16:08:18 -0700381
382 virtual ~MonotonicValueRange() {}
383
Mingyao Yang57e04752015-02-09 18:13:26 -0800384 int32_t GetIncrement() const { return increment_; }
Mingyao Yang57e04752015-02-09 18:13:26 -0800385 ValueBound GetBound() const { return bound_; }
Mingyao Yang3584bce2015-05-19 16:01:59 -0700386 HBasicBlock* GetLoopHeader() const {
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700387 DCHECK(induction_variable_->GetBlock()->IsLoopHeader());
388 return induction_variable_->GetBlock();
389 }
Mingyao Yang57e04752015-02-09 18:13:26 -0800390
391 MonotonicValueRange* AsMonotonicValueRange() OVERRIDE { return this; }
Mingyao Yangf384f882014-10-22 16:08:18 -0700392
393 // If it's certain that this value range fits in other_range.
394 bool FitsIn(ValueRange* other_range) const OVERRIDE {
395 if (other_range == nullptr) {
396 return true;
397 }
398 DCHECK(!other_range->IsMonotonicValueRange());
399 return false;
400 }
401
402 // Try to narrow this MonotonicValueRange given another range.
403 // Ideally it will return a normal ValueRange. But due to
404 // possible overflow/underflow, that may not be possible.
405 ValueRange* Narrow(ValueRange* range) OVERRIDE {
406 if (range == nullptr) {
407 return this;
408 }
409 DCHECK(!range->IsMonotonicValueRange());
410
411 if (increment_ > 0) {
412 // Monotonically increasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800413 ValueBound lower = ValueBound::NarrowLowerBound(bound_, range->GetLower());
Aart Bikaab5b752015-09-23 11:18:57 -0700414 if (!lower.IsConstant() || lower.GetConstant() == std::numeric_limits<int32_t>::min()) {
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700415 // Lower bound isn't useful. Leave it to deoptimization.
416 return this;
417 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700418
Aart Bikaab5b752015-09-23 11:18:57 -0700419 // We currently conservatively assume max array length is Max().
420 // 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 -0700421 // divided by the element size (such as 4 bytes for each integer array), we can
422 // lower this number and rule out some possible overflows.
Aart Bikaab5b752015-09-23 11:18:57 -0700423 int32_t max_array_len = std::numeric_limits<int32_t>::max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700424
Mingyao Yang0304e182015-01-30 16:41:29 -0800425 // max possible integer value of range's upper value.
Aart Bikaab5b752015-09-23 11:18:57 -0700426 int32_t upper = std::numeric_limits<int32_t>::max();
Mingyao Yang0304e182015-01-30 16:41:29 -0800427 // Try to lower upper.
428 ValueBound upper_bound = range->GetUpper();
429 if (upper_bound.IsConstant()) {
430 upper = upper_bound.GetConstant();
431 } else if (upper_bound.IsRelatedToArrayLength() && upper_bound.GetConstant() <= 0) {
432 // Normal case. e.g. <= array.length - 1.
433 upper = max_array_len + upper_bound.GetConstant();
Mingyao Yangf384f882014-10-22 16:08:18 -0700434 }
435
436 // If we can prove for the last number in sequence of initial_,
437 // initial_ + increment_, initial_ + 2 x increment_, ...
438 // that's <= upper, (last_num_in_sequence + increment_) doesn't trigger overflow,
439 // then this MonoticValueRange is narrowed to a normal value range.
440
441 // Be conservative first, assume last number in the sequence hits upper.
Mingyao Yang0304e182015-01-30 16:41:29 -0800442 int32_t last_num_in_sequence = upper;
Mingyao Yangf384f882014-10-22 16:08:18 -0700443 if (initial_->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800444 int32_t initial_constant = initial_->AsIntConstant()->GetValue();
Mingyao Yangf384f882014-10-22 16:08:18 -0700445 if (upper <= initial_constant) {
446 last_num_in_sequence = upper;
447 } else {
Mingyao Yang0304e182015-01-30 16:41:29 -0800448 // Cast to int64_t for the substraction part to avoid int32_t overflow.
Mingyao Yangf384f882014-10-22 16:08:18 -0700449 last_num_in_sequence = initial_constant +
450 ((int64_t)upper - (int64_t)initial_constant) / increment_ * increment_;
451 }
452 }
Aart Bikaab5b752015-09-23 11:18:57 -0700453 if (last_num_in_sequence <= (std::numeric_limits<int32_t>::max() - increment_)) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700454 // No overflow. The sequence will be stopped by the upper bound test as expected.
455 return new (GetAllocator()) ValueRange(GetAllocator(), lower, range->GetUpper());
456 }
457
458 // There might be overflow. Give up narrowing.
459 return this;
460 } else {
461 DCHECK_NE(increment_, 0);
462 // Monotonically decreasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800463 ValueBound upper = ValueBound::NarrowUpperBound(bound_, range->GetUpper());
Aart Bikaab5b752015-09-23 11:18:57 -0700464 if ((!upper.IsConstant() || upper.GetConstant() == std::numeric_limits<int32_t>::max()) &&
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700465 !upper.IsRelatedToArrayLength()) {
466 // Upper bound isn't useful. Leave it to deoptimization.
467 return this;
468 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700469
470 // Need to take care of underflow. Try to prove underflow won't happen
Mingyao Yang0304e182015-01-30 16:41:29 -0800471 // for common cases.
Mingyao Yangf384f882014-10-22 16:08:18 -0700472 if (range->GetLower().IsConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800473 int32_t constant = range->GetLower().GetConstant();
Aart Bikaab5b752015-09-23 11:18:57 -0700474 if (constant >= (std::numeric_limits<int32_t>::min() - increment_)) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700475 return new (GetAllocator()) ValueRange(GetAllocator(), range->GetLower(), upper);
476 }
477 }
478
Mingyao Yang0304e182015-01-30 16:41:29 -0800479 // For non-constant lower bound, just assume might be underflow. Give up narrowing.
Mingyao Yangf384f882014-10-22 16:08:18 -0700480 return this;
481 }
482 }
483
484 private:
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700485 HPhi* const induction_variable_; // Induction variable for this monotonic value range.
486 HInstruction* const initial_; // Initial value.
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700487 const int32_t increment_; // Increment for each loop iteration.
488 const ValueBound bound_; // Additional value bound info for initial_.
Mingyao Yangf384f882014-10-22 16:08:18 -0700489
490 DISALLOW_COPY_AND_ASSIGN(MonotonicValueRange);
491};
492
493class BCEVisitor : public HGraphVisitor {
494 public:
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700495 // The least number of bounds checks that should be eliminated by triggering
496 // the deoptimization technique.
497 static constexpr size_t kThresholdForAddingDeoptimize = 2;
498
Aart Bik1d239822016-02-09 14:26:34 -0800499 // Very large lengths are considered an anomaly. This is a threshold beyond which we don't
500 // bother to apply the deoptimization technique since it's likely, or sometimes certain,
501 // an AIOOBE will be thrown.
502 static constexpr uint32_t kMaxLengthForAddingDeoptimize =
Aart Bikaab5b752015-09-23 11:18:57 -0700503 std::numeric_limits<int32_t>::max() - 1024 * 1024;
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700504
Mingyao Yang3584bce2015-05-19 16:01:59 -0700505 // Added blocks for loop body entry test.
506 bool IsAddedBlock(HBasicBlock* block) const {
507 return block->GetBlockId() >= initial_block_size_;
508 }
509
Aart Bik4a342772015-11-30 10:17:46 -0800510 BCEVisitor(HGraph* graph,
511 const SideEffectsAnalysis& side_effects,
512 HInductionVarAnalysis* induction_analysis)
Aart Bik22af3be2015-09-10 12:50:58 -0700513 : HGraphVisitor(graph),
Vladimir Marko009d1662017-10-10 13:21:15 +0100514 allocator_(graph->GetArenaStack()),
Vladimir Marko5233f932015-09-29 19:01:15 +0100515 maps_(graph->GetBlocks().size(),
Vladimir Marko009d1662017-10-10 13:21:15 +0100516 ScopedArenaSafeMap<int, ValueRange*>(
Vladimir Marko5233f932015-09-29 19:01:15 +0100517 std::less<int>(),
Vladimir Marko009d1662017-10-10 13:21:15 +0100518 allocator_.Adapter(kArenaAllocBoundsCheckElimination)),
519 allocator_.Adapter(kArenaAllocBoundsCheckElimination)),
520 first_index_bounds_check_map_(std::less<int>(),
521 allocator_.Adapter(kArenaAllocBoundsCheckElimination)),
522 early_exit_loop_(std::less<uint32_t>(),
523 allocator_.Adapter(kArenaAllocBoundsCheckElimination)),
524 taken_test_loop_(std::less<uint32_t>(),
525 allocator_.Adapter(kArenaAllocBoundsCheckElimination)),
526 finite_loop_(allocator_.Adapter(kArenaAllocBoundsCheckElimination)),
Aart Bik1d239822016-02-09 14:26:34 -0800527 has_dom_based_dynamic_bce_(false),
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100528 initial_block_size_(graph->GetBlocks().size()),
Aart Bik4a342772015-11-30 10:17:46 -0800529 side_effects_(side_effects),
Andreas Gamped9911ee2017-03-27 13:27:24 -0700530 induction_range_(induction_analysis),
531 next_(nullptr) {}
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700532
533 void VisitBasicBlock(HBasicBlock* block) OVERRIDE {
Mingyao Yang3584bce2015-05-19 16:01:59 -0700534 DCHECK(!IsAddedBlock(block));
Aart Bik1d239822016-02-09 14:26:34 -0800535 first_index_bounds_check_map_.clear();
Aart Bik1e677482016-11-01 14:23:58 -0700536 // Visit phis and instructions using a safe iterator. The iteration protects
537 // against deleting the current instruction during iteration. However, it
538 // must advance next_ if that instruction is deleted during iteration.
539 for (HInstruction* instruction = block->GetFirstPhi(); instruction != nullptr;) {
540 DCHECK(instruction->IsInBlock());
541 next_ = instruction->GetNext();
542 instruction->Accept(this);
543 instruction = next_;
544 }
545 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
546 DCHECK(instruction->IsInBlock());
547 next_ = instruction->GetNext();
548 instruction->Accept(this);
549 instruction = next_;
550 }
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100551 // We should never deoptimize from an osr method, otherwise we might wrongly optimize
552 // code dominated by the deoptimization.
553 if (!GetGraph()->IsCompilingOsr()) {
554 AddComparesWithDeoptimization(block);
555 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700556 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700557
Aart Bik4a342772015-11-30 10:17:46 -0800558 void Finish() {
559 // Preserve SSA structure which may have been broken by adding one or more
560 // new taken-test structures (see TransformLoopForDeoptimizationIfNeeded()).
561 InsertPhiNodes();
562
563 // Clear the loop data structures.
564 early_exit_loop_.clear();
565 taken_test_loop_.clear();
566 finite_loop_.clear();
567 }
568
Mingyao Yangf384f882014-10-22 16:08:18 -0700569 private:
570 // Return the map of proven value ranges at the beginning of a basic block.
Vladimir Marko009d1662017-10-10 13:21:15 +0100571 ScopedArenaSafeMap<int, ValueRange*>* GetValueRangeMap(HBasicBlock* basic_block) {
Mingyao Yang3584bce2015-05-19 16:01:59 -0700572 if (IsAddedBlock(basic_block)) {
573 // Added blocks don't keep value ranges.
574 return nullptr;
575 }
Aart Bik1d239822016-02-09 14:26:34 -0800576 return &maps_[basic_block->GetBlockId()];
Mingyao Yangf384f882014-10-22 16:08:18 -0700577 }
578
579 // Traverse up the dominator tree to look for value range info.
580 ValueRange* LookupValueRange(HInstruction* instruction, HBasicBlock* basic_block) {
581 while (basic_block != nullptr) {
Vladimir Marko009d1662017-10-10 13:21:15 +0100582 ScopedArenaSafeMap<int, ValueRange*>* map = GetValueRangeMap(basic_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -0700583 if (map != nullptr) {
584 if (map->find(instruction->GetId()) != map->end()) {
585 return map->Get(instruction->GetId());
586 }
587 } else {
588 DCHECK(IsAddedBlock(basic_block));
Mingyao Yangf384f882014-10-22 16:08:18 -0700589 }
590 basic_block = basic_block->GetDominator();
591 }
592 // Didn't find any.
593 return nullptr;
594 }
595
Aart Bik1d239822016-02-09 14:26:34 -0800596 // Helper method to assign a new range to an instruction in given basic block.
597 void AssignRange(HBasicBlock* basic_block, HInstruction* instruction, ValueRange* range) {
Mingyao Yang73b326e2017-09-12 14:42:29 -0700598 DCHECK(!range->IsMonotonicValueRange() || instruction->IsLoopHeaderPhi());
Aart Bik1d239822016-02-09 14:26:34 -0800599 GetValueRangeMap(basic_block)->Overwrite(instruction->GetId(), range);
600 }
601
Mingyao Yang0304e182015-01-30 16:41:29 -0800602 // Narrow the value range of `instruction` at the end of `basic_block` with `range`,
603 // and push the narrowed value range to `successor`.
Mingyao Yangf384f882014-10-22 16:08:18 -0700604 void ApplyRangeFromComparison(HInstruction* instruction, HBasicBlock* basic_block,
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800605 HBasicBlock* successor, ValueRange* range) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700606 ValueRange* existing_range = LookupValueRange(instruction, basic_block);
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800607 if (existing_range == nullptr) {
608 if (range != nullptr) {
Aart Bik1d239822016-02-09 14:26:34 -0800609 AssignRange(successor, instruction, range);
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800610 }
611 return;
612 }
613 if (existing_range->IsMonotonicValueRange()) {
614 DCHECK(instruction->IsLoopHeaderPhi());
615 // Make sure the comparison is in the loop header so each increment is
616 // checked with a comparison.
617 if (instruction->GetBlock() != basic_block) {
618 return;
619 }
620 }
Aart Bik1d239822016-02-09 14:26:34 -0800621 AssignRange(successor, instruction, existing_range->Narrow(range));
Mingyao Yangf384f882014-10-22 16:08:18 -0700622 }
623
Mingyao Yang57e04752015-02-09 18:13:26 -0800624 // Special case that we may simultaneously narrow two MonotonicValueRange's to
625 // regular value ranges.
626 void HandleIfBetweenTwoMonotonicValueRanges(HIf* instruction,
627 HInstruction* left,
628 HInstruction* right,
629 IfCondition cond,
630 MonotonicValueRange* left_range,
631 MonotonicValueRange* right_range) {
632 DCHECK(left->IsLoopHeaderPhi());
633 DCHECK(right->IsLoopHeaderPhi());
634 if (instruction->GetBlock() != left->GetBlock()) {
635 // Comparison needs to be in loop header to make sure it's done after each
636 // increment/decrement.
637 return;
638 }
639
640 // Handle common cases which also don't have overflow/underflow concerns.
641 if (left_range->GetIncrement() == 1 &&
642 left_range->GetBound().IsConstant() &&
643 right_range->GetIncrement() == -1 &&
644 right_range->GetBound().IsRelatedToArrayLength() &&
645 right_range->GetBound().GetConstant() < 0) {
Mingyao Yang57e04752015-02-09 18:13:26 -0800646 HBasicBlock* successor = nullptr;
647 int32_t left_compensation = 0;
648 int32_t right_compensation = 0;
649 if (cond == kCondLT) {
650 left_compensation = -1;
651 right_compensation = 1;
652 successor = instruction->IfTrueSuccessor();
653 } else if (cond == kCondLE) {
654 successor = instruction->IfTrueSuccessor();
655 } else if (cond == kCondGT) {
656 successor = instruction->IfFalseSuccessor();
657 } else if (cond == kCondGE) {
658 left_compensation = -1;
659 right_compensation = 1;
660 successor = instruction->IfFalseSuccessor();
661 } else {
662 // We don't handle '=='/'!=' test in case left and right can cross and
663 // miss each other.
664 return;
665 }
666
667 if (successor != nullptr) {
668 bool overflow;
669 bool underflow;
Vladimir Marko009d1662017-10-10 13:21:15 +0100670 ValueRange* new_left_range = new (&allocator_) ValueRange(
671 &allocator_,
Mingyao Yang57e04752015-02-09 18:13:26 -0800672 left_range->GetBound(),
673 right_range->GetBound().Add(left_compensation, &overflow, &underflow));
674 if (!overflow && !underflow) {
675 ApplyRangeFromComparison(left, instruction->GetBlock(), successor,
676 new_left_range);
677 }
678
Vladimir Marko009d1662017-10-10 13:21:15 +0100679 ValueRange* new_right_range = new (&allocator_) ValueRange(
680 &allocator_,
Mingyao Yang57e04752015-02-09 18:13:26 -0800681 left_range->GetBound().Add(right_compensation, &overflow, &underflow),
682 right_range->GetBound());
683 if (!overflow && !underflow) {
684 ApplyRangeFromComparison(right, instruction->GetBlock(), successor,
685 new_right_range);
686 }
687 }
688 }
689 }
690
Mingyao Yangf384f882014-10-22 16:08:18 -0700691 // Handle "if (left cmp_cond right)".
692 void HandleIf(HIf* instruction, HInstruction* left, HInstruction* right, IfCondition cond) {
693 HBasicBlock* block = instruction->GetBlock();
694
695 HBasicBlock* true_successor = instruction->IfTrueSuccessor();
696 // There should be no critical edge at this point.
Vladimir Marko60584552015-09-03 13:35:12 +0000697 DCHECK_EQ(true_successor->GetPredecessors().size(), 1u);
Mingyao Yangf384f882014-10-22 16:08:18 -0700698
699 HBasicBlock* false_successor = instruction->IfFalseSuccessor();
700 // There should be no critical edge at this point.
Vladimir Marko60584552015-09-03 13:35:12 +0000701 DCHECK_EQ(false_successor->GetPredecessors().size(), 1u);
Mingyao Yangf384f882014-10-22 16:08:18 -0700702
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700703 ValueRange* left_range = LookupValueRange(left, block);
704 MonotonicValueRange* left_monotonic_range = nullptr;
705 if (left_range != nullptr) {
706 left_monotonic_range = left_range->AsMonotonicValueRange();
707 if (left_monotonic_range != nullptr) {
Mingyao Yang3584bce2015-05-19 16:01:59 -0700708 HBasicBlock* loop_head = left_monotonic_range->GetLoopHeader();
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700709 if (instruction->GetBlock() != loop_head) {
710 // For monotonic value range, don't handle `instruction`
711 // if it's not defined in the loop header.
712 return;
713 }
714 }
715 }
716
Mingyao Yang64197522014-12-05 15:56:23 -0800717 bool found;
718 ValueBound bound = ValueBound::DetectValueBoundFromValue(right, &found);
Mingyao Yang0304e182015-01-30 16:41:29 -0800719 // Each comparison can establish a lower bound and an upper bound
720 // for the left hand side.
Mingyao Yangf384f882014-10-22 16:08:18 -0700721 ValueBound lower = bound;
722 ValueBound upper = bound;
723 if (!found) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800724 // No constant or array.length+c format bound found.
Mingyao Yangf384f882014-10-22 16:08:18 -0700725 // 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 -0800726 ValueRange* right_range = LookupValueRange(right, block);
727 if (right_range != nullptr) {
728 if (right_range->IsMonotonicValueRange()) {
Mingyao Yang57e04752015-02-09 18:13:26 -0800729 if (left_range != nullptr && left_range->IsMonotonicValueRange()) {
730 HandleIfBetweenTwoMonotonicValueRanges(instruction, left, right, cond,
731 left_range->AsMonotonicValueRange(),
732 right_range->AsMonotonicValueRange());
733 return;
734 }
735 }
736 lower = right_range->GetLower();
737 upper = right_range->GetUpper();
Mingyao Yangf384f882014-10-22 16:08:18 -0700738 } else {
739 lower = ValueBound::Min();
740 upper = ValueBound::Max();
741 }
742 }
743
Mingyao Yang0304e182015-01-30 16:41:29 -0800744 bool overflow, underflow;
Mingyao Yangf384f882014-10-22 16:08:18 -0700745 if (cond == kCondLT || cond == kCondLE) {
746 if (!upper.Equals(ValueBound::Max())) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800747 int32_t compensation = (cond == kCondLT) ? -1 : 0; // upper bound is inclusive
748 ValueBound new_upper = upper.Add(compensation, &overflow, &underflow);
749 if (overflow || underflow) {
750 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800751 }
Vladimir Marko009d1662017-10-10 13:21:15 +0100752 ValueRange* new_range = new (&allocator_) ValueRange(
753 &allocator_, ValueBound::Min(), new_upper);
Mingyao Yangf384f882014-10-22 16:08:18 -0700754 ApplyRangeFromComparison(left, block, true_successor, new_range);
755 }
756
757 // array.length as a lower bound isn't considered useful.
Mingyao Yang0304e182015-01-30 16:41:29 -0800758 if (!lower.Equals(ValueBound::Min()) && !lower.IsRelatedToArrayLength()) {
759 int32_t compensation = (cond == kCondLE) ? 1 : 0; // lower bound is inclusive
760 ValueBound new_lower = lower.Add(compensation, &overflow, &underflow);
761 if (overflow || underflow) {
762 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800763 }
Vladimir Marko009d1662017-10-10 13:21:15 +0100764 ValueRange* new_range = new (&allocator_) ValueRange(
765 &allocator_, new_lower, ValueBound::Max());
Mingyao Yangf384f882014-10-22 16:08:18 -0700766 ApplyRangeFromComparison(left, block, false_successor, new_range);
767 }
768 } else if (cond == kCondGT || cond == kCondGE) {
769 // array.length as a lower bound isn't considered useful.
Mingyao Yang0304e182015-01-30 16:41:29 -0800770 if (!lower.Equals(ValueBound::Min()) && !lower.IsRelatedToArrayLength()) {
771 int32_t compensation = (cond == kCondGT) ? 1 : 0; // lower bound is inclusive
772 ValueBound new_lower = lower.Add(compensation, &overflow, &underflow);
773 if (overflow || underflow) {
774 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800775 }
Vladimir Marko009d1662017-10-10 13:21:15 +0100776 ValueRange* new_range = new (&allocator_) ValueRange(
777 &allocator_, new_lower, ValueBound::Max());
Mingyao Yangf384f882014-10-22 16:08:18 -0700778 ApplyRangeFromComparison(left, block, true_successor, new_range);
779 }
780
781 if (!upper.Equals(ValueBound::Max())) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800782 int32_t compensation = (cond == kCondGE) ? -1 : 0; // upper bound is inclusive
783 ValueBound new_upper = upper.Add(compensation, &overflow, &underflow);
784 if (overflow || underflow) {
785 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800786 }
Vladimir Marko009d1662017-10-10 13:21:15 +0100787 ValueRange* new_range = new (&allocator_) ValueRange(
788 &allocator_, ValueBound::Min(), new_upper);
Mingyao Yangf384f882014-10-22 16:08:18 -0700789 ApplyRangeFromComparison(left, block, false_successor, new_range);
790 }
Aart Bika2106892016-05-04 14:00:55 -0700791 } else if (cond == kCondNE || cond == kCondEQ) {
Aart Bik98f17362018-01-17 14:36:41 -0800792 if (left->IsArrayLength()) {
793 if (lower.IsConstant() && upper.IsConstant()) {
794 // Special case:
795 // length == [c,d] yields [c, d] along true
796 // length != [c,d] yields [c, d] along false
797 if (!lower.Equals(ValueBound::Min()) || !upper.Equals(ValueBound::Max())) {
798 ValueRange* new_range = new (&allocator_) ValueRange(&allocator_, lower, upper);
799 ApplyRangeFromComparison(
800 left, block, cond == kCondEQ ? true_successor : false_successor, new_range);
801 }
802 // In addition:
803 // length == 0 yields [1, max] along false
804 // length != 0 yields [1, max] along true
805 if (lower.GetConstant() == 0 && upper.GetConstant() == 0) {
806 ValueRange* new_range = new (&allocator_) ValueRange(
807 &allocator_, ValueBound(nullptr, 1), ValueBound::Max());
808 ApplyRangeFromComparison(
809 left, block, cond == kCondEQ ? false_successor : true_successor, new_range);
810 }
Aart Bika2106892016-05-04 14:00:55 -0700811 }
Aart Bik98f17362018-01-17 14:36:41 -0800812 } else if (lower.IsRelatedToArrayLength() && lower.Equals(upper)) {
813 // Special aliasing case, with x not array length itself:
814 // x == [length,length] yields x == length along true
815 // x != [length,length] yields x == length along false
816 ValueRange* new_range = new (&allocator_) ValueRange(&allocator_, lower, upper);
817 ApplyRangeFromComparison(
818 left, block, cond == kCondEQ ? true_successor : false_successor, new_range);
Aart Bika2106892016-05-04 14:00:55 -0700819 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700820 }
821 }
822
Aart Bik4a342772015-11-30 10:17:46 -0800823 void VisitBoundsCheck(HBoundsCheck* bounds_check) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700824 HBasicBlock* block = bounds_check->GetBlock();
825 HInstruction* index = bounds_check->InputAt(0);
826 HInstruction* array_length = bounds_check->InputAt(1);
Mingyao Yang3584bce2015-05-19 16:01:59 -0700827 DCHECK(array_length->IsIntConstant() ||
828 array_length->IsArrayLength() ||
829 array_length->IsPhi());
Aart Bik4a342772015-11-30 10:17:46 -0800830 bool try_dynamic_bce = true;
Aart Bik1d239822016-02-09 14:26:34 -0800831 // Analyze index range.
Mingyao Yang0304e182015-01-30 16:41:29 -0800832 if (!index->IsIntConstant()) {
Aart Bik1d239822016-02-09 14:26:34 -0800833 // Non-constant index.
Aart Bik22af3be2015-09-10 12:50:58 -0700834 ValueBound lower = ValueBound(nullptr, 0); // constant 0
835 ValueBound upper = ValueBound(array_length, -1); // array_length - 1
Vladimir Marko009d1662017-10-10 13:21:15 +0100836 ValueRange array_range(&allocator_, lower, upper);
Aart Bik1d239822016-02-09 14:26:34 -0800837 // Try index range obtained by dominator-based analysis.
Mingyao Yang0304e182015-01-30 16:41:29 -0800838 ValueRange* index_range = LookupValueRange(index, block);
Aart Bik22af3be2015-09-10 12:50:58 -0700839 if (index_range != nullptr && index_range->FitsIn(&array_range)) {
Aart Bik4a342772015-11-30 10:17:46 -0800840 ReplaceInstruction(bounds_check, index);
Aart Bik22af3be2015-09-10 12:50:58 -0700841 return;
842 }
Aart Bik1d239822016-02-09 14:26:34 -0800843 // Try index range obtained by induction variable analysis.
Aart Bik4a342772015-11-30 10:17:46 -0800844 // Disables dynamic bce if OOB is certain.
Aart Bik52be7e72016-06-23 11:20:41 -0700845 if (InductionRangeFitsIn(&array_range, bounds_check, &try_dynamic_bce)) {
Aart Bik4a342772015-11-30 10:17:46 -0800846 ReplaceInstruction(bounds_check, index);
Aart Bik22af3be2015-09-10 12:50:58 -0700847 return;
Mingyao Yangf384f882014-10-22 16:08:18 -0700848 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800849 } else {
Aart Bik1d239822016-02-09 14:26:34 -0800850 // Constant index.
Mingyao Yang0304e182015-01-30 16:41:29 -0800851 int32_t constant = index->AsIntConstant()->GetValue();
852 if (constant < 0) {
853 // Will always throw exception.
854 return;
Aart Bik1d239822016-02-09 14:26:34 -0800855 } else if (array_length->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800856 if (constant < array_length->AsIntConstant()->GetValue()) {
Aart Bik4a342772015-11-30 10:17:46 -0800857 ReplaceInstruction(bounds_check, index);
Mingyao Yang0304e182015-01-30 16:41:29 -0800858 }
859 return;
860 }
Aart Bik1d239822016-02-09 14:26:34 -0800861 // Analyze array length range.
Mingyao Yang0304e182015-01-30 16:41:29 -0800862 DCHECK(array_length->IsArrayLength());
863 ValueRange* existing_range = LookupValueRange(array_length, block);
864 if (existing_range != nullptr) {
865 ValueBound lower = existing_range->GetLower();
866 DCHECK(lower.IsConstant());
867 if (constant < lower.GetConstant()) {
Aart Bik4a342772015-11-30 10:17:46 -0800868 ReplaceInstruction(bounds_check, index);
Mingyao Yang0304e182015-01-30 16:41:29 -0800869 return;
870 } else {
871 // Existing range isn't strong enough to eliminate the bounds check.
872 // Fall through to update the array_length range with info from this
873 // bounds check.
874 }
875 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700876 // Once we have an array access like 'array[5] = 1', we record array.length >= 6.
Mingyao Yang0304e182015-01-30 16:41:29 -0800877 // We currently don't do it for non-constant index since a valid array[i] can't prove
878 // a valid array[i-1] yet due to the lower bound side.
Aart Bikaab5b752015-09-23 11:18:57 -0700879 if (constant == std::numeric_limits<int32_t>::max()) {
880 // Max() as an index will definitely throw AIOOBE.
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700881 return;
Aart Bik1d239822016-02-09 14:26:34 -0800882 } else {
883 ValueBound lower = ValueBound(nullptr, constant + 1);
884 ValueBound upper = ValueBound::Max();
Vladimir Marko009d1662017-10-10 13:21:15 +0100885 ValueRange* range = new (&allocator_) ValueRange(&allocator_, lower, upper);
Aart Bik1d239822016-02-09 14:26:34 -0800886 AssignRange(block, array_length, range);
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700887 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700888 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700889
Aart Bik4a342772015-11-30 10:17:46 -0800890 // If static analysis fails, and OOB is not certain, try dynamic elimination.
891 if (try_dynamic_bce) {
Aart Bik1d239822016-02-09 14:26:34 -0800892 // Try loop-based dynamic elimination.
Aart Bik67def592016-07-14 17:19:43 -0700893 HLoopInformation* loop = bounds_check->GetBlock()->GetLoopInformation();
894 bool needs_finite_test = false;
895 bool needs_taken_test = false;
896 if (DynamicBCESeemsProfitable(loop, bounds_check->GetBlock()) &&
Aart Bik16d3a652016-09-09 10:33:50 -0700897 induction_range_.CanGenerateRange(
Aart Bik67def592016-07-14 17:19:43 -0700898 bounds_check, index, &needs_finite_test, &needs_taken_test) &&
899 CanHandleInfiniteLoop(loop, index, needs_finite_test) &&
900 // Do this test last, since it may generate code.
901 CanHandleLength(loop, array_length, needs_taken_test)) {
902 TransformLoopForDeoptimizationIfNeeded(loop, needs_taken_test);
903 TransformLoopForDynamicBCE(loop, bounds_check);
Aart Bik1d239822016-02-09 14:26:34 -0800904 return;
905 }
Aart Bik67def592016-07-14 17:19:43 -0700906 // Otherwise, prepare dominator-based dynamic elimination.
Aart Bik1d239822016-02-09 14:26:34 -0800907 if (first_index_bounds_check_map_.find(array_length->GetId()) ==
908 first_index_bounds_check_map_.end()) {
909 // Remember the first bounds check against each array_length. That bounds check
910 // instruction has an associated HEnvironment where we may add an HDeoptimize
911 // to eliminate subsequent bounds checks against the same array_length.
912 first_index_bounds_check_map_.Put(array_length->GetId(), bounds_check);
913 }
Aart Bik4a342772015-11-30 10:17:46 -0800914 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700915 }
916
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100917 static bool HasSameInputAtBackEdges(HPhi* phi) {
918 DCHECK(phi->IsLoopHeaderPhi());
Vladimir Markoe9004912016-06-16 16:50:52 +0100919 HConstInputsRef inputs = phi->GetInputs();
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100920 // Start with input 1. Input 0 is from the incoming block.
Vladimir Markoe9004912016-06-16 16:50:52 +0100921 const HInstruction* input1 = inputs[1];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100922 DCHECK(phi->GetBlock()->GetLoopInformation()->IsBackEdge(
Vladimir Markoec7802a2015-10-01 20:57:57 +0100923 *phi->GetBlock()->GetPredecessors()[1]));
Vladimir Marko372f10e2016-05-17 16:30:10 +0100924 for (size_t i = 2; i < inputs.size(); ++i) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100925 DCHECK(phi->GetBlock()->GetLoopInformation()->IsBackEdge(
Vladimir Markoec7802a2015-10-01 20:57:57 +0100926 *phi->GetBlock()->GetPredecessors()[i]));
Vladimir Marko372f10e2016-05-17 16:30:10 +0100927 if (input1 != inputs[i]) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100928 return false;
929 }
930 }
931 return true;
932 }
933
Aart Bik4a342772015-11-30 10:17:46 -0800934 void VisitPhi(HPhi* phi) OVERRIDE {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100935 if (phi->IsLoopHeaderPhi()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100936 && (phi->GetType() == DataType::Type::kInt32)
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100937 && HasSameInputAtBackEdges(phi)) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700938 HInstruction* instruction = phi->InputAt(1);
Mingyao Yang0304e182015-01-30 16:41:29 -0800939 HInstruction *left;
940 int32_t increment;
941 if (ValueBound::IsAddOrSubAConstant(instruction, &left, &increment)) {
942 if (left == phi) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700943 HInstruction* initial_value = phi->InputAt(0);
944 ValueRange* range = nullptr;
Mingyao Yang64197522014-12-05 15:56:23 -0800945 if (increment == 0) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700946 // Add constant 0. It's really a fixed value.
Vladimir Marko009d1662017-10-10 13:21:15 +0100947 range = new (&allocator_) ValueRange(
948 &allocator_,
Mingyao Yang64197522014-12-05 15:56:23 -0800949 ValueBound(initial_value, 0),
950 ValueBound(initial_value, 0));
Mingyao Yangf384f882014-10-22 16:08:18 -0700951 } else {
952 // Monotonically increasing/decreasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800953 bool found;
954 ValueBound bound = ValueBound::DetectValueBoundFromValue(
955 initial_value, &found);
956 if (!found) {
957 // No constant or array.length+c bound found.
958 // For i=j, we can still use j's upper bound as i's upper bound.
959 // Same for lower.
960 ValueRange* initial_range = LookupValueRange(initial_value, phi->GetBlock());
961 if (initial_range != nullptr) {
962 bound = increment > 0 ? initial_range->GetLower() :
963 initial_range->GetUpper();
964 } else {
965 bound = increment > 0 ? ValueBound::Min() : ValueBound::Max();
966 }
967 }
Vladimir Marko009d1662017-10-10 13:21:15 +0100968 range = new (&allocator_) MonotonicValueRange(
969 &allocator_,
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700970 phi,
Mingyao Yangf384f882014-10-22 16:08:18 -0700971 initial_value,
Mingyao Yang64197522014-12-05 15:56:23 -0800972 increment,
973 bound);
Mingyao Yangf384f882014-10-22 16:08:18 -0700974 }
Aart Bik1d239822016-02-09 14:26:34 -0800975 AssignRange(phi->GetBlock(), phi, range);
Mingyao Yangf384f882014-10-22 16:08:18 -0700976 }
977 }
978 }
979 }
980
Aart Bik4a342772015-11-30 10:17:46 -0800981 void VisitIf(HIf* instruction) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700982 if (instruction->InputAt(0)->IsCondition()) {
983 HCondition* cond = instruction->InputAt(0)->AsCondition();
Aart Bika2106892016-05-04 14:00:55 -0700984 HandleIf(instruction, cond->GetLeft(), cond->GetRight(), cond->GetCondition());
Mingyao Yangf384f882014-10-22 16:08:18 -0700985 }
986 }
987
Aart Bik4a342772015-11-30 10:17:46 -0800988 void VisitAdd(HAdd* add) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700989 HInstruction* right = add->GetRight();
990 if (right->IsIntConstant()) {
991 ValueRange* left_range = LookupValueRange(add->GetLeft(), add->GetBlock());
992 if (left_range == nullptr) {
993 return;
994 }
995 ValueRange* range = left_range->Add(right->AsIntConstant()->GetValue());
996 if (range != nullptr) {
Aart Bik1d239822016-02-09 14:26:34 -0800997 AssignRange(add->GetBlock(), add, range);
Mingyao Yangf384f882014-10-22 16:08:18 -0700998 }
999 }
1000 }
1001
Aart Bik4a342772015-11-30 10:17:46 -08001002 void VisitSub(HSub* sub) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -07001003 HInstruction* left = sub->GetLeft();
1004 HInstruction* right = sub->GetRight();
1005 if (right->IsIntConstant()) {
1006 ValueRange* left_range = LookupValueRange(left, sub->GetBlock());
1007 if (left_range == nullptr) {
1008 return;
1009 }
1010 ValueRange* range = left_range->Add(-right->AsIntConstant()->GetValue());
1011 if (range != nullptr) {
Aart Bik1d239822016-02-09 14:26:34 -08001012 AssignRange(sub->GetBlock(), sub, range);
Mingyao Yangf384f882014-10-22 16:08:18 -07001013 return;
1014 }
1015 }
1016
1017 // Here we are interested in the typical triangular case of nested loops,
1018 // such as the inner loop 'for (int j=0; j<array.length-i; j++)' where i
1019 // 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 -08001020
1021 // Try to handle (array.length - i) or (array.length + c - i) format.
1022 HInstruction* left_of_left; // left input of left.
1023 int32_t right_const = 0;
1024 if (ValueBound::IsAddOrSubAConstant(left, &left_of_left, &right_const)) {
1025 left = left_of_left;
1026 }
1027 // The value of left input of the sub equals (left + right_const).
1028
Mingyao Yangf384f882014-10-22 16:08:18 -07001029 if (left->IsArrayLength()) {
1030 HInstruction* array_length = left->AsArrayLength();
1031 ValueRange* right_range = LookupValueRange(right, sub->GetBlock());
1032 if (right_range != nullptr) {
1033 ValueBound lower = right_range->GetLower();
1034 ValueBound upper = right_range->GetUpper();
Mingyao Yang0304e182015-01-30 16:41:29 -08001035 if (lower.IsConstant() && upper.IsRelatedToArrayLength()) {
Mingyao Yangf384f882014-10-22 16:08:18 -07001036 HInstruction* upper_inst = upper.GetInstruction();
Mingyao Yang0304e182015-01-30 16:41:29 -08001037 // Make sure it's the same array.
1038 if (ValueBound::Equal(array_length, upper_inst)) {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001039 int32_t c0 = right_const;
1040 int32_t c1 = lower.GetConstant();
1041 int32_t c2 = upper.GetConstant();
1042 // (array.length + c0 - v) where v is in [c1, array.length + c2]
1043 // gets [c0 - c2, array.length + c0 - c1] as its value range.
1044 if (!ValueBound::WouldAddOverflowOrUnderflow(c0, -c2) &&
1045 !ValueBound::WouldAddOverflowOrUnderflow(c0, -c1)) {
1046 if ((c0 - c1) <= 0) {
1047 // array.length + (c0 - c1) won't overflow/underflow.
Vladimir Marko009d1662017-10-10 13:21:15 +01001048 ValueRange* range = new (&allocator_) ValueRange(
1049 &allocator_,
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001050 ValueBound(nullptr, right_const - upper.GetConstant()),
1051 ValueBound(array_length, right_const - lower.GetConstant()));
Aart Bik1d239822016-02-09 14:26:34 -08001052 AssignRange(sub->GetBlock(), sub, range);
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001053 }
1054 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001055 }
1056 }
1057 }
1058 }
1059 }
1060
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001061 void FindAndHandlePartialArrayLength(HBinaryOperation* instruction) {
1062 DCHECK(instruction->IsDiv() || instruction->IsShr() || instruction->IsUShr());
1063 HInstruction* right = instruction->GetRight();
1064 int32_t right_const;
1065 if (right->IsIntConstant()) {
1066 right_const = right->AsIntConstant()->GetValue();
1067 // Detect division by two or more.
1068 if ((instruction->IsDiv() && right_const <= 1) ||
1069 (instruction->IsShr() && right_const < 1) ||
1070 (instruction->IsUShr() && right_const < 1)) {
1071 return;
1072 }
1073 } else {
1074 return;
1075 }
1076
1077 // Try to handle array.length/2 or (array.length-1)/2 format.
1078 HInstruction* left = instruction->GetLeft();
1079 HInstruction* left_of_left; // left input of left.
1080 int32_t c = 0;
1081 if (ValueBound::IsAddOrSubAConstant(left, &left_of_left, &c)) {
1082 left = left_of_left;
1083 }
1084 // The value of left input of instruction equals (left + c).
1085
1086 // (array_length + 1) or smaller divided by two or more
Aart Bikaab5b752015-09-23 11:18:57 -07001087 // always generate a value in [Min(), array_length].
1088 // This is true even if array_length is Max().
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001089 if (left->IsArrayLength() && c <= 1) {
1090 if (instruction->IsUShr() && c < 0) {
1091 // Make sure for unsigned shift, left side is not negative.
1092 // e.g. if array_length is 2, ((array_length - 3) >>> 2) is way bigger
1093 // than array_length.
1094 return;
1095 }
Vladimir Marko009d1662017-10-10 13:21:15 +01001096 ValueRange* range = new (&allocator_) ValueRange(
1097 &allocator_,
Aart Bikaab5b752015-09-23 11:18:57 -07001098 ValueBound(nullptr, std::numeric_limits<int32_t>::min()),
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001099 ValueBound(left, 0));
Aart Bik1d239822016-02-09 14:26:34 -08001100 AssignRange(instruction->GetBlock(), instruction, range);
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001101 }
1102 }
1103
Aart Bik4a342772015-11-30 10:17:46 -08001104 void VisitDiv(HDiv* div) OVERRIDE {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001105 FindAndHandlePartialArrayLength(div);
1106 }
1107
Aart Bik4a342772015-11-30 10:17:46 -08001108 void VisitShr(HShr* shr) OVERRIDE {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001109 FindAndHandlePartialArrayLength(shr);
1110 }
1111
Aart Bik4a342772015-11-30 10:17:46 -08001112 void VisitUShr(HUShr* ushr) OVERRIDE {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001113 FindAndHandlePartialArrayLength(ushr);
1114 }
1115
Aart Bik4a342772015-11-30 10:17:46 -08001116 void VisitAnd(HAnd* instruction) OVERRIDE {
Mingyao Yang4559f002015-02-27 14:43:53 -08001117 if (instruction->GetRight()->IsIntConstant()) {
1118 int32_t constant = instruction->GetRight()->AsIntConstant()->GetValue();
1119 if (constant > 0) {
1120 // constant serves as a mask so any number masked with it
1121 // gets a [0, constant] value range.
Vladimir Marko009d1662017-10-10 13:21:15 +01001122 ValueRange* range = new (&allocator_) ValueRange(
1123 &allocator_,
Mingyao Yang4559f002015-02-27 14:43:53 -08001124 ValueBound(nullptr, 0),
1125 ValueBound(nullptr, constant));
Aart Bik1d239822016-02-09 14:26:34 -08001126 AssignRange(instruction->GetBlock(), instruction, range);
Mingyao Yang4559f002015-02-27 14:43:53 -08001127 }
1128 }
1129 }
1130
xueliang.zhonga22cae72017-06-26 17:49:48 +01001131 void VisitRem(HRem* instruction) OVERRIDE {
1132 HInstruction* left = instruction->GetLeft();
1133 HInstruction* right = instruction->GetRight();
1134
1135 // Handle 'i % CONST' format expression in array index, e.g:
1136 // array[i % 20];
1137 if (right->IsIntConstant()) {
1138 int32_t right_const = std::abs(right->AsIntConstant()->GetValue());
1139 if (right_const == 0) {
1140 return;
1141 }
1142 // The sign of divisor CONST doesn't affect the sign final value range.
1143 // For example:
1144 // if (i > 0) {
1145 // array[i % 10]; // index value range [0, 9]
1146 // array[i % -10]; // index value range [0, 9]
1147 // }
Vladimir Marko009d1662017-10-10 13:21:15 +01001148 ValueRange* right_range = new (&allocator_) ValueRange(
1149 &allocator_,
xueliang.zhonga22cae72017-06-26 17:49:48 +01001150 ValueBound(nullptr, 1 - right_const),
1151 ValueBound(nullptr, right_const - 1));
1152
Aart Bikbae9c9a2017-09-11 14:51:54 -07001153 ValueRange* left_range = LookupValueRange(left, instruction->GetBlock());
xueliang.zhonga22cae72017-06-26 17:49:48 +01001154 if (left_range != nullptr) {
Aart Bikbae9c9a2017-09-11 14:51:54 -07001155 right_range = right_range->Narrow(left_range);
xueliang.zhonga22cae72017-06-26 17:49:48 +01001156 }
1157 AssignRange(instruction->GetBlock(), instruction, right_range);
1158 return;
1159 }
1160
1161 // Handle following pattern:
1162 // i0 NullCheck
1163 // i1 ArrayLength[i0]
1164 // i2 DivByZeroCheck [i1] <-- right
1165 // i3 Rem [i5, i2] <-- we are here.
1166 // i4 BoundsCheck [i3,i1]
1167 if (right->IsDivZeroCheck()) {
1168 // if array_length can pass div-by-zero check,
1169 // array_length must be > 0.
1170 right = right->AsDivZeroCheck()->InputAt(0);
1171 }
1172
1173 // Handle 'i % array.length' format expression in array index, e.g:
1174 // array[(i+7) % array.length];
1175 if (right->IsArrayLength()) {
1176 ValueBound lower = ValueBound::Min(); // ideally, lower should be '1-array_length'.
1177 ValueBound upper = ValueBound(right, -1); // array_length - 1
Vladimir Marko009d1662017-10-10 13:21:15 +01001178 ValueRange* right_range = new (&allocator_) ValueRange(
1179 &allocator_,
xueliang.zhonga22cae72017-06-26 17:49:48 +01001180 lower,
1181 upper);
Aart Bikbae9c9a2017-09-11 14:51:54 -07001182 ValueRange* left_range = LookupValueRange(left, instruction->GetBlock());
xueliang.zhonga22cae72017-06-26 17:49:48 +01001183 if (left_range != nullptr) {
Aart Bikbae9c9a2017-09-11 14:51:54 -07001184 right_range = right_range->Narrow(left_range);
xueliang.zhonga22cae72017-06-26 17:49:48 +01001185 }
1186 AssignRange(instruction->GetBlock(), instruction, right_range);
1187 return;
1188 }
1189 }
1190
Aart Bik4a342772015-11-30 10:17:46 -08001191 void VisitNewArray(HNewArray* new_array) OVERRIDE {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00001192 HInstruction* len = new_array->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -08001193 if (!len->IsIntConstant()) {
1194 HInstruction *left;
1195 int32_t right_const;
1196 if (ValueBound::IsAddOrSubAConstant(len, &left, &right_const)) {
1197 // (left + right_const) is used as size to new the array.
1198 // We record "-right_const <= left <= new_array - right_const";
1199 ValueBound lower = ValueBound(nullptr, -right_const);
1200 // We use new_array for the bound instead of new_array.length,
1201 // which isn't available as an instruction yet. new_array will
1202 // be treated the same as new_array.length when it's used in a ValueBound.
1203 ValueBound upper = ValueBound(new_array, -right_const);
Vladimir Marko009d1662017-10-10 13:21:15 +01001204 ValueRange* range = new (&allocator_) ValueRange(&allocator_, lower, upper);
Nicolas Geoffraya09ff9c2015-06-24 10:38:27 +01001205 ValueRange* existing_range = LookupValueRange(left, new_array->GetBlock());
1206 if (existing_range != nullptr) {
1207 range = existing_range->Narrow(range);
1208 }
Aart Bik1d239822016-02-09 14:26:34 -08001209 AssignRange(new_array->GetBlock(), left, range);
Mingyao Yang0304e182015-01-30 16:41:29 -08001210 }
1211 }
1212 }
1213
Aart Bik4a342772015-11-30 10:17:46 -08001214 /**
1215 * After null/bounds checks are eliminated, some invariant array references
1216 * may be exposed underneath which can be hoisted out of the loop to the
1217 * preheader or, in combination with dynamic bce, the deoptimization block.
1218 *
1219 * for (int i = 0; i < n; i++) {
1220 * <-------+
1221 * for (int j = 0; j < n; j++) |
1222 * a[i][j] = 0; --a[i]--+
1223 * }
1224 *
Aart Bik1d239822016-02-09 14:26:34 -08001225 * Note: this optimization is no longer applied after dominator-based dynamic deoptimization
1226 * has occurred (see AddCompareWithDeoptimization()), since in those cases it would be
1227 * unsafe to hoist array references across their deoptimization instruction inside a loop.
Aart Bik4a342772015-11-30 10:17:46 -08001228 */
1229 void VisitArrayGet(HArrayGet* array_get) OVERRIDE {
Aart Bik1d239822016-02-09 14:26:34 -08001230 if (!has_dom_based_dynamic_bce_ && array_get->IsInLoop()) {
Aart Bik4a342772015-11-30 10:17:46 -08001231 HLoopInformation* loop = array_get->GetBlock()->GetLoopInformation();
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001232 if (loop->IsDefinedOutOfTheLoop(array_get->InputAt(0)) &&
1233 loop->IsDefinedOutOfTheLoop(array_get->InputAt(1))) {
Aart Bik4a342772015-11-30 10:17:46 -08001234 SideEffects loop_effects = side_effects_.GetLoopEffects(loop->GetHeader());
1235 if (!array_get->GetSideEffects().MayDependOn(loop_effects)) {
Anton Shaminf89381f2016-05-16 16:44:13 +06001236 // We can hoist ArrayGet only if its execution is guaranteed on every iteration.
1237 // In other words only if array_get_bb dominates all back branches.
1238 if (loop->DominatesAllBackEdges(array_get->GetBlock())) {
1239 HoistToPreHeaderOrDeoptBlock(loop, array_get);
1240 }
Aart Bik4a342772015-11-30 10:17:46 -08001241 }
1242 }
1243 }
1244 }
1245
Aart Bik67def592016-07-14 17:19:43 -07001246 /** Performs dominator-based dynamic elimination on suitable set of bounds checks. */
Aart Bik1d239822016-02-09 14:26:34 -08001247 void AddCompareWithDeoptimization(HBasicBlock* block,
1248 HInstruction* array_length,
1249 HInstruction* base,
1250 int32_t min_c, int32_t max_c) {
1251 HBoundsCheck* bounds_check =
1252 first_index_bounds_check_map_.Get(array_length->GetId())->AsBoundsCheck();
1253 // Construct deoptimization on single or double bounds on range [base-min_c,base+max_c],
1254 // for example either for a[0]..a[3] just 3 or for a[base-1]..a[base+3] both base-1
1255 // and base+3, since we made the assumption any in between value may occur too.
Aart Bik67def592016-07-14 17:19:43 -07001256 // In code, using unsigned comparisons:
1257 // (1) constants only
1258 // if (max_c >= a.length) deoptimize;
1259 // (2) general case
1260 // if (base-min_c > base+max_c) deoptimize;
1261 // if (base+max_c >= a.length ) deoptimize;
Aart Bik1d239822016-02-09 14:26:34 -08001262 static_assert(kMaxLengthForAddingDeoptimize < std::numeric_limits<int32_t>::max(),
1263 "Incorrect max length may be subject to arithmetic wrap-around");
1264 HInstruction* upper = GetGraph()->GetIntConstant(max_c);
1265 if (base == nullptr) {
1266 DCHECK_GE(min_c, 0);
1267 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +01001268 HInstruction* lower = new (GetGraph()->GetAllocator())
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001269 HAdd(DataType::Type::kInt32, base, GetGraph()->GetIntConstant(min_c));
Vladimir Markoca6fff82017-10-03 14:49:14 +01001270 upper = new (GetGraph()->GetAllocator()) HAdd(DataType::Type::kInt32, base, upper);
Aart Bik1d239822016-02-09 14:26:34 -08001271 block->InsertInstructionBefore(lower, bounds_check);
1272 block->InsertInstructionBefore(upper, bounds_check);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001273 InsertDeoptInBlock(bounds_check, new (GetGraph()->GetAllocator()) HAbove(lower, upper));
Aart Bik1d239822016-02-09 14:26:34 -08001274 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001275 InsertDeoptInBlock(
1276 bounds_check, new (GetGraph()->GetAllocator()) HAboveOrEqual(upper, array_length));
Aart Bik1d239822016-02-09 14:26:34 -08001277 // Flag that this kind of deoptimization has occurred.
1278 has_dom_based_dynamic_bce_ = true;
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001279 }
1280
Aart Bik67def592016-07-14 17:19:43 -07001281 /** Attempts dominator-based dynamic elimination on remaining candidates. */
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001282 void AddComparesWithDeoptimization(HBasicBlock* block) {
Vladimir Markoda571cb2016-02-15 17:54:56 +00001283 for (const auto& entry : first_index_bounds_check_map_) {
1284 HBoundsCheck* bounds_check = entry.second;
Aart Bik1d239822016-02-09 14:26:34 -08001285 HInstruction* index = bounds_check->InputAt(0);
Nicolas Geoffray8df886b2015-06-24 14:57:44 +01001286 HInstruction* array_length = bounds_check->InputAt(1);
1287 if (!array_length->IsArrayLength()) {
Aart Bik1d239822016-02-09 14:26:34 -08001288 continue; // disregard phis and constants
Nicolas Geoffray8df886b2015-06-24 14:57:44 +01001289 }
Aart Bik1ae88742016-03-14 14:11:26 -07001290 // Collect all bounds checks that are still there and that are related as "a[base + constant]"
Aart Bik1d239822016-02-09 14:26:34 -08001291 // for a base instruction (possibly absent) and various constants. Note that no attempt
1292 // is made to partition the set into matching subsets (viz. a[0], a[1] and a[base+1] and
1293 // a[base+2] are considered as one set).
1294 // TODO: would such a partitioning be worthwhile?
1295 ValueBound value = ValueBound::AsValueBound(index);
1296 HInstruction* base = value.GetInstruction();
1297 int32_t min_c = base == nullptr ? 0 : value.GetConstant();
1298 int32_t max_c = value.GetConstant();
Vladimir Marko009d1662017-10-10 13:21:15 +01001299 ScopedArenaVector<HBoundsCheck*> candidates(
1300 allocator_.Adapter(kArenaAllocBoundsCheckElimination));
1301 ScopedArenaVector<HBoundsCheck*> standby(
1302 allocator_.Adapter(kArenaAllocBoundsCheckElimination));
Vladimir Marko46817b82016-03-29 12:21:58 +01001303 for (const HUseListNode<HInstruction*>& use : array_length->GetUses()) {
Aart Bik1d239822016-02-09 14:26:34 -08001304 // Another bounds check in same or dominated block?
Vladimir Marko46817b82016-03-29 12:21:58 +01001305 HInstruction* user = use.GetUser();
Aart Bik1d239822016-02-09 14:26:34 -08001306 HBasicBlock* other_block = user->GetBlock();
1307 if (user->IsBoundsCheck() && block->Dominates(other_block)) {
1308 HBoundsCheck* other_bounds_check = user->AsBoundsCheck();
1309 HInstruction* other_index = other_bounds_check->InputAt(0);
1310 HInstruction* other_array_length = other_bounds_check->InputAt(1);
1311 ValueBound other_value = ValueBound::AsValueBound(other_index);
1312 if (array_length == other_array_length && base == other_value.GetInstruction()) {
Aart Bik1ae88742016-03-14 14:11:26 -07001313 // Reject certain OOB if BoundsCheck(l, l) occurs on considered subset.
1314 if (array_length == other_index) {
1315 candidates.clear();
1316 standby.clear();
1317 break;
1318 }
Aart Bik1d239822016-02-09 14:26:34 -08001319 // Since a subsequent dominated block could be under a conditional, only accept
1320 // the other bounds check if it is in same block or both blocks dominate the exit.
1321 // TODO: we could improve this by testing proper post-dominance, or even if this
1322 // constant is seen along *all* conditional paths that follow.
1323 HBasicBlock* exit = GetGraph()->GetExitBlock();
1324 if (block == user->GetBlock() ||
1325 (block->Dominates(exit) && other_block->Dominates(exit))) {
Aart Bik1ae88742016-03-14 14:11:26 -07001326 int32_t other_c = other_value.GetConstant();
Aart Bik1d239822016-02-09 14:26:34 -08001327 min_c = std::min(min_c, other_c);
1328 max_c = std::max(max_c, other_c);
1329 candidates.push_back(other_bounds_check);
1330 } else {
1331 // Add this candidate later only if it falls into the range.
1332 standby.push_back(other_bounds_check);
1333 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001334 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001335 }
1336 }
Aart Bik1d239822016-02-09 14:26:34 -08001337 // Add standby candidates that fall in selected range.
Vladimir Markoda571cb2016-02-15 17:54:56 +00001338 for (HBoundsCheck* other_bounds_check : standby) {
Aart Bik1d239822016-02-09 14:26:34 -08001339 HInstruction* other_index = other_bounds_check->InputAt(0);
1340 int32_t other_c = ValueBound::AsValueBound(other_index).GetConstant();
1341 if (min_c <= other_c && other_c <= max_c) {
1342 candidates.push_back(other_bounds_check);
1343 }
1344 }
Aart Bik67def592016-07-14 17:19:43 -07001345 // Perform dominator-based deoptimization if it seems profitable, where we eliminate
1346 // bounds checks and replace these with deopt checks that guard against any possible
1347 // OOB. Note that we reject cases where the distance min_c:max_c range gets close to
1348 // the maximum possible array length, since those cases are likely to always deopt
1349 // (such situations do not necessarily go OOB, though, since the array could be really
1350 // large, or the programmer could rely on arithmetic wrap-around from max to min).
Aart Bik1d239822016-02-09 14:26:34 -08001351 size_t threshold = kThresholdForAddingDeoptimize + (base == nullptr ? 0 : 1); // extra test?
1352 uint32_t distance = static_cast<uint32_t>(max_c) - static_cast<uint32_t>(min_c);
1353 if (candidates.size() >= threshold &&
1354 (base != nullptr || min_c >= 0) && // reject certain OOB
1355 distance <= kMaxLengthForAddingDeoptimize) { // reject likely/certain deopt
1356 AddCompareWithDeoptimization(block, array_length, base, min_c, max_c);
Aart Bik67def592016-07-14 17:19:43 -07001357 for (HBoundsCheck* other_bounds_check : candidates) {
Aart Bik1ae88742016-03-14 14:11:26 -07001358 // Only replace if still in the graph. This avoids visiting the same
1359 // bounds check twice if it occurred multiple times in the use list.
1360 if (other_bounds_check->IsInBlock()) {
1361 ReplaceInstruction(other_bounds_check, other_bounds_check->InputAt(0));
1362 }
Aart Bik1d239822016-02-09 14:26:34 -08001363 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001364 }
1365 }
1366 }
1367
Aart Bik4a342772015-11-30 10:17:46 -08001368 /**
1369 * Returns true if static range analysis based on induction variables can determine the bounds
1370 * check on the given array range is always satisfied with the computed index range. The output
1371 * parameter try_dynamic_bce is set to false if OOB is certain.
1372 */
1373 bool InductionRangeFitsIn(ValueRange* array_range,
Aart Bik52be7e72016-06-23 11:20:41 -07001374 HBoundsCheck* context,
Aart Bik4a342772015-11-30 10:17:46 -08001375 bool* try_dynamic_bce) {
1376 InductionVarRange::Value v1;
1377 InductionVarRange::Value v2;
1378 bool needs_finite_test = false;
Aart Bik52be7e72016-06-23 11:20:41 -07001379 HInstruction* index = context->InputAt(0);
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00001380 HInstruction* hint = HuntForDeclaration(context->InputAt(1));
Aart Bik52be7e72016-06-23 11:20:41 -07001381 if (induction_range_.GetInductionRange(context, index, hint, &v1, &v2, &needs_finite_test)) {
1382 if (v1.is_known && (v1.a_constant == 0 || v1.a_constant == 1) &&
1383 v2.is_known && (v2.a_constant == 0 || v2.a_constant == 1)) {
1384 DCHECK(v1.a_constant == 1 || v1.instruction == nullptr);
1385 DCHECK(v2.a_constant == 1 || v2.instruction == nullptr);
Vladimir Marko009d1662017-10-10 13:21:15 +01001386 ValueRange index_range(&allocator_,
Aart Bik52be7e72016-06-23 11:20:41 -07001387 ValueBound(v1.instruction, v1.b_constant),
1388 ValueBound(v2.instruction, v2.b_constant));
1389 // If analysis reveals a certain OOB, disable dynamic BCE. Otherwise,
1390 // use analysis for static bce only if loop is finite.
1391 if (index_range.GetLower().LessThan(array_range->GetLower()) ||
1392 index_range.GetUpper().GreaterThan(array_range->GetUpper())) {
1393 *try_dynamic_bce = false;
1394 } else if (!needs_finite_test && index_range.FitsIn(array_range)) {
1395 return true;
Aart Bikb738d4f2015-12-03 11:23:35 -08001396 }
Aart Bik52be7e72016-06-23 11:20:41 -07001397 }
Aart Bik1fc3afb2016-02-02 13:26:16 -08001398 }
Aart Bik4a342772015-11-30 10:17:46 -08001399 return false;
1400 }
1401
1402 /**
Aart Bik67def592016-07-14 17:19:43 -07001403 * Performs loop-based dynamic elimination on a bounds check. In order to minimize the
1404 * number of eventually generated tests, related bounds checks with tests that can be
1405 * combined with tests for the given bounds check are collected first.
Aart Bik4a342772015-11-30 10:17:46 -08001406 */
Aart Bik67def592016-07-14 17:19:43 -07001407 void TransformLoopForDynamicBCE(HLoopInformation* loop, HBoundsCheck* bounds_check) {
1408 HInstruction* index = bounds_check->InputAt(0);
1409 HInstruction* array_length = bounds_check->InputAt(1);
1410 DCHECK(loop->IsDefinedOutOfTheLoop(array_length)); // pre-checked
1411 DCHECK(loop->DominatesAllBackEdges(bounds_check->GetBlock()));
1412 // Collect all bounds checks in the same loop that are related as "a[base + constant]"
1413 // for a base instruction (possibly absent) and various constants.
1414 ValueBound value = ValueBound::AsValueBound(index);
1415 HInstruction* base = value.GetInstruction();
1416 int32_t min_c = base == nullptr ? 0 : value.GetConstant();
1417 int32_t max_c = value.GetConstant();
Vladimir Marko009d1662017-10-10 13:21:15 +01001418 ScopedArenaVector<HBoundsCheck*> candidates(
1419 allocator_.Adapter(kArenaAllocBoundsCheckElimination));
1420 ScopedArenaVector<HBoundsCheck*> standby(
1421 allocator_.Adapter(kArenaAllocBoundsCheckElimination));
Aart Bik67def592016-07-14 17:19:43 -07001422 for (const HUseListNode<HInstruction*>& use : array_length->GetUses()) {
1423 HInstruction* user = use.GetUser();
1424 if (user->IsBoundsCheck() && loop == user->GetBlock()->GetLoopInformation()) {
1425 HBoundsCheck* other_bounds_check = user->AsBoundsCheck();
1426 HInstruction* other_index = other_bounds_check->InputAt(0);
1427 HInstruction* other_array_length = other_bounds_check->InputAt(1);
1428 ValueBound other_value = ValueBound::AsValueBound(other_index);
1429 int32_t other_c = other_value.GetConstant();
1430 if (array_length == other_array_length && base == other_value.GetInstruction()) {
Aart Bik12a10602016-10-18 11:35:22 -07001431 // Ensure every candidate could be picked for code generation.
1432 bool b1 = false, b2 = false;
1433 if (!induction_range_.CanGenerateRange(other_bounds_check, other_index, &b1, &b2)) {
1434 continue;
1435 }
Aart Bik67def592016-07-14 17:19:43 -07001436 // Does the current basic block dominate all back edges? If not,
1437 // add this candidate later only if it falls into the range.
1438 if (!loop->DominatesAllBackEdges(user->GetBlock())) {
1439 standby.push_back(other_bounds_check);
1440 continue;
1441 }
1442 min_c = std::min(min_c, other_c);
1443 max_c = std::max(max_c, other_c);
1444 candidates.push_back(other_bounds_check);
1445 }
Aart Bik4a342772015-11-30 10:17:46 -08001446 }
Aart Bik4a342772015-11-30 10:17:46 -08001447 }
Aart Bik67def592016-07-14 17:19:43 -07001448 // Add standby candidates that fall in selected range.
1449 for (HBoundsCheck* other_bounds_check : standby) {
1450 HInstruction* other_index = other_bounds_check->InputAt(0);
1451 int32_t other_c = ValueBound::AsValueBound(other_index).GetConstant();
1452 if (min_c <= other_c && other_c <= max_c) {
1453 candidates.push_back(other_bounds_check);
1454 }
1455 }
1456 // Perform loop-based deoptimization if it seems profitable, where we eliminate bounds
1457 // checks and replace these with deopt checks that guard against any possible OOB.
1458 DCHECK_LT(0u, candidates.size());
1459 uint32_t distance = static_cast<uint32_t>(max_c) - static_cast<uint32_t>(min_c);
1460 if ((base != nullptr || min_c >= 0) && // reject certain OOB
1461 distance <= kMaxLengthForAddingDeoptimize) { // reject likely/certain deopt
1462 HBasicBlock* block = GetPreHeader(loop, bounds_check);
1463 HInstruction* min_lower = nullptr;
1464 HInstruction* min_upper = nullptr;
1465 HInstruction* max_lower = nullptr;
1466 HInstruction* max_upper = nullptr;
1467 // Iterate over all bounds checks.
1468 for (HBoundsCheck* other_bounds_check : candidates) {
1469 // Only handle if still in the graph. This avoids visiting the same
1470 // bounds check twice if it occurred multiple times in the use list.
1471 if (other_bounds_check->IsInBlock()) {
1472 HInstruction* other_index = other_bounds_check->InputAt(0);
1473 int32_t other_c = ValueBound::AsValueBound(other_index).GetConstant();
1474 // Generate code for either the maximum or minimum. Range analysis already was queried
1475 // whether code generation on the original and, thus, related bounds check was possible.
1476 // It handles either loop invariants (lower is not set) or unit strides.
1477 if (other_c == max_c) {
Aart Bik16d3a652016-09-09 10:33:50 -07001478 induction_range_.GenerateRange(
Aart Bik67def592016-07-14 17:19:43 -07001479 other_bounds_check, other_index, GetGraph(), block, &max_lower, &max_upper);
1480 } else if (other_c == min_c && base != nullptr) {
Aart Bik16d3a652016-09-09 10:33:50 -07001481 induction_range_.GenerateRange(
Aart Bik67def592016-07-14 17:19:43 -07001482 other_bounds_check, other_index, GetGraph(), block, &min_lower, &min_upper);
1483 }
1484 ReplaceInstruction(other_bounds_check, other_index);
1485 }
1486 }
1487 // In code, using unsigned comparisons:
1488 // (1) constants only
1489 // if (max_upper >= a.length ) deoptimize;
1490 // (2) two symbolic invariants
1491 // if (min_upper > max_upper) deoptimize; unless min_c == max_c
1492 // if (max_upper >= a.length ) deoptimize;
1493 // (3) general case, unit strides (where lower would exceed upper for arithmetic wrap-around)
1494 // if (min_lower > max_lower) deoptimize; unless min_c == max_c
1495 // if (max_lower > max_upper) deoptimize;
1496 // if (max_upper >= a.length ) deoptimize;
1497 if (base == nullptr) {
1498 // Constants only.
1499 DCHECK_GE(min_c, 0);
1500 DCHECK(min_lower == nullptr && min_upper == nullptr &&
1501 max_lower == nullptr && max_upper != nullptr);
1502 } else if (max_lower == nullptr) {
1503 // Two symbolic invariants.
1504 if (min_c != max_c) {
1505 DCHECK(min_lower == nullptr && min_upper != nullptr &&
1506 max_lower == nullptr && max_upper != nullptr);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001507 InsertDeoptInLoop(
1508 loop, block, new (GetGraph()->GetAllocator()) HAbove(min_upper, max_upper));
Aart Bik67def592016-07-14 17:19:43 -07001509 } else {
1510 DCHECK(min_lower == nullptr && min_upper == nullptr &&
1511 max_lower == nullptr && max_upper != nullptr);
1512 }
1513 } else {
1514 // General case, unit strides.
1515 if (min_c != max_c) {
1516 DCHECK(min_lower != nullptr && min_upper != nullptr &&
1517 max_lower != nullptr && max_upper != nullptr);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001518 InsertDeoptInLoop(
1519 loop, block, new (GetGraph()->GetAllocator()) HAbove(min_lower, max_lower));
Aart Bik67def592016-07-14 17:19:43 -07001520 } else {
1521 DCHECK(min_lower == nullptr && min_upper == nullptr &&
1522 max_lower != nullptr && max_upper != nullptr);
1523 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001524 InsertDeoptInLoop(
1525 loop, block, new (GetGraph()->GetAllocator()) HAbove(max_lower, max_upper));
Aart Bik67def592016-07-14 17:19:43 -07001526 }
1527 InsertDeoptInLoop(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001528 loop, block, new (GetGraph()->GetAllocator()) HAboveOrEqual(max_upper, array_length));
Aart Bik67def592016-07-14 17:19:43 -07001529 } else {
1530 // TODO: if rejected, avoid doing this again for subsequent instructions in this set?
1531 }
Aart Bik4a342772015-11-30 10:17:46 -08001532 }
1533
1534 /**
1535 * Returns true if heuristics indicate that dynamic bce may be profitable.
1536 */
1537 bool DynamicBCESeemsProfitable(HLoopInformation* loop, HBasicBlock* block) {
1538 if (loop != nullptr) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001539 // The loop preheader of an irreducible loop does not dominate all the blocks in
1540 // the loop. We would need to find the common dominator of all blocks in the loop.
1541 if (loop->IsIrreducible()) {
1542 return false;
1543 }
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001544 // We should never deoptimize from an osr method, otherwise we might wrongly optimize
1545 // code dominated by the deoptimization.
1546 if (GetGraph()->IsCompilingOsr()) {
1547 return false;
1548 }
Aart Bik4a342772015-11-30 10:17:46 -08001549 // A try boundary preheader is hard to handle.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001550 // TODO: remove this restriction.
Aart Bik4a342772015-11-30 10:17:46 -08001551 if (loop->GetPreHeader()->GetLastInstruction()->IsTryBoundary()) {
1552 return false;
1553 }
1554 // Does loop have early-exits? If so, the full range may not be covered by the loop
1555 // at runtime and testing the range may apply deoptimization unnecessarily.
1556 if (IsEarlyExitLoop(loop)) {
1557 return false;
1558 }
1559 // Does the current basic block dominate all back edges? If not,
1560 // don't apply dynamic bce to something that may not be executed.
Anton Shaminf89381f2016-05-16 16:44:13 +06001561 return loop->DominatesAllBackEdges(block);
Aart Bik4a342772015-11-30 10:17:46 -08001562 }
1563 return false;
1564 }
1565
1566 /**
1567 * Returns true if the loop has early exits, which implies it may not cover
1568 * the full range computed by range analysis based on induction variables.
1569 */
1570 bool IsEarlyExitLoop(HLoopInformation* loop) {
1571 const uint32_t loop_id = loop->GetHeader()->GetBlockId();
1572 // If loop has been analyzed earlier for early-exit, don't repeat the analysis.
1573 auto it = early_exit_loop_.find(loop_id);
1574 if (it != early_exit_loop_.end()) {
1575 return it->second;
1576 }
1577 // First time early-exit analysis for this loop. Since analysis requires scanning
1578 // the full loop-body, results of the analysis is stored for subsequent queries.
1579 HBlocksInLoopReversePostOrderIterator it_loop(*loop);
1580 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
1581 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
1582 if (!loop->Contains(*successor)) {
1583 early_exit_loop_.Put(loop_id, true);
1584 return true;
1585 }
1586 }
1587 }
1588 early_exit_loop_.Put(loop_id, false);
1589 return false;
1590 }
1591
1592 /**
1593 * Returns true if the array length is already loop invariant, or can be made so
1594 * by handling the null check under the hood of the array length operation.
1595 */
1596 bool CanHandleLength(HLoopInformation* loop, HInstruction* length, bool needs_taken_test) {
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001597 if (loop->IsDefinedOutOfTheLoop(length)) {
Aart Bik4a342772015-11-30 10:17:46 -08001598 return true;
1599 } else if (length->IsArrayLength() && length->GetBlock()->GetLoopInformation() == loop) {
1600 if (CanHandleNullCheck(loop, length->InputAt(0), needs_taken_test)) {
Aart Bik55b14df2016-01-12 14:12:47 -08001601 HoistToPreHeaderOrDeoptBlock(loop, length);
Aart Bik4a342772015-11-30 10:17:46 -08001602 return true;
1603 }
1604 }
1605 return false;
1606 }
1607
1608 /**
1609 * Returns true if the null check is already loop invariant, or can be made so
1610 * by generating a deoptimization test.
1611 */
1612 bool CanHandleNullCheck(HLoopInformation* loop, HInstruction* check, bool needs_taken_test) {
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001613 if (loop->IsDefinedOutOfTheLoop(check)) {
Aart Bik4a342772015-11-30 10:17:46 -08001614 return true;
1615 } else if (check->IsNullCheck() && check->GetBlock()->GetLoopInformation() == loop) {
1616 HInstruction* array = check->InputAt(0);
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001617 if (loop->IsDefinedOutOfTheLoop(array)) {
Aart Bik4a342772015-11-30 10:17:46 -08001618 // Generate: if (array == null) deoptimize;
Aart Bik55b14df2016-01-12 14:12:47 -08001619 TransformLoopForDeoptimizationIfNeeded(loop, needs_taken_test);
1620 HBasicBlock* block = GetPreHeader(loop, check);
Aart Bik4a342772015-11-30 10:17:46 -08001621 HInstruction* cond =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001622 new (GetGraph()->GetAllocator()) HEqual(array, GetGraph()->GetNullConstant());
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001623 InsertDeoptInLoop(loop, block, cond, /* is_null_check */ true);
Aart Bik4a342772015-11-30 10:17:46 -08001624 ReplaceInstruction(check, array);
1625 return true;
1626 }
1627 }
1628 return false;
1629 }
1630
1631 /**
1632 * Returns true if compiler can apply dynamic bce to loops that may be infinite
1633 * (e.g. for (int i = 0; i <= U; i++) with U = MAX_INT), which would invalidate
1634 * the range analysis evaluation code by "overshooting" the computed range.
1635 * Since deoptimization would be a bad choice, and there is no other version
1636 * of the loop to use, dynamic bce in such cases is only allowed if other tests
1637 * ensure the loop is finite.
1638 */
Aart Bik67def592016-07-14 17:19:43 -07001639 bool CanHandleInfiniteLoop(HLoopInformation* loop, HInstruction* index, bool needs_infinite_test) {
Aart Bik4a342772015-11-30 10:17:46 -08001640 if (needs_infinite_test) {
1641 // If we already forced the loop to be finite, allow directly.
1642 const uint32_t loop_id = loop->GetHeader()->GetBlockId();
1643 if (finite_loop_.find(loop_id) != finite_loop_.end()) {
1644 return true;
1645 }
1646 // Otherwise, allow dynamic bce if the index (which is necessarily an induction at
1647 // this point) is the direct loop index (viz. a[i]), since then the runtime tests
1648 // ensure upper bound cannot cause an infinite loop.
1649 HInstruction* control = loop->GetHeader()->GetLastInstruction();
1650 if (control->IsIf()) {
1651 HInstruction* if_expr = control->AsIf()->InputAt(0);
1652 if (if_expr->IsCondition()) {
1653 HCondition* condition = if_expr->AsCondition();
1654 if (index == condition->InputAt(0) ||
1655 index == condition->InputAt(1)) {
1656 finite_loop_.insert(loop_id);
1657 return true;
1658 }
1659 }
1660 }
1661 return false;
1662 }
1663 return true;
1664 }
1665
Aart Bik55b14df2016-01-12 14:12:47 -08001666 /**
1667 * Returns appropriate preheader for the loop, depending on whether the
1668 * instruction appears in the loop header or proper loop-body.
1669 */
1670 HBasicBlock* GetPreHeader(HLoopInformation* loop, HInstruction* instruction) {
1671 // Use preheader unless there is an earlier generated deoptimization block since
1672 // hoisted expressions may depend on and/or used by the deoptimization tests.
1673 HBasicBlock* header = loop->GetHeader();
1674 const uint32_t loop_id = header->GetBlockId();
1675 auto it = taken_test_loop_.find(loop_id);
1676 if (it != taken_test_loop_.end()) {
1677 HBasicBlock* block = it->second;
1678 // If always taken, keep it that way by returning the original preheader,
1679 // which can be found by following the predecessor of the true-block twice.
1680 if (instruction->GetBlock() == header) {
1681 return block->GetSinglePredecessor()->GetSinglePredecessor();
1682 }
1683 return block;
1684 }
1685 return loop->GetPreHeader();
1686 }
1687
Aart Bik1d239822016-02-09 14:26:34 -08001688 /** Inserts a deoptimization test in a loop preheader. */
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001689 void InsertDeoptInLoop(HLoopInformation* loop,
1690 HBasicBlock* block,
1691 HInstruction* condition,
1692 bool is_null_check = false) {
Aart Bik4a342772015-11-30 10:17:46 -08001693 HInstruction* suspend = loop->GetSuspendCheck();
1694 block->InsertInstructionBefore(condition, block->GetLastInstruction());
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001695 DeoptimizationKind kind =
1696 is_null_check ? DeoptimizationKind::kLoopNullBCE : DeoptimizationKind::kLoopBoundsBCE;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001697 HDeoptimize* deoptimize = new (GetGraph()->GetAllocator()) HDeoptimize(
1698 GetGraph()->GetAllocator(), condition, kind, suspend->GetDexPc());
Aart Bik4a342772015-11-30 10:17:46 -08001699 block->InsertInstructionBefore(deoptimize, block->GetLastInstruction());
1700 if (suspend->HasEnvironment()) {
1701 deoptimize->CopyEnvironmentFromWithLoopPhiAdjustment(
1702 suspend->GetEnvironment(), loop->GetHeader());
1703 }
1704 }
1705
Aart Bik1d239822016-02-09 14:26:34 -08001706 /** Inserts a deoptimization test right before a bounds check. */
1707 void InsertDeoptInBlock(HBoundsCheck* bounds_check, HInstruction* condition) {
1708 HBasicBlock* block = bounds_check->GetBlock();
1709 block->InsertInstructionBefore(condition, bounds_check);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001710 HDeoptimize* deoptimize = new (GetGraph()->GetAllocator()) HDeoptimize(
1711 GetGraph()->GetAllocator(),
1712 condition,
1713 DeoptimizationKind::kBlockBCE,
1714 bounds_check->GetDexPc());
Aart Bik1d239822016-02-09 14:26:34 -08001715 block->InsertInstructionBefore(deoptimize, bounds_check);
1716 deoptimize->CopyEnvironmentFrom(bounds_check->GetEnvironment());
1717 }
1718
Aart Bik4a342772015-11-30 10:17:46 -08001719 /** Hoists instruction out of the loop to preheader or deoptimization block. */
Aart Bik55b14df2016-01-12 14:12:47 -08001720 void HoistToPreHeaderOrDeoptBlock(HLoopInformation* loop, HInstruction* instruction) {
1721 HBasicBlock* block = GetPreHeader(loop, instruction);
Aart Bik4a342772015-11-30 10:17:46 -08001722 DCHECK(!instruction->HasEnvironment());
1723 instruction->MoveBefore(block->GetLastInstruction());
1724 }
1725
1726 /**
Aart Bik55b14df2016-01-12 14:12:47 -08001727 * Adds a new taken-test structure to a loop if needed and not already done.
Aart Bik4a342772015-11-30 10:17:46 -08001728 * The taken-test protects range analysis evaluation code to avoid any
1729 * deoptimization caused by incorrect trip-count evaluation in non-taken loops.
1730 *
Aart Bik4a342772015-11-30 10:17:46 -08001731 * old_preheader
1732 * |
1733 * if_block <- taken-test protects deoptimization block
1734 * / \
1735 * true_block false_block <- deoptimizations/invariants are placed in true_block
1736 * \ /
1737 * new_preheader <- may require phi nodes to preserve SSA structure
1738 * |
1739 * header
1740 *
1741 * For example, this loop:
1742 *
1743 * for (int i = lower; i < upper; i++) {
1744 * array[i] = 0;
1745 * }
1746 *
1747 * will be transformed to:
1748 *
1749 * if (lower < upper) {
1750 * if (array == null) deoptimize;
1751 * array_length = array.length;
1752 * if (lower > upper) deoptimize; // unsigned
1753 * if (upper >= array_length) deoptimize; // unsigned
1754 * } else {
1755 * array_length = 0;
1756 * }
1757 * for (int i = lower; i < upper; i++) {
1758 * // Loop without null check and bounds check, and any array.length replaced with array_length.
1759 * array[i] = 0;
1760 * }
1761 */
Aart Bik55b14df2016-01-12 14:12:47 -08001762 void TransformLoopForDeoptimizationIfNeeded(HLoopInformation* loop, bool needs_taken_test) {
1763 // Not needed (can use preheader) or already done (can reuse)?
Aart Bik4a342772015-11-30 10:17:46 -08001764 const uint32_t loop_id = loop->GetHeader()->GetBlockId();
Aart Bik55b14df2016-01-12 14:12:47 -08001765 if (!needs_taken_test || taken_test_loop_.find(loop_id) != taken_test_loop_.end()) {
1766 return;
Aart Bik4a342772015-11-30 10:17:46 -08001767 }
1768
1769 // Generate top test structure.
1770 HBasicBlock* header = loop->GetHeader();
1771 GetGraph()->TransformLoopHeaderForBCE(header);
1772 HBasicBlock* new_preheader = loop->GetPreHeader();
1773 HBasicBlock* if_block = new_preheader->GetDominator();
1774 HBasicBlock* true_block = if_block->GetSuccessors()[0]; // True successor.
1775 HBasicBlock* false_block = if_block->GetSuccessors()[1]; // False successor.
1776
1777 // Goto instructions.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001778 true_block->AddInstruction(new (GetGraph()->GetAllocator()) HGoto());
1779 false_block->AddInstruction(new (GetGraph()->GetAllocator()) HGoto());
1780 new_preheader->AddInstruction(new (GetGraph()->GetAllocator()) HGoto());
Aart Bik4a342772015-11-30 10:17:46 -08001781
1782 // Insert the taken-test to see if the loop body is entered. If the
1783 // loop isn't entered at all, it jumps around the deoptimization block.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001784 if_block->AddInstruction(new (GetGraph()->GetAllocator()) HGoto()); // placeholder
Aart Bik16d3a652016-09-09 10:33:50 -07001785 HInstruction* condition = induction_range_.GenerateTakenTest(
1786 header->GetLastInstruction(), GetGraph(), if_block);
Aart Bik4a342772015-11-30 10:17:46 -08001787 DCHECK(condition != nullptr);
1788 if_block->RemoveInstruction(if_block->GetLastInstruction());
Vladimir Markoca6fff82017-10-03 14:49:14 +01001789 if_block->AddInstruction(new (GetGraph()->GetAllocator()) HIf(condition));
Aart Bik4a342772015-11-30 10:17:46 -08001790
1791 taken_test_loop_.Put(loop_id, true_block);
Aart Bik4a342772015-11-30 10:17:46 -08001792 }
1793
1794 /**
1795 * Inserts phi nodes that preserve SSA structure in generated top test structures.
1796 * All uses of instructions in the deoptimization block that reach the loop need
1797 * a phi node in the new loop preheader to fix the dominance relation.
1798 *
1799 * Example:
1800 * if_block
1801 * / \
1802 * x_0 = .. false_block
1803 * \ /
1804 * x_1 = phi(x_0, null) <- synthetic phi
1805 * |
Aart Bik55b14df2016-01-12 14:12:47 -08001806 * new_preheader
Aart Bik4a342772015-11-30 10:17:46 -08001807 */
1808 void InsertPhiNodes() {
1809 // Scan all new deoptimization blocks.
Vladimir Marko7d157fc2017-05-10 16:29:23 +01001810 for (const auto& entry : taken_test_loop_) {
1811 HBasicBlock* true_block = entry.second;
Aart Bik4a342772015-11-30 10:17:46 -08001812 HBasicBlock* new_preheader = true_block->GetSingleSuccessor();
1813 // Scan all instructions in a new deoptimization block.
1814 for (HInstructionIterator it(true_block->GetInstructions()); !it.Done(); it.Advance()) {
1815 HInstruction* instruction = it.Current();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001816 DataType::Type type = instruction->GetType();
Aart Bik4a342772015-11-30 10:17:46 -08001817 HPhi* phi = nullptr;
1818 // Scan all uses of an instruction and replace each later use with a phi node.
Vladimir Marko46817b82016-03-29 12:21:58 +01001819 const HUseList<HInstruction*>& uses = instruction->GetUses();
1820 for (auto it2 = uses.begin(), end2 = uses.end(); it2 != end2; /* ++it2 below */) {
1821 HInstruction* user = it2->GetUser();
1822 size_t index = it2->GetIndex();
1823 // Increment `it2` now because `*it2` may disappear thanks to user->ReplaceInput().
1824 ++it2;
Aart Bik4a342772015-11-30 10:17:46 -08001825 if (user->GetBlock() != true_block) {
1826 if (phi == nullptr) {
1827 phi = NewPhi(new_preheader, instruction, type);
1828 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001829 user->ReplaceInput(phi, index); // Removes the use node from the list.
Aart Bike22445f2017-05-03 14:29:20 -07001830 induction_range_.Replace(user, instruction, phi); // update induction
Aart Bik4a342772015-11-30 10:17:46 -08001831 }
1832 }
1833 // Scan all environment uses of an instruction and replace each later use with a phi node.
Vladimir Marko46817b82016-03-29 12:21:58 +01001834 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1835 for (auto it2 = env_uses.begin(), end2 = env_uses.end(); it2 != end2; /* ++it2 below */) {
1836 HEnvironment* user = it2->GetUser();
1837 size_t index = it2->GetIndex();
1838 // Increment `it2` now because `*it2` may disappear thanks to user->RemoveAsUserOfInput().
1839 ++it2;
Aart Bik4a342772015-11-30 10:17:46 -08001840 if (user->GetHolder()->GetBlock() != true_block) {
1841 if (phi == nullptr) {
1842 phi = NewPhi(new_preheader, instruction, type);
1843 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001844 user->RemoveAsUserOfInput(index);
1845 user->SetRawEnvAt(index, phi);
1846 phi->AddEnvUseAt(user, index);
Aart Bik4a342772015-11-30 10:17:46 -08001847 }
1848 }
1849 }
1850 }
1851 }
1852
1853 /**
1854 * Construct a phi(instruction, 0) in the new preheader to fix the dominance relation.
1855 * These are synthetic phi nodes without a virtual register.
1856 */
1857 HPhi* NewPhi(HBasicBlock* new_preheader,
1858 HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001859 DataType::Type type) {
Aart Bik4a342772015-11-30 10:17:46 -08001860 HGraph* graph = GetGraph();
1861 HInstruction* zero;
1862 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001863 case DataType::Type::kReference: zero = graph->GetNullConstant(); break;
1864 case DataType::Type::kFloat32: zero = graph->GetFloatConstant(0); break;
1865 case DataType::Type::kFloat64: zero = graph->GetDoubleConstant(0); break;
Aart Bik4a342772015-11-30 10:17:46 -08001866 default: zero = graph->GetConstant(type, 0); break;
1867 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001868 HPhi* phi = new (graph->GetAllocator())
1869 HPhi(graph->GetAllocator(), kNoRegNumber, /*number_of_inputs*/ 2, HPhi::ToPhiType(type));
Aart Bik4a342772015-11-30 10:17:46 -08001870 phi->SetRawInputAt(0, instruction);
1871 phi->SetRawInputAt(1, zero);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001872 if (type == DataType::Type::kReference) {
David Brazdil4833f5a2015-12-16 10:37:39 +00001873 phi->SetReferenceTypeInfo(instruction->GetReferenceTypeInfo());
1874 }
Aart Bik4a342772015-11-30 10:17:46 -08001875 new_preheader->AddPhi(phi);
1876 return phi;
1877 }
1878
1879 /** Helper method to replace an instruction with another instruction. */
Aart Bik1e677482016-11-01 14:23:58 -07001880 void ReplaceInstruction(HInstruction* instruction, HInstruction* replacement) {
1881 // Safe iteration.
1882 if (instruction == next_) {
1883 next_ = next_->GetNext();
1884 }
1885 // Replace and remove.
Aart Bik4a342772015-11-30 10:17:46 -08001886 instruction->ReplaceWith(replacement);
1887 instruction->GetBlock()->RemoveInstruction(instruction);
1888 }
1889
Vladimir Marko009d1662017-10-10 13:21:15 +01001890 // Use local allocator for allocating memory.
1891 ScopedArenaAllocator allocator_;
1892
Aart Bik4a342772015-11-30 10:17:46 -08001893 // A set of maps, one per basic block, from instruction to range.
Vladimir Marko009d1662017-10-10 13:21:15 +01001894 ScopedArenaVector<ScopedArenaSafeMap<int, ValueRange*>> maps_;
Mingyao Yangf384f882014-10-22 16:08:18 -07001895
Aart Bik1d239822016-02-09 14:26:34 -08001896 // Map an HArrayLength instruction's id to the first HBoundsCheck instruction
1897 // in a block that checks an index against that HArrayLength.
Vladimir Marko009d1662017-10-10 13:21:15 +01001898 ScopedArenaSafeMap<int, HBoundsCheck*> first_index_bounds_check_map_;
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001899
Aart Bik4a342772015-11-30 10:17:46 -08001900 // Early-exit loop bookkeeping.
Vladimir Marko009d1662017-10-10 13:21:15 +01001901 ScopedArenaSafeMap<uint32_t, bool> early_exit_loop_;
Aart Bik4a342772015-11-30 10:17:46 -08001902
1903 // Taken-test loop bookkeeping.
Vladimir Marko009d1662017-10-10 13:21:15 +01001904 ScopedArenaSafeMap<uint32_t, HBasicBlock*> taken_test_loop_;
Aart Bik4a342772015-11-30 10:17:46 -08001905
1906 // Finite loop bookkeeping.
Vladimir Marko009d1662017-10-10 13:21:15 +01001907 ScopedArenaSet<uint32_t> finite_loop_;
Aart Bik4a342772015-11-30 10:17:46 -08001908
Aart Bik1d239822016-02-09 14:26:34 -08001909 // Flag that denotes whether dominator-based dynamic elimination has occurred.
1910 bool has_dom_based_dynamic_bce_;
Aart Bik4a342772015-11-30 10:17:46 -08001911
Mingyao Yang3584bce2015-05-19 16:01:59 -07001912 // Initial number of blocks.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001913 uint32_t initial_block_size_;
Mingyao Yang3584bce2015-05-19 16:01:59 -07001914
Aart Bik4a342772015-11-30 10:17:46 -08001915 // Side effects.
1916 const SideEffectsAnalysis& side_effects_;
1917
Aart Bik22af3be2015-09-10 12:50:58 -07001918 // Range analysis based on induction variables.
1919 InductionVarRange induction_range_;
1920
Aart Bik1e677482016-11-01 14:23:58 -07001921 // Safe iteration.
1922 HInstruction* next_;
1923
Mingyao Yangf384f882014-10-22 16:08:18 -07001924 DISALLOW_COPY_AND_ASSIGN(BCEVisitor);
1925};
1926
1927void BoundsCheckElimination::Run() {
Mark Mendell1152c922015-04-24 17:06:35 -04001928 if (!graph_->HasBoundsChecks()) {
Mingyao Yange4335eb2015-03-02 15:14:13 -08001929 return;
1930 }
1931
Mingyao Yangf384f882014-10-22 16:08:18 -07001932 // Reverse post order guarantees a node's dominators are visited first.
1933 // We want to visit in the dominator-based order since if a value is known to
1934 // be bounded by a range at one instruction, it must be true that all uses of
1935 // that value dominated by that instruction fits in that range. Range of that
1936 // value can be narrowed further down in the dominator tree.
Aart Bik4a342772015-11-30 10:17:46 -08001937 BCEVisitor visitor(graph_, side_effects_, induction_analysis_);
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001938 for (size_t i = 0, size = graph_->GetReversePostOrder().size(); i != size; ++i) {
1939 HBasicBlock* current = graph_->GetReversePostOrder()[i];
Mingyao Yang3584bce2015-05-19 16:01:59 -07001940 if (visitor.IsAddedBlock(current)) {
1941 // Skip added blocks. Their effects are already taken care of.
1942 continue;
1943 }
1944 visitor.VisitBasicBlock(current);
Aart Bikb6347b72016-02-29 13:56:44 -08001945 // Skip forward to the current block in case new basic blocks were inserted
1946 // (which always appear earlier in reverse post order) to avoid visiting the
1947 // same basic block twice.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001948 size_t new_size = graph_->GetReversePostOrder().size();
1949 DCHECK_GE(new_size, size);
1950 i += new_size - size;
1951 DCHECK_EQ(current, graph_->GetReversePostOrder()[i]);
1952 size = new_size;
Mingyao Yang3584bce2015-05-19 16:01:59 -07001953 }
Aart Bik4a342772015-11-30 10:17:46 -08001954
1955 // Perform cleanup.
1956 visitor.Finish();
Mingyao Yangf384f882014-10-22 16:08:18 -07001957}
1958
1959} // namespace art