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