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