1 /*
   2  * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "asm/assembler.hpp"
  27 #include "asm/assembler.inline.hpp"
  28 #include "compiler/disassembler.hpp"
  29 #include "gc/shared/cardTableModRefBS.hpp"
  30 #include "gc/shared/collectedHeap.inline.hpp"
  31 #include "interpreter/interpreter.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "memory/universe.hpp"
  34 #include "oops/klass.inline.hpp"
  35 #include "prims/methodHandles.hpp"
  36 #include "runtime/biasedLocking.hpp"
  37 #include "runtime/interfaceSupport.hpp"
  38 #include "runtime/objectMonitor.hpp"
  39 #include "runtime/os.hpp"
  40 #include "runtime/sharedRuntime.hpp"
  41 #include "runtime/stubRoutines.hpp"
  42 #include "runtime/thread.hpp"
  43 #include "utilities/macros.hpp"
  44 #if INCLUDE_ALL_GCS
  45 #include "gc/g1/g1CollectedHeap.inline.hpp"
  46 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  47 #include "gc/g1/heapRegion.hpp"
  48 #endif // INCLUDE_ALL_GCS
  49 #include "crc32c.h"
  50 #ifdef COMPILER2
  51 #include "opto/intrinsicnode.hpp"
  52 #endif
  53 
  54 #ifdef PRODUCT
  55 #define BLOCK_COMMENT(str) /* nothing */
  56 #define STOP(error) stop(error)
  57 #else
  58 #define BLOCK_COMMENT(str) block_comment(str)
  59 #define STOP(error) block_comment(error); stop(error)
  60 #endif
  61 
  62 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  63 
  64 #ifdef ASSERT
  65 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  66 #endif
  67 
  68 static Assembler::Condition reverse[] = {
  69     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  70     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  71     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  72     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  73     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  74     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  75     Assembler::above          /* belowEqual    = 0x6 */ ,
  76     Assembler::belowEqual     /* above         = 0x7 */ ,
  77     Assembler::positive       /* negative      = 0x8 */ ,
  78     Assembler::negative       /* positive      = 0x9 */ ,
  79     Assembler::noParity       /* parity        = 0xa */ ,
  80     Assembler::parity         /* noParity      = 0xb */ ,
  81     Assembler::greaterEqual   /* less          = 0xc */ ,
  82     Assembler::less           /* greaterEqual  = 0xd */ ,
  83     Assembler::greater        /* lessEqual     = 0xe */ ,
  84     Assembler::lessEqual      /* greater       = 0xf, */
  85 
  86 };
  87 
  88 
  89 // Implementation of MacroAssembler
  90 
  91 // First all the versions that have distinct versions depending on 32/64 bit
  92 // Unless the difference is trivial (1 line or so).
  93 
  94 #ifndef _LP64
  95 
  96 // 32bit versions
  97 
  98 Address MacroAssembler::as_Address(AddressLiteral adr) {
  99   return Address(adr.target(), adr.rspec());
 100 }
 101 
 102 Address MacroAssembler::as_Address(ArrayAddress adr) {
 103   return Address::make_array(adr);
 104 }
 105 
 106 void MacroAssembler::call_VM_leaf_base(address entry_point,
 107                                        int number_of_arguments) {
 108   call(RuntimeAddress(entry_point));
 109   increment(rsp, number_of_arguments * wordSize);
 110 }
 111 
 112 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 113   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 114 }
 115 
 116 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 117   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 118 }
 119 
 120 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 121   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 122 }
 123 
 124 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 125   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 126 }
 127 
 128 void MacroAssembler::extend_sign(Register hi, Register lo) {
 129   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 130   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 131     cdql();
 132   } else {
 133     movl(hi, lo);
 134     sarl(hi, 31);
 135   }
 136 }
 137 
 138 void MacroAssembler::jC2(Register tmp, Label& L) {
 139   // set parity bit if FPU flag C2 is set (via rax)
 140   save_rax(tmp);
 141   fwait(); fnstsw_ax();
 142   sahf();
 143   restore_rax(tmp);
 144   // branch
 145   jcc(Assembler::parity, L);
 146 }
 147 
 148 void MacroAssembler::jnC2(Register tmp, Label& L) {
 149   // set parity bit if FPU flag C2 is set (via rax)
 150   save_rax(tmp);
 151   fwait(); fnstsw_ax();
 152   sahf();
 153   restore_rax(tmp);
 154   // branch
 155   jcc(Assembler::noParity, L);
 156 }
 157 
 158 // 32bit can do a case table jump in one instruction but we no longer allow the base
 159 // to be installed in the Address class
 160 void MacroAssembler::jump(ArrayAddress entry) {
 161   jmp(as_Address(entry));
 162 }
 163 
 164 // Note: y_lo will be destroyed
 165 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 166   // Long compare for Java (semantics as described in JVM spec.)
 167   Label high, low, done;
 168 
 169   cmpl(x_hi, y_hi);
 170   jcc(Assembler::less, low);
 171   jcc(Assembler::greater, high);
 172   // x_hi is the return register
 173   xorl(x_hi, x_hi);
 174   cmpl(x_lo, y_lo);
 175   jcc(Assembler::below, low);
 176   jcc(Assembler::equal, done);
 177 
 178   bind(high);
 179   xorl(x_hi, x_hi);
 180   increment(x_hi);
 181   jmp(done);
 182 
 183   bind(low);
 184   xorl(x_hi, x_hi);
 185   decrementl(x_hi);
 186 
 187   bind(done);
 188 }
 189 
 190 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 191     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 192 }
 193 
 194 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 195   // leal(dst, as_Address(adr));
 196   // see note in movl as to why we must use a move
 197   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 198 }
 199 
 200 void MacroAssembler::leave() {
 201   mov(rsp, rbp);
 202   pop(rbp);
 203 }
 204 
 205 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 206   // Multiplication of two Java long values stored on the stack
 207   // as illustrated below. Result is in rdx:rax.
 208   //
 209   // rsp ---> [  ??  ] \               \
 210   //            ....    | y_rsp_offset  |
 211   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 212   //          [ y_hi ]                  | (in bytes)
 213   //            ....                    |
 214   //          [ x_lo ]                 /
 215   //          [ x_hi ]
 216   //            ....
 217   //
 218   // Basic idea: lo(result) = lo(x_lo * y_lo)
 219   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 220   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 221   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 222   Label quick;
 223   // load x_hi, y_hi and check if quick
 224   // multiplication is possible
 225   movl(rbx, x_hi);
 226   movl(rcx, y_hi);
 227   movl(rax, rbx);
 228   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 229   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 230   // do full multiplication
 231   // 1st step
 232   mull(y_lo);                                    // x_hi * y_lo
 233   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 234   // 2nd step
 235   movl(rax, x_lo);
 236   mull(rcx);                                     // x_lo * y_hi
 237   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 238   // 3rd step
 239   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 240   movl(rax, x_lo);
 241   mull(y_lo);                                    // x_lo * y_lo
 242   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 243 }
 244 
 245 void MacroAssembler::lneg(Register hi, Register lo) {
 246   negl(lo);
 247   adcl(hi, 0);
 248   negl(hi);
 249 }
 250 
 251 void MacroAssembler::lshl(Register hi, Register lo) {
 252   // Java shift left long support (semantics as described in JVM spec., p.305)
 253   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 254   // shift value is in rcx !
 255   assert(hi != rcx, "must not use rcx");
 256   assert(lo != rcx, "must not use rcx");
 257   const Register s = rcx;                        // shift count
 258   const int      n = BitsPerWord;
 259   Label L;
 260   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 261   cmpl(s, n);                                    // if (s < n)
 262   jcc(Assembler::less, L);                       // else (s >= n)
 263   movl(hi, lo);                                  // x := x << n
 264   xorl(lo, lo);
 265   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 266   bind(L);                                       // s (mod n) < n
 267   shldl(hi, lo);                                 // x := x << s
 268   shll(lo);
 269 }
 270 
 271 
 272 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 273   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 274   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 275   assert(hi != rcx, "must not use rcx");
 276   assert(lo != rcx, "must not use rcx");
 277   const Register s = rcx;                        // shift count
 278   const int      n = BitsPerWord;
 279   Label L;
 280   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 281   cmpl(s, n);                                    // if (s < n)
 282   jcc(Assembler::less, L);                       // else (s >= n)
 283   movl(lo, hi);                                  // x := x >> n
 284   if (sign_extension) sarl(hi, 31);
 285   else                xorl(hi, hi);
 286   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 287   bind(L);                                       // s (mod n) < n
 288   shrdl(lo, hi);                                 // x := x >> s
 289   if (sign_extension) sarl(hi);
 290   else                shrl(hi);
 291 }
 292 
 293 void MacroAssembler::movoop(Register dst, jobject obj) {
 294   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 295 }
 296 
 297 void MacroAssembler::movoop(Address dst, jobject obj) {
 298   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 299 }
 300 
 301 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 302   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 303 }
 304 
 305 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 306   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 307 }
 308 
 309 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 310   // scratch register is not used,
 311   // it is defined to match parameters of 64-bit version of this method.
 312   if (src.is_lval()) {
 313     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 314   } else {
 315     movl(dst, as_Address(src));
 316   }
 317 }
 318 
 319 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 320   movl(as_Address(dst), src);
 321 }
 322 
 323 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 324   movl(dst, as_Address(src));
 325 }
 326 
 327 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 328 void MacroAssembler::movptr(Address dst, intptr_t src) {
 329   movl(dst, src);
 330 }
 331 
 332 
 333 void MacroAssembler::pop_callee_saved_registers() {
 334   pop(rcx);
 335   pop(rdx);
 336   pop(rdi);
 337   pop(rsi);
 338 }
 339 
 340 void MacroAssembler::pop_fTOS() {
 341   fld_d(Address(rsp, 0));
 342   addl(rsp, 2 * wordSize);
 343 }
 344 
 345 void MacroAssembler::push_callee_saved_registers() {
 346   push(rsi);
 347   push(rdi);
 348   push(rdx);
 349   push(rcx);
 350 }
 351 
 352 void MacroAssembler::push_fTOS() {
 353   subl(rsp, 2 * wordSize);
 354   fstp_d(Address(rsp, 0));
 355 }
 356 
 357 
 358 void MacroAssembler::pushoop(jobject obj) {
 359   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 360 }
 361 
 362 void MacroAssembler::pushklass(Metadata* obj) {
 363   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 364 }
 365 
 366 void MacroAssembler::pushptr(AddressLiteral src) {
 367   if (src.is_lval()) {
 368     push_literal32((int32_t)src.target(), src.rspec());
 369   } else {
 370     pushl(as_Address(src));
 371   }
 372 }
 373 
 374 void MacroAssembler::set_word_if_not_zero(Register dst) {
 375   xorl(dst, dst);
 376   set_byte_if_not_zero(dst);
 377 }
 378 
 379 static void pass_arg0(MacroAssembler* masm, Register arg) {
 380   masm->push(arg);
 381 }
 382 
 383 static void pass_arg1(MacroAssembler* masm, Register arg) {
 384   masm->push(arg);
 385 }
 386 
 387 static void pass_arg2(MacroAssembler* masm, Register arg) {
 388   masm->push(arg);
 389 }
 390 
 391 static void pass_arg3(MacroAssembler* masm, Register arg) {
 392   masm->push(arg);
 393 }
 394 
 395 #ifndef PRODUCT
 396 extern "C" void findpc(intptr_t x);
 397 #endif
 398 
 399 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 400   // In order to get locks to work, we need to fake a in_VM state
 401   JavaThread* thread = JavaThread::current();
 402   JavaThreadState saved_state = thread->thread_state();
 403   thread->set_thread_state(_thread_in_vm);
 404   if (ShowMessageBoxOnError) {
 405     JavaThread* thread = JavaThread::current();
 406     JavaThreadState saved_state = thread->thread_state();
 407     thread->set_thread_state(_thread_in_vm);
 408     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 409       ttyLocker ttyl;
 410       BytecodeCounter::print();
 411     }
 412     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 413     // This is the value of eip which points to where verify_oop will return.
 414     if (os::message_box(msg, "Execution stopped, print registers?")) {
 415       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 416       BREAKPOINT;
 417     }
 418   } else {
 419     ttyLocker ttyl;
 420     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 421   }
 422   // Don't assert holding the ttyLock
 423     assert(false, "DEBUG MESSAGE: %s", msg);
 424   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 425 }
 426 
 427 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 428   ttyLocker ttyl;
 429   FlagSetting fs(Debugging, true);
 430   tty->print_cr("eip = 0x%08x", eip);
 431 #ifndef PRODUCT
 432   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 433     tty->cr();
 434     findpc(eip);
 435     tty->cr();
 436   }
 437 #endif
 438 #define PRINT_REG(rax) \
 439   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 440   PRINT_REG(rax);
 441   PRINT_REG(rbx);
 442   PRINT_REG(rcx);
 443   PRINT_REG(rdx);
 444   PRINT_REG(rdi);
 445   PRINT_REG(rsi);
 446   PRINT_REG(rbp);
 447   PRINT_REG(rsp);
 448 #undef PRINT_REG
 449   // Print some words near top of staack.
 450   int* dump_sp = (int*) rsp;
 451   for (int col1 = 0; col1 < 8; col1++) {
 452     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 453     os::print_location(tty, *dump_sp++);
 454   }
 455   for (int row = 0; row < 16; row++) {
 456     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 457     for (int col = 0; col < 8; col++) {
 458       tty->print(" 0x%08x", *dump_sp++);
 459     }
 460     tty->cr();
 461   }
 462   // Print some instructions around pc:
 463   Disassembler::decode((address)eip-64, (address)eip);
 464   tty->print_cr("--------");
 465   Disassembler::decode((address)eip, (address)eip+32);
 466 }
 467 
 468 void MacroAssembler::stop(const char* msg) {
 469   ExternalAddress message((address)msg);
 470   // push address of message
 471   pushptr(message.addr());
 472   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 473   pusha();                                            // push registers
 474   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 475   hlt();
 476 }
 477 
 478 void MacroAssembler::warn(const char* msg) {
 479   push_CPU_state();
 480 
 481   ExternalAddress message((address) msg);
 482   // push address of message
 483   pushptr(message.addr());
 484 
 485   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 486   addl(rsp, wordSize);       // discard argument
 487   pop_CPU_state();
 488 }
 489 
 490 void MacroAssembler::print_state() {
 491   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 492   pusha();                                            // push registers
 493 
 494   push_CPU_state();
 495   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 496   pop_CPU_state();
 497 
 498   popa();
 499   addl(rsp, wordSize);
 500 }
 501 
 502 #else // _LP64
 503 
 504 // 64 bit versions
 505 
 506 Address MacroAssembler::as_Address(AddressLiteral adr) {
 507   // amd64 always does this as a pc-rel
 508   // we can be absolute or disp based on the instruction type
 509   // jmp/call are displacements others are absolute
 510   assert(!adr.is_lval(), "must be rval");
 511   assert(reachable(adr), "must be");
 512   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 513 
 514 }
 515 
 516 Address MacroAssembler::as_Address(ArrayAddress adr) {
 517   AddressLiteral base = adr.base();
 518   lea(rscratch1, base);
 519   Address index = adr.index();
 520   assert(index._disp == 0, "must not have disp"); // maybe it can?
 521   Address array(rscratch1, index._index, index._scale, index._disp);
 522   return array;
 523 }
 524 
 525 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 526   Label L, E;
 527 
 528 #ifdef _WIN64
 529   // Windows always allocates space for it's register args
 530   assert(num_args <= 4, "only register arguments supported");
 531   subq(rsp,  frame::arg_reg_save_area_bytes);
 532 #endif
 533 
 534   // Align stack if necessary
 535   testl(rsp, 15);
 536   jcc(Assembler::zero, L);
 537 
 538   subq(rsp, 8);
 539   {
 540     call(RuntimeAddress(entry_point));
 541   }
 542   addq(rsp, 8);
 543   jmp(E);
 544 
 545   bind(L);
 546   {
 547     call(RuntimeAddress(entry_point));
 548   }
 549 
 550   bind(E);
 551 
 552 #ifdef _WIN64
 553   // restore stack pointer
 554   addq(rsp, frame::arg_reg_save_area_bytes);
 555 #endif
 556 
 557 }
 558 
 559 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 560   assert(!src2.is_lval(), "should use cmpptr");
 561 
 562   if (reachable(src2)) {
 563     cmpq(src1, as_Address(src2));
 564   } else {
 565     lea(rscratch1, src2);
 566     Assembler::cmpq(src1, Address(rscratch1, 0));
 567   }
 568 }
 569 
 570 int MacroAssembler::corrected_idivq(Register reg) {
 571   // Full implementation of Java ldiv and lrem; checks for special
 572   // case as described in JVM spec., p.243 & p.271.  The function
 573   // returns the (pc) offset of the idivl instruction - may be needed
 574   // for implicit exceptions.
 575   //
 576   //         normal case                           special case
 577   //
 578   // input : rax: dividend                         min_long
 579   //         reg: divisor   (may not be eax/edx)   -1
 580   //
 581   // output: rax: quotient  (= rax idiv reg)       min_long
 582   //         rdx: remainder (= rax irem reg)       0
 583   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 584   static const int64_t min_long = 0x8000000000000000;
 585   Label normal_case, special_case;
 586 
 587   // check for special case
 588   cmp64(rax, ExternalAddress((address) &min_long));
 589   jcc(Assembler::notEqual, normal_case);
 590   xorl(rdx, rdx); // prepare rdx for possible special case (where
 591                   // remainder = 0)
 592   cmpq(reg, -1);
 593   jcc(Assembler::equal, special_case);
 594 
 595   // handle normal case
 596   bind(normal_case);
 597   cdqq();
 598   int idivq_offset = offset();
 599   idivq(reg);
 600 
 601   // normal and special case exit
 602   bind(special_case);
 603 
 604   return idivq_offset;
 605 }
 606 
 607 void MacroAssembler::decrementq(Register reg, int value) {
 608   if (value == min_jint) { subq(reg, value); return; }
 609   if (value <  0) { incrementq(reg, -value); return; }
 610   if (value == 0) {                        ; return; }
 611   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 612   /* else */      { subq(reg, value)       ; return; }
 613 }
 614 
 615 void MacroAssembler::decrementq(Address dst, int value) {
 616   if (value == min_jint) { subq(dst, value); return; }
 617   if (value <  0) { incrementq(dst, -value); return; }
 618   if (value == 0) {                        ; return; }
 619   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 620   /* else */      { subq(dst, value)       ; return; }
 621 }
 622 
 623 void MacroAssembler::incrementq(AddressLiteral dst) {
 624   if (reachable(dst)) {
 625     incrementq(as_Address(dst));
 626   } else {
 627     lea(rscratch1, dst);
 628     incrementq(Address(rscratch1, 0));
 629   }
 630 }
 631 
 632 void MacroAssembler::incrementq(Register reg, int value) {
 633   if (value == min_jint) { addq(reg, value); return; }
 634   if (value <  0) { decrementq(reg, -value); return; }
 635   if (value == 0) {                        ; return; }
 636   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 637   /* else */      { addq(reg, value)       ; return; }
 638 }
 639 
 640 void MacroAssembler::incrementq(Address dst, int value) {
 641   if (value == min_jint) { addq(dst, value); return; }
 642   if (value <  0) { decrementq(dst, -value); return; }
 643   if (value == 0) {                        ; return; }
 644   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 645   /* else */      { addq(dst, value)       ; return; }
 646 }
 647 
 648 // 32bit can do a case table jump in one instruction but we no longer allow the base
 649 // to be installed in the Address class
 650 void MacroAssembler::jump(ArrayAddress entry) {
 651   lea(rscratch1, entry.base());
 652   Address dispatch = entry.index();
 653   assert(dispatch._base == noreg, "must be");
 654   dispatch._base = rscratch1;
 655   jmp(dispatch);
 656 }
 657 
 658 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 659   ShouldNotReachHere(); // 64bit doesn't use two regs
 660   cmpq(x_lo, y_lo);
 661 }
 662 
 663 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 664     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 665 }
 666 
 667 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 668   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 669   movptr(dst, rscratch1);
 670 }
 671 
 672 void MacroAssembler::leave() {
 673   // %%% is this really better? Why not on 32bit too?
 674   emit_int8((unsigned char)0xC9); // LEAVE
 675 }
 676 
 677 void MacroAssembler::lneg(Register hi, Register lo) {
 678   ShouldNotReachHere(); // 64bit doesn't use two regs
 679   negq(lo);
 680 }
 681 
 682 void MacroAssembler::movoop(Register dst, jobject obj) {
 683   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 684 }
 685 
 686 void MacroAssembler::movoop(Address dst, jobject obj) {
 687   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 688   movq(dst, rscratch1);
 689 }
 690 
 691 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 692   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 693 }
 694 
 695 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 696   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 697   movq(dst, rscratch1);
 698 }
 699 
 700 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 701   if (src.is_lval()) {
 702     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 703   } else {
 704     if (reachable(src)) {
 705       movq(dst, as_Address(src));
 706     } else {
 707       lea(scratch, src);
 708       movq(dst, Address(scratch, 0));
 709     }
 710   }
 711 }
 712 
 713 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 714   movq(as_Address(dst), src);
 715 }
 716 
 717 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 718   movq(dst, as_Address(src));
 719 }
 720 
 721 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 722 void MacroAssembler::movptr(Address dst, intptr_t src) {
 723   mov64(rscratch1, src);
 724   movq(dst, rscratch1);
 725 }
 726 
 727 // These are mostly for initializing NULL
 728 void MacroAssembler::movptr(Address dst, int32_t src) {
 729   movslq(dst, src);
 730 }
 731 
 732 void MacroAssembler::movptr(Register dst, int32_t src) {
 733   mov64(dst, (intptr_t)src);
 734 }
 735 
 736 void MacroAssembler::pushoop(jobject obj) {
 737   movoop(rscratch1, obj);
 738   push(rscratch1);
 739 }
 740 
 741 void MacroAssembler::pushklass(Metadata* obj) {
 742   mov_metadata(rscratch1, obj);
 743   push(rscratch1);
 744 }
 745 
 746 void MacroAssembler::pushptr(AddressLiteral src) {
 747   lea(rscratch1, src);
 748   if (src.is_lval()) {
 749     push(rscratch1);
 750   } else {
 751     pushq(Address(rscratch1, 0));
 752   }
 753 }
 754 
 755 void MacroAssembler::reset_last_Java_frame(bool clear_fp,
 756                                            bool clear_pc) {
 757   // we must set sp to zero to clear frame
 758   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 759   // must clear fp, so that compiled frames are not confused; it is
 760   // possible that we need it only for debugging
 761   if (clear_fp) {
 762     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 763   }
 764 
 765   if (clear_pc) {
 766     movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 767   }
 768 }
 769 
 770 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 771                                          Register last_java_fp,
 772                                          address  last_java_pc) {
 773   // determine last_java_sp register
 774   if (!last_java_sp->is_valid()) {
 775     last_java_sp = rsp;
 776   }
 777 
 778   // last_java_fp is optional
 779   if (last_java_fp->is_valid()) {
 780     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 781            last_java_fp);
 782   }
 783 
 784   // last_java_pc is optional
 785   if (last_java_pc != NULL) {
 786     Address java_pc(r15_thread,
 787                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 788     lea(rscratch1, InternalAddress(last_java_pc));
 789     movptr(java_pc, rscratch1);
 790   }
 791 
 792   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 793 }
 794 
 795 static void pass_arg0(MacroAssembler* masm, Register arg) {
 796   if (c_rarg0 != arg ) {
 797     masm->mov(c_rarg0, arg);
 798   }
 799 }
 800 
 801 static void pass_arg1(MacroAssembler* masm, Register arg) {
 802   if (c_rarg1 != arg ) {
 803     masm->mov(c_rarg1, arg);
 804   }
 805 }
 806 
 807 static void pass_arg2(MacroAssembler* masm, Register arg) {
 808   if (c_rarg2 != arg ) {
 809     masm->mov(c_rarg2, arg);
 810   }
 811 }
 812 
 813 static void pass_arg3(MacroAssembler* masm, Register arg) {
 814   if (c_rarg3 != arg ) {
 815     masm->mov(c_rarg3, arg);
 816   }
 817 }
 818 
 819 void MacroAssembler::stop(const char* msg) {
 820   address rip = pc();
 821   pusha(); // get regs on stack
 822   lea(c_rarg0, ExternalAddress((address) msg));
 823   lea(c_rarg1, InternalAddress(rip));
 824   movq(c_rarg2, rsp); // pass pointer to regs array
 825   andq(rsp, -16); // align stack as required by ABI
 826   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 827   hlt();
 828 }
 829 
 830 void MacroAssembler::warn(const char* msg) {
 831   push(rbp);
 832   movq(rbp, rsp);
 833   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 834   push_CPU_state();   // keeps alignment at 16 bytes
 835   lea(c_rarg0, ExternalAddress((address) msg));
 836   call_VM_leaf(CAST_FROM_FN_PTR(address, warning), c_rarg0);
 837   pop_CPU_state();
 838   mov(rsp, rbp);
 839   pop(rbp);
 840 }
 841 
 842 void MacroAssembler::print_state() {
 843   address rip = pc();
 844   pusha();            // get regs on stack
 845   push(rbp);
 846   movq(rbp, rsp);
 847   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 848   push_CPU_state();   // keeps alignment at 16 bytes
 849 
 850   lea(c_rarg0, InternalAddress(rip));
 851   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 852   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 853 
 854   pop_CPU_state();
 855   mov(rsp, rbp);
 856   pop(rbp);
 857   popa();
 858 }
 859 
 860 #ifndef PRODUCT
 861 extern "C" void findpc(intptr_t x);
 862 #endif
 863 
 864 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 865   // In order to get locks to work, we need to fake a in_VM state
 866   if (ShowMessageBoxOnError) {
 867     JavaThread* thread = JavaThread::current();
 868     JavaThreadState saved_state = thread->thread_state();
 869     thread->set_thread_state(_thread_in_vm);
 870 #ifndef PRODUCT
 871     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 872       ttyLocker ttyl;
 873       BytecodeCounter::print();
 874     }
 875 #endif
 876     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 877     // XXX correct this offset for amd64
 878     // This is the value of eip which points to where verify_oop will return.
 879     if (os::message_box(msg, "Execution stopped, print registers?")) {
 880       print_state64(pc, regs);
 881       BREAKPOINT;
 882       assert(false, "start up GDB");
 883     }
 884     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 885   } else {
 886     ttyLocker ttyl;
 887     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 888                     msg);
 889     assert(false, "DEBUG MESSAGE: %s", msg);
 890   }
 891 }
 892 
 893 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 894   ttyLocker ttyl;
 895   FlagSetting fs(Debugging, true);
 896   tty->print_cr("rip = 0x%016lx", pc);
 897 #ifndef PRODUCT
 898   tty->cr();
 899   findpc(pc);
 900   tty->cr();
 901 #endif
 902 #define PRINT_REG(rax, value) \
 903   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 904   PRINT_REG(rax, regs[15]);
 905   PRINT_REG(rbx, regs[12]);
 906   PRINT_REG(rcx, regs[14]);
 907   PRINT_REG(rdx, regs[13]);
 908   PRINT_REG(rdi, regs[8]);
 909   PRINT_REG(rsi, regs[9]);
 910   PRINT_REG(rbp, regs[10]);
 911   PRINT_REG(rsp, regs[11]);
 912   PRINT_REG(r8 , regs[7]);
 913   PRINT_REG(r9 , regs[6]);
 914   PRINT_REG(r10, regs[5]);
 915   PRINT_REG(r11, regs[4]);
 916   PRINT_REG(r12, regs[3]);
 917   PRINT_REG(r13, regs[2]);
 918   PRINT_REG(r14, regs[1]);
 919   PRINT_REG(r15, regs[0]);
 920 #undef PRINT_REG
 921   // Print some words near top of staack.
 922   int64_t* rsp = (int64_t*) regs[11];
 923   int64_t* dump_sp = rsp;
 924   for (int col1 = 0; col1 < 8; col1++) {
 925     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 926     os::print_location(tty, *dump_sp++);
 927   }
 928   for (int row = 0; row < 25; row++) {
 929     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 930     for (int col = 0; col < 4; col++) {
 931       tty->print(" 0x%016lx", *dump_sp++);
 932     }
 933     tty->cr();
 934   }
 935   // Print some instructions around pc:
 936   Disassembler::decode((address)pc-64, (address)pc);
 937   tty->print_cr("--------");
 938   Disassembler::decode((address)pc, (address)pc+32);
 939 }
 940 
 941 #endif // _LP64
 942 
 943 // Now versions that are common to 32/64 bit
 944 
 945 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 946   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 947 }
 948 
 949 void MacroAssembler::addptr(Register dst, Register src) {
 950   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 951 }
 952 
 953 void MacroAssembler::addptr(Address dst, Register src) {
 954   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 955 }
 956 
 957 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 958   if (reachable(src)) {
 959     Assembler::addsd(dst, as_Address(src));
 960   } else {
 961     lea(rscratch1, src);
 962     Assembler::addsd(dst, Address(rscratch1, 0));
 963   }
 964 }
 965 
 966 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 967   if (reachable(src)) {
 968     addss(dst, as_Address(src));
 969   } else {
 970     lea(rscratch1, src);
 971     addss(dst, Address(rscratch1, 0));
 972   }
 973 }
 974 
 975 void MacroAssembler::align(int modulus) {
 976   align(modulus, offset());
 977 }
 978 
 979 void MacroAssembler::align(int modulus, int target) {
 980   if (target % modulus != 0) {
 981     nop(modulus - (target % modulus));
 982   }
 983 }
 984 
 985 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
 986   // Used in sign-masking with aligned address.
 987   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 988   if (reachable(src)) {
 989     Assembler::andpd(dst, as_Address(src));
 990   } else {
 991     lea(rscratch1, src);
 992     Assembler::andpd(dst, Address(rscratch1, 0));
 993   }
 994 }
 995 
 996 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
 997   // Used in sign-masking with aligned address.
 998   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 999   if (reachable(src)) {
1000     Assembler::andps(dst, as_Address(src));
1001   } else {
1002     lea(rscratch1, src);
1003     Assembler::andps(dst, Address(rscratch1, 0));
1004   }
1005 }
1006 
1007 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1008   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1009 }
1010 
1011 void MacroAssembler::atomic_incl(Address counter_addr) {
1012   if (os::is_MP())
1013     lock();
1014   incrementl(counter_addr);
1015 }
1016 
1017 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1018   if (reachable(counter_addr)) {
1019     atomic_incl(as_Address(counter_addr));
1020   } else {
1021     lea(scr, counter_addr);
1022     atomic_incl(Address(scr, 0));
1023   }
1024 }
1025 
1026 #ifdef _LP64
1027 void MacroAssembler::atomic_incq(Address counter_addr) {
1028   if (os::is_MP())
1029     lock();
1030   incrementq(counter_addr);
1031 }
1032 
1033 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1034   if (reachable(counter_addr)) {
1035     atomic_incq(as_Address(counter_addr));
1036   } else {
1037     lea(scr, counter_addr);
1038     atomic_incq(Address(scr, 0));
1039   }
1040 }
1041 #endif
1042 
1043 // Writes to stack successive pages until offset reached to check for
1044 // stack overflow + shadow pages.  This clobbers tmp.
1045 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1046   movptr(tmp, rsp);
1047   // Bang stack for total size given plus shadow page size.
1048   // Bang one page at a time because large size can bang beyond yellow and
1049   // red zones.
1050   Label loop;
1051   bind(loop);
1052   movl(Address(tmp, (-os::vm_page_size())), size );
1053   subptr(tmp, os::vm_page_size());
1054   subl(size, os::vm_page_size());
1055   jcc(Assembler::greater, loop);
1056 
1057   // Bang down shadow pages too.
1058   // At this point, (tmp-0) is the last address touched, so don't
1059   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1060   // was post-decremented.)  Skip this address by starting at i=1, and
1061   // touch a few more pages below.  N.B.  It is important to touch all
1062   // the way down to and including i=StackShadowPages.
1063   for (int i = 1; i < StackShadowPages; i++) {
1064     // this could be any sized move but this is can be a debugging crumb
1065     // so the bigger the better.
1066     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1067   }
1068 }
1069 
1070 void MacroAssembler::reserved_stack_check() {
1071     // testing if reserved zone needs to be enabled
1072     Label no_reserved_zone_enabling;
1073     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1074     NOT_LP64(get_thread(rsi);)
1075 
1076     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1077     jcc(Assembler::below, no_reserved_zone_enabling);
1078 
1079     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1080     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1081     should_not_reach_here();
1082 
1083     bind(no_reserved_zone_enabling);
1084 }
1085 
1086 int MacroAssembler::biased_locking_enter(Register lock_reg,
1087                                          Register obj_reg,
1088                                          Register swap_reg,
1089                                          Register tmp_reg,
1090                                          bool swap_reg_contains_mark,
1091                                          Label& done,
1092                                          Label* slow_case,
1093                                          BiasedLockingCounters* counters) {
1094   assert(UseBiasedLocking, "why call this otherwise?");
1095   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1096   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1097   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1098   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1099   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1100   Address saved_mark_addr(lock_reg, 0);
1101 
1102   if (PrintBiasedLockingStatistics && counters == NULL) {
1103     counters = BiasedLocking::counters();
1104   }
1105   // Biased locking
1106   // See whether the lock is currently biased toward our thread and
1107   // whether the epoch is still valid
1108   // Note that the runtime guarantees sufficient alignment of JavaThread
1109   // pointers to allow age to be placed into low bits
1110   // First check to see whether biasing is even enabled for this object
1111   Label cas_label;
1112   int null_check_offset = -1;
1113   if (!swap_reg_contains_mark) {
1114     null_check_offset = offset();
1115     movptr(swap_reg, mark_addr);
1116   }
1117   movptr(tmp_reg, swap_reg);
1118   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1119   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1120   jcc(Assembler::notEqual, cas_label);
1121   // The bias pattern is present in the object's header. Need to check
1122   // whether the bias owner and the epoch are both still current.
1123 #ifndef _LP64
1124   // Note that because there is no current thread register on x86_32 we
1125   // need to store off the mark word we read out of the object to
1126   // avoid reloading it and needing to recheck invariants below. This
1127   // store is unfortunate but it makes the overall code shorter and
1128   // simpler.
1129   movptr(saved_mark_addr, swap_reg);
1130 #endif
1131   if (swap_reg_contains_mark) {
1132     null_check_offset = offset();
1133   }
1134   load_prototype_header(tmp_reg, obj_reg);
1135 #ifdef _LP64
1136   orptr(tmp_reg, r15_thread);
1137   xorptr(tmp_reg, swap_reg);
1138   Register header_reg = tmp_reg;
1139 #else
1140   xorptr(tmp_reg, swap_reg);
1141   get_thread(swap_reg);
1142   xorptr(swap_reg, tmp_reg);
1143   Register header_reg = swap_reg;
1144 #endif
1145   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1146   if (counters != NULL) {
1147     cond_inc32(Assembler::zero,
1148                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1149   }
1150   jcc(Assembler::equal, done);
1151 
1152   Label try_revoke_bias;
1153   Label try_rebias;
1154 
1155   // At this point we know that the header has the bias pattern and
1156   // that we are not the bias owner in the current epoch. We need to
1157   // figure out more details about the state of the header in order to
1158   // know what operations can be legally performed on the object's
1159   // header.
1160 
1161   // If the low three bits in the xor result aren't clear, that means
1162   // the prototype header is no longer biased and we have to revoke
1163   // the bias on this object.
1164   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1165   jccb(Assembler::notZero, try_revoke_bias);
1166 
1167   // Biasing is still enabled for this data type. See whether the
1168   // epoch of the current bias is still valid, meaning that the epoch
1169   // bits of the mark word are equal to the epoch bits of the
1170   // prototype header. (Note that the prototype header's epoch bits
1171   // only change at a safepoint.) If not, attempt to rebias the object
1172   // toward the current thread. Note that we must be absolutely sure
1173   // that the current epoch is invalid in order to do this because
1174   // otherwise the manipulations it performs on the mark word are
1175   // illegal.
1176   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1177   jccb(Assembler::notZero, try_rebias);
1178 
1179   // The epoch of the current bias is still valid but we know nothing
1180   // about the owner; it might be set or it might be clear. Try to
1181   // acquire the bias of the object using an atomic operation. If this
1182   // fails we will go in to the runtime to revoke the object's bias.
1183   // Note that we first construct the presumed unbiased header so we
1184   // don't accidentally blow away another thread's valid bias.
1185   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1186   andptr(swap_reg,
1187          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1188 #ifdef _LP64
1189   movptr(tmp_reg, swap_reg);
1190   orptr(tmp_reg, r15_thread);
1191 #else
1192   get_thread(tmp_reg);
1193   orptr(tmp_reg, swap_reg);
1194 #endif
1195   if (os::is_MP()) {
1196     lock();
1197   }
1198   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1199   // If the biasing toward our thread failed, this means that
1200   // another thread succeeded in biasing it toward itself and we
1201   // need to revoke that bias. The revocation will occur in the
1202   // interpreter runtime in the slow case.
1203   if (counters != NULL) {
1204     cond_inc32(Assembler::zero,
1205                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1206   }
1207   if (slow_case != NULL) {
1208     jcc(Assembler::notZero, *slow_case);
1209   }
1210   jmp(done);
1211 
1212   bind(try_rebias);
1213   // At this point we know the epoch has expired, meaning that the
1214   // current "bias owner", if any, is actually invalid. Under these
1215   // circumstances _only_, we are allowed to use the current header's
1216   // value as the comparison value when doing the cas to acquire the
1217   // bias in the current epoch. In other words, we allow transfer of
1218   // the bias from one thread to another directly in this situation.
1219   //
1220   // FIXME: due to a lack of registers we currently blow away the age
1221   // bits in this situation. Should attempt to preserve them.
1222   load_prototype_header(tmp_reg, obj_reg);
1223 #ifdef _LP64
1224   orptr(tmp_reg, r15_thread);
1225 #else
1226   get_thread(swap_reg);
1227   orptr(tmp_reg, swap_reg);
1228   movptr(swap_reg, saved_mark_addr);
1229 #endif
1230   if (os::is_MP()) {
1231     lock();
1232   }
1233   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1234   // If the biasing toward our thread failed, then another thread
1235   // succeeded in biasing it toward itself and we need to revoke that
1236   // bias. The revocation will occur in the runtime in the slow case.
1237   if (counters != NULL) {
1238     cond_inc32(Assembler::zero,
1239                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1240   }
1241   if (slow_case != NULL) {
1242     jcc(Assembler::notZero, *slow_case);
1243   }
1244   jmp(done);
1245 
1246   bind(try_revoke_bias);
1247   // The prototype mark in the klass doesn't have the bias bit set any
1248   // more, indicating that objects of this data type are not supposed
1249   // to be biased any more. We are going to try to reset the mark of
1250   // this object to the prototype value and fall through to the
1251   // CAS-based locking scheme. Note that if our CAS fails, it means
1252   // that another thread raced us for the privilege of revoking the
1253   // bias of this particular object, so it's okay to continue in the
1254   // normal locking code.
1255   //
1256   // FIXME: due to a lack of registers we currently blow away the age
1257   // bits in this situation. Should attempt to preserve them.
1258   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1259   load_prototype_header(tmp_reg, obj_reg);
1260   if (os::is_MP()) {
1261     lock();
1262   }
1263   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1264   // Fall through to the normal CAS-based lock, because no matter what
1265   // the result of the above CAS, some thread must have succeeded in
1266   // removing the bias bit from the object's header.
1267   if (counters != NULL) {
1268     cond_inc32(Assembler::zero,
1269                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1270   }
1271 
1272   bind(cas_label);
1273 
1274   return null_check_offset;
1275 }
1276 
1277 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1278   assert(UseBiasedLocking, "why call this otherwise?");
1279 
1280   // Check for biased locking unlock case, which is a no-op
1281   // Note: we do not have to check the thread ID for two reasons.
1282   // First, the interpreter checks for IllegalMonitorStateException at
1283   // a higher level. Second, if the bias was revoked while we held the
1284   // lock, the object could not be rebiased toward another thread, so
1285   // the bias bit would be clear.
1286   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1287   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1288   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1289   jcc(Assembler::equal, done);
1290 }
1291 
1292 #ifdef COMPILER2
1293 
1294 #if INCLUDE_RTM_OPT
1295 
1296 // Update rtm_counters based on abort status
1297 // input: abort_status
1298 //        rtm_counters (RTMLockingCounters*)
1299 // flags are killed
1300 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1301 
1302   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1303   if (PrintPreciseRTMLockingStatistics) {
1304     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1305       Label check_abort;
1306       testl(abort_status, (1<<i));
1307       jccb(Assembler::equal, check_abort);
1308       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1309       bind(check_abort);
1310     }
1311   }
1312 }
1313 
1314 // Branch if (random & (count-1) != 0), count is 2^n
1315 // tmp, scr and flags are killed
1316 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1317   assert(tmp == rax, "");
1318   assert(scr == rdx, "");
1319   rdtsc(); // modifies EDX:EAX
1320   andptr(tmp, count-1);
1321   jccb(Assembler::notZero, brLabel);
1322 }
1323 
1324 // Perform abort ratio calculation, set no_rtm bit if high ratio
1325 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1326 // tmpReg, rtm_counters_Reg and flags are killed
1327 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1328                                                  Register rtm_counters_Reg,
1329                                                  RTMLockingCounters* rtm_counters,
1330                                                  Metadata* method_data) {
1331   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1332 
1333   if (RTMLockingCalculationDelay > 0) {
1334     // Delay calculation
1335     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1336     testptr(tmpReg, tmpReg);
1337     jccb(Assembler::equal, L_done);
1338   }
1339   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1340   //   Aborted transactions = abort_count * 100
1341   //   All transactions = total_count *  RTMTotalCountIncrRate
1342   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1343 
1344   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1345   cmpptr(tmpReg, RTMAbortThreshold);
1346   jccb(Assembler::below, L_check_always_rtm2);
1347   imulptr(tmpReg, tmpReg, 100);
1348 
1349   Register scrReg = rtm_counters_Reg;
1350   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1351   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1352   imulptr(scrReg, scrReg, RTMAbortRatio);
1353   cmpptr(tmpReg, scrReg);
1354   jccb(Assembler::below, L_check_always_rtm1);
1355   if (method_data != NULL) {
1356     // set rtm_state to "no rtm" in MDO
1357     mov_metadata(tmpReg, method_data);
1358     if (os::is_MP()) {
1359       lock();
1360     }
1361     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1362   }
1363   jmpb(L_done);
1364   bind(L_check_always_rtm1);
1365   // Reload RTMLockingCounters* address
1366   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1367   bind(L_check_always_rtm2);
1368   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1369   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1370   jccb(Assembler::below, L_done);
1371   if (method_data != NULL) {
1372     // set rtm_state to "always rtm" in MDO
1373     mov_metadata(tmpReg, method_data);
1374     if (os::is_MP()) {
1375       lock();
1376     }
1377     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1378   }
1379   bind(L_done);
1380 }
1381 
1382 // Update counters and perform abort ratio calculation
1383 // input:  abort_status_Reg
1384 // rtm_counters_Reg, flags are killed
1385 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1386                                    Register rtm_counters_Reg,
1387                                    RTMLockingCounters* rtm_counters,
1388                                    Metadata* method_data,
1389                                    bool profile_rtm) {
1390 
1391   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1392   // update rtm counters based on rax value at abort
1393   // reads abort_status_Reg, updates flags
1394   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1395   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1396   if (profile_rtm) {
1397     // Save abort status because abort_status_Reg is used by following code.
1398     if (RTMRetryCount > 0) {
1399       push(abort_status_Reg);
1400     }
1401     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1402     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1403     // restore abort status
1404     if (RTMRetryCount > 0) {
1405       pop(abort_status_Reg);
1406     }
1407   }
1408 }
1409 
1410 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1411 // inputs: retry_count_Reg
1412 //       : abort_status_Reg
1413 // output: retry_count_Reg decremented by 1
1414 // flags are killed
1415 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1416   Label doneRetry;
1417   assert(abort_status_Reg == rax, "");
1418   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1419   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1420   // if reason is in 0x6 and retry count != 0 then retry
1421   andptr(abort_status_Reg, 0x6);
1422   jccb(Assembler::zero, doneRetry);
1423   testl(retry_count_Reg, retry_count_Reg);
1424   jccb(Assembler::zero, doneRetry);
1425   pause();
1426   decrementl(retry_count_Reg);
1427   jmp(retryLabel);
1428   bind(doneRetry);
1429 }
1430 
1431 // Spin and retry if lock is busy,
1432 // inputs: box_Reg (monitor address)
1433 //       : retry_count_Reg
1434 // output: retry_count_Reg decremented by 1
1435 //       : clear z flag if retry count exceeded
1436 // tmp_Reg, scr_Reg, flags are killed
1437 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1438                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1439   Label SpinLoop, SpinExit, doneRetry;
1440   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1441 
1442   testl(retry_count_Reg, retry_count_Reg);
1443   jccb(Assembler::zero, doneRetry);
1444   decrementl(retry_count_Reg);
1445   movptr(scr_Reg, RTMSpinLoopCount);
1446 
1447   bind(SpinLoop);
1448   pause();
1449   decrementl(scr_Reg);
1450   jccb(Assembler::lessEqual, SpinExit);
1451   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1452   testptr(tmp_Reg, tmp_Reg);
1453   jccb(Assembler::notZero, SpinLoop);
1454 
1455   bind(SpinExit);
1456   jmp(retryLabel);
1457   bind(doneRetry);
1458   incrementl(retry_count_Reg); // clear z flag
1459 }
1460 
1461 // Use RTM for normal stack locks
1462 // Input: objReg (object to lock)
1463 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1464                                        Register retry_on_abort_count_Reg,
1465                                        RTMLockingCounters* stack_rtm_counters,
1466                                        Metadata* method_data, bool profile_rtm,
1467                                        Label& DONE_LABEL, Label& IsInflated) {
1468   assert(UseRTMForStackLocks, "why call this otherwise?");
1469   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1470   assert(tmpReg == rax, "");
1471   assert(scrReg == rdx, "");
1472   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1473 
1474   if (RTMRetryCount > 0) {
1475     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1476     bind(L_rtm_retry);
1477   }
1478   movptr(tmpReg, Address(objReg, 0));
1479   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1480   jcc(Assembler::notZero, IsInflated);
1481 
1482   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1483     Label L_noincrement;
1484     if (RTMTotalCountIncrRate > 1) {
1485       // tmpReg, scrReg and flags are killed
1486       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1487     }
1488     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1489     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1490     bind(L_noincrement);
1491   }
1492   xbegin(L_on_abort);
1493   movptr(tmpReg, Address(objReg, 0));       // fetch markword
1494   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1495   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1496   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1497 
1498   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1499   if (UseRTMXendForLockBusy) {
1500     xend();
1501     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1502     jmp(L_decrement_retry);
1503   }
1504   else {
1505     xabort(0);
1506   }
1507   bind(L_on_abort);
1508   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1509     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1510   }
1511   bind(L_decrement_retry);
1512   if (RTMRetryCount > 0) {
1513     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1514     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1515   }
1516 }
1517 
1518 // Use RTM for inflating locks
1519 // inputs: objReg (object to lock)
1520 //         boxReg (on-stack box address (displaced header location) - KILLED)
1521 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1522 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1523                                           Register scrReg, Register retry_on_busy_count_Reg,
1524                                           Register retry_on_abort_count_Reg,
1525                                           RTMLockingCounters* rtm_counters,
1526                                           Metadata* method_data, bool profile_rtm,
1527                                           Label& DONE_LABEL) {
1528   assert(UseRTMLocking, "why call this otherwise?");
1529   assert(tmpReg == rax, "");
1530   assert(scrReg == rdx, "");
1531   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1532   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1533 
1534   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1535   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1536   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1537 
1538   if (RTMRetryCount > 0) {
1539     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1540     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1541     bind(L_rtm_retry);
1542   }
1543   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1544     Label L_noincrement;
1545     if (RTMTotalCountIncrRate > 1) {
1546       // tmpReg, scrReg and flags are killed
1547       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1548     }
1549     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1550     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1551     bind(L_noincrement);
1552   }
1553   xbegin(L_on_abort);
1554   movptr(tmpReg, Address(objReg, 0));
1555   movptr(tmpReg, Address(tmpReg, owner_offset));
1556   testptr(tmpReg, tmpReg);
1557   jcc(Assembler::zero, DONE_LABEL);
1558   if (UseRTMXendForLockBusy) {
1559     xend();
1560     jmp(L_decrement_retry);
1561   }
1562   else {
1563     xabort(0);
1564   }
1565   bind(L_on_abort);
1566   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1567   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1568     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1569   }
1570   if (RTMRetryCount > 0) {
1571     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1572     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1573   }
1574 
1575   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1576   testptr(tmpReg, tmpReg) ;
1577   jccb(Assembler::notZero, L_decrement_retry) ;
1578 
1579   // Appears unlocked - try to swing _owner from null to non-null.
1580   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1581 #ifdef _LP64
1582   Register threadReg = r15_thread;
1583 #else
1584   get_thread(scrReg);
1585   Register threadReg = scrReg;
1586 #endif
1587   if (os::is_MP()) {
1588     lock();
1589   }
1590   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1591 
1592   if (RTMRetryCount > 0) {
1593     // success done else retry
1594     jccb(Assembler::equal, DONE_LABEL) ;
1595     bind(L_decrement_retry);
1596     // Spin and retry if lock is busy.
1597     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1598   }
1599   else {
1600     bind(L_decrement_retry);
1601   }
1602 }
1603 
1604 #endif //  INCLUDE_RTM_OPT
1605 
1606 // Fast_Lock and Fast_Unlock used by C2
1607 
1608 // Because the transitions from emitted code to the runtime
1609 // monitorenter/exit helper stubs are so slow it's critical that
1610 // we inline both the stack-locking fast-path and the inflated fast path.
1611 //
1612 // See also: cmpFastLock and cmpFastUnlock.
1613 //
1614 // What follows is a specialized inline transliteration of the code
1615 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1616 // another option would be to emit TrySlowEnter and TrySlowExit methods
1617 // at startup-time.  These methods would accept arguments as
1618 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1619 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1620 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1621 // In practice, however, the # of lock sites is bounded and is usually small.
1622 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1623 // if the processor uses simple bimodal branch predictors keyed by EIP
1624 // Since the helper routines would be called from multiple synchronization
1625 // sites.
1626 //
1627 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1628 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1629 // to those specialized methods.  That'd give us a mostly platform-independent
1630 // implementation that the JITs could optimize and inline at their pleasure.
1631 // Done correctly, the only time we'd need to cross to native could would be
1632 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1633 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1634 // (b) explicit barriers or fence operations.
1635 //
1636 // TODO:
1637 //
1638 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1639 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1640 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1641 //    the lock operators would typically be faster than reifying Self.
1642 //
1643 // *  Ideally I'd define the primitives as:
1644 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1645 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1646 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1647 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1648 //    Furthermore the register assignments are overconstrained, possibly resulting in
1649 //    sub-optimal code near the synchronization site.
1650 //
1651 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1652 //    Alternately, use a better sp-proximity test.
1653 //
1654 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1655 //    Either one is sufficient to uniquely identify a thread.
1656 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1657 //
1658 // *  Intrinsify notify() and notifyAll() for the common cases where the
1659 //    object is locked by the calling thread but the waitlist is empty.
1660 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1661 //
1662 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1663 //    But beware of excessive branch density on AMD Opterons.
1664 //
1665 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1666 //    or failure of the fast-path.  If the fast-path fails then we pass
1667 //    control to the slow-path, typically in C.  In Fast_Lock and
1668 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1669 //    will emit a conditional branch immediately after the node.
1670 //    So we have branches to branches and lots of ICC.ZF games.
1671 //    Instead, it might be better to have C2 pass a "FailureLabel"
1672 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1673 //    will drop through the node.  ICC.ZF is undefined at exit.
1674 //    In the case of failure, the node will branch directly to the
1675 //    FailureLabel
1676 
1677 
1678 // obj: object to lock
1679 // box: on-stack box address (displaced header location) - KILLED
1680 // rax,: tmp -- KILLED
1681 // scr: tmp -- KILLED
1682 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1683                                Register scrReg, Register cx1Reg, Register cx2Reg,
1684                                BiasedLockingCounters* counters,
1685                                RTMLockingCounters* rtm_counters,
1686                                RTMLockingCounters* stack_rtm_counters,
1687                                Metadata* method_data,
1688                                bool use_rtm, bool profile_rtm) {
1689   // Ensure the register assignents are disjoint
1690   assert(tmpReg == rax, "");
1691 
1692   if (use_rtm) {
1693     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1694   } else {
1695     assert(cx1Reg == noreg, "");
1696     assert(cx2Reg == noreg, "");
1697     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1698   }
1699 
1700   if (counters != NULL) {
1701     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1702   }
1703   if (EmitSync & 1) {
1704       // set box->dhw = markOopDesc::unused_mark()
1705       // Force all sync thru slow-path: slow_enter() and slow_exit()
1706       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1707       cmpptr (rsp, (int32_t)NULL_WORD);
1708   } else {
1709     // Possible cases that we'll encounter in fast_lock
1710     // ------------------------------------------------
1711     // * Inflated
1712     //    -- unlocked
1713     //    -- Locked
1714     //       = by self
1715     //       = by other
1716     // * biased
1717     //    -- by Self
1718     //    -- by other
1719     // * neutral
1720     // * stack-locked
1721     //    -- by self
1722     //       = sp-proximity test hits
1723     //       = sp-proximity test generates false-negative
1724     //    -- by other
1725     //
1726 
1727     Label IsInflated, DONE_LABEL;
1728 
1729     // it's stack-locked, biased or neutral
1730     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1731     // order to reduce the number of conditional branches in the most common cases.
1732     // Beware -- there's a subtle invariant that fetch of the markword
1733     // at [FETCH], below, will never observe a biased encoding (*101b).
1734     // If this invariant is not held we risk exclusion (safety) failure.
1735     if (UseBiasedLocking && !UseOptoBiasInlining) {
1736       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1737     }
1738 
1739 #if INCLUDE_RTM_OPT
1740     if (UseRTMForStackLocks && use_rtm) {
1741       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1742                         stack_rtm_counters, method_data, profile_rtm,
1743                         DONE_LABEL, IsInflated);
1744     }
1745 #endif // INCLUDE_RTM_OPT
1746 
1747     movptr(tmpReg, Address(objReg, 0));          // [FETCH]
1748     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1749     jccb(Assembler::notZero, IsInflated);
1750 
1751     // Attempt stack-locking ...
1752     orptr (tmpReg, markOopDesc::unlocked_value);
1753     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1754     if (os::is_MP()) {
1755       lock();
1756     }
1757     cmpxchgptr(boxReg, Address(objReg, 0));      // Updates tmpReg
1758     if (counters != NULL) {
1759       cond_inc32(Assembler::equal,
1760                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1761     }
1762     jcc(Assembler::equal, DONE_LABEL);           // Success
1763 
1764     // Recursive locking.
1765     // The object is stack-locked: markword contains stack pointer to BasicLock.
1766     // Locked by current thread if difference with current SP is less than one page.
1767     subptr(tmpReg, rsp);
1768     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1769     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1770     movptr(Address(boxReg, 0), tmpReg);
1771     if (counters != NULL) {
1772       cond_inc32(Assembler::equal,
1773                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1774     }
1775     jmp(DONE_LABEL);
1776 
1777     bind(IsInflated);
1778     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1779 
1780 #if INCLUDE_RTM_OPT
1781     // Use the same RTM locking code in 32- and 64-bit VM.
1782     if (use_rtm) {
1783       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1784                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1785     } else {
1786 #endif // INCLUDE_RTM_OPT
1787 
1788 #ifndef _LP64
1789     // The object is inflated.
1790 
1791     // boxReg refers to the on-stack BasicLock in the current frame.
1792     // We'd like to write:
1793     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1794     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1795     // additional latency as we have another ST in the store buffer that must drain.
1796 
1797     if (EmitSync & 8192) {
1798        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1799        get_thread (scrReg);
1800        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1801        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1802        if (os::is_MP()) {
1803          lock();
1804        }
1805        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1806     } else
1807     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1808        // register juggle because we need tmpReg for cmpxchgptr below
1809        movptr(scrReg, boxReg);
1810        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1811 
1812        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1813        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1814           // prefetchw [eax + Offset(_owner)-2]
1815           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1816        }
1817 
1818        if ((EmitSync & 64) == 0) {
1819          // Optimistic form: consider XORL tmpReg,tmpReg
1820          movptr(tmpReg, NULL_WORD);
1821        } else {
1822          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1823          // Test-And-CAS instead of CAS
1824          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1825          testptr(tmpReg, tmpReg);                   // Locked ?
1826          jccb  (Assembler::notZero, DONE_LABEL);
1827        }
1828 
1829        // Appears unlocked - try to swing _owner from null to non-null.
1830        // Ideally, I'd manifest "Self" with get_thread and then attempt
1831        // to CAS the register containing Self into m->Owner.
1832        // But we don't have enough registers, so instead we can either try to CAS
1833        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1834        // we later store "Self" into m->Owner.  Transiently storing a stack address
1835        // (rsp or the address of the box) into  m->owner is harmless.
1836        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1837        if (os::is_MP()) {
1838          lock();
1839        }
1840        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1841        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1842        // If we weren't able to swing _owner from NULL to the BasicLock
1843        // then take the slow path.
1844        jccb  (Assembler::notZero, DONE_LABEL);
1845        // update _owner from BasicLock to thread
1846        get_thread (scrReg);                    // beware: clobbers ICCs
1847        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1848        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1849 
1850        // If the CAS fails we can either retry or pass control to the slow-path.
1851        // We use the latter tactic.
1852        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1853        // If the CAS was successful ...
1854        //   Self has acquired the lock
1855        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1856        // Intentional fall-through into DONE_LABEL ...
1857     } else {
1858        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1859        movptr(boxReg, tmpReg);
1860 
1861        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1862        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1863           // prefetchw [eax + Offset(_owner)-2]
1864           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1865        }
1866 
1867        if ((EmitSync & 64) == 0) {
1868          // Optimistic form
1869          xorptr  (tmpReg, tmpReg);
1870        } else {
1871          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1872          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1873          testptr(tmpReg, tmpReg);                   // Locked ?
1874          jccb  (Assembler::notZero, DONE_LABEL);
1875        }
1876 
1877        // Appears unlocked - try to swing _owner from null to non-null.
1878        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1879        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1880        get_thread (scrReg);
1881        if (os::is_MP()) {
1882          lock();
1883        }
1884        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1885 
1886        // If the CAS fails we can either retry or pass control to the slow-path.
1887        // We use the latter tactic.
1888        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1889        // If the CAS was successful ...
1890        //   Self has acquired the lock
1891        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1892        // Intentional fall-through into DONE_LABEL ...
1893     }
1894 #else // _LP64
1895     // It's inflated
1896     movq(scrReg, tmpReg);
1897     xorq(tmpReg, tmpReg);
1898 
1899     if (os::is_MP()) {
1900       lock();
1901     }
1902     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1903     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1904     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1905     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1906     // Intentional fall-through into DONE_LABEL ...
1907     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1908 #endif // _LP64
1909 #if INCLUDE_RTM_OPT
1910     } // use_rtm()
1911 #endif
1912     // DONE_LABEL is a hot target - we'd really like to place it at the
1913     // start of cache line by padding with NOPs.
1914     // See the AMD and Intel software optimization manuals for the
1915     // most efficient "long" NOP encodings.
1916     // Unfortunately none of our alignment mechanisms suffice.
1917     bind(DONE_LABEL);
1918 
1919     // At DONE_LABEL the icc ZFlag is set as follows ...
1920     // Fast_Unlock uses the same protocol.
1921     // ZFlag == 1 -> Success
1922     // ZFlag == 0 -> Failure - force control through the slow-path
1923   }
1924 }
1925 
1926 // obj: object to unlock
1927 // box: box address (displaced header location), killed.  Must be EAX.
1928 // tmp: killed, cannot be obj nor box.
1929 //
1930 // Some commentary on balanced locking:
1931 //
1932 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1933 // Methods that don't have provably balanced locking are forced to run in the
1934 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1935 // The interpreter provides two properties:
1936 // I1:  At return-time the interpreter automatically and quietly unlocks any
1937 //      objects acquired the current activation (frame).  Recall that the
1938 //      interpreter maintains an on-stack list of locks currently held by
1939 //      a frame.
1940 // I2:  If a method attempts to unlock an object that is not held by the
1941 //      the frame the interpreter throws IMSX.
1942 //
1943 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1944 // B() doesn't have provably balanced locking so it runs in the interpreter.
1945 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1946 // is still locked by A().
1947 //
1948 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1949 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1950 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1951 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1952 // Arguably given that the spec legislates the JNI case as undefined our implementation
1953 // could reasonably *avoid* checking owner in Fast_Unlock().
1954 // In the interest of performance we elide m->Owner==Self check in unlock.
1955 // A perfectly viable alternative is to elide the owner check except when
1956 // Xcheck:jni is enabled.
1957 
1958 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1959   assert(boxReg == rax, "");
1960   assert_different_registers(objReg, boxReg, tmpReg);
1961 
1962   if (EmitSync & 4) {
1963     // Disable - inhibit all inlining.  Force control through the slow-path
1964     cmpptr (rsp, 0);
1965   } else {
1966     Label DONE_LABEL, Stacked, CheckSucc;
1967 
1968     // Critically, the biased locking test must have precedence over
1969     // and appear before the (box->dhw == 0) recursive stack-lock test.
1970     if (UseBiasedLocking && !UseOptoBiasInlining) {
1971        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1972     }
1973 
1974 #if INCLUDE_RTM_OPT
1975     if (UseRTMForStackLocks && use_rtm) {
1976       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1977       Label L_regular_unlock;
1978       movptr(tmpReg, Address(objReg, 0));           // fetch markword
1979       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1980       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1981       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1982       xend();                                       // otherwise end...
1983       jmp(DONE_LABEL);                              // ... and we're done
1984       bind(L_regular_unlock);
1985     }
1986 #endif
1987 
1988     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
1989     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
1990     movptr(tmpReg, Address(objReg, 0));             // Examine the object's markword
1991     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
1992     jccb  (Assembler::zero, Stacked);
1993 
1994     // It's inflated.
1995 #if INCLUDE_RTM_OPT
1996     if (use_rtm) {
1997       Label L_regular_inflated_unlock;
1998       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1999       movptr(boxReg, Address(tmpReg, owner_offset));
2000       testptr(boxReg, boxReg);
2001       jccb(Assembler::notZero, L_regular_inflated_unlock);
2002       xend();
2003       jmpb(DONE_LABEL);
2004       bind(L_regular_inflated_unlock);
2005     }
2006 #endif
2007 
2008     // Despite our balanced locking property we still check that m->_owner == Self
2009     // as java routines or native JNI code called by this thread might
2010     // have released the lock.
2011     // Refer to the comments in synchronizer.cpp for how we might encode extra
2012     // state in _succ so we can avoid fetching EntryList|cxq.
2013     //
2014     // I'd like to add more cases in fast_lock() and fast_unlock() --
2015     // such as recursive enter and exit -- but we have to be wary of
2016     // I$ bloat, T$ effects and BP$ effects.
2017     //
2018     // If there's no contention try a 1-0 exit.  That is, exit without
2019     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2020     // we detect and recover from the race that the 1-0 exit admits.
2021     //
2022     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2023     // before it STs null into _owner, releasing the lock.  Updates
2024     // to data protected by the critical section must be visible before
2025     // we drop the lock (and thus before any other thread could acquire
2026     // the lock and observe the fields protected by the lock).
2027     // IA32's memory-model is SPO, so STs are ordered with respect to
2028     // each other and there's no need for an explicit barrier (fence).
2029     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2030 #ifndef _LP64
2031     get_thread (boxReg);
2032     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2033       // prefetchw [ebx + Offset(_owner)-2]
2034       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2035     }
2036 
2037     // Note that we could employ various encoding schemes to reduce
2038     // the number of loads below (currently 4) to just 2 or 3.
2039     // Refer to the comments in synchronizer.cpp.
2040     // In practice the chain of fetches doesn't seem to impact performance, however.
2041     xorptr(boxReg, boxReg);
2042     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2043        // Attempt to reduce branch density - AMD's branch predictor.
2044        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2045        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2046        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2047        jccb  (Assembler::notZero, DONE_LABEL);
2048        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2049        jmpb  (DONE_LABEL);
2050     } else {
2051        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2052        jccb  (Assembler::notZero, DONE_LABEL);
2053        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2054        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2055        jccb  (Assembler::notZero, CheckSucc);
2056        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2057        jmpb  (DONE_LABEL);
2058     }
2059 
2060     // The Following code fragment (EmitSync & 65536) improves the performance of
2061     // contended applications and contended synchronization microbenchmarks.
2062     // Unfortunately the emission of the code - even though not executed - causes regressions
2063     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2064     // with an equal number of never-executed NOPs results in the same regression.
2065     // We leave it off by default.
2066 
2067     if ((EmitSync & 65536) != 0) {
2068        Label LSuccess, LGoSlowPath ;
2069 
2070        bind  (CheckSucc);
2071 
2072        // Optional pre-test ... it's safe to elide this
2073        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2074        jccb(Assembler::zero, LGoSlowPath);
2075 
2076        // We have a classic Dekker-style idiom:
2077        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2078        // There are a number of ways to implement the barrier:
2079        // (1) lock:andl &m->_owner, 0
2080        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2081        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2082        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2083        // (2) If supported, an explicit MFENCE is appealing.
2084        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2085        //     particularly if the write-buffer is full as might be the case if
2086        //     if stores closely precede the fence or fence-equivalent instruction.
2087        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2088        //     as the situation has changed with Nehalem and Shanghai.
2089        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2090        //     The $lines underlying the top-of-stack should be in M-state.
2091        //     The locked add instruction is serializing, of course.
2092        // (4) Use xchg, which is serializing
2093        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2094        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2095        //     The integer condition codes will tell us if succ was 0.
2096        //     Since _succ and _owner should reside in the same $line and
2097        //     we just stored into _owner, it's likely that the $line
2098        //     remains in M-state for the lock:orl.
2099        //
2100        // We currently use (3), although it's likely that switching to (2)
2101        // is correct for the future.
2102 
2103        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2104        if (os::is_MP()) {
2105          lock(); addptr(Address(rsp, 0), 0);
2106        }
2107        // Ratify _succ remains non-null
2108        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2109        jccb  (Assembler::notZero, LSuccess);
2110 
2111        xorptr(boxReg, boxReg);                  // box is really EAX
2112        if (os::is_MP()) { lock(); }
2113        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2114        // There's no successor so we tried to regrab the lock with the
2115        // placeholder value. If that didn't work, then another thread
2116        // grabbed the lock so we're done (and exit was a success).
2117        jccb  (Assembler::notEqual, LSuccess);
2118        // Since we're low on registers we installed rsp as a placeholding in _owner.
2119        // Now install Self over rsp.  This is safe as we're transitioning from
2120        // non-null to non=null
2121        get_thread (boxReg);
2122        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2123        // Intentional fall-through into LGoSlowPath ...
2124 
2125        bind  (LGoSlowPath);
2126        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2127        jmpb  (DONE_LABEL);
2128 
2129        bind  (LSuccess);
2130        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2131        jmpb  (DONE_LABEL);
2132     }
2133 
2134     bind (Stacked);
2135     // It's not inflated and it's not recursively stack-locked and it's not biased.
2136     // It must be stack-locked.
2137     // Try to reset the header to displaced header.
2138     // The "box" value on the stack is stable, so we can reload
2139     // and be assured we observe the same value as above.
2140     movptr(tmpReg, Address(boxReg, 0));
2141     if (os::is_MP()) {
2142       lock();
2143     }
2144     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2145     // Intention fall-thru into DONE_LABEL
2146 
2147     // DONE_LABEL is a hot target - we'd really like to place it at the
2148     // start of cache line by padding with NOPs.
2149     // See the AMD and Intel software optimization manuals for the
2150     // most efficient "long" NOP encodings.
2151     // Unfortunately none of our alignment mechanisms suffice.
2152     if ((EmitSync & 65536) == 0) {
2153        bind (CheckSucc);
2154     }
2155 #else // _LP64
2156     // It's inflated
2157     if (EmitSync & 1024) {
2158       // Emit code to check that _owner == Self
2159       // We could fold the _owner test into subsequent code more efficiently
2160       // than using a stand-alone check, but since _owner checking is off by
2161       // default we don't bother. We also might consider predicating the
2162       // _owner==Self check on Xcheck:jni or running on a debug build.
2163       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2164       xorptr(boxReg, r15_thread);
2165     } else {
2166       xorptr(boxReg, boxReg);
2167     }
2168     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2169     jccb  (Assembler::notZero, DONE_LABEL);
2170     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2171     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2172     jccb  (Assembler::notZero, CheckSucc);
2173     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2174     jmpb  (DONE_LABEL);
2175 
2176     if ((EmitSync & 65536) == 0) {
2177       // Try to avoid passing control into the slow_path ...
2178       Label LSuccess, LGoSlowPath ;
2179       bind  (CheckSucc);
2180 
2181       // The following optional optimization can be elided if necessary
2182       // Effectively: if (succ == null) goto SlowPath
2183       // The code reduces the window for a race, however,
2184       // and thus benefits performance.
2185       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2186       jccb  (Assembler::zero, LGoSlowPath);
2187 
2188       if ((EmitSync & 16) && os::is_MP()) {
2189         orptr(boxReg, boxReg);
2190         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2191       } else {
2192         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2193         if (os::is_MP()) {
2194           // Memory barrier/fence
2195           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2196           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2197           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2198           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2199           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2200           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2201           lock(); addl(Address(rsp, 0), 0);
2202         }
2203       }
2204       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2205       jccb  (Assembler::notZero, LSuccess);
2206 
2207       // Rare inopportune interleaving - race.
2208       // The successor vanished in the small window above.
2209       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2210       // We need to ensure progress and succession.
2211       // Try to reacquire the lock.
2212       // If that fails then the new owner is responsible for succession and this
2213       // thread needs to take no further action and can exit via the fast path (success).
2214       // If the re-acquire succeeds then pass control into the slow path.
2215       // As implemented, this latter mode is horrible because we generated more
2216       // coherence traffic on the lock *and* artifically extended the critical section
2217       // length while by virtue of passing control into the slow path.
2218 
2219       // box is really RAX -- the following CMPXCHG depends on that binding
2220       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2221       movptr(boxReg, (int32_t)NULL_WORD);
2222       if (os::is_MP()) { lock(); }
2223       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2224       // There's no successor so we tried to regrab the lock.
2225       // If that didn't work, then another thread grabbed the
2226       // lock so we're done (and exit was a success).
2227       jccb  (Assembler::notEqual, LSuccess);
2228       // Intentional fall-through into slow-path
2229 
2230       bind  (LGoSlowPath);
2231       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2232       jmpb  (DONE_LABEL);
2233 
2234       bind  (LSuccess);
2235       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2236       jmpb  (DONE_LABEL);
2237     }
2238 
2239     bind  (Stacked);
2240     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2241     if (os::is_MP()) { lock(); }
2242     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2243 
2244     if (EmitSync & 65536) {
2245        bind (CheckSucc);
2246     }
2247 #endif
2248     bind(DONE_LABEL);
2249   }
2250 }
2251 #endif // COMPILER2
2252 
2253 void MacroAssembler::c2bool(Register x) {
2254   // implements x == 0 ? 0 : 1
2255   // note: must only look at least-significant byte of x
2256   //       since C-style booleans are stored in one byte
2257   //       only! (was bug)
2258   andl(x, 0xFF);
2259   setb(Assembler::notZero, x);
2260 }
2261 
2262 // Wouldn't need if AddressLiteral version had new name
2263 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2264   Assembler::call(L, rtype);
2265 }
2266 
2267 void MacroAssembler::call(Register entry) {
2268   Assembler::call(entry);
2269 }
2270 
2271 void MacroAssembler::call(AddressLiteral entry) {
2272   if (reachable(entry)) {
2273     Assembler::call_literal(entry.target(), entry.rspec());
2274   } else {
2275     lea(rscratch1, entry);
2276     Assembler::call(rscratch1);
2277   }
2278 }
2279 
2280 void MacroAssembler::ic_call(address entry, jint method_index) {
2281   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2282   movptr(rax, (intptr_t)Universe::non_oop_word());
2283   call(AddressLiteral(entry, rh));
2284 }
2285 
2286 // Implementation of call_VM versions
2287 
2288 void MacroAssembler::call_VM(Register oop_result,
2289                              address entry_point,
2290                              bool check_exceptions) {
2291   Label C, E;
2292   call(C, relocInfo::none);
2293   jmp(E);
2294 
2295   bind(C);
2296   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2297   ret(0);
2298 
2299   bind(E);
2300 }
2301 
2302 void MacroAssembler::call_VM(Register oop_result,
2303                              address entry_point,
2304                              Register arg_1,
2305                              bool check_exceptions) {
2306   Label C, E;
2307   call(C, relocInfo::none);
2308   jmp(E);
2309 
2310   bind(C);
2311   pass_arg1(this, arg_1);
2312   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2313   ret(0);
2314 
2315   bind(E);
2316 }
2317 
2318 void MacroAssembler::call_VM(Register oop_result,
2319                              address entry_point,
2320                              Register arg_1,
2321                              Register arg_2,
2322                              bool check_exceptions) {
2323   Label C, E;
2324   call(C, relocInfo::none);
2325   jmp(E);
2326 
2327   bind(C);
2328 
2329   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2330 
2331   pass_arg2(this, arg_2);
2332   pass_arg1(this, arg_1);
2333   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2334   ret(0);
2335 
2336   bind(E);
2337 }
2338 
2339 void MacroAssembler::call_VM(Register oop_result,
2340                              address entry_point,
2341                              Register arg_1,
2342                              Register arg_2,
2343                              Register arg_3,
2344                              bool check_exceptions) {
2345   Label C, E;
2346   call(C, relocInfo::none);
2347   jmp(E);
2348 
2349   bind(C);
2350 
2351   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2352   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2353   pass_arg3(this, arg_3);
2354 
2355   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2356   pass_arg2(this, arg_2);
2357 
2358   pass_arg1(this, arg_1);
2359   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2360   ret(0);
2361 
2362   bind(E);
2363 }
2364 
2365 void MacroAssembler::call_VM(Register oop_result,
2366                              Register last_java_sp,
2367                              address entry_point,
2368                              int number_of_arguments,
2369                              bool check_exceptions) {
2370   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2371   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2372 }
2373 
2374 void MacroAssembler::call_VM(Register oop_result,
2375                              Register last_java_sp,
2376                              address entry_point,
2377                              Register arg_1,
2378                              bool check_exceptions) {
2379   pass_arg1(this, arg_1);
2380   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2381 }
2382 
2383 void MacroAssembler::call_VM(Register oop_result,
2384                              Register last_java_sp,
2385                              address entry_point,
2386                              Register arg_1,
2387                              Register arg_2,
2388                              bool check_exceptions) {
2389 
2390   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2391   pass_arg2(this, arg_2);
2392   pass_arg1(this, arg_1);
2393   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2394 }
2395 
2396 void MacroAssembler::call_VM(Register oop_result,
2397                              Register last_java_sp,
2398                              address entry_point,
2399                              Register arg_1,
2400                              Register arg_2,
2401                              Register arg_3,
2402                              bool check_exceptions) {
2403   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2404   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2405   pass_arg3(this, arg_3);
2406   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2407   pass_arg2(this, arg_2);
2408   pass_arg1(this, arg_1);
2409   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2410 }
2411 
2412 void MacroAssembler::super_call_VM(Register oop_result,
2413                                    Register last_java_sp,
2414                                    address entry_point,
2415                                    int number_of_arguments,
2416                                    bool check_exceptions) {
2417   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2418   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2419 }
2420 
2421 void MacroAssembler::super_call_VM(Register oop_result,
2422                                    Register last_java_sp,
2423                                    address entry_point,
2424                                    Register arg_1,
2425                                    bool check_exceptions) {
2426   pass_arg1(this, arg_1);
2427   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2428 }
2429 
2430 void MacroAssembler::super_call_VM(Register oop_result,
2431                                    Register last_java_sp,
2432                                    address entry_point,
2433                                    Register arg_1,
2434                                    Register arg_2,
2435                                    bool check_exceptions) {
2436 
2437   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2438   pass_arg2(this, arg_2);
2439   pass_arg1(this, arg_1);
2440   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2441 }
2442 
2443 void MacroAssembler::super_call_VM(Register oop_result,
2444                                    Register last_java_sp,
2445                                    address entry_point,
2446                                    Register arg_1,
2447                                    Register arg_2,
2448                                    Register arg_3,
2449                                    bool check_exceptions) {
2450   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2451   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2452   pass_arg3(this, arg_3);
2453   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2454   pass_arg2(this, arg_2);
2455   pass_arg1(this, arg_1);
2456   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2457 }
2458 
2459 void MacroAssembler::call_VM_base(Register oop_result,
2460                                   Register java_thread,
2461                                   Register last_java_sp,
2462                                   address  entry_point,
2463                                   int      number_of_arguments,
2464                                   bool     check_exceptions) {
2465   // determine java_thread register
2466   if (!java_thread->is_valid()) {
2467 #ifdef _LP64
2468     java_thread = r15_thread;
2469 #else
2470     java_thread = rdi;
2471     get_thread(java_thread);
2472 #endif // LP64
2473   }
2474   // determine last_java_sp register
2475   if (!last_java_sp->is_valid()) {
2476     last_java_sp = rsp;
2477   }
2478   // debugging support
2479   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2480   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2481 #ifdef ASSERT
2482   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2483   // r12 is the heapbase.
2484   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2485 #endif // ASSERT
2486 
2487   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2488   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2489 
2490   // push java thread (becomes first argument of C function)
2491 
2492   NOT_LP64(push(java_thread); number_of_arguments++);
2493   LP64_ONLY(mov(c_rarg0, r15_thread));
2494 
2495   // set last Java frame before call
2496   assert(last_java_sp != rbp, "can't use ebp/rbp");
2497 
2498   // Only interpreter should have to set fp
2499   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2500 
2501   // do the call, remove parameters
2502   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2503 
2504   // restore the thread (cannot use the pushed argument since arguments
2505   // may be overwritten by C code generated by an optimizing compiler);
2506   // however can use the register value directly if it is callee saved.
2507   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2508     // rdi & rsi (also r15) are callee saved -> nothing to do
2509 #ifdef ASSERT
2510     guarantee(java_thread != rax, "change this code");
2511     push(rax);
2512     { Label L;
2513       get_thread(rax);
2514       cmpptr(java_thread, rax);
2515       jcc(Assembler::equal, L);
2516       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2517       bind(L);
2518     }
2519     pop(rax);
2520 #endif
2521   } else {
2522     get_thread(java_thread);
2523   }
2524   // reset last Java frame
2525   // Only interpreter should have to clear fp
2526   reset_last_Java_frame(java_thread, true, false);
2527 
2528 #ifndef CC_INTERP
2529    // C++ interp handles this in the interpreter
2530   check_and_handle_popframe(java_thread);
2531   check_and_handle_earlyret(java_thread);
2532 #endif /* CC_INTERP */
2533 
2534   if (check_exceptions) {
2535     // check for pending exceptions (java_thread is set upon return)
2536     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2537 #ifndef _LP64
2538     jump_cc(Assembler::notEqual,
2539             RuntimeAddress(StubRoutines::forward_exception_entry()));
2540 #else
2541     // This used to conditionally jump to forward_exception however it is
2542     // possible if we relocate that the branch will not reach. So we must jump
2543     // around so we can always reach
2544 
2545     Label ok;
2546     jcc(Assembler::equal, ok);
2547     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2548     bind(ok);
2549 #endif // LP64
2550   }
2551 
2552   // get oop result if there is one and reset the value in the thread
2553   if (oop_result->is_valid()) {
2554     get_vm_result(oop_result, java_thread);
2555   }
2556 }
2557 
2558 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2559 
2560   // Calculate the value for last_Java_sp
2561   // somewhat subtle. call_VM does an intermediate call
2562   // which places a return address on the stack just under the
2563   // stack pointer as the user finsihed with it. This allows
2564   // use to retrieve last_Java_pc from last_Java_sp[-1].
2565   // On 32bit we then have to push additional args on the stack to accomplish
2566   // the actual requested call. On 64bit call_VM only can use register args
2567   // so the only extra space is the return address that call_VM created.
2568   // This hopefully explains the calculations here.
2569 
2570 #ifdef _LP64
2571   // We've pushed one address, correct last_Java_sp
2572   lea(rax, Address(rsp, wordSize));
2573 #else
2574   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2575 #endif // LP64
2576 
2577   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2578 
2579 }
2580 
2581 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2582   call_VM_leaf_base(entry_point, number_of_arguments);
2583 }
2584 
2585 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2586   pass_arg0(this, arg_0);
2587   call_VM_leaf(entry_point, 1);
2588 }
2589 
2590 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2591 
2592   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2593   pass_arg1(this, arg_1);
2594   pass_arg0(this, arg_0);
2595   call_VM_leaf(entry_point, 2);
2596 }
2597 
2598 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2599   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2600   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2601   pass_arg2(this, arg_2);
2602   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2603   pass_arg1(this, arg_1);
2604   pass_arg0(this, arg_0);
2605   call_VM_leaf(entry_point, 3);
2606 }
2607 
2608 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2609   pass_arg0(this, arg_0);
2610   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2611 }
2612 
2613 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2614 
2615   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2616   pass_arg1(this, arg_1);
2617   pass_arg0(this, arg_0);
2618   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2619 }
2620 
2621 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2622   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2623   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2624   pass_arg2(this, arg_2);
2625   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2626   pass_arg1(this, arg_1);
2627   pass_arg0(this, arg_0);
2628   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2629 }
2630 
2631 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2632   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2633   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2634   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2635   pass_arg3(this, arg_3);
2636   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2637   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2638   pass_arg2(this, arg_2);
2639   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2640   pass_arg1(this, arg_1);
2641   pass_arg0(this, arg_0);
2642   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2643 }
2644 
2645 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2646   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2647   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2648   verify_oop(oop_result, "broken oop in call_VM_base");
2649 }
2650 
2651 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2652   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2653   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2654 }
2655 
2656 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2657 }
2658 
2659 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2660 }
2661 
2662 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2663   if (reachable(src1)) {
2664     cmpl(as_Address(src1), imm);
2665   } else {
2666     lea(rscratch1, src1);
2667     cmpl(Address(rscratch1, 0), imm);
2668   }
2669 }
2670 
2671 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2672   assert(!src2.is_lval(), "use cmpptr");
2673   if (reachable(src2)) {
2674     cmpl(src1, as_Address(src2));
2675   } else {
2676     lea(rscratch1, src2);
2677     cmpl(src1, Address(rscratch1, 0));
2678   }
2679 }
2680 
2681 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2682   Assembler::cmpl(src1, imm);
2683 }
2684 
2685 void MacroAssembler::cmp32(Register src1, Address src2) {
2686   Assembler::cmpl(src1, src2);
2687 }
2688 
2689 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2690   ucomisd(opr1, opr2);
2691 
2692   Label L;
2693   if (unordered_is_less) {
2694     movl(dst, -1);
2695     jcc(Assembler::parity, L);
2696     jcc(Assembler::below , L);
2697     movl(dst, 0);
2698     jcc(Assembler::equal , L);
2699     increment(dst);
2700   } else { // unordered is greater
2701     movl(dst, 1);
2702     jcc(Assembler::parity, L);
2703     jcc(Assembler::above , L);
2704     movl(dst, 0);
2705     jcc(Assembler::equal , L);
2706     decrementl(dst);
2707   }
2708   bind(L);
2709 }
2710 
2711 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2712   ucomiss(opr1, opr2);
2713 
2714   Label L;
2715   if (unordered_is_less) {
2716     movl(dst, -1);
2717     jcc(Assembler::parity, L);
2718     jcc(Assembler::below , L);
2719     movl(dst, 0);
2720     jcc(Assembler::equal , L);
2721     increment(dst);
2722   } else { // unordered is greater
2723     movl(dst, 1);
2724     jcc(Assembler::parity, L);
2725     jcc(Assembler::above , L);
2726     movl(dst, 0);
2727     jcc(Assembler::equal , L);
2728     decrementl(dst);
2729   }
2730   bind(L);
2731 }
2732 
2733 
2734 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2735   if (reachable(src1)) {
2736     cmpb(as_Address(src1), imm);
2737   } else {
2738     lea(rscratch1, src1);
2739     cmpb(Address(rscratch1, 0), imm);
2740   }
2741 }
2742 
2743 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2744 #ifdef _LP64
2745   if (src2.is_lval()) {
2746     movptr(rscratch1, src2);
2747     Assembler::cmpq(src1, rscratch1);
2748   } else if (reachable(src2)) {
2749     cmpq(src1, as_Address(src2));
2750   } else {
2751     lea(rscratch1, src2);
2752     Assembler::cmpq(src1, Address(rscratch1, 0));
2753   }
2754 #else
2755   if (src2.is_lval()) {
2756     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2757   } else {
2758     cmpl(src1, as_Address(src2));
2759   }
2760 #endif // _LP64
2761 }
2762 
2763 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2764   assert(src2.is_lval(), "not a mem-mem compare");
2765 #ifdef _LP64
2766   // moves src2's literal address
2767   movptr(rscratch1, src2);
2768   Assembler::cmpq(src1, rscratch1);
2769 #else
2770   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2771 #endif // _LP64
2772 }
2773 
2774 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2775   if (reachable(adr)) {
2776     if (os::is_MP())
2777       lock();
2778     cmpxchgptr(reg, as_Address(adr));
2779   } else {
2780     lea(rscratch1, adr);
2781     if (os::is_MP())
2782       lock();
2783     cmpxchgptr(reg, Address(rscratch1, 0));
2784   }
2785 }
2786 
2787 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2788   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2789 }
2790 
2791 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2792   if (reachable(src)) {
2793     Assembler::comisd(dst, as_Address(src));
2794   } else {
2795     lea(rscratch1, src);
2796     Assembler::comisd(dst, Address(rscratch1, 0));
2797   }
2798 }
2799 
2800 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2801   if (reachable(src)) {
2802     Assembler::comiss(dst, as_Address(src));
2803   } else {
2804     lea(rscratch1, src);
2805     Assembler::comiss(dst, Address(rscratch1, 0));
2806   }
2807 }
2808 
2809 
2810 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2811   Condition negated_cond = negate_condition(cond);
2812   Label L;
2813   jcc(negated_cond, L);
2814   pushf(); // Preserve flags
2815   atomic_incl(counter_addr);
2816   popf();
2817   bind(L);
2818 }
2819 
2820 int MacroAssembler::corrected_idivl(Register reg) {
2821   // Full implementation of Java idiv and irem; checks for
2822   // special case as described in JVM spec., p.243 & p.271.
2823   // The function returns the (pc) offset of the idivl
2824   // instruction - may be needed for implicit exceptions.
2825   //
2826   //         normal case                           special case
2827   //
2828   // input : rax,: dividend                         min_int
2829   //         reg: divisor   (may not be rax,/rdx)   -1
2830   //
2831   // output: rax,: quotient  (= rax, idiv reg)       min_int
2832   //         rdx: remainder (= rax, irem reg)       0
2833   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2834   const int min_int = 0x80000000;
2835   Label normal_case, special_case;
2836 
2837   // check for special case
2838   cmpl(rax, min_int);
2839   jcc(Assembler::notEqual, normal_case);
2840   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2841   cmpl(reg, -1);
2842   jcc(Assembler::equal, special_case);
2843 
2844   // handle normal case
2845   bind(normal_case);
2846   cdql();
2847   int idivl_offset = offset();
2848   idivl(reg);
2849 
2850   // normal and special case exit
2851   bind(special_case);
2852 
2853   return idivl_offset;
2854 }
2855 
2856 
2857 
2858 void MacroAssembler::decrementl(Register reg, int value) {
2859   if (value == min_jint) {subl(reg, value) ; return; }
2860   if (value <  0) { incrementl(reg, -value); return; }
2861   if (value == 0) {                        ; return; }
2862   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2863   /* else */      { subl(reg, value)       ; return; }
2864 }
2865 
2866 void MacroAssembler::decrementl(Address dst, int value) {
2867   if (value == min_jint) {subl(dst, value) ; return; }
2868   if (value <  0) { incrementl(dst, -value); return; }
2869   if (value == 0) {                        ; return; }
2870   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2871   /* else */      { subl(dst, value)       ; return; }
2872 }
2873 
2874 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2875   assert (shift_value > 0, "illegal shift value");
2876   Label _is_positive;
2877   testl (reg, reg);
2878   jcc (Assembler::positive, _is_positive);
2879   int offset = (1 << shift_value) - 1 ;
2880 
2881   if (offset == 1) {
2882     incrementl(reg);
2883   } else {
2884     addl(reg, offset);
2885   }
2886 
2887   bind (_is_positive);
2888   sarl(reg, shift_value);
2889 }
2890 
2891 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2892   if (reachable(src)) {
2893     Assembler::divsd(dst, as_Address(src));
2894   } else {
2895     lea(rscratch1, src);
2896     Assembler::divsd(dst, Address(rscratch1, 0));
2897   }
2898 }
2899 
2900 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2901   if (reachable(src)) {
2902     Assembler::divss(dst, as_Address(src));
2903   } else {
2904     lea(rscratch1, src);
2905     Assembler::divss(dst, Address(rscratch1, 0));
2906   }
2907 }
2908 
2909 // !defined(COMPILER2) is because of stupid core builds
2910 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2911 void MacroAssembler::empty_FPU_stack() {
2912   if (VM_Version::supports_mmx()) {
2913     emms();
2914   } else {
2915     for (int i = 8; i-- > 0; ) ffree(i);
2916   }
2917 }
2918 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2919 
2920 
2921 // Defines obj, preserves var_size_in_bytes
2922 void MacroAssembler::eden_allocate(Register obj,
2923                                    Register var_size_in_bytes,
2924                                    int con_size_in_bytes,
2925                                    Register t1,
2926                                    Label& slow_case) {
2927   assert(obj == rax, "obj must be in rax, for cmpxchg");
2928   assert_different_registers(obj, var_size_in_bytes, t1);
2929   if (!Universe::heap()->supports_inline_contig_alloc()) {
2930     jmp(slow_case);
2931   } else {
2932     Register end = t1;
2933     Label retry;
2934     bind(retry);
2935     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2936     movptr(obj, heap_top);
2937     if (var_size_in_bytes == noreg) {
2938       lea(end, Address(obj, con_size_in_bytes));
2939     } else {
2940       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2941     }
2942     // if end < obj then we wrapped around => object too long => slow case
2943     cmpptr(end, obj);
2944     jcc(Assembler::below, slow_case);
2945     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2946     jcc(Assembler::above, slow_case);
2947     // Compare obj with the top addr, and if still equal, store the new top addr in
2948     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2949     // it otherwise. Use lock prefix for atomicity on MPs.
2950     locked_cmpxchgptr(end, heap_top);
2951     jcc(Assembler::notEqual, retry);
2952   }
2953 }
2954 
2955 void MacroAssembler::enter() {
2956   push(rbp);
2957   mov(rbp, rsp);
2958 }
2959 
2960 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2961 void MacroAssembler::fat_nop() {
2962   if (UseAddressNop) {
2963     addr_nop_5();
2964   } else {
2965     emit_int8(0x26); // es:
2966     emit_int8(0x2e); // cs:
2967     emit_int8(0x64); // fs:
2968     emit_int8(0x65); // gs:
2969     emit_int8((unsigned char)0x90);
2970   }
2971 }
2972 
2973 void MacroAssembler::fcmp(Register tmp) {
2974   fcmp(tmp, 1, true, true);
2975 }
2976 
2977 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
2978   assert(!pop_right || pop_left, "usage error");
2979   if (VM_Version::supports_cmov()) {
2980     assert(tmp == noreg, "unneeded temp");
2981     if (pop_left) {
2982       fucomip(index);
2983     } else {
2984       fucomi(index);
2985     }
2986     if (pop_right) {
2987       fpop();
2988     }
2989   } else {
2990     assert(tmp != noreg, "need temp");
2991     if (pop_left) {
2992       if (pop_right) {
2993         fcompp();
2994       } else {
2995         fcomp(index);
2996       }
2997     } else {
2998       fcom(index);
2999     }
3000     // convert FPU condition into eflags condition via rax,
3001     save_rax(tmp);
3002     fwait(); fnstsw_ax();
3003     sahf();
3004     restore_rax(tmp);
3005   }
3006   // condition codes set as follows:
3007   //
3008   // CF (corresponds to C0) if x < y
3009   // PF (corresponds to C2) if unordered
3010   // ZF (corresponds to C3) if x = y
3011 }
3012 
3013 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3014   fcmp2int(dst, unordered_is_less, 1, true, true);
3015 }
3016 
3017 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3018   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3019   Label L;
3020   if (unordered_is_less) {
3021     movl(dst, -1);
3022     jcc(Assembler::parity, L);
3023     jcc(Assembler::below , L);
3024     movl(dst, 0);
3025     jcc(Assembler::equal , L);
3026     increment(dst);
3027   } else { // unordered is greater
3028     movl(dst, 1);
3029     jcc(Assembler::parity, L);
3030     jcc(Assembler::above , L);
3031     movl(dst, 0);
3032     jcc(Assembler::equal , L);
3033     decrementl(dst);
3034   }
3035   bind(L);
3036 }
3037 
3038 void MacroAssembler::fld_d(AddressLiteral src) {
3039   fld_d(as_Address(src));
3040 }
3041 
3042 void MacroAssembler::fld_s(AddressLiteral src) {
3043   fld_s(as_Address(src));
3044 }
3045 
3046 void MacroAssembler::fld_x(AddressLiteral src) {
3047   Assembler::fld_x(as_Address(src));
3048 }
3049 
3050 void MacroAssembler::fldcw(AddressLiteral src) {
3051   Assembler::fldcw(as_Address(src));
3052 }
3053 
3054 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3055   if (reachable(src)) {
3056     Assembler::mulpd(dst, as_Address(src));
3057   } else {
3058     lea(rscratch1, src);
3059     Assembler::mulpd(dst, Address(rscratch1, 0));
3060   }
3061 }
3062 
3063 void MacroAssembler::increase_precision() {
3064   subptr(rsp, BytesPerWord);
3065   fnstcw(Address(rsp, 0));
3066   movl(rax, Address(rsp, 0));
3067   orl(rax, 0x300);
3068   push(rax);
3069   fldcw(Address(rsp, 0));
3070   pop(rax);
3071 }
3072 
3073 void MacroAssembler::restore_precision() {
3074   fldcw(Address(rsp, 0));
3075   addptr(rsp, BytesPerWord);
3076 }
3077 
3078 void MacroAssembler::fpop() {
3079   ffree();
3080   fincstp();
3081 }
3082 
3083 void MacroAssembler::load_float(Address src) {
3084   if (UseSSE >= 1) {
3085     movflt(xmm0, src);
3086   } else {
3087     LP64_ONLY(ShouldNotReachHere());
3088     NOT_LP64(fld_s(src));
3089   }
3090 }
3091 
3092 void MacroAssembler::store_float(Address dst) {
3093   if (UseSSE >= 1) {
3094     movflt(dst, xmm0);
3095   } else {
3096     LP64_ONLY(ShouldNotReachHere());
3097     NOT_LP64(fstp_s(dst));
3098   }
3099 }
3100 
3101 void MacroAssembler::load_double(Address src) {
3102   if (UseSSE >= 2) {
3103     movdbl(xmm0, src);
3104   } else {
3105     LP64_ONLY(ShouldNotReachHere());
3106     NOT_LP64(fld_d(src));
3107   }
3108 }
3109 
3110 void MacroAssembler::store_double(Address dst) {
3111   if (UseSSE >= 2) {
3112     movdbl(dst, xmm0);
3113   } else {
3114     LP64_ONLY(ShouldNotReachHere());
3115     NOT_LP64(fstp_d(dst));
3116   }
3117 }
3118 
3119 void MacroAssembler::fremr(Register tmp) {
3120   save_rax(tmp);
3121   { Label L;
3122     bind(L);
3123     fprem();
3124     fwait(); fnstsw_ax();
3125 #ifdef _LP64
3126     testl(rax, 0x400);
3127     jcc(Assembler::notEqual, L);
3128 #else
3129     sahf();
3130     jcc(Assembler::parity, L);
3131 #endif // _LP64
3132   }
3133   restore_rax(tmp);
3134   // Result is in ST0.
3135   // Note: fxch & fpop to get rid of ST1
3136   // (otherwise FPU stack could overflow eventually)
3137   fxch(1);
3138   fpop();
3139 }
3140 
3141 
3142 void MacroAssembler::incrementl(AddressLiteral dst) {
3143   if (reachable(dst)) {
3144     incrementl(as_Address(dst));
3145   } else {
3146     lea(rscratch1, dst);
3147     incrementl(Address(rscratch1, 0));
3148   }
3149 }
3150 
3151 void MacroAssembler::incrementl(ArrayAddress dst) {
3152   incrementl(as_Address(dst));
3153 }
3154 
3155 void MacroAssembler::incrementl(Register reg, int value) {
3156   if (value == min_jint) {addl(reg, value) ; return; }
3157   if (value <  0) { decrementl(reg, -value); return; }
3158   if (value == 0) {                        ; return; }
3159   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3160   /* else */      { addl(reg, value)       ; return; }
3161 }
3162 
3163 void MacroAssembler::incrementl(Address dst, int value) {
3164   if (value == min_jint) {addl(dst, value) ; return; }
3165   if (value <  0) { decrementl(dst, -value); return; }
3166   if (value == 0) {                        ; return; }
3167   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3168   /* else */      { addl(dst, value)       ; return; }
3169 }
3170 
3171 void MacroAssembler::jump(AddressLiteral dst) {
3172   if (reachable(dst)) {
3173     jmp_literal(dst.target(), dst.rspec());
3174   } else {
3175     lea(rscratch1, dst);
3176     jmp(rscratch1);
3177   }
3178 }
3179 
3180 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3181   if (reachable(dst)) {
3182     InstructionMark im(this);
3183     relocate(dst.reloc());
3184     const int short_size = 2;
3185     const int long_size = 6;
3186     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3187     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3188       // 0111 tttn #8-bit disp
3189       emit_int8(0x70 | cc);
3190       emit_int8((offs - short_size) & 0xFF);
3191     } else {
3192       // 0000 1111 1000 tttn #32-bit disp
3193       emit_int8(0x0F);
3194       emit_int8((unsigned char)(0x80 | cc));
3195       emit_int32(offs - long_size);
3196     }
3197   } else {
3198 #ifdef ASSERT
3199     warning("reversing conditional branch");
3200 #endif /* ASSERT */
3201     Label skip;
3202     jccb(reverse[cc], skip);
3203     lea(rscratch1, dst);
3204     Assembler::jmp(rscratch1);
3205     bind(skip);
3206   }
3207 }
3208 
3209 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3210   if (reachable(src)) {
3211     Assembler::ldmxcsr(as_Address(src));
3212   } else {
3213     lea(rscratch1, src);
3214     Assembler::ldmxcsr(Address(rscratch1, 0));
3215   }
3216 }
3217 
3218 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3219   int off;
3220   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3221     off = offset();
3222     movsbl(dst, src); // movsxb
3223   } else {
3224     off = load_unsigned_byte(dst, src);
3225     shll(dst, 24);
3226     sarl(dst, 24);
3227   }
3228   return off;
3229 }
3230 
3231 // Note: load_signed_short used to be called load_signed_word.
3232 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3233 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3234 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3235 int MacroAssembler::load_signed_short(Register dst, Address src) {
3236   int off;
3237   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3238     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3239     // version but this is what 64bit has always done. This seems to imply
3240     // that users are only using 32bits worth.
3241     off = offset();
3242     movswl(dst, src); // movsxw
3243   } else {
3244     off = load_unsigned_short(dst, src);
3245     shll(dst, 16);
3246     sarl(dst, 16);
3247   }
3248   return off;
3249 }
3250 
3251 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3252   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3253   // and "3.9 Partial Register Penalties", p. 22).
3254   int off;
3255   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3256     off = offset();
3257     movzbl(dst, src); // movzxb
3258   } else {
3259     xorl(dst, dst);
3260     off = offset();
3261     movb(dst, src);
3262   }
3263   return off;
3264 }
3265 
3266 // Note: load_unsigned_short used to be called load_unsigned_word.
3267 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3268   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3269   // and "3.9 Partial Register Penalties", p. 22).
3270   int off;
3271   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3272     off = offset();
3273     movzwl(dst, src); // movzxw
3274   } else {
3275     xorl(dst, dst);
3276     off = offset();
3277     movw(dst, src);
3278   }
3279   return off;
3280 }
3281 
3282 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3283   switch (size_in_bytes) {
3284 #ifndef _LP64
3285   case  8:
3286     assert(dst2 != noreg, "second dest register required");
3287     movl(dst,  src);
3288     movl(dst2, src.plus_disp(BytesPerInt));
3289     break;
3290 #else
3291   case  8:  movq(dst, src); break;
3292 #endif
3293   case  4:  movl(dst, src); break;
3294   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3295   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3296   default:  ShouldNotReachHere();
3297   }
3298 }
3299 
3300 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3301   switch (size_in_bytes) {
3302 #ifndef _LP64
3303   case  8:
3304     assert(src2 != noreg, "second source register required");
3305     movl(dst,                        src);
3306     movl(dst.plus_disp(BytesPerInt), src2);
3307     break;
3308 #else
3309   case  8:  movq(dst, src); break;
3310 #endif
3311   case  4:  movl(dst, src); break;
3312   case  2:  movw(dst, src); break;
3313   case  1:  movb(dst, src); break;
3314   default:  ShouldNotReachHere();
3315   }
3316 }
3317 
3318 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3319   if (reachable(dst)) {
3320     movl(as_Address(dst), src);
3321   } else {
3322     lea(rscratch1, dst);
3323     movl(Address(rscratch1, 0), src);
3324   }
3325 }
3326 
3327 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3328   if (reachable(src)) {
3329     movl(dst, as_Address(src));
3330   } else {
3331     lea(rscratch1, src);
3332     movl(dst, Address(rscratch1, 0));
3333   }
3334 }
3335 
3336 // C++ bool manipulation
3337 
3338 void MacroAssembler::movbool(Register dst, Address src) {
3339   if(sizeof(bool) == 1)
3340     movb(dst, src);
3341   else if(sizeof(bool) == 2)
3342     movw(dst, src);
3343   else if(sizeof(bool) == 4)
3344     movl(dst, src);
3345   else
3346     // unsupported
3347     ShouldNotReachHere();
3348 }
3349 
3350 void MacroAssembler::movbool(Address dst, bool boolconst) {
3351   if(sizeof(bool) == 1)
3352     movb(dst, (int) boolconst);
3353   else if(sizeof(bool) == 2)
3354     movw(dst, (int) boolconst);
3355   else if(sizeof(bool) == 4)
3356     movl(dst, (int) boolconst);
3357   else
3358     // unsupported
3359     ShouldNotReachHere();
3360 }
3361 
3362 void MacroAssembler::movbool(Address dst, Register src) {
3363   if(sizeof(bool) == 1)
3364     movb(dst, src);
3365   else if(sizeof(bool) == 2)
3366     movw(dst, src);
3367   else if(sizeof(bool) == 4)
3368     movl(dst, src);
3369   else
3370     // unsupported
3371     ShouldNotReachHere();
3372 }
3373 
3374 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3375   movb(as_Address(dst), src);
3376 }
3377 
3378 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3379   if (reachable(src)) {
3380     movdl(dst, as_Address(src));
3381   } else {
3382     lea(rscratch1, src);
3383     movdl(dst, Address(rscratch1, 0));
3384   }
3385 }
3386 
3387 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3388   if (reachable(src)) {
3389     movq(dst, as_Address(src));
3390   } else {
3391     lea(rscratch1, src);
3392     movq(dst, Address(rscratch1, 0));
3393   }
3394 }
3395 
3396 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3397   if (reachable(src)) {
3398     if (UseXmmLoadAndClearUpper) {
3399       movsd (dst, as_Address(src));
3400     } else {
3401       movlpd(dst, as_Address(src));
3402     }
3403   } else {
3404     lea(rscratch1, src);
3405     if (UseXmmLoadAndClearUpper) {
3406       movsd (dst, Address(rscratch1, 0));
3407     } else {
3408       movlpd(dst, Address(rscratch1, 0));
3409     }
3410   }
3411 }
3412 
3413 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3414   if (reachable(src)) {
3415     movss(dst, as_Address(src));
3416   } else {
3417     lea(rscratch1, src);
3418     movss(dst, Address(rscratch1, 0));
3419   }
3420 }
3421 
3422 void MacroAssembler::movptr(Register dst, Register src) {
3423   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3424 }
3425 
3426 void MacroAssembler::movptr(Register dst, Address src) {
3427   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3428 }
3429 
3430 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3431 void MacroAssembler::movptr(Register dst, intptr_t src) {
3432   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3433 }
3434 
3435 void MacroAssembler::movptr(Address dst, Register src) {
3436   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3437 }
3438 
3439 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3440   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3441     Assembler::vextractf32x4h(dst, src, 0);
3442   } else {
3443     Assembler::movdqu(dst, src);
3444   }
3445 }
3446 
3447 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3448   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3449     Assembler::vinsertf32x4h(dst, src, 0);
3450   } else {
3451     Assembler::movdqu(dst, src);
3452   }
3453 }
3454 
3455 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3456   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3457     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3458   } else {
3459     Assembler::movdqu(dst, src);
3460   }
3461 }
3462 
3463 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src) {
3464   if (reachable(src)) {
3465     movdqu(dst, as_Address(src));
3466   } else {
3467     lea(rscratch1, src);
3468     movdqu(dst, Address(rscratch1, 0));
3469   }
3470 }
3471 
3472 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3473   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3474     Assembler::vextractf64x4h(dst, src, 0);
3475   } else {
3476     Assembler::vmovdqu(dst, src);
3477   }
3478 }
3479 
3480 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3481   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3482     Assembler::vinsertf64x4h(dst, src, 0);
3483   } else {
3484     Assembler::vmovdqu(dst, src);
3485   }
3486 }
3487 
3488 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3489   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3490     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3491   }
3492   else {
3493     Assembler::vmovdqu(dst, src);
3494   }
3495 }
3496 
3497 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3498   if (reachable(src)) {
3499     vmovdqu(dst, as_Address(src));
3500   }
3501   else {
3502     lea(rscratch1, src);
3503     vmovdqu(dst, Address(rscratch1, 0));
3504   }
3505 }
3506 
3507 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3508   if (reachable(src)) {
3509     Assembler::movdqa(dst, as_Address(src));
3510   } else {
3511     lea(rscratch1, src);
3512     Assembler::movdqa(dst, Address(rscratch1, 0));
3513   }
3514 }
3515 
3516 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3517   if (reachable(src)) {
3518     Assembler::movsd(dst, as_Address(src));
3519   } else {
3520     lea(rscratch1, src);
3521     Assembler::movsd(dst, Address(rscratch1, 0));
3522   }
3523 }
3524 
3525 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3526   if (reachable(src)) {
3527     Assembler::movss(dst, as_Address(src));
3528   } else {
3529     lea(rscratch1, src);
3530     Assembler::movss(dst, Address(rscratch1, 0));
3531   }
3532 }
3533 
3534 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3535   if (reachable(src)) {
3536     Assembler::mulsd(dst, as_Address(src));
3537   } else {
3538     lea(rscratch1, src);
3539     Assembler::mulsd(dst, Address(rscratch1, 0));
3540   }
3541 }
3542 
3543 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3544   if (reachable(src)) {
3545     Assembler::mulss(dst, as_Address(src));
3546   } else {
3547     lea(rscratch1, src);
3548     Assembler::mulss(dst, Address(rscratch1, 0));
3549   }
3550 }
3551 
3552 void MacroAssembler::null_check(Register reg, int offset) {
3553   if (needs_explicit_null_check(offset)) {
3554     // provoke OS NULL exception if reg = NULL by
3555     // accessing M[reg] w/o changing any (non-CC) registers
3556     // NOTE: cmpl is plenty here to provoke a segv
3557     cmpptr(rax, Address(reg, 0));
3558     // Note: should probably use testl(rax, Address(reg, 0));
3559     //       may be shorter code (however, this version of
3560     //       testl needs to be implemented first)
3561   } else {
3562     // nothing to do, (later) access of M[reg + offset]
3563     // will provoke OS NULL exception if reg = NULL
3564   }
3565 }
3566 
3567 void MacroAssembler::os_breakpoint() {
3568   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3569   // (e.g., MSVC can't call ps() otherwise)
3570   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3571 }
3572 
3573 #ifdef _LP64
3574 #define XSTATE_BV 0x200
3575 #endif
3576 
3577 void MacroAssembler::pop_CPU_state() {
3578   pop_FPU_state();
3579   pop_IU_state();
3580 }
3581 
3582 void MacroAssembler::pop_FPU_state() {
3583 #ifndef _LP64
3584   frstor(Address(rsp, 0));
3585 #else
3586   fxrstor(Address(rsp, 0));
3587 #endif
3588   addptr(rsp, FPUStateSizeInWords * wordSize);
3589 }
3590 
3591 void MacroAssembler::pop_IU_state() {
3592   popa();
3593   LP64_ONLY(addq(rsp, 8));
3594   popf();
3595 }
3596 
3597 // Save Integer and Float state
3598 // Warning: Stack must be 16 byte aligned (64bit)
3599 void MacroAssembler::push_CPU_state() {
3600   push_IU_state();
3601   push_FPU_state();
3602 }
3603 
3604 void MacroAssembler::push_FPU_state() {
3605   subptr(rsp, FPUStateSizeInWords * wordSize);
3606 #ifndef _LP64
3607   fnsave(Address(rsp, 0));
3608   fwait();
3609 #else
3610   fxsave(Address(rsp, 0));
3611 #endif // LP64
3612 }
3613 
3614 void MacroAssembler::push_IU_state() {
3615   // Push flags first because pusha kills them
3616   pushf();
3617   // Make sure rsp stays 16-byte aligned
3618   LP64_ONLY(subq(rsp, 8));
3619   pusha();
3620 }
3621 
3622 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp, bool clear_pc) {
3623   // determine java_thread register
3624   if (!java_thread->is_valid()) {
3625     java_thread = rdi;
3626     get_thread(java_thread);
3627   }
3628   // we must set sp to zero to clear frame
3629   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3630   if (clear_fp) {
3631     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3632   }
3633 
3634   if (clear_pc)
3635     movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3636 
3637 }
3638 
3639 void MacroAssembler::restore_rax(Register tmp) {
3640   if (tmp == noreg) pop(rax);
3641   else if (tmp != rax) mov(rax, tmp);
3642 }
3643 
3644 void MacroAssembler::round_to(Register reg, int modulus) {
3645   addptr(reg, modulus - 1);
3646   andptr(reg, -modulus);
3647 }
3648 
3649 void MacroAssembler::save_rax(Register tmp) {
3650   if (tmp == noreg) push(rax);
3651   else if (tmp != rax) mov(tmp, rax);
3652 }
3653 
3654 // Write serialization page so VM thread can do a pseudo remote membar.
3655 // We use the current thread pointer to calculate a thread specific
3656 // offset to write to within the page. This minimizes bus traffic
3657 // due to cache line collision.
3658 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3659   movl(tmp, thread);
3660   shrl(tmp, os::get_serialize_page_shift_count());
3661   andl(tmp, (os::vm_page_size() - sizeof(int)));
3662 
3663   Address index(noreg, tmp, Address::times_1);
3664   ExternalAddress page(os::get_memory_serialize_page());
3665 
3666   // Size of store must match masking code above
3667   movl(as_Address(ArrayAddress(page, index)), tmp);
3668 }
3669 
3670 // Calls to C land
3671 //
3672 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3673 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3674 // has to be reset to 0. This is required to allow proper stack traversal.
3675 void MacroAssembler::set_last_Java_frame(Register java_thread,
3676                                          Register last_java_sp,
3677                                          Register last_java_fp,
3678                                          address  last_java_pc) {
3679   // determine java_thread register
3680   if (!java_thread->is_valid()) {
3681     java_thread = rdi;
3682     get_thread(java_thread);
3683   }
3684   // determine last_java_sp register
3685   if (!last_java_sp->is_valid()) {
3686     last_java_sp = rsp;
3687   }
3688 
3689   // last_java_fp is optional
3690 
3691   if (last_java_fp->is_valid()) {
3692     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3693   }
3694 
3695   // last_java_pc is optional
3696 
3697   if (last_java_pc != NULL) {
3698     lea(Address(java_thread,
3699                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3700         InternalAddress(last_java_pc));
3701 
3702   }
3703   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3704 }
3705 
3706 void MacroAssembler::shlptr(Register dst, int imm8) {
3707   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3708 }
3709 
3710 void MacroAssembler::shrptr(Register dst, int imm8) {
3711   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3712 }
3713 
3714 void MacroAssembler::sign_extend_byte(Register reg) {
3715   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3716     movsbl(reg, reg); // movsxb
3717   } else {
3718     shll(reg, 24);
3719     sarl(reg, 24);
3720   }
3721 }
3722 
3723 void MacroAssembler::sign_extend_short(Register reg) {
3724   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3725     movswl(reg, reg); // movsxw
3726   } else {
3727     shll(reg, 16);
3728     sarl(reg, 16);
3729   }
3730 }
3731 
3732 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3733   assert(reachable(src), "Address should be reachable");
3734   testl(dst, as_Address(src));
3735 }
3736 
3737 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3738   int dst_enc = dst->encoding();
3739   int src_enc = src->encoding();
3740   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3741     Assembler::pcmpeqb(dst, src);
3742   } else if ((dst_enc < 16) && (src_enc < 16)) {
3743     Assembler::pcmpeqb(dst, src);
3744   } else if (src_enc < 16) {
3745     subptr(rsp, 64);
3746     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3747     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3748     Assembler::pcmpeqb(xmm0, src);
3749     movdqu(dst, xmm0);
3750     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3751     addptr(rsp, 64);
3752   } else if (dst_enc < 16) {
3753     subptr(rsp, 64);
3754     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3755     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3756     Assembler::pcmpeqb(dst, xmm0);
3757     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3758     addptr(rsp, 64);
3759   } else {
3760     subptr(rsp, 64);
3761     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3762     subptr(rsp, 64);
3763     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3764     movdqu(xmm0, src);
3765     movdqu(xmm1, dst);
3766     Assembler::pcmpeqb(xmm1, xmm0);
3767     movdqu(dst, xmm1);
3768     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3769     addptr(rsp, 64);
3770     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3771     addptr(rsp, 64);
3772   }
3773 }
3774 
3775 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3776   int dst_enc = dst->encoding();
3777   int src_enc = src->encoding();
3778   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3779     Assembler::pcmpeqw(dst, src);
3780   } else if ((dst_enc < 16) && (src_enc < 16)) {
3781     Assembler::pcmpeqw(dst, src);
3782   } else if (src_enc < 16) {
3783     subptr(rsp, 64);
3784     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3785     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3786     Assembler::pcmpeqw(xmm0, src);
3787     movdqu(dst, xmm0);
3788     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3789     addptr(rsp, 64);
3790   } else if (dst_enc < 16) {
3791     subptr(rsp, 64);
3792     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3793     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3794     Assembler::pcmpeqw(dst, xmm0);
3795     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3796     addptr(rsp, 64);
3797   } else {
3798     subptr(rsp, 64);
3799     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3800     subptr(rsp, 64);
3801     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3802     movdqu(xmm0, src);
3803     movdqu(xmm1, dst);
3804     Assembler::pcmpeqw(xmm1, xmm0);
3805     movdqu(dst, xmm1);
3806     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3807     addptr(rsp, 64);
3808     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3809     addptr(rsp, 64);
3810   }
3811 }
3812 
3813 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3814   int dst_enc = dst->encoding();
3815   if (dst_enc < 16) {
3816     Assembler::pcmpestri(dst, src, imm8);
3817   } else {
3818     subptr(rsp, 64);
3819     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3820     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3821     Assembler::pcmpestri(xmm0, src, imm8);
3822     movdqu(dst, xmm0);
3823     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3824     addptr(rsp, 64);
3825   }
3826 }
3827 
3828 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3829   int dst_enc = dst->encoding();
3830   int src_enc = src->encoding();
3831   if ((dst_enc < 16) && (src_enc < 16)) {
3832     Assembler::pcmpestri(dst, src, imm8);
3833   } else if (src_enc < 16) {
3834     subptr(rsp, 64);
3835     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3836     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3837     Assembler::pcmpestri(xmm0, src, imm8);
3838     movdqu(dst, xmm0);
3839     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3840     addptr(rsp, 64);
3841   } else if (dst_enc < 16) {
3842     subptr(rsp, 64);
3843     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3844     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3845     Assembler::pcmpestri(dst, xmm0, imm8);
3846     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3847     addptr(rsp, 64);
3848   } else {
3849     subptr(rsp, 64);
3850     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3851     subptr(rsp, 64);
3852     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3853     movdqu(xmm0, src);
3854     movdqu(xmm1, dst);
3855     Assembler::pcmpestri(xmm1, xmm0, imm8);
3856     movdqu(dst, xmm1);
3857     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3858     addptr(rsp, 64);
3859     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3860     addptr(rsp, 64);
3861   }
3862 }
3863 
3864 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
3865   int dst_enc = dst->encoding();
3866   int src_enc = src->encoding();
3867   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3868     Assembler::pmovzxbw(dst, src);
3869   } else if ((dst_enc < 16) && (src_enc < 16)) {
3870     Assembler::pmovzxbw(dst, src);
3871   } else if (src_enc < 16) {
3872     subptr(rsp, 64);
3873     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3874     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3875     Assembler::pmovzxbw(xmm0, src);
3876     movdqu(dst, xmm0);
3877     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3878     addptr(rsp, 64);
3879   } else if (dst_enc < 16) {
3880     subptr(rsp, 64);
3881     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3882     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3883     Assembler::pmovzxbw(dst, xmm0);
3884     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3885     addptr(rsp, 64);
3886   } else {
3887     subptr(rsp, 64);
3888     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3889     subptr(rsp, 64);
3890     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3891     movdqu(xmm0, src);
3892     movdqu(xmm1, dst);
3893     Assembler::pmovzxbw(xmm1, xmm0);
3894     movdqu(dst, xmm1);
3895     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3896     addptr(rsp, 64);
3897     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3898     addptr(rsp, 64);
3899   }
3900 }
3901 
3902 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
3903   int dst_enc = dst->encoding();
3904   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3905     Assembler::pmovzxbw(dst, src);
3906   } else if (dst_enc < 16) {
3907     Assembler::pmovzxbw(dst, src);
3908   } else {
3909     subptr(rsp, 64);
3910     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3911     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3912     Assembler::pmovzxbw(xmm0, src);
3913     movdqu(dst, xmm0);
3914     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3915     addptr(rsp, 64);
3916   }
3917 }
3918 
3919 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
3920   int src_enc = src->encoding();
3921   if (src_enc < 16) {
3922     Assembler::pmovmskb(dst, src);
3923   } else {
3924     subptr(rsp, 64);
3925     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3926     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3927     Assembler::pmovmskb(dst, xmm0);
3928     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3929     addptr(rsp, 64);
3930   }
3931 }
3932 
3933 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
3934   int dst_enc = dst->encoding();
3935   int src_enc = src->encoding();
3936   if ((dst_enc < 16) && (src_enc < 16)) {
3937     Assembler::ptest(dst, src);
3938   } else if (src_enc < 16) {
3939     subptr(rsp, 64);
3940     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3941     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3942     Assembler::ptest(xmm0, src);
3943     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3944     addptr(rsp, 64);
3945   } else if (dst_enc < 16) {
3946     subptr(rsp, 64);
3947     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3948     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3949     Assembler::ptest(dst, xmm0);
3950     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3951     addptr(rsp, 64);
3952   } else {
3953     subptr(rsp, 64);
3954     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3955     subptr(rsp, 64);
3956     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3957     movdqu(xmm0, src);
3958     movdqu(xmm1, dst);
3959     Assembler::ptest(xmm1, xmm0);
3960     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3961     addptr(rsp, 64);
3962     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3963     addptr(rsp, 64);
3964   }
3965 }
3966 
3967 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
3968   if (reachable(src)) {
3969     Assembler::sqrtsd(dst, as_Address(src));
3970   } else {
3971     lea(rscratch1, src);
3972     Assembler::sqrtsd(dst, Address(rscratch1, 0));
3973   }
3974 }
3975 
3976 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
3977   if (reachable(src)) {
3978     Assembler::sqrtss(dst, as_Address(src));
3979   } else {
3980     lea(rscratch1, src);
3981     Assembler::sqrtss(dst, Address(rscratch1, 0));
3982   }
3983 }
3984 
3985 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
3986   if (reachable(src)) {
3987     Assembler::subsd(dst, as_Address(src));
3988   } else {
3989     lea(rscratch1, src);
3990     Assembler::subsd(dst, Address(rscratch1, 0));
3991   }
3992 }
3993 
3994 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
3995   if (reachable(src)) {
3996     Assembler::subss(dst, as_Address(src));
3997   } else {
3998     lea(rscratch1, src);
3999     Assembler::subss(dst, Address(rscratch1, 0));
4000   }
4001 }
4002 
4003 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4004   if (reachable(src)) {
4005     Assembler::ucomisd(dst, as_Address(src));
4006   } else {
4007     lea(rscratch1, src);
4008     Assembler::ucomisd(dst, Address(rscratch1, 0));
4009   }
4010 }
4011 
4012 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4013   if (reachable(src)) {
4014     Assembler::ucomiss(dst, as_Address(src));
4015   } else {
4016     lea(rscratch1, src);
4017     Assembler::ucomiss(dst, Address(rscratch1, 0));
4018   }
4019 }
4020 
4021 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4022   // Used in sign-bit flipping with aligned address.
4023   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4024   if (reachable(src)) {
4025     Assembler::xorpd(dst, as_Address(src));
4026   } else {
4027     lea(rscratch1, src);
4028     Assembler::xorpd(dst, Address(rscratch1, 0));
4029   }
4030 }
4031 
4032 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4033   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4034     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4035   }
4036   else {
4037     Assembler::xorpd(dst, src);
4038   }
4039 }
4040 
4041 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4042   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4043     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4044   } else {
4045     Assembler::xorps(dst, src);
4046   }
4047 }
4048 
4049 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4050   // Used in sign-bit flipping with aligned address.
4051   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4052   if (reachable(src)) {
4053     Assembler::xorps(dst, as_Address(src));
4054   } else {
4055     lea(rscratch1, src);
4056     Assembler::xorps(dst, Address(rscratch1, 0));
4057   }
4058 }
4059 
4060 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4061   // Used in sign-bit flipping with aligned address.
4062   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4063   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4064   if (reachable(src)) {
4065     Assembler::pshufb(dst, as_Address(src));
4066   } else {
4067     lea(rscratch1, src);
4068     Assembler::pshufb(dst, Address(rscratch1, 0));
4069   }
4070 }
4071 
4072 // AVX 3-operands instructions
4073 
4074 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4075   if (reachable(src)) {
4076     vaddsd(dst, nds, as_Address(src));
4077   } else {
4078     lea(rscratch1, src);
4079     vaddsd(dst, nds, Address(rscratch1, 0));
4080   }
4081 }
4082 
4083 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4084   if (reachable(src)) {
4085     vaddss(dst, nds, as_Address(src));
4086   } else {
4087     lea(rscratch1, src);
4088     vaddss(dst, nds, Address(rscratch1, 0));
4089   }
4090 }
4091 
4092 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4093   int dst_enc = dst->encoding();
4094   int nds_enc = nds->encoding();
4095   int src_enc = src->encoding();
4096   if ((dst_enc < 16) && (nds_enc < 16)) {
4097     vandps(dst, nds, negate_field, vector_len);
4098   } else if ((src_enc < 16) && (dst_enc < 16)) {
4099     movss(src, nds);
4100     vandps(dst, src, negate_field, vector_len);
4101   } else if (src_enc < 16) {
4102     movss(src, nds);
4103     vandps(src, src, negate_field, vector_len);
4104     movss(dst, src);
4105   } else if (dst_enc < 16) {
4106     movdqu(src, xmm0);
4107     movss(xmm0, nds);
4108     vandps(dst, xmm0, negate_field, vector_len);
4109     movdqu(xmm0, src);
4110   } else if (nds_enc < 16) {
4111     movdqu(src, xmm0);
4112     vandps(xmm0, nds, negate_field, vector_len);
4113     movss(dst, xmm0);
4114     movdqu(xmm0, src);
4115   } else {
4116     movdqu(src, xmm0);
4117     movss(xmm0, nds);
4118     vandps(xmm0, xmm0, negate_field, vector_len);
4119     movss(dst, xmm0);
4120     movdqu(xmm0, src);
4121   }
4122 }
4123 
4124 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4125   int dst_enc = dst->encoding();
4126   int nds_enc = nds->encoding();
4127   int src_enc = src->encoding();
4128   if ((dst_enc < 16) && (nds_enc < 16)) {
4129     vandpd(dst, nds, negate_field, vector_len);
4130   } else if ((src_enc < 16) && (dst_enc < 16)) {
4131     movsd(src, nds);
4132     vandpd(dst, src, negate_field, vector_len);
4133   } else if (src_enc < 16) {
4134     movsd(src, nds);
4135     vandpd(src, src, negate_field, vector_len);
4136     movsd(dst, src);
4137   } else if (dst_enc < 16) {
4138     movdqu(src, xmm0);
4139     movsd(xmm0, nds);
4140     vandpd(dst, xmm0, negate_field, vector_len);
4141     movdqu(xmm0, src);
4142   } else if (nds_enc < 16) {
4143     movdqu(src, xmm0);
4144     vandpd(xmm0, nds, negate_field, vector_len);
4145     movsd(dst, xmm0);
4146     movdqu(xmm0, src);
4147   } else {
4148     movdqu(src, xmm0);
4149     movsd(xmm0, nds);
4150     vandpd(xmm0, xmm0, negate_field, vector_len);
4151     movsd(dst, xmm0);
4152     movdqu(xmm0, src);
4153   }
4154 }
4155 
4156 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4157   int dst_enc = dst->encoding();
4158   int nds_enc = nds->encoding();
4159   int src_enc = src->encoding();
4160   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4161     Assembler::vpaddb(dst, nds, src, vector_len);
4162   } else if ((dst_enc < 16) && (src_enc < 16)) {
4163     Assembler::vpaddb(dst, dst, src, vector_len);
4164   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4165     // use nds as scratch for src
4166     evmovdqul(nds, src, Assembler::AVX_512bit);
4167     Assembler::vpaddb(dst, dst, nds, vector_len);
4168   } else if ((src_enc < 16) && (nds_enc < 16)) {
4169     // use nds as scratch for dst
4170     evmovdqul(nds, dst, Assembler::AVX_512bit);
4171     Assembler::vpaddb(nds, nds, src, vector_len);
4172     evmovdqul(dst, nds, Assembler::AVX_512bit);
4173   } else if (dst_enc < 16) {
4174     // use nds as scatch for xmm0 to hold src
4175     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4176     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4177     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4178     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4179   } else {
4180     // worse case scenario, all regs are in the upper bank
4181     subptr(rsp, 64);
4182     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4183     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4184     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4185     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4186     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4187     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4188     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4189     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4190     addptr(rsp, 64);
4191   }
4192 }
4193 
4194 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4195   int dst_enc = dst->encoding();
4196   int nds_enc = nds->encoding();
4197   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4198     Assembler::vpaddb(dst, nds, src, vector_len);
4199   } else if (dst_enc < 16) {
4200     Assembler::vpaddb(dst, dst, src, vector_len);
4201   } else if (nds_enc < 16) {
4202     // implies dst_enc in upper bank with src as scratch
4203     evmovdqul(nds, dst, Assembler::AVX_512bit);
4204     Assembler::vpaddb(nds, nds, src, vector_len);
4205     evmovdqul(dst, nds, Assembler::AVX_512bit);
4206   } else {
4207     // worse case scenario, all regs in upper bank
4208     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4209     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4210     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4211     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4212   }
4213 }
4214 
4215 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4216   int dst_enc = dst->encoding();
4217   int nds_enc = nds->encoding();
4218   int src_enc = src->encoding();
4219   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4220     Assembler::vpaddw(dst, nds, src, vector_len);
4221   } else if ((dst_enc < 16) && (src_enc < 16)) {
4222     Assembler::vpaddw(dst, dst, src, vector_len);
4223   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4224     // use nds as scratch for src
4225     evmovdqul(nds, src, Assembler::AVX_512bit);
4226     Assembler::vpaddw(dst, dst, nds, vector_len);
4227   } else if ((src_enc < 16) && (nds_enc < 16)) {
4228     // use nds as scratch for dst
4229     evmovdqul(nds, dst, Assembler::AVX_512bit);
4230     Assembler::vpaddw(nds, nds, src, vector_len);
4231     evmovdqul(dst, nds, Assembler::AVX_512bit);
4232   } else if (dst_enc < 16) {
4233     // use nds as scatch for xmm0 to hold src
4234     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4235     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4236     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4237     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4238   } else {
4239     // worse case scenario, all regs are in the upper bank
4240     subptr(rsp, 64);
4241     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4242     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4243     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4244     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4245     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4246     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4247     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4248     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4249     addptr(rsp, 64);
4250   }
4251 }
4252 
4253 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4254   int dst_enc = dst->encoding();
4255   int nds_enc = nds->encoding();
4256   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4257     Assembler::vpaddw(dst, nds, src, vector_len);
4258   } else if (dst_enc < 16) {
4259     Assembler::vpaddw(dst, dst, src, vector_len);
4260   } else if (nds_enc < 16) {
4261     // implies dst_enc in upper bank with src as scratch
4262     evmovdqul(nds, dst, Assembler::AVX_512bit);
4263     Assembler::vpaddw(nds, nds, src, vector_len);
4264     evmovdqul(dst, nds, Assembler::AVX_512bit);
4265   } else {
4266     // worse case scenario, all regs in upper bank
4267     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4268     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4269     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4270     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4271   }
4272 }
4273 
4274 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4275   int dst_enc = dst->encoding();
4276   int src_enc = src->encoding();
4277   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4278     Assembler::vpbroadcastw(dst, src);
4279   } else if ((dst_enc < 16) && (src_enc < 16)) {
4280     Assembler::vpbroadcastw(dst, src);
4281   } else if (src_enc < 16) {
4282     subptr(rsp, 64);
4283     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4284     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4285     Assembler::vpbroadcastw(xmm0, src);
4286     movdqu(dst, xmm0);
4287     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4288     addptr(rsp, 64);
4289   } else if (dst_enc < 16) {
4290     subptr(rsp, 64);
4291     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4292     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4293     Assembler::vpbroadcastw(dst, xmm0);
4294     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4295     addptr(rsp, 64);
4296   } else {
4297     subptr(rsp, 64);
4298     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4299     subptr(rsp, 64);
4300     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4301     movdqu(xmm0, src);
4302     movdqu(xmm1, dst);
4303     Assembler::vpbroadcastw(xmm1, xmm0);
4304     movdqu(dst, xmm1);
4305     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4306     addptr(rsp, 64);
4307     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4308     addptr(rsp, 64);
4309   }
4310 }
4311 
4312 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4313   int dst_enc = dst->encoding();
4314   int nds_enc = nds->encoding();
4315   int src_enc = src->encoding();
4316   assert(dst_enc == nds_enc, "");
4317   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4318     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4319   } else if ((dst_enc < 16) && (src_enc < 16)) {
4320     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4321   } else if (src_enc < 16) {
4322     subptr(rsp, 64);
4323     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4324     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4325     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4326     movdqu(dst, xmm0);
4327     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4328     addptr(rsp, 64);
4329   } else if (dst_enc < 16) {
4330     subptr(rsp, 64);
4331     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4332     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4333     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4334     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4335     addptr(rsp, 64);
4336   } else {
4337     subptr(rsp, 64);
4338     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4339     subptr(rsp, 64);
4340     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4341     movdqu(xmm0, src);
4342     movdqu(xmm1, dst);
4343     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4344     movdqu(dst, xmm1);
4345     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4346     addptr(rsp, 64);
4347     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4348     addptr(rsp, 64);
4349   }
4350 }
4351 
4352 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4353   int dst_enc = dst->encoding();
4354   int nds_enc = nds->encoding();
4355   int src_enc = src->encoding();
4356   assert(dst_enc == nds_enc, "");
4357   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4358     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4359   } else if ((dst_enc < 16) && (src_enc < 16)) {
4360     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4361   } else if (src_enc < 16) {
4362     subptr(rsp, 64);
4363     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4364     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4365     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4366     movdqu(dst, xmm0);
4367     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4368     addptr(rsp, 64);
4369   } else if (dst_enc < 16) {
4370     subptr(rsp, 64);
4371     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4372     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4373     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4374     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4375     addptr(rsp, 64);
4376   } else {
4377     subptr(rsp, 64);
4378     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4379     subptr(rsp, 64);
4380     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4381     movdqu(xmm0, src);
4382     movdqu(xmm1, dst);
4383     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4384     movdqu(dst, xmm1);
4385     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4386     addptr(rsp, 64);
4387     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4388     addptr(rsp, 64);
4389   }
4390 }
4391 
4392 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4393   int dst_enc = dst->encoding();
4394   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4395     Assembler::vpmovzxbw(dst, src, vector_len);
4396   } else if (dst_enc < 16) {
4397     Assembler::vpmovzxbw(dst, src, vector_len);
4398   } else {
4399     subptr(rsp, 64);
4400     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4401     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4402     Assembler::vpmovzxbw(xmm0, src, vector_len);
4403     movdqu(dst, xmm0);
4404     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4405     addptr(rsp, 64);
4406   }
4407 }
4408 
4409 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4410   int src_enc = src->encoding();
4411   if (src_enc < 16) {
4412     Assembler::vpmovmskb(dst, src);
4413   } else {
4414     subptr(rsp, 64);
4415     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4416     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4417     Assembler::vpmovmskb(dst, xmm0);
4418     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4419     addptr(rsp, 64);
4420   }
4421 }
4422 
4423 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4424   int dst_enc = dst->encoding();
4425   int nds_enc = nds->encoding();
4426   int src_enc = src->encoding();
4427   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4428     Assembler::vpmullw(dst, nds, src, vector_len);
4429   } else if ((dst_enc < 16) && (src_enc < 16)) {
4430     Assembler::vpmullw(dst, dst, src, vector_len);
4431   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4432     // use nds as scratch for src
4433     evmovdqul(nds, src, Assembler::AVX_512bit);
4434     Assembler::vpmullw(dst, dst, nds, vector_len);
4435   } else if ((src_enc < 16) && (nds_enc < 16)) {
4436     // use nds as scratch for dst
4437     evmovdqul(nds, dst, Assembler::AVX_512bit);
4438     Assembler::vpmullw(nds, nds, src, vector_len);
4439     evmovdqul(dst, nds, Assembler::AVX_512bit);
4440   } else if (dst_enc < 16) {
4441     // use nds as scatch for xmm0 to hold src
4442     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4443     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4444     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4445     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4446   } else {
4447     // worse case scenario, all regs are in the upper bank
4448     subptr(rsp, 64);
4449     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4450     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4451     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4452     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4453     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4454     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4455     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4456     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4457     addptr(rsp, 64);
4458   }
4459 }
4460 
4461 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4462   int dst_enc = dst->encoding();
4463   int nds_enc = nds->encoding();
4464   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4465     Assembler::vpmullw(dst, nds, src, vector_len);
4466   } else if (dst_enc < 16) {
4467     Assembler::vpmullw(dst, dst, src, vector_len);
4468   } else if (nds_enc < 16) {
4469     // implies dst_enc in upper bank with src as scratch
4470     evmovdqul(nds, dst, Assembler::AVX_512bit);
4471     Assembler::vpmullw(nds, nds, src, vector_len);
4472     evmovdqul(dst, nds, Assembler::AVX_512bit);
4473   } else {
4474     // worse case scenario, all regs in upper bank
4475     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4476     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4477     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4478     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4479   }
4480 }
4481 
4482 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4483   int dst_enc = dst->encoding();
4484   int nds_enc = nds->encoding();
4485   int src_enc = src->encoding();
4486   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4487     Assembler::vpsubb(dst, nds, src, vector_len);
4488   } else if ((dst_enc < 16) && (src_enc < 16)) {
4489     Assembler::vpsubb(dst, dst, src, vector_len);
4490   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4491     // use nds as scratch for src
4492     evmovdqul(nds, src, Assembler::AVX_512bit);
4493     Assembler::vpsubb(dst, dst, nds, vector_len);
4494   } else if ((src_enc < 16) && (nds_enc < 16)) {
4495     // use nds as scratch for dst
4496     evmovdqul(nds, dst, Assembler::AVX_512bit);
4497     Assembler::vpsubb(nds, nds, src, vector_len);
4498     evmovdqul(dst, nds, Assembler::AVX_512bit);
4499   } else if (dst_enc < 16) {
4500     // use nds as scatch for xmm0 to hold src
4501     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4502     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4503     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4504     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4505   } else {
4506     // worse case scenario, all regs are in the upper bank
4507     subptr(rsp, 64);
4508     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4509     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4510     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4511     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4512     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4513     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4514     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4515     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4516     addptr(rsp, 64);
4517   }
4518 }
4519 
4520 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4521   int dst_enc = dst->encoding();
4522   int nds_enc = nds->encoding();
4523   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4524     Assembler::vpsubb(dst, nds, src, vector_len);
4525   } else if (dst_enc < 16) {
4526     Assembler::vpsubb(dst, dst, src, vector_len);
4527   } else if (nds_enc < 16) {
4528     // implies dst_enc in upper bank with src as scratch
4529     evmovdqul(nds, dst, Assembler::AVX_512bit);
4530     Assembler::vpsubb(nds, nds, src, vector_len);
4531     evmovdqul(dst, nds, Assembler::AVX_512bit);
4532   } else {
4533     // worse case scenario, all regs in upper bank
4534     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4535     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4536     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4537     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4538   }
4539 }
4540 
4541 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4542   int dst_enc = dst->encoding();
4543   int nds_enc = nds->encoding();
4544   int src_enc = src->encoding();
4545   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4546     Assembler::vpsubw(dst, nds, src, vector_len);
4547   } else if ((dst_enc < 16) && (src_enc < 16)) {
4548     Assembler::vpsubw(dst, dst, src, vector_len);
4549   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4550     // use nds as scratch for src
4551     evmovdqul(nds, src, Assembler::AVX_512bit);
4552     Assembler::vpsubw(dst, dst, nds, vector_len);
4553   } else if ((src_enc < 16) && (nds_enc < 16)) {
4554     // use nds as scratch for dst
4555     evmovdqul(nds, dst, Assembler::AVX_512bit);
4556     Assembler::vpsubw(nds, nds, src, vector_len);
4557     evmovdqul(dst, nds, Assembler::AVX_512bit);
4558   } else if (dst_enc < 16) {
4559     // use nds as scatch for xmm0 to hold src
4560     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4561     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4562     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4563     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4564   } else {
4565     // worse case scenario, all regs are in the upper bank
4566     subptr(rsp, 64);
4567     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4568     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4569     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4570     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4571     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4572     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4573     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4574     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4575     addptr(rsp, 64);
4576   }
4577 }
4578 
4579 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4580   int dst_enc = dst->encoding();
4581   int nds_enc = nds->encoding();
4582   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4583     Assembler::vpsubw(dst, nds, src, vector_len);
4584   } else if (dst_enc < 16) {
4585     Assembler::vpsubw(dst, dst, src, vector_len);
4586   } else if (nds_enc < 16) {
4587     // implies dst_enc in upper bank with src as scratch
4588     evmovdqul(nds, dst, Assembler::AVX_512bit);
4589     Assembler::vpsubw(nds, nds, src, vector_len);
4590     evmovdqul(dst, nds, Assembler::AVX_512bit);
4591   } else {
4592     // worse case scenario, all regs in upper bank
4593     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4594     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4595     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4596     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4597   }
4598 }
4599 
4600 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4601   int dst_enc = dst->encoding();
4602   int nds_enc = nds->encoding();
4603   int shift_enc = shift->encoding();
4604   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4605     Assembler::vpsraw(dst, nds, shift, vector_len);
4606   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4607     Assembler::vpsraw(dst, dst, shift, vector_len);
4608   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4609     // use nds_enc as scratch with shift
4610     evmovdqul(nds, shift, Assembler::AVX_512bit);
4611     Assembler::vpsraw(dst, dst, nds, vector_len);
4612   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4613     // use nds as scratch with dst
4614     evmovdqul(nds, dst, Assembler::AVX_512bit);
4615     Assembler::vpsraw(nds, nds, shift, vector_len);
4616     evmovdqul(dst, nds, Assembler::AVX_512bit);
4617   } else if (dst_enc < 16) {
4618     // use nds to save a copy of xmm0 and hold shift
4619     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4620     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4621     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4622     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4623   } else if (nds_enc < 16) {
4624     // use nds as dest as temps
4625     evmovdqul(nds, dst, Assembler::AVX_512bit);
4626     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4627     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4628     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4629     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4630     evmovdqul(dst, nds, Assembler::AVX_512bit);
4631   } else {
4632     // worse case scenario, all regs are in the upper bank
4633     subptr(rsp, 64);
4634     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4635     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4636     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4637     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4638     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4639     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4640     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4641     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4642     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4643     addptr(rsp, 64);
4644   }
4645 }
4646 
4647 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4648   int dst_enc = dst->encoding();
4649   int nds_enc = nds->encoding();
4650   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4651     Assembler::vpsraw(dst, nds, shift, vector_len);
4652   } else if (dst_enc < 16) {
4653     Assembler::vpsraw(dst, dst, shift, vector_len);
4654   } else if (nds_enc < 16) {
4655     // use nds as scratch
4656     evmovdqul(nds, dst, Assembler::AVX_512bit);
4657     Assembler::vpsraw(nds, nds, shift, vector_len);
4658     evmovdqul(dst, nds, Assembler::AVX_512bit);
4659   } else {
4660     // use nds as scratch for xmm0
4661     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4662     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4663     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4664     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4665   }
4666 }
4667 
4668 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4669   int dst_enc = dst->encoding();
4670   int nds_enc = nds->encoding();
4671   int shift_enc = shift->encoding();
4672   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4673     Assembler::vpsrlw(dst, nds, shift, vector_len);
4674   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4675     Assembler::vpsrlw(dst, dst, shift, vector_len);
4676   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4677     // use nds_enc as scratch with shift
4678     evmovdqul(nds, shift, Assembler::AVX_512bit);
4679     Assembler::vpsrlw(dst, dst, nds, vector_len);
4680   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4681     // use nds as scratch with dst
4682     evmovdqul(nds, dst, Assembler::AVX_512bit);
4683     Assembler::vpsrlw(nds, nds, shift, vector_len);
4684     evmovdqul(dst, nds, Assembler::AVX_512bit);
4685   } else if (dst_enc < 16) {
4686     // use nds to save a copy of xmm0 and hold shift
4687     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4688     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4689     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4690     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4691   } else if (nds_enc < 16) {
4692     // use nds as dest as temps
4693     evmovdqul(nds, dst, Assembler::AVX_512bit);
4694     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4695     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4696     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4697     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4698     evmovdqul(dst, nds, Assembler::AVX_512bit);
4699   } else {
4700     // worse case scenario, all regs are in the upper bank
4701     subptr(rsp, 64);
4702     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4703     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4704     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4705     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4706     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4707     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4708     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4709     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4710     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4711     addptr(rsp, 64);
4712   }
4713 }
4714 
4715 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4716   int dst_enc = dst->encoding();
4717   int nds_enc = nds->encoding();
4718   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4719     Assembler::vpsrlw(dst, nds, shift, vector_len);
4720   } else if (dst_enc < 16) {
4721     Assembler::vpsrlw(dst, dst, shift, vector_len);
4722   } else if (nds_enc < 16) {
4723     // use nds as scratch
4724     evmovdqul(nds, dst, Assembler::AVX_512bit);
4725     Assembler::vpsrlw(nds, nds, shift, vector_len);
4726     evmovdqul(dst, nds, Assembler::AVX_512bit);
4727   } else {
4728     // use nds as scratch for xmm0
4729     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4730     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4731     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4732     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4733   }
4734 }
4735 
4736 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4737   int dst_enc = dst->encoding();
4738   int nds_enc = nds->encoding();
4739   int shift_enc = shift->encoding();
4740   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4741     Assembler::vpsllw(dst, nds, shift, vector_len);
4742   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4743     Assembler::vpsllw(dst, dst, shift, vector_len);
4744   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4745     // use nds_enc as scratch with shift
4746     evmovdqul(nds, shift, Assembler::AVX_512bit);
4747     Assembler::vpsllw(dst, dst, nds, vector_len);
4748   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4749     // use nds as scratch with dst
4750     evmovdqul(nds, dst, Assembler::AVX_512bit);
4751     Assembler::vpsllw(nds, nds, shift, vector_len);
4752     evmovdqul(dst, nds, Assembler::AVX_512bit);
4753   } else if (dst_enc < 16) {
4754     // use nds to save a copy of xmm0 and hold shift
4755     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4756     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4757     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4758     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4759   } else if (nds_enc < 16) {
4760     // use nds as dest as temps
4761     evmovdqul(nds, dst, Assembler::AVX_512bit);
4762     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4763     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4764     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4765     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4766     evmovdqul(dst, nds, Assembler::AVX_512bit);
4767   } else {
4768     // worse case scenario, all regs are in the upper bank
4769     subptr(rsp, 64);
4770     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4771     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4772     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4773     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4774     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4775     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4776     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4777     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4778     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4779     addptr(rsp, 64);
4780   }
4781 }
4782 
4783 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4784   int dst_enc = dst->encoding();
4785   int nds_enc = nds->encoding();
4786   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4787     Assembler::vpsllw(dst, nds, shift, vector_len);
4788   } else if (dst_enc < 16) {
4789     Assembler::vpsllw(dst, dst, shift, vector_len);
4790   } else if (nds_enc < 16) {
4791     // use nds as scratch
4792     evmovdqul(nds, dst, Assembler::AVX_512bit);
4793     Assembler::vpsllw(nds, nds, shift, vector_len);
4794     evmovdqul(dst, nds, Assembler::AVX_512bit);
4795   } else {
4796     // use nds as scratch for xmm0
4797     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4798     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4799     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4800     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4801   }
4802 }
4803 
4804 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4805   int dst_enc = dst->encoding();
4806   int src_enc = src->encoding();
4807   if ((dst_enc < 16) && (src_enc < 16)) {
4808     Assembler::vptest(dst, src);
4809   } else if (src_enc < 16) {
4810     subptr(rsp, 64);
4811     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4812     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4813     Assembler::vptest(xmm0, src);
4814     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4815     addptr(rsp, 64);
4816   } else if (dst_enc < 16) {
4817     subptr(rsp, 64);
4818     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4819     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4820     Assembler::vptest(dst, xmm0);
4821     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4822     addptr(rsp, 64);
4823   } else {
4824     subptr(rsp, 64);
4825     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4826     subptr(rsp, 64);
4827     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4828     movdqu(xmm0, src);
4829     movdqu(xmm1, dst);
4830     Assembler::vptest(xmm1, xmm0);
4831     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4832     addptr(rsp, 64);
4833     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4834     addptr(rsp, 64);
4835   }
4836 }
4837 
4838 // This instruction exists within macros, ergo we cannot control its input
4839 // when emitted through those patterns.
4840 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4841   if (VM_Version::supports_avx512nobw()) {
4842     int dst_enc = dst->encoding();
4843     int src_enc = src->encoding();
4844     if (dst_enc == src_enc) {
4845       if (dst_enc < 16) {
4846         Assembler::punpcklbw(dst, src);
4847       } else {
4848         subptr(rsp, 64);
4849         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4850         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4851         Assembler::punpcklbw(xmm0, xmm0);
4852         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4853         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4854         addptr(rsp, 64);
4855       }
4856     } else {
4857       if ((src_enc < 16) && (dst_enc < 16)) {
4858         Assembler::punpcklbw(dst, src);
4859       } else if (src_enc < 16) {
4860         subptr(rsp, 64);
4861         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4862         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4863         Assembler::punpcklbw(xmm0, src);
4864         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4865         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4866         addptr(rsp, 64);
4867       } else if (dst_enc < 16) {
4868         subptr(rsp, 64);
4869         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4870         evmovdqul(xmm0, src, Assembler::AVX_512bit);
4871         Assembler::punpcklbw(dst, xmm0);
4872         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4873         addptr(rsp, 64);
4874       } else {
4875         subptr(rsp, 64);
4876         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4877         subptr(rsp, 64);
4878         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4879         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4880         evmovdqul(xmm1, src, Assembler::AVX_512bit);
4881         Assembler::punpcklbw(xmm0, xmm1);
4882         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4883         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4884         addptr(rsp, 64);
4885         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4886         addptr(rsp, 64);
4887       }
4888     }
4889   } else {
4890     Assembler::punpcklbw(dst, src);
4891   }
4892 }
4893 
4894 // This instruction exists within macros, ergo we cannot control its input
4895 // when emitted through those patterns.
4896 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
4897   if (VM_Version::supports_avx512nobw()) {
4898     int dst_enc = dst->encoding();
4899     int src_enc = src->encoding();
4900     if (dst_enc == src_enc) {
4901       if (dst_enc < 16) {
4902         Assembler::pshuflw(dst, src, mode);
4903       } else {
4904         subptr(rsp, 64);
4905         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4906         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4907         Assembler::pshuflw(xmm0, xmm0, mode);
4908         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4909         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4910         addptr(rsp, 64);
4911       }
4912     } else {
4913       if ((src_enc < 16) && (dst_enc < 16)) {
4914         Assembler::pshuflw(dst, src, mode);
4915       } else if (src_enc < 16) {
4916         subptr(rsp, 64);
4917         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4918         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4919         Assembler::pshuflw(xmm0, src, mode);
4920         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4921         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4922         addptr(rsp, 64);
4923       } else if (dst_enc < 16) {
4924         subptr(rsp, 64);
4925         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4926         evmovdqul(xmm0, src, Assembler::AVX_512bit);
4927         Assembler::pshuflw(dst, xmm0, mode);
4928         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4929         addptr(rsp, 64);
4930       } else {
4931         subptr(rsp, 64);
4932         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4933         subptr(rsp, 64);
4934         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4935         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4936         evmovdqul(xmm1, src, Assembler::AVX_512bit);
4937         Assembler::pshuflw(xmm0, xmm1, mode);
4938         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4939         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4940         addptr(rsp, 64);
4941         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4942         addptr(rsp, 64);
4943       }
4944     }
4945   } else {
4946     Assembler::pshuflw(dst, src, mode);
4947   }
4948 }
4949 
4950 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4951   if (reachable(src)) {
4952     vandpd(dst, nds, as_Address(src), vector_len);
4953   } else {
4954     lea(rscratch1, src);
4955     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
4956   }
4957 }
4958 
4959 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4960   if (reachable(src)) {
4961     vandps(dst, nds, as_Address(src), vector_len);
4962   } else {
4963     lea(rscratch1, src);
4964     vandps(dst, nds, Address(rscratch1, 0), vector_len);
4965   }
4966 }
4967 
4968 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4969   if (reachable(src)) {
4970     vdivsd(dst, nds, as_Address(src));
4971   } else {
4972     lea(rscratch1, src);
4973     vdivsd(dst, nds, Address(rscratch1, 0));
4974   }
4975 }
4976 
4977 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4978   if (reachable(src)) {
4979     vdivss(dst, nds, as_Address(src));
4980   } else {
4981     lea(rscratch1, src);
4982     vdivss(dst, nds, Address(rscratch1, 0));
4983   }
4984 }
4985 
4986 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4987   if (reachable(src)) {
4988     vmulsd(dst, nds, as_Address(src));
4989   } else {
4990     lea(rscratch1, src);
4991     vmulsd(dst, nds, Address(rscratch1, 0));
4992   }
4993 }
4994 
4995 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4996   if (reachable(src)) {
4997     vmulss(dst, nds, as_Address(src));
4998   } else {
4999     lea(rscratch1, src);
5000     vmulss(dst, nds, Address(rscratch1, 0));
5001   }
5002 }
5003 
5004 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5005   if (reachable(src)) {
5006     vsubsd(dst, nds, as_Address(src));
5007   } else {
5008     lea(rscratch1, src);
5009     vsubsd(dst, nds, Address(rscratch1, 0));
5010   }
5011 }
5012 
5013 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5014   if (reachable(src)) {
5015     vsubss(dst, nds, as_Address(src));
5016   } else {
5017     lea(rscratch1, src);
5018     vsubss(dst, nds, Address(rscratch1, 0));
5019   }
5020 }
5021 
5022 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5023   int nds_enc = nds->encoding();
5024   int dst_enc = dst->encoding();
5025   bool dst_upper_bank = (dst_enc > 15);
5026   bool nds_upper_bank = (nds_enc > 15);
5027   if (VM_Version::supports_avx512novl() &&
5028       (nds_upper_bank || dst_upper_bank)) {
5029     if (dst_upper_bank) {
5030       subptr(rsp, 64);
5031       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5032       movflt(xmm0, nds);
5033       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5034       movflt(dst, xmm0);
5035       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5036       addptr(rsp, 64);
5037     } else {
5038       movflt(dst, nds);
5039       vxorps(dst, dst, src, Assembler::AVX_128bit);
5040     }
5041   } else {
5042     vxorps(dst, nds, src, Assembler::AVX_128bit);
5043   }
5044 }
5045 
5046 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5047   int nds_enc = nds->encoding();
5048   int dst_enc = dst->encoding();
5049   bool dst_upper_bank = (dst_enc > 15);
5050   bool nds_upper_bank = (nds_enc > 15);
5051   if (VM_Version::supports_avx512novl() &&
5052       (nds_upper_bank || dst_upper_bank)) {
5053     if (dst_upper_bank) {
5054       subptr(rsp, 64);
5055       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5056       movdbl(xmm0, nds);
5057       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5058       movdbl(dst, xmm0);
5059       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5060       addptr(rsp, 64);
5061     } else {
5062       movdbl(dst, nds);
5063       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5064     }
5065   } else {
5066     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5067   }
5068 }
5069 
5070 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5071   if (reachable(src)) {
5072     vxorpd(dst, nds, as_Address(src), vector_len);
5073   } else {
5074     lea(rscratch1, src);
5075     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5076   }
5077 }
5078 
5079 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5080   if (reachable(src)) {
5081     vxorps(dst, nds, as_Address(src), vector_len);
5082   } else {
5083     lea(rscratch1, src);
5084     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5085   }
5086 }
5087 
5088 
5089 //////////////////////////////////////////////////////////////////////////////////
5090 #if INCLUDE_ALL_GCS
5091 
5092 void MacroAssembler::g1_write_barrier_pre(Register obj,
5093                                           Register pre_val,
5094                                           Register thread,
5095                                           Register tmp,
5096                                           bool tosca_live,
5097                                           bool expand_call) {
5098 
5099   // If expand_call is true then we expand the call_VM_leaf macro
5100   // directly to skip generating the check by
5101   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
5102 
5103 #ifdef _LP64
5104   assert(thread == r15_thread, "must be");
5105 #endif // _LP64
5106 
5107   Label done;
5108   Label runtime;
5109 
5110   assert(pre_val != noreg, "check this code");
5111 
5112   if (obj != noreg) {
5113     assert_different_registers(obj, pre_val, tmp);
5114     assert(pre_val != rax, "check this code");
5115   }
5116 
5117   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5118                                        SATBMarkQueue::byte_offset_of_active()));
5119   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5120                                        SATBMarkQueue::byte_offset_of_index()));
5121   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5122                                        SATBMarkQueue::byte_offset_of_buf()));
5123 
5124 
5125   // Is marking active?
5126   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
5127     cmpl(in_progress, 0);
5128   } else {
5129     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
5130     cmpb(in_progress, 0);
5131   }
5132   jcc(Assembler::equal, done);
5133 
5134   // Do we need to load the previous value?
5135   if (obj != noreg) {
5136     load_heap_oop(pre_val, Address(obj, 0));
5137   }
5138 
5139   // Is the previous value null?
5140   cmpptr(pre_val, (int32_t) NULL_WORD);
5141   jcc(Assembler::equal, done);
5142 
5143   // Can we store original value in the thread's buffer?
5144   // Is index == 0?
5145   // (The index field is typed as size_t.)
5146 
5147   movptr(tmp, index);                   // tmp := *index_adr
5148   cmpptr(tmp, 0);                       // tmp == 0?
5149   jcc(Assembler::equal, runtime);       // If yes, goto runtime
5150 
5151   subptr(tmp, wordSize);                // tmp := tmp - wordSize
5152   movptr(index, tmp);                   // *index_adr := tmp
5153   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
5154 
5155   // Record the previous value
5156   movptr(Address(tmp, 0), pre_val);
5157   jmp(done);
5158 
5159   bind(runtime);
5160   // save the live input values
5161   if(tosca_live) push(rax);
5162 
5163   if (obj != noreg && obj != rax)
5164     push(obj);
5165 
5166   if (pre_val != rax)
5167     push(pre_val);
5168 
5169   // Calling the runtime using the regular call_VM_leaf mechanism generates
5170   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
5171   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
5172   //
5173   // If we care generating the pre-barrier without a frame (e.g. in the
5174   // intrinsified Reference.get() routine) then ebp might be pointing to
5175   // the caller frame and so this check will most likely fail at runtime.
5176   //
5177   // Expanding the call directly bypasses the generation of the check.
5178   // So when we do not have have a full interpreter frame on the stack
5179   // expand_call should be passed true.
5180 
5181   NOT_LP64( push(thread); )
5182 
5183   if (expand_call) {
5184     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
5185     pass_arg1(this, thread);
5186     pass_arg0(this, pre_val);
5187     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5188   } else {
5189     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5190   }
5191 
5192   NOT_LP64( pop(thread); )
5193 
5194   // save the live input values
5195   if (pre_val != rax)
5196     pop(pre_val);
5197 
5198   if (obj != noreg && obj != rax)
5199     pop(obj);
5200 
5201   if(tosca_live) pop(rax);
5202 
5203   bind(done);
5204 }
5205 
5206 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5207                                            Register new_val,
5208                                            Register thread,
5209                                            Register tmp,
5210                                            Register tmp2) {
5211 #ifdef _LP64
5212   assert(thread == r15_thread, "must be");
5213 #endif // _LP64
5214 
5215   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5216                                        DirtyCardQueue::byte_offset_of_index()));
5217   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5218                                        DirtyCardQueue::byte_offset_of_buf()));
5219 
5220   CardTableModRefBS* ct =
5221     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5222   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5223 
5224   Label done;
5225   Label runtime;
5226 
5227   // Does store cross heap regions?
5228 
5229   movptr(tmp, store_addr);
5230   xorptr(tmp, new_val);
5231   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5232   jcc(Assembler::equal, done);
5233 
5234   // crosses regions, storing NULL?
5235 
5236   cmpptr(new_val, (int32_t) NULL_WORD);
5237   jcc(Assembler::equal, done);
5238 
5239   // storing region crossing non-NULL, is card already dirty?
5240 
5241   const Register card_addr = tmp;
5242   const Register cardtable = tmp2;
5243 
5244   movptr(card_addr, store_addr);
5245   shrptr(card_addr, CardTableModRefBS::card_shift);
5246   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5247   // a valid address and therefore is not properly handled by the relocation code.
5248   movptr(cardtable, (intptr_t)ct->byte_map_base);
5249   addptr(card_addr, cardtable);
5250 
5251   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
5252   jcc(Assembler::equal, done);
5253 
5254   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5255   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5256   jcc(Assembler::equal, done);
5257 
5258 
5259   // storing a region crossing, non-NULL oop, card is clean.
5260   // dirty card and log.
5261 
5262   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5263 
5264   cmpl(queue_index, 0);
5265   jcc(Assembler::equal, runtime);
5266   subl(queue_index, wordSize);
5267   movptr(tmp2, buffer);
5268 #ifdef _LP64
5269   movslq(rscratch1, queue_index);
5270   addq(tmp2, rscratch1);
5271   movq(Address(tmp2, 0), card_addr);
5272 #else
5273   addl(tmp2, queue_index);
5274   movl(Address(tmp2, 0), card_addr);
5275 #endif
5276   jmp(done);
5277 
5278   bind(runtime);
5279   // save the live input values
5280   push(store_addr);
5281   push(new_val);
5282 #ifdef _LP64
5283   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5284 #else
5285   push(thread);
5286   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5287   pop(thread);
5288 #endif
5289   pop(new_val);
5290   pop(store_addr);
5291 
5292   bind(done);
5293 }
5294 
5295 #endif // INCLUDE_ALL_GCS
5296 //////////////////////////////////////////////////////////////////////////////////
5297 
5298 
5299 void MacroAssembler::store_check(Register obj, Address dst) {
5300   store_check(obj);
5301 }
5302 
5303 void MacroAssembler::store_check(Register obj) {
5304   // Does a store check for the oop in register obj. The content of
5305   // register obj is destroyed afterwards.
5306   BarrierSet* bs = Universe::heap()->barrier_set();
5307   assert(bs->kind() == BarrierSet::CardTableForRS ||
5308          bs->kind() == BarrierSet::CardTableExtension,
5309          "Wrong barrier set kind");
5310 
5311   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5312   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5313 
5314   shrptr(obj, CardTableModRefBS::card_shift);
5315 
5316   Address card_addr;
5317 
5318   // The calculation for byte_map_base is as follows:
5319   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5320   // So this essentially converts an address to a displacement and it will
5321   // never need to be relocated. On 64bit however the value may be too
5322   // large for a 32bit displacement.
5323   intptr_t disp = (intptr_t) ct->byte_map_base;
5324   if (is_simm32(disp)) {
5325     card_addr = Address(noreg, obj, Address::times_1, disp);
5326   } else {
5327     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5328     // displacement and done in a single instruction given favorable mapping and a
5329     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5330     // entry and that entry is not properly handled by the relocation code.
5331     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5332     Address index(noreg, obj, Address::times_1);
5333     card_addr = as_Address(ArrayAddress(cardtable, index));
5334   }
5335 
5336   int dirty = CardTableModRefBS::dirty_card_val();
5337   if (UseCondCardMark) {
5338     Label L_already_dirty;
5339     if (UseConcMarkSweepGC) {
5340       membar(Assembler::StoreLoad);
5341     }
5342     cmpb(card_addr, dirty);
5343     jcc(Assembler::equal, L_already_dirty);
5344     movb(card_addr, dirty);
5345     bind(L_already_dirty);
5346   } else {
5347     movb(card_addr, dirty);
5348   }
5349 }
5350 
5351 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5352   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5353 }
5354 
5355 // Force generation of a 4 byte immediate value even if it fits into 8bit
5356 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5357   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5358 }
5359 
5360 void MacroAssembler::subptr(Register dst, Register src) {
5361   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5362 }
5363 
5364 // C++ bool manipulation
5365 void MacroAssembler::testbool(Register dst) {
5366   if(sizeof(bool) == 1)
5367     testb(dst, 0xff);
5368   else if(sizeof(bool) == 2) {
5369     // testw implementation needed for two byte bools
5370     ShouldNotReachHere();
5371   } else if(sizeof(bool) == 4)
5372     testl(dst, dst);
5373   else
5374     // unsupported
5375     ShouldNotReachHere();
5376 }
5377 
5378 void MacroAssembler::testptr(Register dst, Register src) {
5379   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5380 }
5381 
5382 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5383 void MacroAssembler::tlab_allocate(Register obj,
5384                                    Register var_size_in_bytes,
5385                                    int con_size_in_bytes,
5386                                    Register t1,
5387                                    Register t2,
5388                                    Label& slow_case) {
5389   assert_different_registers(obj, t1, t2);
5390   assert_different_registers(obj, var_size_in_bytes, t1);
5391   Register end = t2;
5392   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5393 
5394   verify_tlab();
5395 
5396   NOT_LP64(get_thread(thread));
5397 
5398   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5399   if (var_size_in_bytes == noreg) {
5400     lea(end, Address(obj, con_size_in_bytes));
5401   } else {
5402     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5403   }
5404   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5405   jcc(Assembler::above, slow_case);
5406 
5407   // update the tlab top pointer
5408   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5409 
5410   // recover var_size_in_bytes if necessary
5411   if (var_size_in_bytes == end) {
5412     subptr(var_size_in_bytes, obj);
5413   }
5414   verify_tlab();
5415 }
5416 
5417 // Preserves rbx, and rdx.
5418 Register MacroAssembler::tlab_refill(Label& retry,
5419                                      Label& try_eden,
5420                                      Label& slow_case) {
5421   Register top = rax;
5422   Register t1  = rcx;
5423   Register t2  = rsi;
5424   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5425   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5426   Label do_refill, discard_tlab;
5427 
5428   if (!Universe::heap()->supports_inline_contig_alloc()) {
5429     // No allocation in the shared eden.
5430     jmp(slow_case);
5431   }
5432 
5433   NOT_LP64(get_thread(thread_reg));
5434 
5435   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5436   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5437 
5438   // calculate amount of free space
5439   subptr(t1, top);
5440   shrptr(t1, LogHeapWordSize);
5441 
5442   // Retain tlab and allocate object in shared space if
5443   // the amount free in the tlab is too large to discard.
5444   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5445   jcc(Assembler::lessEqual, discard_tlab);
5446 
5447   // Retain
5448   // %%% yuck as movptr...
5449   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5450   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5451   if (TLABStats) {
5452     // increment number of slow_allocations
5453     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5454   }
5455   jmp(try_eden);
5456 
5457   bind(discard_tlab);
5458   if (TLABStats) {
5459     // increment number of refills
5460     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5461     // accumulate wastage -- t1 is amount free in tlab
5462     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5463   }
5464 
5465   // if tlab is currently allocated (top or end != null) then
5466   // fill [top, end + alignment_reserve) with array object
5467   testptr(top, top);
5468   jcc(Assembler::zero, do_refill);
5469 
5470   // set up the mark word
5471   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5472   // set the length to the remaining space
5473   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5474   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5475   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5476   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5477   // set klass to intArrayKlass
5478   // dubious reloc why not an oop reloc?
5479   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5480   // store klass last.  concurrent gcs assumes klass length is valid if
5481   // klass field is not null.
5482   store_klass(top, t1);
5483 
5484   movptr(t1, top);
5485   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5486   incr_allocated_bytes(thread_reg, t1, 0);
5487 
5488   // refill the tlab with an eden allocation
5489   bind(do_refill);
5490   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5491   shlptr(t1, LogHeapWordSize);
5492   // allocate new tlab, address returned in top
5493   eden_allocate(top, t1, 0, t2, slow_case);
5494 
5495   // Check that t1 was preserved in eden_allocate.
5496 #ifdef ASSERT
5497   if (UseTLAB) {
5498     Label ok;
5499     Register tsize = rsi;
5500     assert_different_registers(tsize, thread_reg, t1);
5501     push(tsize);
5502     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5503     shlptr(tsize, LogHeapWordSize);
5504     cmpptr(t1, tsize);
5505     jcc(Assembler::equal, ok);
5506     STOP("assert(t1 != tlab size)");
5507     should_not_reach_here();
5508 
5509     bind(ok);
5510     pop(tsize);
5511   }
5512 #endif
5513   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5514   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5515   addptr(top, t1);
5516   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5517   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
5518   verify_tlab();
5519   jmp(retry);
5520 
5521   return thread_reg; // for use by caller
5522 }
5523 
5524 void MacroAssembler::incr_allocated_bytes(Register thread,
5525                                           Register var_size_in_bytes,
5526                                           int con_size_in_bytes,
5527                                           Register t1) {
5528   if (!thread->is_valid()) {
5529 #ifdef _LP64
5530     thread = r15_thread;
5531 #else
5532     assert(t1->is_valid(), "need temp reg");
5533     thread = t1;
5534     get_thread(thread);
5535 #endif
5536   }
5537 
5538 #ifdef _LP64
5539   if (var_size_in_bytes->is_valid()) {
5540     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5541   } else {
5542     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5543   }
5544 #else
5545   if (var_size_in_bytes->is_valid()) {
5546     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5547   } else {
5548     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5549   }
5550   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5551 #endif
5552 }
5553 
5554 void MacroAssembler::fp_runtime_fallback(address runtime_entry, int nb_args, int num_fpu_regs_in_use) {
5555   pusha();
5556 
5557   // if we are coming from c1, xmm registers may be live
5558   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
5559   if (UseAVX > 2) {
5560     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
5561   }
5562 
5563   if (UseSSE == 1)  {
5564     subptr(rsp, sizeof(jdouble)*8);
5565     for (int n = 0; n < 8; n++) {
5566       movflt(Address(rsp, n*sizeof(jdouble)), as_XMMRegister(n));
5567     }
5568   } else if (UseSSE >= 2)  {
5569     if (UseAVX > 2) {
5570       push(rbx);
5571       movl(rbx, 0xffff);
5572       kmovwl(k1, rbx);
5573       pop(rbx);
5574     }
5575 #ifdef COMPILER2
5576     if (MaxVectorSize > 16) {
5577       if(UseAVX > 2) {
5578         // Save upper half of ZMM registers
5579         subptr(rsp, 32*num_xmm_regs);
5580         for (int n = 0; n < num_xmm_regs; n++) {
5581           vextractf64x4h(Address(rsp, n*32), as_XMMRegister(n), 1);
5582         }
5583       }
5584       assert(UseAVX > 0, "256 bit vectors are supported only with AVX");
5585       // Save upper half of YMM registers
5586       subptr(rsp, 16*num_xmm_regs);
5587       for (int n = 0; n < num_xmm_regs; n++) {
5588         vextractf128h(Address(rsp, n*16), as_XMMRegister(n));
5589       }
5590     }
5591 #endif
5592     // Save whole 128bit (16 bytes) XMM registers
5593     subptr(rsp, 16*num_xmm_regs);
5594 #ifdef _LP64
5595     if (VM_Version::supports_evex()) {
5596       for (int n = 0; n < num_xmm_regs; n++) {
5597         vextractf32x4h(Address(rsp, n*16), as_XMMRegister(n), 0);
5598       }
5599     } else {
5600       for (int n = 0; n < num_xmm_regs; n++) {
5601         movdqu(Address(rsp, n*16), as_XMMRegister(n));
5602       }
5603     }
5604 #else
5605     for (int n = 0; n < num_xmm_regs; n++) {
5606       movdqu(Address(rsp, n*16), as_XMMRegister(n));
5607     }
5608 #endif
5609   }
5610 
5611   // Preserve registers across runtime call
5612   int incoming_argument_and_return_value_offset = -1;
5613   if (num_fpu_regs_in_use > 1) {
5614     // Must preserve all other FPU regs (could alternatively convert
5615     // SharedRuntime::dsin, dcos etc. into assembly routines known not to trash
5616     // FPU state, but can not trust C compiler)
5617     NEEDS_CLEANUP;
5618     // NOTE that in this case we also push the incoming argument(s) to
5619     // the stack and restore it later; we also use this stack slot to
5620     // hold the return value from dsin, dcos etc.
5621     for (int i = 0; i < num_fpu_regs_in_use; i++) {
5622       subptr(rsp, sizeof(jdouble));
5623       fstp_d(Address(rsp, 0));
5624     }
5625     incoming_argument_and_return_value_offset = sizeof(jdouble)*(num_fpu_regs_in_use-1);
5626     for (int i = nb_args-1; i >= 0; i--) {
5627       fld_d(Address(rsp, incoming_argument_and_return_value_offset-i*sizeof(jdouble)));
5628     }
5629   }
5630 
5631   subptr(rsp, nb_args*sizeof(jdouble));
5632   for (int i = 0; i < nb_args; i++) {
5633     fstp_d(Address(rsp, i*sizeof(jdouble)));
5634   }
5635 
5636 #ifdef _LP64
5637   if (nb_args > 0) {
5638     movdbl(xmm0, Address(rsp, 0));
5639   }
5640   if (nb_args > 1) {
5641     movdbl(xmm1, Address(rsp, sizeof(jdouble)));
5642   }
5643   assert(nb_args <= 2, "unsupported number of args");
5644 #endif // _LP64
5645 
5646   // NOTE: we must not use call_VM_leaf here because that requires a
5647   // complete interpreter frame in debug mode -- same bug as 4387334
5648   // MacroAssembler::call_VM_leaf_base is perfectly safe and will
5649   // do proper 64bit abi
5650 
5651   NEEDS_CLEANUP;
5652   // Need to add stack banging before this runtime call if it needs to
5653   // be taken; however, there is no generic stack banging routine at
5654   // the MacroAssembler level
5655 
5656   MacroAssembler::call_VM_leaf_base(runtime_entry, 0);
5657 
5658 #ifdef _LP64
5659   movsd(Address(rsp, 0), xmm0);
5660   fld_d(Address(rsp, 0));
5661 #endif // _LP64
5662   addptr(rsp, sizeof(jdouble)*nb_args);
5663   if (num_fpu_regs_in_use > 1) {
5664     // Must save return value to stack and then restore entire FPU
5665     // stack except incoming arguments
5666     fstp_d(Address(rsp, incoming_argument_and_return_value_offset));
5667     for (int i = 0; i < num_fpu_regs_in_use - nb_args; i++) {
5668       fld_d(Address(rsp, 0));
5669       addptr(rsp, sizeof(jdouble));
5670     }
5671     fld_d(Address(rsp, (nb_args-1)*sizeof(jdouble)));
5672     addptr(rsp, sizeof(jdouble)*nb_args);
5673   }
5674 
5675   if (UseSSE == 1)  {
5676     for (int n = 0; n < 8; n++) {
5677       movflt(as_XMMRegister(n), Address(rsp, n*sizeof(jdouble)));
5678     }
5679     addptr(rsp, sizeof(jdouble)*8);
5680   } else if (UseSSE >= 2)  {
5681     // Restore whole 128bit (16 bytes) XMM registers
5682 #ifdef _LP64
5683   if (VM_Version::supports_evex()) {
5684     for (int n = 0; n < num_xmm_regs; n++) {
5685       vinsertf32x4h(as_XMMRegister(n), Address(rsp, n*16), 0);
5686     }
5687   } else {
5688     for (int n = 0; n < num_xmm_regs; n++) {
5689       movdqu(as_XMMRegister(n), Address(rsp, n*16));
5690     }
5691   }
5692 #else
5693   for (int n = 0; n < num_xmm_regs; n++) {
5694     movdqu(as_XMMRegister(n), Address(rsp, n*16));
5695   }
5696 #endif
5697     addptr(rsp, 16*num_xmm_regs);
5698 
5699 #ifdef COMPILER2
5700     if (MaxVectorSize > 16) {
5701       // Restore upper half of YMM registers.
5702       for (int n = 0; n < num_xmm_regs; n++) {
5703         vinsertf128h(as_XMMRegister(n), Address(rsp, n*16));
5704       }
5705       addptr(rsp, 16*num_xmm_regs);
5706       if(UseAVX > 2) {
5707         for (int n = 0; n < num_xmm_regs; n++) {
5708           vinsertf64x4h(as_XMMRegister(n), Address(rsp, n*32), 1);
5709         }
5710         addptr(rsp, 32*num_xmm_regs);
5711       }
5712     }
5713 #endif
5714   }
5715   popa();
5716 }
5717 
5718 static const double     pi_4 =  0.7853981633974483;
5719 
5720 void MacroAssembler::trigfunc(char trig, int num_fpu_regs_in_use) {
5721   // A hand-coded argument reduction for values in fabs(pi/4, pi/2)
5722   // was attempted in this code; unfortunately it appears that the
5723   // switch to 80-bit precision and back causes this to be
5724   // unprofitable compared with simply performing a runtime call if
5725   // the argument is out of the (-pi/4, pi/4) range.
5726 
5727   Register tmp = noreg;
5728   if (!VM_Version::supports_cmov()) {
5729     // fcmp needs a temporary so preserve rbx,
5730     tmp = rbx;
5731     push(tmp);
5732   }
5733 
5734   Label slow_case, done;
5735 
5736   ExternalAddress pi4_adr = (address)&pi_4;
5737   if (reachable(pi4_adr)) {
5738     // x ?<= pi/4
5739     fld_d(pi4_adr);
5740     fld_s(1);                // Stack:  X  PI/4  X
5741     fabs();                  // Stack: |X| PI/4  X
5742     fcmp(tmp);
5743     jcc(Assembler::above, slow_case);
5744 
5745     // fastest case: -pi/4 <= x <= pi/4
5746     switch(trig) {
5747     case 's':
5748       fsin();
5749       break;
5750     case 'c':
5751       fcos();
5752       break;
5753     case 't':
5754       ftan();
5755       break;
5756     default:
5757       assert(false, "bad intrinsic");
5758       break;
5759     }
5760     jmp(done);
5761   }
5762 
5763   // slow case: runtime call
5764   bind(slow_case);
5765 
5766   switch(trig) {
5767   case 's':
5768     {
5769       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dsin), 1, num_fpu_regs_in_use);
5770     }
5771     break;
5772   case 'c':
5773     {
5774       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dcos), 1, num_fpu_regs_in_use);
5775     }
5776     break;
5777   case 't':
5778     {
5779       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dtan), 1, num_fpu_regs_in_use);
5780     }
5781     break;
5782   default:
5783     assert(false, "bad intrinsic");
5784     break;
5785   }
5786 
5787   // Come here with result in F-TOS
5788   bind(done);
5789 
5790   if (tmp != noreg) {
5791     pop(tmp);
5792   }
5793 }
5794 
5795 
5796 // Look up the method for a megamorphic invokeinterface call.
5797 // The target method is determined by <intf_klass, itable_index>.
5798 // The receiver klass is in recv_klass.
5799 // On success, the result will be in method_result, and execution falls through.
5800 // On failure, execution transfers to the given label.
5801 void MacroAssembler::lookup_interface_method(Register recv_klass,
5802                                              Register intf_klass,
5803                                              RegisterOrConstant itable_index,
5804                                              Register method_result,
5805                                              Register scan_temp,
5806                                              Label& L_no_such_interface) {
5807   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
5808   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5809          "caller must use same register for non-constant itable index as for method");
5810 
5811   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5812   int vtable_base = InstanceKlass::vtable_start_offset() * wordSize;
5813   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5814   int scan_step   = itableOffsetEntry::size() * wordSize;
5815   int vte_size    = vtableEntry::size() * wordSize;
5816   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5817   assert(vte_size == wordSize, "else adjust times_vte_scale");
5818 
5819   movl(scan_temp, Address(recv_klass, InstanceKlass::vtable_length_offset() * wordSize));
5820 
5821   // %%% Could store the aligned, prescaled offset in the klassoop.
5822   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5823   if (HeapWordsPerLong > 1) {
5824     // Round up to align_object_offset boundary
5825     // see code for InstanceKlass::start_of_itable!
5826     round_to(scan_temp, BytesPerLong);
5827   }
5828 
5829   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5830   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5831   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5832 
5833   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5834   //   if (scan->interface() == intf) {
5835   //     result = (klass + scan->offset() + itable_index);
5836   //   }
5837   // }
5838   Label search, found_method;
5839 
5840   for (int peel = 1; peel >= 0; peel--) {
5841     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5842     cmpptr(intf_klass, method_result);
5843 
5844     if (peel) {
5845       jccb(Assembler::equal, found_method);
5846     } else {
5847       jccb(Assembler::notEqual, search);
5848       // (invert the test to fall through to found_method...)
5849     }
5850 
5851     if (!peel)  break;
5852 
5853     bind(search);
5854 
5855     // Check that the previous entry is non-null.  A null entry means that
5856     // the receiver class doesn't implement the interface, and wasn't the
5857     // same as when the caller was compiled.
5858     testptr(method_result, method_result);
5859     jcc(Assembler::zero, L_no_such_interface);
5860     addptr(scan_temp, scan_step);
5861   }
5862 
5863   bind(found_method);
5864 
5865   // Got a hit.
5866   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5867   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5868 }
5869 
5870 
5871 // virtual method calling
5872 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5873                                            RegisterOrConstant vtable_index,
5874                                            Register method_result) {
5875   const int base = InstanceKlass::vtable_start_offset() * wordSize;
5876   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5877   Address vtable_entry_addr(recv_klass,
5878                             vtable_index, Address::times_ptr,
5879                             base + vtableEntry::method_offset_in_bytes());
5880   movptr(method_result, vtable_entry_addr);
5881 }
5882 
5883 
5884 void MacroAssembler::check_klass_subtype(Register sub_klass,
5885                            Register super_klass,
5886                            Register temp_reg,
5887                            Label& L_success) {
5888   Label L_failure;
5889   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5890   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5891   bind(L_failure);
5892 }
5893 
5894 
5895 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5896                                                    Register super_klass,
5897                                                    Register temp_reg,
5898                                                    Label* L_success,
5899                                                    Label* L_failure,
5900                                                    Label* L_slow_path,
5901                                         RegisterOrConstant super_check_offset) {
5902   assert_different_registers(sub_klass, super_klass, temp_reg);
5903   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5904   if (super_check_offset.is_register()) {
5905     assert_different_registers(sub_klass, super_klass,
5906                                super_check_offset.as_register());
5907   } else if (must_load_sco) {
5908     assert(temp_reg != noreg, "supply either a temp or a register offset");
5909   }
5910 
5911   Label L_fallthrough;
5912   int label_nulls = 0;
5913   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5914   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5915   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5916   assert(label_nulls <= 1, "at most one NULL in the batch");
5917 
5918   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5919   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5920   Address super_check_offset_addr(super_klass, sco_offset);
5921 
5922   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5923   // range of a jccb.  If this routine grows larger, reconsider at
5924   // least some of these.
5925 #define local_jcc(assembler_cond, label)                                \
5926   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5927   else                             jcc( assembler_cond, label) /*omit semi*/
5928 
5929   // Hacked jmp, which may only be used just before L_fallthrough.
5930 #define final_jmp(label)                                                \
5931   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5932   else                            jmp(label)                /*omit semi*/
5933 
5934   // If the pointers are equal, we are done (e.g., String[] elements).
5935   // This self-check enables sharing of secondary supertype arrays among
5936   // non-primary types such as array-of-interface.  Otherwise, each such
5937   // type would need its own customized SSA.
5938   // We move this check to the front of the fast path because many
5939   // type checks are in fact trivially successful in this manner,
5940   // so we get a nicely predicted branch right at the start of the check.
5941   cmpptr(sub_klass, super_klass);
5942   local_jcc(Assembler::equal, *L_success);
5943 
5944   // Check the supertype display:
5945   if (must_load_sco) {
5946     // Positive movl does right thing on LP64.
5947     movl(temp_reg, super_check_offset_addr);
5948     super_check_offset = RegisterOrConstant(temp_reg);
5949   }
5950   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5951   cmpptr(super_klass, super_check_addr); // load displayed supertype
5952 
5953   // This check has worked decisively for primary supers.
5954   // Secondary supers are sought in the super_cache ('super_cache_addr').
5955   // (Secondary supers are interfaces and very deeply nested subtypes.)
5956   // This works in the same check above because of a tricky aliasing
5957   // between the super_cache and the primary super display elements.
5958   // (The 'super_check_addr' can address either, as the case requires.)
5959   // Note that the cache is updated below if it does not help us find
5960   // what we need immediately.
5961   // So if it was a primary super, we can just fail immediately.
5962   // Otherwise, it's the slow path for us (no success at this point).
5963 
5964   if (super_check_offset.is_register()) {
5965     local_jcc(Assembler::equal, *L_success);
5966     cmpl(super_check_offset.as_register(), sc_offset);
5967     if (L_failure == &L_fallthrough) {
5968       local_jcc(Assembler::equal, *L_slow_path);
5969     } else {
5970       local_jcc(Assembler::notEqual, *L_failure);
5971       final_jmp(*L_slow_path);
5972     }
5973   } else if (super_check_offset.as_constant() == sc_offset) {
5974     // Need a slow path; fast failure is impossible.
5975     if (L_slow_path == &L_fallthrough) {
5976       local_jcc(Assembler::equal, *L_success);
5977     } else {
5978       local_jcc(Assembler::notEqual, *L_slow_path);
5979       final_jmp(*L_success);
5980     }
5981   } else {
5982     // No slow path; it's a fast decision.
5983     if (L_failure == &L_fallthrough) {
5984       local_jcc(Assembler::equal, *L_success);
5985     } else {
5986       local_jcc(Assembler::notEqual, *L_failure);
5987       final_jmp(*L_success);
5988     }
5989   }
5990 
5991   bind(L_fallthrough);
5992 
5993 #undef local_jcc
5994 #undef final_jmp
5995 }
5996 
5997 
5998 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5999                                                    Register super_klass,
6000                                                    Register temp_reg,
6001                                                    Register temp2_reg,
6002                                                    Label* L_success,
6003                                                    Label* L_failure,
6004                                                    bool set_cond_codes) {
6005   assert_different_registers(sub_klass, super_klass, temp_reg);
6006   if (temp2_reg != noreg)
6007     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
6008 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
6009 
6010   Label L_fallthrough;
6011   int label_nulls = 0;
6012   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
6013   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6014   assert(label_nulls <= 1, "at most one NULL in the batch");
6015 
6016   // a couple of useful fields in sub_klass:
6017   int ss_offset = in_bytes(Klass::secondary_supers_offset());
6018   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6019   Address secondary_supers_addr(sub_klass, ss_offset);
6020   Address super_cache_addr(     sub_klass, sc_offset);
6021 
6022   // Do a linear scan of the secondary super-klass chain.
6023   // This code is rarely used, so simplicity is a virtue here.
6024   // The repne_scan instruction uses fixed registers, which we must spill.
6025   // Don't worry too much about pre-existing connections with the input regs.
6026 
6027   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
6028   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
6029 
6030   // Get super_klass value into rax (even if it was in rdi or rcx).
6031   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
6032   if (super_klass != rax || UseCompressedOops) {
6033     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
6034     mov(rax, super_klass);
6035   }
6036   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
6037   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
6038 
6039 #ifndef PRODUCT
6040   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
6041   ExternalAddress pst_counter_addr((address) pst_counter);
6042   NOT_LP64(  incrementl(pst_counter_addr) );
6043   LP64_ONLY( lea(rcx, pst_counter_addr) );
6044   LP64_ONLY( incrementl(Address(rcx, 0)) );
6045 #endif //PRODUCT
6046 
6047   // We will consult the secondary-super array.
6048   movptr(rdi, secondary_supers_addr);
6049   // Load the array length.  (Positive movl does right thing on LP64.)
6050   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
6051   // Skip to start of data.
6052   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
6053 
6054   // Scan RCX words at [RDI] for an occurrence of RAX.
6055   // Set NZ/Z based on last compare.
6056   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
6057   // not change flags (only scas instruction which is repeated sets flags).
6058   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
6059 
6060     testptr(rax,rax); // Set Z = 0
6061     repne_scan();
6062 
6063   // Unspill the temp. registers:
6064   if (pushed_rdi)  pop(rdi);
6065   if (pushed_rcx)  pop(rcx);
6066   if (pushed_rax)  pop(rax);
6067 
6068   if (set_cond_codes) {
6069     // Special hack for the AD files:  rdi is guaranteed non-zero.
6070     assert(!pushed_rdi, "rdi must be left non-NULL");
6071     // Also, the condition codes are properly set Z/NZ on succeed/failure.
6072   }
6073 
6074   if (L_failure == &L_fallthrough)
6075         jccb(Assembler::notEqual, *L_failure);
6076   else  jcc(Assembler::notEqual, *L_failure);
6077 
6078   // Success.  Cache the super we found and proceed in triumph.
6079   movptr(super_cache_addr, super_klass);
6080 
6081   if (L_success != &L_fallthrough) {
6082     jmp(*L_success);
6083   }
6084 
6085 #undef IS_A_TEMP
6086 
6087   bind(L_fallthrough);
6088 }
6089 
6090 
6091 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
6092   if (VM_Version::supports_cmov()) {
6093     cmovl(cc, dst, src);
6094   } else {
6095     Label L;
6096     jccb(negate_condition(cc), L);
6097     movl(dst, src);
6098     bind(L);
6099   }
6100 }
6101 
6102 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
6103   if (VM_Version::supports_cmov()) {
6104     cmovl(cc, dst, src);
6105   } else {
6106     Label L;
6107     jccb(negate_condition(cc), L);
6108     movl(dst, src);
6109     bind(L);
6110   }
6111 }
6112 
6113 void MacroAssembler::verify_oop(Register reg, const char* s) {
6114   if (!VerifyOops) return;
6115 
6116   // Pass register number to verify_oop_subroutine
6117   const char* b = NULL;
6118   {
6119     ResourceMark rm;
6120     stringStream ss;
6121     ss.print("verify_oop: %s: %s", reg->name(), s);
6122     b = code_string(ss.as_string());
6123   }
6124   BLOCK_COMMENT("verify_oop {");
6125 #ifdef _LP64
6126   push(rscratch1);                    // save r10, trashed by movptr()
6127 #endif
6128   push(rax);                          // save rax,
6129   push(reg);                          // pass register argument
6130   ExternalAddress buffer((address) b);
6131   // avoid using pushptr, as it modifies scratch registers
6132   // and our contract is not to modify anything
6133   movptr(rax, buffer.addr());
6134   push(rax);
6135   // call indirectly to solve generation ordering problem
6136   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6137   call(rax);
6138   // Caller pops the arguments (oop, message) and restores rax, r10
6139   BLOCK_COMMENT("} verify_oop");
6140 }
6141 
6142 
6143 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
6144                                                       Register tmp,
6145                                                       int offset) {
6146   intptr_t value = *delayed_value_addr;
6147   if (value != 0)
6148     return RegisterOrConstant(value + offset);
6149 
6150   // load indirectly to solve generation ordering problem
6151   movptr(tmp, ExternalAddress((address) delayed_value_addr));
6152 
6153 #ifdef ASSERT
6154   { Label L;
6155     testptr(tmp, tmp);
6156     if (WizardMode) {
6157       const char* buf = NULL;
6158       {
6159         ResourceMark rm;
6160         stringStream ss;
6161         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
6162         buf = code_string(ss.as_string());
6163       }
6164       jcc(Assembler::notZero, L);
6165       STOP(buf);
6166     } else {
6167       jccb(Assembler::notZero, L);
6168       hlt();
6169     }
6170     bind(L);
6171   }
6172 #endif
6173 
6174   if (offset != 0)
6175     addptr(tmp, offset);
6176 
6177   return RegisterOrConstant(tmp);
6178 }
6179 
6180 
6181 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6182                                          int extra_slot_offset) {
6183   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6184   int stackElementSize = Interpreter::stackElementSize;
6185   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6186 #ifdef ASSERT
6187   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6188   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6189 #endif
6190   Register             scale_reg    = noreg;
6191   Address::ScaleFactor scale_factor = Address::no_scale;
6192   if (arg_slot.is_constant()) {
6193     offset += arg_slot.as_constant() * stackElementSize;
6194   } else {
6195     scale_reg    = arg_slot.as_register();
6196     scale_factor = Address::times(stackElementSize);
6197   }
6198   offset += wordSize;           // return PC is on stack
6199   return Address(rsp, scale_reg, scale_factor, offset);
6200 }
6201 
6202 
6203 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6204   if (!VerifyOops) return;
6205 
6206   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6207   // Pass register number to verify_oop_subroutine
6208   const char* b = NULL;
6209   {
6210     ResourceMark rm;
6211     stringStream ss;
6212     ss.print("verify_oop_addr: %s", s);
6213     b = code_string(ss.as_string());
6214   }
6215 #ifdef _LP64
6216   push(rscratch1);                    // save r10, trashed by movptr()
6217 #endif
6218   push(rax);                          // save rax,
6219   // addr may contain rsp so we will have to adjust it based on the push
6220   // we just did (and on 64 bit we do two pushes)
6221   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6222   // stores rax into addr which is backwards of what was intended.
6223   if (addr.uses(rsp)) {
6224     lea(rax, addr);
6225     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6226   } else {
6227     pushptr(addr);
6228   }
6229 
6230   ExternalAddress buffer((address) b);
6231   // pass msg argument
6232   // avoid using pushptr, as it modifies scratch registers
6233   // and our contract is not to modify anything
6234   movptr(rax, buffer.addr());
6235   push(rax);
6236 
6237   // call indirectly to solve generation ordering problem
6238   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6239   call(rax);
6240   // Caller pops the arguments (addr, message) and restores rax, r10.
6241 }
6242 
6243 void MacroAssembler::verify_tlab() {
6244 #ifdef ASSERT
6245   if (UseTLAB && VerifyOops) {
6246     Label next, ok;
6247     Register t1 = rsi;
6248     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6249 
6250     push(t1);
6251     NOT_LP64(push(thread_reg));
6252     NOT_LP64(get_thread(thread_reg));
6253 
6254     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6255     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6256     jcc(Assembler::aboveEqual, next);
6257     STOP("assert(top >= start)");
6258     should_not_reach_here();
6259 
6260     bind(next);
6261     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6262     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6263     jcc(Assembler::aboveEqual, ok);
6264     STOP("assert(top <= end)");
6265     should_not_reach_here();
6266 
6267     bind(ok);
6268     NOT_LP64(pop(thread_reg));
6269     pop(t1);
6270   }
6271 #endif
6272 }
6273 
6274 class ControlWord {
6275  public:
6276   int32_t _value;
6277 
6278   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6279   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6280   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6281   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6282   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6283   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6284   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6285   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6286 
6287   void print() const {
6288     // rounding control
6289     const char* rc;
6290     switch (rounding_control()) {
6291       case 0: rc = "round near"; break;
6292       case 1: rc = "round down"; break;
6293       case 2: rc = "round up  "; break;
6294       case 3: rc = "chop      "; break;
6295     };
6296     // precision control
6297     const char* pc;
6298     switch (precision_control()) {
6299       case 0: pc = "24 bits "; break;
6300       case 1: pc = "reserved"; break;
6301       case 2: pc = "53 bits "; break;
6302       case 3: pc = "64 bits "; break;
6303     };
6304     // flags
6305     char f[9];
6306     f[0] = ' ';
6307     f[1] = ' ';
6308     f[2] = (precision   ()) ? 'P' : 'p';
6309     f[3] = (underflow   ()) ? 'U' : 'u';
6310     f[4] = (overflow    ()) ? 'O' : 'o';
6311     f[5] = (zero_divide ()) ? 'Z' : 'z';
6312     f[6] = (denormalized()) ? 'D' : 'd';
6313     f[7] = (invalid     ()) ? 'I' : 'i';
6314     f[8] = '\x0';
6315     // output
6316     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6317   }
6318 
6319 };
6320 
6321 class StatusWord {
6322  public:
6323   int32_t _value;
6324 
6325   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6326   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6327   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6328   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6329   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6330   int  top() const                     { return  (_value >> 11) & 7      ; }
6331   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6332   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6333   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6334   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6335   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6336   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6337   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6338   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6339 
6340   void print() const {
6341     // condition codes
6342     char c[5];
6343     c[0] = (C3()) ? '3' : '-';
6344     c[1] = (C2()) ? '2' : '-';
6345     c[2] = (C1()) ? '1' : '-';
6346     c[3] = (C0()) ? '0' : '-';
6347     c[4] = '\x0';
6348     // flags
6349     char f[9];
6350     f[0] = (error_status()) ? 'E' : '-';
6351     f[1] = (stack_fault ()) ? 'S' : '-';
6352     f[2] = (precision   ()) ? 'P' : '-';
6353     f[3] = (underflow   ()) ? 'U' : '-';
6354     f[4] = (overflow    ()) ? 'O' : '-';
6355     f[5] = (zero_divide ()) ? 'Z' : '-';
6356     f[6] = (denormalized()) ? 'D' : '-';
6357     f[7] = (invalid     ()) ? 'I' : '-';
6358     f[8] = '\x0';
6359     // output
6360     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6361   }
6362 
6363 };
6364 
6365 class TagWord {
6366  public:
6367   int32_t _value;
6368 
6369   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6370 
6371   void print() const {
6372     printf("%04x", _value & 0xFFFF);
6373   }
6374 
6375 };
6376 
6377 class FPU_Register {
6378  public:
6379   int32_t _m0;
6380   int32_t _m1;
6381   int16_t _ex;
6382 
6383   bool is_indefinite() const           {
6384     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6385   }
6386 
6387   void print() const {
6388     char  sign = (_ex < 0) ? '-' : '+';
6389     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6390     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6391   };
6392 
6393 };
6394 
6395 class FPU_State {
6396  public:
6397   enum {
6398     register_size       = 10,
6399     number_of_registers =  8,
6400     register_mask       =  7
6401   };
6402 
6403   ControlWord  _control_word;
6404   StatusWord   _status_word;
6405   TagWord      _tag_word;
6406   int32_t      _error_offset;
6407   int32_t      _error_selector;
6408   int32_t      _data_offset;
6409   int32_t      _data_selector;
6410   int8_t       _register[register_size * number_of_registers];
6411 
6412   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6413   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6414 
6415   const char* tag_as_string(int tag) const {
6416     switch (tag) {
6417       case 0: return "valid";
6418       case 1: return "zero";
6419       case 2: return "special";
6420       case 3: return "empty";
6421     }
6422     ShouldNotReachHere();
6423     return NULL;
6424   }
6425 
6426   void print() const {
6427     // print computation registers
6428     { int t = _status_word.top();
6429       for (int i = 0; i < number_of_registers; i++) {
6430         int j = (i - t) & register_mask;
6431         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6432         st(j)->print();
6433         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6434       }
6435     }
6436     printf("\n");
6437     // print control registers
6438     printf("ctrl = "); _control_word.print(); printf("\n");
6439     printf("stat = "); _status_word .print(); printf("\n");
6440     printf("tags = "); _tag_word    .print(); printf("\n");
6441   }
6442 
6443 };
6444 
6445 class Flag_Register {
6446  public:
6447   int32_t _value;
6448 
6449   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6450   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6451   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6452   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6453   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6454   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6455   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6456 
6457   void print() const {
6458     // flags
6459     char f[8];
6460     f[0] = (overflow       ()) ? 'O' : '-';
6461     f[1] = (direction      ()) ? 'D' : '-';
6462     f[2] = (sign           ()) ? 'S' : '-';
6463     f[3] = (zero           ()) ? 'Z' : '-';
6464     f[4] = (auxiliary_carry()) ? 'A' : '-';
6465     f[5] = (parity         ()) ? 'P' : '-';
6466     f[6] = (carry          ()) ? 'C' : '-';
6467     f[7] = '\x0';
6468     // output
6469     printf("%08x  flags = %s", _value, f);
6470   }
6471 
6472 };
6473 
6474 class IU_Register {
6475  public:
6476   int32_t _value;
6477 
6478   void print() const {
6479     printf("%08x  %11d", _value, _value);
6480   }
6481 
6482 };
6483 
6484 class IU_State {
6485  public:
6486   Flag_Register _eflags;
6487   IU_Register   _rdi;
6488   IU_Register   _rsi;
6489   IU_Register   _rbp;
6490   IU_Register   _rsp;
6491   IU_Register   _rbx;
6492   IU_Register   _rdx;
6493   IU_Register   _rcx;
6494   IU_Register   _rax;
6495 
6496   void print() const {
6497     // computation registers
6498     printf("rax,  = "); _rax.print(); printf("\n");
6499     printf("rbx,  = "); _rbx.print(); printf("\n");
6500     printf("rcx  = "); _rcx.print(); printf("\n");
6501     printf("rdx  = "); _rdx.print(); printf("\n");
6502     printf("rdi  = "); _rdi.print(); printf("\n");
6503     printf("rsi  = "); _rsi.print(); printf("\n");
6504     printf("rbp,  = "); _rbp.print(); printf("\n");
6505     printf("rsp  = "); _rsp.print(); printf("\n");
6506     printf("\n");
6507     // control registers
6508     printf("flgs = "); _eflags.print(); printf("\n");
6509   }
6510 };
6511 
6512 
6513 class CPU_State {
6514  public:
6515   FPU_State _fpu_state;
6516   IU_State  _iu_state;
6517 
6518   void print() const {
6519     printf("--------------------------------------------------\n");
6520     _iu_state .print();
6521     printf("\n");
6522     _fpu_state.print();
6523     printf("--------------------------------------------------\n");
6524   }
6525 
6526 };
6527 
6528 
6529 static void _print_CPU_state(CPU_State* state) {
6530   state->print();
6531 };
6532 
6533 
6534 void MacroAssembler::print_CPU_state() {
6535   push_CPU_state();
6536   push(rsp);                // pass CPU state
6537   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6538   addptr(rsp, wordSize);       // discard argument
6539   pop_CPU_state();
6540 }
6541 
6542 
6543 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6544   static int counter = 0;
6545   FPU_State* fs = &state->_fpu_state;
6546   counter++;
6547   // For leaf calls, only verify that the top few elements remain empty.
6548   // We only need 1 empty at the top for C2 code.
6549   if( stack_depth < 0 ) {
6550     if( fs->tag_for_st(7) != 3 ) {
6551       printf("FPR7 not empty\n");
6552       state->print();
6553       assert(false, "error");
6554       return false;
6555     }
6556     return true;                // All other stack states do not matter
6557   }
6558 
6559   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6560          "bad FPU control word");
6561 
6562   // compute stack depth
6563   int i = 0;
6564   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6565   int d = i;
6566   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6567   // verify findings
6568   if (i != FPU_State::number_of_registers) {
6569     // stack not contiguous
6570     printf("%s: stack not contiguous at ST%d\n", s, i);
6571     state->print();
6572     assert(false, "error");
6573     return false;
6574   }
6575   // check if computed stack depth corresponds to expected stack depth
6576   if (stack_depth < 0) {
6577     // expected stack depth is -stack_depth or less
6578     if (d > -stack_depth) {
6579       // too many elements on the stack
6580       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6581       state->print();
6582       assert(false, "error");
6583       return false;
6584     }
6585   } else {
6586     // expected stack depth is stack_depth
6587     if (d != stack_depth) {
6588       // wrong stack depth
6589       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6590       state->print();
6591       assert(false, "error");
6592       return false;
6593     }
6594   }
6595   // everything is cool
6596   return true;
6597 }
6598 
6599 
6600 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6601   if (!VerifyFPU) return;
6602   push_CPU_state();
6603   push(rsp);                // pass CPU state
6604   ExternalAddress msg((address) s);
6605   // pass message string s
6606   pushptr(msg.addr());
6607   push(stack_depth);        // pass stack depth
6608   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6609   addptr(rsp, 3 * wordSize);   // discard arguments
6610   // check for error
6611   { Label L;
6612     testl(rax, rax);
6613     jcc(Assembler::notZero, L);
6614     int3();                  // break if error condition
6615     bind(L);
6616   }
6617   pop_CPU_state();
6618 }
6619 
6620 void MacroAssembler::restore_cpu_control_state_after_jni() {
6621   // Either restore the MXCSR register after returning from the JNI Call
6622   // or verify that it wasn't changed (with -Xcheck:jni flag).
6623   if (VM_Version::supports_sse()) {
6624     if (RestoreMXCSROnJNICalls) {
6625       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6626     } else if (CheckJNICalls) {
6627       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6628     }
6629   }
6630   if (VM_Version::supports_avx()) {
6631     // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6632     vzeroupper();
6633   }
6634 
6635 #ifndef _LP64
6636   // Either restore the x87 floating pointer control word after returning
6637   // from the JNI call or verify that it wasn't changed.
6638   if (CheckJNICalls) {
6639     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6640   }
6641 #endif // _LP64
6642 }
6643 
6644 
6645 void MacroAssembler::load_klass(Register dst, Register src) {
6646 #ifdef _LP64
6647   if (UseCompressedClassPointers) {
6648     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6649     decode_klass_not_null(dst);
6650   } else
6651 #endif
6652     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6653 }
6654 
6655 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6656   load_klass(dst, src);
6657   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6658 }
6659 
6660 void MacroAssembler::store_klass(Register dst, Register src) {
6661 #ifdef _LP64
6662   if (UseCompressedClassPointers) {
6663     encode_klass_not_null(src);
6664     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6665   } else
6666 #endif
6667     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6668 }
6669 
6670 void MacroAssembler::load_heap_oop(Register dst, Address src) {
6671 #ifdef _LP64
6672   // FIXME: Must change all places where we try to load the klass.
6673   if (UseCompressedOops) {
6674     movl(dst, src);
6675     decode_heap_oop(dst);
6676   } else
6677 #endif
6678     movptr(dst, src);
6679 }
6680 
6681 // Doesn't do verfication, generates fixed size code
6682 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6683 #ifdef _LP64
6684   if (UseCompressedOops) {
6685     movl(dst, src);
6686     decode_heap_oop_not_null(dst);
6687   } else
6688 #endif
6689     movptr(dst, src);
6690 }
6691 
6692 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6693 #ifdef _LP64
6694   if (UseCompressedOops) {
6695     assert(!dst.uses(src), "not enough registers");
6696     encode_heap_oop(src);
6697     movl(dst, src);
6698   } else
6699 #endif
6700     movptr(dst, src);
6701 }
6702 
6703 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6704   assert_different_registers(src1, tmp);
6705 #ifdef _LP64
6706   if (UseCompressedOops) {
6707     bool did_push = false;
6708     if (tmp == noreg) {
6709       tmp = rax;
6710       push(tmp);
6711       did_push = true;
6712       assert(!src2.uses(rsp), "can't push");
6713     }
6714     load_heap_oop(tmp, src2);
6715     cmpptr(src1, tmp);
6716     if (did_push)  pop(tmp);
6717   } else
6718 #endif
6719     cmpptr(src1, src2);
6720 }
6721 
6722 // Used for storing NULLs.
6723 void MacroAssembler::store_heap_oop_null(Address dst) {
6724 #ifdef _LP64
6725   if (UseCompressedOops) {
6726     movl(dst, (int32_t)NULL_WORD);
6727   } else {
6728     movslq(dst, (int32_t)NULL_WORD);
6729   }
6730 #else
6731   movl(dst, (int32_t)NULL_WORD);
6732 #endif
6733 }
6734 
6735 #ifdef _LP64
6736 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6737   if (UseCompressedClassPointers) {
6738     // Store to klass gap in destination
6739     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6740   }
6741 }
6742 
6743 #ifdef ASSERT
6744 void MacroAssembler::verify_heapbase(const char* msg) {
6745   assert (UseCompressedOops, "should be compressed");
6746   assert (Universe::heap() != NULL, "java heap should be initialized");
6747   if (CheckCompressedOops) {
6748     Label ok;
6749     push(rscratch1); // cmpptr trashes rscratch1
6750     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6751     jcc(Assembler::equal, ok);
6752     STOP(msg);
6753     bind(ok);
6754     pop(rscratch1);
6755   }
6756 }
6757 #endif
6758 
6759 // Algorithm must match oop.inline.hpp encode_heap_oop.
6760 void MacroAssembler::encode_heap_oop(Register r) {
6761 #ifdef ASSERT
6762   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6763 #endif
6764   verify_oop(r, "broken oop in encode_heap_oop");
6765   if (Universe::narrow_oop_base() == NULL) {
6766     if (Universe::narrow_oop_shift() != 0) {
6767       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6768       shrq(r, LogMinObjAlignmentInBytes);
6769     }
6770     return;
6771   }
6772   testq(r, r);
6773   cmovq(Assembler::equal, r, r12_heapbase);
6774   subq(r, r12_heapbase);
6775   shrq(r, LogMinObjAlignmentInBytes);
6776 }
6777 
6778 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6779 #ifdef ASSERT
6780   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6781   if (CheckCompressedOops) {
6782     Label ok;
6783     testq(r, r);
6784     jcc(Assembler::notEqual, ok);
6785     STOP("null oop passed to encode_heap_oop_not_null");
6786     bind(ok);
6787   }
6788 #endif
6789   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6790   if (Universe::narrow_oop_base() != NULL) {
6791     subq(r, r12_heapbase);
6792   }
6793   if (Universe::narrow_oop_shift() != 0) {
6794     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6795     shrq(r, LogMinObjAlignmentInBytes);
6796   }
6797 }
6798 
6799 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6800 #ifdef ASSERT
6801   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6802   if (CheckCompressedOops) {
6803     Label ok;
6804     testq(src, src);
6805     jcc(Assembler::notEqual, ok);
6806     STOP("null oop passed to encode_heap_oop_not_null2");
6807     bind(ok);
6808   }
6809 #endif
6810   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6811   if (dst != src) {
6812     movq(dst, src);
6813   }
6814   if (Universe::narrow_oop_base() != NULL) {
6815     subq(dst, r12_heapbase);
6816   }
6817   if (Universe::narrow_oop_shift() != 0) {
6818     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6819     shrq(dst, LogMinObjAlignmentInBytes);
6820   }
6821 }
6822 
6823 void  MacroAssembler::decode_heap_oop(Register r) {
6824 #ifdef ASSERT
6825   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6826 #endif
6827   if (Universe::narrow_oop_base() == NULL) {
6828     if (Universe::narrow_oop_shift() != 0) {
6829       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6830       shlq(r, LogMinObjAlignmentInBytes);
6831     }
6832   } else {
6833     Label done;
6834     shlq(r, LogMinObjAlignmentInBytes);
6835     jccb(Assembler::equal, done);
6836     addq(r, r12_heapbase);
6837     bind(done);
6838   }
6839   verify_oop(r, "broken oop in decode_heap_oop");
6840 }
6841 
6842 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6843   // Note: it will change flags
6844   assert (UseCompressedOops, "should only be used for compressed headers");
6845   assert (Universe::heap() != NULL, "java heap should be initialized");
6846   // Cannot assert, unverified entry point counts instructions (see .ad file)
6847   // vtableStubs also counts instructions in pd_code_size_limit.
6848   // Also do not verify_oop as this is called by verify_oop.
6849   if (Universe::narrow_oop_shift() != 0) {
6850     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6851     shlq(r, LogMinObjAlignmentInBytes);
6852     if (Universe::narrow_oop_base() != NULL) {
6853       addq(r, r12_heapbase);
6854     }
6855   } else {
6856     assert (Universe::narrow_oop_base() == NULL, "sanity");
6857   }
6858 }
6859 
6860 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6861   // Note: it will change flags
6862   assert (UseCompressedOops, "should only be used for compressed headers");
6863   assert (Universe::heap() != NULL, "java heap should be initialized");
6864   // Cannot assert, unverified entry point counts instructions (see .ad file)
6865   // vtableStubs also counts instructions in pd_code_size_limit.
6866   // Also do not verify_oop as this is called by verify_oop.
6867   if (Universe::narrow_oop_shift() != 0) {
6868     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6869     if (LogMinObjAlignmentInBytes == Address::times_8) {
6870       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6871     } else {
6872       if (dst != src) {
6873         movq(dst, src);
6874       }
6875       shlq(dst, LogMinObjAlignmentInBytes);
6876       if (Universe::narrow_oop_base() != NULL) {
6877         addq(dst, r12_heapbase);
6878       }
6879     }
6880   } else {
6881     assert (Universe::narrow_oop_base() == NULL, "sanity");
6882     if (dst != src) {
6883       movq(dst, src);
6884     }
6885   }
6886 }
6887 
6888 void MacroAssembler::encode_klass_not_null(Register r) {
6889   if (Universe::narrow_klass_base() != NULL) {
6890     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6891     assert(r != r12_heapbase, "Encoding a klass in r12");
6892     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6893     subq(r, r12_heapbase);
6894   }
6895   if (Universe::narrow_klass_shift() != 0) {
6896     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6897     shrq(r, LogKlassAlignmentInBytes);
6898   }
6899   if (Universe::narrow_klass_base() != NULL) {
6900     reinit_heapbase();
6901   }
6902 }
6903 
6904 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6905   if (dst == src) {
6906     encode_klass_not_null(src);
6907   } else {
6908     if (Universe::narrow_klass_base() != NULL) {
6909       mov64(dst, (int64_t)Universe::narrow_klass_base());
6910       negq(dst);
6911       addq(dst, src);
6912     } else {
6913       movptr(dst, src);
6914     }
6915     if (Universe::narrow_klass_shift() != 0) {
6916       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6917       shrq(dst, LogKlassAlignmentInBytes);
6918     }
6919   }
6920 }
6921 
6922 // Function instr_size_for_decode_klass_not_null() counts the instructions
6923 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6924 // when (Universe::heap() != NULL).  Hence, if the instructions they
6925 // generate change, then this method needs to be updated.
6926 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6927   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6928   if (Universe::narrow_klass_base() != NULL) {
6929     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6930     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
6931   } else {
6932     // longest load decode klass function, mov64, leaq
6933     return 16;
6934   }
6935 }
6936 
6937 // !!! If the instructions that get generated here change then function
6938 // instr_size_for_decode_klass_not_null() needs to get updated.
6939 void  MacroAssembler::decode_klass_not_null(Register r) {
6940   // Note: it will change flags
6941   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6942   assert(r != r12_heapbase, "Decoding a klass in r12");
6943   // Cannot assert, unverified entry point counts instructions (see .ad file)
6944   // vtableStubs also counts instructions in pd_code_size_limit.
6945   // Also do not verify_oop as this is called by verify_oop.
6946   if (Universe::narrow_klass_shift() != 0) {
6947     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6948     shlq(r, LogKlassAlignmentInBytes);
6949   }
6950   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6951   if (Universe::narrow_klass_base() != NULL) {
6952     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6953     addq(r, r12_heapbase);
6954     reinit_heapbase();
6955   }
6956 }
6957 
6958 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
6959   // Note: it will change flags
6960   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6961   if (dst == src) {
6962     decode_klass_not_null(dst);
6963   } else {
6964     // Cannot assert, unverified entry point counts instructions (see .ad file)
6965     // vtableStubs also counts instructions in pd_code_size_limit.
6966     // Also do not verify_oop as this is called by verify_oop.
6967     mov64(dst, (int64_t)Universe::narrow_klass_base());
6968     if (Universe::narrow_klass_shift() != 0) {
6969       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6970       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
6971       leaq(dst, Address(dst, src, Address::times_8, 0));
6972     } else {
6973       addq(dst, src);
6974     }
6975   }
6976 }
6977 
6978 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
6979   assert (UseCompressedOops, "should only be used for compressed headers");
6980   assert (Universe::heap() != NULL, "java heap should be initialized");
6981   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6982   int oop_index = oop_recorder()->find_index(obj);
6983   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6984   mov_narrow_oop(dst, oop_index, rspec);
6985 }
6986 
6987 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
6988   assert (UseCompressedOops, "should only be used for compressed headers");
6989   assert (Universe::heap() != NULL, "java heap should be initialized");
6990   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6991   int oop_index = oop_recorder()->find_index(obj);
6992   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6993   mov_narrow_oop(dst, oop_index, rspec);
6994 }
6995 
6996 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
6997   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6998   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6999   int klass_index = oop_recorder()->find_index(k);
7000   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7001   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7002 }
7003 
7004 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
7005   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7006   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7007   int klass_index = oop_recorder()->find_index(k);
7008   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7009   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7010 }
7011 
7012 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
7013   assert (UseCompressedOops, "should only be used for compressed headers");
7014   assert (Universe::heap() != NULL, "java heap should be initialized");
7015   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7016   int oop_index = oop_recorder()->find_index(obj);
7017   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7018   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7019 }
7020 
7021 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
7022   assert (UseCompressedOops, "should only be used for compressed headers");
7023   assert (Universe::heap() != NULL, "java heap should be initialized");
7024   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7025   int oop_index = oop_recorder()->find_index(obj);
7026   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7027   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7028 }
7029 
7030 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
7031   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7032   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7033   int klass_index = oop_recorder()->find_index(k);
7034   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7035   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7036 }
7037 
7038 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
7039   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7040   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7041   int klass_index = oop_recorder()->find_index(k);
7042   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7043   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7044 }
7045 
7046 void MacroAssembler::reinit_heapbase() {
7047   if (UseCompressedOops || UseCompressedClassPointers) {
7048     if (Universe::heap() != NULL) {
7049       if (Universe::narrow_oop_base() == NULL) {
7050         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
7051       } else {
7052         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
7053       }
7054     } else {
7055       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7056     }
7057   }
7058 }
7059 
7060 #endif // _LP64
7061 
7062 
7063 // C2 compiled method's prolog code.
7064 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
7065 
7066   // WARNING: Initial instruction MUST be 5 bytes or longer so that
7067   // NativeJump::patch_verified_entry will be able to patch out the entry
7068   // code safely. The push to verify stack depth is ok at 5 bytes,
7069   // the frame allocation can be either 3 or 6 bytes. So if we don't do
7070   // stack bang then we must use the 6 byte frame allocation even if
7071   // we have no frame. :-(
7072   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
7073 
7074   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
7075   // Remove word for return addr
7076   framesize -= wordSize;
7077   stack_bang_size -= wordSize;
7078 
7079   // Calls to C2R adapters often do not accept exceptional returns.
7080   // We require that their callers must bang for them.  But be careful, because
7081   // some VM calls (such as call site linkage) can use several kilobytes of
7082   // stack.  But the stack safety zone should account for that.
7083   // See bugs 4446381, 4468289, 4497237.
7084   if (stack_bang_size > 0) {
7085     generate_stack_overflow_check(stack_bang_size);
7086 
7087     // We always push rbp, so that on return to interpreter rbp, will be
7088     // restored correctly and we can correct the stack.
7089     push(rbp);
7090     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7091     if (PreserveFramePointer) {
7092       mov(rbp, rsp);
7093     }
7094     // Remove word for ebp
7095     framesize -= wordSize;
7096 
7097     // Create frame
7098     if (framesize) {
7099       subptr(rsp, framesize);
7100     }
7101   } else {
7102     // Create frame (force generation of a 4 byte immediate value)
7103     subptr_imm32(rsp, framesize);
7104 
7105     // Save RBP register now.
7106     framesize -= wordSize;
7107     movptr(Address(rsp, framesize), rbp);
7108     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7109     if (PreserveFramePointer) {
7110       movptr(rbp, rsp);
7111       if (framesize > 0) {
7112         addptr(rbp, framesize);
7113       }
7114     }
7115   }
7116 
7117   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
7118     framesize -= wordSize;
7119     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
7120   }
7121 
7122 #ifndef _LP64
7123   // If method sets FPU control word do it now
7124   if (fp_mode_24b) {
7125     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
7126   }
7127   if (UseSSE >= 2 && VerifyFPU) {
7128     verify_FPU(0, "FPU stack must be clean on entry");
7129   }
7130 #endif
7131 
7132 #ifdef ASSERT
7133   if (VerifyStackAtCalls) {
7134     Label L;
7135     push(rax);
7136     mov(rax, rsp);
7137     andptr(rax, StackAlignmentInBytes-1);
7138     cmpptr(rax, StackAlignmentInBytes-wordSize);
7139     pop(rax);
7140     jcc(Assembler::equal, L);
7141     STOP("Stack is not properly aligned!");
7142     bind(L);
7143   }
7144 #endif
7145 
7146 }
7147 
7148 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp) {
7149   // cnt - number of qwords (8-byte words).
7150   // base - start address, qword aligned.
7151   assert(base==rdi, "base register must be edi for rep stos");
7152   assert(tmp==rax,   "tmp register must be eax for rep stos");
7153   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
7154 
7155   xorptr(tmp, tmp);
7156   if (UseFastStosb) {
7157     shlptr(cnt,3); // convert to number of bytes
7158     rep_stosb();
7159   } else {
7160     NOT_LP64(shlptr(cnt,1);) // convert to number of dwords for 32-bit VM
7161     rep_stos();
7162   }
7163 }
7164 
7165 #ifdef COMPILER2
7166 
7167 // IndexOf for constant substrings with size >= 8 chars
7168 // which don't need to be loaded through stack.
7169 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7170                                       Register cnt1, Register cnt2,
7171                                       int int_cnt2,  Register result,
7172                                       XMMRegister vec, Register tmp,
7173                                       int ae) {
7174   ShortBranchVerifier sbv(this);
7175   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7176   assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7177   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7178 
7179   // This method uses the pcmpestri instruction with bound registers
7180   //   inputs:
7181   //     xmm - substring
7182   //     rax - substring length (elements count)
7183   //     mem - scanned string
7184   //     rdx - string length (elements count)
7185   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7186   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7187   //   outputs:
7188   //     rcx - matched index in string
7189   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7190   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7191   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7192   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7193   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7194 
7195   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7196         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7197         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7198 
7199   // Note, inline_string_indexOf() generates checks:
7200   // if (substr.count > string.count) return -1;
7201   // if (substr.count == 0) return 0;
7202   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7203 
7204   // Load substring.
7205   if (ae == StrIntrinsicNode::UL) {
7206     pmovzxbw(vec, Address(str2, 0));
7207   } else {
7208     movdqu(vec, Address(str2, 0));
7209   }
7210   movl(cnt2, int_cnt2);
7211   movptr(result, str1); // string addr
7212 
7213   if (int_cnt2 > stride) {
7214     jmpb(SCAN_TO_SUBSTR);
7215 
7216     // Reload substr for rescan, this code
7217     // is executed only for large substrings (> 8 chars)
7218     bind(RELOAD_SUBSTR);
7219     if (ae == StrIntrinsicNode::UL) {
7220       pmovzxbw(vec, Address(str2, 0));
7221     } else {
7222       movdqu(vec, Address(str2, 0));
7223     }
7224     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7225 
7226     bind(RELOAD_STR);
7227     // We came here after the beginning of the substring was
7228     // matched but the rest of it was not so we need to search
7229     // again. Start from the next element after the previous match.
7230 
7231     // cnt2 is number of substring reminding elements and
7232     // cnt1 is number of string reminding elements when cmp failed.
7233     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7234     subl(cnt1, cnt2);
7235     addl(cnt1, int_cnt2);
7236     movl(cnt2, int_cnt2); // Now restore cnt2
7237 
7238     decrementl(cnt1);     // Shift to next element
7239     cmpl(cnt1, cnt2);
7240     jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7241 
7242     addptr(result, (1<<scale1));
7243 
7244   } // (int_cnt2 > 8)
7245 
7246   // Scan string for start of substr in 16-byte vectors
7247   bind(SCAN_TO_SUBSTR);
7248   pcmpestri(vec, Address(result, 0), mode);
7249   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7250   subl(cnt1, stride);
7251   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7252   cmpl(cnt1, cnt2);
7253   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7254   addptr(result, 16);
7255   jmpb(SCAN_TO_SUBSTR);
7256 
7257   // Found a potential substr
7258   bind(FOUND_CANDIDATE);
7259   // Matched whole vector if first element matched (tmp(rcx) == 0).
7260   if (int_cnt2 == stride) {
7261     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7262   } else { // int_cnt2 > 8
7263     jccb(Assembler::overflow, FOUND_SUBSTR);
7264   }
7265   // After pcmpestri tmp(rcx) contains matched element index
7266   // Compute start addr of substr
7267   lea(result, Address(result, tmp, scale1));
7268 
7269   // Make sure string is still long enough
7270   subl(cnt1, tmp);
7271   cmpl(cnt1, cnt2);
7272   if (int_cnt2 == stride) {
7273     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7274   } else { // int_cnt2 > 8
7275     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7276   }
7277   // Left less then substring.
7278 
7279   bind(RET_NOT_FOUND);
7280   movl(result, -1);
7281   jmpb(EXIT);
7282 
7283   if (int_cnt2 > stride) {
7284     // This code is optimized for the case when whole substring
7285     // is matched if its head is matched.
7286     bind(MATCH_SUBSTR_HEAD);
7287     pcmpestri(vec, Address(result, 0), mode);
7288     // Reload only string if does not match
7289     jccb(Assembler::noOverflow, RELOAD_STR); // OF == 0
7290 
7291     Label CONT_SCAN_SUBSTR;
7292     // Compare the rest of substring (> 8 chars).
7293     bind(FOUND_SUBSTR);
7294     // First 8 chars are already matched.
7295     negptr(cnt2);
7296     addptr(cnt2, stride);
7297 
7298     bind(SCAN_SUBSTR);
7299     subl(cnt1, stride);
7300     cmpl(cnt2, -stride); // Do not read beyond substring
7301     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7302     // Back-up strings to avoid reading beyond substring:
7303     // cnt1 = cnt1 - cnt2 + 8
7304     addl(cnt1, cnt2); // cnt2 is negative
7305     addl(cnt1, stride);
7306     movl(cnt2, stride); negptr(cnt2);
7307     bind(CONT_SCAN_SUBSTR);
7308     if (int_cnt2 < (int)G) {
7309       int tail_off1 = int_cnt2<<scale1;
7310       int tail_off2 = int_cnt2<<scale2;
7311       if (ae == StrIntrinsicNode::UL) {
7312         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7313       } else {
7314         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7315       }
7316       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7317     } else {
7318       // calculate index in register to avoid integer overflow (int_cnt2*2)
7319       movl(tmp, int_cnt2);
7320       addptr(tmp, cnt2);
7321       if (ae == StrIntrinsicNode::UL) {
7322         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7323       } else {
7324         movdqu(vec, Address(str2, tmp, scale2, 0));
7325       }
7326       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7327     }
7328     // Need to reload strings pointers if not matched whole vector
7329     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7330     addptr(cnt2, stride);
7331     jcc(Assembler::negative, SCAN_SUBSTR);
7332     // Fall through if found full substring
7333 
7334   } // (int_cnt2 > 8)
7335 
7336   bind(RET_FOUND);
7337   // Found result if we matched full small substring.
7338   // Compute substr offset
7339   subptr(result, str1);
7340   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7341     shrl(result, 1); // index
7342   }
7343   bind(EXIT);
7344 
7345 } // string_indexofC8
7346 
7347 // Small strings are loaded through stack if they cross page boundary.
7348 void MacroAssembler::string_indexof(Register str1, Register str2,
7349                                     Register cnt1, Register cnt2,
7350                                     int int_cnt2,  Register result,
7351                                     XMMRegister vec, Register tmp,
7352                                     int ae) {
7353   ShortBranchVerifier sbv(this);
7354   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7355   assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7356   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7357 
7358   //
7359   // int_cnt2 is length of small (< 8 chars) constant substring
7360   // or (-1) for non constant substring in which case its length
7361   // is in cnt2 register.
7362   //
7363   // Note, inline_string_indexOf() generates checks:
7364   // if (substr.count > string.count) return -1;
7365   // if (substr.count == 0) return 0;
7366   //
7367   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7368   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7369   // This method uses the pcmpestri instruction with bound registers
7370   //   inputs:
7371   //     xmm - substring
7372   //     rax - substring length (elements count)
7373   //     mem - scanned string
7374   //     rdx - string length (elements count)
7375   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7376   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7377   //   outputs:
7378   //     rcx - matched index in string
7379   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7380   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7381   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7382   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7383 
7384   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7385         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7386         FOUND_CANDIDATE;
7387 
7388   { //========================================================
7389     // We don't know where these strings are located
7390     // and we can't read beyond them. Load them through stack.
7391     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7392 
7393     movptr(tmp, rsp); // save old SP
7394 
7395     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7396       if (int_cnt2 == (1>>scale2)) { // One byte
7397         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7398         load_unsigned_byte(result, Address(str2, 0));
7399         movdl(vec, result); // move 32 bits
7400       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7401         // Not enough header space in 32-bit VM: 12+3 = 15.
7402         movl(result, Address(str2, -1));
7403         shrl(result, 8);
7404         movdl(vec, result); // move 32 bits
7405       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7406         load_unsigned_short(result, Address(str2, 0));
7407         movdl(vec, result); // move 32 bits
7408       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7409         movdl(vec, Address(str2, 0)); // move 32 bits
7410       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7411         movq(vec, Address(str2, 0));  // move 64 bits
7412       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7413         // Array header size is 12 bytes in 32-bit VM
7414         // + 6 bytes for 3 chars == 18 bytes,
7415         // enough space to load vec and shift.
7416         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7417         if (ae == StrIntrinsicNode::UL) {
7418           int tail_off = int_cnt2-8;
7419           pmovzxbw(vec, Address(str2, tail_off));
7420           psrldq(vec, -2*tail_off);
7421         }
7422         else {
7423           int tail_off = int_cnt2*(1<<scale2);
7424           movdqu(vec, Address(str2, tail_off-16));
7425           psrldq(vec, 16-tail_off);
7426         }
7427       }
7428     } else { // not constant substring
7429       cmpl(cnt2, stride);
7430       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7431 
7432       // We can read beyond string if srt+16 does not cross page boundary
7433       // since heaps are aligned and mapped by pages.
7434       assert(os::vm_page_size() < (int)G, "default page should be small");
7435       movl(result, str2); // We need only low 32 bits
7436       andl(result, (os::vm_page_size()-1));
7437       cmpl(result, (os::vm_page_size()-16));
7438       jccb(Assembler::belowEqual, CHECK_STR);
7439 
7440       // Move small strings to stack to allow load 16 bytes into vec.
7441       subptr(rsp, 16);
7442       int stk_offset = wordSize-(1<<scale2);
7443       push(cnt2);
7444 
7445       bind(COPY_SUBSTR);
7446       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7447         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7448         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7449       } else if (ae == StrIntrinsicNode::UU) {
7450         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7451         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7452       }
7453       decrement(cnt2);
7454       jccb(Assembler::notZero, COPY_SUBSTR);
7455 
7456       pop(cnt2);
7457       movptr(str2, rsp);  // New substring address
7458     } // non constant
7459 
7460     bind(CHECK_STR);
7461     cmpl(cnt1, stride);
7462     jccb(Assembler::aboveEqual, BIG_STRINGS);
7463 
7464     // Check cross page boundary.
7465     movl(result, str1); // We need only low 32 bits
7466     andl(result, (os::vm_page_size()-1));
7467     cmpl(result, (os::vm_page_size()-16));
7468     jccb(Assembler::belowEqual, BIG_STRINGS);
7469 
7470     subptr(rsp, 16);
7471     int stk_offset = -(1<<scale1);
7472     if (int_cnt2 < 0) { // not constant
7473       push(cnt2);
7474       stk_offset += wordSize;
7475     }
7476     movl(cnt2, cnt1);
7477 
7478     bind(COPY_STR);
7479     if (ae == StrIntrinsicNode::LL) {
7480       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7481       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7482     } else {
7483       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7484       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7485     }
7486     decrement(cnt2);
7487     jccb(Assembler::notZero, COPY_STR);
7488 
7489     if (int_cnt2 < 0) { // not constant
7490       pop(cnt2);
7491     }
7492     movptr(str1, rsp);  // New string address
7493 
7494     bind(BIG_STRINGS);
7495     // Load substring.
7496     if (int_cnt2 < 0) { // -1
7497       if (ae == StrIntrinsicNode::UL) {
7498         pmovzxbw(vec, Address(str2, 0));
7499       } else {
7500         movdqu(vec, Address(str2, 0));
7501       }
7502       push(cnt2);       // substr count
7503       push(str2);       // substr addr
7504       push(str1);       // string addr
7505     } else {
7506       // Small (< 8 chars) constant substrings are loaded already.
7507       movl(cnt2, int_cnt2);
7508     }
7509     push(tmp);  // original SP
7510 
7511   } // Finished loading
7512 
7513   //========================================================
7514   // Start search
7515   //
7516 
7517   movptr(result, str1); // string addr
7518 
7519   if (int_cnt2  < 0) {  // Only for non constant substring
7520     jmpb(SCAN_TO_SUBSTR);
7521 
7522     // SP saved at sp+0
7523     // String saved at sp+1*wordSize
7524     // Substr saved at sp+2*wordSize
7525     // Substr count saved at sp+3*wordSize
7526 
7527     // Reload substr for rescan, this code
7528     // is executed only for large substrings (> 8 chars)
7529     bind(RELOAD_SUBSTR);
7530     movptr(str2, Address(rsp, 2*wordSize));
7531     movl(cnt2, Address(rsp, 3*wordSize));
7532     if (ae == StrIntrinsicNode::UL) {
7533       pmovzxbw(vec, Address(str2, 0));
7534     } else {
7535       movdqu(vec, Address(str2, 0));
7536     }
7537     // We came here after the beginning of the substring was
7538     // matched but the rest of it was not so we need to search
7539     // again. Start from the next element after the previous match.
7540     subptr(str1, result); // Restore counter
7541     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7542       shrl(str1, 1);
7543     }
7544     addl(cnt1, str1);
7545     decrementl(cnt1);   // Shift to next element
7546     cmpl(cnt1, cnt2);
7547     jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7548 
7549     addptr(result, (1<<scale1));
7550   } // non constant
7551 
7552   // Scan string for start of substr in 16-byte vectors
7553   bind(SCAN_TO_SUBSTR);
7554   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7555   pcmpestri(vec, Address(result, 0), mode);
7556   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7557   subl(cnt1, stride);
7558   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7559   cmpl(cnt1, cnt2);
7560   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7561   addptr(result, 16);
7562 
7563   bind(ADJUST_STR);
7564   cmpl(cnt1, stride); // Do not read beyond string
7565   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7566   // Back-up string to avoid reading beyond string.
7567   lea(result, Address(result, cnt1, scale1, -16));
7568   movl(cnt1, stride);
7569   jmpb(SCAN_TO_SUBSTR);
7570 
7571   // Found a potential substr
7572   bind(FOUND_CANDIDATE);
7573   // After pcmpestri tmp(rcx) contains matched element index
7574 
7575   // Make sure string is still long enough
7576   subl(cnt1, tmp);
7577   cmpl(cnt1, cnt2);
7578   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7579   // Left less then substring.
7580 
7581   bind(RET_NOT_FOUND);
7582   movl(result, -1);
7583   jmpb(CLEANUP);
7584 
7585   bind(FOUND_SUBSTR);
7586   // Compute start addr of substr
7587   lea(result, Address(result, tmp, scale1));
7588   if (int_cnt2 > 0) { // Constant substring
7589     // Repeat search for small substring (< 8 chars)
7590     // from new point without reloading substring.
7591     // Have to check that we don't read beyond string.
7592     cmpl(tmp, stride-int_cnt2);
7593     jccb(Assembler::greater, ADJUST_STR);
7594     // Fall through if matched whole substring.
7595   } else { // non constant
7596     assert(int_cnt2 == -1, "should be != 0");
7597 
7598     addl(tmp, cnt2);
7599     // Found result if we matched whole substring.
7600     cmpl(tmp, stride);
7601     jccb(Assembler::lessEqual, RET_FOUND);
7602 
7603     // Repeat search for small substring (<= 8 chars)
7604     // from new point 'str1' without reloading substring.
7605     cmpl(cnt2, stride);
7606     // Have to check that we don't read beyond string.
7607     jccb(Assembler::lessEqual, ADJUST_STR);
7608 
7609     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7610     // Compare the rest of substring (> 8 chars).
7611     movptr(str1, result);
7612 
7613     cmpl(tmp, cnt2);
7614     // First 8 chars are already matched.
7615     jccb(Assembler::equal, CHECK_NEXT);
7616 
7617     bind(SCAN_SUBSTR);
7618     pcmpestri(vec, Address(str1, 0), mode);
7619     // Need to reload strings pointers if not matched whole vector
7620     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7621 
7622     bind(CHECK_NEXT);
7623     subl(cnt2, stride);
7624     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7625     addptr(str1, 16);
7626     if (ae == StrIntrinsicNode::UL) {
7627       addptr(str2, 8);
7628     } else {
7629       addptr(str2, 16);
7630     }
7631     subl(cnt1, stride);
7632     cmpl(cnt2, stride); // Do not read beyond substring
7633     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7634     // Back-up strings to avoid reading beyond substring.
7635 
7636     if (ae == StrIntrinsicNode::UL) {
7637       lea(str2, Address(str2, cnt2, scale2, -8));
7638       lea(str1, Address(str1, cnt2, scale1, -16));
7639     } else {
7640       lea(str2, Address(str2, cnt2, scale2, -16));
7641       lea(str1, Address(str1, cnt2, scale1, -16));
7642     }
7643     subl(cnt1, cnt2);
7644     movl(cnt2, stride);
7645     addl(cnt1, stride);
7646     bind(CONT_SCAN_SUBSTR);
7647     if (ae == StrIntrinsicNode::UL) {
7648       pmovzxbw(vec, Address(str2, 0));
7649     } else {
7650       movdqu(vec, Address(str2, 0));
7651     }
7652     jmpb(SCAN_SUBSTR);
7653 
7654     bind(RET_FOUND_LONG);
7655     movptr(str1, Address(rsp, wordSize));
7656   } // non constant
7657 
7658   bind(RET_FOUND);
7659   // Compute substr offset
7660   subptr(result, str1);
7661   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7662     shrl(result, 1); // index
7663   }
7664   bind(CLEANUP);
7665   pop(rsp); // restore SP
7666 
7667 } // string_indexof
7668 
7669 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7670                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7671   ShortBranchVerifier sbv(this);
7672   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7673   assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7674 
7675   int stride = 8;
7676 
7677   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7678         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7679         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7680         FOUND_SEQ_CHAR, DONE_LABEL;
7681 
7682   movptr(result, str1);
7683   if (UseAVX >= 2) {
7684     cmpl(cnt1, stride);
7685     jccb(Assembler::less, SCAN_TO_CHAR_LOOP);
7686     cmpl(cnt1, 2*stride);
7687     jccb(Assembler::less, SCAN_TO_8_CHAR_INIT);
7688     movdl(vec1, ch);
7689     vpbroadcastw(vec1, vec1);
7690     vpxor(vec2, vec2);
7691     movl(tmp, cnt1);
7692     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7693     andl(cnt1,0x0000000F);  //tail count (in chars)
7694 
7695     bind(SCAN_TO_16_CHAR_LOOP);
7696     vmovdqu(vec3, Address(result, 0));
7697     vpcmpeqw(vec3, vec3, vec1, 1);
7698     vptest(vec2, vec3);
7699     jcc(Assembler::carryClear, FOUND_CHAR);
7700     addptr(result, 32);
7701     subl(tmp, 2*stride);
7702     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7703     jmp(SCAN_TO_8_CHAR);
7704     bind(SCAN_TO_8_CHAR_INIT);
7705     movdl(vec1, ch);
7706     pshuflw(vec1, vec1, 0x00);
7707     pshufd(vec1, vec1, 0);
7708     pxor(vec2, vec2);
7709   }
7710   bind(SCAN_TO_8_CHAR);
7711   cmpl(cnt1, stride);
7712   if (UseAVX >= 2) {
7713     jccb(Assembler::less, SCAN_TO_CHAR);
7714   } else {
7715     jccb(Assembler::less, SCAN_TO_CHAR_LOOP);
7716     movdl(vec1, ch);
7717     pshuflw(vec1, vec1, 0x00);
7718     pshufd(vec1, vec1, 0);
7719     pxor(vec2, vec2);
7720   }
7721   movl(tmp, cnt1);
7722   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7723   andl(cnt1,0x00000007);  //tail count (in chars)
7724 
7725   bind(SCAN_TO_8_CHAR_LOOP);
7726   movdqu(vec3, Address(result, 0));
7727   pcmpeqw(vec3, vec1);
7728   ptest(vec2, vec3);
7729   jcc(Assembler::carryClear, FOUND_CHAR);
7730   addptr(result, 16);
7731   subl(tmp, stride);
7732   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7733   bind(SCAN_TO_CHAR);
7734   testl(cnt1, cnt1);
7735   jcc(Assembler::zero, RET_NOT_FOUND);
7736   bind(SCAN_TO_CHAR_LOOP);
7737   load_unsigned_short(tmp, Address(result, 0));
7738   cmpl(ch, tmp);
7739   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7740   addptr(result, 2);
7741   subl(cnt1, 1);
7742   jccb(Assembler::zero, RET_NOT_FOUND);
7743   jmp(SCAN_TO_CHAR_LOOP);
7744 
7745   bind(RET_NOT_FOUND);
7746   movl(result, -1);
7747   jmpb(DONE_LABEL);
7748 
7749   bind(FOUND_CHAR);
7750   if (UseAVX >= 2) {
7751     vpmovmskb(tmp, vec3);
7752   } else {
7753     pmovmskb(tmp, vec3);
7754   }
7755   bsfl(ch, tmp);
7756   addl(result, ch);
7757 
7758   bind(FOUND_SEQ_CHAR);
7759   subptr(result, str1);
7760   shrl(result, 1);
7761 
7762   bind(DONE_LABEL);
7763 } // string_indexof_char
7764 
7765 // helper function for string_compare
7766 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7767                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7768                                         Address::ScaleFactor scale2, Register index, int ae) {
7769   if (ae == StrIntrinsicNode::LL) {
7770     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7771     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7772   } else if (ae == StrIntrinsicNode::UU) {
7773     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7774     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7775   } else {
7776     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7777     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7778   }
7779 }
7780 
7781 // Compare strings, used for char[] and byte[].
7782 void MacroAssembler::string_compare(Register str1, Register str2,
7783                                     Register cnt1, Register cnt2, Register result,
7784                                     XMMRegister vec1, int ae) {
7785   ShortBranchVerifier sbv(this);
7786   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7787   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7788   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7789   int stride2x2 = 0x40;
7790   Address::ScaleFactor scale, scale1, scale2;
7791 
7792   if (ae != StrIntrinsicNode::LL) {
7793     stride2x2 = 0x20;
7794   }
7795 
7796   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7797     shrl(cnt2, 1);
7798   }
7799   // Compute the minimum of the string lengths and the
7800   // difference of the string lengths (stack).
7801   // Do the conditional move stuff
7802   movl(result, cnt1);
7803   subl(cnt1, cnt2);
7804   push(cnt1);
7805   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7806 
7807   // Is the minimum length zero?
7808   testl(cnt2, cnt2);
7809   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7810   if (ae == StrIntrinsicNode::LL) {
7811     // Load first bytes
7812     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7813     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7814   } else if (ae == StrIntrinsicNode::UU) {
7815     // Load first characters
7816     load_unsigned_short(result, Address(str1, 0));
7817     load_unsigned_short(cnt1, Address(str2, 0));
7818   } else {
7819     load_unsigned_byte(result, Address(str1, 0));
7820     load_unsigned_short(cnt1, Address(str2, 0));
7821   }
7822   subl(result, cnt1);
7823   jcc(Assembler::notZero,  POP_LABEL);
7824 
7825   if (ae == StrIntrinsicNode::UU) {
7826     // Divide length by 2 to get number of chars
7827     shrl(cnt2, 1);
7828   }
7829   cmpl(cnt2, 1);
7830   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7831 
7832   // Check if the strings start at the same location and setup scale and stride
7833   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7834     cmpptr(str1, str2);
7835     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7836     if (ae == StrIntrinsicNode::LL) {
7837       scale = Address::times_1;
7838       stride = 16;
7839     } else {
7840       scale = Address::times_2;
7841       stride = 8;
7842     }
7843   } else {
7844     scale = Address::no_scale;  // not used
7845     scale1 = Address::times_1;
7846     scale2 = Address::times_2;
7847     stride = 8;
7848   }
7849 
7850   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7851     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7852     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7853     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7854     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7855     Label COMPARE_TAIL_LONG;
7856     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7857 
7858     int pcmpmask = 0x19;
7859     if (ae == StrIntrinsicNode::LL) {
7860       pcmpmask &= ~0x01;
7861     }
7862 
7863     // Setup to compare 16-chars (32-bytes) vectors,
7864     // start from first character again because it has aligned address.
7865     if (ae == StrIntrinsicNode::LL) {
7866       stride2 = 32;
7867     } else {
7868       stride2 = 16;
7869     }
7870     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7871       adr_stride = stride << scale;
7872     } else {
7873       adr_stride1 = 8;  //stride << scale1;
7874       adr_stride2 = 16; //stride << scale2;
7875     }
7876 
7877     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7878     // rax and rdx are used by pcmpestri as elements counters
7879     movl(result, cnt2);
7880     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7881     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7882 
7883     // fast path : compare first 2 8-char vectors.
7884     bind(COMPARE_16_CHARS);
7885     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7886       movdqu(vec1, Address(str1, 0));
7887     } else {
7888       pmovzxbw(vec1, Address(str1, 0));
7889     }
7890     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7891     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7892 
7893     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7894       movdqu(vec1, Address(str1, adr_stride));
7895       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7896     } else {
7897       pmovzxbw(vec1, Address(str1, adr_stride1));
7898       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7899     }
7900     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7901     addl(cnt1, stride);
7902 
7903     // Compare the characters at index in cnt1
7904     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
7905     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7906     subl(result, cnt2);
7907     jmp(POP_LABEL);
7908 
7909     // Setup the registers to start vector comparison loop
7910     bind(COMPARE_WIDE_VECTORS);
7911     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7912       lea(str1, Address(str1, result, scale));
7913       lea(str2, Address(str2, result, scale));
7914     } else {
7915       lea(str1, Address(str1, result, scale1));
7916       lea(str2, Address(str2, result, scale2));
7917     }
7918     subl(result, stride2);
7919     subl(cnt2, stride2);
7920     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
7921     negptr(result);
7922 
7923     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7924     bind(COMPARE_WIDE_VECTORS_LOOP);
7925 
7926 #ifdef _LP64
7927     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7928       cmpl(cnt2, stride2x2);
7929       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7930       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
7931       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
7932 
7933       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7934       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7935         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
7936         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7937       } else {
7938         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
7939         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7940       }
7941       kortestql(k7, k7);
7942       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
7943       addptr(result, stride2x2);  // update since we already compared at this addr
7944       subl(cnt2, stride2x2);      // and sub the size too
7945       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7946 
7947       vpxor(vec1, vec1);
7948       jmpb(COMPARE_WIDE_TAIL);
7949     }//if (VM_Version::supports_avx512vlbw())
7950 #endif // _LP64
7951 
7952 
7953     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7954     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7955       vmovdqu(vec1, Address(str1, result, scale));
7956       vpxor(vec1, Address(str2, result, scale));
7957     } else {
7958       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
7959       vpxor(vec1, Address(str2, result, scale2));
7960     }
7961     vptest(vec1, vec1);
7962     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
7963     addptr(result, stride2);
7964     subl(cnt2, stride2);
7965     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
7966     // clean upper bits of YMM registers
7967     vpxor(vec1, vec1);
7968 
7969     // compare wide vectors tail
7970     bind(COMPARE_WIDE_TAIL);
7971     testptr(result, result);
7972     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
7973 
7974     movl(result, stride2);
7975     movl(cnt2, result);
7976     negptr(result);
7977     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7978 
7979     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
7980     bind(VECTOR_NOT_EQUAL);
7981     // clean upper bits of YMM registers
7982     vpxor(vec1, vec1);
7983     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7984       lea(str1, Address(str1, result, scale));
7985       lea(str2, Address(str2, result, scale));
7986     } else {
7987       lea(str1, Address(str1, result, scale1));
7988       lea(str2, Address(str2, result, scale2));
7989     }
7990     jmp(COMPARE_16_CHARS);
7991 
7992     // Compare tail chars, length between 1 to 15 chars
7993     bind(COMPARE_TAIL_LONG);
7994     movl(cnt2, result);
7995     cmpl(cnt2, stride);
7996     jccb(Assembler::less, COMPARE_SMALL_STR);
7997 
7998     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7999       movdqu(vec1, Address(str1, 0));
8000     } else {
8001       pmovzxbw(vec1, Address(str1, 0));
8002     }
8003     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8004     jcc(Assembler::below, COMPARE_INDEX_CHAR);
8005     subptr(cnt2, stride);
8006     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
8007     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8008       lea(str1, Address(str1, result, scale));
8009       lea(str2, Address(str2, result, scale));
8010     } else {
8011       lea(str1, Address(str1, result, scale1));
8012       lea(str2, Address(str2, result, scale2));
8013     }
8014     negptr(cnt2);
8015     jmpb(WHILE_HEAD_LABEL);
8016 
8017     bind(COMPARE_SMALL_STR);
8018   } else if (UseSSE42Intrinsics) {
8019     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8020     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
8021     int pcmpmask = 0x19;
8022     // Setup to compare 8-char (16-byte) vectors,
8023     // start from first character again because it has aligned address.
8024     movl(result, cnt2);
8025     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
8026     if (ae == StrIntrinsicNode::LL) {
8027       pcmpmask &= ~0x01;
8028     }
8029     jccb(Assembler::zero, COMPARE_TAIL);
8030     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8031       lea(str1, Address(str1, result, scale));
8032       lea(str2, Address(str2, result, scale));
8033     } else {
8034       lea(str1, Address(str1, result, scale1));
8035       lea(str2, Address(str2, result, scale2));
8036     }
8037     negptr(result);
8038 
8039     // pcmpestri
8040     //   inputs:
8041     //     vec1- substring
8042     //     rax - negative string length (elements count)
8043     //     mem - scanned string
8044     //     rdx - string length (elements count)
8045     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
8046     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
8047     //   outputs:
8048     //     rcx - first mismatched element index
8049     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8050 
8051     bind(COMPARE_WIDE_VECTORS);
8052     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8053       movdqu(vec1, Address(str1, result, scale));
8054       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8055     } else {
8056       pmovzxbw(vec1, Address(str1, result, scale1));
8057       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8058     }
8059     // After pcmpestri cnt1(rcx) contains mismatched element index
8060 
8061     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
8062     addptr(result, stride);
8063     subptr(cnt2, stride);
8064     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
8065 
8066     // compare wide vectors tail
8067     testptr(result, result);
8068     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
8069 
8070     movl(cnt2, stride);
8071     movl(result, stride);
8072     negptr(result);
8073     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8074       movdqu(vec1, Address(str1, result, scale));
8075       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8076     } else {
8077       pmovzxbw(vec1, Address(str1, result, scale1));
8078       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8079     }
8080     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
8081 
8082     // Mismatched characters in the vectors
8083     bind(VECTOR_NOT_EQUAL);
8084     addptr(cnt1, result);
8085     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8086     subl(result, cnt2);
8087     jmpb(POP_LABEL);
8088 
8089     bind(COMPARE_TAIL); // limit is zero
8090     movl(cnt2, result);
8091     // Fallthru to tail compare
8092   }
8093   // Shift str2 and str1 to the end of the arrays, negate min
8094   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8095     lea(str1, Address(str1, cnt2, scale));
8096     lea(str2, Address(str2, cnt2, scale));
8097   } else {
8098     lea(str1, Address(str1, cnt2, scale1));
8099     lea(str2, Address(str2, cnt2, scale2));
8100   }
8101   decrementl(cnt2);  // first character was compared already
8102   negptr(cnt2);
8103 
8104   // Compare the rest of the elements
8105   bind(WHILE_HEAD_LABEL);
8106   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
8107   subl(result, cnt1);
8108   jccb(Assembler::notZero, POP_LABEL);
8109   increment(cnt2);
8110   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
8111 
8112   // Strings are equal up to min length.  Return the length difference.
8113   bind(LENGTH_DIFF_LABEL);
8114   pop(result);
8115   if (ae == StrIntrinsicNode::UU) {
8116     // Divide diff by 2 to get number of chars
8117     sarl(result, 1);
8118   }
8119   jmpb(DONE_LABEL);
8120 
8121 #ifdef _LP64
8122   if (VM_Version::supports_avx512vlbw()) {
8123 
8124     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
8125 
8126     kmovql(cnt1, k7);
8127     notq(cnt1);
8128     bsfq(cnt2, cnt1);
8129     if (ae != StrIntrinsicNode::LL) {
8130       // Divide diff by 2 to get number of chars
8131       sarl(cnt2, 1);
8132     }
8133     addq(result, cnt2);
8134     if (ae == StrIntrinsicNode::LL) {
8135       load_unsigned_byte(cnt1, Address(str2, result));
8136       load_unsigned_byte(result, Address(str1, result));
8137     } else if (ae == StrIntrinsicNode::UU) {
8138       load_unsigned_short(cnt1, Address(str2, result, scale));
8139       load_unsigned_short(result, Address(str1, result, scale));
8140     } else {
8141       load_unsigned_short(cnt1, Address(str2, result, scale2));
8142       load_unsigned_byte(result, Address(str1, result, scale1));
8143     }
8144     subl(result, cnt1);
8145     jmpb(POP_LABEL);
8146   }//if (VM_Version::supports_avx512vlbw())
8147 #endif // _LP64
8148 
8149   // Discard the stored length difference
8150   bind(POP_LABEL);
8151   pop(cnt1);
8152 
8153   // That's it
8154   bind(DONE_LABEL);
8155   if(ae == StrIntrinsicNode::UL) {
8156     negl(result);
8157   }
8158 
8159 }
8160 
8161 // Search for Non-ASCII character (Negative byte value) in a byte array,
8162 // return true if it has any and false otherwise.
8163 void MacroAssembler::has_negatives(Register ary1, Register len,
8164                                    Register result, Register tmp1,
8165                                    XMMRegister vec1, XMMRegister vec2) {
8166 
8167   // rsi: byte array
8168   // rcx: len
8169   // rax: result
8170   ShortBranchVerifier sbv(this);
8171   assert_different_registers(ary1, len, result, tmp1);
8172   assert_different_registers(vec1, vec2);
8173   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8174 
8175   // len == 0
8176   testl(len, len);
8177   jcc(Assembler::zero, FALSE_LABEL);
8178 
8179   movl(result, len); // copy
8180 
8181   if (UseAVX >= 2 && UseSSE >= 2) {
8182     // With AVX2, use 32-byte vector compare
8183     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8184 
8185     // Compare 32-byte vectors
8186     andl(result, 0x0000001f);  //   tail count (in bytes)
8187     andl(len, 0xffffffe0);   // vector count (in bytes)
8188     jccb(Assembler::zero, COMPARE_TAIL);
8189 
8190     lea(ary1, Address(ary1, len, Address::times_1));
8191     negptr(len);
8192 
8193     movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8194     movdl(vec2, tmp1);
8195     vpbroadcastd(vec2, vec2);
8196 
8197     bind(COMPARE_WIDE_VECTORS);
8198     vmovdqu(vec1, Address(ary1, len, Address::times_1));
8199     vptest(vec1, vec2);
8200     jccb(Assembler::notZero, TRUE_LABEL);
8201     addptr(len, 32);
8202     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8203 
8204     testl(result, result);
8205     jccb(Assembler::zero, FALSE_LABEL);
8206 
8207     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8208     vptest(vec1, vec2);
8209     jccb(Assembler::notZero, TRUE_LABEL);
8210     jmpb(FALSE_LABEL);
8211 
8212     bind(COMPARE_TAIL); // len is zero
8213     movl(len, result);
8214     // Fallthru to tail compare
8215   } else if (UseSSE42Intrinsics) {
8216     assert(UseSSE >= 4, "SSE4 must be  for SSE4.2 intrinsics to be available");
8217     // With SSE4.2, use double quad vector compare
8218     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8219 
8220     // Compare 16-byte vectors
8221     andl(result, 0x0000000f);  //   tail count (in bytes)
8222     andl(len, 0xfffffff0);   // vector count (in bytes)
8223     jccb(Assembler::zero, COMPARE_TAIL);
8224 
8225     lea(ary1, Address(ary1, len, Address::times_1));
8226     negptr(len);
8227 
8228     movl(tmp1, 0x80808080);
8229     movdl(vec2, tmp1);
8230     pshufd(vec2, vec2, 0);
8231 
8232     bind(COMPARE_WIDE_VECTORS);
8233     movdqu(vec1, Address(ary1, len, Address::times_1));
8234     ptest(vec1, vec2);
8235     jccb(Assembler::notZero, TRUE_LABEL);
8236     addptr(len, 16);
8237     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8238 
8239     testl(result, result);
8240     jccb(Assembler::zero, FALSE_LABEL);
8241 
8242     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8243     ptest(vec1, vec2);
8244     jccb(Assembler::notZero, TRUE_LABEL);
8245     jmpb(FALSE_LABEL);
8246 
8247     bind(COMPARE_TAIL); // len is zero
8248     movl(len, result);
8249     // Fallthru to tail compare
8250   }
8251 
8252   // Compare 4-byte vectors
8253   andl(len, 0xfffffffc); // vector count (in bytes)
8254   jccb(Assembler::zero, COMPARE_CHAR);
8255 
8256   lea(ary1, Address(ary1, len, Address::times_1));
8257   negptr(len);
8258 
8259   bind(COMPARE_VECTORS);
8260   movl(tmp1, Address(ary1, len, Address::times_1));
8261   andl(tmp1, 0x80808080);
8262   jccb(Assembler::notZero, TRUE_LABEL);
8263   addptr(len, 4);
8264   jcc(Assembler::notZero, COMPARE_VECTORS);
8265 
8266   // Compare trailing char (final 2 bytes), if any
8267   bind(COMPARE_CHAR);
8268   testl(result, 0x2);   // tail  char
8269   jccb(Assembler::zero, COMPARE_BYTE);
8270   load_unsigned_short(tmp1, Address(ary1, 0));
8271   andl(tmp1, 0x00008080);
8272   jccb(Assembler::notZero, TRUE_LABEL);
8273   subptr(result, 2);
8274   lea(ary1, Address(ary1, 2));
8275 
8276   bind(COMPARE_BYTE);
8277   testl(result, 0x1);   // tail  byte
8278   jccb(Assembler::zero, FALSE_LABEL);
8279   load_unsigned_byte(tmp1, Address(ary1, 0));
8280   andl(tmp1, 0x00000080);
8281   jccb(Assembler::notEqual, TRUE_LABEL);
8282   jmpb(FALSE_LABEL);
8283 
8284   bind(TRUE_LABEL);
8285   movl(result, 1);   // return true
8286   jmpb(DONE);
8287 
8288   bind(FALSE_LABEL);
8289   xorl(result, result); // return false
8290 
8291   // That's it
8292   bind(DONE);
8293   if (UseAVX >= 2 && UseSSE >= 2) {
8294     // clean upper bits of YMM registers
8295     vpxor(vec1, vec1);
8296     vpxor(vec2, vec2);
8297   }
8298 }
8299 
8300 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8301 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8302                                    Register limit, Register result, Register chr,
8303                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8304   ShortBranchVerifier sbv(this);
8305   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8306 
8307   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8308   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8309 
8310   if (is_array_equ) {
8311     // Check the input args
8312     cmpptr(ary1, ary2);
8313     jcc(Assembler::equal, TRUE_LABEL);
8314 
8315     // Need additional checks for arrays_equals.
8316     testptr(ary1, ary1);
8317     jcc(Assembler::zero, FALSE_LABEL);
8318     testptr(ary2, ary2);
8319     jcc(Assembler::zero, FALSE_LABEL);
8320 
8321     // Check the lengths
8322     movl(limit, Address(ary1, length_offset));
8323     cmpl(limit, Address(ary2, length_offset));
8324     jcc(Assembler::notEqual, FALSE_LABEL);
8325   }
8326 
8327   // count == 0
8328   testl(limit, limit);
8329   jcc(Assembler::zero, TRUE_LABEL);
8330 
8331   if (is_array_equ) {
8332     // Load array address
8333     lea(ary1, Address(ary1, base_offset));
8334     lea(ary2, Address(ary2, base_offset));
8335   }
8336 
8337   if (is_array_equ && is_char) {
8338     // arrays_equals when used for char[].
8339     shll(limit, 1);      // byte count != 0
8340   }
8341   movl(result, limit); // copy
8342 
8343   if (UseAVX >= 2) {
8344     // With AVX2, use 32-byte vector compare
8345     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8346 
8347     // Compare 32-byte vectors
8348     andl(result, 0x0000001f);  //   tail count (in bytes)
8349     andl(limit, 0xffffffe0);   // vector count (in bytes)
8350     jcc(Assembler::zero, COMPARE_TAIL);
8351 
8352     lea(ary1, Address(ary1, limit, Address::times_1));
8353     lea(ary2, Address(ary2, limit, Address::times_1));
8354     negptr(limit);
8355 
8356     bind(COMPARE_WIDE_VECTORS);
8357 
8358 #ifdef _LP64
8359     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8360       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8361 
8362       cmpl(limit, -64);
8363       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8364 
8365       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8366 
8367       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8368       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8369       kortestql(k7, k7);
8370       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8371       addptr(limit, 64);  // update since we already compared at this addr
8372       cmpl(limit, -64);
8373       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8374 
8375       // At this point we may still need to compare -limit+result bytes.
8376       // We could execute the next two instruction and just continue via non-wide path:
8377       //  cmpl(limit, 0);
8378       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8379       // But since we stopped at the points ary{1,2}+limit which are
8380       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8381       // (|limit| <= 32 and result < 32),
8382       // we may just compare the last 64 bytes.
8383       //
8384       addptr(result, -64);   // it is safe, bc we just came from this area
8385       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8386       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8387       kortestql(k7, k7);
8388       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8389 
8390       jmp(TRUE_LABEL);
8391 
8392       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8393 
8394     }//if (VM_Version::supports_avx512vlbw())
8395 #endif //_LP64
8396 
8397     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8398     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8399     vpxor(vec1, vec2);
8400 
8401     vptest(vec1, vec1);
8402     jccb(Assembler::notZero, FALSE_LABEL);
8403     addptr(limit, 32);
8404     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8405 
8406     testl(result, result);
8407     jccb(Assembler::zero, TRUE_LABEL);
8408 
8409     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8410     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8411     vpxor(vec1, vec2);
8412 
8413     vptest(vec1, vec1);
8414     jccb(Assembler::notZero, FALSE_LABEL);
8415     jmpb(TRUE_LABEL);
8416 
8417     bind(COMPARE_TAIL); // limit is zero
8418     movl(limit, result);
8419     // Fallthru to tail compare
8420   } else if (UseSSE42Intrinsics) {
8421     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8422     // With SSE4.2, use double quad vector compare
8423     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8424 
8425     // Compare 16-byte vectors
8426     andl(result, 0x0000000f);  //   tail count (in bytes)
8427     andl(limit, 0xfffffff0);   // vector count (in bytes)
8428     jccb(Assembler::zero, COMPARE_TAIL);
8429 
8430     lea(ary1, Address(ary1, limit, Address::times_1));
8431     lea(ary2, Address(ary2, limit, Address::times_1));
8432     negptr(limit);
8433 
8434     bind(COMPARE_WIDE_VECTORS);
8435     movdqu(vec1, Address(ary1, limit, Address::times_1));
8436     movdqu(vec2, Address(ary2, limit, Address::times_1));
8437     pxor(vec1, vec2);
8438 
8439     ptest(vec1, vec1);
8440     jccb(Assembler::notZero, FALSE_LABEL);
8441     addptr(limit, 16);
8442     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8443 
8444     testl(result, result);
8445     jccb(Assembler::zero, TRUE_LABEL);
8446 
8447     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8448     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8449     pxor(vec1, vec2);
8450 
8451     ptest(vec1, vec1);
8452     jccb(Assembler::notZero, FALSE_LABEL);
8453     jmpb(TRUE_LABEL);
8454 
8455     bind(COMPARE_TAIL); // limit is zero
8456     movl(limit, result);
8457     // Fallthru to tail compare
8458   }
8459 
8460   // Compare 4-byte vectors
8461   andl(limit, 0xfffffffc); // vector count (in bytes)
8462   jccb(Assembler::zero, COMPARE_CHAR);
8463 
8464   lea(ary1, Address(ary1, limit, Address::times_1));
8465   lea(ary2, Address(ary2, limit, Address::times_1));
8466   negptr(limit);
8467 
8468   bind(COMPARE_VECTORS);
8469   movl(chr, Address(ary1, limit, Address::times_1));
8470   cmpl(chr, Address(ary2, limit, Address::times_1));
8471   jccb(Assembler::notEqual, FALSE_LABEL);
8472   addptr(limit, 4);
8473   jcc(Assembler::notZero, COMPARE_VECTORS);
8474 
8475   // Compare trailing char (final 2 bytes), if any
8476   bind(COMPARE_CHAR);
8477   testl(result, 0x2);   // tail  char
8478   jccb(Assembler::zero, COMPARE_BYTE);
8479   load_unsigned_short(chr, Address(ary1, 0));
8480   load_unsigned_short(limit, Address(ary2, 0));
8481   cmpl(chr, limit);
8482   jccb(Assembler::notEqual, FALSE_LABEL);
8483 
8484   if (is_array_equ && is_char) {
8485     bind(COMPARE_BYTE);
8486   } else {
8487     lea(ary1, Address(ary1, 2));
8488     lea(ary2, Address(ary2, 2));
8489 
8490     bind(COMPARE_BYTE);
8491     testl(result, 0x1);   // tail  byte
8492     jccb(Assembler::zero, TRUE_LABEL);
8493     load_unsigned_byte(chr, Address(ary1, 0));
8494     load_unsigned_byte(limit, Address(ary2, 0));
8495     cmpl(chr, limit);
8496     jccb(Assembler::notEqual, FALSE_LABEL);
8497   }
8498   bind(TRUE_LABEL);
8499   movl(result, 1);   // return true
8500   jmpb(DONE);
8501 
8502   bind(FALSE_LABEL);
8503   xorl(result, result); // return false
8504 
8505   // That's it
8506   bind(DONE);
8507   if (UseAVX >= 2) {
8508     // clean upper bits of YMM registers
8509     vpxor(vec1, vec1);
8510     vpxor(vec2, vec2);
8511   }
8512 }
8513 
8514 #endif
8515 
8516 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8517                                    Register to, Register value, Register count,
8518                                    Register rtmp, XMMRegister xtmp) {
8519   ShortBranchVerifier sbv(this);
8520   assert_different_registers(to, value, count, rtmp);
8521   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8522   Label L_fill_2_bytes, L_fill_4_bytes;
8523 
8524   int shift = -1;
8525   switch (t) {
8526     case T_BYTE:
8527       shift = 2;
8528       break;
8529     case T_SHORT:
8530       shift = 1;
8531       break;
8532     case T_INT:
8533       shift = 0;
8534       break;
8535     default: ShouldNotReachHere();
8536   }
8537 
8538   if (t == T_BYTE) {
8539     andl(value, 0xff);
8540     movl(rtmp, value);
8541     shll(rtmp, 8);
8542     orl(value, rtmp);
8543   }
8544   if (t == T_SHORT) {
8545     andl(value, 0xffff);
8546   }
8547   if (t == T_BYTE || t == T_SHORT) {
8548     movl(rtmp, value);
8549     shll(rtmp, 16);
8550     orl(value, rtmp);
8551   }
8552 
8553   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8554   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8555   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8556     // align source address at 4 bytes address boundary
8557     if (t == T_BYTE) {
8558       // One byte misalignment happens only for byte arrays
8559       testptr(to, 1);
8560       jccb(Assembler::zero, L_skip_align1);
8561       movb(Address(to, 0), value);
8562       increment(to);
8563       decrement(count);
8564       BIND(L_skip_align1);
8565     }
8566     // Two bytes misalignment happens only for byte and short (char) arrays
8567     testptr(to, 2);
8568     jccb(Assembler::zero, L_skip_align2);
8569     movw(Address(to, 0), value);
8570     addptr(to, 2);
8571     subl(count, 1<<(shift-1));
8572     BIND(L_skip_align2);
8573   }
8574   if (UseSSE < 2) {
8575     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8576     // Fill 32-byte chunks
8577     subl(count, 8 << shift);
8578     jcc(Assembler::less, L_check_fill_8_bytes);
8579     align(16);
8580 
8581     BIND(L_fill_32_bytes_loop);
8582 
8583     for (int i = 0; i < 32; i += 4) {
8584       movl(Address(to, i), value);
8585     }
8586 
8587     addptr(to, 32);
8588     subl(count, 8 << shift);
8589     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8590     BIND(L_check_fill_8_bytes);
8591     addl(count, 8 << shift);
8592     jccb(Assembler::zero, L_exit);
8593     jmpb(L_fill_8_bytes);
8594 
8595     //
8596     // length is too short, just fill qwords
8597     //
8598     BIND(L_fill_8_bytes_loop);
8599     movl(Address(to, 0), value);
8600     movl(Address(to, 4), value);
8601     addptr(to, 8);
8602     BIND(L_fill_8_bytes);
8603     subl(count, 1 << (shift + 1));
8604     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8605     // fall through to fill 4 bytes
8606   } else {
8607     Label L_fill_32_bytes;
8608     if (!UseUnalignedLoadStores) {
8609       // align to 8 bytes, we know we are 4 byte aligned to start
8610       testptr(to, 4);
8611       jccb(Assembler::zero, L_fill_32_bytes);
8612       movl(Address(to, 0), value);
8613       addptr(to, 4);
8614       subl(count, 1<<shift);
8615     }
8616     BIND(L_fill_32_bytes);
8617     {
8618       assert( UseSSE >= 2, "supported cpu only" );
8619       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8620       if (UseAVX > 2) {
8621         movl(rtmp, 0xffff);
8622         kmovwl(k1, rtmp);
8623       }
8624       movdl(xtmp, value);
8625       if (UseAVX > 2 && UseUnalignedLoadStores) {
8626         // Fill 64-byte chunks
8627         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8628         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8629 
8630         subl(count, 16 << shift);
8631         jcc(Assembler::less, L_check_fill_32_bytes);
8632         align(16);
8633 
8634         BIND(L_fill_64_bytes_loop);
8635         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8636         addptr(to, 64);
8637         subl(count, 16 << shift);
8638         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8639 
8640         BIND(L_check_fill_32_bytes);
8641         addl(count, 8 << shift);
8642         jccb(Assembler::less, L_check_fill_8_bytes);
8643         vmovdqu(Address(to, 0), xtmp);
8644         addptr(to, 32);
8645         subl(count, 8 << shift);
8646 
8647         BIND(L_check_fill_8_bytes);
8648       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8649         // Fill 64-byte chunks
8650         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8651         vpbroadcastd(xtmp, xtmp);
8652 
8653         subl(count, 16 << shift);
8654         jcc(Assembler::less, L_check_fill_32_bytes);
8655         align(16);
8656 
8657         BIND(L_fill_64_bytes_loop);
8658         vmovdqu(Address(to, 0), xtmp);
8659         vmovdqu(Address(to, 32), xtmp);
8660         addptr(to, 64);
8661         subl(count, 16 << shift);
8662         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8663 
8664         BIND(L_check_fill_32_bytes);
8665         addl(count, 8 << shift);
8666         jccb(Assembler::less, L_check_fill_8_bytes);
8667         vmovdqu(Address(to, 0), xtmp);
8668         addptr(to, 32);
8669         subl(count, 8 << shift);
8670 
8671         BIND(L_check_fill_8_bytes);
8672         // clean upper bits of YMM registers
8673         movdl(xtmp, value);
8674         pshufd(xtmp, xtmp, 0);
8675       } else {
8676         // Fill 32-byte chunks
8677         pshufd(xtmp, xtmp, 0);
8678 
8679         subl(count, 8 << shift);
8680         jcc(Assembler::less, L_check_fill_8_bytes);
8681         align(16);
8682 
8683         BIND(L_fill_32_bytes_loop);
8684 
8685         if (UseUnalignedLoadStores) {
8686           movdqu(Address(to, 0), xtmp);
8687           movdqu(Address(to, 16), xtmp);
8688         } else {
8689           movq(Address(to, 0), xtmp);
8690           movq(Address(to, 8), xtmp);
8691           movq(Address(to, 16), xtmp);
8692           movq(Address(to, 24), xtmp);
8693         }
8694 
8695         addptr(to, 32);
8696         subl(count, 8 << shift);
8697         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8698 
8699         BIND(L_check_fill_8_bytes);
8700       }
8701       addl(count, 8 << shift);
8702       jccb(Assembler::zero, L_exit);
8703       jmpb(L_fill_8_bytes);
8704 
8705       //
8706       // length is too short, just fill qwords
8707       //
8708       BIND(L_fill_8_bytes_loop);
8709       movq(Address(to, 0), xtmp);
8710       addptr(to, 8);
8711       BIND(L_fill_8_bytes);
8712       subl(count, 1 << (shift + 1));
8713       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8714     }
8715   }
8716   // fill trailing 4 bytes
8717   BIND(L_fill_4_bytes);
8718   testl(count, 1<<shift);
8719   jccb(Assembler::zero, L_fill_2_bytes);
8720   movl(Address(to, 0), value);
8721   if (t == T_BYTE || t == T_SHORT) {
8722     addptr(to, 4);
8723     BIND(L_fill_2_bytes);
8724     // fill trailing 2 bytes
8725     testl(count, 1<<(shift-1));
8726     jccb(Assembler::zero, L_fill_byte);
8727     movw(Address(to, 0), value);
8728     if (t == T_BYTE) {
8729       addptr(to, 2);
8730       BIND(L_fill_byte);
8731       // fill trailing byte
8732       testl(count, 1);
8733       jccb(Assembler::zero, L_exit);
8734       movb(Address(to, 0), value);
8735     } else {
8736       BIND(L_fill_byte);
8737     }
8738   } else {
8739     BIND(L_fill_2_bytes);
8740   }
8741   BIND(L_exit);
8742 }
8743 
8744 // encode char[] to byte[] in ISO_8859_1
8745 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8746                                       XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8747                                       XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8748                                       Register tmp5, Register result) {
8749   // rsi: src
8750   // rdi: dst
8751   // rdx: len
8752   // rcx: tmp5
8753   // rax: result
8754   ShortBranchVerifier sbv(this);
8755   assert_different_registers(src, dst, len, tmp5, result);
8756   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8757 
8758   // set result
8759   xorl(result, result);
8760   // check for zero length
8761   testl(len, len);
8762   jcc(Assembler::zero, L_done);
8763   movl(result, len);
8764 
8765   // Setup pointers
8766   lea(src, Address(src, len, Address::times_2)); // char[]
8767   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8768   negptr(len);
8769 
8770   if (UseSSE42Intrinsics || UseAVX >= 2) {
8771     assert(UseSSE42Intrinsics ? UseSSE >= 4 : true, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8772     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8773     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8774 
8775     if (UseAVX >= 2) {
8776       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8777       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8778       movdl(tmp1Reg, tmp5);
8779       vpbroadcastd(tmp1Reg, tmp1Reg);
8780       jmpb(L_chars_32_check);
8781 
8782       bind(L_copy_32_chars);
8783       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8784       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8785       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8786       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8787       jccb(Assembler::notZero, L_copy_32_chars_exit);
8788       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8789       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8790       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8791 
8792       bind(L_chars_32_check);
8793       addptr(len, 32);
8794       jccb(Assembler::lessEqual, L_copy_32_chars);
8795 
8796       bind(L_copy_32_chars_exit);
8797       subptr(len, 16);
8798       jccb(Assembler::greater, L_copy_16_chars_exit);
8799 
8800     } else if (UseSSE42Intrinsics) {
8801       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8802       movdl(tmp1Reg, tmp5);
8803       pshufd(tmp1Reg, tmp1Reg, 0);
8804       jmpb(L_chars_16_check);
8805     }
8806 
8807     bind(L_copy_16_chars);
8808     if (UseAVX >= 2) {
8809       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8810       vptest(tmp2Reg, tmp1Reg);
8811       jccb(Assembler::notZero, L_copy_16_chars_exit);
8812       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8813       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8814     } else {
8815       if (UseAVX > 0) {
8816         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8817         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8818         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8819       } else {
8820         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8821         por(tmp2Reg, tmp3Reg);
8822         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8823         por(tmp2Reg, tmp4Reg);
8824       }
8825       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8826       jccb(Assembler::notZero, L_copy_16_chars_exit);
8827       packuswb(tmp3Reg, tmp4Reg);
8828     }
8829     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8830 
8831     bind(L_chars_16_check);
8832     addptr(len, 16);
8833     jccb(Assembler::lessEqual, L_copy_16_chars);
8834 
8835     bind(L_copy_16_chars_exit);
8836     if (UseAVX >= 2) {
8837       // clean upper bits of YMM registers
8838       vpxor(tmp2Reg, tmp2Reg);
8839       vpxor(tmp3Reg, tmp3Reg);
8840       vpxor(tmp4Reg, tmp4Reg);
8841       movdl(tmp1Reg, tmp5);
8842       pshufd(tmp1Reg, tmp1Reg, 0);
8843     }
8844     subptr(len, 8);
8845     jccb(Assembler::greater, L_copy_8_chars_exit);
8846 
8847     bind(L_copy_8_chars);
8848     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8849     ptest(tmp3Reg, tmp1Reg);
8850     jccb(Assembler::notZero, L_copy_8_chars_exit);
8851     packuswb(tmp3Reg, tmp1Reg);
8852     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8853     addptr(len, 8);
8854     jccb(Assembler::lessEqual, L_copy_8_chars);
8855 
8856     bind(L_copy_8_chars_exit);
8857     subptr(len, 8);
8858     jccb(Assembler::zero, L_done);
8859   }
8860 
8861   bind(L_copy_1_char);
8862   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8863   testl(tmp5, 0xff00);      // check if Unicode char
8864   jccb(Assembler::notZero, L_copy_1_char_exit);
8865   movb(Address(dst, len, Address::times_1, 0), tmp5);
8866   addptr(len, 1);
8867   jccb(Assembler::less, L_copy_1_char);
8868 
8869   bind(L_copy_1_char_exit);
8870   addptr(result, len); // len is negative count of not processed elements
8871   bind(L_done);
8872 }
8873 
8874 #ifdef _LP64
8875 /**
8876  * Helper for multiply_to_len().
8877  */
8878 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8879   addq(dest_lo, src1);
8880   adcq(dest_hi, 0);
8881   addq(dest_lo, src2);
8882   adcq(dest_hi, 0);
8883 }
8884 
8885 /**
8886  * Multiply 64 bit by 64 bit first loop.
8887  */
8888 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8889                                            Register y, Register y_idx, Register z,
8890                                            Register carry, Register product,
8891                                            Register idx, Register kdx) {
8892   //
8893   //  jlong carry, x[], y[], z[];
8894   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8895   //    huge_128 product = y[idx] * x[xstart] + carry;
8896   //    z[kdx] = (jlong)product;
8897   //    carry  = (jlong)(product >>> 64);
8898   //  }
8899   //  z[xstart] = carry;
8900   //
8901 
8902   Label L_first_loop, L_first_loop_exit;
8903   Label L_one_x, L_one_y, L_multiply;
8904 
8905   decrementl(xstart);
8906   jcc(Assembler::negative, L_one_x);
8907 
8908   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8909   rorq(x_xstart, 32); // convert big-endian to little-endian
8910 
8911   bind(L_first_loop);
8912   decrementl(idx);
8913   jcc(Assembler::negative, L_first_loop_exit);
8914   decrementl(idx);
8915   jcc(Assembler::negative, L_one_y);
8916   movq(y_idx, Address(y, idx, Address::times_4,  0));
8917   rorq(y_idx, 32); // convert big-endian to little-endian
8918   bind(L_multiply);
8919   movq(product, x_xstart);
8920   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
8921   addq(product, carry);
8922   adcq(rdx, 0);
8923   subl(kdx, 2);
8924   movl(Address(z, kdx, Address::times_4,  4), product);
8925   shrq(product, 32);
8926   movl(Address(z, kdx, Address::times_4,  0), product);
8927   movq(carry, rdx);
8928   jmp(L_first_loop);
8929 
8930   bind(L_one_y);
8931   movl(y_idx, Address(y,  0));
8932   jmp(L_multiply);
8933 
8934   bind(L_one_x);
8935   movl(x_xstart, Address(x,  0));
8936   jmp(L_first_loop);
8937 
8938   bind(L_first_loop_exit);
8939 }
8940 
8941 /**
8942  * Multiply 64 bit by 64 bit and add 128 bit.
8943  */
8944 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
8945                                             Register yz_idx, Register idx,
8946                                             Register carry, Register product, int offset) {
8947   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
8948   //     z[kdx] = (jlong)product;
8949 
8950   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
8951   rorq(yz_idx, 32); // convert big-endian to little-endian
8952   movq(product, x_xstart);
8953   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
8954   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
8955   rorq(yz_idx, 32); // convert big-endian to little-endian
8956 
8957   add2_with_carry(rdx, product, carry, yz_idx);
8958 
8959   movl(Address(z, idx, Address::times_4,  offset+4), product);
8960   shrq(product, 32);
8961   movl(Address(z, idx, Address::times_4,  offset), product);
8962 
8963 }
8964 
8965 /**
8966  * Multiply 128 bit by 128 bit. Unrolled inner loop.
8967  */
8968 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
8969                                              Register yz_idx, Register idx, Register jdx,
8970                                              Register carry, Register product,
8971                                              Register carry2) {
8972   //   jlong carry, x[], y[], z[];
8973   //   int kdx = ystart+1;
8974   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8975   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
8976   //     z[kdx+idx+1] = (jlong)product;
8977   //     jlong carry2  = (jlong)(product >>> 64);
8978   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
8979   //     z[kdx+idx] = (jlong)product;
8980   //     carry  = (jlong)(product >>> 64);
8981   //   }
8982   //   idx += 2;
8983   //   if (idx > 0) {
8984   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
8985   //     z[kdx+idx] = (jlong)product;
8986   //     carry  = (jlong)(product >>> 64);
8987   //   }
8988   //
8989 
8990   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8991 
8992   movl(jdx, idx);
8993   andl(jdx, 0xFFFFFFFC);
8994   shrl(jdx, 2);
8995 
8996   bind(L_third_loop);
8997   subl(jdx, 1);
8998   jcc(Assembler::negative, L_third_loop_exit);
8999   subl(idx, 4);
9000 
9001   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
9002   movq(carry2, rdx);
9003 
9004   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
9005   movq(carry, rdx);
9006   jmp(L_third_loop);
9007 
9008   bind (L_third_loop_exit);
9009 
9010   andl (idx, 0x3);
9011   jcc(Assembler::zero, L_post_third_loop_done);
9012 
9013   Label L_check_1;
9014   subl(idx, 2);
9015   jcc(Assembler::negative, L_check_1);
9016 
9017   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
9018   movq(carry, rdx);
9019 
9020   bind (L_check_1);
9021   addl (idx, 0x2);
9022   andl (idx, 0x1);
9023   subl(idx, 1);
9024   jcc(Assembler::negative, L_post_third_loop_done);
9025 
9026   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9027   movq(product, x_xstart);
9028   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9029   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9030 
9031   add2_with_carry(rdx, product, yz_idx, carry);
9032 
9033   movl(Address(z, idx, Address::times_4,  0), product);
9034   shrq(product, 32);
9035 
9036   shlq(rdx, 32);
9037   orq(product, rdx);
9038   movq(carry, product);
9039 
9040   bind(L_post_third_loop_done);
9041 }
9042 
9043 /**
9044  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9045  *
9046  */
9047 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9048                                                   Register carry, Register carry2,
9049                                                   Register idx, Register jdx,
9050                                                   Register yz_idx1, Register yz_idx2,
9051                                                   Register tmp, Register tmp3, Register tmp4) {
9052   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9053 
9054   //   jlong carry, x[], y[], z[];
9055   //   int kdx = ystart+1;
9056   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9057   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9058   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9059   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9060   //     carry  = (jlong)(tmp4 >>> 64);
9061   //     z[kdx+idx+1] = (jlong)tmp3;
9062   //     z[kdx+idx] = (jlong)tmp4;
9063   //   }
9064   //   idx += 2;
9065   //   if (idx > 0) {
9066   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9067   //     z[kdx+idx] = (jlong)yz_idx1;
9068   //     carry  = (jlong)(yz_idx1 >>> 64);
9069   //   }
9070   //
9071 
9072   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9073 
9074   movl(jdx, idx);
9075   andl(jdx, 0xFFFFFFFC);
9076   shrl(jdx, 2);
9077 
9078   bind(L_third_loop);
9079   subl(jdx, 1);
9080   jcc(Assembler::negative, L_third_loop_exit);
9081   subl(idx, 4);
9082 
9083   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9084   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9085   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9086   rorxq(yz_idx2, yz_idx2, 32);
9087 
9088   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9089   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9090 
9091   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9092   rorxq(yz_idx1, yz_idx1, 32);
9093   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9094   rorxq(yz_idx2, yz_idx2, 32);
9095 
9096   if (VM_Version::supports_adx()) {
9097     adcxq(tmp3, carry);
9098     adoxq(tmp3, yz_idx1);
9099 
9100     adcxq(tmp4, tmp);
9101     adoxq(tmp4, yz_idx2);
9102 
9103     movl(carry, 0); // does not affect flags
9104     adcxq(carry2, carry);
9105     adoxq(carry2, carry);
9106   } else {
9107     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9108     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9109   }
9110   movq(carry, carry2);
9111 
9112   movl(Address(z, idx, Address::times_4, 12), tmp3);
9113   shrq(tmp3, 32);
9114   movl(Address(z, idx, Address::times_4,  8), tmp3);
9115 
9116   movl(Address(z, idx, Address::times_4,  4), tmp4);
9117   shrq(tmp4, 32);
9118   movl(Address(z, idx, Address::times_4,  0), tmp4);
9119 
9120   jmp(L_third_loop);
9121 
9122   bind (L_third_loop_exit);
9123 
9124   andl (idx, 0x3);
9125   jcc(Assembler::zero, L_post_third_loop_done);
9126 
9127   Label L_check_1;
9128   subl(idx, 2);
9129   jcc(Assembler::negative, L_check_1);
9130 
9131   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9132   rorxq(yz_idx1, yz_idx1, 32);
9133   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9134   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9135   rorxq(yz_idx2, yz_idx2, 32);
9136 
9137   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9138 
9139   movl(Address(z, idx, Address::times_4,  4), tmp3);
9140   shrq(tmp3, 32);
9141   movl(Address(z, idx, Address::times_4,  0), tmp3);
9142   movq(carry, tmp4);
9143 
9144   bind (L_check_1);
9145   addl (idx, 0x2);
9146   andl (idx, 0x1);
9147   subl(idx, 1);
9148   jcc(Assembler::negative, L_post_third_loop_done);
9149   movl(tmp4, Address(y, idx, Address::times_4,  0));
9150   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9151   movl(tmp4, Address(z, idx, Address::times_4,  0));
9152 
9153   add2_with_carry(carry2, tmp3, tmp4, carry);
9154 
9155   movl(Address(z, idx, Address::times_4,  0), tmp3);
9156   shrq(tmp3, 32);
9157 
9158   shlq(carry2, 32);
9159   orq(tmp3, carry2);
9160   movq(carry, tmp3);
9161 
9162   bind(L_post_third_loop_done);
9163 }
9164 
9165 /**
9166  * Code for BigInteger::multiplyToLen() instrinsic.
9167  *
9168  * rdi: x
9169  * rax: xlen
9170  * rsi: y
9171  * rcx: ylen
9172  * r8:  z
9173  * r11: zlen
9174  * r12: tmp1
9175  * r13: tmp2
9176  * r14: tmp3
9177  * r15: tmp4
9178  * rbx: tmp5
9179  *
9180  */
9181 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9182                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9183   ShortBranchVerifier sbv(this);
9184   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9185 
9186   push(tmp1);
9187   push(tmp2);
9188   push(tmp3);
9189   push(tmp4);
9190   push(tmp5);
9191 
9192   push(xlen);
9193   push(zlen);
9194 
9195   const Register idx = tmp1;
9196   const Register kdx = tmp2;
9197   const Register xstart = tmp3;
9198 
9199   const Register y_idx = tmp4;
9200   const Register carry = tmp5;
9201   const Register product  = xlen;
9202   const Register x_xstart = zlen;  // reuse register
9203 
9204   // First Loop.
9205   //
9206   //  final static long LONG_MASK = 0xffffffffL;
9207   //  int xstart = xlen - 1;
9208   //  int ystart = ylen - 1;
9209   //  long carry = 0;
9210   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9211   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9212   //    z[kdx] = (int)product;
9213   //    carry = product >>> 32;
9214   //  }
9215   //  z[xstart] = (int)carry;
9216   //
9217 
9218   movl(idx, ylen);      // idx = ylen;
9219   movl(kdx, zlen);      // kdx = xlen+ylen;
9220   xorq(carry, carry);   // carry = 0;
9221 
9222   Label L_done;
9223 
9224   movl(xstart, xlen);
9225   decrementl(xstart);
9226   jcc(Assembler::negative, L_done);
9227 
9228   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9229 
9230   Label L_second_loop;
9231   testl(kdx, kdx);
9232   jcc(Assembler::zero, L_second_loop);
9233 
9234   Label L_carry;
9235   subl(kdx, 1);
9236   jcc(Assembler::zero, L_carry);
9237 
9238   movl(Address(z, kdx, Address::times_4,  0), carry);
9239   shrq(carry, 32);
9240   subl(kdx, 1);
9241 
9242   bind(L_carry);
9243   movl(Address(z, kdx, Address::times_4,  0), carry);
9244 
9245   // Second and third (nested) loops.
9246   //
9247   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9248   //   carry = 0;
9249   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9250   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9251   //                    (z[k] & LONG_MASK) + carry;
9252   //     z[k] = (int)product;
9253   //     carry = product >>> 32;
9254   //   }
9255   //   z[i] = (int)carry;
9256   // }
9257   //
9258   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9259 
9260   const Register jdx = tmp1;
9261 
9262   bind(L_second_loop);
9263   xorl(carry, carry);    // carry = 0;
9264   movl(jdx, ylen);       // j = ystart+1
9265 
9266   subl(xstart, 1);       // i = xstart-1;
9267   jcc(Assembler::negative, L_done);
9268 
9269   push (z);
9270 
9271   Label L_last_x;
9272   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9273   subl(xstart, 1);       // i = xstart-1;
9274   jcc(Assembler::negative, L_last_x);
9275 
9276   if (UseBMI2Instructions) {
9277     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9278     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9279   } else {
9280     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9281     rorq(x_xstart, 32);  // convert big-endian to little-endian
9282   }
9283 
9284   Label L_third_loop_prologue;
9285   bind(L_third_loop_prologue);
9286 
9287   push (x);
9288   push (xstart);
9289   push (ylen);
9290 
9291 
9292   if (UseBMI2Instructions) {
9293     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9294   } else { // !UseBMI2Instructions
9295     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9296   }
9297 
9298   pop(ylen);
9299   pop(xlen);
9300   pop(x);
9301   pop(z);
9302 
9303   movl(tmp3, xlen);
9304   addl(tmp3, 1);
9305   movl(Address(z, tmp3, Address::times_4,  0), carry);
9306   subl(tmp3, 1);
9307   jccb(Assembler::negative, L_done);
9308 
9309   shrq(carry, 32);
9310   movl(Address(z, tmp3, Address::times_4,  0), carry);
9311   jmp(L_second_loop);
9312 
9313   // Next infrequent code is moved outside loops.
9314   bind(L_last_x);
9315   if (UseBMI2Instructions) {
9316     movl(rdx, Address(x,  0));
9317   } else {
9318     movl(x_xstart, Address(x,  0));
9319   }
9320   jmp(L_third_loop_prologue);
9321 
9322   bind(L_done);
9323 
9324   pop(zlen);
9325   pop(xlen);
9326 
9327   pop(tmp5);
9328   pop(tmp4);
9329   pop(tmp3);
9330   pop(tmp2);
9331   pop(tmp1);
9332 }
9333 
9334 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9335   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9336   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9337   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9338   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9339   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9340   Label SAME_TILL_END, DONE;
9341   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9342 
9343   //scale is in rcx in both Win64 and Unix
9344   ShortBranchVerifier sbv(this);
9345 
9346   shlq(length);
9347   xorq(result, result);
9348 
9349   cmpq(length, 8);
9350   jcc(Assembler::equal, VECTOR8_LOOP);
9351   jcc(Assembler::less, VECTOR4_TAIL);
9352 
9353   if (UseAVX >= 2){
9354 
9355     cmpq(length, 16);
9356     jcc(Assembler::equal, VECTOR16_LOOP);
9357     jcc(Assembler::less, VECTOR8_LOOP);
9358 
9359     cmpq(length, 32);
9360     jccb(Assembler::less, VECTOR16_TAIL);
9361 
9362     subq(length, 32);
9363     bind(VECTOR32_LOOP);
9364     vmovdqu(rymm0, Address(obja, result));
9365     vmovdqu(rymm1, Address(objb, result));
9366     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9367     vptest(rymm2, rymm2);
9368     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9369     addq(result, 32);
9370     subq(length, 32);
9371     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9372     addq(length, 32);
9373     jcc(Assembler::equal, SAME_TILL_END);
9374     //falling through if less than 32 bytes left //close the branch here.
9375 
9376     bind(VECTOR16_TAIL);
9377     cmpq(length, 16);
9378     jccb(Assembler::less, VECTOR8_TAIL);
9379     bind(VECTOR16_LOOP);
9380     movdqu(rymm0, Address(obja, result));
9381     movdqu(rymm1, Address(objb, result));
9382     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9383     ptest(rymm2, rymm2);
9384     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9385     addq(result, 16);
9386     subq(length, 16);
9387     jcc(Assembler::equal, SAME_TILL_END);
9388     //falling through if less than 16 bytes left
9389   } else {//regular intrinsics
9390 
9391     cmpq(length, 16);
9392     jccb(Assembler::less, VECTOR8_TAIL);
9393 
9394     subq(length, 16);
9395     bind(VECTOR16_LOOP);
9396     movdqu(rymm0, Address(obja, result));
9397     movdqu(rymm1, Address(objb, result));
9398     pxor(rymm0, rymm1);
9399     ptest(rymm0, rymm0);
9400     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9401     addq(result, 16);
9402     subq(length, 16);
9403     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9404     addq(length, 16);
9405     jcc(Assembler::equal, SAME_TILL_END);
9406     //falling through if less than 16 bytes left
9407   }
9408 
9409   bind(VECTOR8_TAIL);
9410   cmpq(length, 8);
9411   jccb(Assembler::less, VECTOR4_TAIL);
9412   bind(VECTOR8_LOOP);
9413   movq(tmp1, Address(obja, result));
9414   movq(tmp2, Address(objb, result));
9415   xorq(tmp1, tmp2);
9416   testq(tmp1, tmp1);
9417   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9418   addq(result, 8);
9419   subq(length, 8);
9420   jcc(Assembler::equal, SAME_TILL_END);
9421   //falling through if less than 8 bytes left
9422 
9423   bind(VECTOR4_TAIL);
9424   cmpq(length, 4);
9425   jccb(Assembler::less, BYTES_TAIL);
9426   bind(VECTOR4_LOOP);
9427   movl(tmp1, Address(obja, result));
9428   xorl(tmp1, Address(objb, result));
9429   testl(tmp1, tmp1);
9430   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9431   addq(result, 4);
9432   subq(length, 4);
9433   jcc(Assembler::equal, SAME_TILL_END);
9434   //falling through if less than 4 bytes left
9435 
9436   bind(BYTES_TAIL);
9437   bind(BYTES_LOOP);
9438   load_unsigned_byte(tmp1, Address(obja, result));
9439   load_unsigned_byte(tmp2, Address(objb, result));
9440   xorl(tmp1, tmp2);
9441   testl(tmp1, tmp1);
9442   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9443   decq(length);
9444   jccb(Assembler::zero, SAME_TILL_END);
9445   incq(result);
9446   load_unsigned_byte(tmp1, Address(obja, result));
9447   load_unsigned_byte(tmp2, Address(objb, result));
9448   xorl(tmp1, tmp2);
9449   testl(tmp1, tmp1);
9450   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9451   decq(length);
9452   jccb(Assembler::zero, SAME_TILL_END);
9453   incq(result);
9454   load_unsigned_byte(tmp1, Address(obja, result));
9455   load_unsigned_byte(tmp2, Address(objb, result));
9456   xorl(tmp1, tmp2);
9457   testl(tmp1, tmp1);
9458   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9459   jmpb(SAME_TILL_END);
9460 
9461   if (UseAVX >= 2){
9462     bind(VECTOR32_NOT_EQUAL);
9463     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9464     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9465     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9466     vpmovmskb(tmp1, rymm0);
9467     bsfq(tmp1, tmp1);
9468     addq(result, tmp1);
9469     shrq(result);
9470     jmpb(DONE);
9471   }
9472 
9473   bind(VECTOR16_NOT_EQUAL);
9474   if (UseAVX >= 2){
9475     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9476     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9477     pxor(rymm0, rymm2);
9478   } else {
9479     pcmpeqb(rymm2, rymm2);
9480     pxor(rymm0, rymm1);
9481     pcmpeqb(rymm0, rymm1);
9482     pxor(rymm0, rymm2);
9483   }
9484   pmovmskb(tmp1, rymm0);
9485   bsfq(tmp1, tmp1);
9486   addq(result, tmp1);
9487   shrq(result);
9488   jmpb(DONE);
9489 
9490   bind(VECTOR8_NOT_EQUAL);
9491   bind(VECTOR4_NOT_EQUAL);
9492   bsfq(tmp1, tmp1);
9493   shrq(tmp1, 3);
9494   addq(result, tmp1);
9495   bind(BYTES_NOT_EQUAL);
9496   shrq(result);
9497   jmpb(DONE);
9498 
9499   bind(SAME_TILL_END);
9500   mov64(result, -1);
9501 
9502   bind(DONE);
9503 }
9504 
9505 
9506 //Helper functions for square_to_len()
9507 
9508 /**
9509  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9510  * Preserves x and z and modifies rest of the registers.
9511  */
9512 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9513   // Perform square and right shift by 1
9514   // Handle odd xlen case first, then for even xlen do the following
9515   // jlong carry = 0;
9516   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9517   //     huge_128 product = x[j:j+1] * x[j:j+1];
9518   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9519   //     z[i+2:i+3] = (jlong)(product >>> 1);
9520   //     carry = (jlong)product;
9521   // }
9522 
9523   xorq(tmp5, tmp5);     // carry
9524   xorq(rdxReg, rdxReg);
9525   xorl(tmp1, tmp1);     // index for x
9526   xorl(tmp4, tmp4);     // index for z
9527 
9528   Label L_first_loop, L_first_loop_exit;
9529 
9530   testl(xlen, 1);
9531   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9532 
9533   // Square and right shift by 1 the odd element using 32 bit multiply
9534   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9535   imulq(raxReg, raxReg);
9536   shrq(raxReg, 1);
9537   adcq(tmp5, 0);
9538   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9539   incrementl(tmp1);
9540   addl(tmp4, 2);
9541 
9542   // Square and  right shift by 1 the rest using 64 bit multiply
9543   bind(L_first_loop);
9544   cmpptr(tmp1, xlen);
9545   jccb(Assembler::equal, L_first_loop_exit);
9546 
9547   // Square
9548   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9549   rorq(raxReg, 32);    // convert big-endian to little-endian
9550   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9551 
9552   // Right shift by 1 and save carry
9553   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9554   rcrq(rdxReg, 1);
9555   rcrq(raxReg, 1);
9556   adcq(tmp5, 0);
9557 
9558   // Store result in z
9559   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9560   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9561 
9562   // Update indices for x and z
9563   addl(tmp1, 2);
9564   addl(tmp4, 4);
9565   jmp(L_first_loop);
9566 
9567   bind(L_first_loop_exit);
9568 }
9569 
9570 
9571 /**
9572  * Perform the following multiply add operation using BMI2 instructions
9573  * carry:sum = sum + op1*op2 + carry
9574  * op2 should be in rdx
9575  * op2 is preserved, all other registers are modified
9576  */
9577 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9578   // assert op2 is rdx
9579   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9580   addq(sum, carry);
9581   adcq(tmp2, 0);
9582   addq(sum, op1);
9583   adcq(tmp2, 0);
9584   movq(carry, tmp2);
9585 }
9586 
9587 /**
9588  * Perform the following multiply add operation:
9589  * carry:sum = sum + op1*op2 + carry
9590  * Preserves op1, op2 and modifies rest of registers
9591  */
9592 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9593   // rdx:rax = op1 * op2
9594   movq(raxReg, op2);
9595   mulq(op1);
9596 
9597   //  rdx:rax = sum + carry + rdx:rax
9598   addq(sum, carry);
9599   adcq(rdxReg, 0);
9600   addq(sum, raxReg);
9601   adcq(rdxReg, 0);
9602 
9603   // carry:sum = rdx:sum
9604   movq(carry, rdxReg);
9605 }
9606 
9607 /**
9608  * Add 64 bit long carry into z[] with carry propogation.
9609  * Preserves z and carry register values and modifies rest of registers.
9610  *
9611  */
9612 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9613   Label L_fourth_loop, L_fourth_loop_exit;
9614 
9615   movl(tmp1, 1);
9616   subl(zlen, 2);
9617   addq(Address(z, zlen, Address::times_4, 0), carry);
9618 
9619   bind(L_fourth_loop);
9620   jccb(Assembler::carryClear, L_fourth_loop_exit);
9621   subl(zlen, 2);
9622   jccb(Assembler::negative, L_fourth_loop_exit);
9623   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9624   jmp(L_fourth_loop);
9625   bind(L_fourth_loop_exit);
9626 }
9627 
9628 /**
9629  * Shift z[] left by 1 bit.
9630  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9631  *
9632  */
9633 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9634 
9635   Label L_fifth_loop, L_fifth_loop_exit;
9636 
9637   // Fifth loop
9638   // Perform primitiveLeftShift(z, zlen, 1)
9639 
9640   const Register prev_carry = tmp1;
9641   const Register new_carry = tmp4;
9642   const Register value = tmp2;
9643   const Register zidx = tmp3;
9644 
9645   // int zidx, carry;
9646   // long value;
9647   // carry = 0;
9648   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9649   //    (carry:value)  = (z[i] << 1) | carry ;
9650   //    z[i] = value;
9651   // }
9652 
9653   movl(zidx, zlen);
9654   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9655 
9656   bind(L_fifth_loop);
9657   decl(zidx);  // Use decl to preserve carry flag
9658   decl(zidx);
9659   jccb(Assembler::negative, L_fifth_loop_exit);
9660 
9661   if (UseBMI2Instructions) {
9662      movq(value, Address(z, zidx, Address::times_4, 0));
9663      rclq(value, 1);
9664      rorxq(value, value, 32);
9665      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9666   }
9667   else {
9668     // clear new_carry
9669     xorl(new_carry, new_carry);
9670 
9671     // Shift z[i] by 1, or in previous carry and save new carry
9672     movq(value, Address(z, zidx, Address::times_4, 0));
9673     shlq(value, 1);
9674     adcl(new_carry, 0);
9675 
9676     orq(value, prev_carry);
9677     rorq(value, 0x20);
9678     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9679 
9680     // Set previous carry = new carry
9681     movl(prev_carry, new_carry);
9682   }
9683   jmp(L_fifth_loop);
9684 
9685   bind(L_fifth_loop_exit);
9686 }
9687 
9688 
9689 /**
9690  * Code for BigInteger::squareToLen() intrinsic
9691  *
9692  * rdi: x
9693  * rsi: len
9694  * r8:  z
9695  * rcx: zlen
9696  * r12: tmp1
9697  * r13: tmp2
9698  * r14: tmp3
9699  * r15: tmp4
9700  * rbx: tmp5
9701  *
9702  */
9703 void MacroAssembler::square_to_len(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9704 
9705   Label L_second_loop, L_second_loop_exit, L_third_loop, L_third_loop_exit, fifth_loop, fifth_loop_exit, L_last_x, L_multiply;
9706   push(tmp1);
9707   push(tmp2);
9708   push(tmp3);
9709   push(tmp4);
9710   push(tmp5);
9711 
9712   // First loop
9713   // Store the squares, right shifted one bit (i.e., divided by 2).
9714   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9715 
9716   // Add in off-diagonal sums.
9717   //
9718   // Second, third (nested) and fourth loops.
9719   // zlen +=2;
9720   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9721   //    carry = 0;
9722   //    long op2 = x[xidx:xidx+1];
9723   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9724   //       k -= 2;
9725   //       long op1 = x[j:j+1];
9726   //       long sum = z[k:k+1];
9727   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9728   //       z[k:k+1] = sum;
9729   //    }
9730   //    add_one_64(z, k, carry, tmp_regs);
9731   // }
9732 
9733   const Register carry = tmp5;
9734   const Register sum = tmp3;
9735   const Register op1 = tmp4;
9736   Register op2 = tmp2;
9737 
9738   push(zlen);
9739   push(len);
9740   addl(zlen,2);
9741   bind(L_second_loop);
9742   xorq(carry, carry);
9743   subl(zlen, 4);
9744   subl(len, 2);
9745   push(zlen);
9746   push(len);
9747   cmpl(len, 0);
9748   jccb(Assembler::lessEqual, L_second_loop_exit);
9749 
9750   // Multiply an array by one 64 bit long.
9751   if (UseBMI2Instructions) {
9752     op2 = rdxReg;
9753     movq(op2, Address(x, len, Address::times_4,  0));
9754     rorxq(op2, op2, 32);
9755   }
9756   else {
9757     movq(op2, Address(x, len, Address::times_4,  0));
9758     rorq(op2, 32);
9759   }
9760 
9761   bind(L_third_loop);
9762   decrementl(len);
9763   jccb(Assembler::negative, L_third_loop_exit);
9764   decrementl(len);
9765   jccb(Assembler::negative, L_last_x);
9766 
9767   movq(op1, Address(x, len, Address::times_4,  0));
9768   rorq(op1, 32);
9769 
9770   bind(L_multiply);
9771   subl(zlen, 2);
9772   movq(sum, Address(z, zlen, Address::times_4,  0));
9773 
9774   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9775   if (UseBMI2Instructions) {
9776     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9777   }
9778   else {
9779     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9780   }
9781 
9782   movq(Address(z, zlen, Address::times_4, 0), sum);
9783 
9784   jmp(L_third_loop);
9785   bind(L_third_loop_exit);
9786 
9787   // Fourth loop
9788   // Add 64 bit long carry into z with carry propogation.
9789   // Uses offsetted zlen.
9790   add_one_64(z, zlen, carry, tmp1);
9791 
9792   pop(len);
9793   pop(zlen);
9794   jmp(L_second_loop);
9795 
9796   // Next infrequent code is moved outside loops.
9797   bind(L_last_x);
9798   movl(op1, Address(x, 0));
9799   jmp(L_multiply);
9800 
9801   bind(L_second_loop_exit);
9802   pop(len);
9803   pop(zlen);
9804   pop(len);
9805   pop(zlen);
9806 
9807   // Fifth loop
9808   // Shift z left 1 bit.
9809   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9810 
9811   // z[zlen-1] |= x[len-1] & 1;
9812   movl(tmp3, Address(x, len, Address::times_4, -4));
9813   andl(tmp3, 1);
9814   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9815 
9816   pop(tmp5);
9817   pop(tmp4);
9818   pop(tmp3);
9819   pop(tmp2);
9820   pop(tmp1);
9821 }
9822 
9823 /**
9824  * Helper function for mul_add()
9825  * Multiply the in[] by int k and add to out[] starting at offset offs using
9826  * 128 bit by 32 bit multiply and return the carry in tmp5.
9827  * Only quad int aligned length of in[] is operated on in this function.
9828  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9829  * This function preserves out, in and k registers.
9830  * len and offset point to the appropriate index in "in" & "out" correspondingly
9831  * tmp5 has the carry.
9832  * other registers are temporary and are modified.
9833  *
9834  */
9835 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9836   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9837   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9838 
9839   Label L_first_loop, L_first_loop_exit;
9840 
9841   movl(tmp1, len);
9842   shrl(tmp1, 2);
9843 
9844   bind(L_first_loop);
9845   subl(tmp1, 1);
9846   jccb(Assembler::negative, L_first_loop_exit);
9847 
9848   subl(len, 4);
9849   subl(offset, 4);
9850 
9851   Register op2 = tmp2;
9852   const Register sum = tmp3;
9853   const Register op1 = tmp4;
9854   const Register carry = tmp5;
9855 
9856   if (UseBMI2Instructions) {
9857     op2 = rdxReg;
9858   }
9859 
9860   movq(op1, Address(in, len, Address::times_4,  8));
9861   rorq(op1, 32);
9862   movq(sum, Address(out, offset, Address::times_4,  8));
9863   rorq(sum, 32);
9864   if (UseBMI2Instructions) {
9865     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9866   }
9867   else {
9868     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9869   }
9870   // Store back in big endian from little endian
9871   rorq(sum, 0x20);
9872   movq(Address(out, offset, Address::times_4,  8), sum);
9873 
9874   movq(op1, Address(in, len, Address::times_4,  0));
9875   rorq(op1, 32);
9876   movq(sum, Address(out, offset, Address::times_4,  0));
9877   rorq(sum, 32);
9878   if (UseBMI2Instructions) {
9879     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9880   }
9881   else {
9882     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9883   }
9884   // Store back in big endian from little endian
9885   rorq(sum, 0x20);
9886   movq(Address(out, offset, Address::times_4,  0), sum);
9887 
9888   jmp(L_first_loop);
9889   bind(L_first_loop_exit);
9890 }
9891 
9892 /**
9893  * Code for BigInteger::mulAdd() intrinsic
9894  *
9895  * rdi: out
9896  * rsi: in
9897  * r11: offs (out.length - offset)
9898  * rcx: len
9899  * r8:  k
9900  * r12: tmp1
9901  * r13: tmp2
9902  * r14: tmp3
9903  * r15: tmp4
9904  * rbx: tmp5
9905  * Multiply the in[] by word k and add to out[], return the carry in rax
9906  */
9907 void MacroAssembler::mul_add(Register out, Register in, Register offs,
9908    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
9909    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9910 
9911   Label L_carry, L_last_in, L_done;
9912 
9913 // carry = 0;
9914 // for (int j=len-1; j >= 0; j--) {
9915 //    long product = (in[j] & LONG_MASK) * kLong +
9916 //                   (out[offs] & LONG_MASK) + carry;
9917 //    out[offs--] = (int)product;
9918 //    carry = product >>> 32;
9919 // }
9920 //
9921   push(tmp1);
9922   push(tmp2);
9923   push(tmp3);
9924   push(tmp4);
9925   push(tmp5);
9926 
9927   Register op2 = tmp2;
9928   const Register sum = tmp3;
9929   const Register op1 = tmp4;
9930   const Register carry =  tmp5;
9931 
9932   if (UseBMI2Instructions) {
9933     op2 = rdxReg;
9934     movl(op2, k);
9935   }
9936   else {
9937     movl(op2, k);
9938   }
9939 
9940   xorq(carry, carry);
9941 
9942   //First loop
9943 
9944   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
9945   //The carry is in tmp5
9946   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
9947 
9948   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
9949   decrementl(len);
9950   jccb(Assembler::negative, L_carry);
9951   decrementl(len);
9952   jccb(Assembler::negative, L_last_in);
9953 
9954   movq(op1, Address(in, len, Address::times_4,  0));
9955   rorq(op1, 32);
9956 
9957   subl(offs, 2);
9958   movq(sum, Address(out, offs, Address::times_4,  0));
9959   rorq(sum, 32);
9960 
9961   if (UseBMI2Instructions) {
9962     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9963   }
9964   else {
9965     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9966   }
9967 
9968   // Store back in big endian from little endian
9969   rorq(sum, 0x20);
9970   movq(Address(out, offs, Address::times_4,  0), sum);
9971 
9972   testl(len, len);
9973   jccb(Assembler::zero, L_carry);
9974 
9975   //Multiply the last in[] entry, if any
9976   bind(L_last_in);
9977   movl(op1, Address(in, 0));
9978   movl(sum, Address(out, offs, Address::times_4,  -4));
9979 
9980   movl(raxReg, k);
9981   mull(op1); //tmp4 * eax -> edx:eax
9982   addl(sum, carry);
9983   adcl(rdxReg, 0);
9984   addl(sum, raxReg);
9985   adcl(rdxReg, 0);
9986   movl(carry, rdxReg);
9987 
9988   movl(Address(out, offs, Address::times_4,  -4), sum);
9989 
9990   bind(L_carry);
9991   //return tmp5/carry as carry in rax
9992   movl(rax, carry);
9993 
9994   bind(L_done);
9995   pop(tmp5);
9996   pop(tmp4);
9997   pop(tmp3);
9998   pop(tmp2);
9999   pop(tmp1);
10000 }
10001 #endif
10002 
10003 /**
10004  * Emits code to update CRC-32 with a byte value according to constants in table
10005  *
10006  * @param [in,out]crc   Register containing the crc.
10007  * @param [in]val       Register containing the byte to fold into the CRC.
10008  * @param [in]table     Register containing the table of crc constants.
10009  *
10010  * uint32_t crc;
10011  * val = crc_table[(val ^ crc) & 0xFF];
10012  * crc = val ^ (crc >> 8);
10013  *
10014  */
10015 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
10016   xorl(val, crc);
10017   andl(val, 0xFF);
10018   shrl(crc, 8); // unsigned shift
10019   xorl(crc, Address(table, val, Address::times_4, 0));
10020 }
10021 
10022 /**
10023  * Fold 128-bit data chunk
10024  */
10025 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
10026   if (UseAVX > 0) {
10027     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
10028     vpclmulldq(xcrc, xK, xcrc); // [63:0]
10029     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
10030     pxor(xcrc, xtmp);
10031   } else {
10032     movdqa(xtmp, xcrc);
10033     pclmulhdq(xtmp, xK);   // [123:64]
10034     pclmulldq(xcrc, xK);   // [63:0]
10035     pxor(xcrc, xtmp);
10036     movdqu(xtmp, Address(buf, offset));
10037     pxor(xcrc, xtmp);
10038   }
10039 }
10040 
10041 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
10042   if (UseAVX > 0) {
10043     vpclmulhdq(xtmp, xK, xcrc);
10044     vpclmulldq(xcrc, xK, xcrc);
10045     pxor(xcrc, xbuf);
10046     pxor(xcrc, xtmp);
10047   } else {
10048     movdqa(xtmp, xcrc);
10049     pclmulhdq(xtmp, xK);
10050     pclmulldq(xcrc, xK);
10051     pxor(xcrc, xbuf);
10052     pxor(xcrc, xtmp);
10053   }
10054 }
10055 
10056 /**
10057  * 8-bit folds to compute 32-bit CRC
10058  *
10059  * uint64_t xcrc;
10060  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
10061  */
10062 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
10063   movdl(tmp, xcrc);
10064   andl(tmp, 0xFF);
10065   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
10066   psrldq(xcrc, 1); // unsigned shift one byte
10067   pxor(xcrc, xtmp);
10068 }
10069 
10070 /**
10071  * uint32_t crc;
10072  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10073  */
10074 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10075   movl(tmp, crc);
10076   andl(tmp, 0xFF);
10077   shrl(crc, 8);
10078   xorl(crc, Address(table, tmp, Address::times_4, 0));
10079 }
10080 
10081 /**
10082  * @param crc   register containing existing CRC (32-bit)
10083  * @param buf   register pointing to input byte buffer (byte*)
10084  * @param len   register containing number of bytes
10085  * @param table register that will contain address of CRC table
10086  * @param tmp   scratch register
10087  */
10088 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10089   assert_different_registers(crc, buf, len, table, tmp, rax);
10090 
10091   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10092   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10093 
10094   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10095   // context for the registers used, where all instructions below are using 128-bit mode
10096   // On EVEX without VL and BW, these instructions will all be AVX.
10097   if (VM_Version::supports_avx512vlbw()) {
10098     movl(tmp, 0xffff);
10099     kmovwl(k1, tmp);
10100   }
10101 
10102   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10103   notl(crc); // ~crc
10104   cmpl(len, 16);
10105   jcc(Assembler::less, L_tail);
10106 
10107   // Align buffer to 16 bytes
10108   movl(tmp, buf);
10109   andl(tmp, 0xF);
10110   jccb(Assembler::zero, L_aligned);
10111   subl(tmp,  16);
10112   addl(len, tmp);
10113 
10114   align(4);
10115   BIND(L_align_loop);
10116   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10117   update_byte_crc32(crc, rax, table);
10118   increment(buf);
10119   incrementl(tmp);
10120   jccb(Assembler::less, L_align_loop);
10121 
10122   BIND(L_aligned);
10123   movl(tmp, len); // save
10124   shrl(len, 4);
10125   jcc(Assembler::zero, L_tail_restore);
10126 
10127   // Fold crc into first bytes of vector
10128   movdqa(xmm1, Address(buf, 0));
10129   movdl(rax, xmm1);
10130   xorl(crc, rax);
10131   pinsrd(xmm1, crc, 0);
10132   addptr(buf, 16);
10133   subl(len, 4); // len > 0
10134   jcc(Assembler::less, L_fold_tail);
10135 
10136   movdqa(xmm2, Address(buf,  0));
10137   movdqa(xmm3, Address(buf, 16));
10138   movdqa(xmm4, Address(buf, 32));
10139   addptr(buf, 48);
10140   subl(len, 3);
10141   jcc(Assembler::lessEqual, L_fold_512b);
10142 
10143   // Fold total 512 bits of polynomial on each iteration,
10144   // 128 bits per each of 4 parallel streams.
10145   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10146 
10147   align(32);
10148   BIND(L_fold_512b_loop);
10149   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10150   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10151   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10152   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10153   addptr(buf, 64);
10154   subl(len, 4);
10155   jcc(Assembler::greater, L_fold_512b_loop);
10156 
10157   // Fold 512 bits to 128 bits.
10158   BIND(L_fold_512b);
10159   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10160   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10161   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10162   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10163 
10164   // Fold the rest of 128 bits data chunks
10165   BIND(L_fold_tail);
10166   addl(len, 3);
10167   jccb(Assembler::lessEqual, L_fold_128b);
10168   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10169 
10170   BIND(L_fold_tail_loop);
10171   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10172   addptr(buf, 16);
10173   decrementl(len);
10174   jccb(Assembler::greater, L_fold_tail_loop);
10175 
10176   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10177   BIND(L_fold_128b);
10178   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10179   if (UseAVX > 0) {
10180     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10181     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10182     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10183   } else {
10184     movdqa(xmm2, xmm0);
10185     pclmulqdq(xmm2, xmm1, 0x1);
10186     movdqa(xmm3, xmm0);
10187     pand(xmm3, xmm2);
10188     pclmulqdq(xmm0, xmm3, 0x1);
10189   }
10190   psrldq(xmm1, 8);
10191   psrldq(xmm2, 4);
10192   pxor(xmm0, xmm1);
10193   pxor(xmm0, xmm2);
10194 
10195   // 8 8-bit folds to compute 32-bit CRC.
10196   for (int j = 0; j < 4; j++) {
10197     fold_8bit_crc32(xmm0, table, xmm1, rax);
10198   }
10199   movdl(crc, xmm0); // mov 32 bits to general register
10200   for (int j = 0; j < 4; j++) {
10201     fold_8bit_crc32(crc, table, rax);
10202   }
10203 
10204   BIND(L_tail_restore);
10205   movl(len, tmp); // restore
10206   BIND(L_tail);
10207   andl(len, 0xf);
10208   jccb(Assembler::zero, L_exit);
10209 
10210   // Fold the rest of bytes
10211   align(4);
10212   BIND(L_tail_loop);
10213   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10214   update_byte_crc32(crc, rax, table);
10215   increment(buf);
10216   decrementl(len);
10217   jccb(Assembler::greater, L_tail_loop);
10218 
10219   BIND(L_exit);
10220   notl(crc); // ~c
10221 }
10222 
10223 #ifdef _LP64
10224 // S. Gueron / Information Processing Letters 112 (2012) 184
10225 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10226 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10227 // Output: the 64-bit carry-less product of B * CONST
10228 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10229                                      Register tmp1, Register tmp2, Register tmp3) {
10230   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10231   if (n > 0) {
10232     addq(tmp3, n * 256 * 8);
10233   }
10234   //    Q1 = TABLEExt[n][B & 0xFF];
10235   movl(tmp1, in);
10236   andl(tmp1, 0x000000FF);
10237   shll(tmp1, 3);
10238   addq(tmp1, tmp3);
10239   movq(tmp1, Address(tmp1, 0));
10240 
10241   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10242   movl(tmp2, in);
10243   shrl(tmp2, 8);
10244   andl(tmp2, 0x000000FF);
10245   shll(tmp2, 3);
10246   addq(tmp2, tmp3);
10247   movq(tmp2, Address(tmp2, 0));
10248 
10249   shlq(tmp2, 8);
10250   xorq(tmp1, tmp2);
10251 
10252   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10253   movl(tmp2, in);
10254   shrl(tmp2, 16);
10255   andl(tmp2, 0x000000FF);
10256   shll(tmp2, 3);
10257   addq(tmp2, tmp3);
10258   movq(tmp2, Address(tmp2, 0));
10259 
10260   shlq(tmp2, 16);
10261   xorq(tmp1, tmp2);
10262 
10263   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10264   shrl(in, 24);
10265   andl(in, 0x000000FF);
10266   shll(in, 3);
10267   addq(in, tmp3);
10268   movq(in, Address(in, 0));
10269 
10270   shlq(in, 24);
10271   xorq(in, tmp1);
10272   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10273 }
10274 
10275 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10276                                       Register in_out,
10277                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10278                                       XMMRegister w_xtmp2,
10279                                       Register tmp1,
10280                                       Register n_tmp2, Register n_tmp3) {
10281   if (is_pclmulqdq_supported) {
10282     movdl(w_xtmp1, in_out); // modified blindly
10283 
10284     movl(tmp1, const_or_pre_comp_const_index);
10285     movdl(w_xtmp2, tmp1);
10286     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10287 
10288     movdq(in_out, w_xtmp1);
10289   } else {
10290     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10291   }
10292 }
10293 
10294 // Recombination Alternative 2: No bit-reflections
10295 // T1 = (CRC_A * U1) << 1
10296 // T2 = (CRC_B * U2) << 1
10297 // C1 = T1 >> 32
10298 // C2 = T2 >> 32
10299 // T1 = T1 & 0xFFFFFFFF
10300 // T2 = T2 & 0xFFFFFFFF
10301 // T1 = CRC32(0, T1)
10302 // T2 = CRC32(0, T2)
10303 // C1 = C1 ^ T1
10304 // C2 = C2 ^ T2
10305 // CRC = C1 ^ C2 ^ CRC_C
10306 void MacroAssembler::crc32c_rec_alt2(uint32_t const_or_pre_comp_const_index_u1, uint32_t const_or_pre_comp_const_index_u2, bool is_pclmulqdq_supported, Register in_out, Register in1, Register in2,
10307                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10308                                      Register tmp1, Register tmp2,
10309                                      Register n_tmp3) {
10310   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10311   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10312   shlq(in_out, 1);
10313   movl(tmp1, in_out);
10314   shrq(in_out, 32);
10315   xorl(tmp2, tmp2);
10316   crc32(tmp2, tmp1, 4);
10317   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10318   shlq(in1, 1);
10319   movl(tmp1, in1);
10320   shrq(in1, 32);
10321   xorl(tmp2, tmp2);
10322   crc32(tmp2, tmp1, 4);
10323   xorl(in1, tmp2);
10324   xorl(in_out, in1);
10325   xorl(in_out, in2);
10326 }
10327 
10328 // Set N to predefined value
10329 // Subtract from a lenght of a buffer
10330 // execute in a loop:
10331 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10332 // for i = 1 to N do
10333 //  CRC_A = CRC32(CRC_A, A[i])
10334 //  CRC_B = CRC32(CRC_B, B[i])
10335 //  CRC_C = CRC32(CRC_C, C[i])
10336 // end for
10337 // Recombine
10338 void MacroAssembler::crc32c_proc_chunk(uint32_t size, uint32_t const_or_pre_comp_const_index_u1, uint32_t const_or_pre_comp_const_index_u2, bool is_pclmulqdq_supported,
10339                                        Register in_out1, Register in_out2, Register in_out3,
10340                                        Register tmp1, Register tmp2, Register tmp3,
10341                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10342                                        Register tmp4, Register tmp5,
10343                                        Register n_tmp6) {
10344   Label L_processPartitions;
10345   Label L_processPartition;
10346   Label L_exit;
10347 
10348   bind(L_processPartitions);
10349   cmpl(in_out1, 3 * size);
10350   jcc(Assembler::less, L_exit);
10351     xorl(tmp1, tmp1);
10352     xorl(tmp2, tmp2);
10353     movq(tmp3, in_out2);
10354     addq(tmp3, size);
10355 
10356     bind(L_processPartition);
10357       crc32(in_out3, Address(in_out2, 0), 8);
10358       crc32(tmp1, Address(in_out2, size), 8);
10359       crc32(tmp2, Address(in_out2, size * 2), 8);
10360       addq(in_out2, 8);
10361       cmpq(in_out2, tmp3);
10362       jcc(Assembler::less, L_processPartition);
10363     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10364             w_xtmp1, w_xtmp2, w_xtmp3,
10365             tmp4, tmp5,
10366             n_tmp6);
10367     addq(in_out2, 2 * size);
10368     subl(in_out1, 3 * size);
10369     jmp(L_processPartitions);
10370 
10371   bind(L_exit);
10372 }
10373 #else
10374 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10375                                      Register tmp1, Register tmp2, Register tmp3,
10376                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10377   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10378   if (n > 0) {
10379     addl(tmp3, n * 256 * 8);
10380   }
10381   //    Q1 = TABLEExt[n][B & 0xFF];
10382   movl(tmp1, in_out);
10383   andl(tmp1, 0x000000FF);
10384   shll(tmp1, 3);
10385   addl(tmp1, tmp3);
10386   movq(xtmp1, Address(tmp1, 0));
10387 
10388   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10389   movl(tmp2, in_out);
10390   shrl(tmp2, 8);
10391   andl(tmp2, 0x000000FF);
10392   shll(tmp2, 3);
10393   addl(tmp2, tmp3);
10394   movq(xtmp2, Address(tmp2, 0));
10395 
10396   psllq(xtmp2, 8);
10397   pxor(xtmp1, xtmp2);
10398 
10399   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10400   movl(tmp2, in_out);
10401   shrl(tmp2, 16);
10402   andl(tmp2, 0x000000FF);
10403   shll(tmp2, 3);
10404   addl(tmp2, tmp3);
10405   movq(xtmp2, Address(tmp2, 0));
10406 
10407   psllq(xtmp2, 16);
10408   pxor(xtmp1, xtmp2);
10409 
10410   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10411   shrl(in_out, 24);
10412   andl(in_out, 0x000000FF);
10413   shll(in_out, 3);
10414   addl(in_out, tmp3);
10415   movq(xtmp2, Address(in_out, 0));
10416 
10417   psllq(xtmp2, 24);
10418   pxor(xtmp1, xtmp2); // Result in CXMM
10419   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10420 }
10421 
10422 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10423                                       Register in_out,
10424                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10425                                       XMMRegister w_xtmp2,
10426                                       Register tmp1,
10427                                       Register n_tmp2, Register n_tmp3) {
10428   if (is_pclmulqdq_supported) {
10429     movdl(w_xtmp1, in_out);
10430 
10431     movl(tmp1, const_or_pre_comp_const_index);
10432     movdl(w_xtmp2, tmp1);
10433     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10434     // Keep result in XMM since GPR is 32 bit in length
10435   } else {
10436     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10437   }
10438 }
10439 
10440 void MacroAssembler::crc32c_rec_alt2(uint32_t const_or_pre_comp_const_index_u1, uint32_t const_or_pre_comp_const_index_u2, bool is_pclmulqdq_supported, Register in_out, Register in1, Register in2,
10441                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10442                                      Register tmp1, Register tmp2,
10443                                      Register n_tmp3) {
10444   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10445   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10446 
10447   psllq(w_xtmp1, 1);
10448   movdl(tmp1, w_xtmp1);
10449   psrlq(w_xtmp1, 32);
10450   movdl(in_out, w_xtmp1);
10451 
10452   xorl(tmp2, tmp2);
10453   crc32(tmp2, tmp1, 4);
10454   xorl(in_out, tmp2);
10455 
10456   psllq(w_xtmp2, 1);
10457   movdl(tmp1, w_xtmp2);
10458   psrlq(w_xtmp2, 32);
10459   movdl(in1, w_xtmp2);
10460 
10461   xorl(tmp2, tmp2);
10462   crc32(tmp2, tmp1, 4);
10463   xorl(in1, tmp2);
10464   xorl(in_out, in1);
10465   xorl(in_out, in2);
10466 }
10467 
10468 void MacroAssembler::crc32c_proc_chunk(uint32_t size, uint32_t const_or_pre_comp_const_index_u1, uint32_t const_or_pre_comp_const_index_u2, bool is_pclmulqdq_supported,
10469                                        Register in_out1, Register in_out2, Register in_out3,
10470                                        Register tmp1, Register tmp2, Register tmp3,
10471                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10472                                        Register tmp4, Register tmp5,
10473                                        Register n_tmp6) {
10474   Label L_processPartitions;
10475   Label L_processPartition;
10476   Label L_exit;
10477 
10478   bind(L_processPartitions);
10479   cmpl(in_out1, 3 * size);
10480   jcc(Assembler::less, L_exit);
10481     xorl(tmp1, tmp1);
10482     xorl(tmp2, tmp2);
10483     movl(tmp3, in_out2);
10484     addl(tmp3, size);
10485 
10486     bind(L_processPartition);
10487       crc32(in_out3, Address(in_out2, 0), 4);
10488       crc32(tmp1, Address(in_out2, size), 4);
10489       crc32(tmp2, Address(in_out2, size*2), 4);
10490       crc32(in_out3, Address(in_out2, 0+4), 4);
10491       crc32(tmp1, Address(in_out2, size+4), 4);
10492       crc32(tmp2, Address(in_out2, size*2+4), 4);
10493       addl(in_out2, 8);
10494       cmpl(in_out2, tmp3);
10495       jcc(Assembler::less, L_processPartition);
10496 
10497         push(tmp3);
10498         push(in_out1);
10499         push(in_out2);
10500         tmp4 = tmp3;
10501         tmp5 = in_out1;
10502         n_tmp6 = in_out2;
10503 
10504       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10505             w_xtmp1, w_xtmp2, w_xtmp3,
10506             tmp4, tmp5,
10507             n_tmp6);
10508 
10509         pop(in_out2);
10510         pop(in_out1);
10511         pop(tmp3);
10512 
10513     addl(in_out2, 2 * size);
10514     subl(in_out1, 3 * size);
10515     jmp(L_processPartitions);
10516 
10517   bind(L_exit);
10518 }
10519 #endif //LP64
10520 
10521 #ifdef _LP64
10522 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10523 // Input: A buffer I of L bytes.
10524 // Output: the CRC32C value of the buffer.
10525 // Notations:
10526 // Write L = 24N + r, with N = floor (L/24).
10527 // r = L mod 24 (0 <= r < 24).
10528 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10529 // N quadwords, and R consists of r bytes.
10530 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10531 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10532 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10533 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10534 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10535                                           Register tmp1, Register tmp2, Register tmp3,
10536                                           Register tmp4, Register tmp5, Register tmp6,
10537                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10538                                           bool is_pclmulqdq_supported) {
10539   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10540   Label L_wordByWord;
10541   Label L_byteByByteProlog;
10542   Label L_byteByByte;
10543   Label L_exit;
10544 
10545   if (is_pclmulqdq_supported ) {
10546     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10547     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10548 
10549     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10550     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10551 
10552     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10553     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10554     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10555   } else {
10556     const_or_pre_comp_const_index[0] = 1;
10557     const_or_pre_comp_const_index[1] = 0;
10558 
10559     const_or_pre_comp_const_index[2] = 3;
10560     const_or_pre_comp_const_index[3] = 2;
10561 
10562     const_or_pre_comp_const_index[4] = 5;
10563     const_or_pre_comp_const_index[5] = 4;
10564    }
10565   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10566                     in2, in1, in_out,
10567                     tmp1, tmp2, tmp3,
10568                     w_xtmp1, w_xtmp2, w_xtmp3,
10569                     tmp4, tmp5,
10570                     tmp6);
10571   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10572                     in2, in1, in_out,
10573                     tmp1, tmp2, tmp3,
10574                     w_xtmp1, w_xtmp2, w_xtmp3,
10575                     tmp4, tmp5,
10576                     tmp6);
10577   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10578                     in2, in1, in_out,
10579                     tmp1, tmp2, tmp3,
10580                     w_xtmp1, w_xtmp2, w_xtmp3,
10581                     tmp4, tmp5,
10582                     tmp6);
10583   movl(tmp1, in2);
10584   andl(tmp1, 0x00000007);
10585   negl(tmp1);
10586   addl(tmp1, in2);
10587   addq(tmp1, in1);
10588 
10589   BIND(L_wordByWord);
10590   cmpq(in1, tmp1);
10591   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10592     crc32(in_out, Address(in1, 0), 4);
10593     addq(in1, 4);
10594     jmp(L_wordByWord);
10595 
10596   BIND(L_byteByByteProlog);
10597   andl(in2, 0x00000007);
10598   movl(tmp2, 1);
10599 
10600   BIND(L_byteByByte);
10601   cmpl(tmp2, in2);
10602   jccb(Assembler::greater, L_exit);
10603     crc32(in_out, Address(in1, 0), 1);
10604     incq(in1);
10605     incl(tmp2);
10606     jmp(L_byteByByte);
10607 
10608   BIND(L_exit);
10609 }
10610 #else
10611 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10612                                           Register tmp1, Register  tmp2, Register tmp3,
10613                                           Register tmp4, Register  tmp5, Register tmp6,
10614                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10615                                           bool is_pclmulqdq_supported) {
10616   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10617   Label L_wordByWord;
10618   Label L_byteByByteProlog;
10619   Label L_byteByByte;
10620   Label L_exit;
10621 
10622   if (is_pclmulqdq_supported) {
10623     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10624     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10625 
10626     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10627     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10628 
10629     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10630     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10631   } else {
10632     const_or_pre_comp_const_index[0] = 1;
10633     const_or_pre_comp_const_index[1] = 0;
10634 
10635     const_or_pre_comp_const_index[2] = 3;
10636     const_or_pre_comp_const_index[3] = 2;
10637 
10638     const_or_pre_comp_const_index[4] = 5;
10639     const_or_pre_comp_const_index[5] = 4;
10640   }
10641   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10642                     in2, in1, in_out,
10643                     tmp1, tmp2, tmp3,
10644                     w_xtmp1, w_xtmp2, w_xtmp3,
10645                     tmp4, tmp5,
10646                     tmp6);
10647   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10648                     in2, in1, in_out,
10649                     tmp1, tmp2, tmp3,
10650                     w_xtmp1, w_xtmp2, w_xtmp3,
10651                     tmp4, tmp5,
10652                     tmp6);
10653   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10654                     in2, in1, in_out,
10655                     tmp1, tmp2, tmp3,
10656                     w_xtmp1, w_xtmp2, w_xtmp3,
10657                     tmp4, tmp5,
10658                     tmp6);
10659   movl(tmp1, in2);
10660   andl(tmp1, 0x00000007);
10661   negl(tmp1);
10662   addl(tmp1, in2);
10663   addl(tmp1, in1);
10664 
10665   BIND(L_wordByWord);
10666   cmpl(in1, tmp1);
10667   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10668     crc32(in_out, Address(in1,0), 4);
10669     addl(in1, 4);
10670     jmp(L_wordByWord);
10671 
10672   BIND(L_byteByByteProlog);
10673   andl(in2, 0x00000007);
10674   movl(tmp2, 1);
10675 
10676   BIND(L_byteByByte);
10677   cmpl(tmp2, in2);
10678   jccb(Assembler::greater, L_exit);
10679     movb(tmp1, Address(in1, 0));
10680     crc32(in_out, tmp1, 1);
10681     incl(in1);
10682     incl(tmp2);
10683     jmp(L_byteByByte);
10684 
10685   BIND(L_exit);
10686 }
10687 #endif // LP64
10688 #undef BIND
10689 #undef BLOCK_COMMENT
10690 
10691 
10692 // Compress char[] array to byte[].
10693 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10694                                          XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10695                                          XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10696                                          Register tmp5, Register result) {
10697   Label copy_chars_loop, return_length, return_zero, done;
10698 
10699   // rsi: src
10700   // rdi: dst
10701   // rdx: len
10702   // rcx: tmp5
10703   // rax: result
10704 
10705   // rsi holds start addr of source char[] to be compressed
10706   // rdi holds start addr of destination byte[]
10707   // rdx holds length
10708 
10709   assert(len != result, "");
10710 
10711   // save length for return
10712   push(len);
10713 
10714   if (UseSSE42Intrinsics) {
10715     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
10716     Label copy_32_loop, copy_16, copy_tail;
10717 
10718     movl(result, len);
10719     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
10720 
10721     // vectored compression
10722     andl(len, 0xfffffff0);    // vector count (in chars)
10723     andl(result, 0x0000000f);    // tail count (in chars)
10724     testl(len, len);
10725     jccb(Assembler::zero, copy_16);
10726 
10727     // compress 16 chars per iter
10728     movdl(tmp1Reg, tmp5);
10729     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10730     pxor(tmp4Reg, tmp4Reg);
10731 
10732     lea(src, Address(src, len, Address::times_2));
10733     lea(dst, Address(dst, len, Address::times_1));
10734     negptr(len);
10735 
10736     bind(copy_32_loop);
10737     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
10738     por(tmp4Reg, tmp2Reg);
10739     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
10740     por(tmp4Reg, tmp3Reg);
10741     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
10742     jcc(Assembler::notZero, return_zero);
10743     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
10744     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
10745     addptr(len, 16);
10746     jcc(Assembler::notZero, copy_32_loop);
10747 
10748     // compress next vector of 8 chars (if any)
10749     bind(copy_16);
10750     movl(len, result);
10751     andl(len, 0xfffffff8);    // vector count (in chars)
10752     andl(result, 0x00000007);    // tail count (in chars)
10753     testl(len, len);
10754     jccb(Assembler::zero, copy_tail);
10755 
10756     movdl(tmp1Reg, tmp5);
10757     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10758     pxor(tmp3Reg, tmp3Reg);
10759 
10760     movdqu(tmp2Reg, Address(src, 0));
10761     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
10762     jccb(Assembler::notZero, return_zero);
10763     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
10764     movq(Address(dst, 0), tmp2Reg);
10765     addptr(src, 16);
10766     addptr(dst, 8);
10767 
10768     bind(copy_tail);
10769     movl(len, result);
10770   }
10771   // compress 1 char per iter
10772   testl(len, len);
10773   jccb(Assembler::zero, return_length);
10774   lea(src, Address(src, len, Address::times_2));
10775   lea(dst, Address(dst, len, Address::times_1));
10776   negptr(len);
10777 
10778   bind(copy_chars_loop);
10779   load_unsigned_short(result, Address(src, len, Address::times_2));
10780   testl(result, 0xff00);      // check if Unicode char
10781   jccb(Assembler::notZero, return_zero);
10782   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
10783   increment(len);
10784   jcc(Assembler::notZero, copy_chars_loop);
10785 
10786   // if compression succeeded, return length
10787   bind(return_length);
10788   pop(result);
10789   jmpb(done);
10790 
10791   // if compression failed, return 0
10792   bind(return_zero);
10793   xorl(result, result);
10794   addptr(rsp, wordSize);
10795 
10796   bind(done);
10797 }
10798 
10799 // Inflate byte[] array to char[].
10800 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
10801                                         XMMRegister tmp1, Register tmp2) {
10802   Label copy_chars_loop, done;
10803 
10804   // rsi: src
10805   // rdi: dst
10806   // rdx: len
10807   // rcx: tmp2
10808 
10809   // rsi holds start addr of source byte[] to be inflated
10810   // rdi holds start addr of destination char[]
10811   // rdx holds length
10812   assert_different_registers(src, dst, len, tmp2);
10813 
10814   if (UseSSE42Intrinsics) {
10815     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
10816     Label copy_8_loop, copy_bytes, copy_tail;
10817 
10818     movl(tmp2, len);
10819     andl(tmp2, 0x00000007);   // tail count (in chars)
10820     andl(len, 0xfffffff8);    // vector count (in chars)
10821     jccb(Assembler::zero, copy_tail);
10822 
10823     // vectored inflation
10824     lea(src, Address(src, len, Address::times_1));
10825     lea(dst, Address(dst, len, Address::times_2));
10826     negptr(len);
10827 
10828     // inflate 8 chars per iter
10829     bind(copy_8_loop);
10830     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
10831     movdqu(Address(dst, len, Address::times_2), tmp1);
10832     addptr(len, 8);
10833     jcc(Assembler::notZero, copy_8_loop);
10834 
10835     bind(copy_tail);
10836     movl(len, tmp2);
10837 
10838     cmpl(len, 4);
10839     jccb(Assembler::less, copy_bytes);
10840 
10841     movdl(tmp1, Address(src, 0));  // load 4 byte chars
10842     pmovzxbw(tmp1, tmp1);
10843     movq(Address(dst, 0), tmp1);
10844     subptr(len, 4);
10845     addptr(src, 4);
10846     addptr(dst, 8);
10847 
10848     bind(copy_bytes);
10849   }
10850   testl(len, len);
10851   jccb(Assembler::zero, done);
10852   lea(src, Address(src, len, Address::times_1));
10853   lea(dst, Address(dst, len, Address::times_2));
10854   negptr(len);
10855 
10856   // inflate 1 char per iter
10857   bind(copy_chars_loop);
10858   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
10859   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
10860   increment(len);
10861   jcc(Assembler::notZero, copy_chars_loop);
10862 
10863   bind(done);
10864 }
10865 
10866 
10867 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
10868   switch (cond) {
10869     // Note some conditions are synonyms for others
10870     case Assembler::zero:         return Assembler::notZero;
10871     case Assembler::notZero:      return Assembler::zero;
10872     case Assembler::less:         return Assembler::greaterEqual;
10873     case Assembler::lessEqual:    return Assembler::greater;
10874     case Assembler::greater:      return Assembler::lessEqual;
10875     case Assembler::greaterEqual: return Assembler::less;
10876     case Assembler::below:        return Assembler::aboveEqual;
10877     case Assembler::belowEqual:   return Assembler::above;
10878     case Assembler::above:        return Assembler::belowEqual;
10879     case Assembler::aboveEqual:   return Assembler::below;
10880     case Assembler::overflow:     return Assembler::noOverflow;
10881     case Assembler::noOverflow:   return Assembler::overflow;
10882     case Assembler::negative:     return Assembler::positive;
10883     case Assembler::positive:     return Assembler::negative;
10884     case Assembler::parity:       return Assembler::noParity;
10885     case Assembler::noParity:     return Assembler::parity;
10886   }
10887   ShouldNotReachHere(); return Assembler::overflow;
10888 }
10889 
10890 SkipIfEqual::SkipIfEqual(
10891     MacroAssembler* masm, const bool* flag_addr, bool value) {
10892   _masm = masm;
10893   _masm->cmp8(ExternalAddress((address)flag_addr), value);
10894   _masm->jcc(Assembler::equal, _label);
10895 }
10896 
10897 SkipIfEqual::~SkipIfEqual() {
10898   _masm->bind(_label);
10899 }
10900 
10901 // 32-bit Windows has its own fast-path implementation
10902 // of get_thread
10903 #if !defined(WIN32) || defined(_LP64)
10904 
10905 // This is simply a call to Thread::current()
10906 void MacroAssembler::get_thread(Register thread) {
10907   if (thread != rax) {
10908     push(rax);
10909   }
10910   LP64_ONLY(push(rdi);)
10911   LP64_ONLY(push(rsi);)
10912   push(rdx);
10913   push(rcx);
10914 #ifdef _LP64
10915   push(r8);
10916   push(r9);
10917   push(r10);
10918   push(r11);
10919 #endif
10920 
10921   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
10922 
10923 #ifdef _LP64
10924   pop(r11);
10925   pop(r10);
10926   pop(r9);
10927   pop(r8);
10928 #endif
10929   pop(rcx);
10930   pop(rdx);
10931   LP64_ONLY(pop(rsi);)
10932   LP64_ONLY(pop(rdi);)
10933   if (thread != rax) {
10934     mov(thread, rax);
10935     pop(rax);
10936   }
10937 }
10938 
10939 #endif