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