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