1 /*
   2  * Copyright (c) 1999, 2010, 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 "incls/_precompiled.incl"
  26 #include "incls/_c1_Runtime1.cpp.incl"
  27 
  28 
  29 // Implementation of StubAssembler
  30 
  31 StubAssembler::StubAssembler(CodeBuffer* code, const char * name, int stub_id) : C1_MacroAssembler(code) {
  32   _name = name;
  33   _must_gc_arguments = false;
  34   _frame_size = no_frame_size;
  35   _num_rt_args = 0;
  36   _stub_id = stub_id;
  37 }
  38 
  39 
  40 void StubAssembler::set_info(const char* name, bool must_gc_arguments) {
  41   _name = name;
  42   _must_gc_arguments = must_gc_arguments;
  43 }
  44 
  45 
  46 void StubAssembler::set_frame_size(int size) {
  47   if (_frame_size == no_frame_size) {
  48     _frame_size = size;
  49   }
  50   assert(_frame_size == size, "can't change the frame size");
  51 }
  52 
  53 
  54 void StubAssembler::set_num_rt_args(int args) {
  55   if (_num_rt_args == 0) {
  56     _num_rt_args = args;
  57   }
  58   assert(_num_rt_args == args, "can't change the number of args");
  59 }
  60 
  61 // Implementation of Runtime1
  62 
  63 CodeBlob* Runtime1::_blobs[Runtime1::number_of_ids];
  64 const char *Runtime1::_blob_names[] = {
  65   RUNTIME1_STUBS(STUB_NAME, LAST_STUB_NAME)
  66 };
  67 
  68 #ifndef PRODUCT
  69 // statistics
  70 int Runtime1::_generic_arraycopy_cnt = 0;
  71 int Runtime1::_primitive_arraycopy_cnt = 0;
  72 int Runtime1::_oop_arraycopy_cnt = 0;
  73 int Runtime1::_arraycopy_slowcase_cnt = 0;
  74 int Runtime1::_new_type_array_slowcase_cnt = 0;
  75 int Runtime1::_new_object_array_slowcase_cnt = 0;
  76 int Runtime1::_new_instance_slowcase_cnt = 0;
  77 int Runtime1::_new_multi_array_slowcase_cnt = 0;
  78 int Runtime1::_monitorenter_slowcase_cnt = 0;
  79 int Runtime1::_monitorexit_slowcase_cnt = 0;
  80 int Runtime1::_patch_code_slowcase_cnt = 0;
  81 int Runtime1::_throw_range_check_exception_count = 0;
  82 int Runtime1::_throw_index_exception_count = 0;
  83 int Runtime1::_throw_div0_exception_count = 0;
  84 int Runtime1::_throw_null_pointer_exception_count = 0;
  85 int Runtime1::_throw_class_cast_exception_count = 0;
  86 int Runtime1::_throw_incompatible_class_change_error_count = 0;
  87 int Runtime1::_throw_array_store_exception_count = 0;
  88 int Runtime1::_throw_count = 0;
  89 #endif
  90 
  91 // Simple helper to see if the caller of a runtime stub which
  92 // entered the VM has been deoptimized
  93 
  94 static bool caller_is_deopted() {
  95   JavaThread* thread = JavaThread::current();
  96   RegisterMap reg_map(thread, false);
  97   frame runtime_frame = thread->last_frame();
  98   frame caller_frame = runtime_frame.sender(&reg_map);
  99   assert(caller_frame.is_compiled_frame(), "must be compiled");
 100   return caller_frame.is_deoptimized_frame();
 101 }
 102 
 103 // Stress deoptimization
 104 static void deopt_caller() {
 105   if ( !caller_is_deopted()) {
 106     JavaThread* thread = JavaThread::current();
 107     RegisterMap reg_map(thread, false);
 108     frame runtime_frame = thread->last_frame();
 109     frame caller_frame = runtime_frame.sender(&reg_map);
 110     // bypass VM_DeoptimizeFrame and deoptimize the frame directly
 111     Deoptimization::deoptimize_frame(thread, caller_frame.id());
 112     assert(caller_is_deopted(), "Must be deoptimized");
 113   }
 114 }
 115 
 116 
 117 void Runtime1::generate_blob_for(BufferBlob* buffer_blob, StubID id) {
 118   assert(0 <= id && id < number_of_ids, "illegal stub id");
 119   ResourceMark rm;
 120   // create code buffer for code storage
 121   CodeBuffer code(buffer_blob);
 122 
 123   Compilation::setup_code_buffer(&code, 0);
 124 
 125   // create assembler for code generation
 126   StubAssembler* sasm = new StubAssembler(&code, name_for(id), id);
 127   // generate code for runtime stub
 128   OopMapSet* oop_maps;
 129   oop_maps = generate_code_for(id, sasm);
 130   assert(oop_maps == NULL || sasm->frame_size() != no_frame_size,
 131          "if stub has an oop map it must have a valid frame size");
 132 
 133 #ifdef ASSERT
 134   // Make sure that stubs that need oopmaps have them
 135   switch (id) {
 136     // These stubs don't need to have an oopmap
 137     case dtrace_object_alloc_id:
 138     case g1_pre_barrier_slow_id:
 139     case g1_post_barrier_slow_id:
 140     case slow_subtype_check_id:
 141     case fpu2long_stub_id:
 142     case unwind_exception_id:
 143     case counter_overflow_id:
 144 #if defined(SPARC) || defined(PPC)
 145     case handle_exception_nofpu_id:  // Unused on sparc
 146 #endif
 147       break;
 148 
 149     // All other stubs should have oopmaps
 150     default:
 151       assert(oop_maps != NULL, "must have an oopmap");
 152   }
 153 #endif
 154 
 155   // align so printing shows nop's instead of random code at the end (SimpleStubs are aligned)
 156   sasm->align(BytesPerWord);
 157   // make sure all code is in code buffer
 158   sasm->flush();
 159   // create blob - distinguish a few special cases
 160   CodeBlob* blob = RuntimeStub::new_runtime_stub(name_for(id),
 161                                                  &code,
 162                                                  CodeOffsets::frame_never_safe,
 163                                                  sasm->frame_size(),
 164                                                  oop_maps,
 165                                                  sasm->must_gc_arguments());
 166   // install blob
 167   assert(blob != NULL, "blob must exist");
 168   _blobs[id] = blob;
 169 }
 170 
 171 
 172 void Runtime1::initialize(BufferBlob* blob) {
 173   // platform-dependent initialization
 174   initialize_pd();
 175   // generate stubs
 176   for (int id = 0; id < number_of_ids; id++) generate_blob_for(blob, (StubID)id);
 177   // printing
 178 #ifndef PRODUCT
 179   if (PrintSimpleStubs) {
 180     ResourceMark rm;
 181     for (int id = 0; id < number_of_ids; id++) {
 182       _blobs[id]->print();
 183       if (_blobs[id]->oop_maps() != NULL) {
 184         _blobs[id]->oop_maps()->print();
 185       }
 186     }
 187   }
 188 #endif
 189 }
 190 
 191 
 192 CodeBlob* Runtime1::blob_for(StubID id) {
 193   assert(0 <= id && id < number_of_ids, "illegal stub id");
 194   return _blobs[id];
 195 }
 196 
 197 
 198 const char* Runtime1::name_for(StubID id) {
 199   assert(0 <= id && id < number_of_ids, "illegal stub id");
 200   return _blob_names[id];
 201 }
 202 
 203 const char* Runtime1::name_for_address(address entry) {
 204   for (int id = 0; id < number_of_ids; id++) {
 205     if (entry == entry_for((StubID)id)) return name_for((StubID)id);
 206   }
 207 
 208 #define FUNCTION_CASE(a, f) \
 209   if ((intptr_t)a == CAST_FROM_FN_PTR(intptr_t, f))  return #f
 210 
 211   FUNCTION_CASE(entry, os::javaTimeMillis);
 212   FUNCTION_CASE(entry, os::javaTimeNanos);
 213   FUNCTION_CASE(entry, SharedRuntime::OSR_migration_end);
 214   FUNCTION_CASE(entry, SharedRuntime::d2f);
 215   FUNCTION_CASE(entry, SharedRuntime::d2i);
 216   FUNCTION_CASE(entry, SharedRuntime::d2l);
 217   FUNCTION_CASE(entry, SharedRuntime::dcos);
 218   FUNCTION_CASE(entry, SharedRuntime::dexp);
 219   FUNCTION_CASE(entry, SharedRuntime::dlog);
 220   FUNCTION_CASE(entry, SharedRuntime::dlog10);
 221   FUNCTION_CASE(entry, SharedRuntime::dpow);
 222   FUNCTION_CASE(entry, SharedRuntime::drem);
 223   FUNCTION_CASE(entry, SharedRuntime::dsin);
 224   FUNCTION_CASE(entry, SharedRuntime::dtan);
 225   FUNCTION_CASE(entry, SharedRuntime::f2i);
 226   FUNCTION_CASE(entry, SharedRuntime::f2l);
 227   FUNCTION_CASE(entry, SharedRuntime::frem);
 228   FUNCTION_CASE(entry, SharedRuntime::l2d);
 229   FUNCTION_CASE(entry, SharedRuntime::l2f);
 230   FUNCTION_CASE(entry, SharedRuntime::ldiv);
 231   FUNCTION_CASE(entry, SharedRuntime::lmul);
 232   FUNCTION_CASE(entry, SharedRuntime::lrem);
 233   FUNCTION_CASE(entry, SharedRuntime::lrem);
 234   FUNCTION_CASE(entry, SharedRuntime::dtrace_method_entry);
 235   FUNCTION_CASE(entry, SharedRuntime::dtrace_method_exit);
 236   FUNCTION_CASE(entry, trace_block_entry);
 237 
 238 #undef FUNCTION_CASE
 239 
 240   // Soft float adds more runtime names.
 241   return pd_name_for_address(entry);
 242 }
 243 
 244 
 245 JRT_ENTRY(void, Runtime1::new_instance(JavaThread* thread, klassOopDesc* klass))
 246   NOT_PRODUCT(_new_instance_slowcase_cnt++;)
 247 
 248   assert(oop(klass)->is_klass(), "not a class");
 249   instanceKlassHandle h(thread, klass);
 250   h->check_valid_for_instantiation(true, CHECK);
 251   // make sure klass is initialized
 252   h->initialize(CHECK);
 253   // allocate instance and return via TLS
 254   oop obj = h->allocate_instance(CHECK);
 255   thread->set_vm_result(obj);
 256 JRT_END
 257 
 258 
 259 JRT_ENTRY(void, Runtime1::new_type_array(JavaThread* thread, klassOopDesc* klass, jint length))
 260   NOT_PRODUCT(_new_type_array_slowcase_cnt++;)
 261   // Note: no handle for klass needed since they are not used
 262   //       anymore after new_typeArray() and no GC can happen before.
 263   //       (This may have to change if this code changes!)
 264   assert(oop(klass)->is_klass(), "not a class");
 265   BasicType elt_type = typeArrayKlass::cast(klass)->element_type();
 266   oop obj = oopFactory::new_typeArray(elt_type, length, CHECK);
 267   thread->set_vm_result(obj);
 268   // This is pretty rare but this runtime patch is stressful to deoptimization
 269   // if we deoptimize here so force a deopt to stress the path.
 270   if (DeoptimizeALot) {
 271     deopt_caller();
 272   }
 273 
 274 JRT_END
 275 
 276 
 277 JRT_ENTRY(void, Runtime1::new_object_array(JavaThread* thread, klassOopDesc* array_klass, jint length))
 278   NOT_PRODUCT(_new_object_array_slowcase_cnt++;)
 279 
 280   // Note: no handle for klass needed since they are not used
 281   //       anymore after new_objArray() and no GC can happen before.
 282   //       (This may have to change if this code changes!)
 283   assert(oop(array_klass)->is_klass(), "not a class");
 284   klassOop elem_klass = objArrayKlass::cast(array_klass)->element_klass();
 285   objArrayOop obj = oopFactory::new_objArray(elem_klass, length, CHECK);
 286   thread->set_vm_result(obj);
 287   // This is pretty rare but this runtime patch is stressful to deoptimization
 288   // if we deoptimize here so force a deopt to stress the path.
 289   if (DeoptimizeALot) {
 290     deopt_caller();
 291   }
 292 JRT_END
 293 
 294 
 295 JRT_ENTRY(void, Runtime1::new_multi_array(JavaThread* thread, klassOopDesc* klass, int rank, jint* dims))
 296   NOT_PRODUCT(_new_multi_array_slowcase_cnt++;)
 297 
 298   assert(oop(klass)->is_klass(), "not a class");
 299   assert(rank >= 1, "rank must be nonzero");
 300   oop obj = arrayKlass::cast(klass)->multi_allocate(rank, dims, CHECK);
 301   thread->set_vm_result(obj);
 302 JRT_END
 303 
 304 
 305 JRT_ENTRY(void, Runtime1::unimplemented_entry(JavaThread* thread, StubID id))
 306   tty->print_cr("Runtime1::entry_for(%d) returned unimplemented entry point", id);
 307 JRT_END
 308 
 309 
 310 JRT_ENTRY(void, Runtime1::throw_array_store_exception(JavaThread* thread))
 311   THROW(vmSymbolHandles::java_lang_ArrayStoreException());
 312 JRT_END
 313 
 314 
 315 JRT_ENTRY(void, Runtime1::post_jvmti_exception_throw(JavaThread* thread))
 316   if (JvmtiExport::can_post_on_exceptions()) {
 317     vframeStream vfst(thread, true);
 318     address bcp = vfst.method()->bcp_from(vfst.bci());
 319     JvmtiExport::post_exception_throw(thread, vfst.method(), bcp, thread->exception_oop());
 320   }
 321 JRT_END
 322 
 323 // This is a helper to allow us to safepoint but allow the outer entry
 324 // to be safepoint free if we need to do an osr
 325 static nmethod* counter_overflow_helper(JavaThread* THREAD, int branch_bci, methodOopDesc* m) {
 326   nmethod* osr_nm = NULL;
 327   methodHandle method(THREAD, m);
 328 
 329   RegisterMap map(THREAD, false);
 330   frame fr =  THREAD->last_frame().sender(&map);
 331   nmethod* nm = (nmethod*) fr.cb();
 332   assert(nm!= NULL && nm->is_nmethod(), "Sanity check");
 333   methodHandle enclosing_method(THREAD, nm->method());
 334 
 335   CompLevel level = (CompLevel)nm->comp_level();
 336   int bci = InvocationEntryBci;
 337   if (branch_bci != InvocationEntryBci) {
 338     // Compute desination bci
 339     address pc = method()->code_base() + branch_bci;
 340     Bytecodes::Code branch = Bytecodes::code_at(pc, method());
 341     int offset = 0;
 342     switch (branch) {
 343       case Bytecodes::_if_icmplt: case Bytecodes::_iflt:
 344       case Bytecodes::_if_icmpgt: case Bytecodes::_ifgt:
 345       case Bytecodes::_if_icmple: case Bytecodes::_ifle:
 346       case Bytecodes::_if_icmpge: case Bytecodes::_ifge:
 347       case Bytecodes::_if_icmpeq: case Bytecodes::_if_acmpeq: case Bytecodes::_ifeq:
 348       case Bytecodes::_if_icmpne: case Bytecodes::_if_acmpne: case Bytecodes::_ifne:
 349       case Bytecodes::_ifnull: case Bytecodes::_ifnonnull: case Bytecodes::_goto:
 350         offset = (int16_t)Bytes::get_Java_u2(pc + 1);
 351         break;
 352       case Bytecodes::_goto_w:
 353         offset = Bytes::get_Java_u4(pc + 1);
 354         break;
 355       default: ;
 356     }
 357     bci = branch_bci + offset;
 358   }
 359 
 360   osr_nm = CompilationPolicy::policy()->event(enclosing_method, method, branch_bci, bci, level, THREAD);
 361   return osr_nm;
 362 }
 363 
 364 JRT_BLOCK_ENTRY(address, Runtime1::counter_overflow(JavaThread* thread, int bci, methodOopDesc* method))
 365   nmethod* osr_nm;
 366   JRT_BLOCK
 367     osr_nm = counter_overflow_helper(thread, bci, method);
 368     if (osr_nm != NULL) {
 369       RegisterMap map(thread, false);
 370       frame fr =  thread->last_frame().sender(&map);
 371       VM_DeoptimizeFrame deopt(thread, fr.id());
 372       VMThread::execute(&deopt);
 373     }
 374   JRT_BLOCK_END
 375   return NULL;
 376 JRT_END
 377 
 378 extern void vm_exit(int code);
 379 
 380 // Enter this method from compiled code handler below. This is where we transition
 381 // to VM mode. This is done as a helper routine so that the method called directly
 382 // from compiled code does not have to transition to VM. This allows the entry
 383 // method to see if the nmethod that we have just looked up a handler for has
 384 // been deoptimized while we were in the vm. This simplifies the assembly code
 385 // cpu directories.
 386 //
 387 // We are entering here from exception stub (via the entry method below)
 388 // If there is a compiled exception handler in this method, we will continue there;
 389 // otherwise we will unwind the stack and continue at the caller of top frame method
 390 // Note: we enter in Java using a special JRT wrapper. This wrapper allows us to
 391 // control the area where we can allow a safepoint. After we exit the safepoint area we can
 392 // check to see if the handler we are going to return is now in a nmethod that has
 393 // been deoptimized. If that is the case we return the deopt blob
 394 // unpack_with_exception entry instead. This makes life for the exception blob easier
 395 // because making that same check and diverting is painful from assembly language.
 396 //
 397 
 398 
 399 JRT_ENTRY_NO_ASYNC(static address, exception_handler_for_pc_helper(JavaThread* thread, oopDesc* ex, address pc, nmethod*& nm))
 400 
 401   Handle exception(thread, ex);
 402   nm = CodeCache::find_nmethod(pc);
 403   assert(nm != NULL, "this is not an nmethod");
 404   // Adjust the pc as needed/
 405   if (nm->is_deopt_pc(pc)) {
 406     RegisterMap map(thread, false);
 407     frame exception_frame = thread->last_frame().sender(&map);
 408     // if the frame isn't deopted then pc must not correspond to the caller of last_frame
 409     assert(exception_frame.is_deoptimized_frame(), "must be deopted");
 410     pc = exception_frame.pc();
 411   }
 412 #ifdef ASSERT
 413   assert(exception.not_null(), "NULL exceptions should be handled by throw_exception");
 414   assert(exception->is_oop(), "just checking");
 415   // Check that exception is a subclass of Throwable, otherwise we have a VerifyError
 416   if (!(exception->is_a(SystemDictionary::Throwable_klass()))) {
 417     if (ExitVMOnVerifyError) vm_exit(-1);
 418     ShouldNotReachHere();
 419   }
 420 #endif
 421 
 422   // Check the stack guard pages and reenable them if necessary and there is
 423   // enough space on the stack to do so.  Use fast exceptions only if the guard
 424   // pages are enabled.
 425   bool guard_pages_enabled = thread->stack_yellow_zone_enabled();
 426   if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack();
 427 
 428   if (JvmtiExport::can_post_on_exceptions()) {
 429     // To ensure correct notification of exception catches and throws
 430     // we have to deoptimize here.  If we attempted to notify the
 431     // catches and throws during this exception lookup it's possible
 432     // we could deoptimize on the way out of the VM and end back in
 433     // the interpreter at the throw site.  This would result in double
 434     // notifications since the interpreter would also notify about
 435     // these same catches and throws as it unwound the frame.
 436 
 437     RegisterMap reg_map(thread);
 438     frame stub_frame = thread->last_frame();
 439     frame caller_frame = stub_frame.sender(&reg_map);
 440 
 441     // We don't really want to deoptimize the nmethod itself since we
 442     // can actually continue in the exception handler ourselves but I
 443     // don't see an easy way to have the desired effect.
 444     VM_DeoptimizeFrame deopt(thread, caller_frame.id());
 445     VMThread::execute(&deopt);
 446 
 447     return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
 448   }
 449 
 450   // ExceptionCache is used only for exceptions at call and not for implicit exceptions
 451   if (guard_pages_enabled) {
 452     address fast_continuation = nm->handler_for_exception_and_pc(exception, pc);
 453     if (fast_continuation != NULL) {
 454       if (fast_continuation == ExceptionCache::unwind_handler()) fast_continuation = NULL;
 455       return fast_continuation;
 456     }
 457   }
 458 
 459   // If the stack guard pages are enabled, check whether there is a handler in
 460   // the current method.  Otherwise (guard pages disabled), force an unwind and
 461   // skip the exception cache update (i.e., just leave continuation==NULL).
 462   address continuation = NULL;
 463   if (guard_pages_enabled) {
 464 
 465     // New exception handling mechanism can support inlined methods
 466     // with exception handlers since the mappings are from PC to PC
 467 
 468     // debugging support
 469     // tracing
 470     if (TraceExceptions) {
 471       ttyLocker ttyl;
 472       ResourceMark rm;
 473       tty->print_cr("Exception <%s> (0x%x) thrown in compiled method <%s> at PC " PTR_FORMAT " for thread 0x%x",
 474                     exception->print_value_string(), (address)exception(), nm->method()->print_value_string(), pc, thread);
 475     }
 476     // for AbortVMOnException flag
 477     NOT_PRODUCT(Exceptions::debug_check_abort(exception));
 478 
 479     // Clear out the exception oop and pc since looking up an
 480     // exception handler can cause class loading, which might throw an
 481     // exception and those fields are expected to be clear during
 482     // normal bytecode execution.
 483     thread->set_exception_oop(NULL);
 484     thread->set_exception_pc(NULL);
 485 
 486     continuation = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, false, false);
 487     // If an exception was thrown during exception dispatch, the exception oop may have changed
 488     thread->set_exception_oop(exception());
 489     thread->set_exception_pc(pc);
 490 
 491     // the exception cache is used only by non-implicit exceptions
 492     if (continuation == NULL) {
 493       nm->add_handler_for_exception_and_pc(exception, pc, ExceptionCache::unwind_handler());
 494     } else {
 495       nm->add_handler_for_exception_and_pc(exception, pc, continuation);
 496     }
 497   }
 498 
 499   thread->set_vm_result(exception());
 500 
 501   if (TraceExceptions) {
 502     ttyLocker ttyl;
 503     ResourceMark rm;
 504     tty->print_cr("Thread " PTR_FORMAT " continuing at PC " PTR_FORMAT " for exception thrown at PC " PTR_FORMAT,
 505                   thread, continuation, pc);
 506   }
 507 
 508   return continuation;
 509 JRT_END
 510 
 511 // Enter this method from compiled code only if there is a Java exception handler
 512 // in the method handling the exception
 513 // We are entering here from exception stub. We don't do a normal VM transition here.
 514 // We do it in a helper. This is so we can check to see if the nmethod we have just
 515 // searched for an exception handler has been deoptimized in the meantime.
 516 address  Runtime1::exception_handler_for_pc(JavaThread* thread) {
 517   oop exception = thread->exception_oop();
 518   address pc = thread->exception_pc();
 519   // Still in Java mode
 520   debug_only(ResetNoHandleMark rnhm);
 521   nmethod* nm = NULL;
 522   address continuation = NULL;
 523   {
 524     // Enter VM mode by calling the helper
 525 
 526     ResetNoHandleMark rnhm;
 527     continuation = exception_handler_for_pc_helper(thread, exception, pc, nm);
 528   }
 529   // Back in JAVA, use no oops DON'T safepoint
 530 
 531   // Now check to see if the nmethod we were called from is now deoptimized.
 532   // If so we must return to the deopt blob and deoptimize the nmethod
 533 
 534   if (nm != NULL && caller_is_deopted()) {
 535     continuation = SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
 536   }
 537 
 538   return continuation;
 539 }
 540 
 541 
 542 JRT_ENTRY(void, Runtime1::throw_range_check_exception(JavaThread* thread, int index))
 543   NOT_PRODUCT(_throw_range_check_exception_count++;)
 544   Events::log("throw_range_check");
 545   char message[jintAsStringSize];
 546   sprintf(message, "%d", index);
 547   SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), message);
 548 JRT_END
 549 
 550 
 551 JRT_ENTRY(void, Runtime1::throw_index_exception(JavaThread* thread, int index))
 552   NOT_PRODUCT(_throw_index_exception_count++;)
 553   Events::log("throw_index");
 554   char message[16];
 555   sprintf(message, "%d", index);
 556   SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_IndexOutOfBoundsException(), message);
 557 JRT_END
 558 
 559 
 560 JRT_ENTRY(void, Runtime1::throw_div0_exception(JavaThread* thread))
 561   NOT_PRODUCT(_throw_div0_exception_count++;)
 562   SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_ArithmeticException(), "/ by zero");
 563 JRT_END
 564 
 565 
 566 JRT_ENTRY(void, Runtime1::throw_null_pointer_exception(JavaThread* thread))
 567   NOT_PRODUCT(_throw_null_pointer_exception_count++;)
 568   SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_NullPointerException());
 569 JRT_END
 570 
 571 
 572 JRT_ENTRY(void, Runtime1::throw_class_cast_exception(JavaThread* thread, oopDesc* object))
 573   NOT_PRODUCT(_throw_class_cast_exception_count++;)
 574   ResourceMark rm(thread);
 575   char* message = SharedRuntime::generate_class_cast_message(
 576     thread, Klass::cast(object->klass())->external_name());
 577   SharedRuntime::throw_and_post_jvmti_exception(
 578     thread, vmSymbols::java_lang_ClassCastException(), message);
 579 JRT_END
 580 
 581 
 582 JRT_ENTRY(void, Runtime1::throw_incompatible_class_change_error(JavaThread* thread))
 583   NOT_PRODUCT(_throw_incompatible_class_change_error_count++;)
 584   ResourceMark rm(thread);
 585   SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_IncompatibleClassChangeError());
 586 JRT_END
 587 
 588 
 589 JRT_ENTRY_NO_ASYNC(void, Runtime1::monitorenter(JavaThread* thread, oopDesc* obj, BasicObjectLock* lock))
 590   NOT_PRODUCT(_monitorenter_slowcase_cnt++;)
 591   if (PrintBiasedLockingStatistics) {
 592     Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
 593   }
 594   Handle h_obj(thread, obj);
 595   assert(h_obj()->is_oop(), "must be NULL or an object");
 596   if (UseBiasedLocking) {
 597     // Retry fast entry if bias is revoked to avoid unnecessary inflation
 598     ObjectSynchronizer::fast_enter(h_obj, lock->lock(), true, CHECK);
 599   } else {
 600     if (UseFastLocking) {
 601       // When using fast locking, the compiled code has already tried the fast case
 602       assert(obj == lock->obj(), "must match");
 603       ObjectSynchronizer::slow_enter(h_obj, lock->lock(), THREAD);
 604     } else {
 605       lock->set_obj(obj);
 606       ObjectSynchronizer::fast_enter(h_obj, lock->lock(), false, THREAD);
 607     }
 608   }
 609 JRT_END
 610 
 611 
 612 JRT_LEAF(void, Runtime1::monitorexit(JavaThread* thread, BasicObjectLock* lock))
 613   NOT_PRODUCT(_monitorexit_slowcase_cnt++;)
 614   assert(thread == JavaThread::current(), "threads must correspond");
 615   assert(thread->last_Java_sp(), "last_Java_sp must be set");
 616   // monitorexit is non-blocking (leaf routine) => no exceptions can be thrown
 617   EXCEPTION_MARK;
 618 
 619   oop obj = lock->obj();
 620   assert(obj->is_oop(), "must be NULL or an object");
 621   if (UseFastLocking) {
 622     // When using fast locking, the compiled code has already tried the fast case
 623     ObjectSynchronizer::slow_exit(obj, lock->lock(), THREAD);
 624   } else {
 625     ObjectSynchronizer::fast_exit(obj, lock->lock(), THREAD);
 626   }
 627 JRT_END
 628 
 629 
 630 static klassOop resolve_field_return_klass(methodHandle caller, int bci, TRAPS) {
 631   Bytecode_field* field_access = Bytecode_field_at(caller, bci);
 632   // This can be static or non-static field access
 633   Bytecodes::Code code       = field_access->code();
 634 
 635   // We must load class, initialize class and resolvethe field
 636   FieldAccessInfo result; // initialize class if needed
 637   constantPoolHandle constants(THREAD, caller->constants());
 638   LinkResolver::resolve_field(result, constants, field_access->index(), Bytecodes::java_code(code), false, CHECK_NULL);
 639   return result.klass()();
 640 }
 641 
 642 
 643 //
 644 // This routine patches sites where a class wasn't loaded or
 645 // initialized at the time the code was generated.  It handles
 646 // references to classes, fields and forcing of initialization.  Most
 647 // of the cases are straightforward and involving simply forcing
 648 // resolution of a class, rewriting the instruction stream with the
 649 // needed constant and replacing the call in this function with the
 650 // patched code.  The case for static field is more complicated since
 651 // the thread which is in the process of initializing a class can
 652 // access it's static fields but other threads can't so the code
 653 // either has to deoptimize when this case is detected or execute a
 654 // check that the current thread is the initializing thread.  The
 655 // current
 656 //
 657 // Patches basically look like this:
 658 //
 659 //
 660 // patch_site: jmp patch stub     ;; will be patched
 661 // continue:   ...
 662 //             ...
 663 //             ...
 664 //             ...
 665 //
 666 // They have a stub which looks like this:
 667 //
 668 //             ;; patch body
 669 //             movl <const>, reg           (for class constants)
 670 //        <or> movl [reg1 + <const>], reg  (for field offsets)
 671 //        <or> movl reg, [reg1 + <const>]  (for field offsets)
 672 //             <being_init offset> <bytes to copy> <bytes to skip>
 673 // patch_stub: call Runtime1::patch_code (through a runtime stub)
 674 //             jmp patch_site
 675 //
 676 //
 677 // A normal patch is done by rewriting the patch body, usually a move,
 678 // and then copying it into place over top of the jmp instruction
 679 // being careful to flush caches and doing it in an MP-safe way.  The
 680 // constants following the patch body are used to find various pieces
 681 // of the patch relative to the call site for Runtime1::patch_code.
 682 // The case for getstatic and putstatic is more complicated because
 683 // getstatic and putstatic have special semantics when executing while
 684 // the class is being initialized.  getstatic/putstatic on a class
 685 // which is being_initialized may be executed by the initializing
 686 // thread but other threads have to block when they execute it.  This
 687 // is accomplished in compiled code by executing a test of the current
 688 // thread against the initializing thread of the class.  It's emitted
 689 // as boilerplate in their stub which allows the patched code to be
 690 // executed before it's copied back into the main body of the nmethod.
 691 //
 692 // being_init: get_thread(<tmp reg>
 693 //             cmpl [reg1 + <init_thread_offset>], <tmp reg>
 694 //             jne patch_stub
 695 //             movl [reg1 + <const>], reg  (for field offsets)  <or>
 696 //             movl reg, [reg1 + <const>]  (for field offsets)
 697 //             jmp continue
 698 //             <being_init offset> <bytes to copy> <bytes to skip>
 699 // patch_stub: jmp Runtim1::patch_code (through a runtime stub)
 700 //             jmp patch_site
 701 //
 702 // If the class is being initialized the patch body is rewritten and
 703 // the patch site is rewritten to jump to being_init, instead of
 704 // patch_stub.  Whenever this code is executed it checks the current
 705 // thread against the intializing thread so other threads will enter
 706 // the runtime and end up blocked waiting the class to finish
 707 // initializing inside the calls to resolve_field below.  The
 708 // initializing class will continue on it's way.  Once the class is
 709 // fully_initialized, the intializing_thread of the class becomes
 710 // NULL, so the next thread to execute this code will fail the test,
 711 // call into patch_code and complete the patching process by copying
 712 // the patch body back into the main part of the nmethod and resume
 713 // executing.
 714 //
 715 //
 716 
 717 JRT_ENTRY(void, Runtime1::patch_code(JavaThread* thread, Runtime1::StubID stub_id ))
 718   NOT_PRODUCT(_patch_code_slowcase_cnt++;)
 719 
 720   ResourceMark rm(thread);
 721   RegisterMap reg_map(thread, false);
 722   frame runtime_frame = thread->last_frame();
 723   frame caller_frame = runtime_frame.sender(&reg_map);
 724 
 725   // last java frame on stack
 726   vframeStream vfst(thread, true);
 727   assert(!vfst.at_end(), "Java frame must exist");
 728 
 729   methodHandle caller_method(THREAD, vfst.method());
 730   // Note that caller_method->code() may not be same as caller_code because of OSR's
 731   // Note also that in the presence of inlining it is not guaranteed
 732   // that caller_method() == caller_code->method()
 733 
 734 
 735   int bci = vfst.bci();
 736 
 737   Events::log("patch_code @ " INTPTR_FORMAT , caller_frame.pc());
 738 
 739   Bytecodes::Code code = Bytecode_at(caller_method->bcp_from(bci))->java_code();
 740 
 741 #ifndef PRODUCT
 742   // this is used by assertions in the access_field_patching_id
 743   BasicType patch_field_type = T_ILLEGAL;
 744 #endif // PRODUCT
 745   bool deoptimize_for_volatile = false;
 746   int patch_field_offset = -1;
 747   KlassHandle init_klass(THREAD, klassOop(NULL)); // klass needed by access_field_patching code
 748   Handle load_klass(THREAD, NULL);                // oop needed by load_klass_patching code
 749   if (stub_id == Runtime1::access_field_patching_id) {
 750 
 751     Bytecode_field* field_access = Bytecode_field_at(caller_method, bci);
 752     FieldAccessInfo result; // initialize class if needed
 753     Bytecodes::Code code = field_access->code();
 754     constantPoolHandle constants(THREAD, caller_method->constants());
 755     LinkResolver::resolve_field(result, constants, field_access->index(), Bytecodes::java_code(code), false, CHECK);
 756     patch_field_offset = result.field_offset();
 757 
 758     // If we're patching a field which is volatile then at compile it
 759     // must not have been know to be volatile, so the generated code
 760     // isn't correct for a volatile reference.  The nmethod has to be
 761     // deoptimized so that the code can be regenerated correctly.
 762     // This check is only needed for access_field_patching since this
 763     // is the path for patching field offsets.  load_klass is only
 764     // used for patching references to oops which don't need special
 765     // handling in the volatile case.
 766     deoptimize_for_volatile = result.access_flags().is_volatile();
 767 
 768 #ifndef PRODUCT
 769     patch_field_type = result.field_type();
 770 #endif
 771   } else if (stub_id == Runtime1::load_klass_patching_id) {
 772     oop k;
 773     switch (code) {
 774       case Bytecodes::_putstatic:
 775       case Bytecodes::_getstatic:
 776         { klassOop klass = resolve_field_return_klass(caller_method, bci, CHECK);
 777           // Save a reference to the class that has to be checked for initialization
 778           init_klass = KlassHandle(THREAD, klass);
 779           k = klass;
 780         }
 781         break;
 782       case Bytecodes::_new:
 783         { Bytecode_new* bnew = Bytecode_new_at(caller_method->bcp_from(bci));
 784           k = caller_method->constants()->klass_at(bnew->index(), CHECK);
 785         }
 786         break;
 787       case Bytecodes::_multianewarray:
 788         { Bytecode_multianewarray* mna = Bytecode_multianewarray_at(caller_method->bcp_from(bci));
 789           k = caller_method->constants()->klass_at(mna->index(), CHECK);
 790         }
 791         break;
 792       case Bytecodes::_instanceof:
 793         { Bytecode_instanceof* io = Bytecode_instanceof_at(caller_method->bcp_from(bci));
 794           k = caller_method->constants()->klass_at(io->index(), CHECK);
 795         }
 796         break;
 797       case Bytecodes::_checkcast:
 798         { Bytecode_checkcast* cc = Bytecode_checkcast_at(caller_method->bcp_from(bci));
 799           k = caller_method->constants()->klass_at(cc->index(), CHECK);
 800         }
 801         break;
 802       case Bytecodes::_anewarray:
 803         { Bytecode_anewarray* anew = Bytecode_anewarray_at(caller_method->bcp_from(bci));
 804           klassOop ek = caller_method->constants()->klass_at(anew->index(), CHECK);
 805           k = Klass::cast(ek)->array_klass(CHECK);
 806         }
 807         break;
 808       case Bytecodes::_ldc:
 809       case Bytecodes::_ldc_w:
 810         {
 811           Bytecode_loadconstant* cc = Bytecode_loadconstant_at(caller_method, bci);
 812           k = cc->resolve_constant(CHECK);
 813           assert(k != NULL && !k->is_klass(), "must be class mirror or other Java constant");
 814         }
 815         break;
 816       default: Unimplemented();
 817     }
 818     // convert to handle
 819     load_klass = Handle(THREAD, k);
 820   } else {
 821     ShouldNotReachHere();
 822   }
 823 
 824   if (deoptimize_for_volatile) {
 825     // At compile time we assumed the field wasn't volatile but after
 826     // loading it turns out it was volatile so we have to throw the
 827     // compiled code out and let it be regenerated.
 828     if (TracePatching) {
 829       tty->print_cr("Deoptimizing for patching volatile field reference");
 830     }
 831     // It's possible the nmethod was invalidated in the last
 832     // safepoint, but if it's still alive then make it not_entrant.
 833     nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
 834     if (nm != NULL) {
 835       nm->make_not_entrant();
 836     }
 837 
 838     VM_DeoptimizeFrame deopt(thread, caller_frame.id());
 839     VMThread::execute(&deopt);
 840 
 841     // Return to the now deoptimized frame.
 842   }
 843 
 844   // If we are patching in a non-perm oop, make sure the nmethod
 845   // is on the right list.
 846   if (ScavengeRootsInCode && load_klass.not_null() && load_klass->is_scavengable()) {
 847     MutexLockerEx ml_code (CodeCache_lock, Mutex::_no_safepoint_check_flag);
 848     nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
 849     guarantee(nm != NULL, "only nmethods can contain non-perm oops");
 850     if (!nm->on_scavenge_root_list())
 851       CodeCache::add_scavenge_root_nmethod(nm);
 852   }
 853 
 854   // Now copy code back
 855 
 856   {
 857     MutexLockerEx ml_patch (Patching_lock, Mutex::_no_safepoint_check_flag);
 858     //
 859     // Deoptimization may have happened while we waited for the lock.
 860     // In that case we don't bother to do any patching we just return
 861     // and let the deopt happen
 862     if (!caller_is_deopted()) {
 863       NativeGeneralJump* jump = nativeGeneralJump_at(caller_frame.pc());
 864       address instr_pc = jump->jump_destination();
 865       NativeInstruction* ni = nativeInstruction_at(instr_pc);
 866       if (ni->is_jump() ) {
 867         // the jump has not been patched yet
 868         // The jump destination is slow case and therefore not part of the stubs
 869         // (stubs are only for StaticCalls)
 870 
 871         // format of buffer
 872         //    ....
 873         //    instr byte 0     <-- copy_buff
 874         //    instr byte 1
 875         //    ..
 876         //    instr byte n-1
 877         //      n
 878         //    ....             <-- call destination
 879 
 880         address stub_location = caller_frame.pc() + PatchingStub::patch_info_offset();
 881         unsigned char* byte_count = (unsigned char*) (stub_location - 1);
 882         unsigned char* byte_skip = (unsigned char*) (stub_location - 2);
 883         unsigned char* being_initialized_entry_offset = (unsigned char*) (stub_location - 3);
 884         address copy_buff = stub_location - *byte_skip - *byte_count;
 885         address being_initialized_entry = stub_location - *being_initialized_entry_offset;
 886         if (TracePatching) {
 887           tty->print_cr(" Patching %s at bci %d at address 0x%x  (%s)", Bytecodes::name(code), bci,
 888                         instr_pc, (stub_id == Runtime1::access_field_patching_id) ? "field" : "klass");
 889           nmethod* caller_code = CodeCache::find_nmethod(caller_frame.pc());
 890           assert(caller_code != NULL, "nmethod not found");
 891 
 892           // NOTE we use pc() not original_pc() because we already know they are
 893           // identical otherwise we'd have never entered this block of code
 894 
 895           OopMap* map = caller_code->oop_map_for_return_address(caller_frame.pc());
 896           assert(map != NULL, "null check");
 897           map->print();
 898           tty->cr();
 899 
 900           Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
 901         }
 902         // depending on the code below, do_patch says whether to copy the patch body back into the nmethod
 903         bool do_patch = true;
 904         if (stub_id == Runtime1::access_field_patching_id) {
 905           // The offset may not be correct if the class was not loaded at code generation time.
 906           // Set it now.
 907           NativeMovRegMem* n_move = nativeMovRegMem_at(copy_buff);
 908           assert(n_move->offset() == 0 || (n_move->offset() == 4 && (patch_field_type == T_DOUBLE || patch_field_type == T_LONG)), "illegal offset for type");
 909           assert(patch_field_offset >= 0, "illegal offset");
 910           n_move->add_offset_in_bytes(patch_field_offset);
 911         } else if (stub_id == Runtime1::load_klass_patching_id) {
 912           // If a getstatic or putstatic is referencing a klass which
 913           // isn't fully initialized, the patch body isn't copied into
 914           // place until initialization is complete.  In this case the
 915           // patch site is setup so that any threads besides the
 916           // initializing thread are forced to come into the VM and
 917           // block.
 918           do_patch = (code != Bytecodes::_getstatic && code != Bytecodes::_putstatic) ||
 919                      instanceKlass::cast(init_klass())->is_initialized();
 920           NativeGeneralJump* jump = nativeGeneralJump_at(instr_pc);
 921           if (jump->jump_destination() == being_initialized_entry) {
 922             assert(do_patch == true, "initialization must be complete at this point");
 923           } else {
 924             // patch the instruction <move reg, klass>
 925             NativeMovConstReg* n_copy = nativeMovConstReg_at(copy_buff);
 926 
 927             assert(n_copy->data() == 0 ||
 928                    n_copy->data() == (intptr_t)Universe::non_oop_word(),
 929                    "illegal init value");
 930             assert(load_klass() != NULL, "klass not set");
 931             n_copy->set_data((intx) (load_klass()));
 932 
 933             if (TracePatching) {
 934               Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
 935             }
 936 
 937 #if defined(SPARC) || defined(PPC)
 938             // Update the oop location in the nmethod with the proper
 939             // oop.  When the code was generated, a NULL was stuffed
 940             // in the oop table and that table needs to be update to
 941             // have the right value.  On intel the value is kept
 942             // directly in the instruction instead of in the oop
 943             // table, so set_data above effectively updated the value.
 944             nmethod* nm = CodeCache::find_nmethod(instr_pc);
 945             assert(nm != NULL, "invalid nmethod_pc");
 946             RelocIterator oops(nm, copy_buff, copy_buff + 1);
 947             bool found = false;
 948             while (oops.next() && !found) {
 949               if (oops.type() == relocInfo::oop_type) {
 950                 oop_Relocation* r = oops.oop_reloc();
 951                 oop* oop_adr = r->oop_addr();
 952                 *oop_adr = load_klass();
 953                 r->fix_oop_relocation();
 954                 found = true;
 955               }
 956             }
 957             assert(found, "the oop must exist!");
 958 #endif
 959 
 960           }
 961         } else {
 962           ShouldNotReachHere();
 963         }
 964         if (do_patch) {
 965           // replace instructions
 966           // first replace the tail, then the call
 967 #ifdef ARM
 968           if(stub_id == Runtime1::load_klass_patching_id && !VM_Version::supports_movw()) {
 969             copy_buff -= *byte_count;
 970             NativeMovConstReg* n_copy2 = nativeMovConstReg_at(copy_buff);
 971             n_copy2->set_data((intx) (load_klass()), instr_pc);
 972           }
 973 #endif
 974 
 975           for (int i = NativeCall::instruction_size; i < *byte_count; i++) {
 976             address ptr = copy_buff + i;
 977             int a_byte = (*ptr) & 0xFF;
 978             address dst = instr_pc + i;
 979             *(unsigned char*)dst = (unsigned char) a_byte;
 980           }
 981           ICache::invalidate_range(instr_pc, *byte_count);
 982           NativeGeneralJump::replace_mt_safe(instr_pc, copy_buff);
 983 
 984           if (stub_id == Runtime1::load_klass_patching_id) {
 985             // update relocInfo to oop
 986             nmethod* nm = CodeCache::find_nmethod(instr_pc);
 987             assert(nm != NULL, "invalid nmethod_pc");
 988 
 989             // The old patch site is now a move instruction so update
 990             // the reloc info so that it will get updated during
 991             // future GCs.
 992             RelocIterator iter(nm, (address)instr_pc, (address)(instr_pc + 1));
 993             relocInfo::change_reloc_info_for_address(&iter, (address) instr_pc,
 994                                                      relocInfo::none, relocInfo::oop_type);
 995 #ifdef SPARC
 996             // Sparc takes two relocations for an oop so update the second one.
 997             address instr_pc2 = instr_pc + NativeMovConstReg::add_offset;
 998             RelocIterator iter2(nm, instr_pc2, instr_pc2 + 1);
 999             relocInfo::change_reloc_info_for_address(&iter2, (address) instr_pc2,
1000                                                      relocInfo::none, relocInfo::oop_type);
1001 #endif
1002 #ifdef PPC
1003           { address instr_pc2 = instr_pc + NativeMovConstReg::lo_offset;
1004             RelocIterator iter2(nm, instr_pc2, instr_pc2 + 1);
1005             relocInfo::change_reloc_info_for_address(&iter2, (address) instr_pc2, relocInfo::none, relocInfo::oop_type);
1006           }
1007 #endif
1008           }
1009 
1010         } else {
1011           ICache::invalidate_range(copy_buff, *byte_count);
1012           NativeGeneralJump::insert_unconditional(instr_pc, being_initialized_entry);
1013         }
1014       }
1015     }
1016   }
1017 JRT_END
1018 
1019 //
1020 // Entry point for compiled code. We want to patch a nmethod.
1021 // We don't do a normal VM transition here because we want to
1022 // know after the patching is complete and any safepoint(s) are taken
1023 // if the calling nmethod was deoptimized. We do this by calling a
1024 // helper method which does the normal VM transition and when it
1025 // completes we can check for deoptimization. This simplifies the
1026 // assembly code in the cpu directories.
1027 //
1028 int Runtime1::move_klass_patching(JavaThread* thread) {
1029 //
1030 // NOTE: we are still in Java
1031 //
1032   Thread* THREAD = thread;
1033   debug_only(NoHandleMark nhm;)
1034   {
1035     // Enter VM mode
1036 
1037     ResetNoHandleMark rnhm;
1038     patch_code(thread, load_klass_patching_id);
1039   }
1040   // Back in JAVA, use no oops DON'T safepoint
1041 
1042   // Return true if calling code is deoptimized
1043 
1044   return caller_is_deopted();
1045 }
1046 
1047 //
1048 // Entry point for compiled code. We want to patch a nmethod.
1049 // We don't do a normal VM transition here because we want to
1050 // know after the patching is complete and any safepoint(s) are taken
1051 // if the calling nmethod was deoptimized. We do this by calling a
1052 // helper method which does the normal VM transition and when it
1053 // completes we can check for deoptimization. This simplifies the
1054 // assembly code in the cpu directories.
1055 //
1056 
1057 int Runtime1::access_field_patching(JavaThread* thread) {
1058 //
1059 // NOTE: we are still in Java
1060 //
1061   Thread* THREAD = thread;
1062   debug_only(NoHandleMark nhm;)
1063   {
1064     // Enter VM mode
1065 
1066     ResetNoHandleMark rnhm;
1067     patch_code(thread, access_field_patching_id);
1068   }
1069   // Back in JAVA, use no oops DON'T safepoint
1070 
1071   // Return true if calling code is deoptimized
1072 
1073   return caller_is_deopted();
1074 JRT_END
1075 
1076 
1077 JRT_LEAF(void, Runtime1::trace_block_entry(jint block_id))
1078   // for now we just print out the block id
1079   tty->print("%d ", block_id);
1080 JRT_END
1081 
1082 
1083 // Array copy return codes.
1084 enum {
1085   ac_failed = -1, // arraycopy failed
1086   ac_ok = 0       // arraycopy succeeded
1087 };
1088 
1089 
1090 // Below length is the # elements copied.
1091 template <class T> int obj_arraycopy_work(oopDesc* src, T* src_addr,
1092                                           oopDesc* dst, T* dst_addr,
1093                                           int length) {
1094 
1095   // For performance reasons, we assume we are using a card marking write
1096   // barrier. The assert will fail if this is not the case.
1097   // Note that we use the non-virtual inlineable variant of write_ref_array.
1098   BarrierSet* bs = Universe::heap()->barrier_set();
1099   assert(bs->has_write_ref_array_opt(), "Barrier set must have ref array opt");
1100   assert(bs->has_write_ref_array_pre_opt(), "For pre-barrier as well.");
1101   if (src == dst) {
1102     // same object, no check
1103     bs->write_ref_array_pre(dst_addr, length);
1104     Copy::conjoint_oops_atomic(src_addr, dst_addr, length);
1105     bs->write_ref_array((HeapWord*)dst_addr, length);
1106     return ac_ok;
1107   } else {
1108     klassOop bound = objArrayKlass::cast(dst->klass())->element_klass();
1109     klassOop stype = objArrayKlass::cast(src->klass())->element_klass();
1110     if (stype == bound || Klass::cast(stype)->is_subtype_of(bound)) {
1111       // Elements are guaranteed to be subtypes, so no check necessary
1112       bs->write_ref_array_pre(dst_addr, length);
1113       Copy::conjoint_oops_atomic(src_addr, dst_addr, length);
1114       bs->write_ref_array((HeapWord*)dst_addr, length);
1115       return ac_ok;
1116     }
1117   }
1118   return ac_failed;
1119 }
1120 
1121 // fast and direct copy of arrays; returning -1, means that an exception may be thrown
1122 // and we did not copy anything
1123 JRT_LEAF(int, Runtime1::arraycopy(oopDesc* src, int src_pos, oopDesc* dst, int dst_pos, int length))
1124 #ifndef PRODUCT
1125   _generic_arraycopy_cnt++;        // Slow-path oop array copy
1126 #endif
1127 
1128   if (src == NULL || dst == NULL || src_pos < 0 || dst_pos < 0 || length < 0) return ac_failed;
1129   if (!dst->is_array() || !src->is_array()) return ac_failed;
1130   if ((unsigned int) arrayOop(src)->length() < (unsigned int)src_pos + (unsigned int)length) return ac_failed;
1131   if ((unsigned int) arrayOop(dst)->length() < (unsigned int)dst_pos + (unsigned int)length) return ac_failed;
1132 
1133   if (length == 0) return ac_ok;
1134   if (src->is_typeArray()) {
1135     const klassOop klass_oop = src->klass();
1136     if (klass_oop != dst->klass()) return ac_failed;
1137     typeArrayKlass* klass = typeArrayKlass::cast(klass_oop);
1138     const int l2es = klass->log2_element_size();
1139     const int ihs = klass->array_header_in_bytes() / wordSize;
1140     char* src_addr = (char*) ((oopDesc**)src + ihs) + (src_pos << l2es);
1141     char* dst_addr = (char*) ((oopDesc**)dst + ihs) + (dst_pos << l2es);
1142     // Potential problem: memmove is not guaranteed to be word atomic
1143     // Revisit in Merlin
1144     memmove(dst_addr, src_addr, length << l2es);
1145     return ac_ok;
1146   } else if (src->is_objArray() && dst->is_objArray()) {
1147     if (UseCompressedOops) {  // will need for tiered
1148       narrowOop *src_addr  = objArrayOop(src)->obj_at_addr<narrowOop>(src_pos);
1149       narrowOop *dst_addr  = objArrayOop(dst)->obj_at_addr<narrowOop>(dst_pos);
1150       return obj_arraycopy_work(src, src_addr, dst, dst_addr, length);
1151     } else {
1152       oop *src_addr  = objArrayOop(src)->obj_at_addr<oop>(src_pos);
1153       oop *dst_addr  = objArrayOop(dst)->obj_at_addr<oop>(dst_pos);
1154       return obj_arraycopy_work(src, src_addr, dst, dst_addr, length);
1155     }
1156   }
1157   return ac_failed;
1158 JRT_END
1159 
1160 
1161 JRT_LEAF(void, Runtime1::primitive_arraycopy(HeapWord* src, HeapWord* dst, int length))
1162 #ifndef PRODUCT
1163   _primitive_arraycopy_cnt++;
1164 #endif
1165 
1166   if (length == 0) return;
1167   // Not guaranteed to be word atomic, but that doesn't matter
1168   // for anything but an oop array, which is covered by oop_arraycopy.
1169   Copy::conjoint_jbytes(src, dst, length);
1170 JRT_END
1171 
1172 JRT_LEAF(void, Runtime1::oop_arraycopy(HeapWord* src, HeapWord* dst, int num))
1173 #ifndef PRODUCT
1174   _oop_arraycopy_cnt++;
1175 #endif
1176 
1177   if (num == 0) return;
1178   BarrierSet* bs = Universe::heap()->barrier_set();
1179   assert(bs->has_write_ref_array_opt(), "Barrier set must have ref array opt");
1180   assert(bs->has_write_ref_array_pre_opt(), "For pre-barrier as well.");
1181   if (UseCompressedOops) {
1182     bs->write_ref_array_pre((narrowOop*)dst, num);
1183   } else {
1184     bs->write_ref_array_pre((oop*)dst, num);
1185   }
1186   Copy::conjoint_oops_atomic((oop*) src, (oop*) dst, num);
1187   bs->write_ref_array(dst, num);
1188 JRT_END
1189 
1190 
1191 #ifndef PRODUCT
1192 void Runtime1::print_statistics() {
1193   tty->print_cr("C1 Runtime statistics:");
1194   tty->print_cr(" _resolve_invoke_virtual_cnt:     %d", SharedRuntime::_resolve_virtual_ctr);
1195   tty->print_cr(" _resolve_invoke_opt_virtual_cnt: %d", SharedRuntime::_resolve_opt_virtual_ctr);
1196   tty->print_cr(" _resolve_invoke_static_cnt:      %d", SharedRuntime::_resolve_static_ctr);
1197   tty->print_cr(" _handle_wrong_method_cnt:        %d", SharedRuntime::_wrong_method_ctr);
1198   tty->print_cr(" _ic_miss_cnt:                    %d", SharedRuntime::_ic_miss_ctr);
1199   tty->print_cr(" _generic_arraycopy_cnt:          %d", _generic_arraycopy_cnt);
1200   tty->print_cr(" _primitive_arraycopy_cnt:        %d", _primitive_arraycopy_cnt);
1201   tty->print_cr(" _oop_arraycopy_cnt:              %d", _oop_arraycopy_cnt);
1202   tty->print_cr(" _arraycopy_slowcase_cnt:         %d", _arraycopy_slowcase_cnt);
1203 
1204   tty->print_cr(" _new_type_array_slowcase_cnt:    %d", _new_type_array_slowcase_cnt);
1205   tty->print_cr(" _new_object_array_slowcase_cnt:  %d", _new_object_array_slowcase_cnt);
1206   tty->print_cr(" _new_instance_slowcase_cnt:      %d", _new_instance_slowcase_cnt);
1207   tty->print_cr(" _new_multi_array_slowcase_cnt:   %d", _new_multi_array_slowcase_cnt);
1208   tty->print_cr(" _monitorenter_slowcase_cnt:      %d", _monitorenter_slowcase_cnt);
1209   tty->print_cr(" _monitorexit_slowcase_cnt:       %d", _monitorexit_slowcase_cnt);
1210   tty->print_cr(" _patch_code_slowcase_cnt:        %d", _patch_code_slowcase_cnt);
1211 
1212   tty->print_cr(" _throw_range_check_exception_count:            %d:", _throw_range_check_exception_count);
1213   tty->print_cr(" _throw_index_exception_count:                  %d:", _throw_index_exception_count);
1214   tty->print_cr(" _throw_div0_exception_count:                   %d:", _throw_div0_exception_count);
1215   tty->print_cr(" _throw_null_pointer_exception_count:           %d:", _throw_null_pointer_exception_count);
1216   tty->print_cr(" _throw_class_cast_exception_count:             %d:", _throw_class_cast_exception_count);
1217   tty->print_cr(" _throw_incompatible_class_change_error_count:  %d:", _throw_incompatible_class_change_error_count);
1218   tty->print_cr(" _throw_array_store_exception_count:            %d:", _throw_array_store_exception_count);
1219   tty->print_cr(" _throw_count:                                  %d:", _throw_count);
1220 
1221   SharedRuntime::print_ic_miss_histogram();
1222   tty->cr();
1223 }
1224 #endif // PRODUCT