blob: 1d167949f43358cea9fdf735b8f180076f1ab5c8 [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
Mathieu Chartierb666f482015-02-18 14:33:14 -080017#include "base/arena_containers.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070018#include "bounds_check_elimination.h"
19#include "nodes.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070020
21namespace art {
22
23class MonotonicValueRange;
24
25/**
26 * A value bound is represented as a pair of value and constant,
27 * e.g. array.length - 1.
28 */
29class ValueBound : public ValueObject {
30 public:
Mingyao Yang0304e182015-01-30 16:41:29 -080031 ValueBound(HInstruction* instruction, int32_t constant) {
Mingyao Yang64197522014-12-05 15:56:23 -080032 if (instruction != nullptr && instruction->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -080033 // Normalize ValueBound with constant instruction.
34 int32_t instr_const = instruction->AsIntConstant()->GetValue();
Mingyao Yang8c8bad82015-02-09 18:13:26 -080035 if (!WouldAddOverflowOrUnderflow(instr_const, constant)) {
Mingyao Yang64197522014-12-05 15:56:23 -080036 instruction_ = nullptr;
37 constant_ = instr_const + constant;
38 return;
39 }
Mingyao Yangf384f882014-10-22 16:08:18 -070040 }
Mingyao Yang64197522014-12-05 15:56:23 -080041 instruction_ = instruction;
42 constant_ = constant;
43 }
44
Mingyao Yang8c8bad82015-02-09 18:13:26 -080045 // Return whether (left + right) overflows or underflows.
46 static bool WouldAddOverflowOrUnderflow(int32_t left, int32_t right) {
47 if (right == 0) {
48 return false;
49 }
50 if ((right > 0) && (left <= INT_MAX - right)) {
51 // No overflow.
52 return false;
53 }
54 if ((right < 0) && (left >= INT_MIN - right)) {
55 // No underflow.
56 return false;
57 }
58 return true;
59 }
60
Mingyao Yang0304e182015-01-30 16:41:29 -080061 static bool IsAddOrSubAConstant(HInstruction* instruction,
62 HInstruction** left_instruction,
63 int* right_constant) {
64 if (instruction->IsAdd() || instruction->IsSub()) {
65 HBinaryOperation* bin_op = instruction->AsBinaryOperation();
66 HInstruction* left = bin_op->GetLeft();
67 HInstruction* right = bin_op->GetRight();
68 if (right->IsIntConstant()) {
69 *left_instruction = left;
70 int32_t c = right->AsIntConstant()->GetValue();
71 *right_constant = instruction->IsAdd() ? c : -c;
72 return true;
73 }
74 }
75 *left_instruction = nullptr;
76 *right_constant = 0;
77 return false;
78 }
79
Mingyao Yang64197522014-12-05 15:56:23 -080080 // Try to detect useful value bound format from an instruction, e.g.
81 // a constant or array length related value.
82 static ValueBound DetectValueBoundFromValue(HInstruction* instruction, bool* found) {
83 DCHECK(instruction != nullptr);
Mingyao Yangf384f882014-10-22 16:08:18 -070084 if (instruction->IsIntConstant()) {
Mingyao Yang64197522014-12-05 15:56:23 -080085 *found = true;
86 return ValueBound(nullptr, instruction->AsIntConstant()->GetValue());
Mingyao Yangf384f882014-10-22 16:08:18 -070087 }
Mingyao Yang64197522014-12-05 15:56:23 -080088
89 if (instruction->IsArrayLength()) {
90 *found = true;
91 return ValueBound(instruction, 0);
92 }
93 // Try to detect (array.length + c) format.
Mingyao Yang0304e182015-01-30 16:41:29 -080094 HInstruction *left;
95 int32_t right;
96 if (IsAddOrSubAConstant(instruction, &left, &right)) {
97 if (left->IsArrayLength()) {
Mingyao Yang64197522014-12-05 15:56:23 -080098 *found = true;
Mingyao Yang0304e182015-01-30 16:41:29 -080099 return ValueBound(left, right);
Mingyao Yang64197522014-12-05 15:56:23 -0800100 }
101 }
102
103 // No useful bound detected.
104 *found = false;
105 return ValueBound::Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700106 }
107
108 HInstruction* GetInstruction() const { return instruction_; }
Mingyao Yang0304e182015-01-30 16:41:29 -0800109 int32_t GetConstant() const { return constant_; }
Mingyao Yangf384f882014-10-22 16:08:18 -0700110
Mingyao Yang0304e182015-01-30 16:41:29 -0800111 bool IsRelatedToArrayLength() const {
112 // Some bounds are created with HNewArray* as the instruction instead
113 // of HArrayLength*. They are treated the same.
114 return (instruction_ != nullptr) &&
115 (instruction_->IsArrayLength() || instruction_->IsNewArray());
Mingyao Yangf384f882014-10-22 16:08:18 -0700116 }
117
118 bool IsConstant() const {
119 return instruction_ == nullptr;
120 }
121
122 static ValueBound Min() { return ValueBound(nullptr, INT_MIN); }
123 static ValueBound Max() { return ValueBound(nullptr, INT_MAX); }
124
125 bool Equals(ValueBound bound) const {
126 return instruction_ == bound.instruction_ && constant_ == bound.constant_;
127 }
128
Mingyao Yang0304e182015-01-30 16:41:29 -0800129 static HInstruction* FromArrayLengthToNewArrayIfPossible(HInstruction* instruction) {
130 // Null check on the NewArray should have been eliminated by instruction
131 // simplifier already.
132 if (instruction->IsArrayLength() && instruction->InputAt(0)->IsNewArray()) {
133 return instruction->InputAt(0)->AsNewArray();
134 }
135 return instruction;
136 }
137
138 static bool Equal(HInstruction* instruction1, HInstruction* instruction2) {
139 if (instruction1 == instruction2) {
140 return true;
141 }
142
143 if (instruction1 == nullptr || instruction2 == nullptr) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700144 return false;
145 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800146
147 // Some bounds are created with HNewArray* as the instruction instead
148 // of HArrayLength*. They are treated the same.
149 instruction1 = FromArrayLengthToNewArrayIfPossible(instruction1);
150 instruction2 = FromArrayLengthToNewArrayIfPossible(instruction2);
151 return instruction1 == instruction2;
152 }
153
154 // Returns if it's certain this->bound >= `bound`.
155 bool GreaterThanOrEqualTo(ValueBound bound) const {
156 if (Equal(instruction_, bound.instruction_)) {
157 return constant_ >= bound.constant_;
158 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700159 // Not comparable. Just return false.
160 return false;
161 }
162
Mingyao Yang0304e182015-01-30 16:41:29 -0800163 // Returns if it's certain this->bound <= `bound`.
164 bool LessThanOrEqualTo(ValueBound bound) const {
165 if (Equal(instruction_, bound.instruction_)) {
166 return constant_ <= bound.constant_;
Mingyao Yangf384f882014-10-22 16:08:18 -0700167 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700168 // Not comparable. Just return false.
169 return false;
170 }
171
172 // Try to narrow lower bound. Returns the greatest of the two if possible.
173 // Pick one if they are not comparable.
174 static ValueBound NarrowLowerBound(ValueBound bound1, ValueBound bound2) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800175 if (bound1.GreaterThanOrEqualTo(bound2)) {
176 return bound1;
177 }
178 if (bound2.GreaterThanOrEqualTo(bound1)) {
179 return bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700180 }
181
182 // Not comparable. Just pick one. We may lose some info, but that's ok.
183 // Favor constant as lower bound.
184 return bound1.IsConstant() ? bound1 : bound2;
185 }
186
187 // Try to narrow upper bound. Returns the lowest of the two if possible.
188 // Pick one if they are not comparable.
189 static ValueBound NarrowUpperBound(ValueBound bound1, ValueBound bound2) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800190 if (bound1.LessThanOrEqualTo(bound2)) {
191 return bound1;
192 }
193 if (bound2.LessThanOrEqualTo(bound1)) {
194 return bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700195 }
196
197 // Not comparable. Just pick one. We may lose some info, but that's ok.
198 // Favor array length as upper bound.
Mingyao Yang0304e182015-01-30 16:41:29 -0800199 return bound1.IsRelatedToArrayLength() ? bound1 : bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700200 }
201
Mingyao Yang0304e182015-01-30 16:41:29 -0800202 // Add a constant to a ValueBound.
203 // `overflow` or `underflow` will return whether the resulting bound may
204 // overflow or underflow an int.
205 ValueBound Add(int32_t c, bool* overflow, bool* underflow) const {
206 *overflow = *underflow = false;
Mingyao Yangf384f882014-10-22 16:08:18 -0700207 if (c == 0) {
208 return *this;
209 }
210
Mingyao Yang0304e182015-01-30 16:41:29 -0800211 int32_t new_constant;
Mingyao Yangf384f882014-10-22 16:08:18 -0700212 if (c > 0) {
213 if (constant_ > INT_MAX - c) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800214 *overflow = true;
Mingyao Yang64197522014-12-05 15:56:23 -0800215 return Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700216 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800217
218 new_constant = constant_ + c;
219 // (array.length + non-positive-constant) won't overflow an int.
220 if (IsConstant() || (IsRelatedToArrayLength() && new_constant <= 0)) {
221 return ValueBound(instruction_, new_constant);
222 }
223 // Be conservative.
224 *overflow = true;
225 return Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700226 } else {
227 if (constant_ < INT_MIN - c) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800228 *underflow = true;
229 return Min();
Mingyao Yangf384f882014-10-22 16:08:18 -0700230 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800231
232 new_constant = constant_ + c;
233 // Regardless of the value new_constant, (array.length+new_constant) will
234 // never underflow since array.length is no less than 0.
235 if (IsConstant() || IsRelatedToArrayLength()) {
236 return ValueBound(instruction_, new_constant);
237 }
238 // Be conservative.
239 *underflow = true;
240 return Min();
Mingyao Yangf384f882014-10-22 16:08:18 -0700241 }
242 return ValueBound(instruction_, new_constant);
243 }
244
245 private:
Mingyao Yangf384f882014-10-22 16:08:18 -0700246 HInstruction* instruction_;
Mingyao Yang0304e182015-01-30 16:41:29 -0800247 int32_t constant_;
Mingyao Yangf384f882014-10-22 16:08:18 -0700248};
249
250/**
251 * Represent a range of lower bound and upper bound, both being inclusive.
252 * Currently a ValueRange may be generated as a result of the following:
253 * comparisons related to array bounds, array bounds check, add/sub on top
Mingyao Yang0304e182015-01-30 16:41:29 -0800254 * of an existing value range, NewArray or a loop phi corresponding to an
Mingyao Yangf384f882014-10-22 16:08:18 -0700255 * incrementing/decrementing array index (MonotonicValueRange).
256 */
257class ValueRange : public ArenaObject<kArenaAllocMisc> {
258 public:
259 ValueRange(ArenaAllocator* allocator, ValueBound lower, ValueBound upper)
260 : allocator_(allocator), lower_(lower), upper_(upper) {}
261
262 virtual ~ValueRange() {}
263
Mingyao Yang57e04752015-02-09 18:13:26 -0800264 virtual MonotonicValueRange* AsMonotonicValueRange() { return nullptr; }
265 bool IsMonotonicValueRange() {
Mingyao Yangf384f882014-10-22 16:08:18 -0700266 return AsMonotonicValueRange() != nullptr;
267 }
268
269 ArenaAllocator* GetAllocator() const { return allocator_; }
270 ValueBound GetLower() const { return lower_; }
271 ValueBound GetUpper() const { return upper_; }
272
273 // If it's certain that this value range fits in other_range.
274 virtual bool FitsIn(ValueRange* other_range) const {
275 if (other_range == nullptr) {
276 return true;
277 }
278 DCHECK(!other_range->IsMonotonicValueRange());
Mingyao Yang0304e182015-01-30 16:41:29 -0800279 return lower_.GreaterThanOrEqualTo(other_range->lower_) &&
280 upper_.LessThanOrEqualTo(other_range->upper_);
Mingyao Yangf384f882014-10-22 16:08:18 -0700281 }
282
283 // Returns the intersection of this and range.
284 // If it's not possible to do intersection because some
285 // bounds are not comparable, it's ok to pick either bound.
286 virtual ValueRange* Narrow(ValueRange* range) {
287 if (range == nullptr) {
288 return this;
289 }
290
291 if (range->IsMonotonicValueRange()) {
292 return this;
293 }
294
295 return new (allocator_) ValueRange(
296 allocator_,
297 ValueBound::NarrowLowerBound(lower_, range->lower_),
298 ValueBound::NarrowUpperBound(upper_, range->upper_));
299 }
300
Mingyao Yang0304e182015-01-30 16:41:29 -0800301 // Shift a range by a constant.
302 ValueRange* Add(int32_t constant) const {
303 bool overflow, underflow;
304 ValueBound lower = lower_.Add(constant, &overflow, &underflow);
305 if (underflow) {
306 // Lower bound underflow will wrap around to positive values
307 // and invalidate the upper bound.
308 return nullptr;
Mingyao Yangf384f882014-10-22 16:08:18 -0700309 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800310 ValueBound upper = upper_.Add(constant, &overflow, &underflow);
311 if (overflow) {
312 // Upper bound overflow will wrap around to negative values
313 // and invalidate the lower bound.
314 return nullptr;
Mingyao Yangf384f882014-10-22 16:08:18 -0700315 }
316 return new (allocator_) ValueRange(allocator_, lower, upper);
317 }
318
Mingyao Yangf384f882014-10-22 16:08:18 -0700319 private:
320 ArenaAllocator* const allocator_;
321 const ValueBound lower_; // inclusive
322 const ValueBound upper_; // inclusive
323
324 DISALLOW_COPY_AND_ASSIGN(ValueRange);
325};
326
327/**
328 * A monotonically incrementing/decrementing value range, e.g.
329 * the variable i in "for (int i=0; i<array.length; i++)".
330 * Special care needs to be taken to account for overflow/underflow
331 * of such value ranges.
332 */
333class MonotonicValueRange : public ValueRange {
334 public:
Mingyao Yang64197522014-12-05 15:56:23 -0800335 MonotonicValueRange(ArenaAllocator* allocator,
336 HInstruction* initial,
Mingyao Yang0304e182015-01-30 16:41:29 -0800337 int32_t increment,
Mingyao Yang64197522014-12-05 15:56:23 -0800338 ValueBound bound)
339 // To be conservative, give it full range [INT_MIN, INT_MAX] in case it's
340 // used as a regular value range, due to possible overflow/underflow.
341 : ValueRange(allocator, ValueBound::Min(), ValueBound::Max()),
342 initial_(initial),
343 increment_(increment),
344 bound_(bound) {}
Mingyao Yangf384f882014-10-22 16:08:18 -0700345
346 virtual ~MonotonicValueRange() {}
347
Mingyao Yang57e04752015-02-09 18:13:26 -0800348 int32_t GetIncrement() const { return increment_; }
349
350 ValueBound GetBound() const { return bound_; }
351
352 MonotonicValueRange* AsMonotonicValueRange() OVERRIDE { return this; }
Mingyao Yangf384f882014-10-22 16:08:18 -0700353
354 // If it's certain that this value range fits in other_range.
355 bool FitsIn(ValueRange* other_range) const OVERRIDE {
356 if (other_range == nullptr) {
357 return true;
358 }
359 DCHECK(!other_range->IsMonotonicValueRange());
360 return false;
361 }
362
363 // Try to narrow this MonotonicValueRange given another range.
364 // Ideally it will return a normal ValueRange. But due to
365 // possible overflow/underflow, that may not be possible.
366 ValueRange* Narrow(ValueRange* range) OVERRIDE {
367 if (range == nullptr) {
368 return this;
369 }
370 DCHECK(!range->IsMonotonicValueRange());
371
372 if (increment_ > 0) {
373 // Monotonically increasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800374 ValueBound lower = ValueBound::NarrowLowerBound(bound_, range->GetLower());
Mingyao Yangf384f882014-10-22 16:08:18 -0700375
376 // We currently conservatively assume max array length is INT_MAX. If we can
377 // make assumptions about the max array length, e.g. due to the max heap size,
378 // divided by the element size (such as 4 bytes for each integer array), we can
379 // lower this number and rule out some possible overflows.
Mingyao Yang0304e182015-01-30 16:41:29 -0800380 int32_t max_array_len = INT_MAX;
Mingyao Yangf384f882014-10-22 16:08:18 -0700381
Mingyao Yang0304e182015-01-30 16:41:29 -0800382 // max possible integer value of range's upper value.
383 int32_t upper = INT_MAX;
384 // Try to lower upper.
385 ValueBound upper_bound = range->GetUpper();
386 if (upper_bound.IsConstant()) {
387 upper = upper_bound.GetConstant();
388 } else if (upper_bound.IsRelatedToArrayLength() && upper_bound.GetConstant() <= 0) {
389 // Normal case. e.g. <= array.length - 1.
390 upper = max_array_len + upper_bound.GetConstant();
Mingyao Yangf384f882014-10-22 16:08:18 -0700391 }
392
393 // If we can prove for the last number in sequence of initial_,
394 // initial_ + increment_, initial_ + 2 x increment_, ...
395 // that's <= upper, (last_num_in_sequence + increment_) doesn't trigger overflow,
396 // then this MonoticValueRange is narrowed to a normal value range.
397
398 // Be conservative first, assume last number in the sequence hits upper.
Mingyao Yang0304e182015-01-30 16:41:29 -0800399 int32_t last_num_in_sequence = upper;
Mingyao Yangf384f882014-10-22 16:08:18 -0700400 if (initial_->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800401 int32_t initial_constant = initial_->AsIntConstant()->GetValue();
Mingyao Yangf384f882014-10-22 16:08:18 -0700402 if (upper <= initial_constant) {
403 last_num_in_sequence = upper;
404 } else {
Mingyao Yang0304e182015-01-30 16:41:29 -0800405 // Cast to int64_t for the substraction part to avoid int32_t overflow.
Mingyao Yangf384f882014-10-22 16:08:18 -0700406 last_num_in_sequence = initial_constant +
407 ((int64_t)upper - (int64_t)initial_constant) / increment_ * increment_;
408 }
409 }
410 if (last_num_in_sequence <= INT_MAX - increment_) {
411 // No overflow. The sequence will be stopped by the upper bound test as expected.
412 return new (GetAllocator()) ValueRange(GetAllocator(), lower, range->GetUpper());
413 }
414
415 // There might be overflow. Give up narrowing.
416 return this;
417 } else {
418 DCHECK_NE(increment_, 0);
419 // Monotonically decreasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800420 ValueBound upper = ValueBound::NarrowUpperBound(bound_, range->GetUpper());
Mingyao Yangf384f882014-10-22 16:08:18 -0700421
422 // Need to take care of underflow. Try to prove underflow won't happen
Mingyao Yang0304e182015-01-30 16:41:29 -0800423 // for common cases.
Mingyao Yangf384f882014-10-22 16:08:18 -0700424 if (range->GetLower().IsConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800425 int32_t constant = range->GetLower().GetConstant();
Mingyao Yangf384f882014-10-22 16:08:18 -0700426 if (constant >= INT_MIN - increment_) {
427 return new (GetAllocator()) ValueRange(GetAllocator(), range->GetLower(), upper);
428 }
429 }
430
Mingyao Yang0304e182015-01-30 16:41:29 -0800431 // For non-constant lower bound, just assume might be underflow. Give up narrowing.
Mingyao Yangf384f882014-10-22 16:08:18 -0700432 return this;
433 }
434 }
435
436 private:
Mingyao Yangf384f882014-10-22 16:08:18 -0700437 HInstruction* const initial_;
Mingyao Yang0304e182015-01-30 16:41:29 -0800438 const int32_t increment_;
Mingyao Yang64197522014-12-05 15:56:23 -0800439 ValueBound bound_; // Additional value bound info for initial_;
Mingyao Yangf384f882014-10-22 16:08:18 -0700440
441 DISALLOW_COPY_AND_ASSIGN(MonotonicValueRange);
442};
443
444class BCEVisitor : public HGraphVisitor {
445 public:
Andreas Gampe0418b5b2014-12-04 17:24:50 -0800446 explicit BCEVisitor(HGraph* graph)
Mingyao Yangf384f882014-10-22 16:08:18 -0700447 : HGraphVisitor(graph),
448 maps_(graph->GetBlocks().Size()) {}
449
450 private:
451 // Return the map of proven value ranges at the beginning of a basic block.
452 ArenaSafeMap<int, ValueRange*>* GetValueRangeMap(HBasicBlock* basic_block) {
453 int block_id = basic_block->GetBlockId();
454 if (maps_.at(block_id) == nullptr) {
455 std::unique_ptr<ArenaSafeMap<int, ValueRange*>> map(
456 new ArenaSafeMap<int, ValueRange*>(
457 std::less<int>(), GetGraph()->GetArena()->Adapter()));
458 maps_.at(block_id) = std::move(map);
459 }
460 return maps_.at(block_id).get();
461 }
462
463 // Traverse up the dominator tree to look for value range info.
464 ValueRange* LookupValueRange(HInstruction* instruction, HBasicBlock* basic_block) {
465 while (basic_block != nullptr) {
466 ArenaSafeMap<int, ValueRange*>* map = GetValueRangeMap(basic_block);
467 if (map->find(instruction->GetId()) != map->end()) {
468 return map->Get(instruction->GetId());
469 }
470 basic_block = basic_block->GetDominator();
471 }
472 // Didn't find any.
473 return nullptr;
474 }
475
Mingyao Yang0304e182015-01-30 16:41:29 -0800476 // Narrow the value range of `instruction` at the end of `basic_block` with `range`,
477 // and push the narrowed value range to `successor`.
Mingyao Yangf384f882014-10-22 16:08:18 -0700478 void ApplyRangeFromComparison(HInstruction* instruction, HBasicBlock* basic_block,
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800479 HBasicBlock* successor, ValueRange* range) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700480 ValueRange* existing_range = LookupValueRange(instruction, basic_block);
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800481 if (existing_range == nullptr) {
482 if (range != nullptr) {
483 GetValueRangeMap(successor)->Overwrite(instruction->GetId(), range);
484 }
485 return;
486 }
487 if (existing_range->IsMonotonicValueRange()) {
488 DCHECK(instruction->IsLoopHeaderPhi());
489 // Make sure the comparison is in the loop header so each increment is
490 // checked with a comparison.
491 if (instruction->GetBlock() != basic_block) {
492 return;
493 }
494 }
495 ValueRange* narrowed_range = existing_range->Narrow(range);
Mingyao Yangf384f882014-10-22 16:08:18 -0700496 if (narrowed_range != nullptr) {
497 GetValueRangeMap(successor)->Overwrite(instruction->GetId(), narrowed_range);
498 }
499 }
500
Mingyao Yang57e04752015-02-09 18:13:26 -0800501 // Special case that we may simultaneously narrow two MonotonicValueRange's to
502 // regular value ranges.
503 void HandleIfBetweenTwoMonotonicValueRanges(HIf* instruction,
504 HInstruction* left,
505 HInstruction* right,
506 IfCondition cond,
507 MonotonicValueRange* left_range,
508 MonotonicValueRange* right_range) {
509 DCHECK(left->IsLoopHeaderPhi());
510 DCHECK(right->IsLoopHeaderPhi());
511 if (instruction->GetBlock() != left->GetBlock()) {
512 // Comparison needs to be in loop header to make sure it's done after each
513 // increment/decrement.
514 return;
515 }
516
517 // Handle common cases which also don't have overflow/underflow concerns.
518 if (left_range->GetIncrement() == 1 &&
519 left_range->GetBound().IsConstant() &&
520 right_range->GetIncrement() == -1 &&
521 right_range->GetBound().IsRelatedToArrayLength() &&
522 right_range->GetBound().GetConstant() < 0) {
Mingyao Yang57e04752015-02-09 18:13:26 -0800523 HBasicBlock* successor = nullptr;
524 int32_t left_compensation = 0;
525 int32_t right_compensation = 0;
526 if (cond == kCondLT) {
527 left_compensation = -1;
528 right_compensation = 1;
529 successor = instruction->IfTrueSuccessor();
530 } else if (cond == kCondLE) {
531 successor = instruction->IfTrueSuccessor();
532 } else if (cond == kCondGT) {
533 successor = instruction->IfFalseSuccessor();
534 } else if (cond == kCondGE) {
535 left_compensation = -1;
536 right_compensation = 1;
537 successor = instruction->IfFalseSuccessor();
538 } else {
539 // We don't handle '=='/'!=' test in case left and right can cross and
540 // miss each other.
541 return;
542 }
543
544 if (successor != nullptr) {
545 bool overflow;
546 bool underflow;
547 ValueRange* new_left_range = new (GetGraph()->GetArena()) ValueRange(
548 GetGraph()->GetArena(),
549 left_range->GetBound(),
550 right_range->GetBound().Add(left_compensation, &overflow, &underflow));
551 if (!overflow && !underflow) {
552 ApplyRangeFromComparison(left, instruction->GetBlock(), successor,
553 new_left_range);
554 }
555
556 ValueRange* new_right_range = new (GetGraph()->GetArena()) ValueRange(
557 GetGraph()->GetArena(),
558 left_range->GetBound().Add(right_compensation, &overflow, &underflow),
559 right_range->GetBound());
560 if (!overflow && !underflow) {
561 ApplyRangeFromComparison(right, instruction->GetBlock(), successor,
562 new_right_range);
563 }
564 }
565 }
566 }
567
Mingyao Yangf384f882014-10-22 16:08:18 -0700568 // Handle "if (left cmp_cond right)".
569 void HandleIf(HIf* instruction, HInstruction* left, HInstruction* right, IfCondition cond) {
570 HBasicBlock* block = instruction->GetBlock();
571
572 HBasicBlock* true_successor = instruction->IfTrueSuccessor();
573 // There should be no critical edge at this point.
574 DCHECK_EQ(true_successor->GetPredecessors().Size(), 1u);
575
576 HBasicBlock* false_successor = instruction->IfFalseSuccessor();
577 // There should be no critical edge at this point.
578 DCHECK_EQ(false_successor->GetPredecessors().Size(), 1u);
579
Mingyao Yang64197522014-12-05 15:56:23 -0800580 bool found;
581 ValueBound bound = ValueBound::DetectValueBoundFromValue(right, &found);
Mingyao Yang0304e182015-01-30 16:41:29 -0800582 // Each comparison can establish a lower bound and an upper bound
583 // for the left hand side.
Mingyao Yangf384f882014-10-22 16:08:18 -0700584 ValueBound lower = bound;
585 ValueBound upper = bound;
586 if (!found) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800587 // No constant or array.length+c format bound found.
Mingyao Yangf384f882014-10-22 16:08:18 -0700588 // 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 -0800589 ValueRange* right_range = LookupValueRange(right, block);
590 if (right_range != nullptr) {
591 if (right_range->IsMonotonicValueRange()) {
592 ValueRange* left_range = LookupValueRange(left, block);
593 if (left_range != nullptr && left_range->IsMonotonicValueRange()) {
594 HandleIfBetweenTwoMonotonicValueRanges(instruction, left, right, cond,
595 left_range->AsMonotonicValueRange(),
596 right_range->AsMonotonicValueRange());
597 return;
598 }
599 }
600 lower = right_range->GetLower();
601 upper = right_range->GetUpper();
Mingyao Yangf384f882014-10-22 16:08:18 -0700602 } else {
603 lower = ValueBound::Min();
604 upper = ValueBound::Max();
605 }
606 }
607
Mingyao Yang0304e182015-01-30 16:41:29 -0800608 bool overflow, underflow;
Mingyao Yangf384f882014-10-22 16:08:18 -0700609 if (cond == kCondLT || cond == kCondLE) {
610 if (!upper.Equals(ValueBound::Max())) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800611 int32_t compensation = (cond == kCondLT) ? -1 : 0; // upper bound is inclusive
612 ValueBound new_upper = upper.Add(compensation, &overflow, &underflow);
613 if (overflow || underflow) {
614 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800615 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700616 ValueRange* new_range = new (GetGraph()->GetArena())
617 ValueRange(GetGraph()->GetArena(), ValueBound::Min(), new_upper);
618 ApplyRangeFromComparison(left, block, true_successor, new_range);
619 }
620
621 // array.length as a lower bound isn't considered useful.
Mingyao Yang0304e182015-01-30 16:41:29 -0800622 if (!lower.Equals(ValueBound::Min()) && !lower.IsRelatedToArrayLength()) {
623 int32_t compensation = (cond == kCondLE) ? 1 : 0; // lower bound is inclusive
624 ValueBound new_lower = lower.Add(compensation, &overflow, &underflow);
625 if (overflow || underflow) {
626 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800627 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700628 ValueRange* new_range = new (GetGraph()->GetArena())
629 ValueRange(GetGraph()->GetArena(), new_lower, ValueBound::Max());
630 ApplyRangeFromComparison(left, block, false_successor, new_range);
631 }
632 } else if (cond == kCondGT || cond == kCondGE) {
633 // array.length as a lower bound isn't considered useful.
Mingyao Yang0304e182015-01-30 16:41:29 -0800634 if (!lower.Equals(ValueBound::Min()) && !lower.IsRelatedToArrayLength()) {
635 int32_t compensation = (cond == kCondGT) ? 1 : 0; // lower bound is inclusive
636 ValueBound new_lower = lower.Add(compensation, &overflow, &underflow);
637 if (overflow || underflow) {
638 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800639 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700640 ValueRange* new_range = new (GetGraph()->GetArena())
641 ValueRange(GetGraph()->GetArena(), new_lower, ValueBound::Max());
642 ApplyRangeFromComparison(left, block, true_successor, new_range);
643 }
644
645 if (!upper.Equals(ValueBound::Max())) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800646 int32_t compensation = (cond == kCondGE) ? -1 : 0; // upper bound is inclusive
647 ValueBound new_upper = upper.Add(compensation, &overflow, &underflow);
648 if (overflow || underflow) {
649 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800650 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700651 ValueRange* new_range = new (GetGraph()->GetArena())
652 ValueRange(GetGraph()->GetArena(), ValueBound::Min(), new_upper);
653 ApplyRangeFromComparison(left, block, false_successor, new_range);
654 }
655 }
656 }
657
658 void VisitBoundsCheck(HBoundsCheck* bounds_check) {
659 HBasicBlock* block = bounds_check->GetBlock();
660 HInstruction* index = bounds_check->InputAt(0);
661 HInstruction* array_length = bounds_check->InputAt(1);
Mingyao Yang0304e182015-01-30 16:41:29 -0800662 DCHECK(array_length->IsIntConstant() || array_length->IsArrayLength());
Mingyao Yangf384f882014-10-22 16:08:18 -0700663
Mingyao Yang0304e182015-01-30 16:41:29 -0800664 if (!index->IsIntConstant()) {
665 ValueRange* index_range = LookupValueRange(index, block);
666 if (index_range != nullptr) {
667 ValueBound lower = ValueBound(nullptr, 0); // constant 0
668 ValueBound upper = ValueBound(array_length, -1); // array_length - 1
669 ValueRange* array_range = new (GetGraph()->GetArena())
670 ValueRange(GetGraph()->GetArena(), lower, upper);
671 if (index_range->FitsIn(array_range)) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700672 ReplaceBoundsCheck(bounds_check, index);
673 return;
674 }
675 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800676 } else {
677 int32_t constant = index->AsIntConstant()->GetValue();
678 if (constant < 0) {
679 // Will always throw exception.
680 return;
681 }
682 if (array_length->IsIntConstant()) {
683 if (constant < array_length->AsIntConstant()->GetValue()) {
684 ReplaceBoundsCheck(bounds_check, index);
685 }
686 return;
687 }
688
689 DCHECK(array_length->IsArrayLength());
690 ValueRange* existing_range = LookupValueRange(array_length, block);
691 if (existing_range != nullptr) {
692 ValueBound lower = existing_range->GetLower();
693 DCHECK(lower.IsConstant());
694 if (constant < lower.GetConstant()) {
695 ReplaceBoundsCheck(bounds_check, index);
696 return;
697 } else {
698 // Existing range isn't strong enough to eliminate the bounds check.
699 // Fall through to update the array_length range with info from this
700 // bounds check.
701 }
702 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700703
704 // Once we have an array access like 'array[5] = 1', we record array.length >= 6.
Mingyao Yang0304e182015-01-30 16:41:29 -0800705 // We currently don't do it for non-constant index since a valid array[i] can't prove
706 // a valid array[i-1] yet due to the lower bound side.
Mingyao Yang64197522014-12-05 15:56:23 -0800707 ValueBound lower = ValueBound(nullptr, constant + 1);
Mingyao Yangf384f882014-10-22 16:08:18 -0700708 ValueBound upper = ValueBound::Max();
709 ValueRange* range = new (GetGraph()->GetArena())
710 ValueRange(GetGraph()->GetArena(), lower, upper);
Mingyao Yang0304e182015-01-30 16:41:29 -0800711 GetValueRangeMap(block)->Overwrite(array_length->GetId(), range);
Mingyao Yangf384f882014-10-22 16:08:18 -0700712 }
713 }
714
715 void ReplaceBoundsCheck(HInstruction* bounds_check, HInstruction* index) {
716 bounds_check->ReplaceWith(index);
717 bounds_check->GetBlock()->RemoveInstruction(bounds_check);
718 }
719
720 void VisitPhi(HPhi* phi) {
721 if (phi->IsLoopHeaderPhi() && phi->GetType() == Primitive::kPrimInt) {
Andreas Gampe0418b5b2014-12-04 17:24:50 -0800722 DCHECK_EQ(phi->InputCount(), 2U);
Mingyao Yangf384f882014-10-22 16:08:18 -0700723 HInstruction* instruction = phi->InputAt(1);
Mingyao Yang0304e182015-01-30 16:41:29 -0800724 HInstruction *left;
725 int32_t increment;
726 if (ValueBound::IsAddOrSubAConstant(instruction, &left, &increment)) {
727 if (left == phi) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700728 HInstruction* initial_value = phi->InputAt(0);
729 ValueRange* range = nullptr;
Mingyao Yang64197522014-12-05 15:56:23 -0800730 if (increment == 0) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700731 // Add constant 0. It's really a fixed value.
732 range = new (GetGraph()->GetArena()) ValueRange(
733 GetGraph()->GetArena(),
Mingyao Yang64197522014-12-05 15:56:23 -0800734 ValueBound(initial_value, 0),
735 ValueBound(initial_value, 0));
Mingyao Yangf384f882014-10-22 16:08:18 -0700736 } else {
737 // Monotonically increasing/decreasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800738 bool found;
739 ValueBound bound = ValueBound::DetectValueBoundFromValue(
740 initial_value, &found);
741 if (!found) {
742 // No constant or array.length+c bound found.
743 // For i=j, we can still use j's upper bound as i's upper bound.
744 // Same for lower.
745 ValueRange* initial_range = LookupValueRange(initial_value, phi->GetBlock());
746 if (initial_range != nullptr) {
747 bound = increment > 0 ? initial_range->GetLower() :
748 initial_range->GetUpper();
749 } else {
750 bound = increment > 0 ? ValueBound::Min() : ValueBound::Max();
751 }
752 }
753 range = new (GetGraph()->GetArena()) MonotonicValueRange(
Mingyao Yangf384f882014-10-22 16:08:18 -0700754 GetGraph()->GetArena(),
755 initial_value,
Mingyao Yang64197522014-12-05 15:56:23 -0800756 increment,
757 bound);
Mingyao Yangf384f882014-10-22 16:08:18 -0700758 }
759 GetValueRangeMap(phi->GetBlock())->Overwrite(phi->GetId(), range);
760 }
761 }
762 }
763 }
764
765 void VisitIf(HIf* instruction) {
766 if (instruction->InputAt(0)->IsCondition()) {
767 HCondition* cond = instruction->InputAt(0)->AsCondition();
768 IfCondition cmp = cond->GetCondition();
769 if (cmp == kCondGT || cmp == kCondGE ||
770 cmp == kCondLT || cmp == kCondLE) {
771 HInstruction* left = cond->GetLeft();
772 HInstruction* right = cond->GetRight();
773 HandleIf(instruction, left, right, cmp);
774 }
775 }
776 }
777
778 void VisitAdd(HAdd* add) {
779 HInstruction* right = add->GetRight();
780 if (right->IsIntConstant()) {
781 ValueRange* left_range = LookupValueRange(add->GetLeft(), add->GetBlock());
782 if (left_range == nullptr) {
783 return;
784 }
785 ValueRange* range = left_range->Add(right->AsIntConstant()->GetValue());
786 if (range != nullptr) {
787 GetValueRangeMap(add->GetBlock())->Overwrite(add->GetId(), range);
788 }
789 }
790 }
791
792 void VisitSub(HSub* sub) {
793 HInstruction* left = sub->GetLeft();
794 HInstruction* right = sub->GetRight();
795 if (right->IsIntConstant()) {
796 ValueRange* left_range = LookupValueRange(left, sub->GetBlock());
797 if (left_range == nullptr) {
798 return;
799 }
800 ValueRange* range = left_range->Add(-right->AsIntConstant()->GetValue());
801 if (range != nullptr) {
802 GetValueRangeMap(sub->GetBlock())->Overwrite(sub->GetId(), range);
803 return;
804 }
805 }
806
807 // Here we are interested in the typical triangular case of nested loops,
808 // such as the inner loop 'for (int j=0; j<array.length-i; j++)' where i
809 // 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 -0800810
811 // Try to handle (array.length - i) or (array.length + c - i) format.
812 HInstruction* left_of_left; // left input of left.
813 int32_t right_const = 0;
814 if (ValueBound::IsAddOrSubAConstant(left, &left_of_left, &right_const)) {
815 left = left_of_left;
816 }
817 // The value of left input of the sub equals (left + right_const).
818
Mingyao Yangf384f882014-10-22 16:08:18 -0700819 if (left->IsArrayLength()) {
820 HInstruction* array_length = left->AsArrayLength();
821 ValueRange* right_range = LookupValueRange(right, sub->GetBlock());
822 if (right_range != nullptr) {
823 ValueBound lower = right_range->GetLower();
824 ValueBound upper = right_range->GetUpper();
Mingyao Yang0304e182015-01-30 16:41:29 -0800825 if (lower.IsConstant() && upper.IsRelatedToArrayLength()) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700826 HInstruction* upper_inst = upper.GetInstruction();
Mingyao Yang0304e182015-01-30 16:41:29 -0800827 // Make sure it's the same array.
828 if (ValueBound::Equal(array_length, upper_inst)) {
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800829 int32_t c0 = right_const;
830 int32_t c1 = lower.GetConstant();
831 int32_t c2 = upper.GetConstant();
832 // (array.length + c0 - v) where v is in [c1, array.length + c2]
833 // gets [c0 - c2, array.length + c0 - c1] as its value range.
834 if (!ValueBound::WouldAddOverflowOrUnderflow(c0, -c2) &&
835 !ValueBound::WouldAddOverflowOrUnderflow(c0, -c1)) {
836 if ((c0 - c1) <= 0) {
837 // array.length + (c0 - c1) won't overflow/underflow.
838 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
839 GetGraph()->GetArena(),
840 ValueBound(nullptr, right_const - upper.GetConstant()),
841 ValueBound(array_length, right_const - lower.GetConstant()));
842 GetValueRangeMap(sub->GetBlock())->Overwrite(sub->GetId(), range);
843 }
844 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700845 }
846 }
847 }
848 }
849 }
850
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800851 void FindAndHandlePartialArrayLength(HBinaryOperation* instruction) {
852 DCHECK(instruction->IsDiv() || instruction->IsShr() || instruction->IsUShr());
853 HInstruction* right = instruction->GetRight();
854 int32_t right_const;
855 if (right->IsIntConstant()) {
856 right_const = right->AsIntConstant()->GetValue();
857 // Detect division by two or more.
858 if ((instruction->IsDiv() && right_const <= 1) ||
859 (instruction->IsShr() && right_const < 1) ||
860 (instruction->IsUShr() && right_const < 1)) {
861 return;
862 }
863 } else {
864 return;
865 }
866
867 // Try to handle array.length/2 or (array.length-1)/2 format.
868 HInstruction* left = instruction->GetLeft();
869 HInstruction* left_of_left; // left input of left.
870 int32_t c = 0;
871 if (ValueBound::IsAddOrSubAConstant(left, &left_of_left, &c)) {
872 left = left_of_left;
873 }
874 // The value of left input of instruction equals (left + c).
875
876 // (array_length + 1) or smaller divided by two or more
877 // always generate a value in [INT_MIN, array_length].
878 // This is true even if array_length is INT_MAX.
879 if (left->IsArrayLength() && c <= 1) {
880 if (instruction->IsUShr() && c < 0) {
881 // Make sure for unsigned shift, left side is not negative.
882 // e.g. if array_length is 2, ((array_length - 3) >>> 2) is way bigger
883 // than array_length.
884 return;
885 }
886 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
887 GetGraph()->GetArena(),
888 ValueBound(nullptr, INT_MIN),
889 ValueBound(left, 0));
890 GetValueRangeMap(instruction->GetBlock())->Overwrite(instruction->GetId(), range);
891 }
892 }
893
894 void VisitDiv(HDiv* div) {
895 FindAndHandlePartialArrayLength(div);
896 }
897
898 void VisitShr(HShr* shr) {
899 FindAndHandlePartialArrayLength(shr);
900 }
901
902 void VisitUShr(HUShr* ushr) {
903 FindAndHandlePartialArrayLength(ushr);
904 }
905
Mingyao Yang4559f002015-02-27 14:43:53 -0800906 void VisitAnd(HAnd* instruction) {
907 if (instruction->GetRight()->IsIntConstant()) {
908 int32_t constant = instruction->GetRight()->AsIntConstant()->GetValue();
909 if (constant > 0) {
910 // constant serves as a mask so any number masked with it
911 // gets a [0, constant] value range.
912 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
913 GetGraph()->GetArena(),
914 ValueBound(nullptr, 0),
915 ValueBound(nullptr, constant));
916 GetValueRangeMap(instruction->GetBlock())->Overwrite(instruction->GetId(), range);
917 }
918 }
919 }
920
Mingyao Yang0304e182015-01-30 16:41:29 -0800921 void VisitNewArray(HNewArray* new_array) {
922 HInstruction* len = new_array->InputAt(0);
923 if (!len->IsIntConstant()) {
924 HInstruction *left;
925 int32_t right_const;
926 if (ValueBound::IsAddOrSubAConstant(len, &left, &right_const)) {
927 // (left + right_const) is used as size to new the array.
928 // We record "-right_const <= left <= new_array - right_const";
929 ValueBound lower = ValueBound(nullptr, -right_const);
930 // We use new_array for the bound instead of new_array.length,
931 // which isn't available as an instruction yet. new_array will
932 // be treated the same as new_array.length when it's used in a ValueBound.
933 ValueBound upper = ValueBound(new_array, -right_const);
934 ValueRange* range = new (GetGraph()->GetArena())
935 ValueRange(GetGraph()->GetArena(), lower, upper);
936 GetValueRangeMap(new_array->GetBlock())->Overwrite(left->GetId(), range);
937 }
938 }
939 }
940
Mingyao Yangf384f882014-10-22 16:08:18 -0700941 std::vector<std::unique_ptr<ArenaSafeMap<int, ValueRange*>>> maps_;
942
943 DISALLOW_COPY_AND_ASSIGN(BCEVisitor);
944};
945
946void BoundsCheckElimination::Run() {
Mingyao Yange4335eb2015-03-02 15:14:13 -0800947 if (!graph_->HasArrayAccesses()) {
948 return;
949 }
950
Mingyao Yangf384f882014-10-22 16:08:18 -0700951 BCEVisitor visitor(graph_);
952 // Reverse post order guarantees a node's dominators are visited first.
953 // We want to visit in the dominator-based order since if a value is known to
954 // be bounded by a range at one instruction, it must be true that all uses of
955 // that value dominated by that instruction fits in that range. Range of that
956 // value can be narrowed further down in the dominator tree.
957 //
958 // TODO: only visit blocks that dominate some array accesses.
959 visitor.VisitReversePostOrder();
960}
961
962} // namespace art