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