1 /*
   2  * Copyright (c) 1997, 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/assembler.hpp"
  27 #include "interpreter/bytecodeHistogram.hpp"
  28 #include "interpreter/interpreter.hpp"
  29 #include "interpreter/interpreterGenerator.hpp"
  30 #include "interpreter/interpreterRuntime.hpp"
  31 #include "interpreter/templateTable.hpp"
  32 #include "oops/arrayOop.hpp"
  33 #include "oops/methodDataOop.hpp"
  34 #include "oops/methodOop.hpp"
  35 #include "oops/oop.inline.hpp"
  36 #include "prims/jvmtiExport.hpp"
  37 #include "prims/jvmtiThreadState.hpp"
  38 #include "runtime/arguments.hpp"
  39 #include "runtime/deoptimization.hpp"
  40 #include "runtime/frame.inline.hpp"
  41 #include "runtime/sharedRuntime.hpp"
  42 #include "runtime/stubRoutines.hpp"
  43 #include "runtime/synchronizer.hpp"
  44 #include "runtime/timer.hpp"
  45 #include "runtime/vframeArray.hpp"
  46 #include "utilities/debug.hpp"
  47 
  48 #define __ _masm->
  49 
  50 
  51 #ifndef CC_INTERP
  52 const int method_offset = frame::interpreter_frame_method_offset * wordSize;
  53 const int bci_offset    = frame::interpreter_frame_bcx_offset    * wordSize;
  54 const int locals_offset = frame::interpreter_frame_locals_offset * wordSize;
  55 
  56 //------------------------------------------------------------------------------------------------------------------------
  57 
  58 address TemplateInterpreterGenerator::generate_StackOverflowError_handler() {
  59   address entry = __ pc();
  60 
  61   // Note: There should be a minimal interpreter frame set up when stack
  62   // overflow occurs since we check explicitly for it now.
  63   //
  64 #ifdef ASSERT
  65   { Label L;
  66     __ lea(rax, Address(rbp,
  67                 frame::interpreter_frame_monitor_block_top_offset * wordSize));
  68     __ cmpptr(rax, rsp);  // rax, = maximal rsp for current rbp,
  69                         //  (stack grows negative)
  70     __ jcc(Assembler::aboveEqual, L); // check if frame is complete
  71     __ stop ("interpreter frame not set up");
  72     __ bind(L);
  73   }
  74 #endif // ASSERT
  75   // Restore bcp under the assumption that the current frame is still
  76   // interpreted
  77   __ restore_bcp();
  78 
  79   // expression stack must be empty before entering the VM if an exception
  80   // happened
  81   __ empty_expression_stack();
  82   __ empty_FPU_stack();
  83   // throw exception
  84   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_StackOverflowError));
  85   return entry;
  86 }
  87 
  88 address TemplateInterpreterGenerator::generate_ArrayIndexOutOfBounds_handler(const char* name) {
  89   address entry = __ pc();
  90   // expression stack must be empty before entering the VM if an exception happened
  91   __ empty_expression_stack();
  92   __ empty_FPU_stack();
  93   // setup parameters
  94   // ??? convention: expect aberrant index in register rbx,
  95   __ lea(rax, ExternalAddress((address)name));
  96   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException), rax, rbx);
  97   return entry;
  98 }
  99 
 100 address TemplateInterpreterGenerator::generate_ClassCastException_handler() {
 101   address entry = __ pc();
 102   // object is at TOS
 103   __ pop(rax);
 104   // expression stack must be empty before entering the VM if an exception
 105   // happened
 106   __ empty_expression_stack();
 107   __ empty_FPU_stack();
 108   __ call_VM(noreg,
 109              CAST_FROM_FN_PTR(address,
 110                               InterpreterRuntime::throw_ClassCastException),
 111              rax);
 112   return entry;
 113 }
 114 
 115 address TemplateInterpreterGenerator::generate_exception_handler_common(const char* name, const char* message, bool pass_oop) {
 116   assert(!pass_oop || message == NULL, "either oop or message but not both");
 117   address entry = __ pc();
 118   if (pass_oop) {
 119     // object is at TOS
 120     __ pop(rbx);
 121   }
 122   // expression stack must be empty before entering the VM if an exception happened
 123   __ empty_expression_stack();
 124   __ empty_FPU_stack();
 125   // setup parameters
 126   __ lea(rax, ExternalAddress((address)name));
 127   if (pass_oop) {
 128     __ call_VM(rax, CAST_FROM_FN_PTR(address, InterpreterRuntime::create_klass_exception), rax, rbx);
 129   } else {
 130     if (message != NULL) {
 131       __ lea(rbx, ExternalAddress((address)message));
 132     } else {
 133       __ movptr(rbx, NULL_WORD);
 134     }
 135     __ call_VM(rax, CAST_FROM_FN_PTR(address, InterpreterRuntime::create_exception), rax, rbx);
 136   }
 137   // throw exception
 138   __ jump(ExternalAddress(Interpreter::throw_exception_entry()));
 139   return entry;
 140 }
 141 
 142 
 143 address TemplateInterpreterGenerator::generate_continuation_for(TosState state) {
 144   address entry = __ pc();
 145   // NULL last_sp until next java call
 146   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
 147   __ dispatch_next(state);
 148   return entry;
 149 }
 150 
 151 
 152 address TemplateInterpreterGenerator::generate_return_entry_for(TosState state, int step) {
 153   TosState incoming_state = state;
 154   address entry = __ pc();
 155 
 156 #ifdef COMPILER2
 157   // The FPU stack is clean if UseSSE >= 2 but must be cleaned in other cases
 158   if ((incoming_state == ftos && UseSSE < 1) || (incoming_state == dtos && UseSSE < 2)) {
 159     for (int i = 1; i < 8; i++) {
 160         __ ffree(i);
 161     }
 162   } else if (UseSSE < 2) {
 163     __ empty_FPU_stack();
 164   }
 165 #endif
 166   if ((incoming_state == ftos && UseSSE < 1) || (incoming_state == dtos && UseSSE < 2)) {
 167     __ MacroAssembler::verify_FPU(1, "generate_return_entry_for compiled");
 168   } else {
 169     __ MacroAssembler::verify_FPU(0, "generate_return_entry_for compiled");
 170   }
 171 
 172   // In SSE mode, interpreter returns FP results in xmm0 but they need
 173   // to end up back on the FPU so it can operate on them.
 174   if (incoming_state == ftos && UseSSE >= 1) {
 175     __ subptr(rsp, wordSize);
 176     __ movflt(Address(rsp, 0), xmm0);
 177     __ fld_s(Address(rsp, 0));
 178     __ addptr(rsp, wordSize);
 179   } else if (incoming_state == dtos && UseSSE >= 2) {
 180     __ subptr(rsp, 2*wordSize);
 181     __ movdbl(Address(rsp, 0), xmm0);
 182     __ fld_d(Address(rsp, 0));
 183     __ addptr(rsp, 2*wordSize);
 184   }
 185 
 186   __ MacroAssembler::verify_FPU(state == ftos || state == dtos ? 1 : 0, "generate_return_entry_for in interpreter");
 187 
 188   // Restore stack bottom in case i2c adjusted stack
 189   __ movptr(rsp, Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize));
 190   // and NULL it as marker that rsp is now tos until next java call
 191   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
 192 
 193   __ restore_bcp();
 194   __ restore_locals();
 195 
 196   Label L_got_cache, L_giant_index;
 197   if (EnableInvokeDynamic) {
 198     __ cmpb(Address(rsi, 0), Bytecodes::_invokedynamic);
 199     __ jcc(Assembler::equal, L_giant_index);
 200   }
 201   __ get_cache_and_index_at_bcp(rbx, rcx, 1, sizeof(u2));
 202   __ bind(L_got_cache);
 203   __ movl(rbx, Address(rbx, rcx,
 204                     Address::times_ptr, constantPoolCacheOopDesc::base_offset() +
 205                     ConstantPoolCacheEntry::flags_offset()));
 206   __ andptr(rbx, 0xFF);
 207   __ lea(rsp, Address(rsp, rbx, Interpreter::stackElementScale()));
 208   __ dispatch_next(state, step);
 209 
 210   // out of the main line of code...
 211   if (EnableInvokeDynamic) {
 212     __ bind(L_giant_index);
 213     __ get_cache_and_index_at_bcp(rbx, rcx, 1, sizeof(u4));
 214     __ jmp(L_got_cache);
 215   }
 216 
 217   return entry;
 218 }
 219 
 220 
 221 address TemplateInterpreterGenerator::generate_deopt_entry_for(TosState state, int step) {
 222   address entry = __ pc();
 223 
 224   // In SSE mode, FP results are in xmm0
 225   if (state == ftos && UseSSE > 0) {
 226     __ subptr(rsp, wordSize);
 227     __ movflt(Address(rsp, 0), xmm0);
 228     __ fld_s(Address(rsp, 0));
 229     __ addptr(rsp, wordSize);
 230   } else if (state == dtos && UseSSE >= 2) {
 231     __ subptr(rsp, 2*wordSize);
 232     __ movdbl(Address(rsp, 0), xmm0);
 233     __ fld_d(Address(rsp, 0));
 234     __ addptr(rsp, 2*wordSize);
 235   }
 236 
 237   __ MacroAssembler::verify_FPU(state == ftos || state == dtos ? 1 : 0, "generate_deopt_entry_for in interpreter");
 238 
 239   // The stack is not extended by deopt but we must NULL last_sp as this
 240   // entry is like a "return".
 241   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
 242   __ restore_bcp();
 243   __ restore_locals();
 244   // handle exceptions
 245   { Label L;
 246     const Register thread = rcx;
 247     __ get_thread(thread);
 248     __ cmpptr(Address(thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
 249     __ jcc(Assembler::zero, L);
 250     __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_pending_exception));
 251     __ should_not_reach_here();
 252     __ bind(L);
 253   }
 254   __ dispatch_next(state, step);
 255   return entry;
 256 }
 257 
 258 
 259 int AbstractInterpreter::BasicType_as_index(BasicType type) {
 260   int i = 0;
 261   switch (type) {
 262     case T_BOOLEAN: i = 0; break;
 263     case T_CHAR   : i = 1; break;
 264     case T_BYTE   : i = 2; break;
 265     case T_SHORT  : i = 3; break;
 266     case T_INT    : // fall through
 267     case T_LONG   : // fall through
 268     case T_VOID   : i = 4; break;
 269     case T_FLOAT  : i = 5; break;  // have to treat float and double separately for SSE
 270     case T_DOUBLE : i = 6; break;
 271     case T_OBJECT : // fall through
 272     case T_ARRAY  : i = 7; break;
 273     default       : ShouldNotReachHere();
 274   }
 275   assert(0 <= i && i < AbstractInterpreter::number_of_result_handlers, "index out of bounds");
 276   return i;
 277 }
 278 
 279 
 280 address TemplateInterpreterGenerator::generate_result_handler_for(BasicType type) {
 281   address entry = __ pc();
 282   switch (type) {
 283     case T_BOOLEAN: __ c2bool(rax);            break;
 284     case T_CHAR   : __ andptr(rax, 0xFFFF);    break;
 285     case T_BYTE   : __ sign_extend_byte (rax); break;
 286     case T_SHORT  : __ sign_extend_short(rax); break;
 287     case T_INT    : /* nothing to do */        break;
 288     case T_DOUBLE :
 289     case T_FLOAT  :
 290       { const Register t = InterpreterRuntime::SignatureHandlerGenerator::temp();
 291         __ pop(t);                            // remove return address first
 292         // Must return a result for interpreter or compiler. In SSE
 293         // mode, results are returned in xmm0 and the FPU stack must
 294         // be empty.
 295         if (type == T_FLOAT && UseSSE >= 1) {
 296           // Load ST0
 297           __ fld_d(Address(rsp, 0));
 298           // Store as float and empty fpu stack
 299           __ fstp_s(Address(rsp, 0));
 300           // and reload
 301           __ movflt(xmm0, Address(rsp, 0));
 302         } else if (type == T_DOUBLE && UseSSE >= 2 ) {
 303           __ movdbl(xmm0, Address(rsp, 0));
 304         } else {
 305           // restore ST0
 306           __ fld_d(Address(rsp, 0));
 307         }
 308         // and pop the temp
 309         __ addptr(rsp, 2 * wordSize);
 310         __ push(t);                           // restore return address
 311       }
 312       break;
 313     case T_OBJECT :
 314       // retrieve result from frame
 315       __ movptr(rax, Address(rbp, frame::interpreter_frame_oop_temp_offset*wordSize));
 316       // and verify it
 317       __ verify_oop(rax);
 318       break;
 319     default       : ShouldNotReachHere();
 320   }
 321   __ ret(0);                                   // return from result handler
 322   return entry;
 323 }
 324 
 325 address TemplateInterpreterGenerator::generate_safept_entry_for(TosState state, address runtime_entry) {
 326   address entry = __ pc();
 327   __ push(state);
 328   __ call_VM(noreg, runtime_entry);
 329   __ dispatch_via(vtos, Interpreter::_normal_table.table_for(vtos));
 330   return entry;
 331 }
 332 
 333 
 334 // Helpers for commoning out cases in the various type of method entries.
 335 //
 336 
 337 // increment invocation count & check for overflow
 338 //
 339 // Note: checking for negative value instead of overflow
 340 //       so we have a 'sticky' overflow test
 341 //
 342 // rbx,: method
 343 // rcx: invocation counter
 344 //
 345 void InterpreterGenerator::generate_counter_incr(Label* overflow, Label* profile_method, Label* profile_method_continue) {
 346   const Address invocation_counter(rbx, in_bytes(methodOopDesc::invocation_counter_offset()) +
 347                                         in_bytes(InvocationCounter::counter_offset()));
 348   // Note: In tiered we increment either counters in methodOop or in MDO depending if we're profiling or not.
 349   if (TieredCompilation) {
 350     int increment = InvocationCounter::count_increment;
 351     int mask = ((1 << Tier0InvokeNotifyFreqLog)  - 1) << InvocationCounter::count_shift;
 352     Label no_mdo, done;
 353     if (ProfileInterpreter) {
 354       // Are we profiling?
 355       __ movptr(rax, Address(rbx, methodOopDesc::method_data_offset()));
 356       __ testptr(rax, rax);
 357       __ jccb(Assembler::zero, no_mdo);
 358       // Increment counter in the MDO
 359       const Address mdo_invocation_counter(rax, in_bytes(methodDataOopDesc::invocation_counter_offset()) +
 360                                                 in_bytes(InvocationCounter::counter_offset()));
 361       __ increment_mask_and_jump(mdo_invocation_counter, increment, mask, rcx, false, Assembler::zero, overflow);
 362       __ jmpb(done);
 363     }
 364     __ bind(no_mdo);
 365     // Increment counter in methodOop (we don't need to load it, it's in rcx).
 366     __ increment_mask_and_jump(invocation_counter, increment, mask, rcx, true, Assembler::zero, overflow);
 367     __ bind(done);
 368   } else {
 369     const Address backedge_counter  (rbx, methodOopDesc::backedge_counter_offset() +
 370                                           InvocationCounter::counter_offset());
 371 
 372     if (ProfileInterpreter) { // %%% Merge this into methodDataOop
 373       __ incrementl(Address(rbx,methodOopDesc::interpreter_invocation_counter_offset()));
 374     }
 375     // Update standard invocation counters
 376     __ movl(rax, backedge_counter);               // load backedge counter
 377 
 378     __ incrementl(rcx, InvocationCounter::count_increment);
 379     __ andl(rax, InvocationCounter::count_mask_value);  // mask out the status bits
 380 
 381     __ movl(invocation_counter, rcx);             // save invocation count
 382     __ addl(rcx, rax);                            // add both counters
 383 
 384     // profile_method is non-null only for interpreted method so
 385     // profile_method != NULL == !native_call
 386     // BytecodeInterpreter only calls for native so code is elided.
 387 
 388     if (ProfileInterpreter && profile_method != NULL) {
 389       // Test to see if we should create a method data oop
 390       __ cmp32(rcx,
 391                ExternalAddress((address)&InvocationCounter::InterpreterProfileLimit));
 392       __ jcc(Assembler::less, *profile_method_continue);
 393 
 394       // if no method data exists, go to profile_method
 395       __ test_method_data_pointer(rax, *profile_method);
 396     }
 397 
 398     __ cmp32(rcx,
 399              ExternalAddress((address)&InvocationCounter::InterpreterInvocationLimit));
 400     __ jcc(Assembler::aboveEqual, *overflow);
 401   }
 402 }
 403 
 404 void InterpreterGenerator::generate_counter_overflow(Label* do_continue) {
 405 
 406   // Asm interpreter on entry
 407   // rdi - locals
 408   // rsi - bcp
 409   // rbx, - method
 410   // rdx - cpool
 411   // rbp, - interpreter frame
 412 
 413   // C++ interpreter on entry
 414   // rsi - new interpreter state pointer
 415   // rbp - interpreter frame pointer
 416   // rbx - method
 417 
 418   // On return (i.e. jump to entry_point) [ back to invocation of interpreter ]
 419   // rbx, - method
 420   // rcx - rcvr (assuming there is one)
 421   // top of stack return address of interpreter caller
 422   // rsp - sender_sp
 423 
 424   // C++ interpreter only
 425   // rsi - previous interpreter state pointer
 426 
 427   const Address size_of_parameters(rbx, methodOopDesc::size_of_parameters_offset());
 428 
 429   // InterpreterRuntime::frequency_counter_overflow takes one argument
 430   // indicating if the counter overflow occurs at a backwards branch (non-NULL bcp).
 431   // The call returns the address of the verified entry point for the method or NULL
 432   // if the compilation did not complete (either went background or bailed out).
 433   __ movptr(rax, (intptr_t)false);
 434   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::frequency_counter_overflow), rax);
 435 
 436   __ movptr(rbx, Address(rbp, method_offset));   // restore methodOop
 437 
 438   // Preserve invariant that rsi/rdi contain bcp/locals of sender frame
 439   // and jump to the interpreted entry.
 440   __ jmp(*do_continue, relocInfo::none);
 441 
 442 }
 443 
 444 void InterpreterGenerator::generate_stack_overflow_check(void) {
 445   // see if we've got enough room on the stack for locals plus overhead.
 446   // the expression stack grows down incrementally, so the normal guard
 447   // page mechanism will work for that.
 448   //
 449   // Registers live on entry:
 450   //
 451   // Asm interpreter
 452   // rdx: number of additional locals this frame needs (what we must check)
 453   // rbx,: methodOop
 454 
 455   // destroyed on exit
 456   // rax,
 457 
 458   // NOTE:  since the additional locals are also always pushed (wasn't obvious in
 459   // generate_method_entry) so the guard should work for them too.
 460   //
 461 
 462   // monitor entry size: see picture of stack set (generate_method_entry) and frame_x86.hpp
 463   const int entry_size    = frame::interpreter_frame_monitor_size() * wordSize;
 464 
 465   // total overhead size: entry_size + (saved rbp, thru expr stack bottom).
 466   // be sure to change this if you add/subtract anything to/from the overhead area
 467   const int overhead_size = -(frame::interpreter_frame_initial_sp_offset*wordSize) + entry_size;
 468 
 469   const int page_size = os::vm_page_size();
 470 
 471   Label after_frame_check;
 472 
 473   // see if the frame is greater than one page in size. If so,
 474   // then we need to verify there is enough stack space remaining
 475   // for the additional locals.
 476   __ cmpl(rdx, (page_size - overhead_size)/Interpreter::stackElementSize);
 477   __ jcc(Assembler::belowEqual, after_frame_check);
 478 
 479   // compute rsp as if this were going to be the last frame on
 480   // the stack before the red zone
 481 
 482   Label after_frame_check_pop;
 483 
 484   __ push(rsi);
 485 
 486   const Register thread = rsi;
 487 
 488   __ get_thread(thread);
 489 
 490   const Address stack_base(thread, Thread::stack_base_offset());
 491   const Address stack_size(thread, Thread::stack_size_offset());
 492 
 493   // locals + overhead, in bytes
 494   __ lea(rax, Address(noreg, rdx, Interpreter::stackElementScale(), overhead_size));
 495 
 496 #ifdef ASSERT
 497   Label stack_base_okay, stack_size_okay;
 498   // verify that thread stack base is non-zero
 499   __ cmpptr(stack_base, (int32_t)NULL_WORD);
 500   __ jcc(Assembler::notEqual, stack_base_okay);
 501   __ stop("stack base is zero");
 502   __ bind(stack_base_okay);
 503   // verify that thread stack size is non-zero
 504   __ cmpptr(stack_size, 0);
 505   __ jcc(Assembler::notEqual, stack_size_okay);
 506   __ stop("stack size is zero");
 507   __ bind(stack_size_okay);
 508 #endif
 509 
 510   // Add stack base to locals and subtract stack size
 511   __ addptr(rax, stack_base);
 512   __ subptr(rax, stack_size);
 513 
 514   // Use the maximum number of pages we might bang.
 515   const int max_pages = StackShadowPages > (StackRedPages+StackYellowPages) ? StackShadowPages :
 516                                                                               (StackRedPages+StackYellowPages);
 517   __ addptr(rax, max_pages * page_size);
 518 
 519   // check against the current stack bottom
 520   __ cmpptr(rsp, rax);
 521   __ jcc(Assembler::above, after_frame_check_pop);
 522 
 523   __ pop(rsi);  // get saved bcp / (c++ prev state ).
 524 
 525   // Restore sender's sp as SP. This is necessary if the sender's
 526   // frame is an extended compiled frame (see gen_c2i_adapter())
 527   // and safer anyway in case of JSR292 adaptations.
 528 
 529   __ pop(rax); // return address must be moved if SP is changed
 530   __ mov(rsp, rsi);
 531   __ push(rax);
 532 
 533   // Note: the restored frame is not necessarily interpreted.
 534   // Use the shared runtime version of the StackOverflowError.
 535   assert(StubRoutines::throw_StackOverflowError_entry() != NULL, "stub not yet generated");
 536   __ jump(ExternalAddress(StubRoutines::throw_StackOverflowError_entry()));
 537   // all done with frame size check
 538   __ bind(after_frame_check_pop);
 539   __ pop(rsi);
 540 
 541   __ bind(after_frame_check);
 542 }
 543 
 544 // Allocate monitor and lock method (asm interpreter)
 545 // rbx, - methodOop
 546 //
 547 void InterpreterGenerator::lock_method(void) {
 548   // synchronize method
 549   const Address access_flags      (rbx, methodOopDesc::access_flags_offset());
 550   const Address monitor_block_top (rbp, frame::interpreter_frame_monitor_block_top_offset * wordSize);
 551   const int entry_size            = frame::interpreter_frame_monitor_size() * wordSize;
 552 
 553   #ifdef ASSERT
 554     { Label L;
 555       __ movl(rax, access_flags);
 556       __ testl(rax, JVM_ACC_SYNCHRONIZED);
 557       __ jcc(Assembler::notZero, L);
 558       __ stop("method doesn't need synchronization");
 559       __ bind(L);
 560     }
 561   #endif // ASSERT
 562   // get synchronization object
 563   { Label done;
 564     const int mirror_offset = in_bytes(Klass::java_mirror_offset());
 565     __ movl(rax, access_flags);
 566     __ testl(rax, JVM_ACC_STATIC);
 567     __ movptr(rax, Address(rdi, Interpreter::local_offset_in_bytes(0)));  // get receiver (assume this is frequent case)
 568     __ jcc(Assembler::zero, done);
 569     __ movptr(rax, Address(rbx, methodOopDesc::constants_offset()));
 570     __ movptr(rax, Address(rax, constantPoolOopDesc::pool_holder_offset_in_bytes()));
 571     __ movptr(rax, Address(rax, mirror_offset));
 572     __ bind(done);
 573   }
 574   // add space for monitor & lock
 575   __ subptr(rsp, entry_size);                                           // add space for a monitor entry
 576   __ movptr(monitor_block_top, rsp);                                    // set new monitor block top
 577   __ movptr(Address(rsp, BasicObjectLock::obj_offset_in_bytes()), rax); // store object
 578   __ mov(rdx, rsp);                                                    // object address
 579   __ lock_object(rdx);
 580 }
 581 
 582 //
 583 // Generate a fixed interpreter frame. This is identical setup for interpreted methods
 584 // and for native methods hence the shared code.
 585 
 586 void TemplateInterpreterGenerator::generate_fixed_frame(bool native_call) {
 587   // initialize fixed part of activation frame
 588   __ push(rax);                                       // save return address
 589   __ enter();                                         // save old & set new rbp,
 590 
 591 
 592   __ push(rsi);                                       // set sender sp
 593   __ push((int32_t)NULL_WORD);                        // leave last_sp as null
 594   __ movptr(rsi, Address(rbx,methodOopDesc::const_offset())); // get constMethodOop
 595   __ lea(rsi, Address(rsi,constMethodOopDesc::codes_offset())); // get codebase
 596   __ push(rbx);                                      // save methodOop
 597   if (ProfileInterpreter) {
 598     Label method_data_continue;
 599     __ movptr(rdx, Address(rbx, in_bytes(methodOopDesc::method_data_offset())));
 600     __ testptr(rdx, rdx);
 601     __ jcc(Assembler::zero, method_data_continue);
 602     __ addptr(rdx, in_bytes(methodDataOopDesc::data_offset()));
 603     __ bind(method_data_continue);
 604     __ push(rdx);                                       // set the mdp (method data pointer)
 605   } else {
 606     __ push(0);
 607   }
 608 
 609   __ movptr(rdx, Address(rbx, methodOopDesc::constants_offset()));
 610   __ movptr(rdx, Address(rdx, constantPoolOopDesc::cache_offset_in_bytes()));
 611   __ push(rdx);                                       // set constant pool cache
 612   __ push(rdi);                                       // set locals pointer
 613   if (native_call) {
 614     __ push(0);                                       // no bcp
 615   } else {
 616     __ push(rsi);                                     // set bcp
 617     }
 618   __ push(0);                                         // reserve word for pointer to expression stack bottom
 619   __ movptr(Address(rsp, 0), rsp);                    // set expression stack bottom
 620 }
 621 
 622 // End of helpers
 623 
 624 //
 625 // Various method entries
 626 //------------------------------------------------------------------------------------------------------------------------
 627 //
 628 //
 629 
 630 // Call an accessor method (assuming it is resolved, otherwise drop into vanilla (slow path) entry
 631 
 632 address InterpreterGenerator::generate_accessor_entry(void) {
 633 
 634   // rbx,: methodOop
 635   // rcx: receiver (preserve for slow entry into asm interpreter)
 636 
 637   // rsi: senderSP must preserved for slow path, set SP to it on fast path
 638 
 639   address entry_point = __ pc();
 640   Label xreturn_path;
 641 
 642   // do fastpath for resolved accessor methods
 643   if (UseFastAccessorMethods) {
 644     Label slow_path;
 645     // If we need a safepoint check, generate full interpreter entry.
 646     ExternalAddress state(SafepointSynchronize::address_of_state());
 647     __ cmp32(ExternalAddress(SafepointSynchronize::address_of_state()),
 648              SafepointSynchronize::_not_synchronized);
 649 
 650     __ jcc(Assembler::notEqual, slow_path);
 651     // ASM/C++ Interpreter
 652     // Code: _aload_0, _(i|a)getfield, _(i|a)return or any rewrites thereof; parameter size = 1
 653     // Note: We can only use this code if the getfield has been resolved
 654     //       and if we don't have a null-pointer exception => check for
 655     //       these conditions first and use slow path if necessary.
 656     // rbx,: method
 657     // rcx: receiver
 658     __ movptr(rax, Address(rsp, wordSize));
 659 
 660     // check if local 0 != NULL and read field
 661     __ testptr(rax, rax);
 662     __ jcc(Assembler::zero, slow_path);
 663 
 664     __ movptr(rdi, Address(rbx, methodOopDesc::constants_offset()));
 665     // read first instruction word and extract bytecode @ 1 and index @ 2
 666     __ movptr(rdx, Address(rbx, methodOopDesc::const_offset()));
 667     __ movl(rdx, Address(rdx, constMethodOopDesc::codes_offset()));
 668     // Shift codes right to get the index on the right.
 669     // The bytecode fetched looks like <index><0xb4><0x2a>
 670     __ shrl(rdx, 2*BitsPerByte);
 671     __ shll(rdx, exact_log2(in_words(ConstantPoolCacheEntry::size())));
 672     __ movptr(rdi, Address(rdi, constantPoolOopDesc::cache_offset_in_bytes()));
 673 
 674     // rax,: local 0
 675     // rbx,: method
 676     // rcx: receiver - do not destroy since it is needed for slow path!
 677     // rcx: scratch
 678     // rdx: constant pool cache index
 679     // rdi: constant pool cache
 680     // rsi: sender sp
 681 
 682     // check if getfield has been resolved and read constant pool cache entry
 683     // check the validity of the cache entry by testing whether _indices field
 684     // contains Bytecode::_getfield in b1 byte.
 685     assert(in_words(ConstantPoolCacheEntry::size()) == 4, "adjust shift below");
 686     __ movl(rcx,
 687             Address(rdi,
 688                     rdx,
 689                     Address::times_ptr, constantPoolCacheOopDesc::base_offset() + ConstantPoolCacheEntry::indices_offset()));
 690     __ shrl(rcx, 2*BitsPerByte);
 691     __ andl(rcx, 0xFF);
 692     __ cmpl(rcx, Bytecodes::_getfield);
 693     __ jcc(Assembler::notEqual, slow_path);
 694 
 695     // Note: constant pool entry is not valid before bytecode is resolved
 696     __ movptr(rcx,
 697               Address(rdi,
 698                       rdx,
 699                       Address::times_ptr, constantPoolCacheOopDesc::base_offset() + ConstantPoolCacheEntry::f2_offset()));
 700     __ movl(rdx,
 701             Address(rdi,
 702                     rdx,
 703                     Address::times_ptr, constantPoolCacheOopDesc::base_offset() + ConstantPoolCacheEntry::flags_offset()));
 704 
 705     Label notByte, notShort, notChar;
 706     const Address field_address (rax, rcx, Address::times_1);
 707 
 708     // Need to differentiate between igetfield, agetfield, bgetfield etc.
 709     // because they are different sizes.
 710     // Use the type from the constant pool cache
 711     __ shrl(rdx, ConstantPoolCacheEntry::tosBits);
 712     // Make sure we don't need to mask rdx for tosBits after the above shift
 713     ConstantPoolCacheEntry::verify_tosBits();
 714     __ cmpl(rdx, btos);
 715     __ jcc(Assembler::notEqual, notByte);
 716     __ load_signed_byte(rax, field_address);
 717     __ jmp(xreturn_path);
 718 
 719     __ bind(notByte);
 720     __ cmpl(rdx, stos);
 721     __ jcc(Assembler::notEqual, notShort);
 722     __ load_signed_short(rax, field_address);
 723     __ jmp(xreturn_path);
 724 
 725     __ bind(notShort);
 726     __ cmpl(rdx, ctos);
 727     __ jcc(Assembler::notEqual, notChar);
 728     __ load_unsigned_short(rax, field_address);
 729     __ jmp(xreturn_path);
 730 
 731     __ bind(notChar);
 732 #ifdef ASSERT
 733     Label okay;
 734     __ cmpl(rdx, atos);
 735     __ jcc(Assembler::equal, okay);
 736     __ cmpl(rdx, itos);
 737     __ jcc(Assembler::equal, okay);
 738     __ stop("what type is this?");
 739     __ bind(okay);
 740 #endif // ASSERT
 741     // All the rest are a 32 bit wordsize
 742     // This is ok for now. Since fast accessors should be going away
 743     __ movptr(rax, field_address);
 744 
 745     __ bind(xreturn_path);
 746 
 747     // _ireturn/_areturn
 748     __ pop(rdi);                               // get return address
 749     __ mov(rsp, rsi);                          // set sp to sender sp
 750     __ jmp(rdi);
 751 
 752     // generate a vanilla interpreter entry as the slow path
 753     __ bind(slow_path);
 754 
 755     (void) generate_normal_entry(false);
 756     return entry_point;
 757   }
 758   return NULL;
 759 
 760 }
 761 
 762 // Method entry for java.lang.ref.Reference.get.
 763 address InterpreterGenerator::generate_Reference_get_entry(void) {
 764 #ifndef SERIALGC
 765   // Code: _aload_0, _getfield, _areturn
 766   // parameter size = 1
 767   //
 768   // The code that gets generated by this routine is split into 2 parts:
 769   //    1. The "intrinsified" code for G1 (or any SATB based GC),
 770   //    2. The slow path - which is an expansion of the regular method entry.
 771   //
 772   // Notes:-
 773   // * In the G1 code we do not check whether we need to block for
 774   //   a safepoint. If G1 is enabled then we must execute the specialized
 775   //   code for Reference.get (except when the Reference object is null)
 776   //   so that we can log the value in the referent field with an SATB
 777   //   update buffer.
 778   //   If the code for the getfield template is modified so that the
 779   //   G1 pre-barrier code is executed when the current method is
 780   //   Reference.get() then going through the normal method entry
 781   //   will be fine.
 782   // * The G1 code below can, however, check the receiver object (the instance
 783   //   of java.lang.Reference) and jump to the slow path if null. If the
 784   //   Reference object is null then we obviously cannot fetch the referent
 785   //   and so we don't need to call the G1 pre-barrier. Thus we can use the
 786   //   regular method entry code to generate the NPE.
 787   //
 788   // This code is based on generate_accessor_enty.
 789 
 790   // rbx,: methodOop
 791   // rcx: receiver (preserve for slow entry into asm interpreter)
 792 
 793   // rsi: senderSP must preserved for slow path, set SP to it on fast path
 794 
 795   address entry = __ pc();
 796 
 797   const int referent_offset = java_lang_ref_Reference::referent_offset;
 798   guarantee(referent_offset > 0, "referent offset not initialized");
 799 
 800   if (UseG1GC) {
 801     Label slow_path;
 802 
 803     // Check if local 0 != NULL
 804     // If the receiver is null then it is OK to jump to the slow path.
 805     __ movptr(rax, Address(rsp, wordSize));
 806     __ testptr(rax, rax);
 807     __ jcc(Assembler::zero, slow_path);
 808 
 809     // rax: local 0 (must be preserved across the G1 barrier call)
 810     //
 811     // rbx: method (at this point it's scratch)
 812     // rcx: receiver (at this point it's scratch)
 813     // rdx: scratch
 814     // rdi: scratch
 815     //
 816     // rsi: sender sp
 817 
 818     // Preserve the sender sp in case the pre-barrier
 819     // calls the runtime
 820     __ push(rsi);
 821 
 822     // Load the value of the referent field.
 823     const Address field_address(rax, referent_offset);
 824     __ movptr(rax, field_address);
 825 
 826     // Generate the G1 pre-barrier code to log the value of
 827     // the referent field in an SATB buffer.
 828     __ get_thread(rcx);
 829     __ g1_write_barrier_pre(noreg /* obj */,
 830                             rax /* pre_val */,
 831                             rcx /* thread */,
 832                             rbx /* tmp */,
 833                             true /* tosca_save */,
 834                             true /* expand_call */);
 835 
 836     // _areturn
 837     __ pop(rsi);                // get sender sp
 838     __ pop(rdi);                // get return address
 839     __ mov(rsp, rsi);           // set sp to sender sp
 840     __ jmp(rdi);
 841 
 842     __ bind(slow_path);
 843     (void) generate_normal_entry(false);
 844 
 845     return entry;
 846   }
 847 #endif // SERIALGC
 848 
 849   // If G1 is not enabled then attempt to go through the accessor entry point
 850   // Reference.get is an accessor
 851   return generate_accessor_entry();
 852 }
 853 
 854 //
 855 // Interpreter stub for calling a native method. (asm interpreter)
 856 // This sets up a somewhat different looking stack for calling the native method
 857 // than the typical interpreter frame setup.
 858 //
 859 
 860 address InterpreterGenerator::generate_native_entry(bool synchronized) {
 861   // determine code generation flags
 862   bool inc_counter  = UseCompiler || CountCompiledCalls;
 863 
 864   // rbx,: methodOop
 865   // rsi: sender sp
 866   // rsi: previous interpreter state (C++ interpreter) must preserve
 867   address entry_point = __ pc();
 868 
 869 
 870   const Address size_of_parameters(rbx, methodOopDesc::size_of_parameters_offset());
 871   const Address invocation_counter(rbx, methodOopDesc::invocation_counter_offset() + InvocationCounter::counter_offset());
 872   const Address access_flags      (rbx, methodOopDesc::access_flags_offset());
 873 
 874   // get parameter size (always needed)
 875   __ load_unsigned_short(rcx, size_of_parameters);
 876 
 877   // native calls don't need the stack size check since they have no expression stack
 878   // and the arguments are already on the stack and we only add a handful of words
 879   // to the stack
 880 
 881   // rbx,: methodOop
 882   // rcx: size of parameters
 883   // rsi: sender sp
 884 
 885   __ pop(rax);                                       // get return address
 886   // for natives the size of locals is zero
 887 
 888   // compute beginning of parameters (rdi)
 889   __ lea(rdi, Address(rsp, rcx, Interpreter::stackElementScale(), -wordSize));
 890 
 891 
 892   // add 2 zero-initialized slots for native calls
 893   // NULL result handler
 894   __ push((int32_t)NULL_WORD);
 895   // NULL oop temp (mirror or jni oop result)
 896   __ push((int32_t)NULL_WORD);
 897 
 898   if (inc_counter) __ movl(rcx, invocation_counter);  // (pre-)fetch invocation count
 899   // initialize fixed part of activation frame
 900 
 901   generate_fixed_frame(true);
 902 
 903   // make sure method is native & not abstract
 904 #ifdef ASSERT
 905   __ movl(rax, access_flags);
 906   {
 907     Label L;
 908     __ testl(rax, JVM_ACC_NATIVE);
 909     __ jcc(Assembler::notZero, L);
 910     __ stop("tried to execute non-native method as native");
 911     __ bind(L);
 912   }
 913   { Label L;
 914     __ testl(rax, JVM_ACC_ABSTRACT);
 915     __ jcc(Assembler::zero, L);
 916     __ stop("tried to execute abstract method in interpreter");
 917     __ bind(L);
 918   }
 919 #endif
 920 
 921   // Since at this point in the method invocation the exception handler
 922   // would try to exit the monitor of synchronized methods which hasn't
 923   // been entered yet, we set the thread local variable
 924   // _do_not_unlock_if_synchronized to true. The remove_activation will
 925   // check this flag.
 926 
 927   __ get_thread(rax);
 928   const Address do_not_unlock_if_synchronized(rax,
 929         in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
 930   __ movbool(do_not_unlock_if_synchronized, true);
 931 
 932   // increment invocation count & check for overflow
 933   Label invocation_counter_overflow;
 934   if (inc_counter) {
 935     generate_counter_incr(&invocation_counter_overflow, NULL, NULL);
 936   }
 937 
 938   Label continue_after_compile;
 939   __ bind(continue_after_compile);
 940 
 941   bang_stack_shadow_pages(true);
 942 
 943   // reset the _do_not_unlock_if_synchronized flag
 944   __ get_thread(rax);
 945   __ movbool(do_not_unlock_if_synchronized, false);
 946 
 947   // check for synchronized methods
 948   // Must happen AFTER invocation_counter check and stack overflow check,
 949   // so method is not locked if overflows.
 950   //
 951   if (synchronized) {
 952     lock_method();
 953   } else {
 954     // no synchronization necessary
 955 #ifdef ASSERT
 956       { Label L;
 957         __ movl(rax, access_flags);
 958         __ testl(rax, JVM_ACC_SYNCHRONIZED);
 959         __ jcc(Assembler::zero, L);
 960         __ stop("method needs synchronization");
 961         __ bind(L);
 962       }
 963 #endif
 964   }
 965 
 966   // start execution
 967 #ifdef ASSERT
 968   { Label L;
 969     const Address monitor_block_top (rbp,
 970                  frame::interpreter_frame_monitor_block_top_offset * wordSize);
 971     __ movptr(rax, monitor_block_top);
 972     __ cmpptr(rax, rsp);
 973     __ jcc(Assembler::equal, L);
 974     __ stop("broken stack frame setup in interpreter");
 975     __ bind(L);
 976   }
 977 #endif
 978 
 979   // jvmti/dtrace support
 980   __ notify_method_entry();
 981 
 982   // work registers
 983   const Register method = rbx;
 984   const Register thread = rdi;
 985   const Register t      = rcx;
 986 
 987   // allocate space for parameters
 988   __ get_method(method);
 989   __ verify_oop(method);
 990   __ load_unsigned_short(t, Address(method, methodOopDesc::size_of_parameters_offset()));
 991   __ shlptr(t, Interpreter::logStackElementSize);
 992   __ addptr(t, 2*wordSize);     // allocate two more slots for JNIEnv and possible mirror
 993   __ subptr(rsp, t);
 994   __ andptr(rsp, -(StackAlignmentInBytes)); // gcc needs 16 byte aligned stacks to do XMM intrinsics
 995 
 996   // get signature handler
 997   { Label L;
 998     __ movptr(t, Address(method, methodOopDesc::signature_handler_offset()));
 999     __ testptr(t, t);
1000     __ jcc(Assembler::notZero, L);
1001     __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::prepare_native_call), method);
1002     __ get_method(method);
1003     __ movptr(t, Address(method, methodOopDesc::signature_handler_offset()));
1004     __ bind(L);
1005   }
1006 
1007   // call signature handler
1008   assert(InterpreterRuntime::SignatureHandlerGenerator::from() == rdi, "adjust this code");
1009   assert(InterpreterRuntime::SignatureHandlerGenerator::to  () == rsp, "adjust this code");
1010   assert(InterpreterRuntime::SignatureHandlerGenerator::temp() == t  , "adjust this code");
1011   // The generated handlers do not touch RBX (the method oop).
1012   // However, large signatures cannot be cached and are generated
1013   // each time here.  The slow-path generator will blow RBX
1014   // sometime, so we must reload it after the call.
1015   __ call(t);
1016   __ get_method(method);        // slow path call blows RBX on DevStudio 5.0
1017 
1018   // result handler is in rax,
1019   // set result handler
1020   __ movptr(Address(rbp, frame::interpreter_frame_result_handler_offset*wordSize), rax);
1021 
1022   // pass mirror handle if static call
1023   { Label L;
1024     const int mirror_offset = in_bytes(Klass::java_mirror_offset());
1025     __ movl(t, Address(method, methodOopDesc::access_flags_offset()));
1026     __ testl(t, JVM_ACC_STATIC);
1027     __ jcc(Assembler::zero, L);
1028     // get mirror
1029     __ movptr(t, Address(method, methodOopDesc:: constants_offset()));
1030     __ movptr(t, Address(t, constantPoolOopDesc::pool_holder_offset_in_bytes()));
1031     __ movptr(t, Address(t, mirror_offset));
1032     // copy mirror into activation frame
1033     __ movptr(Address(rbp, frame::interpreter_frame_oop_temp_offset * wordSize), t);
1034     // pass handle to mirror
1035     __ lea(t, Address(rbp, frame::interpreter_frame_oop_temp_offset * wordSize));
1036     __ movptr(Address(rsp, wordSize), t);
1037     __ bind(L);
1038   }
1039 
1040   // get native function entry point
1041   { Label L;
1042     __ movptr(rax, Address(method, methodOopDesc::native_function_offset()));
1043     ExternalAddress unsatisfied(SharedRuntime::native_method_throw_unsatisfied_link_error_entry());
1044     __ cmpptr(rax, unsatisfied.addr());
1045     __ jcc(Assembler::notEqual, L);
1046     __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::prepare_native_call), method);
1047     __ get_method(method);
1048     __ verify_oop(method);
1049     __ movptr(rax, Address(method, methodOopDesc::native_function_offset()));
1050     __ bind(L);
1051   }
1052 
1053   // pass JNIEnv
1054   __ get_thread(thread);
1055   __ lea(t, Address(thread, JavaThread::jni_environment_offset()));
1056   __ movptr(Address(rsp, 0), t);
1057 
1058   // set_last_Java_frame_before_call
1059   // It is enough that the pc()
1060   // points into the right code segment. It does not have to be the correct return pc.
1061   __ set_last_Java_frame(thread, noreg, rbp, __ pc());
1062 
1063   // change thread state
1064 #ifdef ASSERT
1065   { Label L;
1066     __ movl(t, Address(thread, JavaThread::thread_state_offset()));
1067     __ cmpl(t, _thread_in_Java);
1068     __ jcc(Assembler::equal, L);
1069     __ stop("Wrong thread state in native stub");
1070     __ bind(L);
1071   }
1072 #endif
1073 
1074   // Change state to native
1075   __ movl(Address(thread, JavaThread::thread_state_offset()), _thread_in_native);
1076   __ call(rax);
1077 
1078   // result potentially in rdx:rax or ST0
1079 
1080   // Either restore the MXCSR register after returning from the JNI Call
1081   // or verify that it wasn't changed.
1082   if (VM_Version::supports_sse()) {
1083     if (RestoreMXCSROnJNICalls) {
1084       __ ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
1085     }
1086     else if (CheckJNICalls ) {
1087       __ call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
1088     }
1089   }
1090 
1091   // Either restore the x87 floating pointer control word after returning
1092   // from the JNI call or verify that it wasn't changed.
1093   if (CheckJNICalls) {
1094     __ call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
1095   }
1096 
1097   // save potential result in ST(0) & rdx:rax
1098   // (if result handler is the T_FLOAT or T_DOUBLE handler, result must be in ST0 -
1099   // the check is necessary to avoid potential Intel FPU overflow problems by saving/restoring 'empty' FPU registers)
1100   // It is safe to do this push because state is _thread_in_native and return address will be found
1101   // via _last_native_pc and not via _last_jave_sp
1102 
1103   // NOTE: the order of theses push(es) is known to frame::interpreter_frame_result.
1104   // If the order changes or anything else is added to the stack the code in
1105   // interpreter_frame_result will have to be changed.
1106 
1107   { Label L;
1108     Label push_double;
1109     ExternalAddress float_handler(AbstractInterpreter::result_handler(T_FLOAT));
1110     ExternalAddress double_handler(AbstractInterpreter::result_handler(T_DOUBLE));
1111     __ cmpptr(Address(rbp, (frame::interpreter_frame_oop_temp_offset + 1)*wordSize),
1112               float_handler.addr());
1113     __ jcc(Assembler::equal, push_double);
1114     __ cmpptr(Address(rbp, (frame::interpreter_frame_oop_temp_offset + 1)*wordSize),
1115               double_handler.addr());
1116     __ jcc(Assembler::notEqual, L);
1117     __ bind(push_double);
1118     __ push(dtos);
1119     __ bind(L);
1120   }
1121   __ push(ltos);
1122 
1123   // change thread state
1124   __ get_thread(thread);
1125   __ movl(Address(thread, JavaThread::thread_state_offset()), _thread_in_native_trans);
1126   if(os::is_MP()) {
1127     if (UseMembar) {
1128       // Force this write out before the read below
1129       __ membar(Assembler::Membar_mask_bits(
1130            Assembler::LoadLoad | Assembler::LoadStore |
1131            Assembler::StoreLoad | Assembler::StoreStore));
1132     } else {
1133       // Write serialization page so VM thread can do a pseudo remote membar.
1134       // We use the current thread pointer to calculate a thread specific
1135       // offset to write to within the page. This minimizes bus traffic
1136       // due to cache line collision.
1137       __ serialize_memory(thread, rcx);
1138     }
1139   }
1140 
1141   if (AlwaysRestoreFPU) {
1142     //  Make sure the control word is correct.
1143     __ fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
1144   }
1145 
1146   // check for safepoint operation in progress and/or pending suspend requests
1147   { Label Continue;
1148 
1149     __ cmp32(ExternalAddress(SafepointSynchronize::address_of_state()),
1150              SafepointSynchronize::_not_synchronized);
1151 
1152     Label L;
1153     __ jcc(Assembler::notEqual, L);
1154     __ cmpl(Address(thread, JavaThread::suspend_flags_offset()), 0);
1155     __ jcc(Assembler::equal, Continue);
1156     __ bind(L);
1157 
1158     // Don't use call_VM as it will see a possible pending exception and forward it
1159     // and never return here preventing us from clearing _last_native_pc down below.
1160     // Also can't use call_VM_leaf either as it will check to see if rsi & rdi are
1161     // preserved and correspond to the bcp/locals pointers. So we do a runtime call
1162     // by hand.
1163     //
1164     __ push(thread);
1165     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address,
1166                                             JavaThread::check_special_condition_for_native_trans)));
1167     __ increment(rsp, wordSize);
1168     __ get_thread(thread);
1169 
1170     __ bind(Continue);
1171   }
1172 
1173   // change thread state
1174   __ movl(Address(thread, JavaThread::thread_state_offset()), _thread_in_Java);
1175 
1176   __ reset_last_Java_frame(thread, true, true);
1177 
1178   // reset handle block
1179   __ movptr(t, Address(thread, JavaThread::active_handles_offset()));
1180   __ movptr(Address(t, JNIHandleBlock::top_offset_in_bytes()), NULL_WORD);
1181 
1182   // If result was an oop then unbox and save it in the frame
1183   { Label L;
1184     Label no_oop, store_result;
1185     ExternalAddress handler(AbstractInterpreter::result_handler(T_OBJECT));
1186     __ cmpptr(Address(rbp, frame::interpreter_frame_result_handler_offset*wordSize),
1187               handler.addr());
1188     __ jcc(Assembler::notEqual, no_oop);
1189     __ cmpptr(Address(rsp, 0), (int32_t)NULL_WORD);
1190     __ pop(ltos);
1191     __ testptr(rax, rax);
1192     __ jcc(Assembler::zero, store_result);
1193     // unbox
1194     __ movptr(rax, Address(rax, 0));
1195     __ bind(store_result);
1196     __ movptr(Address(rbp, (frame::interpreter_frame_oop_temp_offset)*wordSize), rax);
1197     // keep stack depth as expected by pushing oop which will eventually be discarded
1198     __ push(ltos);
1199     __ bind(no_oop);
1200   }
1201 
1202   {
1203      Label no_reguard;
1204      __ cmpl(Address(thread, JavaThread::stack_guard_state_offset()), JavaThread::stack_guard_yellow_disabled);
1205      __ jcc(Assembler::notEqual, no_reguard);
1206 
1207      __ pusha();
1208      __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages)));
1209      __ popa();
1210 
1211      __ bind(no_reguard);
1212    }
1213 
1214   // restore rsi to have legal interpreter frame,
1215   // i.e., bci == 0 <=> rsi == code_base()
1216   // Can't call_VM until bcp is within reasonable.
1217   __ get_method(method);      // method is junk from thread_in_native to now.
1218   __ verify_oop(method);
1219   __ movptr(rsi, Address(method,methodOopDesc::const_offset()));   // get constMethodOop
1220   __ lea(rsi, Address(rsi,constMethodOopDesc::codes_offset()));    // get codebase
1221 
1222   // handle exceptions (exception handling will handle unlocking!)
1223   { Label L;
1224     __ cmpptr(Address(thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
1225     __ jcc(Assembler::zero, L);
1226     // Note: At some point we may want to unify this with the code used in call_VM_base();
1227     //       i.e., we should use the StubRoutines::forward_exception code. For now this
1228     //       doesn't work here because the rsp is not correctly set at this point.
1229     __ MacroAssembler::call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_pending_exception));
1230     __ should_not_reach_here();
1231     __ bind(L);
1232   }
1233 
1234   // do unlocking if necessary
1235   { Label L;
1236     __ movl(t, Address(method, methodOopDesc::access_flags_offset()));
1237     __ testl(t, JVM_ACC_SYNCHRONIZED);
1238     __ jcc(Assembler::zero, L);
1239     // the code below should be shared with interpreter macro assembler implementation
1240     { Label unlock;
1241       // BasicObjectLock will be first in list, since this is a synchronized method. However, need
1242       // to check that the object has not been unlocked by an explicit monitorexit bytecode.
1243       const Address monitor(rbp, frame::interpreter_frame_initial_sp_offset * wordSize - (int)sizeof(BasicObjectLock));
1244 
1245       __ lea(rdx, monitor);                   // address of first monitor
1246 
1247       __ movptr(t, Address(rdx, BasicObjectLock::obj_offset_in_bytes()));
1248       __ testptr(t, t);
1249       __ jcc(Assembler::notZero, unlock);
1250 
1251       // Entry already unlocked, need to throw exception
1252       __ MacroAssembler::call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_illegal_monitor_state_exception));
1253       __ should_not_reach_here();
1254 
1255       __ bind(unlock);
1256       __ unlock_object(rdx);
1257     }
1258     __ bind(L);
1259   }
1260 
1261   // jvmti/dtrace support
1262   // Note: This must happen _after_ handling/throwing any exceptions since
1263   //       the exception handler code notifies the runtime of method exits
1264   //       too. If this happens before, method entry/exit notifications are
1265   //       not properly paired (was bug - gri 11/22/99).
1266   __ notify_method_exit(vtos, InterpreterMacroAssembler::NotifyJVMTI);
1267 
1268   // restore potential result in rdx:rax, call result handler to restore potential result in ST0 & handle result
1269   __ pop(ltos);
1270   __ movptr(t, Address(rbp, frame::interpreter_frame_result_handler_offset*wordSize));
1271   __ call(t);
1272 
1273   // remove activation
1274   __ movptr(t, Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize)); // get sender sp
1275   __ leave();                                // remove frame anchor
1276   __ pop(rdi);                               // get return address
1277   __ mov(rsp, t);                            // set sp to sender sp
1278   __ jmp(rdi);
1279 
1280   if (inc_counter) {
1281     // Handle overflow of counter and compile method
1282     __ bind(invocation_counter_overflow);
1283     generate_counter_overflow(&continue_after_compile);
1284   }
1285 
1286   return entry_point;
1287 }
1288 
1289 //
1290 // Generic interpreted method entry to (asm) interpreter
1291 //
1292 address InterpreterGenerator::generate_normal_entry(bool synchronized) {
1293   // determine code generation flags
1294   bool inc_counter  = UseCompiler || CountCompiledCalls;
1295 
1296   // rbx,: methodOop
1297   // rsi: sender sp
1298   address entry_point = __ pc();
1299 
1300 
1301   const Address size_of_parameters(rbx, methodOopDesc::size_of_parameters_offset());
1302   const Address size_of_locals    (rbx, methodOopDesc::size_of_locals_offset());
1303   const Address invocation_counter(rbx, methodOopDesc::invocation_counter_offset() + InvocationCounter::counter_offset());
1304   const Address access_flags      (rbx, methodOopDesc::access_flags_offset());
1305 
1306   // get parameter size (always needed)
1307   __ load_unsigned_short(rcx, size_of_parameters);
1308 
1309   // rbx,: methodOop
1310   // rcx: size of parameters
1311 
1312   // rsi: sender_sp (could differ from sp+wordSize if we were called via c2i )
1313 
1314   __ load_unsigned_short(rdx, size_of_locals);       // get size of locals in words
1315   __ subl(rdx, rcx);                                // rdx = no. of additional locals
1316 
1317   // see if we've got enough room on the stack for locals plus overhead.
1318   generate_stack_overflow_check();
1319 
1320   // get return address
1321   __ pop(rax);
1322 
1323   // compute beginning of parameters (rdi)
1324   __ lea(rdi, Address(rsp, rcx, Interpreter::stackElementScale(), -wordSize));
1325 
1326   // rdx - # of additional locals
1327   // allocate space for locals
1328   // explicitly initialize locals
1329   {
1330     Label exit, loop;
1331     __ testl(rdx, rdx);
1332     __ jcc(Assembler::lessEqual, exit);               // do nothing if rdx <= 0
1333     __ bind(loop);
1334     __ push((int32_t)NULL_WORD);                      // initialize local variables
1335     __ decrement(rdx);                                // until everything initialized
1336     __ jcc(Assembler::greater, loop);
1337     __ bind(exit);
1338   }
1339 
1340   if (inc_counter) __ movl(rcx, invocation_counter);  // (pre-)fetch invocation count
1341   // initialize fixed part of activation frame
1342   generate_fixed_frame(false);
1343 
1344   // make sure method is not native & not abstract
1345 #ifdef ASSERT
1346   __ movl(rax, access_flags);
1347   {
1348     Label L;
1349     __ testl(rax, JVM_ACC_NATIVE);
1350     __ jcc(Assembler::zero, L);
1351     __ stop("tried to execute native method as non-native");
1352     __ bind(L);
1353   }
1354   { Label L;
1355     __ testl(rax, JVM_ACC_ABSTRACT);
1356     __ jcc(Assembler::zero, L);
1357     __ stop("tried to execute abstract method in interpreter");
1358     __ bind(L);
1359   }
1360 #endif
1361 
1362   // Since at this point in the method invocation the exception handler
1363   // would try to exit the monitor of synchronized methods which hasn't
1364   // been entered yet, we set the thread local variable
1365   // _do_not_unlock_if_synchronized to true. The remove_activation will
1366   // check this flag.
1367 
1368   __ get_thread(rax);
1369   const Address do_not_unlock_if_synchronized(rax,
1370         in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
1371   __ movbool(do_not_unlock_if_synchronized, true);
1372 
1373   // increment invocation count & check for overflow
1374   Label invocation_counter_overflow;
1375   Label profile_method;
1376   Label profile_method_continue;
1377   if (inc_counter) {
1378     generate_counter_incr(&invocation_counter_overflow, &profile_method, &profile_method_continue);
1379     if (ProfileInterpreter) {
1380       __ bind(profile_method_continue);
1381     }
1382   }
1383   Label continue_after_compile;
1384   __ bind(continue_after_compile);
1385 
1386   bang_stack_shadow_pages(false);
1387 
1388   // reset the _do_not_unlock_if_synchronized flag
1389   __ get_thread(rax);
1390   __ movbool(do_not_unlock_if_synchronized, false);
1391 
1392   // check for synchronized methods
1393   // Must happen AFTER invocation_counter check and stack overflow check,
1394   // so method is not locked if overflows.
1395   //
1396   if (synchronized) {
1397     // Allocate monitor and lock method
1398     lock_method();
1399   } else {
1400     // no synchronization necessary
1401 #ifdef ASSERT
1402       { Label L;
1403         __ movl(rax, access_flags);
1404         __ testl(rax, JVM_ACC_SYNCHRONIZED);
1405         __ jcc(Assembler::zero, L);
1406         __ stop("method needs synchronization");
1407         __ bind(L);
1408       }
1409 #endif
1410   }
1411 
1412   // start execution
1413 #ifdef ASSERT
1414   { Label L;
1415      const Address monitor_block_top (rbp,
1416                  frame::interpreter_frame_monitor_block_top_offset * wordSize);
1417     __ movptr(rax, monitor_block_top);
1418     __ cmpptr(rax, rsp);
1419     __ jcc(Assembler::equal, L);
1420     __ stop("broken stack frame setup in interpreter");
1421     __ bind(L);
1422   }
1423 #endif
1424 
1425   // jvmti support
1426   __ notify_method_entry();
1427 
1428   __ dispatch_next(vtos);
1429 
1430   // invocation counter overflow
1431   if (inc_counter) {
1432     if (ProfileInterpreter) {
1433       // We have decided to profile this method in the interpreter
1434       __ bind(profile_method);
1435       __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::profile_method));
1436       __ set_method_data_pointer_for_bcp();
1437       __ get_method(rbx);
1438       __ jmp(profile_method_continue);
1439     }
1440     // Handle overflow of counter and compile method
1441     __ bind(invocation_counter_overflow);
1442     generate_counter_overflow(&continue_after_compile);
1443   }
1444 
1445   return entry_point;
1446 }
1447 
1448 //------------------------------------------------------------------------------------------------------------------------
1449 // Entry points
1450 //
1451 // Here we generate the various kind of entries into the interpreter.
1452 // The two main entry type are generic bytecode methods and native call method.
1453 // These both come in synchronized and non-synchronized versions but the
1454 // frame layout they create is very similar. The other method entry
1455 // types are really just special purpose entries that are really entry
1456 // and interpretation all in one. These are for trivial methods like
1457 // accessor, empty, or special math methods.
1458 //
1459 // When control flow reaches any of the entry types for the interpreter
1460 // the following holds ->
1461 //
1462 // Arguments:
1463 //
1464 // rbx,: methodOop
1465 // rcx: receiver
1466 //
1467 //
1468 // Stack layout immediately at entry
1469 //
1470 // [ return address     ] <--- rsp
1471 // [ parameter n        ]
1472 //   ...
1473 // [ parameter 1        ]
1474 // [ expression stack   ] (caller's java expression stack)
1475 
1476 // Assuming that we don't go to one of the trivial specialized
1477 // entries the stack will look like below when we are ready to execute
1478 // the first bytecode (or call the native routine). The register usage
1479 // will be as the template based interpreter expects (see interpreter_x86.hpp).
1480 //
1481 // local variables follow incoming parameters immediately; i.e.
1482 // the return address is moved to the end of the locals).
1483 //
1484 // [ monitor entry      ] <--- rsp
1485 //   ...
1486 // [ monitor entry      ]
1487 // [ expr. stack bottom ]
1488 // [ saved rsi          ]
1489 // [ current rdi        ]
1490 // [ methodOop          ]
1491 // [ saved rbp,          ] <--- rbp,
1492 // [ return address     ]
1493 // [ local variable m   ]
1494 //   ...
1495 // [ local variable 1   ]
1496 // [ parameter n        ]
1497 //   ...
1498 // [ parameter 1        ] <--- rdi
1499 
1500 address AbstractInterpreterGenerator::generate_method_entry(AbstractInterpreter::MethodKind kind) {
1501   // determine code generation flags
1502   bool synchronized = false;
1503   address entry_point = NULL;
1504 
1505   switch (kind) {
1506     case Interpreter::zerolocals             :                                                                             break;
1507     case Interpreter::zerolocals_synchronized: synchronized = true;                                                        break;
1508     case Interpreter::native                 : entry_point = ((InterpreterGenerator*)this)->generate_native_entry(false);  break;
1509     case Interpreter::native_synchronized    : entry_point = ((InterpreterGenerator*)this)->generate_native_entry(true);   break;
1510     case Interpreter::empty                  : entry_point = ((InterpreterGenerator*)this)->generate_empty_entry();        break;
1511     case Interpreter::accessor               : entry_point = ((InterpreterGenerator*)this)->generate_accessor_entry();     break;
1512     case Interpreter::abstract               : entry_point = ((InterpreterGenerator*)this)->generate_abstract_entry();     break;
1513     case Interpreter::method_handle          : entry_point = ((InterpreterGenerator*)this)->generate_method_handle_entry(); break;
1514 
1515     case Interpreter::java_lang_math_sin     : // fall thru
1516     case Interpreter::java_lang_math_cos     : // fall thru
1517     case Interpreter::java_lang_math_tan     : // fall thru
1518     case Interpreter::java_lang_math_abs     : // fall thru
1519     case Interpreter::java_lang_math_log     : // fall thru
1520     case Interpreter::java_lang_math_log10   : // fall thru
1521     case Interpreter::java_lang_math_sqrt    : // fall thru
1522     case Interpreter::java_lang_math_pow     : // fall thru
1523     case Interpreter::java_lang_math_exp     : entry_point = ((InterpreterGenerator*)this)->generate_math_entry(kind);     break;
1524     case Interpreter::java_lang_ref_reference_get
1525                                              : entry_point = ((InterpreterGenerator*)this)->generate_Reference_get_entry(); break;
1526     default                                  : ShouldNotReachHere();                                                       break;
1527   }
1528 
1529   if (entry_point) return entry_point;
1530 
1531   return ((InterpreterGenerator*)this)->generate_normal_entry(synchronized);
1532 
1533 }
1534 
1535 // These should never be compiled since the interpreter will prefer
1536 // the compiled version to the intrinsic version.
1537 bool AbstractInterpreter::can_be_compiled(methodHandle m) {
1538   switch (method_kind(m)) {
1539     case Interpreter::java_lang_math_sin     : // fall thru
1540     case Interpreter::java_lang_math_cos     : // fall thru
1541     case Interpreter::java_lang_math_tan     : // fall thru
1542     case Interpreter::java_lang_math_abs     : // fall thru
1543     case Interpreter::java_lang_math_log     : // fall thru
1544     case Interpreter::java_lang_math_log10   : // fall thru
1545     case Interpreter::java_lang_math_sqrt    : // fall thru
1546     case Interpreter::java_lang_math_pow     : // fall thru
1547     case Interpreter::java_lang_math_exp     :
1548       return false;
1549     default:
1550       return true;
1551   }
1552 }
1553 
1554 // How much stack a method activation needs in words.
1555 int AbstractInterpreter::size_top_interpreter_activation(methodOop method) {
1556 
1557   const int stub_code = 4;  // see generate_call_stub
1558   // Save space for one monitor to get into the interpreted method in case
1559   // the method is synchronized
1560   int monitor_size    = method->is_synchronized() ?
1561                                 1*frame::interpreter_frame_monitor_size() : 0;
1562 
1563   // total overhead size: entry_size + (saved rbp, thru expr stack bottom).
1564   // be sure to change this if you add/subtract anything to/from the overhead area
1565   const int overhead_size = -frame::interpreter_frame_initial_sp_offset;
1566 
1567   const int extra_stack = methodOopDesc::extra_stack_entries();
1568   const int method_stack = (method->max_locals() + method->max_stack() + extra_stack) *
1569                            Interpreter::stackElementWords;
1570   return overhead_size + method_stack + stub_code;
1571 }
1572 
1573 // asm based interpreter deoptimization helpers
1574 
1575 int AbstractInterpreter::layout_activation(methodOop method,
1576                                            int tempcount,
1577                                            int popframe_extra_args,
1578                                            int moncount,
1579                                            int caller_actual_parameters,
1580                                            int callee_param_count,
1581                                            int callee_locals,
1582                                            frame* caller,
1583                                            frame* interpreter_frame,
1584                                            bool is_top_frame) {
1585   // Note: This calculation must exactly parallel the frame setup
1586   // in AbstractInterpreterGenerator::generate_method_entry.
1587   // If interpreter_frame!=NULL, set up the method, locals, and monitors.
1588   // The frame interpreter_frame, if not NULL, is guaranteed to be the right size,
1589   // as determined by a previous call to this method.
1590   // It is also guaranteed to be walkable even though it is in a skeletal state
1591   // NOTE: return size is in words not bytes
1592 
1593   // fixed size of an interpreter frame:
1594   int max_locals = method->max_locals() * Interpreter::stackElementWords;
1595   int extra_locals = (method->max_locals() - method->size_of_parameters()) *
1596                      Interpreter::stackElementWords;
1597 
1598   int overhead = frame::sender_sp_offset - frame::interpreter_frame_initial_sp_offset;
1599 
1600   // Our locals were accounted for by the caller (or last_frame_adjust on the transistion)
1601   // Since the callee parameters already account for the callee's params we only need to account for
1602   // the extra locals.
1603 
1604 
1605   int size = overhead +
1606          ((callee_locals - callee_param_count)*Interpreter::stackElementWords) +
1607          (moncount*frame::interpreter_frame_monitor_size()) +
1608          tempcount*Interpreter::stackElementWords + popframe_extra_args;
1609 
1610   if (interpreter_frame != NULL) {
1611 #ifdef ASSERT
1612     if (!EnableInvokeDynamic)
1613       // @@@ FIXME: Should we correct interpreter_frame_sender_sp in the calling sequences?
1614       // Probably, since deoptimization doesn't work yet.
1615       assert(caller->unextended_sp() == interpreter_frame->interpreter_frame_sender_sp(), "Frame not properly walkable");
1616     assert(caller->sp() == interpreter_frame->sender_sp(), "Frame not properly walkable(2)");
1617 #endif
1618 
1619     interpreter_frame->interpreter_frame_set_method(method);
1620     // NOTE the difference in using sender_sp and interpreter_frame_sender_sp
1621     // interpreter_frame_sender_sp is the original sp of the caller (the unextended_sp)
1622     // and sender_sp is fp+8
1623     intptr_t* locals = interpreter_frame->sender_sp() + max_locals - 1;
1624 
1625 #ifdef ASSERT
1626     if (caller->is_interpreted_frame()) {
1627       assert(locals < caller->fp() + frame::interpreter_frame_initial_sp_offset, "bad placement");
1628     }
1629 #endif
1630 
1631     interpreter_frame->interpreter_frame_set_locals(locals);
1632     BasicObjectLock* montop = interpreter_frame->interpreter_frame_monitor_begin();
1633     BasicObjectLock* monbot = montop - moncount;
1634     interpreter_frame->interpreter_frame_set_monitor_end(monbot);
1635 
1636     // Set last_sp
1637     intptr_t*  rsp = (intptr_t*) monbot  -
1638                      tempcount*Interpreter::stackElementWords -
1639                      popframe_extra_args;
1640     interpreter_frame->interpreter_frame_set_last_sp(rsp);
1641 
1642     // All frames but the initial (oldest) interpreter frame we fill in have a
1643     // value for sender_sp that allows walking the stack but isn't
1644     // truly correct. Correct the value here.
1645 
1646     if (extra_locals != 0 &&
1647         interpreter_frame->sender_sp() == interpreter_frame->interpreter_frame_sender_sp() ) {
1648       interpreter_frame->set_interpreter_frame_sender_sp(caller->sp() + extra_locals);
1649     }
1650     *interpreter_frame->interpreter_frame_cache_addr() =
1651       method->constants()->cache();
1652   }
1653   return size;
1654 }
1655 
1656 
1657 //------------------------------------------------------------------------------------------------------------------------
1658 // Exceptions
1659 
1660 void TemplateInterpreterGenerator::generate_throw_exception() {
1661   // Entry point in previous activation (i.e., if the caller was interpreted)
1662   Interpreter::_rethrow_exception_entry = __ pc();
1663   const Register thread = rcx;
1664 
1665   // Restore sp to interpreter_frame_last_sp even though we are going
1666   // to empty the expression stack for the exception processing.
1667   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
1668   // rax,: exception
1669   // rdx: return address/pc that threw exception
1670   __ restore_bcp();                              // rsi points to call/send
1671   __ restore_locals();
1672 
1673   // Entry point for exceptions thrown within interpreter code
1674   Interpreter::_throw_exception_entry = __ pc();
1675   // expression stack is undefined here
1676   // rax,: exception
1677   // rsi: exception bcp
1678   __ verify_oop(rax);
1679 
1680   // expression stack must be empty before entering the VM in case of an exception
1681   __ empty_expression_stack();
1682   __ empty_FPU_stack();
1683   // find exception handler address and preserve exception oop
1684   __ call_VM(rdx, CAST_FROM_FN_PTR(address, InterpreterRuntime::exception_handler_for_exception), rax);
1685   // rax,: exception handler entry point
1686   // rdx: preserved exception oop
1687   // rsi: bcp for exception handler
1688   __ push_ptr(rdx);                              // push exception which is now the only value on the stack
1689   __ jmp(rax);                                   // jump to exception handler (may be _remove_activation_entry!)
1690 
1691   // If the exception is not handled in the current frame the frame is removed and
1692   // the exception is rethrown (i.e. exception continuation is _rethrow_exception).
1693   //
1694   // Note: At this point the bci is still the bxi for the instruction which caused
1695   //       the exception and the expression stack is empty. Thus, for any VM calls
1696   //       at this point, GC will find a legal oop map (with empty expression stack).
1697 
1698   // In current activation
1699   // tos: exception
1700   // rsi: exception bcp
1701 
1702   //
1703   // JVMTI PopFrame support
1704   //
1705 
1706    Interpreter::_remove_activation_preserving_args_entry = __ pc();
1707   __ empty_expression_stack();
1708   __ empty_FPU_stack();
1709   // Set the popframe_processing bit in pending_popframe_condition indicating that we are
1710   // currently handling popframe, so that call_VMs that may happen later do not trigger new
1711   // popframe handling cycles.
1712   __ get_thread(thread);
1713   __ movl(rdx, Address(thread, JavaThread::popframe_condition_offset()));
1714   __ orl(rdx, JavaThread::popframe_processing_bit);
1715   __ movl(Address(thread, JavaThread::popframe_condition_offset()), rdx);
1716 
1717   {
1718     // Check to see whether we are returning to a deoptimized frame.
1719     // (The PopFrame call ensures that the caller of the popped frame is
1720     // either interpreted or compiled and deoptimizes it if compiled.)
1721     // In this case, we can't call dispatch_next() after the frame is
1722     // popped, but instead must save the incoming arguments and restore
1723     // them after deoptimization has occurred.
1724     //
1725     // Note that we don't compare the return PC against the
1726     // deoptimization blob's unpack entry because of the presence of
1727     // adapter frames in C2.
1728     Label caller_not_deoptimized;
1729     __ movptr(rdx, Address(rbp, frame::return_addr_offset * wordSize));
1730     __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::interpreter_contains), rdx);
1731     __ testl(rax, rax);
1732     __ jcc(Assembler::notZero, caller_not_deoptimized);
1733 
1734     // Compute size of arguments for saving when returning to deoptimized caller
1735     __ get_method(rax);
1736     __ verify_oop(rax);
1737     __ load_unsigned_short(rax, Address(rax, in_bytes(methodOopDesc::size_of_parameters_offset())));
1738     __ shlptr(rax, Interpreter::logStackElementSize);
1739     __ restore_locals();
1740     __ subptr(rdi, rax);
1741     __ addptr(rdi, wordSize);
1742     // Save these arguments
1743     __ get_thread(thread);
1744     __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::popframe_preserve_args), thread, rax, rdi);
1745 
1746     __ remove_activation(vtos, rdx,
1747                          /* throw_monitor_exception */ false,
1748                          /* install_monitor_exception */ false,
1749                          /* notify_jvmdi */ false);
1750 
1751     // Inform deoptimization that it is responsible for restoring these arguments
1752     __ get_thread(thread);
1753     __ movl(Address(thread, JavaThread::popframe_condition_offset()), JavaThread::popframe_force_deopt_reexecution_bit);
1754 
1755     // Continue in deoptimization handler
1756     __ jmp(rdx);
1757 
1758     __ bind(caller_not_deoptimized);
1759   }
1760 
1761   __ remove_activation(vtos, rdx,
1762                        /* throw_monitor_exception */ false,
1763                        /* install_monitor_exception */ false,
1764                        /* notify_jvmdi */ false);
1765 
1766   // Finish with popframe handling
1767   // A previous I2C followed by a deoptimization might have moved the
1768   // outgoing arguments further up the stack. PopFrame expects the
1769   // mutations to those outgoing arguments to be preserved and other
1770   // constraints basically require this frame to look exactly as
1771   // though it had previously invoked an interpreted activation with
1772   // no space between the top of the expression stack (current
1773   // last_sp) and the top of stack. Rather than force deopt to
1774   // maintain this kind of invariant all the time we call a small
1775   // fixup routine to move the mutated arguments onto the top of our
1776   // expression stack if necessary.
1777   __ mov(rax, rsp);
1778   __ movptr(rbx, Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize));
1779   __ get_thread(thread);
1780   // PC must point into interpreter here
1781   __ set_last_Java_frame(thread, noreg, rbp, __ pc());
1782   __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::popframe_move_outgoing_args), thread, rax, rbx);
1783   __ get_thread(thread);
1784   __ reset_last_Java_frame(thread, true, true);
1785   // Restore the last_sp and null it out
1786   __ movptr(rsp, Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize));
1787   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
1788 
1789   __ restore_bcp();
1790   __ restore_locals();
1791   // The method data pointer was incremented already during
1792   // call profiling. We have to restore the mdp for the current bcp.
1793   if (ProfileInterpreter) {
1794     __ set_method_data_pointer_for_bcp();
1795   }
1796 
1797   // Clear the popframe condition flag
1798   __ get_thread(thread);
1799   __ movl(Address(thread, JavaThread::popframe_condition_offset()), JavaThread::popframe_inactive);
1800 
1801   __ dispatch_next(vtos);
1802   // end of PopFrame support
1803 
1804   Interpreter::_remove_activation_entry = __ pc();
1805 
1806   // preserve exception over this code sequence
1807   __ pop_ptr(rax);
1808   __ get_thread(thread);
1809   __ movptr(Address(thread, JavaThread::vm_result_offset()), rax);
1810   // remove the activation (without doing throws on illegalMonitorExceptions)
1811   __ remove_activation(vtos, rdx, false, true, false);
1812   // restore exception
1813   __ get_thread(thread);
1814   __ movptr(rax, Address(thread, JavaThread::vm_result_offset()));
1815   __ movptr(Address(thread, JavaThread::vm_result_offset()), NULL_WORD);
1816   __ verify_oop(rax);
1817 
1818   // Inbetween activations - previous activation type unknown yet
1819   // compute continuation point - the continuation point expects
1820   // the following registers set up:
1821   //
1822   // rax: exception
1823   // rdx: return address/pc that threw exception
1824   // rsp: expression stack of caller
1825   // rbp: rbp, of caller
1826   __ push(rax);                                  // save exception
1827   __ push(rdx);                                  // save return address
1828   __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address), thread, rdx);
1829   __ mov(rbx, rax);                              // save exception handler
1830   __ pop(rdx);                                   // restore return address
1831   __ pop(rax);                                   // restore exception
1832   // Note that an "issuing PC" is actually the next PC after the call
1833   __ jmp(rbx);                                   // jump to exception handler of caller
1834 }
1835 
1836 
1837 //
1838 // JVMTI ForceEarlyReturn support
1839 //
1840 address TemplateInterpreterGenerator::generate_earlyret_entry_for(TosState state) {
1841   address entry = __ pc();
1842   const Register thread = rcx;
1843 
1844   __ restore_bcp();
1845   __ restore_locals();
1846   __ empty_expression_stack();
1847   __ empty_FPU_stack();
1848   __ load_earlyret_value(state);
1849 
1850   __ get_thread(thread);
1851   __ movptr(rcx, Address(thread, JavaThread::jvmti_thread_state_offset()));
1852   const Address cond_addr(rcx, JvmtiThreadState::earlyret_state_offset());
1853 
1854   // Clear the earlyret state
1855   __ movl(cond_addr, JvmtiThreadState::earlyret_inactive);
1856 
1857   __ remove_activation(state, rsi,
1858                        false, /* throw_monitor_exception */
1859                        false, /* install_monitor_exception */
1860                        true); /* notify_jvmdi */
1861   __ jmp(rsi);
1862   return entry;
1863 } // end of ForceEarlyReturn support
1864 
1865 
1866 //------------------------------------------------------------------------------------------------------------------------
1867 // Helper for vtos entry point generation
1868 
1869 void TemplateInterpreterGenerator::set_vtos_entry_points (Template* t, address& bep, address& cep, address& sep, address& aep, address& iep, address& lep, address& fep, address& dep, address& vep) {
1870   assert(t->is_valid() && t->tos_in() == vtos, "illegal template");
1871   Label L;
1872   fep = __ pc(); __ push(ftos); __ jmp(L);
1873   dep = __ pc(); __ push(dtos); __ jmp(L);
1874   lep = __ pc(); __ push(ltos); __ jmp(L);
1875   aep = __ pc(); __ push(atos); __ jmp(L);
1876   bep = cep = sep =             // fall through
1877   iep = __ pc(); __ push(itos); // fall through
1878   vep = __ pc(); __ bind(L);    // fall through
1879   generate_and_dispatch(t);
1880 }
1881 
1882 //------------------------------------------------------------------------------------------------------------------------
1883 // Generation of individual instructions
1884 
1885 // helpers for generate_and_dispatch
1886 
1887 
1888 
1889 InterpreterGenerator::InterpreterGenerator(StubQueue* code)
1890  : TemplateInterpreterGenerator(code) {
1891    generate_all(); // down here so it can be "virtual"
1892 }
1893 
1894 //------------------------------------------------------------------------------------------------------------------------
1895 
1896 // Non-product code
1897 #ifndef PRODUCT
1898 address TemplateInterpreterGenerator::generate_trace_code(TosState state) {
1899   address entry = __ pc();
1900 
1901   // prepare expression stack
1902   __ pop(rcx);          // pop return address so expression stack is 'pure'
1903   __ push(state);       // save tosca
1904 
1905   // pass tosca registers as arguments & call tracer
1906   __ call_VM(noreg, CAST_FROM_FN_PTR(address, SharedRuntime::trace_bytecode), rcx, rax, rdx);
1907   __ mov(rcx, rax);     // make sure return address is not destroyed by pop(state)
1908   __ pop(state);        // restore tosca
1909 
1910   // return
1911   __ jmp(rcx);
1912 
1913   return entry;
1914 }
1915 
1916 
1917 void TemplateInterpreterGenerator::count_bytecode() {
1918   __ incrementl(ExternalAddress((address) &BytecodeCounter::_counter_value));
1919 }
1920 
1921 
1922 void TemplateInterpreterGenerator::histogram_bytecode(Template* t) {
1923   __ incrementl(ExternalAddress((address) &BytecodeHistogram::_counters[t->bytecode()]));
1924 }
1925 
1926 
1927 void TemplateInterpreterGenerator::histogram_bytecode_pair(Template* t) {
1928   __ mov32(ExternalAddress((address) &BytecodePairHistogram::_index), rbx);
1929   __ shrl(rbx, BytecodePairHistogram::log2_number_of_codes);
1930   __ orl(rbx, ((int)t->bytecode()) << BytecodePairHistogram::log2_number_of_codes);
1931   ExternalAddress table((address) BytecodePairHistogram::_counters);
1932   Address index(noreg, rbx, Address::times_4);
1933   __ incrementl(ArrayAddress(table, index));
1934 }
1935 
1936 
1937 void TemplateInterpreterGenerator::trace_bytecode(Template* t) {
1938   // Call a little run-time stub to avoid blow-up for each bytecode.
1939   // The run-time runtime saves the right registers, depending on
1940   // the tosca in-state for the given template.
1941   assert(Interpreter::trace_code(t->tos_in()) != NULL,
1942          "entry must have been generated");
1943   __ call(RuntimeAddress(Interpreter::trace_code(t->tos_in())));
1944 }
1945 
1946 
1947 void TemplateInterpreterGenerator::stop_interpreter_at() {
1948   Label L;
1949   __ cmp32(ExternalAddress((address) &BytecodeCounter::_counter_value),
1950            StopInterpreterAt);
1951   __ jcc(Assembler::notEqual, L);
1952   __ int3();
1953   __ bind(L);
1954 }
1955 #endif // !PRODUCT
1956 #endif // CC_INTERP