1 /*
   2  * Copyright (c) 2018, 2025, 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 "classfile/javaClasses.inline.hpp"
  26 #include "classfile/vmSymbols.hpp"
  27 #include "code/codeCache.inline.hpp"
  28 #include "code/nmethod.inline.hpp"
  29 #include "code/vmreg.inline.hpp"
  30 #include "compiler/oopMap.inline.hpp"
  31 #include "gc/shared/continuationGCSupport.inline.hpp"
  32 #include "gc/shared/gc_globals.hpp"
  33 #include "gc/shared/barrierSet.hpp"
  34 #include "gc/shared/memAllocator.hpp"
  35 #include "gc/shared/threadLocalAllocBuffer.inline.hpp"
  36 #include "interpreter/interpreter.hpp"
  37 #include "jfr/jfrEvents.hpp"
  38 #include "logging/log.hpp"
  39 #include "logging/logStream.hpp"
  40 #include "oops/access.inline.hpp"
  41 #include "oops/method.inline.hpp"
  42 #include "oops/oopsHierarchy.hpp"
  43 #include "oops/objArrayOop.inline.hpp"
  44 #include "oops/stackChunkOop.inline.hpp"
  45 #include "prims/jvmtiThreadState.hpp"
  46 #include "runtime/arguments.hpp"
  47 #include "runtime/continuation.hpp"
  48 #include "runtime/continuationEntry.inline.hpp"
  49 #include "runtime/continuationHelper.inline.hpp"
  50 #include "runtime/continuationJavaClasses.inline.hpp"
  51 #include "runtime/continuationWrapper.inline.hpp"
  52 #include "runtime/frame.inline.hpp"
  53 #include "runtime/interfaceSupport.inline.hpp"
  54 #include "runtime/javaThread.inline.hpp"
  55 #include "runtime/jniHandles.inline.hpp"
  56 #include "runtime/keepStackGCProcessed.hpp"
  57 #include "runtime/objectMonitor.inline.hpp"
  58 #include "runtime/orderAccess.hpp"
  59 #include "runtime/prefetch.inline.hpp"
  60 #include "runtime/smallRegisterMap.inline.hpp"
  61 #include "runtime/sharedRuntime.hpp"
  62 #include "runtime/stackChunkFrameStream.inline.hpp"
  63 #include "runtime/stackFrameStream.inline.hpp"
  64 #include "runtime/stackOverflow.hpp"
  65 #include "runtime/stackWatermarkSet.inline.hpp"
  66 #include "utilities/debug.hpp"
  67 #include "utilities/exceptions.hpp"
  68 #include "utilities/macros.hpp"
  69 #include "utilities/vmError.hpp"
  70 #if INCLUDE_ZGC
  71 #include "gc/z/zStackChunkGCData.inline.hpp"
  72 #endif
  73 #if INCLUDE_JFR
  74 #include "jfr/jfr.inline.hpp"
  75 #endif
  76 
  77 #include <type_traits>
  78 
  79 /*
  80  * This file contains the implementation of continuation freezing (yield) and thawing (run).
  81  *
  82  * This code is very latency-critical and very hot. An ordinary and well-behaved server application
  83  * would likely call these operations many thousands of times per second second, on every core.
  84  *
  85  * Freeze might be called every time the application performs any I/O operation, every time it
  86  * acquires a j.u.c. lock, every time it takes a message from a queue, and thaw can be called
  87  * multiple times in each of those cases, as it is called by the return barrier, which may be
  88  * invoked on method return.
  89  *
  90  * The amortized budget for each of those two operations is ~100-150ns. That is why, for
  91  * example, every effort is made to avoid Java-VM transitions as much as possible.
  92  *
  93  * On the fast path, all frames are known to be compiled, and the chunk requires no barriers
  94  * and so frames simply copied, and the bottom-most one is patched.
  95  * On the slow path, internal pointers in interpreted frames are de/relativized to/from offsets
  96  * and absolute pointers, and barriers invoked.
  97  */
  98 
  99 /************************************************
 100 
 101 Thread-stack layout on freeze/thaw.
 102 See corresponding stack-chunk layout in instanceStackChunkKlass.hpp
 103 
 104             +----------------------------+
 105             |      .                     |
 106             |      .                     |
 107             |      .                     |
 108             |   carrier frames           |
 109             |                            |
 110             |----------------------------|
 111             |                            |
 112             |    Continuation.run        |
 113             |                            |
 114             |============================|
 115             |    enterSpecial frame      |
 116             |  pc                        |
 117             |  rbp                       |
 118             |  -----                     |
 119         ^   |  int argsize               | = ContinuationEntry
 120         |   |  oopDesc* cont             |
 121         |   |  oopDesc* chunk            |
 122         |   |  ContinuationEntry* parent |
 123         |   |  ...                       |
 124         |   |============================| <------ JavaThread::_cont_entry = entry->sp()
 125         |   |  ? alignment word ?        |
 126         |   |----------------------------| <--\
 127         |   |                            |    |
 128         |   |  ? caller stack args ?     |    |   argsize (might not be 2-word aligned) words
 129 Address |   |                            |    |   Caller is still in the chunk.
 130         |   |----------------------------|    |
 131         |   |  pc (? return barrier ?)   |    |  This pc contains the return barrier when the bottom-most frame
 132         |   |  rbp                       |    |  isn't the last one in the continuation.
 133         |   |                            |    |
 134         |   |    frame                   |    |
 135         |   |                            |    |
 136             +----------------------------|     \__ Continuation frames to be frozen/thawed
 137             |                            |     /
 138             |    frame                   |    |
 139             |                            |    |
 140             |----------------------------|    |
 141             |                            |    |
 142             |    frame                   |    |
 143             |                            |    |
 144             |----------------------------| <--/
 145             |                            |
 146             |    doYield/safepoint stub  | When preempting forcefully, we could have a safepoint stub
 147             |                            | instead of a doYield stub
 148             |============================| <- the sp passed to freeze
 149             |                            |
 150             |  Native freeze/thaw frames |
 151             |      .                     |
 152             |      .                     |
 153             |      .                     |
 154             +----------------------------+
 155 
 156 ************************************************/
 157 
 158 static const bool TEST_THAW_ONE_CHUNK_FRAME = false; // force thawing frames one-at-a-time for testing
 159 
 160 #define CONT_JFR false // emit low-level JFR events that count slow/fast path for continuation performance debugging only
 161 #if CONT_JFR
 162   #define CONT_JFR_ONLY(code) code
 163 #else
 164   #define CONT_JFR_ONLY(code)
 165 #endif
 166 
 167 // TODO: See AbstractAssembler::generate_stack_overflow_check,
 168 // Compile::bang_size_in_bytes(), m->as_SafePoint()->jvms()->interpreter_frame_size()
 169 // when we stack-bang, we need to update a thread field with the lowest (farthest) bang point.
 170 
 171 // Data invariants are defined by Continuation::debug_verify_continuation and Continuation::debug_verify_stack_chunk
 172 
 173 // Used to just annotatate cold/hot branches
 174 #define LIKELY(condition)   (condition)
 175 #define UNLIKELY(condition) (condition)
 176 
 177 // debugging functions
 178 #ifdef ASSERT
 179 extern "C" bool dbg_is_safe(const void* p, intptr_t errvalue); // address p is readable and *(intptr_t*)p != errvalue
 180 
 181 static void verify_continuation(oop continuation) { Continuation::debug_verify_continuation(continuation); }
 182 
 183 static void do_deopt_after_thaw(JavaThread* thread);
 184 static bool do_verify_after_thaw(JavaThread* thread, stackChunkOop chunk, outputStream* st);
 185 static void log_frames(JavaThread* thread);
 186 static void log_frames_after_thaw(JavaThread* thread, ContinuationWrapper& cont, intptr_t* sp, bool preempted);
 187 static void print_frame_layout(const frame& f, bool callee_complete, outputStream* st = tty);
 188 
 189 #define assert_pfl(p, ...) \
 190 do {                                           \
 191   if (!(p)) {                                  \
 192     JavaThread* t = JavaThread::active();      \
 193     if (t->has_last_Java_frame()) {            \
 194       tty->print_cr("assert(" #p ") failed:"); \
 195       t->print_frame_layout();                 \
 196     }                                          \
 197   }                                            \
 198   vmassert(p, __VA_ARGS__);                    \
 199 } while(0)
 200 
 201 #else
 202 static void verify_continuation(oop continuation) { }
 203 #define assert_pfl(p, ...)
 204 #endif
 205 
 206 static freeze_result is_pinned0(JavaThread* thread, oop cont_scope, bool safepoint);
 207 template<typename ConfigT, bool preempt> static inline freeze_result freeze_internal(JavaThread* current, intptr_t* const sp);
 208 
 209 static inline int prepare_thaw_internal(JavaThread* thread, bool return_barrier);
 210 template<typename ConfigT> static inline intptr_t* thaw_internal(JavaThread* thread, const Continuation::thaw_kind kind);
 211 
 212 
 213 // Entry point to freeze. Transitions are handled manually
 214 // Called from gen_continuation_yield() in sharedRuntime_<cpu>.cpp through Continuation::freeze_entry();
 215 template<typename ConfigT>
 216 static JRT_BLOCK_ENTRY(int, freeze(JavaThread* current, intptr_t* sp))
 217   assert(sp == current->frame_anchor()->last_Java_sp(), "");
 218 
 219   if (current->raw_cont_fastpath() > current->last_continuation()->entry_sp() || current->raw_cont_fastpath() < sp) {
 220     current->set_cont_fastpath(nullptr);
 221   }
 222 
 223   return checked_cast<int>(ConfigT::freeze(current, sp));
 224 JRT_END
 225 
 226 JRT_LEAF(int, Continuation::prepare_thaw(JavaThread* thread, bool return_barrier))
 227   return prepare_thaw_internal(thread, return_barrier);
 228 JRT_END
 229 
 230 template<typename ConfigT>
 231 static JRT_LEAF(intptr_t*, thaw(JavaThread* thread, int kind))
 232   // TODO: JRT_LEAF and NoHandleMark is problematic for JFR events.
 233   // vFrameStreamCommon allocates Handles in RegisterMap for continuations.
 234   // Also the preemption case with JVMTI events enabled might safepoint so
 235   // undo the NoSafepointVerifier here and rely on handling by ContinuationWrapper.
 236   // JRT_ENTRY instead?
 237   ResetNoHandleMark rnhm;
 238   DEBUG_ONLY(PauseNoSafepointVerifier pnsv(&__nsv);)
 239 
 240   // we might modify the code cache via BarrierSetNMethod::nmethod_entry_barrier
 241   MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, thread));
 242   return ConfigT::thaw(thread, (Continuation::thaw_kind)kind);
 243 JRT_END
 244 
 245 JVM_ENTRY(jint, CONT_isPinned0(JNIEnv* env, jobject cont_scope)) {
 246   JavaThread* thread = JavaThread::thread_from_jni_environment(env);
 247   return is_pinned0(thread, JNIHandles::resolve(cont_scope), false);
 248 }
 249 JVM_END
 250 
 251 ///////////
 252 
 253 enum class oop_kind { NARROW, WIDE };
 254 template <oop_kind oops, typename BarrierSetT>
 255 class Config {
 256 public:
 257   typedef Config<oops, BarrierSetT> SelfT;
 258   using OopT = std::conditional_t<oops == oop_kind::NARROW, narrowOop, oop>;
 259 
 260   static freeze_result freeze(JavaThread* thread, intptr_t* const sp) {
 261     freeze_result res = freeze_internal<SelfT, false>(thread, sp);
 262     JFR_ONLY(assert((res == freeze_ok) || (res == thread->last_freeze_fail_result()), "freeze failure not set"));
 263     return res;
 264   }
 265 
 266   static freeze_result freeze_preempt(JavaThread* thread, intptr_t* const sp) {
 267     return freeze_internal<SelfT, true>(thread, sp);
 268   }
 269 
 270   static intptr_t* thaw(JavaThread* thread, Continuation::thaw_kind kind) {
 271     return thaw_internal<SelfT>(thread, kind);
 272   }
 273 };
 274 
 275 #ifdef _WINDOWS
 276 static void map_stack_pages(JavaThread* thread, size_t size, address sp) {
 277   address new_sp = sp - size;
 278   address watermark = thread->stack_overflow_state()->shadow_zone_growth_watermark();
 279 
 280   if (new_sp < watermark) {
 281     size_t page_size = os::vm_page_size();
 282     address last_touched_page = watermark - StackOverflow::stack_shadow_zone_size();
 283     size_t pages_to_touch = align_up(watermark - new_sp, page_size) / page_size;
 284     while (pages_to_touch-- > 0) {
 285       last_touched_page -= page_size;
 286       *last_touched_page = 0;
 287     }
 288     thread->stack_overflow_state()->set_shadow_zone_growth_watermark(new_sp);
 289   }
 290 }
 291 #endif
 292 
 293 static bool stack_overflow_check(JavaThread* thread, size_t size, address sp) {
 294   const size_t page_size = os::vm_page_size();
 295   if (size > page_size) {
 296     if (sp - size < thread->stack_overflow_state()->shadow_zone_safe_limit()) {
 297       return false;
 298     }
 299     WINDOWS_ONLY(map_stack_pages(thread, size, sp));
 300   }
 301   return true;
 302 }
 303 
 304 #ifdef ASSERT
 305 static oop get_continuation(JavaThread* thread) {
 306   assert(thread != nullptr, "");
 307   assert(thread->threadObj() != nullptr, "");
 308   return java_lang_Thread::continuation(thread->threadObj());
 309 }
 310 #endif // ASSERT
 311 
 312 inline void clear_anchor(JavaThread* thread) {
 313   thread->frame_anchor()->clear();
 314 }
 315 
 316 static void set_anchor(JavaThread* thread, intptr_t* sp, address pc) {
 317   assert(pc != nullptr, "");
 318 
 319   JavaFrameAnchor* anchor = thread->frame_anchor();
 320   anchor->set_last_Java_sp(sp);
 321   anchor->set_last_Java_pc(pc);
 322   ContinuationHelper::set_anchor_pd(anchor, sp);
 323 
 324   assert(thread->has_last_Java_frame(), "");
 325   assert(thread->last_frame().cb() != nullptr, "");
 326 }
 327 
 328 static void set_anchor(JavaThread* thread, intptr_t* sp) {
 329   address pc = ContinuationHelper::return_address_at(
 330            sp - frame::sender_sp_ret_address_offset());
 331   set_anchor(thread, sp, pc);
 332 }
 333 
 334 static void set_anchor_to_entry(JavaThread* thread, ContinuationEntry* entry) {
 335   JavaFrameAnchor* anchor = thread->frame_anchor();
 336   anchor->set_last_Java_sp(entry->entry_sp());
 337   anchor->set_last_Java_pc(entry->entry_pc());
 338   ContinuationHelper::set_anchor_to_entry_pd(anchor, entry);
 339 
 340   assert(thread->has_last_Java_frame(), "");
 341   assert(thread->last_frame().cb() != nullptr, "");
 342 }
 343 
 344 #if CONT_JFR
 345 class FreezeThawJfrInfo : public StackObj {
 346   short _e_size;
 347   short _e_num_interpreted_frames;
 348  public:
 349 
 350   FreezeThawJfrInfo() : _e_size(0), _e_num_interpreted_frames(0) {}
 351   inline void record_interpreted_frame() { _e_num_interpreted_frames++; }
 352   inline void record_size_copied(int size) { _e_size += size << LogBytesPerWord; }
 353   template<typename Event> void post_jfr_event(Event *e, oop continuation, JavaThread* jt);
 354 };
 355 
 356 template<typename Event> void FreezeThawJfrInfo::post_jfr_event(Event* e, oop continuation, JavaThread* jt) {
 357   if (e->should_commit()) {
 358     log_develop_trace(continuations)("JFR event: iframes: %d size: %d", _e_num_interpreted_frames, _e_size);
 359     e->set_carrierThread(JFR_JVM_THREAD_ID(jt));
 360     e->set_continuationClass(continuation->klass());
 361     e->set_interpretedFrames(_e_num_interpreted_frames);
 362     e->set_size(_e_size);
 363     e->commit();
 364   }
 365 }
 366 #endif // CONT_JFR
 367 
 368 /////////////// FREEZE ////
 369 
 370 class FreezeBase : public StackObj {
 371 protected:
 372   JavaThread* const _thread;
 373   ContinuationWrapper& _cont;
 374   bool _barriers; // only set when we allocate a chunk
 375 
 376   intptr_t* _bottom_address;
 377 
 378   // Used for preemption only
 379   const bool _preempt;
 380   frame _last_frame;
 381 
 382   // Used to support freezing with held monitors
 383   int _monitors_in_lockstack;
 384 
 385   int _freeze_size; // total size of all frames plus metadata in words.
 386   int _total_align_size;
 387 
 388   intptr_t* _cont_stack_top;
 389   intptr_t* _cont_stack_bottom;
 390 
 391   CONT_JFR_ONLY(FreezeThawJfrInfo _jfr_info;)
 392 
 393 #ifdef ASSERT
 394   intptr_t* _orig_chunk_sp;
 395   int _fast_freeze_size;
 396   bool _empty;
 397 #endif
 398 
 399   JvmtiSampledObjectAllocEventCollector* _jvmti_event_collector;
 400 
 401   NOT_PRODUCT(int _frames;)
 402   DEBUG_ONLY(intptr_t* _last_write;)
 403 
 404   inline FreezeBase(JavaThread* thread, ContinuationWrapper& cont, intptr_t* sp, bool preempt);
 405 
 406 public:
 407   NOINLINE freeze_result freeze_slow();
 408   void freeze_fast_existing_chunk();
 409 
 410   CONT_JFR_ONLY(FreezeThawJfrInfo& jfr_info() { return _jfr_info; })
 411   void set_jvmti_event_collector(JvmtiSampledObjectAllocEventCollector* jsoaec) { _jvmti_event_collector = jsoaec; }
 412 
 413   inline int size_if_fast_freeze_available();
 414 
 415   inline frame& last_frame() { return _last_frame; }
 416 
 417 #ifdef ASSERT
 418   bool check_valid_fast_path();
 419 #endif
 420 
 421 protected:
 422   inline void init_rest();
 423   void throw_stack_overflow_on_humongous_chunk();
 424 
 425   // fast path
 426   inline void copy_to_chunk(intptr_t* from, intptr_t* to, int size);
 427   inline void unwind_frames();
 428   inline void patch_stack_pd(intptr_t* frame_sp, intptr_t* heap_sp);
 429 
 430   // slow path
 431   virtual stackChunkOop allocate_chunk_slow(size_t stack_size, int argsize_md) = 0;
 432 
 433   int cont_size() { return pointer_delta_as_int(_cont_stack_bottom, _cont_stack_top); }
 434 
 435 private:
 436   // slow path
 437   frame freeze_start_frame();
 438   frame freeze_start_frame_on_preempt();
 439   NOINLINE freeze_result recurse_freeze(frame& f, frame& caller, int callee_argsize, bool callee_interpreted, bool top);
 440   inline frame freeze_start_frame_yield_stub();
 441   template<typename FKind>
 442   inline freeze_result recurse_freeze_java_frame(const frame& f, frame& caller, int fsize, int argsize);
 443   inline void before_freeze_java_frame(const frame& f, const frame& caller, int fsize, int argsize, bool is_bottom_frame);
 444   inline void after_freeze_java_frame(const frame& hf, bool is_bottom_frame);
 445   freeze_result finalize_freeze(const frame& callee, frame& caller, int argsize);
 446   void patch(const frame& f, frame& hf, const frame& caller, bool is_bottom_frame);
 447   NOINLINE freeze_result recurse_freeze_interpreted_frame(frame& f, frame& caller, int callee_argsize, bool callee_interpreted);
 448   freeze_result recurse_freeze_compiled_frame(frame& f, frame& caller, int callee_argsize, bool callee_interpreted);
 449   NOINLINE freeze_result recurse_freeze_stub_frame(frame& f, frame& caller);
 450   NOINLINE freeze_result recurse_freeze_native_frame(frame& f, frame& caller);
 451   NOINLINE void finish_freeze(const frame& f, const frame& top);
 452 
 453   void freeze_lockstack(stackChunkOop chunk);
 454 
 455   inline bool stack_overflow();
 456 
 457   static frame sender(const frame& f) { return f.is_interpreted_frame() ? sender<ContinuationHelper::InterpretedFrame>(f)
 458                                                                         : sender<ContinuationHelper::NonInterpretedUnknownFrame>(f); }
 459   template<typename FKind> static inline frame sender(const frame& f);
 460   template<typename FKind> frame new_heap_frame(frame& f, frame& caller, int size_adjust = 0);
 461   inline void set_top_frame_metadata_pd(const frame& hf);
 462   inline void patch_pd(frame& callee, const frame& caller, bool is_bottom_frame);
 463   void adjust_interpreted_frame_unextended_sp(frame& f);
 464   static inline void prepare_freeze_interpreted_top_frame(frame& f);
 465   static inline void relativize_interpreted_frame_metadata(const frame& f, const frame& hf);
 466 
 467 protected:
 468   void freeze_fast_copy(stackChunkOop chunk, int chunk_start_sp CONT_JFR_ONLY(COMMA bool chunk_is_allocated));
 469   bool freeze_fast_new_chunk(stackChunkOop chunk);
 470 };
 471 
 472 template <typename ConfigT>
 473 class Freeze : public FreezeBase {
 474 private:
 475   stackChunkOop allocate_chunk(size_t stack_size, int argsize_md);
 476 
 477 public:
 478   inline Freeze(JavaThread* thread, ContinuationWrapper& cont, intptr_t* frame_sp, bool preempt)
 479     : FreezeBase(thread, cont, frame_sp, preempt) {}
 480 
 481   freeze_result try_freeze_fast();
 482 
 483 protected:
 484   virtual stackChunkOop allocate_chunk_slow(size_t stack_size, int argsize_md) override { return allocate_chunk(stack_size, argsize_md); }
 485 };
 486 
 487 FreezeBase::FreezeBase(JavaThread* thread, ContinuationWrapper& cont, intptr_t* frame_sp, bool preempt) :
 488     _thread(thread), _cont(cont), _barriers(false), _preempt(preempt), _last_frame(false /* no initialization */) {
 489   DEBUG_ONLY(_jvmti_event_collector = nullptr;)
 490 
 491   assert(_thread != nullptr, "");
 492   assert(_thread->last_continuation()->entry_sp() == _cont.entrySP(), "");
 493 
 494   DEBUG_ONLY(_cont.entry()->verify_cookie();)
 495 
 496   assert(!Interpreter::contains(_cont.entryPC()), "");
 497 
 498   _bottom_address = _cont.entrySP() - _cont.entry_frame_extension();
 499 #ifdef _LP64
 500   if (((intptr_t)_bottom_address & 0xf) != 0) {
 501     _bottom_address--;
 502   }
 503   assert(is_aligned(_bottom_address, frame::frame_alignment), "");
 504 #endif
 505 
 506   log_develop_trace(continuations)("bottom_address: " INTPTR_FORMAT " entrySP: " INTPTR_FORMAT " argsize: " PTR_FORMAT,
 507                 p2i(_bottom_address), p2i(_cont.entrySP()), (_cont.entrySP() - _bottom_address) << LogBytesPerWord);
 508   assert(_bottom_address != nullptr, "");
 509   assert(_bottom_address <= _cont.entrySP(), "");
 510   DEBUG_ONLY(_last_write = nullptr;)
 511 
 512   assert(_cont.chunk_invariant(), "");
 513   assert(!Interpreter::contains(_cont.entryPC()), "");
 514 #if !defined(PPC64) || defined(ZERO)
 515   static const int doYield_stub_frame_size = frame::metadata_words;
 516 #else
 517   static const int doYield_stub_frame_size = frame::native_abi_reg_args_size >> LogBytesPerWord;
 518 #endif
 519   // With preemption doYield() might not have been resolved yet
 520   assert(_preempt || SharedRuntime::cont_doYield_stub()->frame_size() == doYield_stub_frame_size, "");
 521 
 522   if (preempt) {
 523     _last_frame = _thread->last_frame();
 524   }
 525 
 526   // properties of the continuation on the stack; all sizes are in words
 527   _cont_stack_top    = frame_sp + (!preempt ? doYield_stub_frame_size : 0); // we don't freeze the doYield stub frame
 528   _cont_stack_bottom = _cont.entrySP() + (_cont.argsize() == 0 ? frame::metadata_words_at_top : 0)
 529       - ContinuationHelper::frame_align_words(_cont.argsize()); // see alignment in thaw
 530 
 531   log_develop_trace(continuations)("freeze size: %d argsize: %d top: " INTPTR_FORMAT " bottom: " INTPTR_FORMAT,
 532     cont_size(), _cont.argsize(), p2i(_cont_stack_top), p2i(_cont_stack_bottom));
 533   assert(cont_size() > 0, "");
 534 
 535   if (LockingMode != LM_LIGHTWEIGHT) {
 536     _monitors_in_lockstack = 0;
 537   } else {
 538     _monitors_in_lockstack = _thread->lock_stack().monitor_count();
 539   }
 540 }
 541 
 542 void FreezeBase::init_rest() { // we want to postpone some initialization after chunk handling
 543   _freeze_size = 0;
 544   _total_align_size = 0;
 545   NOT_PRODUCT(_frames = 0;)
 546 }
 547 
 548 void FreezeBase::freeze_lockstack(stackChunkOop chunk) {
 549   assert(chunk->sp_address() - chunk->start_address() >= _monitors_in_lockstack, "no room for lockstack");
 550 
 551   _thread->lock_stack().move_to_address((oop*)chunk->start_address());
 552   chunk->set_lockstack_size(checked_cast<uint8_t>(_monitors_in_lockstack));
 553   chunk->set_has_lockstack(true);
 554 }
 555 
 556 void FreezeBase::copy_to_chunk(intptr_t* from, intptr_t* to, int size) {
 557   stackChunkOop chunk = _cont.tail();
 558   chunk->copy_from_stack_to_chunk(from, to, size);
 559   CONT_JFR_ONLY(_jfr_info.record_size_copied(size);)
 560 
 561 #ifdef ASSERT
 562   if (_last_write != nullptr) {
 563     assert(_last_write == to + size, "Missed a spot: _last_write: " INTPTR_FORMAT " to+size: " INTPTR_FORMAT
 564         " stack_size: %d _last_write offset: " PTR_FORMAT " to+size: " PTR_FORMAT, p2i(_last_write), p2i(to+size),
 565         chunk->stack_size(), _last_write-chunk->start_address(), to+size-chunk->start_address());
 566     _last_write = to;
 567   }
 568 #endif
 569 }
 570 
 571 static void assert_frames_in_continuation_are_safe(JavaThread* thread) {
 572 #ifdef ASSERT
 573   StackWatermark* watermark = StackWatermarkSet::get(thread, StackWatermarkKind::gc);
 574   if (watermark == nullptr) {
 575     return;
 576   }
 577   ContinuationEntry* ce = thread->last_continuation();
 578   RegisterMap map(thread,
 579                   RegisterMap::UpdateMap::include,
 580                   RegisterMap::ProcessFrames::skip,
 581                   RegisterMap::WalkContinuation::skip);
 582   map.set_include_argument_oops(false);
 583   for (frame f = thread->last_frame(); Continuation::is_frame_in_continuation(ce, f); f = f.sender(&map)) {
 584     watermark->assert_is_frame_safe(f);
 585   }
 586 #endif // ASSERT
 587 }
 588 
 589 #ifdef ASSERT
 590 static bool monitors_on_stack(JavaThread* thread) {
 591   assert_frames_in_continuation_are_safe(thread);
 592   ContinuationEntry* ce = thread->last_continuation();
 593   RegisterMap map(thread,
 594                   RegisterMap::UpdateMap::include,
 595                   RegisterMap::ProcessFrames::skip,
 596                   RegisterMap::WalkContinuation::skip);
 597   map.set_include_argument_oops(false);
 598   for (frame f = thread->last_frame(); Continuation::is_frame_in_continuation(ce, f); f = f.sender(&map)) {
 599     if ((f.is_interpreted_frame() && ContinuationHelper::InterpretedFrame::is_owning_locks(f)) ||
 600         (f.is_compiled_frame() && ContinuationHelper::CompiledFrame::is_owning_locks(map.thread(), &map, f)) ||
 601         (f.is_native_frame() && ContinuationHelper::NativeFrame::is_owning_locks(map.thread(), f))) {
 602       return true;
 603     }
 604   }
 605   return false;
 606 }
 607 #endif // ASSERT
 608 
 609 // Called _after_ the last possible safepoint during the freeze operation (chunk allocation)
 610 void FreezeBase::unwind_frames() {
 611   ContinuationEntry* entry = _cont.entry();
 612   entry->flush_stack_processing(_thread);
 613   assert_frames_in_continuation_are_safe(_thread);
 614   JFR_ONLY(Jfr::check_and_process_sample_request(_thread);)
 615   assert(LockingMode != LM_LEGACY || !monitors_on_stack(_thread), "unexpected monitors on stack");
 616   set_anchor_to_entry(_thread, entry);
 617 }
 618 
 619 template <typename ConfigT>
 620 freeze_result Freeze<ConfigT>::try_freeze_fast() {
 621   assert(_thread->thread_state() == _thread_in_vm, "");
 622   assert(_thread->cont_fastpath(), "");
 623 
 624   DEBUG_ONLY(_fast_freeze_size = size_if_fast_freeze_available();)
 625   assert(_fast_freeze_size == 0, "");
 626 
 627   stackChunkOop chunk = allocate_chunk(cont_size() + frame::metadata_words + _monitors_in_lockstack, _cont.argsize() + frame::metadata_words_at_top);
 628   if (freeze_fast_new_chunk(chunk)) {
 629     return freeze_ok;
 630   }
 631   if (_thread->has_pending_exception()) {
 632     return freeze_exception;
 633   }
 634 
 635   // TODO R REMOVE when deopt change is fixed
 636   assert(!_thread->cont_fastpath() || _barriers, "");
 637   log_develop_trace(continuations)("-- RETRYING SLOW --");
 638   return freeze_slow();
 639 }
 640 
 641 // Returns size needed if the continuation fits, otherwise 0.
 642 int FreezeBase::size_if_fast_freeze_available() {
 643   stackChunkOop chunk = _cont.tail();
 644   if (chunk == nullptr || chunk->is_gc_mode() || chunk->requires_barriers() || chunk->has_mixed_frames()) {
 645     log_develop_trace(continuations)("chunk available %s", chunk == nullptr ? "no chunk" : "chunk requires barriers");
 646     return 0;
 647   }
 648 
 649   int total_size_needed = cont_size();
 650   const int chunk_sp = chunk->sp();
 651 
 652   // argsize can be nonzero if we have a caller, but the caller could be in a non-empty parent chunk,
 653   // so we subtract it only if we overlap with the caller, i.e. the current chunk isn't empty.
 654   // Consider leaving the chunk's argsize set when emptying it and removing the following branch,
 655   // although that would require changing stackChunkOopDesc::is_empty
 656   if (!chunk->is_empty()) {
 657     total_size_needed -= _cont.argsize() + frame::metadata_words_at_top;
 658   }
 659 
 660   total_size_needed += _monitors_in_lockstack;
 661 
 662   int chunk_free_room = chunk_sp - frame::metadata_words_at_bottom;
 663   bool available = chunk_free_room >= total_size_needed;
 664   log_develop_trace(continuations)("chunk available: %s size: %d argsize: %d top: " INTPTR_FORMAT " bottom: " INTPTR_FORMAT,
 665     available ? "yes" : "no" , total_size_needed, _cont.argsize(), p2i(_cont_stack_top), p2i(_cont_stack_bottom));
 666   return available ? total_size_needed : 0;
 667 }
 668 
 669 void FreezeBase::freeze_fast_existing_chunk() {
 670   stackChunkOop chunk = _cont.tail();
 671 
 672   DEBUG_ONLY(_fast_freeze_size = size_if_fast_freeze_available();)
 673   assert(_fast_freeze_size > 0, "");
 674 
 675   if (!chunk->is_empty()) { // we are copying into a non-empty chunk
 676     DEBUG_ONLY(_empty = false;)
 677     DEBUG_ONLY(_orig_chunk_sp = chunk->sp_address();)
 678 #ifdef ASSERT
 679     {
 680       intptr_t* retaddr_slot = (chunk->sp_address()
 681                                 - frame::sender_sp_ret_address_offset());
 682       assert(ContinuationHelper::return_address_at(retaddr_slot) == chunk->pc(),
 683              "unexpected saved return address");
 684     }
 685 #endif
 686 
 687     // the chunk's sp before the freeze, adjusted to point beyond the stack-passed arguments in the topmost frame
 688     // we overlap; we'll overwrite the chunk's top frame's callee arguments
 689     const int chunk_start_sp = chunk->sp() + _cont.argsize() + frame::metadata_words_at_top;
 690     assert(chunk_start_sp <= chunk->stack_size(), "sp not pointing into stack");
 691 
 692     // increase max_size by what we're freezing minus the overlap
 693     chunk->set_max_thawing_size(chunk->max_thawing_size() + cont_size() - _cont.argsize() - frame::metadata_words_at_top);
 694 
 695     intptr_t* const bottom_sp = _cont_stack_bottom - _cont.argsize() - frame::metadata_words_at_top;
 696     assert(bottom_sp == _bottom_address, "");
 697     // Because the chunk isn't empty, we know there's a caller in the chunk, therefore the bottom-most frame
 698     // should have a return barrier (installed back when we thawed it).
 699 #ifdef ASSERT
 700     {
 701       intptr_t* retaddr_slot = (bottom_sp
 702                                 - frame::sender_sp_ret_address_offset());
 703       assert(ContinuationHelper::return_address_at(retaddr_slot)
 704              == StubRoutines::cont_returnBarrier(),
 705              "should be the continuation return barrier");
 706     }
 707 #endif
 708     // We copy the fp from the chunk back to the stack because it contains some caller data,
 709     // including, possibly, an oop that might have gone stale since we thawed.
 710     patch_stack_pd(bottom_sp, chunk->sp_address());
 711     // we don't patch the return pc at this time, so as not to make the stack unwalkable for async walks
 712 
 713     freeze_fast_copy(chunk, chunk_start_sp CONT_JFR_ONLY(COMMA false));
 714   } else { // the chunk is empty
 715     const int chunk_start_sp = chunk->stack_size();
 716 
 717     DEBUG_ONLY(_empty = true;)
 718     DEBUG_ONLY(_orig_chunk_sp = chunk->start_address() + chunk_start_sp;)
 719 
 720     chunk->set_max_thawing_size(cont_size());
 721     chunk->set_bottom(chunk_start_sp - _cont.argsize() - frame::metadata_words_at_top);
 722     chunk->set_sp(chunk->bottom());
 723 
 724     freeze_fast_copy(chunk, chunk_start_sp CONT_JFR_ONLY(COMMA false));
 725   }
 726 }
 727 
 728 bool FreezeBase::freeze_fast_new_chunk(stackChunkOop chunk) {
 729   DEBUG_ONLY(_empty = true;)
 730 
 731   // Install new chunk
 732   _cont.set_tail(chunk);
 733 
 734   if (UNLIKELY(chunk == nullptr || !_thread->cont_fastpath() || _barriers)) { // OOME/probably humongous
 735     log_develop_trace(continuations)("Retrying slow. Barriers: %d", _barriers);
 736     return false;
 737   }
 738 
 739   chunk->set_max_thawing_size(cont_size());
 740 
 741   // in a fresh chunk, we freeze *with* the bottom-most frame's stack arguments.
 742   // They'll then be stored twice: in the chunk and in the parent chunk's top frame
 743   const int chunk_start_sp = cont_size() + frame::metadata_words + _monitors_in_lockstack;
 744   assert(chunk_start_sp == chunk->stack_size(), "");
 745 
 746   DEBUG_ONLY(_orig_chunk_sp = chunk->start_address() + chunk_start_sp;)
 747 
 748   freeze_fast_copy(chunk, chunk_start_sp CONT_JFR_ONLY(COMMA true));
 749 
 750   return true;
 751 }
 752 
 753 void FreezeBase::freeze_fast_copy(stackChunkOop chunk, int chunk_start_sp CONT_JFR_ONLY(COMMA bool chunk_is_allocated)) {
 754   assert(chunk != nullptr, "");
 755   assert(!chunk->has_mixed_frames(), "");
 756   assert(!chunk->is_gc_mode(), "");
 757   assert(!chunk->has_bitmap(), "");
 758   assert(!chunk->requires_barriers(), "");
 759   assert(chunk == _cont.tail(), "");
 760 
 761   // We unwind frames after the last safepoint so that the GC will have found the oops in the frames, but before
 762   // writing into the chunk. This is so that an asynchronous stack walk (not at a safepoint) that suspends us here
 763   // will either see no continuation on the stack, or a consistent chunk.
 764   unwind_frames();
 765 
 766   log_develop_trace(continuations)("freeze_fast start: chunk " INTPTR_FORMAT " size: %d orig sp: %d argsize: %d",
 767     p2i((oopDesc*)chunk), chunk->stack_size(), chunk_start_sp, _cont.argsize());
 768   assert(chunk_start_sp <= chunk->stack_size(), "");
 769   assert(chunk_start_sp >= cont_size(), "no room in the chunk");
 770 
 771   const int chunk_new_sp = chunk_start_sp - cont_size(); // the chunk's new sp, after freeze
 772   assert(!(_fast_freeze_size > 0) || (_orig_chunk_sp - (chunk->start_address() + chunk_new_sp)) == (_fast_freeze_size - _monitors_in_lockstack), "");
 773 
 774   intptr_t* chunk_top = chunk->start_address() + chunk_new_sp;
 775 #ifdef ASSERT
 776   if (!_empty) {
 777     intptr_t* retaddr_slot = (_orig_chunk_sp
 778                               - frame::sender_sp_ret_address_offset());
 779     assert(ContinuationHelper::return_address_at(retaddr_slot) == chunk->pc(),
 780            "unexpected saved return address");
 781   }
 782 #endif
 783 
 784   log_develop_trace(continuations)("freeze_fast start: " INTPTR_FORMAT " sp: %d chunk_top: " INTPTR_FORMAT,
 785                               p2i(chunk->start_address()), chunk_new_sp, p2i(chunk_top));
 786   intptr_t* from = _cont_stack_top - frame::metadata_words_at_bottom;
 787   intptr_t* to   = chunk_top - frame::metadata_words_at_bottom;
 788   copy_to_chunk(from, to, cont_size() + frame::metadata_words_at_bottom);
 789   // Because we're not patched yet, the chunk is now in a bad state
 790 
 791   // patch return pc of the bottom-most frozen frame (now in the chunk)
 792   // with the actual caller's return address
 793   intptr_t* chunk_bottom_retaddr_slot = (chunk_top + cont_size()
 794                                          - _cont.argsize()
 795                                          - frame::metadata_words_at_top
 796                                          - frame::sender_sp_ret_address_offset());
 797 #ifdef ASSERT
 798   if (!_empty) {
 799     assert(ContinuationHelper::return_address_at(chunk_bottom_retaddr_slot)
 800            == StubRoutines::cont_returnBarrier(),
 801            "should be the continuation return barrier");
 802   }
 803 #endif
 804   ContinuationHelper::patch_return_address_at(chunk_bottom_retaddr_slot,
 805                                               chunk->pc());
 806 
 807   // We're always writing to a young chunk, so the GC can't see it until the next safepoint.
 808   chunk->set_sp(chunk_new_sp);
 809 
 810   // set chunk->pc to the return address of the topmost frame in the chunk
 811   if (_preempt) {
 812     // On aarch64/riscv64, the return pc of the top frame won't necessarily be at sp[-1].
 813     // Also, on x64, if the top frame is the native wrapper frame, sp[-1] will not
 814     // be the pc we used when creating the oopmap. Get the top's frame last pc from
 815     // the anchor instead.
 816     address last_pc = _last_frame.pc();
 817     ContinuationHelper::patch_return_address_at(chunk_top - frame::sender_sp_ret_address_offset(), last_pc);
 818     chunk->set_pc(last_pc);
 819   } else {
 820     chunk->set_pc(ContinuationHelper::return_address_at(
 821                   _cont_stack_top - frame::sender_sp_ret_address_offset()));
 822   }
 823 
 824   if (_monitors_in_lockstack > 0) {
 825     freeze_lockstack(chunk);
 826   }
 827 
 828   _cont.write();
 829 
 830   log_develop_trace(continuations)("FREEZE CHUNK #" INTPTR_FORMAT " (young)", _cont.hash());
 831   LogTarget(Trace, continuations) lt;
 832   if (lt.develop_is_enabled()) {
 833     LogStream ls(lt);
 834     chunk->print_on(true, &ls);
 835   }
 836 
 837   // Verification
 838   assert(_cont.chunk_invariant(), "");
 839   chunk->verify();
 840 
 841 #if CONT_JFR
 842   EventContinuationFreezeFast e;
 843   if (e.should_commit()) {
 844     e.set_id(cast_from_oop<u8>(chunk));
 845     DEBUG_ONLY(e.set_allocate(chunk_is_allocated);)
 846     e.set_size(cont_size() << LogBytesPerWord);
 847     e.commit();
 848   }
 849 #endif
 850 }
 851 
 852 NOINLINE freeze_result FreezeBase::freeze_slow() {
 853 #ifdef ASSERT
 854   ResourceMark rm;
 855 #endif
 856 
 857   log_develop_trace(continuations)("freeze_slow  #" INTPTR_FORMAT, _cont.hash());
 858   assert(_thread->thread_state() == _thread_in_vm || _thread->thread_state() == _thread_blocked, "");
 859 
 860 #if CONT_JFR
 861   EventContinuationFreezeSlow e;
 862   if (e.should_commit()) {
 863     e.set_id(cast_from_oop<u8>(_cont.continuation()));
 864     e.commit();
 865   }
 866 #endif
 867 
 868   init_rest();
 869 
 870   HandleMark hm(Thread::current());
 871 
 872   frame f = freeze_start_frame();
 873 
 874   LogTarget(Debug, continuations) lt;
 875   if (lt.develop_is_enabled()) {
 876     LogStream ls(lt);
 877     f.print_on(&ls);
 878   }
 879 
 880   frame caller; // the frozen caller in the chunk
 881   freeze_result res = recurse_freeze(f, caller, 0, false, true);
 882 
 883   if (res == freeze_ok) {
 884     finish_freeze(f, caller);
 885     _cont.write();
 886   }
 887 
 888   return res;
 889 }
 890 
 891 frame FreezeBase::freeze_start_frame() {
 892   if (LIKELY(!_preempt)) {
 893     return freeze_start_frame_yield_stub();
 894   } else {
 895     return freeze_start_frame_on_preempt();
 896   }
 897 }
 898 
 899 frame FreezeBase::freeze_start_frame_yield_stub() {
 900   frame f = _thread->last_frame();
 901   assert(SharedRuntime::cont_doYield_stub()->contains(f.pc()), "must be");
 902   f = sender<ContinuationHelper::NonInterpretedUnknownFrame>(f);
 903   assert(Continuation::is_frame_in_continuation(_thread->last_continuation(), f), "");
 904   return f;
 905 }
 906 
 907 frame FreezeBase::freeze_start_frame_on_preempt() {
 908   assert(_last_frame.sp() == _thread->last_frame().sp(), "_last_frame should be already initialized");
 909   assert(Continuation::is_frame_in_continuation(_thread->last_continuation(), _last_frame), "");
 910   return _last_frame;
 911 }
 912 
 913 // The parameter callee_argsize includes metadata that has to be part of caller/callee overlap.
 914 NOINLINE freeze_result FreezeBase::recurse_freeze(frame& f, frame& caller, int callee_argsize, bool callee_interpreted, bool top) {
 915   assert(f.unextended_sp() < _bottom_address, ""); // see recurse_freeze_java_frame
 916   assert(f.is_interpreted_frame() || ((top && _preempt) == ContinuationHelper::Frame::is_stub(f.cb()))
 917          || ((top && _preempt) == f.is_native_frame()), "");
 918 
 919   if (stack_overflow()) {
 920     return freeze_exception;
 921   }
 922 
 923   if (f.is_compiled_frame()) {
 924     if (UNLIKELY(f.oop_map() == nullptr)) {
 925       // special native frame
 926       return freeze_pinned_native;
 927     }
 928     return recurse_freeze_compiled_frame(f, caller, callee_argsize, callee_interpreted);
 929   } else if (f.is_interpreted_frame()) {
 930     assert(!f.interpreter_frame_method()->is_native() || (top && _preempt), "");
 931     return recurse_freeze_interpreted_frame(f, caller, callee_argsize, callee_interpreted);
 932   } else if (top && _preempt) {
 933     assert(f.is_native_frame() || f.is_runtime_frame(), "");
 934     return f.is_native_frame() ? recurse_freeze_native_frame(f, caller) : recurse_freeze_stub_frame(f, caller);
 935   } else {
 936     // Frame can't be frozen. Most likely the call_stub or upcall_stub
 937     // which indicates there are further natives frames up the stack.
 938     return freeze_pinned_native;
 939   }
 940 }
 941 
 942 // The parameter callee_argsize includes metadata that has to be part of caller/callee overlap.
 943 // See also StackChunkFrameStream<frame_kind>::frame_size()
 944 template<typename FKind>
 945 inline freeze_result FreezeBase::recurse_freeze_java_frame(const frame& f, frame& caller, int fsize, int argsize) {
 946   assert(FKind::is_instance(f), "");
 947 
 948   assert(fsize > 0, "");
 949   assert(argsize >= 0, "");
 950   _freeze_size += fsize;
 951   NOT_PRODUCT(_frames++;)
 952 
 953   assert(FKind::frame_bottom(f) <= _bottom_address, "");
 954 
 955   // We don't use FKind::frame_bottom(f) == _bottom_address because on x64 there's sometimes an extra word between
 956   // enterSpecial and an interpreted frame
 957   if (FKind::frame_bottom(f) >= _bottom_address - 1) {
 958     return finalize_freeze(f, caller, argsize); // recursion end
 959   } else {
 960     frame senderf = sender<FKind>(f);
 961     assert(FKind::interpreted || senderf.sp() == senderf.unextended_sp(), "");
 962     freeze_result result = recurse_freeze(senderf, caller, argsize, FKind::interpreted, false); // recursive call
 963     return result;
 964   }
 965 }
 966 
 967 inline void FreezeBase::before_freeze_java_frame(const frame& f, const frame& caller, int fsize, int argsize, bool is_bottom_frame) {
 968   LogTarget(Trace, continuations) lt;
 969   if (lt.develop_is_enabled()) {
 970     LogStream ls(lt);
 971     ls.print_cr("======== FREEZING FRAME interpreted: %d bottom: %d", f.is_interpreted_frame(), is_bottom_frame);
 972     ls.print_cr("fsize: %d argsize: %d", fsize, argsize);
 973     f.print_value_on(&ls);
 974   }
 975   assert(caller.is_interpreted_frame() == Interpreter::contains(caller.pc()), "");
 976 }
 977 
 978 inline void FreezeBase::after_freeze_java_frame(const frame& hf, bool is_bottom_frame) {
 979   LogTarget(Trace, continuations) lt;
 980   if (lt.develop_is_enabled()) {
 981     LogStream ls(lt);
 982     DEBUG_ONLY(hf.print_value_on(&ls);)
 983     assert(hf.is_heap_frame(), "should be");
 984     DEBUG_ONLY(print_frame_layout(hf, false, &ls);)
 985     if (is_bottom_frame) {
 986       ls.print_cr("bottom h-frame:");
 987       hf.print_on(&ls);
 988     }
 989   }
 990 }
 991 
 992 // The parameter argsize_md includes metadata that has to be part of caller/callee overlap.
 993 // See also StackChunkFrameStream<frame_kind>::frame_size()
 994 freeze_result FreezeBase::finalize_freeze(const frame& callee, frame& caller, int argsize_md) {
 995   int argsize = argsize_md - frame::metadata_words_at_top;
 996   assert(callee.is_interpreted_frame()
 997     || ContinuationHelper::Frame::is_stub(callee.cb())
 998     || callee.cb()->as_nmethod()->is_osr_method()
 999     || argsize == _cont.argsize(), "argsize: %d cont.argsize: %d", argsize, _cont.argsize());
1000   log_develop_trace(continuations)("bottom: " INTPTR_FORMAT " count %d size: %d argsize: %d",
1001     p2i(_bottom_address), _frames, _freeze_size << LogBytesPerWord, argsize);
1002 
1003   LogTarget(Trace, continuations) lt;
1004 
1005 #ifdef ASSERT
1006   bool empty = _cont.is_empty();
1007   log_develop_trace(continuations)("empty: %d", empty);
1008 #endif
1009 
1010   stackChunkOop chunk = _cont.tail();
1011 
1012   assert(chunk == nullptr || (chunk->max_thawing_size() == 0) == chunk->is_empty(), "");
1013 
1014   _freeze_size += frame::metadata_words; // for top frame's metadata
1015 
1016   int overlap = 0; // the args overlap the caller -- if there is one in this chunk and is of the same kind
1017   int unextended_sp = -1;
1018   if (chunk != nullptr) {
1019     if (!chunk->is_empty()) {
1020       StackChunkFrameStream<ChunkFrames::Mixed> last(chunk);
1021       unextended_sp = chunk->to_offset(StackChunkFrameStream<ChunkFrames::Mixed>(chunk).unextended_sp());
1022       bool top_interpreted = Interpreter::contains(chunk->pc());
1023       if (callee.is_interpreted_frame() == top_interpreted) {
1024         overlap = argsize_md;
1025       }
1026     } else {
1027       unextended_sp = chunk->stack_size() - frame::metadata_words_at_top;
1028     }
1029   }
1030 
1031   log_develop_trace(continuations)("finalize _size: %d overlap: %d unextended_sp: %d", _freeze_size, overlap, unextended_sp);
1032 
1033   _freeze_size -= overlap;
1034   assert(_freeze_size >= 0, "");
1035 
1036   assert(chunk == nullptr || chunk->is_empty()
1037           || unextended_sp == chunk->to_offset(StackChunkFrameStream<ChunkFrames::Mixed>(chunk).unextended_sp()), "");
1038   assert(chunk != nullptr || unextended_sp < _freeze_size, "");
1039 
1040   _freeze_size += _monitors_in_lockstack;
1041 
1042   // _barriers can be set to true by an allocation in freeze_fast, in which case the chunk is available
1043   bool allocated_old_in_freeze_fast = _barriers;
1044   assert(!allocated_old_in_freeze_fast || (unextended_sp >= _freeze_size && chunk->is_empty()),
1045     "Chunk allocated in freeze_fast is of insufficient size "
1046     "unextended_sp: %d size: %d is_empty: %d", unextended_sp, _freeze_size, chunk->is_empty());
1047   assert(!allocated_old_in_freeze_fast || (!UseZGC && !UseG1GC), "Unexpected allocation");
1048 
1049   DEBUG_ONLY(bool empty_chunk = true);
1050   if (unextended_sp < _freeze_size || chunk->is_gc_mode() || (!allocated_old_in_freeze_fast && chunk->requires_barriers())) {
1051     // ALLOCATE NEW CHUNK
1052 
1053     if (lt.develop_is_enabled()) {
1054       LogStream ls(lt);
1055       if (chunk == nullptr) {
1056         ls.print_cr("no chunk");
1057       } else {
1058         ls.print_cr("chunk barriers: %d _size: %d free size: %d",
1059           chunk->requires_barriers(), _freeze_size, chunk->sp() - frame::metadata_words);
1060         chunk->print_on(&ls);
1061       }
1062     }
1063 
1064     _freeze_size += overlap; // we're allocating a new chunk, so no overlap
1065     // overlap = 0;
1066 
1067     chunk = allocate_chunk_slow(_freeze_size, argsize_md);
1068     if (chunk == nullptr) {
1069       return freeze_exception;
1070     }
1071 
1072     // Install new chunk
1073     _cont.set_tail(chunk);
1074     assert(chunk->is_empty(), "");
1075   } else {
1076     // REUSE EXISTING CHUNK
1077     log_develop_trace(continuations)("Reusing chunk mixed: %d empty: %d", chunk->has_mixed_frames(), chunk->is_empty());
1078     if (chunk->is_empty()) {
1079       int sp = chunk->stack_size() - argsize_md;
1080       chunk->set_sp(sp);
1081       chunk->set_bottom(sp);
1082       _freeze_size += overlap;
1083       assert(chunk->max_thawing_size() == 0, "");
1084     } DEBUG_ONLY(else empty_chunk = false;)
1085   }
1086   assert(!chunk->is_gc_mode(), "");
1087   assert(!chunk->has_bitmap(), "");
1088   chunk->set_has_mixed_frames(true);
1089 
1090   assert(chunk->requires_barriers() == _barriers, "");
1091   assert(!_barriers || chunk->is_empty(), "");
1092 
1093   assert(!chunk->is_empty() || StackChunkFrameStream<ChunkFrames::Mixed>(chunk).is_done(), "");
1094   assert(!chunk->is_empty() || StackChunkFrameStream<ChunkFrames::Mixed>(chunk).to_frame().is_empty(), "");
1095 
1096   if (_preempt) {
1097     frame f = _thread->last_frame();
1098     if (f.is_interpreted_frame()) {
1099       // Some platforms do not save the last_sp in the top interpreter frame on VM calls.
1100       // We need it so that on resume we can restore the sp to the right place, since
1101       // thawing might add an alignment word to the expression stack (see finish_thaw()).
1102       // We do it now that we know freezing will be successful.
1103       prepare_freeze_interpreted_top_frame(f);
1104     }
1105   }
1106 
1107   // We unwind frames after the last safepoint so that the GC will have found the oops in the frames, but before
1108   // writing into the chunk. This is so that an asynchronous stack walk (not at a safepoint) that suspends us here
1109   // will either see no continuation or a consistent chunk.
1110   unwind_frames();
1111 
1112   chunk->set_max_thawing_size(chunk->max_thawing_size() + _freeze_size - _monitors_in_lockstack - frame::metadata_words);
1113 
1114   if (lt.develop_is_enabled()) {
1115     LogStream ls(lt);
1116     ls.print_cr("top chunk:");
1117     chunk->print_on(&ls);
1118   }
1119 
1120   if (_monitors_in_lockstack > 0) {
1121     freeze_lockstack(chunk);
1122   }
1123 
1124   // The topmost existing frame in the chunk; or an empty frame if the chunk is empty
1125   caller = StackChunkFrameStream<ChunkFrames::Mixed>(chunk).to_frame();
1126 
1127   DEBUG_ONLY(_last_write = caller.unextended_sp() + (empty_chunk ? argsize_md : overlap);)
1128 
1129   assert(chunk->is_in_chunk(_last_write - _freeze_size),
1130     "last_write-size: " INTPTR_FORMAT " start: " INTPTR_FORMAT, p2i(_last_write-_freeze_size), p2i(chunk->start_address()));
1131 #ifdef ASSERT
1132   if (lt.develop_is_enabled()) {
1133     LogStream ls(lt);
1134     ls.print_cr("top hframe before (freeze):");
1135     assert(caller.is_heap_frame(), "should be");
1136     caller.print_on(&ls);
1137   }
1138 
1139   assert(!empty || Continuation::is_continuation_entry_frame(callee, nullptr), "");
1140 
1141   frame entry = sender(callee);
1142 
1143   assert((!empty && Continuation::is_return_barrier_entry(entry.pc())) || (empty && Continuation::is_continuation_enterSpecial(entry)), "");
1144   assert(callee.is_interpreted_frame() || entry.sp() == entry.unextended_sp(), "");
1145 #endif
1146 
1147   return freeze_ok_bottom;
1148 }
1149 
1150 // After freezing a frame we need to possibly adjust some values related to the caller frame.
1151 void FreezeBase::patch(const frame& f, frame& hf, const frame& caller, bool is_bottom_frame) {
1152   if (is_bottom_frame) {
1153     // If we're the bottom frame, we need to replace the return barrier with the real
1154     // caller's pc.
1155     address last_pc = caller.pc();
1156     assert((last_pc == nullptr) == _cont.tail()->is_empty(), "");
1157     ContinuationHelper::Frame::patch_pc(caller, last_pc);
1158   } else {
1159     assert(!caller.is_empty(), "");
1160   }
1161 
1162   patch_pd(hf, caller, is_bottom_frame);
1163 
1164   if (f.is_interpreted_frame()) {
1165     assert(hf.is_heap_frame(), "should be");
1166     ContinuationHelper::InterpretedFrame::patch_sender_sp(hf, caller);
1167   }
1168 
1169 #ifdef ASSERT
1170   if (hf.is_compiled_frame()) {
1171     if (f.is_deoptimized_frame()) { // TODO DEOPT: long term solution: unroll on freeze and patch pc
1172       log_develop_trace(continuations)("Freezing deoptimized frame");
1173       assert(f.cb()->as_nmethod()->is_deopt_pc(f.raw_pc()), "");
1174       assert(f.cb()->as_nmethod()->is_deopt_pc(ContinuationHelper::Frame::real_pc(f)), "");
1175     }
1176   }
1177 #endif
1178 }
1179 
1180 #ifdef ASSERT
1181 static void verify_frame_top(const frame& f, intptr_t* top) {
1182   ResourceMark rm;
1183   InterpreterOopMap mask;
1184   f.interpreted_frame_oop_map(&mask);
1185   assert(top <= ContinuationHelper::InterpretedFrame::frame_top(f, &mask),
1186          "frame_top: " INTPTR_FORMAT " Interpreted::frame_top: " INTPTR_FORMAT,
1187            p2i(top), p2i(ContinuationHelper::InterpretedFrame::frame_top(f, &mask)));
1188 }
1189 #endif // ASSERT
1190 
1191 // The parameter callee_argsize includes metadata that has to be part of caller/callee overlap.
1192 // See also StackChunkFrameStream<frame_kind>::frame_size()
1193 NOINLINE freeze_result FreezeBase::recurse_freeze_interpreted_frame(frame& f, frame& caller,
1194                                                                     int callee_argsize /* incl. metadata */,
1195                                                                     bool callee_interpreted) {
1196   adjust_interpreted_frame_unextended_sp(f);
1197 
1198   // The frame's top never includes the stack arguments to the callee
1199   intptr_t* const stack_frame_top = ContinuationHelper::InterpretedFrame::frame_top(f, callee_argsize, callee_interpreted);
1200   intptr_t* const stack_frame_bottom = ContinuationHelper::InterpretedFrame::frame_bottom(f);
1201   const int fsize = pointer_delta_as_int(stack_frame_bottom, stack_frame_top);
1202 
1203   DEBUG_ONLY(verify_frame_top(f, stack_frame_top));
1204 
1205   Method* frame_method = ContinuationHelper::Frame::frame_method(f);
1206   // including metadata between f and its args
1207   const int argsize = ContinuationHelper::InterpretedFrame::stack_argsize(f) + frame::metadata_words_at_top;
1208 
1209   log_develop_trace(continuations)("recurse_freeze_interpreted_frame %s _size: %d fsize: %d argsize: %d callee_interpreted: %d",
1210     frame_method->name_and_sig_as_C_string(), _freeze_size, fsize, argsize, callee_interpreted);
1211   // we'd rather not yield inside methods annotated with @JvmtiMountTransition
1212   assert(!ContinuationHelper::Frame::frame_method(f)->jvmti_mount_transition(), "");
1213 
1214   freeze_result result = recurse_freeze_java_frame<ContinuationHelper::InterpretedFrame>(f, caller, fsize, argsize);
1215   if (UNLIKELY(result > freeze_ok_bottom)) {
1216     return result;
1217   }
1218 
1219   bool is_bottom_frame = result == freeze_ok_bottom;
1220   assert(!caller.is_empty() || is_bottom_frame, "");
1221 
1222   DEBUG_ONLY(before_freeze_java_frame(f, caller, fsize, 0, is_bottom_frame);)
1223 
1224   frame hf = new_heap_frame<ContinuationHelper::InterpretedFrame>(f, caller);
1225   _total_align_size += frame::align_wiggle; // add alignment room for internal interpreted frame alignment on AArch64/PPC64
1226 
1227   intptr_t* heap_frame_top = ContinuationHelper::InterpretedFrame::frame_top(hf, callee_argsize, callee_interpreted);
1228   intptr_t* heap_frame_bottom = ContinuationHelper::InterpretedFrame::frame_bottom(hf);
1229   assert(heap_frame_bottom == heap_frame_top + fsize, "");
1230 
1231   // Some architectures (like AArch64/PPC64/RISC-V) add padding between the locals and the fixed_frame to keep the fp 16-byte-aligned.
1232   // On those architectures we freeze the padding in order to keep the same fp-relative offsets in the fixed_frame.
1233   copy_to_chunk(stack_frame_top, heap_frame_top, fsize);
1234   assert(!is_bottom_frame || !caller.is_interpreted_frame() || (heap_frame_top + fsize) == (caller.unextended_sp() + argsize), "");
1235 
1236   relativize_interpreted_frame_metadata(f, hf);
1237 
1238   patch(f, hf, caller, is_bottom_frame);
1239 
1240   CONT_JFR_ONLY(_jfr_info.record_interpreted_frame();)
1241   DEBUG_ONLY(after_freeze_java_frame(hf, is_bottom_frame);)
1242   caller = hf;
1243 
1244   // Mark frame_method's GC epoch for class redefinition on_stack calculation.
1245   frame_method->record_gc_epoch();
1246 
1247   return freeze_ok;
1248 }
1249 
1250 // The parameter callee_argsize includes metadata that has to be part of caller/callee overlap.
1251 // See also StackChunkFrameStream<frame_kind>::frame_size()
1252 freeze_result FreezeBase::recurse_freeze_compiled_frame(frame& f, frame& caller,
1253                                                         int callee_argsize /* incl. metadata */,
1254                                                         bool callee_interpreted) {
1255   // The frame's top never includes the stack arguments to the callee
1256   intptr_t* const stack_frame_top = ContinuationHelper::CompiledFrame::frame_top(f, callee_argsize, callee_interpreted);
1257   intptr_t* const stack_frame_bottom = ContinuationHelper::CompiledFrame::frame_bottom(f);
1258   // including metadata between f and its stackargs
1259   int argsize = ContinuationHelper::CompiledFrame::stack_argsize(f) + frame::metadata_words_at_top;
1260   int fsize = pointer_delta_as_int(stack_frame_bottom + argsize, stack_frame_top);
1261 
1262   int real_frame_size = 0;
1263   bool augmented = f.was_augmented_on_entry(real_frame_size);
1264   if (augmented) {
1265     // The args reside inside the frame so clear argsize. If the caller is compiled,
1266     // this will cause the stack arguments passed by the caller to be freezed when
1267     // freezing the caller frame itself. If the caller is interpreted this will have
1268     // the effect of discarding the arg area created in the i2c stub.
1269     argsize = 0;
1270     fsize = real_frame_size - (callee_interpreted ? 0 : callee_argsize);
1271 #ifdef ASSERT
1272     nmethod* nm = f.cb()->as_nmethod();
1273     Method* method = nm->method();
1274     address return_pc = ContinuationHelper::CompiledFrame::return_pc(f);
1275     CodeBlob* caller_cb = CodeCache::find_blob_fast(return_pc);
1276     assert(nm->is_compiled_by_c2() || (caller_cb->is_nmethod() && caller_cb->as_nmethod()->is_compiled_by_c2()), "caller or callee should be c2 compiled");
1277     assert((!caller_cb->is_nmethod() && nm->is_compiled_by_c2()) ||
1278            (nm->compiler_type() != caller_cb->as_nmethod()->compiler_type()) ||
1279            (nm->is_compiled_by_c2() && !method->is_static() && method->method_holder()->is_inline_klass()),
1280            "frame should not be extended");
1281 #endif
1282   }
1283 
1284   log_develop_trace(continuations)("recurse_freeze_compiled_frame %s _size: %d fsize: %d argsize: %d augmented: %d",
1285                              ContinuationHelper::Frame::frame_method(f) != nullptr ?
1286                              ContinuationHelper::Frame::frame_method(f)->name_and_sig_as_C_string() : "",
1287                              _freeze_size, fsize, argsize, augmented);
1288   // we'd rather not yield inside methods annotated with @JvmtiMountTransition
1289   assert(!ContinuationHelper::Frame::frame_method(f)->jvmti_mount_transition(), "");
1290 
1291   freeze_result result = recurse_freeze_java_frame<ContinuationHelper::CompiledFrame>(f, caller, fsize, argsize);
1292   if (UNLIKELY(result > freeze_ok_bottom)) {
1293     return result;
1294   }
1295 
1296   bool is_bottom_frame = result == freeze_ok_bottom;
1297   assert(!caller.is_empty() || is_bottom_frame, "");
1298   assert(!is_bottom_frame || !augmented, "thaw extended frame without caller?");
1299 
1300   DEBUG_ONLY(before_freeze_java_frame(f, caller, fsize, argsize, is_bottom_frame);)
1301 
1302   frame hf = new_heap_frame<ContinuationHelper::CompiledFrame>(f, caller, augmented ? real_frame_size - f.cb()->as_nmethod()->frame_size() : 0);
1303 
1304   intptr_t* heap_frame_top = ContinuationHelper::CompiledFrame::frame_top(hf, callee_argsize, callee_interpreted);
1305 
1306   copy_to_chunk(stack_frame_top, heap_frame_top, fsize);
1307   assert(!is_bottom_frame || !caller.is_compiled_frame() || (heap_frame_top + fsize) == (caller.unextended_sp() + argsize), "");
1308 
1309   if (caller.is_interpreted_frame()) {
1310     // When thawing the frame we might need to add alignment (see Thaw::align)
1311     _total_align_size += frame::align_wiggle;
1312   }
1313 
1314   patch(f, hf, caller, is_bottom_frame);
1315 
1316   assert(is_bottom_frame || Interpreter::contains(ContinuationHelper::CompiledFrame::real_pc(caller)) == caller.is_interpreted_frame(), "");
1317 
1318   DEBUG_ONLY(after_freeze_java_frame(hf, is_bottom_frame);)
1319   caller = hf;
1320   return freeze_ok;
1321 }
1322 
1323 NOINLINE freeze_result FreezeBase::recurse_freeze_stub_frame(frame& f, frame& caller) {
1324   DEBUG_ONLY(frame fsender = sender(f);)
1325   assert(fsender.is_compiled_frame(), "sender should be compiled frame");
1326 
1327   intptr_t* const stack_frame_top = ContinuationHelper::StubFrame::frame_top(f);
1328   const int fsize = f.cb()->frame_size();
1329 
1330   log_develop_trace(continuations)("recurse_freeze_stub_frame %s _size: %d fsize: %d :: " INTPTR_FORMAT " - " INTPTR_FORMAT,
1331     f.cb()->name(), _freeze_size, fsize, p2i(stack_frame_top), p2i(stack_frame_top+fsize));
1332 
1333   freeze_result result = recurse_freeze_java_frame<ContinuationHelper::StubFrame>(f, caller, fsize, 0);
1334   if (UNLIKELY(result > freeze_ok_bottom)) {
1335     return result;
1336   }
1337 
1338   assert(result == freeze_ok, "should have caller");
1339   DEBUG_ONLY(before_freeze_java_frame(f, caller, fsize, 0, false /*is_bottom_frame*/);)
1340 
1341   frame hf = new_heap_frame<ContinuationHelper::StubFrame>(f, caller);
1342   intptr_t* heap_frame_top = ContinuationHelper::StubFrame::frame_top(hf);
1343 
1344   copy_to_chunk(stack_frame_top, heap_frame_top, fsize);
1345 
1346   patch(f, hf, caller, false /*is_bottom_frame*/);
1347 
1348   DEBUG_ONLY(after_freeze_java_frame(hf, false /*is_bottom_frame*/);)
1349 
1350   caller = hf;
1351   return freeze_ok;
1352 }
1353 
1354 NOINLINE freeze_result FreezeBase::recurse_freeze_native_frame(frame& f, frame& caller) {
1355   if (!f.cb()->as_nmethod()->method()->is_object_wait0()) {
1356     assert(f.cb()->as_nmethod()->method()->is_synchronized(), "");
1357     // Synchronized native method case. Unlike the interpreter native wrapper, the compiled
1358     // native wrapper tries to acquire the monitor after marshalling the arguments from the
1359     // caller into the native convention. This is so that we have a valid oopMap in case of
1360     // having to block in the slow path. But that would require freezing those registers too
1361     // and then fixing them back on thaw in case of oops. To avoid complicating things and
1362     // given that this would be a rare case anyways just pin the vthread to the carrier.
1363     return freeze_pinned_native;
1364   }
1365 
1366   intptr_t* const stack_frame_top = ContinuationHelper::NativeFrame::frame_top(f);
1367   // There are no stackargs but argsize must include the metadata
1368   const int argsize = frame::metadata_words_at_top;
1369   const int fsize = f.cb()->frame_size() + argsize;
1370 
1371   log_develop_trace(continuations)("recurse_freeze_native_frame %s _size: %d fsize: %d :: " INTPTR_FORMAT " - " INTPTR_FORMAT,
1372     f.cb()->name(), _freeze_size, fsize, p2i(stack_frame_top), p2i(stack_frame_top+fsize));
1373 
1374   freeze_result result = recurse_freeze_java_frame<ContinuationHelper::NativeFrame>(f, caller, fsize, argsize);
1375   if (UNLIKELY(result > freeze_ok_bottom)) {
1376     return result;
1377   }
1378 
1379   assert(result == freeze_ok, "should have caller frame");
1380   DEBUG_ONLY(before_freeze_java_frame(f, caller, fsize, argsize, false /* is_bottom_frame */);)
1381 
1382   frame hf = new_heap_frame<ContinuationHelper::NativeFrame>(f, caller);
1383   intptr_t* heap_frame_top = ContinuationHelper::NativeFrame::frame_top(hf);
1384 
1385   copy_to_chunk(stack_frame_top, heap_frame_top, fsize);
1386 
1387   if (caller.is_interpreted_frame()) {
1388     // When thawing the frame we might need to add alignment (see Thaw::align)
1389     _total_align_size += frame::align_wiggle;
1390   }
1391 
1392   patch(f, hf, caller, false /* is_bottom_frame */);
1393 
1394   DEBUG_ONLY(after_freeze_java_frame(hf, false /* is_bottom_frame */);)
1395 
1396   caller = hf;
1397   return freeze_ok;
1398 }
1399 
1400 NOINLINE void FreezeBase::finish_freeze(const frame& f, const frame& top) {
1401   stackChunkOop chunk = _cont.tail();
1402 
1403   LogTarget(Trace, continuations) lt;
1404   if (lt.develop_is_enabled()) {
1405     LogStream ls(lt);
1406     assert(top.is_heap_frame(), "should be");
1407     top.print_on(&ls);
1408   }
1409 
1410   set_top_frame_metadata_pd(top);
1411 
1412   chunk->set_sp(chunk->to_offset(top.sp()));
1413   chunk->set_pc(top.pc());
1414 
1415   chunk->set_max_thawing_size(chunk->max_thawing_size() + _total_align_size);
1416 
1417   assert(chunk->sp_address() - chunk->start_address() >= _monitors_in_lockstack, "clash with lockstack");
1418 
1419   // At this point the chunk is consistent
1420 
1421   if (UNLIKELY(_barriers)) {
1422     log_develop_trace(continuations)("do barriers on old chunk");
1423     // Serial and Parallel GC can allocate objects directly into the old generation.
1424     // Then we want to relativize the derived pointers eagerly so that
1425     // old chunks are all in GC mode.
1426     assert(!UseG1GC, "G1 can not deal with allocating outside of eden");
1427     assert(!UseZGC, "ZGC can not deal with allocating chunks visible to marking");
1428     if (UseShenandoahGC) {
1429       _cont.tail()->relativize_derived_pointers_concurrently();
1430     } else {
1431       ContinuationGCSupport::transform_stack_chunk(_cont.tail());
1432     }
1433     // For objects in the old generation we must maintain the remembered set
1434     _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>();
1435   }
1436 
1437   log_develop_trace(continuations)("finish_freeze: has_mixed_frames: %d", chunk->has_mixed_frames());
1438   if (lt.develop_is_enabled()) {
1439     LogStream ls(lt);
1440     chunk->print_on(true, &ls);
1441   }
1442 
1443   if (lt.develop_is_enabled()) {
1444     LogStream ls(lt);
1445     ls.print_cr("top hframe after (freeze):");
1446     assert(_cont.last_frame().is_heap_frame(), "should be");
1447     _cont.last_frame().print_on(&ls);
1448     DEBUG_ONLY(print_frame_layout(top, false, &ls);)
1449   }
1450 
1451   assert(_cont.chunk_invariant(), "");
1452 }
1453 
1454 inline bool FreezeBase::stack_overflow() { // detect stack overflow in recursive native code
1455   JavaThread* t = !_preempt ? _thread : JavaThread::current();
1456   assert(t == JavaThread::current(), "");
1457   if (os::current_stack_pointer() < t->stack_overflow_state()->shadow_zone_safe_limit()) {
1458     if (!_preempt) {
1459       ContinuationWrapper::SafepointOp so(t, _cont); // could also call _cont.done() instead
1460       Exceptions::_throw_msg(t, __FILE__, __LINE__, vmSymbols::java_lang_StackOverflowError(), "Stack overflow while freezing");
1461     }
1462     return true;
1463   }
1464   return false;
1465 }
1466 
1467 class StackChunkAllocator : public MemAllocator {
1468   const size_t                                 _stack_size;
1469   int                                          _argsize_md;
1470   ContinuationWrapper&                         _continuation_wrapper;
1471   JvmtiSampledObjectAllocEventCollector* const _jvmti_event_collector;
1472   mutable bool                                 _took_slow_path;
1473 
1474   // Does the minimal amount of initialization needed for a TLAB allocation.
1475   // We don't need to do a full initialization, as such an allocation need not be immediately walkable.
1476   virtual oop initialize(HeapWord* mem) const override {
1477     assert(_stack_size > 0, "");
1478     assert(_stack_size <= max_jint, "");
1479     assert(_word_size > _stack_size, "");
1480 
1481     // zero out fields (but not the stack)
1482     const size_t hs = oopDesc::header_size();
1483     if (oopDesc::has_klass_gap()) {
1484       oopDesc::set_klass_gap(mem, 0);
1485     }
1486     Copy::fill_to_aligned_words(mem + hs, vmClasses::StackChunk_klass()->size_helper() - hs);
1487 
1488     int bottom = (int)_stack_size - _argsize_md;
1489 
1490     jdk_internal_vm_StackChunk::set_size(mem, (int)_stack_size);
1491     jdk_internal_vm_StackChunk::set_bottom(mem, bottom);
1492     jdk_internal_vm_StackChunk::set_sp(mem, bottom);
1493 
1494     return finish(mem);
1495   }
1496 
1497   stackChunkOop allocate_fast() const {
1498     if (!UseTLAB) {
1499       return nullptr;
1500     }
1501 
1502     HeapWord* const mem = MemAllocator::mem_allocate_inside_tlab_fast();
1503     if (mem == nullptr) {
1504       return nullptr;
1505     }
1506 
1507     oop obj = initialize(mem);
1508     return stackChunkOopDesc::cast(obj);
1509   }
1510 
1511 public:
1512   StackChunkAllocator(Klass* klass,
1513                       size_t word_size,
1514                       Thread* thread,
1515                       size_t stack_size,
1516                       int argsize_md,
1517                       ContinuationWrapper& continuation_wrapper,
1518                       JvmtiSampledObjectAllocEventCollector* jvmti_event_collector)
1519     : MemAllocator(klass, word_size, thread),
1520       _stack_size(stack_size),
1521       _argsize_md(argsize_md),
1522       _continuation_wrapper(continuation_wrapper),
1523       _jvmti_event_collector(jvmti_event_collector),
1524       _took_slow_path(false) {}
1525 
1526   // Provides it's own, specialized allocation which skips instrumentation
1527   // if the memory can be allocated without going to a slow-path.
1528   stackChunkOop allocate() const {
1529     // First try to allocate without any slow-paths or instrumentation.
1530     stackChunkOop obj = allocate_fast();
1531     if (obj != nullptr) {
1532       return obj;
1533     }
1534 
1535     // Now try full-blown allocation with all expensive operations,
1536     // including potentially safepoint operations.
1537     _took_slow_path = true;
1538 
1539     // Protect unhandled Loom oops
1540     ContinuationWrapper::SafepointOp so(_thread, _continuation_wrapper);
1541 
1542     // Can safepoint
1543     _jvmti_event_collector->start();
1544 
1545     // Can safepoint
1546     return stackChunkOopDesc::cast(MemAllocator::allocate());
1547   }
1548 
1549   bool took_slow_path() const {
1550     return _took_slow_path;
1551   }
1552 };
1553 
1554 template <typename ConfigT>
1555 stackChunkOop Freeze<ConfigT>::allocate_chunk(size_t stack_size, int argsize_md) {
1556   log_develop_trace(continuations)("allocate_chunk allocating new chunk");
1557 
1558   InstanceStackChunkKlass* klass = InstanceStackChunkKlass::cast(vmClasses::StackChunk_klass());
1559   size_t size_in_words = klass->instance_size(stack_size);
1560 
1561   if (CollectedHeap::stack_chunk_max_size() > 0 && size_in_words >= CollectedHeap::stack_chunk_max_size()) {
1562     if (!_preempt) {
1563       throw_stack_overflow_on_humongous_chunk();
1564     }
1565     return nullptr;
1566   }
1567 
1568   JavaThread* current = _preempt ? JavaThread::current() : _thread;
1569   assert(current == JavaThread::current(), "should be current");
1570 
1571   // Allocate the chunk.
1572   //
1573   // This might safepoint while allocating, but all safepointing due to
1574   // instrumentation have been deferred. This property is important for
1575   // some GCs, as this ensures that the allocated object is in the young
1576   // generation / newly allocated memory.
1577   StackChunkAllocator allocator(klass, size_in_words, current, stack_size, argsize_md, _cont, _jvmti_event_collector);
1578   stackChunkOop chunk = allocator.allocate();
1579 
1580   if (chunk == nullptr) {
1581     return nullptr; // OOME
1582   }
1583 
1584   // assert that chunk is properly initialized
1585   assert(chunk->stack_size() == (int)stack_size, "");
1586   assert(chunk->size() >= stack_size, "chunk->size(): %zu size: %zu", chunk->size(), stack_size);
1587   assert(chunk->sp() == chunk->bottom(), "");
1588   assert((intptr_t)chunk->start_address() % 8 == 0, "");
1589   assert(chunk->max_thawing_size() == 0, "");
1590   assert(chunk->pc() == nullptr, "");
1591   assert(chunk->is_empty(), "");
1592   assert(chunk->flags() == 0, "");
1593   assert(chunk->is_gc_mode() == false, "");
1594   assert(chunk->lockstack_size() == 0, "");
1595 
1596   // fields are uninitialized
1597   chunk->set_parent_access<IS_DEST_UNINITIALIZED>(_cont.last_nonempty_chunk());
1598   chunk->set_cont_access<IS_DEST_UNINITIALIZED>(_cont.continuation());
1599 
1600 #if INCLUDE_ZGC
1601   if (UseZGC) {
1602     ZStackChunkGCData::initialize(chunk);
1603     assert(!chunk->requires_barriers(), "ZGC always allocates in the young generation");
1604     _barriers = false;
1605   } else
1606 #endif
1607 #if INCLUDE_SHENANDOAHGC
1608   if (UseShenandoahGC) {
1609     _barriers = chunk->requires_barriers();
1610   } else
1611 #endif
1612   {
1613     if (!allocator.took_slow_path()) {
1614       // Guaranteed to be in young gen / newly allocated memory
1615       assert(!chunk->requires_barriers(), "Unfamiliar GC requires barriers on TLAB allocation");
1616       _barriers = false;
1617     } else {
1618       // Some GCs could put direct allocations in old gen for slow-path
1619       // allocations; need to explicitly check if that was the case.
1620       _barriers = chunk->requires_barriers();
1621     }
1622   }
1623 
1624   if (_barriers) {
1625     log_develop_trace(continuations)("allocation requires barriers");
1626   }
1627 
1628   assert(chunk->parent() == nullptr || chunk->parent()->is_stackChunk(), "");
1629 
1630   return chunk;
1631 }
1632 
1633 void FreezeBase::throw_stack_overflow_on_humongous_chunk() {
1634   ContinuationWrapper::SafepointOp so(_thread, _cont); // could also call _cont.done() instead
1635   Exceptions::_throw_msg(_thread, __FILE__, __LINE__, vmSymbols::java_lang_StackOverflowError(), "Humongous stack chunk");
1636 }
1637 
1638 #if INCLUDE_JVMTI
1639 static int num_java_frames(ContinuationWrapper& cont) {
1640   ResourceMark rm; // used for scope traversal in num_java_frames(nmethod*, address)
1641   int count = 0;
1642   for (stackChunkOop chunk = cont.tail(); chunk != nullptr; chunk = chunk->parent()) {
1643     count += chunk->num_java_frames();
1644   }
1645   return count;
1646 }
1647 
1648 static void invalidate_jvmti_stack(JavaThread* thread) {
1649   if (thread->is_interp_only_mode()) {
1650     JvmtiThreadState *state = thread->jvmti_thread_state();
1651     if (state != nullptr)
1652       state->invalidate_cur_stack_depth();
1653   }
1654 }
1655 
1656 static void jvmti_yield_cleanup(JavaThread* thread, ContinuationWrapper& cont) {
1657   if (JvmtiExport::can_post_frame_pop()) {
1658     int num_frames = num_java_frames(cont);
1659 
1660     ContinuationWrapper::SafepointOp so(Thread::current(), cont);
1661     JvmtiExport::continuation_yield_cleanup(JavaThread::current(), num_frames);
1662   }
1663   invalidate_jvmti_stack(thread);
1664 }
1665 
1666 static void jvmti_mount_end(JavaThread* current, ContinuationWrapper& cont, frame top) {
1667   assert(current->vthread() != nullptr, "must be");
1668 
1669   HandleMarkCleaner hm(current);
1670   Handle vth(current, current->vthread());
1671 
1672   ContinuationWrapper::SafepointOp so(current, cont);
1673 
1674   // Since we might safepoint set the anchor so that the stack can be walked.
1675   set_anchor(current, top.sp());
1676 
1677   JRT_BLOCK
1678     JvmtiVTMSTransitionDisabler::VTMS_vthread_mount((jthread)vth.raw_value(), false);
1679 
1680     if (current->pending_contended_entered_event()) {
1681       JvmtiExport::post_monitor_contended_entered(current, current->contended_entered_monitor());
1682       current->set_contended_entered_monitor(nullptr);
1683     }
1684   JRT_BLOCK_END
1685 
1686   clear_anchor(current);
1687 }
1688 #endif // INCLUDE_JVMTI
1689 
1690 #ifdef ASSERT
1691 // There are no interpreted frames if we're not called from the interpreter and we haven't ancountered an i2c
1692 // adapter or called Deoptimization::unpack_frames. As for native frames, upcalls from JNI also go through the
1693 // interpreter (see JavaCalls::call_helper), while the UpcallLinker explicitly sets cont_fastpath.
1694 bool FreezeBase::check_valid_fast_path() {
1695   ContinuationEntry* ce = _thread->last_continuation();
1696   RegisterMap map(_thread,
1697                   RegisterMap::UpdateMap::skip,
1698                   RegisterMap::ProcessFrames::skip,
1699                   RegisterMap::WalkContinuation::skip);
1700   map.set_include_argument_oops(false);
1701   bool is_top_frame = true;
1702   for (frame f = freeze_start_frame(); Continuation::is_frame_in_continuation(ce, f); f = f.sender(&map), is_top_frame = false) {
1703     if (!((f.is_compiled_frame() && !f.is_deoptimized_frame()) || (is_top_frame && (f.is_runtime_frame() || f.is_native_frame())))) {
1704       return false;
1705     }
1706   }
1707   return true;
1708 }
1709 #endif // ASSERT
1710 
1711 static inline freeze_result freeze_epilog(ContinuationWrapper& cont) {
1712   verify_continuation(cont.continuation());
1713   assert(!cont.is_empty(), "");
1714 
1715   log_develop_debug(continuations)("=== End of freeze cont ### #" INTPTR_FORMAT, cont.hash());
1716   return freeze_ok;
1717 }
1718 
1719 static freeze_result freeze_epilog(JavaThread* thread, ContinuationWrapper& cont, freeze_result res) {
1720   if (UNLIKELY(res != freeze_ok)) {
1721     JFR_ONLY(thread->set_last_freeze_fail_result(res);)
1722     verify_continuation(cont.continuation());
1723     log_develop_trace(continuations)("=== end of freeze (fail %d)", res);
1724     return res;
1725   }
1726 
1727   JVMTI_ONLY(jvmti_yield_cleanup(thread, cont)); // can safepoint
1728   return freeze_epilog(cont);
1729 }
1730 
1731 static freeze_result preempt_epilog(ContinuationWrapper& cont, freeze_result res, frame& old_last_frame) {
1732   if (UNLIKELY(res != freeze_ok)) {
1733     verify_continuation(cont.continuation());
1734     log_develop_trace(continuations)("=== end of freeze (fail %d)", res);
1735     return res;
1736   }
1737 
1738   patch_return_pc_with_preempt_stub(old_last_frame);
1739   cont.tail()->set_preempted(true);
1740 
1741   return freeze_epilog(cont);
1742 }
1743 
1744 template<typename ConfigT, bool preempt>
1745 static inline freeze_result freeze_internal(JavaThread* current, intptr_t* const sp) {
1746   assert(!current->has_pending_exception(), "");
1747 
1748 #ifdef ASSERT
1749   log_trace(continuations)("~~~~ freeze sp: " INTPTR_FORMAT "JavaThread: " INTPTR_FORMAT, p2i(current->last_continuation()->entry_sp()), p2i(current));
1750   log_frames(current);
1751 #endif
1752 
1753   CONT_JFR_ONLY(EventContinuationFreeze event;)
1754 
1755   ContinuationEntry* entry = current->last_continuation();
1756 
1757   oop oopCont = entry->cont_oop(current);
1758   assert(oopCont == current->last_continuation()->cont_oop(current), "");
1759   assert(ContinuationEntry::assert_entry_frame_laid_out(current), "");
1760 
1761   verify_continuation(oopCont);
1762   ContinuationWrapper cont(current, oopCont);
1763   log_develop_debug(continuations)("FREEZE #" INTPTR_FORMAT " " INTPTR_FORMAT, cont.hash(), p2i((oopDesc*)oopCont));
1764 
1765   assert(entry->is_virtual_thread() == (entry->scope(current) == java_lang_VirtualThread::vthread_scope()), "");
1766 
1767   assert(LockingMode == LM_LEGACY || (current->held_monitor_count() == 0 && current->jni_monitor_count() == 0),
1768          "Held monitor count should only be used for LM_LEGACY: " INT64_FORMAT " JNI: " INT64_FORMAT, (int64_t)current->held_monitor_count(), (int64_t)current->jni_monitor_count());
1769 
1770   if (entry->is_pinned() || current->held_monitor_count() > 0) {
1771     log_develop_debug(continuations)("PINNED due to critical section/hold monitor");
1772     verify_continuation(cont.continuation());
1773     freeze_result res = entry->is_pinned() ? freeze_pinned_cs : freeze_pinned_monitor;
1774     if (!preempt) {
1775       JFR_ONLY(current->set_last_freeze_fail_result(res);)
1776     }
1777     log_develop_trace(continuations)("=== end of freeze (fail %d)", res);
1778     // Avoid Thread.yield() loops without safepoint polls.
1779     if (SafepointMechanism::should_process(current) && !preempt) {
1780       cont.done(); // allow safepoint
1781       ThreadInVMfromJava tivmfj(current);
1782     }
1783     return res;
1784   }
1785 
1786   Freeze<ConfigT> freeze(current, cont, sp, preempt);
1787 
1788   assert(!current->cont_fastpath() || freeze.check_valid_fast_path(), "");
1789   bool fast = UseContinuationFastPath && current->cont_fastpath();
1790   if (fast && freeze.size_if_fast_freeze_available() > 0) {
1791     freeze.freeze_fast_existing_chunk();
1792     CONT_JFR_ONLY(freeze.jfr_info().post_jfr_event(&event, oopCont, current);)
1793     return !preempt ? freeze_epilog(cont) : preempt_epilog(cont, freeze_ok, freeze.last_frame());
1794   }
1795 
1796   if (preempt) {
1797     JvmtiSampledObjectAllocEventCollector jsoaec(false);
1798     freeze.set_jvmti_event_collector(&jsoaec);
1799 
1800     freeze_result res = fast ? freeze.try_freeze_fast() : freeze.freeze_slow();
1801 
1802     CONT_JFR_ONLY(freeze.jfr_info().post_jfr_event(&event, oopCont, current);)
1803     preempt_epilog(cont, res, freeze.last_frame());
1804     return res;
1805   }
1806 
1807   log_develop_trace(continuations)("chunk unavailable; transitioning to VM");
1808   assert(current == JavaThread::current(), "must be current thread");
1809   JRT_BLOCK
1810     // delays a possible JvmtiSampledObjectAllocEventCollector in alloc_chunk
1811     JvmtiSampledObjectAllocEventCollector jsoaec(false);
1812     freeze.set_jvmti_event_collector(&jsoaec);
1813 
1814     freeze_result res = fast ? freeze.try_freeze_fast() : freeze.freeze_slow();
1815 
1816     CONT_JFR_ONLY(freeze.jfr_info().post_jfr_event(&event, oopCont, current);)
1817     freeze_epilog(current, cont, res);
1818     cont.done(); // allow safepoint in the transition back to Java
1819     return res;
1820   JRT_BLOCK_END
1821 }
1822 
1823 static freeze_result is_pinned0(JavaThread* thread, oop cont_scope, bool safepoint) {
1824   ContinuationEntry* entry = thread->last_continuation();
1825   if (entry == nullptr) {
1826     return freeze_ok;
1827   }
1828   if (entry->is_pinned()) {
1829     return freeze_pinned_cs;
1830   } else if (thread->held_monitor_count() > 0) {
1831     return freeze_pinned_monitor;
1832   }
1833 
1834   RegisterMap map(thread,
1835                   RegisterMap::UpdateMap::include,
1836                   RegisterMap::ProcessFrames::skip,
1837                   RegisterMap::WalkContinuation::skip);
1838   map.set_include_argument_oops(false);
1839   frame f = thread->last_frame();
1840 
1841   if (!safepoint) {
1842     f = f.sender(&map); // this is the yield frame
1843   } else { // safepoint yield
1844 #if (defined(X86) || defined(AARCH64) || defined(RISCV64)) && !defined(ZERO)
1845     f.set_fp(f.real_fp()); // Instead of this, maybe in ContinuationWrapper::set_last_frame always use the real_fp?
1846 #else
1847     Unimplemented();
1848 #endif
1849     if (!Interpreter::contains(f.pc())) {
1850       assert(ContinuationHelper::Frame::is_stub(f.cb()), "must be");
1851       assert(f.oop_map() != nullptr, "must be");
1852       f.oop_map()->update_register_map(&f, &map); // we have callee-save registers in this case
1853     }
1854   }
1855 
1856   while (true) {
1857     if ((f.is_interpreted_frame() && f.interpreter_frame_method()->is_native()) || f.is_native_frame()) {
1858       return freeze_pinned_native;
1859     }
1860 
1861     f = f.sender(&map);
1862     if (!Continuation::is_frame_in_continuation(entry, f)) {
1863       oop scope = jdk_internal_vm_Continuation::scope(entry->cont_oop(thread));
1864       if (scope == cont_scope) {
1865         break;
1866       }
1867       intx monitor_count = entry->parent_held_monitor_count();
1868       entry = entry->parent();
1869       if (entry == nullptr) {
1870         break;
1871       }
1872       if (entry->is_pinned()) {
1873         return freeze_pinned_cs;
1874       } else if (monitor_count > 0) {
1875         return freeze_pinned_monitor;
1876       }
1877     }
1878   }
1879   return freeze_ok;
1880 }
1881 
1882 /////////////// THAW ////
1883 
1884 static int thaw_size(stackChunkOop chunk) {
1885   int size = chunk->max_thawing_size();
1886   size += frame::metadata_words; // For the top pc+fp in push_return_frame or top = stack_sp - frame::metadata_words in thaw_fast
1887   size += 2*frame::align_wiggle; // in case of alignments at the top and bottom
1888   return size;
1889 }
1890 
1891 // make room on the stack for thaw
1892 // returns the size in bytes, or 0 on failure
1893 static inline int prepare_thaw_internal(JavaThread* thread, bool return_barrier) {
1894   log_develop_trace(continuations)("~~~~ prepare_thaw return_barrier: %d", return_barrier);
1895 
1896   assert(thread == JavaThread::current(), "");
1897 
1898   ContinuationEntry* ce = thread->last_continuation();
1899   assert(ce != nullptr, "");
1900   oop continuation = ce->cont_oop(thread);
1901   assert(continuation == get_continuation(thread), "");
1902   verify_continuation(continuation);
1903 
1904   stackChunkOop chunk = jdk_internal_vm_Continuation::tail(continuation);
1905   assert(chunk != nullptr, "");
1906 
1907   // The tail can be empty because it might still be available for another freeze.
1908   // However, here we want to thaw, so we get rid of it (it will be GCed).
1909   if (UNLIKELY(chunk->is_empty())) {
1910     chunk = chunk->parent();
1911     assert(chunk != nullptr, "");
1912     assert(!chunk->is_empty(), "");
1913     jdk_internal_vm_Continuation::set_tail(continuation, chunk);
1914   }
1915 
1916   // Verification
1917   chunk->verify();
1918   assert(chunk->max_thawing_size() > 0, "chunk invariant violated; expected to not be empty");
1919 
1920   // Only make space for the last chunk because we only thaw from the last chunk
1921   int size = thaw_size(chunk) << LogBytesPerWord;
1922 
1923   const address bottom = (address)thread->last_continuation()->entry_sp();
1924   // 300 is an estimate for stack size taken for this native code, in addition to StackShadowPages
1925   // for the Java frames in the check below.
1926   if (!stack_overflow_check(thread, size + 300, bottom)) {
1927     return 0;
1928   }
1929 
1930   log_develop_trace(continuations)("prepare_thaw bottom: " INTPTR_FORMAT " top: " INTPTR_FORMAT " size: %d",
1931                               p2i(bottom), p2i(bottom - size), size);
1932   return size;
1933 }
1934 
1935 class ThawBase : public StackObj {
1936 protected:
1937   JavaThread* _thread;
1938   ContinuationWrapper& _cont;
1939   CONT_JFR_ONLY(FreezeThawJfrInfo _jfr_info;)
1940 
1941   intptr_t* _fastpath;
1942   bool _barriers;
1943   bool _preempted_case;
1944   intptr_t* _top_unextended_sp_before_thaw;
1945   int _align_size;
1946   DEBUG_ONLY(intptr_t* _top_stack_address);
1947 
1948   StackChunkFrameStream<ChunkFrames::Mixed> _stream;
1949 
1950   NOT_PRODUCT(int _frames;)
1951 
1952 protected:
1953   ThawBase(JavaThread* thread, ContinuationWrapper& cont) :
1954       _thread(thread), _cont(cont),
1955       _fastpath(nullptr) {
1956     DEBUG_ONLY(_top_unextended_sp_before_thaw = nullptr;)
1957     assert (cont.tail() != nullptr, "no last chunk");
1958     DEBUG_ONLY(_top_stack_address = _cont.entrySP() - thaw_size(cont.tail());)
1959   }
1960 
1961   void clear_chunk(stackChunkOop chunk);
1962   template<bool check_stub>
1963   int remove_top_compiled_frame_from_chunk(stackChunkOop chunk, int &argsize);
1964   int remove_scalarized_frames(StackChunkFrameStream<ChunkFrames::CompiledOnly>& scfs, stackChunkOop chunk, int &argsize);
1965   void copy_from_chunk(intptr_t* from, intptr_t* to, int size);
1966 
1967   void thaw_lockstack(stackChunkOop chunk);
1968 
1969   // fast path
1970   inline void prefetch_chunk_pd(void* start, int size_words);
1971   void patch_return(intptr_t* sp, bool is_last);
1972 
1973   intptr_t* handle_preempted_continuation(intptr_t* sp, Continuation::preempt_kind preempt_kind, bool fast_case);
1974   inline intptr_t* push_cleanup_continuation();
1975   void throw_interrupted_exception(JavaThread* current, frame& top);
1976 
1977   void recurse_thaw(const frame& heap_frame, frame& caller, int num_frames, bool top_on_preempt_case);
1978   void finish_thaw(frame& f);
1979 
1980 private:
1981   template<typename FKind> bool recurse_thaw_java_frame(frame& caller, int num_frames);
1982   void finalize_thaw(frame& entry, int argsize);
1983 
1984   inline bool seen_by_gc();
1985 
1986   inline void before_thaw_java_frame(const frame& hf, const frame& caller, bool bottom, int num_frame);
1987   inline void after_thaw_java_frame(const frame& f, bool bottom);
1988   inline void patch(frame& f, const frame& caller, bool bottom, bool augmented = false);
1989   void clear_bitmap_bits(address start, address end);
1990 
1991   NOINLINE void recurse_thaw_interpreted_frame(const frame& hf, frame& caller, int num_frames);
1992   void recurse_thaw_compiled_frame(const frame& hf, frame& caller, int num_frames, bool stub_caller);
1993   void recurse_thaw_stub_frame(const frame& hf, frame& caller, int num_frames);
1994   void recurse_thaw_native_frame(const frame& hf, frame& caller, int num_frames);
1995 
1996   void push_return_frame(frame& f);
1997   inline frame new_entry_frame();
1998   template<typename FKind> frame new_stack_frame(const frame& hf, frame& caller, bool bottom, int size_adjust = 0);
1999   inline void patch_pd(frame& f, const frame& sender);
2000   inline void patch_pd(frame& f, intptr_t* caller_sp);
2001   inline intptr_t* align(const frame& hf, intptr_t* frame_sp, frame& caller, bool bottom);
2002 
2003   void maybe_set_fastpath(intptr_t* sp) { if (sp > _fastpath) _fastpath = sp; }
2004 
2005   static inline void derelativize_interpreted_frame_metadata(const frame& hf, const frame& f);
2006 
2007  public:
2008   CONT_JFR_ONLY(FreezeThawJfrInfo& jfr_info() { return _jfr_info; })
2009 };
2010 
2011 template <typename ConfigT>
2012 class Thaw : public ThawBase {
2013 public:
2014   Thaw(JavaThread* thread, ContinuationWrapper& cont) : ThawBase(thread, cont) {}
2015 
2016   inline bool can_thaw_fast(stackChunkOop chunk) {
2017     return    !_barriers
2018            &&  _thread->cont_fastpath_thread_state()
2019            && !chunk->has_thaw_slowpath_condition()
2020            && !PreserveFramePointer;
2021   }
2022 
2023   inline intptr_t* thaw(Continuation::thaw_kind kind);
2024   template<bool check_stub = false>
2025   NOINLINE intptr_t* thaw_fast(stackChunkOop chunk);
2026   NOINLINE intptr_t* thaw_slow(stackChunkOop chunk, Continuation::thaw_kind kind);
2027   inline void patch_caller_links(intptr_t* sp, intptr_t* bottom);
2028 };
2029 
2030 template <typename ConfigT>
2031 inline intptr_t* Thaw<ConfigT>::thaw(Continuation::thaw_kind kind) {
2032   verify_continuation(_cont.continuation());
2033   assert(!jdk_internal_vm_Continuation::done(_cont.continuation()), "");
2034   assert(!_cont.is_empty(), "");
2035 
2036   stackChunkOop chunk = _cont.tail();
2037   assert(chunk != nullptr, "guaranteed by prepare_thaw");
2038   assert(!chunk->is_empty(), "guaranteed by prepare_thaw");
2039 
2040   _barriers = chunk->requires_barriers();
2041   return (LIKELY(can_thaw_fast(chunk))) ? thaw_fast(chunk)
2042                                         : thaw_slow(chunk, kind);
2043 }
2044 
2045 class ReconstructedStack : public StackObj {
2046   intptr_t* _base;  // _cont.entrySP(); // top of the entry frame
2047   int _thaw_size;
2048   int _argsize;
2049 public:
2050   ReconstructedStack(intptr_t* base, int thaw_size, int argsize)
2051   : _base(base), _thaw_size(thaw_size - (argsize == 0 ? frame::metadata_words_at_top : 0)), _argsize(argsize) {
2052     // The only possible source of misalignment is stack-passed arguments b/c compiled frames are 16-byte aligned.
2053     assert(argsize != 0 || (_base - _thaw_size) == ContinuationHelper::frame_align_pointer(_base - _thaw_size), "");
2054     // We're at most one alignment word away from entrySP
2055     assert(_base - 1 <= top() + total_size() + frame::metadata_words_at_bottom, "missed entry frame");
2056   }
2057 
2058   int entry_frame_extension() const { return _argsize + (_argsize > 0 ? frame::metadata_words_at_top : 0); }
2059 
2060   // top and bottom stack pointers
2061   intptr_t* sp() const { return ContinuationHelper::frame_align_pointer(_base - _thaw_size); }
2062   intptr_t* bottom_sp() const { return ContinuationHelper::frame_align_pointer(_base - entry_frame_extension()); }
2063 
2064   // several operations operate on the totality of the stack being reconstructed,
2065   // including the metadata words
2066   intptr_t* top() const { return sp() - frame::metadata_words_at_bottom;  }
2067   int total_size() const { return _thaw_size + frame::metadata_words_at_bottom; }
2068 };
2069 
2070 inline void ThawBase::clear_chunk(stackChunkOop chunk) {
2071   chunk->set_sp(chunk->bottom());
2072   chunk->set_max_thawing_size(0);
2073 }
2074 
2075 int ThawBase::remove_scalarized_frames(StackChunkFrameStream<ChunkFrames::CompiledOnly>& f, stackChunkOop chunk, int &argsize) {
2076   DEBUG_ONLY(intptr_t* const chunk_sp = chunk->start_address() + chunk->sp();)
2077   intptr_t* top = f.sp();
2078 
2079   while (f.cb()->as_nmethod_or_null()->needs_stack_repair()) {
2080     f.next(SmallRegisterMap::instance(), false /* stop */);
2081   }
2082   assert(!f.is_done(), "");
2083   assert(f.is_compiled(), "");
2084 
2085   intptr_t* bottom = f.sp() + f.cb()->frame_size();
2086   argsize = f.stack_argsize();
2087   int frames_size = bottom - top;
2088 
2089   f.next(SmallRegisterMap::instance(), true /* stop */);
2090   bool empty = f.is_done();
2091   assert(!empty || argsize == chunk->argsize(), "");
2092 
2093   if (empty) {
2094     clear_chunk(chunk);
2095   } else {
2096     chunk->set_sp(chunk->sp() + frames_size);
2097     chunk->set_max_thawing_size(chunk->max_thawing_size() - frames_size);
2098     // We set chunk->pc to the return pc into the next frame
2099     chunk->set_pc(f.pc());
2100 #ifdef ASSERT
2101     {
2102       intptr_t* retaddr_slot = (chunk_sp
2103                                 + frames_size
2104                                 - frame::sender_sp_ret_address_offset());
2105       assert(f.pc() == ContinuationHelper::return_address_at(retaddr_slot),
2106              "unexpected pc");
2107     }
2108 #endif
2109   }
2110   assert(empty == chunk->is_empty(), "");
2111   // returns the size required to store the frame on stack, and because it is a
2112   // compiled frame, it must include a copy of the arguments passed by the caller
2113   return frames_size + argsize + frame::metadata_words_at_top;
2114 }
2115 
2116 template<bool check_stub>
2117 int ThawBase::remove_top_compiled_frame_from_chunk(stackChunkOop chunk, int &argsize) {
2118   bool empty = false;
2119   StackChunkFrameStream<ChunkFrames::CompiledOnly> f(chunk);
2120   DEBUG_ONLY(intptr_t* const chunk_sp = chunk->start_address() + chunk->sp();)
2121   assert(chunk_sp == f.sp(), "");
2122   assert(chunk_sp == f.unextended_sp(), "");
2123 
2124   if (f.cb()->as_nmethod_or_null()->needs_stack_repair()) {
2125     return remove_scalarized_frames(f, chunk, argsize);
2126   }
2127 
2128   int frame_size = f.cb()->frame_size();
2129   argsize = f.stack_argsize();
2130 
2131   assert(!f.is_stub() || check_stub, "");
2132   if (check_stub && f.is_stub()) {
2133     // If we don't thaw the top compiled frame too, after restoring the saved
2134     // registers back in Java, we would hit the return barrier to thaw one more
2135     // frame effectively overwriting the restored registers during that call.
2136     f.next(SmallRegisterMap::instance(), true /* stop */);
2137     assert(!f.is_done(), "");
2138 
2139     f.get_cb();
2140     assert(f.is_compiled(), "");
2141     frame_size += f.cb()->frame_size();
2142     argsize = f.stack_argsize();
2143 
2144     if (f.cb()->as_nmethod()->is_marked_for_deoptimization()) {
2145       // The caller of the runtime stub when the continuation is preempted is not at a
2146       // Java call instruction, and so cannot rely on nmethod patching for deopt.
2147       log_develop_trace(continuations)("Deoptimizing runtime stub caller");
2148       f.to_frame().deoptimize(nullptr); // the null thread simply avoids the assertion in deoptimize which we're not set up for
2149     }
2150   }
2151 
2152   f.next(SmallRegisterMap::instance(), true /* stop */);
2153   empty = f.is_done();
2154   assert(!empty || argsize == chunk->argsize(), "");
2155 
2156   if (empty) {
2157     clear_chunk(chunk);
2158   } else {
2159     chunk->set_sp(chunk->sp() + frame_size);
2160     chunk->set_max_thawing_size(chunk->max_thawing_size() - frame_size);
2161     // We set chunk->pc to the return pc into the next frame
2162     chunk->set_pc(f.pc());
2163 #ifdef ASSERT
2164     {
2165       intptr_t* retaddr_slot = (chunk_sp
2166                                 + frame_size
2167                                 - frame::sender_sp_ret_address_offset());
2168       assert(f.pc() == ContinuationHelper::return_address_at(retaddr_slot),
2169              "unexpected pc");
2170     }
2171 #endif
2172   }
2173   assert(empty == chunk->is_empty(), "");
2174   // returns the size required to store the frame on stack, and because it is a
2175   // compiled frame, it must include a copy of the arguments passed by the caller
2176   return frame_size + argsize + frame::metadata_words_at_top;
2177 }
2178 
2179 void ThawBase::thaw_lockstack(stackChunkOop chunk) {
2180   int lockStackSize = chunk->lockstack_size();
2181   assert(lockStackSize > 0 && lockStackSize <= LockStack::CAPACITY, "");
2182 
2183   oop tmp_lockstack[LockStack::CAPACITY];
2184   chunk->transfer_lockstack(tmp_lockstack, _barriers);
2185   _thread->lock_stack().move_from_address(tmp_lockstack, lockStackSize);
2186 
2187   chunk->set_lockstack_size(0);
2188   chunk->set_has_lockstack(false);
2189 }
2190 
2191 void ThawBase::copy_from_chunk(intptr_t* from, intptr_t* to, int size) {
2192   assert(to >= _top_stack_address, "overwrote past thawing space"
2193     " to: " INTPTR_FORMAT " top_address: " INTPTR_FORMAT, p2i(to), p2i(_top_stack_address));
2194   assert(to + size <= _cont.entrySP(), "overwrote past thawing space");
2195   _cont.tail()->copy_from_chunk_to_stack(from, to, size);
2196   CONT_JFR_ONLY(_jfr_info.record_size_copied(size);)
2197 }
2198 
2199 void ThawBase::patch_return(intptr_t* sp, bool is_last) {
2200   log_develop_trace(continuations)("thaw_fast patching -- sp: " INTPTR_FORMAT, p2i(sp));
2201 
2202   address pc = !is_last ? StubRoutines::cont_returnBarrier() : _cont.entryPC();
2203   ContinuationHelper::patch_return_address_at(
2204     sp - frame::sender_sp_ret_address_offset(),
2205     pc);
2206 }
2207 
2208 template <typename ConfigT>
2209 template<bool check_stub>
2210 NOINLINE intptr_t* Thaw<ConfigT>::thaw_fast(stackChunkOop chunk) {
2211   assert(chunk == _cont.tail(), "");
2212   assert(!chunk->has_mixed_frames(), "");
2213   assert(!chunk->requires_barriers(), "");
2214   assert(!chunk->has_bitmap(), "");
2215   assert(!_thread->is_interp_only_mode(), "");
2216 
2217   LogTarget(Trace, continuations) lt;
2218   if (lt.develop_is_enabled()) {
2219     LogStream ls(lt);
2220     ls.print_cr("thaw_fast");
2221     chunk->print_on(true, &ls);
2222   }
2223 
2224   // Below this heuristic, we thaw the whole chunk, above it we thaw just one frame.
2225   static const int threshold = 500; // words
2226 
2227   const int full_chunk_size = chunk->stack_size() - chunk->sp(); // this initial size could be reduced if it's a partial thaw
2228   int argsize, thaw_size;
2229 
2230   intptr_t* const chunk_sp = chunk->start_address() + chunk->sp();
2231 
2232   bool partial, empty;
2233   if (LIKELY(!TEST_THAW_ONE_CHUNK_FRAME && (full_chunk_size < threshold))) {
2234     prefetch_chunk_pd(chunk->start_address(), full_chunk_size); // prefetch anticipating memcpy starting at highest address
2235 
2236     partial = false;
2237     argsize = chunk->argsize(); // must be called *before* clearing the chunk
2238     clear_chunk(chunk);
2239     thaw_size = full_chunk_size;
2240     empty = true;
2241   } else { // thaw a single frame
2242     partial = true;
2243     thaw_size = remove_top_compiled_frame_from_chunk<check_stub>(chunk, argsize);
2244     empty = chunk->is_empty();
2245   }
2246 
2247   // Are we thawing the last frame(s) in the continuation
2248   const bool is_last = empty && chunk->parent() == nullptr;
2249   assert(!is_last || argsize == 0, "");
2250 
2251   log_develop_trace(continuations)("thaw_fast partial: %d is_last: %d empty: %d size: %d argsize: %d entrySP: " PTR_FORMAT,
2252                               partial, is_last, empty, thaw_size, argsize, p2i(_cont.entrySP()));
2253 
2254   ReconstructedStack rs(_cont.entrySP(), thaw_size, argsize);
2255 
2256   // also copy metadata words at frame bottom
2257   copy_from_chunk(chunk_sp - frame::metadata_words_at_bottom, rs.top(), rs.total_size());
2258 
2259   // update the ContinuationEntry
2260   _cont.set_argsize(argsize);
2261   log_develop_trace(continuations)("setting entry argsize: %d", _cont.argsize());
2262   assert(rs.bottom_sp() == _cont.entry()->bottom_sender_sp(), "");
2263 
2264   // install the return barrier if not last frame, or the entry's pc if last
2265   patch_return(rs.bottom_sp(), is_last);
2266 
2267   // insert the back links from callee to caller frames
2268   patch_caller_links(rs.top(), rs.top() + rs.total_size());
2269 
2270   assert(is_last == _cont.is_empty(), "");
2271   assert(_cont.chunk_invariant(), "");
2272 
2273 #if CONT_JFR
2274   EventContinuationThawFast e;
2275   if (e.should_commit()) {
2276     e.set_id(cast_from_oop<u8>(chunk));
2277     e.set_size(thaw_size << LogBytesPerWord);
2278     e.set_full(!partial);
2279     e.commit();
2280   }
2281 #endif
2282 
2283 #ifdef ASSERT
2284   set_anchor(_thread, rs.sp());
2285   log_frames(_thread);
2286   if (LoomDeoptAfterThaw) {
2287     do_deopt_after_thaw(_thread);
2288   }
2289   clear_anchor(_thread);
2290 #endif
2291 
2292   return rs.sp();
2293 }
2294 
2295 inline bool ThawBase::seen_by_gc() {
2296   return _barriers || _cont.tail()->is_gc_mode();
2297 }
2298 
2299 static inline void relativize_chunk_concurrently(stackChunkOop chunk) {
2300 #if INCLUDE_ZGC || INCLUDE_SHENANDOAHGC
2301   if (UseZGC || UseShenandoahGC) {
2302     chunk->relativize_derived_pointers_concurrently();
2303   }
2304 #endif
2305 }
2306 
2307 template <typename ConfigT>
2308 NOINLINE intptr_t* Thaw<ConfigT>::thaw_slow(stackChunkOop chunk, Continuation::thaw_kind kind) {
2309   Continuation::preempt_kind preempt_kind;
2310   bool retry_fast_path = false;
2311 
2312   _preempted_case = chunk->preempted();
2313   if (_preempted_case) {
2314     ObjectWaiter* waiter = java_lang_VirtualThread::objectWaiter(_thread->vthread());
2315     if (waiter != nullptr) {
2316       // Mounted again after preemption. Resume the pending monitor operation,
2317       // which will be either a monitorenter or Object.wait() call.
2318       ObjectMonitor* mon = waiter->monitor();
2319       preempt_kind = waiter->is_wait() ? Continuation::freeze_on_wait : Continuation::freeze_on_monitorenter;
2320 
2321       bool mon_acquired = mon->resume_operation(_thread, waiter, _cont);
2322       assert(!mon_acquired || mon->has_owner(_thread), "invariant");
2323       if (!mon_acquired) {
2324         // Failed to acquire monitor. Return to enterSpecial to unmount again.
2325         return push_cleanup_continuation();
2326       }
2327       chunk = _cont.tail();  // reload oop in case of safepoint in resume_operation (if posting JVMTI events).
2328     } else {
2329       // Preemption cancelled in moniterenter case. We actually acquired
2330       // the monitor after freezing all frames so nothing to do.
2331       preempt_kind = Continuation::freeze_on_monitorenter;
2332     }
2333     // Call this first to avoid racing with GC threads later when modifying the chunk flags.
2334     relativize_chunk_concurrently(chunk);
2335     chunk->set_preempted(false);
2336     retry_fast_path = true;
2337   } else {
2338     relativize_chunk_concurrently(chunk);
2339   }
2340 
2341   // On first thaw after freeze restore oops to the lockstack if any.
2342   assert(chunk->lockstack_size() == 0 || kind == Continuation::thaw_top, "");
2343   if (kind == Continuation::thaw_top && chunk->lockstack_size() > 0) {
2344     thaw_lockstack(chunk);
2345     retry_fast_path = true;
2346   }
2347 
2348   // Retry the fast path now that we possibly cleared the FLAG_HAS_LOCKSTACK
2349   // and FLAG_PREEMPTED flags from the stackChunk.
2350   if (retry_fast_path && can_thaw_fast(chunk)) {
2351     intptr_t* sp = thaw_fast<true>(chunk);
2352     if (_preempted_case) {
2353       return handle_preempted_continuation(sp, preempt_kind, true /* fast_case */);
2354     }
2355     return sp;
2356   }
2357 
2358   LogTarget(Trace, continuations) lt;
2359   if (lt.develop_is_enabled()) {
2360     LogStream ls(lt);
2361     ls.print_cr("thaw slow return_barrier: %d " INTPTR_FORMAT, kind, p2i(chunk));
2362     chunk->print_on(true, &ls);
2363   }
2364 
2365 #if CONT_JFR
2366   EventContinuationThawSlow e;
2367   if (e.should_commit()) {
2368     e.set_id(cast_from_oop<u8>(_cont.continuation()));
2369     e.commit();
2370   }
2371 #endif
2372 
2373   DEBUG_ONLY(_frames = 0;)
2374   _align_size = 0;
2375   int num_frames = kind == Continuation::thaw_top ? 2 : 1;
2376 
2377   _stream = StackChunkFrameStream<ChunkFrames::Mixed>(chunk);
2378   _top_unextended_sp_before_thaw = _stream.unextended_sp();
2379 
2380   frame heap_frame = _stream.to_frame();
2381   if (lt.develop_is_enabled()) {
2382     LogStream ls(lt);
2383     ls.print_cr("top hframe before (thaw):");
2384     assert(heap_frame.is_heap_frame(), "should have created a relative frame");
2385     heap_frame.print_value_on(&ls);
2386   }
2387 
2388   frame caller; // the thawed caller on the stack
2389   recurse_thaw(heap_frame, caller, num_frames, _preempted_case);
2390   finish_thaw(caller); // caller is now the topmost thawed frame
2391   _cont.write();
2392 
2393   assert(_cont.chunk_invariant(), "");
2394 
2395   JVMTI_ONLY(invalidate_jvmti_stack(_thread));
2396 
2397   _thread->set_cont_fastpath(_fastpath);
2398 
2399   intptr_t* sp = caller.sp();
2400 
2401   if (_preempted_case) {
2402     return handle_preempted_continuation(sp, preempt_kind, false /* fast_case */);
2403   }
2404   return sp;
2405 }
2406 
2407 void ThawBase::recurse_thaw(const frame& heap_frame, frame& caller, int num_frames, bool top_on_preempt_case) {
2408   log_develop_debug(continuations)("thaw num_frames: %d", num_frames);
2409   assert(!_cont.is_empty(), "no more frames");
2410   assert(num_frames > 0, "");
2411   assert(!heap_frame.is_empty(), "");
2412 
2413   if (top_on_preempt_case && (heap_frame.is_native_frame() || heap_frame.is_runtime_frame())) {
2414     heap_frame.is_native_frame() ? recurse_thaw_native_frame(heap_frame, caller, 2) : recurse_thaw_stub_frame(heap_frame, caller, 2);
2415   } else if (!heap_frame.is_interpreted_frame()) {
2416     recurse_thaw_compiled_frame(heap_frame, caller, num_frames, false);
2417   } else {
2418     recurse_thaw_interpreted_frame(heap_frame, caller, num_frames);
2419   }
2420 }
2421 
2422 template<typename FKind>
2423 bool ThawBase::recurse_thaw_java_frame(frame& caller, int num_frames) {
2424   assert(num_frames > 0, "");
2425 
2426   DEBUG_ONLY(_frames++;)
2427 
2428   int argsize = _stream.stack_argsize();
2429   CodeBlob* cb = _stream.cb();
2430 
2431   _stream.next(SmallRegisterMap::instance());
2432   assert(_stream.to_frame().is_empty() == _stream.is_done(), "");
2433 
2434   // We never leave a compiled caller of an interpreted frame as the top frame in the chunk
2435   // as it makes detecting that situation and adjusting unextended_sp tricky. We also always
2436   // thaw the caller of a frame that needs_stack_repair, as it would otherwise complicate things:
2437   // - Regardless of whether the frame was extended or not, we would need to copy the right arg
2438   //   size if its greater than the one given by the normal method signature (non-scalarized).
2439   // - If the frame was indeed extended, leaving its caller as the top frame would complicate walking
2440   //   the chunk (we need unextended_sp, but we only have sp).
2441   if (num_frames == 1 && !_stream.is_done() && ((FKind::interpreted && _stream.is_compiled()) || (FKind::compiled && cb->as_nmethod_or_null()->needs_stack_repair()))) {
2442     log_develop_trace(continuations)("thawing extra compiled frame to not leave a compiled interpreted-caller at top");
2443     num_frames++;
2444   }
2445 
2446   if (num_frames == 1 || _stream.is_done()) { // end recursion
2447     finalize_thaw(caller, FKind::interpreted ? 0 : argsize);
2448     return true; // bottom
2449   } else { // recurse
2450     recurse_thaw(_stream.to_frame(), caller, num_frames - 1, false /* top_on_preempt_case */);
2451     return false;
2452   }
2453 }
2454 
2455 void ThawBase::finalize_thaw(frame& entry, int argsize) {
2456   stackChunkOop chunk = _cont.tail();
2457 
2458   if (!_stream.is_done()) {
2459     assert(_stream.sp() >= chunk->sp_address(), "");
2460     chunk->set_sp(chunk->to_offset(_stream.sp()));
2461     chunk->set_pc(_stream.pc());
2462   } else {
2463     chunk->set_sp(chunk->bottom());
2464     chunk->set_pc(nullptr);
2465   }
2466   assert(_stream.is_done() == chunk->is_empty(), "");
2467 
2468   int total_thawed = pointer_delta_as_int(_stream.unextended_sp(), _top_unextended_sp_before_thaw);
2469   chunk->set_max_thawing_size(chunk->max_thawing_size() - total_thawed);
2470 
2471   _cont.set_argsize(argsize);
2472   entry = new_entry_frame();
2473 
2474   assert(entry.sp() == _cont.entrySP(), "");
2475   assert(Continuation::is_continuation_enterSpecial(entry), "");
2476   assert(_cont.is_entry_frame(entry), "");
2477 }
2478 
2479 inline void ThawBase::before_thaw_java_frame(const frame& hf, const frame& caller, bool bottom, int num_frame) {
2480   LogTarget(Trace, continuations) lt;
2481   if (lt.develop_is_enabled()) {
2482     LogStream ls(lt);
2483     ls.print_cr("======== THAWING FRAME: %d", num_frame);
2484     assert(hf.is_heap_frame(), "should be");
2485     hf.print_value_on(&ls);
2486   }
2487   assert(bottom == _cont.is_entry_frame(caller), "bottom: %d is_entry_frame: %d", bottom, _cont.is_entry_frame(hf));
2488 }
2489 
2490 inline void ThawBase::after_thaw_java_frame(const frame& f, bool bottom) {
2491 #ifdef ASSERT
2492   LogTarget(Trace, continuations) lt;
2493   if (lt.develop_is_enabled()) {
2494     LogStream ls(lt);
2495     ls.print_cr("thawed frame:");
2496     print_frame_layout(f, false, &ls); // f.print_on(&ls);
2497   }
2498 #endif
2499 }
2500 
2501 inline void ThawBase::patch(frame& f, const frame& caller, bool bottom, bool augmented) {
2502   assert(!bottom || caller.fp() == _cont.entryFP(), "");
2503   if (bottom) {
2504     ContinuationHelper::Frame::patch_pc(caller, _cont.is_empty() ? caller.pc()
2505                                                                  : StubRoutines::cont_returnBarrier());
2506   } else if (caller.is_compiled_frame()){
2507     // caller might have been deoptimized during thaw but we've overwritten the return address when copying f from the heap.
2508     // If the caller is not deoptimized, pc is unchanged.
2509     ContinuationHelper::Frame::patch_pc(caller, caller.raw_pc(), augmented /*callee_augmented*/);
2510   }
2511 
2512   patch_pd(f, caller);
2513 
2514   if (f.is_interpreted_frame()) {
2515     ContinuationHelper::InterpretedFrame::patch_sender_sp(f, caller);
2516   }
2517 
2518   assert(!bottom || !_cont.is_empty() || Continuation::is_continuation_entry_frame(f, nullptr), "");
2519   assert(!bottom || (_cont.is_empty() != Continuation::is_cont_barrier_frame(f)), "");
2520 }
2521 
2522 void ThawBase::clear_bitmap_bits(address start, address end) {
2523   assert(is_aligned(start, wordSize), "should be aligned: " PTR_FORMAT, p2i(start));
2524   assert(is_aligned(end, VMRegImpl::stack_slot_size), "should be aligned: " PTR_FORMAT, p2i(end));
2525 
2526   // we need to clear the bits that correspond to arguments as they reside in the caller frame
2527   // or they will keep objects that are otherwise unreachable alive.
2528 
2529   // Align `end` if UseCompressedOops is not set to avoid UB when calculating the bit index, since
2530   // `end` could be at an odd number of stack slots from `start`, i.e might not be oop aligned.
2531   // If that's the case the bit range corresponding to the last stack slot should not have bits set
2532   // anyways and we assert that before returning.
2533   address effective_end = UseCompressedOops ? end : align_down(end, wordSize);
2534   log_develop_trace(continuations)("clearing bitmap for " INTPTR_FORMAT " - " INTPTR_FORMAT, p2i(start), p2i(effective_end));
2535   stackChunkOop chunk = _cont.tail();
2536   chunk->bitmap().clear_range(chunk->bit_index_for(start), chunk->bit_index_for(effective_end));
2537   assert(effective_end == end || !chunk->bitmap().at(chunk->bit_index_for(effective_end)), "bit should not be set");
2538 }
2539 
2540 intptr_t* ThawBase::handle_preempted_continuation(intptr_t* sp, Continuation::preempt_kind preempt_kind, bool fast_case) {
2541   assert(preempt_kind == Continuation::freeze_on_wait || preempt_kind == Continuation::freeze_on_monitorenter, "");
2542   frame top(sp);
2543   assert(top.pc() == *(address*)(sp - frame::sender_sp_ret_address_offset()), "");
2544 
2545 #if INCLUDE_JVMTI
2546   // Finish the VTMS transition.
2547   assert(_thread->is_in_VTMS_transition(), "must be");
2548   bool is_vthread = Continuation::continuation_scope(_cont.continuation()) == java_lang_VirtualThread::vthread_scope();
2549   if (is_vthread) {
2550     if (JvmtiVTMSTransitionDisabler::VTMS_notify_jvmti_events()) {
2551       jvmti_mount_end(_thread, _cont, top);
2552     } else {
2553       _thread->set_is_in_VTMS_transition(false);
2554       java_lang_Thread::set_is_in_VTMS_transition(_thread->vthread(), false);
2555     }
2556   }
2557 #endif
2558 
2559   if (fast_case) {
2560     // If we thawed in the slow path the runtime stub/native wrapper frame already
2561     // has the correct fp (see ThawBase::new_stack_frame). On the fast path though,
2562     // we copied the original fp at the time of freeze which now will have to be fixed.
2563     assert(top.is_runtime_frame() || top.is_native_frame(), "");
2564     int fsize = top.cb()->frame_size();
2565     patch_pd(top, sp + fsize);
2566   }
2567 
2568   if (preempt_kind == Continuation::freeze_on_wait) {
2569     // Check now if we need to throw IE exception.
2570     if (_thread->pending_interrupted_exception()) {
2571       throw_interrupted_exception(_thread, top);
2572       _thread->set_pending_interrupted_exception(false);
2573     }
2574   } else if (top.is_runtime_frame()) {
2575     // The continuation might now run on a different platform thread than the previous time so
2576     // we need to adjust the current thread saved in the stub frame before restoring registers.
2577     JavaThread** thread_addr = frame::saved_thread_address(top);
2578     if (thread_addr != nullptr) *thread_addr = _thread;
2579   }
2580   return sp;
2581 }
2582 
2583 void ThawBase::throw_interrupted_exception(JavaThread* current, frame& top) {
2584   ContinuationWrapper::SafepointOp so(current, _cont);
2585   // Since we might safepoint set the anchor so that the stack can be walked.
2586   set_anchor(current, top.sp());
2587   JRT_BLOCK
2588     THROW(vmSymbols::java_lang_InterruptedException());
2589   JRT_BLOCK_END
2590   clear_anchor(current);
2591 }
2592 
2593 NOINLINE void ThawBase::recurse_thaw_interpreted_frame(const frame& hf, frame& caller, int num_frames) {
2594   assert(hf.is_interpreted_frame(), "");
2595 
2596   if (UNLIKELY(seen_by_gc())) {
2597     _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>(_stream, SmallRegisterMap::instance());
2598   }
2599 
2600   const bool is_bottom_frame = recurse_thaw_java_frame<ContinuationHelper::InterpretedFrame>(caller, num_frames);
2601 
2602   DEBUG_ONLY(before_thaw_java_frame(hf, caller, is_bottom_frame, num_frames);)
2603 
2604   _align_size += frame::align_wiggle; // possible added alignment for internal interpreted frame alignment om AArch64
2605 
2606   frame f = new_stack_frame<ContinuationHelper::InterpretedFrame>(hf, caller, is_bottom_frame);
2607 
2608   intptr_t* const stack_frame_top = f.sp() + frame::metadata_words_at_top;
2609   intptr_t* const stack_frame_bottom = ContinuationHelper::InterpretedFrame::frame_bottom(f);
2610   intptr_t* const heap_frame_top = hf.unextended_sp() + frame::metadata_words_at_top;
2611   intptr_t* const heap_frame_bottom = ContinuationHelper::InterpretedFrame::frame_bottom(hf);
2612 
2613   assert(hf.is_heap_frame(), "should be");
2614   assert(!f.is_heap_frame(), "should not be");
2615 
2616   const int fsize = pointer_delta_as_int(heap_frame_bottom, heap_frame_top);
2617   assert((stack_frame_bottom == stack_frame_top + fsize), "");
2618 
2619   // Some architectures (like AArch64/PPC64/RISC-V) add padding between the locals and the fixed_frame to keep the fp 16-byte-aligned.
2620   // On those architectures we freeze the padding in order to keep the same fp-relative offsets in the fixed_frame.
2621   copy_from_chunk(heap_frame_top, stack_frame_top, fsize);
2622 
2623   // Make sure the relativized locals is already set.
2624   assert(f.interpreter_frame_local_at(0) == stack_frame_bottom - 1, "invalid frame bottom");
2625 
2626   derelativize_interpreted_frame_metadata(hf, f);
2627   patch(f, caller, is_bottom_frame);
2628 
2629   assert(f.is_interpreted_frame_valid(_cont.thread()), "invalid thawed frame");
2630   assert(stack_frame_bottom <= ContinuationHelper::Frame::frame_top(caller), "");
2631 
2632   CONT_JFR_ONLY(_jfr_info.record_interpreted_frame();)
2633 
2634   maybe_set_fastpath(f.sp());
2635 
2636   Method* m = hf.interpreter_frame_method();
2637   assert(!m->is_native() || !is_bottom_frame, "should be top frame of thaw_top case; missing caller frame");
2638   const int locals = m->max_locals();
2639 
2640   if (!is_bottom_frame) {
2641     // can only fix caller once this frame is thawed (due to callee saved regs)
2642     _cont.tail()->fix_thawed_frame(caller, SmallRegisterMap::instance());
2643   } else if (_cont.tail()->has_bitmap() && locals > 0) {
2644     assert(hf.is_heap_frame(), "should be");
2645     address start = (address)(heap_frame_bottom - locals);
2646     address end = (address)heap_frame_bottom;
2647     clear_bitmap_bits(start, end);
2648   }
2649 
2650   DEBUG_ONLY(after_thaw_java_frame(f, is_bottom_frame);)
2651   caller = f;
2652 }
2653 
2654 void ThawBase::recurse_thaw_compiled_frame(const frame& hf, frame& caller, int num_frames, bool stub_caller) {
2655   assert(hf.is_compiled_frame(), "");
2656   assert(_preempted_case || !stub_caller, "stub caller not at preemption");
2657 
2658   if (!stub_caller && UNLIKELY(seen_by_gc())) { // recurse_thaw_stub_frame already invoked our barriers with a full regmap
2659     _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>(_stream, SmallRegisterMap::instance());
2660   }
2661 
2662   const bool is_bottom_frame = recurse_thaw_java_frame<ContinuationHelper::CompiledFrame>(caller, num_frames);
2663 
2664   DEBUG_ONLY(before_thaw_java_frame(hf, caller, is_bottom_frame, num_frames);)
2665 
2666   assert(caller.sp() == caller.unextended_sp(), "");
2667 
2668   if ((!is_bottom_frame && caller.is_interpreted_frame()) || (is_bottom_frame && Interpreter::contains(_cont.tail()->pc()))) {
2669     _align_size += frame::align_wiggle; // we add one whether or not we've aligned because we add it in recurse_freeze_compiled_frame
2670   }
2671 
2672   int fsize = 0;
2673   int added_argsize = 0;
2674   bool augmented = hf.was_augmented_on_entry(fsize);
2675   if (!augmented) {
2676     added_argsize = (is_bottom_frame || caller.is_interpreted_frame()) ? hf.compiled_frame_stack_argsize() : 0;
2677     fsize += added_argsize;
2678   }
2679   assert(!is_bottom_frame || !augmented, "");
2680 
2681 
2682   // new_stack_frame must construct the resulting frame using hf.pc() rather than hf.raw_pc() because the frame is not
2683   // yet laid out in the stack, and so the original_pc is not stored in it.
2684   // As a result, f.is_deoptimized_frame() is always false and we must test hf to know if the frame is deoptimized.
2685   frame f = new_stack_frame<ContinuationHelper::CompiledFrame>(hf, caller, is_bottom_frame, augmented ? fsize - hf.cb()->frame_size() : 0);
2686   assert(f.cb()->frame_size() == (int)(caller.sp() - f.sp()), "");
2687 
2688   intptr_t* const stack_frame_top = f.sp();
2689   intptr_t* const heap_frame_top = hf.unextended_sp();
2690   intptr_t* from = heap_frame_top - frame::metadata_words_at_bottom;
2691   intptr_t* to   = stack_frame_top - frame::metadata_words_at_bottom;
2692   // copy metadata, except the metadata at the top of the (unextended) entry frame
2693   int sz = fsize + frame::metadata_words_at_bottom + (is_bottom_frame && added_argsize == 0 ? 0 : frame::metadata_words_at_top);
2694 
2695   // If we're the bottom-most thawed frame, we're writing to within one word from entrySP
2696   // (we might have one padding word for alignment)
2697   assert(!is_bottom_frame || (_cont.entrySP() - 1 <= to + sz && to + sz <= _cont.entrySP()), "");
2698   assert(!is_bottom_frame || hf.compiled_frame_stack_argsize() != 0 || (to + sz && to + sz == _cont.entrySP()), "");
2699 
2700   copy_from_chunk(from, to, sz); // copying good oops because we invoked barriers above
2701 
2702   patch(f, caller, is_bottom_frame, augmented);
2703 
2704   // f.is_deoptimized_frame() is always false and we must test hf.is_deoptimized_frame() (see comment above)
2705   assert(!f.is_deoptimized_frame(), "");
2706   if (hf.is_deoptimized_frame()) {
2707     maybe_set_fastpath(f.sp());
2708   } else if (_thread->is_interp_only_mode()
2709               || (stub_caller && f.cb()->as_nmethod()->is_marked_for_deoptimization())) {
2710     // The caller of the safepoint stub when the continuation is preempted is not at a call instruction, and so
2711     // cannot rely on nmethod patching for deopt.
2712     assert(_thread->is_interp_only_mode() || stub_caller, "expected a stub-caller");
2713 
2714     log_develop_trace(continuations)("Deoptimizing thawed frame");
2715     DEBUG_ONLY(ContinuationHelper::Frame::patch_pc(f, nullptr));
2716 
2717     f.deoptimize(nullptr); // the null thread simply avoids the assertion in deoptimize which we're not set up for
2718     assert(f.is_deoptimized_frame(), "");
2719     assert(ContinuationHelper::Frame::is_deopt_return(f.raw_pc(), f), "");
2720     maybe_set_fastpath(f.sp());
2721   }
2722 
2723   if (!is_bottom_frame) {
2724     // can only fix caller once this frame is thawed (due to callee saved regs); this happens on the stack
2725     _cont.tail()->fix_thawed_frame(caller, SmallRegisterMap::instance());
2726   } else if (_cont.tail()->has_bitmap() && added_argsize > 0) {
2727     address start = (address)(heap_frame_top + ContinuationHelper::CompiledFrame::size(hf) + frame::metadata_words_at_top);
2728     int stack_args_slots = f.cb()->as_nmethod()->num_stack_arg_slots(false /* rounded */);
2729     int argsize_in_bytes = stack_args_slots * VMRegImpl::stack_slot_size;
2730     clear_bitmap_bits(start, start + argsize_in_bytes);
2731   }
2732 
2733   DEBUG_ONLY(after_thaw_java_frame(f, is_bottom_frame);)
2734   caller = f;
2735 }
2736 
2737 void ThawBase::recurse_thaw_stub_frame(const frame& hf, frame& caller, int num_frames) {
2738   DEBUG_ONLY(_frames++;)
2739 
2740   if (UNLIKELY(seen_by_gc())) {
2741     // Process the stub's caller here since we might need the full map.
2742     RegisterMap map(nullptr,
2743                     RegisterMap::UpdateMap::include,
2744                     RegisterMap::ProcessFrames::skip,
2745                     RegisterMap::WalkContinuation::skip);
2746     map.set_include_argument_oops(false);
2747     _stream.next(&map);
2748     assert(!_stream.is_done(), "");
2749     _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>(_stream, &map);
2750   } else {
2751     _stream.next(SmallRegisterMap::instance());
2752     assert(!_stream.is_done(), "");
2753   }
2754 
2755   recurse_thaw_compiled_frame(_stream.to_frame(), caller, num_frames, true);
2756 
2757   assert(caller.is_compiled_frame(), "");
2758   assert(caller.sp() == caller.unextended_sp(), "");
2759 
2760   DEBUG_ONLY(before_thaw_java_frame(hf, caller, false /*is_bottom_frame*/, num_frames);)
2761 
2762   frame f = new_stack_frame<ContinuationHelper::StubFrame>(hf, caller, false);
2763   intptr_t* stack_frame_top = f.sp();
2764   intptr_t* heap_frame_top = hf.sp();
2765   int fsize = ContinuationHelper::StubFrame::size(hf);
2766 
2767   copy_from_chunk(heap_frame_top - frame::metadata_words, stack_frame_top - frame::metadata_words,
2768                   fsize + frame::metadata_words);
2769 
2770   patch(f, caller, false /*is_bottom_frame*/);
2771 
2772   // can only fix caller once this frame is thawed (due to callee saved regs)
2773   RegisterMap map(nullptr,
2774                   RegisterMap::UpdateMap::include,
2775                   RegisterMap::ProcessFrames::skip,
2776                   RegisterMap::WalkContinuation::skip);
2777   map.set_include_argument_oops(false);
2778   f.oop_map()->update_register_map(&f, &map);
2779   ContinuationHelper::update_register_map_with_callee(caller, &map);
2780   _cont.tail()->fix_thawed_frame(caller, &map);
2781 
2782   DEBUG_ONLY(after_thaw_java_frame(f, false /*is_bottom_frame*/);)
2783   caller = f;
2784 }
2785 
2786 void ThawBase::recurse_thaw_native_frame(const frame& hf, frame& caller, int num_frames) {
2787   assert(hf.is_native_frame(), "");
2788   assert(_preempted_case && hf.cb()->as_nmethod()->method()->is_object_wait0(), "");
2789 
2790   if (UNLIKELY(seen_by_gc())) { // recurse_thaw_stub_frame already invoked our barriers with a full regmap
2791     _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>(_stream, SmallRegisterMap::instance());
2792   }
2793 
2794   const bool is_bottom_frame = recurse_thaw_java_frame<ContinuationHelper::NativeFrame>(caller, num_frames);
2795   assert(!is_bottom_frame, "");
2796 
2797   DEBUG_ONLY(before_thaw_java_frame(hf, caller, is_bottom_frame, num_frames);)
2798 
2799   assert(caller.sp() == caller.unextended_sp(), "");
2800 
2801   if (caller.is_interpreted_frame()) {
2802     _align_size += frame::align_wiggle; // we add one whether or not we've aligned because we add it in recurse_freeze_native_frame
2803   }
2804 
2805   // new_stack_frame must construct the resulting frame using hf.pc() rather than hf.raw_pc() because the frame is not
2806   // yet laid out in the stack, and so the original_pc is not stored in it.
2807   // As a result, f.is_deoptimized_frame() is always false and we must test hf to know if the frame is deoptimized.
2808   frame f = new_stack_frame<ContinuationHelper::NativeFrame>(hf, caller, false /* bottom */);
2809   intptr_t* const stack_frame_top = f.sp();
2810   intptr_t* const heap_frame_top = hf.unextended_sp();
2811 
2812   int fsize = ContinuationHelper::NativeFrame::size(hf);
2813   assert(fsize <= (int)(caller.unextended_sp() - f.unextended_sp()), "");
2814 
2815   intptr_t* from = heap_frame_top - frame::metadata_words_at_bottom;
2816   intptr_t* to   = stack_frame_top - frame::metadata_words_at_bottom;
2817   int sz = fsize + frame::metadata_words_at_bottom;
2818 
2819   copy_from_chunk(from, to, sz); // copying good oops because we invoked barriers above
2820 
2821   patch(f, caller, false /* bottom */);
2822 
2823   // f.is_deoptimized_frame() is always false and we must test hf.is_deoptimized_frame() (see comment above)
2824   assert(!f.is_deoptimized_frame(), "");
2825   assert(!hf.is_deoptimized_frame(), "");
2826   assert(!f.cb()->as_nmethod()->is_marked_for_deoptimization(), "");
2827 
2828   // can only fix caller once this frame is thawed (due to callee saved regs); this happens on the stack
2829   _cont.tail()->fix_thawed_frame(caller, SmallRegisterMap::instance());
2830 
2831   DEBUG_ONLY(after_thaw_java_frame(f, false /* bottom */);)
2832   caller = f;
2833 }
2834 
2835 void ThawBase::finish_thaw(frame& f) {
2836   stackChunkOop chunk = _cont.tail();
2837 
2838   if (chunk->is_empty()) {
2839     // Only remove chunk from list if it can't be reused for another freeze
2840     if (seen_by_gc()) {
2841       _cont.set_tail(chunk->parent());
2842     } else {
2843       chunk->set_has_mixed_frames(false);
2844     }
2845     chunk->set_max_thawing_size(0);
2846   } else {
2847     chunk->set_max_thawing_size(chunk->max_thawing_size() - _align_size);
2848   }
2849   assert(chunk->is_empty() == (chunk->max_thawing_size() == 0), "");
2850 
2851   if (!is_aligned(f.sp(), frame::frame_alignment)) {
2852     assert(f.is_interpreted_frame(), "");
2853     f.set_sp(align_down(f.sp(), frame::frame_alignment));
2854   }
2855   push_return_frame(f);
2856   chunk->fix_thawed_frame(f, SmallRegisterMap::instance()); // can only fix caller after push_return_frame (due to callee saved regs)
2857 
2858   assert(_cont.is_empty() == _cont.last_frame().is_empty(), "");
2859 
2860   log_develop_trace(continuations)("thawed %d frames", _frames);
2861 
2862   LogTarget(Trace, continuations) lt;
2863   if (lt.develop_is_enabled()) {
2864     LogStream ls(lt);
2865     ls.print_cr("top hframe after (thaw):");
2866     _cont.last_frame().print_value_on(&ls);
2867   }
2868 }
2869 
2870 void ThawBase::push_return_frame(frame& f) { // see generate_cont_thaw
2871   assert(!f.is_compiled_frame() || f.is_deoptimized_frame() == f.cb()->as_nmethod()->is_deopt_pc(f.raw_pc()), "");
2872   assert(!f.is_compiled_frame() || f.is_deoptimized_frame() == (f.pc() != f.raw_pc()), "");
2873 
2874   LogTarget(Trace, continuations) lt;
2875   if (lt.develop_is_enabled()) {
2876     LogStream ls(lt);
2877     ls.print_cr("push_return_frame");
2878     f.print_value_on(&ls);
2879   }
2880 
2881   assert(f.sp() - frame::metadata_words_at_bottom >= _top_stack_address, "overwrote past thawing space"
2882     " to: " INTPTR_FORMAT " top_address: " INTPTR_FORMAT, p2i(f.sp() - frame::metadata_words), p2i(_top_stack_address));
2883   ContinuationHelper::Frame::patch_pc(f, f.raw_pc()); // in case we want to deopt the frame in a full transition, this is checked.
2884   ContinuationHelper::push_pd(f);
2885 
2886   assert(ContinuationHelper::Frame::assert_frame_laid_out(f), "");
2887 }
2888 
2889 // returns new top sp
2890 // called after preparations (stack overflow check and making room)
2891 template<typename ConfigT>
2892 static inline intptr_t* thaw_internal(JavaThread* thread, const Continuation::thaw_kind kind) {
2893   assert(thread == JavaThread::current(), "Must be current thread");
2894 
2895   CONT_JFR_ONLY(EventContinuationThaw event;)
2896 
2897   log_develop_trace(continuations)("~~~~ thaw kind: %d sp: " INTPTR_FORMAT, kind, p2i(thread->last_continuation()->entry_sp()));
2898 
2899   ContinuationEntry* entry = thread->last_continuation();
2900   assert(entry != nullptr, "");
2901   oop oopCont = entry->cont_oop(thread);
2902 
2903   assert(!jdk_internal_vm_Continuation::done(oopCont), "");
2904   assert(oopCont == get_continuation(thread), "");
2905   verify_continuation(oopCont);
2906 
2907   assert(entry->is_virtual_thread() == (entry->scope(thread) == java_lang_VirtualThread::vthread_scope()), "");
2908 
2909   ContinuationWrapper cont(thread, oopCont);
2910   log_develop_debug(continuations)("THAW #" INTPTR_FORMAT " " INTPTR_FORMAT, cont.hash(), p2i((oopDesc*)oopCont));
2911 
2912 #ifdef ASSERT
2913   set_anchor_to_entry(thread, cont.entry());
2914   log_frames(thread);
2915   clear_anchor(thread);
2916 #endif
2917 
2918   DEBUG_ONLY(bool preempted = cont.tail()->preempted();)
2919   Thaw<ConfigT> thw(thread, cont);
2920   intptr_t* const sp = thw.thaw(kind);
2921   assert(is_aligned(sp, frame::frame_alignment), "");
2922   DEBUG_ONLY(log_frames_after_thaw(thread, cont, sp, preempted);)
2923 
2924   CONT_JFR_ONLY(thw.jfr_info().post_jfr_event(&event, cont.continuation(), thread);)
2925 
2926   verify_continuation(cont.continuation());
2927   log_develop_debug(continuations)("=== End of thaw #" INTPTR_FORMAT, cont.hash());
2928 
2929   return sp;
2930 }
2931 
2932 #ifdef ASSERT
2933 static void do_deopt_after_thaw(JavaThread* thread) {
2934   int i = 0;
2935   StackFrameStream fst(thread, true, false);
2936   fst.register_map()->set_include_argument_oops(false);
2937   ContinuationHelper::update_register_map_with_callee(*fst.current(), fst.register_map());
2938   for (; !fst.is_done(); fst.next()) {
2939     if (fst.current()->cb()->is_nmethod()) {
2940       nmethod* nm = fst.current()->cb()->as_nmethod();
2941       if (!nm->method()->is_continuation_native_intrinsic()) {
2942         nm->make_deoptimized();
2943       }
2944     }
2945   }
2946 }
2947 
2948 class ThawVerifyOopsClosure: public OopClosure {
2949   intptr_t* _p;
2950   outputStream* _st;
2951   bool is_good_oop(oop o) {
2952     return dbg_is_safe(o, -1) && dbg_is_safe(o->klass(), -1) && oopDesc::is_oop(o) && o->klass()->is_klass();
2953   }
2954 public:
2955   ThawVerifyOopsClosure(outputStream* st) : _p(nullptr), _st(st) {}
2956   intptr_t* p() { return _p; }
2957   void reset() { _p = nullptr; }
2958 
2959   virtual void do_oop(oop* p) {
2960     oop o = *p;
2961     if (o == nullptr || is_good_oop(o)) {
2962       return;
2963     }
2964     _p = (intptr_t*)p;
2965     _st->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT, p2i(*p), p2i(p));
2966   }
2967   virtual void do_oop(narrowOop* p) {
2968     oop o = RawAccess<>::oop_load(p);
2969     if (o == nullptr || is_good_oop(o)) {
2970       return;
2971     }
2972     _p = (intptr_t*)p;
2973     _st->print_cr("*** (narrow) non-oop %x found at " PTR_FORMAT, (int)(*p), p2i(p));
2974   }
2975 };
2976 
2977 static bool do_verify_after_thaw(JavaThread* thread, stackChunkOop chunk, outputStream* st) {
2978   assert(thread->has_last_Java_frame(), "");
2979 
2980   ResourceMark rm;
2981   ThawVerifyOopsClosure cl(st);
2982   NMethodToOopClosure cf(&cl, false);
2983 
2984   StackFrameStream fst(thread, true, false);
2985   fst.register_map()->set_include_argument_oops(false);
2986   ContinuationHelper::update_register_map_with_callee(*fst.current(), fst.register_map());
2987   for (; !fst.is_done() && !Continuation::is_continuation_enterSpecial(*fst.current()); fst.next()) {
2988     if (fst.current()->cb()->is_nmethod() && fst.current()->cb()->as_nmethod()->is_marked_for_deoptimization()) {
2989       st->print_cr(">>> do_verify_after_thaw deopt");
2990       fst.current()->deoptimize(nullptr);
2991       fst.current()->print_on(st);
2992     }
2993 
2994     fst.current()->oops_do(&cl, &cf, fst.register_map());
2995     if (cl.p() != nullptr) {
2996       frame fr = *fst.current();
2997       st->print_cr("Failed for frame barriers: %d",chunk->requires_barriers());
2998       fr.print_on(st);
2999       if (!fr.is_interpreted_frame()) {
3000         st->print_cr("size: %d argsize: %d",
3001                      ContinuationHelper::NonInterpretedUnknownFrame::size(fr),
3002                      ContinuationHelper::NonInterpretedUnknownFrame::stack_argsize(fr));
3003       }
3004       VMReg reg = fst.register_map()->find_register_spilled_here(cl.p(), fst.current()->sp());
3005       if (reg != nullptr) {
3006         st->print_cr("Reg %s %d", reg->name(), reg->is_stack() ? (int)reg->reg2stack() : -99);
3007       }
3008       cl.reset();
3009       DEBUG_ONLY(thread->print_frame_layout();)
3010       if (chunk != nullptr) {
3011         chunk->print_on(true, st);
3012       }
3013       return false;
3014     }
3015   }
3016   return true;
3017 }
3018 
3019 static void log_frames(JavaThread* thread) {
3020   const static int show_entry_callers = 3;
3021   LogTarget(Trace, continuations) lt;
3022   if (!lt.develop_is_enabled()) {
3023     return;
3024   }
3025   LogStream ls(lt);
3026 
3027   ls.print_cr("------- frames --------- for thread " INTPTR_FORMAT, p2i(thread));
3028   if (!thread->has_last_Java_frame()) {
3029     ls.print_cr("NO ANCHOR!");
3030   }
3031 
3032   RegisterMap map(thread,
3033                   RegisterMap::UpdateMap::include,
3034                   RegisterMap::ProcessFrames::include,
3035                   RegisterMap::WalkContinuation::skip);
3036   map.set_include_argument_oops(false);
3037 
3038   if (false) {
3039     for (frame f = thread->last_frame(); !f.is_entry_frame(); f = f.sender(&map)) {
3040       f.print_on(&ls);
3041     }
3042   } else {
3043     map.set_skip_missing(true);
3044     ResetNoHandleMark rnhm;
3045     ResourceMark rm;
3046     HandleMark hm(Thread::current());
3047     FrameValues values;
3048 
3049     int i = 0;
3050     int post_entry = -1;
3051     for (frame f = thread->last_frame(); !f.is_first_frame(); f = f.sender(&map), i++) {
3052       f.describe(values, i, &map, i == 0);
3053       if (post_entry >= 0 || Continuation::is_continuation_enterSpecial(f))
3054         post_entry++;
3055       if (post_entry >= show_entry_callers)
3056         break;
3057     }
3058     values.print_on(thread, &ls);
3059   }
3060 
3061   ls.print_cr("======= end frames =========");
3062 }
3063 
3064 static void log_frames_after_thaw(JavaThread* thread, ContinuationWrapper& cont, intptr_t* sp, bool preempted) {
3065   intptr_t* sp0 = sp;
3066   address pc0 = *(address*)(sp - frame::sender_sp_ret_address_offset());
3067 
3068   if (preempted && sp0 == cont.entrySP()) {
3069     // Still preempted (monitor not acquired) so no frames were thawed.
3070     assert(cont.tail()->preempted(), "");
3071     set_anchor(thread, cont.entrySP(), cont.entryPC());
3072   } else {
3073     set_anchor(thread, sp0);
3074   }
3075 
3076   log_frames(thread);
3077   if (LoomVerifyAfterThaw) {
3078     assert(do_verify_after_thaw(thread, cont.tail(), tty), "");
3079   }
3080   assert(ContinuationEntry::assert_entry_frame_laid_out(thread), "");
3081   clear_anchor(thread);
3082 
3083   LogTarget(Trace, continuations) lt;
3084   if (lt.develop_is_enabled()) {
3085     LogStream ls(lt);
3086     ls.print_cr("Jumping to frame (thaw):");
3087     frame(sp).print_value_on(&ls);
3088   }
3089 }
3090 #endif // ASSERT
3091 
3092 #include CPU_HEADER_INLINE(continuationFreezeThaw)
3093 
3094 #ifdef ASSERT
3095 static void print_frame_layout(const frame& f, bool callee_complete, outputStream* st) {
3096   ResourceMark rm;
3097   FrameValues values;
3098   assert(f.get_cb() != nullptr, "");
3099   RegisterMap map(f.is_heap_frame() ?
3100                     nullptr :
3101                     JavaThread::current(),
3102                   RegisterMap::UpdateMap::include,
3103                   RegisterMap::ProcessFrames::skip,
3104                   RegisterMap::WalkContinuation::skip);
3105   map.set_include_argument_oops(false);
3106   map.set_skip_missing(true);
3107   if (callee_complete) {
3108     frame::update_map_with_saved_link(&map, ContinuationHelper::Frame::callee_link_address(f));
3109   }
3110   const_cast<frame&>(f).describe(values, 0, &map, true);
3111   values.print_on(static_cast<JavaThread*>(nullptr), st);
3112 }
3113 #endif
3114 
3115 static address thaw_entry   = nullptr;
3116 static address freeze_entry = nullptr;
3117 static address freeze_preempt_entry = nullptr;
3118 
3119 address Continuation::thaw_entry() {
3120   return ::thaw_entry;
3121 }
3122 
3123 address Continuation::freeze_entry() {
3124   return ::freeze_entry;
3125 }
3126 
3127 address Continuation::freeze_preempt_entry() {
3128   return ::freeze_preempt_entry;
3129 }
3130 
3131 class ConfigResolve {
3132 public:
3133   static void resolve() { resolve_compressed(); }
3134 
3135   static void resolve_compressed() {
3136     UseCompressedOops ? resolve_gc<true>()
3137                       : resolve_gc<false>();
3138   }
3139 
3140 private:
3141   template <bool use_compressed>
3142   static void resolve_gc() {
3143     BarrierSet* bs = BarrierSet::barrier_set();
3144     assert(bs != nullptr, "freeze/thaw invoked before BarrierSet is set");
3145     switch (bs->kind()) {
3146 #define BARRIER_SET_RESOLVE_BARRIER_CLOSURE(bs_name)                    \
3147       case BarrierSet::bs_name: {                                       \
3148         resolve<use_compressed, typename BarrierSet::GetType<BarrierSet::bs_name>::type>(); \
3149       }                                                                 \
3150         break;
3151       FOR_EACH_CONCRETE_BARRIER_SET_DO(BARRIER_SET_RESOLVE_BARRIER_CLOSURE)
3152 #undef BARRIER_SET_RESOLVE_BARRIER_CLOSURE
3153 
3154     default:
3155       fatal("BarrierSet resolving not implemented");
3156     };
3157   }
3158 
3159   template <bool use_compressed, typename BarrierSetT>
3160   static void resolve() {
3161     typedef Config<use_compressed ? oop_kind::NARROW : oop_kind::WIDE, BarrierSetT> SelectedConfigT;
3162 
3163     freeze_entry = (address)freeze<SelectedConfigT>;
3164     freeze_preempt_entry = (address)SelectedConfigT::freeze_preempt;
3165 
3166     // If we wanted, we could templatize by kind and have three different thaw entries
3167     thaw_entry   = (address)thaw<SelectedConfigT>;
3168   }
3169 };
3170 
3171 void Continuation::init() {
3172   ConfigResolve::resolve();
3173 }