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