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