1 /*
   2  * Copyright (c) 1999, 2026, 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 "asm/codeBuffer.hpp"
  26 #include "c1/c1_CodeStubs.hpp"
  27 #include "c1/c1_Defs.hpp"
  28 #include "c1/c1_LIRAssembler.hpp"
  29 #include "c1/c1_MacroAssembler.hpp"
  30 #include "c1/c1_Runtime1.hpp"
  31 #include "classfile/javaClasses.inline.hpp"
  32 #include "classfile/vmClasses.hpp"
  33 #include "classfile/vmSymbols.hpp"
  34 #include "code/aotCodeCache.hpp"
  35 #include "code/codeBlob.hpp"
  36 #include "code/compiledIC.hpp"
  37 #include "code/scopeDesc.hpp"
  38 #include "code/vtableStubs.hpp"
  39 #include "compiler/compilationPolicy.hpp"
  40 #include "compiler/disassembler.hpp"
  41 #include "compiler/oopMap.hpp"
  42 #include "gc/shared/barrierSet.hpp"
  43 #include "gc/shared/c1/barrierSetC1.hpp"
  44 #include "gc/shared/collectedHeap.hpp"
  45 #include "interpreter/bytecode.hpp"
  46 #include "interpreter/interpreter.hpp"
  47 #include "jfr/support/jfrIntrinsics.hpp"
  48 #include "logging/log.hpp"
  49 #include "memory/oopFactory.hpp"
  50 #include "memory/resourceArea.hpp"
  51 #include "memory/universe.hpp"
  52 #include "oops/access.inline.hpp"
  53 #include "oops/arrayOop.inline.hpp"
  54 #include "oops/arrayProperties.hpp"
  55 #include "oops/flatArrayKlass.hpp"
  56 #include "oops/flatArrayOop.inline.hpp"
  57 #include "oops/objArrayKlass.hpp"
  58 #include "oops/objArrayOop.inline.hpp"
  59 #include "oops/oop.inline.hpp"
  60 #include "oops/oopCast.inline.hpp"
  61 #include "prims/jvmtiExport.hpp"
  62 #include "runtime/atomicAccess.hpp"
  63 #include "runtime/fieldDescriptor.inline.hpp"
  64 #include "runtime/frame.inline.hpp"
  65 #include "runtime/handles.inline.hpp"
  66 #include "runtime/interfaceSupport.inline.hpp"
  67 #include "runtime/javaCalls.hpp"
  68 #include "runtime/sharedRuntime.hpp"
  69 #include "runtime/stackWatermarkSet.hpp"
  70 #include "runtime/stubInfo.hpp"
  71 #include "runtime/stubRoutines.hpp"
  72 #include "runtime/vframe.inline.hpp"
  73 #include "runtime/vframeArray.hpp"
  74 #include "runtime/vm_version.hpp"
  75 #include "utilities/copy.hpp"
  76 #include "utilities/events.hpp"
  77 
  78 
  79 // Implementation of StubAssembler
  80 
  81 StubAssembler::StubAssembler(CodeBuffer* code, const char * name, int stub_id) : C1_MacroAssembler(code) {
  82   _name = name;
  83   _must_gc_arguments = false;
  84   _frame_size = no_frame_size;
  85   _num_rt_args = 0;
  86   _stub_id = stub_id;
  87 }
  88 
  89 
  90 void StubAssembler::set_info(const char* name, bool must_gc_arguments) {
  91   _name = name;
  92   _must_gc_arguments = must_gc_arguments;
  93 }
  94 
  95 
  96 void StubAssembler::set_frame_size(int size) {
  97   if (_frame_size == no_frame_size) {
  98     _frame_size = size;
  99   }
 100   assert(_frame_size == size, "can't change the frame size");
 101 }
 102 
 103 
 104 void StubAssembler::set_num_rt_args(int args) {
 105   if (_num_rt_args == 0) {
 106     _num_rt_args = args;
 107   }
 108   assert(_num_rt_args == args, "can't change the number of args");
 109 }
 110 
 111 // Implementation of Runtime1
 112 CodeBlob* Runtime1::_blobs[StubInfo::C1_STUB_COUNT];
 113 
 114 #ifndef PRODUCT
 115 // statistics
 116 uint Runtime1::_generic_arraycopystub_cnt = 0;
 117 uint Runtime1::_arraycopy_slowcase_cnt = 0;
 118 uint Runtime1::_arraycopy_checkcast_cnt = 0;
 119 uint Runtime1::_arraycopy_checkcast_attempt_cnt = 0;
 120 uint Runtime1::_new_type_array_slowcase_cnt = 0;
 121 uint Runtime1::_new_object_array_slowcase_cnt = 0;
 122 uint Runtime1::_new_null_free_array_slowcase_cnt = 0;
 123 uint Runtime1::_new_instance_slowcase_cnt = 0;
 124 uint Runtime1::_new_multi_array_slowcase_cnt = 0;
 125 uint Runtime1::_load_flat_array_slowcase_cnt = 0;
 126 uint Runtime1::_store_flat_array_slowcase_cnt = 0;
 127 uint Runtime1::_substitutability_check_slowcase_cnt = 0;
 128 uint Runtime1::_buffer_inline_args_slowcase_cnt = 0;
 129 uint Runtime1::_buffer_inline_args_no_receiver_slowcase_cnt = 0;
 130 uint Runtime1::_monitorenter_slowcase_cnt = 0;
 131 uint Runtime1::_monitorexit_slowcase_cnt = 0;
 132 uint Runtime1::_patch_code_slowcase_cnt = 0;
 133 uint Runtime1::_throw_range_check_exception_count = 0;
 134 uint Runtime1::_throw_index_exception_count = 0;
 135 uint Runtime1::_throw_div0_exception_count = 0;
 136 uint Runtime1::_throw_null_pointer_exception_count = 0;
 137 uint Runtime1::_throw_class_cast_exception_count = 0;
 138 uint Runtime1::_throw_incompatible_class_change_error_count = 0;
 139 uint Runtime1::_throw_illegal_monitor_state_exception_count = 0;
 140 uint Runtime1::_throw_identity_exception_count = 0;
 141 uint Runtime1::_throw_count = 0;
 142 
 143 static uint _byte_arraycopy_stub_cnt = 0;
 144 static uint _short_arraycopy_stub_cnt = 0;
 145 static uint _int_arraycopy_stub_cnt = 0;
 146 static uint _long_arraycopy_stub_cnt = 0;
 147 static uint _oop_arraycopy_stub_cnt = 0;
 148 
 149 address Runtime1::arraycopy_count_address(BasicType type) {
 150   switch (type) {
 151   case T_BOOLEAN:
 152   case T_BYTE:   return (address)&_byte_arraycopy_stub_cnt;
 153   case T_CHAR:
 154   case T_SHORT:  return (address)&_short_arraycopy_stub_cnt;
 155   case T_FLOAT:
 156   case T_INT:    return (address)&_int_arraycopy_stub_cnt;
 157   case T_DOUBLE:
 158   case T_LONG:   return (address)&_long_arraycopy_stub_cnt;
 159   case T_ARRAY:
 160   case T_OBJECT: return (address)&_oop_arraycopy_stub_cnt;
 161   default:
 162     ShouldNotReachHere();
 163     return nullptr;
 164   }
 165 }
 166 
 167 
 168 #endif
 169 
 170 // Simple helper to see if the caller of a runtime stub which
 171 // entered the VM has been deoptimized
 172 
 173 static bool caller_is_deopted(JavaThread* current) {
 174   RegisterMap reg_map(current,
 175                       RegisterMap::UpdateMap::skip,
 176                       RegisterMap::ProcessFrames::include,
 177                       RegisterMap::WalkContinuation::skip);
 178   frame runtime_frame = current->last_frame();
 179   frame caller_frame = runtime_frame.sender(&reg_map);
 180   assert(caller_frame.is_compiled_frame(), "must be compiled");
 181   return caller_frame.is_deoptimized_frame();
 182 }
 183 
 184 // Stress deoptimization
 185 static void deopt_caller(JavaThread* current) {
 186   if (!caller_is_deopted(current)) {
 187     RegisterMap reg_map(current,
 188                         RegisterMap::UpdateMap::skip,
 189                         RegisterMap::ProcessFrames::include,
 190                         RegisterMap::WalkContinuation::skip);
 191     frame runtime_frame = current->last_frame();
 192     frame caller_frame = runtime_frame.sender(&reg_map);
 193     Deoptimization::deoptimize_frame(current, caller_frame.id());
 194     assert(caller_is_deopted(current), "Must be deoptimized");
 195   }
 196 }
 197 
 198 class C1StubAssemblerCodeGenClosure: public StubAssemblerCodeGenClosure {
 199  private:
 200   StubId _id;
 201  public:
 202   C1StubAssemblerCodeGenClosure(StubId id) : _id(id) {
 203     assert(StubInfo::is_c1(_id), "not a c1 stub id %s", StubInfo::name(_id));
 204   }
 205   virtual OopMapSet* generate_code(StubAssembler* sasm) {
 206     return Runtime1::generate_code_for(_id, sasm);
 207   }
 208 };
 209 
 210 CodeBlob* Runtime1::generate_blob(BufferBlob* buffer_blob, StubId id, const char* name, bool expect_oop_map, StubAssemblerCodeGenClosure* cl) {
 211   if (id != StubId::NO_STUBID) {
 212     CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::C1Blob, StubInfo::blob(id));
 213     if (blob != nullptr) {
 214       return blob;
 215     }
 216   }
 217 
 218   ResourceMark rm;
 219   // create code buffer for code storage
 220   CodeBuffer code(buffer_blob);
 221 
 222   OopMapSet* oop_maps;
 223   int frame_size;
 224   bool must_gc_arguments;
 225 
 226   Compilation::setup_code_buffer(&code, 0);
 227 
 228   // create assembler for code generation
 229   StubAssembler* sasm = new StubAssembler(&code, name, (int)id);
 230   // generate code for runtime stub
 231   oop_maps = cl->generate_code(sasm);
 232   assert(oop_maps == nullptr || sasm->frame_size() != no_frame_size,
 233          "if stub has an oop map it must have a valid frame size");
 234   assert(!expect_oop_map || oop_maps != nullptr, "must have an oopmap");
 235 
 236   // align so printing shows nop's instead of random code at the end (SimpleStubs are aligned)
 237   sasm->align(BytesPerWord);
 238   // make sure all code is in code buffer
 239   sasm->flush();
 240 
 241   frame_size = sasm->frame_size();
 242   must_gc_arguments = sasm->must_gc_arguments();
 243   // create blob - distinguish a few special cases
 244   CodeBlob* blob = RuntimeStub::new_runtime_stub(name,
 245                                                  &code,
 246                                                  CodeOffsets::frame_never_safe,
 247                                                  frame_size,
 248                                                  oop_maps,
 249                                                  must_gc_arguments,
 250                                                  false /* alloc_fail_is_fatal */ );
 251   if (blob != nullptr && (int)id >= 0) {
 252     AOTCodeCache::store_code_blob(*blob, AOTCodeEntry::C1Blob, StubInfo::blob(id));
 253   }
 254   return blob;
 255 }
 256 
 257 bool Runtime1::generate_blob_for(BufferBlob* buffer_blob, StubId id) {
 258   assert(StubInfo::is_c1(id), "not a c1 stub %s", StubInfo::name(id));
 259   bool expect_oop_map = true;
 260 #ifdef ASSERT
 261   // Make sure that stubs that need oopmaps have them
 262   switch (id) {
 263     // These stubs don't need to have an oopmap
 264   case StubId::c1_dtrace_object_alloc_id:
 265   case StubId::c1_slow_subtype_check_id:
 266   case StubId::c1_fpu2long_stub_id:
 267   case StubId::c1_unwind_exception_id:
 268   case StubId::c1_counter_overflow_id:
 269   case StubId::c1_is_instance_of_id:
 270     expect_oop_map = false;
 271     break;
 272   default:
 273     break;
 274   }
 275 #endif
 276   C1StubAssemblerCodeGenClosure cl(id);
 277   CodeBlob* blob = generate_blob(buffer_blob, id, name_for(id), expect_oop_map, &cl);
 278   // install blob
 279   int idx = StubInfo::c1_offset(id);   // will assert on non-c1 id
 280   _blobs[idx] = blob;
 281   return blob != nullptr;
 282 }
 283 
 284 bool Runtime1::initialize(BufferBlob* blob) {
 285   // platform-dependent initialization
 286   initialize_pd();
 287   // iterate blobs in C1 group and generate a single stub per blob
 288   StubId id = StubInfo::stub_base(StubGroup::C1);
 289   StubId limit = StubInfo::next(StubInfo::stub_max(StubGroup::C1));
 290   for (; id != limit; id = StubInfo::next(id)) {
 291     if (!generate_blob_for(blob, id)) {
 292       return false;
 293     }
 294     if (id == StubId::c1_forward_exception_id) {
 295       // publish early c1 stubs at this point so later stubs can refer to them
 296       AOTCodeCache::init_early_c1_table();
 297     }
 298   }
 299   // printing
 300 #ifndef PRODUCT
 301   if (PrintSimpleStubs) {
 302     ResourceMark rm;
 303     id = StubInfo::stub_base(StubGroup::C1);
 304     for (; id != limit; id = StubInfo::next(id)) {
 305       CodeBlob* blob = blob_for(id);
 306       blob->print();
 307       if (blob->oop_maps() != nullptr) {
 308         blob->oop_maps()->print();
 309       }
 310     }
 311   }
 312 #endif
 313   BarrierSetC1* bs = BarrierSet::barrier_set()->barrier_set_c1();
 314   return bs->generate_c1_runtime_stubs(blob);
 315 }
 316 
 317 CodeBlob* Runtime1::blob_for(StubId id) {
 318   int idx = StubInfo::c1_offset(id);   // will assert on non-c1 id
 319   return _blobs[idx];
 320 }
 321 
 322 
 323 const char* Runtime1::name_for(StubId id) {
 324   return StubInfo::name(id);
 325 }
 326 
 327 const char* Runtime1::name_for_address(address entry) {
 328   // iterate stubs starting from C1 group base
 329   StubId id = StubInfo::stub_base(StubGroup::C1);
 330   StubId limit = StubInfo::next(StubInfo::stub_max(StubGroup::C1));
 331   for (; id != limit; id = StubInfo::next(id)) {
 332     if (entry == entry_for(id)) return StubInfo::name(id);
 333   }
 334 
 335 #define FUNCTION_CASE(a, f) \
 336   if ((intptr_t)a == CAST_FROM_FN_PTR(intptr_t, f))  return #f
 337 
 338   FUNCTION_CASE(entry, os::javaTimeMillis);
 339   FUNCTION_CASE(entry, os::javaTimeNanos);
 340   FUNCTION_CASE(entry, SharedRuntime::OSR_migration_end);
 341   FUNCTION_CASE(entry, SharedRuntime::d2f);
 342   FUNCTION_CASE(entry, SharedRuntime::d2i);
 343   FUNCTION_CASE(entry, SharedRuntime::d2l);
 344   FUNCTION_CASE(entry, SharedRuntime::dcos);
 345   FUNCTION_CASE(entry, SharedRuntime::dexp);
 346   FUNCTION_CASE(entry, SharedRuntime::dlog);
 347   FUNCTION_CASE(entry, SharedRuntime::dlog10);
 348   FUNCTION_CASE(entry, SharedRuntime::dpow);
 349   FUNCTION_CASE(entry, SharedRuntime::drem);
 350   FUNCTION_CASE(entry, SharedRuntime::dsin);
 351   FUNCTION_CASE(entry, SharedRuntime::dtan);
 352   FUNCTION_CASE(entry, SharedRuntime::f2i);
 353   FUNCTION_CASE(entry, SharedRuntime::f2l);
 354   FUNCTION_CASE(entry, SharedRuntime::frem);
 355   FUNCTION_CASE(entry, SharedRuntime::l2d);
 356   FUNCTION_CASE(entry, SharedRuntime::l2f);
 357   FUNCTION_CASE(entry, SharedRuntime::ldiv);
 358   FUNCTION_CASE(entry, SharedRuntime::lmul);
 359   FUNCTION_CASE(entry, SharedRuntime::lrem);
 360   FUNCTION_CASE(entry, SharedRuntime::lrem);
 361   FUNCTION_CASE(entry, SharedRuntime::dtrace_method_entry);
 362   FUNCTION_CASE(entry, SharedRuntime::dtrace_method_exit);
 363   FUNCTION_CASE(entry, is_instance_of);
 364   FUNCTION_CASE(entry, trace_block_entry);
 365 #ifdef JFR_HAVE_INTRINSICS
 366   FUNCTION_CASE(entry, JfrTime::time_function());
 367 #endif
 368   FUNCTION_CASE(entry, StubRoutines::updateBytesCRC32());
 369   FUNCTION_CASE(entry, StubRoutines::updateBytesCRC32C());
 370   FUNCTION_CASE(entry, StubRoutines::vectorizedMismatch());
 371   FUNCTION_CASE(entry, StubRoutines::dexp());
 372   FUNCTION_CASE(entry, StubRoutines::dlog());
 373   FUNCTION_CASE(entry, StubRoutines::dlog10());
 374   FUNCTION_CASE(entry, StubRoutines::dpow());
 375   FUNCTION_CASE(entry, StubRoutines::dsin());
 376   FUNCTION_CASE(entry, StubRoutines::dcos());
 377   FUNCTION_CASE(entry, StubRoutines::dtan());
 378   FUNCTION_CASE(entry, StubRoutines::dsinh());
 379   FUNCTION_CASE(entry, StubRoutines::dtanh());
 380   FUNCTION_CASE(entry, StubRoutines::dcbrt());
 381 
 382 #undef FUNCTION_CASE
 383 
 384   // Soft float adds more runtime names.
 385   return pd_name_for_address(entry);
 386 }
 387 
 388 static void allocate_instance(JavaThread* current, Klass* klass, TRAPS) {
 389 #ifndef PRODUCT
 390   if (PrintC1Statistics) {
 391     Runtime1::_new_instance_slowcase_cnt++;
 392   }
 393 #endif
 394   assert(klass->is_klass(), "not a class");
 395   Handle holder(current, klass->klass_holder()); // keep the klass alive
 396   InstanceKlass* h = InstanceKlass::cast(klass);
 397   h->check_valid_for_instantiation(true, CHECK);
 398   // make sure klass is initialized
 399   h->initialize(CHECK);
 400   // allocate instance and return via TLS
 401   oop obj = h->allocate_instance(CHECK);
 402   current->set_vm_result_oop(obj);
 403 JRT_END
 404 
 405 JRT_ENTRY(void, Runtime1::new_instance(JavaThread* current, Klass* klass))
 406   allocate_instance(current, klass, CHECK);
 407 JRT_END
 408 
 409 JRT_ENTRY(void, Runtime1::new_type_array(JavaThread* current, Klass* klass, jint length))
 410 #ifndef PRODUCT
 411   if (PrintC1Statistics) {
 412     _new_type_array_slowcase_cnt++;
 413   }
 414 #endif
 415   // Note: no handle for klass needed since they are not used
 416   //       anymore after new_typeArray() and no GC can happen before.
 417   //       (This may have to change if this code changes!)
 418   assert(klass->is_klass(), "not a class");
 419   BasicType elt_type = TypeArrayKlass::cast(klass)->element_type();
 420   oop obj = oopFactory::new_typeArray(elt_type, length, CHECK);
 421   current->set_vm_result_oop(obj);
 422   // This is pretty rare but this runtime patch is stressful to deoptimization
 423   // if we deoptimize here so force a deopt to stress the path.
 424   if (DeoptimizeALot) {
 425     deopt_caller(current);
 426   }
 427 
 428 JRT_END
 429 
 430 
 431 JRT_ENTRY(void, Runtime1::new_object_array(JavaThread* current, Klass* array_klass, jint length))
 432 #ifndef PRODUCT
 433   if (PrintC1Statistics) {
 434     _new_object_array_slowcase_cnt++;
 435   }
 436 #endif
 437   // Note: no handle for klass needed since they are not used
 438   //       anymore after new_objArray() and no GC can happen before.
 439   //       (This may have to change if this code changes!)
 440   assert(array_klass->is_klass(), "not a class");
 441   Handle holder(current, array_klass->klass_holder()); // keep the klass alive
 442   Klass* elem_klass = ObjArrayKlass::cast(array_klass)->element_klass();
 443   objArrayOop obj = oopFactory::new_objArray(elem_klass, length, CHECK);
 444   current->set_vm_result_oop(obj);
 445   // This is pretty rare but this runtime patch is stressful to deoptimization
 446   // if we deoptimize here so force a deopt to stress the path.
 447   if (DeoptimizeALot) {
 448     deopt_caller(current);
 449   }
 450 JRT_END
 451 
 452 
 453 JRT_ENTRY(void, Runtime1::new_null_free_array(JavaThread* current, Klass* array_klass, jint length))
 454   NOT_PRODUCT(_new_null_free_array_slowcase_cnt++;)
 455   // TODO 8350865 This is dead code since 8325660 because null-free arrays can only be created via the factory methods that are not yet implemented in C1. Should probably be fixed by 8265122.
 456 
 457   // Note: no handle for klass needed since they are not used
 458   //       anymore after new_objArray() and no GC can happen before.
 459   //       (This may have to change if this code changes!)
 460   assert(array_klass->is_klass(), "not a class");
 461   Handle holder(THREAD, array_klass->klass_holder()); // keep the klass alive
 462   Klass* elem_klass = ObjArrayKlass::cast(array_klass)->element_klass();
 463   assert(elem_klass->is_inline_klass(), "must be");
 464   // Logically creates elements, ensure klass init
 465   elem_klass->initialize(CHECK);
 466 
 467   const ArrayProperties props = ArrayProperties::Default().with_null_restricted();
 468   arrayOop obj = oopFactory::new_objArray(elem_klass, length, props, CHECK);
 469 
 470   current->set_vm_result_oop(obj);
 471   // This is pretty rare but this runtime patch is stressful to deoptimization
 472   // if we deoptimize here so force a deopt to stress the path.
 473   if (DeoptimizeALot) {
 474     deopt_caller(current);
 475   }
 476 JRT_END
 477 
 478 
 479 JRT_ENTRY(void, Runtime1::new_multi_array(JavaThread* current, Klass* klass, int rank, jint* dims))
 480 #ifndef PRODUCT
 481   if (PrintC1Statistics) {
 482     _new_multi_array_slowcase_cnt++;
 483   }
 484 #endif
 485   assert(klass->is_klass(), "not a class");
 486   assert(rank >= 1, "rank must be nonzero");
 487   Handle holder(current, klass->klass_holder()); // keep the klass alive
 488   oop obj = ArrayKlass::cast(klass)->multi_allocate(rank, dims, CHECK);
 489   current->set_vm_result_oop(obj);
 490 JRT_END
 491 
 492 
 493 static void profile_flat_array(JavaThread* current, bool load, bool null_free) {
 494   ResourceMark rm(current);
 495   vframeStream vfst(current, true);
 496   assert(!vfst.at_end(), "Java frame must exist");
 497   // Check if array access profiling is enabled
 498   if (vfst.nm()->comp_level() != CompLevel_full_profile || !C1UpdateMethodData) {
 499     return;
 500   }
 501   int bci = vfst.bci();
 502   Method* method = vfst.method();
 503   MethodData* md = method->method_data();
 504   if (md != nullptr) {
 505     // Lock to access ProfileData, and ensure lock is not broken by a safepoint
 506     MutexLocker ml(md->extra_data_lock(), Mutex::_no_safepoint_check_flag);
 507 
 508     ProfileData* data = md->bci_to_data(bci);
 509     assert(data != nullptr, "incorrect profiling entry");
 510     if (data->is_ArrayLoadData()) {
 511       assert(load, "should be an array load");
 512       ArrayLoadData* load_data = (ArrayLoadData*) data;
 513       load_data->set_flat_array();
 514       if (null_free) {
 515         load_data->set_null_free_array();
 516       }
 517     } else {
 518       assert(data->is_ArrayStoreData(), "");
 519       assert(!load, "should be an array store");
 520       ArrayStoreData* store_data = (ArrayStoreData*) data;
 521       store_data->set_flat_array();
 522       if (null_free) {
 523         store_data->set_null_free_array();
 524       }
 525     }
 526   }
 527 }
 528 
 529 JRT_ENTRY(void, Runtime1::load_flat_array(JavaThread* current, flatArrayOopDesc* array, int index))
 530   assert(array->klass()->is_flatArray_klass(), "should not be called");
 531   profile_flat_array(current, true, array->is_null_free_array());
 532 
 533   NOT_PRODUCT(_load_flat_array_slowcase_cnt++;)
 534   assert(array->length() > 0 && index < array->length(), "already checked");
 535   flatArrayHandle vah(current, array);
 536   oop obj = array->obj_at(index, CHECK);
 537   current->set_vm_result_oop(obj);
 538 JRT_END
 539 
 540 JRT_ENTRY(void, Runtime1::store_flat_array(JavaThread* current, arrayOopDesc* array, int index, oopDesc* value))
 541   // TOOD 8350865 We can call here with a non-flat array because of LIR_Assembler::emit_opFlattenedArrayCheck
 542   if (array->is_flatArray()) {
 543     profile_flat_array(current, false, array->is_null_free_array());
 544   }
 545 
 546   NOT_PRODUCT(_store_flat_array_slowcase_cnt++;)
 547   if (value == nullptr && array->is_null_free_array()) {
 548     SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_NullPointerException());
 549   } else {
 550     // Here we know that we have a flat array
 551     oop_cast<flatArrayOop>(array)->obj_at_put(index, value, CHECK);
 552   }
 553 JRT_END
 554 
 555 JRT_ENTRY(int, Runtime1::substitutability_check(JavaThread* current, oopDesc* left, oopDesc* right))
 556   NOT_PRODUCT(_substitutability_check_slowcase_cnt++;)
 557   JavaCallArguments args;
 558   args.push_oop(Handle(THREAD, left));
 559   args.push_oop(Handle(THREAD, right));
 560   JavaValue result(T_BOOLEAN);
 561   JavaCalls::call_static(&result,
 562                          vmClasses::ValueObjectMethods_klass(),
 563                          vmSymbols::isSubstitutable_name(),
 564                          vmSymbols::object_object_boolean_signature(),
 565                          &args, CHECK_0);
 566   return result.get_jboolean() ? 1 : 0;
 567 JRT_END
 568 
 569 
 570 extern "C" void ps();
 571 
 572 void Runtime1::buffer_inline_args_impl(JavaThread* current, Method* m, bool allocate_receiver) {
 573   JavaThread* THREAD = current;
 574   methodHandle method(current, m); // We are inside the verified_entry or verified_inline_ro_entry of this method.
 575   oop obj = SharedRuntime::allocate_inline_types_impl(current, method, allocate_receiver, true, CHECK);
 576   current->set_vm_result_oop(obj);
 577 }
 578 
 579 JRT_ENTRY(void, Runtime1::buffer_inline_args(JavaThread* current, Method* method))
 580   NOT_PRODUCT(_buffer_inline_args_slowcase_cnt++;)
 581   buffer_inline_args_impl(current, method, true);
 582 JRT_END
 583 
 584 JRT_ENTRY(void, Runtime1::buffer_inline_args_no_receiver(JavaThread* current, Method* method))
 585   NOT_PRODUCT(_buffer_inline_args_no_receiver_slowcase_cnt++;)
 586   buffer_inline_args_impl(current, method, false);
 587 JRT_END
 588 
 589 JRT_ENTRY(void, Runtime1::unimplemented_entry(JavaThread* current, StubId id))
 590   tty->print_cr("Runtime1::entry_for(%d) returned unimplemented entry point", (int)id);
 591 JRT_END
 592 
 593 
 594 JRT_ENTRY(void, Runtime1::throw_array_store_exception(JavaThread* current, oopDesc* obj))
 595   ResourceMark rm(current);
 596   const char* klass_name = obj->klass()->external_name();
 597   SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArrayStoreException(), klass_name);
 598 JRT_END
 599 
 600 
 601 // counter_overflow() is called from within C1-compiled methods. The enclosing method is the method
 602 // associated with the top activation record. The inlinee (that is possibly included in the enclosing
 603 // method) method is passed as an argument. In order to do that it is embedded in the code as
 604 // a constant.
 605 static nmethod* counter_overflow_helper(JavaThread* current, int branch_bci, Method* m) {
 606   nmethod* osr_nm = nullptr;
 607   methodHandle method(current, m);
 608 
 609   RegisterMap map(current,
 610                   RegisterMap::UpdateMap::skip,
 611                   RegisterMap::ProcessFrames::include,
 612                   RegisterMap::WalkContinuation::skip);
 613   frame fr =  current->last_frame().sender(&map);
 614   nmethod* nm = (nmethod*) fr.cb();
 615   assert(nm!= nullptr && nm->is_nmethod(), "Sanity check");
 616   methodHandle enclosing_method(current, nm->method());
 617 
 618   CompLevel level = (CompLevel)nm->comp_level();
 619   int bci = InvocationEntryBci;
 620   if (branch_bci != InvocationEntryBci) {
 621     // Compute destination bci
 622     address pc = method()->code_base() + branch_bci;
 623     Bytecodes::Code branch = Bytecodes::code_at(method(), pc);
 624     int offset = 0;
 625     switch (branch) {
 626       case Bytecodes::_if_icmplt: case Bytecodes::_iflt:
 627       case Bytecodes::_if_icmpgt: case Bytecodes::_ifgt:
 628       case Bytecodes::_if_icmple: case Bytecodes::_ifle:
 629       case Bytecodes::_if_icmpge: case Bytecodes::_ifge:
 630       case Bytecodes::_if_icmpeq: case Bytecodes::_if_acmpeq: case Bytecodes::_ifeq:
 631       case Bytecodes::_if_icmpne: case Bytecodes::_if_acmpne: case Bytecodes::_ifne:
 632       case Bytecodes::_ifnull: case Bytecodes::_ifnonnull: case Bytecodes::_goto:
 633         offset = (int16_t)Bytes::get_Java_u2(pc + 1);
 634         break;
 635       case Bytecodes::_goto_w:
 636         offset = Bytes::get_Java_u4(pc + 1);
 637         break;
 638       default: ;
 639     }
 640     bci = branch_bci + offset;
 641   }
 642   osr_nm = CompilationPolicy::event(enclosing_method, method, branch_bci, bci, level, nm, current);
 643   return osr_nm;
 644 }
 645 
 646 JRT_BLOCK_ENTRY(address, Runtime1::counter_overflow(JavaThread* current, int bci, Method* method))
 647   nmethod* osr_nm;
 648   JRT_BLOCK_NO_ASYNC
 649     osr_nm = counter_overflow_helper(current, bci, method);
 650     if (osr_nm != nullptr) {
 651       RegisterMap map(current,
 652                       RegisterMap::UpdateMap::skip,
 653                       RegisterMap::ProcessFrames::include,
 654                       RegisterMap::WalkContinuation::skip);
 655       frame fr =  current->last_frame().sender(&map);
 656       Deoptimization::deoptimize_frame(current, fr.id());
 657     }
 658   JRT_BLOCK_END
 659   return nullptr;
 660 JRT_END
 661 
 662 extern void vm_exit(int code);
 663 
 664 // Enter this method from compiled code handler below. This is where we transition
 665 // to VM mode. This is done as a helper routine so that the method called directly
 666 // from compiled code does not have to transition to VM. This allows the entry
 667 // method to see if the nmethod that we have just looked up a handler for has
 668 // been deoptimized while we were in the vm. This simplifies the assembly code
 669 // cpu directories.
 670 //
 671 // We are entering here from exception stub (via the entry method below)
 672 // If there is a compiled exception handler in this method, we will continue there;
 673 // otherwise we will unwind the stack and continue at the caller of top frame method
 674 // Note: we enter in Java using a special JRT wrapper. This wrapper allows us to
 675 // control the area where we can allow a safepoint. After we exit the safepoint area we can
 676 // check to see if the handler we are going to return is now in a nmethod that has
 677 // been deoptimized. If that is the case we return the deopt blob
 678 // unpack_with_exception entry instead. This makes life for the exception blob easier
 679 // because making that same check and diverting is painful from assembly language.
 680 JRT_ENTRY_NO_ASYNC(static address, exception_handler_for_pc_helper(JavaThread* current, oopDesc* ex, address pc, nmethod*& nm))
 681   MACOS_AARCH64_ONLY(current->wx_enable_write());
 682   Handle exception(current, ex);
 683 
 684   // This function is called when we are about to throw an exception. Therefore,
 685   // we have to poll the stack watermark barrier to make sure that not yet safe
 686   // stack frames are made safe before returning into them.
 687   if (current->last_frame().cb() == Runtime1::blob_for(StubId::c1_handle_exception_from_callee_id)) {
 688     // The StubId::c1_handle_exception_from_callee_id handler is invoked after the
 689     // frame has been unwound. It instead builds its own stub frame, to call the
 690     // runtime. But the throwing frame has already been unwound here.
 691     StackWatermarkSet::after_unwind(current);
 692   }
 693 
 694   nm = CodeCache::find_nmethod(pc);
 695   assert(nm != nullptr, "this is not an nmethod");
 696   // Adjust the pc as needed/
 697   if (nm->is_deopt_pc(pc)) {
 698     RegisterMap map(current,
 699                     RegisterMap::UpdateMap::skip,
 700                     RegisterMap::ProcessFrames::include,
 701                     RegisterMap::WalkContinuation::skip);
 702     frame exception_frame = current->last_frame().sender(&map);
 703     // if the frame isn't deopted then pc must not correspond to the caller of last_frame
 704     assert(exception_frame.is_deoptimized_frame(), "must be deopted");
 705     pc = exception_frame.pc();
 706   }
 707   assert(exception.not_null(), "null exceptions should be handled by throw_exception");
 708   // Check that exception is a subclass of Throwable
 709   assert(exception->is_a(vmClasses::Throwable_klass()),
 710          "Exception not subclass of Throwable");
 711 
 712   // debugging support
 713   // tracing
 714   if (log_is_enabled(Info, exceptions)) {
 715     ResourceMark rm; // print_value_string
 716     stringStream tempst;
 717     assert(nm->method() != nullptr, "Unexpected null method()");
 718     tempst.print("C1 compiled method <%s>\n"
 719                  " at PC" INTPTR_FORMAT " for thread " INTPTR_FORMAT,
 720                  nm->method()->print_value_string(), p2i(pc), p2i(current));
 721     Exceptions::log_exception(exception, tempst.freeze());
 722   }
 723   // for AbortVMOnException flag
 724   Exceptions::debug_check_abort(exception);
 725 
 726   // Check the stack guard pages and re-enable them if necessary and there is
 727   // enough space on the stack to do so.  Use fast exceptions only if the guard
 728   // pages are enabled.
 729   bool guard_pages_enabled = current->stack_overflow_state()->reguard_stack_if_needed();
 730 
 731   if (JvmtiExport::can_post_on_exceptions()) {
 732     // To ensure correct notification of exception catches and throws
 733     // we have to deoptimize here.  If we attempted to notify the
 734     // catches and throws during this exception lookup it's possible
 735     // we could deoptimize on the way out of the VM and end back in
 736     // the interpreter at the throw site.  This would result in double
 737     // notifications since the interpreter would also notify about
 738     // these same catches and throws as it unwound the frame.
 739 
 740     RegisterMap reg_map(current,
 741                         RegisterMap::UpdateMap::include,
 742                         RegisterMap::ProcessFrames::include,
 743                         RegisterMap::WalkContinuation::skip);
 744     frame stub_frame = current->last_frame();
 745     frame caller_frame = stub_frame.sender(&reg_map);
 746 
 747     // We don't really want to deoptimize the nmethod itself since we
 748     // can actually continue in the exception handler ourselves but I
 749     // don't see an easy way to have the desired effect.
 750     Deoptimization::deoptimize_frame(current, caller_frame.id());
 751     assert(caller_is_deopted(current), "Must be deoptimized");
 752 
 753     return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
 754   }
 755 
 756   // ExceptionCache is used only for exceptions at call sites and not for implicit exceptions
 757   if (guard_pages_enabled) {
 758     address fast_continuation = nm->handler_for_exception_and_pc(exception, pc);
 759     if (fast_continuation != nullptr) {
 760       return fast_continuation;
 761     }
 762   }
 763 
 764   // If the stack guard pages are enabled, check whether there is a handler in
 765   // the current method.  Otherwise (guard pages disabled), force an unwind and
 766   // skip the exception cache update (i.e., just leave continuation as null).
 767   address continuation = nullptr;
 768   if (guard_pages_enabled) {
 769 
 770     // New exception handling mechanism can support inlined methods
 771     // with exception handlers since the mappings are from PC to PC
 772 
 773     // Clear out the exception oop and pc since looking up an
 774     // exception handler can cause class loading, which might throw an
 775     // exception and those fields are expected to be clear during
 776     // normal bytecode execution.
 777     current->clear_exception_oop_and_pc();
 778 
 779     bool recursive_exception = false;
 780     continuation = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, false, false, recursive_exception);
 781     // If an exception was thrown during exception dispatch, the exception oop may have changed
 782     current->set_exception_oop(exception());
 783     current->set_exception_pc(pc);
 784 
 785     // the exception cache is used only by non-implicit exceptions
 786     // Update the exception cache only when there didn't happen
 787     // another exception during the computation of the compiled
 788     // exception handler. Checking for exception oop equality is not
 789     // sufficient because some exceptions are pre-allocated and reused.
 790     if (continuation != nullptr && !recursive_exception) {
 791       nm->add_handler_for_exception_and_pc(exception, pc, continuation);
 792     }
 793   }
 794 
 795   current->set_vm_result_oop(exception());
 796 
 797   if (log_is_enabled(Info, exceptions)) {
 798     ResourceMark rm;
 799     log_info(exceptions)("Thread " PTR_FORMAT " continuing at PC " PTR_FORMAT
 800                          " for exception thrown at PC " PTR_FORMAT,
 801                          p2i(current), p2i(continuation), p2i(pc));
 802   }
 803 
 804   return continuation;
 805 JRT_END
 806 
 807 // Enter this method from compiled code only if there is a Java exception handler
 808 // in the method handling the exception.
 809 // We are entering here from exception stub. We don't do a normal VM transition here.
 810 // We do it in a helper. This is so we can check to see if the nmethod we have just
 811 // searched for an exception handler has been deoptimized in the meantime.
 812 address Runtime1::exception_handler_for_pc(JavaThread* current) {
 813   oop exception = current->exception_oop();
 814   address pc = current->exception_pc();
 815   // Still in Java mode
 816   DEBUG_ONLY(NoHandleMark nhm);
 817   nmethod* nm = nullptr;
 818   address continuation = nullptr;
 819   {
 820     // Enter VM mode by calling the helper
 821     ResetNoHandleMark rnhm;
 822     continuation = exception_handler_for_pc_helper(current, exception, pc, nm);
 823   }
 824   // Back in JAVA, use no oops DON'T safepoint
 825 
 826   // Now check to see if the nmethod we were called from is now deoptimized.
 827   // If so we must return to the deopt blob and deoptimize the nmethod
 828   if (nm != nullptr && caller_is_deopted(current)) {
 829     continuation = SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
 830   }
 831 
 832   assert(continuation != nullptr, "no handler found");
 833   return continuation;
 834 }
 835 
 836 
 837 JRT_ENTRY(void, Runtime1::throw_range_check_exception(JavaThread* current, int index, arrayOopDesc* a))
 838 #ifndef PRODUCT
 839   if (PrintC1Statistics) {
 840     _throw_range_check_exception_count++;
 841   }
 842 #endif
 843   const int len = 35;
 844   assert(len < strlen("Index %d out of bounds for length %d"), "Must allocate more space for message.");
 845   char message[2 * jintAsStringSize + len];
 846   os::snprintf_checked(message, sizeof(message), "Index %d out of bounds for length %d", index, a->length());
 847   SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), message);
 848 JRT_END
 849 
 850 
 851 JRT_ENTRY(void, Runtime1::throw_index_exception(JavaThread* current, int index))
 852 #ifndef PRODUCT
 853   if (PrintC1Statistics) {
 854     _throw_index_exception_count++;
 855   }
 856 #endif
 857   char message[16];
 858   os::snprintf_checked(message, sizeof(message), "%d", index);
 859   SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IndexOutOfBoundsException(), message);
 860 JRT_END
 861 
 862 
 863 JRT_ENTRY(void, Runtime1::throw_div0_exception(JavaThread* current))
 864 #ifndef PRODUCT
 865   if (PrintC1Statistics) {
 866     _throw_div0_exception_count++;
 867   }
 868 #endif
 869   SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArithmeticException(), "/ by zero");
 870 JRT_END
 871 
 872 
 873 JRT_ENTRY(void, Runtime1::throw_null_pointer_exception(JavaThread* current))
 874 #ifndef PRODUCT
 875   if (PrintC1Statistics) {
 876     _throw_null_pointer_exception_count++;
 877   }
 878 #endif
 879   SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_NullPointerException());
 880 JRT_END
 881 
 882 
 883 JRT_ENTRY(void, Runtime1::throw_class_cast_exception(JavaThread* current, oopDesc* object))
 884 #ifndef PRODUCT
 885   if (PrintC1Statistics) {
 886     _throw_class_cast_exception_count++;
 887   }
 888 #endif
 889   ResourceMark rm(current);
 890   char* message = SharedRuntime::generate_class_cast_message(current, object->klass());
 891   SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ClassCastException(), message);
 892 JRT_END
 893 
 894 
 895 JRT_ENTRY(void, Runtime1::throw_incompatible_class_change_error(JavaThread* current))
 896 #ifndef PRODUCT
 897   if (PrintC1Statistics) {
 898     _throw_incompatible_class_change_error_count++;
 899   }
 900 #endif
 901   ResourceMark rm(current);
 902   SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IncompatibleClassChangeError());
 903 JRT_END
 904 
 905 
 906 JRT_ENTRY(void, Runtime1::throw_illegal_monitor_state_exception(JavaThread* current))
 907   NOT_PRODUCT(_throw_illegal_monitor_state_exception_count++;)
 908   ResourceMark rm(current);
 909   SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IllegalMonitorStateException());
 910 JRT_END
 911 
 912 JRT_ENTRY(void, Runtime1::throw_identity_exception(JavaThread* current, oopDesc* object))
 913   NOT_PRODUCT(_throw_identity_exception_count++;)
 914   ResourceMark rm(current);
 915   char* message = SharedRuntime::generate_identity_exception_message(current, object->klass());
 916   SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IdentityException(), message);
 917 JRT_END
 918 
 919 JRT_BLOCK_ENTRY(void, Runtime1::monitorenter(JavaThread* current, oopDesc* obj, BasicObjectLock* lock))
 920 #ifndef PRODUCT
 921   if (PrintC1Statistics) {
 922     _monitorenter_slowcase_cnt++;
 923   }
 924 #endif
 925   assert(obj == lock->obj(), "must match");
 926   SharedRuntime::monitor_enter_helper(obj, lock->lock(), current);
 927 JRT_END
 928 
 929 
 930 JRT_LEAF(void, Runtime1::monitorexit(JavaThread* current, BasicObjectLock* lock))
 931   assert(current == JavaThread::current(), "pre-condition");
 932 #ifndef PRODUCT
 933   if (PrintC1Statistics) {
 934     _monitorexit_slowcase_cnt++;
 935   }
 936 #endif
 937   assert(current->last_Java_sp(), "last_Java_sp must be set");
 938   oop obj = lock->obj();
 939   assert(oopDesc::is_oop(obj), "must be null or an object");
 940   SharedRuntime::monitor_exit_helper(obj, lock->lock(), current);
 941 JRT_END
 942 
 943 // Cf. OptoRuntime::deoptimize_caller_frame
 944 JRT_ENTRY(void, Runtime1::deoptimize(JavaThread* current, jint trap_request))
 945   // Called from within the owner thread, so no need for safepoint
 946   RegisterMap reg_map(current,
 947                       RegisterMap::UpdateMap::skip,
 948                       RegisterMap::ProcessFrames::include,
 949                       RegisterMap::WalkContinuation::skip);
 950   frame stub_frame = current->last_frame();
 951   assert(stub_frame.is_runtime_frame(), "Sanity check");
 952   frame caller_frame = stub_frame.sender(&reg_map);
 953   nmethod* nm = caller_frame.cb()->as_nmethod_or_null();
 954   assert(nm != nullptr, "Sanity check");
 955   methodHandle method(current, nm->method());
 956   assert(nm == CodeCache::find_nmethod(caller_frame.pc()), "Should be the same");
 957   Deoptimization::DeoptAction action = Deoptimization::trap_request_action(trap_request);
 958   Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);
 959 
 960   if (action == Deoptimization::Action_make_not_entrant) {
 961     if (nm->make_not_entrant(nmethod::InvalidationReason::C1_DEOPTIMIZE)) {
 962       if (reason == Deoptimization::Reason_tenured) {
 963         MethodData* trap_mdo = Deoptimization::get_method_data(current, method, true /*create_if_missing*/);
 964         if (trap_mdo != nullptr) {
 965           trap_mdo->inc_tenure_traps();
 966         }
 967       }
 968     }
 969   }
 970 
 971   // Deoptimize the caller frame.
 972   Deoptimization::deoptimize_frame(current, caller_frame.id());
 973   // Return to the now deoptimized frame.
 974 JRT_END
 975 
 976 
 977 #ifndef DEOPTIMIZE_WHEN_PATCHING
 978 
 979 static Klass* resolve_field_return_klass(const methodHandle& caller, int bci, TRAPS) {
 980   Bytecode_field field_access(caller, bci);
 981   // This can be static or non-static field access
 982   Bytecodes::Code code       = field_access.code();
 983 
 984   // We must load class, initialize class and resolve the field
 985   fieldDescriptor result; // initialize class if needed
 986   constantPoolHandle constants(THREAD, caller->constants());
 987   LinkResolver::resolve_field_access(result, constants, field_access.index(), caller, Bytecodes::java_code(code), CHECK_NULL);
 988   return result.field_holder();
 989 }
 990 
 991 
 992 //
 993 // This routine patches sites where a class wasn't loaded or
 994 // initialized at the time the code was generated.  It handles
 995 // references to classes, fields and forcing of initialization.  Most
 996 // of the cases are straightforward and involving simply forcing
 997 // resolution of a class, rewriting the instruction stream with the
 998 // needed constant and replacing the call in this function with the
 999 // patched code.  The case for static field is more complicated since
1000 // the thread which is in the process of initializing a class can
1001 // access it's static fields but other threads can't so the code
1002 // either has to deoptimize when this case is detected or execute a
1003 // check that the current thread is the initializing thread.  The
1004 // current
1005 //
1006 // Patches basically look like this:
1007 //
1008 //
1009 // patch_site: jmp patch stub     ;; will be patched
1010 // continue:   ...
1011 //             ...
1012 //             ...
1013 //             ...
1014 //
1015 // They have a stub which looks like this:
1016 //
1017 //             ;; patch body
1018 //             movl <const>, reg           (for class constants)
1019 //        <or> movl [reg1 + <const>], reg  (for field offsets)
1020 //        <or> movl reg, [reg1 + <const>]  (for field offsets)
1021 //             <being_init offset> <bytes to copy> <bytes to skip>
1022 // patch_stub: call Runtime1::patch_code (through a runtime stub)
1023 //             jmp patch_site
1024 //
1025 //
1026 // A normal patch is done by rewriting the patch body, usually a move,
1027 // and then copying it into place over top of the jmp instruction
1028 // being careful to flush caches and doing it in an MP-safe way.  The
1029 // constants following the patch body are used to find various pieces
1030 // of the patch relative to the call site for Runtime1::patch_code.
1031 // The case for getstatic and putstatic is more complicated because
1032 // getstatic and putstatic have special semantics when executing while
1033 // the class is being initialized.  getstatic/putstatic on a class
1034 // which is being_initialized may be executed by the initializing
1035 // thread but other threads have to block when they execute it.  This
1036 // is accomplished in compiled code by executing a test of the current
1037 // thread against the initializing thread of the class.  It's emitted
1038 // as boilerplate in their stub which allows the patched code to be
1039 // executed before it's copied back into the main body of the nmethod.
1040 //
1041 // being_init: get_thread(<tmp reg>
1042 //             cmpl [reg1 + <init_thread_offset>], <tmp reg>
1043 //             jne patch_stub
1044 //             movl [reg1 + <const>], reg  (for field offsets)  <or>
1045 //             movl reg, [reg1 + <const>]  (for field offsets)
1046 //             jmp continue
1047 //             <being_init offset> <bytes to copy> <bytes to skip>
1048 // patch_stub: jmp Runtime1::patch_code (through a runtime stub)
1049 //             jmp patch_site
1050 //
1051 // If the class is being initialized the patch body is rewritten and
1052 // the patch site is rewritten to jump to being_init, instead of
1053 // patch_stub.  Whenever this code is executed it checks the current
1054 // thread against the initializing thread so other threads will enter
1055 // the runtime and end up blocked waiting the class to finish
1056 // initializing inside the calls to resolve_field below.  The
1057 // initializing class will continue on it's way.  Once the class is
1058 // fully_initialized, the intializing_thread of the class becomes
1059 // null, so the next thread to execute this code will fail the test,
1060 // call into patch_code and complete the patching process by copying
1061 // the patch body back into the main part of the nmethod and resume
1062 // executing.
1063 
1064 // NB:
1065 //
1066 // Patchable instruction sequences inherently exhibit race conditions,
1067 // where thread A is patching an instruction at the same time thread B
1068 // is executing it.  The algorithms we use ensure that any observation
1069 // that B can make on any intermediate states during A's patching will
1070 // always end up with a correct outcome.  This is easiest if there are
1071 // few or no intermediate states.  (Some inline caches have two
1072 // related instructions that must be patched in tandem.  For those,
1073 // intermediate states seem to be unavoidable, but we will get the
1074 // right answer from all possible observation orders.)
1075 //
1076 // When patching the entry instruction at the head of a method, or a
1077 // linkable call instruction inside of a method, we try very hard to
1078 // use a patch sequence which executes as a single memory transaction.
1079 // This means, in practice, that when thread A patches an instruction,
1080 // it should patch a 32-bit or 64-bit word that somehow overlaps the
1081 // instruction or is contained in it.  We believe that memory hardware
1082 // will never break up such a word write, if it is naturally aligned
1083 // for the word being written.  We also know that some CPUs work very
1084 // hard to create atomic updates even of naturally unaligned words,
1085 // but we don't want to bet the farm on this always working.
1086 //
1087 // Therefore, if there is any chance of a race condition, we try to
1088 // patch only naturally aligned words, as single, full-word writes.
1089 
1090 JRT_ENTRY(void, Runtime1::patch_code(JavaThread* current, StubId stub_id ))
1091 #ifndef PRODUCT
1092   if (PrintC1Statistics) {
1093     _patch_code_slowcase_cnt++;
1094   }
1095 #endif
1096 
1097   ResourceMark rm(current);
1098   RegisterMap reg_map(current,
1099                       RegisterMap::UpdateMap::skip,
1100                       RegisterMap::ProcessFrames::include,
1101                       RegisterMap::WalkContinuation::skip);
1102   frame runtime_frame = current->last_frame();
1103   frame caller_frame = runtime_frame.sender(&reg_map);
1104 
1105   // last java frame on stack
1106   vframeStream vfst(current, true);
1107   assert(!vfst.at_end(), "Java frame must exist");
1108 
1109   methodHandle caller_method(current, vfst.method());
1110   // Note that caller_method->code() may not be same as caller_code because of OSR's
1111   // Note also that in the presence of inlining it is not guaranteed
1112   // that caller_method() == caller_code->method()
1113 
1114   int bci = vfst.bci();
1115   Bytecodes::Code code = caller_method()->java_code_at(bci);
1116 
1117   // this is used by assertions in the access_field_patching_id
1118   BasicType patch_field_type = T_ILLEGAL;
1119   bool deoptimize_for_volatile = false;
1120   bool deoptimize_for_atomic = false;
1121   bool deoptimize_for_null_free = false;
1122   bool deoptimize_for_flat = false;
1123   bool deoptimize_for_strict_static = false;
1124   int patch_field_offset = -1;
1125   Klass* init_klass = nullptr; // klass needed by load_klass_patching code
1126   Klass* load_klass = nullptr; // klass needed by load_klass_patching code
1127   Handle mirror(current, nullptr); // oop needed by load_mirror_patching code
1128   Handle appendix(current, nullptr); // oop needed by appendix_patching code
1129   bool load_klass_or_mirror_patch_id =
1130     (stub_id == StubId::c1_load_klass_patching_id || stub_id == StubId::c1_load_mirror_patching_id);
1131 
1132   if (stub_id == StubId::c1_access_field_patching_id) {
1133 
1134     Bytecode_field field_access(caller_method, bci);
1135     fieldDescriptor result; // initialize class if needed
1136     Bytecodes::Code code = field_access.code();
1137     constantPoolHandle constants(current, caller_method->constants());
1138     LinkResolver::resolve_field_access(result, constants, field_access.index(), caller_method, Bytecodes::java_code(code), CHECK);
1139     patch_field_offset = result.offset();
1140 
1141     // If we're patching a field which is volatile then at compile it
1142     // must not have been know to be volatile, so the generated code
1143     // isn't correct for a volatile reference.  The nmethod has to be
1144     // deoptimized so that the code can be regenerated correctly.
1145     // This check is only needed for access_field_patching since this
1146     // is the path for patching field offsets.  load_klass is only
1147     // used for patching references to oops which don't need special
1148     // handling in the volatile case.
1149 
1150     deoptimize_for_volatile = result.access_flags().is_volatile();
1151 
1152     // If we are patching a field which should be atomic, then
1153     // the generated code is not correct either, force deoptimizing.
1154     // We need to only cover T_LONG and T_DOUBLE fields, as we can
1155     // break access atomicity only for them.
1156 
1157     // Strictly speaking, the deoptimization on 64-bit platforms
1158     // is unnecessary, and T_LONG stores on 32-bit platforms need
1159     // to be handled by special patching code when AlwaysAtomicAccesses
1160     // becomes product feature. At this point, we are still going
1161     // for the deoptimization for consistency against volatile
1162     // accesses.
1163 
1164     patch_field_type = result.field_type();
1165     deoptimize_for_atomic = (AlwaysAtomicAccesses && (patch_field_type == T_DOUBLE || patch_field_type == T_LONG));
1166 
1167     // The field we are patching is null-free. Deoptimize and regenerate
1168     // the compiled code if we patch a putfield/putstatic because it
1169     // does not contain the required null check.
1170     deoptimize_for_null_free = result.is_null_free_inline_type() && (field_access.is_putfield() || field_access.is_putstatic());
1171 
1172     // The field we are patching is flat. Deoptimize and regenerate
1173     // the compiled code which can't handle the layout of the flat
1174     // field because it was unknown at compile time.
1175     deoptimize_for_flat = result.is_flat();
1176 
1177     // Strict statics may require tracking if their class is not fully initialized.
1178     // For now we can bail out of the compiler and let the interpreter handle it.
1179     deoptimize_for_strict_static = result.is_strict_static_unset();
1180   } else if (load_klass_or_mirror_patch_id) {
1181     Klass* k = nullptr;
1182     switch (code) {
1183       case Bytecodes::_putstatic:
1184       case Bytecodes::_getstatic:
1185         { Klass* klass = resolve_field_return_klass(caller_method, bci, CHECK);
1186           init_klass = klass;
1187           mirror = Handle(current, klass->java_mirror());
1188         }
1189         break;
1190       case Bytecodes::_new:
1191         { Bytecode_new bnew(caller_method(), caller_method->bcp_from(bci));
1192           k = caller_method->constants()->klass_at(bnew.index(), CHECK);
1193         }
1194         break;
1195       case Bytecodes::_multianewarray:
1196         { Bytecode_multianewarray mna(caller_method(), caller_method->bcp_from(bci));
1197           k = caller_method->constants()->klass_at(mna.index(), CHECK);
1198         }
1199         break;
1200       case Bytecodes::_instanceof:
1201         { Bytecode_instanceof io(caller_method(), caller_method->bcp_from(bci));
1202           k = caller_method->constants()->klass_at(io.index(), CHECK);
1203         }
1204         break;
1205       case Bytecodes::_checkcast:
1206         { Bytecode_checkcast cc(caller_method(), caller_method->bcp_from(bci));
1207           k = caller_method->constants()->klass_at(cc.index(), CHECK);
1208         }
1209         break;
1210       case Bytecodes::_anewarray:
1211         { Bytecode_anewarray anew(caller_method(), caller_method->bcp_from(bci));
1212           Klass* ek = caller_method->constants()->klass_at(anew.index(), CHECK);
1213           k = ek->array_klass(CHECK);
1214           if (!k->is_typeArray_klass() && !k->is_refArray_klass() && !k->is_flatArray_klass()) {
1215             k = ObjArrayKlass::cast(k)->klass_with_properties(ArrayProperties::Default(), THREAD);
1216           }
1217           if (k->is_flatArray_klass()) {
1218             deoptimize_for_flat = true;
1219           }
1220         }
1221         break;
1222       case Bytecodes::_ldc:
1223       case Bytecodes::_ldc_w:
1224       case Bytecodes::_ldc2_w:
1225         {
1226           Bytecode_loadconstant cc(caller_method, bci);
1227           oop m = cc.resolve_constant(CHECK);
1228           mirror = Handle(current, m);
1229         }
1230         break;
1231       default: fatal("unexpected bytecode for load_klass_or_mirror_patch_id");
1232     }
1233     load_klass = k;
1234   } else if (stub_id == StubId::c1_load_appendix_patching_id) {
1235     Bytecode_invoke bytecode(caller_method, bci);
1236     Bytecodes::Code bc = bytecode.invoke_code();
1237 
1238     CallInfo info;
1239     constantPoolHandle pool(current, caller_method->constants());
1240     int index = bytecode.index();
1241     LinkResolver::resolve_invoke(info, Handle(), pool, index, bc, CHECK);
1242     switch (bc) {
1243       case Bytecodes::_invokehandle: {
1244         ResolvedMethodEntry* entry = pool->cache()->set_method_handle(index, info);
1245         appendix = Handle(current, pool->cache()->appendix_if_resolved(entry));
1246         break;
1247       }
1248       case Bytecodes::_invokedynamic: {
1249         appendix = Handle(current, pool->cache()->set_dynamic_call(info, index));
1250         break;
1251       }
1252       default: fatal("unexpected bytecode for load_appendix_patching_id");
1253     }
1254   } else {
1255     ShouldNotReachHere();
1256   }
1257 
1258   if (deoptimize_for_volatile  ||
1259       deoptimize_for_atomic    ||
1260       deoptimize_for_null_free ||
1261       deoptimize_for_flat      ||
1262       deoptimize_for_strict_static) {
1263     // At compile time we assumed the field wasn't volatile/atomic but after
1264     // loading it turns out it was volatile/atomic so we have to throw the
1265     // compiled code out and let it be regenerated.
1266     if (TracePatching) {
1267       if (deoptimize_for_volatile) {
1268         tty->print_cr("Deoptimizing for patching volatile field reference");
1269       }
1270       if (deoptimize_for_atomic) {
1271         tty->print_cr("Deoptimizing for patching atomic field reference");
1272       }
1273       if (deoptimize_for_null_free) {
1274         tty->print_cr("Deoptimizing for patching null-free field reference");
1275       }
1276       if (deoptimize_for_flat) {
1277         tty->print_cr("Deoptimizing for patching flat field or array reference");
1278       }
1279       if (deoptimize_for_strict_static) {
1280         tty->print_cr("Deoptimizing for patching strict static field reference");
1281       }
1282     }
1283 
1284     // It's possible the nmethod was invalidated in the last
1285     // safepoint, but if it's still alive then make it not_entrant.
1286     nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
1287     if (nm != nullptr) {
1288       nm->make_not_entrant(nmethod::InvalidationReason::C1_CODEPATCH);
1289     }
1290 
1291     Deoptimization::deoptimize_frame(current, caller_frame.id());
1292 
1293     // Return to the now deoptimized frame.
1294   }
1295 
1296   // Now copy code back
1297 
1298   {
1299     MutexLocker ml_code (current, CodeCache_lock, Mutex::_no_safepoint_check_flag);
1300     //
1301     // Deoptimization may have happened while we waited for the lock.
1302     // In that case we don't bother to do any patching we just return
1303     // and let the deopt happen
1304     if (!caller_is_deopted(current)) {
1305       NativeGeneralJump* jump = nativeGeneralJump_at(caller_frame.pc());
1306       address instr_pc = jump->jump_destination();
1307       NativeInstruction* ni = nativeInstruction_at(instr_pc);
1308       if (ni->is_jump() ) {
1309         // the jump has not been patched yet
1310         // The jump destination is slow case and therefore not part of the stubs
1311         // (stubs are only for StaticCalls)
1312 
1313         // format of buffer
1314         //    ....
1315         //    instr byte 0     <-- copy_buff
1316         //    instr byte 1
1317         //    ..
1318         //    instr byte n-1
1319         //      n
1320         //    ....             <-- call destination
1321 
1322         address stub_location = caller_frame.pc() + PatchingStub::patch_info_offset();
1323         unsigned char* byte_count = (unsigned char*) (stub_location - 1);
1324         unsigned char* byte_skip = (unsigned char*) (stub_location - 2);
1325         unsigned char* being_initialized_entry_offset = (unsigned char*) (stub_location - 3);
1326         address copy_buff = stub_location - *byte_skip - *byte_count;
1327         address being_initialized_entry = stub_location - *being_initialized_entry_offset;
1328         if (TracePatching) {
1329           ttyLocker ttyl;
1330           tty->print_cr(" Patching %s at bci %d at address " INTPTR_FORMAT "  (%s)", Bytecodes::name(code), bci,
1331                         p2i(instr_pc), (stub_id == StubId::c1_access_field_patching_id) ? "field" : "klass");
1332           nmethod* caller_code = CodeCache::find_nmethod(caller_frame.pc());
1333           assert(caller_code != nullptr, "nmethod not found");
1334 
1335           // NOTE we use pc() not original_pc() because we already know they are
1336           // identical otherwise we'd have never entered this block of code
1337 
1338           const ImmutableOopMap* map = caller_code->oop_map_for_return_address(caller_frame.pc());
1339           assert(map != nullptr, "null check");
1340           map->print();
1341           tty->cr();
1342 
1343           Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
1344         }
1345         // depending on the code below, do_patch says whether to copy the patch body back into the nmethod
1346         bool do_patch = true;
1347         if (stub_id == StubId::c1_access_field_patching_id) {
1348           // The offset may not be correct if the class was not loaded at code generation time.
1349           // Set it now.
1350           NativeMovRegMem* n_move = nativeMovRegMem_at(copy_buff);
1351           assert(n_move->offset() == 0 || (n_move->offset() == 4 && (patch_field_type == T_DOUBLE || patch_field_type == T_LONG)), "illegal offset for type");
1352           assert(patch_field_offset >= 0, "illegal offset");
1353           n_move->add_offset_in_bytes(patch_field_offset);
1354         } else if (load_klass_or_mirror_patch_id) {
1355           // If a getstatic or putstatic is referencing a klass which
1356           // isn't fully initialized, the patch body isn't copied into
1357           // place until initialization is complete.  In this case the
1358           // patch site is setup so that any threads besides the
1359           // initializing thread are forced to come into the VM and
1360           // block.
1361           do_patch = (code != Bytecodes::_getstatic && code != Bytecodes::_putstatic) ||
1362                      InstanceKlass::cast(init_klass)->is_initialized();
1363           NativeGeneralJump* jump = nativeGeneralJump_at(instr_pc);
1364           if (jump->jump_destination() == being_initialized_entry) {
1365             assert(do_patch == true, "initialization must be complete at this point");
1366           } else {
1367             // patch the instruction <move reg, klass>
1368             NativeMovConstReg* n_copy = nativeMovConstReg_at(copy_buff);
1369 
1370             assert(n_copy->data() == 0 ||
1371                    n_copy->data() == (intptr_t)Universe::non_oop_word(),
1372                    "illegal init value");
1373             if (stub_id == StubId::c1_load_klass_patching_id) {
1374               assert(load_klass != nullptr, "klass not set");
1375               n_copy->set_data((intx) (load_klass));
1376             } else {
1377               // Don't need a G1 pre-barrier here since we assert above that data isn't an oop.
1378               n_copy->set_data(cast_from_oop<intx>(mirror()));
1379             }
1380 
1381             if (TracePatching) {
1382               Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
1383             }
1384           }
1385         } else if (stub_id == StubId::c1_load_appendix_patching_id) {
1386           NativeMovConstReg* n_copy = nativeMovConstReg_at(copy_buff);
1387           assert(n_copy->data() == 0 ||
1388                  n_copy->data() == (intptr_t)Universe::non_oop_word(),
1389                  "illegal init value");
1390           n_copy->set_data(cast_from_oop<intx>(appendix()));
1391 
1392           if (TracePatching) {
1393             Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
1394           }
1395         } else {
1396           ShouldNotReachHere();
1397         }
1398 
1399         if (do_patch) {
1400           // replace instructions
1401           // first replace the tail, then the call
1402 #ifdef ARM
1403           if((load_klass_or_mirror_patch_id ||
1404               stub_id == StubId::c1_load_appendix_patching_id) &&
1405               nativeMovConstReg_at(copy_buff)->is_pc_relative()) {
1406             nmethod* nm = CodeCache::find_nmethod(instr_pc);
1407             address addr = nullptr;
1408             assert(nm != nullptr, "invalid nmethod_pc");
1409             RelocIterator mds(nm, copy_buff, copy_buff + 1);
1410             while (mds.next()) {
1411               if (mds.type() == relocInfo::oop_type) {
1412                 assert(stub_id == StubId::c1_load_mirror_patching_id ||
1413                        stub_id == StubId::c1_load_appendix_patching_id, "wrong stub id");
1414                 oop_Relocation* r = mds.oop_reloc();
1415                 addr = (address)r->oop_addr();
1416                 break;
1417               } else if (mds.type() == relocInfo::metadata_type) {
1418                 assert(stub_id == StubId::c1_load_klass_patching_id, "wrong stub id");
1419                 metadata_Relocation* r = mds.metadata_reloc();
1420                 addr = (address)r->metadata_addr();
1421                 break;
1422               }
1423             }
1424             assert(addr != nullptr, "metadata relocation must exist");
1425             copy_buff -= *byte_count;
1426             NativeMovConstReg* n_copy2 = nativeMovConstReg_at(copy_buff);
1427             n_copy2->set_pc_relative_offset(addr, instr_pc);
1428           }
1429 #endif
1430 
1431           for (int i = NativeGeneralJump::instruction_size; i < *byte_count; i++) {
1432             address ptr = copy_buff + i;
1433             int a_byte = (*ptr) & 0xFF;
1434             address dst = instr_pc + i;
1435             *(unsigned char*)dst = (unsigned char) a_byte;
1436           }
1437           ICache::invalidate_range(instr_pc, *byte_count);
1438           NativeGeneralJump::replace_mt_safe(instr_pc, copy_buff);
1439 
1440           if (load_klass_or_mirror_patch_id ||
1441               stub_id == StubId::c1_load_appendix_patching_id) {
1442             relocInfo::relocType rtype =
1443               (stub_id == StubId::c1_load_klass_patching_id) ?
1444                                    relocInfo::metadata_type :
1445                                    relocInfo::oop_type;
1446             // update relocInfo to metadata
1447             nmethod* nm = CodeCache::find_nmethod(instr_pc);
1448             assert(nm != nullptr, "invalid nmethod_pc");
1449 
1450             // The old patch site is now a move instruction so update
1451             // the reloc info so that it will get updated during
1452             // future GCs.
1453             RelocIterator iter(nm, (address)instr_pc, (address)(instr_pc + 1));
1454             relocInfo::change_reloc_info_for_address(&iter, (address) instr_pc,
1455                                                      relocInfo::none, rtype);
1456           }
1457 
1458         } else {
1459           ICache::invalidate_range(copy_buff, *byte_count);
1460           NativeGeneralJump::insert_unconditional(instr_pc, being_initialized_entry);
1461         }
1462       }
1463     }
1464     // If we are patching in a non-perm oop, make sure the nmethod
1465     // is on the right list.
1466     nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
1467     guarantee(nm != nullptr, "only nmethods can contain non-perm oops");
1468 
1469     // Since we've patched some oops in the nmethod,
1470     // (re)register it with the heap.
1471     Universe::heap()->register_nmethod(nm);
1472   }
1473 JRT_END
1474 
1475 #else // DEOPTIMIZE_WHEN_PATCHING
1476 
1477 static bool is_patching_needed(JavaThread* current, StubId stub_id) {
1478   if (stub_id == StubId::c1_load_klass_patching_id ||
1479       stub_id == StubId::c1_load_mirror_patching_id) {
1480     // last java frame on stack
1481     vframeStream vfst(current, true);
1482     assert(!vfst.at_end(), "Java frame must exist");
1483 
1484     methodHandle caller_method(current, vfst.method());
1485     int bci = vfst.bci();
1486     Bytecodes::Code code = caller_method()->java_code_at(bci);
1487 
1488     switch (code) {
1489       case Bytecodes::_new:
1490       case Bytecodes::_anewarray:
1491       case Bytecodes::_multianewarray:
1492       case Bytecodes::_instanceof:
1493       case Bytecodes::_checkcast: {
1494         Bytecode bc(caller_method(), caller_method->bcp_from(bci));
1495         constantTag tag = caller_method->constants()->tag_at(bc.get_index_u2(code));
1496         if (tag.is_unresolved_klass_in_error()) {
1497           return false; // throws resolution error
1498         }
1499         break;
1500       }
1501 
1502       default: break;
1503     }
1504   }
1505   return true;
1506 }
1507 
1508 void Runtime1::patch_code(JavaThread* current, StubId stub_id) {
1509 #ifndef PRODUCT
1510   if (PrintC1Statistics) {
1511     _patch_code_slowcase_cnt++;
1512   }
1513 #endif
1514 
1515   // Enable WXWrite: the function is called by c1 stub as a runtime function
1516   // (see another implementation above).
1517   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current));
1518 
1519   if (TracePatching) {
1520     tty->print_cr("Deoptimizing because patch is needed");
1521   }
1522 
1523   RegisterMap reg_map(current,
1524                       RegisterMap::UpdateMap::skip,
1525                       RegisterMap::ProcessFrames::include,
1526                       RegisterMap::WalkContinuation::skip);
1527 
1528   frame runtime_frame = current->last_frame();
1529   frame caller_frame = runtime_frame.sender(&reg_map);
1530   assert(caller_frame.is_compiled_frame(), "Wrong frame type");
1531 
1532   if (is_patching_needed(current, stub_id)) {
1533     // Make sure the nmethod is invalidated, i.e. made not entrant.
1534     nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
1535     if (nm != nullptr) {
1536       nm->make_not_entrant(nmethod::InvalidationReason::C1_DEOPTIMIZE_FOR_PATCHING);
1537     }
1538   }
1539 
1540   Deoptimization::deoptimize_frame(current, caller_frame.id());
1541   // Return to the now deoptimized frame.
1542   postcond(caller_is_deopted(current));
1543 }
1544 
1545 #endif // DEOPTIMIZE_WHEN_PATCHING
1546 
1547 // Entry point for compiled code. We want to patch a nmethod.
1548 // We don't do a normal VM transition here because we want to
1549 // know after the patching is complete and any safepoint(s) are taken
1550 // if the calling nmethod was deoptimized. We do this by calling a
1551 // helper method which does the normal VM transition and when it
1552 // completes we can check for deoptimization. This simplifies the
1553 // assembly code in the cpu directories.
1554 //
1555 int Runtime1::move_klass_patching(JavaThread* current) {
1556 //
1557 // NOTE: we are still in Java
1558 //
1559   DEBUG_ONLY(NoHandleMark nhm;)
1560   {
1561     // Enter VM mode
1562     ResetNoHandleMark rnhm;
1563     patch_code(current, StubId::c1_load_klass_patching_id);
1564   }
1565   // Back in JAVA, use no oops DON'T safepoint
1566 
1567   // Return true if calling code is deoptimized
1568 
1569   return caller_is_deopted(current);
1570 }
1571 
1572 int Runtime1::move_mirror_patching(JavaThread* current) {
1573 //
1574 // NOTE: we are still in Java
1575 //
1576   DEBUG_ONLY(NoHandleMark nhm;)
1577   {
1578     // Enter VM mode
1579     ResetNoHandleMark rnhm;
1580     patch_code(current, StubId::c1_load_mirror_patching_id);
1581   }
1582   // Back in JAVA, use no oops DON'T safepoint
1583 
1584   // Return true if calling code is deoptimized
1585 
1586   return caller_is_deopted(current);
1587 }
1588 
1589 int Runtime1::move_appendix_patching(JavaThread* current) {
1590 //
1591 // NOTE: we are still in Java
1592 //
1593   DEBUG_ONLY(NoHandleMark nhm;)
1594   {
1595     // Enter VM mode
1596     ResetNoHandleMark rnhm;
1597     patch_code(current, StubId::c1_load_appendix_patching_id);
1598   }
1599   // Back in JAVA, use no oops DON'T safepoint
1600 
1601   // Return true if calling code is deoptimized
1602 
1603   return caller_is_deopted(current);
1604 }
1605 
1606 // Entry point for compiled code. We want to patch a nmethod.
1607 // We don't do a normal VM transition here because we want to
1608 // know after the patching is complete and any safepoint(s) are taken
1609 // if the calling nmethod was deoptimized. We do this by calling a
1610 // helper method which does the normal VM transition and when it
1611 // completes we can check for deoptimization. This simplifies the
1612 // assembly code in the cpu directories.
1613 //
1614 int Runtime1::access_field_patching(JavaThread* current) {
1615   //
1616   // NOTE: we are still in Java
1617   //
1618   // Handles created in this function will be deleted by the
1619   // HandleMarkCleaner in the transition to the VM.
1620   NoHandleMark nhm;
1621   {
1622     // Enter VM mode
1623     ResetNoHandleMark rnhm;
1624     patch_code(current, StubId::c1_access_field_patching_id);
1625   }
1626   // Back in JAVA, use no oops DON'T safepoint
1627 
1628   // Return true if calling code is deoptimized
1629 
1630   return caller_is_deopted(current);
1631 }
1632 
1633 
1634 JRT_LEAF(void, Runtime1::trace_block_entry(jint block_id))
1635   // for now we just print out the block id
1636   tty->print("%d ", block_id);
1637 JRT_END
1638 
1639 
1640 JRT_LEAF(int, Runtime1::is_instance_of(oopDesc* mirror, oopDesc* obj))
1641   // had to return int instead of bool, otherwise there may be a mismatch
1642   // between the C calling convention and the Java one.
1643   // e.g., on x86, GCC may clear only %al when returning a bool false, but
1644   // JVM takes the whole %eax as the return value, which may misinterpret
1645   // the return value as a boolean true.
1646 
1647   assert(mirror != nullptr, "should null-check on mirror before calling");
1648   Klass* k = java_lang_Class::as_Klass(mirror);
1649   return (k != nullptr && obj != nullptr && obj->is_a(k)) ? 1 : 0;
1650 JRT_END
1651 
1652 JRT_ENTRY(void, Runtime1::predicate_failed_trap(JavaThread* current))
1653   ResourceMark rm;
1654 
1655   RegisterMap reg_map(current,
1656                       RegisterMap::UpdateMap::skip,
1657                       RegisterMap::ProcessFrames::include,
1658                       RegisterMap::WalkContinuation::skip);
1659   frame runtime_frame = current->last_frame();
1660   frame caller_frame = runtime_frame.sender(&reg_map);
1661 
1662   nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
1663   assert (nm != nullptr, "no more nmethod?");
1664   nm->make_not_entrant(nmethod::InvalidationReason::C1_PREDICATE_FAILED_TRAP);
1665 
1666   methodHandle m(current, nm->method());
1667   MethodData* mdo = m->method_data();
1668 
1669   if (mdo == nullptr && !HAS_PENDING_EXCEPTION) {
1670     // Build an MDO.  Ignore errors like OutOfMemory;
1671     // that simply means we won't have an MDO to update.
1672     Method::build_profiling_method_data(m, THREAD);
1673     if (HAS_PENDING_EXCEPTION) {
1674       // Only metaspace OOM is expected. No Java code executed.
1675       assert((PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())), "we expect only an OOM error here");
1676       CLEAR_PENDING_EXCEPTION;
1677     }
1678     mdo = m->method_data();
1679   }
1680 
1681   if (mdo != nullptr) {
1682     mdo->inc_trap_count(Deoptimization::Reason_none);
1683   }
1684 
1685   if (TracePredicateFailedTraps) {
1686     stringStream ss1, ss2;
1687     vframeStream vfst(current);
1688     Method* inlinee = vfst.method();
1689     inlinee->print_short_name(&ss1);
1690     m->print_short_name(&ss2);
1691     tty->print_cr("Predicate failed trap in method %s at bci %d inlined in %s at pc " INTPTR_FORMAT, ss1.freeze(), vfst.bci(), ss2.freeze(), p2i(caller_frame.pc()));
1692   }
1693 
1694 
1695   Deoptimization::deoptimize_frame(current, caller_frame.id());
1696 
1697 JRT_END
1698 
1699 // Check exception if AbortVMOnException flag set
1700 JRT_LEAF(void, Runtime1::check_abort_on_vm_exception(oopDesc* ex))
1701   ResourceMark rm;
1702   const char* message = nullptr;
1703   if (ex->is_a(vmClasses::Throwable_klass())) {
1704     oop msg = java_lang_Throwable::message(ex);
1705     if (msg != nullptr) {
1706       message = java_lang_String::as_utf8_string(msg);
1707     }
1708   }
1709   Exceptions::debug_check_abort(ex->klass()->external_name(), message);
1710 JRT_END
1711 
1712 #ifndef PRODUCT
1713 void Runtime1::print_statistics() {
1714   tty->print_cr("C1 Runtime statistics:");
1715   tty->print_cr(" _resolve_invoke_virtual_cnt:     %u", SharedRuntime::_resolve_virtual_ctr);
1716   tty->print_cr(" _resolve_invoke_opt_virtual_cnt: %u", SharedRuntime::_resolve_opt_virtual_ctr);
1717   tty->print_cr(" _resolve_invoke_static_cnt:      %u", SharedRuntime::_resolve_static_ctr);
1718   tty->print_cr(" _handle_wrong_method_cnt:        %u", SharedRuntime::_wrong_method_ctr);
1719   tty->print_cr(" _ic_miss_cnt:                    %u", SharedRuntime::_ic_miss_ctr);
1720   tty->print_cr(" _generic_arraycopystub_cnt:      %u", _generic_arraycopystub_cnt);
1721   tty->print_cr(" _byte_arraycopy_cnt:             %u", _byte_arraycopy_stub_cnt);
1722   tty->print_cr(" _short_arraycopy_cnt:            %u", _short_arraycopy_stub_cnt);
1723   tty->print_cr(" _int_arraycopy_cnt:              %u", _int_arraycopy_stub_cnt);
1724   tty->print_cr(" _long_arraycopy_cnt:             %u", _long_arraycopy_stub_cnt);
1725   tty->print_cr(" _oop_arraycopy_cnt:              %u", _oop_arraycopy_stub_cnt);
1726   tty->print_cr(" _arraycopy_slowcase_cnt:         %u", _arraycopy_slowcase_cnt);
1727   tty->print_cr(" _arraycopy_checkcast_cnt:        %u", _arraycopy_checkcast_cnt);
1728   tty->print_cr(" _arraycopy_checkcast_attempt_cnt:%u", _arraycopy_checkcast_attempt_cnt);
1729 
1730   tty->print_cr(" _new_type_array_slowcase_cnt:    %u", _new_type_array_slowcase_cnt);
1731   tty->print_cr(" _new_object_array_slowcase_cnt:  %u", _new_object_array_slowcase_cnt);
1732   tty->print_cr(" _new_null_free_array_slowcase_cnt: %u", _new_null_free_array_slowcase_cnt);
1733   tty->print_cr(" _new_instance_slowcase_cnt:      %u", _new_instance_slowcase_cnt);
1734   tty->print_cr(" _new_multi_array_slowcase_cnt:   %u", _new_multi_array_slowcase_cnt);
1735   tty->print_cr(" _load_flat_array_slowcase_cnt:   %u", _load_flat_array_slowcase_cnt);
1736   tty->print_cr(" _store_flat_array_slowcase_cnt:  %u", _store_flat_array_slowcase_cnt);
1737   tty->print_cr(" _substitutability_check_slowcase_cnt: %u", _substitutability_check_slowcase_cnt);
1738   tty->print_cr(" _buffer_inline_args_slowcase_cnt:%u", _buffer_inline_args_slowcase_cnt);
1739   tty->print_cr(" _buffer_inline_args_no_receiver_slowcase_cnt:%u", _buffer_inline_args_no_receiver_slowcase_cnt);
1740 
1741   tty->print_cr(" _monitorenter_slowcase_cnt:      %u", _monitorenter_slowcase_cnt);
1742   tty->print_cr(" _monitorexit_slowcase_cnt:       %u", _monitorexit_slowcase_cnt);
1743   tty->print_cr(" _patch_code_slowcase_cnt:        %u", _patch_code_slowcase_cnt);
1744 
1745   tty->print_cr(" _throw_range_check_exception_count:            %u:", _throw_range_check_exception_count);
1746   tty->print_cr(" _throw_index_exception_count:                  %u:", _throw_index_exception_count);
1747   tty->print_cr(" _throw_div0_exception_count:                   %u:", _throw_div0_exception_count);
1748   tty->print_cr(" _throw_null_pointer_exception_count:           %u:", _throw_null_pointer_exception_count);
1749   tty->print_cr(" _throw_class_cast_exception_count:             %u:", _throw_class_cast_exception_count);
1750   tty->print_cr(" _throw_incompatible_class_change_error_count:  %u:", _throw_incompatible_class_change_error_count);
1751   tty->print_cr(" _throw_illegal_monitor_state_exception_count:  %u:", _throw_illegal_monitor_state_exception_count);
1752   tty->print_cr(" _throw_identity_exception_count:               %u:", _throw_identity_exception_count);
1753   tty->print_cr(" _throw_count:                                  %u:", _throw_count);
1754 
1755   SharedRuntime::print_ic_miss_histogram();
1756   tty->cr();
1757 }
1758 #endif // PRODUCT