blob: 89ad85e0b45a3ddb7692a11136728b22fd7536eb [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
Vladimir Marko009d1662017-10-10 13:21:15 +010019#include "base/array_ref.h"
20#include "base/scoped_arena_allocator.h"
21#include "base/scoped_arena_containers.h"
Aart Bik96fd51d2016-11-28 11:22:35 -080022#include "escape.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070023#include "load_store_analysis.h"
Mingyao Yang8df69d42015-10-22 15:40:58 -070024#include "side_effects_analysis.h"
25
26#include <iostream>
27
28namespace art {
29
Mingyao Yang8df69d42015-10-22 15:40:58 -070030// An unknown heap value. Loads with such a value in the heap location cannot be eliminated.
Mingyao Yangfb8464a2015-11-02 10:56:59 -080031// A heap location can be set to kUnknownHeapValue when:
32// - initially set a value.
33// - killed due to aliasing, merging, invocation, or loop side effects.
Mingyao Yang8df69d42015-10-22 15:40:58 -070034static HInstruction* const kUnknownHeapValue =
35 reinterpret_cast<HInstruction*>(static_cast<uintptr_t>(-1));
Mingyao Yangfb8464a2015-11-02 10:56:59 -080036
Mingyao Yang8df69d42015-10-22 15:40:58 -070037// Default heap value after an allocation.
Mingyao Yangfb8464a2015-11-02 10:56:59 -080038// A heap location can be set to that value right after an allocation.
Mingyao Yang8df69d42015-10-22 15:40:58 -070039static HInstruction* const kDefaultHeapValue =
40 reinterpret_cast<HInstruction*>(static_cast<uintptr_t>(-2));
41
Mingyao Yangc62b7ec2017-10-25 16:42:15 -070042// Use HGraphDelegateVisitor for which all VisitInvokeXXX() delegate to VisitInvoke().
43class LSEVisitor : public HGraphDelegateVisitor {
Mingyao Yang8df69d42015-10-22 15:40:58 -070044 public:
45 LSEVisitor(HGraph* graph,
46 const HeapLocationCollector& heap_locations_collector,
Igor Murashkin6ef45672017-08-08 13:59:55 -070047 const SideEffectsAnalysis& side_effects,
48 OptimizingCompilerStats* stats)
Mingyao Yangc62b7ec2017-10-25 16:42:15 -070049 : HGraphDelegateVisitor(graph, stats),
Mingyao Yang8df69d42015-10-22 15:40:58 -070050 heap_location_collector_(heap_locations_collector),
51 side_effects_(side_effects),
Vladimir Marko009d1662017-10-10 13:21:15 +010052 allocator_(graph->GetArenaStack()),
Mingyao Yang8df69d42015-10-22 15:40:58 -070053 heap_values_for_(graph->GetBlocks().size(),
Vladimir Marko009d1662017-10-10 13:21:15 +010054 ScopedArenaVector<HInstruction*>(heap_locations_collector.
55 GetNumberOfHeapLocations(),
56 kUnknownHeapValue,
57 allocator_.Adapter(kArenaAllocLSE)),
58 allocator_.Adapter(kArenaAllocLSE)),
59 removed_loads_(allocator_.Adapter(kArenaAllocLSE)),
60 substitute_instructions_for_loads_(allocator_.Adapter(kArenaAllocLSE)),
61 possibly_removed_stores_(allocator_.Adapter(kArenaAllocLSE)),
62 singleton_new_instances_(allocator_.Adapter(kArenaAllocLSE)),
63 singleton_new_arrays_(allocator_.Adapter(kArenaAllocLSE)) {
Mingyao Yang8df69d42015-10-22 15:40:58 -070064 }
65
66 void VisitBasicBlock(HBasicBlock* block) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080067 // Populate the heap_values array for this block.
Mingyao Yang8df69d42015-10-22 15:40:58 -070068 // TODO: try to reuse the heap_values array from one predecessor if possible.
69 if (block->IsLoopHeader()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080070 HandleLoopSideEffects(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -070071 } else {
72 MergePredecessorValues(block);
73 }
74 HGraphVisitor::VisitBasicBlock(block);
75 }
76
77 // Remove recorded instructions that should be eliminated.
78 void RemoveInstructions() {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080079 size_t size = removed_loads_.size();
80 DCHECK_EQ(size, substitute_instructions_for_loads_.size());
Mingyao Yang8df69d42015-10-22 15:40:58 -070081 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080082 HInstruction* load = removed_loads_[i];
83 DCHECK(load != nullptr);
84 DCHECK(load->IsInstanceFieldGet() ||
85 load->IsStaticFieldGet() ||
Nicolas Geoffray8c4ddb22017-11-13 11:49:53 +000086 load->IsArrayGet());
Mingyao Yangfb8464a2015-11-02 10:56:59 -080087 HInstruction* substitute = substitute_instructions_for_loads_[i];
88 DCHECK(substitute != nullptr);
89 // Keep tracing substitute till one that's not removed.
90 HInstruction* sub_sub = FindSubstitute(substitute);
91 while (sub_sub != substitute) {
92 substitute = sub_sub;
93 sub_sub = FindSubstitute(substitute);
Mingyao Yang8df69d42015-10-22 15:40:58 -070094 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -080095 load->ReplaceWith(substitute);
96 load->GetBlock()->RemoveInstruction(load);
Mingyao Yang8df69d42015-10-22 15:40:58 -070097 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -080098
99 // At this point, stores in possibly_removed_stores_ can be safely removed.
Mingyao Yang86974902017-03-01 14:03:51 -0800100 for (HInstruction* store : possibly_removed_stores_) {
Nicolas Geoffray8c4ddb22017-11-13 11:49:53 +0000101 DCHECK(store->IsInstanceFieldSet() || store->IsStaticFieldSet() || store->IsArraySet());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800102 store->GetBlock()->RemoveInstruction(store);
103 }
104
Igor Murashkind01745e2017-04-05 16:40:31 -0700105 // Eliminate singleton-classified instructions:
106 // * - Constructor fences (they never escape this thread).
107 // * - Allocations (if they are unused).
Mingyao Yang86974902017-03-01 14:03:51 -0800108 for (HInstruction* new_instance : singleton_new_instances_) {
Igor Murashkin6ef45672017-08-08 13:59:55 -0700109 size_t removed = HConstructorFence::RemoveConstructorFences(new_instance);
110 MaybeRecordStat(stats_,
111 MethodCompilationStat::kConstructorFenceRemovedLSE,
112 removed);
Igor Murashkind01745e2017-04-05 16:40:31 -0700113
Mingyao Yang062157f2016-03-02 10:15:36 -0800114 if (!new_instance->HasNonEnvironmentUses()) {
115 new_instance->RemoveEnvironmentUsers();
116 new_instance->GetBlock()->RemoveInstruction(new_instance);
117 }
118 }
Mingyao Yang86974902017-03-01 14:03:51 -0800119 for (HInstruction* new_array : singleton_new_arrays_) {
Igor Murashkin6ef45672017-08-08 13:59:55 -0700120 size_t removed = HConstructorFence::RemoveConstructorFences(new_array);
121 MaybeRecordStat(stats_,
122 MethodCompilationStat::kConstructorFenceRemovedLSE,
123 removed);
Igor Murashkind01745e2017-04-05 16:40:31 -0700124
Mingyao Yang86974902017-03-01 14:03:51 -0800125 if (!new_array->HasNonEnvironmentUses()) {
126 new_array->RemoveEnvironmentUsers();
127 new_array->GetBlock()->RemoveInstruction(new_array);
128 }
129 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700130 }
131
132 private:
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800133 // If heap_values[index] is an instance field store, need to keep the store.
134 // This is necessary if a heap value is killed due to merging, or loop side
135 // effects (which is essentially merging also), since a load later from the
136 // location won't be eliminated.
137 void KeepIfIsStore(HInstruction* heap_value) {
138 if (heap_value == kDefaultHeapValue ||
139 heap_value == kUnknownHeapValue ||
Nicolas Geoffray8c4ddb22017-11-13 11:49:53 +0000140 !(heap_value->IsInstanceFieldSet() || heap_value->IsArraySet())) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800141 return;
142 }
143 auto idx = std::find(possibly_removed_stores_.begin(),
144 possibly_removed_stores_.end(), heap_value);
145 if (idx != possibly_removed_stores_.end()) {
146 // Make sure the store is kept.
147 possibly_removed_stores_.erase(idx);
148 }
149 }
150
151 void HandleLoopSideEffects(HBasicBlock* block) {
152 DCHECK(block->IsLoopHeader());
153 int block_id = block->GetBlockId();
Vladimir Marko009d1662017-10-10 13:21:15 +0100154 ScopedArenaVector<HInstruction*>& heap_values = heap_values_for_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000155
156 // Don't eliminate loads in irreducible loops. This is safe for singletons, because
157 // they are always used by the non-eliminated loop-phi.
158 if (block->GetLoopInformation()->IsIrreducible()) {
159 if (kIsDebugBuild) {
160 for (size_t i = 0; i < heap_values.size(); i++) {
161 DCHECK_EQ(heap_values[i], kUnknownHeapValue);
162 }
163 }
164 return;
165 }
166
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800167 HBasicBlock* pre_header = block->GetLoopInformation()->GetPreHeader();
Vladimir Marko009d1662017-10-10 13:21:15 +0100168 ScopedArenaVector<HInstruction*>& pre_header_heap_values =
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800169 heap_values_for_[pre_header->GetBlockId()];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000170
Mingyao Yang803cbb92015-12-01 12:24:36 -0800171 // Inherit the values from pre-header.
172 for (size_t i = 0; i < heap_values.size(); i++) {
173 heap_values[i] = pre_header_heap_values[i];
174 }
175
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800176 // We do a single pass in reverse post order. For loops, use the side effects as a hint
177 // to see if the heap values should be killed.
178 if (side_effects_.GetLoopEffects(block).DoesAnyWrite()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800179 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang803cbb92015-12-01 12:24:36 -0800180 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
181 ReferenceInfo* ref_info = location->GetReferenceInfo();
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800182 if (ref_info->IsSingletonAndRemovable() &&
183 !location->IsValueKilledByLoopSideEffects()) {
184 // A removable singleton's field that's not stored into inside a loop is
185 // invariant throughout the loop. Nothing to do.
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800186 } else {
187 // heap value is killed by loop side effects (stored into directly, or
188 // due to aliasing). Or the heap value may be needed after method return
189 // or deoptimization.
Mingyao Yang803cbb92015-12-01 12:24:36 -0800190 KeepIfIsStore(pre_header_heap_values[i]);
191 heap_values[i] = kUnknownHeapValue;
Mingyao Yang803cbb92015-12-01 12:24:36 -0800192 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800193 }
194 }
195 }
196
Mingyao Yang8df69d42015-10-22 15:40:58 -0700197 void MergePredecessorValues(HBasicBlock* block) {
Vladimir Marko009d1662017-10-10 13:21:15 +0100198 ArrayRef<HBasicBlock* const> predecessors(block->GetPredecessors());
Mingyao Yang8df69d42015-10-22 15:40:58 -0700199 if (predecessors.size() == 0) {
200 return;
201 }
Mingyao Yang46721ef2017-10-05 14:45:17 -0700202 if (block->IsExitBlock()) {
203 // Exit block doesn't really merge values since the control flow ends in
204 // its predecessors. Each predecessor needs to make sure stores are kept
205 // if necessary.
206 return;
207 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700208
Vladimir Marko009d1662017-10-10 13:21:15 +0100209 ScopedArenaVector<HInstruction*>& heap_values = heap_values_for_[block->GetBlockId()];
Mingyao Yang8df69d42015-10-22 15:40:58 -0700210 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700211 HInstruction* merged_value = nullptr;
212 // Whether merged_value is a result that's merged from all predecessors.
213 bool from_all_predecessors = true;
214 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
215 HInstruction* singleton_ref = nullptr;
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800216 if (ref_info->IsSingleton()) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700217 // We do more analysis of liveness when merging heap values for such
218 // cases since stores into such references may potentially be eliminated.
219 singleton_ref = ref_info->GetReference();
220 }
221
222 for (HBasicBlock* predecessor : predecessors) {
223 HInstruction* pred_value = heap_values_for_[predecessor->GetBlockId()][i];
224 if ((singleton_ref != nullptr) &&
225 !singleton_ref->GetBlock()->Dominates(predecessor)) {
226 // singleton_ref is not live in this predecessor. Skip this predecessor since
227 // it does not really have the location.
228 DCHECK_EQ(pred_value, kUnknownHeapValue);
229 from_all_predecessors = false;
230 continue;
231 }
232 if (merged_value == nullptr) {
233 // First seen heap value.
234 merged_value = pred_value;
235 } else if (pred_value != merged_value) {
236 // There are conflicting values.
237 merged_value = kUnknownHeapValue;
238 break;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700239 }
240 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800241
Mingyao Yang46721ef2017-10-05 14:45:17 -0700242 if (ref_info->IsSingleton()) {
243 if (ref_info->IsSingletonAndNonRemovable() ||
244 (merged_value == kUnknownHeapValue &&
245 !block->IsSingleReturnOrReturnVoidAllowingPhis())) {
246 // The heap value may be needed after method return or deoptimization,
247 // or there are conflicting heap values from different predecessors and
248 // this block is not a single return,
249 // keep the last store in each predecessor since future loads may not
250 // be eliminated.
251 for (HBasicBlock* predecessor : predecessors) {
252 ScopedArenaVector<HInstruction*>& pred_values =
253 heap_values_for_[predecessor->GetBlockId()];
254 KeepIfIsStore(pred_values[i]);
255 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800256 }
Mingyao Yang46721ef2017-10-05 14:45:17 -0700257 } else {
258 // Currenctly we don't eliminate stores to non-singletons.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800259 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700260
261 if ((merged_value == nullptr) || !from_all_predecessors) {
262 DCHECK(singleton_ref != nullptr);
263 DCHECK((singleton_ref->GetBlock() == block) ||
264 !singleton_ref->GetBlock()->Dominates(block));
265 // singleton_ref is not defined before block or defined only in some of its
266 // predecessors, so block doesn't really have the location at its entry.
267 heap_values[i] = kUnknownHeapValue;
268 } else {
269 heap_values[i] = merged_value;
270 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700271 }
272 }
273
274 // `instruction` is being removed. Try to see if the null check on it
275 // can be removed. This can happen if the same value is set in two branches
276 // but not in dominators. Such as:
277 // int[] a = foo();
278 // if () {
279 // a[0] = 2;
280 // } else {
281 // a[0] = 2;
282 // }
283 // // a[0] can now be replaced with constant 2, and the null check on it can be removed.
284 void TryRemovingNullCheck(HInstruction* instruction) {
285 HInstruction* prev = instruction->GetPrevious();
286 if ((prev != nullptr) && prev->IsNullCheck() && (prev == instruction->InputAt(0))) {
287 // Previous instruction is a null check for this instruction. Remove the null check.
288 prev->ReplaceWith(prev->InputAt(0));
289 prev->GetBlock()->RemoveInstruction(prev);
290 }
291 }
292
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100293 HInstruction* GetDefaultValue(DataType::Type type) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700294 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100295 case DataType::Type::kReference:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700296 return GetGraph()->GetNullConstant();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100297 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100298 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100299 case DataType::Type::kInt8:
300 case DataType::Type::kUint16:
301 case DataType::Type::kInt16:
302 case DataType::Type::kInt32:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700303 return GetGraph()->GetIntConstant(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100304 case DataType::Type::kInt64:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700305 return GetGraph()->GetLongConstant(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100306 case DataType::Type::kFloat32:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700307 return GetGraph()->GetFloatConstant(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100308 case DataType::Type::kFloat64:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700309 return GetGraph()->GetDoubleConstant(0);
310 default:
311 UNREACHABLE();
312 }
313 }
314
315 void VisitGetLocation(HInstruction* instruction,
316 HInstruction* ref,
317 size_t offset,
318 HInstruction* index,
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100319 size_t vector_length,
Mingyao Yang8df69d42015-10-22 15:40:58 -0700320 int16_t declaring_class_def_index) {
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100321 HInstruction* original_ref = heap_location_collector_.HuntForOriginalReference(ref);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700322 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
323 size_t idx = heap_location_collector_.FindHeapLocationIndex(
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100324 ref_info, offset, index, vector_length, declaring_class_def_index);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700325 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
Vladimir Marko009d1662017-10-10 13:21:15 +0100326 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang8df69d42015-10-22 15:40:58 -0700327 heap_values_for_[instruction->GetBlock()->GetBlockId()];
328 HInstruction* heap_value = heap_values[idx];
329 if (heap_value == kDefaultHeapValue) {
330 HInstruction* constant = GetDefaultValue(instruction->GetType());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800331 removed_loads_.push_back(instruction);
332 substitute_instructions_for_loads_.push_back(constant);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700333 heap_values[idx] = constant;
334 return;
335 }
Mingyao Yang86974902017-03-01 14:03:51 -0800336 if (heap_value != kUnknownHeapValue) {
Nicolas Geoffray8c4ddb22017-11-13 11:49:53 +0000337 if (heap_value->IsInstanceFieldSet() || heap_value->IsArraySet()) {
Mingyao Yang86974902017-03-01 14:03:51 -0800338 HInstruction* store = heap_value;
339 // This load must be from a singleton since it's from the same
340 // field/element that a "removed" store puts the value. That store
341 // must be to a singleton's field/element.
342 DCHECK(ref_info->IsSingleton());
343 // Get the real heap value of the store.
344 heap_value = heap_value->IsInstanceFieldSet() ? store->InputAt(1) : store->InputAt(2);
345 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800346 }
David Brazdil15693bf2015-12-16 10:30:45 +0000347 if (heap_value == kUnknownHeapValue) {
348 // Load isn't eliminated. Put the load as the value into the HeapLocation.
349 // This acts like GVN but with better aliasing analysis.
350 heap_values[idx] = instruction;
351 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100352 if (DataType::Kind(heap_value->GetType()) != DataType::Kind(instruction->GetType())) {
Nicolas Geoffray03971632016-03-17 10:44:24 +0000353 // The only situation where the same heap location has different type is when
Nicolas Geoffray65fef302016-05-04 14:00:12 +0100354 // we do an array get on an instruction that originates from the null constant
355 // (the null could be behind a field access, an array access, a null check or
356 // a bound type).
357 // In order to stay properly typed on primitive types, we do not eliminate
358 // the array gets.
Nicolas Geoffray03971632016-03-17 10:44:24 +0000359 if (kIsDebugBuild) {
360 DCHECK(heap_value->IsArrayGet()) << heap_value->DebugName();
361 DCHECK(instruction->IsArrayGet()) << instruction->DebugName();
Nicolas Geoffray03971632016-03-17 10:44:24 +0000362 }
363 return;
364 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800365 removed_loads_.push_back(instruction);
366 substitute_instructions_for_loads_.push_back(heap_value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700367 TryRemovingNullCheck(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700368 }
369 }
370
371 bool Equal(HInstruction* heap_value, HInstruction* value) {
372 if (heap_value == value) {
373 return true;
374 }
375 if (heap_value == kDefaultHeapValue && GetDefaultValue(value->GetType()) == value) {
376 return true;
377 }
378 return false;
379 }
380
381 void VisitSetLocation(HInstruction* instruction,
382 HInstruction* ref,
383 size_t offset,
384 HInstruction* index,
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100385 size_t vector_length,
Mingyao Yang8df69d42015-10-22 15:40:58 -0700386 int16_t declaring_class_def_index,
387 HInstruction* value) {
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100388 HInstruction* original_ref = heap_location_collector_.HuntForOriginalReference(ref);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700389 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
390 size_t idx = heap_location_collector_.FindHeapLocationIndex(
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100391 ref_info, offset, index, vector_length, declaring_class_def_index);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700392 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
Vladimir Marko009d1662017-10-10 13:21:15 +0100393 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang8df69d42015-10-22 15:40:58 -0700394 heap_values_for_[instruction->GetBlock()->GetBlockId()];
395 HInstruction* heap_value = heap_values[idx];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800396 bool same_value = false;
397 bool possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700398 if (Equal(heap_value, value)) {
399 // Store into the heap location with the same value.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800400 same_value = true;
Mingyao Yang0e3151b2017-10-30 11:19:57 -0700401 } else if (index != nullptr &&
402 heap_location_collector_.GetHeapLocation(idx)->HasAliasedLocations()) {
403 // For array element, don't eliminate stores if the location can be aliased
404 // (due to either ref or index aliasing).
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800405 } else if (ref_info->IsSingleton()) {
Mingyao Yang025c1a62017-10-30 11:19:57 -0700406 // Store into a field/element of a singleton. The value cannot be killed due to
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800407 // aliasing/invocation. It can be redundant since future loads can
408 // directly get the value set by this instruction. The value can still be killed due to
409 // merging or loop side effects. Stores whose values are killed due to merging/loop side
410 // effects later will be removed from possibly_removed_stores_ when that is detected.
411 // Stores whose values may be needed after method return or deoptimization
412 // are also removed from possibly_removed_stores_ when that is detected.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800413 possibly_redundant = true;
Mingyao Yang025c1a62017-10-30 11:19:57 -0700414 HLoopInformation* loop_info = instruction->GetBlock()->GetLoopInformation();
415 if (loop_info != nullptr) {
416 // instruction is a store in the loop so the loop must does write.
417 DCHECK(side_effects_.GetLoopEffects(loop_info->GetHeader()).DoesAnyWrite());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800418
Mingyao Yang025c1a62017-10-30 11:19:57 -0700419 if (loop_info->IsDefinedOutOfTheLoop(original_ref)) {
420 DCHECK(original_ref->GetBlock()->Dominates(loop_info->GetPreHeader()));
421 // Keep the store since its value may be needed at the loop header.
422 possibly_redundant = false;
423 } else {
424 // The singleton is created inside the loop. Value stored to it isn't needed at
425 // the loop header. This is true for outer loops also.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800426 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700427 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700428 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800429 if (same_value || possibly_redundant) {
430 possibly_removed_stores_.push_back(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700431 }
Mingyao Yange9d6e602015-10-23 17:08:42 -0700432
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800433 if (!same_value) {
434 if (possibly_redundant) {
Nicolas Geoffray8c4ddb22017-11-13 11:49:53 +0000435 DCHECK(instruction->IsInstanceFieldSet() || instruction->IsArraySet());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800436 // Put the store as the heap value. If the value is loaded from heap
437 // by a load later, this store isn't really redundant.
438 heap_values[idx] = instruction;
439 } else {
440 heap_values[idx] = value;
441 }
442 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700443 // This store may kill values in other heap locations due to aliasing.
444 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800445 if (i == idx) {
446 continue;
447 }
Nicolas Geoffray8c4ddb22017-11-13 11:49:53 +0000448 if (heap_values[i] == value) {
449 // Same value should be kept even if aliasing happens.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700450 continue;
451 }
452 if (heap_values[i] == kUnknownHeapValue) {
453 // Value is already unknown, no need for aliasing check.
454 continue;
455 }
456 if (heap_location_collector_.MayAlias(i, idx)) {
457 // Kill heap locations that may alias.
458 heap_values[i] = kUnknownHeapValue;
459 }
460 }
461 }
462
463 void VisitInstanceFieldGet(HInstanceFieldGet* instruction) OVERRIDE {
464 HInstruction* obj = instruction->InputAt(0);
465 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
466 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100467 VisitGetLocation(instruction,
468 obj,
469 offset,
470 nullptr,
471 HeapLocation::kScalar,
472 declaring_class_def_index);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700473 }
474
475 void VisitInstanceFieldSet(HInstanceFieldSet* instruction) OVERRIDE {
476 HInstruction* obj = instruction->InputAt(0);
477 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
478 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
479 HInstruction* value = instruction->InputAt(1);
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100480 VisitSetLocation(instruction,
481 obj,
482 offset,
483 nullptr,
484 HeapLocation::kScalar,
485 declaring_class_def_index,
486 value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700487 }
488
489 void VisitStaticFieldGet(HStaticFieldGet* instruction) OVERRIDE {
490 HInstruction* cls = instruction->InputAt(0);
491 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
492 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100493 VisitGetLocation(instruction,
494 cls,
495 offset,
496 nullptr,
497 HeapLocation::kScalar,
498 declaring_class_def_index);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700499 }
500
501 void VisitStaticFieldSet(HStaticFieldSet* instruction) OVERRIDE {
502 HInstruction* cls = instruction->InputAt(0);
503 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
504 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
505 HInstruction* value = instruction->InputAt(1);
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100506 VisitSetLocation(instruction,
507 cls,
508 offset,
509 nullptr,
510 HeapLocation::kScalar,
511 declaring_class_def_index,
512 value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700513 }
514
515 void VisitArrayGet(HArrayGet* instruction) OVERRIDE {
516 HInstruction* array = instruction->InputAt(0);
517 HInstruction* index = instruction->InputAt(1);
518 VisitGetLocation(instruction,
519 array,
520 HeapLocation::kInvalidFieldOffset,
521 index,
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100522 HeapLocation::kScalar,
Mingyao Yang8df69d42015-10-22 15:40:58 -0700523 HeapLocation::kDeclaringClassDefIndexForArrays);
524 }
525
526 void VisitArraySet(HArraySet* instruction) OVERRIDE {
527 HInstruction* array = instruction->InputAt(0);
528 HInstruction* index = instruction->InputAt(1);
529 HInstruction* value = instruction->InputAt(2);
530 VisitSetLocation(instruction,
531 array,
532 HeapLocation::kInvalidFieldOffset,
533 index,
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100534 HeapLocation::kScalar,
Mingyao Yang8df69d42015-10-22 15:40:58 -0700535 HeapLocation::kDeclaringClassDefIndexForArrays,
536 value);
537 }
538
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800539 void VisitDeoptimize(HDeoptimize* instruction) {
Vladimir Marko009d1662017-10-10 13:21:15 +0100540 const ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800541 heap_values_for_[instruction->GetBlock()->GetBlockId()];
542 for (HInstruction* heap_value : heap_values) {
543 // Filter out fake instructions before checking instruction kind below.
544 if (heap_value == kUnknownHeapValue || heap_value == kDefaultHeapValue) {
545 continue;
546 }
547 // A store is kept as the heap value for possibly removed stores.
Nicolas Geoffray8c4ddb22017-11-13 11:49:53 +0000548 if (heap_value->IsInstanceFieldSet() || heap_value->IsArraySet()) {
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800549 // Check whether the reference for a store is used by an environment local of
550 // HDeoptimize.
551 HInstruction* reference = heap_value->InputAt(0);
552 DCHECK(heap_location_collector_.FindReferenceInfoOf(reference)->IsSingleton());
553 for (const HUseListNode<HEnvironment*>& use : reference->GetEnvUses()) {
554 HEnvironment* user = use.GetUser();
555 if (user->GetHolder() == instruction) {
556 // The singleton for the store is visible at this deoptimization
557 // point. Need to keep the store so that the heap value is
558 // seen by the interpreter.
559 KeepIfIsStore(heap_value);
560 }
561 }
562 }
563 }
564 }
565
Mingyao Yang46721ef2017-10-05 14:45:17 -0700566 // Keep necessary stores before exiting a method via return/throw.
567 void HandleExit(HBasicBlock* block) {
568 const ScopedArenaVector<HInstruction*>& heap_values =
569 heap_values_for_[block->GetBlockId()];
570 for (size_t i = 0; i < heap_values.size(); i++) {
571 HInstruction* heap_value = heap_values[i];
572 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
573 if (!ref_info->IsSingletonAndRemovable()) {
574 KeepIfIsStore(heap_value);
575 }
576 }
577 }
578
579 void VisitReturn(HReturn* instruction) OVERRIDE {
580 HandleExit(instruction->GetBlock());
581 }
582
583 void VisitReturnVoid(HReturnVoid* return_void) OVERRIDE {
584 HandleExit(return_void->GetBlock());
585 }
586
587 void VisitThrow(HThrow* throw_instruction) OVERRIDE {
588 HandleExit(throw_instruction->GetBlock());
589 }
590
Mingyao Yang293f1c02017-11-08 15:22:17 -0800591 void HandleInvoke(HInstruction* instruction) {
592 SideEffects side_effects = instruction->GetSideEffects();
Vladimir Marko009d1662017-10-10 13:21:15 +0100593 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang293f1c02017-11-08 15:22:17 -0800594 heap_values_for_[instruction->GetBlock()->GetBlockId()];
Mingyao Yang8df69d42015-10-22 15:40:58 -0700595 for (size_t i = 0; i < heap_values.size(); i++) {
596 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
597 if (ref_info->IsSingleton()) {
598 // Singleton references cannot be seen by the callee.
599 } else {
Mingyao Yang293f1c02017-11-08 15:22:17 -0800600 if (side_effects.DoesAnyRead()) {
601 KeepIfIsStore(heap_values[i]);
602 }
603 if (side_effects.DoesAnyWrite()) {
604 heap_values[i] = kUnknownHeapValue;
605 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700606 }
607 }
608 }
609
Mingyao Yangc62b7ec2017-10-25 16:42:15 -0700610 void VisitInvoke(HInvoke* invoke) OVERRIDE {
Orion Hodsonac141392017-01-13 11:53:47 +0000611 HandleInvoke(invoke);
612 }
613
Mingyao Yang8df69d42015-10-22 15:40:58 -0700614 void VisitClinitCheck(HClinitCheck* clinit) OVERRIDE {
615 HandleInvoke(clinit);
616 }
617
618 void VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet* instruction) OVERRIDE {
619 // Conservatively treat it as an invocation.
620 HandleInvoke(instruction);
621 }
622
623 void VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet* instruction) OVERRIDE {
624 // Conservatively treat it as an invocation.
625 HandleInvoke(instruction);
626 }
627
628 void VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet* instruction) OVERRIDE {
629 // Conservatively treat it as an invocation.
630 HandleInvoke(instruction);
631 }
632
633 void VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet* instruction) OVERRIDE {
634 // Conservatively treat it as an invocation.
635 HandleInvoke(instruction);
636 }
637
638 void VisitNewInstance(HNewInstance* new_instance) OVERRIDE {
639 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_instance);
640 if (ref_info == nullptr) {
641 // new_instance isn't used for field accesses. No need to process it.
642 return;
643 }
Mingyao Yang025c1a62017-10-30 11:19:57 -0700644 if (ref_info->IsSingletonAndRemovable() && !new_instance->NeedsChecks()) {
645 DCHECK(!new_instance->IsFinalizable());
Mingyao Yang062157f2016-03-02 10:15:36 -0800646 singleton_new_instances_.push_back(new_instance);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700647 }
Vladimir Marko009d1662017-10-10 13:21:15 +0100648 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang8df69d42015-10-22 15:40:58 -0700649 heap_values_for_[new_instance->GetBlock()->GetBlockId()];
650 for (size_t i = 0; i < heap_values.size(); i++) {
651 HInstruction* ref =
652 heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo()->GetReference();
653 size_t offset = heap_location_collector_.GetHeapLocation(i)->GetOffset();
654 if (ref == new_instance && offset >= mirror::kObjectHeaderSize) {
655 // Instance fields except the header fields are set to default heap values.
656 heap_values[i] = kDefaultHeapValue;
657 }
658 }
659 }
660
Mingyao Yang86974902017-03-01 14:03:51 -0800661 void VisitNewArray(HNewArray* new_array) OVERRIDE {
662 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_array);
663 if (ref_info == nullptr) {
664 // new_array isn't used for array accesses. No need to process it.
665 return;
666 }
667 if (ref_info->IsSingletonAndRemovable()) {
668 singleton_new_arrays_.push_back(new_array);
669 }
Vladimir Marko009d1662017-10-10 13:21:15 +0100670 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang86974902017-03-01 14:03:51 -0800671 heap_values_for_[new_array->GetBlock()->GetBlockId()];
672 for (size_t i = 0; i < heap_values.size(); i++) {
673 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
674 HInstruction* ref = location->GetReferenceInfo()->GetReference();
675 if (ref == new_array && location->GetIndex() != nullptr) {
676 // Array elements are set to default heap values.
677 heap_values[i] = kDefaultHeapValue;
678 }
679 }
680 }
681
Mingyao Yang8df69d42015-10-22 15:40:58 -0700682 // Find an instruction's substitute if it should be removed.
683 // Return the same instruction if it should not be removed.
684 HInstruction* FindSubstitute(HInstruction* instruction) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800685 size_t size = removed_loads_.size();
Mingyao Yang8df69d42015-10-22 15:40:58 -0700686 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800687 if (removed_loads_[i] == instruction) {
688 return substitute_instructions_for_loads_[i];
Mingyao Yang8df69d42015-10-22 15:40:58 -0700689 }
690 }
691 return instruction;
692 }
693
694 const HeapLocationCollector& heap_location_collector_;
695 const SideEffectsAnalysis& side_effects_;
696
Vladimir Marko009d1662017-10-10 13:21:15 +0100697 // Use local allocator for allocating memory.
698 ScopedArenaAllocator allocator_;
699
Mingyao Yang8df69d42015-10-22 15:40:58 -0700700 // One array of heap values for each block.
Vladimir Marko009d1662017-10-10 13:21:15 +0100701 ScopedArenaVector<ScopedArenaVector<HInstruction*>> heap_values_for_;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700702
703 // We record the instructions that should be eliminated but may be
704 // used by heap locations. They'll be removed in the end.
Vladimir Marko009d1662017-10-10 13:21:15 +0100705 ScopedArenaVector<HInstruction*> removed_loads_;
706 ScopedArenaVector<HInstruction*> substitute_instructions_for_loads_;
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800707
708 // Stores in this list may be removed from the list later when it's
709 // found that the store cannot be eliminated.
Vladimir Marko009d1662017-10-10 13:21:15 +0100710 ScopedArenaVector<HInstruction*> possibly_removed_stores_;
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800711
Vladimir Marko009d1662017-10-10 13:21:15 +0100712 ScopedArenaVector<HInstruction*> singleton_new_instances_;
713 ScopedArenaVector<HInstruction*> singleton_new_arrays_;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700714
715 DISALLOW_COPY_AND_ASSIGN(LSEVisitor);
716};
717
718void LoadStoreElimination::Run() {
David Brazdil8993caf2015-12-07 10:04:40 +0000719 if (graph_->IsDebuggable() || graph_->HasTryCatch()) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700720 // Debugger may set heap values or trigger deoptimization of callers.
David Brazdil8993caf2015-12-07 10:04:40 +0000721 // Try/catch support not implemented yet.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700722 // Skip this optimization.
723 return;
724 }
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100725 const HeapLocationCollector& heap_location_collector = lsa_.GetHeapLocationCollector();
726 if (heap_location_collector.GetNumberOfHeapLocations() == 0) {
727 // No HeapLocation information from LSA, skip this optimization.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700728 return;
729 }
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100730
Nicolas Geoffray8c4ddb22017-11-13 11:49:53 +0000731 // TODO: analyze VecLoad/VecStore better.
732 if (graph_->HasSIMD()) {
733 return;
734 }
735
Igor Murashkin6ef45672017-08-08 13:59:55 -0700736 LSEVisitor lse_visitor(graph_, heap_location_collector, side_effects_, stats_);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100737 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
738 lse_visitor.VisitBasicBlock(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700739 }
740 lse_visitor.RemoveInstructions();
741}
742
743} // namespace art