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