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