blob: 46ba048738e35ffc15a9ce51a0a69de2e4640db6 [file] [log] [blame]
Mingyao Yang8df69d42015-10-22 15:40:58 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "load_store_elimination.h"
Aart Bik96fd51d2016-11-28 11:22:35 -080018
19#include "escape.h"
Mingyao Yang8df69d42015-10-22 15:40:58 -070020#include "side_effects_analysis.h"
21
22#include <iostream>
23
24namespace art {
25
26class ReferenceInfo;
27
28// A cap for the number of heap locations to prevent pathological time/space consumption.
29// The number of heap locations for most of the methods stays below this threshold.
30constexpr size_t kMaxNumberOfHeapLocations = 32;
31
32// A ReferenceInfo contains additional info about a reference such as
33// whether it's a singleton, returned, etc.
34class ReferenceInfo : public ArenaObject<kArenaAllocMisc> {
35 public:
Aart Bik96fd51d2016-11-28 11:22:35 -080036 ReferenceInfo(HInstruction* reference, size_t pos)
37 : reference_(reference),
38 position_(pos),
39 is_singleton_(true),
Aart Bik71bf7b42016-11-16 10:17:46 -080040 is_singleton_and_not_returned_(true),
Mingyao Yang86974902017-03-01 14:03:51 -080041 is_singleton_and_not_deopt_visible_(true),
42 has_index_aliasing_(false) {
Aart Bik71bf7b42016-11-16 10:17:46 -080043 CalculateEscape(reference_,
44 nullptr,
45 &is_singleton_,
46 &is_singleton_and_not_returned_,
47 &is_singleton_and_not_deopt_visible_);
Mingyao Yang8df69d42015-10-22 15:40:58 -070048 }
49
50 HInstruction* GetReference() const {
51 return reference_;
52 }
53
54 size_t GetPosition() const {
55 return position_;
56 }
57
58 // Returns true if reference_ is the only name that can refer to its value during
59 // the lifetime of the method. So it's guaranteed to not have any alias in
60 // the method (including its callees).
61 bool IsSingleton() const {
62 return is_singleton_;
63 }
64
Mingyao Yange58bdca2016-10-28 11:07:24 -070065 // Returns true if reference_ is a singleton and not returned to the caller or
66 // used as an environment local of an HDeoptimize instruction.
Mingyao Yang8df69d42015-10-22 15:40:58 -070067 // The allocation and stores into reference_ may be eliminated for such cases.
Aart Bik71bf7b42016-11-16 10:17:46 -080068 bool IsSingletonAndRemovable() const {
69 return is_singleton_and_not_returned_ && is_singleton_and_not_deopt_visible_;
Mingyao Yang8df69d42015-10-22 15:40:58 -070070 }
71
Mingyao Yang86974902017-03-01 14:03:51 -080072 bool HasIndexAliasing() {
73 return has_index_aliasing_;
74 }
75
76 void SetHasIndexAliasing(bool has_index_aliasing) {
77 // Only allow setting to true.
78 DCHECK(has_index_aliasing);
79 has_index_aliasing_ = has_index_aliasing;
80 }
81
Mingyao Yang8df69d42015-10-22 15:40:58 -070082 private:
83 HInstruction* const reference_;
Aart Bik71bf7b42016-11-16 10:17:46 -080084 const size_t position_; // position in HeapLocationCollector's ref_info_array_.
Mingyao Yange58bdca2016-10-28 11:07:24 -070085
Mingyao Yang86974902017-03-01 14:03:51 -080086 // Can only be referred to by a single name in the method.
87 bool is_singleton_;
88 // Is singleton and not returned to caller.
89 bool is_singleton_and_not_returned_;
90 // Is singleton and not used as an environment local of HDeoptimize.
91 bool is_singleton_and_not_deopt_visible_;
92 // Some heap locations with reference_ have array index aliasing,
93 // e.g. arr[i] and arr[j] may be the same location.
94 bool has_index_aliasing_;
Mingyao Yang8df69d42015-10-22 15:40:58 -070095
96 DISALLOW_COPY_AND_ASSIGN(ReferenceInfo);
97};
98
99// A heap location is a reference-offset/index pair that a value can be loaded from
100// or stored to.
101class HeapLocation : public ArenaObject<kArenaAllocMisc> {
102 public:
103 static constexpr size_t kInvalidFieldOffset = -1;
104
105 // TODO: more fine-grained array types.
106 static constexpr int16_t kDeclaringClassDefIndexForArrays = -1;
107
108 HeapLocation(ReferenceInfo* ref_info,
109 size_t offset,
110 HInstruction* index,
111 int16_t declaring_class_def_index)
112 : ref_info_(ref_info),
113 offset_(offset),
114 index_(index),
Mingyao Yang803cbb92015-12-01 12:24:36 -0800115 declaring_class_def_index_(declaring_class_def_index),
116 value_killed_by_loop_side_effects_(true) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700117 DCHECK(ref_info != nullptr);
118 DCHECK((offset == kInvalidFieldOffset && index != nullptr) ||
119 (offset != kInvalidFieldOffset && index == nullptr));
Mingyao Yang803cbb92015-12-01 12:24:36 -0800120 if (ref_info->IsSingleton() && !IsArrayElement()) {
121 // Assume this location's value cannot be killed by loop side effects
122 // until proven otherwise.
123 value_killed_by_loop_side_effects_ = false;
124 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700125 }
126
127 ReferenceInfo* GetReferenceInfo() const { return ref_info_; }
128 size_t GetOffset() const { return offset_; }
129 HInstruction* GetIndex() const { return index_; }
130
131 // Returns the definition of declaring class' dex index.
132 // It's kDeclaringClassDefIndexForArrays for an array element.
133 int16_t GetDeclaringClassDefIndex() const {
134 return declaring_class_def_index_;
135 }
136
137 bool IsArrayElement() const {
138 return index_ != nullptr;
139 }
140
Mingyao Yang803cbb92015-12-01 12:24:36 -0800141 bool IsValueKilledByLoopSideEffects() const {
142 return value_killed_by_loop_side_effects_;
143 }
144
145 void SetValueKilledByLoopSideEffects(bool val) {
146 value_killed_by_loop_side_effects_ = val;
147 }
148
Mingyao Yang8df69d42015-10-22 15:40:58 -0700149 private:
150 ReferenceInfo* const ref_info_; // reference for instance/static field or array access.
151 const size_t offset_; // offset of static/instance field.
152 HInstruction* const index_; // index of an array element.
153 const int16_t declaring_class_def_index_; // declaring class's def's dex index.
Mingyao Yang803cbb92015-12-01 12:24:36 -0800154 bool value_killed_by_loop_side_effects_; // value of this location may be killed by loop
155 // side effects because this location is stored
Mingyao Yang0a845202016-10-14 16:26:08 -0700156 // into inside a loop. This gives
157 // better info on whether a singleton's location
158 // value may be killed by loop side effects.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700159
160 DISALLOW_COPY_AND_ASSIGN(HeapLocation);
161};
162
163static HInstruction* HuntForOriginalReference(HInstruction* ref) {
164 DCHECK(ref != nullptr);
165 while (ref->IsNullCheck() || ref->IsBoundType()) {
166 ref = ref->InputAt(0);
167 }
168 return ref;
169}
170
171// A HeapLocationCollector collects all relevant heap locations and keeps
172// an aliasing matrix for all locations.
173class HeapLocationCollector : public HGraphVisitor {
174 public:
175 static constexpr size_t kHeapLocationNotFound = -1;
176 // Start with a single uint32_t word. That's enough bits for pair-wise
177 // aliasing matrix of 8 heap locations.
178 static constexpr uint32_t kInitialAliasingMatrixBitVectorSize = 32;
179
180 explicit HeapLocationCollector(HGraph* graph)
181 : HGraphVisitor(graph),
182 ref_info_array_(graph->GetArena()->Adapter(kArenaAllocLSE)),
183 heap_locations_(graph->GetArena()->Adapter(kArenaAllocLSE)),
Vladimir Markof6a35de2016-03-21 12:01:50 +0000184 aliasing_matrix_(graph->GetArena(),
185 kInitialAliasingMatrixBitVectorSize,
186 true,
187 kArenaAllocLSE),
Mingyao Yang8df69d42015-10-22 15:40:58 -0700188 has_heap_stores_(false),
189 has_volatile_(false),
Mingyao Yange58bdca2016-10-28 11:07:24 -0700190 has_monitor_operations_(false) {}
Mingyao Yang8df69d42015-10-22 15:40:58 -0700191
192 size_t GetNumberOfHeapLocations() const {
193 return heap_locations_.size();
194 }
195
196 HeapLocation* GetHeapLocation(size_t index) const {
197 return heap_locations_[index];
198 }
199
200 ReferenceInfo* FindReferenceInfoOf(HInstruction* ref) const {
201 for (size_t i = 0; i < ref_info_array_.size(); i++) {
202 ReferenceInfo* ref_info = ref_info_array_[i];
203 if (ref_info->GetReference() == ref) {
204 DCHECK_EQ(i, ref_info->GetPosition());
205 return ref_info;
206 }
207 }
208 return nullptr;
209 }
210
211 bool HasHeapStores() const {
212 return has_heap_stores_;
213 }
214
215 bool HasVolatile() const {
216 return has_volatile_;
217 }
218
219 bool HasMonitorOps() const {
220 return has_monitor_operations_;
221 }
222
Mingyao Yang8df69d42015-10-22 15:40:58 -0700223 // Find and return the heap location index in heap_locations_.
224 size_t FindHeapLocationIndex(ReferenceInfo* ref_info,
225 size_t offset,
226 HInstruction* index,
227 int16_t declaring_class_def_index) const {
228 for (size_t i = 0; i < heap_locations_.size(); i++) {
229 HeapLocation* loc = heap_locations_[i];
230 if (loc->GetReferenceInfo() == ref_info &&
231 loc->GetOffset() == offset &&
232 loc->GetIndex() == index &&
233 loc->GetDeclaringClassDefIndex() == declaring_class_def_index) {
234 return i;
235 }
236 }
237 return kHeapLocationNotFound;
238 }
239
240 // Returns true if heap_locations_[index1] and heap_locations_[index2] may alias.
241 bool MayAlias(size_t index1, size_t index2) const {
242 if (index1 < index2) {
243 return aliasing_matrix_.IsBitSet(AliasingMatrixPosition(index1, index2));
244 } else if (index1 > index2) {
245 return aliasing_matrix_.IsBitSet(AliasingMatrixPosition(index2, index1));
246 } else {
247 DCHECK(false) << "index1 and index2 are expected to be different";
248 return true;
249 }
250 }
251
252 void BuildAliasingMatrix() {
253 const size_t number_of_locations = heap_locations_.size();
254 if (number_of_locations == 0) {
255 return;
256 }
257 size_t pos = 0;
258 // Compute aliasing info between every pair of different heap locations.
259 // Save the result in a matrix represented as a BitVector.
260 for (size_t i = 0; i < number_of_locations - 1; i++) {
261 for (size_t j = i + 1; j < number_of_locations; j++) {
262 if (ComputeMayAlias(i, j)) {
263 aliasing_matrix_.SetBit(CheckedAliasingMatrixPosition(i, j, pos));
264 }
265 pos++;
266 }
267 }
268 }
269
270 private:
271 // An allocation cannot alias with a name which already exists at the point
272 // of the allocation, such as a parameter or a load happening before the allocation.
273 bool MayAliasWithPreexistenceChecking(ReferenceInfo* ref_info1, ReferenceInfo* ref_info2) const {
274 if (ref_info1->GetReference()->IsNewInstance() || ref_info1->GetReference()->IsNewArray()) {
275 // Any reference that can alias with the allocation must appear after it in the block/in
276 // the block's successors. In reverse post order, those instructions will be visited after
277 // the allocation.
278 return ref_info2->GetPosition() >= ref_info1->GetPosition();
279 }
280 return true;
281 }
282
283 bool CanReferencesAlias(ReferenceInfo* ref_info1, ReferenceInfo* ref_info2) const {
284 if (ref_info1 == ref_info2) {
285 return true;
286 } else if (ref_info1->IsSingleton()) {
287 return false;
288 } else if (ref_info2->IsSingleton()) {
289 return false;
290 } else if (!MayAliasWithPreexistenceChecking(ref_info1, ref_info2) ||
291 !MayAliasWithPreexistenceChecking(ref_info2, ref_info1)) {
292 return false;
293 }
294 return true;
295 }
296
297 // `index1` and `index2` are indices in the array of collected heap locations.
298 // Returns the position in the bit vector that tracks whether the two heap
299 // locations may alias.
300 size_t AliasingMatrixPosition(size_t index1, size_t index2) const {
301 DCHECK(index2 > index1);
302 const size_t number_of_locations = heap_locations_.size();
303 // It's (num_of_locations - 1) + ... + (num_of_locations - index1) + (index2 - index1 - 1).
304 return (number_of_locations * index1 - (1 + index1) * index1 / 2 + (index2 - index1 - 1));
305 }
306
307 // An additional position is passed in to make sure the calculated position is correct.
308 size_t CheckedAliasingMatrixPosition(size_t index1, size_t index2, size_t position) {
309 size_t calculated_position = AliasingMatrixPosition(index1, index2);
310 DCHECK_EQ(calculated_position, position);
311 return calculated_position;
312 }
313
314 // Compute if two locations may alias to each other.
315 bool ComputeMayAlias(size_t index1, size_t index2) const {
316 HeapLocation* loc1 = heap_locations_[index1];
317 HeapLocation* loc2 = heap_locations_[index2];
318 if (loc1->GetOffset() != loc2->GetOffset()) {
319 // Either two different instance fields, or one is an instance
320 // field and the other is an array element.
321 return false;
322 }
323 if (loc1->GetDeclaringClassDefIndex() != loc2->GetDeclaringClassDefIndex()) {
324 // Different types.
325 return false;
326 }
327 if (!CanReferencesAlias(loc1->GetReferenceInfo(), loc2->GetReferenceInfo())) {
328 return false;
329 }
330 if (loc1->IsArrayElement() && loc2->IsArrayElement()) {
331 HInstruction* array_index1 = loc1->GetIndex();
332 HInstruction* array_index2 = loc2->GetIndex();
333 DCHECK(array_index1 != nullptr);
334 DCHECK(array_index2 != nullptr);
335 if (array_index1->IsIntConstant() &&
336 array_index2->IsIntConstant() &&
337 array_index1->AsIntConstant()->GetValue() != array_index2->AsIntConstant()->GetValue()) {
338 // Different constant indices do not alias.
339 return false;
340 }
Mingyao Yang86974902017-03-01 14:03:51 -0800341 ReferenceInfo* ref_info = loc1->GetReferenceInfo();
342 if (ref_info->IsSingleton()) {
343 // This is guaranteed by the CanReferencesAlias() test above.
344 DCHECK_EQ(ref_info, loc2->GetReferenceInfo());
345 ref_info->SetHasIndexAliasing(true);
346 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700347 }
348 return true;
349 }
350
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800351 ReferenceInfo* GetOrCreateReferenceInfo(HInstruction* instruction) {
352 ReferenceInfo* ref_info = FindReferenceInfoOf(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700353 if (ref_info == nullptr) {
354 size_t pos = ref_info_array_.size();
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800355 ref_info = new (GetGraph()->GetArena()) ReferenceInfo(instruction, pos);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700356 ref_info_array_.push_back(ref_info);
357 }
358 return ref_info;
359 }
360
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800361 void CreateReferenceInfoForReferenceType(HInstruction* instruction) {
362 if (instruction->GetType() != Primitive::kPrimNot) {
363 return;
364 }
365 DCHECK(FindReferenceInfoOf(instruction) == nullptr);
366 GetOrCreateReferenceInfo(instruction);
367 }
368
Mingyao Yang8df69d42015-10-22 15:40:58 -0700369 HeapLocation* GetOrCreateHeapLocation(HInstruction* ref,
370 size_t offset,
371 HInstruction* index,
372 int16_t declaring_class_def_index) {
373 HInstruction* original_ref = HuntForOriginalReference(ref);
374 ReferenceInfo* ref_info = GetOrCreateReferenceInfo(original_ref);
375 size_t heap_location_idx = FindHeapLocationIndex(
376 ref_info, offset, index, declaring_class_def_index);
377 if (heap_location_idx == kHeapLocationNotFound) {
378 HeapLocation* heap_loc = new (GetGraph()->GetArena())
379 HeapLocation(ref_info, offset, index, declaring_class_def_index);
380 heap_locations_.push_back(heap_loc);
381 return heap_loc;
382 }
383 return heap_locations_[heap_location_idx];
384 }
385
Mingyao Yang803cbb92015-12-01 12:24:36 -0800386 HeapLocation* VisitFieldAccess(HInstruction* ref, const FieldInfo& field_info) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700387 if (field_info.IsVolatile()) {
388 has_volatile_ = true;
389 }
390 const uint16_t declaring_class_def_index = field_info.GetDeclaringClassDefIndex();
391 const size_t offset = field_info.GetFieldOffset().SizeValue();
Mingyao Yang803cbb92015-12-01 12:24:36 -0800392 return GetOrCreateHeapLocation(ref, offset, nullptr, declaring_class_def_index);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700393 }
394
395 void VisitArrayAccess(HInstruction* array, HInstruction* index) {
396 GetOrCreateHeapLocation(array, HeapLocation::kInvalidFieldOffset,
397 index, HeapLocation::kDeclaringClassDefIndexForArrays);
398 }
399
400 void VisitInstanceFieldGet(HInstanceFieldGet* instruction) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800401 VisitFieldAccess(instruction->InputAt(0), instruction->GetFieldInfo());
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800402 CreateReferenceInfoForReferenceType(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700403 }
404
405 void VisitInstanceFieldSet(HInstanceFieldSet* instruction) OVERRIDE {
Mingyao Yang803cbb92015-12-01 12:24:36 -0800406 HeapLocation* location = VisitFieldAccess(instruction->InputAt(0), instruction->GetFieldInfo());
Mingyao Yang8df69d42015-10-22 15:40:58 -0700407 has_heap_stores_ = true;
Mingyao Yang0a845202016-10-14 16:26:08 -0700408 if (location->GetReferenceInfo()->IsSingleton()) {
409 // A singleton's location value may be killed by loop side effects if it's
410 // defined before that loop, and it's stored into inside that loop.
411 HLoopInformation* loop_info = instruction->GetBlock()->GetLoopInformation();
412 if (loop_info != nullptr) {
413 HInstruction* ref = location->GetReferenceInfo()->GetReference();
414 DCHECK(ref->IsNewInstance());
415 if (loop_info->IsDefinedOutOfTheLoop(ref)) {
416 // ref's location value may be killed by this loop's side effects.
417 location->SetValueKilledByLoopSideEffects(true);
418 } else {
419 // ref is defined inside this loop so this loop's side effects cannot
420 // kill its location value at the loop header since ref/its location doesn't
421 // exist yet at the loop header.
422 }
423 }
424 } else {
425 // For non-singletons, value_killed_by_loop_side_effects_ is inited to
426 // true.
427 DCHECK_EQ(location->IsValueKilledByLoopSideEffects(), true);
Mingyao Yang803cbb92015-12-01 12:24:36 -0800428 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700429 }
430
431 void VisitStaticFieldGet(HStaticFieldGet* instruction) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800432 VisitFieldAccess(instruction->InputAt(0), instruction->GetFieldInfo());
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800433 CreateReferenceInfoForReferenceType(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700434 }
435
436 void VisitStaticFieldSet(HStaticFieldSet* instruction) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800437 VisitFieldAccess(instruction->InputAt(0), instruction->GetFieldInfo());
Mingyao Yang8df69d42015-10-22 15:40:58 -0700438 has_heap_stores_ = true;
439 }
440
441 // We intentionally don't collect HUnresolvedInstanceField/HUnresolvedStaticField accesses
442 // since we cannot accurately track the fields.
443
444 void VisitArrayGet(HArrayGet* instruction) OVERRIDE {
445 VisitArrayAccess(instruction->InputAt(0), instruction->InputAt(1));
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800446 CreateReferenceInfoForReferenceType(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700447 }
448
449 void VisitArraySet(HArraySet* instruction) OVERRIDE {
450 VisitArrayAccess(instruction->InputAt(0), instruction->InputAt(1));
451 has_heap_stores_ = true;
452 }
453
454 void VisitNewInstance(HNewInstance* new_instance) OVERRIDE {
455 // Any references appearing in the ref_info_array_ so far cannot alias with new_instance.
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800456 CreateReferenceInfoForReferenceType(new_instance);
457 }
458
459 void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* instruction) OVERRIDE {
460 CreateReferenceInfoForReferenceType(instruction);
461 }
462
463 void VisitInvokeVirtual(HInvokeVirtual* instruction) OVERRIDE {
464 CreateReferenceInfoForReferenceType(instruction);
465 }
466
467 void VisitInvokeInterface(HInvokeInterface* instruction) OVERRIDE {
468 CreateReferenceInfoForReferenceType(instruction);
469 }
470
471 void VisitParameterValue(HParameterValue* instruction) OVERRIDE {
472 CreateReferenceInfoForReferenceType(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700473 }
474
Mingyao Yang40bcb932016-02-03 05:46:57 -0800475 void VisitSelect(HSelect* instruction) OVERRIDE {
476 CreateReferenceInfoForReferenceType(instruction);
477 }
478
Mingyao Yang8df69d42015-10-22 15:40:58 -0700479 void VisitMonitorOperation(HMonitorOperation* monitor ATTRIBUTE_UNUSED) OVERRIDE {
480 has_monitor_operations_ = true;
481 }
482
483 ArenaVector<ReferenceInfo*> ref_info_array_; // All references used for heap accesses.
484 ArenaVector<HeapLocation*> heap_locations_; // All heap locations.
485 ArenaBitVector aliasing_matrix_; // aliasing info between each pair of locations.
486 bool has_heap_stores_; // If there is no heap stores, LSE acts as GVN with better
487 // alias analysis and won't be as effective.
488 bool has_volatile_; // If there are volatile field accesses.
489 bool has_monitor_operations_; // If there are monitor operations.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700490
491 DISALLOW_COPY_AND_ASSIGN(HeapLocationCollector);
492};
493
494// An unknown heap value. Loads with such a value in the heap location cannot be eliminated.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800495// A heap location can be set to kUnknownHeapValue when:
496// - initially set a value.
497// - killed due to aliasing, merging, invocation, or loop side effects.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700498static HInstruction* const kUnknownHeapValue =
499 reinterpret_cast<HInstruction*>(static_cast<uintptr_t>(-1));
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800500
Mingyao Yang8df69d42015-10-22 15:40:58 -0700501// Default heap value after an allocation.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800502// A heap location can be set to that value right after an allocation.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700503static HInstruction* const kDefaultHeapValue =
504 reinterpret_cast<HInstruction*>(static_cast<uintptr_t>(-2));
505
506class LSEVisitor : public HGraphVisitor {
507 public:
508 LSEVisitor(HGraph* graph,
509 const HeapLocationCollector& heap_locations_collector,
510 const SideEffectsAnalysis& side_effects)
511 : HGraphVisitor(graph),
512 heap_location_collector_(heap_locations_collector),
513 side_effects_(side_effects),
514 heap_values_for_(graph->GetBlocks().size(),
515 ArenaVector<HInstruction*>(heap_locations_collector.
516 GetNumberOfHeapLocations(),
517 kUnknownHeapValue,
518 graph->GetArena()->Adapter(kArenaAllocLSE)),
519 graph->GetArena()->Adapter(kArenaAllocLSE)),
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800520 removed_loads_(graph->GetArena()->Adapter(kArenaAllocLSE)),
521 substitute_instructions_for_loads_(graph->GetArena()->Adapter(kArenaAllocLSE)),
522 possibly_removed_stores_(graph->GetArena()->Adapter(kArenaAllocLSE)),
Mingyao Yang86974902017-03-01 14:03:51 -0800523 singleton_new_instances_(graph->GetArena()->Adapter(kArenaAllocLSE)),
524 singleton_new_arrays_(graph->GetArena()->Adapter(kArenaAllocLSE)) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700525 }
526
527 void VisitBasicBlock(HBasicBlock* block) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800528 // Populate the heap_values array for this block.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700529 // TODO: try to reuse the heap_values array from one predecessor if possible.
530 if (block->IsLoopHeader()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800531 HandleLoopSideEffects(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700532 } else {
533 MergePredecessorValues(block);
534 }
535 HGraphVisitor::VisitBasicBlock(block);
536 }
537
538 // Remove recorded instructions that should be eliminated.
539 void RemoveInstructions() {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800540 size_t size = removed_loads_.size();
541 DCHECK_EQ(size, substitute_instructions_for_loads_.size());
Mingyao Yang8df69d42015-10-22 15:40:58 -0700542 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800543 HInstruction* load = removed_loads_[i];
544 DCHECK(load != nullptr);
545 DCHECK(load->IsInstanceFieldGet() ||
546 load->IsStaticFieldGet() ||
547 load->IsArrayGet());
548 HInstruction* substitute = substitute_instructions_for_loads_[i];
549 DCHECK(substitute != nullptr);
550 // Keep tracing substitute till one that's not removed.
551 HInstruction* sub_sub = FindSubstitute(substitute);
552 while (sub_sub != substitute) {
553 substitute = sub_sub;
554 sub_sub = FindSubstitute(substitute);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700555 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800556 load->ReplaceWith(substitute);
557 load->GetBlock()->RemoveInstruction(load);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700558 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800559
560 // At this point, stores in possibly_removed_stores_ can be safely removed.
Mingyao Yang86974902017-03-01 14:03:51 -0800561 for (HInstruction* store : possibly_removed_stores_) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800562 DCHECK(store->IsInstanceFieldSet() || store->IsStaticFieldSet() || store->IsArraySet());
563 store->GetBlock()->RemoveInstruction(store);
564 }
565
Mingyao Yang062157f2016-03-02 10:15:36 -0800566 // Eliminate allocations that are not used.
Mingyao Yang86974902017-03-01 14:03:51 -0800567 for (HInstruction* new_instance : singleton_new_instances_) {
Mingyao Yang062157f2016-03-02 10:15:36 -0800568 if (!new_instance->HasNonEnvironmentUses()) {
569 new_instance->RemoveEnvironmentUsers();
570 new_instance->GetBlock()->RemoveInstruction(new_instance);
571 }
572 }
Mingyao Yang86974902017-03-01 14:03:51 -0800573 for (HInstruction* new_array : singleton_new_arrays_) {
574 if (!new_array->HasNonEnvironmentUses()) {
575 new_array->RemoveEnvironmentUsers();
576 new_array->GetBlock()->RemoveInstruction(new_array);
577 }
578 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700579 }
580
581 private:
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800582 // If heap_values[index] is an instance field store, need to keep the store.
583 // This is necessary if a heap value is killed due to merging, or loop side
584 // effects (which is essentially merging also), since a load later from the
585 // location won't be eliminated.
586 void KeepIfIsStore(HInstruction* heap_value) {
587 if (heap_value == kDefaultHeapValue ||
588 heap_value == kUnknownHeapValue ||
Mingyao Yang86974902017-03-01 14:03:51 -0800589 !(heap_value->IsInstanceFieldSet() || heap_value->IsArraySet())) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800590 return;
591 }
592 auto idx = std::find(possibly_removed_stores_.begin(),
593 possibly_removed_stores_.end(), heap_value);
594 if (idx != possibly_removed_stores_.end()) {
595 // Make sure the store is kept.
596 possibly_removed_stores_.erase(idx);
597 }
598 }
599
600 void HandleLoopSideEffects(HBasicBlock* block) {
601 DCHECK(block->IsLoopHeader());
602 int block_id = block->GetBlockId();
603 ArenaVector<HInstruction*>& heap_values = heap_values_for_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000604
605 // Don't eliminate loads in irreducible loops. This is safe for singletons, because
606 // they are always used by the non-eliminated loop-phi.
607 if (block->GetLoopInformation()->IsIrreducible()) {
608 if (kIsDebugBuild) {
609 for (size_t i = 0; i < heap_values.size(); i++) {
610 DCHECK_EQ(heap_values[i], kUnknownHeapValue);
611 }
612 }
613 return;
614 }
615
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800616 HBasicBlock* pre_header = block->GetLoopInformation()->GetPreHeader();
617 ArenaVector<HInstruction*>& pre_header_heap_values =
618 heap_values_for_[pre_header->GetBlockId()];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000619
Mingyao Yang803cbb92015-12-01 12:24:36 -0800620 // Inherit the values from pre-header.
621 for (size_t i = 0; i < heap_values.size(); i++) {
622 heap_values[i] = pre_header_heap_values[i];
623 }
624
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800625 // We do a single pass in reverse post order. For loops, use the side effects as a hint
626 // to see if the heap values should be killed.
627 if (side_effects_.GetLoopEffects(block).DoesAnyWrite()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800628 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang803cbb92015-12-01 12:24:36 -0800629 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
630 ReferenceInfo* ref_info = location->GetReferenceInfo();
631 if (!ref_info->IsSingleton() || location->IsValueKilledByLoopSideEffects()) {
632 // heap value is killed by loop side effects (stored into directly, or due to
633 // aliasing).
634 KeepIfIsStore(pre_header_heap_values[i]);
635 heap_values[i] = kUnknownHeapValue;
636 } else {
637 // A singleton's field that's not stored into inside a loop is invariant throughout
638 // the loop.
639 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800640 }
641 }
642 }
643
Mingyao Yang8df69d42015-10-22 15:40:58 -0700644 void MergePredecessorValues(HBasicBlock* block) {
645 const ArenaVector<HBasicBlock*>& predecessors = block->GetPredecessors();
646 if (predecessors.size() == 0) {
647 return;
648 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700649
Mingyao Yang8df69d42015-10-22 15:40:58 -0700650 ArenaVector<HInstruction*>& heap_values = heap_values_for_[block->GetBlockId()];
651 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700652 HInstruction* merged_value = nullptr;
653 // Whether merged_value is a result that's merged from all predecessors.
654 bool from_all_predecessors = true;
655 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
656 HInstruction* singleton_ref = nullptr;
Aart Bik71bf7b42016-11-16 10:17:46 -0800657 if (ref_info->IsSingletonAndRemovable()) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700658 // We do more analysis of liveness when merging heap values for such
659 // cases since stores into such references may potentially be eliminated.
660 singleton_ref = ref_info->GetReference();
661 }
662
663 for (HBasicBlock* predecessor : predecessors) {
664 HInstruction* pred_value = heap_values_for_[predecessor->GetBlockId()][i];
665 if ((singleton_ref != nullptr) &&
666 !singleton_ref->GetBlock()->Dominates(predecessor)) {
667 // singleton_ref is not live in this predecessor. Skip this predecessor since
668 // it does not really have the location.
669 DCHECK_EQ(pred_value, kUnknownHeapValue);
670 from_all_predecessors = false;
671 continue;
672 }
673 if (merged_value == nullptr) {
674 // First seen heap value.
675 merged_value = pred_value;
676 } else if (pred_value != merged_value) {
677 // There are conflicting values.
678 merged_value = kUnknownHeapValue;
679 break;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700680 }
681 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800682
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700683 if (merged_value == kUnknownHeapValue) {
684 // There are conflicting heap values from different predecessors.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800685 // Keep the last store in each predecessor since future loads cannot be eliminated.
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700686 for (HBasicBlock* predecessor : predecessors) {
687 ArenaVector<HInstruction*>& pred_values = heap_values_for_[predecessor->GetBlockId()];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800688 KeepIfIsStore(pred_values[i]);
689 }
690 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700691
692 if ((merged_value == nullptr) || !from_all_predecessors) {
693 DCHECK(singleton_ref != nullptr);
694 DCHECK((singleton_ref->GetBlock() == block) ||
695 !singleton_ref->GetBlock()->Dominates(block));
696 // singleton_ref is not defined before block or defined only in some of its
697 // predecessors, so block doesn't really have the location at its entry.
698 heap_values[i] = kUnknownHeapValue;
699 } else {
700 heap_values[i] = merged_value;
701 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700702 }
703 }
704
705 // `instruction` is being removed. Try to see if the null check on it
706 // can be removed. This can happen if the same value is set in two branches
707 // but not in dominators. Such as:
708 // int[] a = foo();
709 // if () {
710 // a[0] = 2;
711 // } else {
712 // a[0] = 2;
713 // }
714 // // a[0] can now be replaced with constant 2, and the null check on it can be removed.
715 void TryRemovingNullCheck(HInstruction* instruction) {
716 HInstruction* prev = instruction->GetPrevious();
717 if ((prev != nullptr) && prev->IsNullCheck() && (prev == instruction->InputAt(0))) {
718 // Previous instruction is a null check for this instruction. Remove the null check.
719 prev->ReplaceWith(prev->InputAt(0));
720 prev->GetBlock()->RemoveInstruction(prev);
721 }
722 }
723
724 HInstruction* GetDefaultValue(Primitive::Type type) {
725 switch (type) {
726 case Primitive::kPrimNot:
727 return GetGraph()->GetNullConstant();
728 case Primitive::kPrimBoolean:
729 case Primitive::kPrimByte:
730 case Primitive::kPrimChar:
731 case Primitive::kPrimShort:
732 case Primitive::kPrimInt:
733 return GetGraph()->GetIntConstant(0);
734 case Primitive::kPrimLong:
735 return GetGraph()->GetLongConstant(0);
736 case Primitive::kPrimFloat:
737 return GetGraph()->GetFloatConstant(0);
738 case Primitive::kPrimDouble:
739 return GetGraph()->GetDoubleConstant(0);
740 default:
741 UNREACHABLE();
742 }
743 }
744
745 void VisitGetLocation(HInstruction* instruction,
746 HInstruction* ref,
747 size_t offset,
748 HInstruction* index,
749 int16_t declaring_class_def_index) {
750 HInstruction* original_ref = HuntForOriginalReference(ref);
751 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
752 size_t idx = heap_location_collector_.FindHeapLocationIndex(
753 ref_info, offset, index, declaring_class_def_index);
754 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
755 ArenaVector<HInstruction*>& heap_values =
756 heap_values_for_[instruction->GetBlock()->GetBlockId()];
757 HInstruction* heap_value = heap_values[idx];
758 if (heap_value == kDefaultHeapValue) {
759 HInstruction* constant = GetDefaultValue(instruction->GetType());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800760 removed_loads_.push_back(instruction);
761 substitute_instructions_for_loads_.push_back(constant);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700762 heap_values[idx] = constant;
763 return;
764 }
Mingyao Yang86974902017-03-01 14:03:51 -0800765 if (heap_value != kUnknownHeapValue) {
766 if (heap_value->IsInstanceFieldSet() || heap_value->IsArraySet()) {
767 HInstruction* store = heap_value;
768 // This load must be from a singleton since it's from the same
769 // field/element that a "removed" store puts the value. That store
770 // must be to a singleton's field/element.
771 DCHECK(ref_info->IsSingleton());
772 // Get the real heap value of the store.
773 heap_value = heap_value->IsInstanceFieldSet() ? store->InputAt(1) : store->InputAt(2);
774 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800775 }
David Brazdil15693bf2015-12-16 10:30:45 +0000776 if (heap_value == kUnknownHeapValue) {
777 // Load isn't eliminated. Put the load as the value into the HeapLocation.
778 // This acts like GVN but with better aliasing analysis.
779 heap_values[idx] = instruction;
780 } else {
Nicolas Geoffray03971632016-03-17 10:44:24 +0000781 if (Primitive::PrimitiveKind(heap_value->GetType())
782 != Primitive::PrimitiveKind(instruction->GetType())) {
783 // The only situation where the same heap location has different type is when
Nicolas Geoffray65fef302016-05-04 14:00:12 +0100784 // we do an array get on an instruction that originates from the null constant
785 // (the null could be behind a field access, an array access, a null check or
786 // a bound type).
787 // In order to stay properly typed on primitive types, we do not eliminate
788 // the array gets.
Nicolas Geoffray03971632016-03-17 10:44:24 +0000789 if (kIsDebugBuild) {
790 DCHECK(heap_value->IsArrayGet()) << heap_value->DebugName();
791 DCHECK(instruction->IsArrayGet()) << instruction->DebugName();
Nicolas Geoffray03971632016-03-17 10:44:24 +0000792 }
793 return;
794 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800795 removed_loads_.push_back(instruction);
796 substitute_instructions_for_loads_.push_back(heap_value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700797 TryRemovingNullCheck(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700798 }
799 }
800
801 bool Equal(HInstruction* heap_value, HInstruction* value) {
802 if (heap_value == value) {
803 return true;
804 }
805 if (heap_value == kDefaultHeapValue && GetDefaultValue(value->GetType()) == value) {
806 return true;
807 }
808 return false;
809 }
810
811 void VisitSetLocation(HInstruction* instruction,
812 HInstruction* ref,
813 size_t offset,
814 HInstruction* index,
815 int16_t declaring_class_def_index,
816 HInstruction* value) {
817 HInstruction* original_ref = HuntForOriginalReference(ref);
818 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
819 size_t idx = heap_location_collector_.FindHeapLocationIndex(
820 ref_info, offset, index, declaring_class_def_index);
821 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
822 ArenaVector<HInstruction*>& heap_values =
823 heap_values_for_[instruction->GetBlock()->GetBlockId()];
824 HInstruction* heap_value = heap_values[idx];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800825 bool same_value = false;
826 bool possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700827 if (Equal(heap_value, value)) {
828 // Store into the heap location with the same value.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800829 same_value = true;
Mingyao Yang86974902017-03-01 14:03:51 -0800830 } else if (index != nullptr && ref_info->HasIndexAliasing()) {
831 // For array element, don't eliminate stores if the index can be
832 // aliased.
Aart Bik71bf7b42016-11-16 10:17:46 -0800833 } else if (ref_info->IsSingletonAndRemovable()) {
Mingyao Yang86974902017-03-01 14:03:51 -0800834 // Store into a field/element of a singleton instance/array that's not returned.
835 // The value cannot be killed due to aliasing/invocation. It can be redundant since
836 // future loads can directly get the value set by this instruction. The value can
837 // still be killed due to merging or loop side effects. Stores whose values are
838 // killed due to merging/loop side effects later will be removed from
839 // possibly_removed_stores_ when that is detected.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800840 possibly_redundant = true;
841 HNewInstance* new_instance = ref_info->GetReference()->AsNewInstance();
Mingyao Yang86974902017-03-01 14:03:51 -0800842 if (new_instance != nullptr && new_instance->IsFinalizable()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800843 // Finalizable objects escape globally. Need to keep the store.
844 possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700845 } else {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800846 HLoopInformation* loop_info = instruction->GetBlock()->GetLoopInformation();
847 if (loop_info != nullptr) {
848 // instruction is a store in the loop so the loop must does write.
849 DCHECK(side_effects_.GetLoopEffects(loop_info->GetHeader()).DoesAnyWrite());
850
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800851 if (loop_info->IsDefinedOutOfTheLoop(original_ref)) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800852 DCHECK(original_ref->GetBlock()->Dominates(loop_info->GetPreHeader()));
853 // Keep the store since its value may be needed at the loop header.
854 possibly_redundant = false;
855 } else {
856 // The singleton is created inside the loop. Value stored to it isn't needed at
857 // the loop header. This is true for outer loops also.
858 }
859 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700860 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700861 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800862 if (same_value || possibly_redundant) {
863 possibly_removed_stores_.push_back(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700864 }
Mingyao Yange9d6e602015-10-23 17:08:42 -0700865
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800866 if (!same_value) {
867 if (possibly_redundant) {
Mingyao Yang86974902017-03-01 14:03:51 -0800868 DCHECK(instruction->IsInstanceFieldSet() || instruction->IsArraySet());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800869 // Put the store as the heap value. If the value is loaded from heap
870 // by a load later, this store isn't really redundant.
871 heap_values[idx] = instruction;
872 } else {
873 heap_values[idx] = value;
874 }
875 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700876 // This store may kill values in other heap locations due to aliasing.
877 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800878 if (i == idx) {
879 continue;
880 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700881 if (heap_values[i] == value) {
882 // Same value should be kept even if aliasing happens.
883 continue;
884 }
885 if (heap_values[i] == kUnknownHeapValue) {
886 // Value is already unknown, no need for aliasing check.
887 continue;
888 }
889 if (heap_location_collector_.MayAlias(i, idx)) {
890 // Kill heap locations that may alias.
891 heap_values[i] = kUnknownHeapValue;
892 }
893 }
894 }
895
896 void VisitInstanceFieldGet(HInstanceFieldGet* instruction) OVERRIDE {
897 HInstruction* obj = instruction->InputAt(0);
898 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
899 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
900 VisitGetLocation(instruction, obj, offset, nullptr, declaring_class_def_index);
901 }
902
903 void VisitInstanceFieldSet(HInstanceFieldSet* instruction) OVERRIDE {
904 HInstruction* obj = instruction->InputAt(0);
905 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
906 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
907 HInstruction* value = instruction->InputAt(1);
908 VisitSetLocation(instruction, obj, offset, nullptr, declaring_class_def_index, value);
909 }
910
911 void VisitStaticFieldGet(HStaticFieldGet* instruction) OVERRIDE {
912 HInstruction* cls = instruction->InputAt(0);
913 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
914 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
915 VisitGetLocation(instruction, cls, offset, nullptr, declaring_class_def_index);
916 }
917
918 void VisitStaticFieldSet(HStaticFieldSet* instruction) OVERRIDE {
919 HInstruction* cls = instruction->InputAt(0);
920 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
921 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
922 HInstruction* value = instruction->InputAt(1);
923 VisitSetLocation(instruction, cls, offset, nullptr, declaring_class_def_index, value);
924 }
925
926 void VisitArrayGet(HArrayGet* instruction) OVERRIDE {
927 HInstruction* array = instruction->InputAt(0);
928 HInstruction* index = instruction->InputAt(1);
929 VisitGetLocation(instruction,
930 array,
931 HeapLocation::kInvalidFieldOffset,
932 index,
933 HeapLocation::kDeclaringClassDefIndexForArrays);
934 }
935
936 void VisitArraySet(HArraySet* instruction) OVERRIDE {
937 HInstruction* array = instruction->InputAt(0);
938 HInstruction* index = instruction->InputAt(1);
939 HInstruction* value = instruction->InputAt(2);
940 VisitSetLocation(instruction,
941 array,
942 HeapLocation::kInvalidFieldOffset,
943 index,
944 HeapLocation::kDeclaringClassDefIndexForArrays,
945 value);
946 }
947
948 void HandleInvoke(HInstruction* invoke) {
949 ArenaVector<HInstruction*>& heap_values =
950 heap_values_for_[invoke->GetBlock()->GetBlockId()];
951 for (size_t i = 0; i < heap_values.size(); i++) {
952 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
953 if (ref_info->IsSingleton()) {
954 // Singleton references cannot be seen by the callee.
955 } else {
956 heap_values[i] = kUnknownHeapValue;
957 }
958 }
959 }
960
961 void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) OVERRIDE {
962 HandleInvoke(invoke);
963 }
964
965 void VisitInvokeVirtual(HInvokeVirtual* invoke) OVERRIDE {
966 HandleInvoke(invoke);
967 }
968
969 void VisitInvokeInterface(HInvokeInterface* invoke) OVERRIDE {
970 HandleInvoke(invoke);
971 }
972
973 void VisitInvokeUnresolved(HInvokeUnresolved* invoke) OVERRIDE {
974 HandleInvoke(invoke);
975 }
976
Orion Hodsonac141392017-01-13 11:53:47 +0000977 void VisitInvokePolymorphic(HInvokePolymorphic* invoke) OVERRIDE {
978 HandleInvoke(invoke);
979 }
980
Mingyao Yang8df69d42015-10-22 15:40:58 -0700981 void VisitClinitCheck(HClinitCheck* clinit) OVERRIDE {
982 HandleInvoke(clinit);
983 }
984
985 void VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet* instruction) OVERRIDE {
986 // Conservatively treat it as an invocation.
987 HandleInvoke(instruction);
988 }
989
990 void VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet* instruction) OVERRIDE {
991 // Conservatively treat it as an invocation.
992 HandleInvoke(instruction);
993 }
994
995 void VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet* instruction) OVERRIDE {
996 // Conservatively treat it as an invocation.
997 HandleInvoke(instruction);
998 }
999
1000 void VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet* instruction) OVERRIDE {
1001 // Conservatively treat it as an invocation.
1002 HandleInvoke(instruction);
1003 }
1004
1005 void VisitNewInstance(HNewInstance* new_instance) OVERRIDE {
1006 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_instance);
1007 if (ref_info == nullptr) {
1008 // new_instance isn't used for field accesses. No need to process it.
1009 return;
1010 }
Aart Bik71bf7b42016-11-16 10:17:46 -08001011 if (ref_info->IsSingletonAndRemovable() &&
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001012 !new_instance->IsFinalizable() &&
Nicolas Geoffray5247c082017-01-13 14:17:29 +00001013 !new_instance->NeedsChecks()) {
Mingyao Yang062157f2016-03-02 10:15:36 -08001014 singleton_new_instances_.push_back(new_instance);
Mingyao Yang8df69d42015-10-22 15:40:58 -07001015 }
1016 ArenaVector<HInstruction*>& heap_values =
1017 heap_values_for_[new_instance->GetBlock()->GetBlockId()];
1018 for (size_t i = 0; i < heap_values.size(); i++) {
1019 HInstruction* ref =
1020 heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo()->GetReference();
1021 size_t offset = heap_location_collector_.GetHeapLocation(i)->GetOffset();
1022 if (ref == new_instance && offset >= mirror::kObjectHeaderSize) {
1023 // Instance fields except the header fields are set to default heap values.
1024 heap_values[i] = kDefaultHeapValue;
1025 }
1026 }
1027 }
1028
Mingyao Yang86974902017-03-01 14:03:51 -08001029 void VisitNewArray(HNewArray* new_array) OVERRIDE {
1030 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_array);
1031 if (ref_info == nullptr) {
1032 // new_array isn't used for array accesses. No need to process it.
1033 return;
1034 }
1035 if (ref_info->IsSingletonAndRemovable()) {
1036 singleton_new_arrays_.push_back(new_array);
1037 }
1038 ArenaVector<HInstruction*>& heap_values =
1039 heap_values_for_[new_array->GetBlock()->GetBlockId()];
1040 for (size_t i = 0; i < heap_values.size(); i++) {
1041 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
1042 HInstruction* ref = location->GetReferenceInfo()->GetReference();
1043 if (ref == new_array && location->GetIndex() != nullptr) {
1044 // Array elements are set to default heap values.
1045 heap_values[i] = kDefaultHeapValue;
1046 }
1047 }
1048 }
1049
Mingyao Yang8df69d42015-10-22 15:40:58 -07001050 // Find an instruction's substitute if it should be removed.
1051 // Return the same instruction if it should not be removed.
1052 HInstruction* FindSubstitute(HInstruction* instruction) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001053 size_t size = removed_loads_.size();
Mingyao Yang8df69d42015-10-22 15:40:58 -07001054 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001055 if (removed_loads_[i] == instruction) {
1056 return substitute_instructions_for_loads_[i];
Mingyao Yang8df69d42015-10-22 15:40:58 -07001057 }
1058 }
1059 return instruction;
1060 }
1061
1062 const HeapLocationCollector& heap_location_collector_;
1063 const SideEffectsAnalysis& side_effects_;
1064
1065 // One array of heap values for each block.
1066 ArenaVector<ArenaVector<HInstruction*>> heap_values_for_;
1067
1068 // We record the instructions that should be eliminated but may be
1069 // used by heap locations. They'll be removed in the end.
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001070 ArenaVector<HInstruction*> removed_loads_;
1071 ArenaVector<HInstruction*> substitute_instructions_for_loads_;
1072
1073 // Stores in this list may be removed from the list later when it's
1074 // found that the store cannot be eliminated.
1075 ArenaVector<HInstruction*> possibly_removed_stores_;
1076
Mingyao Yang8df69d42015-10-22 15:40:58 -07001077 ArenaVector<HInstruction*> singleton_new_instances_;
Mingyao Yang86974902017-03-01 14:03:51 -08001078 ArenaVector<HInstruction*> singleton_new_arrays_;
Mingyao Yang8df69d42015-10-22 15:40:58 -07001079
1080 DISALLOW_COPY_AND_ASSIGN(LSEVisitor);
1081};
1082
1083void LoadStoreElimination::Run() {
David Brazdil8993caf2015-12-07 10:04:40 +00001084 if (graph_->IsDebuggable() || graph_->HasTryCatch()) {
Mingyao Yang8df69d42015-10-22 15:40:58 -07001085 // Debugger may set heap values or trigger deoptimization of callers.
David Brazdil8993caf2015-12-07 10:04:40 +00001086 // Try/catch support not implemented yet.
Mingyao Yang8df69d42015-10-22 15:40:58 -07001087 // Skip this optimization.
1088 return;
1089 }
1090 HeapLocationCollector heap_location_collector(graph_);
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001091 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1092 heap_location_collector.VisitBasicBlock(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -07001093 }
1094 if (heap_location_collector.GetNumberOfHeapLocations() > kMaxNumberOfHeapLocations) {
1095 // Bail out if there are too many heap locations to deal with.
1096 return;
1097 }
1098 if (!heap_location_collector.HasHeapStores()) {
1099 // Without heap stores, this pass would act mostly as GVN on heap accesses.
1100 return;
1101 }
1102 if (heap_location_collector.HasVolatile() || heap_location_collector.HasMonitorOps()) {
1103 // Don't do load/store elimination if the method has volatile field accesses or
1104 // monitor operations, for now.
1105 // TODO: do it right.
1106 return;
1107 }
1108 heap_location_collector.BuildAliasingMatrix();
1109 LSEVisitor lse_visitor(graph_, heap_location_collector, side_effects_);
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001110 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1111 lse_visitor.VisitBasicBlock(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -07001112 }
1113 lse_visitor.RemoveInstructions();
1114}
1115
1116} // namespace art