blob: 561dcfbb1fc433830ae0b7600ce94509765b4f32 [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"
18#include "side_effects_analysis.h"
19
20#include <iostream>
21
22namespace art {
23
24class ReferenceInfo;
25
26// A cap for the number of heap locations to prevent pathological time/space consumption.
27// The number of heap locations for most of the methods stays below this threshold.
28constexpr size_t kMaxNumberOfHeapLocations = 32;
29
30// A ReferenceInfo contains additional info about a reference such as
31// whether it's a singleton, returned, etc.
32class ReferenceInfo : public ArenaObject<kArenaAllocMisc> {
33 public:
34 ReferenceInfo(HInstruction* reference, size_t pos) : reference_(reference), position_(pos) {
35 is_singleton_ = true;
36 is_singleton_and_not_returned_ = true;
37 if (!reference_->IsNewInstance() && !reference_->IsNewArray()) {
38 // For references not allocated in the method, don't assume anything.
39 is_singleton_ = false;
40 is_singleton_and_not_returned_ = false;
41 return;
42 }
43
44 // Visit all uses to determine if this reference can spread into the heap,
45 // a method call, etc.
46 for (HUseIterator<HInstruction*> use_it(reference_->GetUses());
47 !use_it.Done();
48 use_it.Advance()) {
49 HInstruction* use = use_it.Current()->GetUser();
50 DCHECK(!use->IsNullCheck()) << "NullCheck should have been eliminated";
51 if (use->IsBoundType()) {
52 // BoundType shouldn't normally be necessary for a NewInstance.
53 // Just be conservative for the uncommon cases.
54 is_singleton_ = false;
55 is_singleton_and_not_returned_ = false;
56 return;
57 }
Mingyao Yange5c71f92016-02-02 20:10:32 -080058 if (use->IsPhi() || use->IsSelect() || use->IsInvoke() ||
Mingyao Yang8df69d42015-10-22 15:40:58 -070059 (use->IsInstanceFieldSet() && (reference_ == use->InputAt(1))) ||
60 (use->IsUnresolvedInstanceFieldSet() && (reference_ == use->InputAt(1))) ||
61 (use->IsStaticFieldSet() && (reference_ == use->InputAt(1))) ||
Nicolas Geoffrayd9309292015-10-31 22:21:31 +000062 (use->IsUnresolvedStaticFieldSet() && (reference_ == use->InputAt(0))) ||
Mingyao Yang8df69d42015-10-22 15:40:58 -070063 (use->IsArraySet() && (reference_ == use->InputAt(2)))) {
Mingyao Yang40bcb932016-02-03 05:46:57 -080064 // reference_ is merged to HPhi/HSelect, passed to a callee, or stored to heap.
Mingyao Yang8df69d42015-10-22 15:40:58 -070065 // reference_ isn't the only name that can refer to its value anymore.
66 is_singleton_ = false;
67 is_singleton_and_not_returned_ = false;
68 return;
69 }
70 if (use->IsReturn()) {
71 is_singleton_and_not_returned_ = false;
72 }
73 }
74 }
75
76 HInstruction* GetReference() const {
77 return reference_;
78 }
79
80 size_t GetPosition() const {
81 return position_;
82 }
83
84 // Returns true if reference_ is the only name that can refer to its value during
85 // the lifetime of the method. So it's guaranteed to not have any alias in
86 // the method (including its callees).
87 bool IsSingleton() const {
88 return is_singleton_;
89 }
90
91 // Returns true if reference_ is a singleton and not returned to the caller.
92 // The allocation and stores into reference_ may be eliminated for such cases.
93 bool IsSingletonAndNotReturned() const {
94 return is_singleton_and_not_returned_;
95 }
96
97 private:
98 HInstruction* const reference_;
99 const size_t position_; // position in HeapLocationCollector's ref_info_array_.
100 bool is_singleton_; // can only be referred to by a single name in the method.
101 bool is_singleton_and_not_returned_; // reference_ is singleton and not returned to caller.
102
103 DISALLOW_COPY_AND_ASSIGN(ReferenceInfo);
104};
105
106// A heap location is a reference-offset/index pair that a value can be loaded from
107// or stored to.
108class HeapLocation : public ArenaObject<kArenaAllocMisc> {
109 public:
110 static constexpr size_t kInvalidFieldOffset = -1;
111
112 // TODO: more fine-grained array types.
113 static constexpr int16_t kDeclaringClassDefIndexForArrays = -1;
114
115 HeapLocation(ReferenceInfo* ref_info,
116 size_t offset,
117 HInstruction* index,
118 int16_t declaring_class_def_index)
119 : ref_info_(ref_info),
120 offset_(offset),
121 index_(index),
Mingyao Yang803cbb92015-12-01 12:24:36 -0800122 declaring_class_def_index_(declaring_class_def_index),
123 value_killed_by_loop_side_effects_(true) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700124 DCHECK(ref_info != nullptr);
125 DCHECK((offset == kInvalidFieldOffset && index != nullptr) ||
126 (offset != kInvalidFieldOffset && index == nullptr));
Mingyao Yang803cbb92015-12-01 12:24:36 -0800127 if (ref_info->IsSingleton() && !IsArrayElement()) {
128 // Assume this location's value cannot be killed by loop side effects
129 // until proven otherwise.
130 value_killed_by_loop_side_effects_ = false;
131 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700132 }
133
134 ReferenceInfo* GetReferenceInfo() const { return ref_info_; }
135 size_t GetOffset() const { return offset_; }
136 HInstruction* GetIndex() const { return index_; }
137
138 // Returns the definition of declaring class' dex index.
139 // It's kDeclaringClassDefIndexForArrays for an array element.
140 int16_t GetDeclaringClassDefIndex() const {
141 return declaring_class_def_index_;
142 }
143
144 bool IsArrayElement() const {
145 return index_ != nullptr;
146 }
147
Mingyao Yang803cbb92015-12-01 12:24:36 -0800148 bool IsValueKilledByLoopSideEffects() const {
149 return value_killed_by_loop_side_effects_;
150 }
151
152 void SetValueKilledByLoopSideEffects(bool val) {
153 value_killed_by_loop_side_effects_ = val;
154 }
155
Mingyao Yang8df69d42015-10-22 15:40:58 -0700156 private:
157 ReferenceInfo* const ref_info_; // reference for instance/static field or array access.
158 const size_t offset_; // offset of static/instance field.
159 HInstruction* const index_; // index of an array element.
160 const int16_t declaring_class_def_index_; // declaring class's def's dex index.
Mingyao Yang803cbb92015-12-01 12:24:36 -0800161 bool value_killed_by_loop_side_effects_; // value of this location may be killed by loop
162 // side effects because this location is stored
163 // into inside a loop.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700164
165 DISALLOW_COPY_AND_ASSIGN(HeapLocation);
166};
167
168static HInstruction* HuntForOriginalReference(HInstruction* ref) {
169 DCHECK(ref != nullptr);
170 while (ref->IsNullCheck() || ref->IsBoundType()) {
171 ref = ref->InputAt(0);
172 }
173 return ref;
174}
175
176// A HeapLocationCollector collects all relevant heap locations and keeps
177// an aliasing matrix for all locations.
178class HeapLocationCollector : public HGraphVisitor {
179 public:
180 static constexpr size_t kHeapLocationNotFound = -1;
181 // Start with a single uint32_t word. That's enough bits for pair-wise
182 // aliasing matrix of 8 heap locations.
183 static constexpr uint32_t kInitialAliasingMatrixBitVectorSize = 32;
184
185 explicit HeapLocationCollector(HGraph* graph)
186 : HGraphVisitor(graph),
187 ref_info_array_(graph->GetArena()->Adapter(kArenaAllocLSE)),
188 heap_locations_(graph->GetArena()->Adapter(kArenaAllocLSE)),
189 aliasing_matrix_(graph->GetArena(), kInitialAliasingMatrixBitVectorSize, true),
190 has_heap_stores_(false),
191 has_volatile_(false),
192 has_monitor_operations_(false),
193 may_deoptimize_(false) {}
194
195 size_t GetNumberOfHeapLocations() const {
196 return heap_locations_.size();
197 }
198
199 HeapLocation* GetHeapLocation(size_t index) const {
200 return heap_locations_[index];
201 }
202
203 ReferenceInfo* FindReferenceInfoOf(HInstruction* ref) const {
204 for (size_t i = 0; i < ref_info_array_.size(); i++) {
205 ReferenceInfo* ref_info = ref_info_array_[i];
206 if (ref_info->GetReference() == ref) {
207 DCHECK_EQ(i, ref_info->GetPosition());
208 return ref_info;
209 }
210 }
211 return nullptr;
212 }
213
214 bool HasHeapStores() const {
215 return has_heap_stores_;
216 }
217
218 bool HasVolatile() const {
219 return has_volatile_;
220 }
221
222 bool HasMonitorOps() const {
223 return has_monitor_operations_;
224 }
225
226 // Returns whether this method may be deoptimized.
227 // Currently we don't have meta data support for deoptimizing
228 // a method that eliminates allocations/stores.
229 bool MayDeoptimize() const {
230 return may_deoptimize_;
231 }
232
233 // Find and return the heap location index in heap_locations_.
234 size_t FindHeapLocationIndex(ReferenceInfo* ref_info,
235 size_t offset,
236 HInstruction* index,
237 int16_t declaring_class_def_index) const {
238 for (size_t i = 0; i < heap_locations_.size(); i++) {
239 HeapLocation* loc = heap_locations_[i];
240 if (loc->GetReferenceInfo() == ref_info &&
241 loc->GetOffset() == offset &&
242 loc->GetIndex() == index &&
243 loc->GetDeclaringClassDefIndex() == declaring_class_def_index) {
244 return i;
245 }
246 }
247 return kHeapLocationNotFound;
248 }
249
250 // Returns true if heap_locations_[index1] and heap_locations_[index2] may alias.
251 bool MayAlias(size_t index1, size_t index2) const {
252 if (index1 < index2) {
253 return aliasing_matrix_.IsBitSet(AliasingMatrixPosition(index1, index2));
254 } else if (index1 > index2) {
255 return aliasing_matrix_.IsBitSet(AliasingMatrixPosition(index2, index1));
256 } else {
257 DCHECK(false) << "index1 and index2 are expected to be different";
258 return true;
259 }
260 }
261
262 void BuildAliasingMatrix() {
263 const size_t number_of_locations = heap_locations_.size();
264 if (number_of_locations == 0) {
265 return;
266 }
267 size_t pos = 0;
268 // Compute aliasing info between every pair of different heap locations.
269 // Save the result in a matrix represented as a BitVector.
270 for (size_t i = 0; i < number_of_locations - 1; i++) {
271 for (size_t j = i + 1; j < number_of_locations; j++) {
272 if (ComputeMayAlias(i, j)) {
273 aliasing_matrix_.SetBit(CheckedAliasingMatrixPosition(i, j, pos));
274 }
275 pos++;
276 }
277 }
278 }
279
280 private:
281 // An allocation cannot alias with a name which already exists at the point
282 // of the allocation, such as a parameter or a load happening before the allocation.
283 bool MayAliasWithPreexistenceChecking(ReferenceInfo* ref_info1, ReferenceInfo* ref_info2) const {
284 if (ref_info1->GetReference()->IsNewInstance() || ref_info1->GetReference()->IsNewArray()) {
285 // Any reference that can alias with the allocation must appear after it in the block/in
286 // the block's successors. In reverse post order, those instructions will be visited after
287 // the allocation.
288 return ref_info2->GetPosition() >= ref_info1->GetPosition();
289 }
290 return true;
291 }
292
293 bool CanReferencesAlias(ReferenceInfo* ref_info1, ReferenceInfo* ref_info2) const {
294 if (ref_info1 == ref_info2) {
295 return true;
296 } else if (ref_info1->IsSingleton()) {
297 return false;
298 } else if (ref_info2->IsSingleton()) {
299 return false;
300 } else if (!MayAliasWithPreexistenceChecking(ref_info1, ref_info2) ||
301 !MayAliasWithPreexistenceChecking(ref_info2, ref_info1)) {
302 return false;
303 }
304 return true;
305 }
306
307 // `index1` and `index2` are indices in the array of collected heap locations.
308 // Returns the position in the bit vector that tracks whether the two heap
309 // locations may alias.
310 size_t AliasingMatrixPosition(size_t index1, size_t index2) const {
311 DCHECK(index2 > index1);
312 const size_t number_of_locations = heap_locations_.size();
313 // It's (num_of_locations - 1) + ... + (num_of_locations - index1) + (index2 - index1 - 1).
314 return (number_of_locations * index1 - (1 + index1) * index1 / 2 + (index2 - index1 - 1));
315 }
316
317 // An additional position is passed in to make sure the calculated position is correct.
318 size_t CheckedAliasingMatrixPosition(size_t index1, size_t index2, size_t position) {
319 size_t calculated_position = AliasingMatrixPosition(index1, index2);
320 DCHECK_EQ(calculated_position, position);
321 return calculated_position;
322 }
323
324 // Compute if two locations may alias to each other.
325 bool ComputeMayAlias(size_t index1, size_t index2) const {
326 HeapLocation* loc1 = heap_locations_[index1];
327 HeapLocation* loc2 = heap_locations_[index2];
328 if (loc1->GetOffset() != loc2->GetOffset()) {
329 // Either two different instance fields, or one is an instance
330 // field and the other is an array element.
331 return false;
332 }
333 if (loc1->GetDeclaringClassDefIndex() != loc2->GetDeclaringClassDefIndex()) {
334 // Different types.
335 return false;
336 }
337 if (!CanReferencesAlias(loc1->GetReferenceInfo(), loc2->GetReferenceInfo())) {
338 return false;
339 }
340 if (loc1->IsArrayElement() && loc2->IsArrayElement()) {
341 HInstruction* array_index1 = loc1->GetIndex();
342 HInstruction* array_index2 = loc2->GetIndex();
343 DCHECK(array_index1 != nullptr);
344 DCHECK(array_index2 != nullptr);
345 if (array_index1->IsIntConstant() &&
346 array_index2->IsIntConstant() &&
347 array_index1->AsIntConstant()->GetValue() != array_index2->AsIntConstant()->GetValue()) {
348 // Different constant indices do not alias.
349 return false;
350 }
351 }
352 return true;
353 }
354
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800355 ReferenceInfo* GetOrCreateReferenceInfo(HInstruction* instruction) {
356 ReferenceInfo* ref_info = FindReferenceInfoOf(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700357 if (ref_info == nullptr) {
358 size_t pos = ref_info_array_.size();
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800359 ref_info = new (GetGraph()->GetArena()) ReferenceInfo(instruction, pos);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700360 ref_info_array_.push_back(ref_info);
361 }
362 return ref_info;
363 }
364
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800365 void CreateReferenceInfoForReferenceType(HInstruction* instruction) {
366 if (instruction->GetType() != Primitive::kPrimNot) {
367 return;
368 }
369 DCHECK(FindReferenceInfoOf(instruction) == nullptr);
370 GetOrCreateReferenceInfo(instruction);
371 }
372
Mingyao Yang8df69d42015-10-22 15:40:58 -0700373 HeapLocation* GetOrCreateHeapLocation(HInstruction* ref,
374 size_t offset,
375 HInstruction* index,
376 int16_t declaring_class_def_index) {
377 HInstruction* original_ref = HuntForOriginalReference(ref);
378 ReferenceInfo* ref_info = GetOrCreateReferenceInfo(original_ref);
379 size_t heap_location_idx = FindHeapLocationIndex(
380 ref_info, offset, index, declaring_class_def_index);
381 if (heap_location_idx == kHeapLocationNotFound) {
382 HeapLocation* heap_loc = new (GetGraph()->GetArena())
383 HeapLocation(ref_info, offset, index, declaring_class_def_index);
384 heap_locations_.push_back(heap_loc);
385 return heap_loc;
386 }
387 return heap_locations_[heap_location_idx];
388 }
389
Mingyao Yang803cbb92015-12-01 12:24:36 -0800390 HeapLocation* VisitFieldAccess(HInstruction* ref, const FieldInfo& field_info) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700391 if (field_info.IsVolatile()) {
392 has_volatile_ = true;
393 }
394 const uint16_t declaring_class_def_index = field_info.GetDeclaringClassDefIndex();
395 const size_t offset = field_info.GetFieldOffset().SizeValue();
Mingyao Yang803cbb92015-12-01 12:24:36 -0800396 return GetOrCreateHeapLocation(ref, offset, nullptr, declaring_class_def_index);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700397 }
398
399 void VisitArrayAccess(HInstruction* array, HInstruction* index) {
400 GetOrCreateHeapLocation(array, HeapLocation::kInvalidFieldOffset,
401 index, HeapLocation::kDeclaringClassDefIndexForArrays);
402 }
403
404 void VisitInstanceFieldGet(HInstanceFieldGet* instruction) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800405 VisitFieldAccess(instruction->InputAt(0), instruction->GetFieldInfo());
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800406 CreateReferenceInfoForReferenceType(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700407 }
408
409 void VisitInstanceFieldSet(HInstanceFieldSet* instruction) OVERRIDE {
Mingyao Yang803cbb92015-12-01 12:24:36 -0800410 HeapLocation* location = VisitFieldAccess(instruction->InputAt(0), instruction->GetFieldInfo());
Mingyao Yang8df69d42015-10-22 15:40:58 -0700411 has_heap_stores_ = true;
Mingyao Yang803cbb92015-12-01 12:24:36 -0800412 if (instruction->GetBlock()->GetLoopInformation() != nullptr) {
413 location->SetValueKilledByLoopSideEffects(true);
414 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700415 }
416
417 void VisitStaticFieldGet(HStaticFieldGet* instruction) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800418 VisitFieldAccess(instruction->InputAt(0), instruction->GetFieldInfo());
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800419 CreateReferenceInfoForReferenceType(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700420 }
421
422 void VisitStaticFieldSet(HStaticFieldSet* instruction) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800423 VisitFieldAccess(instruction->InputAt(0), instruction->GetFieldInfo());
Mingyao Yang8df69d42015-10-22 15:40:58 -0700424 has_heap_stores_ = true;
425 }
426
427 // We intentionally don't collect HUnresolvedInstanceField/HUnresolvedStaticField accesses
428 // since we cannot accurately track the fields.
429
430 void VisitArrayGet(HArrayGet* instruction) OVERRIDE {
431 VisitArrayAccess(instruction->InputAt(0), instruction->InputAt(1));
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800432 CreateReferenceInfoForReferenceType(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700433 }
434
435 void VisitArraySet(HArraySet* instruction) OVERRIDE {
436 VisitArrayAccess(instruction->InputAt(0), instruction->InputAt(1));
437 has_heap_stores_ = true;
438 }
439
440 void VisitNewInstance(HNewInstance* new_instance) OVERRIDE {
441 // Any references appearing in the ref_info_array_ so far cannot alias with new_instance.
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800442 CreateReferenceInfoForReferenceType(new_instance);
443 }
444
445 void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* instruction) OVERRIDE {
446 CreateReferenceInfoForReferenceType(instruction);
447 }
448
449 void VisitInvokeVirtual(HInvokeVirtual* instruction) OVERRIDE {
450 CreateReferenceInfoForReferenceType(instruction);
451 }
452
453 void VisitInvokeInterface(HInvokeInterface* instruction) OVERRIDE {
454 CreateReferenceInfoForReferenceType(instruction);
455 }
456
457 void VisitParameterValue(HParameterValue* instruction) OVERRIDE {
458 CreateReferenceInfoForReferenceType(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700459 }
460
Mingyao Yang40bcb932016-02-03 05:46:57 -0800461 void VisitSelect(HSelect* instruction) OVERRIDE {
462 CreateReferenceInfoForReferenceType(instruction);
463 }
464
Mingyao Yang8df69d42015-10-22 15:40:58 -0700465 void VisitDeoptimize(HDeoptimize* instruction ATTRIBUTE_UNUSED) OVERRIDE {
466 may_deoptimize_ = true;
467 }
468
469 void VisitMonitorOperation(HMonitorOperation* monitor ATTRIBUTE_UNUSED) OVERRIDE {
470 has_monitor_operations_ = true;
471 }
472
473 ArenaVector<ReferenceInfo*> ref_info_array_; // All references used for heap accesses.
474 ArenaVector<HeapLocation*> heap_locations_; // All heap locations.
475 ArenaBitVector aliasing_matrix_; // aliasing info between each pair of locations.
476 bool has_heap_stores_; // If there is no heap stores, LSE acts as GVN with better
477 // alias analysis and won't be as effective.
478 bool has_volatile_; // If there are volatile field accesses.
479 bool has_monitor_operations_; // If there are monitor operations.
480 bool may_deoptimize_;
481
482 DISALLOW_COPY_AND_ASSIGN(HeapLocationCollector);
483};
484
485// An unknown heap value. Loads with such a value in the heap location cannot be eliminated.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800486// A heap location can be set to kUnknownHeapValue when:
487// - initially set a value.
488// - killed due to aliasing, merging, invocation, or loop side effects.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700489static HInstruction* const kUnknownHeapValue =
490 reinterpret_cast<HInstruction*>(static_cast<uintptr_t>(-1));
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800491
Mingyao Yang8df69d42015-10-22 15:40:58 -0700492// Default heap value after an allocation.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800493// A heap location can be set to that value right after an allocation.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700494static HInstruction* const kDefaultHeapValue =
495 reinterpret_cast<HInstruction*>(static_cast<uintptr_t>(-2));
496
497class LSEVisitor : public HGraphVisitor {
498 public:
499 LSEVisitor(HGraph* graph,
500 const HeapLocationCollector& heap_locations_collector,
501 const SideEffectsAnalysis& side_effects)
502 : HGraphVisitor(graph),
503 heap_location_collector_(heap_locations_collector),
504 side_effects_(side_effects),
505 heap_values_for_(graph->GetBlocks().size(),
506 ArenaVector<HInstruction*>(heap_locations_collector.
507 GetNumberOfHeapLocations(),
508 kUnknownHeapValue,
509 graph->GetArena()->Adapter(kArenaAllocLSE)),
510 graph->GetArena()->Adapter(kArenaAllocLSE)),
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800511 removed_loads_(graph->GetArena()->Adapter(kArenaAllocLSE)),
512 substitute_instructions_for_loads_(graph->GetArena()->Adapter(kArenaAllocLSE)),
513 possibly_removed_stores_(graph->GetArena()->Adapter(kArenaAllocLSE)),
Mingyao Yang8df69d42015-10-22 15:40:58 -0700514 singleton_new_instances_(graph->GetArena()->Adapter(kArenaAllocLSE)) {
515 }
516
517 void VisitBasicBlock(HBasicBlock* block) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800518 // Populate the heap_values array for this block.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700519 // TODO: try to reuse the heap_values array from one predecessor if possible.
520 if (block->IsLoopHeader()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800521 HandleLoopSideEffects(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700522 } else {
523 MergePredecessorValues(block);
524 }
525 HGraphVisitor::VisitBasicBlock(block);
526 }
527
528 // Remove recorded instructions that should be eliminated.
529 void RemoveInstructions() {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800530 size_t size = removed_loads_.size();
531 DCHECK_EQ(size, substitute_instructions_for_loads_.size());
Mingyao Yang8df69d42015-10-22 15:40:58 -0700532 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800533 HInstruction* load = removed_loads_[i];
534 DCHECK(load != nullptr);
535 DCHECK(load->IsInstanceFieldGet() ||
536 load->IsStaticFieldGet() ||
537 load->IsArrayGet());
538 HInstruction* substitute = substitute_instructions_for_loads_[i];
539 DCHECK(substitute != nullptr);
540 // Keep tracing substitute till one that's not removed.
541 HInstruction* sub_sub = FindSubstitute(substitute);
542 while (sub_sub != substitute) {
543 substitute = sub_sub;
544 sub_sub = FindSubstitute(substitute);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700545 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800546 load->ReplaceWith(substitute);
547 load->GetBlock()->RemoveInstruction(load);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700548 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800549
550 // At this point, stores in possibly_removed_stores_ can be safely removed.
551 size = possibly_removed_stores_.size();
552 for (size_t i = 0; i < size; i++) {
553 HInstruction* store = possibly_removed_stores_[i];
554 DCHECK(store->IsInstanceFieldSet() || store->IsStaticFieldSet() || store->IsArraySet());
555 store->GetBlock()->RemoveInstruction(store);
556 }
557
Mingyao Yang8df69d42015-10-22 15:40:58 -0700558 // TODO: remove unnecessary allocations.
559 // Eliminate instructions in singleton_new_instances_ that:
560 // - don't have uses,
561 // - don't have finalizers,
562 // - are instantiable and accessible,
563 // - have no/separate clinit check.
564 }
565
566 private:
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800567 // If heap_values[index] is an instance field store, need to keep the store.
568 // This is necessary if a heap value is killed due to merging, or loop side
569 // effects (which is essentially merging also), since a load later from the
570 // location won't be eliminated.
571 void KeepIfIsStore(HInstruction* heap_value) {
572 if (heap_value == kDefaultHeapValue ||
573 heap_value == kUnknownHeapValue ||
574 !heap_value->IsInstanceFieldSet()) {
575 return;
576 }
577 auto idx = std::find(possibly_removed_stores_.begin(),
578 possibly_removed_stores_.end(), heap_value);
579 if (idx != possibly_removed_stores_.end()) {
580 // Make sure the store is kept.
581 possibly_removed_stores_.erase(idx);
582 }
583 }
584
585 void HandleLoopSideEffects(HBasicBlock* block) {
586 DCHECK(block->IsLoopHeader());
587 int block_id = block->GetBlockId();
588 ArenaVector<HInstruction*>& heap_values = heap_values_for_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000589
590 // Don't eliminate loads in irreducible loops. This is safe for singletons, because
591 // they are always used by the non-eliminated loop-phi.
592 if (block->GetLoopInformation()->IsIrreducible()) {
593 if (kIsDebugBuild) {
594 for (size_t i = 0; i < heap_values.size(); i++) {
595 DCHECK_EQ(heap_values[i], kUnknownHeapValue);
596 }
597 }
598 return;
599 }
600
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800601 HBasicBlock* pre_header = block->GetLoopInformation()->GetPreHeader();
602 ArenaVector<HInstruction*>& pre_header_heap_values =
603 heap_values_for_[pre_header->GetBlockId()];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000604
Mingyao Yang803cbb92015-12-01 12:24:36 -0800605 // Inherit the values from pre-header.
606 for (size_t i = 0; i < heap_values.size(); i++) {
607 heap_values[i] = pre_header_heap_values[i];
608 }
609
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800610 // We do a single pass in reverse post order. For loops, use the side effects as a hint
611 // to see if the heap values should be killed.
612 if (side_effects_.GetLoopEffects(block).DoesAnyWrite()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800613 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang803cbb92015-12-01 12:24:36 -0800614 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
615 ReferenceInfo* ref_info = location->GetReferenceInfo();
616 if (!ref_info->IsSingleton() || location->IsValueKilledByLoopSideEffects()) {
617 // heap value is killed by loop side effects (stored into directly, or due to
618 // aliasing).
619 KeepIfIsStore(pre_header_heap_values[i]);
620 heap_values[i] = kUnknownHeapValue;
621 } else {
622 // A singleton's field that's not stored into inside a loop is invariant throughout
623 // the loop.
624 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800625 }
626 }
627 }
628
Mingyao Yang8df69d42015-10-22 15:40:58 -0700629 void MergePredecessorValues(HBasicBlock* block) {
630 const ArenaVector<HBasicBlock*>& predecessors = block->GetPredecessors();
631 if (predecessors.size() == 0) {
632 return;
633 }
634 ArenaVector<HInstruction*>& heap_values = heap_values_for_[block->GetBlockId()];
635 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800636 HInstruction* pred0_value = heap_values_for_[predecessors[0]->GetBlockId()][i];
637 heap_values[i] = pred0_value;
638 if (pred0_value != kUnknownHeapValue) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700639 for (size_t j = 1; j < predecessors.size(); j++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800640 HInstruction* pred_value = heap_values_for_[predecessors[j]->GetBlockId()][i];
641 if (pred_value != pred0_value) {
642 heap_values[i] = kUnknownHeapValue;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700643 break;
644 }
645 }
646 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800647
648 if (heap_values[i] == kUnknownHeapValue) {
649 // Keep the last store in each predecessor since future loads cannot be eliminated.
650 for (size_t j = 0; j < predecessors.size(); j++) {
651 ArenaVector<HInstruction*>& pred_values = heap_values_for_[predecessors[j]->GetBlockId()];
652 KeepIfIsStore(pred_values[i]);
653 }
654 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700655 }
656 }
657
658 // `instruction` is being removed. Try to see if the null check on it
659 // can be removed. This can happen if the same value is set in two branches
660 // but not in dominators. Such as:
661 // int[] a = foo();
662 // if () {
663 // a[0] = 2;
664 // } else {
665 // a[0] = 2;
666 // }
667 // // a[0] can now be replaced with constant 2, and the null check on it can be removed.
668 void TryRemovingNullCheck(HInstruction* instruction) {
669 HInstruction* prev = instruction->GetPrevious();
670 if ((prev != nullptr) && prev->IsNullCheck() && (prev == instruction->InputAt(0))) {
671 // Previous instruction is a null check for this instruction. Remove the null check.
672 prev->ReplaceWith(prev->InputAt(0));
673 prev->GetBlock()->RemoveInstruction(prev);
674 }
675 }
676
677 HInstruction* GetDefaultValue(Primitive::Type type) {
678 switch (type) {
679 case Primitive::kPrimNot:
680 return GetGraph()->GetNullConstant();
681 case Primitive::kPrimBoolean:
682 case Primitive::kPrimByte:
683 case Primitive::kPrimChar:
684 case Primitive::kPrimShort:
685 case Primitive::kPrimInt:
686 return GetGraph()->GetIntConstant(0);
687 case Primitive::kPrimLong:
688 return GetGraph()->GetLongConstant(0);
689 case Primitive::kPrimFloat:
690 return GetGraph()->GetFloatConstant(0);
691 case Primitive::kPrimDouble:
692 return GetGraph()->GetDoubleConstant(0);
693 default:
694 UNREACHABLE();
695 }
696 }
697
698 void VisitGetLocation(HInstruction* instruction,
699 HInstruction* ref,
700 size_t offset,
701 HInstruction* index,
702 int16_t declaring_class_def_index) {
703 HInstruction* original_ref = HuntForOriginalReference(ref);
704 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
705 size_t idx = heap_location_collector_.FindHeapLocationIndex(
706 ref_info, offset, index, declaring_class_def_index);
707 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
708 ArenaVector<HInstruction*>& heap_values =
709 heap_values_for_[instruction->GetBlock()->GetBlockId()];
710 HInstruction* heap_value = heap_values[idx];
711 if (heap_value == kDefaultHeapValue) {
712 HInstruction* constant = GetDefaultValue(instruction->GetType());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800713 removed_loads_.push_back(instruction);
714 substitute_instructions_for_loads_.push_back(constant);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700715 heap_values[idx] = constant;
716 return;
717 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800718 if (heap_value != kUnknownHeapValue && heap_value->IsInstanceFieldSet()) {
719 HInstruction* store = heap_value;
720 // This load must be from a singleton since it's from the same field
721 // that a "removed" store puts the value. That store must be to a singleton's field.
722 DCHECK(ref_info->IsSingleton());
723 // Get the real heap value of the store.
724 heap_value = store->InputAt(1);
725 }
David Brazdil15693bf2015-12-16 10:30:45 +0000726 if (heap_value == kUnknownHeapValue) {
727 // Load isn't eliminated. Put the load as the value into the HeapLocation.
728 // This acts like GVN but with better aliasing analysis.
729 heap_values[idx] = instruction;
730 } else {
Nicolas Geoffray03971632016-03-17 10:44:24 +0000731 if (Primitive::PrimitiveKind(heap_value->GetType())
732 != Primitive::PrimitiveKind(instruction->GetType())) {
733 // The only situation where the same heap location has different type is when
734 // we do an array get from a null constant. In order to stay properly typed
735 // we do not merge the array gets.
736 if (kIsDebugBuild) {
737 DCHECK(heap_value->IsArrayGet()) << heap_value->DebugName();
738 DCHECK(instruction->IsArrayGet()) << instruction->DebugName();
739 HInstruction* array = instruction->AsArrayGet()->GetArray();
740 DCHECK(array->IsNullCheck()) << array->DebugName();
741 DCHECK(array->InputAt(0)->IsNullConstant()) << array->InputAt(0)->DebugName();
742 array = heap_value->AsArrayGet()->GetArray();
743 DCHECK(array->IsNullCheck()) << array->DebugName();
744 DCHECK(array->InputAt(0)->IsNullConstant()) << array->InputAt(0)->DebugName();
745 }
746 return;
747 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800748 removed_loads_.push_back(instruction);
749 substitute_instructions_for_loads_.push_back(heap_value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700750 TryRemovingNullCheck(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700751 }
752 }
753
754 bool Equal(HInstruction* heap_value, HInstruction* value) {
755 if (heap_value == value) {
756 return true;
757 }
758 if (heap_value == kDefaultHeapValue && GetDefaultValue(value->GetType()) == value) {
759 return true;
760 }
761 return false;
762 }
763
764 void VisitSetLocation(HInstruction* instruction,
765 HInstruction* ref,
766 size_t offset,
767 HInstruction* index,
768 int16_t declaring_class_def_index,
769 HInstruction* value) {
770 HInstruction* original_ref = HuntForOriginalReference(ref);
771 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
772 size_t idx = heap_location_collector_.FindHeapLocationIndex(
773 ref_info, offset, index, declaring_class_def_index);
774 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
775 ArenaVector<HInstruction*>& heap_values =
776 heap_values_for_[instruction->GetBlock()->GetBlockId()];
777 HInstruction* heap_value = heap_values[idx];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800778 bool same_value = false;
779 bool possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700780 if (Equal(heap_value, value)) {
781 // Store into the heap location with the same value.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800782 same_value = true;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700783 } else if (index != nullptr) {
784 // For array element, don't eliminate stores since it can be easily aliased
785 // with non-constant index.
786 } else if (!heap_location_collector_.MayDeoptimize() &&
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800787 ref_info->IsSingletonAndNotReturned()) {
788 // Store into a field of a singleton that's not returned. The value cannot be
789 // killed due to aliasing/invocation. It can be redundant since future loads can
790 // directly get the value set by this instruction. The value can still be killed due to
791 // merging or loop side effects. Stores whose values are killed due to merging/loop side
792 // effects later will be removed from possibly_removed_stores_ when that is detected.
793 possibly_redundant = true;
794 HNewInstance* new_instance = ref_info->GetReference()->AsNewInstance();
795 DCHECK(new_instance != nullptr);
796 if (new_instance->IsFinalizable()) {
797 // Finalizable objects escape globally. Need to keep the store.
798 possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700799 } else {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800800 HLoopInformation* loop_info = instruction->GetBlock()->GetLoopInformation();
801 if (loop_info != nullptr) {
802 // instruction is a store in the loop so the loop must does write.
803 DCHECK(side_effects_.GetLoopEffects(loop_info->GetHeader()).DoesAnyWrite());
Mingyao Yang803cbb92015-12-01 12:24:36 -0800804 // If it's a singleton, IsValueKilledByLoopSideEffects() must be true.
805 DCHECK(!ref_info->IsSingleton() ||
806 heap_location_collector_.GetHeapLocation(idx)->IsValueKilledByLoopSideEffects());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800807
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800808 if (loop_info->IsDefinedOutOfTheLoop(original_ref)) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800809 DCHECK(original_ref->GetBlock()->Dominates(loop_info->GetPreHeader()));
810 // Keep the store since its value may be needed at the loop header.
811 possibly_redundant = false;
812 } else {
813 // The singleton is created inside the loop. Value stored to it isn't needed at
814 // the loop header. This is true for outer loops also.
815 }
816 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700817 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700818 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800819 if (same_value || possibly_redundant) {
820 possibly_removed_stores_.push_back(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700821 }
Mingyao Yange9d6e602015-10-23 17:08:42 -0700822
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800823 if (!same_value) {
824 if (possibly_redundant) {
825 DCHECK(instruction->IsInstanceFieldSet());
826 // Put the store as the heap value. If the value is loaded from heap
827 // by a load later, this store isn't really redundant.
828 heap_values[idx] = instruction;
829 } else {
830 heap_values[idx] = value;
831 }
832 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700833 // This store may kill values in other heap locations due to aliasing.
834 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800835 if (i == idx) {
836 continue;
837 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700838 if (heap_values[i] == value) {
839 // Same value should be kept even if aliasing happens.
840 continue;
841 }
842 if (heap_values[i] == kUnknownHeapValue) {
843 // Value is already unknown, no need for aliasing check.
844 continue;
845 }
846 if (heap_location_collector_.MayAlias(i, idx)) {
847 // Kill heap locations that may alias.
848 heap_values[i] = kUnknownHeapValue;
849 }
850 }
851 }
852
853 void VisitInstanceFieldGet(HInstanceFieldGet* instruction) OVERRIDE {
854 HInstruction* obj = instruction->InputAt(0);
855 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
856 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
857 VisitGetLocation(instruction, obj, offset, nullptr, declaring_class_def_index);
858 }
859
860 void VisitInstanceFieldSet(HInstanceFieldSet* instruction) OVERRIDE {
861 HInstruction* obj = instruction->InputAt(0);
862 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
863 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
864 HInstruction* value = instruction->InputAt(1);
865 VisitSetLocation(instruction, obj, offset, nullptr, declaring_class_def_index, value);
866 }
867
868 void VisitStaticFieldGet(HStaticFieldGet* instruction) OVERRIDE {
869 HInstruction* cls = instruction->InputAt(0);
870 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
871 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
872 VisitGetLocation(instruction, cls, offset, nullptr, declaring_class_def_index);
873 }
874
875 void VisitStaticFieldSet(HStaticFieldSet* instruction) OVERRIDE {
876 HInstruction* cls = instruction->InputAt(0);
877 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
878 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
879 HInstruction* value = instruction->InputAt(1);
880 VisitSetLocation(instruction, cls, offset, nullptr, declaring_class_def_index, value);
881 }
882
883 void VisitArrayGet(HArrayGet* instruction) OVERRIDE {
884 HInstruction* array = instruction->InputAt(0);
885 HInstruction* index = instruction->InputAt(1);
886 VisitGetLocation(instruction,
887 array,
888 HeapLocation::kInvalidFieldOffset,
889 index,
890 HeapLocation::kDeclaringClassDefIndexForArrays);
891 }
892
893 void VisitArraySet(HArraySet* instruction) OVERRIDE {
894 HInstruction* array = instruction->InputAt(0);
895 HInstruction* index = instruction->InputAt(1);
896 HInstruction* value = instruction->InputAt(2);
897 VisitSetLocation(instruction,
898 array,
899 HeapLocation::kInvalidFieldOffset,
900 index,
901 HeapLocation::kDeclaringClassDefIndexForArrays,
902 value);
903 }
904
905 void HandleInvoke(HInstruction* invoke) {
906 ArenaVector<HInstruction*>& heap_values =
907 heap_values_for_[invoke->GetBlock()->GetBlockId()];
908 for (size_t i = 0; i < heap_values.size(); i++) {
909 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
910 if (ref_info->IsSingleton()) {
911 // Singleton references cannot be seen by the callee.
912 } else {
913 heap_values[i] = kUnknownHeapValue;
914 }
915 }
916 }
917
918 void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) OVERRIDE {
919 HandleInvoke(invoke);
920 }
921
922 void VisitInvokeVirtual(HInvokeVirtual* invoke) OVERRIDE {
923 HandleInvoke(invoke);
924 }
925
926 void VisitInvokeInterface(HInvokeInterface* invoke) OVERRIDE {
927 HandleInvoke(invoke);
928 }
929
930 void VisitInvokeUnresolved(HInvokeUnresolved* invoke) OVERRIDE {
931 HandleInvoke(invoke);
932 }
933
934 void VisitClinitCheck(HClinitCheck* clinit) OVERRIDE {
935 HandleInvoke(clinit);
936 }
937
938 void VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet* instruction) OVERRIDE {
939 // Conservatively treat it as an invocation.
940 HandleInvoke(instruction);
941 }
942
943 void VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet* instruction) OVERRIDE {
944 // Conservatively treat it as an invocation.
945 HandleInvoke(instruction);
946 }
947
948 void VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet* instruction) OVERRIDE {
949 // Conservatively treat it as an invocation.
950 HandleInvoke(instruction);
951 }
952
953 void VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet* instruction) OVERRIDE {
954 // Conservatively treat it as an invocation.
955 HandleInvoke(instruction);
956 }
957
958 void VisitNewInstance(HNewInstance* new_instance) OVERRIDE {
959 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_instance);
960 if (ref_info == nullptr) {
961 // new_instance isn't used for field accesses. No need to process it.
962 return;
963 }
964 if (!heap_location_collector_.MayDeoptimize() &&
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800965 ref_info->IsSingletonAndNotReturned() &&
966 !new_instance->IsFinalizable() &&
967 !new_instance->CanThrow()) {
968 // TODO: add new_instance to singleton_new_instances_ and enable allocation elimination.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700969 }
970 ArenaVector<HInstruction*>& heap_values =
971 heap_values_for_[new_instance->GetBlock()->GetBlockId()];
972 for (size_t i = 0; i < heap_values.size(); i++) {
973 HInstruction* ref =
974 heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo()->GetReference();
975 size_t offset = heap_location_collector_.GetHeapLocation(i)->GetOffset();
976 if (ref == new_instance && offset >= mirror::kObjectHeaderSize) {
977 // Instance fields except the header fields are set to default heap values.
978 heap_values[i] = kDefaultHeapValue;
979 }
980 }
981 }
982
983 // Find an instruction's substitute if it should be removed.
984 // Return the same instruction if it should not be removed.
985 HInstruction* FindSubstitute(HInstruction* instruction) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800986 size_t size = removed_loads_.size();
Mingyao Yang8df69d42015-10-22 15:40:58 -0700987 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800988 if (removed_loads_[i] == instruction) {
989 return substitute_instructions_for_loads_[i];
Mingyao Yang8df69d42015-10-22 15:40:58 -0700990 }
991 }
992 return instruction;
993 }
994
995 const HeapLocationCollector& heap_location_collector_;
996 const SideEffectsAnalysis& side_effects_;
997
998 // One array of heap values for each block.
999 ArenaVector<ArenaVector<HInstruction*>> heap_values_for_;
1000
1001 // We record the instructions that should be eliminated but may be
1002 // used by heap locations. They'll be removed in the end.
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001003 ArenaVector<HInstruction*> removed_loads_;
1004 ArenaVector<HInstruction*> substitute_instructions_for_loads_;
1005
1006 // Stores in this list may be removed from the list later when it's
1007 // found that the store cannot be eliminated.
1008 ArenaVector<HInstruction*> possibly_removed_stores_;
1009
Mingyao Yang8df69d42015-10-22 15:40:58 -07001010 ArenaVector<HInstruction*> singleton_new_instances_;
1011
1012 DISALLOW_COPY_AND_ASSIGN(LSEVisitor);
1013};
1014
1015void LoadStoreElimination::Run() {
David Brazdil8993caf2015-12-07 10:04:40 +00001016 if (graph_->IsDebuggable() || graph_->HasTryCatch()) {
Mingyao Yang8df69d42015-10-22 15:40:58 -07001017 // Debugger may set heap values or trigger deoptimization of callers.
David Brazdil8993caf2015-12-07 10:04:40 +00001018 // Try/catch support not implemented yet.
Mingyao Yang8df69d42015-10-22 15:40:58 -07001019 // Skip this optimization.
1020 return;
1021 }
1022 HeapLocationCollector heap_location_collector(graph_);
1023 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1024 heap_location_collector.VisitBasicBlock(it.Current());
1025 }
1026 if (heap_location_collector.GetNumberOfHeapLocations() > kMaxNumberOfHeapLocations) {
1027 // Bail out if there are too many heap locations to deal with.
1028 return;
1029 }
1030 if (!heap_location_collector.HasHeapStores()) {
1031 // Without heap stores, this pass would act mostly as GVN on heap accesses.
1032 return;
1033 }
1034 if (heap_location_collector.HasVolatile() || heap_location_collector.HasMonitorOps()) {
1035 // Don't do load/store elimination if the method has volatile field accesses or
1036 // monitor operations, for now.
1037 // TODO: do it right.
1038 return;
1039 }
1040 heap_location_collector.BuildAliasingMatrix();
1041 LSEVisitor lse_visitor(graph_, heap_location_collector, side_effects_);
1042 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1043 lse_visitor.VisitBasicBlock(it.Current());
1044 }
1045 lse_visitor.RemoveInstructions();
1046}
1047
1048} // namespace art