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