blob: edecf17f334116d11193c34509078f2ad73b6fd8 [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),
40 is_singleton_and_non_escaping_(true) {
41 CalculateEscape(reference_, nullptr, &is_singleton_, &is_singleton_and_non_escaping_);
Mingyao Yang8df69d42015-10-22 15:40:58 -070042 }
43
44 HInstruction* GetReference() const {
45 return reference_;
46 }
47
48 size_t GetPosition() const {
49 return position_;
50 }
51
52 // Returns true if reference_ is the only name that can refer to its value during
53 // the lifetime of the method. So it's guaranteed to not have any alias in
54 // the method (including its callees).
55 bool IsSingleton() const {
56 return is_singleton_;
57 }
58
Mingyao Yange58bdca2016-10-28 11:07:24 -070059 // Returns true if reference_ is a singleton and not returned to the caller or
60 // used as an environment local of an HDeoptimize instruction.
Mingyao Yang8df69d42015-10-22 15:40:58 -070061 // The allocation and stores into reference_ may be eliminated for such cases.
Mingyao Yange58bdca2016-10-28 11:07:24 -070062 bool IsSingletonAndNonEscaping() const {
63 return is_singleton_and_non_escaping_;
Mingyao Yang8df69d42015-10-22 15:40:58 -070064 }
65
66 private:
67 HInstruction* const reference_;
68 const size_t position_; // position in HeapLocationCollector's ref_info_array_.
69 bool is_singleton_; // can only be referred to by a single name in the method.
Mingyao Yange58bdca2016-10-28 11:07:24 -070070
71 // reference_ is singleton and does not escape in the end either by
72 // returning to the caller, or being used as an environment local of an
73 // HDeoptimize instruction.
74 bool is_singleton_and_non_escaping_;
Mingyao Yang8df69d42015-10-22 15:40:58 -070075
76 DISALLOW_COPY_AND_ASSIGN(ReferenceInfo);
77};
78
79// A heap location is a reference-offset/index pair that a value can be loaded from
80// or stored to.
81class HeapLocation : public ArenaObject<kArenaAllocMisc> {
82 public:
83 static constexpr size_t kInvalidFieldOffset = -1;
84
85 // TODO: more fine-grained array types.
86 static constexpr int16_t kDeclaringClassDefIndexForArrays = -1;
87
88 HeapLocation(ReferenceInfo* ref_info,
89 size_t offset,
90 HInstruction* index,
91 int16_t declaring_class_def_index)
92 : ref_info_(ref_info),
93 offset_(offset),
94 index_(index),
Mingyao Yang803cbb92015-12-01 12:24:36 -080095 declaring_class_def_index_(declaring_class_def_index),
96 value_killed_by_loop_side_effects_(true) {
Mingyao Yang8df69d42015-10-22 15:40:58 -070097 DCHECK(ref_info != nullptr);
98 DCHECK((offset == kInvalidFieldOffset && index != nullptr) ||
99 (offset != kInvalidFieldOffset && index == nullptr));
Mingyao Yang803cbb92015-12-01 12:24:36 -0800100 if (ref_info->IsSingleton() && !IsArrayElement()) {
101 // Assume this location's value cannot be killed by loop side effects
102 // until proven otherwise.
103 value_killed_by_loop_side_effects_ = false;
104 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700105 }
106
107 ReferenceInfo* GetReferenceInfo() const { return ref_info_; }
108 size_t GetOffset() const { return offset_; }
109 HInstruction* GetIndex() const { return index_; }
110
111 // Returns the definition of declaring class' dex index.
112 // It's kDeclaringClassDefIndexForArrays for an array element.
113 int16_t GetDeclaringClassDefIndex() const {
114 return declaring_class_def_index_;
115 }
116
117 bool IsArrayElement() const {
118 return index_ != nullptr;
119 }
120
Mingyao Yang803cbb92015-12-01 12:24:36 -0800121 bool IsValueKilledByLoopSideEffects() const {
122 return value_killed_by_loop_side_effects_;
123 }
124
125 void SetValueKilledByLoopSideEffects(bool val) {
126 value_killed_by_loop_side_effects_ = val;
127 }
128
Mingyao Yang8df69d42015-10-22 15:40:58 -0700129 private:
130 ReferenceInfo* const ref_info_; // reference for instance/static field or array access.
131 const size_t offset_; // offset of static/instance field.
132 HInstruction* const index_; // index of an array element.
133 const int16_t declaring_class_def_index_; // declaring class's def's dex index.
Mingyao Yang803cbb92015-12-01 12:24:36 -0800134 bool value_killed_by_loop_side_effects_; // value of this location may be killed by loop
135 // side effects because this location is stored
Mingyao Yang0a845202016-10-14 16:26:08 -0700136 // into inside a loop. This gives
137 // better info on whether a singleton's location
138 // value may be killed by loop side effects.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700139
140 DISALLOW_COPY_AND_ASSIGN(HeapLocation);
141};
142
143static HInstruction* HuntForOriginalReference(HInstruction* ref) {
144 DCHECK(ref != nullptr);
145 while (ref->IsNullCheck() || ref->IsBoundType()) {
146 ref = ref->InputAt(0);
147 }
148 return ref;
149}
150
151// A HeapLocationCollector collects all relevant heap locations and keeps
152// an aliasing matrix for all locations.
153class HeapLocationCollector : public HGraphVisitor {
154 public:
155 static constexpr size_t kHeapLocationNotFound = -1;
156 // Start with a single uint32_t word. That's enough bits for pair-wise
157 // aliasing matrix of 8 heap locations.
158 static constexpr uint32_t kInitialAliasingMatrixBitVectorSize = 32;
159
160 explicit HeapLocationCollector(HGraph* graph)
161 : HGraphVisitor(graph),
162 ref_info_array_(graph->GetArena()->Adapter(kArenaAllocLSE)),
163 heap_locations_(graph->GetArena()->Adapter(kArenaAllocLSE)),
Vladimir Markof6a35de2016-03-21 12:01:50 +0000164 aliasing_matrix_(graph->GetArena(),
165 kInitialAliasingMatrixBitVectorSize,
166 true,
167 kArenaAllocLSE),
Mingyao Yang8df69d42015-10-22 15:40:58 -0700168 has_heap_stores_(false),
169 has_volatile_(false),
Mingyao Yange58bdca2016-10-28 11:07:24 -0700170 has_monitor_operations_(false) {}
Mingyao Yang8df69d42015-10-22 15:40:58 -0700171
172 size_t GetNumberOfHeapLocations() const {
173 return heap_locations_.size();
174 }
175
176 HeapLocation* GetHeapLocation(size_t index) const {
177 return heap_locations_[index];
178 }
179
180 ReferenceInfo* FindReferenceInfoOf(HInstruction* ref) const {
181 for (size_t i = 0; i < ref_info_array_.size(); i++) {
182 ReferenceInfo* ref_info = ref_info_array_[i];
183 if (ref_info->GetReference() == ref) {
184 DCHECK_EQ(i, ref_info->GetPosition());
185 return ref_info;
186 }
187 }
188 return nullptr;
189 }
190
191 bool HasHeapStores() const {
192 return has_heap_stores_;
193 }
194
195 bool HasVolatile() const {
196 return has_volatile_;
197 }
198
199 bool HasMonitorOps() const {
200 return has_monitor_operations_;
201 }
202
Mingyao Yang8df69d42015-10-22 15:40:58 -0700203 // Find and return the heap location index in heap_locations_.
204 size_t FindHeapLocationIndex(ReferenceInfo* ref_info,
205 size_t offset,
206 HInstruction* index,
207 int16_t declaring_class_def_index) const {
208 for (size_t i = 0; i < heap_locations_.size(); i++) {
209 HeapLocation* loc = heap_locations_[i];
210 if (loc->GetReferenceInfo() == ref_info &&
211 loc->GetOffset() == offset &&
212 loc->GetIndex() == index &&
213 loc->GetDeclaringClassDefIndex() == declaring_class_def_index) {
214 return i;
215 }
216 }
217 return kHeapLocationNotFound;
218 }
219
220 // Returns true if heap_locations_[index1] and heap_locations_[index2] may alias.
221 bool MayAlias(size_t index1, size_t index2) const {
222 if (index1 < index2) {
223 return aliasing_matrix_.IsBitSet(AliasingMatrixPosition(index1, index2));
224 } else if (index1 > index2) {
225 return aliasing_matrix_.IsBitSet(AliasingMatrixPosition(index2, index1));
226 } else {
227 DCHECK(false) << "index1 and index2 are expected to be different";
228 return true;
229 }
230 }
231
232 void BuildAliasingMatrix() {
233 const size_t number_of_locations = heap_locations_.size();
234 if (number_of_locations == 0) {
235 return;
236 }
237 size_t pos = 0;
238 // Compute aliasing info between every pair of different heap locations.
239 // Save the result in a matrix represented as a BitVector.
240 for (size_t i = 0; i < number_of_locations - 1; i++) {
241 for (size_t j = i + 1; j < number_of_locations; j++) {
242 if (ComputeMayAlias(i, j)) {
243 aliasing_matrix_.SetBit(CheckedAliasingMatrixPosition(i, j, pos));
244 }
245 pos++;
246 }
247 }
248 }
249
250 private:
251 // An allocation cannot alias with a name which already exists at the point
252 // of the allocation, such as a parameter or a load happening before the allocation.
253 bool MayAliasWithPreexistenceChecking(ReferenceInfo* ref_info1, ReferenceInfo* ref_info2) const {
254 if (ref_info1->GetReference()->IsNewInstance() || ref_info1->GetReference()->IsNewArray()) {
255 // Any reference that can alias with the allocation must appear after it in the block/in
256 // the block's successors. In reverse post order, those instructions will be visited after
257 // the allocation.
258 return ref_info2->GetPosition() >= ref_info1->GetPosition();
259 }
260 return true;
261 }
262
263 bool CanReferencesAlias(ReferenceInfo* ref_info1, ReferenceInfo* ref_info2) const {
264 if (ref_info1 == ref_info2) {
265 return true;
266 } else if (ref_info1->IsSingleton()) {
267 return false;
268 } else if (ref_info2->IsSingleton()) {
269 return false;
270 } else if (!MayAliasWithPreexistenceChecking(ref_info1, ref_info2) ||
271 !MayAliasWithPreexistenceChecking(ref_info2, ref_info1)) {
272 return false;
273 }
274 return true;
275 }
276
277 // `index1` and `index2` are indices in the array of collected heap locations.
278 // Returns the position in the bit vector that tracks whether the two heap
279 // locations may alias.
280 size_t AliasingMatrixPosition(size_t index1, size_t index2) const {
281 DCHECK(index2 > index1);
282 const size_t number_of_locations = heap_locations_.size();
283 // It's (num_of_locations - 1) + ... + (num_of_locations - index1) + (index2 - index1 - 1).
284 return (number_of_locations * index1 - (1 + index1) * index1 / 2 + (index2 - index1 - 1));
285 }
286
287 // An additional position is passed in to make sure the calculated position is correct.
288 size_t CheckedAliasingMatrixPosition(size_t index1, size_t index2, size_t position) {
289 size_t calculated_position = AliasingMatrixPosition(index1, index2);
290 DCHECK_EQ(calculated_position, position);
291 return calculated_position;
292 }
293
294 // Compute if two locations may alias to each other.
295 bool ComputeMayAlias(size_t index1, size_t index2) const {
296 HeapLocation* loc1 = heap_locations_[index1];
297 HeapLocation* loc2 = heap_locations_[index2];
298 if (loc1->GetOffset() != loc2->GetOffset()) {
299 // Either two different instance fields, or one is an instance
300 // field and the other is an array element.
301 return false;
302 }
303 if (loc1->GetDeclaringClassDefIndex() != loc2->GetDeclaringClassDefIndex()) {
304 // Different types.
305 return false;
306 }
307 if (!CanReferencesAlias(loc1->GetReferenceInfo(), loc2->GetReferenceInfo())) {
308 return false;
309 }
310 if (loc1->IsArrayElement() && loc2->IsArrayElement()) {
311 HInstruction* array_index1 = loc1->GetIndex();
312 HInstruction* array_index2 = loc2->GetIndex();
313 DCHECK(array_index1 != nullptr);
314 DCHECK(array_index2 != nullptr);
315 if (array_index1->IsIntConstant() &&
316 array_index2->IsIntConstant() &&
317 array_index1->AsIntConstant()->GetValue() != array_index2->AsIntConstant()->GetValue()) {
318 // Different constant indices do not alias.
319 return false;
320 }
321 }
322 return true;
323 }
324
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800325 ReferenceInfo* GetOrCreateReferenceInfo(HInstruction* instruction) {
326 ReferenceInfo* ref_info = FindReferenceInfoOf(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700327 if (ref_info == nullptr) {
328 size_t pos = ref_info_array_.size();
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800329 ref_info = new (GetGraph()->GetArena()) ReferenceInfo(instruction, pos);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700330 ref_info_array_.push_back(ref_info);
331 }
332 return ref_info;
333 }
334
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800335 void CreateReferenceInfoForReferenceType(HInstruction* instruction) {
336 if (instruction->GetType() != Primitive::kPrimNot) {
337 return;
338 }
339 DCHECK(FindReferenceInfoOf(instruction) == nullptr);
340 GetOrCreateReferenceInfo(instruction);
341 }
342
Mingyao Yang8df69d42015-10-22 15:40:58 -0700343 HeapLocation* GetOrCreateHeapLocation(HInstruction* ref,
344 size_t offset,
345 HInstruction* index,
346 int16_t declaring_class_def_index) {
347 HInstruction* original_ref = HuntForOriginalReference(ref);
348 ReferenceInfo* ref_info = GetOrCreateReferenceInfo(original_ref);
349 size_t heap_location_idx = FindHeapLocationIndex(
350 ref_info, offset, index, declaring_class_def_index);
351 if (heap_location_idx == kHeapLocationNotFound) {
352 HeapLocation* heap_loc = new (GetGraph()->GetArena())
353 HeapLocation(ref_info, offset, index, declaring_class_def_index);
354 heap_locations_.push_back(heap_loc);
355 return heap_loc;
356 }
357 return heap_locations_[heap_location_idx];
358 }
359
Mingyao Yang803cbb92015-12-01 12:24:36 -0800360 HeapLocation* VisitFieldAccess(HInstruction* ref, const FieldInfo& field_info) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700361 if (field_info.IsVolatile()) {
362 has_volatile_ = true;
363 }
364 const uint16_t declaring_class_def_index = field_info.GetDeclaringClassDefIndex();
365 const size_t offset = field_info.GetFieldOffset().SizeValue();
Mingyao Yang803cbb92015-12-01 12:24:36 -0800366 return GetOrCreateHeapLocation(ref, offset, nullptr, declaring_class_def_index);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700367 }
368
369 void VisitArrayAccess(HInstruction* array, HInstruction* index) {
370 GetOrCreateHeapLocation(array, HeapLocation::kInvalidFieldOffset,
371 index, HeapLocation::kDeclaringClassDefIndexForArrays);
372 }
373
374 void VisitInstanceFieldGet(HInstanceFieldGet* instruction) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800375 VisitFieldAccess(instruction->InputAt(0), instruction->GetFieldInfo());
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800376 CreateReferenceInfoForReferenceType(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700377 }
378
379 void VisitInstanceFieldSet(HInstanceFieldSet* instruction) OVERRIDE {
Mingyao Yang803cbb92015-12-01 12:24:36 -0800380 HeapLocation* location = VisitFieldAccess(instruction->InputAt(0), instruction->GetFieldInfo());
Mingyao Yang8df69d42015-10-22 15:40:58 -0700381 has_heap_stores_ = true;
Mingyao Yang0a845202016-10-14 16:26:08 -0700382 if (location->GetReferenceInfo()->IsSingleton()) {
383 // A singleton's location value may be killed by loop side effects if it's
384 // defined before that loop, and it's stored into inside that loop.
385 HLoopInformation* loop_info = instruction->GetBlock()->GetLoopInformation();
386 if (loop_info != nullptr) {
387 HInstruction* ref = location->GetReferenceInfo()->GetReference();
388 DCHECK(ref->IsNewInstance());
389 if (loop_info->IsDefinedOutOfTheLoop(ref)) {
390 // ref's location value may be killed by this loop's side effects.
391 location->SetValueKilledByLoopSideEffects(true);
392 } else {
393 // ref is defined inside this loop so this loop's side effects cannot
394 // kill its location value at the loop header since ref/its location doesn't
395 // exist yet at the loop header.
396 }
397 }
398 } else {
399 // For non-singletons, value_killed_by_loop_side_effects_ is inited to
400 // true.
401 DCHECK_EQ(location->IsValueKilledByLoopSideEffects(), true);
Mingyao Yang803cbb92015-12-01 12:24:36 -0800402 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700403 }
404
405 void VisitStaticFieldGet(HStaticFieldGet* instruction) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800406 VisitFieldAccess(instruction->InputAt(0), instruction->GetFieldInfo());
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800407 CreateReferenceInfoForReferenceType(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700408 }
409
410 void VisitStaticFieldSet(HStaticFieldSet* instruction) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800411 VisitFieldAccess(instruction->InputAt(0), instruction->GetFieldInfo());
Mingyao Yang8df69d42015-10-22 15:40:58 -0700412 has_heap_stores_ = true;
413 }
414
415 // We intentionally don't collect HUnresolvedInstanceField/HUnresolvedStaticField accesses
416 // since we cannot accurately track the fields.
417
418 void VisitArrayGet(HArrayGet* instruction) OVERRIDE {
419 VisitArrayAccess(instruction->InputAt(0), instruction->InputAt(1));
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800420 CreateReferenceInfoForReferenceType(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700421 }
422
423 void VisitArraySet(HArraySet* instruction) OVERRIDE {
424 VisitArrayAccess(instruction->InputAt(0), instruction->InputAt(1));
425 has_heap_stores_ = true;
426 }
427
428 void VisitNewInstance(HNewInstance* new_instance) OVERRIDE {
429 // Any references appearing in the ref_info_array_ so far cannot alias with new_instance.
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800430 CreateReferenceInfoForReferenceType(new_instance);
431 }
432
433 void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* instruction) OVERRIDE {
434 CreateReferenceInfoForReferenceType(instruction);
435 }
436
437 void VisitInvokeVirtual(HInvokeVirtual* instruction) OVERRIDE {
438 CreateReferenceInfoForReferenceType(instruction);
439 }
440
441 void VisitInvokeInterface(HInvokeInterface* instruction) OVERRIDE {
442 CreateReferenceInfoForReferenceType(instruction);
443 }
444
445 void VisitParameterValue(HParameterValue* instruction) OVERRIDE {
446 CreateReferenceInfoForReferenceType(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700447 }
448
Mingyao Yang40bcb932016-02-03 05:46:57 -0800449 void VisitSelect(HSelect* instruction) OVERRIDE {
450 CreateReferenceInfoForReferenceType(instruction);
451 }
452
Mingyao Yang8df69d42015-10-22 15:40:58 -0700453 void VisitMonitorOperation(HMonitorOperation* monitor ATTRIBUTE_UNUSED) OVERRIDE {
454 has_monitor_operations_ = true;
455 }
456
457 ArenaVector<ReferenceInfo*> ref_info_array_; // All references used for heap accesses.
458 ArenaVector<HeapLocation*> heap_locations_; // All heap locations.
459 ArenaBitVector aliasing_matrix_; // aliasing info between each pair of locations.
460 bool has_heap_stores_; // If there is no heap stores, LSE acts as GVN with better
461 // alias analysis and won't be as effective.
462 bool has_volatile_; // If there are volatile field accesses.
463 bool has_monitor_operations_; // If there are monitor operations.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700464
465 DISALLOW_COPY_AND_ASSIGN(HeapLocationCollector);
466};
467
468// An unknown heap value. Loads with such a value in the heap location cannot be eliminated.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800469// A heap location can be set to kUnknownHeapValue when:
470// - initially set a value.
471// - killed due to aliasing, merging, invocation, or loop side effects.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700472static HInstruction* const kUnknownHeapValue =
473 reinterpret_cast<HInstruction*>(static_cast<uintptr_t>(-1));
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800474
Mingyao Yang8df69d42015-10-22 15:40:58 -0700475// Default heap value after an allocation.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800476// A heap location can be set to that value right after an allocation.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700477static HInstruction* const kDefaultHeapValue =
478 reinterpret_cast<HInstruction*>(static_cast<uintptr_t>(-2));
479
480class LSEVisitor : public HGraphVisitor {
481 public:
482 LSEVisitor(HGraph* graph,
483 const HeapLocationCollector& heap_locations_collector,
484 const SideEffectsAnalysis& side_effects)
485 : HGraphVisitor(graph),
486 heap_location_collector_(heap_locations_collector),
487 side_effects_(side_effects),
488 heap_values_for_(graph->GetBlocks().size(),
489 ArenaVector<HInstruction*>(heap_locations_collector.
490 GetNumberOfHeapLocations(),
491 kUnknownHeapValue,
492 graph->GetArena()->Adapter(kArenaAllocLSE)),
493 graph->GetArena()->Adapter(kArenaAllocLSE)),
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800494 removed_loads_(graph->GetArena()->Adapter(kArenaAllocLSE)),
495 substitute_instructions_for_loads_(graph->GetArena()->Adapter(kArenaAllocLSE)),
496 possibly_removed_stores_(graph->GetArena()->Adapter(kArenaAllocLSE)),
Mingyao Yang8df69d42015-10-22 15:40:58 -0700497 singleton_new_instances_(graph->GetArena()->Adapter(kArenaAllocLSE)) {
498 }
499
500 void VisitBasicBlock(HBasicBlock* block) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800501 // Populate the heap_values array for this block.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700502 // TODO: try to reuse the heap_values array from one predecessor if possible.
503 if (block->IsLoopHeader()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800504 HandleLoopSideEffects(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700505 } else {
506 MergePredecessorValues(block);
507 }
508 HGraphVisitor::VisitBasicBlock(block);
509 }
510
511 // Remove recorded instructions that should be eliminated.
512 void RemoveInstructions() {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800513 size_t size = removed_loads_.size();
514 DCHECK_EQ(size, substitute_instructions_for_loads_.size());
Mingyao Yang8df69d42015-10-22 15:40:58 -0700515 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800516 HInstruction* load = removed_loads_[i];
517 DCHECK(load != nullptr);
518 DCHECK(load->IsInstanceFieldGet() ||
519 load->IsStaticFieldGet() ||
520 load->IsArrayGet());
521 HInstruction* substitute = substitute_instructions_for_loads_[i];
522 DCHECK(substitute != nullptr);
523 // Keep tracing substitute till one that's not removed.
524 HInstruction* sub_sub = FindSubstitute(substitute);
525 while (sub_sub != substitute) {
526 substitute = sub_sub;
527 sub_sub = FindSubstitute(substitute);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700528 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800529 load->ReplaceWith(substitute);
530 load->GetBlock()->RemoveInstruction(load);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700531 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800532
533 // At this point, stores in possibly_removed_stores_ can be safely removed.
Mingyao Yang062157f2016-03-02 10:15:36 -0800534 for (size_t i = 0, e = possibly_removed_stores_.size(); i < e; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800535 HInstruction* store = possibly_removed_stores_[i];
536 DCHECK(store->IsInstanceFieldSet() || store->IsStaticFieldSet() || store->IsArraySet());
537 store->GetBlock()->RemoveInstruction(store);
538 }
539
Mingyao Yang062157f2016-03-02 10:15:36 -0800540 // Eliminate allocations that are not used.
541 for (size_t i = 0, e = singleton_new_instances_.size(); i < e; i++) {
542 HInstruction* new_instance = singleton_new_instances_[i];
543 if (!new_instance->HasNonEnvironmentUses()) {
544 new_instance->RemoveEnvironmentUsers();
545 new_instance->GetBlock()->RemoveInstruction(new_instance);
546 }
547 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700548 }
549
550 private:
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800551 // If heap_values[index] is an instance field store, need to keep the store.
552 // This is necessary if a heap value is killed due to merging, or loop side
553 // effects (which is essentially merging also), since a load later from the
554 // location won't be eliminated.
555 void KeepIfIsStore(HInstruction* heap_value) {
556 if (heap_value == kDefaultHeapValue ||
557 heap_value == kUnknownHeapValue ||
558 !heap_value->IsInstanceFieldSet()) {
559 return;
560 }
561 auto idx = std::find(possibly_removed_stores_.begin(),
562 possibly_removed_stores_.end(), heap_value);
563 if (idx != possibly_removed_stores_.end()) {
564 // Make sure the store is kept.
565 possibly_removed_stores_.erase(idx);
566 }
567 }
568
569 void HandleLoopSideEffects(HBasicBlock* block) {
570 DCHECK(block->IsLoopHeader());
571 int block_id = block->GetBlockId();
572 ArenaVector<HInstruction*>& heap_values = heap_values_for_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000573
574 // Don't eliminate loads in irreducible loops. This is safe for singletons, because
575 // they are always used by the non-eliminated loop-phi.
576 if (block->GetLoopInformation()->IsIrreducible()) {
577 if (kIsDebugBuild) {
578 for (size_t i = 0; i < heap_values.size(); i++) {
579 DCHECK_EQ(heap_values[i], kUnknownHeapValue);
580 }
581 }
582 return;
583 }
584
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800585 HBasicBlock* pre_header = block->GetLoopInformation()->GetPreHeader();
586 ArenaVector<HInstruction*>& pre_header_heap_values =
587 heap_values_for_[pre_header->GetBlockId()];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000588
Mingyao Yang803cbb92015-12-01 12:24:36 -0800589 // Inherit the values from pre-header.
590 for (size_t i = 0; i < heap_values.size(); i++) {
591 heap_values[i] = pre_header_heap_values[i];
592 }
593
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800594 // We do a single pass in reverse post order. For loops, use the side effects as a hint
595 // to see if the heap values should be killed.
596 if (side_effects_.GetLoopEffects(block).DoesAnyWrite()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800597 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang803cbb92015-12-01 12:24:36 -0800598 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
599 ReferenceInfo* ref_info = location->GetReferenceInfo();
600 if (!ref_info->IsSingleton() || location->IsValueKilledByLoopSideEffects()) {
601 // heap value is killed by loop side effects (stored into directly, or due to
602 // aliasing).
603 KeepIfIsStore(pre_header_heap_values[i]);
604 heap_values[i] = kUnknownHeapValue;
605 } else {
606 // A singleton's field that's not stored into inside a loop is invariant throughout
607 // the loop.
608 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800609 }
610 }
611 }
612
Mingyao Yang8df69d42015-10-22 15:40:58 -0700613 void MergePredecessorValues(HBasicBlock* block) {
614 const ArenaVector<HBasicBlock*>& predecessors = block->GetPredecessors();
615 if (predecessors.size() == 0) {
616 return;
617 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700618
Mingyao Yang8df69d42015-10-22 15:40:58 -0700619 ArenaVector<HInstruction*>& heap_values = heap_values_for_[block->GetBlockId()];
620 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700621 HInstruction* merged_value = nullptr;
622 // Whether merged_value is a result that's merged from all predecessors.
623 bool from_all_predecessors = true;
624 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
625 HInstruction* singleton_ref = nullptr;
Mingyao Yange58bdca2016-10-28 11:07:24 -0700626 if (ref_info->IsSingletonAndNonEscaping()) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700627 // We do more analysis of liveness when merging heap values for such
628 // cases since stores into such references may potentially be eliminated.
629 singleton_ref = ref_info->GetReference();
630 }
631
632 for (HBasicBlock* predecessor : predecessors) {
633 HInstruction* pred_value = heap_values_for_[predecessor->GetBlockId()][i];
634 if ((singleton_ref != nullptr) &&
635 !singleton_ref->GetBlock()->Dominates(predecessor)) {
636 // singleton_ref is not live in this predecessor. Skip this predecessor since
637 // it does not really have the location.
638 DCHECK_EQ(pred_value, kUnknownHeapValue);
639 from_all_predecessors = false;
640 continue;
641 }
642 if (merged_value == nullptr) {
643 // First seen heap value.
644 merged_value = pred_value;
645 } else if (pred_value != merged_value) {
646 // There are conflicting values.
647 merged_value = kUnknownHeapValue;
648 break;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700649 }
650 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800651
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700652 if (merged_value == kUnknownHeapValue) {
653 // There are conflicting heap values from different predecessors.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800654 // Keep the last store in each predecessor since future loads cannot be eliminated.
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700655 for (HBasicBlock* predecessor : predecessors) {
656 ArenaVector<HInstruction*>& pred_values = heap_values_for_[predecessor->GetBlockId()];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800657 KeepIfIsStore(pred_values[i]);
658 }
659 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700660
661 if ((merged_value == nullptr) || !from_all_predecessors) {
662 DCHECK(singleton_ref != nullptr);
663 DCHECK((singleton_ref->GetBlock() == block) ||
664 !singleton_ref->GetBlock()->Dominates(block));
665 // singleton_ref is not defined before block or defined only in some of its
666 // predecessors, so block doesn't really have the location at its entry.
667 heap_values[i] = kUnknownHeapValue;
668 } else {
669 heap_values[i] = merged_value;
670 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700671 }
672 }
673
674 // `instruction` is being removed. Try to see if the null check on it
675 // can be removed. This can happen if the same value is set in two branches
676 // but not in dominators. Such as:
677 // int[] a = foo();
678 // if () {
679 // a[0] = 2;
680 // } else {
681 // a[0] = 2;
682 // }
683 // // a[0] can now be replaced with constant 2, and the null check on it can be removed.
684 void TryRemovingNullCheck(HInstruction* instruction) {
685 HInstruction* prev = instruction->GetPrevious();
686 if ((prev != nullptr) && prev->IsNullCheck() && (prev == instruction->InputAt(0))) {
687 // Previous instruction is a null check for this instruction. Remove the null check.
688 prev->ReplaceWith(prev->InputAt(0));
689 prev->GetBlock()->RemoveInstruction(prev);
690 }
691 }
692
693 HInstruction* GetDefaultValue(Primitive::Type type) {
694 switch (type) {
695 case Primitive::kPrimNot:
696 return GetGraph()->GetNullConstant();
697 case Primitive::kPrimBoolean:
698 case Primitive::kPrimByte:
699 case Primitive::kPrimChar:
700 case Primitive::kPrimShort:
701 case Primitive::kPrimInt:
702 return GetGraph()->GetIntConstant(0);
703 case Primitive::kPrimLong:
704 return GetGraph()->GetLongConstant(0);
705 case Primitive::kPrimFloat:
706 return GetGraph()->GetFloatConstant(0);
707 case Primitive::kPrimDouble:
708 return GetGraph()->GetDoubleConstant(0);
709 default:
710 UNREACHABLE();
711 }
712 }
713
714 void VisitGetLocation(HInstruction* instruction,
715 HInstruction* ref,
716 size_t offset,
717 HInstruction* index,
718 int16_t declaring_class_def_index) {
719 HInstruction* original_ref = HuntForOriginalReference(ref);
720 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
721 size_t idx = heap_location_collector_.FindHeapLocationIndex(
722 ref_info, offset, index, declaring_class_def_index);
723 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
724 ArenaVector<HInstruction*>& heap_values =
725 heap_values_for_[instruction->GetBlock()->GetBlockId()];
726 HInstruction* heap_value = heap_values[idx];
727 if (heap_value == kDefaultHeapValue) {
728 HInstruction* constant = GetDefaultValue(instruction->GetType());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800729 removed_loads_.push_back(instruction);
730 substitute_instructions_for_loads_.push_back(constant);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700731 heap_values[idx] = constant;
732 return;
733 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800734 if (heap_value != kUnknownHeapValue && heap_value->IsInstanceFieldSet()) {
735 HInstruction* store = heap_value;
736 // This load must be from a singleton since it's from the same field
737 // that a "removed" store puts the value. That store must be to a singleton's field.
738 DCHECK(ref_info->IsSingleton());
739 // Get the real heap value of the store.
740 heap_value = store->InputAt(1);
741 }
David Brazdil15693bf2015-12-16 10:30:45 +0000742 if (heap_value == kUnknownHeapValue) {
743 // Load isn't eliminated. Put the load as the value into the HeapLocation.
744 // This acts like GVN but with better aliasing analysis.
745 heap_values[idx] = instruction;
746 } else {
Nicolas Geoffray03971632016-03-17 10:44:24 +0000747 if (Primitive::PrimitiveKind(heap_value->GetType())
748 != Primitive::PrimitiveKind(instruction->GetType())) {
749 // The only situation where the same heap location has different type is when
Nicolas Geoffray65fef302016-05-04 14:00:12 +0100750 // we do an array get on an instruction that originates from the null constant
751 // (the null could be behind a field access, an array access, a null check or
752 // a bound type).
753 // In order to stay properly typed on primitive types, we do not eliminate
754 // the array gets.
Nicolas Geoffray03971632016-03-17 10:44:24 +0000755 if (kIsDebugBuild) {
756 DCHECK(heap_value->IsArrayGet()) << heap_value->DebugName();
757 DCHECK(instruction->IsArrayGet()) << instruction->DebugName();
Nicolas Geoffray03971632016-03-17 10:44:24 +0000758 }
759 return;
760 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800761 removed_loads_.push_back(instruction);
762 substitute_instructions_for_loads_.push_back(heap_value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700763 TryRemovingNullCheck(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700764 }
765 }
766
767 bool Equal(HInstruction* heap_value, HInstruction* value) {
768 if (heap_value == value) {
769 return true;
770 }
771 if (heap_value == kDefaultHeapValue && GetDefaultValue(value->GetType()) == value) {
772 return true;
773 }
774 return false;
775 }
776
777 void VisitSetLocation(HInstruction* instruction,
778 HInstruction* ref,
779 size_t offset,
780 HInstruction* index,
781 int16_t declaring_class_def_index,
782 HInstruction* value) {
783 HInstruction* original_ref = HuntForOriginalReference(ref);
784 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
785 size_t idx = heap_location_collector_.FindHeapLocationIndex(
786 ref_info, offset, index, declaring_class_def_index);
787 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
788 ArenaVector<HInstruction*>& heap_values =
789 heap_values_for_[instruction->GetBlock()->GetBlockId()];
790 HInstruction* heap_value = heap_values[idx];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800791 bool same_value = false;
792 bool possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700793 if (Equal(heap_value, value)) {
794 // Store into the heap location with the same value.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800795 same_value = true;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700796 } else if (index != nullptr) {
797 // For array element, don't eliminate stores since it can be easily aliased
798 // with non-constant index.
Mingyao Yange58bdca2016-10-28 11:07:24 -0700799 } else if (ref_info->IsSingletonAndNonEscaping()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800800 // Store into a field of a singleton that's not returned. The value cannot be
801 // killed due to aliasing/invocation. It can be redundant since future loads can
802 // directly get the value set by this instruction. The value can still be killed due to
803 // merging or loop side effects. Stores whose values are killed due to merging/loop side
804 // effects later will be removed from possibly_removed_stores_ when that is detected.
805 possibly_redundant = true;
806 HNewInstance* new_instance = ref_info->GetReference()->AsNewInstance();
807 DCHECK(new_instance != nullptr);
808 if (new_instance->IsFinalizable()) {
809 // Finalizable objects escape globally. Need to keep the store.
810 possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700811 } else {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800812 HLoopInformation* loop_info = instruction->GetBlock()->GetLoopInformation();
813 if (loop_info != nullptr) {
814 // instruction is a store in the loop so the loop must does write.
815 DCHECK(side_effects_.GetLoopEffects(loop_info->GetHeader()).DoesAnyWrite());
816
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800817 if (loop_info->IsDefinedOutOfTheLoop(original_ref)) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800818 DCHECK(original_ref->GetBlock()->Dominates(loop_info->GetPreHeader()));
819 // Keep the store since its value may be needed at the loop header.
820 possibly_redundant = false;
821 } else {
822 // The singleton is created inside the loop. Value stored to it isn't needed at
823 // the loop header. This is true for outer loops also.
824 }
825 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700826 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700827 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800828 if (same_value || possibly_redundant) {
829 possibly_removed_stores_.push_back(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700830 }
Mingyao Yange9d6e602015-10-23 17:08:42 -0700831
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800832 if (!same_value) {
833 if (possibly_redundant) {
834 DCHECK(instruction->IsInstanceFieldSet());
835 // Put the store as the heap value. If the value is loaded from heap
836 // by a load later, this store isn't really redundant.
837 heap_values[idx] = instruction;
838 } else {
839 heap_values[idx] = value;
840 }
841 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700842 // This store may kill values in other heap locations due to aliasing.
843 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800844 if (i == idx) {
845 continue;
846 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700847 if (heap_values[i] == value) {
848 // Same value should be kept even if aliasing happens.
849 continue;
850 }
851 if (heap_values[i] == kUnknownHeapValue) {
852 // Value is already unknown, no need for aliasing check.
853 continue;
854 }
855 if (heap_location_collector_.MayAlias(i, idx)) {
856 // Kill heap locations that may alias.
857 heap_values[i] = kUnknownHeapValue;
858 }
859 }
860 }
861
862 void VisitInstanceFieldGet(HInstanceFieldGet* instruction) OVERRIDE {
863 HInstruction* obj = instruction->InputAt(0);
864 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
865 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
866 VisitGetLocation(instruction, obj, offset, nullptr, declaring_class_def_index);
867 }
868
869 void VisitInstanceFieldSet(HInstanceFieldSet* instruction) OVERRIDE {
870 HInstruction* obj = instruction->InputAt(0);
871 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
872 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
873 HInstruction* value = instruction->InputAt(1);
874 VisitSetLocation(instruction, obj, offset, nullptr, declaring_class_def_index, value);
875 }
876
877 void VisitStaticFieldGet(HStaticFieldGet* instruction) OVERRIDE {
878 HInstruction* cls = instruction->InputAt(0);
879 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
880 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
881 VisitGetLocation(instruction, cls, offset, nullptr, declaring_class_def_index);
882 }
883
884 void VisitStaticFieldSet(HStaticFieldSet* instruction) OVERRIDE {
885 HInstruction* cls = instruction->InputAt(0);
886 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
887 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
888 HInstruction* value = instruction->InputAt(1);
889 VisitSetLocation(instruction, cls, offset, nullptr, declaring_class_def_index, value);
890 }
891
892 void VisitArrayGet(HArrayGet* instruction) OVERRIDE {
893 HInstruction* array = instruction->InputAt(0);
894 HInstruction* index = instruction->InputAt(1);
895 VisitGetLocation(instruction,
896 array,
897 HeapLocation::kInvalidFieldOffset,
898 index,
899 HeapLocation::kDeclaringClassDefIndexForArrays);
900 }
901
902 void VisitArraySet(HArraySet* instruction) OVERRIDE {
903 HInstruction* array = instruction->InputAt(0);
904 HInstruction* index = instruction->InputAt(1);
905 HInstruction* value = instruction->InputAt(2);
906 VisitSetLocation(instruction,
907 array,
908 HeapLocation::kInvalidFieldOffset,
909 index,
910 HeapLocation::kDeclaringClassDefIndexForArrays,
911 value);
912 }
913
914 void HandleInvoke(HInstruction* invoke) {
915 ArenaVector<HInstruction*>& heap_values =
916 heap_values_for_[invoke->GetBlock()->GetBlockId()];
917 for (size_t i = 0; i < heap_values.size(); i++) {
918 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
919 if (ref_info->IsSingleton()) {
920 // Singleton references cannot be seen by the callee.
921 } else {
922 heap_values[i] = kUnknownHeapValue;
923 }
924 }
925 }
926
927 void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) OVERRIDE {
928 HandleInvoke(invoke);
929 }
930
931 void VisitInvokeVirtual(HInvokeVirtual* invoke) OVERRIDE {
932 HandleInvoke(invoke);
933 }
934
935 void VisitInvokeInterface(HInvokeInterface* invoke) OVERRIDE {
936 HandleInvoke(invoke);
937 }
938
939 void VisitInvokeUnresolved(HInvokeUnresolved* invoke) OVERRIDE {
940 HandleInvoke(invoke);
941 }
942
943 void VisitClinitCheck(HClinitCheck* clinit) OVERRIDE {
944 HandleInvoke(clinit);
945 }
946
947 void VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet* instruction) OVERRIDE {
948 // Conservatively treat it as an invocation.
949 HandleInvoke(instruction);
950 }
951
952 void VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet* instruction) OVERRIDE {
953 // Conservatively treat it as an invocation.
954 HandleInvoke(instruction);
955 }
956
957 void VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet* instruction) OVERRIDE {
958 // Conservatively treat it as an invocation.
959 HandleInvoke(instruction);
960 }
961
962 void VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet* instruction) OVERRIDE {
963 // Conservatively treat it as an invocation.
964 HandleInvoke(instruction);
965 }
966
967 void VisitNewInstance(HNewInstance* new_instance) OVERRIDE {
968 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_instance);
969 if (ref_info == nullptr) {
970 // new_instance isn't used for field accesses. No need to process it.
971 return;
972 }
Mingyao Yange58bdca2016-10-28 11:07:24 -0700973 if (ref_info->IsSingletonAndNonEscaping() &&
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800974 !new_instance->IsFinalizable() &&
Mingyao Yang062157f2016-03-02 10:15:36 -0800975 !new_instance->NeedsAccessCheck()) {
976 singleton_new_instances_.push_back(new_instance);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700977 }
978 ArenaVector<HInstruction*>& heap_values =
979 heap_values_for_[new_instance->GetBlock()->GetBlockId()];
980 for (size_t i = 0; i < heap_values.size(); i++) {
981 HInstruction* ref =
982 heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo()->GetReference();
983 size_t offset = heap_location_collector_.GetHeapLocation(i)->GetOffset();
984 if (ref == new_instance && offset >= mirror::kObjectHeaderSize) {
985 // Instance fields except the header fields are set to default heap values.
986 heap_values[i] = kDefaultHeapValue;
987 }
988 }
989 }
990
991 // Find an instruction's substitute if it should be removed.
992 // Return the same instruction if it should not be removed.
993 HInstruction* FindSubstitute(HInstruction* instruction) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800994 size_t size = removed_loads_.size();
Mingyao Yang8df69d42015-10-22 15:40:58 -0700995 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800996 if (removed_loads_[i] == instruction) {
997 return substitute_instructions_for_loads_[i];
Mingyao Yang8df69d42015-10-22 15:40:58 -0700998 }
999 }
1000 return instruction;
1001 }
1002
1003 const HeapLocationCollector& heap_location_collector_;
1004 const SideEffectsAnalysis& side_effects_;
1005
1006 // One array of heap values for each block.
1007 ArenaVector<ArenaVector<HInstruction*>> heap_values_for_;
1008
1009 // We record the instructions that should be eliminated but may be
1010 // used by heap locations. They'll be removed in the end.
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001011 ArenaVector<HInstruction*> removed_loads_;
1012 ArenaVector<HInstruction*> substitute_instructions_for_loads_;
1013
1014 // Stores in this list may be removed from the list later when it's
1015 // found that the store cannot be eliminated.
1016 ArenaVector<HInstruction*> possibly_removed_stores_;
1017
Mingyao Yang8df69d42015-10-22 15:40:58 -07001018 ArenaVector<HInstruction*> singleton_new_instances_;
1019
1020 DISALLOW_COPY_AND_ASSIGN(LSEVisitor);
1021};
1022
1023void LoadStoreElimination::Run() {
David Brazdil8993caf2015-12-07 10:04:40 +00001024 if (graph_->IsDebuggable() || graph_->HasTryCatch()) {
Mingyao Yang8df69d42015-10-22 15:40:58 -07001025 // Debugger may set heap values or trigger deoptimization of callers.
David Brazdil8993caf2015-12-07 10:04:40 +00001026 // Try/catch support not implemented yet.
Mingyao Yang8df69d42015-10-22 15:40:58 -07001027 // Skip this optimization.
1028 return;
1029 }
1030 HeapLocationCollector heap_location_collector(graph_);
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001031 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1032 heap_location_collector.VisitBasicBlock(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -07001033 }
1034 if (heap_location_collector.GetNumberOfHeapLocations() > kMaxNumberOfHeapLocations) {
1035 // Bail out if there are too many heap locations to deal with.
1036 return;
1037 }
1038 if (!heap_location_collector.HasHeapStores()) {
1039 // Without heap stores, this pass would act mostly as GVN on heap accesses.
1040 return;
1041 }
1042 if (heap_location_collector.HasVolatile() || heap_location_collector.HasMonitorOps()) {
1043 // Don't do load/store elimination if the method has volatile field accesses or
1044 // monitor operations, for now.
1045 // TODO: do it right.
1046 return;
1047 }
1048 heap_location_collector.BuildAliasingMatrix();
1049 LSEVisitor lse_visitor(graph_, heap_location_collector, side_effects_);
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001050 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1051 lse_visitor.VisitBasicBlock(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -07001052 }
1053 lse_visitor.RemoveInstructions();
1054}
1055
1056} // namespace art