1 /*
  2  * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "precompiled.hpp"
 26 #include "code/compiledIC.hpp"
 27 #include "code/compiledMethod.inline.hpp"
 28 #include "code/exceptionHandlerTable.hpp"
 29 #include "code/scopeDesc.hpp"
 30 #include "code/codeCache.hpp"
 31 #include "code/icBuffer.hpp"
 32 #include "gc/shared/barrierSet.hpp"
 33 #include "gc/shared/barrierSetNMethod.hpp"
 34 #include "gc/shared/gcBehaviours.hpp"
 35 #include "interpreter/bytecode.inline.hpp"
 36 #include "logging/log.hpp"
 37 #include "logging/logTag.hpp"
 38 #include "memory/resourceArea.hpp"
 39 #include "oops/compiledICHolder.inline.hpp"
 40 #include "oops/klass.inline.hpp"
 41 #include "oops/methodData.hpp"
 42 #include "oops/method.inline.hpp"
 43 #include "oops/weakHandle.inline.hpp"
 44 #include "prims/methodHandles.hpp"
 45 #include "runtime/atomic.hpp"
 46 #include "runtime/deoptimization.hpp"
 47 #include "runtime/frame.inline.hpp"
 48 #include "runtime/jniHandles.inline.hpp"
 49 #include "runtime/handles.inline.hpp"
 50 #include "runtime/mutexLocker.hpp"
 51 #include "runtime/sharedRuntime.hpp"
 52 
 53 CompiledMethod::CompiledMethod(Method* method, const char* name, CompilerType type, const CodeBlobLayout& layout,
 54                                int frame_complete_offset, int frame_size, ImmutableOopMapSet* oop_maps,
 55                                bool caller_must_gc_arguments, bool compiled)
 56   : CodeBlob(name, type, layout, frame_complete_offset, frame_size, oop_maps, caller_must_gc_arguments, compiled),
 57     _mark_for_deoptimization_status(not_marked),
 58     _method(method),
 59     _gc_data(NULL)
 60 {
 61   init_defaults();
 62 }
 63 
 64 CompiledMethod::CompiledMethod(Method* method, const char* name, CompilerType type, int size,
 65                                int header_size, CodeBuffer* cb, int frame_complete_offset, int frame_size,
 66                                OopMapSet* oop_maps, bool caller_must_gc_arguments, bool compiled)
 67   : CodeBlob(name, type, CodeBlobLayout((address) this, size, header_size, cb), cb,
 68              frame_complete_offset, frame_size, oop_maps, caller_must_gc_arguments, compiled),
 69     _mark_for_deoptimization_status(not_marked),
 70     _method(method),
 71     _gc_data(NULL)
 72 {
 73   init_defaults();
 74 }
 75 
 76 void CompiledMethod::init_defaults() {
 77   { // avoid uninitialized fields, even for short time periods
 78     _scopes_data_begin          = NULL;
 79     _deopt_handler_begin        = NULL;
 80     _deopt_mh_handler_begin     = NULL;
 81     _exception_cache            = NULL;
 82   }
 83   _has_unsafe_access          = 0;
 84   _has_method_handle_invokes  = 0;
 85   _has_wide_vectors           = 0;
 86   _has_monitors               = 0;
 87 }
 88 
 89 bool CompiledMethod::is_method_handle_return(address return_pc) {
 90   if (!has_method_handle_invokes())  return false;
 91   PcDesc* pd = pc_desc_at(return_pc);
 92   if (pd == NULL)
 93     return false;
 94   return pd->is_method_handle_invoke();
 95 }
 96 
 97 // Returns a string version of the method state.
 98 const char* CompiledMethod::state() const {
 99   int state = get_state();
100   switch (state) {
101   case not_installed:
102     return "not installed";
103   case in_use:
104     return "in use";
105   case not_used:
106     return "not_used";
107   case not_entrant:
108     return "not_entrant";
109   case zombie:
110     return "zombie";
111   case unloaded:
112     return "unloaded";
113   default:
114     fatal("unexpected method state: %d", state);
115     return NULL;
116   }
117 }
118 
119 //-----------------------------------------------------------------------------
120 void CompiledMethod::mark_for_deoptimization(bool inc_recompile_counts) {
121   // assert (can_be_deoptimized(), ""); // in some places we check before marking, in others not.
122   MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock,
123                  Mutex::_no_safepoint_check_flag);
124   _mark_for_deoptimization_status = (inc_recompile_counts ? deoptimize : deoptimize_noupdate);
125 }
126 
127 //-----------------------------------------------------------------------------
128 
129 ExceptionCache* CompiledMethod::exception_cache_acquire() const {
130   return Atomic::load_acquire(&_exception_cache);
131 }
132 
133 void CompiledMethod::add_exception_cache_entry(ExceptionCache* new_entry) {
134   assert(ExceptionCache_lock->owned_by_self(),"Must hold the ExceptionCache_lock");
135   assert(new_entry != NULL,"Must be non null");
136   assert(new_entry->next() == NULL, "Must be null");
137 
138   for (;;) {
139     ExceptionCache *ec = exception_cache();
140     if (ec != NULL) {
141       Klass* ex_klass = ec->exception_type();
142       if (!ex_klass->is_loader_alive()) {
143         // We must guarantee that entries are not inserted with new next pointer
144         // edges to ExceptionCache entries with dead klasses, due to bad interactions
145         // with concurrent ExceptionCache cleanup. Therefore, the inserts roll
146         // the head pointer forward to the first live ExceptionCache, so that the new
147         // next pointers always point at live ExceptionCaches, that are not removed due
148         // to concurrent ExceptionCache cleanup.
149         ExceptionCache* next = ec->next();
150         if (Atomic::cmpxchg(&_exception_cache, ec, next) == ec) {
151           CodeCache::release_exception_cache(ec);
152         }
153         continue;
154       }
155       ec = exception_cache();
156       if (ec != NULL) {
157         new_entry->set_next(ec);
158       }
159     }
160     if (Atomic::cmpxchg(&_exception_cache, ec, new_entry) == ec) {
161       return;
162     }
163   }
164 }
165 
166 void CompiledMethod::clean_exception_cache() {
167   // For each nmethod, only a single thread may call this cleanup function
168   // at the same time, whether called in STW cleanup or concurrent cleanup.
169   // Note that if the GC is processing exception cache cleaning in a concurrent phase,
170   // then a single writer may contend with cleaning up the head pointer to the
171   // first ExceptionCache node that has a Klass* that is alive. That is fine,
172   // as long as there is no concurrent cleanup of next pointers from concurrent writers.
173   // And the concurrent writers do not clean up next pointers, only the head.
174   // Also note that concurent readers will walk through Klass* pointers that are not
175   // alive. That does not cause ABA problems, because Klass* is deleted after
176   // a handshake with all threads, after all stale ExceptionCaches have been
177   // unlinked. That is also when the CodeCache::exception_cache_purge_list()
178   // is deleted, with all ExceptionCache entries that were cleaned concurrently.
179   // That similarly implies that CAS operations on ExceptionCache entries do not
180   // suffer from ABA problems as unlinking and deletion is separated by a global
181   // handshake operation.
182   ExceptionCache* prev = NULL;
183   ExceptionCache* curr = exception_cache_acquire();
184 
185   while (curr != NULL) {
186     ExceptionCache* next = curr->next();
187 
188     if (!curr->exception_type()->is_loader_alive()) {
189       if (prev == NULL) {
190         // Try to clean head; this is contended by concurrent inserts, that
191         // both lazily clean the head, and insert entries at the head. If
192         // the CAS fails, the operation is restarted.
193         if (Atomic::cmpxchg(&_exception_cache, curr, next) != curr) {
194           prev = NULL;
195           curr = exception_cache_acquire();
196           continue;
197         }
198       } else {
199         // It is impossible to during cleanup connect the next pointer to
200         // an ExceptionCache that has not been published before a safepoint
201         // prior to the cleanup. Therefore, release is not required.
202         prev->set_next(next);
203       }
204       // prev stays the same.
205 
206       CodeCache::release_exception_cache(curr);
207     } else {
208       prev = curr;
209     }
210 
211     curr = next;
212   }
213 }
214 
215 // public method for accessing the exception cache
216 // These are the public access methods.
217 address CompiledMethod::handler_for_exception_and_pc(Handle exception, address pc) {
218   // We never grab a lock to read the exception cache, so we may
219   // have false negatives. This is okay, as it can only happen during
220   // the first few exception lookups for a given nmethod.
221   ExceptionCache* ec = exception_cache_acquire();
222   while (ec != NULL) {
223     address ret_val;
224     if ((ret_val = ec->match(exception,pc)) != NULL) {
225       return ret_val;
226     }
227     ec = ec->next();
228   }
229   return NULL;
230 }
231 
232 void CompiledMethod::add_handler_for_exception_and_pc(Handle exception, address pc, address handler) {
233   // There are potential race conditions during exception cache updates, so we
234   // must own the ExceptionCache_lock before doing ANY modifications. Because
235   // we don't lock during reads, it is possible to have several threads attempt
236   // to update the cache with the same data. We need to check for already inserted
237   // copies of the current data before adding it.
238 
239   MutexLocker ml(ExceptionCache_lock);
240   ExceptionCache* target_entry = exception_cache_entry_for_exception(exception);
241 
242   if (target_entry == NULL || !target_entry->add_address_and_handler(pc,handler)) {
243     target_entry = new ExceptionCache(exception,pc,handler);
244     add_exception_cache_entry(target_entry);
245   }
246 }
247 
248 // private method for handling exception cache
249 // These methods are private, and used to manipulate the exception cache
250 // directly.
251 ExceptionCache* CompiledMethod::exception_cache_entry_for_exception(Handle exception) {
252   ExceptionCache* ec = exception_cache_acquire();
253   while (ec != NULL) {
254     if (ec->match_exception_with_space(exception)) {
255       return ec;
256     }
257     ec = ec->next();
258   }
259   return NULL;
260 }
261 
262 //-------------end of code for ExceptionCache--------------
263 
264 bool CompiledMethod::is_at_poll_return(address pc) {
265   RelocIterator iter(this, pc, pc+1);
266   while (iter.next()) {
267     if (iter.type() == relocInfo::poll_return_type)
268       return true;
269   }
270   return false;
271 }
272 
273 
274 bool CompiledMethod::is_at_poll_or_poll_return(address pc) {
275   RelocIterator iter(this, pc, pc+1);
276   while (iter.next()) {
277     relocInfo::relocType t = iter.type();
278     if (t == relocInfo::poll_return_type || t == relocInfo::poll_type)
279       return true;
280   }
281   return false;
282 }
283 
284 void CompiledMethod::verify_oop_relocations() {
285   // Ensure sure that the code matches the current oop values
286   RelocIterator iter(this, NULL, NULL);
287   while (iter.next()) {
288     if (iter.type() == relocInfo::oop_type) {
289       oop_Relocation* reloc = iter.oop_reloc();
290       if (!reloc->oop_is_immediate()) {
291         reloc->verify_oop_relocation();
292       }
293     }
294   }
295 }
296 
297 
298 ScopeDesc* CompiledMethod::scope_desc_at(address pc) {
299   PcDesc* pd = pc_desc_at(pc);
300   guarantee(pd != NULL, "scope must be present");
301   return new ScopeDesc(this, pd);
302 }
303 
304 ScopeDesc* CompiledMethod::scope_desc_near(address pc) {
305   PcDesc* pd = pc_desc_near(pc);
306   guarantee(pd != NULL, "scope must be present");
307   return new ScopeDesc(this, pd);
308 }
309 
310 address CompiledMethod::oops_reloc_begin() const {
311   // If the method is not entrant or zombie then a JMP is plastered over the
312   // first few bytes.  If an oop in the old code was there, that oop
313   // should not get GC'd.  Skip the first few bytes of oops on
314   // not-entrant methods.
315   if (frame_complete_offset() != CodeOffsets::frame_never_safe &&
316       code_begin() + frame_complete_offset() >
317       verified_entry_point() + NativeJump::instruction_size)
318   {
319     // If we have a frame_complete_offset after the native jump, then there
320     // is no point trying to look for oops before that. This is a requirement
321     // for being allowed to scan oops concurrently.
322     return code_begin() + frame_complete_offset();
323   }
324 
325   // It is not safe to read oops concurrently using entry barriers, if their
326   // location depend on whether the nmethod is entrant or not.
327   // assert(BarrierSet::barrier_set()->barrier_set_nmethod() == NULL, "Not safe oop scan");
328 
329   address low_boundary = verified_entry_point();
330   if (!is_in_use() && is_nmethod()) {
331     low_boundary += NativeJump::instruction_size;
332     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
333     // This means that the low_boundary is going to be a little too high.
334     // This shouldn't matter, since oops of non-entrant methods are never used.
335     // In fact, why are we bothering to look at oops in a non-entrant method??
336   }
337   return low_boundary;
338 }
339 
340 int CompiledMethod::verify_icholder_relocations() {
341   ResourceMark rm;
342   int count = 0;
343 
344   RelocIterator iter(this);
345   while(iter.next()) {
346     if (iter.type() == relocInfo::virtual_call_type) {
347       if (CompiledIC::is_icholder_call_site(iter.virtual_call_reloc(), this)) {
348         CompiledIC *ic = CompiledIC_at(&iter);
349         if (TraceCompiledIC) {
350           tty->print("noticed icholder " INTPTR_FORMAT " ", p2i(ic->cached_icholder()));
351           ic->print();
352         }
353         assert(ic->cached_icholder() != NULL, "must be non-NULL");
354         count++;
355       }
356     }
357   }
358 
359   return count;
360 }
361 
362 // Method that knows how to preserve outgoing arguments at call. This method must be
363 // called with a frame corresponding to a Java invoke
364 void CompiledMethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) {
365   if (method() != NULL) {
366     // handle the case of an anchor explicitly set in continuation code that doesn't have a callee
367     JavaThread* thread = reg_map->thread();
368     if (thread->has_last_Java_frame() && fr.sp() == thread->last_Java_sp()) {
369       // if (!method()->is_native()) fr.print_on(tty);
370       // assert (method()->is_native(), "");
371       return;
372     }
373 
374     if (!method()->is_native()) {
375       address pc = fr.pc();
376       bool has_receiver, has_appendix;
377       Symbol* signature;
378 
379       // The method attached by JIT-compilers should be used, if present.
380       // Bytecode can be inaccurate in such case.
381       Method* callee = attached_method_before_pc(pc);
382       if (callee != NULL) {
383         has_receiver = !(callee->access_flags().is_static());
384         has_appendix = false;
385         signature    = callee->signature();
386       } else {
387         SimpleScopeDesc ssd(this, pc);
388         if (ssd.is_optimized_linkToNative()) return; // call was replaced
389         Bytecode_invoke call(methodHandle(Thread::current(), ssd.method()), ssd.bci());
390         has_receiver = call.has_receiver();
391         has_appendix = call.has_appendix();
392         signature    = call.signature();
393       }
394 
395       fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f);
396     } else if (method()->is_continuation_enter_intrinsic()) {
397       // This method only calls Continuation.enter()
398       Symbol* signature = vmSymbols::continuationEnter_signature();
399       fr.oops_compiled_arguments_do(signature, false, false, reg_map, f);
400     }
401   }
402 }
403 
404 Method* CompiledMethod::attached_method(address call_instr) {
405   assert(code_contains(call_instr), "not part of the nmethod");
406   RelocIterator iter(this, call_instr, call_instr + 1);
407   while (iter.next()) {
408     if (iter.addr() == call_instr) {
409       switch(iter.type()) {
410         case relocInfo::static_call_type:      return iter.static_call_reloc()->method_value();
411         case relocInfo::opt_virtual_call_type: return iter.opt_virtual_call_reloc()->method_value();
412         case relocInfo::virtual_call_type:     return iter.virtual_call_reloc()->method_value();
413         default:                               break;
414       }
415     }
416   }
417   return NULL; // not found
418 }
419 
420 Method* CompiledMethod::attached_method_before_pc(address pc) {
421   if (NativeCall::is_call_before(pc)) {
422     NativeCall* ncall = nativeCall_before(pc);
423     return attached_method(ncall->instruction_address());
424   }
425   return NULL; // not a call
426 }
427 
428 void CompiledMethod::clear_inline_caches() {
429   assert(SafepointSynchronize::is_at_safepoint(), "cleaning of IC's only allowed at safepoint");
430   if (is_zombie()) {
431     return;
432   }
433 
434   RelocIterator iter(this);
435   while (iter.next()) {
436     iter.reloc()->clear_inline_cache();
437   }
438 }
439 
440 // Clear IC callsites, releasing ICStubs of all compiled ICs
441 // as well as any associated CompiledICHolders.
442 void CompiledMethod::clear_ic_callsites() {
443   assert(CompiledICLocker::is_safe(this), "mt unsafe call");
444   ResourceMark rm;
445   RelocIterator iter(this);
446   while(iter.next()) {
447     if (iter.type() == relocInfo::virtual_call_type) {
448       CompiledIC* ic = CompiledIC_at(&iter);
449       ic->set_to_clean(false);
450     }
451   }
452 }
453 
454 #ifdef ASSERT
455 // Check class_loader is alive for this bit of metadata.
456 class CheckClass : public MetadataClosure {
457   void do_metadata(Metadata* md) {
458     Klass* klass = NULL;
459     if (md->is_klass()) {
460       klass = ((Klass*)md);
461     } else if (md->is_method()) {
462       klass = ((Method*)md)->method_holder();
463     } else if (md->is_methodData()) {
464       klass = ((MethodData*)md)->method()->method_holder();
465     } else {
466       md->print();
467       ShouldNotReachHere();
468     }
469     assert(klass->is_loader_alive(), "must be alive");
470   }
471 };
472 #endif // ASSERT
473 
474 
475 bool CompiledMethod::clean_ic_if_metadata_is_dead(CompiledIC *ic) {
476   if (ic->is_clean()) {
477     return true;
478   }
479   if (ic->is_icholder_call()) {
480     // The only exception is compiledICHolder metdata which may
481     // yet be marked below. (We check this further below).
482     CompiledICHolder* cichk_metdata = ic->cached_icholder();
483 
484     if (cichk_metdata->is_loader_alive()) {
485       return true;
486     }
487   } else {
488     Metadata* ic_metdata = ic->cached_metadata();
489     if (ic_metdata != NULL) {
490       if (ic_metdata->is_klass()) {
491         if (((Klass*)ic_metdata)->is_loader_alive()) {
492           return true;
493         }
494       } else if (ic_metdata->is_method()) {
495         Method* method = (Method*)ic_metdata;
496         assert(!method->is_old(), "old method should have been cleaned");
497         if (method->method_holder()->is_loader_alive()) {
498           return true;
499         }
500       } else {
501         ShouldNotReachHere();
502       }
503     }
504   }
505 
506   return ic->set_to_clean();
507 }
508 
509 // Clean references to unloaded nmethods at addr from this one, which is not unloaded.
510 template <class CompiledICorStaticCall>
511 static bool clean_if_nmethod_is_unloaded(CompiledICorStaticCall *ic, address addr, CompiledMethod* from,
512                                          bool clean_all) {
513   // Ok, to lookup references to zombies here
514   CodeBlob *cb = CodeCache::find_blob_unsafe(addr);
515   CompiledMethod* nm = (cb != NULL) ? cb->as_compiled_method_or_null() : NULL;
516   if (nm != NULL) {
517     // Clean inline caches pointing to both zombie and not_entrant methods
518     if (clean_all || !nm->is_in_use() || nm->is_unloading() || (nm->method()->code() != nm)) {
519       // Inline cache cleaning should only be initiated on CompiledMethods that have been
520       // observed to be is_alive(). However, with concurrent code cache unloading, it is
521       // possible that by now, the state has become !is_alive. This can happen in two ways:
522       // 1) It can be racingly flipped to unloaded if the nmethod // being cleaned (from the
523       // sweeper) is_unloading(). This is fine, because if that happens, then the inline
524       // caches have already been cleaned under the same CompiledICLocker that we now hold during
525       // inline cache cleaning, and we will simply walk the inline caches again, and likely not
526       // find much of interest to clean. However, this race prevents us from asserting that the
527       // nmethod is_alive(). The is_unloading() function is completely monotonic; once set due
528       // to an oop dying, it remains set forever until freed. Because of that, all unloaded
529       // nmethods are is_unloading(), but notably, an unloaded nmethod may also subsequently
530       // become zombie (when the sweeper converts it to zombie).
531       // 2) It can be racingly flipped to zombie if the nmethod being cleaned (by the concurrent
532       // GC) cleans a zombie nmethod that is concurrently made zombie by the sweeper. In this
533       // scenario, the sweeper will first transition the nmethod to zombie, and then when
534       // unregistering from the GC, it will wait until the GC is done. The GC will then clean
535       // the inline caches *with IC stubs*, even though no IC stubs are needed. This is fine,
536       // as long as the IC stubs are guaranteed to be released until the next safepoint, where
537       // IC finalization requires live IC stubs to not be associated with zombie nmethods.
538       // This is guaranteed, because the sweeper does not have a single safepoint check until
539       // after it completes the whole transition function; it will wake up after the GC is
540       // done with concurrent code cache cleaning (which blocks out safepoints using the
541       // suspendible threads set), and then call clear_ic_callsites, which will release the
542       // associated IC stubs, before a subsequent safepoint poll can be reached. This
543       // guarantees that the spuriously created IC stubs are released appropriately before
544       // IC finalization in a safepoint gets to run. Therefore, this race is fine. This is also
545       // valid in a scenario where an inline cache of a zombie nmethod gets a spurious IC stub,
546       // and then when cleaning another inline cache, fails to request an IC stub because we
547       // exhausted the IC stub buffer. In this scenario, the GC will request a safepoint after
548       // yielding the suspendible therad set, effectively unblocking safepoints. Before such
549       // a safepoint can be reached, the sweeper similarly has to wake up, clear the IC stubs,
550       // and reach the next safepoint poll, after the whole transition function has completed.
551       // Due to the various races that can cause an nmethod to first be is_alive() and then
552       // racingly become !is_alive(), it is unfortunately not possible to assert the nmethod
553       // is_alive(), !is_unloaded() or !is_zombie() here.
554       if (!ic->set_to_clean(!from->is_unloading())) {
555         return false;
556       }
557       assert(ic->is_clean(), "nmethod " PTR_FORMAT "not clean %s", p2i(from), from->method()->name_and_sig_as_C_string());
558     }
559   }
560   return true;
561 }
562 
563 static bool clean_if_nmethod_is_unloaded(CompiledIC *ic, CompiledMethod* from,
564                                          bool clean_all) {
565   return clean_if_nmethod_is_unloaded(ic, ic->ic_destination(), from, clean_all);
566 }
567 
568 static bool clean_if_nmethod_is_unloaded(CompiledStaticCall *csc, CompiledMethod* from,
569                                          bool clean_all) {
570   return clean_if_nmethod_is_unloaded(csc, csc->destination(), from, clean_all);
571 }
572 
573 // Cleans caches in nmethods that point to either classes that are unloaded
574 // or nmethods that are unloaded.
575 //
576 // Can be called either in parallel by G1 currently or after all
577 // nmethods are unloaded.  Return postponed=true in the parallel case for
578 // inline caches found that point to nmethods that are not yet visited during
579 // the do_unloading walk.
580 bool CompiledMethod::unload_nmethod_caches(bool unloading_occurred) {
581   ResourceMark rm;
582 
583   // Exception cache only needs to be called if unloading occurred
584   if (unloading_occurred) {
585     clean_exception_cache();
586   }
587 
588   if (!cleanup_inline_caches_impl(unloading_occurred, false)) {
589     return false;
590   }
591 
592 #ifdef ASSERT
593   // Check that the metadata embedded in the nmethod is alive
594   CheckClass check_class;
595   metadata_do(&check_class);
596 #endif
597   return true;
598 }
599 
600 void CompiledMethod::run_nmethod_entry_barrier() {
601   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
602   if (bs_nm != NULL) {
603     // We want to keep an invariant that nmethods found through iterations of a Thread's
604     // nmethods found in safepoints have gone through an entry barrier and are not armed.
605     // By calling this nmethod entry barrier, it plays along and acts
606     // like any other nmethod found on the stack of a thread (fewer surprises).
607     nmethod* nm = as_nmethod_or_null();
608     if (nm != NULL && bs_nm->is_armed(nm)) {
609       bool alive = bs_nm->nmethod_entry_barrier(nm);
610       assert(alive, "should be alive");
611     }
612   }
613 }
614 
615 void CompiledMethod::cleanup_inline_caches(bool clean_all) {
616   for (;;) {
617     ICRefillVerifier ic_refill_verifier;
618     { CompiledICLocker ic_locker(this);
619       if (cleanup_inline_caches_impl(false, clean_all)) {
620         return;
621       }
622     }
623     // Call this nmethod entry barrier from the sweeper.
624     run_nmethod_entry_barrier();
625     InlineCacheBuffer::refill_ic_stubs();
626   }
627 }
628 
629 address* CompiledMethod::orig_pc_addr(const frame* fr) {
630   return (address*) ((address)fr->unextended_sp() + orig_pc_offset());
631 }
632 
633 // Called to clean up after class unloading for live nmethods and from the sweeper
634 // for all methods.
635 bool CompiledMethod::cleanup_inline_caches_impl(bool unloading_occurred, bool clean_all) {
636   assert(CompiledICLocker::is_safe(this), "mt unsafe call");
637   ResourceMark rm;
638 
639   // Find all calls in an nmethod and clear the ones that point to non-entrant,
640   // zombie and unloaded nmethods.
641   RelocIterator iter(this, oops_reloc_begin());
642   bool is_in_static_stub = false;
643   while(iter.next()) {
644 
645     switch (iter.type()) {
646 
647     case relocInfo::virtual_call_type:
648       if (unloading_occurred) {
649         // If class unloading occurred we first clear ICs where the cached metadata
650         // is referring to an unloaded klass or method.
651         if (!clean_ic_if_metadata_is_dead(CompiledIC_at(&iter))) {
652           return false;
653         }
654       }
655 
656       if (!clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), this, clean_all)) {
657         return false;
658       }
659       break;
660 
661     case relocInfo::opt_virtual_call_type:
662       if (!clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), this, clean_all)) {
663         return false;
664       }
665       break;
666 
667     case relocInfo::static_call_type:
668       if (!clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), this, clean_all)) {
669         return false;
670       }
671       break;
672 
673     case relocInfo::static_stub_type: {
674       is_in_static_stub = true;
675       break;
676     }
677 
678     case relocInfo::metadata_type: {
679       // Only the metadata relocations contained in static/opt virtual call stubs
680       // contains the Method* passed to c2i adapters. It is the only metadata
681       // relocation that needs to be walked, as it is the one metadata relocation
682       // that violates the invariant that all metadata relocations have an oop
683       // in the compiled method (due to deferred resolution and code patching).
684 
685       // This causes dead metadata to remain in compiled methods that are not
686       // unloading. Unless these slippery metadata relocations of the static
687       // stubs are at least cleared, subsequent class redefinition operations
688       // will access potentially free memory, and JavaThread execution
689       // concurrent to class unloading may call c2i adapters with dead methods.
690       if (!is_in_static_stub) {
691         // The first metadata relocation after a static stub relocation is the
692         // metadata relocation of the static stub used to pass the Method* to
693         // c2i adapters.
694         continue;
695       }
696       is_in_static_stub = false;
697       if (is_unloading()) {
698         // If the nmethod itself is dying, then it may point at dead metadata.
699         // Nobody should follow that metadata; it is strictly unsafe.
700         continue;
701       }
702       metadata_Relocation* r = iter.metadata_reloc();
703       Metadata* md = r->metadata_value();
704       if (md != NULL && md->is_method()) {
705         Method* method = static_cast<Method*>(md);
706         if (!method->method_holder()->is_loader_alive()) {
707           Atomic::store(r->metadata_addr(), (Method*)NULL);
708 
709           if (!r->metadata_is_immediate()) {
710             r->fix_metadata_relocation();
711           }
712         }
713       }
714       break;
715     }
716 
717     default:
718       break;
719     }
720   }
721 
722   return true;
723 }
724 
725 address CompiledMethod::continuation_for_implicit_exception(address pc, bool for_div0_check) {
726   // Exception happened outside inline-cache check code => we are inside
727   // an active nmethod => use cpc to determine a return address
728   int exception_offset = pc - code_begin();
729   int cont_offset = ImplicitExceptionTable(this).continuation_offset( exception_offset );
730 #ifdef ASSERT
731   if (cont_offset == 0) {
732     Thread* thread = Thread::current();
733     ResourceMark rm(thread);
734     CodeBlob* cb = CodeCache::find_blob(pc);
735     assert(cb != NULL && cb == this, "");
736     ttyLocker ttyl;
737     tty->print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc));
738     print();
739     method()->print_codes();
740     print_code();
741     print_pcs();
742   }
743 #endif
744   if (cont_offset == 0) {
745     // Let the normal error handling report the exception
746     return NULL;
747   }
748   if (cont_offset == exception_offset) {
749 #if INCLUDE_JVMCI
750     Deoptimization::DeoptReason deopt_reason = for_div0_check ? Deoptimization::Reason_div0_check : Deoptimization::Reason_null_check;
751     JavaThread *thread = JavaThread::current();
752     thread->set_jvmci_implicit_exception_pc(pc);
753     thread->set_pending_deoptimization(Deoptimization::make_trap_request(deopt_reason,
754                                                                          Deoptimization::Action_reinterpret));
755     return (SharedRuntime::deopt_blob()->implicit_exception_uncommon_trap());
756 #else
757     ShouldNotReachHere();
758 #endif
759   }
760   return code_begin() + cont_offset;
761 }
762 
763 class HasEvolDependency : public MetadataClosure {
764   bool _has_evol_dependency;
765  public:
766   HasEvolDependency() : _has_evol_dependency(false) {}
767   void do_metadata(Metadata* md) {
768     if (md->is_method()) {
769       Method* method = (Method*)md;
770       if (method->is_old()) {
771         _has_evol_dependency = true;
772       }
773     }
774   }
775   bool has_evol_dependency() const { return _has_evol_dependency; }
776 };
777 
778 bool CompiledMethod::has_evol_metadata() {
779   // Check the metadata in relocIter and CompiledIC and also deoptimize
780   // any nmethod that has reference to old methods.
781   HasEvolDependency check_evol;
782   metadata_do(&check_evol);
783   if (check_evol.has_evol_dependency() && log_is_enabled(Debug, redefine, class, nmethod)) {
784     ResourceMark rm;
785     log_debug(redefine, class, nmethod)
786             ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on in nmethod metadata",
787              _method->method_holder()->external_name(),
788              _method->name()->as_C_string(),
789              _method->signature()->as_C_string(),
790              compile_id());
791   }
792   return check_evol.has_evol_dependency();
793 }