1 /*
   2  * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "asm/macroAssembler.hpp"
  27 #include "asm/macroAssembler.inline.hpp"
  28 #include "gc/shared/barrierSet.hpp"
  29 #include "gc/shared/barrierSetAssembler.hpp"
  30 #include "interpreter/interpreter.hpp"
  31 #include "memory/universe.hpp"
  32 #include "nativeInst_x86.hpp"
  33 #include "oops/instanceOop.hpp"
  34 #include "oops/method.hpp"
  35 #include "oops/objArrayKlass.hpp"
  36 #include "oops/oop.inline.hpp"
  37 #include "prims/methodHandles.hpp"
  38 #include "runtime/frame.inline.hpp"
  39 #include "runtime/handles.inline.hpp"
  40 #include "runtime/sharedRuntime.hpp"
  41 #include "runtime/stubCodeGenerator.hpp"
  42 #include "runtime/stubRoutines.hpp"
  43 #include "runtime/thread.inline.hpp"
  44 #ifdef COMPILER2
  45 #include "opto/runtime.hpp"
  46 #endif
  47 
  48 // Declaration and definition of StubGenerator (no .hpp file).
  49 // For a more detailed description of the stub routine structure
  50 // see the comment in stubRoutines.hpp
  51 
  52 #define __ _masm->
  53 #define a__ ((Assembler*)_masm)->
  54 
  55 #ifdef PRODUCT
  56 #define BLOCK_COMMENT(str) /* nothing */
  57 #else
  58 #define BLOCK_COMMENT(str) __ block_comment(str)
  59 #endif
  60 
  61 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  62 
  63 const int MXCSR_MASK  = 0xFFC0;  // Mask out any pending exceptions
  64 const int FPU_CNTRL_WRD_MASK = 0xFFFF;
  65 
  66 // -------------------------------------------------------------------------------------------------------------------------
  67 // Stub Code definitions
  68 
  69 class StubGenerator: public StubCodeGenerator {
  70  private:
  71 
  72 #ifdef PRODUCT
  73 #define inc_counter_np(counter) ((void)0)
  74 #else
  75   void inc_counter_np_(int& counter) {
  76     __ incrementl(ExternalAddress((address)&counter));
  77   }
  78 #define inc_counter_np(counter) \
  79   BLOCK_COMMENT("inc_counter " #counter); \
  80   inc_counter_np_(counter);
  81 #endif //PRODUCT
  82 
  83   void inc_copy_counter_np(BasicType t) {
  84 #ifndef PRODUCT
  85     switch (t) {
  86     case T_BYTE:    inc_counter_np(SharedRuntime::_jbyte_array_copy_ctr); return;
  87     case T_SHORT:   inc_counter_np(SharedRuntime::_jshort_array_copy_ctr); return;
  88     case T_INT:     inc_counter_np(SharedRuntime::_jint_array_copy_ctr); return;
  89     case T_LONG:    inc_counter_np(SharedRuntime::_jlong_array_copy_ctr); return;
  90     case T_OBJECT:  inc_counter_np(SharedRuntime::_oop_array_copy_ctr); return;
  91     default:        ShouldNotReachHere();
  92     }
  93 #endif //PRODUCT
  94   }
  95 
  96   //------------------------------------------------------------------------------------------------------------------------
  97   // Call stubs are used to call Java from C
  98   //
  99   //    [ return_from_Java     ] <--- rsp
 100   //    [ argument word n      ]
 101   //      ...
 102   // -N [ argument word 1      ]
 103   // -7 [ Possible padding for stack alignment ]
 104   // -6 [ Possible padding for stack alignment ]
 105   // -5 [ Possible padding for stack alignment ]
 106   // -4 [ mxcsr save           ] <--- rsp_after_call
 107   // -3 [ saved rbx,            ]
 108   // -2 [ saved rsi            ]
 109   // -1 [ saved rdi            ]
 110   //  0 [ saved rbp,            ] <--- rbp,
 111   //  1 [ return address       ]
 112   //  2 [ ptr. to call wrapper ]
 113   //  3 [ result               ]
 114   //  4 [ result_type          ]
 115   //  5 [ method               ]
 116   //  6 [ entry_point          ]
 117   //  7 [ parameters           ]
 118   //  8 [ parameter_size       ]
 119   //  9 [ thread               ]
 120 
 121 
 122   address generate_call_stub(address& return_address) {
 123     StubCodeMark mark(this, "StubRoutines", "call_stub");
 124     address start = __ pc();
 125 
 126     // stub code parameters / addresses
 127     assert(frame::entry_frame_call_wrapper_offset == 2, "adjust this code");
 128     bool  sse_save = false;
 129     const Address rsp_after_call(rbp, -4 * wordSize); // same as in generate_catch_exception()!
 130     const int     locals_count_in_bytes  (4*wordSize);
 131     const Address mxcsr_save    (rbp, -4 * wordSize);
 132     const Address saved_rbx     (rbp, -3 * wordSize);
 133     const Address saved_rsi     (rbp, -2 * wordSize);
 134     const Address saved_rdi     (rbp, -1 * wordSize);
 135     const Address result        (rbp,  3 * wordSize);
 136     const Address result_type   (rbp,  4 * wordSize);
 137     const Address method        (rbp,  5 * wordSize);
 138     const Address entry_point   (rbp,  6 * wordSize);
 139     const Address parameters    (rbp,  7 * wordSize);
 140     const Address parameter_size(rbp,  8 * wordSize);
 141     const Address thread        (rbp,  9 * wordSize); // same as in generate_catch_exception()!
 142     sse_save =  UseSSE > 0;
 143 
 144     // stub code
 145     __ enter();
 146     __ movptr(rcx, parameter_size);              // parameter counter
 147     __ shlptr(rcx, Interpreter::logStackElementSize); // convert parameter count to bytes
 148     __ addptr(rcx, locals_count_in_bytes);       // reserve space for register saves
 149     __ subptr(rsp, rcx);
 150     __ andptr(rsp, -(StackAlignmentInBytes));    // Align stack
 151 
 152     // save rdi, rsi, & rbx, according to C calling conventions
 153     __ movptr(saved_rdi, rdi);
 154     __ movptr(saved_rsi, rsi);
 155     __ movptr(saved_rbx, rbx);
 156 
 157     // save and initialize %mxcsr
 158     if (sse_save) {
 159       Label skip_ldmx;
 160       __ stmxcsr(mxcsr_save);
 161       __ movl(rax, mxcsr_save);
 162       __ andl(rax, MXCSR_MASK);    // Only check control and mask bits
 163       ExternalAddress mxcsr_std(StubRoutines::addr_mxcsr_std());
 164       __ cmp32(rax, mxcsr_std);
 165       __ jcc(Assembler::equal, skip_ldmx);
 166       __ ldmxcsr(mxcsr_std);
 167       __ bind(skip_ldmx);
 168     }
 169 
 170     // make sure the control word is correct.
 171     __ fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
 172 
 173 #ifdef ASSERT
 174     // make sure we have no pending exceptions
 175     { Label L;
 176       __ movptr(rcx, thread);
 177       __ cmpptr(Address(rcx, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
 178       __ jcc(Assembler::equal, L);
 179       __ stop("StubRoutines::call_stub: entered with pending exception");
 180       __ bind(L);
 181     }
 182 #endif
 183 
 184     // pass parameters if any
 185     BLOCK_COMMENT("pass parameters if any");
 186     Label parameters_done;
 187     __ movl(rcx, parameter_size);  // parameter counter
 188     __ testl(rcx, rcx);
 189     __ jcc(Assembler::zero, parameters_done);
 190 
 191     // parameter passing loop
 192 
 193     Label loop;
 194     // Copy Java parameters in reverse order (receiver last)
 195     // Note that the argument order is inverted in the process
 196     // source is rdx[rcx: N-1..0]
 197     // dest   is rsp[rbx: 0..N-1]
 198 
 199     __ movptr(rdx, parameters);          // parameter pointer
 200     __ xorptr(rbx, rbx);
 201 
 202     __ BIND(loop);
 203 
 204     // get parameter
 205     __ movptr(rax, Address(rdx, rcx, Interpreter::stackElementScale(), -wordSize));
 206     __ movptr(Address(rsp, rbx, Interpreter::stackElementScale(),
 207                     Interpreter::expr_offset_in_bytes(0)), rax);          // store parameter
 208     __ increment(rbx);
 209     __ decrement(rcx);
 210     __ jcc(Assembler::notZero, loop);
 211 
 212     // call Java function
 213     __ BIND(parameters_done);
 214     __ movptr(rbx, method);           // get Method*
 215     __ movptr(rax, entry_point);      // get entry_point
 216     __ mov(rsi, rsp);                 // set sender sp
 217     BLOCK_COMMENT("call Java function");
 218     __ call(rax);
 219 
 220     BLOCK_COMMENT("call_stub_return_address:");
 221     return_address = __ pc();
 222 
 223 #ifdef COMPILER2
 224     {
 225       Label L_skip;
 226       if (UseSSE >= 2) {
 227         __ verify_FPU(0, "call_stub_return");
 228       } else {
 229         for (int i = 1; i < 8; i++) {
 230           __ ffree(i);
 231         }
 232 
 233         // UseSSE <= 1 so double result should be left on TOS
 234         __ movl(rsi, result_type);
 235         __ cmpl(rsi, T_DOUBLE);
 236         __ jcc(Assembler::equal, L_skip);
 237         if (UseSSE == 0) {
 238           // UseSSE == 0 so float result should be left on TOS
 239           __ cmpl(rsi, T_FLOAT);
 240           __ jcc(Assembler::equal, L_skip);
 241         }
 242         __ ffree(0);
 243       }
 244       __ BIND(L_skip);
 245     }
 246 #endif // COMPILER2
 247 
 248     // store result depending on type
 249     // (everything that is not T_LONG, T_FLOAT or T_DOUBLE is treated as T_INT)
 250     __ movptr(rdi, result);
 251     Label is_long, is_float, is_double, exit;
 252     __ movl(rsi, result_type);
 253     __ cmpl(rsi, T_LONG);
 254     __ jcc(Assembler::equal, is_long);
 255     __ cmpl(rsi, T_FLOAT);
 256     __ jcc(Assembler::equal, is_float);
 257     __ cmpl(rsi, T_DOUBLE);
 258     __ jcc(Assembler::equal, is_double);
 259 
 260     // handle T_INT case
 261     __ movl(Address(rdi, 0), rax);
 262     __ BIND(exit);
 263 
 264     // check that FPU stack is empty
 265     __ verify_FPU(0, "generate_call_stub");
 266 
 267     // pop parameters
 268     __ lea(rsp, rsp_after_call);
 269 
 270     // restore %mxcsr
 271     if (sse_save) {
 272       __ ldmxcsr(mxcsr_save);
 273     }
 274 
 275     // restore rdi, rsi and rbx,
 276     __ movptr(rbx, saved_rbx);
 277     __ movptr(rsi, saved_rsi);
 278     __ movptr(rdi, saved_rdi);
 279     __ addptr(rsp, 4*wordSize);
 280 
 281     // return
 282     __ pop(rbp);
 283     __ ret(0);
 284 
 285     // handle return types different from T_INT
 286     __ BIND(is_long);
 287     __ movl(Address(rdi, 0 * wordSize), rax);
 288     __ movl(Address(rdi, 1 * wordSize), rdx);
 289     __ jmp(exit);
 290 
 291     __ BIND(is_float);
 292     // interpreter uses xmm0 for return values
 293     if (UseSSE >= 1) {
 294       __ movflt(Address(rdi, 0), xmm0);
 295     } else {
 296       __ fstp_s(Address(rdi, 0));
 297     }
 298     __ jmp(exit);
 299 
 300     __ BIND(is_double);
 301     // interpreter uses xmm0 for return values
 302     if (UseSSE >= 2) {
 303       __ movdbl(Address(rdi, 0), xmm0);
 304     } else {
 305       __ fstp_d(Address(rdi, 0));
 306     }
 307     __ jmp(exit);
 308 
 309     return start;
 310   }
 311 
 312 
 313   //------------------------------------------------------------------------------------------------------------------------
 314   // Return point for a Java call if there's an exception thrown in Java code.
 315   // The exception is caught and transformed into a pending exception stored in
 316   // JavaThread that can be tested from within the VM.
 317   //
 318   // Note: Usually the parameters are removed by the callee. In case of an exception
 319   //       crossing an activation frame boundary, that is not the case if the callee
 320   //       is compiled code => need to setup the rsp.
 321   //
 322   // rax,: exception oop
 323 
 324   address generate_catch_exception() {
 325     StubCodeMark mark(this, "StubRoutines", "catch_exception");
 326     const Address rsp_after_call(rbp, -4 * wordSize); // same as in generate_call_stub()!
 327     const Address thread        (rbp,  9 * wordSize); // same as in generate_call_stub()!
 328     address start = __ pc();
 329 
 330     // get thread directly
 331     __ movptr(rcx, thread);
 332 #ifdef ASSERT
 333     // verify that threads correspond
 334     { Label L;
 335       __ get_thread(rbx);
 336       __ cmpptr(rbx, rcx);
 337       __ jcc(Assembler::equal, L);
 338       __ stop("StubRoutines::catch_exception: threads must correspond");
 339       __ bind(L);
 340     }
 341 #endif
 342     // set pending exception
 343     __ verify_oop(rax);
 344     __ movptr(Address(rcx, Thread::pending_exception_offset()), rax          );
 345     __ lea(Address(rcx, Thread::exception_file_offset   ()),
 346            ExternalAddress((address)__FILE__));
 347     __ movl(Address(rcx, Thread::exception_line_offset   ()), __LINE__ );
 348     // complete return to VM
 349     assert(StubRoutines::_call_stub_return_address != NULL, "_call_stub_return_address must have been generated before");
 350     __ jump(RuntimeAddress(StubRoutines::_call_stub_return_address));
 351 
 352     return start;
 353   }
 354 
 355 
 356   //------------------------------------------------------------------------------------------------------------------------
 357   // Continuation point for runtime calls returning with a pending exception.
 358   // The pending exception check happened in the runtime or native call stub.
 359   // The pending exception in Thread is converted into a Java-level exception.
 360   //
 361   // Contract with Java-level exception handlers:
 362   // rax: exception
 363   // rdx: throwing pc
 364   //
 365   // NOTE: At entry of this stub, exception-pc must be on stack !!
 366 
 367   address generate_forward_exception() {
 368     StubCodeMark mark(this, "StubRoutines", "forward exception");
 369     address start = __ pc();
 370     const Register thread = rcx;
 371 
 372     // other registers used in this stub
 373     const Register exception_oop = rax;
 374     const Register handler_addr  = rbx;
 375     const Register exception_pc  = rdx;
 376 
 377     // Upon entry, the sp points to the return address returning into Java
 378     // (interpreted or compiled) code; i.e., the return address becomes the
 379     // throwing pc.
 380     //
 381     // Arguments pushed before the runtime call are still on the stack but
 382     // the exception handler will reset the stack pointer -> ignore them.
 383     // A potential result in registers can be ignored as well.
 384 
 385 #ifdef ASSERT
 386     // make sure this code is only executed if there is a pending exception
 387     { Label L;
 388       __ get_thread(thread);
 389       __ cmpptr(Address(thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
 390       __ jcc(Assembler::notEqual, L);
 391       __ stop("StubRoutines::forward exception: no pending exception (1)");
 392       __ bind(L);
 393     }
 394 #endif
 395 
 396     // compute exception handler into rbx,
 397     __ get_thread(thread);
 398     __ movptr(exception_pc, Address(rsp, 0));
 399     BLOCK_COMMENT("call exception_handler_for_return_address");
 400     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address), thread, exception_pc);
 401     __ mov(handler_addr, rax);
 402 
 403     // setup rax & rdx, remove return address & clear pending exception
 404     __ get_thread(thread);
 405     __ pop(exception_pc);
 406     __ movptr(exception_oop, Address(thread, Thread::pending_exception_offset()));
 407     __ movptr(Address(thread, Thread::pending_exception_offset()), NULL_WORD);
 408 
 409 #ifdef ASSERT
 410     // make sure exception is set
 411     { Label L;
 412       __ testptr(exception_oop, exception_oop);
 413       __ jcc(Assembler::notEqual, L);
 414       __ stop("StubRoutines::forward exception: no pending exception (2)");
 415       __ bind(L);
 416     }
 417 #endif
 418 
 419     // Verify that there is really a valid exception in RAX.
 420     __ verify_oop(exception_oop);
 421 
 422     // continue at exception handler (return address removed)
 423     // rax: exception
 424     // rbx: exception handler
 425     // rdx: throwing pc
 426     __ jmp(handler_addr);
 427 
 428     return start;
 429   }
 430 
 431 
 432   //----------------------------------------------------------------------------------------------------
 433   // Support for int32_t Atomic::xchg(volatile int32_t* dest, int32_t exchange_value)
 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     __ push(rdx);
 451     Address exchange(rsp, 2 * wordSize);
 452     Address dest_addr(rsp, 3 * wordSize);
 453     __ movl(rax, exchange);
 454     __ movptr(rdx, dest_addr);
 455     __ xchgl(rax, Address(rdx, 0));
 456     __ pop(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       __ push(rax);
 480       __ subptr(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       __ addptr(rsp, wordSize);
 493       __ pop(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       __ push(rax);
 518       __ subptr(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       __ addptr(rsp, wordSize);
 532       __ pop(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     __ subptr(rsp, wordSize * 2);
 567     __ fstp_d(Address(rsp, 0));
 568 
 569     // Save CPU & FPU state
 570     __ push(rbx);
 571     __ push(rcx);
 572     __ push(rsi);
 573     __ push(rdi);
 574     __ push(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     __ subptr(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     __ pop(rbp);
 596     __ pop(rdi);
 597     __ pop(rsi);
 598     __ pop(rcx);
 599     __ pop(rbx);
 600     __ addptr(rsp, wordSize * 2);
 601 
 602     __ ret(0);
 603 
 604     return start;
 605   }
 606   //---------------------------------------------------------------------------------------------------
 607 
 608   address generate_vector_mask(const char *stub_name, int32_t mask) {
 609     __ align(CodeEntryAlignment);
 610     StubCodeMark mark(this, "StubRoutines", stub_name);
 611     address start = __ pc();
 612 
 613     for (int i = 0; i < 16; i++) {
 614       __ emit_data(mask, relocInfo::none, 0);
 615     }
 616 
 617     return start;
 618   }
 619 
 620   address generate_vector_mask_long_double(const char *stub_name, int32_t maskhi, int32_t masklo) {
 621     __ align(CodeEntryAlignment);
 622     StubCodeMark mark(this, "StubRoutines", stub_name);
 623     address start = __ pc();
 624 
 625     for (int i = 0; i < 8; i++) {
 626       __ emit_data(masklo, relocInfo::none, 0);
 627       __ emit_data(maskhi, relocInfo::none, 0);
 628     }
 629 
 630     return start;
 631   }
 632 
 633   //----------------------------------------------------------------------------------------------------
 634 
 635   address generate_vector_byte_perm_mask(const char *stub_name) {
 636     __ align(CodeEntryAlignment);
 637     StubCodeMark mark(this, "StubRoutines", stub_name);
 638     address start = __ pc();
 639 
 640     __ emit_data(0x00000001, relocInfo::none, 0);
 641     __ emit_data(0x00000000, relocInfo::none, 0);
 642     __ emit_data(0x00000003, relocInfo::none, 0);
 643     __ emit_data(0x00000000, relocInfo::none, 0);
 644     __ emit_data(0x00000005, relocInfo::none, 0);
 645     __ emit_data(0x00000000, relocInfo::none, 0);
 646     __ emit_data(0x00000007, relocInfo::none, 0);
 647     __ emit_data(0x00000000, relocInfo::none, 0);
 648     __ emit_data(0x00000000, relocInfo::none, 0);
 649     __ emit_data(0x00000000, relocInfo::none, 0);
 650     __ emit_data(0x00000002, relocInfo::none, 0);
 651     __ emit_data(0x00000000, relocInfo::none, 0);
 652     __ emit_data(0x00000004, relocInfo::none, 0);
 653     __ emit_data(0x00000000, relocInfo::none, 0);
 654     __ emit_data(0x00000006, relocInfo::none, 0);
 655     __ emit_data(0x00000000, relocInfo::none, 0);
 656 
 657     return start;
 658   }
 659 
 660   //----------------------------------------------------------------------------------------------------
 661   // Non-destructive plausibility checks for oops
 662 
 663   address generate_verify_oop() {
 664     StubCodeMark mark(this, "StubRoutines", "verify_oop");
 665     address start = __ pc();
 666 
 667     // Incoming arguments on stack after saving rax,:
 668     //
 669     // [tos    ]: saved rdx
 670     // [tos + 1]: saved EFLAGS
 671     // [tos + 2]: return address
 672     // [tos + 3]: char* error message
 673     // [tos + 4]: oop   object to verify
 674     // [tos + 5]: saved rax, - saved by caller and bashed
 675 
 676     Label exit, error;
 677     __ pushf();
 678     __ incrementl(ExternalAddress((address) StubRoutines::verify_oop_count_addr()));
 679     __ push(rdx);                                // save rdx
 680     // make sure object is 'reasonable'
 681     __ movptr(rax, Address(rsp, 4 * wordSize));    // get object
 682     __ testptr(rax, rax);
 683     __ jcc(Assembler::zero, exit);               // if obj is NULL it is ok
 684 
 685     // Check if the oop is in the right area of memory
 686     const int oop_mask = Universe::verify_oop_mask();
 687     const int oop_bits = Universe::verify_oop_bits();
 688     __ mov(rdx, rax);
 689     __ andptr(rdx, oop_mask);
 690     __ cmpptr(rdx, oop_bits);
 691     __ jcc(Assembler::notZero, error);
 692 
 693     // make sure klass is 'reasonable', which is not zero.
 694     __ movptr(rax, Address(rax, oopDesc::klass_offset_in_bytes())); // get klass
 695     __ testptr(rax, rax);
 696     __ jcc(Assembler::zero, error);              // if klass is NULL it is broken
 697 
 698     // return if everything seems ok
 699     __ bind(exit);
 700     __ movptr(rax, Address(rsp, 5 * wordSize));  // get saved rax, back
 701     __ pop(rdx);                                 // restore rdx
 702     __ popf();                                   // restore EFLAGS
 703     __ ret(3 * wordSize);                        // pop arguments
 704 
 705     // handle errors
 706     __ bind(error);
 707     __ movptr(rax, Address(rsp, 5 * wordSize));  // get saved rax, back
 708     __ pop(rdx);                                 // get saved rdx back
 709     __ popf();                                   // get saved EFLAGS off stack -- will be ignored
 710     __ pusha();                                  // push registers (eip = return address & msg are already pushed)
 711     BLOCK_COMMENT("call MacroAssembler::debug");
 712     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 713     __ hlt();
 714     return start;
 715   }
 716 
 717 
 718   // Copy 64 bytes chunks
 719   //
 720   // Inputs:
 721   //   from        - source array address
 722   //   to_from     - destination array address - from
 723   //   qword_count - 8-bytes element count, negative
 724   //
 725   void xmm_copy_forward(Register from, Register to_from, Register qword_count) {
 726     assert( UseSSE >= 2, "supported cpu only" );
 727     Label L_copy_64_bytes_loop, L_copy_64_bytes, L_copy_8_bytes, L_exit;
 728 
 729     // Copy 64-byte chunks
 730     __ jmpb(L_copy_64_bytes);
 731     __ align(OptoLoopAlignment);
 732   __ BIND(L_copy_64_bytes_loop);
 733 
 734     if (UseUnalignedLoadStores) {
 735       if (UseAVX > 2) {
 736         __ evmovdqul(xmm0, Address(from, 0), Assembler::AVX_512bit);
 737         __ evmovdqul(Address(from, to_from, Address::times_1, 0), xmm0, Assembler::AVX_512bit);
 738       } else if (UseAVX == 2) {
 739         __ vmovdqu(xmm0, Address(from,  0));
 740         __ vmovdqu(Address(from, to_from, Address::times_1,  0), xmm0);
 741         __ vmovdqu(xmm1, Address(from, 32));
 742         __ vmovdqu(Address(from, to_from, Address::times_1, 32), xmm1);
 743       } else {
 744         __ movdqu(xmm0, Address(from, 0));
 745         __ movdqu(Address(from, to_from, Address::times_1, 0), xmm0);
 746         __ movdqu(xmm1, Address(from, 16));
 747         __ movdqu(Address(from, to_from, Address::times_1, 16), xmm1);
 748         __ movdqu(xmm2, Address(from, 32));
 749         __ movdqu(Address(from, to_from, Address::times_1, 32), xmm2);
 750         __ movdqu(xmm3, Address(from, 48));
 751         __ movdqu(Address(from, to_from, Address::times_1, 48), xmm3);
 752       }
 753     } else {
 754       __ movq(xmm0, Address(from, 0));
 755       __ movq(Address(from, to_from, Address::times_1, 0), xmm0);
 756       __ movq(xmm1, Address(from, 8));
 757       __ movq(Address(from, to_from, Address::times_1, 8), xmm1);
 758       __ movq(xmm2, Address(from, 16));
 759       __ movq(Address(from, to_from, Address::times_1, 16), xmm2);
 760       __ movq(xmm3, Address(from, 24));
 761       __ movq(Address(from, to_from, Address::times_1, 24), xmm3);
 762       __ movq(xmm4, Address(from, 32));
 763       __ movq(Address(from, to_from, Address::times_1, 32), xmm4);
 764       __ movq(xmm5, Address(from, 40));
 765       __ movq(Address(from, to_from, Address::times_1, 40), xmm5);
 766       __ movq(xmm6, Address(from, 48));
 767       __ movq(Address(from, to_from, Address::times_1, 48), xmm6);
 768       __ movq(xmm7, Address(from, 56));
 769       __ movq(Address(from, to_from, Address::times_1, 56), xmm7);
 770     }
 771 
 772     __ addl(from, 64);
 773   __ BIND(L_copy_64_bytes);
 774     __ subl(qword_count, 8);
 775     __ jcc(Assembler::greaterEqual, L_copy_64_bytes_loop);
 776 
 777     if (UseUnalignedLoadStores && (UseAVX == 2)) {
 778       // clean upper bits of YMM registers
 779       __ vpxor(xmm0, xmm0);
 780       __ vpxor(xmm1, xmm1);
 781     }
 782     __ addl(qword_count, 8);
 783     __ jccb(Assembler::zero, L_exit);
 784     //
 785     // length is too short, just copy qwords
 786     //
 787   __ BIND(L_copy_8_bytes);
 788     __ movq(xmm0, Address(from, 0));
 789     __ movq(Address(from, to_from, Address::times_1), xmm0);
 790     __ addl(from, 8);
 791     __ decrement(qword_count);
 792     __ jcc(Assembler::greater, L_copy_8_bytes);
 793   __ BIND(L_exit);
 794   }
 795 
 796   // Copy 64 bytes chunks
 797   //
 798   // Inputs:
 799   //   from        - source array address
 800   //   to_from     - destination array address - from
 801   //   qword_count - 8-bytes element count, negative
 802   //
 803   void mmx_copy_forward(Register from, Register to_from, Register qword_count) {
 804     assert( VM_Version::supports_mmx(), "supported cpu only" );
 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(OptoLoopAlignment);
 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     __ addptr(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     __ addptr(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                                  bool dest_uninitialized = false) {
 849     __ align(CodeEntryAlignment);
 850     StubCodeMark mark(this, "StubRoutines", name);
 851     address start = __ pc();
 852 
 853     Label L_0_count, L_exit, L_skip_align1, L_skip_align2, L_copy_byte;
 854     Label L_copy_2_bytes, L_copy_4_bytes, L_copy_64_bytes;
 855 
 856     int shift = Address::times_ptr - sf;
 857 
 858     const Register from     = rsi;  // source array address
 859     const Register to       = rdi;  // destination array address
 860     const Register count    = rcx;  // elements count
 861     const Register to_from  = to;   // (to - from)
 862     const Register saved_to = rdx;  // saved destination array address
 863 
 864     __ enter(); // required for proper stackwalking of RuntimeStub frame
 865     __ push(rsi);
 866     __ push(rdi);
 867     __ movptr(from , Address(rsp, 12+ 4));
 868     __ movptr(to   , Address(rsp, 12+ 8));
 869     __ movl(count, Address(rsp, 12+ 12));
 870 
 871     if (entry != NULL) {
 872       *entry = __ pc(); // Entry point from conjoint arraycopy stub.
 873       BLOCK_COMMENT("Entry:");
 874     }
 875 
 876     if (t == T_OBJECT) {
 877       __ testl(count, count);
 878       __ jcc(Assembler::zero, L_0_count);
 879     }
 880 
 881     DecoratorSet decorators = IN_HEAP | IS_ARRAY | ARRAYCOPY_DISJOINT;
 882     if (dest_uninitialized) {
 883       decorators |= IS_DEST_UNINITIALIZED;
 884     }
 885     if (aligned) {
 886       decorators |= ARRAYCOPY_ALIGNED;
 887     }
 888 
 889     BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
 890     bs->arraycopy_prologue(_masm, decorators, t, from, to, count);
 891     {
 892       bool add_entry = (t != T_OBJECT && (!aligned || t == T_INT));
 893       // UnsafeCopyMemory page error: continue after ucm
 894       UnsafeCopyMemoryMark ucmm(this, add_entry, true);
 895       __ subptr(to, from); // to --> to_from
 896       __ cmpl(count, 2<<shift); // Short arrays (< 8 bytes) copy by element
 897       __ jcc(Assembler::below, L_copy_4_bytes); // use unsigned cmp
 898       if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
 899         // align source address at 4 bytes address boundary
 900         if (t == T_BYTE) {
 901           // One byte misalignment happens only for byte arrays
 902           __ testl(from, 1);
 903           __ jccb(Assembler::zero, L_skip_align1);
 904           __ movb(rax, Address(from, 0));
 905           __ movb(Address(from, to_from, Address::times_1, 0), rax);
 906           __ increment(from);
 907           __ decrement(count);
 908         __ BIND(L_skip_align1);
 909         }
 910         // Two bytes misalignment happens only for byte and short (char) arrays
 911         __ testl(from, 2);
 912         __ jccb(Assembler::zero, L_skip_align2);
 913         __ movw(rax, Address(from, 0));
 914         __ movw(Address(from, to_from, Address::times_1, 0), rax);
 915         __ addptr(from, 2);
 916         __ subl(count, 1<<(shift-1));
 917       __ BIND(L_skip_align2);
 918       }
 919       if (!VM_Version::supports_mmx()) {
 920         __ mov(rax, count);      // save 'count'
 921         __ shrl(count, shift); // bytes count
 922         __ addptr(to_from, from);// restore 'to'
 923         __ rep_mov();
 924         __ subptr(to_from, from);// restore 'to_from'
 925         __ mov(count, rax);      // restore 'count'
 926         __ jmpb(L_copy_2_bytes); // all dwords were copied
 927       } else {
 928         if (!UseUnalignedLoadStores) {
 929           // align to 8 bytes, we know we are 4 byte aligned to start
 930           __ testptr(from, 4);
 931           __ jccb(Assembler::zero, L_copy_64_bytes);
 932           __ movl(rax, Address(from, 0));
 933           __ movl(Address(from, to_from, Address::times_1, 0), rax);
 934           __ addptr(from, 4);
 935           __ subl(count, 1<<shift);
 936          }
 937       __ BIND(L_copy_64_bytes);
 938         __ mov(rax, count);
 939         __ shrl(rax, shift+1);  // 8 bytes chunk count
 940         //
 941         // Copy 8-byte chunks through MMX registers, 8 per iteration of the loop
 942         //
 943         if (UseXMMForArrayCopy) {
 944           xmm_copy_forward(from, to_from, rax);
 945         } else {
 946           mmx_copy_forward(from, to_from, rax);
 947         }
 948       }
 949       // copy tailing dword
 950     __ BIND(L_copy_4_bytes);
 951       __ testl(count, 1<<shift);
 952       __ jccb(Assembler::zero, L_copy_2_bytes);
 953       __ movl(rax, Address(from, 0));
 954       __ movl(Address(from, to_from, Address::times_1, 0), rax);
 955       if (t == T_BYTE || t == T_SHORT) {
 956         __ addptr(from, 4);
 957       __ BIND(L_copy_2_bytes);
 958         // copy tailing word
 959         __ testl(count, 1<<(shift-1));
 960         __ jccb(Assembler::zero, L_copy_byte);
 961         __ movw(rax, Address(from, 0));
 962         __ movw(Address(from, to_from, Address::times_1, 0), rax);
 963         if (t == T_BYTE) {
 964           __ addptr(from, 2);
 965         __ BIND(L_copy_byte);
 966           // copy tailing byte
 967           __ testl(count, 1);
 968           __ jccb(Assembler::zero, L_exit);
 969           __ movb(rax, Address(from, 0));
 970           __ movb(Address(from, to_from, Address::times_1, 0), rax);
 971         __ BIND(L_exit);
 972         } else {
 973         __ BIND(L_copy_byte);
 974         }
 975       } else {
 976       __ BIND(L_copy_2_bytes);
 977       }
 978     }
 979 
 980     if (VM_Version::supports_mmx() && !UseXMMForArrayCopy) {
 981       __ emms();
 982     }
 983     __ movl(count, Address(rsp, 12+12)); // reread 'count'
 984     bs->arraycopy_epilogue(_masm, decorators, t, from, to, count);
 985 
 986     if (t == T_OBJECT) {
 987     __ BIND(L_0_count);
 988     }
 989     inc_copy_counter_np(t);
 990     __ pop(rdi);
 991     __ pop(rsi);
 992     __ leave(); // required for proper stackwalking of RuntimeStub frame
 993     __ vzeroupper();
 994     __ xorptr(rax, rax); // return 0
 995     __ ret(0);
 996     return start;
 997   }
 998 
 999 
1000   address generate_fill(BasicType t, bool aligned, const char *name) {
1001     __ align(CodeEntryAlignment);
1002     StubCodeMark mark(this, "StubRoutines", name);
1003     address start = __ pc();
1004 
1005     BLOCK_COMMENT("Entry:");
1006 
1007     const Register to       = rdi;  // source array address
1008     const Register value    = rdx;  // value
1009     const Register count    = rsi;  // elements count
1010 
1011     __ enter(); // required for proper stackwalking of RuntimeStub frame
1012     __ push(rsi);
1013     __ push(rdi);
1014     __ movptr(to   , Address(rsp, 12+ 4));
1015     __ movl(value, Address(rsp, 12+ 8));
1016     __ movl(count, Address(rsp, 12+ 12));
1017 
1018     __ generate_fill(t, aligned, to, value, count, rax, xmm0);
1019 
1020     __ pop(rdi);
1021     __ pop(rsi);
1022     __ leave(); // required for proper stackwalking of RuntimeStub frame
1023     __ ret(0);
1024     return start;
1025   }
1026 
1027   address generate_conjoint_copy(BasicType t, bool aligned,
1028                                  Address::ScaleFactor sf,
1029                                  address nooverlap_target,
1030                                  address* entry, const char *name,
1031                                  bool dest_uninitialized = false) {
1032     __ align(CodeEntryAlignment);
1033     StubCodeMark mark(this, "StubRoutines", name);
1034     address start = __ pc();
1035 
1036     Label L_0_count, L_exit, L_skip_align1, L_skip_align2, L_copy_byte;
1037     Label L_copy_2_bytes, L_copy_4_bytes, L_copy_8_bytes, L_copy_8_bytes_loop;
1038 
1039     int shift = Address::times_ptr - sf;
1040 
1041     const Register src   = rax;  // source array address
1042     const Register dst   = rdx;  // destination array address
1043     const Register from  = rsi;  // source array address
1044     const Register to    = rdi;  // destination array address
1045     const Register count = rcx;  // elements count
1046     const Register end   = rax;  // array end address
1047 
1048     __ enter(); // required for proper stackwalking of RuntimeStub frame
1049     __ push(rsi);
1050     __ push(rdi);
1051     __ movptr(src  , Address(rsp, 12+ 4));   // from
1052     __ movptr(dst  , Address(rsp, 12+ 8));   // to
1053     __ movl2ptr(count, Address(rsp, 12+12)); // count
1054 
1055     if (entry != NULL) {
1056       *entry = __ pc(); // Entry point from generic arraycopy stub.
1057       BLOCK_COMMENT("Entry:");
1058     }
1059 
1060     // nooverlap_target expects arguments in rsi and rdi.
1061     __ mov(from, src);
1062     __ mov(to  , dst);
1063 
1064     // arrays overlap test: dispatch to disjoint stub if necessary.
1065     RuntimeAddress nooverlap(nooverlap_target);
1066     __ cmpptr(dst, src);
1067     __ lea(end, Address(src, count, sf, 0)); // src + count * elem_size
1068     __ jump_cc(Assembler::belowEqual, nooverlap);
1069     __ cmpptr(dst, end);
1070     __ jump_cc(Assembler::aboveEqual, nooverlap);
1071 
1072     if (t == T_OBJECT) {
1073       __ testl(count, count);
1074       __ jcc(Assembler::zero, L_0_count);
1075     }
1076 
1077     DecoratorSet decorators = IN_HEAP | IS_ARRAY;
1078     if (dest_uninitialized) {
1079       decorators |= IS_DEST_UNINITIALIZED;
1080     }
1081     if (aligned) {
1082       decorators |= ARRAYCOPY_ALIGNED;
1083     }
1084 
1085     BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
1086     bs->arraycopy_prologue(_masm, decorators, t, from, to, count);
1087 
1088     {
1089       bool add_entry = (t != T_OBJECT && (!aligned || t == T_INT));
1090       // UnsafeCopyMemory page error: continue after ucm
1091       UnsafeCopyMemoryMark ucmm(this, add_entry, true);
1092       // copy from high to low
1093       __ cmpl(count, 2<<shift); // Short arrays (< 8 bytes) copy by element
1094       __ jcc(Assembler::below, L_copy_4_bytes); // use unsigned cmp
1095       if (t == T_BYTE || t == T_SHORT) {
1096         // Align the end of destination array at 4 bytes address boundary
1097         __ lea(end, Address(dst, count, sf, 0));
1098         if (t == T_BYTE) {
1099           // One byte misalignment happens only for byte arrays
1100           __ testl(end, 1);
1101           __ jccb(Assembler::zero, L_skip_align1);
1102           __ decrement(count);
1103           __ movb(rdx, Address(from, count, sf, 0));
1104           __ movb(Address(to, count, sf, 0), rdx);
1105         __ BIND(L_skip_align1);
1106         }
1107         // Two bytes misalignment happens only for byte and short (char) arrays
1108         __ testl(end, 2);
1109         __ jccb(Assembler::zero, L_skip_align2);
1110         __ subptr(count, 1<<(shift-1));
1111         __ movw(rdx, Address(from, count, sf, 0));
1112         __ movw(Address(to, count, sf, 0), rdx);
1113       __ BIND(L_skip_align2);
1114         __ cmpl(count, 2<<shift); // Short arrays (< 8 bytes) copy by element
1115         __ jcc(Assembler::below, L_copy_4_bytes);
1116       }
1117 
1118       if (!VM_Version::supports_mmx()) {
1119         __ std();
1120         __ mov(rax, count); // Save 'count'
1121         __ mov(rdx, to);    // Save 'to'
1122         __ lea(rsi, Address(from, count, sf, -4));
1123         __ lea(rdi, Address(to  , count, sf, -4));
1124         __ shrptr(count, shift); // bytes count
1125         __ rep_mov();
1126         __ cld();
1127         __ mov(count, rax); // restore 'count'
1128         __ andl(count, (1<<shift)-1);      // mask the number of rest elements
1129         __ movptr(from, Address(rsp, 12+4)); // reread 'from'
1130         __ mov(to, rdx);   // restore 'to'
1131         __ jmpb(L_copy_2_bytes); // all dword were copied
1132       } else {
1133         // Align to 8 bytes the end of array. It is aligned to 4 bytes already.
1134         __ testptr(end, 4);
1135         __ jccb(Assembler::zero, L_copy_8_bytes);
1136         __ subl(count, 1<<shift);
1137         __ movl(rdx, Address(from, count, sf, 0));
1138         __ movl(Address(to, count, sf, 0), rdx);
1139         __ jmpb(L_copy_8_bytes);
1140 
1141         __ align(OptoLoopAlignment);
1142         // Move 8 bytes
1143       __ BIND(L_copy_8_bytes_loop);
1144         if (UseXMMForArrayCopy) {
1145           __ movq(xmm0, Address(from, count, sf, 0));
1146           __ movq(Address(to, count, sf, 0), xmm0);
1147         } else {
1148           __ movq(mmx0, Address(from, count, sf, 0));
1149           __ movq(Address(to, count, sf, 0), mmx0);
1150         }
1151       __ BIND(L_copy_8_bytes);
1152         __ subl(count, 2<<shift);
1153         __ jcc(Assembler::greaterEqual, L_copy_8_bytes_loop);
1154         __ addl(count, 2<<shift);
1155         if (!UseXMMForArrayCopy) {
1156           __ emms();
1157         }
1158       }
1159     __ BIND(L_copy_4_bytes);
1160       // copy prefix qword
1161       __ testl(count, 1<<shift);
1162       __ jccb(Assembler::zero, L_copy_2_bytes);
1163       __ movl(rdx, Address(from, count, sf, -4));
1164       __ movl(Address(to, count, sf, -4), rdx);
1165 
1166       if (t == T_BYTE || t == T_SHORT) {
1167           __ subl(count, (1<<shift));
1168         __ BIND(L_copy_2_bytes);
1169           // copy prefix dword
1170           __ testl(count, 1<<(shift-1));
1171           __ jccb(Assembler::zero, L_copy_byte);
1172           __ movw(rdx, Address(from, count, sf, -2));
1173           __ movw(Address(to, count, sf, -2), rdx);
1174           if (t == T_BYTE) {
1175             __ subl(count, 1<<(shift-1));
1176           __ BIND(L_copy_byte);
1177             // copy prefix byte
1178             __ testl(count, 1);
1179             __ jccb(Assembler::zero, L_exit);
1180             __ movb(rdx, Address(from, 0));
1181             __ movb(Address(to, 0), rdx);
1182           __ BIND(L_exit);
1183           } else {
1184           __ BIND(L_copy_byte);
1185           }
1186       } else {
1187       __ BIND(L_copy_2_bytes);
1188       }
1189     }
1190 
1191     if (VM_Version::supports_mmx() && !UseXMMForArrayCopy) {
1192       __ emms();
1193     }
1194     __ movl2ptr(count, Address(rsp, 12+12)); // reread count
1195     bs->arraycopy_epilogue(_masm, decorators, t, from, to, count);
1196 
1197     if (t == T_OBJECT) {
1198     __ BIND(L_0_count);
1199     }
1200     inc_copy_counter_np(t);
1201     __ pop(rdi);
1202     __ pop(rsi);
1203     __ leave(); // required for proper stackwalking of RuntimeStub frame
1204     __ xorptr(rax, rax); // return 0
1205     __ ret(0);
1206     return start;
1207   }
1208 
1209 
1210   address generate_disjoint_long_copy(address* entry, const char *name) {
1211     __ align(CodeEntryAlignment);
1212     StubCodeMark mark(this, "StubRoutines", name);
1213     address start = __ pc();
1214 
1215     Label L_copy_8_bytes, L_copy_8_bytes_loop;
1216     const Register from       = rax;  // source array address
1217     const Register to         = rdx;  // destination array address
1218     const Register count      = rcx;  // elements count
1219     const Register to_from    = rdx;  // (to - from)
1220 
1221     __ enter(); // required for proper stackwalking of RuntimeStub frame
1222     __ movptr(from , Address(rsp, 8+0));       // from
1223     __ movptr(to   , Address(rsp, 8+4));       // to
1224     __ movl2ptr(count, Address(rsp, 8+8));     // count
1225 
1226     *entry = __ pc(); // Entry point from conjoint arraycopy stub.
1227     BLOCK_COMMENT("Entry:");
1228 
1229     {
1230       // UnsafeCopyMemory page error: continue after ucm
1231       UnsafeCopyMemoryMark ucmm(this, true, true);
1232       __ subptr(to, from); // to --> to_from
1233       if (VM_Version::supports_mmx()) {
1234         if (UseXMMForArrayCopy) {
1235           xmm_copy_forward(from, to_from, count);
1236         } else {
1237           mmx_copy_forward(from, to_from, count);
1238         }
1239       } else {
1240         __ jmpb(L_copy_8_bytes);
1241         __ align(OptoLoopAlignment);
1242       __ BIND(L_copy_8_bytes_loop);
1243         __ fild_d(Address(from, 0));
1244         __ fistp_d(Address(from, to_from, Address::times_1));
1245         __ addptr(from, 8);
1246       __ BIND(L_copy_8_bytes);
1247         __ decrement(count);
1248         __ jcc(Assembler::greaterEqual, L_copy_8_bytes_loop);
1249       }
1250     }
1251     if (VM_Version::supports_mmx() && !UseXMMForArrayCopy) {
1252       __ emms();
1253     }
1254     inc_copy_counter_np(T_LONG);
1255     __ leave(); // required for proper stackwalking of RuntimeStub frame
1256     __ vzeroupper();
1257     __ xorptr(rax, rax); // return 0
1258     __ ret(0);
1259     return start;
1260   }
1261 
1262   address generate_conjoint_long_copy(address nooverlap_target,
1263                                       address* entry, const char *name) {
1264     __ align(CodeEntryAlignment);
1265     StubCodeMark mark(this, "StubRoutines", name);
1266     address start = __ pc();
1267 
1268     Label L_copy_8_bytes, L_copy_8_bytes_loop;
1269     const Register from       = rax;  // source array address
1270     const Register to         = rdx;  // destination array address
1271     const Register count      = rcx;  // elements count
1272     const Register end_from   = rax;  // source array end address
1273 
1274     __ enter(); // required for proper stackwalking of RuntimeStub frame
1275     __ movptr(from , Address(rsp, 8+0));       // from
1276     __ movptr(to   , Address(rsp, 8+4));       // to
1277     __ movl2ptr(count, Address(rsp, 8+8));     // count
1278 
1279     *entry = __ pc(); // Entry point from generic arraycopy stub.
1280     BLOCK_COMMENT("Entry:");
1281 
1282     // arrays overlap test
1283     __ cmpptr(to, from);
1284     RuntimeAddress nooverlap(nooverlap_target);
1285     __ jump_cc(Assembler::belowEqual, nooverlap);
1286     __ lea(end_from, Address(from, count, Address::times_8, 0));
1287     __ cmpptr(to, end_from);
1288     __ movptr(from, Address(rsp, 8));  // from
1289     __ jump_cc(Assembler::aboveEqual, nooverlap);
1290 
1291     {
1292       // UnsafeCopyMemory page error: continue after ucm
1293       UnsafeCopyMemoryMark ucmm(this, true, true);
1294 
1295       __ jmpb(L_copy_8_bytes);
1296 
1297       __ align(OptoLoopAlignment);
1298     __ BIND(L_copy_8_bytes_loop);
1299       if (VM_Version::supports_mmx()) {
1300         if (UseXMMForArrayCopy) {
1301           __ movq(xmm0, Address(from, count, Address::times_8));
1302           __ movq(Address(to, count, Address::times_8), xmm0);
1303         } else {
1304           __ movq(mmx0, Address(from, count, Address::times_8));
1305           __ movq(Address(to, count, Address::times_8), mmx0);
1306         }
1307       } else {
1308         __ fild_d(Address(from, count, Address::times_8));
1309         __ fistp_d(Address(to, count, Address::times_8));
1310       }
1311     __ BIND(L_copy_8_bytes);
1312       __ decrement(count);
1313       __ jcc(Assembler::greaterEqual, L_copy_8_bytes_loop);
1314 
1315     }
1316     if (VM_Version::supports_mmx() && !UseXMMForArrayCopy) {
1317       __ emms();
1318     }
1319     inc_copy_counter_np(T_LONG);
1320     __ leave(); // required for proper stackwalking of RuntimeStub frame
1321     __ xorptr(rax, rax); // return 0
1322     __ ret(0);
1323     return start;
1324   }
1325 
1326 
1327   // Helper for generating a dynamic type check.
1328   // The sub_klass must be one of {rbx, rdx, rsi}.
1329   // The temp is killed.
1330   void generate_type_check(Register sub_klass,
1331                            Address& super_check_offset_addr,
1332                            Address& super_klass_addr,
1333                            Register temp,
1334                            Label* L_success, Label* L_failure) {
1335     BLOCK_COMMENT("type_check:");
1336 
1337     Label L_fallthrough;
1338 #define LOCAL_JCC(assembler_con, label_ptr)                             \
1339     if (label_ptr != NULL)  __ jcc(assembler_con, *(label_ptr));        \
1340     else                    __ jcc(assembler_con, L_fallthrough) /*omit semi*/
1341 
1342     // The following is a strange variation of the fast path which requires
1343     // one less register, because needed values are on the argument stack.
1344     // __ check_klass_subtype_fast_path(sub_klass, *super_klass*, temp,
1345     //                                  L_success, L_failure, NULL);
1346     assert_different_registers(sub_klass, temp);
1347 
1348     int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
1349 
1350     // if the pointers are equal, we are done (e.g., String[] elements)
1351     __ cmpptr(sub_klass, super_klass_addr);
1352     LOCAL_JCC(Assembler::equal, L_success);
1353 
1354     // check the supertype display:
1355     __ movl2ptr(temp, super_check_offset_addr);
1356     Address super_check_addr(sub_klass, temp, Address::times_1, 0);
1357     __ movptr(temp, super_check_addr); // load displayed supertype
1358     __ cmpptr(temp, super_klass_addr); // test the super type
1359     LOCAL_JCC(Assembler::equal, L_success);
1360 
1361     // if it was a primary super, we can just fail immediately
1362     __ cmpl(super_check_offset_addr, sc_offset);
1363     LOCAL_JCC(Assembler::notEqual, L_failure);
1364 
1365     // The repne_scan instruction uses fixed registers, which will get spilled.
1366     // We happen to know this works best when super_klass is in rax.
1367     Register super_klass = temp;
1368     __ movptr(super_klass, super_klass_addr);
1369     __ check_klass_subtype_slow_path(sub_klass, super_klass, noreg, noreg,
1370                                      L_success, L_failure);
1371 
1372     __ bind(L_fallthrough);
1373 
1374     if (L_success == NULL) { BLOCK_COMMENT("L_success:"); }
1375     if (L_failure == NULL) { BLOCK_COMMENT("L_failure:"); }
1376 
1377 #undef LOCAL_JCC
1378   }
1379 
1380   //
1381   //  Generate checkcasting array copy stub
1382   //
1383   //  Input:
1384   //    4(rsp)   - source array address
1385   //    8(rsp)   - destination array address
1386   //   12(rsp)   - element count, can be zero
1387   //   16(rsp)   - size_t ckoff (super_check_offset)
1388   //   20(rsp)   - oop ckval (super_klass)
1389   //
1390   //  Output:
1391   //    rax, ==  0  -  success
1392   //    rax, == -1^K - failure, where K is partial transfer count
1393   //
1394   address generate_checkcast_copy(const char *name, address* entry, bool dest_uninitialized = false) {
1395     __ align(CodeEntryAlignment);
1396     StubCodeMark mark(this, "StubRoutines", name);
1397     address start = __ pc();
1398 
1399     Label L_load_element, L_store_element, L_do_card_marks, L_done;
1400 
1401     // register use:
1402     //  rax, rdx, rcx -- loop control (end_from, end_to, count)
1403     //  rdi, rsi      -- element access (oop, klass)
1404     //  rbx,           -- temp
1405     const Register from       = rax;    // source array address
1406     const Register to         = rdx;    // destination array address
1407     const Register length     = rcx;    // elements count
1408     const Register elem       = rdi;    // each oop copied
1409     const Register elem_klass = rsi;    // each elem._klass (sub_klass)
1410     const Register temp       = rbx;    // lone remaining temp
1411 
1412     __ enter(); // required for proper stackwalking of RuntimeStub frame
1413 
1414     __ push(rsi);
1415     __ push(rdi);
1416     __ push(rbx);
1417 
1418     Address   from_arg(rsp, 16+ 4);     // from
1419     Address     to_arg(rsp, 16+ 8);     // to
1420     Address length_arg(rsp, 16+12);     // elements count
1421     Address  ckoff_arg(rsp, 16+16);     // super_check_offset
1422     Address  ckval_arg(rsp, 16+20);     // super_klass
1423 
1424     // Load up:
1425     __ movptr(from,     from_arg);
1426     __ movptr(to,         to_arg);
1427     __ movl2ptr(length, length_arg);
1428 
1429     if (entry != NULL) {
1430       *entry = __ pc(); // Entry point from generic arraycopy stub.
1431       BLOCK_COMMENT("Entry:");
1432     }
1433 
1434     //---------------------------------------------------------------
1435     // Assembler stub will be used for this call to arraycopy
1436     // if the two arrays are subtypes of Object[] but the
1437     // destination array type is not equal to or a supertype
1438     // of the source type.  Each element must be separately
1439     // checked.
1440 
1441     // Loop-invariant addresses.  They are exclusive end pointers.
1442     Address end_from_addr(from, length, Address::times_ptr, 0);
1443     Address   end_to_addr(to,   length, Address::times_ptr, 0);
1444 
1445     Register end_from = from;           // re-use
1446     Register end_to   = to;             // re-use
1447     Register count    = length;         // re-use
1448 
1449     // Loop-variant addresses.  They assume post-incremented count < 0.
1450     Address from_element_addr(end_from, count, Address::times_ptr, 0);
1451     Address   to_element_addr(end_to,   count, Address::times_ptr, 0);
1452     Address elem_klass_addr(elem, oopDesc::klass_offset_in_bytes());
1453 
1454     DecoratorSet decorators = IN_HEAP | IS_ARRAY | ARRAYCOPY_CHECKCAST;
1455     if (dest_uninitialized) {
1456       decorators |= IS_DEST_UNINITIALIZED;
1457     }
1458 
1459     BasicType type = T_OBJECT;
1460     BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
1461     bs->arraycopy_prologue(_masm, decorators, type, from, to, count);
1462 
1463     // Copy from low to high addresses, indexed from the end of each array.
1464     __ lea(end_from, end_from_addr);
1465     __ lea(end_to,   end_to_addr);
1466     assert(length == count, "");        // else fix next line:
1467     __ negptr(count);                   // negate and test the length
1468     __ jccb(Assembler::notZero, L_load_element);
1469 
1470     // Empty array:  Nothing to do.
1471     __ xorptr(rax, rax);                  // return 0 on (trivial) success
1472     __ jmp(L_done);
1473 
1474     // ======== begin loop ========
1475     // (Loop is rotated; its entry is L_load_element.)
1476     // Loop control:
1477     //   for (count = -count; count != 0; count++)
1478     // Base pointers src, dst are biased by 8*count,to last element.
1479     __ align(OptoLoopAlignment);
1480 
1481     __ BIND(L_store_element);
1482     __ movptr(to_element_addr, elem);     // store the oop
1483     __ increment(count);                // increment the count toward zero
1484     __ jccb(Assembler::zero, L_do_card_marks);
1485 
1486     // ======== loop entry is here ========
1487     __ BIND(L_load_element);
1488     __ movptr(elem, from_element_addr);   // load the oop
1489     __ testptr(elem, elem);
1490     __ jccb(Assembler::zero, L_store_element);
1491 
1492     // (Could do a trick here:  Remember last successful non-null
1493     // element stored and make a quick oop equality check on it.)
1494 
1495     __ movptr(elem_klass, elem_klass_addr); // query the object klass
1496     generate_type_check(elem_klass, ckoff_arg, ckval_arg, temp,
1497                         &L_store_element, NULL);
1498     // (On fall-through, we have failed the element type check.)
1499     // ======== end loop ========
1500 
1501     // It was a real error; we must depend on the caller to finish the job.
1502     // Register "count" = -1 * number of *remaining* oops, length_arg = *total* oops.
1503     // Emit GC store barriers for the oops we have copied (length_arg + count),
1504     // and report their number to the caller.
1505     assert_different_registers(to, count, rax);
1506     Label L_post_barrier;
1507     __ addl(count, length_arg);         // transfers = (length - remaining)
1508     __ movl2ptr(rax, count);            // save the value
1509     __ notptr(rax);                     // report (-1^K) to caller (does not affect flags)
1510     __ jccb(Assembler::notZero, L_post_barrier);
1511     __ jmp(L_done); // K == 0, nothing was copied, skip post barrier
1512 
1513     // Come here on success only.
1514     __ BIND(L_do_card_marks);
1515     __ xorptr(rax, rax);                // return 0 on success
1516     __ movl2ptr(count, length_arg);
1517 
1518     __ BIND(L_post_barrier);
1519     __ movptr(to, to_arg);              // reload
1520     bs->arraycopy_epilogue(_masm, decorators, type, from, to, count);
1521 
1522     // Common exit point (success or failure).
1523     __ BIND(L_done);
1524     __ pop(rbx);
1525     __ pop(rdi);
1526     __ pop(rsi);
1527     inc_counter_np(SharedRuntime::_checkcast_array_copy_ctr);
1528     __ leave(); // required for proper stackwalking of RuntimeStub frame
1529     __ ret(0);
1530 
1531     return start;
1532   }
1533 
1534   //
1535   //  Generate 'unsafe' array copy stub
1536   //  Though just as safe as the other stubs, it takes an unscaled
1537   //  size_t argument instead of an element count.
1538   //
1539   //  Input:
1540   //    4(rsp)   - source array address
1541   //    8(rsp)   - destination array address
1542   //   12(rsp)   - byte count, can be zero
1543   //
1544   //  Output:
1545   //    rax, ==  0  -  success
1546   //    rax, == -1  -  need to call System.arraycopy
1547   //
1548   // Examines the alignment of the operands and dispatches
1549   // to a long, int, short, or byte copy loop.
1550   //
1551   address generate_unsafe_copy(const char *name,
1552                                address byte_copy_entry,
1553                                address short_copy_entry,
1554                                address int_copy_entry,
1555                                address long_copy_entry) {
1556 
1557     Label L_long_aligned, L_int_aligned, L_short_aligned;
1558 
1559     __ align(CodeEntryAlignment);
1560     StubCodeMark mark(this, "StubRoutines", name);
1561     address start = __ pc();
1562 
1563     const Register from       = rax;  // source array address
1564     const Register to         = rdx;  // destination array address
1565     const Register count      = rcx;  // elements count
1566 
1567     __ enter(); // required for proper stackwalking of RuntimeStub frame
1568     __ push(rsi);
1569     __ push(rdi);
1570     Address  from_arg(rsp, 12+ 4);      // from
1571     Address    to_arg(rsp, 12+ 8);      // to
1572     Address count_arg(rsp, 12+12);      // byte count
1573 
1574     // Load up:
1575     __ movptr(from ,  from_arg);
1576     __ movptr(to   ,    to_arg);
1577     __ movl2ptr(count, count_arg);
1578 
1579     // bump this on entry, not on exit:
1580     inc_counter_np(SharedRuntime::_unsafe_array_copy_ctr);
1581 
1582     const Register bits = rsi;
1583     __ mov(bits, from);
1584     __ orptr(bits, to);
1585     __ orptr(bits, count);
1586 
1587     __ testl(bits, BytesPerLong-1);
1588     __ jccb(Assembler::zero, L_long_aligned);
1589 
1590     __ testl(bits, BytesPerInt-1);
1591     __ jccb(Assembler::zero, L_int_aligned);
1592 
1593     __ testl(bits, BytesPerShort-1);
1594     __ jump_cc(Assembler::notZero, RuntimeAddress(byte_copy_entry));
1595 
1596     __ BIND(L_short_aligned);
1597     __ shrptr(count, LogBytesPerShort); // size => short_count
1598     __ movl(count_arg, count);          // update 'count'
1599     __ jump(RuntimeAddress(short_copy_entry));
1600 
1601     __ BIND(L_int_aligned);
1602     __ shrptr(count, LogBytesPerInt); // size => int_count
1603     __ movl(count_arg, count);          // update 'count'
1604     __ jump(RuntimeAddress(int_copy_entry));
1605 
1606     __ BIND(L_long_aligned);
1607     __ shrptr(count, LogBytesPerLong); // size => qword_count
1608     __ movl(count_arg, count);          // update 'count'
1609     __ pop(rdi); // Do pops here since jlong_arraycopy stub does not do it.
1610     __ pop(rsi);
1611     __ jump(RuntimeAddress(long_copy_entry));
1612 
1613     return start;
1614   }
1615 
1616 
1617   // Perform range checks on the proposed arraycopy.
1618   // Smashes src_pos and dst_pos.  (Uses them up for temps.)
1619   void arraycopy_range_checks(Register src,
1620                               Register src_pos,
1621                               Register dst,
1622                               Register dst_pos,
1623                               Address& length,
1624                               Label& L_failed) {
1625     BLOCK_COMMENT("arraycopy_range_checks:");
1626     const Register src_end = src_pos;   // source array end position
1627     const Register dst_end = dst_pos;   // destination array end position
1628     __ addl(src_end, length); // src_pos + length
1629     __ addl(dst_end, length); // dst_pos + length
1630 
1631     //  if (src_pos + length > arrayOop(src)->length() ) FAIL;
1632     __ cmpl(src_end, Address(src, arrayOopDesc::length_offset_in_bytes()));
1633     __ jcc(Assembler::above, L_failed);
1634 
1635     //  if (dst_pos + length > arrayOop(dst)->length() ) FAIL;
1636     __ cmpl(dst_end, Address(dst, arrayOopDesc::length_offset_in_bytes()));
1637     __ jcc(Assembler::above, L_failed);
1638 
1639     BLOCK_COMMENT("arraycopy_range_checks done");
1640   }
1641 
1642 
1643   //
1644   //  Generate generic array copy stubs
1645   //
1646   //  Input:
1647   //     4(rsp)    -  src oop
1648   //     8(rsp)    -  src_pos
1649   //    12(rsp)    -  dst oop
1650   //    16(rsp)    -  dst_pos
1651   //    20(rsp)    -  element count
1652   //
1653   //  Output:
1654   //    rax, ==  0  -  success
1655   //    rax, == -1^K - failure, where K is partial transfer count
1656   //
1657   address generate_generic_copy(const char *name,
1658                                 address entry_jbyte_arraycopy,
1659                                 address entry_jshort_arraycopy,
1660                                 address entry_jint_arraycopy,
1661                                 address entry_oop_arraycopy,
1662                                 address entry_jlong_arraycopy,
1663                                 address entry_checkcast_arraycopy) {
1664     Label L_failed, L_failed_0, L_objArray;
1665 
1666     { int modulus = CodeEntryAlignment;
1667       int target  = modulus - 5; // 5 = sizeof jmp(L_failed)
1668       int advance = target - (__ offset() % modulus);
1669       if (advance < 0)  advance += modulus;
1670       if (advance > 0)  __ nop(advance);
1671     }
1672     StubCodeMark mark(this, "StubRoutines", name);
1673 
1674     // Short-hop target to L_failed.  Makes for denser prologue code.
1675     __ BIND(L_failed_0);
1676     __ jmp(L_failed);
1677     assert(__ offset() % CodeEntryAlignment == 0, "no further alignment needed");
1678 
1679     __ align(CodeEntryAlignment);
1680     address start = __ pc();
1681 
1682     __ enter(); // required for proper stackwalking of RuntimeStub frame
1683     __ push(rsi);
1684     __ push(rdi);
1685 
1686     // bump this on entry, not on exit:
1687     inc_counter_np(SharedRuntime::_generic_array_copy_ctr);
1688 
1689     // Input values
1690     Address SRC     (rsp, 12+ 4);
1691     Address SRC_POS (rsp, 12+ 8);
1692     Address DST     (rsp, 12+12);
1693     Address DST_POS (rsp, 12+16);
1694     Address LENGTH  (rsp, 12+20);
1695 
1696     //-----------------------------------------------------------------------
1697     // Assembler stub will be used for this call to arraycopy
1698     // if the following conditions are met:
1699     //
1700     // (1) src and dst must not be null.
1701     // (2) src_pos must not be negative.
1702     // (3) dst_pos must not be negative.
1703     // (4) length  must not be negative.
1704     // (5) src klass and dst klass should be the same and not NULL.
1705     // (6) src and dst should be arrays.
1706     // (7) src_pos + length must not exceed length of src.
1707     // (8) dst_pos + length must not exceed length of dst.
1708     //
1709 
1710     const Register src     = rax;       // source array oop
1711     const Register src_pos = rsi;
1712     const Register dst     = rdx;       // destination array oop
1713     const Register dst_pos = rdi;
1714     const Register length  = rcx;       // transfer count
1715 
1716     //  if (src == NULL) return -1;
1717     __ movptr(src, SRC);      // src oop
1718     __ testptr(src, src);
1719     __ jccb(Assembler::zero, L_failed_0);
1720 
1721     //  if (src_pos < 0) return -1;
1722     __ movl2ptr(src_pos, SRC_POS);  // src_pos
1723     __ testl(src_pos, src_pos);
1724     __ jccb(Assembler::negative, L_failed_0);
1725 
1726     //  if (dst == NULL) return -1;
1727     __ movptr(dst, DST);      // dst oop
1728     __ testptr(dst, dst);
1729     __ jccb(Assembler::zero, L_failed_0);
1730 
1731     //  if (dst_pos < 0) return -1;
1732     __ movl2ptr(dst_pos, DST_POS);  // dst_pos
1733     __ testl(dst_pos, dst_pos);
1734     __ jccb(Assembler::negative, L_failed_0);
1735 
1736     //  if (length < 0) return -1;
1737     __ movl2ptr(length, LENGTH);   // length
1738     __ testl(length, length);
1739     __ jccb(Assembler::negative, L_failed_0);
1740 
1741     //  if (src->klass() == NULL) return -1;
1742     Address src_klass_addr(src, oopDesc::klass_offset_in_bytes());
1743     Address dst_klass_addr(dst, oopDesc::klass_offset_in_bytes());
1744     const Register rcx_src_klass = rcx;    // array klass
1745     __ movptr(rcx_src_klass, Address(src, oopDesc::klass_offset_in_bytes()));
1746 
1747 #ifdef ASSERT
1748     //  assert(src->klass() != NULL);
1749     BLOCK_COMMENT("assert klasses not null");
1750     { Label L1, L2;
1751       __ testptr(rcx_src_klass, rcx_src_klass);
1752       __ jccb(Assembler::notZero, L2);   // it is broken if klass is NULL
1753       __ bind(L1);
1754       __ stop("broken null klass");
1755       __ bind(L2);
1756       __ cmpptr(dst_klass_addr, (int32_t)NULL_WORD);
1757       __ jccb(Assembler::equal, L1);      // this would be broken also
1758       BLOCK_COMMENT("assert done");
1759     }
1760 #endif //ASSERT
1761 
1762     // Load layout helper (32-bits)
1763     //
1764     //  |array_tag|     | header_size | element_type |     |log2_element_size|
1765     // 32        30    24            16              8     2                 0
1766     //
1767     //   array_tag: typeArray = 0x3, objArray = 0x2, non-array = 0x0
1768     //
1769 
1770     int lh_offset = in_bytes(Klass::layout_helper_offset());
1771     Address src_klass_lh_addr(rcx_src_klass, lh_offset);
1772 
1773     // Handle objArrays completely differently...
1774     jint objArray_lh = Klass::array_layout_helper(T_OBJECT);
1775     __ cmpl(src_klass_lh_addr, objArray_lh);
1776     __ jcc(Assembler::equal, L_objArray);
1777 
1778     //  if (src->klass() != dst->klass()) return -1;
1779     __ cmpptr(rcx_src_klass, dst_klass_addr);
1780     __ jccb(Assembler::notEqual, L_failed_0);
1781 
1782     const Register rcx_lh = rcx;  // layout helper
1783     assert(rcx_lh == rcx_src_klass, "known alias");
1784     __ movl(rcx_lh, src_klass_lh_addr);
1785 
1786     //  if (!src->is_Array()) return -1;
1787     __ cmpl(rcx_lh, Klass::_lh_neutral_value);
1788     __ jcc(Assembler::greaterEqual, L_failed_0); // signed cmp
1789 
1790     // At this point, it is known to be a typeArray (array_tag 0x3).
1791 #ifdef ASSERT
1792     { Label L;
1793       __ cmpl(rcx_lh, (Klass::_lh_array_tag_type_value << Klass::_lh_array_tag_shift));
1794       __ jcc(Assembler::greaterEqual, L); // signed cmp
1795       __ stop("must be a primitive array");
1796       __ bind(L);
1797     }
1798 #endif
1799 
1800     assert_different_registers(src, src_pos, dst, dst_pos, rcx_lh);
1801     arraycopy_range_checks(src, src_pos, dst, dst_pos, LENGTH, L_failed);
1802 
1803     // TypeArrayKlass
1804     //
1805     // src_addr = (src + array_header_in_bytes()) + (src_pos << log2elemsize);
1806     // dst_addr = (dst + array_header_in_bytes()) + (dst_pos << log2elemsize);
1807     //
1808     const Register rsi_offset = rsi; // array offset
1809     const Register src_array  = src; // src array offset
1810     const Register dst_array  = dst; // dst array offset
1811     const Register rdi_elsize = rdi; // log2 element size
1812 
1813     __ mov(rsi_offset, rcx_lh);
1814     __ shrptr(rsi_offset, Klass::_lh_header_size_shift);
1815     __ andptr(rsi_offset, Klass::_lh_header_size_mask);   // array_offset
1816     __ addptr(src_array, rsi_offset);  // src array offset
1817     __ addptr(dst_array, rsi_offset);  // dst array offset
1818     __ andptr(rcx_lh, Klass::_lh_log2_element_size_mask); // log2 elsize
1819 
1820     // next registers should be set before the jump to corresponding stub
1821     const Register from       = src; // source array address
1822     const Register to         = dst; // destination array address
1823     const Register count      = rcx; // elements count
1824     // some of them should be duplicated on stack
1825 #define FROM   Address(rsp, 12+ 4)
1826 #define TO     Address(rsp, 12+ 8)   // Not used now
1827 #define COUNT  Address(rsp, 12+12)   // Only for oop arraycopy
1828 
1829     BLOCK_COMMENT("scale indexes to element size");
1830     __ movl2ptr(rsi, SRC_POS);  // src_pos
1831     __ shlptr(rsi);             // src_pos << rcx (log2 elsize)
1832     assert(src_array == from, "");
1833     __ addptr(from, rsi);       // from = src_array + SRC_POS << log2 elsize
1834     __ movl2ptr(rdi, DST_POS);  // dst_pos
1835     __ shlptr(rdi);             // dst_pos << rcx (log2 elsize)
1836     assert(dst_array == to, "");
1837     __ addptr(to,  rdi);        // to   = dst_array + DST_POS << log2 elsize
1838     __ movptr(FROM, from);      // src_addr
1839     __ mov(rdi_elsize, rcx_lh); // log2 elsize
1840     __ movl2ptr(count, LENGTH); // elements count
1841 
1842     BLOCK_COMMENT("choose copy loop based on element size");
1843     __ cmpl(rdi_elsize, 0);
1844 
1845     __ jump_cc(Assembler::equal, RuntimeAddress(entry_jbyte_arraycopy));
1846     __ cmpl(rdi_elsize, LogBytesPerShort);
1847     __ jump_cc(Assembler::equal, RuntimeAddress(entry_jshort_arraycopy));
1848     __ cmpl(rdi_elsize, LogBytesPerInt);
1849     __ jump_cc(Assembler::equal, RuntimeAddress(entry_jint_arraycopy));
1850 #ifdef ASSERT
1851     __ cmpl(rdi_elsize, LogBytesPerLong);
1852     __ jccb(Assembler::notEqual, L_failed);
1853 #endif
1854     __ pop(rdi); // Do pops here since jlong_arraycopy stub does not do it.
1855     __ pop(rsi);
1856     __ jump(RuntimeAddress(entry_jlong_arraycopy));
1857 
1858   __ BIND(L_failed);
1859     __ xorptr(rax, rax);
1860     __ notptr(rax); // return -1
1861     __ pop(rdi);
1862     __ pop(rsi);
1863     __ leave(); // required for proper stackwalking of RuntimeStub frame
1864     __ ret(0);
1865 
1866     // ObjArrayKlass
1867   __ BIND(L_objArray);
1868     // live at this point:  rcx_src_klass, src[_pos], dst[_pos]
1869 
1870     Label L_plain_copy, L_checkcast_copy;
1871     //  test array classes for subtyping
1872     __ cmpptr(rcx_src_klass, dst_klass_addr); // usual case is exact equality
1873     __ jccb(Assembler::notEqual, L_checkcast_copy);
1874 
1875     // Identically typed arrays can be copied without element-wise checks.
1876     assert_different_registers(src, src_pos, dst, dst_pos, rcx_src_klass);
1877     arraycopy_range_checks(src, src_pos, dst, dst_pos, LENGTH, L_failed);
1878 
1879   __ BIND(L_plain_copy);
1880     __ movl2ptr(count, LENGTH); // elements count
1881     __ movl2ptr(src_pos, SRC_POS);  // reload src_pos
1882     __ lea(from, Address(src, src_pos, Address::times_ptr,
1883                  arrayOopDesc::base_offset_in_bytes(T_OBJECT))); // src_addr
1884     __ movl2ptr(dst_pos, DST_POS);  // reload dst_pos
1885     __ lea(to,   Address(dst, dst_pos, Address::times_ptr,
1886                  arrayOopDesc::base_offset_in_bytes(T_OBJECT))); // dst_addr
1887     __ movptr(FROM,  from);   // src_addr
1888     __ movptr(TO,    to);     // dst_addr
1889     __ movl(COUNT, count);  // count
1890     __ jump(RuntimeAddress(entry_oop_arraycopy));
1891 
1892   __ BIND(L_checkcast_copy);
1893     // live at this point:  rcx_src_klass, dst[_pos], src[_pos]
1894     {
1895       // Handy offsets:
1896       int  ek_offset = in_bytes(ObjArrayKlass::element_klass_offset());
1897       int sco_offset = in_bytes(Klass::super_check_offset_offset());
1898 
1899       Register rsi_dst_klass = rsi;
1900       Register rdi_temp      = rdi;
1901       assert(rsi_dst_klass == src_pos, "expected alias w/ src_pos");
1902       assert(rdi_temp      == dst_pos, "expected alias w/ dst_pos");
1903       Address dst_klass_lh_addr(rsi_dst_klass, lh_offset);
1904 
1905       // Before looking at dst.length, make sure dst is also an objArray.
1906       __ movptr(rsi_dst_klass, dst_klass_addr);
1907       __ cmpl(dst_klass_lh_addr, objArray_lh);
1908       __ jccb(Assembler::notEqual, L_failed);
1909 
1910       // It is safe to examine both src.length and dst.length.
1911       __ movl2ptr(src_pos, SRC_POS);        // reload rsi
1912       arraycopy_range_checks(src, src_pos, dst, dst_pos, LENGTH, L_failed);
1913       // (Now src_pos and dst_pos are killed, but not src and dst.)
1914 
1915       // We'll need this temp (don't forget to pop it after the type check).
1916       __ push(rbx);
1917       Register rbx_src_klass = rbx;
1918 
1919       __ mov(rbx_src_klass, rcx_src_klass); // spill away from rcx
1920       __ movptr(rsi_dst_klass, dst_klass_addr);
1921       Address super_check_offset_addr(rsi_dst_klass, sco_offset);
1922       Label L_fail_array_check;
1923       generate_type_check(rbx_src_klass,
1924                           super_check_offset_addr, dst_klass_addr,
1925                           rdi_temp, NULL, &L_fail_array_check);
1926       // (On fall-through, we have passed the array type check.)
1927       __ pop(rbx);
1928       __ jmp(L_plain_copy);
1929 
1930       __ BIND(L_fail_array_check);
1931       // Reshuffle arguments so we can call checkcast_arraycopy:
1932 
1933       // match initial saves for checkcast_arraycopy
1934       // push(rsi);    // already done; see above
1935       // push(rdi);    // already done; see above
1936       // push(rbx);    // already done; see above
1937 
1938       // Marshal outgoing arguments now, freeing registers.
1939       Address   from_arg(rsp, 16+ 4);   // from
1940       Address     to_arg(rsp, 16+ 8);   // to
1941       Address length_arg(rsp, 16+12);   // elements count
1942       Address  ckoff_arg(rsp, 16+16);   // super_check_offset
1943       Address  ckval_arg(rsp, 16+20);   // super_klass
1944 
1945       Address SRC_POS_arg(rsp, 16+ 8);
1946       Address DST_POS_arg(rsp, 16+16);
1947       Address  LENGTH_arg(rsp, 16+20);
1948       // push rbx, changed the incoming offsets (why not just use rbp,??)
1949       // assert(SRC_POS_arg.disp() == SRC_POS.disp() + 4, "");
1950 
1951       __ movptr(rbx, Address(rsi_dst_klass, ek_offset));
1952       __ movl2ptr(length, LENGTH_arg);    // reload elements count
1953       __ movl2ptr(src_pos, SRC_POS_arg);  // reload src_pos
1954       __ movl2ptr(dst_pos, DST_POS_arg);  // reload dst_pos
1955 
1956       __ movptr(ckval_arg, rbx);          // destination element type
1957       __ movl(rbx, Address(rbx, sco_offset));
1958       __ movl(ckoff_arg, rbx);          // corresponding class check offset
1959 
1960       __ movl(length_arg, length);      // outgoing length argument
1961 
1962       __ lea(from, Address(src, src_pos, Address::times_ptr,
1963                             arrayOopDesc::base_offset_in_bytes(T_OBJECT)));
1964       __ movptr(from_arg, from);
1965 
1966       __ lea(to, Address(dst, dst_pos, Address::times_ptr,
1967                           arrayOopDesc::base_offset_in_bytes(T_OBJECT)));
1968       __ movptr(to_arg, to);
1969       __ jump(RuntimeAddress(entry_checkcast_arraycopy));
1970     }
1971 
1972     return start;
1973   }
1974 
1975   void generate_arraycopy_stubs() {
1976     address entry;
1977     address entry_jbyte_arraycopy;
1978     address entry_jshort_arraycopy;
1979     address entry_jint_arraycopy;
1980     address entry_oop_arraycopy;
1981     address entry_jlong_arraycopy;
1982     address entry_checkcast_arraycopy;
1983 
1984     StubRoutines::_arrayof_jbyte_disjoint_arraycopy =
1985         generate_disjoint_copy(T_BYTE,  true, Address::times_1, &entry,
1986                                "arrayof_jbyte_disjoint_arraycopy");
1987     StubRoutines::_arrayof_jbyte_arraycopy =
1988         generate_conjoint_copy(T_BYTE,  true, Address::times_1,  entry,
1989                                NULL, "arrayof_jbyte_arraycopy");
1990     StubRoutines::_jbyte_disjoint_arraycopy =
1991         generate_disjoint_copy(T_BYTE, false, Address::times_1, &entry,
1992                                "jbyte_disjoint_arraycopy");
1993     StubRoutines::_jbyte_arraycopy =
1994         generate_conjoint_copy(T_BYTE, false, Address::times_1,  entry,
1995                                &entry_jbyte_arraycopy, "jbyte_arraycopy");
1996 
1997     StubRoutines::_arrayof_jshort_disjoint_arraycopy =
1998         generate_disjoint_copy(T_SHORT,  true, Address::times_2, &entry,
1999                                "arrayof_jshort_disjoint_arraycopy");
2000     StubRoutines::_arrayof_jshort_arraycopy =
2001         generate_conjoint_copy(T_SHORT,  true, Address::times_2,  entry,
2002                                NULL, "arrayof_jshort_arraycopy");
2003     StubRoutines::_jshort_disjoint_arraycopy =
2004         generate_disjoint_copy(T_SHORT, false, Address::times_2, &entry,
2005                                "jshort_disjoint_arraycopy");
2006     StubRoutines::_jshort_arraycopy =
2007         generate_conjoint_copy(T_SHORT, false, Address::times_2,  entry,
2008                                &entry_jshort_arraycopy, "jshort_arraycopy");
2009 
2010     // Next arrays are always aligned on 4 bytes at least.
2011     StubRoutines::_jint_disjoint_arraycopy =
2012         generate_disjoint_copy(T_INT, true, Address::times_4, &entry,
2013                                "jint_disjoint_arraycopy");
2014     StubRoutines::_jint_arraycopy =
2015         generate_conjoint_copy(T_INT, true, Address::times_4,  entry,
2016                                &entry_jint_arraycopy, "jint_arraycopy");
2017 
2018     StubRoutines::_oop_disjoint_arraycopy =
2019         generate_disjoint_copy(T_OBJECT, true, Address::times_ptr, &entry,
2020                                "oop_disjoint_arraycopy");
2021     StubRoutines::_oop_arraycopy =
2022         generate_conjoint_copy(T_OBJECT, true, Address::times_ptr,  entry,
2023                                &entry_oop_arraycopy, "oop_arraycopy");
2024 
2025     StubRoutines::_oop_disjoint_arraycopy_uninit =
2026         generate_disjoint_copy(T_OBJECT, true, Address::times_ptr, &entry,
2027                                "oop_disjoint_arraycopy_uninit",
2028                                /*dest_uninitialized*/true);
2029     StubRoutines::_oop_arraycopy_uninit =
2030         generate_conjoint_copy(T_OBJECT, true, Address::times_ptr,  entry,
2031                                NULL, "oop_arraycopy_uninit",
2032                                /*dest_uninitialized*/true);
2033 
2034     StubRoutines::_jlong_disjoint_arraycopy =
2035         generate_disjoint_long_copy(&entry, "jlong_disjoint_arraycopy");
2036     StubRoutines::_jlong_arraycopy =
2037         generate_conjoint_long_copy(entry, &entry_jlong_arraycopy,
2038                                     "jlong_arraycopy");
2039 
2040     StubRoutines::_jbyte_fill = generate_fill(T_BYTE, false, "jbyte_fill");
2041     StubRoutines::_jshort_fill = generate_fill(T_SHORT, false, "jshort_fill");
2042     StubRoutines::_jint_fill = generate_fill(T_INT, false, "jint_fill");
2043     StubRoutines::_arrayof_jbyte_fill = generate_fill(T_BYTE, true, "arrayof_jbyte_fill");
2044     StubRoutines::_arrayof_jshort_fill = generate_fill(T_SHORT, true, "arrayof_jshort_fill");
2045     StubRoutines::_arrayof_jint_fill = generate_fill(T_INT, true, "arrayof_jint_fill");
2046 
2047     StubRoutines::_arrayof_jint_disjoint_arraycopy       = StubRoutines::_jint_disjoint_arraycopy;
2048     StubRoutines::_arrayof_oop_disjoint_arraycopy        = StubRoutines::_oop_disjoint_arraycopy;
2049     StubRoutines::_arrayof_oop_disjoint_arraycopy_uninit = StubRoutines::_oop_disjoint_arraycopy_uninit;
2050     StubRoutines::_arrayof_jlong_disjoint_arraycopy      = StubRoutines::_jlong_disjoint_arraycopy;
2051 
2052     StubRoutines::_arrayof_jint_arraycopy       = StubRoutines::_jint_arraycopy;
2053     StubRoutines::_arrayof_oop_arraycopy        = StubRoutines::_oop_arraycopy;
2054     StubRoutines::_arrayof_oop_arraycopy_uninit = StubRoutines::_oop_arraycopy_uninit;
2055     StubRoutines::_arrayof_jlong_arraycopy      = StubRoutines::_jlong_arraycopy;
2056 
2057     StubRoutines::_checkcast_arraycopy =
2058         generate_checkcast_copy("checkcast_arraycopy", &entry_checkcast_arraycopy);
2059     StubRoutines::_checkcast_arraycopy_uninit =
2060         generate_checkcast_copy("checkcast_arraycopy_uninit", NULL, /*dest_uninitialized*/true);
2061 
2062     StubRoutines::_unsafe_arraycopy =
2063         generate_unsafe_copy("unsafe_arraycopy",
2064                                entry_jbyte_arraycopy,
2065                                entry_jshort_arraycopy,
2066                                entry_jint_arraycopy,
2067                                entry_jlong_arraycopy);
2068 
2069     StubRoutines::_generic_arraycopy =
2070         generate_generic_copy("generic_arraycopy",
2071                                entry_jbyte_arraycopy,
2072                                entry_jshort_arraycopy,
2073                                entry_jint_arraycopy,
2074                                entry_oop_arraycopy,
2075                                entry_jlong_arraycopy,
2076                                entry_checkcast_arraycopy);
2077   }
2078 
2079   // AES intrinsic stubs
2080   enum {AESBlockSize = 16};
2081 
2082   address generate_key_shuffle_mask() {
2083     __ align(16);
2084     StubCodeMark mark(this, "StubRoutines", "key_shuffle_mask");
2085     address start = __ pc();
2086     __ emit_data(0x00010203, relocInfo::none, 0 );
2087     __ emit_data(0x04050607, relocInfo::none, 0 );
2088     __ emit_data(0x08090a0b, relocInfo::none, 0 );
2089     __ emit_data(0x0c0d0e0f, relocInfo::none, 0 );
2090     return start;
2091   }
2092 
2093   address generate_counter_shuffle_mask() {
2094     __ align(16);
2095     StubCodeMark mark(this, "StubRoutines", "counter_shuffle_mask");
2096     address start = __ pc();
2097     __ emit_data(0x0c0d0e0f, relocInfo::none, 0);
2098     __ emit_data(0x08090a0b, relocInfo::none, 0);
2099     __ emit_data(0x04050607, relocInfo::none, 0);
2100     __ emit_data(0x00010203, relocInfo::none, 0);
2101     return start;
2102   }
2103 
2104   // Utility routine for loading a 128-bit key word in little endian format
2105   // can optionally specify that the shuffle mask is already in an xmmregister
2106   void load_key(XMMRegister xmmdst, Register key, int offset, XMMRegister xmm_shuf_mask=NULL) {
2107     __ movdqu(xmmdst, Address(key, offset));
2108     if (xmm_shuf_mask != NULL) {
2109       __ pshufb(xmmdst, xmm_shuf_mask);
2110     } else {
2111       __ pshufb(xmmdst, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2112     }
2113   }
2114 
2115   // aesenc using specified key+offset
2116   // can optionally specify that the shuffle mask is already in an xmmregister
2117   void aes_enc_key(XMMRegister xmmdst, XMMRegister xmmtmp, Register key, int offset, XMMRegister xmm_shuf_mask=NULL) {
2118     load_key(xmmtmp, key, offset, xmm_shuf_mask);
2119     __ aesenc(xmmdst, xmmtmp);
2120   }
2121 
2122   // aesdec using specified key+offset
2123   // can optionally specify that the shuffle mask is already in an xmmregister
2124   void aes_dec_key(XMMRegister xmmdst, XMMRegister xmmtmp, Register key, int offset, XMMRegister xmm_shuf_mask=NULL) {
2125     load_key(xmmtmp, key, offset, xmm_shuf_mask);
2126     __ aesdec(xmmdst, xmmtmp);
2127   }
2128 
2129   // Utility routine for increase 128bit counter (iv in CTR mode)
2130   //  XMM_128bit,  D3, D2, D1, D0
2131   void inc_counter(Register reg, XMMRegister xmmdst, int inc_delta, Label& next_block) {
2132     __ pextrd(reg, xmmdst, 0x0);
2133     __ addl(reg, inc_delta);
2134     __ pinsrd(xmmdst, reg, 0x0);
2135     __ jcc(Assembler::carryClear, next_block); // jump if no carry
2136 
2137     __ pextrd(reg, xmmdst, 0x01); // Carry-> D1
2138     __ addl(reg, 0x01);
2139     __ pinsrd(xmmdst, reg, 0x01);
2140     __ jcc(Assembler::carryClear, next_block); // jump if no carry
2141 
2142     __ pextrd(reg, xmmdst, 0x02); // Carry-> D2
2143     __ addl(reg, 0x01);
2144     __ pinsrd(xmmdst, reg, 0x02);
2145     __ jcc(Assembler::carryClear, next_block); // jump if no carry
2146 
2147     __ pextrd(reg, xmmdst, 0x03); // Carry -> D3
2148     __ addl(reg, 0x01);
2149     __ pinsrd(xmmdst, reg, 0x03);
2150 
2151     __ BIND(next_block);          // next instruction
2152   }
2153 
2154 
2155   // Arguments:
2156   //
2157   // Inputs:
2158   //   c_rarg0   - source byte array address
2159   //   c_rarg1   - destination byte array address
2160   //   c_rarg2   - K (key) in little endian int array
2161   //
2162   address generate_aescrypt_encryptBlock() {
2163     assert(UseAES, "need AES instructions and misaligned SSE support");
2164     __ align(CodeEntryAlignment);
2165     StubCodeMark mark(this, "StubRoutines", "aescrypt_encryptBlock");
2166     Label L_doLast;
2167     address start = __ pc();
2168 
2169     const Register from        = rdx;      // source array address
2170     const Register to          = rdx;      // destination array address
2171     const Register key         = rcx;      // key array address
2172     const Register keylen      = rax;
2173     const Address  from_param(rbp, 8+0);
2174     const Address  to_param  (rbp, 8+4);
2175     const Address  key_param (rbp, 8+8);
2176 
2177     const XMMRegister xmm_result = xmm0;
2178     const XMMRegister xmm_key_shuf_mask = xmm1;
2179     const XMMRegister xmm_temp1  = xmm2;
2180     const XMMRegister xmm_temp2  = xmm3;
2181     const XMMRegister xmm_temp3  = xmm4;
2182     const XMMRegister xmm_temp4  = xmm5;
2183 
2184     __ enter();   // required for proper stackwalking of RuntimeStub frame
2185 
2186     __ movptr(from, from_param);
2187     __ movptr(key, key_param);
2188 
2189     // keylen could be only {11, 13, 15} * 4 = {44, 52, 60}
2190     __ movl(keylen, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT)));
2191 
2192     __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2193     __ movdqu(xmm_result, Address(from, 0));  // get 16 bytes of input
2194     __ movptr(to, to_param);
2195 
2196     // For encryption, the java expanded key ordering is just what we need
2197 
2198     load_key(xmm_temp1, key, 0x00, xmm_key_shuf_mask);
2199     __ pxor(xmm_result, xmm_temp1);
2200 
2201     load_key(xmm_temp1, key, 0x10, xmm_key_shuf_mask);
2202     load_key(xmm_temp2, key, 0x20, xmm_key_shuf_mask);
2203     load_key(xmm_temp3, key, 0x30, xmm_key_shuf_mask);
2204     load_key(xmm_temp4, key, 0x40, xmm_key_shuf_mask);
2205 
2206     __ aesenc(xmm_result, xmm_temp1);
2207     __ aesenc(xmm_result, xmm_temp2);
2208     __ aesenc(xmm_result, xmm_temp3);
2209     __ aesenc(xmm_result, xmm_temp4);
2210 
2211     load_key(xmm_temp1, key, 0x50, xmm_key_shuf_mask);
2212     load_key(xmm_temp2, key, 0x60, xmm_key_shuf_mask);
2213     load_key(xmm_temp3, key, 0x70, xmm_key_shuf_mask);
2214     load_key(xmm_temp4, key, 0x80, xmm_key_shuf_mask);
2215 
2216     __ aesenc(xmm_result, xmm_temp1);
2217     __ aesenc(xmm_result, xmm_temp2);
2218     __ aesenc(xmm_result, xmm_temp3);
2219     __ aesenc(xmm_result, xmm_temp4);
2220 
2221     load_key(xmm_temp1, key, 0x90, xmm_key_shuf_mask);
2222     load_key(xmm_temp2, key, 0xa0, xmm_key_shuf_mask);
2223 
2224     __ cmpl(keylen, 44);
2225     __ jccb(Assembler::equal, L_doLast);
2226 
2227     __ aesenc(xmm_result, xmm_temp1);
2228     __ aesenc(xmm_result, xmm_temp2);
2229 
2230     load_key(xmm_temp1, key, 0xb0, xmm_key_shuf_mask);
2231     load_key(xmm_temp2, key, 0xc0, xmm_key_shuf_mask);
2232 
2233     __ cmpl(keylen, 52);
2234     __ jccb(Assembler::equal, L_doLast);
2235 
2236     __ aesenc(xmm_result, xmm_temp1);
2237     __ aesenc(xmm_result, xmm_temp2);
2238 
2239     load_key(xmm_temp1, key, 0xd0, xmm_key_shuf_mask);
2240     load_key(xmm_temp2, key, 0xe0, xmm_key_shuf_mask);
2241 
2242     __ BIND(L_doLast);
2243     __ aesenc(xmm_result, xmm_temp1);
2244     __ aesenclast(xmm_result, xmm_temp2);
2245     __ movdqu(Address(to, 0), xmm_result);        // store the result
2246     __ xorptr(rax, rax); // return 0
2247     __ leave(); // required for proper stackwalking of RuntimeStub frame
2248     __ ret(0);
2249 
2250     return start;
2251   }
2252 
2253 
2254   // Arguments:
2255   //
2256   // Inputs:
2257   //   c_rarg0   - source byte array address
2258   //   c_rarg1   - destination byte array address
2259   //   c_rarg2   - K (key) in little endian int array
2260   //
2261   address generate_aescrypt_decryptBlock() {
2262     assert(UseAES, "need AES instructions and misaligned SSE support");
2263     __ align(CodeEntryAlignment);
2264     StubCodeMark mark(this, "StubRoutines", "aescrypt_decryptBlock");
2265     Label L_doLast;
2266     address start = __ pc();
2267 
2268     const Register from        = rdx;      // source array address
2269     const Register to          = rdx;      // destination array address
2270     const Register key         = rcx;      // key array address
2271     const Register keylen      = rax;
2272     const Address  from_param(rbp, 8+0);
2273     const Address  to_param  (rbp, 8+4);
2274     const Address  key_param (rbp, 8+8);
2275 
2276     const XMMRegister xmm_result = xmm0;
2277     const XMMRegister xmm_key_shuf_mask = xmm1;
2278     const XMMRegister xmm_temp1  = xmm2;
2279     const XMMRegister xmm_temp2  = xmm3;
2280     const XMMRegister xmm_temp3  = xmm4;
2281     const XMMRegister xmm_temp4  = xmm5;
2282 
2283     __ enter(); // required for proper stackwalking of RuntimeStub frame
2284 
2285     __ movptr(from, from_param);
2286     __ movptr(key, key_param);
2287 
2288     // keylen could be only {11, 13, 15} * 4 = {44, 52, 60}
2289     __ movl(keylen, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT)));
2290 
2291     __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2292     __ movdqu(xmm_result, Address(from, 0));
2293     __ movptr(to, to_param);
2294 
2295     // for decryption java expanded key ordering is rotated one position from what we want
2296     // so we start from 0x10 here and hit 0x00 last
2297     // we don't know if the key is aligned, hence not using load-execute form
2298     load_key(xmm_temp1, key, 0x10, xmm_key_shuf_mask);
2299     load_key(xmm_temp2, key, 0x20, xmm_key_shuf_mask);
2300     load_key(xmm_temp3, key, 0x30, xmm_key_shuf_mask);
2301     load_key(xmm_temp4, key, 0x40, xmm_key_shuf_mask);
2302 
2303     __ pxor  (xmm_result, xmm_temp1);
2304     __ aesdec(xmm_result, xmm_temp2);
2305     __ aesdec(xmm_result, xmm_temp3);
2306     __ aesdec(xmm_result, xmm_temp4);
2307 
2308     load_key(xmm_temp1, key, 0x50, xmm_key_shuf_mask);
2309     load_key(xmm_temp2, key, 0x60, xmm_key_shuf_mask);
2310     load_key(xmm_temp3, key, 0x70, xmm_key_shuf_mask);
2311     load_key(xmm_temp4, key, 0x80, xmm_key_shuf_mask);
2312 
2313     __ aesdec(xmm_result, xmm_temp1);
2314     __ aesdec(xmm_result, xmm_temp2);
2315     __ aesdec(xmm_result, xmm_temp3);
2316     __ aesdec(xmm_result, xmm_temp4);
2317 
2318     load_key(xmm_temp1, key, 0x90, xmm_key_shuf_mask);
2319     load_key(xmm_temp2, key, 0xa0, xmm_key_shuf_mask);
2320     load_key(xmm_temp3, key, 0x00, xmm_key_shuf_mask);
2321 
2322     __ cmpl(keylen, 44);
2323     __ jccb(Assembler::equal, L_doLast);
2324 
2325     __ aesdec(xmm_result, xmm_temp1);
2326     __ aesdec(xmm_result, xmm_temp2);
2327 
2328     load_key(xmm_temp1, key, 0xb0, xmm_key_shuf_mask);
2329     load_key(xmm_temp2, key, 0xc0, xmm_key_shuf_mask);
2330 
2331     __ cmpl(keylen, 52);
2332     __ jccb(Assembler::equal, L_doLast);
2333 
2334     __ aesdec(xmm_result, xmm_temp1);
2335     __ aesdec(xmm_result, xmm_temp2);
2336 
2337     load_key(xmm_temp1, key, 0xd0, xmm_key_shuf_mask);
2338     load_key(xmm_temp2, key, 0xe0, xmm_key_shuf_mask);
2339 
2340     __ BIND(L_doLast);
2341     __ aesdec(xmm_result, xmm_temp1);
2342     __ aesdec(xmm_result, xmm_temp2);
2343 
2344     // for decryption the aesdeclast operation is always on key+0x00
2345     __ aesdeclast(xmm_result, xmm_temp3);
2346     __ movdqu(Address(to, 0), xmm_result);  // store the result
2347     __ xorptr(rax, rax); // return 0
2348     __ leave(); // required for proper stackwalking of RuntimeStub frame
2349     __ ret(0);
2350 
2351     return start;
2352   }
2353 
2354   void handleSOERegisters(bool saving) {
2355     const int saveFrameSizeInBytes = 4 * wordSize;
2356     const Address saved_rbx     (rbp, -3 * wordSize);
2357     const Address saved_rsi     (rbp, -2 * wordSize);
2358     const Address saved_rdi     (rbp, -1 * wordSize);
2359 
2360     if (saving) {
2361       __ subptr(rsp, saveFrameSizeInBytes);
2362       __ movptr(saved_rsi, rsi);
2363       __ movptr(saved_rdi, rdi);
2364       __ movptr(saved_rbx, rbx);
2365     } else {
2366       // restoring
2367       __ movptr(rsi, saved_rsi);
2368       __ movptr(rdi, saved_rdi);
2369       __ movptr(rbx, saved_rbx);
2370     }
2371   }
2372 
2373   // Arguments:
2374   //
2375   // Inputs:
2376   //   c_rarg0   - source byte array address
2377   //   c_rarg1   - destination byte array address
2378   //   c_rarg2   - K (key) in little endian int array
2379   //   c_rarg3   - r vector byte array address
2380   //   c_rarg4   - input length
2381   //
2382   // Output:
2383   //   rax       - input length
2384   //
2385   address generate_cipherBlockChaining_encryptAESCrypt() {
2386     assert(UseAES, "need AES instructions and misaligned SSE support");
2387     __ align(CodeEntryAlignment);
2388     StubCodeMark mark(this, "StubRoutines", "cipherBlockChaining_encryptAESCrypt");
2389     address start = __ pc();
2390 
2391     Label L_exit, L_key_192_256, L_key_256, L_loopTop_128, L_loopTop_192, L_loopTop_256;
2392     const Register from        = rsi;      // source array address
2393     const Register to          = rdx;      // destination array address
2394     const Register key         = rcx;      // key array address
2395     const Register rvec        = rdi;      // r byte array initialized from initvector array address
2396                                            // and left with the results of the last encryption block
2397     const Register len_reg     = rbx;      // src len (must be multiple of blocksize 16)
2398     const Register pos         = rax;
2399 
2400     // xmm register assignments for the loops below
2401     const XMMRegister xmm_result = xmm0;
2402     const XMMRegister xmm_temp   = xmm1;
2403     // first 6 keys preloaded into xmm2-xmm7
2404     const int XMM_REG_NUM_KEY_FIRST = 2;
2405     const int XMM_REG_NUM_KEY_LAST  = 7;
2406     const XMMRegister xmm_key0   = as_XMMRegister(XMM_REG_NUM_KEY_FIRST);
2407 
2408     __ enter(); // required for proper stackwalking of RuntimeStub frame
2409     handleSOERegisters(true /*saving*/);
2410 
2411     // load registers from incoming parameters
2412     const Address  from_param(rbp, 8+0);
2413     const Address  to_param  (rbp, 8+4);
2414     const Address  key_param (rbp, 8+8);
2415     const Address  rvec_param (rbp, 8+12);
2416     const Address  len_param  (rbp, 8+16);
2417     __ movptr(from , from_param);
2418     __ movptr(to   , to_param);
2419     __ movptr(key  , key_param);
2420     __ movptr(rvec , rvec_param);
2421     __ movptr(len_reg , len_param);
2422 
2423     const XMMRegister xmm_key_shuf_mask = xmm_temp;  // used temporarily to swap key bytes up front
2424     __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2425     // load up xmm regs 2 thru 7 with keys 0-5
2426     for (int rnum = XMM_REG_NUM_KEY_FIRST, offset = 0x00; rnum  <= XMM_REG_NUM_KEY_LAST; rnum++) {
2427       load_key(as_XMMRegister(rnum), key, offset, xmm_key_shuf_mask);
2428       offset += 0x10;
2429     }
2430 
2431     __ movdqu(xmm_result, Address(rvec, 0x00));   // initialize xmm_result with r vec
2432 
2433     // now split to different paths depending on the keylen (len in ints of AESCrypt.KLE array (52=192, or 60=256))
2434     __ movl(rax, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT)));
2435     __ cmpl(rax, 44);
2436     __ jcc(Assembler::notEqual, L_key_192_256);
2437 
2438     // 128 bit code follows here
2439     __ movl(pos, 0);
2440     __ align(OptoLoopAlignment);
2441     __ BIND(L_loopTop_128);
2442     __ movdqu(xmm_temp, Address(from, pos, Address::times_1, 0));   // get next 16 bytes of input
2443     __ pxor  (xmm_result, xmm_temp);                                // xor with the current r vector
2444 
2445     __ pxor  (xmm_result, xmm_key0);                                // do the aes rounds
2446     for (int rnum = XMM_REG_NUM_KEY_FIRST + 1; rnum  <= XMM_REG_NUM_KEY_LAST; rnum++) {
2447       __ aesenc(xmm_result, as_XMMRegister(rnum));
2448     }
2449     for (int key_offset = 0x60; key_offset <= 0x90; key_offset += 0x10) {
2450       aes_enc_key(xmm_result, xmm_temp, key, key_offset);
2451     }
2452     load_key(xmm_temp, key, 0xa0);
2453     __ aesenclast(xmm_result, xmm_temp);
2454 
2455     __ movdqu(Address(to, pos, Address::times_1, 0), xmm_result);     // store into the next 16 bytes of output
2456     // no need to store r to memory until we exit
2457     __ addptr(pos, AESBlockSize);
2458     __ subptr(len_reg, AESBlockSize);
2459     __ jcc(Assembler::notEqual, L_loopTop_128);
2460 
2461     __ BIND(L_exit);
2462     __ movdqu(Address(rvec, 0), xmm_result);     // final value of r stored in rvec of CipherBlockChaining object
2463 
2464     handleSOERegisters(false /*restoring*/);
2465     __ movptr(rax, len_param); // return length
2466     __ leave();                                  // required for proper stackwalking of RuntimeStub frame
2467     __ ret(0);
2468 
2469     __ BIND(L_key_192_256);
2470     // here rax = len in ints of AESCrypt.KLE array (52=192, or 60=256)
2471     __ cmpl(rax, 52);
2472     __ jcc(Assembler::notEqual, L_key_256);
2473 
2474     // 192-bit code follows here (could be changed to use more xmm registers)
2475     __ movl(pos, 0);
2476     __ align(OptoLoopAlignment);
2477     __ BIND(L_loopTop_192);
2478     __ movdqu(xmm_temp, Address(from, pos, Address::times_1, 0));   // get next 16 bytes of input
2479     __ pxor  (xmm_result, xmm_temp);                                // xor with the current r vector
2480 
2481     __ pxor  (xmm_result, xmm_key0);                                // do the aes rounds
2482     for (int rnum = XMM_REG_NUM_KEY_FIRST + 1; rnum  <= XMM_REG_NUM_KEY_LAST; rnum++) {
2483       __ aesenc(xmm_result, as_XMMRegister(rnum));
2484     }
2485     for (int key_offset = 0x60; key_offset <= 0xb0; key_offset += 0x10) {
2486       aes_enc_key(xmm_result, xmm_temp, key, key_offset);
2487     }
2488     load_key(xmm_temp, key, 0xc0);
2489     __ aesenclast(xmm_result, xmm_temp);
2490 
2491     __ movdqu(Address(to, pos, Address::times_1, 0), xmm_result);   // store into the next 16 bytes of output
2492     // no need to store r to memory until we exit
2493     __ addptr(pos, AESBlockSize);
2494     __ subptr(len_reg, AESBlockSize);
2495     __ jcc(Assembler::notEqual, L_loopTop_192);
2496     __ jmp(L_exit);
2497 
2498     __ BIND(L_key_256);
2499     // 256-bit code follows here (could be changed to use more xmm registers)
2500     __ movl(pos, 0);
2501     __ align(OptoLoopAlignment);
2502     __ BIND(L_loopTop_256);
2503     __ movdqu(xmm_temp, Address(from, pos, Address::times_1, 0));   // get next 16 bytes of input
2504     __ pxor  (xmm_result, xmm_temp);                                // xor with the current r vector
2505 
2506     __ pxor  (xmm_result, xmm_key0);                                // do the aes rounds
2507     for (int rnum = XMM_REG_NUM_KEY_FIRST + 1; rnum  <= XMM_REG_NUM_KEY_LAST; rnum++) {
2508       __ aesenc(xmm_result, as_XMMRegister(rnum));
2509     }
2510     for (int key_offset = 0x60; key_offset <= 0xd0; key_offset += 0x10) {
2511       aes_enc_key(xmm_result, xmm_temp, key, key_offset);
2512     }
2513     load_key(xmm_temp, key, 0xe0);
2514     __ aesenclast(xmm_result, xmm_temp);
2515 
2516     __ movdqu(Address(to, pos, Address::times_1, 0), xmm_result);   // store into the next 16 bytes of output
2517     // no need to store r to memory until we exit
2518     __ addptr(pos, AESBlockSize);
2519     __ subptr(len_reg, AESBlockSize);
2520     __ jcc(Assembler::notEqual, L_loopTop_256);
2521     __ jmp(L_exit);
2522 
2523     return start;
2524   }
2525 
2526 
2527   // CBC AES Decryption.
2528   // In 32-bit stub, because of lack of registers we do not try to parallelize 4 blocks at a time.
2529   //
2530   // Arguments:
2531   //
2532   // Inputs:
2533   //   c_rarg0   - source byte array address
2534   //   c_rarg1   - destination byte array address
2535   //   c_rarg2   - K (key) in little endian int array
2536   //   c_rarg3   - r vector byte array address
2537   //   c_rarg4   - input length
2538   //
2539   // Output:
2540   //   rax       - input length
2541   //
2542 
2543   address generate_cipherBlockChaining_decryptAESCrypt_Parallel() {
2544     assert(UseAES, "need AES instructions and misaligned SSE support");
2545     __ align(CodeEntryAlignment);
2546     StubCodeMark mark(this, "StubRoutines", "cipherBlockChaining_decryptAESCrypt");
2547     address start = __ pc();
2548 
2549     const Register from        = rsi;      // source array address
2550     const Register to          = rdx;      // destination array address
2551     const Register key         = rcx;      // key array address
2552     const Register rvec        = rdi;      // r byte array initialized from initvector array address
2553                                            // and left with the results of the last encryption block
2554     const Register len_reg     = rbx;      // src len (must be multiple of blocksize 16)
2555     const Register pos         = rax;
2556 
2557     const int PARALLEL_FACTOR = 4;
2558     const int ROUNDS[3] = { 10, 12, 14 }; //aes rounds for key128, key192, key256
2559 
2560     Label L_exit;
2561     Label L_singleBlock_loopTop[3]; //128, 192, 256
2562     Label L_multiBlock_loopTop[3]; //128, 192, 256
2563 
2564     const XMMRegister xmm_prev_block_cipher = xmm0; // holds cipher of previous block
2565     const XMMRegister xmm_key_shuf_mask = xmm1;
2566 
2567     const XMMRegister xmm_key_tmp0 = xmm2;
2568     const XMMRegister xmm_key_tmp1 = xmm3;
2569 
2570     // registers holding the six results in the parallelized loop
2571     const XMMRegister xmm_result0 = xmm4;
2572     const XMMRegister xmm_result1 = xmm5;
2573     const XMMRegister xmm_result2 = xmm6;
2574     const XMMRegister xmm_result3 = xmm7;
2575 
2576     __ enter(); // required for proper stackwalking of RuntimeStub frame
2577     handleSOERegisters(true /*saving*/);
2578 
2579     // load registers from incoming parameters
2580     const Address  from_param(rbp, 8+0);
2581     const Address  to_param  (rbp, 8+4);
2582     const Address  key_param (rbp, 8+8);
2583     const Address  rvec_param (rbp, 8+12);
2584     const Address  len_param  (rbp, 8+16);
2585 
2586     __ movptr(from , from_param);
2587     __ movptr(to   , to_param);
2588     __ movptr(key  , key_param);
2589     __ movptr(rvec , rvec_param);
2590     __ movptr(len_reg , len_param);
2591 
2592     __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2593     __ movdqu(xmm_prev_block_cipher, Address(rvec, 0x00)); // initialize with initial rvec
2594 
2595     __ xorptr(pos, pos);
2596 
2597     // now split to different paths depending on the keylen (len in ints of AESCrypt.KLE array (52=192, or 60=256))
2598     // rvec is reused
2599     __ movl(rvec, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT)));
2600     __ cmpl(rvec, 52);
2601     __ jcc(Assembler::equal, L_multiBlock_loopTop[1]);
2602     __ cmpl(rvec, 60);
2603     __ jcc(Assembler::equal, L_multiBlock_loopTop[2]);
2604 
2605 #define DoFour(opc, src_reg)           \
2606   __ opc(xmm_result0, src_reg);         \
2607   __ opc(xmm_result1, src_reg);         \
2608   __ opc(xmm_result2, src_reg);         \
2609   __ opc(xmm_result3, src_reg);         \
2610 
2611     for (int k = 0; k < 3; ++k) {
2612       __ align(OptoLoopAlignment);
2613       __ BIND(L_multiBlock_loopTop[k]);
2614       __ cmpptr(len_reg, PARALLEL_FACTOR * AESBlockSize); // see if at least 4 blocks left
2615       __ jcc(Assembler::less, L_singleBlock_loopTop[k]);
2616 
2617       __ movdqu(xmm_result0, Address(from, pos, Address::times_1, 0 * AESBlockSize)); // get next 4 blocks into xmmresult registers
2618       __ movdqu(xmm_result1, Address(from, pos, Address::times_1, 1 * AESBlockSize));
2619       __ movdqu(xmm_result2, Address(from, pos, Address::times_1, 2 * AESBlockSize));
2620       __ movdqu(xmm_result3, Address(from, pos, Address::times_1, 3 * AESBlockSize));
2621 
2622       // the java expanded key ordering is rotated one position from what we want
2623       // so we start from 0x10 here and hit 0x00 last
2624       load_key(xmm_key_tmp0, key, 0x10, xmm_key_shuf_mask);
2625       DoFour(pxor, xmm_key_tmp0); //xor with first key
2626       // do the aes dec rounds
2627       for (int rnum = 1; rnum <= ROUNDS[k];) {
2628         //load two keys at a time
2629         //k1->0x20, ..., k9->0xa0, k10->0x00
2630         load_key(xmm_key_tmp1, key, (rnum + 1) * 0x10, xmm_key_shuf_mask);
2631         load_key(xmm_key_tmp0, key, ((rnum + 2) % (ROUNDS[k] + 1)) * 0x10, xmm_key_shuf_mask); // hit 0x00 last!
2632         DoFour(aesdec, xmm_key_tmp1);
2633         rnum++;
2634         if (rnum != ROUNDS[k]) {
2635           DoFour(aesdec, xmm_key_tmp0);
2636         }
2637         else {
2638           DoFour(aesdeclast, xmm_key_tmp0);
2639         }
2640         rnum++;
2641       }
2642 
2643       // for each result, xor with the r vector of previous cipher block
2644       __ pxor(xmm_result0, xmm_prev_block_cipher);
2645       __ movdqu(xmm_prev_block_cipher, Address(from, pos, Address::times_1, 0 * AESBlockSize));
2646       __ pxor(xmm_result1, xmm_prev_block_cipher);
2647       __ movdqu(xmm_prev_block_cipher, Address(from, pos, Address::times_1, 1 * AESBlockSize));
2648       __ pxor(xmm_result2, xmm_prev_block_cipher);
2649       __ movdqu(xmm_prev_block_cipher, Address(from, pos, Address::times_1, 2 * AESBlockSize));
2650       __ pxor(xmm_result3, xmm_prev_block_cipher);
2651       __ movdqu(xmm_prev_block_cipher, Address(from, pos, Address::times_1, 3 * AESBlockSize)); // this will carry over to next set of blocks
2652 
2653             // store 4 results into the next 64 bytes of output
2654        __ movdqu(Address(to, pos, Address::times_1, 0 * AESBlockSize), xmm_result0);
2655        __ movdqu(Address(to, pos, Address::times_1, 1 * AESBlockSize), xmm_result1);
2656        __ movdqu(Address(to, pos, Address::times_1, 2 * AESBlockSize), xmm_result2);
2657        __ movdqu(Address(to, pos, Address::times_1, 3 * AESBlockSize), xmm_result3);
2658 
2659        __ addptr(pos, 4 * AESBlockSize);
2660        __ subptr(len_reg, 4 * AESBlockSize);
2661        __ jmp(L_multiBlock_loopTop[k]);
2662 
2663        //singleBlock starts here
2664        __ align(OptoLoopAlignment);
2665        __ BIND(L_singleBlock_loopTop[k]);
2666        __ cmpptr(len_reg, 0); // any blocks left?
2667        __ jcc(Assembler::equal, L_exit);
2668        __ movdqu(xmm_result0, Address(from, pos, Address::times_1, 0)); // get next 16 bytes of cipher input
2669        __ movdqa(xmm_result1, xmm_result0);
2670 
2671        load_key(xmm_key_tmp0, key, 0x10, xmm_key_shuf_mask);
2672        __ pxor(xmm_result0, xmm_key_tmp0);
2673        // do the aes dec rounds
2674        for (int rnum = 1; rnum < ROUNDS[k]; rnum++) {
2675          // the java expanded key ordering is rotated one position from what we want
2676          load_key(xmm_key_tmp0, key, (rnum + 1) * 0x10, xmm_key_shuf_mask);
2677          __ aesdec(xmm_result0, xmm_key_tmp0);
2678        }
2679        load_key(xmm_key_tmp0, key, 0x00, xmm_key_shuf_mask);
2680        __ aesdeclast(xmm_result0, xmm_key_tmp0);
2681        __ pxor(xmm_result0, xmm_prev_block_cipher); // xor with the current r vector
2682        __ movdqu(Address(to, pos, Address::times_1, 0), xmm_result0); // store into the next 16 bytes of output
2683        // no need to store r to memory until we exit
2684        __ movdqa(xmm_prev_block_cipher, xmm_result1); // set up next r vector with cipher input from this block
2685 
2686        __ addptr(pos, AESBlockSize);
2687        __ subptr(len_reg, AESBlockSize);
2688        __ jmp(L_singleBlock_loopTop[k]);
2689     }//for 128/192/256
2690 
2691     __ BIND(L_exit);
2692     __ movptr(rvec, rvec_param);                        // restore this since reused earlier
2693     __ movdqu(Address(rvec, 0), xmm_prev_block_cipher); // final value of r stored in rvec of CipherBlockChaining object
2694     handleSOERegisters(false /*restoring*/);
2695     __ movptr(rax, len_param);                          // return length
2696     __ leave();                                         // required for proper stackwalking of RuntimeStub frame
2697     __ ret(0);
2698 
2699     return start;
2700   }
2701 
2702   // CTR AES crypt.
2703   // In 32-bit stub, parallelize 4 blocks at a time
2704   // Arguments:
2705   //
2706   // Inputs:
2707   //   c_rarg0   - source byte array address
2708   //   c_rarg1   - destination byte array address
2709   //   c_rarg2   - K (key) in little endian int array
2710   //   c_rarg3   - counter vector byte array address
2711   //   c_rarg4   - input length
2712   //
2713   // Output:
2714   //   rax       - input length
2715   //
2716   address generate_counterMode_AESCrypt_Parallel() {
2717     assert(UseAES, "need AES instructions and misaligned SSE support");
2718     __ align(CodeEntryAlignment);
2719     StubCodeMark mark(this, "StubRoutines", "counterMode_AESCrypt");
2720     address start = __ pc();
2721     const Register from        = rsi;      // source array address
2722     const Register to          = rdx;      // destination array address
2723     const Register key         = rcx;      // key array address
2724     const Register counter     = rdi;      // counter byte array initialized from initvector array address
2725                                            // and updated with the incremented counter in the end
2726     const Register len_reg     = rbx;
2727     const Register pos         = rax;
2728 
2729     __ enter(); // required for proper stackwalking of RuntimeStub frame
2730     handleSOERegisters(true /*saving*/); // save rbx, rsi, rdi
2731 
2732     // load registers from incoming parameters
2733     const Address  from_param(rbp, 8+0);
2734     const Address  to_param  (rbp, 8+4);
2735     const Address  key_param (rbp, 8+8);
2736     const Address  rvec_param (rbp, 8+12);
2737     const Address  len_param  (rbp, 8+16);
2738     const Address  saved_counter_param(rbp, 8 + 20);
2739     const Address  used_addr_param(rbp, 8 + 24);
2740 
2741     __ movptr(from , from_param);
2742     __ movptr(to   , to_param);
2743     __ movptr(len_reg , len_param);
2744 
2745     // Use the partially used encrpyted counter from last invocation
2746     Label L_exit_preLoop, L_preLoop_start;
2747 
2748     // Use the registers 'counter' and 'key' here in this preloop
2749     // to hold of last 2 params 'used' and 'saved_encCounter_start'
2750     Register used = counter;
2751     Register saved_encCounter_start = key;
2752     Register used_addr = saved_encCounter_start;
2753 
2754     __ movptr(used_addr, used_addr_param);
2755     __ movptr(used, Address(used_addr, 0));
2756     __ movptr(saved_encCounter_start, saved_counter_param);
2757 
2758     __ BIND(L_preLoop_start);
2759     __ cmpptr(used, 16);
2760     __ jcc(Assembler::aboveEqual, L_exit_preLoop);
2761     __ cmpptr(len_reg, 0);
2762     __ jcc(Assembler::lessEqual, L_exit_preLoop);
2763     __ movb(rax, Address(saved_encCounter_start, used));
2764     __ xorb(rax, Address(from, 0));
2765     __ movb(Address(to, 0), rax);
2766     __ addptr(from, 1);
2767     __ addptr(to, 1);
2768     __ addptr(used, 1);
2769     __ subptr(len_reg, 1);
2770 
2771     __ jmp(L_preLoop_start);
2772 
2773     __ BIND(L_exit_preLoop);
2774     __ movptr(used_addr, used_addr_param);
2775     __ movptr(used_addr, used_addr_param);
2776     __ movl(Address(used_addr, 0), used);
2777 
2778     // load the parameters 'key' and 'counter'
2779     __ movptr(key, key_param);
2780     __ movptr(counter, rvec_param);
2781 
2782     // xmm register assignments for the loops below
2783     const XMMRegister xmm_curr_counter      = xmm0;
2784     const XMMRegister xmm_counter_shuf_mask = xmm1;  // need to be reloaded
2785     const XMMRegister xmm_key_shuf_mask     = xmm2;  // need to be reloaded
2786     const XMMRegister xmm_key               = xmm3;
2787     const XMMRegister xmm_result0           = xmm4;
2788     const XMMRegister xmm_result1           = xmm5;
2789     const XMMRegister xmm_result2           = xmm6;
2790     const XMMRegister xmm_result3           = xmm7;
2791     const XMMRegister xmm_from0             = xmm1;   //reuse XMM register
2792     const XMMRegister xmm_from1             = xmm2;
2793     const XMMRegister xmm_from2             = xmm3;
2794     const XMMRegister xmm_from3             = xmm4;
2795 
2796     //for key_128, key_192, key_256
2797     const int rounds[3] = {10, 12, 14};
2798     Label L_singleBlockLoopTop[3];
2799     Label L_multiBlock_loopTop[3];
2800     Label L_key192_top, L_key256_top;
2801     Label L_incCounter[3][4]; // 3: different key length,  4: 4 blocks at a time
2802     Label L_incCounter_single[3]; //for single block, key128, key192, key256
2803     Label L_processTail_insr[3], L_processTail_4_insr[3], L_processTail_2_insr[3], L_processTail_1_insr[3], L_processTail_exit_insr[3];
2804     Label L_processTail_extr[3], L_processTail_4_extr[3], L_processTail_2_extr[3], L_processTail_1_extr[3], L_processTail_exit_extr[3];
2805 
2806     Label L_exit;
2807     const int PARALLEL_FACTOR = 4;  //because of the limited register number
2808 
2809     // initialize counter with initial counter
2810     __ movdqu(xmm_curr_counter, Address(counter, 0x00));
2811     __ movdqu(xmm_counter_shuf_mask, ExternalAddress(StubRoutines::x86::counter_shuffle_mask_addr()));
2812     __ pshufb(xmm_curr_counter, xmm_counter_shuf_mask); //counter is shuffled for increase
2813 
2814     // key length could be only {11, 13, 15} * 4 = {44, 52, 60}
2815     __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2816     __ movl(rax, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT)));
2817     __ cmpl(rax, 52);
2818     __ jcc(Assembler::equal, L_key192_top);
2819     __ cmpl(rax, 60);
2820     __ jcc(Assembler::equal, L_key256_top);
2821 
2822     //key128 begins here
2823     __ movptr(pos, 0); // init pos before L_multiBlock_loopTop
2824 
2825 #define CTR_DoFour(opc, src_reg)               \
2826     __ opc(xmm_result0, src_reg);              \
2827     __ opc(xmm_result1, src_reg);              \
2828     __ opc(xmm_result2, src_reg);              \
2829     __ opc(xmm_result3, src_reg);
2830 
2831     // k == 0 :  generate code for key_128
2832     // k == 1 :  generate code for key_192
2833     // k == 2 :  generate code for key_256
2834     for (int k = 0; k < 3; ++k) {
2835       //multi blocks starts here
2836       __ align(OptoLoopAlignment);
2837       __ BIND(L_multiBlock_loopTop[k]);
2838       __ cmpptr(len_reg, PARALLEL_FACTOR * AESBlockSize); // see if at least PARALLEL_FACTOR blocks left
2839       __ jcc(Assembler::less, L_singleBlockLoopTop[k]);
2840 
2841       __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2842       __ movdqu(xmm_counter_shuf_mask, ExternalAddress(StubRoutines::x86::counter_shuffle_mask_addr()));
2843 
2844       //load, then increase counters
2845       CTR_DoFour(movdqa, xmm_curr_counter);
2846       __ push(rbx);
2847       inc_counter(rbx, xmm_result1, 0x01, L_incCounter[k][0]);
2848       inc_counter(rbx, xmm_result2, 0x02, L_incCounter[k][1]);
2849       inc_counter(rbx, xmm_result3, 0x03, L_incCounter[k][2]);
2850       inc_counter(rbx, xmm_curr_counter, 0x04, L_incCounter[k][3]);
2851       __ pop (rbx);
2852 
2853       load_key(xmm_key, key, 0x00, xmm_key_shuf_mask); // load Round 0 key. interleaving for better performance
2854 
2855       CTR_DoFour(pshufb, xmm_counter_shuf_mask); // after increased, shuffled counters back for PXOR
2856       CTR_DoFour(pxor, xmm_key);   //PXOR with Round 0 key
2857 
2858       for (int i = 1; i < rounds[k]; ++i) {
2859         load_key(xmm_key, key, (0x10 * i), xmm_key_shuf_mask);
2860         CTR_DoFour(aesenc, xmm_key);
2861       }
2862       load_key(xmm_key, key, (0x10 * rounds[k]), xmm_key_shuf_mask);
2863       CTR_DoFour(aesenclast, xmm_key);
2864 
2865       // get next PARALLEL_FACTOR blocks into xmm_from registers
2866       __ movdqu(xmm_from0, Address(from, pos, Address::times_1, 0 * AESBlockSize));
2867       __ movdqu(xmm_from1, Address(from, pos, Address::times_1, 1 * AESBlockSize));
2868       __ movdqu(xmm_from2, Address(from, pos, Address::times_1, 2 * AESBlockSize));
2869 
2870       // PXOR with input text
2871       __ pxor(xmm_result0, xmm_from0); //result0 is xmm4
2872       __ pxor(xmm_result1, xmm_from1);
2873       __ pxor(xmm_result2, xmm_from2);
2874 
2875       // store PARALLEL_FACTOR results into the next 64 bytes of output
2876       __ movdqu(Address(to, pos, Address::times_1, 0 * AESBlockSize), xmm_result0);
2877       __ movdqu(Address(to, pos, Address::times_1, 1 * AESBlockSize), xmm_result1);
2878       __ movdqu(Address(to, pos, Address::times_1, 2 * AESBlockSize), xmm_result2);
2879 
2880       // do it here after xmm_result0 is saved, because xmm_from3 reuse the same register of xmm_result0.
2881       __ movdqu(xmm_from3, Address(from, pos, Address::times_1, 3 * AESBlockSize));
2882       __ pxor(xmm_result3, xmm_from3);
2883       __ movdqu(Address(to, pos, Address::times_1, 3 * AESBlockSize), xmm_result3);
2884 
2885       __ addptr(pos, PARALLEL_FACTOR * AESBlockSize); // increase the length of crypt text
2886       __ subptr(len_reg, PARALLEL_FACTOR * AESBlockSize); // decrease the remaining length
2887       __ jmp(L_multiBlock_loopTop[k]);
2888 
2889       // singleBlock starts here
2890       __ align(OptoLoopAlignment);
2891       __ BIND(L_singleBlockLoopTop[k]);
2892       __ cmpptr(len_reg, 0);
2893       __ jcc(Assembler::equal, L_exit);
2894       __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2895       __ movdqu(xmm_counter_shuf_mask, ExternalAddress(StubRoutines::x86::counter_shuffle_mask_addr()));
2896       __ movdqa(xmm_result0, xmm_curr_counter);
2897       load_key(xmm_key, key, 0x00, xmm_key_shuf_mask);
2898       __ push(rbx);//rbx is used for increasing counter
2899       inc_counter(rbx, xmm_curr_counter, 0x01, L_incCounter_single[k]);
2900       __ pop (rbx);
2901       __ pshufb(xmm_result0, xmm_counter_shuf_mask);
2902       __ pxor(xmm_result0, xmm_key);
2903       for (int i = 1; i < rounds[k]; i++) {
2904         load_key(xmm_key, key, (0x10 * i), xmm_key_shuf_mask);
2905         __ aesenc(xmm_result0, xmm_key);
2906       }
2907       load_key(xmm_key, key, (0x10 * rounds[k]), xmm_key_shuf_mask);
2908       __ aesenclast(xmm_result0, xmm_key);
2909       __ cmpptr(len_reg, AESBlockSize);
2910       __ jcc(Assembler::less, L_processTail_insr[k]);
2911         __ movdqu(xmm_from0, Address(from, pos, Address::times_1, 0 * AESBlockSize));
2912         __ pxor(xmm_result0, xmm_from0);
2913         __ movdqu(Address(to, pos, Address::times_1, 0 * AESBlockSize), xmm_result0);
2914         __ addptr(pos, AESBlockSize);
2915         __ subptr(len_reg, AESBlockSize);
2916         __ jmp(L_singleBlockLoopTop[k]);
2917 
2918       __ BIND(L_processTail_insr[k]);                                               // Process the tail part of the input array
2919         __ addptr(pos, len_reg);                                                    // 1. Insert bytes from src array into xmm_from0 register
2920         __ testptr(len_reg, 8);
2921         __ jcc(Assembler::zero, L_processTail_4_insr[k]);
2922           __ subptr(pos,8);
2923           __ pinsrd(xmm_from0, Address(from, pos), 0);
2924           __ pinsrd(xmm_from0, Address(from, pos, Address::times_1, 4), 1);
2925         __ BIND(L_processTail_4_insr[k]);
2926         __ testptr(len_reg, 4);
2927         __ jcc(Assembler::zero, L_processTail_2_insr[k]);
2928           __ subptr(pos,4);
2929           __ pslldq(xmm_from0, 4);
2930           __ pinsrd(xmm_from0, Address(from, pos), 0);
2931         __ BIND(L_processTail_2_insr[k]);
2932         __ testptr(len_reg, 2);
2933         __ jcc(Assembler::zero, L_processTail_1_insr[k]);
2934           __ subptr(pos, 2);
2935           __ pslldq(xmm_from0, 2);
2936           __ pinsrw(xmm_from0, Address(from, pos), 0);
2937         __ BIND(L_processTail_1_insr[k]);
2938         __ testptr(len_reg, 1);
2939         __ jcc(Assembler::zero, L_processTail_exit_insr[k]);
2940           __ subptr(pos, 1);
2941           __ pslldq(xmm_from0, 1);
2942           __ pinsrb(xmm_from0, Address(from, pos), 0);
2943         __ BIND(L_processTail_exit_insr[k]);
2944 
2945         __ movptr(saved_encCounter_start, saved_counter_param);
2946         __ movdqu(Address(saved_encCounter_start, 0), xmm_result0);               // 2. Perform pxor of the encrypted counter and plaintext Bytes.
2947         __ pxor(xmm_result0, xmm_from0);                                          //    Also the encrypted counter is saved for next invocation.
2948 
2949         __ testptr(len_reg, 8);
2950         __ jcc(Assembler::zero, L_processTail_4_extr[k]);                        // 3. Extract bytes from xmm_result0 into the dest. array
2951           __ pextrd(Address(to, pos), xmm_result0, 0);
2952           __ pextrd(Address(to, pos, Address::times_1, 4), xmm_result0, 1);
2953           __ psrldq(xmm_result0, 8);
2954           __ addptr(pos, 8);
2955         __ BIND(L_processTail_4_extr[k]);
2956         __ testptr(len_reg, 4);
2957         __ jcc(Assembler::zero, L_processTail_2_extr[k]);
2958           __ pextrd(Address(to, pos), xmm_result0, 0);
2959           __ psrldq(xmm_result0, 4);
2960           __ addptr(pos, 4);
2961         __ BIND(L_processTail_2_extr[k]);
2962         __ testptr(len_reg, 2);
2963         __ jcc(Assembler::zero, L_processTail_1_extr[k]);
2964           __ pextrb(Address(to, pos), xmm_result0, 0);
2965           __ pextrb(Address(to, pos, Address::times_1, 1), xmm_result0, 1);
2966           __ psrldq(xmm_result0, 2);
2967           __ addptr(pos, 2);
2968         __ BIND(L_processTail_1_extr[k]);
2969         __ testptr(len_reg, 1);
2970         __ jcc(Assembler::zero, L_processTail_exit_extr[k]);
2971           __ pextrb(Address(to, pos), xmm_result0, 0);
2972 
2973         __ BIND(L_processTail_exit_extr[k]);
2974         __ movptr(used_addr, used_addr_param);
2975         __ movl(Address(used_addr, 0), len_reg);
2976         __ jmp(L_exit);
2977     }
2978 
2979     __ BIND(L_exit);
2980     __ movdqu(xmm_counter_shuf_mask, ExternalAddress(StubRoutines::x86::counter_shuffle_mask_addr()));
2981     __ pshufb(xmm_curr_counter, xmm_counter_shuf_mask); //counter is shuffled back.
2982     __ movdqu(Address(counter, 0), xmm_curr_counter); //save counter back
2983     handleSOERegisters(false /*restoring*/);
2984     __ movptr(rax, len_param); // return length
2985     __ leave();                // required for proper stackwalking of RuntimeStub frame
2986     __ ret(0);
2987 
2988     __ BIND (L_key192_top);
2989     __ movptr(pos, 0); // init pos before L_multiBlock_loopTop
2990     __ jmp(L_multiBlock_loopTop[1]); //key192
2991 
2992     __ BIND (L_key256_top);
2993     __ movptr(pos, 0); // init pos before L_multiBlock_loopTop
2994     __ jmp(L_multiBlock_loopTop[2]); //key192
2995 
2996     return start;
2997   }
2998 
2999   address generate_upper_word_mask() {
3000     __ align(64);
3001     StubCodeMark mark(this, "StubRoutines", "upper_word_mask");
3002     address start = __ pc();
3003     __ emit_data(0x00000000, relocInfo::none, 0);
3004     __ emit_data(0x00000000, relocInfo::none, 0);
3005     __ emit_data(0x00000000, relocInfo::none, 0);
3006     __ emit_data(0xFFFFFFFF, relocInfo::none, 0);
3007     return start;
3008   }
3009 
3010   address generate_shuffle_byte_flip_mask() {
3011     __ align(64);
3012     StubCodeMark mark(this, "StubRoutines", "shuffle_byte_flip_mask");
3013     address start = __ pc();
3014     __ emit_data(0x0c0d0e0f, relocInfo::none, 0);
3015     __ emit_data(0x08090a0b, relocInfo::none, 0);
3016     __ emit_data(0x04050607, relocInfo::none, 0);
3017     __ emit_data(0x00010203, relocInfo::none, 0);
3018     return start;
3019   }
3020 
3021   // ofs and limit are use for multi-block byte array.
3022   // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
3023   address generate_sha1_implCompress(bool multi_block, const char *name) {
3024     __ align(CodeEntryAlignment);
3025     StubCodeMark mark(this, "StubRoutines", name);
3026     address start = __ pc();
3027 
3028     Register buf   = rax;
3029     Register state = rdx;
3030     Register ofs   = rcx;
3031     Register limit = rdi;
3032 
3033     const Address  buf_param(rbp, 8 + 0);
3034     const Address  state_param(rbp, 8 + 4);
3035     const Address  ofs_param(rbp, 8 + 8);
3036     const Address  limit_param(rbp, 8 + 12);
3037 
3038     const XMMRegister abcd = xmm0;
3039     const XMMRegister e0 = xmm1;
3040     const XMMRegister e1 = xmm2;
3041     const XMMRegister msg0 = xmm3;
3042 
3043     const XMMRegister msg1 = xmm4;
3044     const XMMRegister msg2 = xmm5;
3045     const XMMRegister msg3 = xmm6;
3046     const XMMRegister shuf_mask = xmm7;
3047 
3048     __ enter();
3049     __ subptr(rsp, 8 * wordSize);
3050     handleSOERegisters(true /*saving*/);
3051 
3052     __ movptr(buf, buf_param);
3053     __ movptr(state, state_param);
3054     if (multi_block) {
3055       __ movptr(ofs, ofs_param);
3056       __ movptr(limit, limit_param);
3057     }
3058 
3059     __ fast_sha1(abcd, e0, e1, msg0, msg1, msg2, msg3, shuf_mask,
3060       buf, state, ofs, limit, rsp, multi_block);
3061 
3062     handleSOERegisters(false /*restoring*/);
3063     __ addptr(rsp, 8 * wordSize);
3064     __ leave();
3065     __ ret(0);
3066     return start;
3067   }
3068 
3069   address generate_pshuffle_byte_flip_mask() {
3070     __ align(64);
3071     StubCodeMark mark(this, "StubRoutines", "pshuffle_byte_flip_mask");
3072     address start = __ pc();
3073     __ emit_data(0x00010203, relocInfo::none, 0);
3074     __ emit_data(0x04050607, relocInfo::none, 0);
3075     __ emit_data(0x08090a0b, relocInfo::none, 0);
3076     __ emit_data(0x0c0d0e0f, relocInfo::none, 0);
3077     return start;
3078   }
3079 
3080   // ofs and limit are use for multi-block byte array.
3081   // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
3082  address generate_sha256_implCompress(bool multi_block, const char *name) {
3083     __ align(CodeEntryAlignment);
3084     StubCodeMark mark(this, "StubRoutines", name);
3085     address start = __ pc();
3086 
3087     Register buf = rbx;
3088     Register state = rsi;
3089     Register ofs = rdx;
3090     Register limit = rcx;
3091 
3092     const Address  buf_param(rbp, 8 + 0);
3093     const Address  state_param(rbp, 8 + 4);
3094     const Address  ofs_param(rbp, 8 + 8);
3095     const Address  limit_param(rbp, 8 + 12);
3096 
3097     const XMMRegister msg = xmm0;
3098     const XMMRegister state0 = xmm1;
3099     const XMMRegister state1 = xmm2;
3100     const XMMRegister msgtmp0 = xmm3;
3101 
3102     const XMMRegister msgtmp1 = xmm4;
3103     const XMMRegister msgtmp2 = xmm5;
3104     const XMMRegister msgtmp3 = xmm6;
3105     const XMMRegister msgtmp4 = xmm7;
3106 
3107     __ enter();
3108     __ subptr(rsp, 8 * wordSize);
3109     handleSOERegisters(true /*saving*/);
3110     __ movptr(buf, buf_param);
3111     __ movptr(state, state_param);
3112     if (multi_block) {
3113      __ movptr(ofs, ofs_param);
3114      __ movptr(limit, limit_param);
3115     }
3116 
3117     __ fast_sha256(msg, state0, state1, msgtmp0, msgtmp1, msgtmp2, msgtmp3, msgtmp4,
3118       buf, state, ofs, limit, rsp, multi_block);
3119 
3120     handleSOERegisters(false);
3121     __ addptr(rsp, 8 * wordSize);
3122     __ leave();
3123     __ ret(0);
3124     return start;
3125   }
3126 
3127   // byte swap x86 long
3128   address generate_ghash_long_swap_mask() {
3129     __ align(CodeEntryAlignment);
3130     StubCodeMark mark(this, "StubRoutines", "ghash_long_swap_mask");
3131     address start = __ pc();
3132     __ emit_data(0x0b0a0908, relocInfo::none, 0);
3133     __ emit_data(0x0f0e0d0c, relocInfo::none, 0);
3134     __ emit_data(0x03020100, relocInfo::none, 0);
3135     __ emit_data(0x07060504, relocInfo::none, 0);
3136 
3137   return start;
3138   }
3139 
3140   // byte swap x86 byte array
3141   address generate_ghash_byte_swap_mask() {
3142     __ align(CodeEntryAlignment);
3143     StubCodeMark mark(this, "StubRoutines", "ghash_byte_swap_mask");
3144     address start = __ pc();
3145     __ emit_data(0x0c0d0e0f, relocInfo::none, 0);
3146     __ emit_data(0x08090a0b, relocInfo::none, 0);
3147     __ emit_data(0x04050607, relocInfo::none, 0);
3148     __ emit_data(0x00010203, relocInfo::none, 0);
3149   return start;
3150   }
3151 
3152   /* Single and multi-block ghash operations */
3153   address generate_ghash_processBlocks() {
3154     assert(UseGHASHIntrinsics, "need GHASH intrinsics and CLMUL support");
3155     __ align(CodeEntryAlignment);
3156     Label L_ghash_loop, L_exit;
3157     StubCodeMark mark(this, "StubRoutines", "ghash_processBlocks");
3158     address start = __ pc();
3159 
3160     const Register state        = rdi;
3161     const Register subkeyH      = rsi;
3162     const Register data         = rdx;
3163     const Register blocks       = rcx;
3164 
3165     const Address  state_param(rbp, 8+0);
3166     const Address  subkeyH_param(rbp, 8+4);
3167     const Address  data_param(rbp, 8+8);
3168     const Address  blocks_param(rbp, 8+12);
3169 
3170     const XMMRegister xmm_temp0 = xmm0;
3171     const XMMRegister xmm_temp1 = xmm1;
3172     const XMMRegister xmm_temp2 = xmm2;
3173     const XMMRegister xmm_temp3 = xmm3;
3174     const XMMRegister xmm_temp4 = xmm4;
3175     const XMMRegister xmm_temp5 = xmm5;
3176     const XMMRegister xmm_temp6 = xmm6;
3177     const XMMRegister xmm_temp7 = xmm7;
3178 
3179     __ enter();
3180     handleSOERegisters(true);  // Save registers
3181 
3182     __ movptr(state, state_param);
3183     __ movptr(subkeyH, subkeyH_param);
3184     __ movptr(data, data_param);
3185     __ movptr(blocks, blocks_param);
3186 
3187     __ movdqu(xmm_temp0, Address(state, 0));
3188     __ pshufb(xmm_temp0, ExternalAddress(StubRoutines::x86::ghash_long_swap_mask_addr()));
3189 
3190     __ movdqu(xmm_temp1, Address(subkeyH, 0));
3191     __ pshufb(xmm_temp1, ExternalAddress(StubRoutines::x86::ghash_long_swap_mask_addr()));
3192 
3193     __ BIND(L_ghash_loop);
3194     __ movdqu(xmm_temp2, Address(data, 0));
3195     __ pshufb(xmm_temp2, ExternalAddress(StubRoutines::x86::ghash_byte_swap_mask_addr()));
3196 
3197     __ pxor(xmm_temp0, xmm_temp2);
3198 
3199     //
3200     // Multiply with the hash key
3201     //
3202     __ movdqu(xmm_temp3, xmm_temp0);
3203     __ pclmulqdq(xmm_temp3, xmm_temp1, 0);      // xmm3 holds a0*b0
3204     __ movdqu(xmm_temp4, xmm_temp0);
3205     __ pclmulqdq(xmm_temp4, xmm_temp1, 16);     // xmm4 holds a0*b1
3206 
3207     __ movdqu(xmm_temp5, xmm_temp0);
3208     __ pclmulqdq(xmm_temp5, xmm_temp1, 1);      // xmm5 holds a1*b0
3209     __ movdqu(xmm_temp6, xmm_temp0);
3210     __ pclmulqdq(xmm_temp6, xmm_temp1, 17);     // xmm6 holds a1*b1
3211 
3212     __ pxor(xmm_temp4, xmm_temp5);      // xmm4 holds a0*b1 + a1*b0
3213 
3214     __ movdqu(xmm_temp5, xmm_temp4);    // move the contents of xmm4 to xmm5
3215     __ psrldq(xmm_temp4, 8);    // shift by xmm4 64 bits to the right
3216     __ pslldq(xmm_temp5, 8);    // shift by xmm5 64 bits to the left
3217     __ pxor(xmm_temp3, xmm_temp5);
3218     __ pxor(xmm_temp6, xmm_temp4);      // Register pair <xmm6:xmm3> holds the result
3219                                         // of the carry-less multiplication of
3220                                         // xmm0 by xmm1.
3221 
3222     // We shift the result of the multiplication by one bit position
3223     // to the left to cope for the fact that the bits are reversed.
3224     __ movdqu(xmm_temp7, xmm_temp3);
3225     __ movdqu(xmm_temp4, xmm_temp6);
3226     __ pslld (xmm_temp3, 1);
3227     __ pslld(xmm_temp6, 1);
3228     __ psrld(xmm_temp7, 31);
3229     __ psrld(xmm_temp4, 31);
3230     __ movdqu(xmm_temp5, xmm_temp7);
3231     __ pslldq(xmm_temp4, 4);
3232     __ pslldq(xmm_temp7, 4);
3233     __ psrldq(xmm_temp5, 12);
3234     __ por(xmm_temp3, xmm_temp7);
3235     __ por(xmm_temp6, xmm_temp4);
3236     __ por(xmm_temp6, xmm_temp5);
3237 
3238     //
3239     // First phase of the reduction
3240     //
3241     // Move xmm3 into xmm4, xmm5, xmm7 in order to perform the shifts
3242     // independently.
3243     __ movdqu(xmm_temp7, xmm_temp3);
3244     __ movdqu(xmm_temp4, xmm_temp3);
3245     __ movdqu(xmm_temp5, xmm_temp3);
3246     __ pslld(xmm_temp7, 31);    // packed right shift shifting << 31
3247     __ pslld(xmm_temp4, 30);    // packed right shift shifting << 30
3248     __ pslld(xmm_temp5, 25);    // packed right shift shifting << 25
3249     __ pxor(xmm_temp7, xmm_temp4);      // xor the shifted versions
3250     __ pxor(xmm_temp7, xmm_temp5);
3251     __ movdqu(xmm_temp4, xmm_temp7);
3252     __ pslldq(xmm_temp7, 12);
3253     __ psrldq(xmm_temp4, 4);
3254     __ pxor(xmm_temp3, xmm_temp7);      // first phase of the reduction complete
3255 
3256     //
3257     // Second phase of the reduction
3258     //
3259     // Make 3 copies of xmm3 in xmm2, xmm5, xmm7 for doing these
3260     // shift operations.
3261     __ movdqu(xmm_temp2, xmm_temp3);
3262     __ movdqu(xmm_temp7, xmm_temp3);
3263     __ movdqu(xmm_temp5, xmm_temp3);
3264     __ psrld(xmm_temp2, 1);     // packed left shifting >> 1
3265     __ psrld(xmm_temp7, 2);     // packed left shifting >> 2
3266     __ psrld(xmm_temp5, 7);     // packed left shifting >> 7
3267     __ pxor(xmm_temp2, xmm_temp7);      // xor the shifted versions
3268     __ pxor(xmm_temp2, xmm_temp5);
3269     __ pxor(xmm_temp2, xmm_temp4);
3270     __ pxor(xmm_temp3, xmm_temp2);
3271     __ pxor(xmm_temp6, xmm_temp3);      // the result is in xmm6
3272 
3273     __ decrement(blocks);
3274     __ jcc(Assembler::zero, L_exit);
3275     __ movdqu(xmm_temp0, xmm_temp6);
3276     __ addptr(data, 16);
3277     __ jmp(L_ghash_loop);
3278 
3279     __ BIND(L_exit);
3280        // Byte swap 16-byte result
3281     __ pshufb(xmm_temp6, ExternalAddress(StubRoutines::x86::ghash_long_swap_mask_addr()));
3282     __ movdqu(Address(state, 0), xmm_temp6);   // store the result
3283 
3284     handleSOERegisters(false);  // restore registers
3285     __ leave();
3286     __ ret(0);
3287     return start;
3288   }
3289 
3290   /**
3291    *  Arguments:
3292    *
3293    * Inputs:
3294    *   rsp(4)   - int crc
3295    *   rsp(8)   - byte* buf
3296    *   rsp(12)  - int length
3297    *
3298    * Ouput:
3299    *       rax   - int crc result
3300    */
3301   address generate_updateBytesCRC32() {
3302     assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions");
3303 
3304     __ align(CodeEntryAlignment);
3305     StubCodeMark mark(this, "StubRoutines", "updateBytesCRC32");
3306 
3307     address start = __ pc();
3308 
3309     const Register crc   = rdx;  // crc
3310     const Register buf   = rsi;  // source java byte array address
3311     const Register len   = rcx;  // length
3312     const Register table = rdi;  // crc_table address (reuse register)
3313     const Register tmp   = rbx;
3314     assert_different_registers(crc, buf, len, table, tmp, rax);
3315 
3316     BLOCK_COMMENT("Entry:");
3317     __ enter(); // required for proper stackwalking of RuntimeStub frame
3318     __ push(rsi);
3319     __ push(rdi);
3320     __ push(rbx);
3321 
3322     Address crc_arg(rbp, 8 + 0);
3323     Address buf_arg(rbp, 8 + 4);
3324     Address len_arg(rbp, 8 + 8);
3325 
3326     // Load up:
3327     __ movl(crc,   crc_arg);
3328     __ movptr(buf, buf_arg);
3329     __ movl(len,   len_arg);
3330 
3331     __ kernel_crc32(crc, buf, len, table, tmp);
3332 
3333     __ movl(rax, crc);
3334     __ pop(rbx);
3335     __ pop(rdi);
3336     __ pop(rsi);
3337     __ vzeroupper();
3338     __ leave(); // required for proper stackwalking of RuntimeStub frame
3339     __ ret(0);
3340 
3341     return start;
3342   }
3343 
3344   /**
3345   *  Arguments:
3346   *
3347   * Inputs:
3348   *   rsp(4)   - int crc
3349   *   rsp(8)   - byte* buf
3350   *   rsp(12)  - int length
3351   *   rsp(16)  - table_start - optional (present only when doing a library_calll,
3352   *              not used by x86 algorithm)
3353   *
3354   * Ouput:
3355   *       rax  - int crc result
3356   */
3357   address generate_updateBytesCRC32C(bool is_pclmulqdq_supported) {
3358     assert(UseCRC32CIntrinsics, "need SSE4_2");
3359     __ align(CodeEntryAlignment);
3360     StubCodeMark mark(this, "StubRoutines", "updateBytesCRC32C");
3361     address start = __ pc();
3362     const Register crc = rax;  // crc
3363     const Register buf = rcx;  // source java byte array address
3364     const Register len = rdx;  // length
3365     const Register d = rbx;
3366     const Register g = rsi;
3367     const Register h = rdi;
3368     const Register empty = 0; // will never be used, in order not
3369                               // to change a signature for crc32c_IPL_Alg2_Alt2
3370                               // between 64/32 I'm just keeping it here
3371     assert_different_registers(crc, buf, len, d, g, h);
3372 
3373     BLOCK_COMMENT("Entry:");
3374     __ enter(); // required for proper stackwalking of RuntimeStub frame
3375     Address crc_arg(rsp, 4 + 4 + 0); // ESP+4 +
3376                                      // we need to add additional 4 because __ enter
3377                                      // have just pushed ebp on a stack
3378     Address buf_arg(rsp, 4 + 4 + 4);
3379     Address len_arg(rsp, 4 + 4 + 8);
3380       // Load up:
3381       __ movl(crc, crc_arg);
3382       __ movl(buf, buf_arg);
3383       __ movl(len, len_arg);
3384       __ push(d);
3385       __ push(g);
3386       __ push(h);
3387       __ crc32c_ipl_alg2_alt2(crc, buf, len,
3388                               d, g, h,
3389                               empty, empty, empty,
3390                               xmm0, xmm1, xmm2,
3391                               is_pclmulqdq_supported);
3392       __ pop(h);
3393       __ pop(g);
3394       __ pop(d);
3395     __ vzeroupper();
3396     __ leave(); // required for proper stackwalking of RuntimeStub frame
3397     __ ret(0);
3398 
3399     return start;
3400   }
3401 
3402  address generate_libmExp() {
3403     StubCodeMark mark(this, "StubRoutines", "libmExp");
3404 
3405     address start = __ pc();
3406 
3407     const XMMRegister x0  = xmm0;
3408     const XMMRegister x1  = xmm1;
3409     const XMMRegister x2  = xmm2;
3410     const XMMRegister x3  = xmm3;
3411 
3412     const XMMRegister x4  = xmm4;
3413     const XMMRegister x5  = xmm5;
3414     const XMMRegister x6  = xmm6;
3415     const XMMRegister x7  = xmm7;
3416 
3417     const Register tmp   = rbx;
3418 
3419     BLOCK_COMMENT("Entry:");
3420     __ enter(); // required for proper stackwalking of RuntimeStub frame
3421     __ fast_exp(x0, x1, x2, x3, x4, x5, x6, x7, rax, rcx, rdx, tmp);
3422     __ leave(); // required for proper stackwalking of RuntimeStub frame
3423     __ ret(0);
3424 
3425     return start;
3426 
3427   }
3428 
3429  address generate_libmLog() {
3430    StubCodeMark mark(this, "StubRoutines", "libmLog");
3431 
3432    address start = __ pc();
3433 
3434    const XMMRegister x0 = xmm0;
3435    const XMMRegister x1 = xmm1;
3436    const XMMRegister x2 = xmm2;
3437    const XMMRegister x3 = xmm3;
3438 
3439    const XMMRegister x4 = xmm4;
3440    const XMMRegister x5 = xmm5;
3441    const XMMRegister x6 = xmm6;
3442    const XMMRegister x7 = xmm7;
3443 
3444    const Register tmp = rbx;
3445 
3446    BLOCK_COMMENT("Entry:");
3447    __ enter(); // required for proper stackwalking of RuntimeStub frame
3448    __ fast_log(x0, x1, x2, x3, x4, x5, x6, x7, rax, rcx, rdx, tmp);
3449    __ leave(); // required for proper stackwalking of RuntimeStub frame
3450    __ ret(0);
3451 
3452    return start;
3453 
3454  }
3455 
3456  address generate_libmLog10() {
3457    StubCodeMark mark(this, "StubRoutines", "libmLog10");
3458 
3459    address start = __ pc();
3460 
3461    const XMMRegister x0 = xmm0;
3462    const XMMRegister x1 = xmm1;
3463    const XMMRegister x2 = xmm2;
3464    const XMMRegister x3 = xmm3;
3465 
3466    const XMMRegister x4 = xmm4;
3467    const XMMRegister x5 = xmm5;
3468    const XMMRegister x6 = xmm6;
3469    const XMMRegister x7 = xmm7;
3470 
3471    const Register tmp = rbx;
3472 
3473    BLOCK_COMMENT("Entry:");
3474    __ enter(); // required for proper stackwalking of RuntimeStub frame
3475    __ fast_log10(x0, x1, x2, x3, x4, x5, x6, x7, rax, rcx, rdx, tmp);
3476    __ leave(); // required for proper stackwalking of RuntimeStub frame
3477    __ ret(0);
3478 
3479    return start;
3480 
3481  }
3482 
3483  address generate_libmPow() {
3484    StubCodeMark mark(this, "StubRoutines", "libmPow");
3485 
3486    address start = __ pc();
3487 
3488    const XMMRegister x0 = xmm0;
3489    const XMMRegister x1 = xmm1;
3490    const XMMRegister x2 = xmm2;
3491    const XMMRegister x3 = xmm3;
3492 
3493    const XMMRegister x4 = xmm4;
3494    const XMMRegister x5 = xmm5;
3495    const XMMRegister x6 = xmm6;
3496    const XMMRegister x7 = xmm7;
3497 
3498    const Register tmp = rbx;
3499 
3500    BLOCK_COMMENT("Entry:");
3501    __ enter(); // required for proper stackwalking of RuntimeStub frame
3502    __ fast_pow(x0, x1, x2, x3, x4, x5, x6, x7, rax, rcx, rdx, tmp);
3503    __ leave(); // required for proper stackwalking of RuntimeStub frame
3504    __ ret(0);
3505 
3506    return start;
3507 
3508  }
3509 
3510  address generate_libm_reduce_pi04l() {
3511    StubCodeMark mark(this, "StubRoutines", "libm_reduce_pi04l");
3512 
3513    address start = __ pc();
3514 
3515    BLOCK_COMMENT("Entry:");
3516    __ libm_reduce_pi04l(rax, rcx, rdx, rbx, rsi, rdi, rbp, rsp);
3517 
3518    return start;
3519 
3520  }
3521 
3522  address generate_libm_sin_cos_huge() {
3523    StubCodeMark mark(this, "StubRoutines", "libm_sin_cos_huge");
3524 
3525    address start = __ pc();
3526 
3527    const XMMRegister x0 = xmm0;
3528    const XMMRegister x1 = xmm1;
3529 
3530    BLOCK_COMMENT("Entry:");
3531    __ libm_sincos_huge(x0, x1, rax, rcx, rdx, rbx, rsi, rdi, rbp, rsp);
3532 
3533    return start;
3534 
3535  }
3536 
3537  address generate_libmSin() {
3538    StubCodeMark mark(this, "StubRoutines", "libmSin");
3539 
3540    address start = __ pc();
3541 
3542    const XMMRegister x0 = xmm0;
3543    const XMMRegister x1 = xmm1;
3544    const XMMRegister x2 = xmm2;
3545    const XMMRegister x3 = xmm3;
3546 
3547    const XMMRegister x4 = xmm4;
3548    const XMMRegister x5 = xmm5;
3549    const XMMRegister x6 = xmm6;
3550    const XMMRegister x7 = xmm7;
3551 
3552    BLOCK_COMMENT("Entry:");
3553    __ enter(); // required for proper stackwalking of RuntimeStub frame
3554    __ fast_sin(x0, x1, x2, x3, x4, x5, x6, x7, rax, rbx, rdx);
3555    __ leave(); // required for proper stackwalking of RuntimeStub frame
3556    __ ret(0);
3557 
3558    return start;
3559 
3560  }
3561 
3562  address generate_libmCos() {
3563    StubCodeMark mark(this, "StubRoutines", "libmCos");
3564 
3565    address start = __ pc();
3566 
3567    const XMMRegister x0 = xmm0;
3568    const XMMRegister x1 = xmm1;
3569    const XMMRegister x2 = xmm2;
3570    const XMMRegister x3 = xmm3;
3571 
3572    const XMMRegister x4 = xmm4;
3573    const XMMRegister x5 = xmm5;
3574    const XMMRegister x6 = xmm6;
3575    const XMMRegister x7 = xmm7;
3576 
3577    const Register tmp = rbx;
3578 
3579    BLOCK_COMMENT("Entry:");
3580    __ enter(); // required for proper stackwalking of RuntimeStub frame
3581    __ fast_cos(x0, x1, x2, x3, x4, x5, x6, x7, rax, rcx, rdx, tmp);
3582    __ leave(); // required for proper stackwalking of RuntimeStub frame
3583    __ ret(0);
3584 
3585    return start;
3586 
3587  }
3588 
3589  address generate_libm_tan_cot_huge() {
3590    StubCodeMark mark(this, "StubRoutines", "libm_tan_cot_huge");
3591 
3592    address start = __ pc();
3593 
3594    const XMMRegister x0 = xmm0;
3595    const XMMRegister x1 = xmm1;
3596 
3597    BLOCK_COMMENT("Entry:");
3598    __ libm_tancot_huge(x0, x1, rax, rcx, rdx, rbx, rsi, rdi, rbp, rsp);
3599 
3600    return start;
3601 
3602  }
3603 
3604  address generate_libmTan() {
3605    StubCodeMark mark(this, "StubRoutines", "libmTan");
3606 
3607    address start = __ pc();
3608 
3609    const XMMRegister x0 = xmm0;
3610    const XMMRegister x1 = xmm1;
3611    const XMMRegister x2 = xmm2;
3612    const XMMRegister x3 = xmm3;
3613 
3614    const XMMRegister x4 = xmm4;
3615    const XMMRegister x5 = xmm5;
3616    const XMMRegister x6 = xmm6;
3617    const XMMRegister x7 = xmm7;
3618 
3619    const Register tmp = rbx;
3620 
3621    BLOCK_COMMENT("Entry:");
3622    __ enter(); // required for proper stackwalking of RuntimeStub frame
3623    __ fast_tan(x0, x1, x2, x3, x4, x5, x6, x7, rax, rcx, rdx, tmp);
3624    __ leave(); // required for proper stackwalking of RuntimeStub frame
3625    __ ret(0);
3626 
3627    return start;
3628 
3629  }
3630 
3631   // Safefetch stubs.
3632   void generate_safefetch(const char* name, int size, address* entry,
3633                           address* fault_pc, address* continuation_pc) {
3634     // safefetch signatures:
3635     //   int      SafeFetch32(int*      adr, int      errValue);
3636     //   intptr_t SafeFetchN (intptr_t* adr, intptr_t errValue);
3637 
3638     StubCodeMark mark(this, "StubRoutines", name);
3639 
3640     // Entry point, pc or function descriptor.
3641     *entry = __ pc();
3642 
3643     __ movl(rax, Address(rsp, 0x8));
3644     __ movl(rcx, Address(rsp, 0x4));
3645     // Load *adr into eax, may fault.
3646     *fault_pc = __ pc();
3647     switch (size) {
3648       case 4:
3649         // int32_t
3650         __ movl(rax, Address(rcx, 0));
3651         break;
3652       case 8:
3653         // int64_t
3654         Unimplemented();
3655         break;
3656       default:
3657         ShouldNotReachHere();
3658     }
3659 
3660     // Return errValue or *adr.
3661     *continuation_pc = __ pc();
3662     __ ret(0);
3663   }
3664 
3665  public:
3666   // Information about frame layout at time of blocking runtime call.
3667   // Note that we only have to preserve callee-saved registers since
3668   // the compilers are responsible for supplying a continuation point
3669   // if they expect all registers to be preserved.
3670   enum layout {
3671     thread_off,    // last_java_sp
3672     arg1_off,
3673     arg2_off,
3674     rbp_off,       // callee saved register
3675     ret_pc,
3676     framesize
3677   };
3678 
3679  private:
3680 
3681 #undef  __
3682 #define __ masm->
3683 
3684   //------------------------------------------------------------------------------------------------------------------------
3685   // Continuation point for throwing of implicit exceptions that are not handled in
3686   // the current activation. Fabricates an exception oop and initiates normal
3687   // exception dispatching in this frame.
3688   //
3689   // Previously the compiler (c2) allowed for callee save registers on Java calls.
3690   // This is no longer true after adapter frames were removed but could possibly
3691   // be brought back in the future if the interpreter code was reworked and it
3692   // was deemed worthwhile. The comment below was left to describe what must
3693   // happen here if callee saves were resurrected. As it stands now this stub
3694   // could actually be a vanilla BufferBlob and have now oopMap at all.
3695   // Since it doesn't make much difference we've chosen to leave it the
3696   // way it was in the callee save days and keep the comment.
3697 
3698   // If we need to preserve callee-saved values we need a callee-saved oop map and
3699   // therefore have to make these stubs into RuntimeStubs rather than BufferBlobs.
3700   // If the compiler needs all registers to be preserved between the fault
3701   // point and the exception handler then it must assume responsibility for that in
3702   // AbstractCompiler::continuation_for_implicit_null_exception or
3703   // continuation_for_implicit_division_by_zero_exception. All other implicit
3704   // exceptions (e.g., NullPointerException or AbstractMethodError on entry) are
3705   // either at call sites or otherwise assume that stack unwinding will be initiated,
3706   // so caller saved registers were assumed volatile in the compiler.
3707   address generate_throw_exception(const char* name, address runtime_entry,
3708                                    Register arg1 = noreg, Register arg2 = noreg) {
3709 
3710     int insts_size = 256;
3711     int locs_size  = 32;
3712 
3713     CodeBuffer code(name, insts_size, locs_size);
3714     OopMapSet* oop_maps  = new OopMapSet();
3715     MacroAssembler* masm = new MacroAssembler(&code);
3716 
3717     address start = __ pc();
3718 
3719     // This is an inlined and slightly modified version of call_VM
3720     // which has the ability to fetch the return PC out of
3721     // thread-local storage and also sets up last_Java_sp slightly
3722     // differently than the real call_VM
3723     Register java_thread = rbx;
3724     __ get_thread(java_thread);
3725 
3726     __ enter(); // required for proper stackwalking of RuntimeStub frame
3727 
3728     // pc and rbp, already pushed
3729     __ subptr(rsp, (framesize-2) * wordSize); // prolog
3730 
3731     // Frame is now completed as far as size and linkage.
3732 
3733     int frame_complete = __ pc() - start;
3734 
3735     // push java thread (becomes first argument of C function)
3736     __ movptr(Address(rsp, thread_off * wordSize), java_thread);
3737     if (arg1 != noreg) {
3738       __ movptr(Address(rsp, arg1_off * wordSize), arg1);
3739     }
3740     if (arg2 != noreg) {
3741       assert(arg1 != noreg, "missing reg arg");
3742       __ movptr(Address(rsp, arg2_off * wordSize), arg2);
3743     }
3744 
3745     // Set up last_Java_sp and last_Java_fp
3746     __ set_last_Java_frame(java_thread, rsp, rbp, NULL);
3747 
3748     // Call runtime
3749     BLOCK_COMMENT("call runtime_entry");
3750     __ call(RuntimeAddress(runtime_entry));
3751     // Generate oop map
3752     OopMap* map =  new OopMap(framesize, 0);
3753     oop_maps->add_gc_map(__ pc() - start, map);
3754 
3755     // restore the thread (cannot use the pushed argument since arguments
3756     // may be overwritten by C code generated by an optimizing compiler);
3757     // however can use the register value directly if it is callee saved.
3758     __ get_thread(java_thread);
3759 
3760     __ reset_last_Java_frame(java_thread, true);
3761 
3762     __ leave(); // required for proper stackwalking of RuntimeStub frame
3763 
3764     // check for pending exceptions
3765 #ifdef ASSERT
3766     Label L;
3767     __ cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3768     __ jcc(Assembler::notEqual, L);
3769     __ should_not_reach_here();
3770     __ bind(L);
3771 #endif /* ASSERT */
3772     __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3773 
3774 
3775     RuntimeStub* stub = RuntimeStub::new_runtime_stub(name, &code, frame_complete, framesize, oop_maps, false);
3776     return stub->entry_point();
3777   }
3778 
3779 
3780   void create_control_words() {
3781     // Round to nearest, 53-bit mode, exceptions masked
3782     StubRoutines::_fpu_cntrl_wrd_std   = 0x027F;
3783     // Round to zero, 53-bit mode, exception mased
3784     StubRoutines::_fpu_cntrl_wrd_trunc = 0x0D7F;
3785     // Round to nearest, 24-bit mode, exceptions masked
3786     StubRoutines::_fpu_cntrl_wrd_24    = 0x007F;
3787     // Round to nearest, 64-bit mode, exceptions masked
3788     StubRoutines::_mxcsr_std           = 0x1F80;
3789     // Note: the following two constants are 80-bit values
3790     //       layout is critical for correct loading by FPU.
3791     // Bias for strict fp multiply/divide
3792     StubRoutines::_fpu_subnormal_bias1[0]= 0x00000000; // 2^(-15360) == 0x03ff 8000 0000 0000 0000
3793     StubRoutines::_fpu_subnormal_bias1[1]= 0x80000000;
3794     StubRoutines::_fpu_subnormal_bias1[2]= 0x03ff;
3795     // Un-Bias for strict fp multiply/divide
3796     StubRoutines::_fpu_subnormal_bias2[0]= 0x00000000; // 2^(+15360) == 0x7bff 8000 0000 0000 0000
3797     StubRoutines::_fpu_subnormal_bias2[1]= 0x80000000;
3798     StubRoutines::_fpu_subnormal_bias2[2]= 0x7bff;
3799   }
3800 
3801   //---------------------------------------------------------------------------
3802   // Initialization
3803 
3804   void generate_initial() {
3805     // Generates all stubs and initializes the entry points
3806 
3807     //------------------------------------------------------------------------------------------------------------------------
3808     // entry points that exist in all platforms
3809     // Note: This is code that could be shared among different platforms - however the benefit seems to be smaller than
3810     //       the disadvantage of having a much more complicated generator structure. See also comment in stubRoutines.hpp.
3811     StubRoutines::_forward_exception_entry      = generate_forward_exception();
3812 
3813     StubRoutines::_call_stub_entry              =
3814       generate_call_stub(StubRoutines::_call_stub_return_address);
3815     // is referenced by megamorphic call
3816     StubRoutines::_catch_exception_entry        = generate_catch_exception();
3817 
3818     // These are currently used by Solaris/Intel
3819     StubRoutines::_atomic_xchg_entry            = generate_atomic_xchg();
3820 
3821     // platform dependent
3822     create_control_words();
3823 
3824     StubRoutines::x86::_verify_mxcsr_entry                 = generate_verify_mxcsr();
3825     StubRoutines::x86::_verify_fpu_cntrl_wrd_entry         = generate_verify_fpu_cntrl_wrd();
3826     StubRoutines::_d2i_wrapper                              = generate_d2i_wrapper(T_INT,
3827                                                                                    CAST_FROM_FN_PTR(address, SharedRuntime::d2i));
3828     StubRoutines::_d2l_wrapper                              = generate_d2i_wrapper(T_LONG,
3829                                                                                    CAST_FROM_FN_PTR(address, SharedRuntime::d2l));
3830 
3831     // Build this early so it's available for the interpreter
3832     StubRoutines::_throw_StackOverflowError_entry          = generate_throw_exception("StackOverflowError throw_exception",
3833                                                                                       CAST_FROM_FN_PTR(address, SharedRuntime::throw_StackOverflowError));
3834     StubRoutines::_throw_delayed_StackOverflowError_entry  = generate_throw_exception("delayed StackOverflowError throw_exception",
3835                                                                                       CAST_FROM_FN_PTR(address, SharedRuntime::throw_delayed_StackOverflowError));
3836 
3837     if (UseCRC32Intrinsics) {
3838       // set table address before stub generation which use it
3839       StubRoutines::_crc_table_adr = (address)StubRoutines::x86::_crc_table;
3840       StubRoutines::_updateBytesCRC32 = generate_updateBytesCRC32();
3841     }
3842 
3843     if (UseCRC32CIntrinsics) {
3844       bool supports_clmul = VM_Version::supports_clmul();
3845       StubRoutines::x86::generate_CRC32C_table(supports_clmul);
3846       StubRoutines::_crc32c_table_addr = (address)StubRoutines::x86::_crc32c_table;
3847       StubRoutines::_updateBytesCRC32C = generate_updateBytesCRC32C(supports_clmul);
3848     }
3849     if (VM_Version::supports_sse2() && UseLibmIntrinsic && InlineIntrinsics) {
3850       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dsin) ||
3851           vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dcos) ||
3852           vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dtan)) {
3853         StubRoutines::x86::_L_2il0floatpacket_0_adr = (address)StubRoutines::x86::_L_2il0floatpacket_0;
3854         StubRoutines::x86::_Pi4Inv_adr = (address)StubRoutines::x86::_Pi4Inv;
3855         StubRoutines::x86::_Pi4x3_adr = (address)StubRoutines::x86::_Pi4x3;
3856         StubRoutines::x86::_Pi4x4_adr = (address)StubRoutines::x86::_Pi4x4;
3857         StubRoutines::x86::_ones_adr = (address)StubRoutines::x86::_ones;
3858       }
3859       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dexp)) {
3860         StubRoutines::_dexp = generate_libmExp();
3861       }
3862       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dlog)) {
3863         StubRoutines::_dlog = generate_libmLog();
3864       }
3865       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dlog10)) {
3866         StubRoutines::_dlog10 = generate_libmLog10();
3867       }
3868       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dpow)) {
3869         StubRoutines::_dpow = generate_libmPow();
3870       }
3871       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dsin) ||
3872         vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dcos) ||
3873         vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dtan)) {
3874         StubRoutines::_dlibm_reduce_pi04l = generate_libm_reduce_pi04l();
3875       }
3876       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dsin) ||
3877         vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dcos)) {
3878         StubRoutines::_dlibm_sin_cos_huge = generate_libm_sin_cos_huge();
3879       }
3880       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dsin)) {
3881         StubRoutines::_dsin = generate_libmSin();
3882       }
3883       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dcos)) {
3884         StubRoutines::_dcos = generate_libmCos();
3885       }
3886       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dtan)) {
3887         StubRoutines::_dlibm_tan_cot_huge = generate_libm_tan_cot_huge();
3888         StubRoutines::_dtan = generate_libmTan();
3889       }
3890     }
3891   }
3892 
3893   void generate_all() {
3894     // Generates all stubs and initializes the entry points
3895 
3896     // These entry points require SharedInfo::stack0 to be set up in non-core builds
3897     // and need to be relocatable, so they each fabricate a RuntimeStub internally.
3898     StubRoutines::_throw_AbstractMethodError_entry         = generate_throw_exception("AbstractMethodError throw_exception",          CAST_FROM_FN_PTR(address, SharedRuntime::throw_AbstractMethodError));
3899     StubRoutines::_throw_IncompatibleClassChangeError_entry= generate_throw_exception("IncompatibleClassChangeError throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_IncompatibleClassChangeError));
3900     StubRoutines::_throw_NullPointerException_at_call_entry= generate_throw_exception("NullPointerException at call throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_NullPointerException_at_call));
3901 
3902     //------------------------------------------------------------------------------------------------------------------------
3903     // entry points that are platform specific
3904 
3905     StubRoutines::x86::_vector_float_sign_mask = generate_vector_mask("vector_float_sign_mask", 0x7FFFFFFF);
3906     StubRoutines::x86::_vector_float_sign_flip = generate_vector_mask("vector_float_sign_flip", 0x80000000);
3907     StubRoutines::x86::_vector_double_sign_mask = generate_vector_mask_long_double("vector_double_sign_mask", 0x7FFFFFFF, 0xFFFFFFFF);
3908     StubRoutines::x86::_vector_double_sign_flip = generate_vector_mask_long_double("vector_double_sign_flip", 0x80000000, 0x00000000);
3909     StubRoutines::x86::_vector_short_to_byte_mask = generate_vector_mask("vector_short_to_byte_mask", 0x00ff00ff);
3910     StubRoutines::x86::_vector_byte_perm_mask = generate_vector_byte_perm_mask("vector_byte_perm_mask");
3911     StubRoutines::x86::_vector_long_sign_mask = generate_vector_mask_long_double("vector_long_sign_mask", 0x80000000, 0x00000000);
3912 
3913     // support for verify_oop (must happen after universe_init)
3914     StubRoutines::_verify_oop_subroutine_entry     = generate_verify_oop();
3915 
3916     // arraycopy stubs used by compilers
3917     generate_arraycopy_stubs();
3918 
3919     // don't bother generating these AES intrinsic stubs unless global flag is set
3920     if (UseAESIntrinsics) {
3921       StubRoutines::x86::_key_shuffle_mask_addr = generate_key_shuffle_mask();  // might be needed by the others
3922 
3923       StubRoutines::_aescrypt_encryptBlock = generate_aescrypt_encryptBlock();
3924       StubRoutines::_aescrypt_decryptBlock = generate_aescrypt_decryptBlock();
3925       StubRoutines::_cipherBlockChaining_encryptAESCrypt = generate_cipherBlockChaining_encryptAESCrypt();
3926       StubRoutines::_cipherBlockChaining_decryptAESCrypt = generate_cipherBlockChaining_decryptAESCrypt_Parallel();
3927     }
3928 
3929     if (UseAESCTRIntrinsics) {
3930       StubRoutines::x86::_counter_shuffle_mask_addr = generate_counter_shuffle_mask();
3931       StubRoutines::_counterMode_AESCrypt = generate_counterMode_AESCrypt_Parallel();
3932     }
3933 
3934     if (UseSHA1Intrinsics) {
3935       StubRoutines::x86::_upper_word_mask_addr = generate_upper_word_mask();
3936       StubRoutines::x86::_shuffle_byte_flip_mask_addr = generate_shuffle_byte_flip_mask();
3937       StubRoutines::_sha1_implCompress = generate_sha1_implCompress(false, "sha1_implCompress");
3938       StubRoutines::_sha1_implCompressMB = generate_sha1_implCompress(true, "sha1_implCompressMB");
3939     }
3940     if (UseSHA256Intrinsics) {
3941       StubRoutines::x86::_k256_adr = (address)StubRoutines::x86::_k256;
3942       StubRoutines::x86::_pshuffle_byte_flip_mask_addr = generate_pshuffle_byte_flip_mask();
3943       StubRoutines::_sha256_implCompress = generate_sha256_implCompress(false, "sha256_implCompress");
3944       StubRoutines::_sha256_implCompressMB = generate_sha256_implCompress(true, "sha256_implCompressMB");
3945     }
3946 
3947     // Generate GHASH intrinsics code
3948     if (UseGHASHIntrinsics) {
3949       StubRoutines::x86::_ghash_long_swap_mask_addr = generate_ghash_long_swap_mask();
3950       StubRoutines::x86::_ghash_byte_swap_mask_addr = generate_ghash_byte_swap_mask();
3951       StubRoutines::_ghash_processBlocks = generate_ghash_processBlocks();
3952     }
3953 
3954     // Safefetch stubs.
3955     generate_safefetch("SafeFetch32", sizeof(int), &StubRoutines::_safefetch32_entry,
3956                                                    &StubRoutines::_safefetch32_fault_pc,
3957                                                    &StubRoutines::_safefetch32_continuation_pc);
3958     StubRoutines::_safefetchN_entry           = StubRoutines::_safefetch32_entry;
3959     StubRoutines::_safefetchN_fault_pc        = StubRoutines::_safefetch32_fault_pc;
3960     StubRoutines::_safefetchN_continuation_pc = StubRoutines::_safefetch32_continuation_pc;
3961   }
3962 
3963 
3964  public:
3965   StubGenerator(CodeBuffer* code, bool all) : StubCodeGenerator(code) {
3966     if (all) {
3967       generate_all();
3968     } else {
3969       generate_initial();
3970     }
3971   }
3972 }; // end class declaration
3973 
3974 #define UCM_TABLE_MAX_ENTRIES 8
3975 void StubGenerator_generate(CodeBuffer* code, bool all) {
3976   if (UnsafeCopyMemory::_table == NULL) {
3977     UnsafeCopyMemory::create_table(UCM_TABLE_MAX_ENTRIES);
3978   }
3979   StubGenerator g(code, all);
3980 }