blob: a1ad58507df7ce1cd51a7c3e69118beab4e49a1b [file] [log] [blame]
Mingyao Yang063fc772016-08-02 11:02:54 -07001/*
2 * Copyright (C) 2016 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 "cha.h"
18
19#include "jit/jit.h"
20#include "jit/jit_code_cache.h"
21#include "runtime.h"
22#include "scoped_thread_state_change-inl.h"
23#include "stack.h"
24#include "thread.h"
25#include "thread_list.h"
26#include "thread_pool.h"
27
28namespace art {
29
30void ClassHierarchyAnalysis::AddDependency(ArtMethod* method,
31 ArtMethod* dependent_method,
32 OatQuickMethodHeader* dependent_header) {
33 auto it = cha_dependency_map_.find(method);
34 if (it == cha_dependency_map_.end()) {
35 cha_dependency_map_[method] =
36 new std::vector<std::pair<art::ArtMethod*, art::OatQuickMethodHeader*>>();
37 it = cha_dependency_map_.find(method);
38 } else {
39 DCHECK(it->second != nullptr);
40 }
41 it->second->push_back(std::make_pair(dependent_method, dependent_header));
42}
43
44std::vector<std::pair<ArtMethod*, OatQuickMethodHeader*>>*
45 ClassHierarchyAnalysis::GetDependents(ArtMethod* method) {
46 auto it = cha_dependency_map_.find(method);
47 if (it != cha_dependency_map_.end()) {
48 DCHECK(it->second != nullptr);
49 return it->second;
50 }
51 return nullptr;
52}
53
54void ClassHierarchyAnalysis::RemoveDependencyFor(ArtMethod* method) {
55 auto it = cha_dependency_map_.find(method);
56 if (it != cha_dependency_map_.end()) {
57 auto dependents = it->second;
58 cha_dependency_map_.erase(it);
59 delete dependents;
60 }
61}
62
63void ClassHierarchyAnalysis::RemoveDependentsWithMethodHeaders(
64 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
65 // Iterate through all entries in the dependency map and remove any entry that
66 // contains one of those in method_headers.
67 for (auto map_it = cha_dependency_map_.begin(); map_it != cha_dependency_map_.end(); ) {
68 auto dependents = map_it->second;
69 for (auto vec_it = dependents->begin(); vec_it != dependents->end(); ) {
70 OatQuickMethodHeader* method_header = vec_it->second;
71 auto it = std::find(method_headers.begin(), method_headers.end(), method_header);
72 if (it != method_headers.end()) {
73 vec_it = dependents->erase(vec_it);
74 } else {
75 vec_it++;
76 }
77 }
78 // Remove the map entry if there are no more dependents.
79 if (dependents->empty()) {
80 map_it = cha_dependency_map_.erase(map_it);
81 delete dependents;
82 } else {
83 map_it++;
84 }
85 }
86}
87
88// This stack visitor walks the stack and for compiled code with certain method
89// headers, sets the should_deoptimize flag on stack to 1.
90// TODO: also set the register value to 1 when should_deoptimize is allocated in
91// a register.
92class CHAStackVisitor FINAL : public StackVisitor {
93 public:
94 CHAStackVisitor(Thread* thread_in,
95 Context* context,
96 const std::unordered_set<OatQuickMethodHeader*>& method_headers)
97 : StackVisitor(thread_in, context, StackVisitor::StackWalkKind::kSkipInlinedFrames),
98 method_headers_(method_headers) {
99 }
100
101 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
102 ArtMethod* method = GetMethod();
Mingyao Yang7b9a83f2016-12-13 12:28:31 -0800103 // Avoid types of methods that do not have an oat quick method header.
104 if (method == nullptr ||
105 method->IsRuntimeMethod() ||
106 method->IsNative() ||
107 method->IsProxyMethod()) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700108 return true;
109 }
110 if (GetCurrentQuickFrame() == nullptr) {
111 // Not compiled code.
112 return true;
113 }
114 // Method may have multiple versions of compiled code. Check
115 // the method header to see if it has should_deoptimize flag.
116 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
Mingyao Yang7b9a83f2016-12-13 12:28:31 -0800117 DCHECK(method_header != nullptr);
Mingyao Yang063fc772016-08-02 11:02:54 -0700118 if (!method_header->HasShouldDeoptimizeFlag()) {
119 // This compiled version doesn't have should_deoptimize flag. Skip.
120 return true;
121 }
122 auto it = std::find(method_headers_.begin(), method_headers_.end(), method_header);
123 if (it == method_headers_.end()) {
124 // Not in the list of method headers that should be deoptimized.
125 return true;
126 }
127
128 // The compiled code on stack is not valid anymore. Need to deoptimize.
129 SetShouldDeoptimizeFlag();
130
131 return true;
132 }
133
134 private:
135 void SetShouldDeoptimizeFlag() REQUIRES_SHARED(Locks::mutator_lock_) {
136 QuickMethodFrameInfo frame_info = GetCurrentQuickFrameInfo();
137 size_t frame_size = frame_info.FrameSizeInBytes();
138 uint8_t* sp = reinterpret_cast<uint8_t*>(GetCurrentQuickFrame());
139 size_t core_spill_size = POPCOUNT(frame_info.CoreSpillMask()) *
140 GetBytesPerGprSpillLocation(kRuntimeISA);
141 size_t fpu_spill_size = POPCOUNT(frame_info.FpSpillMask()) *
142 GetBytesPerFprSpillLocation(kRuntimeISA);
143 size_t offset = frame_size - core_spill_size - fpu_spill_size - kShouldDeoptimizeFlagSize;
144 uint8_t* should_deoptimize_addr = sp + offset;
145 // Set deoptimization flag to 1.
146 DCHECK(*should_deoptimize_addr == 0 || *should_deoptimize_addr == 1);
147 *should_deoptimize_addr = 1;
148 }
149
150 // Set of method headers for compiled code that should be deoptimized.
151 const std::unordered_set<OatQuickMethodHeader*>& method_headers_;
152
153 DISALLOW_COPY_AND_ASSIGN(CHAStackVisitor);
154};
155
156class CHACheckpoint FINAL : public Closure {
157 public:
158 explicit CHACheckpoint(const std::unordered_set<OatQuickMethodHeader*>& method_headers)
159 : barrier_(0),
160 method_headers_(method_headers) {}
161
162 void Run(Thread* thread) OVERRIDE {
163 // Note thread and self may not be equal if thread was already suspended at
164 // the point of the request.
165 Thread* self = Thread::Current();
166 ScopedObjectAccess soa(self);
167 CHAStackVisitor visitor(thread, nullptr, method_headers_);
168 visitor.WalkStack();
169 barrier_.Pass(self);
170 }
171
172 void WaitForThreadsToRunThroughCheckpoint(size_t threads_running_checkpoint) {
173 Thread* self = Thread::Current();
174 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
175 barrier_.Increment(self, threads_running_checkpoint);
176 }
177
178 private:
179 // The barrier to be passed through and for the requestor to wait upon.
180 Barrier barrier_;
181 // List of method headers for invalidated compiled code.
182 const std::unordered_set<OatQuickMethodHeader*>& method_headers_;
183
184 DISALLOW_COPY_AND_ASSIGN(CHACheckpoint);
185};
186
187void ClassHierarchyAnalysis::VerifyNonSingleImplementation(mirror::Class* verify_class,
Mingyao Yangae6c1892017-01-05 13:46:36 -0800188 uint16_t verify_index,
189 ArtMethod* excluded_method) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700190 // Grab cha_lock_ to make sure all single-implementation updates are seen.
191 PointerSize image_pointer_size =
192 Runtime::Current()->GetClassLinker()->GetImagePointerSize();
193 MutexLock cha_mu(Thread::Current(), *Locks::cha_lock_);
194 while (verify_class != nullptr) {
195 if (verify_index >= verify_class->GetVTableLength()) {
196 return;
197 }
198 ArtMethod* verify_method = verify_class->GetVTableEntry(verify_index, image_pointer_size);
Mingyao Yangae6c1892017-01-05 13:46:36 -0800199 if (verify_method != excluded_method) {
200 DCHECK(!verify_method->HasSingleImplementation())
201 << "class: " << verify_class->PrettyClass()
202 << " verify_method: " << verify_method->PrettyMethod(true);
203 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700204 verify_class = verify_class->GetSuperClass();
205 }
206}
207
208void ClassHierarchyAnalysis::CheckSingleImplementationInfo(
209 Handle<mirror::Class> klass,
210 ArtMethod* virtual_method,
211 ArtMethod* method_in_super,
Mingyao Yangae6c1892017-01-05 13:46:36 -0800212 std::unordered_set<ArtMethod*>& invalidated_single_impl_methods,
213 PointerSize pointer_size) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700214 // TODO: if klass is not instantiable, virtual_method isn't invocable yet so
215 // even if it overrides, it doesn't invalidate single-implementation
216 // assumption.
217
Mingyao Yangae6c1892017-01-05 13:46:36 -0800218 DCHECK((virtual_method != method_in_super) || virtual_method->IsAbstract());
Mingyao Yang063fc772016-08-02 11:02:54 -0700219 DCHECK(method_in_super->GetDeclaringClass()->IsResolved()) << "class isn't resolved";
220 // If virtual_method doesn't come from a default interface method, it should
221 // be supplied by klass.
Mingyao Yangae6c1892017-01-05 13:46:36 -0800222 DCHECK(virtual_method == method_in_super ||
223 virtual_method->IsCopied() ||
Mingyao Yang063fc772016-08-02 11:02:54 -0700224 virtual_method->GetDeclaringClass() == klass.Get());
225
Mingyao Yangae6c1892017-01-05 13:46:36 -0800226 // To make updating single-implementation flags simple, we always maintain the following
227 // invariant:
228 // Say all virtual methods in the same vtable slot, starting from the bottom child class
229 // to super classes, is a sequence of unique methods m3, m2, m1, ... (after removing duplicate
230 // methods for inherited methods).
231 // For example for the following class hierarchy,
232 // class A { void m() { ... } }
233 // class B extends A { void m() { ... } }
234 // class C extends B {}
235 // class D extends C { void m() { ... } }
236 // the sequence is D.m(), B.m(), A.m().
237 // The single-implementation status for that sequence of methods begin with one or two true's,
238 // then become all falses. The only case where two true's are possible is for one abstract
239 // method m and one non-abstract method mImpl that overrides method m.
240 // With the invariant, when linking in a new class, we only need to at most update one or
241 // two methods in the sequence for their single-implementation status, in order to maintain
242 // the invariant.
243
Mingyao Yang063fc772016-08-02 11:02:54 -0700244 if (!method_in_super->HasSingleImplementation()) {
245 // method_in_super already has multiple implementations. All methods in the
246 // same vtable slots in its super classes should have
247 // non-single-implementation already.
248 if (kIsDebugBuild) {
249 VerifyNonSingleImplementation(klass->GetSuperClass()->GetSuperClass(),
Mingyao Yangae6c1892017-01-05 13:46:36 -0800250 method_in_super->GetMethodIndex(),
251 nullptr /* excluded_method */);
Mingyao Yang063fc772016-08-02 11:02:54 -0700252 }
253 return;
254 }
255
256 // Native methods don't have single-implementation flag set.
257 DCHECK(!method_in_super->IsNative());
Mingyao Yangae6c1892017-01-05 13:46:36 -0800258
259 uint16_t method_index = method_in_super->GetMethodIndex();
260 if (method_in_super->IsAbstract()) {
261 if (kIsDebugBuild) {
262 // An abstract method should have made all methods in the same vtable
263 // slot above it in the class hierarchy having non-single-implementation.
264 mirror::Class* super_super = klass->GetSuperClass()->GetSuperClass();
265 VerifyNonSingleImplementation(super_super,
266 method_index,
267 method_in_super);
268 }
269
270 if (virtual_method->IsAbstract()) {
271 // SUPER: abstract, VIRTUAL: abstract.
272 if (method_in_super == virtual_method) {
273 DCHECK(klass->IsInstantiable());
274 // An instantiable subclass hasn't provided a concrete implementation of
275 // the abstract method. Invoking method_in_super may throw AbstractMethodError.
276 // This is an uncommon case, so we simply treat method_in_super as not
277 // having single-implementation.
278 invalidated_single_impl_methods.insert(method_in_super);
279 return;
280 } else {
281 // One abstract method overrides another abstract method. This is an uncommon
282 // case. We simply treat method_in_super as not having single-implementation.
283 invalidated_single_impl_methods.insert(method_in_super);
284 return;
285 }
286 } else {
287 // SUPER: abstract, VIRTUAL: non-abstract.
288 // A non-abstract method overrides an abstract method.
289 if (method_in_super->GetSingleImplementation(pointer_size) == nullptr) {
290 // Abstract method_in_super gets its first implementation. Keep it as having
291 // single-implementation and record that single implementation.
292 DCHECK(method_in_super->HasSingleImplementation());
293 method_in_super->SetSingleImplementation(virtual_method, pointer_size);
294 return;
295 } else {
296 // Abstract method_in_super already got one implementation.
297 // Invalidate method_in_super's single-implementation status.
298 invalidated_single_impl_methods.insert(method_in_super);
299 return;
300 }
301 }
302 } else {
303 if (virtual_method->IsAbstract()) {
304 // SUPER: non-abstract, VIRTUAL: abstract.
305 // An abstract method overrides a non-abstract method. This is an uncommon
306 // case, we simply treat both methods as not having single-implementation.
307 invalidated_single_impl_methods.insert(virtual_method);
308 // Fall-through to handle invalidating method_in_super of its
309 // single-implementation status.
310 }
311
312 // SUPER: non-abstract, VIRTUAL: non-abstract/abstract(fall-through from previous if).
313 // Invalidate method_in_super's single-implementation status.
314 invalidated_single_impl_methods.insert(method_in_super);
315
316 // method_in_super might be the single-implementation of another abstract method,
317 // which should be also invalidated of its single-implementation status.
318 mirror::Class* super_super = klass->GetSuperClass()->GetSuperClass();
319 while (super_super != nullptr &&
320 method_index < super_super->GetVTableLength()) {
321 ArtMethod* method_in_super_super = super_super->GetVTableEntry(method_index, pointer_size);
322 if (method_in_super_super != method_in_super) {
323 if (method_in_super_super->IsAbstract()) {
324 if (method_in_super_super->HasSingleImplementation()) {
325 // Invalidate method_in_super's single-implementation status.
326 invalidated_single_impl_methods.insert(method_in_super_super);
327 // No need to further traverse up the class hierarchy since if there
328 // are cases that one abstract method overrides another method, we
329 // should have made that method having non-single-implementation already.
330 } else {
331 // method_in_super_super is already non-single-implementation.
332 // No need to further traverse up the class hierarchy.
333 }
334 } else {
335 DCHECK(!method_in_super_super->HasSingleImplementation());
336 // No need to further traverse up the class hierarchy since two non-abstract
337 // methods (method_in_super and method_in_super_super) should have set all
338 // other methods (abstract or not) in the vtable slot to be non-single-implementation.
339 }
340
341 if (kIsDebugBuild) {
342 VerifyNonSingleImplementation(super_super->GetSuperClass(),
343 method_index,
344 method_in_super_super);
345 }
346 // No need to go any further.
347 return;
348 } else {
349 super_super = super_super->GetSuperClass();
350 }
351 }
352 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700353}
354
355void ClassHierarchyAnalysis::InitSingleImplementationFlag(Handle<mirror::Class> klass,
Mingyao Yangae6c1892017-01-05 13:46:36 -0800356 ArtMethod* method,
357 PointerSize pointer_size) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700358 DCHECK(method->IsCopied() || method->GetDeclaringClass() == klass.Get());
359 if (klass->IsFinal() || method->IsFinal()) {
360 // Final classes or methods do not need CHA for devirtualization.
361 // This frees up modifier bits for intrinsics which currently are only
362 // used for static methods or methods of final classes.
363 return;
364 }
365 if (method->IsNative()) {
366 // Native method's invocation overhead is already high and it
367 // cannot be inlined. It's not worthwhile to devirtualize the
368 // call which can add a deoptimization point.
369 DCHECK(!method->HasSingleImplementation());
Mingyao Yangae6c1892017-01-05 13:46:36 -0800370 } else if (method->IsAbstract()) {
371 if (method->GetDeclaringClass()->IsInstantiable()) {
372 // Rare case, but we do accept it (such as 800-smali/smali/b_26143249.smali).
373 // Do not attempt to devirtualize it.
374 method->SetHasSingleImplementation(false);
375 } else {
376 // Abstract method starts with single-implementation flag set and null
377 // implementation method.
378 method->SetHasSingleImplementation(true);
379 DCHECK(method->GetSingleImplementation(pointer_size) == nullptr);
380 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700381 } else {
382 method->SetHasSingleImplementation(true);
Mingyao Yangae6c1892017-01-05 13:46:36 -0800383 // Single implementation of non-abstract method is itself.
384 DCHECK_EQ(method->GetSingleImplementation(pointer_size), method);
Mingyao Yang063fc772016-08-02 11:02:54 -0700385 }
386}
387
388void ClassHierarchyAnalysis::UpdateAfterLoadingOf(Handle<mirror::Class> klass) {
389 if (klass->IsInterface()) {
390 return;
391 }
392 mirror::Class* super_class = klass->GetSuperClass();
393 if (super_class == nullptr) {
394 return;
395 }
396
397 // Keeps track of all methods whose single-implementation assumption
398 // is invalidated by linking `klass`.
399 std::unordered_set<ArtMethod*> invalidated_single_impl_methods;
400
401 PointerSize image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
402 // Do an entry-by-entry comparison of vtable contents with super's vtable.
403 for (int32_t i = 0; i < super_class->GetVTableLength(); ++i) {
404 ArtMethod* method = klass->GetVTableEntry(i, image_pointer_size);
405 ArtMethod* method_in_super = super_class->GetVTableEntry(i, image_pointer_size);
406 if (method == method_in_super) {
407 // vtable slot entry is inherited from super class.
Mingyao Yangae6c1892017-01-05 13:46:36 -0800408 if (method->IsAbstract() && klass->IsInstantiable()) {
409 // An instantiable class that inherits an abstract method is treated as
410 // supplying an implementation that throws AbstractMethodError.
411 CheckSingleImplementationInfo(klass,
412 method,
413 method_in_super,
414 invalidated_single_impl_methods,
415 image_pointer_size);
416 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700417 continue;
418 }
Mingyao Yangae6c1892017-01-05 13:46:36 -0800419 InitSingleImplementationFlag(klass, method, image_pointer_size);
Mingyao Yang063fc772016-08-02 11:02:54 -0700420 CheckSingleImplementationInfo(klass,
421 method,
422 method_in_super,
Mingyao Yangae6c1892017-01-05 13:46:36 -0800423 invalidated_single_impl_methods,
424 image_pointer_size);
Mingyao Yang063fc772016-08-02 11:02:54 -0700425 }
426
427 // For new virtual methods that don't override.
428 for (int32_t i = super_class->GetVTableLength(); i < klass->GetVTableLength(); ++i) {
429 ArtMethod* method = klass->GetVTableEntry(i, image_pointer_size);
Mingyao Yangae6c1892017-01-05 13:46:36 -0800430 InitSingleImplementationFlag(klass, method, image_pointer_size);
Mingyao Yang063fc772016-08-02 11:02:54 -0700431 }
432
433 Runtime* const runtime = Runtime::Current();
434 if (!invalidated_single_impl_methods.empty()) {
435 Thread *self = Thread::Current();
436 // Method headers for compiled code to be invalidated.
437 std::unordered_set<OatQuickMethodHeader*> dependent_method_headers;
438
439 {
440 // We do this under cha_lock_. Committing code also grabs this lock to
441 // make sure the code is only committed when all single-implementation
442 // assumptions are still true.
443 MutexLock cha_mu(self, *Locks::cha_lock_);
444 // Invalidate compiled methods that assume some virtual calls have only
445 // single implementations.
446 for (ArtMethod* invalidated : invalidated_single_impl_methods) {
447 if (!invalidated->HasSingleImplementation()) {
448 // It might have been invalidated already when other class linking is
449 // going on.
450 continue;
451 }
452 invalidated->SetHasSingleImplementation(false);
453
454 if (runtime->IsAotCompiler()) {
455 // No need to invalidate any compiled code as the AotCompiler doesn't
456 // run any code.
457 continue;
458 }
459
460 // Invalidate all dependents.
461 auto dependents = GetDependents(invalidated);
462 if (dependents == nullptr) {
463 continue;
464 }
465 for (const auto& dependent : *dependents) {
466 ArtMethod* method = dependent.first;;
467 OatQuickMethodHeader* method_header = dependent.second;
468 VLOG(class_linker) << "CHA invalidated compiled code for " << method->PrettyMethod();
469 DCHECK(runtime->UseJitCompilation());
470 runtime->GetJit()->GetCodeCache()->InvalidateCompiledCodeFor(
471 method, method_header);
472 dependent_method_headers.insert(method_header);
473 }
474 RemoveDependencyFor(invalidated);
475 }
476 }
477
478 if (dependent_method_headers.empty()) {
479 return;
480 }
481 // Deoptimze compiled code on stack that should have been invalidated.
482 CHACheckpoint checkpoint(dependent_method_headers);
483 size_t threads_running_checkpoint = runtime->GetThreadList()->RunCheckpoint(&checkpoint);
484 if (threads_running_checkpoint != 0) {
485 checkpoint.WaitForThreadsToRunThroughCheckpoint(threads_running_checkpoint);
486 }
487 }
488}
489
490} // namespace art