1 /*
   2  * Copyright 1999-2007 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  20  * CA 95054 USA or visit www.sun.com if you need additional information or
  21  * have any questions.
  22  *
  23  */
  24 
  25 #include "incls/_precompiled.incl"
  26 #include "incls/_stubGenerator_x86_32.cpp.incl"
  27 
  28 // Declaration and definition of StubGenerator (no .hpp file).
  29 // For a more detailed description of the stub routine structure
  30 // see the comment in stubRoutines.hpp
  31 
  32 #define __ _masm->
  33 
  34 #ifdef PRODUCT
  35 #define BLOCK_COMMENT(str) /* nothing */
  36 #else
  37 #define BLOCK_COMMENT(str) __ block_comment(str)
  38 #endif
  39 
  40 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  41 
  42 const int MXCSR_MASK  = 0xFFC0;  // Mask out any pending exceptions
  43 const int FPU_CNTRL_WRD_MASK = 0xFFFF;
  44 
  45 // -------------------------------------------------------------------------------------------------------------------------
  46 // Stub Code definitions
  47 
  48 static address handle_unsafe_access() {
  49   JavaThread* thread = JavaThread::current();
  50   address pc  = thread->saved_exception_pc();
  51   // pc is the instruction which we must emulate
  52   // doing a no-op is fine:  return garbage from the load
  53   // therefore, compute npc
  54   address npc = Assembler::locate_next_instruction(pc);
  55 
  56   // request an async exception
  57   thread->set_pending_unsafe_access_error();
  58 
  59   // return address of next instruction to execute
  60   return npc;
  61 }
  62 
  63 class StubGenerator: public StubCodeGenerator {
  64  private:
  65 
  66 #ifdef PRODUCT
  67 #define inc_counter_np(counter) (0)
  68 #else
  69   void inc_counter_np_(int& counter) {
  70     __ increment(ExternalAddress((address)&counter));
  71   }
  72 #define inc_counter_np(counter) \
  73   BLOCK_COMMENT("inc_counter " #counter); \
  74   inc_counter_np_(counter);
  75 #endif //PRODUCT
  76 
  77   void inc_copy_counter_np(BasicType t) {
  78 #ifndef PRODUCT
  79     switch (t) {
  80     case T_BYTE:    inc_counter_np(SharedRuntime::_jbyte_array_copy_ctr); return;
  81     case T_SHORT:   inc_counter_np(SharedRuntime::_jshort_array_copy_ctr); return;
  82     case T_INT:     inc_counter_np(SharedRuntime::_jint_array_copy_ctr); return;
  83     case T_LONG:    inc_counter_np(SharedRuntime::_jlong_array_copy_ctr); return;
  84     case T_OBJECT:  inc_counter_np(SharedRuntime::_oop_array_copy_ctr); return;
  85     }
  86     ShouldNotReachHere();
  87 #endif //PRODUCT
  88   }
  89 
  90   //------------------------------------------------------------------------------------------------------------------------
  91   // Call stubs are used to call Java from C
  92   //
  93   //    [ return_from_Java     ] <--- rsp
  94   //    [ argument word n      ]
  95   //      ...
  96   // -N [ argument word 1      ]
  97   // -7 [ Possible padding for stack alignment ]
  98   // -6 [ Possible padding for stack alignment ]
  99   // -5 [ Possible padding for stack alignment ]
 100   // -4 [ mxcsr save           ] <--- rsp_after_call
 101   // -3 [ saved rbx,            ]
 102   // -2 [ saved rsi            ]
 103   // -1 [ saved rdi            ]
 104   //  0 [ saved rbp,            ] <--- rbp,
 105   //  1 [ return address       ]
 106   //  2 [ ptr. to call wrapper ]
 107   //  3 [ result               ]
 108   //  4 [ result_type          ]
 109   //  5 [ method               ]
 110   //  6 [ entry_point          ]
 111   //  7 [ parameters           ]
 112   //  8 [ parameter_size       ]
 113   //  9 [ thread               ]
 114 
 115 
 116   address generate_call_stub(address& return_address) {
 117     StubCodeMark mark(this, "StubRoutines", "call_stub");
 118     address start = __ pc();
 119 
 120     // stub code parameters / addresses
 121     assert(frame::entry_frame_call_wrapper_offset == 2, "adjust this code");
 122     bool  sse_save = false;
 123     const Address rsp_after_call(rbp, -4 * wordSize); // same as in generate_catch_exception()!
 124     const int     locals_count_in_bytes  (4*wordSize);
 125     const Address mxcsr_save    (rbp, -4 * wordSize);
 126     const Address saved_rbx     (rbp, -3 * wordSize);
 127     const Address saved_rsi     (rbp, -2 * wordSize);
 128     const Address saved_rdi     (rbp, -1 * wordSize);
 129     const Address result        (rbp,  3 * wordSize);
 130     const Address result_type   (rbp,  4 * wordSize);
 131     const Address method        (rbp,  5 * wordSize);
 132     const Address entry_point   (rbp,  6 * wordSize);
 133     const Address parameters    (rbp,  7 * wordSize);
 134     const Address parameter_size(rbp,  8 * wordSize);
 135     const Address thread        (rbp,  9 * wordSize); // same as in generate_catch_exception()!
 136     sse_save =  UseSSE > 0;
 137 
 138     // stub code
 139     __ enter();
 140     __ movl(rcx, parameter_size);              // parameter counter
 141     __ shll(rcx, Interpreter::logStackElementSize()); // convert parameter count to bytes
 142     __ addl(rcx, locals_count_in_bytes);       // reserve space for register saves
 143     __ subl(rsp, rcx);
 144     __ andl(rsp, -(StackAlignmentInBytes));    // Align stack
 145 
 146     // save rdi, rsi, & rbx, according to C calling conventions
 147     __ movl(saved_rdi, rdi);
 148     __ movl(saved_rsi, rsi);
 149     __ movl(saved_rbx, rbx);
 150     // save and initialize %mxcsr
 151     if (sse_save) {
 152       Label skip_ldmx;
 153       __ stmxcsr(mxcsr_save);
 154       __ movl(rax, mxcsr_save);
 155       __ andl(rax, MXCSR_MASK);    // Only check control and mask bits
 156       ExternalAddress mxcsr_std(StubRoutines::addr_mxcsr_std());
 157       __ cmp32(rax, mxcsr_std);
 158       __ jcc(Assembler::equal, skip_ldmx);
 159       __ ldmxcsr(mxcsr_std);
 160       __ bind(skip_ldmx);
 161     }
 162 
 163     // make sure the control word is correct.
 164     __ fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
 165 
 166 #ifdef ASSERT
 167     // make sure we have no pending exceptions
 168     { Label L;
 169       __ movl(rcx, thread);
 170       __ cmpl(Address(rcx, Thread::pending_exception_offset()), NULL_WORD);
 171       __ jcc(Assembler::equal, L);
 172       __ stop("StubRoutines::call_stub: entered with pending exception");
 173       __ bind(L);
 174     }
 175 #endif
 176 
 177     // pass parameters if any
 178     BLOCK_COMMENT("pass parameters if any");
 179     Label parameters_done;
 180     __ movl(rcx, parameter_size);  // parameter counter
 181     __ testl(rcx, rcx);
 182     __ jcc(Assembler::zero, parameters_done);
 183 
 184     // parameter passing loop
 185 
 186     Label loop;
 187     // Copy Java parameters in reverse order (receiver last)
 188     // Note that the argument order is inverted in the process
 189     // source is rdx[rcx: N-1..0]
 190     // dest   is rsp[rbx: 0..N-1]
 191 
 192     __ movl(rdx, parameters);          // parameter pointer
 193     __ xorl(rbx, rbx);
 194 
 195     __ BIND(loop);
 196     if (TaggedStackInterpreter) {
 197       __ movl(rax, Address(rdx, rcx, Interpreter::stackElementScale(),
 198                       -2*wordSize));                          // get tag
 199       __ movl(Address(rsp, rbx, Interpreter::stackElementScale(),
 200                       Interpreter::expr_tag_offset_in_bytes(0)), rax);     // store tag
 201     }
 202 
 203     // get parameter
 204     __ movl(rax, Address(rdx, rcx, Interpreter::stackElementScale(), -wordSize));
 205     __ movl(Address(rsp, rbx, Interpreter::stackElementScale(),
 206                     Interpreter::expr_offset_in_bytes(0)), rax);          // store parameter
 207     __ increment(rbx);
 208     __ decrement(rcx);
 209     __ jcc(Assembler::notZero, loop);
 210 
 211     // call Java function
 212     __ BIND(parameters_done);
 213     __ movl(rbx, method);              // get methodOop
 214     __ movl(rax, entry_point);         // get entry_point
 215     __ movl(rsi, rsp);                 // set sender sp
 216     BLOCK_COMMENT("call Java function");
 217     __ call(rax);
 218 
 219     BLOCK_COMMENT("call_stub_return_address:");
 220     return_address = __ pc();
 221 
 222     Label common_return;
 223 
 224     __ BIND(common_return);
 225 
 226     // store result depending on type
 227     // (everything that is not T_LONG, T_FLOAT or T_DOUBLE is treated as T_INT)
 228     __ movl(rdi, result);
 229     Label is_long, is_float, is_double, exit;
 230     __ movl(rsi, result_type);
 231     __ cmpl(rsi, T_LONG);
 232     __ jcc(Assembler::equal, is_long);
 233     __ cmpl(rsi, T_FLOAT);
 234     __ jcc(Assembler::equal, is_float);
 235     __ cmpl(rsi, T_DOUBLE);
 236     __ jcc(Assembler::equal, is_double);
 237 
 238     // handle T_INT case
 239     __ movl(Address(rdi, 0), rax);
 240     __ BIND(exit);
 241 
 242     // check that FPU stack is empty
 243     __ verify_FPU(0, "generate_call_stub");
 244 
 245     // pop parameters
 246     __ leal(rsp, rsp_after_call);
 247 
 248     // restore %mxcsr
 249     if (sse_save) {
 250       __ ldmxcsr(mxcsr_save);
 251     }
 252 
 253     // restore rdi, rsi and rbx,
 254     __ movl(rbx, saved_rbx);
 255     __ movl(rsi, saved_rsi);
 256     __ movl(rdi, saved_rdi);
 257     __ addl(rsp, 4*wordSize);
 258 
 259     // return
 260     __ popl(rbp);
 261     __ ret(0);
 262 
 263     // handle return types different from T_INT
 264     __ BIND(is_long);
 265     __ movl(Address(rdi, 0 * wordSize), rax);
 266     __ movl(Address(rdi, 1 * wordSize), rdx);
 267     __ jmp(exit);
 268 
 269     __ BIND(is_float);
 270     // interpreter uses xmm0 for return values
 271     if (UseSSE >= 1) {
 272       __ movflt(Address(rdi, 0), xmm0);
 273     } else {
 274       __ fstp_s(Address(rdi, 0));
 275     }
 276     __ jmp(exit);
 277 
 278     __ BIND(is_double);
 279     // interpreter uses xmm0 for return values
 280     if (UseSSE >= 2) {
 281       __ movdbl(Address(rdi, 0), xmm0);
 282     } else {
 283       __ fstp_d(Address(rdi, 0));
 284     }
 285     __ jmp(exit);
 286 
 287     // If we call compiled code directly from the call stub we will
 288     // need to adjust the return back to the call stub to a specialized
 289     // piece of code that can handle compiled results and cleaning the fpu
 290     // stack. compiled code will be set to return here instead of the
 291     // return above that handles interpreter returns.
 292 
 293     BLOCK_COMMENT("call_stub_compiled_return:");
 294     StubRoutines::i486::set_call_stub_compiled_return( __ pc());
 295 
 296 #ifdef COMPILER2
 297     if (UseSSE >= 2) {
 298       __ verify_FPU(0, "call_stub_compiled_return");
 299     } else {
 300       for (int i = 1; i < 8; i++) {
 301         __ ffree(i);
 302       }
 303 
 304       // UseSSE <= 1 so double result should be left on TOS
 305       __ movl(rsi, result_type);
 306       __ cmpl(rsi, T_DOUBLE);
 307       __ jcc(Assembler::equal, common_return);
 308       if (UseSSE == 0) {
 309         // UseSSE == 0 so float result should be left on TOS
 310         __ cmpl(rsi, T_FLOAT);
 311         __ jcc(Assembler::equal, common_return);
 312       }
 313       __ ffree(0);
 314     }
 315 #endif /* COMPILER2 */
 316     __ jmp(common_return);
 317 
 318     return start;
 319   }
 320 
 321 
 322   //------------------------------------------------------------------------------------------------------------------------
 323   // Return point for a Java call if there's an exception thrown in Java code.
 324   // The exception is caught and transformed into a pending exception stored in
 325   // JavaThread that can be tested from within the VM.
 326   //
 327   // Note: Usually the parameters are removed by the callee. In case of an exception
 328   //       crossing an activation frame boundary, that is not the case if the callee
 329   //       is compiled code => need to setup the rsp.
 330   //
 331   // rax,: exception oop
 332 
 333   address generate_catch_exception() {
 334     StubCodeMark mark(this, "StubRoutines", "catch_exception");
 335     const Address rsp_after_call(rbp, -4 * wordSize); // same as in generate_call_stub()!
 336     const Address thread        (rbp,  9 * wordSize); // same as in generate_call_stub()!
 337     address start = __ pc();
 338 
 339     // get thread directly
 340     __ movl(rcx, thread);
 341 #ifdef ASSERT
 342     // verify that threads correspond
 343     { Label L;
 344       __ get_thread(rbx);
 345       __ cmpl(rbx, rcx);
 346       __ jcc(Assembler::equal, L);
 347       __ stop("StubRoutines::catch_exception: threads must correspond");
 348       __ bind(L);
 349     }
 350 #endif
 351     // set pending exception
 352     __ verify_oop(rax);
 353     __ movl(Address(rcx, Thread::pending_exception_offset()), rax          );
 354     __ lea(Address(rcx, Thread::exception_file_offset   ()),
 355            ExternalAddress((address)__FILE__));
 356     __ movl(Address(rcx, Thread::exception_line_offset   ()), __LINE__ );
 357     // complete return to VM
 358     assert(StubRoutines::_call_stub_return_address != NULL, "_call_stub_return_address must have been generated before");
 359     __ jump(RuntimeAddress(StubRoutines::_call_stub_return_address));
 360 
 361     return start;
 362   }
 363 
 364 
 365   //------------------------------------------------------------------------------------------------------------------------
 366   // Continuation point for runtime calls returning with a pending exception.
 367   // The pending exception check happened in the runtime or native call stub.
 368   // The pending exception in Thread is converted into a Java-level exception.
 369   //
 370   // Contract with Java-level exception handlers:
 371   // rax,: exception
 372   // rdx: throwing pc
 373   //
 374   // NOTE: At entry of this stub, exception-pc must be on stack !!
 375 
 376   address generate_forward_exception() {
 377     StubCodeMark mark(this, "StubRoutines", "forward exception");
 378     address start = __ pc();
 379 
 380     // Upon entry, the sp points to the return address returning into Java
 381     // (interpreted or compiled) code; i.e., the return address becomes the
 382     // throwing pc.
 383     //
 384     // Arguments pushed before the runtime call are still on the stack but
 385     // the exception handler will reset the stack pointer -> ignore them.
 386     // A potential result in registers can be ignored as well.
 387 
 388 #ifdef ASSERT
 389     // make sure this code is only executed if there is a pending exception
 390     { Label L;
 391       __ get_thread(rcx);
 392       __ cmpl(Address(rcx, Thread::pending_exception_offset()), NULL_WORD);
 393       __ jcc(Assembler::notEqual, L);
 394       __ stop("StubRoutines::forward exception: no pending exception (1)");
 395       __ bind(L);
 396     }
 397 #endif
 398 
 399     // compute exception handler into rbx,
 400     __ movl(rax, Address(rsp, 0));
 401     BLOCK_COMMENT("call exception_handler_for_return_address");
 402     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address), rax);
 403     __ movl(rbx, rax);
 404 
 405     // setup rax, & rdx, remove return address & clear pending exception
 406     __ get_thread(rcx);
 407     __ popl(rdx);
 408     __ movl(rax, Address(rcx, Thread::pending_exception_offset()));
 409     __ movl(Address(rcx, Thread::pending_exception_offset()), NULL_WORD);
 410 
 411 #ifdef ASSERT
 412     // make sure exception is set
 413     { Label L;
 414       __ testl(rax, rax);
 415       __ jcc(Assembler::notEqual, L);
 416       __ stop("StubRoutines::forward exception: no pending exception (2)");
 417       __ bind(L);
 418     }
 419 #endif
 420 
 421     // continue at exception handler (return address removed)
 422     // rax,: exception
 423     // rbx,: exception handler
 424     // rdx: throwing pc
 425     __ verify_oop(rax);
 426     __ jmp(rbx);
 427 
 428     return start;
 429   }
 430 
 431 
 432   //----------------------------------------------------------------------------------------------------
 433   // Support for jint Atomic::xchg(jint exchange_value, volatile jint* dest)
 434   //
 435   // xchg exists as far back as 8086, lock needed for MP only
 436   // Stack layout immediately after call:
 437   //
 438   // 0 [ret addr ] <--- rsp
 439   // 1 [  ex     ]
 440   // 2 [  dest   ]
 441   //
 442   // Result:   *dest <- ex, return (old *dest)
 443   //
 444   // Note: win32 does not currently use this code
 445 
 446   address generate_atomic_xchg() {
 447     StubCodeMark mark(this, "StubRoutines", "atomic_xchg");
 448     address start = __ pc();
 449 
 450     __ pushl(rdx);
 451     Address exchange(rsp, 2 * wordSize);
 452     Address dest_addr(rsp, 3 * wordSize);
 453     __ movl(rax, exchange);
 454     __ movl(rdx, dest_addr);
 455     __ xchg(rax, Address(rdx, 0));
 456     __ popl(rdx);
 457     __ ret(0);
 458 
 459     return start;
 460   }
 461 
 462   //----------------------------------------------------------------------------------------------------
 463   // Support for void verify_mxcsr()
 464   //
 465   // This routine is used with -Xcheck:jni to verify that native
 466   // JNI code does not return to Java code without restoring the
 467   // MXCSR register to our expected state.
 468 
 469 
 470   address generate_verify_mxcsr() {
 471     StubCodeMark mark(this, "StubRoutines", "verify_mxcsr");
 472     address start = __ pc();
 473 
 474     const Address mxcsr_save(rsp, 0);
 475 
 476     if (CheckJNICalls && UseSSE > 0 ) {
 477       Label ok_ret;
 478       ExternalAddress mxcsr_std(StubRoutines::addr_mxcsr_std());
 479       __ pushl(rax);
 480       __ subl(rsp, wordSize);      // allocate a temp location
 481       __ stmxcsr(mxcsr_save);
 482       __ movl(rax, mxcsr_save);
 483       __ andl(rax, MXCSR_MASK);
 484       __ cmp32(rax, mxcsr_std);
 485       __ jcc(Assembler::equal, ok_ret);
 486 
 487       __ warn("MXCSR changed by native JNI code.");
 488 
 489       __ ldmxcsr(mxcsr_std);
 490 
 491       __ bind(ok_ret);
 492       __ addl(rsp, wordSize);
 493       __ popl(rax);
 494     }
 495 
 496     __ ret(0);
 497 
 498     return start;
 499   }
 500 
 501 
 502   //---------------------------------------------------------------------------
 503   // Support for void verify_fpu_cntrl_wrd()
 504   //
 505   // This routine is used with -Xcheck:jni to verify that native
 506   // JNI code does not return to Java code without restoring the
 507   // FP control word to our expected state.
 508 
 509   address generate_verify_fpu_cntrl_wrd() {
 510     StubCodeMark mark(this, "StubRoutines", "verify_spcw");
 511     address start = __ pc();
 512 
 513     const Address fpu_cntrl_wrd_save(rsp, 0);
 514 
 515     if (CheckJNICalls) {
 516       Label ok_ret;
 517       __ pushl(rax);
 518       __ subl(rsp, wordSize);      // allocate a temp location
 519       __ fnstcw(fpu_cntrl_wrd_save);
 520       __ movl(rax, fpu_cntrl_wrd_save);
 521       __ andl(rax, FPU_CNTRL_WRD_MASK);
 522       ExternalAddress fpu_std(StubRoutines::addr_fpu_cntrl_wrd_std());
 523       __ cmp32(rax, fpu_std);
 524       __ jcc(Assembler::equal, ok_ret);
 525 
 526       __ warn("Floating point control word changed by native JNI code.");
 527 
 528       __ fldcw(fpu_std);
 529 
 530       __ bind(ok_ret);
 531       __ addl(rsp, wordSize);
 532       __ popl(rax);
 533     }
 534 
 535     __ ret(0);
 536 
 537     return start;
 538   }
 539 
 540   //---------------------------------------------------------------------------
 541   // Wrapper for slow-case handling of double-to-integer conversion
 542   // d2i or f2i fast case failed either because it is nan or because
 543   // of under/overflow.
 544   // Input:  FPU TOS: float value
 545   // Output: rax, (rdx): integer (long) result
 546 
 547   address generate_d2i_wrapper(BasicType t, address fcn) {
 548     StubCodeMark mark(this, "StubRoutines", "d2i_wrapper");
 549     address start = __ pc();
 550 
 551   // Capture info about frame layout
 552   enum layout { FPUState_off         = 0,
 553                 rbp_off              = FPUStateSizeInWords,
 554                 rdi_off,
 555                 rsi_off,
 556                 rcx_off,
 557                 rbx_off,
 558                 saved_argument_off,
 559                 saved_argument_off2, // 2nd half of double
 560                 framesize
 561   };
 562 
 563   assert(FPUStateSizeInWords == 27, "update stack layout");
 564 
 565     // Save outgoing argument to stack across push_FPU_state()
 566     __ subl(rsp, wordSize * 2);
 567     __ fstp_d(Address(rsp, 0));
 568 
 569     // Save CPU & FPU state
 570     __ pushl(rbx);
 571     __ pushl(rcx);
 572     __ pushl(rsi);
 573     __ pushl(rdi);
 574     __ pushl(rbp);
 575     __ push_FPU_state();
 576 
 577     // push_FPU_state() resets the FP top of stack
 578     // Load original double into FP top of stack
 579     __ fld_d(Address(rsp, saved_argument_off * wordSize));
 580     // Store double into stack as outgoing argument
 581     __ subl(rsp, wordSize*2);
 582     __ fst_d(Address(rsp, 0));
 583 
 584     // Prepare FPU for doing math in C-land
 585     __ empty_FPU_stack();
 586     // Call the C code to massage the double.  Result in EAX
 587     if (t == T_INT)
 588       { BLOCK_COMMENT("SharedRuntime::d2i"); }
 589     else if (t == T_LONG)
 590       { BLOCK_COMMENT("SharedRuntime::d2l"); }
 591     __ call_VM_leaf( fcn, 2 );
 592 
 593     // Restore CPU & FPU state
 594     __ pop_FPU_state();
 595     __ popl(rbp);
 596     __ popl(rdi);
 597     __ popl(rsi);
 598     __ popl(rcx);
 599     __ popl(rbx);
 600     __ addl(rsp, wordSize * 2);
 601 
 602     __ ret(0);
 603 
 604     return start;
 605   }
 606 
 607 
 608   //---------------------------------------------------------------------------
 609   // The following routine generates a subroutine to throw an asynchronous
 610   // UnknownError when an unsafe access gets a fault that could not be
 611   // reasonably prevented by the programmer.  (Example: SIGBUS/OBJERR.)
 612   address generate_handler_for_unsafe_access() {
 613     StubCodeMark mark(this, "StubRoutines", "handler_for_unsafe_access");
 614     address start = __ pc();
 615 
 616     __ pushl(0);                      // hole for return address-to-be
 617     __ pushad();                      // push registers
 618     Address next_pc(rsp, RegisterImpl::number_of_registers * BytesPerWord);
 619     BLOCK_COMMENT("call handle_unsafe_access");
 620     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, handle_unsafe_access)));
 621     __ movl(next_pc, rax);            // stuff next address
 622     __ popad();
 623     __ ret(0);                        // jump to next address
 624 
 625     return start;
 626   }
 627 
 628 
 629   //----------------------------------------------------------------------------------------------------
 630   // Non-destructive plausibility checks for oops
 631 
 632   address generate_verify_oop() {
 633     StubCodeMark mark(this, "StubRoutines", "verify_oop");
 634     address start = __ pc();
 635 
 636     // Incoming arguments on stack after saving rax,:
 637     //
 638     // [tos    ]: saved rdx
 639     // [tos + 1]: saved EFLAGS
 640     // [tos + 2]: return address
 641     // [tos + 3]: char* error message
 642     // [tos + 4]: oop   object to verify
 643     // [tos + 5]: saved rax, - saved by caller and bashed
 644 
 645     Label exit, error;
 646     __ pushfd();
 647     __ increment(ExternalAddress((address) StubRoutines::verify_oop_count_addr()));
 648     __ pushl(rdx);                               // save rdx
 649     // make sure object is 'reasonable'
 650     __ movl(rax, Address(rsp, 4 * wordSize));    // get object
 651     __ testl(rax, rax);
 652     __ jcc(Assembler::zero, exit);               // if obj is NULL it is ok
 653 
 654     // Check if the oop is in the right area of memory
 655     const int oop_mask = Universe::verify_oop_mask();
 656     const int oop_bits = Universe::verify_oop_bits();
 657     __ movl(rdx, rax);
 658     __ andl(rdx, oop_mask);
 659     __ cmpl(rdx, oop_bits);
 660     __ jcc(Assembler::notZero, error);
 661 
 662     // make sure klass is 'reasonable'
 663     __ movl(rax, Address(rax, oopDesc::klass_offset_in_bytes())); // get klass
 664     __ testl(rax, rax);
 665     __ jcc(Assembler::zero, error);              // if klass is NULL it is broken
 666 
 667     // Check if the klass is in the right area of memory
 668     const int klass_mask = Universe::verify_klass_mask();
 669     const int klass_bits = Universe::verify_klass_bits();
 670     __ movl(rdx, rax);
 671     __ andl(rdx, klass_mask);
 672     __ cmpl(rdx, klass_bits);
 673     __ jcc(Assembler::notZero, error);
 674 
 675     // make sure klass' klass is 'reasonable'
 676     __ movl(rax, Address(rax, oopDesc::klass_offset_in_bytes())); // get klass' klass
 677     __ testl(rax, rax);
 678     __ jcc(Assembler::zero, error);              // if klass' klass is NULL it is broken
 679 
 680     __ movl(rdx, rax);
 681     __ andl(rdx, klass_mask);
 682     __ cmpl(rdx, klass_bits);
 683     __ jcc(Assembler::notZero, error);           // if klass not in right area
 684                                                  // of memory it is broken too.
 685 
 686     // return if everything seems ok
 687     __ bind(exit);
 688     __ movl(rax, Address(rsp, 5 * wordSize));    // get saved rax, back
 689     __ popl(rdx);                                // restore rdx
 690     __ popfd();                                  // restore EFLAGS
 691     __ ret(3 * wordSize);                        // pop arguments
 692 
 693     // handle errors
 694     __ bind(error);
 695     __ movl(rax, Address(rsp, 5 * wordSize));    // get saved rax, back
 696     __ popl(rdx);                                // get saved rdx back
 697     __ popfd();                                  // get saved EFLAGS off stack -- will be ignored
 698     __ pushad();                                 // push registers (eip = return address & msg are already pushed)
 699     BLOCK_COMMENT("call MacroAssembler::debug");
 700     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug)));
 701     __ popad();
 702     __ ret(3 * wordSize);                        // pop arguments
 703     return start;
 704   }
 705 
 706   //
 707   //  Generate pre-barrier for array stores
 708   //
 709   //  Input:
 710   //     start   -  starting address
 711   //     end     -  element count
 712   void  gen_write_ref_array_pre_barrier(Register start, Register count) {
 713     assert_different_registers(start, count);
 714 #if 0 // G1 only
 715     BarrierSet* bs = Universe::heap()->barrier_set();
 716     switch (bs->kind()) {
 717       case BarrierSet::G1SATBCT:
 718       case BarrierSet::G1SATBCTLogging:
 719         {
 720           __ pushad();                      // push registers
 721           __ pushl(count);
 722           __ pushl(start);
 723           __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, BarrierSet::static_write_ref_array_pre));
 724           __ addl(esp, wordSize * 2);
 725           __ popad();
 726         }
 727         break;
 728       case BarrierSet::CardTableModRef:
 729       case BarrierSet::CardTableExtension:
 730       case BarrierSet::ModRef:
 731         break;
 732       default      :
 733         ShouldNotReachHere();
 734 
 735     }
 736 #endif // 0 - G1 only
 737   }
 738 
 739 
 740   //
 741   // Generate a post-barrier for an array store
 742   //
 743   //     start    -  starting address
 744   //     count    -  element count
 745   //
 746   //  The two input registers are overwritten.
 747   //
 748   void  gen_write_ref_array_post_barrier(Register start, Register count) {
 749     BarrierSet* bs = Universe::heap()->barrier_set();
 750     assert_different_registers(start, count);
 751     switch (bs->kind()) {
 752 #if 0 // G1 only
 753       case BarrierSet::G1SATBCT:
 754       case BarrierSet::G1SATBCTLogging:
 755         {
 756           __ pushad();                      // push registers
 757           __ pushl(count);
 758           __ pushl(start);
 759           __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, BarrierSet::static_write_ref_array_post));
 760           __ addl(esp, wordSize * 2);
 761           __ popad();
 762 
 763         }
 764         break;
 765 #endif // 0 G1 only
 766 
 767       case BarrierSet::CardTableModRef:
 768       case BarrierSet::CardTableExtension:
 769         {
 770           CardTableModRefBS* ct = (CardTableModRefBS*)bs;
 771           assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
 772 
 773           Label L_loop;
 774           const Register end = count;  // elements count; end == start+count-1
 775           assert_different_registers(start, end);
 776 
 777           __ leal(end,   Address(start, count, Address::times_4, -4));
 778           __ shrl(start, CardTableModRefBS::card_shift);
 779           __ shrl(end,   CardTableModRefBS::card_shift);
 780           __ subl(end, start); // end --> count
 781         __ BIND(L_loop);
 782           ExternalAddress base((address)ct->byte_map_base);
 783           Address index(start, count, Address::times_1, 0);
 784           __ movbyte(ArrayAddress(base, index), 0);
 785           __ decrement(count);
 786           __ jcc(Assembler::greaterEqual, L_loop);
 787         }
 788         break;
 789       case BarrierSet::ModRef:
 790         break;
 791       default      :
 792         ShouldNotReachHere();
 793 
 794     }
 795   }
 796 
 797   // Copy 64 bytes chunks
 798   //
 799   // Inputs:
 800   //   from        - source array address
 801   //   to_from     - destination array address - from
 802   //   qword_count - 8-bytes element count, negative
 803   //
 804   void mmx_copy_forward(Register from, Register to_from, Register qword_count) {
 805     Label L_copy_64_bytes_loop, L_copy_64_bytes, L_copy_8_bytes, L_exit;
 806     // Copy 64-byte chunks
 807     __ jmpb(L_copy_64_bytes);
 808     __ align(16);
 809   __ BIND(L_copy_64_bytes_loop);
 810     __ movq(mmx0, Address(from, 0));
 811     __ movq(mmx1, Address(from, 8));
 812     __ movq(mmx2, Address(from, 16));
 813     __ movq(Address(from, to_from, Address::times_1, 0), mmx0);
 814     __ movq(mmx3, Address(from, 24));
 815     __ movq(Address(from, to_from, Address::times_1, 8), mmx1);
 816     __ movq(mmx4, Address(from, 32));
 817     __ movq(Address(from, to_from, Address::times_1, 16), mmx2);
 818     __ movq(mmx5, Address(from, 40));
 819     __ movq(Address(from, to_from, Address::times_1, 24), mmx3);
 820     __ movq(mmx6, Address(from, 48));
 821     __ movq(Address(from, to_from, Address::times_1, 32), mmx4);
 822     __ movq(mmx7, Address(from, 56));
 823     __ movq(Address(from, to_from, Address::times_1, 40), mmx5);
 824     __ movq(Address(from, to_from, Address::times_1, 48), mmx6);
 825     __ movq(Address(from, to_from, Address::times_1, 56), mmx7);
 826     __ addl(from, 64);
 827   __ BIND(L_copy_64_bytes);
 828     __ subl(qword_count, 8);
 829     __ jcc(Assembler::greaterEqual, L_copy_64_bytes_loop);
 830     __ addl(qword_count, 8);
 831     __ jccb(Assembler::zero, L_exit);
 832     //
 833     // length is too short, just copy qwords
 834     //
 835   __ BIND(L_copy_8_bytes);
 836     __ movq(mmx0, Address(from, 0));
 837     __ movq(Address(from, to_from, Address::times_1), mmx0);
 838     __ addl(from, 8);
 839     __ decrement(qword_count);
 840     __ jcc(Assembler::greater, L_copy_8_bytes);
 841   __ BIND(L_exit);
 842     __ emms();
 843   }
 844 
 845   address generate_disjoint_copy(BasicType t, bool aligned,
 846                                  Address::ScaleFactor sf,
 847                                  address* entry, const char *name) {
 848     __ align(CodeEntryAlignment);
 849     StubCodeMark mark(this, "StubRoutines", name);
 850     address start = __ pc();
 851 
 852     Label L_0_count, L_exit, L_skip_align1, L_skip_align2, L_copy_byte;
 853     Label L_copy_2_bytes, L_copy_4_bytes, L_copy_64_bytes;
 854 
 855     int shift = Address::times_4 - sf;
 856 
 857     const Register from     = rsi;  // source array address
 858     const Register to       = rdi;  // destination array address
 859     const Register count    = rcx;  // elements count
 860     const Register to_from  = to;   // (to - from)
 861     const Register saved_to = rdx;  // saved destination array address
 862 
 863     __ enter(); // required for proper stackwalking of RuntimeStub frame
 864     __ pushl(rsi);
 865     __ pushl(rdi);
 866     __ movl(from , Address(rsp, 12+ 4));
 867     __ movl(to   , Address(rsp, 12+ 8));
 868     __ movl(count, Address(rsp, 12+ 12));
 869     if (t == T_OBJECT) {
 870       __ testl(count, count);
 871       __ jcc(Assembler::zero, L_0_count);
 872       gen_write_ref_array_pre_barrier(to, count);
 873       __ movl(saved_to, to);          // save 'to'
 874     }
 875 
 876     *entry = __ pc(); // Entry point from conjoint arraycopy stub.
 877     BLOCK_COMMENT("Entry:");
 878 
 879     __ subl(to, from); // to --> to_from
 880     __ cmpl(count, 2<<shift); // Short arrays (< 8 bytes) copy by element
 881     __ jcc(Assembler::below, L_copy_4_bytes); // use unsigned cmp
 882     if (!aligned && (t == T_BYTE || t == T_SHORT)) {
 883       // align source address at 4 bytes address boundary
 884       if (t == T_BYTE) {
 885         // One byte misalignment happens only for byte arrays
 886         __ testl(from, 1);
 887         __ jccb(Assembler::zero, L_skip_align1);
 888         __ movb(rax, Address(from, 0));
 889         __ movb(Address(from, to_from, Address::times_1, 0), rax);
 890         __ increment(from);
 891         __ decrement(count);
 892       __ BIND(L_skip_align1);
 893       }
 894       // Two bytes misalignment happens only for byte and short (char) arrays
 895       __ testl(from, 2);
 896       __ jccb(Assembler::zero, L_skip_align2);
 897       __ movw(rax, Address(from, 0));
 898       __ movw(Address(from, to_from, Address::times_1, 0), rax);
 899       __ addl(from, 2);
 900       __ subl(count, 1<<(shift-1));
 901     __ BIND(L_skip_align2);
 902     }
 903     if (!VM_Version::supports_mmx()) {
 904       __ movl(rax, count);     // save 'count'
 905       __ shrl(count, shift);   // bytes count
 906       __ addl(to_from, from);  // restore 'to'
 907       __ rep_movl();
 908       __ subl(to_from, from);  // restore 'to_from'
 909       __ movl(count, rax);     // restore 'count'
 910       __ jmpb(L_copy_2_bytes); // all dwords were copied
 911     } else {
 912       // align to 8 bytes, we know we are 4 byte aligned to start
 913       __ testl(from, 4);
 914       __ jccb(Assembler::zero, L_copy_64_bytes);
 915       __ movl(rax, Address(from, 0));
 916       __ movl(Address(from, to_from, Address::times_1, 0), rax);
 917       __ addl(from, 4);
 918       __ subl(count, 1<<shift);
 919     __ BIND(L_copy_64_bytes);
 920       __ movl(rax, count);
 921       __ shrl(rax, shift+1);  // 8 bytes chunk count
 922       //
 923       // Copy 8-byte chunks through MMX registers, 8 per iteration of the loop
 924       //
 925       mmx_copy_forward(from, to_from, rax);
 926     }
 927     // copy tailing dword
 928   __ BIND(L_copy_4_bytes);
 929     __ testl(count, 1<<shift);
 930     __ jccb(Assembler::zero, L_copy_2_bytes);
 931     __ movl(rax, Address(from, 0));
 932     __ movl(Address(from, to_from, Address::times_1, 0), rax);
 933     if (t == T_BYTE || t == T_SHORT) {
 934       __ addl(from, 4);
 935     __ BIND(L_copy_2_bytes);
 936       // copy tailing word
 937       __ testl(count, 1<<(shift-1));
 938       __ jccb(Assembler::zero, L_copy_byte);
 939       __ movw(rax, Address(from, 0));
 940       __ movw(Address(from, to_from, Address::times_1, 0), rax);
 941       if (t == T_BYTE) {
 942         __ addl(from, 2);
 943       __ BIND(L_copy_byte);
 944         // copy tailing byte
 945         __ testl(count, 1);
 946         __ jccb(Assembler::zero, L_exit);
 947         __ movb(rax, Address(from, 0));
 948         __ movb(Address(from, to_from, Address::times_1, 0), rax);
 949       __ BIND(L_exit);
 950       } else {
 951       __ BIND(L_copy_byte);
 952       }
 953     } else {
 954     __ BIND(L_copy_2_bytes);
 955     }
 956 
 957     if (t == T_OBJECT) {
 958       __ movl(count, Address(rsp, 12+12)); // reread 'count'
 959       __ movl(to, saved_to); // restore 'to'
 960       gen_write_ref_array_post_barrier(to, count);
 961     __ BIND(L_0_count);
 962     }
 963     inc_copy_counter_np(t);
 964     __ popl(rdi);
 965     __ popl(rsi);
 966     __ leave(); // required for proper stackwalking of RuntimeStub frame
 967     __ xorl(rax, rax); // return 0
 968     __ ret(0);
 969     return start;
 970   }
 971 
 972 
 973   address generate_conjoint_copy(BasicType t, bool aligned,
 974                                  Address::ScaleFactor sf,
 975                                  address nooverlap_target,
 976                                  address* entry, const char *name) {
 977     __ align(CodeEntryAlignment);
 978     StubCodeMark mark(this, "StubRoutines", name);
 979     address start = __ pc();
 980 
 981     Label L_0_count, L_exit, L_skip_align1, L_skip_align2, L_copy_byte;
 982     Label L_copy_2_bytes, L_copy_4_bytes, L_copy_8_bytes, L_copy_8_bytes_loop;
 983 
 984     int shift = Address::times_4 - sf;
 985 
 986     const Register src   = rax;  // source array address
 987     const Register dst   = rdx;  // destination array address
 988     const Register from  = rsi;  // source array address
 989     const Register to    = rdi;  // destination array address
 990     const Register count = rcx;  // elements count
 991     const Register end   = rax;  // array end address
 992 
 993     __ enter(); // required for proper stackwalking of RuntimeStub frame
 994     __ pushl(rsi);
 995     __ pushl(rdi);
 996     __ movl(src  , Address(rsp, 12+ 4));  // from
 997     __ movl(dst  , Address(rsp, 12+ 8));  // to
 998     __ movl(count, Address(rsp, 12+12));  // count
 999     if (t == T_OBJECT) {
1000        gen_write_ref_array_pre_barrier(dst, count);
1001     }
1002 
1003     if (entry != NULL) {
1004       *entry = __ pc(); // Entry point from generic arraycopy stub.
1005       BLOCK_COMMENT("Entry:");
1006     }
1007 
1008     if (t == T_OBJECT) {
1009       __ testl(count, count);
1010       __ jcc(Assembler::zero, L_0_count);
1011     }
1012     __ movl(from, src);
1013     __ movl(to  , dst);
1014 
1015     // arrays overlap test
1016     RuntimeAddress nooverlap(nooverlap_target);
1017     __ cmpl(dst, src);
1018     __ leal(end, Address(src, count, sf, 0)); // src + count * elem_size
1019     __ jump_cc(Assembler::belowEqual, nooverlap);
1020     __ cmpl(dst, end);
1021     __ jump_cc(Assembler::aboveEqual, nooverlap);
1022 
1023     // copy from high to low
1024     __ cmpl(count, 2<<shift); // Short arrays (< 8 bytes) copy by element
1025     __ jcc(Assembler::below, L_copy_4_bytes); // use unsigned cmp
1026     if (t == T_BYTE || t == T_SHORT) {
1027       // Align the end of destination array at 4 bytes address boundary
1028       __ leal(end, Address(dst, count, sf, 0));
1029       if (t == T_BYTE) {
1030         // One byte misalignment happens only for byte arrays
1031         __ testl(end, 1);
1032         __ jccb(Assembler::zero, L_skip_align1);
1033         __ decrement(count);
1034         __ movb(rdx, Address(from, count, sf, 0));
1035         __ movb(Address(to, count, sf, 0), rdx);
1036       __ BIND(L_skip_align1);
1037       }
1038       // Two bytes misalignment happens only for byte and short (char) arrays
1039       __ testl(end, 2);
1040       __ jccb(Assembler::zero, L_skip_align2);
1041       __ subl(count, 1<<(shift-1));
1042       __ movw(rdx, Address(from, count, sf, 0));
1043       __ movw(Address(to, count, sf, 0), rdx);
1044     __ BIND(L_skip_align2);
1045       __ cmpl(count, 2<<shift); // Short arrays (< 8 bytes) copy by element
1046       __ jcc(Assembler::below, L_copy_4_bytes);
1047     }
1048 
1049     if (!VM_Version::supports_mmx()) {
1050       __ std();
1051       __ movl(rax, count); // Save 'count'
1052       __ movl(rdx, to);    // Save 'to'
1053       __ leal(rsi, Address(from, count, sf, -4));
1054       __ leal(rdi, Address(to  , count, sf, -4));
1055       __ shrl(count, shift); // bytes count
1056       __ rep_movl();
1057       __ cld();
1058       __ movl(count, rax); // restore 'count'
1059       __ andl(count, (1<<shift)-1);      // mask the number of rest elements
1060       __ movl(from, Address(rsp, 12+4)); // reread 'from'
1061       __ movl(to, rdx);   // restore 'to'
1062       __ jmpb(L_copy_2_bytes); // all dword were copied
1063    } else {
1064       // Align to 8 bytes the end of array. It is aligned to 4 bytes already.
1065       __ testl(end, 4);
1066       __ jccb(Assembler::zero, L_copy_8_bytes);
1067       __ subl(count, 1<<shift);
1068       __ movl(rdx, Address(from, count, sf, 0));
1069       __ movl(Address(to, count, sf, 0), rdx);
1070       __ jmpb(L_copy_8_bytes);
1071 
1072       __ align(16);
1073       // Move 8 bytes
1074     __ BIND(L_copy_8_bytes_loop);
1075       __ movq(mmx0, Address(from, count, sf, 0));
1076       __ movq(Address(to, count, sf, 0), mmx0);
1077     __ BIND(L_copy_8_bytes);
1078       __ subl(count, 2<<shift);
1079       __ jcc(Assembler::greaterEqual, L_copy_8_bytes_loop);
1080       __ addl(count, 2<<shift);
1081       __ emms();
1082     }
1083   __ BIND(L_copy_4_bytes);
1084     // copy prefix qword
1085     __ testl(count, 1<<shift);
1086     __ jccb(Assembler::zero, L_copy_2_bytes);
1087     __ movl(rdx, Address(from, count, sf, -4));
1088     __ movl(Address(to, count, sf, -4), rdx);
1089 
1090     if (t == T_BYTE || t == T_SHORT) {
1091         __ subl(count, (1<<shift));
1092       __ BIND(L_copy_2_bytes);
1093         // copy prefix dword
1094         __ testl(count, 1<<(shift-1));
1095         __ jccb(Assembler::zero, L_copy_byte);
1096         __ movw(rdx, Address(from, count, sf, -2));
1097         __ movw(Address(to, count, sf, -2), rdx);
1098         if (t == T_BYTE) {
1099           __ subl(count, 1<<(shift-1));
1100         __ BIND(L_copy_byte);
1101           // copy prefix byte
1102           __ testl(count, 1);
1103           __ jccb(Assembler::zero, L_exit);
1104           __ movb(rdx, Address(from, 0));
1105           __ movb(Address(to, 0), rdx);
1106         __ BIND(L_exit);
1107         } else {
1108         __ BIND(L_copy_byte);
1109         }
1110     } else {
1111     __ BIND(L_copy_2_bytes);
1112     }
1113     if (t == T_OBJECT) {
1114       __ movl(count, Address(rsp, 12+12)); // reread count
1115       gen_write_ref_array_post_barrier(to, count);
1116     __ BIND(L_0_count);
1117     }
1118     inc_copy_counter_np(t);
1119     __ popl(rdi);
1120     __ popl(rsi);
1121     __ leave(); // required for proper stackwalking of RuntimeStub frame
1122     __ xorl(rax, rax); // return 0
1123     __ ret(0);
1124     return start;
1125   }
1126 
1127 
1128   address generate_disjoint_long_copy(address* entry, const char *name) {
1129     __ align(CodeEntryAlignment);
1130     StubCodeMark mark(this, "StubRoutines", name);
1131     address start = __ pc();
1132 
1133     Label L_copy_8_bytes, L_copy_8_bytes_loop;
1134     const Register from       = rax;  // source array address
1135     const Register to         = rdx;  // destination array address
1136     const Register count      = rcx;  // elements count
1137     const Register to_from    = rdx;  // (to - from)
1138 
1139     __ enter(); // required for proper stackwalking of RuntimeStub frame
1140     __ movl(from , Address(rsp, 8+0));       // from
1141     __ movl(to   , Address(rsp, 8+4));       // to
1142     __ movl(count, Address(rsp, 8+8));       // count
1143 
1144     *entry = __ pc(); // Entry point from conjoint arraycopy stub.
1145     BLOCK_COMMENT("Entry:");
1146 
1147     __ subl(to, from); // to --> to_from
1148     if (VM_Version::supports_mmx()) {
1149       mmx_copy_forward(from, to_from, count);
1150     } else {
1151       __ jmpb(L_copy_8_bytes);
1152       __ align(16);
1153     __ BIND(L_copy_8_bytes_loop);
1154       __ fild_d(Address(from, 0));
1155       __ fistp_d(Address(from, to_from, Address::times_1));
1156       __ addl(from, 8);
1157     __ BIND(L_copy_8_bytes);
1158       __ decrement(count);
1159       __ jcc(Assembler::greaterEqual, L_copy_8_bytes_loop);
1160     }
1161     inc_copy_counter_np(T_LONG);
1162     __ leave(); // required for proper stackwalking of RuntimeStub frame
1163     __ xorl(rax, rax); // return 0
1164     __ ret(0);
1165     return start;
1166   }
1167 
1168   address generate_conjoint_long_copy(address nooverlap_target,
1169                                       address* entry, const char *name) {
1170     __ align(CodeEntryAlignment);
1171     StubCodeMark mark(this, "StubRoutines", name);
1172     address start = __ pc();
1173 
1174     Label L_copy_8_bytes, L_copy_8_bytes_loop;
1175     const Register from       = rax;  // source array address
1176     const Register to         = rdx;  // destination array address
1177     const Register count      = rcx;  // elements count
1178     const Register end_from   = rax;  // source array end address
1179 
1180     __ enter(); // required for proper stackwalking of RuntimeStub frame
1181     __ movl(from , Address(rsp, 8+0));       // from
1182     __ movl(to   , Address(rsp, 8+4));       // to
1183     __ movl(count, Address(rsp, 8+8));       // count
1184 
1185     *entry = __ pc(); // Entry point from generic arraycopy stub.
1186     BLOCK_COMMENT("Entry:");
1187 
1188     // arrays overlap test
1189     __ cmpl(to, from);
1190     RuntimeAddress nooverlap(nooverlap_target);
1191     __ jump_cc(Assembler::belowEqual, nooverlap);
1192     __ leal(end_from, Address(from, count, Address::times_8, 0));
1193     __ cmpl(to, end_from);
1194     __ movl(from, Address(rsp, 8));  // from
1195     __ jump_cc(Assembler::aboveEqual, nooverlap);
1196 
1197     __ jmpb(L_copy_8_bytes);
1198 
1199     __ align(16);
1200   __ BIND(L_copy_8_bytes_loop);
1201     if (VM_Version::supports_mmx()) {
1202       __ movq(mmx0, Address(from, count, Address::times_8));
1203       __ movq(Address(to, count, Address::times_8), mmx0);
1204     } else {
1205       __ fild_d(Address(from, count, Address::times_8));
1206       __ fistp_d(Address(to, count, Address::times_8));
1207     }
1208   __ BIND(L_copy_8_bytes);
1209     __ decrement(count);
1210     __ jcc(Assembler::greaterEqual, L_copy_8_bytes_loop);
1211 
1212     if (VM_Version::supports_mmx()) {
1213       __ emms();
1214     }
1215     inc_copy_counter_np(T_LONG);
1216     __ leave(); // required for proper stackwalking of RuntimeStub frame
1217     __ xorl(rax, rax); // return 0
1218     __ ret(0);
1219     return start;
1220   }
1221 
1222 
1223   // Helper for generating a dynamic type check.
1224   // The sub_klass must be one of {rbx, rdx, rsi}.
1225   // The temp is killed.
1226   void generate_type_check(Register sub_klass,
1227                            Address& super_check_offset_addr,
1228                            Address& super_klass_addr,
1229                            Register temp,
1230                            Label* L_success_ptr, Label* L_failure_ptr) {
1231     BLOCK_COMMENT("type_check:");
1232 
1233     Label L_fallthrough;
1234     bool fall_through_on_success = (L_success_ptr == NULL);
1235     if (fall_through_on_success) {
1236       L_success_ptr = &L_fallthrough;
1237     } else {
1238       L_failure_ptr = &L_fallthrough;
1239     }
1240     Label& L_success = *L_success_ptr;
1241     Label& L_failure = *L_failure_ptr;
1242 
1243     assert_different_registers(sub_klass, temp);
1244 
1245     // a couple of useful fields in sub_klass:
1246     int ss_offset = (klassOopDesc::header_size() * HeapWordSize +
1247                      Klass::secondary_supers_offset_in_bytes());
1248     int sc_offset = (klassOopDesc::header_size() * HeapWordSize +
1249                      Klass::secondary_super_cache_offset_in_bytes());
1250     Address secondary_supers_addr(sub_klass, ss_offset);
1251     Address super_cache_addr(     sub_klass, sc_offset);
1252 
1253     // if the pointers are equal, we are done (e.g., String[] elements)
1254     __ cmpl(sub_klass, super_klass_addr);
1255     __ jcc(Assembler::equal, L_success);
1256 
1257     // check the supertype display:
1258     __ movl(temp, super_check_offset_addr);
1259     Address super_check_addr(sub_klass, temp, Address::times_1, 0);
1260     __ movl(temp, super_check_addr); // load displayed supertype
1261     __ cmpl(temp, super_klass_addr); // test the super type
1262     __ jcc(Assembler::equal, L_success);
1263 
1264     // if it was a primary super, we can just fail immediately
1265     __ cmpl(super_check_offset_addr, sc_offset);
1266     __ jcc(Assembler::notEqual, L_failure);
1267 
1268     // Now do a linear scan of the secondary super-klass chain.
1269     // This code is rarely used, so simplicity is a virtue here.
1270     inc_counter_np(SharedRuntime::_partial_subtype_ctr);
1271     {
1272       // The repne_scan instruction uses fixed registers, which we must spill.
1273       // (We need a couple more temps in any case.)
1274       __ pushl(rax);
1275       __ pushl(rcx);
1276       __ pushl(rdi);
1277       assert_different_registers(sub_klass, rax, rcx, rdi);
1278 
1279       __ movl(rdi, secondary_supers_addr);
1280       // Load the array length.
1281       __ movl(rcx, Address(rdi, arrayOopDesc::length_offset_in_bytes()));
1282       // Skip to start of data.
1283       __ addl(rdi, arrayOopDesc::base_offset_in_bytes(T_OBJECT));
1284       // Scan rcx words at [edi] for occurance of rax,
1285       // Set NZ/Z based on last compare
1286       __ movl(rax, super_klass_addr);
1287       __ repne_scan();
1288 
1289       // Unspill the temp. registers:
1290       __ popl(rdi);
1291       __ popl(rcx);
1292       __ popl(rax);
1293     }
1294     __ jcc(Assembler::notEqual, L_failure);
1295 
1296     // Success.  Cache the super we found and proceed in triumph.
1297     __ movl(temp, super_klass_addr); // note: rax, is dead
1298     __ movl(super_cache_addr, temp);
1299 
1300     if (!fall_through_on_success)
1301       __ jmp(L_success);
1302 
1303     // Fall through on failure!
1304     __ bind(L_fallthrough);
1305   }
1306 
1307   //
1308   //  Generate checkcasting array copy stub
1309   //
1310   //  Input:
1311   //    4(rsp)   - source array address
1312   //    8(rsp)   - destination array address
1313   //   12(rsp)   - element count, can be zero
1314   //   16(rsp)   - size_t ckoff (super_check_offset)
1315   //   20(rsp)   - oop ckval (super_klass)
1316   //
1317   //  Output:
1318   //    rax, ==  0  -  success
1319   //    rax, == -1^K - failure, where K is partial transfer count
1320   //
1321   address generate_checkcast_copy(const char *name, address* entry) {
1322     __ align(CodeEntryAlignment);
1323     StubCodeMark mark(this, "StubRoutines", name);
1324     address start = __ pc();
1325 
1326     Label L_load_element, L_store_element, L_do_card_marks, L_done;
1327 
1328     // register use:
1329     //  rax, rdx, rcx -- loop control (end_from, end_to, count)
1330     //  rdi, rsi      -- element access (oop, klass)
1331     //  rbx,           -- temp
1332     const Register from       = rax;    // source array address
1333     const Register to         = rdx;    // destination array address
1334     const Register length     = rcx;    // elements count
1335     const Register elem       = rdi;    // each oop copied
1336     const Register elem_klass = rsi;    // each elem._klass (sub_klass)
1337     const Register temp       = rbx;    // lone remaining temp
1338 
1339     __ enter(); // required for proper stackwalking of RuntimeStub frame
1340 
1341     __ pushl(rsi);
1342     __ pushl(rdi);
1343     __ pushl(rbx);
1344 
1345     Address   from_arg(rsp, 16+ 4);     // from
1346     Address     to_arg(rsp, 16+ 8);     // to
1347     Address length_arg(rsp, 16+12);     // elements count
1348     Address  ckoff_arg(rsp, 16+16);     // super_check_offset
1349     Address  ckval_arg(rsp, 16+20);     // super_klass
1350 
1351     // Load up:
1352     __ movl(from,     from_arg);
1353     __ movl(to,         to_arg);
1354     __ movl(length, length_arg);
1355 
1356     *entry = __ pc(); // Entry point from generic arraycopy stub.
1357     BLOCK_COMMENT("Entry:");
1358 
1359     //---------------------------------------------------------------
1360     // Assembler stub will be used for this call to arraycopy
1361     // if the two arrays are subtypes of Object[] but the
1362     // destination array type is not equal to or a supertype
1363     // of the source type.  Each element must be separately
1364     // checked.
1365 
1366     // Loop-invariant addresses.  They are exclusive end pointers.
1367     Address end_from_addr(from, length, Address::times_4, 0);
1368     Address   end_to_addr(to,   length, Address::times_4, 0);
1369 
1370     Register end_from = from;           // re-use
1371     Register end_to   = to;             // re-use
1372     Register count    = length;         // re-use
1373 
1374     // Loop-variant addresses.  They assume post-incremented count < 0.
1375     Address from_element_addr(end_from, count, Address::times_4, 0);
1376     Address   to_element_addr(end_to,   count, Address::times_4, 0);
1377     Address elem_klass_addr(elem, oopDesc::klass_offset_in_bytes());
1378 
1379     // Copy from low to high addresses, indexed from the end of each array.
1380     __ leal(end_from, end_from_addr);
1381     __ leal(end_to,   end_to_addr);
1382     gen_write_ref_array_pre_barrier(to, count);
1383     assert(length == count, "");        // else fix next line:
1384     __ negl(count);                     // negate and test the length
1385     __ jccb(Assembler::notZero, L_load_element);
1386 
1387     // Empty array:  Nothing to do.
1388     __ xorl(rax, rax);                  // return 0 on (trivial) success
1389     __ jmp(L_done);
1390 
1391     // ======== begin loop ========
1392     // (Loop is rotated; its entry is L_load_element.)
1393     // Loop control:
1394     //   for (count = -count; count != 0; count++)
1395     // Base pointers src, dst are biased by 8*count,to last element.
1396     __ align(16);
1397 
1398     __ BIND(L_store_element);
1399     __ movl(to_element_addr, elem);     // store the oop
1400     __ increment(count);                // increment the count toward zero
1401     __ jccb(Assembler::zero, L_do_card_marks);
1402 
1403     // ======== loop entry is here ========
1404     __ BIND(L_load_element);
1405     __ movl(elem, from_element_addr);   // load the oop
1406     __ testl(elem, elem);
1407     __ jccb(Assembler::zero, L_store_element);
1408 
1409     // (Could do a trick here:  Remember last successful non-null
1410     // element stored and make a quick oop equality check on it.)
1411 
1412     __ movl(elem_klass, elem_klass_addr); // query the object klass
1413     generate_type_check(elem_klass, ckoff_arg, ckval_arg, temp,
1414                         &L_store_element, NULL);
1415       // (On fall-through, we have failed the element type check.)
1416     // ======== end loop ========
1417 
1418     // It was a real error; we must depend on the caller to finish the job.
1419     // Register "count" = -1 * number of *remaining* oops, length_arg = *total* oops.
1420     // Emit GC store barriers for the oops we have copied (length_arg + count),
1421     // and report their number to the caller.
1422     __ addl(count, length_arg);         // transfers = (length - remaining)
1423     __ movl(rax, count);                // save the value
1424     __ notl(rax);                       // report (-1^K) to caller
1425     __ movl(to, to_arg);                // reload
1426     assert_different_registers(to, count, rax);
1427     gen_write_ref_array_post_barrier(to, count);
1428     __ jmpb(L_done);
1429 
1430     // Come here on success only.
1431     __ BIND(L_do_card_marks);
1432     __ movl(count, length_arg);
1433     __ movl(to, to_arg);                // reload
1434     gen_write_ref_array_post_barrier(to, count);
1435     __ xorl(rax, rax);                  // return 0 on success
1436 
1437     // Common exit point (success or failure).
1438     __ BIND(L_done);
1439     __ popl(rbx);
1440     __ popl(rdi);
1441     __ popl(rsi);
1442     inc_counter_np(SharedRuntime::_checkcast_array_copy_ctr);
1443     __ leave(); // required for proper stackwalking of RuntimeStub frame
1444     __ ret(0);
1445 
1446     return start;
1447   }
1448 
1449   //
1450   //  Generate 'unsafe' array copy stub
1451   //  Though just as safe as the other stubs, it takes an unscaled
1452   //  size_t argument instead of an element count.
1453   //
1454   //  Input:
1455   //    4(rsp)   - source array address
1456   //    8(rsp)   - destination array address
1457   //   12(rsp)   - byte count, can be zero
1458   //
1459   //  Output:
1460   //    rax, ==  0  -  success
1461   //    rax, == -1  -  need to call System.arraycopy
1462   //
1463   // Examines the alignment of the operands and dispatches
1464   // to a long, int, short, or byte copy loop.
1465   //
1466   address generate_unsafe_copy(const char *name,
1467                                address byte_copy_entry,
1468                                address short_copy_entry,
1469                                address int_copy_entry,
1470                                address long_copy_entry) {
1471 
1472     Label L_long_aligned, L_int_aligned, L_short_aligned;
1473 
1474     __ align(CodeEntryAlignment);
1475     StubCodeMark mark(this, "StubRoutines", name);
1476     address start = __ pc();
1477 
1478     const Register from       = rax;  // source array address
1479     const Register to         = rdx;  // destination array address
1480     const Register count      = rcx;  // elements count
1481 
1482     __ enter(); // required for proper stackwalking of RuntimeStub frame
1483     __ pushl(rsi);
1484     __ pushl(rdi);
1485     Address  from_arg(rsp, 12+ 4);      // from
1486     Address    to_arg(rsp, 12+ 8);      // to
1487     Address count_arg(rsp, 12+12);      // byte count
1488 
1489     // Load up:
1490     __ movl(from ,  from_arg);
1491     __ movl(to   ,    to_arg);
1492     __ movl(count, count_arg);
1493 
1494     // bump this on entry, not on exit:
1495     inc_counter_np(SharedRuntime::_unsafe_array_copy_ctr);
1496 
1497     const Register bits = rsi;
1498     __ movl(bits, from);
1499     __ orl(bits, to);
1500     __ orl(bits, count);
1501 
1502     __ testl(bits, BytesPerLong-1);
1503     __ jccb(Assembler::zero, L_long_aligned);
1504 
1505     __ testl(bits, BytesPerInt-1);
1506     __ jccb(Assembler::zero, L_int_aligned);
1507 
1508     __ testl(bits, BytesPerShort-1);
1509     __ jump_cc(Assembler::notZero, RuntimeAddress(byte_copy_entry));
1510 
1511     __ BIND(L_short_aligned);
1512     __ shrl(count, LogBytesPerShort); // size => short_count
1513     __ movl(count_arg, count);          // update 'count'
1514     __ jump(RuntimeAddress(short_copy_entry));
1515 
1516     __ BIND(L_int_aligned);
1517     __ shrl(count, LogBytesPerInt); // size => int_count
1518     __ movl(count_arg, count);          // update 'count'
1519     __ jump(RuntimeAddress(int_copy_entry));
1520 
1521     __ BIND(L_long_aligned);
1522     __ shrl(count, LogBytesPerLong); // size => qword_count
1523     __ movl(count_arg, count);          // update 'count'
1524     __ popl(rdi); // Do pops here since jlong_arraycopy stub does not do it.
1525     __ popl(rsi);
1526     __ jump(RuntimeAddress(long_copy_entry));
1527 
1528     return start;
1529   }
1530 
1531 
1532   // Perform range checks on the proposed arraycopy.
1533   // Smashes src_pos and dst_pos.  (Uses them up for temps.)
1534   void arraycopy_range_checks(Register src,
1535                               Register src_pos,
1536                               Register dst,
1537                               Register dst_pos,
1538                               Address& length,
1539                               Label& L_failed) {
1540     BLOCK_COMMENT("arraycopy_range_checks:");
1541     const Register src_end = src_pos;   // source array end position
1542     const Register dst_end = dst_pos;   // destination array end position
1543     __ addl(src_end, length); // src_pos + length
1544     __ addl(dst_end, length); // dst_pos + length
1545 
1546     //  if (src_pos + length > arrayOop(src)->length() ) FAIL;
1547     __ cmpl(src_end, Address(src, arrayOopDesc::length_offset_in_bytes()));
1548     __ jcc(Assembler::above, L_failed);
1549 
1550     //  if (dst_pos + length > arrayOop(dst)->length() ) FAIL;
1551     __ cmpl(dst_end, Address(dst, arrayOopDesc::length_offset_in_bytes()));
1552     __ jcc(Assembler::above, L_failed);
1553 
1554     BLOCK_COMMENT("arraycopy_range_checks done");
1555   }
1556 
1557 
1558   //
1559   //  Generate generic array copy stubs
1560   //
1561   //  Input:
1562   //     4(rsp)    -  src oop
1563   //     8(rsp)    -  src_pos
1564   //    12(rsp)    -  dst oop
1565   //    16(rsp)    -  dst_pos
1566   //    20(rsp)    -  element count
1567   //
1568   //  Output:
1569   //    rax, ==  0  -  success
1570   //    rax, == -1^K - failure, where K is partial transfer count
1571   //
1572   address generate_generic_copy(const char *name,
1573                                 address entry_jbyte_arraycopy,
1574                                 address entry_jshort_arraycopy,
1575                                 address entry_jint_arraycopy,
1576                                 address entry_oop_arraycopy,
1577                                 address entry_jlong_arraycopy,
1578                                 address entry_checkcast_arraycopy) {
1579     Label L_failed, L_failed_0, L_objArray;
1580 
1581     { int modulus = CodeEntryAlignment;
1582       int target  = modulus - 5; // 5 = sizeof jmp(L_failed)
1583       int advance = target - (__ offset() % modulus);
1584       if (advance < 0)  advance += modulus;
1585       if (advance > 0)  __ nop(advance);
1586     }
1587     StubCodeMark mark(this, "StubRoutines", name);
1588 
1589     // Short-hop target to L_failed.  Makes for denser prologue code.
1590     __ BIND(L_failed_0);
1591     __ jmp(L_failed);
1592     assert(__ offset() % CodeEntryAlignment == 0, "no further alignment needed");
1593 
1594     __ align(CodeEntryAlignment);
1595     address start = __ pc();
1596 
1597     __ enter(); // required for proper stackwalking of RuntimeStub frame
1598     __ pushl(rsi);
1599     __ pushl(rdi);
1600 
1601     // bump this on entry, not on exit:
1602     inc_counter_np(SharedRuntime::_generic_array_copy_ctr);
1603 
1604     // Input values
1605     Address SRC     (rsp, 12+ 4);
1606     Address SRC_POS (rsp, 12+ 8);
1607     Address DST     (rsp, 12+12);
1608     Address DST_POS (rsp, 12+16);
1609     Address LENGTH  (rsp, 12+20);
1610 
1611     //-----------------------------------------------------------------------
1612     // Assembler stub will be used for this call to arraycopy
1613     // if the following conditions are met:
1614     //
1615     // (1) src and dst must not be null.
1616     // (2) src_pos must not be negative.
1617     // (3) dst_pos must not be negative.
1618     // (4) length  must not be negative.
1619     // (5) src klass and dst klass should be the same and not NULL.
1620     // (6) src and dst should be arrays.
1621     // (7) src_pos + length must not exceed length of src.
1622     // (8) dst_pos + length must not exceed length of dst.
1623     //
1624 
1625     const Register src     = rax;       // source array oop
1626     const Register src_pos = rsi;
1627     const Register dst     = rdx;       // destination array oop
1628     const Register dst_pos = rdi;
1629     const Register length  = rcx;       // transfer count
1630 
1631     //  if (src == NULL) return -1;
1632     __ movl(src, SRC);      // src oop
1633     __ testl(src, src);
1634     __ jccb(Assembler::zero, L_failed_0);
1635 
1636     //  if (src_pos < 0) return -1;
1637     __ movl(src_pos, SRC_POS);  // src_pos
1638     __ testl(src_pos, src_pos);
1639     __ jccb(Assembler::negative, L_failed_0);
1640 
1641     //  if (dst == NULL) return -1;
1642     __ movl(dst, DST);      // dst oop
1643     __ testl(dst, dst);
1644     __ jccb(Assembler::zero, L_failed_0);
1645 
1646     //  if (dst_pos < 0) return -1;
1647     __ movl(dst_pos, DST_POS);  // dst_pos
1648     __ testl(dst_pos, dst_pos);
1649     __ jccb(Assembler::negative, L_failed_0);
1650 
1651     //  if (length < 0) return -1;
1652     __ movl(length, LENGTH);   // length
1653     __ testl(length, length);
1654     __ jccb(Assembler::negative, L_failed_0);
1655 
1656     //  if (src->klass() == NULL) return -1;
1657     Address src_klass_addr(src, oopDesc::klass_offset_in_bytes());
1658     Address dst_klass_addr(dst, oopDesc::klass_offset_in_bytes());
1659     const Register rcx_src_klass = rcx;    // array klass
1660     __ movl(rcx_src_klass, Address(src, oopDesc::klass_offset_in_bytes()));
1661 
1662 #ifdef ASSERT
1663     //  assert(src->klass() != NULL);
1664     BLOCK_COMMENT("assert klasses not null");
1665     { Label L1, L2;
1666       __ testl(rcx_src_klass, rcx_src_klass);
1667       __ jccb(Assembler::notZero, L2);   // it is broken if klass is NULL
1668       __ bind(L1);
1669       __ stop("broken null klass");
1670       __ bind(L2);
1671       __ cmpl(dst_klass_addr, 0);
1672       __ jccb(Assembler::equal, L1);      // this would be broken also
1673       BLOCK_COMMENT("assert done");
1674     }
1675 #endif //ASSERT
1676 
1677     // Load layout helper (32-bits)
1678     //
1679     //  |array_tag|     | header_size | element_type |     |log2_element_size|
1680     // 32        30    24            16              8     2                 0
1681     //
1682     //   array_tag: typeArray = 0x3, objArray = 0x2, non-array = 0x0
1683     //
1684 
1685     int lh_offset = klassOopDesc::header_size() * HeapWordSize +
1686                     Klass::layout_helper_offset_in_bytes();
1687     Address src_klass_lh_addr(rcx_src_klass, lh_offset);
1688 
1689     // Handle objArrays completely differently...
1690     jint objArray_lh = Klass::array_layout_helper(T_OBJECT);
1691     __ cmpl(src_klass_lh_addr, objArray_lh);
1692     __ jcc(Assembler::equal, L_objArray);
1693 
1694     //  if (src->klass() != dst->klass()) return -1;
1695     __ cmpl(rcx_src_klass, dst_klass_addr);
1696     __ jccb(Assembler::notEqual, L_failed_0);
1697 
1698     const Register rcx_lh = rcx;  // layout helper
1699     assert(rcx_lh == rcx_src_klass, "known alias");
1700     __ movl(rcx_lh, src_klass_lh_addr);
1701 
1702     //  if (!src->is_Array()) return -1;
1703     __ cmpl(rcx_lh, Klass::_lh_neutral_value);
1704     __ jcc(Assembler::greaterEqual, L_failed_0); // signed cmp
1705 
1706     // At this point, it is known to be a typeArray (array_tag 0x3).
1707 #ifdef ASSERT
1708     { Label L;
1709       __ cmpl(rcx_lh, (Klass::_lh_array_tag_type_value << Klass::_lh_array_tag_shift));
1710       __ jcc(Assembler::greaterEqual, L); // signed cmp
1711       __ stop("must be a primitive array");
1712       __ bind(L);
1713     }
1714 #endif
1715 
1716     assert_different_registers(src, src_pos, dst, dst_pos, rcx_lh);
1717     arraycopy_range_checks(src, src_pos, dst, dst_pos, LENGTH, L_failed);
1718 
1719     // typeArrayKlass
1720     //
1721     // src_addr = (src + array_header_in_bytes()) + (src_pos << log2elemsize);
1722     // dst_addr = (dst + array_header_in_bytes()) + (dst_pos << log2elemsize);
1723     //
1724     const Register rsi_offset = rsi; // array offset
1725     const Register src_array  = src; // src array offset
1726     const Register dst_array  = dst; // dst array offset
1727     const Register rdi_elsize = rdi; // log2 element size
1728 
1729     __ movl(rsi_offset, rcx_lh);
1730     __ shrl(rsi_offset, Klass::_lh_header_size_shift);
1731     __ andl(rsi_offset, Klass::_lh_header_size_mask);   // array_offset
1732     __ addl(src_array, rsi_offset);  // src array offset
1733     __ addl(dst_array, rsi_offset);  // dst array offset
1734     __ andl(rcx_lh, Klass::_lh_log2_element_size_mask); // log2 elsize
1735 
1736     // next registers should be set before the jump to corresponding stub
1737     const Register from       = src; // source array address
1738     const Register to         = dst; // destination array address
1739     const Register count      = rcx; // elements count
1740     // some of them should be duplicated on stack
1741 #define FROM   Address(rsp, 12+ 4)
1742 #define TO     Address(rsp, 12+ 8)   // Not used now
1743 #define COUNT  Address(rsp, 12+12)   // Only for oop arraycopy
1744 
1745     BLOCK_COMMENT("scale indexes to element size");
1746     __ movl(rsi, SRC_POS);  // src_pos
1747     __ shll(rsi); // src_pos << rcx (log2 elsize)
1748     assert(src_array == from, "");
1749     __ addl(from, rsi);     // from = src_array + SRC_POS << log2 elsize
1750     __ movl(rdi, DST_POS);  // dst_pos
1751     __ shll(rdi); // dst_pos << rcx (log2 elsize)
1752     assert(dst_array == to, "");
1753     __ addl(to,  rdi);      // to   = dst_array + DST_POS << log2 elsize
1754     __ movl(FROM, from);    // src_addr
1755     __ movl(rdi_elsize, rcx_lh); // log2 elsize
1756     __ movl(count, LENGTH); // elements count
1757 
1758     BLOCK_COMMENT("choose copy loop based on element size");
1759     __ cmpl(rdi_elsize, 0);
1760 
1761     __ jump_cc(Assembler::equal, RuntimeAddress(entry_jbyte_arraycopy));
1762     __ cmpl(rdi_elsize, LogBytesPerShort);
1763     __ jump_cc(Assembler::equal, RuntimeAddress(entry_jshort_arraycopy));
1764     __ cmpl(rdi_elsize, LogBytesPerInt);
1765     __ jump_cc(Assembler::equal, RuntimeAddress(entry_jint_arraycopy));
1766 #ifdef ASSERT
1767     __ cmpl(rdi_elsize, LogBytesPerLong);
1768     __ jccb(Assembler::notEqual, L_failed);
1769 #endif
1770     __ popl(rdi); // Do pops here since jlong_arraycopy stub does not do it.
1771     __ popl(rsi);
1772     __ jump(RuntimeAddress(entry_jlong_arraycopy));
1773 
1774   __ BIND(L_failed);
1775     __ xorl(rax, rax);
1776     __ notl(rax); // return -1
1777     __ popl(rdi);
1778     __ popl(rsi);
1779     __ leave(); // required for proper stackwalking of RuntimeStub frame
1780     __ ret(0);
1781 
1782     // objArrayKlass
1783   __ BIND(L_objArray);
1784     // live at this point:  rcx_src_klass, src[_pos], dst[_pos]
1785 
1786     Label L_plain_copy, L_checkcast_copy;
1787     //  test array classes for subtyping
1788     __ cmpl(rcx_src_klass, dst_klass_addr); // usual case is exact equality
1789     __ jccb(Assembler::notEqual, L_checkcast_copy);
1790 
1791     // Identically typed arrays can be copied without element-wise checks.
1792     assert_different_registers(src, src_pos, dst, dst_pos, rcx_src_klass);
1793     arraycopy_range_checks(src, src_pos, dst, dst_pos, LENGTH, L_failed);
1794 
1795   __ BIND(L_plain_copy);
1796     __ movl(count, LENGTH); // elements count
1797     __ movl(src_pos, SRC_POS);  // reload src_pos
1798     __ leal(from, Address(src, src_pos, Address::times_4,
1799                   arrayOopDesc::base_offset_in_bytes(T_OBJECT))); // src_addr
1800     __ movl(dst_pos, DST_POS);  // reload dst_pos
1801     __ leal(to,   Address(dst, dst_pos, Address::times_4,
1802                   arrayOopDesc::base_offset_in_bytes(T_OBJECT))); // dst_addr
1803     __ movl(FROM,  from);   // src_addr
1804     __ movl(TO,    to);     // dst_addr
1805     __ movl(COUNT, count);  // count
1806     __ jump(RuntimeAddress(entry_oop_arraycopy));
1807 
1808   __ BIND(L_checkcast_copy);
1809     // live at this point:  rcx_src_klass, dst[_pos], src[_pos]
1810     {
1811       // Handy offsets:
1812       int  ek_offset = (klassOopDesc::header_size() * HeapWordSize +
1813                         objArrayKlass::element_klass_offset_in_bytes());
1814       int sco_offset = (klassOopDesc::header_size() * HeapWordSize +
1815                         Klass::super_check_offset_offset_in_bytes());
1816 
1817       Register rsi_dst_klass = rsi;
1818       Register rdi_temp      = rdi;
1819       assert(rsi_dst_klass == src_pos, "expected alias w/ src_pos");
1820       assert(rdi_temp      == dst_pos, "expected alias w/ dst_pos");
1821       Address dst_klass_lh_addr(rsi_dst_klass, lh_offset);
1822 
1823       // Before looking at dst.length, make sure dst is also an objArray.
1824       __ movl(rsi_dst_klass, dst_klass_addr);
1825       __ cmpl(dst_klass_lh_addr, objArray_lh);
1826       __ jccb(Assembler::notEqual, L_failed);
1827 
1828       // It is safe to examine both src.length and dst.length.
1829       __ movl(src_pos, SRC_POS);        // reload rsi
1830       arraycopy_range_checks(src, src_pos, dst, dst_pos, LENGTH, L_failed);
1831       // (Now src_pos and dst_pos are killed, but not src and dst.)
1832 
1833       // We'll need this temp (don't forget to pop it after the type check).
1834       __ pushl(rbx);
1835       Register rbx_src_klass = rbx;
1836 
1837       __ movl(rbx_src_klass, rcx_src_klass); // spill away from rcx
1838       __ movl(rsi_dst_klass, dst_klass_addr);
1839       Address super_check_offset_addr(rsi_dst_klass, sco_offset);
1840       Label L_fail_array_check;
1841       generate_type_check(rbx_src_klass,
1842                           super_check_offset_addr, dst_klass_addr,
1843                           rdi_temp, NULL, &L_fail_array_check);
1844       // (On fall-through, we have passed the array type check.)
1845       __ popl(rbx);
1846       __ jmp(L_plain_copy);
1847 
1848       __ BIND(L_fail_array_check);
1849       // Reshuffle arguments so we can call checkcast_arraycopy:
1850 
1851       // match initial saves for checkcast_arraycopy
1852       // pushl(rsi);    // already done; see above
1853       // pushl(rdi);    // already done; see above
1854       // pushl(rbx);    // already done; see above
1855 
1856       // Marshal outgoing arguments now, freeing registers.
1857       Address   from_arg(rsp, 16+ 4);   // from
1858       Address     to_arg(rsp, 16+ 8);   // to
1859       Address length_arg(rsp, 16+12);   // elements count
1860       Address  ckoff_arg(rsp, 16+16);   // super_check_offset
1861       Address  ckval_arg(rsp, 16+20);   // super_klass
1862 
1863       Address SRC_POS_arg(rsp, 16+ 8);
1864       Address DST_POS_arg(rsp, 16+16);
1865       Address  LENGTH_arg(rsp, 16+20);
1866       // push rbx, changed the incoming offsets (why not just use rbp,??)
1867       // assert(SRC_POS_arg.disp() == SRC_POS.disp() + 4, "");
1868 
1869       __ movl(rbx, Address(rsi_dst_klass, ek_offset));
1870       __ movl(length, LENGTH_arg);    // reload elements count
1871       __ movl(src_pos, SRC_POS_arg);  // reload src_pos
1872       __ movl(dst_pos, DST_POS_arg);  // reload dst_pos
1873 
1874       __ movl(ckval_arg, rbx);          // destination element type
1875       __ movl(rbx, Address(rbx, sco_offset));
1876       __ movl(ckoff_arg, rbx);          // corresponding class check offset
1877 
1878       __ movl(length_arg, length);      // outgoing length argument
1879 
1880       __ leal(from, Address(src, src_pos, Address::times_4,
1881                             arrayOopDesc::base_offset_in_bytes(T_OBJECT)));
1882       __ movl(from_arg, from);
1883 
1884       __ leal(to, Address(dst, dst_pos, Address::times_4,
1885                           arrayOopDesc::base_offset_in_bytes(T_OBJECT)));
1886       __ movl(to_arg, to);
1887       __ jump(RuntimeAddress(entry_checkcast_arraycopy));
1888     }
1889 
1890     return start;
1891   }
1892 
1893   void generate_arraycopy_stubs() {
1894     address entry;
1895     address entry_jbyte_arraycopy;
1896     address entry_jshort_arraycopy;
1897     address entry_jint_arraycopy;
1898     address entry_oop_arraycopy;
1899     address entry_jlong_arraycopy;
1900     address entry_checkcast_arraycopy;
1901 
1902     StubRoutines::_arrayof_jbyte_disjoint_arraycopy =
1903         generate_disjoint_copy(T_BYTE,  true, Address::times_1, &entry,
1904                                "arrayof_jbyte_disjoint_arraycopy");
1905     StubRoutines::_arrayof_jbyte_arraycopy =
1906         generate_conjoint_copy(T_BYTE,  true, Address::times_1,  entry,
1907                                NULL, "arrayof_jbyte_arraycopy");
1908     StubRoutines::_jbyte_disjoint_arraycopy =
1909         generate_disjoint_copy(T_BYTE, false, Address::times_1, &entry,
1910                                "jbyte_disjoint_arraycopy");
1911     StubRoutines::_jbyte_arraycopy =
1912         generate_conjoint_copy(T_BYTE, false, Address::times_1,  entry,
1913                                &entry_jbyte_arraycopy, "jbyte_arraycopy");
1914 
1915     StubRoutines::_arrayof_jshort_disjoint_arraycopy =
1916         generate_disjoint_copy(T_SHORT,  true, Address::times_2, &entry,
1917                                "arrayof_jshort_disjoint_arraycopy");
1918     StubRoutines::_arrayof_jshort_arraycopy =
1919         generate_conjoint_copy(T_SHORT,  true, Address::times_2,  entry,
1920                                NULL, "arrayof_jshort_arraycopy");
1921     StubRoutines::_jshort_disjoint_arraycopy =
1922         generate_disjoint_copy(T_SHORT, false, Address::times_2, &entry,
1923                                "jshort_disjoint_arraycopy");
1924     StubRoutines::_jshort_arraycopy =
1925         generate_conjoint_copy(T_SHORT, false, Address::times_2,  entry,
1926                                &entry_jshort_arraycopy, "jshort_arraycopy");
1927 
1928     // Next arrays are always aligned on 4 bytes at least.
1929     StubRoutines::_jint_disjoint_arraycopy =
1930         generate_disjoint_copy(T_INT, true, Address::times_4, &entry,
1931                                "jint_disjoint_arraycopy");
1932     StubRoutines::_jint_arraycopy =
1933         generate_conjoint_copy(T_INT, true, Address::times_4,  entry,
1934                                &entry_jint_arraycopy, "jint_arraycopy");
1935 
1936     StubRoutines::_oop_disjoint_arraycopy =
1937         generate_disjoint_copy(T_OBJECT, true, Address::times_4, &entry,
1938                                "oop_disjoint_arraycopy");
1939     StubRoutines::_oop_arraycopy =
1940         generate_conjoint_copy(T_OBJECT, true, Address::times_4,  entry,
1941                                &entry_oop_arraycopy, "oop_arraycopy");
1942 
1943     StubRoutines::_jlong_disjoint_arraycopy =
1944         generate_disjoint_long_copy(&entry, "jlong_disjoint_arraycopy");
1945     StubRoutines::_jlong_arraycopy =
1946         generate_conjoint_long_copy(entry, &entry_jlong_arraycopy,
1947                                     "jlong_arraycopy");
1948 
1949     StubRoutines::_arrayof_jint_disjoint_arraycopy  =
1950         StubRoutines::_jint_disjoint_arraycopy;
1951     StubRoutines::_arrayof_oop_disjoint_arraycopy   =
1952         StubRoutines::_oop_disjoint_arraycopy;
1953     StubRoutines::_arrayof_jlong_disjoint_arraycopy =
1954         StubRoutines::_jlong_disjoint_arraycopy;
1955 
1956     StubRoutines::_arrayof_jint_arraycopy  = StubRoutines::_jint_arraycopy;
1957     StubRoutines::_arrayof_oop_arraycopy   = StubRoutines::_oop_arraycopy;
1958     StubRoutines::_arrayof_jlong_arraycopy = StubRoutines::_jlong_arraycopy;
1959 
1960     StubRoutines::_checkcast_arraycopy =
1961         generate_checkcast_copy("checkcast_arraycopy",
1962                                   &entry_checkcast_arraycopy);
1963 
1964     StubRoutines::_unsafe_arraycopy =
1965         generate_unsafe_copy("unsafe_arraycopy",
1966                                entry_jbyte_arraycopy,
1967                                entry_jshort_arraycopy,
1968                                entry_jint_arraycopy,
1969                                entry_jlong_arraycopy);
1970 
1971     StubRoutines::_generic_arraycopy =
1972         generate_generic_copy("generic_arraycopy",
1973                                entry_jbyte_arraycopy,
1974                                entry_jshort_arraycopy,
1975                                entry_jint_arraycopy,
1976                                entry_oop_arraycopy,
1977                                entry_jlong_arraycopy,
1978                                entry_checkcast_arraycopy);
1979   }
1980 
1981  public:
1982   // Information about frame layout at time of blocking runtime call.
1983   // Note that we only have to preserve callee-saved registers since
1984   // the compilers are responsible for supplying a continuation point
1985   // if they expect all registers to be preserved.
1986   enum layout {
1987     thread_off,    // last_java_sp
1988     rbp_off,       // callee saved register
1989     ret_pc,
1990     framesize
1991   };
1992 
1993  private:
1994 
1995 #undef  __
1996 #define __ masm->
1997 
1998   //------------------------------------------------------------------------------------------------------------------------
1999   // Continuation point for throwing of implicit exceptions that are not handled in
2000   // the current activation. Fabricates an exception oop and initiates normal
2001   // exception dispatching in this frame.
2002   //
2003   // Previously the compiler (c2) allowed for callee save registers on Java calls.
2004   // This is no longer true after adapter frames were removed but could possibly
2005   // be brought back in the future if the interpreter code was reworked and it
2006   // was deemed worthwhile. The comment below was left to describe what must
2007   // happen here if callee saves were resurrected. As it stands now this stub
2008   // could actually be a vanilla BufferBlob and have now oopMap at all.
2009   // Since it doesn't make much difference we've chosen to leave it the
2010   // way it was in the callee save days and keep the comment.
2011 
2012   // If we need to preserve callee-saved values we need a callee-saved oop map and
2013   // therefore have to make these stubs into RuntimeStubs rather than BufferBlobs.
2014   // If the compiler needs all registers to be preserved between the fault
2015   // point and the exception handler then it must assume responsibility for that in
2016   // AbstractCompiler::continuation_for_implicit_null_exception or
2017   // continuation_for_implicit_division_by_zero_exception. All other implicit
2018   // exceptions (e.g., NullPointerException or AbstractMethodError on entry) are
2019   // either at call sites or otherwise assume that stack unwinding will be initiated,
2020   // so caller saved registers were assumed volatile in the compiler.
2021   address generate_throw_exception(const char* name, address runtime_entry,
2022                                    bool restore_saved_exception_pc) {
2023 
2024     int insts_size = 256;
2025     int locs_size  = 32;
2026 
2027     CodeBuffer code(name, insts_size, locs_size);
2028     OopMapSet* oop_maps  = new OopMapSet();
2029     MacroAssembler* masm = new MacroAssembler(&code);
2030 
2031     address start = __ pc();
2032 
2033     // This is an inlined and slightly modified version of call_VM
2034     // which has the ability to fetch the return PC out of
2035     // thread-local storage and also sets up last_Java_sp slightly
2036     // differently than the real call_VM
2037     Register java_thread = rbx;
2038     __ get_thread(java_thread);
2039     if (restore_saved_exception_pc) {
2040       __ movl(rax, Address(java_thread, in_bytes(JavaThread::saved_exception_pc_offset())));
2041       __ pushl(rax);
2042     }
2043 
2044     __ enter(); // required for proper stackwalking of RuntimeStub frame
2045 
2046     // pc and rbp, already pushed
2047     __ subl(rsp, (framesize-2) * wordSize); // prolog
2048 
2049     // Frame is now completed as far as size and linkage.
2050 
2051     int frame_complete = __ pc() - start;
2052 
2053     // push java thread (becomes first argument of C function)
2054     __ movl(Address(rsp, thread_off * wordSize), java_thread);
2055 
2056     // Set up last_Java_sp and last_Java_fp
2057     __ set_last_Java_frame(java_thread, rsp, rbp, NULL);
2058 
2059     // Call runtime
2060     BLOCK_COMMENT("call runtime_entry");
2061     __ call(RuntimeAddress(runtime_entry));
2062     // Generate oop map
2063     OopMap* map =  new OopMap(framesize, 0);
2064     oop_maps->add_gc_map(__ pc() - start, map);
2065 
2066     // restore the thread (cannot use the pushed argument since arguments
2067     // may be overwritten by C code generated by an optimizing compiler);
2068     // however can use the register value directly if it is callee saved.
2069     __ get_thread(java_thread);
2070 
2071     __ reset_last_Java_frame(java_thread, true, false);
2072 
2073     __ leave(); // required for proper stackwalking of RuntimeStub frame
2074 
2075     // check for pending exceptions
2076 #ifdef ASSERT
2077     Label L;
2078     __ cmpl(Address(java_thread, Thread::pending_exception_offset()), NULL_WORD);
2079     __ jcc(Assembler::notEqual, L);
2080     __ should_not_reach_here();
2081     __ bind(L);
2082 #endif /* ASSERT */
2083     __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2084 
2085 
2086     RuntimeStub* stub = RuntimeStub::new_runtime_stub(name, &code, frame_complete, framesize, oop_maps, false);
2087     return stub->entry_point();
2088   }
2089 
2090 
2091   void create_control_words() {
2092     // Round to nearest, 53-bit mode, exceptions masked
2093     StubRoutines::_fpu_cntrl_wrd_std   = 0x027F;
2094     // Round to zero, 53-bit mode, exception mased
2095     StubRoutines::_fpu_cntrl_wrd_trunc = 0x0D7F;
2096     // Round to nearest, 24-bit mode, exceptions masked
2097     StubRoutines::_fpu_cntrl_wrd_24    = 0x007F;
2098     // Round to nearest, 64-bit mode, exceptions masked
2099     StubRoutines::_fpu_cntrl_wrd_64    = 0x037F;
2100     // Round to nearest, 64-bit mode, exceptions masked
2101     StubRoutines::_mxcsr_std           = 0x1F80;
2102     // Note: the following two constants are 80-bit values
2103     //       layout is critical for correct loading by FPU.
2104     // Bias for strict fp multiply/divide
2105     StubRoutines::_fpu_subnormal_bias1[0]= 0x00000000; // 2^(-15360) == 0x03ff 8000 0000 0000 0000
2106     StubRoutines::_fpu_subnormal_bias1[1]= 0x80000000;
2107     StubRoutines::_fpu_subnormal_bias1[2]= 0x03ff;
2108     // Un-Bias for strict fp multiply/divide
2109     StubRoutines::_fpu_subnormal_bias2[0]= 0x00000000; // 2^(+15360) == 0x7bff 8000 0000 0000 0000
2110     StubRoutines::_fpu_subnormal_bias2[1]= 0x80000000;
2111     StubRoutines::_fpu_subnormal_bias2[2]= 0x7bff;
2112   }
2113 
2114   //---------------------------------------------------------------------------
2115   // Initialization
2116 
2117   void generate_initial() {
2118     // Generates all stubs and initializes the entry points
2119 
2120     //------------------------------------------------------------------------------------------------------------------------
2121     // entry points that exist in all platforms
2122     // Note: This is code that could be shared among different platforms - however the benefit seems to be smaller than
2123     //       the disadvantage of having a much more complicated generator structure. See also comment in stubRoutines.hpp.
2124     StubRoutines::_forward_exception_entry      = generate_forward_exception();
2125 
2126     StubRoutines::_call_stub_entry              =
2127       generate_call_stub(StubRoutines::_call_stub_return_address);
2128     // is referenced by megamorphic call
2129     StubRoutines::_catch_exception_entry        = generate_catch_exception();
2130 
2131     // These are currently used by Solaris/Intel
2132     StubRoutines::_atomic_xchg_entry            = generate_atomic_xchg();
2133 
2134     StubRoutines::_handler_for_unsafe_access_entry =
2135       generate_handler_for_unsafe_access();
2136 
2137     // platform dependent
2138     create_control_words();
2139 
2140     StubRoutines::i486::_verify_mxcsr_entry                 = generate_verify_mxcsr();
2141     StubRoutines::i486::_verify_fpu_cntrl_wrd_entry         = generate_verify_fpu_cntrl_wrd();
2142     StubRoutines::_d2i_wrapper                              = generate_d2i_wrapper(T_INT,
2143                                                                                    CAST_FROM_FN_PTR(address, SharedRuntime::d2i));
2144     StubRoutines::_d2l_wrapper                              = generate_d2i_wrapper(T_LONG,
2145                                                                                    CAST_FROM_FN_PTR(address, SharedRuntime::d2l));
2146   }
2147 
2148 
2149   void generate_all() {
2150     // Generates all stubs and initializes the entry points
2151 
2152     // These entry points require SharedInfo::stack0 to be set up in non-core builds
2153     // and need to be relocatable, so they each fabricate a RuntimeStub internally.
2154     StubRoutines::_throw_AbstractMethodError_entry         = generate_throw_exception("AbstractMethodError throw_exception",          CAST_FROM_FN_PTR(address, SharedRuntime::throw_AbstractMethodError),  false);
2155     StubRoutines::_throw_IncompatibleClassChangeError_entry= generate_throw_exception("IncompatibleClassChangeError throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_IncompatibleClassChangeError),  false);
2156     StubRoutines::_throw_ArithmeticException_entry         = generate_throw_exception("ArithmeticException throw_exception",          CAST_FROM_FN_PTR(address, SharedRuntime::throw_ArithmeticException),  true);
2157     StubRoutines::_throw_NullPointerException_entry        = generate_throw_exception("NullPointerException throw_exception",         CAST_FROM_FN_PTR(address, SharedRuntime::throw_NullPointerException), true);
2158     StubRoutines::_throw_NullPointerException_at_call_entry= generate_throw_exception("NullPointerException at call throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_NullPointerException_at_call), false);
2159     StubRoutines::_throw_StackOverflowError_entry          = generate_throw_exception("StackOverflowError throw_exception",           CAST_FROM_FN_PTR(address, SharedRuntime::throw_StackOverflowError),   false);
2160 
2161     //------------------------------------------------------------------------------------------------------------------------
2162     // entry points that are platform specific
2163 
2164     // support for verify_oop (must happen after universe_init)
2165     StubRoutines::_verify_oop_subroutine_entry     = generate_verify_oop();
2166 
2167     // arraycopy stubs used by compilers
2168     generate_arraycopy_stubs();
2169   }
2170 
2171 
2172  public:
2173   StubGenerator(CodeBuffer* code, bool all) : StubCodeGenerator(code) {
2174     if (all) {
2175       generate_all();
2176     } else {
2177       generate_initial();
2178     }
2179   }
2180 }; // end class declaration
2181 
2182 
2183 void StubGenerator_generate(CodeBuffer* code, bool all) {
2184   StubGenerator g(code, all);
2185 }