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