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