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