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) {
2281   RelocationHolder rh = virtual_call_Relocation::spec(pc());
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    // C++ interp handles this in the interpreter
2529   check_and_handle_popframe(java_thread);
2530   check_and_handle_earlyret(java_thread);
2531 
2532   if (check_exceptions) {
2533     // check for pending exceptions (java_thread is set upon return)
2534     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2535 #ifndef _LP64
2536     jump_cc(Assembler::notEqual,
2537             RuntimeAddress(StubRoutines::forward_exception_entry()));
2538 #else
2539     // This used to conditionally jump to forward_exception however it is
2540     // possible if we relocate that the branch will not reach. So we must jump
2541     // around so we can always reach
2542 
2543     Label ok;
2544     jcc(Assembler::equal, ok);
2545     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2546     bind(ok);
2547 #endif // LP64
2548   }
2549 
2550   // get oop result if there is one and reset the value in the thread
2551   if (oop_result->is_valid()) {
2552     get_vm_result(oop_result, java_thread);
2553   }
2554 }
2555 
2556 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2557 
2558   // Calculate the value for last_Java_sp
2559   // somewhat subtle. call_VM does an intermediate call
2560   // which places a return address on the stack just under the
2561   // stack pointer as the user finsihed with it. This allows
2562   // use to retrieve last_Java_pc from last_Java_sp[-1].
2563   // On 32bit we then have to push additional args on the stack to accomplish
2564   // the actual requested call. On 64bit call_VM only can use register args
2565   // so the only extra space is the return address that call_VM created.
2566   // This hopefully explains the calculations here.
2567 
2568 #ifdef _LP64
2569   // We've pushed one address, correct last_Java_sp
2570   lea(rax, Address(rsp, wordSize));
2571 #else
2572   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2573 #endif // LP64
2574 
2575   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2576 
2577 }
2578 
2579 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2580   call_VM_leaf_base(entry_point, number_of_arguments);
2581 }
2582 
2583 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2584   pass_arg0(this, arg_0);
2585   call_VM_leaf(entry_point, 1);
2586 }
2587 
2588 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2589 
2590   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2591   pass_arg1(this, arg_1);
2592   pass_arg0(this, arg_0);
2593   call_VM_leaf(entry_point, 2);
2594 }
2595 
2596 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2597   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2598   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2599   pass_arg2(this, arg_2);
2600   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2601   pass_arg1(this, arg_1);
2602   pass_arg0(this, arg_0);
2603   call_VM_leaf(entry_point, 3);
2604 }
2605 
2606 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2607   pass_arg0(this, arg_0);
2608   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2609 }
2610 
2611 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2612 
2613   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2614   pass_arg1(this, arg_1);
2615   pass_arg0(this, arg_0);
2616   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2617 }
2618 
2619 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2620   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2621   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2622   pass_arg2(this, arg_2);
2623   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2624   pass_arg1(this, arg_1);
2625   pass_arg0(this, arg_0);
2626   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2627 }
2628 
2629 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2630   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2631   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2632   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2633   pass_arg3(this, arg_3);
2634   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2635   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2636   pass_arg2(this, arg_2);
2637   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2638   pass_arg1(this, arg_1);
2639   pass_arg0(this, arg_0);
2640   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2641 }
2642 
2643 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2644   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2645   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2646   verify_oop(oop_result, "broken oop in call_VM_base");
2647 }
2648 
2649 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2650   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2651   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2652 }
2653 
2654 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2655 }
2656 
2657 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2658 }
2659 
2660 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2661   if (reachable(src1)) {
2662     cmpl(as_Address(src1), imm);
2663   } else {
2664     lea(rscratch1, src1);
2665     cmpl(Address(rscratch1, 0), imm);
2666   }
2667 }
2668 
2669 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2670   assert(!src2.is_lval(), "use cmpptr");
2671   if (reachable(src2)) {
2672     cmpl(src1, as_Address(src2));
2673   } else {
2674     lea(rscratch1, src2);
2675     cmpl(src1, Address(rscratch1, 0));
2676   }
2677 }
2678 
2679 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2680   Assembler::cmpl(src1, imm);
2681 }
2682 
2683 void MacroAssembler::cmp32(Register src1, Address src2) {
2684   Assembler::cmpl(src1, src2);
2685 }
2686 
2687 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2688   ucomisd(opr1, opr2);
2689 
2690   Label L;
2691   if (unordered_is_less) {
2692     movl(dst, -1);
2693     jcc(Assembler::parity, L);
2694     jcc(Assembler::below , L);
2695     movl(dst, 0);
2696     jcc(Assembler::equal , L);
2697     increment(dst);
2698   } else { // unordered is greater
2699     movl(dst, 1);
2700     jcc(Assembler::parity, L);
2701     jcc(Assembler::above , L);
2702     movl(dst, 0);
2703     jcc(Assembler::equal , L);
2704     decrementl(dst);
2705   }
2706   bind(L);
2707 }
2708 
2709 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2710   ucomiss(opr1, opr2);
2711 
2712   Label L;
2713   if (unordered_is_less) {
2714     movl(dst, -1);
2715     jcc(Assembler::parity, L);
2716     jcc(Assembler::below , L);
2717     movl(dst, 0);
2718     jcc(Assembler::equal , L);
2719     increment(dst);
2720   } else { // unordered is greater
2721     movl(dst, 1);
2722     jcc(Assembler::parity, L);
2723     jcc(Assembler::above , L);
2724     movl(dst, 0);
2725     jcc(Assembler::equal , L);
2726     decrementl(dst);
2727   }
2728   bind(L);
2729 }
2730 
2731 
2732 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2733   if (reachable(src1)) {
2734     cmpb(as_Address(src1), imm);
2735   } else {
2736     lea(rscratch1, src1);
2737     cmpb(Address(rscratch1, 0), imm);
2738   }
2739 }
2740 
2741 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2742 #ifdef _LP64
2743   if (src2.is_lval()) {
2744     movptr(rscratch1, src2);
2745     Assembler::cmpq(src1, rscratch1);
2746   } else if (reachable(src2)) {
2747     cmpq(src1, as_Address(src2));
2748   } else {
2749     lea(rscratch1, src2);
2750     Assembler::cmpq(src1, Address(rscratch1, 0));
2751   }
2752 #else
2753   if (src2.is_lval()) {
2754     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2755   } else {
2756     cmpl(src1, as_Address(src2));
2757   }
2758 #endif // _LP64
2759 }
2760 
2761 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2762   assert(src2.is_lval(), "not a mem-mem compare");
2763 #ifdef _LP64
2764   // moves src2's literal address
2765   movptr(rscratch1, src2);
2766   Assembler::cmpq(src1, rscratch1);
2767 #else
2768   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2769 #endif // _LP64
2770 }
2771 
2772 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2773   if (reachable(adr)) {
2774     if (os::is_MP())
2775       lock();
2776     cmpxchgptr(reg, as_Address(adr));
2777   } else {
2778     lea(rscratch1, adr);
2779     if (os::is_MP())
2780       lock();
2781     cmpxchgptr(reg, Address(rscratch1, 0));
2782   }
2783 }
2784 
2785 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2786   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2787 }
2788 
2789 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2790   if (reachable(src)) {
2791     Assembler::comisd(dst, as_Address(src));
2792   } else {
2793     lea(rscratch1, src);
2794     Assembler::comisd(dst, Address(rscratch1, 0));
2795   }
2796 }
2797 
2798 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2799   if (reachable(src)) {
2800     Assembler::comiss(dst, as_Address(src));
2801   } else {
2802     lea(rscratch1, src);
2803     Assembler::comiss(dst, Address(rscratch1, 0));
2804   }
2805 }
2806 
2807 
2808 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2809   Condition negated_cond = negate_condition(cond);
2810   Label L;
2811   jcc(negated_cond, L);
2812   pushf(); // Preserve flags
2813   atomic_incl(counter_addr);
2814   popf();
2815   bind(L);
2816 }
2817 
2818 int MacroAssembler::corrected_idivl(Register reg) {
2819   // Full implementation of Java idiv and irem; checks for
2820   // special case as described in JVM spec., p.243 & p.271.
2821   // The function returns the (pc) offset of the idivl
2822   // instruction - may be needed for implicit exceptions.
2823   //
2824   //         normal case                           special case
2825   //
2826   // input : rax,: dividend                         min_int
2827   //         reg: divisor   (may not be rax,/rdx)   -1
2828   //
2829   // output: rax,: quotient  (= rax, idiv reg)       min_int
2830   //         rdx: remainder (= rax, irem reg)       0
2831   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2832   const int min_int = 0x80000000;
2833   Label normal_case, special_case;
2834 
2835   // check for special case
2836   cmpl(rax, min_int);
2837   jcc(Assembler::notEqual, normal_case);
2838   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2839   cmpl(reg, -1);
2840   jcc(Assembler::equal, special_case);
2841 
2842   // handle normal case
2843   bind(normal_case);
2844   cdql();
2845   int idivl_offset = offset();
2846   idivl(reg);
2847 
2848   // normal and special case exit
2849   bind(special_case);
2850 
2851   return idivl_offset;
2852 }
2853 
2854 
2855 
2856 void MacroAssembler::decrementl(Register reg, int value) {
2857   if (value == min_jint) {subl(reg, value) ; return; }
2858   if (value <  0) { incrementl(reg, -value); return; }
2859   if (value == 0) {                        ; return; }
2860   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2861   /* else */      { subl(reg, value)       ; return; }
2862 }
2863 
2864 void MacroAssembler::decrementl(Address dst, int value) {
2865   if (value == min_jint) {subl(dst, value) ; return; }
2866   if (value <  0) { incrementl(dst, -value); return; }
2867   if (value == 0) {                        ; return; }
2868   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2869   /* else */      { subl(dst, value)       ; return; }
2870 }
2871 
2872 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2873   assert (shift_value > 0, "illegal shift value");
2874   Label _is_positive;
2875   testl (reg, reg);
2876   jcc (Assembler::positive, _is_positive);
2877   int offset = (1 << shift_value) - 1 ;
2878 
2879   if (offset == 1) {
2880     incrementl(reg);
2881   } else {
2882     addl(reg, offset);
2883   }
2884 
2885   bind (_is_positive);
2886   sarl(reg, shift_value);
2887 }
2888 
2889 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2890   if (reachable(src)) {
2891     Assembler::divsd(dst, as_Address(src));
2892   } else {
2893     lea(rscratch1, src);
2894     Assembler::divsd(dst, Address(rscratch1, 0));
2895   }
2896 }
2897 
2898 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2899   if (reachable(src)) {
2900     Assembler::divss(dst, as_Address(src));
2901   } else {
2902     lea(rscratch1, src);
2903     Assembler::divss(dst, Address(rscratch1, 0));
2904   }
2905 }
2906 
2907 // !defined(COMPILER2) is because of stupid core builds
2908 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2909 void MacroAssembler::empty_FPU_stack() {
2910   if (VM_Version::supports_mmx()) {
2911     emms();
2912   } else {
2913     for (int i = 8; i-- > 0; ) ffree(i);
2914   }
2915 }
2916 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2917 
2918 
2919 // Defines obj, preserves var_size_in_bytes
2920 void MacroAssembler::eden_allocate(Register obj,
2921                                    Register var_size_in_bytes,
2922                                    int con_size_in_bytes,
2923                                    Register t1,
2924                                    Label& slow_case) {
2925   assert(obj == rax, "obj must be in rax, for cmpxchg");
2926   assert_different_registers(obj, var_size_in_bytes, t1);
2927   if (!Universe::heap()->supports_inline_contig_alloc()) {
2928     jmp(slow_case);
2929   } else {
2930     Register end = t1;
2931     Label retry;
2932     bind(retry);
2933     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2934     movptr(obj, heap_top);
2935     if (var_size_in_bytes == noreg) {
2936       lea(end, Address(obj, con_size_in_bytes));
2937     } else {
2938       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2939     }
2940     // if end < obj then we wrapped around => object too long => slow case
2941     cmpptr(end, obj);
2942     jcc(Assembler::below, slow_case);
2943     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2944     jcc(Assembler::above, slow_case);
2945     // Compare obj with the top addr, and if still equal, store the new top addr in
2946     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2947     // it otherwise. Use lock prefix for atomicity on MPs.
2948     locked_cmpxchgptr(end, heap_top);
2949     jcc(Assembler::notEqual, retry);
2950   }
2951 }
2952 
2953 void MacroAssembler::enter() {
2954   push(rbp);
2955   mov(rbp, rsp);
2956 }
2957 
2958 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2959 void MacroAssembler::fat_nop() {
2960   if (UseAddressNop) {
2961     addr_nop_5();
2962   } else {
2963     emit_int8(0x26); // es:
2964     emit_int8(0x2e); // cs:
2965     emit_int8(0x64); // fs:
2966     emit_int8(0x65); // gs:
2967     emit_int8((unsigned char)0x90);
2968   }
2969 }
2970 
2971 void MacroAssembler::fcmp(Register tmp) {
2972   fcmp(tmp, 1, true, true);
2973 }
2974 
2975 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
2976   assert(!pop_right || pop_left, "usage error");
2977   if (VM_Version::supports_cmov()) {
2978     assert(tmp == noreg, "unneeded temp");
2979     if (pop_left) {
2980       fucomip(index);
2981     } else {
2982       fucomi(index);
2983     }
2984     if (pop_right) {
2985       fpop();
2986     }
2987   } else {
2988     assert(tmp != noreg, "need temp");
2989     if (pop_left) {
2990       if (pop_right) {
2991         fcompp();
2992       } else {
2993         fcomp(index);
2994       }
2995     } else {
2996       fcom(index);
2997     }
2998     // convert FPU condition into eflags condition via rax,
2999     save_rax(tmp);
3000     fwait(); fnstsw_ax();
3001     sahf();
3002     restore_rax(tmp);
3003   }
3004   // condition codes set as follows:
3005   //
3006   // CF (corresponds to C0) if x < y
3007   // PF (corresponds to C2) if unordered
3008   // ZF (corresponds to C3) if x = y
3009 }
3010 
3011 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3012   fcmp2int(dst, unordered_is_less, 1, true, true);
3013 }
3014 
3015 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3016   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3017   Label L;
3018   if (unordered_is_less) {
3019     movl(dst, -1);
3020     jcc(Assembler::parity, L);
3021     jcc(Assembler::below , L);
3022     movl(dst, 0);
3023     jcc(Assembler::equal , L);
3024     increment(dst);
3025   } else { // unordered is greater
3026     movl(dst, 1);
3027     jcc(Assembler::parity, L);
3028     jcc(Assembler::above , L);
3029     movl(dst, 0);
3030     jcc(Assembler::equal , L);
3031     decrementl(dst);
3032   }
3033   bind(L);
3034 }
3035 
3036 void MacroAssembler::fld_d(AddressLiteral src) {
3037   fld_d(as_Address(src));
3038 }
3039 
3040 void MacroAssembler::fld_s(AddressLiteral src) {
3041   fld_s(as_Address(src));
3042 }
3043 
3044 void MacroAssembler::fld_x(AddressLiteral src) {
3045   Assembler::fld_x(as_Address(src));
3046 }
3047 
3048 void MacroAssembler::fldcw(AddressLiteral src) {
3049   Assembler::fldcw(as_Address(src));
3050 }
3051 
3052 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3053   if (reachable(src)) {
3054     Assembler::mulpd(dst, as_Address(src));
3055   } else {
3056     lea(rscratch1, src);
3057     Assembler::mulpd(dst, Address(rscratch1, 0));
3058   }
3059 }
3060 
3061 void MacroAssembler::pow_exp_core_encoding() {
3062   // kills rax, rcx, rdx
3063   subptr(rsp,sizeof(jdouble));
3064   // computes 2^X. Stack: X ...
3065   // f2xm1 computes 2^X-1 but only operates on -1<=X<=1. Get int(X) and
3066   // keep it on the thread's stack to compute 2^int(X) later
3067   // then compute 2^(X-int(X)) as (2^(X-int(X)-1+1)
3068   // final result is obtained with: 2^X = 2^int(X) * 2^(X-int(X))
3069   fld_s(0);                 // Stack: X X ...
3070   frndint();                // Stack: int(X) X ...
3071   fsuba(1);                 // Stack: int(X) X-int(X) ...
3072   fistp_s(Address(rsp,0));  // move int(X) as integer to thread's stack. Stack: X-int(X) ...
3073   f2xm1();                  // Stack: 2^(X-int(X))-1 ...
3074   fld1();                   // Stack: 1 2^(X-int(X))-1 ...
3075   faddp(1);                 // Stack: 2^(X-int(X))
3076   // computes 2^(int(X)): add exponent bias (1023) to int(X), then
3077   // shift int(X)+1023 to exponent position.
3078   // Exponent is limited to 11 bits if int(X)+1023 does not fit in 11
3079   // bits, set result to NaN. 0x000 and 0x7FF are reserved exponent
3080   // values so detect them and set result to NaN.
3081   movl(rax,Address(rsp,0));
3082   movl(rcx, -2048); // 11 bit mask and valid NaN binary encoding
3083   addl(rax, 1023);
3084   movl(rdx,rax);
3085   shll(rax,20);
3086   // Check that 0 < int(X)+1023 < 2047. Otherwise set rax to NaN.
3087   addl(rdx,1);
3088   // Check that 1 < int(X)+1023+1 < 2048
3089   // in 3 steps:
3090   // 1- (int(X)+1023+1)&-2048 == 0 => 0 <= int(X)+1023+1 < 2048
3091   // 2- (int(X)+1023+1)&-2048 != 0
3092   // 3- (int(X)+1023+1)&-2048 != 1
3093   // Do 2- first because addl just updated the flags.
3094   cmov32(Assembler::equal,rax,rcx);
3095   cmpl(rdx,1);
3096   cmov32(Assembler::equal,rax,rcx);
3097   testl(rdx,rcx);
3098   cmov32(Assembler::notEqual,rax,rcx);
3099   movl(Address(rsp,4),rax);
3100   movl(Address(rsp,0),0);
3101   fmul_d(Address(rsp,0));   // Stack: 2^X ...
3102   addptr(rsp,sizeof(jdouble));
3103 }
3104 
3105 void MacroAssembler::increase_precision() {
3106   subptr(rsp, BytesPerWord);
3107   fnstcw(Address(rsp, 0));
3108   movl(rax, Address(rsp, 0));
3109   orl(rax, 0x300);
3110   push(rax);
3111   fldcw(Address(rsp, 0));
3112   pop(rax);
3113 }
3114 
3115 void MacroAssembler::restore_precision() {
3116   fldcw(Address(rsp, 0));
3117   addptr(rsp, BytesPerWord);
3118 }
3119 
3120 void MacroAssembler::fast_pow() {
3121   // computes X^Y = 2^(Y * log2(X))
3122   // if fast computation is not possible, result is NaN. Requires
3123   // fallback from user of this macro.
3124   // increase precision for intermediate steps of the computation
3125   BLOCK_COMMENT("fast_pow {");
3126   increase_precision();
3127   fyl2x();                 // Stack: (Y*log2(X)) ...
3128   pow_exp_core_encoding(); // Stack: exp(X) ...
3129   restore_precision();
3130   BLOCK_COMMENT("} fast_pow");
3131 }
3132 
3133 void MacroAssembler::pow_or_exp(int num_fpu_regs_in_use) {
3134   // kills rax, rcx, rdx
3135   // pow and exp needs 2 extra registers on the fpu stack.
3136   Label slow_case, done;
3137   Register tmp = noreg;
3138   if (!VM_Version::supports_cmov()) {
3139     // fcmp needs a temporary so preserve rdx,
3140     tmp = rdx;
3141   }
3142   Register tmp2 = rax;
3143   Register tmp3 = rcx;
3144 
3145   // Stack: X Y
3146   Label x_negative, y_not_2;
3147 
3148   static double two = 2.0;
3149   ExternalAddress two_addr((address)&two);
3150 
3151   // constant maybe too far on 64 bit
3152   lea(tmp2, two_addr);
3153   fld_d(Address(tmp2, 0));    // Stack: 2 X Y
3154   fcmp(tmp, 2, true, false);  // Stack: X Y
3155   jcc(Assembler::parity, y_not_2);
3156   jcc(Assembler::notEqual, y_not_2);
3157 
3158   fxch(); fpop();             // Stack: X
3159   fmul(0);                    // Stack: X*X
3160 
3161   jmp(done);
3162 
3163   bind(y_not_2);
3164 
3165   fldz();                     // Stack: 0 X Y
3166   fcmp(tmp, 1, true, false);  // Stack: X Y
3167   jcc(Assembler::above, x_negative);
3168 
3169   // X >= 0
3170 
3171   fld_s(1);                   // duplicate arguments for runtime call. Stack: Y X Y
3172   fld_s(1);                   // Stack: X Y X Y
3173   fast_pow();                 // Stack: X^Y X Y
3174   fcmp(tmp, 0, false, false); // Stack: X^Y X Y
3175   // X^Y not equal to itself: X^Y is NaN go to slow case.
3176   jcc(Assembler::parity, slow_case);
3177   // get rid of duplicate arguments. Stack: X^Y
3178   if (num_fpu_regs_in_use > 0) {
3179     fxch(); fpop();
3180     fxch(); fpop();
3181   } else {
3182     ffree(2);
3183     ffree(1);
3184   }
3185   jmp(done);
3186 
3187   // X <= 0
3188   bind(x_negative);
3189 
3190   fld_s(1);                   // Stack: Y X Y
3191   frndint();                  // Stack: int(Y) X Y
3192   fcmp(tmp, 2, false, false); // Stack: int(Y) X Y
3193   jcc(Assembler::notEqual, slow_case);
3194 
3195   subptr(rsp, 8);
3196 
3197   // For X^Y, when X < 0, Y has to be an integer and the final
3198   // result depends on whether it's odd or even. We just checked
3199   // that int(Y) == Y.  We move int(Y) to gp registers as a 64 bit
3200   // integer to test its parity. If int(Y) is huge and doesn't fit
3201   // in the 64 bit integer range, the integer indefinite value will
3202   // end up in the gp registers. Huge numbers are all even, the
3203   // integer indefinite number is even so it's fine.
3204 
3205 #ifdef ASSERT
3206   // Let's check we don't end up with an integer indefinite number
3207   // when not expected. First test for huge numbers: check whether
3208   // int(Y)+1 == int(Y) which is true for very large numbers and
3209   // those are all even. A 64 bit integer is guaranteed to not
3210   // overflow for numbers where y+1 != y (when precision is set to
3211   // double precision).
3212   Label y_not_huge;
3213 
3214   fld1();                     // Stack: 1 int(Y) X Y
3215   fadd(1);                    // Stack: 1+int(Y) int(Y) X Y
3216 
3217 #ifdef _LP64
3218   // trip to memory to force the precision down from double extended
3219   // precision
3220   fstp_d(Address(rsp, 0));
3221   fld_d(Address(rsp, 0));
3222 #endif
3223 
3224   fcmp(tmp, 1, true, false);  // Stack: int(Y) X Y
3225 #endif
3226 
3227   // move int(Y) as 64 bit integer to thread's stack
3228   fistp_d(Address(rsp,0));    // Stack: X Y
3229 
3230 #ifdef ASSERT
3231   jcc(Assembler::notEqual, y_not_huge);
3232 
3233   // Y is huge so we know it's even. It may not fit in a 64 bit
3234   // integer and we don't want the debug code below to see the
3235   // integer indefinite value so overwrite int(Y) on the thread's
3236   // stack with 0.
3237   movl(Address(rsp, 0), 0);
3238   movl(Address(rsp, 4), 0);
3239 
3240   bind(y_not_huge);
3241 #endif
3242 
3243   fld_s(1);                   // duplicate arguments for runtime call. Stack: Y X Y
3244   fld_s(1);                   // Stack: X Y X Y
3245   fabs();                     // Stack: abs(X) Y X Y
3246   fast_pow();                 // Stack: abs(X)^Y X Y
3247   fcmp(tmp, 0, false, false); // Stack: abs(X)^Y X Y
3248   // abs(X)^Y not equal to itself: abs(X)^Y is NaN go to slow case.
3249 
3250   pop(tmp2);
3251   NOT_LP64(pop(tmp3));
3252   jcc(Assembler::parity, slow_case);
3253 
3254 #ifdef ASSERT
3255   // Check that int(Y) is not integer indefinite value (int
3256   // overflow). Shouldn't happen because for values that would
3257   // overflow, 1+int(Y)==Y which was tested earlier.
3258 #ifndef _LP64
3259   {
3260     Label integer;
3261     testl(tmp2, tmp2);
3262     jcc(Assembler::notZero, integer);
3263     cmpl(tmp3, 0x80000000);
3264     jcc(Assembler::notZero, integer);
3265     STOP("integer indefinite value shouldn't be seen here");
3266     bind(integer);
3267   }
3268 #else
3269   {
3270     Label integer;
3271     mov(tmp3, tmp2); // preserve tmp2 for parity check below
3272     shlq(tmp3, 1);
3273     jcc(Assembler::carryClear, integer);
3274     jcc(Assembler::notZero, integer);
3275     STOP("integer indefinite value shouldn't be seen here");
3276     bind(integer);
3277   }
3278 #endif
3279 #endif
3280 
3281   // get rid of duplicate arguments. Stack: X^Y
3282   if (num_fpu_regs_in_use > 0) {
3283     fxch(); fpop();
3284     fxch(); fpop();
3285   } else {
3286     ffree(2);
3287     ffree(1);
3288   }
3289 
3290   testl(tmp2, 1);
3291   jcc(Assembler::zero, done); // X <= 0, Y even: X^Y = abs(X)^Y
3292   // X <= 0, Y even: X^Y = -abs(X)^Y
3293 
3294   fchs();                     // Stack: -abs(X)^Y Y
3295   jmp(done);
3296 
3297   // slow case: runtime call
3298   bind(slow_case);
3299 
3300   fpop();                       // pop incorrect result or int(Y)
3301 
3302   fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dpow), 2, num_fpu_regs_in_use);
3303 
3304   // Come here with result in F-TOS
3305   bind(done);
3306 }
3307 
3308 void MacroAssembler::fpop() {
3309   ffree();
3310   fincstp();
3311 }
3312 
3313 void MacroAssembler::load_float(Address src) {
3314   if (UseSSE >= 1) {
3315     movflt(xmm0, src);
3316   } else {
3317     LP64_ONLY(ShouldNotReachHere());
3318     NOT_LP64(fld_s(src));
3319   }
3320 }
3321 
3322 void MacroAssembler::store_float(Address dst) {
3323   if (UseSSE >= 1) {
3324     movflt(dst, xmm0);
3325   } else {
3326     LP64_ONLY(ShouldNotReachHere());
3327     NOT_LP64(fstp_s(dst));
3328   }
3329 }
3330 
3331 void MacroAssembler::load_double(Address src) {
3332   if (UseSSE >= 2) {
3333     movdbl(xmm0, src);
3334   } else {
3335     LP64_ONLY(ShouldNotReachHere());
3336     NOT_LP64(fld_d(src));
3337   }
3338 }
3339 
3340 void MacroAssembler::store_double(Address dst) {
3341   if (UseSSE >= 2) {
3342     movdbl(dst, xmm0);
3343   } else {
3344     LP64_ONLY(ShouldNotReachHere());
3345     NOT_LP64(fstp_d(dst));
3346   }
3347 }
3348 
3349 void MacroAssembler::fremr(Register tmp) {
3350   save_rax(tmp);
3351   { Label L;
3352     bind(L);
3353     fprem();
3354     fwait(); fnstsw_ax();
3355 #ifdef _LP64
3356     testl(rax, 0x400);
3357     jcc(Assembler::notEqual, L);
3358 #else
3359     sahf();
3360     jcc(Assembler::parity, L);
3361 #endif // _LP64
3362   }
3363   restore_rax(tmp);
3364   // Result is in ST0.
3365   // Note: fxch & fpop to get rid of ST1
3366   // (otherwise FPU stack could overflow eventually)
3367   fxch(1);
3368   fpop();
3369 }
3370 
3371 
3372 void MacroAssembler::incrementl(AddressLiteral dst) {
3373   if (reachable(dst)) {
3374     incrementl(as_Address(dst));
3375   } else {
3376     lea(rscratch1, dst);
3377     incrementl(Address(rscratch1, 0));
3378   }
3379 }
3380 
3381 void MacroAssembler::incrementl(ArrayAddress dst) {
3382   incrementl(as_Address(dst));
3383 }
3384 
3385 void MacroAssembler::incrementl(Register reg, int value) {
3386   if (value == min_jint) {addl(reg, value) ; return; }
3387   if (value <  0) { decrementl(reg, -value); return; }
3388   if (value == 0) {                        ; return; }
3389   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3390   /* else */      { addl(reg, value)       ; return; }
3391 }
3392 
3393 void MacroAssembler::incrementl(Address dst, int value) {
3394   if (value == min_jint) {addl(dst, value) ; return; }
3395   if (value <  0) { decrementl(dst, -value); return; }
3396   if (value == 0) {                        ; return; }
3397   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3398   /* else */      { addl(dst, value)       ; return; }
3399 }
3400 
3401 void MacroAssembler::jump(AddressLiteral dst) {
3402   if (reachable(dst)) {
3403     jmp_literal(dst.target(), dst.rspec());
3404   } else {
3405     lea(rscratch1, dst);
3406     jmp(rscratch1);
3407   }
3408 }
3409 
3410 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3411   if (reachable(dst)) {
3412     InstructionMark im(this);
3413     relocate(dst.reloc());
3414     const int short_size = 2;
3415     const int long_size = 6;
3416     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3417     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3418       // 0111 tttn #8-bit disp
3419       emit_int8(0x70 | cc);
3420       emit_int8((offs - short_size) & 0xFF);
3421     } else {
3422       // 0000 1111 1000 tttn #32-bit disp
3423       emit_int8(0x0F);
3424       emit_int8((unsigned char)(0x80 | cc));
3425       emit_int32(offs - long_size);
3426     }
3427   } else {
3428 #ifdef ASSERT
3429     warning("reversing conditional branch");
3430 #endif /* ASSERT */
3431     Label skip;
3432     jccb(reverse[cc], skip);
3433     lea(rscratch1, dst);
3434     Assembler::jmp(rscratch1);
3435     bind(skip);
3436   }
3437 }
3438 
3439 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3440   if (reachable(src)) {
3441     Assembler::ldmxcsr(as_Address(src));
3442   } else {
3443     lea(rscratch1, src);
3444     Assembler::ldmxcsr(Address(rscratch1, 0));
3445   }
3446 }
3447 
3448 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3449   int off;
3450   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3451     off = offset();
3452     movsbl(dst, src); // movsxb
3453   } else {
3454     off = load_unsigned_byte(dst, src);
3455     shll(dst, 24);
3456     sarl(dst, 24);
3457   }
3458   return off;
3459 }
3460 
3461 // Note: load_signed_short used to be called load_signed_word.
3462 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3463 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3464 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3465 int MacroAssembler::load_signed_short(Register dst, Address src) {
3466   int off;
3467   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3468     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3469     // version but this is what 64bit has always done. This seems to imply
3470     // that users are only using 32bits worth.
3471     off = offset();
3472     movswl(dst, src); // movsxw
3473   } else {
3474     off = load_unsigned_short(dst, src);
3475     shll(dst, 16);
3476     sarl(dst, 16);
3477   }
3478   return off;
3479 }
3480 
3481 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3482   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3483   // and "3.9 Partial Register Penalties", p. 22).
3484   int off;
3485   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3486     off = offset();
3487     movzbl(dst, src); // movzxb
3488   } else {
3489     xorl(dst, dst);
3490     off = offset();
3491     movb(dst, src);
3492   }
3493   return off;
3494 }
3495 
3496 // Note: load_unsigned_short used to be called load_unsigned_word.
3497 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3498   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3499   // and "3.9 Partial Register Penalties", p. 22).
3500   int off;
3501   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3502     off = offset();
3503     movzwl(dst, src); // movzxw
3504   } else {
3505     xorl(dst, dst);
3506     off = offset();
3507     movw(dst, src);
3508   }
3509   return off;
3510 }
3511 
3512 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3513   switch (size_in_bytes) {
3514 #ifndef _LP64
3515   case  8:
3516     assert(dst2 != noreg, "second dest register required");
3517     movl(dst,  src);
3518     movl(dst2, src.plus_disp(BytesPerInt));
3519     break;
3520 #else
3521   case  8:  movq(dst, src); break;
3522 #endif
3523   case  4:  movl(dst, src); break;
3524   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3525   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3526   default:  ShouldNotReachHere();
3527   }
3528 }
3529 
3530 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3531   switch (size_in_bytes) {
3532 #ifndef _LP64
3533   case  8:
3534     assert(src2 != noreg, "second source register required");
3535     movl(dst,                        src);
3536     movl(dst.plus_disp(BytesPerInt), src2);
3537     break;
3538 #else
3539   case  8:  movq(dst, src); break;
3540 #endif
3541   case  4:  movl(dst, src); break;
3542   case  2:  movw(dst, src); break;
3543   case  1:  movb(dst, src); break;
3544   default:  ShouldNotReachHere();
3545   }
3546 }
3547 
3548 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3549   if (reachable(dst)) {
3550     movl(as_Address(dst), src);
3551   } else {
3552     lea(rscratch1, dst);
3553     movl(Address(rscratch1, 0), src);
3554   }
3555 }
3556 
3557 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3558   if (reachable(src)) {
3559     movl(dst, as_Address(src));
3560   } else {
3561     lea(rscratch1, src);
3562     movl(dst, Address(rscratch1, 0));
3563   }
3564 }
3565 
3566 // C++ bool manipulation
3567 
3568 void MacroAssembler::movbool(Register dst, Address src) {
3569   if(sizeof(bool) == 1)
3570     movb(dst, src);
3571   else if(sizeof(bool) == 2)
3572     movw(dst, src);
3573   else if(sizeof(bool) == 4)
3574     movl(dst, src);
3575   else
3576     // unsupported
3577     ShouldNotReachHere();
3578 }
3579 
3580 void MacroAssembler::movbool(Address dst, bool boolconst) {
3581   if(sizeof(bool) == 1)
3582     movb(dst, (int) boolconst);
3583   else if(sizeof(bool) == 2)
3584     movw(dst, (int) boolconst);
3585   else if(sizeof(bool) == 4)
3586     movl(dst, (int) boolconst);
3587   else
3588     // unsupported
3589     ShouldNotReachHere();
3590 }
3591 
3592 void MacroAssembler::movbool(Address dst, Register src) {
3593   if(sizeof(bool) == 1)
3594     movb(dst, src);
3595   else if(sizeof(bool) == 2)
3596     movw(dst, src);
3597   else if(sizeof(bool) == 4)
3598     movl(dst, src);
3599   else
3600     // unsupported
3601     ShouldNotReachHere();
3602 }
3603 
3604 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3605   movb(as_Address(dst), src);
3606 }
3607 
3608 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3609   if (reachable(src)) {
3610     movdl(dst, as_Address(src));
3611   } else {
3612     lea(rscratch1, src);
3613     movdl(dst, Address(rscratch1, 0));
3614   }
3615 }
3616 
3617 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3618   if (reachable(src)) {
3619     movq(dst, as_Address(src));
3620   } else {
3621     lea(rscratch1, src);
3622     movq(dst, Address(rscratch1, 0));
3623   }
3624 }
3625 
3626 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3627   if (reachable(src)) {
3628     if (UseXmmLoadAndClearUpper) {
3629       movsd (dst, as_Address(src));
3630     } else {
3631       movlpd(dst, as_Address(src));
3632     }
3633   } else {
3634     lea(rscratch1, src);
3635     if (UseXmmLoadAndClearUpper) {
3636       movsd (dst, Address(rscratch1, 0));
3637     } else {
3638       movlpd(dst, Address(rscratch1, 0));
3639     }
3640   }
3641 }
3642 
3643 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3644   if (reachable(src)) {
3645     movss(dst, as_Address(src));
3646   } else {
3647     lea(rscratch1, src);
3648     movss(dst, Address(rscratch1, 0));
3649   }
3650 }
3651 
3652 void MacroAssembler::movptr(Register dst, Register src) {
3653   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3654 }
3655 
3656 void MacroAssembler::movptr(Register dst, Address src) {
3657   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3658 }
3659 
3660 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3661 void MacroAssembler::movptr(Register dst, intptr_t src) {
3662   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3663 }
3664 
3665 void MacroAssembler::movptr(Address dst, Register src) {
3666   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3667 }
3668 
3669 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3670   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3671     Assembler::vextractf32x4h(dst, src, 0);
3672   } else {
3673     Assembler::movdqu(dst, src);
3674   }
3675 }
3676 
3677 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3678   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3679     Assembler::vinsertf32x4h(dst, src, 0);
3680   } else {
3681     Assembler::movdqu(dst, src);
3682   }
3683 }
3684 
3685 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3686   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3687     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3688   } else {
3689     Assembler::movdqu(dst, src);
3690   }
3691 }
3692 
3693 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src) {
3694   if (reachable(src)) {
3695     movdqu(dst, as_Address(src));
3696   } else {
3697     lea(rscratch1, src);
3698     movdqu(dst, Address(rscratch1, 0));
3699   }
3700 }
3701 
3702 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3703   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3704     Assembler::vextractf64x4h(dst, src, 0);
3705   } else {
3706     Assembler::vmovdqu(dst, src);
3707   }
3708 }
3709 
3710 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3711   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3712     Assembler::vinsertf64x4h(dst, src, 0);
3713   } else {
3714     Assembler::vmovdqu(dst, src);
3715   }
3716 }
3717 
3718 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3719   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3720     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3721   }
3722   else {
3723     Assembler::vmovdqu(dst, src);
3724   }
3725 }
3726 
3727 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3728   if (reachable(src)) {
3729     vmovdqu(dst, as_Address(src));
3730   }
3731   else {
3732     lea(rscratch1, src);
3733     vmovdqu(dst, Address(rscratch1, 0));
3734   }
3735 }
3736 
3737 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3738   if (reachable(src)) {
3739     Assembler::movdqa(dst, as_Address(src));
3740   } else {
3741     lea(rscratch1, src);
3742     Assembler::movdqa(dst, Address(rscratch1, 0));
3743   }
3744 }
3745 
3746 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3747   if (reachable(src)) {
3748     Assembler::movsd(dst, as_Address(src));
3749   } else {
3750     lea(rscratch1, src);
3751     Assembler::movsd(dst, Address(rscratch1, 0));
3752   }
3753 }
3754 
3755 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3756   if (reachable(src)) {
3757     Assembler::movss(dst, as_Address(src));
3758   } else {
3759     lea(rscratch1, src);
3760     Assembler::movss(dst, Address(rscratch1, 0));
3761   }
3762 }
3763 
3764 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3765   if (reachable(src)) {
3766     Assembler::mulsd(dst, as_Address(src));
3767   } else {
3768     lea(rscratch1, src);
3769     Assembler::mulsd(dst, Address(rscratch1, 0));
3770   }
3771 }
3772 
3773 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3774   if (reachable(src)) {
3775     Assembler::mulss(dst, as_Address(src));
3776   } else {
3777     lea(rscratch1, src);
3778     Assembler::mulss(dst, Address(rscratch1, 0));
3779   }
3780 }
3781 
3782 void MacroAssembler::null_check(Register reg, int offset) {
3783   if (needs_explicit_null_check(offset)) {
3784     // provoke OS NULL exception if reg = NULL by
3785     // accessing M[reg] w/o changing any (non-CC) registers
3786     // NOTE: cmpl is plenty here to provoke a segv
3787     cmpptr(rax, Address(reg, 0));
3788     // Note: should probably use testl(rax, Address(reg, 0));
3789     //       may be shorter code (however, this version of
3790     //       testl needs to be implemented first)
3791   } else {
3792     // nothing to do, (later) access of M[reg + offset]
3793     // will provoke OS NULL exception if reg = NULL
3794   }
3795 }
3796 
3797 void MacroAssembler::os_breakpoint() {
3798   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3799   // (e.g., MSVC can't call ps() otherwise)
3800   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3801 }
3802 
3803 #ifdef _LP64
3804 #define XSTATE_BV 0x200
3805 #endif
3806 
3807 void MacroAssembler::pop_CPU_state() {
3808   pop_FPU_state();
3809   pop_IU_state();
3810 }
3811 
3812 void MacroAssembler::pop_FPU_state() {
3813 #ifndef _LP64
3814   frstor(Address(rsp, 0));
3815 #else
3816   fxrstor(Address(rsp, 0));
3817 #endif
3818   addptr(rsp, FPUStateSizeInWords * wordSize);
3819 }
3820 
3821 void MacroAssembler::pop_IU_state() {
3822   popa();
3823   LP64_ONLY(addq(rsp, 8));
3824   popf();
3825 }
3826 
3827 // Save Integer and Float state
3828 // Warning: Stack must be 16 byte aligned (64bit)
3829 void MacroAssembler::push_CPU_state() {
3830   push_IU_state();
3831   push_FPU_state();
3832 }
3833 
3834 void MacroAssembler::push_FPU_state() {
3835   subptr(rsp, FPUStateSizeInWords * wordSize);
3836 #ifndef _LP64
3837   fnsave(Address(rsp, 0));
3838   fwait();
3839 #else
3840   fxsave(Address(rsp, 0));
3841 #endif // LP64
3842 }
3843 
3844 void MacroAssembler::push_IU_state() {
3845   // Push flags first because pusha kills them
3846   pushf();
3847   // Make sure rsp stays 16-byte aligned
3848   LP64_ONLY(subq(rsp, 8));
3849   pusha();
3850 }
3851 
3852 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp, bool clear_pc) {
3853   // determine java_thread register
3854   if (!java_thread->is_valid()) {
3855     java_thread = rdi;
3856     get_thread(java_thread);
3857   }
3858   // we must set sp to zero to clear frame
3859   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3860   if (clear_fp) {
3861     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3862   }
3863 
3864   if (clear_pc)
3865     movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3866 
3867 }
3868 
3869 void MacroAssembler::restore_rax(Register tmp) {
3870   if (tmp == noreg) pop(rax);
3871   else if (tmp != rax) mov(rax, tmp);
3872 }
3873 
3874 void MacroAssembler::round_to(Register reg, int modulus) {
3875   addptr(reg, modulus - 1);
3876   andptr(reg, -modulus);
3877 }
3878 
3879 void MacroAssembler::save_rax(Register tmp) {
3880   if (tmp == noreg) push(rax);
3881   else if (tmp != rax) mov(tmp, rax);
3882 }
3883 
3884 // Write serialization page so VM thread can do a pseudo remote membar.
3885 // We use the current thread pointer to calculate a thread specific
3886 // offset to write to within the page. This minimizes bus traffic
3887 // due to cache line collision.
3888 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3889   movl(tmp, thread);
3890   shrl(tmp, os::get_serialize_page_shift_count());
3891   andl(tmp, (os::vm_page_size() - sizeof(int)));
3892 
3893   Address index(noreg, tmp, Address::times_1);
3894   ExternalAddress page(os::get_memory_serialize_page());
3895 
3896   // Size of store must match masking code above
3897   movl(as_Address(ArrayAddress(page, index)), tmp);
3898 }
3899 
3900 // Calls to C land
3901 //
3902 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3903 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3904 // has to be reset to 0. This is required to allow proper stack traversal.
3905 void MacroAssembler::set_last_Java_frame(Register java_thread,
3906                                          Register last_java_sp,
3907                                          Register last_java_fp,
3908                                          address  last_java_pc) {
3909   // determine java_thread register
3910   if (!java_thread->is_valid()) {
3911     java_thread = rdi;
3912     get_thread(java_thread);
3913   }
3914   // determine last_java_sp register
3915   if (!last_java_sp->is_valid()) {
3916     last_java_sp = rsp;
3917   }
3918 
3919   // last_java_fp is optional
3920 
3921   if (last_java_fp->is_valid()) {
3922     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3923   }
3924 
3925   // last_java_pc is optional
3926 
3927   if (last_java_pc != NULL) {
3928     lea(Address(java_thread,
3929                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3930         InternalAddress(last_java_pc));
3931 
3932   }
3933   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3934 }
3935 
3936 void MacroAssembler::shlptr(Register dst, int imm8) {
3937   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3938 }
3939 
3940 void MacroAssembler::shrptr(Register dst, int imm8) {
3941   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3942 }
3943 
3944 void MacroAssembler::sign_extend_byte(Register reg) {
3945   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3946     movsbl(reg, reg); // movsxb
3947   } else {
3948     shll(reg, 24);
3949     sarl(reg, 24);
3950   }
3951 }
3952 
3953 void MacroAssembler::sign_extend_short(Register reg) {
3954   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3955     movswl(reg, reg); // movsxw
3956   } else {
3957     shll(reg, 16);
3958     sarl(reg, 16);
3959   }
3960 }
3961 
3962 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3963   assert(reachable(src), "Address should be reachable");
3964   testl(dst, as_Address(src));
3965 }
3966 
3967 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3968   int dst_enc = dst->encoding();
3969   int src_enc = src->encoding();
3970   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3971     Assembler::pcmpeqb(dst, src);
3972   } else if ((dst_enc < 16) && (src_enc < 16)) {
3973     Assembler::pcmpeqb(dst, src);
3974   } else if (src_enc < 16) {
3975     subptr(rsp, 64);
3976     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3977     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3978     Assembler::pcmpeqb(xmm0, src);
3979     movdqu(dst, xmm0);
3980     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3981     addptr(rsp, 64);
3982   } else if (dst_enc < 16) {
3983     subptr(rsp, 64);
3984     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3985     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3986     Assembler::pcmpeqb(dst, xmm0);
3987     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3988     addptr(rsp, 64);
3989   } else {
3990     subptr(rsp, 64);
3991     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3992     subptr(rsp, 64);
3993     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3994     movdqu(xmm0, src);
3995     movdqu(xmm1, dst);
3996     Assembler::pcmpeqb(xmm1, xmm0);
3997     movdqu(dst, xmm1);
3998     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3999     addptr(rsp, 64);
4000     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4001     addptr(rsp, 64);
4002   }
4003 }
4004 
4005 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
4006   int dst_enc = dst->encoding();
4007   int src_enc = src->encoding();
4008   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4009     Assembler::pcmpeqw(dst, src);
4010   } else if ((dst_enc < 16) && (src_enc < 16)) {
4011     Assembler::pcmpeqw(dst, src);
4012   } else if (src_enc < 16) {
4013     subptr(rsp, 64);
4014     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4015     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4016     Assembler::pcmpeqw(xmm0, src);
4017     movdqu(dst, xmm0);
4018     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4019     addptr(rsp, 64);
4020   } else if (dst_enc < 16) {
4021     subptr(rsp, 64);
4022     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4023     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4024     Assembler::pcmpeqw(dst, xmm0);
4025     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4026     addptr(rsp, 64);
4027   } else {
4028     subptr(rsp, 64);
4029     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4030     subptr(rsp, 64);
4031     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4032     movdqu(xmm0, src);
4033     movdqu(xmm1, dst);
4034     Assembler::pcmpeqw(xmm1, xmm0);
4035     movdqu(dst, xmm1);
4036     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4037     addptr(rsp, 64);
4038     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4039     addptr(rsp, 64);
4040   }
4041 }
4042 
4043 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
4044   int dst_enc = dst->encoding();
4045   if (dst_enc < 16) {
4046     Assembler::pcmpestri(dst, src, imm8);
4047   } else {
4048     subptr(rsp, 64);
4049     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4050     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4051     Assembler::pcmpestri(xmm0, src, imm8);
4052     movdqu(dst, xmm0);
4053     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4054     addptr(rsp, 64);
4055   }
4056 }
4057 
4058 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
4059   int dst_enc = dst->encoding();
4060   int src_enc = src->encoding();
4061   if ((dst_enc < 16) && (src_enc < 16)) {
4062     Assembler::pcmpestri(dst, src, imm8);
4063   } else if (src_enc < 16) {
4064     subptr(rsp, 64);
4065     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4066     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4067     Assembler::pcmpestri(xmm0, src, imm8);
4068     movdqu(dst, xmm0);
4069     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4070     addptr(rsp, 64);
4071   } else if (dst_enc < 16) {
4072     subptr(rsp, 64);
4073     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4074     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4075     Assembler::pcmpestri(dst, xmm0, imm8);
4076     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4077     addptr(rsp, 64);
4078   } else {
4079     subptr(rsp, 64);
4080     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4081     subptr(rsp, 64);
4082     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4083     movdqu(xmm0, src);
4084     movdqu(xmm1, dst);
4085     Assembler::pcmpestri(xmm1, xmm0, imm8);
4086     movdqu(dst, xmm1);
4087     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4088     addptr(rsp, 64);
4089     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4090     addptr(rsp, 64);
4091   }
4092 }
4093 
4094 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
4095   int dst_enc = dst->encoding();
4096   int src_enc = src->encoding();
4097   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4098     Assembler::pmovzxbw(dst, src);
4099   } else if ((dst_enc < 16) && (src_enc < 16)) {
4100     Assembler::pmovzxbw(dst, src);
4101   } else if (src_enc < 16) {
4102     subptr(rsp, 64);
4103     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4104     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4105     Assembler::pmovzxbw(xmm0, src);
4106     movdqu(dst, xmm0);
4107     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4108     addptr(rsp, 64);
4109   } else if (dst_enc < 16) {
4110     subptr(rsp, 64);
4111     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4112     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4113     Assembler::pmovzxbw(dst, xmm0);
4114     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4115     addptr(rsp, 64);
4116   } else {
4117     subptr(rsp, 64);
4118     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4119     subptr(rsp, 64);
4120     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4121     movdqu(xmm0, src);
4122     movdqu(xmm1, dst);
4123     Assembler::pmovzxbw(xmm1, xmm0);
4124     movdqu(dst, xmm1);
4125     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4126     addptr(rsp, 64);
4127     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4128     addptr(rsp, 64);
4129   }
4130 }
4131 
4132 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
4133   int dst_enc = dst->encoding();
4134   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4135     Assembler::pmovzxbw(dst, src);
4136   } else if (dst_enc < 16) {
4137     Assembler::pmovzxbw(dst, src);
4138   } else {
4139     subptr(rsp, 64);
4140     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4141     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4142     Assembler::pmovzxbw(xmm0, src);
4143     movdqu(dst, xmm0);
4144     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4145     addptr(rsp, 64);
4146   }
4147 }
4148 
4149 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4150   int src_enc = src->encoding();
4151   if (src_enc < 16) {
4152     Assembler::pmovmskb(dst, src);
4153   } else {
4154     subptr(rsp, 64);
4155     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4156     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4157     Assembler::pmovmskb(dst, xmm0);
4158     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4159     addptr(rsp, 64);
4160   }
4161 }
4162 
4163 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4164   int dst_enc = dst->encoding();
4165   int src_enc = src->encoding();
4166   if ((dst_enc < 16) && (src_enc < 16)) {
4167     Assembler::ptest(dst, src);
4168   } else if (src_enc < 16) {
4169     subptr(rsp, 64);
4170     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4171     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4172     Assembler::ptest(xmm0, src);
4173     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4174     addptr(rsp, 64);
4175   } else if (dst_enc < 16) {
4176     subptr(rsp, 64);
4177     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4178     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4179     Assembler::ptest(dst, xmm0);
4180     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4181     addptr(rsp, 64);
4182   } else {
4183     subptr(rsp, 64);
4184     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4185     subptr(rsp, 64);
4186     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4187     movdqu(xmm0, src);
4188     movdqu(xmm1, dst);
4189     Assembler::ptest(xmm1, xmm0);
4190     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4191     addptr(rsp, 64);
4192     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4193     addptr(rsp, 64);
4194   }
4195 }
4196 
4197 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4198   if (reachable(src)) {
4199     Assembler::sqrtsd(dst, as_Address(src));
4200   } else {
4201     lea(rscratch1, src);
4202     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4203   }
4204 }
4205 
4206 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4207   if (reachable(src)) {
4208     Assembler::sqrtss(dst, as_Address(src));
4209   } else {
4210     lea(rscratch1, src);
4211     Assembler::sqrtss(dst, Address(rscratch1, 0));
4212   }
4213 }
4214 
4215 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4216   if (reachable(src)) {
4217     Assembler::subsd(dst, as_Address(src));
4218   } else {
4219     lea(rscratch1, src);
4220     Assembler::subsd(dst, Address(rscratch1, 0));
4221   }
4222 }
4223 
4224 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4225   if (reachable(src)) {
4226     Assembler::subss(dst, as_Address(src));
4227   } else {
4228     lea(rscratch1, src);
4229     Assembler::subss(dst, Address(rscratch1, 0));
4230   }
4231 }
4232 
4233 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4234   if (reachable(src)) {
4235     Assembler::ucomisd(dst, as_Address(src));
4236   } else {
4237     lea(rscratch1, src);
4238     Assembler::ucomisd(dst, Address(rscratch1, 0));
4239   }
4240 }
4241 
4242 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4243   if (reachable(src)) {
4244     Assembler::ucomiss(dst, as_Address(src));
4245   } else {
4246     lea(rscratch1, src);
4247     Assembler::ucomiss(dst, Address(rscratch1, 0));
4248   }
4249 }
4250 
4251 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4252   // Used in sign-bit flipping with aligned address.
4253   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4254   if (reachable(src)) {
4255     Assembler::xorpd(dst, as_Address(src));
4256   } else {
4257     lea(rscratch1, src);
4258     Assembler::xorpd(dst, Address(rscratch1, 0));
4259   }
4260 }
4261 
4262 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4263   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4264     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4265   }
4266   else {
4267     Assembler::xorpd(dst, src);
4268   }
4269 }
4270 
4271 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4272   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4273     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4274   } else {
4275     Assembler::xorps(dst, src);
4276   }
4277 }
4278 
4279 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4280   // Used in sign-bit flipping with aligned address.
4281   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4282   if (reachable(src)) {
4283     Assembler::xorps(dst, as_Address(src));
4284   } else {
4285     lea(rscratch1, src);
4286     Assembler::xorps(dst, Address(rscratch1, 0));
4287   }
4288 }
4289 
4290 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4291   // Used in sign-bit flipping with aligned address.
4292   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4293   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4294   if (reachable(src)) {
4295     Assembler::pshufb(dst, as_Address(src));
4296   } else {
4297     lea(rscratch1, src);
4298     Assembler::pshufb(dst, Address(rscratch1, 0));
4299   }
4300 }
4301 
4302 // AVX 3-operands instructions
4303 
4304 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4305   if (reachable(src)) {
4306     vaddsd(dst, nds, as_Address(src));
4307   } else {
4308     lea(rscratch1, src);
4309     vaddsd(dst, nds, Address(rscratch1, 0));
4310   }
4311 }
4312 
4313 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4314   if (reachable(src)) {
4315     vaddss(dst, nds, as_Address(src));
4316   } else {
4317     lea(rscratch1, src);
4318     vaddss(dst, nds, Address(rscratch1, 0));
4319   }
4320 }
4321 
4322 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4323   int dst_enc = dst->encoding();
4324   int nds_enc = nds->encoding();
4325   int src_enc = src->encoding();
4326   if ((dst_enc < 16) && (nds_enc < 16)) {
4327     vandps(dst, nds, negate_field, vector_len);
4328   } else if ((src_enc < 16) && (dst_enc < 16)) {
4329     movss(src, nds);
4330     vandps(dst, src, negate_field, vector_len);
4331   } else if (src_enc < 16) {
4332     movss(src, nds);
4333     vandps(src, src, negate_field, vector_len);
4334     movss(dst, src);
4335   } else if (dst_enc < 16) {
4336     movdqu(src, xmm0);
4337     movss(xmm0, nds);
4338     vandps(dst, xmm0, negate_field, vector_len);
4339     movdqu(xmm0, src);
4340   } else if (nds_enc < 16) {
4341     movdqu(src, xmm0);
4342     vandps(xmm0, nds, negate_field, vector_len);
4343     movss(dst, xmm0);
4344     movdqu(xmm0, src);
4345   } else {
4346     movdqu(src, xmm0);
4347     movss(xmm0, nds);
4348     vandps(xmm0, xmm0, negate_field, vector_len);
4349     movss(dst, xmm0);
4350     movdqu(xmm0, src);
4351   }
4352 }
4353 
4354 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4355   int dst_enc = dst->encoding();
4356   int nds_enc = nds->encoding();
4357   int src_enc = src->encoding();
4358   if ((dst_enc < 16) && (nds_enc < 16)) {
4359     vandpd(dst, nds, negate_field, vector_len);
4360   } else if ((src_enc < 16) && (dst_enc < 16)) {
4361     movsd(src, nds);
4362     vandpd(dst, src, negate_field, vector_len);
4363   } else if (src_enc < 16) {
4364     movsd(src, nds);
4365     vandpd(src, src, negate_field, vector_len);
4366     movsd(dst, src);
4367   } else if (dst_enc < 16) {
4368     movdqu(src, xmm0);
4369     movsd(xmm0, nds);
4370     vandpd(dst, xmm0, negate_field, vector_len);
4371     movdqu(xmm0, src);
4372   } else if (nds_enc < 16) {
4373     movdqu(src, xmm0);
4374     vandpd(xmm0, nds, negate_field, vector_len);
4375     movsd(dst, xmm0);
4376     movdqu(xmm0, src);
4377   } else {
4378     movdqu(src, xmm0);
4379     movsd(xmm0, nds);
4380     vandpd(xmm0, xmm0, negate_field, vector_len);
4381     movsd(dst, xmm0);
4382     movdqu(xmm0, src);
4383   }
4384 }
4385 
4386 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4387   int dst_enc = dst->encoding();
4388   int nds_enc = nds->encoding();
4389   int src_enc = src->encoding();
4390   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4391     Assembler::vpaddb(dst, nds, src, vector_len);
4392   } else if ((dst_enc < 16) && (src_enc < 16)) {
4393     Assembler::vpaddb(dst, dst, src, vector_len);
4394   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4395     // use nds as scratch for src
4396     evmovdqul(nds, src, Assembler::AVX_512bit);
4397     Assembler::vpaddb(dst, dst, nds, vector_len);
4398   } else if ((src_enc < 16) && (nds_enc < 16)) {
4399     // use nds as scratch for dst
4400     evmovdqul(nds, dst, Assembler::AVX_512bit);
4401     Assembler::vpaddb(nds, nds, src, vector_len);
4402     evmovdqul(dst, nds, Assembler::AVX_512bit);
4403   } else if (dst_enc < 16) {
4404     // use nds as scatch for xmm0 to hold src
4405     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4406     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4407     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4408     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4409   } else {
4410     // worse case scenario, all regs are in the upper bank
4411     subptr(rsp, 64);
4412     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4413     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4414     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4415     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4416     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4417     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4418     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4419     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4420     addptr(rsp, 64);
4421   }
4422 }
4423 
4424 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4425   int dst_enc = dst->encoding();
4426   int nds_enc = nds->encoding();
4427   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4428     Assembler::vpaddb(dst, nds, src, vector_len);
4429   } else if (dst_enc < 16) {
4430     Assembler::vpaddb(dst, dst, src, vector_len);
4431   } else if (nds_enc < 16) {
4432     // implies dst_enc in upper bank with src as scratch
4433     evmovdqul(nds, dst, Assembler::AVX_512bit);
4434     Assembler::vpaddb(nds, nds, src, vector_len);
4435     evmovdqul(dst, nds, Assembler::AVX_512bit);
4436   } else {
4437     // worse case scenario, all regs in upper bank
4438     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4439     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4440     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4441     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4442   }
4443 }
4444 
4445 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4446   int dst_enc = dst->encoding();
4447   int nds_enc = nds->encoding();
4448   int src_enc = src->encoding();
4449   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4450     Assembler::vpaddw(dst, nds, src, vector_len);
4451   } else if ((dst_enc < 16) && (src_enc < 16)) {
4452     Assembler::vpaddw(dst, dst, src, vector_len);
4453   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4454     // use nds as scratch for src
4455     evmovdqul(nds, src, Assembler::AVX_512bit);
4456     Assembler::vpaddw(dst, dst, nds, vector_len);
4457   } else if ((src_enc < 16) && (nds_enc < 16)) {
4458     // use nds as scratch for dst
4459     evmovdqul(nds, dst, Assembler::AVX_512bit);
4460     Assembler::vpaddw(nds, nds, src, vector_len);
4461     evmovdqul(dst, nds, Assembler::AVX_512bit);
4462   } else if (dst_enc < 16) {
4463     // use nds as scatch for xmm0 to hold src
4464     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4465     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4466     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4467     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4468   } else {
4469     // worse case scenario, all regs are in the upper bank
4470     subptr(rsp, 64);
4471     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4472     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4473     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4474     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4475     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4476     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4477     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4478     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4479     addptr(rsp, 64);
4480   }
4481 }
4482 
4483 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4484   int dst_enc = dst->encoding();
4485   int nds_enc = nds->encoding();
4486   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4487     Assembler::vpaddw(dst, nds, src, vector_len);
4488   } else if (dst_enc < 16) {
4489     Assembler::vpaddw(dst, dst, src, vector_len);
4490   } else if (nds_enc < 16) {
4491     // implies dst_enc in upper bank with src as scratch
4492     evmovdqul(nds, dst, Assembler::AVX_512bit);
4493     Assembler::vpaddw(nds, nds, src, vector_len);
4494     evmovdqul(dst, nds, Assembler::AVX_512bit);
4495   } else {
4496     // worse case scenario, all regs in upper bank
4497     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4498     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4499     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4500     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4501   }
4502 }
4503 
4504 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4505   int dst_enc = dst->encoding();
4506   int src_enc = src->encoding();
4507   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4508     Assembler::vpbroadcastw(dst, src);
4509   } else if ((dst_enc < 16) && (src_enc < 16)) {
4510     Assembler::vpbroadcastw(dst, src);
4511   } else if (src_enc < 16) {
4512     subptr(rsp, 64);
4513     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4514     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4515     Assembler::vpbroadcastw(xmm0, src);
4516     movdqu(dst, xmm0);
4517     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4518     addptr(rsp, 64);
4519   } else if (dst_enc < 16) {
4520     subptr(rsp, 64);
4521     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4522     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4523     Assembler::vpbroadcastw(dst, xmm0);
4524     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4525     addptr(rsp, 64);
4526   } else {
4527     subptr(rsp, 64);
4528     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4529     subptr(rsp, 64);
4530     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4531     movdqu(xmm0, src);
4532     movdqu(xmm1, dst);
4533     Assembler::vpbroadcastw(xmm1, xmm0);
4534     movdqu(dst, xmm1);
4535     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4536     addptr(rsp, 64);
4537     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4538     addptr(rsp, 64);
4539   }
4540 }
4541 
4542 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4543   int dst_enc = dst->encoding();
4544   int nds_enc = nds->encoding();
4545   int src_enc = src->encoding();
4546   assert(dst_enc == nds_enc, "");
4547   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4548     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4549   } else if ((dst_enc < 16) && (src_enc < 16)) {
4550     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4551   } else if (src_enc < 16) {
4552     subptr(rsp, 64);
4553     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4554     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4555     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4556     movdqu(dst, xmm0);
4557     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4558     addptr(rsp, 64);
4559   } else if (dst_enc < 16) {
4560     subptr(rsp, 64);
4561     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4562     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4563     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4564     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4565     addptr(rsp, 64);
4566   } else {
4567     subptr(rsp, 64);
4568     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4569     subptr(rsp, 64);
4570     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4571     movdqu(xmm0, src);
4572     movdqu(xmm1, dst);
4573     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4574     movdqu(dst, xmm1);
4575     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4576     addptr(rsp, 64);
4577     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4578     addptr(rsp, 64);
4579   }
4580 }
4581 
4582 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4583   int dst_enc = dst->encoding();
4584   int nds_enc = nds->encoding();
4585   int src_enc = src->encoding();
4586   assert(dst_enc == nds_enc, "");
4587   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4588     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4589   } else if ((dst_enc < 16) && (src_enc < 16)) {
4590     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4591   } else if (src_enc < 16) {
4592     subptr(rsp, 64);
4593     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4594     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4595     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4596     movdqu(dst, xmm0);
4597     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4598     addptr(rsp, 64);
4599   } else if (dst_enc < 16) {
4600     subptr(rsp, 64);
4601     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4602     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4603     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4604     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4605     addptr(rsp, 64);
4606   } else {
4607     subptr(rsp, 64);
4608     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4609     subptr(rsp, 64);
4610     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4611     movdqu(xmm0, src);
4612     movdqu(xmm1, dst);
4613     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4614     movdqu(dst, xmm1);
4615     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4616     addptr(rsp, 64);
4617     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4618     addptr(rsp, 64);
4619   }
4620 }
4621 
4622 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4623   int dst_enc = dst->encoding();
4624   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4625     Assembler::vpmovzxbw(dst, src, vector_len);
4626   } else if (dst_enc < 16) {
4627     Assembler::vpmovzxbw(dst, src, vector_len);
4628   } else {
4629     subptr(rsp, 64);
4630     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4631     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4632     Assembler::vpmovzxbw(xmm0, src, vector_len);
4633     movdqu(dst, xmm0);
4634     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4635     addptr(rsp, 64);
4636   }
4637 }
4638 
4639 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4640   int src_enc = src->encoding();
4641   if (src_enc < 16) {
4642     Assembler::vpmovmskb(dst, src);
4643   } else {
4644     subptr(rsp, 64);
4645     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4646     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4647     Assembler::vpmovmskb(dst, xmm0);
4648     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4649     addptr(rsp, 64);
4650   }
4651 }
4652 
4653 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4654   int dst_enc = dst->encoding();
4655   int nds_enc = nds->encoding();
4656   int src_enc = src->encoding();
4657   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4658     Assembler::vpmullw(dst, nds, src, vector_len);
4659   } else if ((dst_enc < 16) && (src_enc < 16)) {
4660     Assembler::vpmullw(dst, dst, src, vector_len);
4661   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4662     // use nds as scratch for src
4663     evmovdqul(nds, src, Assembler::AVX_512bit);
4664     Assembler::vpmullw(dst, dst, nds, vector_len);
4665   } else if ((src_enc < 16) && (nds_enc < 16)) {
4666     // use nds as scratch for dst
4667     evmovdqul(nds, dst, Assembler::AVX_512bit);
4668     Assembler::vpmullw(nds, nds, src, vector_len);
4669     evmovdqul(dst, nds, Assembler::AVX_512bit);
4670   } else if (dst_enc < 16) {
4671     // use nds as scatch for xmm0 to hold src
4672     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4673     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4674     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4675     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4676   } else {
4677     // worse case scenario, all regs are in the upper bank
4678     subptr(rsp, 64);
4679     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4680     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4681     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4682     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4683     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4684     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4685     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4686     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4687     addptr(rsp, 64);
4688   }
4689 }
4690 
4691 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4692   int dst_enc = dst->encoding();
4693   int nds_enc = nds->encoding();
4694   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4695     Assembler::vpmullw(dst, nds, src, vector_len);
4696   } else if (dst_enc < 16) {
4697     Assembler::vpmullw(dst, dst, src, vector_len);
4698   } else if (nds_enc < 16) {
4699     // implies dst_enc in upper bank with src as scratch
4700     evmovdqul(nds, dst, Assembler::AVX_512bit);
4701     Assembler::vpmullw(nds, nds, src, vector_len);
4702     evmovdqul(dst, nds, Assembler::AVX_512bit);
4703   } else {
4704     // worse case scenario, all regs in upper bank
4705     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4706     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4707     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4708     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4709   }
4710 }
4711 
4712 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4713   int dst_enc = dst->encoding();
4714   int nds_enc = nds->encoding();
4715   int src_enc = src->encoding();
4716   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4717     Assembler::vpsubb(dst, nds, src, vector_len);
4718   } else if ((dst_enc < 16) && (src_enc < 16)) {
4719     Assembler::vpsubb(dst, dst, src, vector_len);
4720   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4721     // use nds as scratch for src
4722     evmovdqul(nds, src, Assembler::AVX_512bit);
4723     Assembler::vpsubb(dst, dst, nds, vector_len);
4724   } else if ((src_enc < 16) && (nds_enc < 16)) {
4725     // use nds as scratch for dst
4726     evmovdqul(nds, dst, Assembler::AVX_512bit);
4727     Assembler::vpsubb(nds, nds, src, vector_len);
4728     evmovdqul(dst, nds, Assembler::AVX_512bit);
4729   } else if (dst_enc < 16) {
4730     // use nds as scatch for xmm0 to hold src
4731     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4732     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4733     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4734     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4735   } else {
4736     // worse case scenario, all regs are in the upper bank
4737     subptr(rsp, 64);
4738     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4739     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4740     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4741     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4742     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4743     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4744     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4745     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4746     addptr(rsp, 64);
4747   }
4748 }
4749 
4750 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4751   int dst_enc = dst->encoding();
4752   int nds_enc = nds->encoding();
4753   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4754     Assembler::vpsubb(dst, nds, src, vector_len);
4755   } else if (dst_enc < 16) {
4756     Assembler::vpsubb(dst, dst, src, vector_len);
4757   } else if (nds_enc < 16) {
4758     // implies dst_enc in upper bank with src as scratch
4759     evmovdqul(nds, dst, Assembler::AVX_512bit);
4760     Assembler::vpsubb(nds, nds, src, vector_len);
4761     evmovdqul(dst, nds, Assembler::AVX_512bit);
4762   } else {
4763     // worse case scenario, all regs in upper bank
4764     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4765     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4766     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4767     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4768   }
4769 }
4770 
4771 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4772   int dst_enc = dst->encoding();
4773   int nds_enc = nds->encoding();
4774   int src_enc = src->encoding();
4775   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4776     Assembler::vpsubw(dst, nds, src, vector_len);
4777   } else if ((dst_enc < 16) && (src_enc < 16)) {
4778     Assembler::vpsubw(dst, dst, src, vector_len);
4779   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4780     // use nds as scratch for src
4781     evmovdqul(nds, src, Assembler::AVX_512bit);
4782     Assembler::vpsubw(dst, dst, nds, vector_len);
4783   } else if ((src_enc < 16) && (nds_enc < 16)) {
4784     // use nds as scratch for dst
4785     evmovdqul(nds, dst, Assembler::AVX_512bit);
4786     Assembler::vpsubw(nds, nds, src, vector_len);
4787     evmovdqul(dst, nds, Assembler::AVX_512bit);
4788   } else if (dst_enc < 16) {
4789     // use nds as scatch for xmm0 to hold src
4790     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4791     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4792     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4793     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4794   } else {
4795     // worse case scenario, all regs are in the upper bank
4796     subptr(rsp, 64);
4797     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4798     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4799     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4800     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4801     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4802     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4803     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4804     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4805     addptr(rsp, 64);
4806   }
4807 }
4808 
4809 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4810   int dst_enc = dst->encoding();
4811   int nds_enc = nds->encoding();
4812   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4813     Assembler::vpsubw(dst, nds, src, vector_len);
4814   } else if (dst_enc < 16) {
4815     Assembler::vpsubw(dst, dst, src, vector_len);
4816   } else if (nds_enc < 16) {
4817     // implies dst_enc in upper bank with src as scratch
4818     evmovdqul(nds, dst, Assembler::AVX_512bit);
4819     Assembler::vpsubw(nds, nds, src, vector_len);
4820     evmovdqul(dst, nds, Assembler::AVX_512bit);
4821   } else {
4822     // worse case scenario, all regs in upper bank
4823     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4824     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4825     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4826     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4827   }
4828 }
4829 
4830 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4831   int dst_enc = dst->encoding();
4832   int nds_enc = nds->encoding();
4833   int shift_enc = shift->encoding();
4834   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4835     Assembler::vpsraw(dst, nds, shift, vector_len);
4836   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4837     Assembler::vpsraw(dst, dst, shift, vector_len);
4838   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4839     // use nds_enc as scratch with shift
4840     evmovdqul(nds, shift, Assembler::AVX_512bit);
4841     Assembler::vpsraw(dst, dst, nds, vector_len);
4842   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4843     // use nds as scratch with dst
4844     evmovdqul(nds, dst, Assembler::AVX_512bit);
4845     Assembler::vpsraw(nds, nds, shift, vector_len);
4846     evmovdqul(dst, nds, Assembler::AVX_512bit);
4847   } else if (dst_enc < 16) {
4848     // use nds to save a copy of xmm0 and hold shift
4849     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4850     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4851     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4852     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4853   } else if (nds_enc < 16) {
4854     // use nds as dest as temps
4855     evmovdqul(nds, dst, Assembler::AVX_512bit);
4856     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4857     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4858     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4859     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4860     evmovdqul(dst, nds, Assembler::AVX_512bit);
4861   } else {
4862     // worse case scenario, all regs are in the upper bank
4863     subptr(rsp, 64);
4864     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4865     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4866     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4867     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4868     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4869     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4870     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4871     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4872     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4873     addptr(rsp, 64);
4874   }
4875 }
4876 
4877 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4878   int dst_enc = dst->encoding();
4879   int nds_enc = nds->encoding();
4880   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4881     Assembler::vpsraw(dst, nds, shift, vector_len);
4882   } else if (dst_enc < 16) {
4883     Assembler::vpsraw(dst, dst, shift, vector_len);
4884   } else if (nds_enc < 16) {
4885     // use nds as scratch
4886     evmovdqul(nds, dst, Assembler::AVX_512bit);
4887     Assembler::vpsraw(nds, nds, shift, vector_len);
4888     evmovdqul(dst, nds, Assembler::AVX_512bit);
4889   } else {
4890     // use nds as scratch for xmm0
4891     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4892     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4893     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4894     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4895   }
4896 }
4897 
4898 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4899   int dst_enc = dst->encoding();
4900   int nds_enc = nds->encoding();
4901   int shift_enc = shift->encoding();
4902   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4903     Assembler::vpsrlw(dst, nds, shift, vector_len);
4904   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4905     Assembler::vpsrlw(dst, dst, shift, vector_len);
4906   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4907     // use nds_enc as scratch with shift
4908     evmovdqul(nds, shift, Assembler::AVX_512bit);
4909     Assembler::vpsrlw(dst, dst, nds, vector_len);
4910   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4911     // use nds as scratch with dst
4912     evmovdqul(nds, dst, Assembler::AVX_512bit);
4913     Assembler::vpsrlw(nds, nds, shift, vector_len);
4914     evmovdqul(dst, nds, Assembler::AVX_512bit);
4915   } else if (dst_enc < 16) {
4916     // use nds to save a copy of xmm0 and hold shift
4917     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4918     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4919     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4920     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4921   } else if (nds_enc < 16) {
4922     // use nds as dest as temps
4923     evmovdqul(nds, dst, Assembler::AVX_512bit);
4924     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4925     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4926     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4927     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4928     evmovdqul(dst, nds, Assembler::AVX_512bit);
4929   } else {
4930     // worse case scenario, all regs are in the upper bank
4931     subptr(rsp, 64);
4932     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4933     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4934     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4935     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4936     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4937     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4938     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4939     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4940     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4941     addptr(rsp, 64);
4942   }
4943 }
4944 
4945 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4946   int dst_enc = dst->encoding();
4947   int nds_enc = nds->encoding();
4948   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4949     Assembler::vpsrlw(dst, nds, shift, vector_len);
4950   } else if (dst_enc < 16) {
4951     Assembler::vpsrlw(dst, dst, shift, vector_len);
4952   } else if (nds_enc < 16) {
4953     // use nds as scratch
4954     evmovdqul(nds, dst, Assembler::AVX_512bit);
4955     Assembler::vpsrlw(nds, nds, shift, vector_len);
4956     evmovdqul(dst, nds, Assembler::AVX_512bit);
4957   } else {
4958     // use nds as scratch for xmm0
4959     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4960     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4961     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4962     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4963   }
4964 }
4965 
4966 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4967   int dst_enc = dst->encoding();
4968   int nds_enc = nds->encoding();
4969   int shift_enc = shift->encoding();
4970   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4971     Assembler::vpsllw(dst, nds, shift, vector_len);
4972   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4973     Assembler::vpsllw(dst, dst, shift, vector_len);
4974   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4975     // use nds_enc as scratch with shift
4976     evmovdqul(nds, shift, Assembler::AVX_512bit);
4977     Assembler::vpsllw(dst, dst, nds, vector_len);
4978   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4979     // use nds as scratch with dst
4980     evmovdqul(nds, dst, Assembler::AVX_512bit);
4981     Assembler::vpsllw(nds, nds, shift, vector_len);
4982     evmovdqul(dst, nds, Assembler::AVX_512bit);
4983   } else if (dst_enc < 16) {
4984     // use nds to save a copy of xmm0 and hold shift
4985     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4986     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4987     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4988     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4989   } else if (nds_enc < 16) {
4990     // use nds as dest as temps
4991     evmovdqul(nds, dst, Assembler::AVX_512bit);
4992     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4993     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4994     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4995     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4996     evmovdqul(dst, nds, Assembler::AVX_512bit);
4997   } else {
4998     // worse case scenario, all regs are in the upper bank
4999     subptr(rsp, 64);
5000     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5001     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
5002     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
5003     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5004     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
5005     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
5006     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5007     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
5008     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5009     addptr(rsp, 64);
5010   }
5011 }
5012 
5013 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
5014   int dst_enc = dst->encoding();
5015   int nds_enc = nds->encoding();
5016   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
5017     Assembler::vpsllw(dst, nds, shift, vector_len);
5018   } else if (dst_enc < 16) {
5019     Assembler::vpsllw(dst, dst, shift, vector_len);
5020   } else if (nds_enc < 16) {
5021     // use nds as scratch
5022     evmovdqul(nds, dst, Assembler::AVX_512bit);
5023     Assembler::vpsllw(nds, nds, shift, vector_len);
5024     evmovdqul(dst, nds, Assembler::AVX_512bit);
5025   } else {
5026     // use nds as scratch for xmm0
5027     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
5028     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5029     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
5030     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
5031   }
5032 }
5033 
5034 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
5035   int dst_enc = dst->encoding();
5036   int src_enc = src->encoding();
5037   if ((dst_enc < 16) && (src_enc < 16)) {
5038     Assembler::vptest(dst, src);
5039   } else if (src_enc < 16) {
5040     subptr(rsp, 64);
5041     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5042     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5043     Assembler::vptest(xmm0, src);
5044     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5045     addptr(rsp, 64);
5046   } else if (dst_enc < 16) {
5047     subptr(rsp, 64);
5048     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5049     evmovdqul(xmm0, src, Assembler::AVX_512bit);
5050     Assembler::vptest(dst, xmm0);
5051     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5052     addptr(rsp, 64);
5053   } else {
5054     subptr(rsp, 64);
5055     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5056     subptr(rsp, 64);
5057     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5058     movdqu(xmm0, src);
5059     movdqu(xmm1, dst);
5060     Assembler::vptest(xmm1, xmm0);
5061     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5062     addptr(rsp, 64);
5063     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5064     addptr(rsp, 64);
5065   }
5066 }
5067 
5068 // This instruction exists within macros, ergo we cannot control its input
5069 // when emitted through those patterns.
5070 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
5071   if (VM_Version::supports_avx512nobw()) {
5072     int dst_enc = dst->encoding();
5073     int src_enc = src->encoding();
5074     if (dst_enc == src_enc) {
5075       if (dst_enc < 16) {
5076         Assembler::punpcklbw(dst, src);
5077       } else {
5078         subptr(rsp, 64);
5079         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5080         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5081         Assembler::punpcklbw(xmm0, xmm0);
5082         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5083         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5084         addptr(rsp, 64);
5085       }
5086     } else {
5087       if ((src_enc < 16) && (dst_enc < 16)) {
5088         Assembler::punpcklbw(dst, src);
5089       } else if (src_enc < 16) {
5090         subptr(rsp, 64);
5091         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5092         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5093         Assembler::punpcklbw(xmm0, src);
5094         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5095         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5096         addptr(rsp, 64);
5097       } else if (dst_enc < 16) {
5098         subptr(rsp, 64);
5099         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5100         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5101         Assembler::punpcklbw(dst, xmm0);
5102         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5103         addptr(rsp, 64);
5104       } else {
5105         subptr(rsp, 64);
5106         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5107         subptr(rsp, 64);
5108         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5109         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5110         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5111         Assembler::punpcklbw(xmm0, xmm1);
5112         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5113         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5114         addptr(rsp, 64);
5115         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5116         addptr(rsp, 64);
5117       }
5118     }
5119   } else {
5120     Assembler::punpcklbw(dst, src);
5121   }
5122 }
5123 
5124 // This instruction exists within macros, ergo we cannot control its input
5125 // when emitted through those patterns.
5126 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5127   if (VM_Version::supports_avx512nobw()) {
5128     int dst_enc = dst->encoding();
5129     int src_enc = src->encoding();
5130     if (dst_enc == src_enc) {
5131       if (dst_enc < 16) {
5132         Assembler::pshuflw(dst, src, mode);
5133       } else {
5134         subptr(rsp, 64);
5135         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5136         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5137         Assembler::pshuflw(xmm0, xmm0, mode);
5138         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5139         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5140         addptr(rsp, 64);
5141       }
5142     } else {
5143       if ((src_enc < 16) && (dst_enc < 16)) {
5144         Assembler::pshuflw(dst, src, mode);
5145       } else if (src_enc < 16) {
5146         subptr(rsp, 64);
5147         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5148         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5149         Assembler::pshuflw(xmm0, src, mode);
5150         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5151         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5152         addptr(rsp, 64);
5153       } else if (dst_enc < 16) {
5154         subptr(rsp, 64);
5155         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5156         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5157         Assembler::pshuflw(dst, xmm0, mode);
5158         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5159         addptr(rsp, 64);
5160       } else {
5161         subptr(rsp, 64);
5162         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5163         subptr(rsp, 64);
5164         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5165         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5166         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5167         Assembler::pshuflw(xmm0, xmm1, mode);
5168         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5169         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5170         addptr(rsp, 64);
5171         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5172         addptr(rsp, 64);
5173       }
5174     }
5175   } else {
5176     Assembler::pshuflw(dst, src, mode);
5177   }
5178 }
5179 
5180 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5181   if (reachable(src)) {
5182     vandpd(dst, nds, as_Address(src), vector_len);
5183   } else {
5184     lea(rscratch1, src);
5185     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5186   }
5187 }
5188 
5189 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5190   if (reachable(src)) {
5191     vandps(dst, nds, as_Address(src), vector_len);
5192   } else {
5193     lea(rscratch1, src);
5194     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5195   }
5196 }
5197 
5198 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5199   if (reachable(src)) {
5200     vdivsd(dst, nds, as_Address(src));
5201   } else {
5202     lea(rscratch1, src);
5203     vdivsd(dst, nds, Address(rscratch1, 0));
5204   }
5205 }
5206 
5207 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5208   if (reachable(src)) {
5209     vdivss(dst, nds, as_Address(src));
5210   } else {
5211     lea(rscratch1, src);
5212     vdivss(dst, nds, Address(rscratch1, 0));
5213   }
5214 }
5215 
5216 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5217   if (reachable(src)) {
5218     vmulsd(dst, nds, as_Address(src));
5219   } else {
5220     lea(rscratch1, src);
5221     vmulsd(dst, nds, Address(rscratch1, 0));
5222   }
5223 }
5224 
5225 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5226   if (reachable(src)) {
5227     vmulss(dst, nds, as_Address(src));
5228   } else {
5229     lea(rscratch1, src);
5230     vmulss(dst, nds, Address(rscratch1, 0));
5231   }
5232 }
5233 
5234 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5235   if (reachable(src)) {
5236     vsubsd(dst, nds, as_Address(src));
5237   } else {
5238     lea(rscratch1, src);
5239     vsubsd(dst, nds, Address(rscratch1, 0));
5240   }
5241 }
5242 
5243 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5244   if (reachable(src)) {
5245     vsubss(dst, nds, as_Address(src));
5246   } else {
5247     lea(rscratch1, src);
5248     vsubss(dst, nds, Address(rscratch1, 0));
5249   }
5250 }
5251 
5252 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5253   int nds_enc = nds->encoding();
5254   int dst_enc = dst->encoding();
5255   bool dst_upper_bank = (dst_enc > 15);
5256   bool nds_upper_bank = (nds_enc > 15);
5257   if (VM_Version::supports_avx512novl() &&
5258       (nds_upper_bank || dst_upper_bank)) {
5259     if (dst_upper_bank) {
5260       subptr(rsp, 64);
5261       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5262       movflt(xmm0, nds);
5263       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5264       movflt(dst, xmm0);
5265       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5266       addptr(rsp, 64);
5267     } else {
5268       movflt(dst, nds);
5269       vxorps(dst, dst, src, Assembler::AVX_128bit);
5270     }
5271   } else {
5272     vxorps(dst, nds, src, Assembler::AVX_128bit);
5273   }
5274 }
5275 
5276 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5277   int nds_enc = nds->encoding();
5278   int dst_enc = dst->encoding();
5279   bool dst_upper_bank = (dst_enc > 15);
5280   bool nds_upper_bank = (nds_enc > 15);
5281   if (VM_Version::supports_avx512novl() &&
5282       (nds_upper_bank || dst_upper_bank)) {
5283     if (dst_upper_bank) {
5284       subptr(rsp, 64);
5285       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5286       movdbl(xmm0, nds);
5287       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5288       movdbl(dst, xmm0);
5289       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5290       addptr(rsp, 64);
5291     } else {
5292       movdbl(dst, nds);
5293       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5294     }
5295   } else {
5296     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5297   }
5298 }
5299 
5300 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5301   if (reachable(src)) {
5302     vxorpd(dst, nds, as_Address(src), vector_len);
5303   } else {
5304     lea(rscratch1, src);
5305     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5306   }
5307 }
5308 
5309 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5310   if (reachable(src)) {
5311     vxorps(dst, nds, as_Address(src), vector_len);
5312   } else {
5313     lea(rscratch1, src);
5314     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5315   }
5316 }
5317 
5318 
5319 //////////////////////////////////////////////////////////////////////////////////
5320 #if INCLUDE_ALL_GCS
5321 
5322 void MacroAssembler::g1_write_barrier_pre(Register obj,
5323                                           Register pre_val,
5324                                           Register thread,
5325                                           Register tmp,
5326                                           bool tosca_live,
5327                                           bool expand_call) {
5328 
5329   // If expand_call is true then we expand the call_VM_leaf macro
5330   // directly to skip generating the check by
5331   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
5332 
5333 #ifdef _LP64
5334   assert(thread == r15_thread, "must be");
5335 #endif // _LP64
5336 
5337   Label done;
5338   Label runtime;
5339 
5340   assert(pre_val != noreg, "check this code");
5341 
5342   if (obj != noreg) {
5343     assert_different_registers(obj, pre_val, tmp);
5344     assert(pre_val != rax, "check this code");
5345   }
5346 
5347   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5348                                        SATBMarkQueue::byte_offset_of_active()));
5349   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5350                                        SATBMarkQueue::byte_offset_of_index()));
5351   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5352                                        SATBMarkQueue::byte_offset_of_buf()));
5353 
5354 
5355   // Is marking active?
5356   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
5357     cmpl(in_progress, 0);
5358   } else {
5359     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
5360     cmpb(in_progress, 0);
5361   }
5362   jcc(Assembler::equal, done);
5363 
5364   // Do we need to load the previous value?
5365   if (obj != noreg) {
5366     load_heap_oop(pre_val, Address(obj, 0));
5367   }
5368 
5369   // Is the previous value null?
5370   cmpptr(pre_val, (int32_t) NULL_WORD);
5371   jcc(Assembler::equal, done);
5372 
5373   // Can we store original value in the thread's buffer?
5374   // Is index == 0?
5375   // (The index field is typed as size_t.)
5376 
5377   movptr(tmp, index);                   // tmp := *index_adr
5378   cmpptr(tmp, 0);                       // tmp == 0?
5379   jcc(Assembler::equal, runtime);       // If yes, goto runtime
5380 
5381   subptr(tmp, wordSize);                // tmp := tmp - wordSize
5382   movptr(index, tmp);                   // *index_adr := tmp
5383   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
5384 
5385   // Record the previous value
5386   movptr(Address(tmp, 0), pre_val);
5387   jmp(done);
5388 
5389   bind(runtime);
5390   // save the live input values
5391   if(tosca_live) push(rax);
5392 
5393   if (obj != noreg && obj != rax)
5394     push(obj);
5395 
5396   if (pre_val != rax)
5397     push(pre_val);
5398 
5399   // Calling the runtime using the regular call_VM_leaf mechanism generates
5400   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
5401   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
5402   //
5403   // If we care generating the pre-barrier without a frame (e.g. in the
5404   // intrinsified Reference.get() routine) then ebp might be pointing to
5405   // the caller frame and so this check will most likely fail at runtime.
5406   //
5407   // Expanding the call directly bypasses the generation of the check.
5408   // So when we do not have have a full interpreter frame on the stack
5409   // expand_call should be passed true.
5410 
5411   NOT_LP64( push(thread); )
5412 
5413   if (expand_call) {
5414     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
5415     pass_arg1(this, thread);
5416     pass_arg0(this, pre_val);
5417     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5418   } else {
5419     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5420   }
5421 
5422   NOT_LP64( pop(thread); )
5423 
5424   // save the live input values
5425   if (pre_val != rax)
5426     pop(pre_val);
5427 
5428   if (obj != noreg && obj != rax)
5429     pop(obj);
5430 
5431   if(tosca_live) pop(rax);
5432 
5433   bind(done);
5434 }
5435 
5436 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5437                                            Register new_val,
5438                                            Register thread,
5439                                            Register tmp,
5440                                            Register tmp2) {
5441 #ifdef _LP64
5442   assert(thread == r15_thread, "must be");
5443 #endif // _LP64
5444 
5445   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5446                                        DirtyCardQueue::byte_offset_of_index()));
5447   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5448                                        DirtyCardQueue::byte_offset_of_buf()));
5449 
5450   CardTableModRefBS* ct =
5451     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5452   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5453 
5454   Label done;
5455   Label runtime;
5456 
5457   // Does store cross heap regions?
5458 
5459   movptr(tmp, store_addr);
5460   xorptr(tmp, new_val);
5461   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5462   jcc(Assembler::equal, done);
5463 
5464   // crosses regions, storing NULL?
5465 
5466   cmpptr(new_val, (int32_t) NULL_WORD);
5467   jcc(Assembler::equal, done);
5468 
5469   // storing region crossing non-NULL, is card already dirty?
5470 
5471   const Register card_addr = tmp;
5472   const Register cardtable = tmp2;
5473 
5474   movptr(card_addr, store_addr);
5475   shrptr(card_addr, CardTableModRefBS::card_shift);
5476   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5477   // a valid address and therefore is not properly handled by the relocation code.
5478   movptr(cardtable, (intptr_t)ct->byte_map_base);
5479   addptr(card_addr, cardtable);
5480 
5481   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
5482   jcc(Assembler::equal, done);
5483 
5484   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5485   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5486   jcc(Assembler::equal, done);
5487 
5488 
5489   // storing a region crossing, non-NULL oop, card is clean.
5490   // dirty card and log.
5491 
5492   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5493 
5494   cmpl(queue_index, 0);
5495   jcc(Assembler::equal, runtime);
5496   subl(queue_index, wordSize);
5497   movptr(tmp2, buffer);
5498 #ifdef _LP64
5499   movslq(rscratch1, queue_index);
5500   addq(tmp2, rscratch1);
5501   movq(Address(tmp2, 0), card_addr);
5502 #else
5503   addl(tmp2, queue_index);
5504   movl(Address(tmp2, 0), card_addr);
5505 #endif
5506   jmp(done);
5507 
5508   bind(runtime);
5509   // save the live input values
5510   push(store_addr);
5511   push(new_val);
5512 #ifdef _LP64
5513   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5514 #else
5515   push(thread);
5516   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5517   pop(thread);
5518 #endif
5519   pop(new_val);
5520   pop(store_addr);
5521 
5522   bind(done);
5523 }
5524 
5525 #endif // INCLUDE_ALL_GCS
5526 //////////////////////////////////////////////////////////////////////////////////
5527 
5528 
5529 void MacroAssembler::store_check(Register obj, Address dst) {
5530   store_check(obj);
5531 }
5532 
5533 void MacroAssembler::store_check(Register obj) {
5534   // Does a store check for the oop in register obj. The content of
5535   // register obj is destroyed afterwards.
5536   BarrierSet* bs = Universe::heap()->barrier_set();
5537   assert(bs->kind() == BarrierSet::CardTableForRS ||
5538          bs->kind() == BarrierSet::CardTableExtension,
5539          "Wrong barrier set kind");
5540 
5541   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5542   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5543 
5544   shrptr(obj, CardTableModRefBS::card_shift);
5545 
5546   Address card_addr;
5547 
5548   // The calculation for byte_map_base is as follows:
5549   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5550   // So this essentially converts an address to a displacement and it will
5551   // never need to be relocated. On 64bit however the value may be too
5552   // large for a 32bit displacement.
5553   intptr_t disp = (intptr_t) ct->byte_map_base;
5554   if (is_simm32(disp)) {
5555     card_addr = Address(noreg, obj, Address::times_1, disp);
5556   } else {
5557     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5558     // displacement and done in a single instruction given favorable mapping and a
5559     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5560     // entry and that entry is not properly handled by the relocation code.
5561     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5562     Address index(noreg, obj, Address::times_1);
5563     card_addr = as_Address(ArrayAddress(cardtable, index));
5564   }
5565 
5566   int dirty = CardTableModRefBS::dirty_card_val();
5567   if (UseCondCardMark) {
5568     Label L_already_dirty;
5569     if (UseConcMarkSweepGC) {
5570       membar(Assembler::StoreLoad);
5571     }
5572     cmpb(card_addr, dirty);
5573     jcc(Assembler::equal, L_already_dirty);
5574     movb(card_addr, dirty);
5575     bind(L_already_dirty);
5576   } else {
5577     movb(card_addr, dirty);
5578   }
5579 }
5580 
5581 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5582   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5583 }
5584 
5585 // Force generation of a 4 byte immediate value even if it fits into 8bit
5586 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5587   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5588 }
5589 
5590 void MacroAssembler::subptr(Register dst, Register src) {
5591   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5592 }
5593 
5594 // C++ bool manipulation
5595 void MacroAssembler::testbool(Register dst) {
5596   if(sizeof(bool) == 1)
5597     testb(dst, 0xff);
5598   else if(sizeof(bool) == 2) {
5599     // testw implementation needed for two byte bools
5600     ShouldNotReachHere();
5601   } else if(sizeof(bool) == 4)
5602     testl(dst, dst);
5603   else
5604     // unsupported
5605     ShouldNotReachHere();
5606 }
5607 
5608 void MacroAssembler::testptr(Register dst, Register src) {
5609   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5610 }
5611 
5612 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5613 void MacroAssembler::tlab_allocate(Register obj,
5614                                    Register var_size_in_bytes,
5615                                    int con_size_in_bytes,
5616                                    Register t1,
5617                                    Register t2,
5618                                    Label& slow_case) {
5619   assert_different_registers(obj, t1, t2);
5620   assert_different_registers(obj, var_size_in_bytes, t1);
5621   Register end = t2;
5622   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5623 
5624   verify_tlab();
5625 
5626   NOT_LP64(get_thread(thread));
5627 
5628   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5629   if (var_size_in_bytes == noreg) {
5630     lea(end, Address(obj, con_size_in_bytes));
5631   } else {
5632     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5633   }
5634   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5635   jcc(Assembler::above, slow_case);
5636 
5637   // update the tlab top pointer
5638   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5639 
5640   // recover var_size_in_bytes if necessary
5641   if (var_size_in_bytes == end) {
5642     subptr(var_size_in_bytes, obj);
5643   }
5644   verify_tlab();
5645 }
5646 
5647 // Preserves rbx, and rdx.
5648 Register MacroAssembler::tlab_refill(Label& retry,
5649                                      Label& try_eden,
5650                                      Label& slow_case) {
5651   Register top = rax;
5652   Register t1  = rcx;
5653   Register t2  = rsi;
5654   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5655   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5656   Label do_refill, discard_tlab;
5657 
5658   if (!Universe::heap()->supports_inline_contig_alloc()) {
5659     // No allocation in the shared eden.
5660     jmp(slow_case);
5661   }
5662 
5663   NOT_LP64(get_thread(thread_reg));
5664 
5665   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5666   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5667 
5668   // calculate amount of free space
5669   subptr(t1, top);
5670   shrptr(t1, LogHeapWordSize);
5671 
5672   // Retain tlab and allocate object in shared space if
5673   // the amount free in the tlab is too large to discard.
5674   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5675   jcc(Assembler::lessEqual, discard_tlab);
5676 
5677   // Retain
5678   // %%% yuck as movptr...
5679   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5680   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5681   if (TLABStats) {
5682     // increment number of slow_allocations
5683     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5684   }
5685   jmp(try_eden);
5686 
5687   bind(discard_tlab);
5688   if (TLABStats) {
5689     // increment number of refills
5690     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5691     // accumulate wastage -- t1 is amount free in tlab
5692     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5693   }
5694 
5695   // if tlab is currently allocated (top or end != null) then
5696   // fill [top, end + alignment_reserve) with array object
5697   testptr(top, top);
5698   jcc(Assembler::zero, do_refill);
5699 
5700   // set up the mark word
5701   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5702   // set the length to the remaining space
5703   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5704   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5705   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5706   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5707   // set klass to intArrayKlass
5708   // dubious reloc why not an oop reloc?
5709   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5710   // store klass last.  concurrent gcs assumes klass length is valid if
5711   // klass field is not null.
5712   store_klass(top, t1);
5713 
5714   movptr(t1, top);
5715   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5716   incr_allocated_bytes(thread_reg, t1, 0);
5717 
5718   // refill the tlab with an eden allocation
5719   bind(do_refill);
5720   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5721   shlptr(t1, LogHeapWordSize);
5722   // allocate new tlab, address returned in top
5723   eden_allocate(top, t1, 0, t2, slow_case);
5724 
5725   // Check that t1 was preserved in eden_allocate.
5726 #ifdef ASSERT
5727   if (UseTLAB) {
5728     Label ok;
5729     Register tsize = rsi;
5730     assert_different_registers(tsize, thread_reg, t1);
5731     push(tsize);
5732     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5733     shlptr(tsize, LogHeapWordSize);
5734     cmpptr(t1, tsize);
5735     jcc(Assembler::equal, ok);
5736     STOP("assert(t1 != tlab size)");
5737     should_not_reach_here();
5738 
5739     bind(ok);
5740     pop(tsize);
5741   }
5742 #endif
5743   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5744   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5745   addptr(top, t1);
5746   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5747   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
5748   verify_tlab();
5749   jmp(retry);
5750 
5751   return thread_reg; // for use by caller
5752 }
5753 
5754 void MacroAssembler::incr_allocated_bytes(Register thread,
5755                                           Register var_size_in_bytes,
5756                                           int con_size_in_bytes,
5757                                           Register t1) {
5758   if (!thread->is_valid()) {
5759 #ifdef _LP64
5760     thread = r15_thread;
5761 #else
5762     assert(t1->is_valid(), "need temp reg");
5763     thread = t1;
5764     get_thread(thread);
5765 #endif
5766   }
5767 
5768 #ifdef _LP64
5769   if (var_size_in_bytes->is_valid()) {
5770     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5771   } else {
5772     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5773   }
5774 #else
5775   if (var_size_in_bytes->is_valid()) {
5776     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5777   } else {
5778     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5779   }
5780   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5781 #endif
5782 }
5783 
5784 void MacroAssembler::fp_runtime_fallback(address runtime_entry, int nb_args, int num_fpu_regs_in_use) {
5785   pusha();
5786 
5787   // if we are coming from c1, xmm registers may be live
5788   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
5789   if (UseAVX > 2) {
5790     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
5791   }
5792 
5793   if (UseSSE == 1)  {
5794     subptr(rsp, sizeof(jdouble)*8);
5795     for (int n = 0; n < 8; n++) {
5796       movflt(Address(rsp, n*sizeof(jdouble)), as_XMMRegister(n));
5797     }
5798   } else if (UseSSE >= 2)  {
5799     if (UseAVX > 2) {
5800       push(rbx);
5801       movl(rbx, 0xffff);
5802       kmovwl(k1, rbx);
5803       pop(rbx);
5804     }
5805 #ifdef COMPILER2
5806     if (MaxVectorSize > 16) {
5807       if(UseAVX > 2) {
5808         // Save upper half of ZMM registers
5809         subptr(rsp, 32*num_xmm_regs);
5810         for (int n = 0; n < num_xmm_regs; n++) {
5811           vextractf64x4h(Address(rsp, n*32), as_XMMRegister(n), 1);
5812         }
5813       }
5814       assert(UseAVX > 0, "256 bit vectors are supported only with AVX");
5815       // Save upper half of YMM registers
5816       subptr(rsp, 16*num_xmm_regs);
5817       for (int n = 0; n < num_xmm_regs; n++) {
5818         vextractf128h(Address(rsp, n*16), as_XMMRegister(n));
5819       }
5820     }
5821 #endif
5822     // Save whole 128bit (16 bytes) XMM registers
5823     subptr(rsp, 16*num_xmm_regs);
5824 #ifdef _LP64
5825     if (VM_Version::supports_evex()) {
5826       for (int n = 0; n < num_xmm_regs; n++) {
5827         vextractf32x4h(Address(rsp, n*16), as_XMMRegister(n), 0);
5828       }
5829     } else {
5830       for (int n = 0; n < num_xmm_regs; n++) {
5831         movdqu(Address(rsp, n*16), as_XMMRegister(n));
5832       }
5833     }
5834 #else
5835     for (int n = 0; n < num_xmm_regs; n++) {
5836       movdqu(Address(rsp, n*16), as_XMMRegister(n));
5837     }
5838 #endif
5839   }
5840 
5841   // Preserve registers across runtime call
5842   int incoming_argument_and_return_value_offset = -1;
5843   if (num_fpu_regs_in_use > 1) {
5844     // Must preserve all other FPU regs (could alternatively convert
5845     // SharedRuntime::dsin, dcos etc. into assembly routines known not to trash
5846     // FPU state, but can not trust C compiler)
5847     NEEDS_CLEANUP;
5848     // NOTE that in this case we also push the incoming argument(s) to
5849     // the stack and restore it later; we also use this stack slot to
5850     // hold the return value from dsin, dcos etc.
5851     for (int i = 0; i < num_fpu_regs_in_use; i++) {
5852       subptr(rsp, sizeof(jdouble));
5853       fstp_d(Address(rsp, 0));
5854     }
5855     incoming_argument_and_return_value_offset = sizeof(jdouble)*(num_fpu_regs_in_use-1);
5856     for (int i = nb_args-1; i >= 0; i--) {
5857       fld_d(Address(rsp, incoming_argument_and_return_value_offset-i*sizeof(jdouble)));
5858     }
5859   }
5860 
5861   subptr(rsp, nb_args*sizeof(jdouble));
5862   for (int i = 0; i < nb_args; i++) {
5863     fstp_d(Address(rsp, i*sizeof(jdouble)));
5864   }
5865 
5866 #ifdef _LP64
5867   if (nb_args > 0) {
5868     movdbl(xmm0, Address(rsp, 0));
5869   }
5870   if (nb_args > 1) {
5871     movdbl(xmm1, Address(rsp, sizeof(jdouble)));
5872   }
5873   assert(nb_args <= 2, "unsupported number of args");
5874 #endif // _LP64
5875 
5876   // NOTE: we must not use call_VM_leaf here because that requires a
5877   // complete interpreter frame in debug mode -- same bug as 4387334
5878   // MacroAssembler::call_VM_leaf_base is perfectly safe and will
5879   // do proper 64bit abi
5880 
5881   NEEDS_CLEANUP;
5882   // Need to add stack banging before this runtime call if it needs to
5883   // be taken; however, there is no generic stack banging routine at
5884   // the MacroAssembler level
5885 
5886   MacroAssembler::call_VM_leaf_base(runtime_entry, 0);
5887 
5888 #ifdef _LP64
5889   movsd(Address(rsp, 0), xmm0);
5890   fld_d(Address(rsp, 0));
5891 #endif // _LP64
5892   addptr(rsp, sizeof(jdouble)*nb_args);
5893   if (num_fpu_regs_in_use > 1) {
5894     // Must save return value to stack and then restore entire FPU
5895     // stack except incoming arguments
5896     fstp_d(Address(rsp, incoming_argument_and_return_value_offset));
5897     for (int i = 0; i < num_fpu_regs_in_use - nb_args; i++) {
5898       fld_d(Address(rsp, 0));
5899       addptr(rsp, sizeof(jdouble));
5900     }
5901     fld_d(Address(rsp, (nb_args-1)*sizeof(jdouble)));
5902     addptr(rsp, sizeof(jdouble)*nb_args);
5903   }
5904 
5905   if (UseSSE == 1)  {
5906     for (int n = 0; n < 8; n++) {
5907       movflt(as_XMMRegister(n), Address(rsp, n*sizeof(jdouble)));
5908     }
5909     addptr(rsp, sizeof(jdouble)*8);
5910   } else if (UseSSE >= 2)  {
5911     // Restore whole 128bit (16 bytes) XMM registers
5912 #ifdef _LP64
5913   if (VM_Version::supports_evex()) {
5914     for (int n = 0; n < num_xmm_regs; n++) {
5915       vinsertf32x4h(as_XMMRegister(n), Address(rsp, n*16), 0);
5916     }
5917   } else {
5918     for (int n = 0; n < num_xmm_regs; n++) {
5919       movdqu(as_XMMRegister(n), Address(rsp, n*16));
5920     }
5921   }
5922 #else
5923   for (int n = 0; n < num_xmm_regs; n++) {
5924     movdqu(as_XMMRegister(n), Address(rsp, n*16));
5925   }
5926 #endif
5927     addptr(rsp, 16*num_xmm_regs);
5928 
5929 #ifdef COMPILER2
5930     if (MaxVectorSize > 16) {
5931       // Restore upper half of YMM registers.
5932       for (int n = 0; n < num_xmm_regs; n++) {
5933         vinsertf128h(as_XMMRegister(n), Address(rsp, n*16));
5934       }
5935       addptr(rsp, 16*num_xmm_regs);
5936       if(UseAVX > 2) {
5937         for (int n = 0; n < num_xmm_regs; n++) {
5938           vinsertf64x4h(as_XMMRegister(n), Address(rsp, n*32), 1);
5939         }
5940         addptr(rsp, 32*num_xmm_regs);
5941       }
5942     }
5943 #endif
5944   }
5945   popa();
5946 }
5947 
5948 static const double     pi_4 =  0.7853981633974483;
5949 
5950 void MacroAssembler::trigfunc(char trig, int num_fpu_regs_in_use) {
5951   // A hand-coded argument reduction for values in fabs(pi/4, pi/2)
5952   // was attempted in this code; unfortunately it appears that the
5953   // switch to 80-bit precision and back causes this to be
5954   // unprofitable compared with simply performing a runtime call if
5955   // the argument is out of the (-pi/4, pi/4) range.
5956 
5957   Register tmp = noreg;
5958   if (!VM_Version::supports_cmov()) {
5959     // fcmp needs a temporary so preserve rbx,
5960     tmp = rbx;
5961     push(tmp);
5962   }
5963 
5964   Label slow_case, done;
5965 
5966   ExternalAddress pi4_adr = (address)&pi_4;
5967   if (reachable(pi4_adr)) {
5968     // x ?<= pi/4
5969     fld_d(pi4_adr);
5970     fld_s(1);                // Stack:  X  PI/4  X
5971     fabs();                  // Stack: |X| PI/4  X
5972     fcmp(tmp);
5973     jcc(Assembler::above, slow_case);
5974 
5975     // fastest case: -pi/4 <= x <= pi/4
5976     switch(trig) {
5977     case 's':
5978       fsin();
5979       break;
5980     case 'c':
5981       fcos();
5982       break;
5983     case 't':
5984       ftan();
5985       break;
5986     default:
5987       assert(false, "bad intrinsic");
5988       break;
5989     }
5990     jmp(done);
5991   }
5992 
5993   // slow case: runtime call
5994   bind(slow_case);
5995 
5996   switch(trig) {
5997   case 's':
5998     {
5999       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dsin), 1, num_fpu_regs_in_use);
6000     }
6001     break;
6002   case 'c':
6003     {
6004       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dcos), 1, num_fpu_regs_in_use);
6005     }
6006     break;
6007   case 't':
6008     {
6009       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dtan), 1, num_fpu_regs_in_use);
6010     }
6011     break;
6012   default:
6013     assert(false, "bad intrinsic");
6014     break;
6015   }
6016 
6017   // Come here with result in F-TOS
6018   bind(done);
6019 
6020   if (tmp != noreg) {
6021     pop(tmp);
6022   }
6023 }
6024 
6025 
6026 // Look up the method for a megamorphic invokeinterface call.
6027 // The target method is determined by <intf_klass, itable_index>.
6028 // The receiver klass is in recv_klass.
6029 // On success, the result will be in method_result, and execution falls through.
6030 // On failure, execution transfers to the given label.
6031 void MacroAssembler::lookup_interface_method(Register recv_klass,
6032                                              Register intf_klass,
6033                                              RegisterOrConstant itable_index,
6034                                              Register method_result,
6035                                              Register scan_temp,
6036                                              Label& L_no_such_interface) {
6037   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
6038   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
6039          "caller must use same register for non-constant itable index as for method");
6040 
6041   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
6042   int vtable_base = InstanceKlass::vtable_start_offset() * wordSize;
6043   int itentry_off = itableMethodEntry::method_offset_in_bytes();
6044   int scan_step   = itableOffsetEntry::size() * wordSize;
6045   int vte_size    = vtableEntry::size() * wordSize;
6046   Address::ScaleFactor times_vte_scale = Address::times_ptr;
6047   assert(vte_size == wordSize, "else adjust times_vte_scale");
6048 
6049   movl(scan_temp, Address(recv_klass, InstanceKlass::vtable_length_offset() * wordSize));
6050 
6051   // %%% Could store the aligned, prescaled offset in the klassoop.
6052   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
6053   if (HeapWordsPerLong > 1) {
6054     // Round up to align_object_offset boundary
6055     // see code for InstanceKlass::start_of_itable!
6056     round_to(scan_temp, BytesPerLong);
6057   }
6058 
6059   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
6060   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
6061   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
6062 
6063   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
6064   //   if (scan->interface() == intf) {
6065   //     result = (klass + scan->offset() + itable_index);
6066   //   }
6067   // }
6068   Label search, found_method;
6069 
6070   for (int peel = 1; peel >= 0; peel--) {
6071     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
6072     cmpptr(intf_klass, method_result);
6073 
6074     if (peel) {
6075       jccb(Assembler::equal, found_method);
6076     } else {
6077       jccb(Assembler::notEqual, search);
6078       // (invert the test to fall through to found_method...)
6079     }
6080 
6081     if (!peel)  break;
6082 
6083     bind(search);
6084 
6085     // Check that the previous entry is non-null.  A null entry means that
6086     // the receiver class doesn't implement the interface, and wasn't the
6087     // same as when the caller was compiled.
6088     testptr(method_result, method_result);
6089     jcc(Assembler::zero, L_no_such_interface);
6090     addptr(scan_temp, scan_step);
6091   }
6092 
6093   bind(found_method);
6094 
6095   // Got a hit.
6096   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
6097   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
6098 }
6099 
6100 
6101 // virtual method calling
6102 void MacroAssembler::lookup_virtual_method(Register recv_klass,
6103                                            RegisterOrConstant vtable_index,
6104                                            Register method_result) {
6105   const int base = InstanceKlass::vtable_start_offset() * wordSize;
6106   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
6107   Address vtable_entry_addr(recv_klass,
6108                             vtable_index, Address::times_ptr,
6109                             base + vtableEntry::method_offset_in_bytes());
6110   movptr(method_result, vtable_entry_addr);
6111 }
6112 
6113 
6114 void MacroAssembler::check_klass_subtype(Register sub_klass,
6115                            Register super_klass,
6116                            Register temp_reg,
6117                            Label& L_success) {
6118   Label L_failure;
6119   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
6120   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
6121   bind(L_failure);
6122 }
6123 
6124 
6125 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
6126                                                    Register super_klass,
6127                                                    Register temp_reg,
6128                                                    Label* L_success,
6129                                                    Label* L_failure,
6130                                                    Label* L_slow_path,
6131                                         RegisterOrConstant super_check_offset) {
6132   assert_different_registers(sub_klass, super_klass, temp_reg);
6133   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
6134   if (super_check_offset.is_register()) {
6135     assert_different_registers(sub_klass, super_klass,
6136                                super_check_offset.as_register());
6137   } else if (must_load_sco) {
6138     assert(temp_reg != noreg, "supply either a temp or a register offset");
6139   }
6140 
6141   Label L_fallthrough;
6142   int label_nulls = 0;
6143   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
6144   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6145   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
6146   assert(label_nulls <= 1, "at most one NULL in the batch");
6147 
6148   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6149   int sco_offset = in_bytes(Klass::super_check_offset_offset());
6150   Address super_check_offset_addr(super_klass, sco_offset);
6151 
6152   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
6153   // range of a jccb.  If this routine grows larger, reconsider at
6154   // least some of these.
6155 #define local_jcc(assembler_cond, label)                                \
6156   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
6157   else                             jcc( assembler_cond, label) /*omit semi*/
6158 
6159   // Hacked jmp, which may only be used just before L_fallthrough.
6160 #define final_jmp(label)                                                \
6161   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
6162   else                            jmp(label)                /*omit semi*/
6163 
6164   // If the pointers are equal, we are done (e.g., String[] elements).
6165   // This self-check enables sharing of secondary supertype arrays among
6166   // non-primary types such as array-of-interface.  Otherwise, each such
6167   // type would need its own customized SSA.
6168   // We move this check to the front of the fast path because many
6169   // type checks are in fact trivially successful in this manner,
6170   // so we get a nicely predicted branch right at the start of the check.
6171   cmpptr(sub_klass, super_klass);
6172   local_jcc(Assembler::equal, *L_success);
6173 
6174   // Check the supertype display:
6175   if (must_load_sco) {
6176     // Positive movl does right thing on LP64.
6177     movl(temp_reg, super_check_offset_addr);
6178     super_check_offset = RegisterOrConstant(temp_reg);
6179   }
6180   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
6181   cmpptr(super_klass, super_check_addr); // load displayed supertype
6182 
6183   // This check has worked decisively for primary supers.
6184   // Secondary supers are sought in the super_cache ('super_cache_addr').
6185   // (Secondary supers are interfaces and very deeply nested subtypes.)
6186   // This works in the same check above because of a tricky aliasing
6187   // between the super_cache and the primary super display elements.
6188   // (The 'super_check_addr' can address either, as the case requires.)
6189   // Note that the cache is updated below if it does not help us find
6190   // what we need immediately.
6191   // So if it was a primary super, we can just fail immediately.
6192   // Otherwise, it's the slow path for us (no success at this point).
6193 
6194   if (super_check_offset.is_register()) {
6195     local_jcc(Assembler::equal, *L_success);
6196     cmpl(super_check_offset.as_register(), sc_offset);
6197     if (L_failure == &L_fallthrough) {
6198       local_jcc(Assembler::equal, *L_slow_path);
6199     } else {
6200       local_jcc(Assembler::notEqual, *L_failure);
6201       final_jmp(*L_slow_path);
6202     }
6203   } else if (super_check_offset.as_constant() == sc_offset) {
6204     // Need a slow path; fast failure is impossible.
6205     if (L_slow_path == &L_fallthrough) {
6206       local_jcc(Assembler::equal, *L_success);
6207     } else {
6208       local_jcc(Assembler::notEqual, *L_slow_path);
6209       final_jmp(*L_success);
6210     }
6211   } else {
6212     // No slow path; it's a fast decision.
6213     if (L_failure == &L_fallthrough) {
6214       local_jcc(Assembler::equal, *L_success);
6215     } else {
6216       local_jcc(Assembler::notEqual, *L_failure);
6217       final_jmp(*L_success);
6218     }
6219   }
6220 
6221   bind(L_fallthrough);
6222 
6223 #undef local_jcc
6224 #undef final_jmp
6225 }
6226 
6227 
6228 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
6229                                                    Register super_klass,
6230                                                    Register temp_reg,
6231                                                    Register temp2_reg,
6232                                                    Label* L_success,
6233                                                    Label* L_failure,
6234                                                    bool set_cond_codes) {
6235   assert_different_registers(sub_klass, super_klass, temp_reg);
6236   if (temp2_reg != noreg)
6237     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
6238 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
6239 
6240   Label L_fallthrough;
6241   int label_nulls = 0;
6242   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
6243   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6244   assert(label_nulls <= 1, "at most one NULL in the batch");
6245 
6246   // a couple of useful fields in sub_klass:
6247   int ss_offset = in_bytes(Klass::secondary_supers_offset());
6248   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6249   Address secondary_supers_addr(sub_klass, ss_offset);
6250   Address super_cache_addr(     sub_klass, sc_offset);
6251 
6252   // Do a linear scan of the secondary super-klass chain.
6253   // This code is rarely used, so simplicity is a virtue here.
6254   // The repne_scan instruction uses fixed registers, which we must spill.
6255   // Don't worry too much about pre-existing connections with the input regs.
6256 
6257   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
6258   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
6259 
6260   // Get super_klass value into rax (even if it was in rdi or rcx).
6261   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
6262   if (super_klass != rax || UseCompressedOops) {
6263     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
6264     mov(rax, super_klass);
6265   }
6266   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
6267   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
6268 
6269 #ifndef PRODUCT
6270   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
6271   ExternalAddress pst_counter_addr((address) pst_counter);
6272   NOT_LP64(  incrementl(pst_counter_addr) );
6273   LP64_ONLY( lea(rcx, pst_counter_addr) );
6274   LP64_ONLY( incrementl(Address(rcx, 0)) );
6275 #endif //PRODUCT
6276 
6277   // We will consult the secondary-super array.
6278   movptr(rdi, secondary_supers_addr);
6279   // Load the array length.  (Positive movl does right thing on LP64.)
6280   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
6281   // Skip to start of data.
6282   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
6283 
6284   // Scan RCX words at [RDI] for an occurrence of RAX.
6285   // Set NZ/Z based on last compare.
6286   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
6287   // not change flags (only scas instruction which is repeated sets flags).
6288   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
6289 
6290     testptr(rax,rax); // Set Z = 0
6291     repne_scan();
6292 
6293   // Unspill the temp. registers:
6294   if (pushed_rdi)  pop(rdi);
6295   if (pushed_rcx)  pop(rcx);
6296   if (pushed_rax)  pop(rax);
6297 
6298   if (set_cond_codes) {
6299     // Special hack for the AD files:  rdi is guaranteed non-zero.
6300     assert(!pushed_rdi, "rdi must be left non-NULL");
6301     // Also, the condition codes are properly set Z/NZ on succeed/failure.
6302   }
6303 
6304   if (L_failure == &L_fallthrough)
6305         jccb(Assembler::notEqual, *L_failure);
6306   else  jcc(Assembler::notEqual, *L_failure);
6307 
6308   // Success.  Cache the super we found and proceed in triumph.
6309   movptr(super_cache_addr, super_klass);
6310 
6311   if (L_success != &L_fallthrough) {
6312     jmp(*L_success);
6313   }
6314 
6315 #undef IS_A_TEMP
6316 
6317   bind(L_fallthrough);
6318 }
6319 
6320 
6321 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
6322   if (VM_Version::supports_cmov()) {
6323     cmovl(cc, dst, src);
6324   } else {
6325     Label L;
6326     jccb(negate_condition(cc), L);
6327     movl(dst, src);
6328     bind(L);
6329   }
6330 }
6331 
6332 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
6333   if (VM_Version::supports_cmov()) {
6334     cmovl(cc, dst, src);
6335   } else {
6336     Label L;
6337     jccb(negate_condition(cc), L);
6338     movl(dst, src);
6339     bind(L);
6340   }
6341 }
6342 
6343 void MacroAssembler::verify_oop(Register reg, const char* s) {
6344   if (!VerifyOops) return;
6345 
6346   // Pass register number to verify_oop_subroutine
6347   const char* b = NULL;
6348   {
6349     ResourceMark rm;
6350     stringStream ss;
6351     ss.print("verify_oop: %s: %s", reg->name(), s);
6352     b = code_string(ss.as_string());
6353   }
6354   BLOCK_COMMENT("verify_oop {");
6355 #ifdef _LP64
6356   push(rscratch1);                    // save r10, trashed by movptr()
6357 #endif
6358   push(rax);                          // save rax,
6359   push(reg);                          // pass register argument
6360   ExternalAddress buffer((address) b);
6361   // avoid using pushptr, as it modifies scratch registers
6362   // and our contract is not to modify anything
6363   movptr(rax, buffer.addr());
6364   push(rax);
6365   // call indirectly to solve generation ordering problem
6366   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6367   call(rax);
6368   // Caller pops the arguments (oop, message) and restores rax, r10
6369   BLOCK_COMMENT("} verify_oop");
6370 }
6371 
6372 
6373 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
6374                                                       Register tmp,
6375                                                       int offset) {
6376   intptr_t value = *delayed_value_addr;
6377   if (value != 0)
6378     return RegisterOrConstant(value + offset);
6379 
6380   // load indirectly to solve generation ordering problem
6381   movptr(tmp, ExternalAddress((address) delayed_value_addr));
6382 
6383 #ifdef ASSERT
6384   { Label L;
6385     testptr(tmp, tmp);
6386     if (WizardMode) {
6387       const char* buf = NULL;
6388       {
6389         ResourceMark rm;
6390         stringStream ss;
6391         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
6392         buf = code_string(ss.as_string());
6393       }
6394       jcc(Assembler::notZero, L);
6395       STOP(buf);
6396     } else {
6397       jccb(Assembler::notZero, L);
6398       hlt();
6399     }
6400     bind(L);
6401   }
6402 #endif
6403 
6404   if (offset != 0)
6405     addptr(tmp, offset);
6406 
6407   return RegisterOrConstant(tmp);
6408 }
6409 
6410 
6411 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6412                                          int extra_slot_offset) {
6413   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6414   int stackElementSize = Interpreter::stackElementSize;
6415   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6416 #ifdef ASSERT
6417   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6418   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6419 #endif
6420   Register             scale_reg    = noreg;
6421   Address::ScaleFactor scale_factor = Address::no_scale;
6422   if (arg_slot.is_constant()) {
6423     offset += arg_slot.as_constant() * stackElementSize;
6424   } else {
6425     scale_reg    = arg_slot.as_register();
6426     scale_factor = Address::times(stackElementSize);
6427   }
6428   offset += wordSize;           // return PC is on stack
6429   return Address(rsp, scale_reg, scale_factor, offset);
6430 }
6431 
6432 
6433 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6434   if (!VerifyOops) return;
6435 
6436   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6437   // Pass register number to verify_oop_subroutine
6438   const char* b = NULL;
6439   {
6440     ResourceMark rm;
6441     stringStream ss;
6442     ss.print("verify_oop_addr: %s", s);
6443     b = code_string(ss.as_string());
6444   }
6445 #ifdef _LP64
6446   push(rscratch1);                    // save r10, trashed by movptr()
6447 #endif
6448   push(rax);                          // save rax,
6449   // addr may contain rsp so we will have to adjust it based on the push
6450   // we just did (and on 64 bit we do two pushes)
6451   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6452   // stores rax into addr which is backwards of what was intended.
6453   if (addr.uses(rsp)) {
6454     lea(rax, addr);
6455     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6456   } else {
6457     pushptr(addr);
6458   }
6459 
6460   ExternalAddress buffer((address) b);
6461   // pass msg argument
6462   // avoid using pushptr, as it modifies scratch registers
6463   // and our contract is not to modify anything
6464   movptr(rax, buffer.addr());
6465   push(rax);
6466 
6467   // call indirectly to solve generation ordering problem
6468   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6469   call(rax);
6470   // Caller pops the arguments (addr, message) and restores rax, r10.
6471 }
6472 
6473 void MacroAssembler::verify_tlab() {
6474 #ifdef ASSERT
6475   if (UseTLAB && VerifyOops) {
6476     Label next, ok;
6477     Register t1 = rsi;
6478     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6479 
6480     push(t1);
6481     NOT_LP64(push(thread_reg));
6482     NOT_LP64(get_thread(thread_reg));
6483 
6484     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6485     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6486     jcc(Assembler::aboveEqual, next);
6487     STOP("assert(top >= start)");
6488     should_not_reach_here();
6489 
6490     bind(next);
6491     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6492     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6493     jcc(Assembler::aboveEqual, ok);
6494     STOP("assert(top <= end)");
6495     should_not_reach_here();
6496 
6497     bind(ok);
6498     NOT_LP64(pop(thread_reg));
6499     pop(t1);
6500   }
6501 #endif
6502 }
6503 
6504 class ControlWord {
6505  public:
6506   int32_t _value;
6507 
6508   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6509   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6510   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6511   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6512   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6513   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6514   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6515   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6516 
6517   void print() const {
6518     // rounding control
6519     const char* rc;
6520     switch (rounding_control()) {
6521       case 0: rc = "round near"; break;
6522       case 1: rc = "round down"; break;
6523       case 2: rc = "round up  "; break;
6524       case 3: rc = "chop      "; break;
6525     };
6526     // precision control
6527     const char* pc;
6528     switch (precision_control()) {
6529       case 0: pc = "24 bits "; break;
6530       case 1: pc = "reserved"; break;
6531       case 2: pc = "53 bits "; break;
6532       case 3: pc = "64 bits "; break;
6533     };
6534     // flags
6535     char f[9];
6536     f[0] = ' ';
6537     f[1] = ' ';
6538     f[2] = (precision   ()) ? 'P' : 'p';
6539     f[3] = (underflow   ()) ? 'U' : 'u';
6540     f[4] = (overflow    ()) ? 'O' : 'o';
6541     f[5] = (zero_divide ()) ? 'Z' : 'z';
6542     f[6] = (denormalized()) ? 'D' : 'd';
6543     f[7] = (invalid     ()) ? 'I' : 'i';
6544     f[8] = '\x0';
6545     // output
6546     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6547   }
6548 
6549 };
6550 
6551 class StatusWord {
6552  public:
6553   int32_t _value;
6554 
6555   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6556   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6557   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6558   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6559   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6560   int  top() const                     { return  (_value >> 11) & 7      ; }
6561   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6562   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6563   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6564   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6565   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6566   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6567   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6568   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6569 
6570   void print() const {
6571     // condition codes
6572     char c[5];
6573     c[0] = (C3()) ? '3' : '-';
6574     c[1] = (C2()) ? '2' : '-';
6575     c[2] = (C1()) ? '1' : '-';
6576     c[3] = (C0()) ? '0' : '-';
6577     c[4] = '\x0';
6578     // flags
6579     char f[9];
6580     f[0] = (error_status()) ? 'E' : '-';
6581     f[1] = (stack_fault ()) ? 'S' : '-';
6582     f[2] = (precision   ()) ? 'P' : '-';
6583     f[3] = (underflow   ()) ? 'U' : '-';
6584     f[4] = (overflow    ()) ? 'O' : '-';
6585     f[5] = (zero_divide ()) ? 'Z' : '-';
6586     f[6] = (denormalized()) ? 'D' : '-';
6587     f[7] = (invalid     ()) ? 'I' : '-';
6588     f[8] = '\x0';
6589     // output
6590     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6591   }
6592 
6593 };
6594 
6595 class TagWord {
6596  public:
6597   int32_t _value;
6598 
6599   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6600 
6601   void print() const {
6602     printf("%04x", _value & 0xFFFF);
6603   }
6604 
6605 };
6606 
6607 class FPU_Register {
6608  public:
6609   int32_t _m0;
6610   int32_t _m1;
6611   int16_t _ex;
6612 
6613   bool is_indefinite() const           {
6614     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6615   }
6616 
6617   void print() const {
6618     char  sign = (_ex < 0) ? '-' : '+';
6619     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6620     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6621   };
6622 
6623 };
6624 
6625 class FPU_State {
6626  public:
6627   enum {
6628     register_size       = 10,
6629     number_of_registers =  8,
6630     register_mask       =  7
6631   };
6632 
6633   ControlWord  _control_word;
6634   StatusWord   _status_word;
6635   TagWord      _tag_word;
6636   int32_t      _error_offset;
6637   int32_t      _error_selector;
6638   int32_t      _data_offset;
6639   int32_t      _data_selector;
6640   int8_t       _register[register_size * number_of_registers];
6641 
6642   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6643   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6644 
6645   const char* tag_as_string(int tag) const {
6646     switch (tag) {
6647       case 0: return "valid";
6648       case 1: return "zero";
6649       case 2: return "special";
6650       case 3: return "empty";
6651     }
6652     ShouldNotReachHere();
6653     return NULL;
6654   }
6655 
6656   void print() const {
6657     // print computation registers
6658     { int t = _status_word.top();
6659       for (int i = 0; i < number_of_registers; i++) {
6660         int j = (i - t) & register_mask;
6661         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6662         st(j)->print();
6663         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6664       }
6665     }
6666     printf("\n");
6667     // print control registers
6668     printf("ctrl = "); _control_word.print(); printf("\n");
6669     printf("stat = "); _status_word .print(); printf("\n");
6670     printf("tags = "); _tag_word    .print(); printf("\n");
6671   }
6672 
6673 };
6674 
6675 class Flag_Register {
6676  public:
6677   int32_t _value;
6678 
6679   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6680   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6681   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6682   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6683   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6684   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6685   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6686 
6687   void print() const {
6688     // flags
6689     char f[8];
6690     f[0] = (overflow       ()) ? 'O' : '-';
6691     f[1] = (direction      ()) ? 'D' : '-';
6692     f[2] = (sign           ()) ? 'S' : '-';
6693     f[3] = (zero           ()) ? 'Z' : '-';
6694     f[4] = (auxiliary_carry()) ? 'A' : '-';
6695     f[5] = (parity         ()) ? 'P' : '-';
6696     f[6] = (carry          ()) ? 'C' : '-';
6697     f[7] = '\x0';
6698     // output
6699     printf("%08x  flags = %s", _value, f);
6700   }
6701 
6702 };
6703 
6704 class IU_Register {
6705  public:
6706   int32_t _value;
6707 
6708   void print() const {
6709     printf("%08x  %11d", _value, _value);
6710   }
6711 
6712 };
6713 
6714 class IU_State {
6715  public:
6716   Flag_Register _eflags;
6717   IU_Register   _rdi;
6718   IU_Register   _rsi;
6719   IU_Register   _rbp;
6720   IU_Register   _rsp;
6721   IU_Register   _rbx;
6722   IU_Register   _rdx;
6723   IU_Register   _rcx;
6724   IU_Register   _rax;
6725 
6726   void print() const {
6727     // computation registers
6728     printf("rax,  = "); _rax.print(); printf("\n");
6729     printf("rbx,  = "); _rbx.print(); printf("\n");
6730     printf("rcx  = "); _rcx.print(); printf("\n");
6731     printf("rdx  = "); _rdx.print(); printf("\n");
6732     printf("rdi  = "); _rdi.print(); printf("\n");
6733     printf("rsi  = "); _rsi.print(); printf("\n");
6734     printf("rbp,  = "); _rbp.print(); printf("\n");
6735     printf("rsp  = "); _rsp.print(); printf("\n");
6736     printf("\n");
6737     // control registers
6738     printf("flgs = "); _eflags.print(); printf("\n");
6739   }
6740 };
6741 
6742 
6743 class CPU_State {
6744  public:
6745   FPU_State _fpu_state;
6746   IU_State  _iu_state;
6747 
6748   void print() const {
6749     printf("--------------------------------------------------\n");
6750     _iu_state .print();
6751     printf("\n");
6752     _fpu_state.print();
6753     printf("--------------------------------------------------\n");
6754   }
6755 
6756 };
6757 
6758 
6759 static void _print_CPU_state(CPU_State* state) {
6760   state->print();
6761 };
6762 
6763 
6764 void MacroAssembler::print_CPU_state() {
6765   push_CPU_state();
6766   push(rsp);                // pass CPU state
6767   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6768   addptr(rsp, wordSize);       // discard argument
6769   pop_CPU_state();
6770 }
6771 
6772 
6773 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6774   static int counter = 0;
6775   FPU_State* fs = &state->_fpu_state;
6776   counter++;
6777   // For leaf calls, only verify that the top few elements remain empty.
6778   // We only need 1 empty at the top for C2 code.
6779   if( stack_depth < 0 ) {
6780     if( fs->tag_for_st(7) != 3 ) {
6781       printf("FPR7 not empty\n");
6782       state->print();
6783       assert(false, "error");
6784       return false;
6785     }
6786     return true;                // All other stack states do not matter
6787   }
6788 
6789   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6790          "bad FPU control word");
6791 
6792   // compute stack depth
6793   int i = 0;
6794   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6795   int d = i;
6796   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6797   // verify findings
6798   if (i != FPU_State::number_of_registers) {
6799     // stack not contiguous
6800     printf("%s: stack not contiguous at ST%d\n", s, i);
6801     state->print();
6802     assert(false, "error");
6803     return false;
6804   }
6805   // check if computed stack depth corresponds to expected stack depth
6806   if (stack_depth < 0) {
6807     // expected stack depth is -stack_depth or less
6808     if (d > -stack_depth) {
6809       // too many elements on the stack
6810       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6811       state->print();
6812       assert(false, "error");
6813       return false;
6814     }
6815   } else {
6816     // expected stack depth is stack_depth
6817     if (d != stack_depth) {
6818       // wrong stack depth
6819       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6820       state->print();
6821       assert(false, "error");
6822       return false;
6823     }
6824   }
6825   // everything is cool
6826   return true;
6827 }
6828 
6829 
6830 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6831   if (!VerifyFPU) return;
6832   push_CPU_state();
6833   push(rsp);                // pass CPU state
6834   ExternalAddress msg((address) s);
6835   // pass message string s
6836   pushptr(msg.addr());
6837   push(stack_depth);        // pass stack depth
6838   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6839   addptr(rsp, 3 * wordSize);   // discard arguments
6840   // check for error
6841   { Label L;
6842     testl(rax, rax);
6843     jcc(Assembler::notZero, L);
6844     int3();                  // break if error condition
6845     bind(L);
6846   }
6847   pop_CPU_state();
6848 }
6849 
6850 void MacroAssembler::restore_cpu_control_state_after_jni() {
6851   // Either restore the MXCSR register after returning from the JNI Call
6852   // or verify that it wasn't changed (with -Xcheck:jni flag).
6853   if (VM_Version::supports_sse()) {
6854     if (RestoreMXCSROnJNICalls) {
6855       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6856     } else if (CheckJNICalls) {
6857       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6858     }
6859   }
6860   if (VM_Version::supports_avx()) {
6861     // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6862     vzeroupper();
6863   }
6864 
6865 #ifndef _LP64
6866   // Either restore the x87 floating pointer control word after returning
6867   // from the JNI call or verify that it wasn't changed.
6868   if (CheckJNICalls) {
6869     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6870   }
6871 #endif // _LP64
6872 }
6873 
6874 
6875 void MacroAssembler::load_klass(Register dst, Register src) {
6876 #ifdef _LP64
6877   if (UseCompressedClassPointers) {
6878     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6879     decode_klass_not_null(dst);
6880   } else
6881 #endif
6882     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6883 }
6884 
6885 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6886   load_klass(dst, src);
6887   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6888 }
6889 
6890 void MacroAssembler::store_klass(Register dst, Register src) {
6891 #ifdef _LP64
6892   if (UseCompressedClassPointers) {
6893     encode_klass_not_null(src);
6894     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6895   } else
6896 #endif
6897     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6898 }
6899 
6900 void MacroAssembler::load_heap_oop(Register dst, Address src) {
6901 #ifdef _LP64
6902   // FIXME: Must change all places where we try to load the klass.
6903   if (UseCompressedOops) {
6904     movl(dst, src);
6905     decode_heap_oop(dst);
6906   } else
6907 #endif
6908     movptr(dst, src);
6909 }
6910 
6911 // Doesn't do verfication, generates fixed size code
6912 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6913 #ifdef _LP64
6914   if (UseCompressedOops) {
6915     movl(dst, src);
6916     decode_heap_oop_not_null(dst);
6917   } else
6918 #endif
6919     movptr(dst, src);
6920 }
6921 
6922 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6923 #ifdef _LP64
6924   if (UseCompressedOops) {
6925     assert(!dst.uses(src), "not enough registers");
6926     encode_heap_oop(src);
6927     movl(dst, src);
6928   } else
6929 #endif
6930     movptr(dst, src);
6931 }
6932 
6933 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6934   assert_different_registers(src1, tmp);
6935 #ifdef _LP64
6936   if (UseCompressedOops) {
6937     bool did_push = false;
6938     if (tmp == noreg) {
6939       tmp = rax;
6940       push(tmp);
6941       did_push = true;
6942       assert(!src2.uses(rsp), "can't push");
6943     }
6944     load_heap_oop(tmp, src2);
6945     cmpptr(src1, tmp);
6946     if (did_push)  pop(tmp);
6947   } else
6948 #endif
6949     cmpptr(src1, src2);
6950 }
6951 
6952 // Used for storing NULLs.
6953 void MacroAssembler::store_heap_oop_null(Address dst) {
6954 #ifdef _LP64
6955   if (UseCompressedOops) {
6956     movl(dst, (int32_t)NULL_WORD);
6957   } else {
6958     movslq(dst, (int32_t)NULL_WORD);
6959   }
6960 #else
6961   movl(dst, (int32_t)NULL_WORD);
6962 #endif
6963 }
6964 
6965 #ifdef _LP64
6966 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6967   if (UseCompressedClassPointers) {
6968     // Store to klass gap in destination
6969     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6970   }
6971 }
6972 
6973 #ifdef ASSERT
6974 void MacroAssembler::verify_heapbase(const char* msg) {
6975   assert (UseCompressedOops, "should be compressed");
6976   assert (Universe::heap() != NULL, "java heap should be initialized");
6977   if (CheckCompressedOops) {
6978     Label ok;
6979     push(rscratch1); // cmpptr trashes rscratch1
6980     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6981     jcc(Assembler::equal, ok);
6982     STOP(msg);
6983     bind(ok);
6984     pop(rscratch1);
6985   }
6986 }
6987 #endif
6988 
6989 // Algorithm must match oop.inline.hpp encode_heap_oop.
6990 void MacroAssembler::encode_heap_oop(Register r) {
6991 #ifdef ASSERT
6992   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6993 #endif
6994   verify_oop(r, "broken oop in encode_heap_oop");
6995   if (Universe::narrow_oop_base() == NULL) {
6996     if (Universe::narrow_oop_shift() != 0) {
6997       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6998       shrq(r, LogMinObjAlignmentInBytes);
6999     }
7000     return;
7001   }
7002   testq(r, r);
7003   cmovq(Assembler::equal, r, r12_heapbase);
7004   subq(r, r12_heapbase);
7005   shrq(r, LogMinObjAlignmentInBytes);
7006 }
7007 
7008 void MacroAssembler::encode_heap_oop_not_null(Register r) {
7009 #ifdef ASSERT
7010   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
7011   if (CheckCompressedOops) {
7012     Label ok;
7013     testq(r, r);
7014     jcc(Assembler::notEqual, ok);
7015     STOP("null oop passed to encode_heap_oop_not_null");
7016     bind(ok);
7017   }
7018 #endif
7019   verify_oop(r, "broken oop in encode_heap_oop_not_null");
7020   if (Universe::narrow_oop_base() != NULL) {
7021     subq(r, r12_heapbase);
7022   }
7023   if (Universe::narrow_oop_shift() != 0) {
7024     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7025     shrq(r, LogMinObjAlignmentInBytes);
7026   }
7027 }
7028 
7029 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
7030 #ifdef ASSERT
7031   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
7032   if (CheckCompressedOops) {
7033     Label ok;
7034     testq(src, src);
7035     jcc(Assembler::notEqual, ok);
7036     STOP("null oop passed to encode_heap_oop_not_null2");
7037     bind(ok);
7038   }
7039 #endif
7040   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
7041   if (dst != src) {
7042     movq(dst, src);
7043   }
7044   if (Universe::narrow_oop_base() != NULL) {
7045     subq(dst, r12_heapbase);
7046   }
7047   if (Universe::narrow_oop_shift() != 0) {
7048     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7049     shrq(dst, LogMinObjAlignmentInBytes);
7050   }
7051 }
7052 
7053 void  MacroAssembler::decode_heap_oop(Register r) {
7054 #ifdef ASSERT
7055   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
7056 #endif
7057   if (Universe::narrow_oop_base() == NULL) {
7058     if (Universe::narrow_oop_shift() != 0) {
7059       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7060       shlq(r, LogMinObjAlignmentInBytes);
7061     }
7062   } else {
7063     Label done;
7064     shlq(r, LogMinObjAlignmentInBytes);
7065     jccb(Assembler::equal, done);
7066     addq(r, r12_heapbase);
7067     bind(done);
7068   }
7069   verify_oop(r, "broken oop in decode_heap_oop");
7070 }
7071 
7072 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
7073   // Note: it will change flags
7074   assert (UseCompressedOops, "should only be used for compressed headers");
7075   assert (Universe::heap() != NULL, "java heap should be initialized");
7076   // Cannot assert, unverified entry point counts instructions (see .ad file)
7077   // vtableStubs also counts instructions in pd_code_size_limit.
7078   // Also do not verify_oop as this is called by verify_oop.
7079   if (Universe::narrow_oop_shift() != 0) {
7080     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7081     shlq(r, LogMinObjAlignmentInBytes);
7082     if (Universe::narrow_oop_base() != NULL) {
7083       addq(r, r12_heapbase);
7084     }
7085   } else {
7086     assert (Universe::narrow_oop_base() == NULL, "sanity");
7087   }
7088 }
7089 
7090 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
7091   // Note: it will change flags
7092   assert (UseCompressedOops, "should only be used for compressed headers");
7093   assert (Universe::heap() != NULL, "java heap should be initialized");
7094   // Cannot assert, unverified entry point counts instructions (see .ad file)
7095   // vtableStubs also counts instructions in pd_code_size_limit.
7096   // Also do not verify_oop as this is called by verify_oop.
7097   if (Universe::narrow_oop_shift() != 0) {
7098     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7099     if (LogMinObjAlignmentInBytes == Address::times_8) {
7100       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
7101     } else {
7102       if (dst != src) {
7103         movq(dst, src);
7104       }
7105       shlq(dst, LogMinObjAlignmentInBytes);
7106       if (Universe::narrow_oop_base() != NULL) {
7107         addq(dst, r12_heapbase);
7108       }
7109     }
7110   } else {
7111     assert (Universe::narrow_oop_base() == NULL, "sanity");
7112     if (dst != src) {
7113       movq(dst, src);
7114     }
7115   }
7116 }
7117 
7118 void MacroAssembler::encode_klass_not_null(Register r) {
7119   if (Universe::narrow_klass_base() != NULL) {
7120     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7121     assert(r != r12_heapbase, "Encoding a klass in r12");
7122     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7123     subq(r, r12_heapbase);
7124   }
7125   if (Universe::narrow_klass_shift() != 0) {
7126     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7127     shrq(r, LogKlassAlignmentInBytes);
7128   }
7129   if (Universe::narrow_klass_base() != NULL) {
7130     reinit_heapbase();
7131   }
7132 }
7133 
7134 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
7135   if (dst == src) {
7136     encode_klass_not_null(src);
7137   } else {
7138     if (Universe::narrow_klass_base() != NULL) {
7139       mov64(dst, (int64_t)Universe::narrow_klass_base());
7140       negq(dst);
7141       addq(dst, src);
7142     } else {
7143       movptr(dst, src);
7144     }
7145     if (Universe::narrow_klass_shift() != 0) {
7146       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7147       shrq(dst, LogKlassAlignmentInBytes);
7148     }
7149   }
7150 }
7151 
7152 // Function instr_size_for_decode_klass_not_null() counts the instructions
7153 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
7154 // when (Universe::heap() != NULL).  Hence, if the instructions they
7155 // generate change, then this method needs to be updated.
7156 int MacroAssembler::instr_size_for_decode_klass_not_null() {
7157   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
7158   if (Universe::narrow_klass_base() != NULL) {
7159     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
7160     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
7161   } else {
7162     // longest load decode klass function, mov64, leaq
7163     return 16;
7164   }
7165 }
7166 
7167 // !!! If the instructions that get generated here change then function
7168 // instr_size_for_decode_klass_not_null() needs to get updated.
7169 void  MacroAssembler::decode_klass_not_null(Register r) {
7170   // Note: it will change flags
7171   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7172   assert(r != r12_heapbase, "Decoding a klass in r12");
7173   // Cannot assert, unverified entry point counts instructions (see .ad file)
7174   // vtableStubs also counts instructions in pd_code_size_limit.
7175   // Also do not verify_oop as this is called by verify_oop.
7176   if (Universe::narrow_klass_shift() != 0) {
7177     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7178     shlq(r, LogKlassAlignmentInBytes);
7179   }
7180   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7181   if (Universe::narrow_klass_base() != NULL) {
7182     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7183     addq(r, r12_heapbase);
7184     reinit_heapbase();
7185   }
7186 }
7187 
7188 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
7189   // Note: it will change flags
7190   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7191   if (dst == src) {
7192     decode_klass_not_null(dst);
7193   } else {
7194     // Cannot assert, unverified entry point counts instructions (see .ad file)
7195     // vtableStubs also counts instructions in pd_code_size_limit.
7196     // Also do not verify_oop as this is called by verify_oop.
7197     mov64(dst, (int64_t)Universe::narrow_klass_base());
7198     if (Universe::narrow_klass_shift() != 0) {
7199       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7200       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
7201       leaq(dst, Address(dst, src, Address::times_8, 0));
7202     } else {
7203       addq(dst, src);
7204     }
7205   }
7206 }
7207 
7208 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
7209   assert (UseCompressedOops, "should only be used for compressed headers");
7210   assert (Universe::heap() != NULL, "java heap should be initialized");
7211   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7212   int oop_index = oop_recorder()->find_index(obj);
7213   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7214   mov_narrow_oop(dst, oop_index, rspec);
7215 }
7216 
7217 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
7218   assert (UseCompressedOops, "should only be used for compressed headers");
7219   assert (Universe::heap() != NULL, "java heap should be initialized");
7220   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7221   int oop_index = oop_recorder()->find_index(obj);
7222   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7223   mov_narrow_oop(dst, oop_index, rspec);
7224 }
7225 
7226 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
7227   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7228   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7229   int klass_index = oop_recorder()->find_index(k);
7230   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7231   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7232 }
7233 
7234 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
7235   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7236   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7237   int klass_index = oop_recorder()->find_index(k);
7238   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7239   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7240 }
7241 
7242 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
7243   assert (UseCompressedOops, "should only be used for compressed headers");
7244   assert (Universe::heap() != NULL, "java heap should be initialized");
7245   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7246   int oop_index = oop_recorder()->find_index(obj);
7247   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7248   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7249 }
7250 
7251 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
7252   assert (UseCompressedOops, "should only be used for compressed headers");
7253   assert (Universe::heap() != NULL, "java heap should be initialized");
7254   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7255   int oop_index = oop_recorder()->find_index(obj);
7256   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7257   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7258 }
7259 
7260 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
7261   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7262   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7263   int klass_index = oop_recorder()->find_index(k);
7264   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7265   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7266 }
7267 
7268 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
7269   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7270   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7271   int klass_index = oop_recorder()->find_index(k);
7272   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7273   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7274 }
7275 
7276 void MacroAssembler::reinit_heapbase() {
7277   if (UseCompressedOops || UseCompressedClassPointers) {
7278     if (Universe::heap() != NULL) {
7279       if (Universe::narrow_oop_base() == NULL) {
7280         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
7281       } else {
7282         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
7283       }
7284     } else {
7285       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7286     }
7287   }
7288 }
7289 
7290 #endif // _LP64
7291 
7292 
7293 // C2 compiled method's prolog code.
7294 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
7295 
7296   // WARNING: Initial instruction MUST be 5 bytes or longer so that
7297   // NativeJump::patch_verified_entry will be able to patch out the entry
7298   // code safely. The push to verify stack depth is ok at 5 bytes,
7299   // the frame allocation can be either 3 or 6 bytes. So if we don't do
7300   // stack bang then we must use the 6 byte frame allocation even if
7301   // we have no frame. :-(
7302   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
7303 
7304   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
7305   // Remove word for return addr
7306   framesize -= wordSize;
7307   stack_bang_size -= wordSize;
7308 
7309   // Calls to C2R adapters often do not accept exceptional returns.
7310   // We require that their callers must bang for them.  But be careful, because
7311   // some VM calls (such as call site linkage) can use several kilobytes of
7312   // stack.  But the stack safety zone should account for that.
7313   // See bugs 4446381, 4468289, 4497237.
7314   if (stack_bang_size > 0) {
7315     generate_stack_overflow_check(stack_bang_size);
7316 
7317     // We always push rbp, so that on return to interpreter rbp, will be
7318     // restored correctly and we can correct the stack.
7319     push(rbp);
7320     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7321     if (PreserveFramePointer) {
7322       mov(rbp, rsp);
7323     }
7324     // Remove word for ebp
7325     framesize -= wordSize;
7326 
7327     // Create frame
7328     if (framesize) {
7329       subptr(rsp, framesize);
7330     }
7331   } else {
7332     // Create frame (force generation of a 4 byte immediate value)
7333     subptr_imm32(rsp, framesize);
7334 
7335     // Save RBP register now.
7336     framesize -= wordSize;
7337     movptr(Address(rsp, framesize), rbp);
7338     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7339     if (PreserveFramePointer) {
7340       movptr(rbp, rsp);
7341       if (framesize > 0) {
7342         addptr(rbp, framesize);
7343       }
7344     }
7345   }
7346 
7347   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
7348     framesize -= wordSize;
7349     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
7350   }
7351 
7352 #ifndef _LP64
7353   // If method sets FPU control word do it now
7354   if (fp_mode_24b) {
7355     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
7356   }
7357   if (UseSSE >= 2 && VerifyFPU) {
7358     verify_FPU(0, "FPU stack must be clean on entry");
7359   }
7360 #endif
7361 
7362 #ifdef ASSERT
7363   if (VerifyStackAtCalls) {
7364     Label L;
7365     push(rax);
7366     mov(rax, rsp);
7367     andptr(rax, StackAlignmentInBytes-1);
7368     cmpptr(rax, StackAlignmentInBytes-wordSize);
7369     pop(rax);
7370     jcc(Assembler::equal, L);
7371     STOP("Stack is not properly aligned!");
7372     bind(L);
7373   }
7374 #endif
7375 
7376 }
7377 
7378 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp) {
7379   // cnt - number of qwords (8-byte words).
7380   // base - start address, qword aligned.
7381   assert(base==rdi, "base register must be edi for rep stos");
7382   assert(tmp==rax,   "tmp register must be eax for rep stos");
7383   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
7384 
7385   xorptr(tmp, tmp);
7386   if (UseFastStosb) {
7387     shlptr(cnt,3); // convert to number of bytes
7388     rep_stosb();
7389   } else {
7390     NOT_LP64(shlptr(cnt,1);) // convert to number of dwords for 32-bit VM
7391     rep_stos();
7392   }
7393 }
7394 
7395 #ifdef COMPILER2
7396 
7397 // IndexOf for constant substrings with size >= 8 chars
7398 // which don't need to be loaded through stack.
7399 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7400                                       Register cnt1, Register cnt2,
7401                                       int int_cnt2,  Register result,
7402                                       XMMRegister vec, Register tmp,
7403                                       int ae) {
7404   ShortBranchVerifier sbv(this);
7405   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7406   assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7407   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7408 
7409   // This method uses the pcmpestri instruction with bound registers
7410   //   inputs:
7411   //     xmm - substring
7412   //     rax - substring length (elements count)
7413   //     mem - scanned string
7414   //     rdx - string length (elements count)
7415   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7416   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7417   //   outputs:
7418   //     rcx - matched index in string
7419   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7420   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7421   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7422   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7423   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7424 
7425   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7426         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7427         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7428 
7429   // Note, inline_string_indexOf() generates checks:
7430   // if (substr.count > string.count) return -1;
7431   // if (substr.count == 0) return 0;
7432   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7433 
7434   // Load substring.
7435   if (ae == StrIntrinsicNode::UL) {
7436     pmovzxbw(vec, Address(str2, 0));
7437   } else {
7438     movdqu(vec, Address(str2, 0));
7439   }
7440   movl(cnt2, int_cnt2);
7441   movptr(result, str1); // string addr
7442 
7443   if (int_cnt2 > stride) {
7444     jmpb(SCAN_TO_SUBSTR);
7445 
7446     // Reload substr for rescan, this code
7447     // is executed only for large substrings (> 8 chars)
7448     bind(RELOAD_SUBSTR);
7449     if (ae == StrIntrinsicNode::UL) {
7450       pmovzxbw(vec, Address(str2, 0));
7451     } else {
7452       movdqu(vec, Address(str2, 0));
7453     }
7454     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7455 
7456     bind(RELOAD_STR);
7457     // We came here after the beginning of the substring was
7458     // matched but the rest of it was not so we need to search
7459     // again. Start from the next element after the previous match.
7460 
7461     // cnt2 is number of substring reminding elements and
7462     // cnt1 is number of string reminding elements when cmp failed.
7463     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7464     subl(cnt1, cnt2);
7465     addl(cnt1, int_cnt2);
7466     movl(cnt2, int_cnt2); // Now restore cnt2
7467 
7468     decrementl(cnt1);     // Shift to next element
7469     cmpl(cnt1, cnt2);
7470     jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7471 
7472     addptr(result, (1<<scale1));
7473 
7474   } // (int_cnt2 > 8)
7475 
7476   // Scan string for start of substr in 16-byte vectors
7477   bind(SCAN_TO_SUBSTR);
7478   pcmpestri(vec, Address(result, 0), mode);
7479   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7480   subl(cnt1, stride);
7481   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7482   cmpl(cnt1, cnt2);
7483   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7484   addptr(result, 16);
7485   jmpb(SCAN_TO_SUBSTR);
7486 
7487   // Found a potential substr
7488   bind(FOUND_CANDIDATE);
7489   // Matched whole vector if first element matched (tmp(rcx) == 0).
7490   if (int_cnt2 == stride) {
7491     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7492   } else { // int_cnt2 > 8
7493     jccb(Assembler::overflow, FOUND_SUBSTR);
7494   }
7495   // After pcmpestri tmp(rcx) contains matched element index
7496   // Compute start addr of substr
7497   lea(result, Address(result, tmp, scale1));
7498 
7499   // Make sure string is still long enough
7500   subl(cnt1, tmp);
7501   cmpl(cnt1, cnt2);
7502   if (int_cnt2 == stride) {
7503     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7504   } else { // int_cnt2 > 8
7505     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7506   }
7507   // Left less then substring.
7508 
7509   bind(RET_NOT_FOUND);
7510   movl(result, -1);
7511   jmpb(EXIT);
7512 
7513   if (int_cnt2 > stride) {
7514     // This code is optimized for the case when whole substring
7515     // is matched if its head is matched.
7516     bind(MATCH_SUBSTR_HEAD);
7517     pcmpestri(vec, Address(result, 0), mode);
7518     // Reload only string if does not match
7519     jccb(Assembler::noOverflow, RELOAD_STR); // OF == 0
7520 
7521     Label CONT_SCAN_SUBSTR;
7522     // Compare the rest of substring (> 8 chars).
7523     bind(FOUND_SUBSTR);
7524     // First 8 chars are already matched.
7525     negptr(cnt2);
7526     addptr(cnt2, stride);
7527 
7528     bind(SCAN_SUBSTR);
7529     subl(cnt1, stride);
7530     cmpl(cnt2, -stride); // Do not read beyond substring
7531     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7532     // Back-up strings to avoid reading beyond substring:
7533     // cnt1 = cnt1 - cnt2 + 8
7534     addl(cnt1, cnt2); // cnt2 is negative
7535     addl(cnt1, stride);
7536     movl(cnt2, stride); negptr(cnt2);
7537     bind(CONT_SCAN_SUBSTR);
7538     if (int_cnt2 < (int)G) {
7539       int tail_off1 = int_cnt2<<scale1;
7540       int tail_off2 = int_cnt2<<scale2;
7541       if (ae == StrIntrinsicNode::UL) {
7542         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7543       } else {
7544         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7545       }
7546       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7547     } else {
7548       // calculate index in register to avoid integer overflow (int_cnt2*2)
7549       movl(tmp, int_cnt2);
7550       addptr(tmp, cnt2);
7551       if (ae == StrIntrinsicNode::UL) {
7552         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7553       } else {
7554         movdqu(vec, Address(str2, tmp, scale2, 0));
7555       }
7556       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7557     }
7558     // Need to reload strings pointers if not matched whole vector
7559     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7560     addptr(cnt2, stride);
7561     jcc(Assembler::negative, SCAN_SUBSTR);
7562     // Fall through if found full substring
7563 
7564   } // (int_cnt2 > 8)
7565 
7566   bind(RET_FOUND);
7567   // Found result if we matched full small substring.
7568   // Compute substr offset
7569   subptr(result, str1);
7570   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7571     shrl(result, 1); // index
7572   }
7573   bind(EXIT);
7574 
7575 } // string_indexofC8
7576 
7577 // Small strings are loaded through stack if they cross page boundary.
7578 void MacroAssembler::string_indexof(Register str1, Register str2,
7579                                     Register cnt1, Register cnt2,
7580                                     int int_cnt2,  Register result,
7581                                     XMMRegister vec, Register tmp,
7582                                     int ae) {
7583   ShortBranchVerifier sbv(this);
7584   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7585   assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7586   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7587 
7588   //
7589   // int_cnt2 is length of small (< 8 chars) constant substring
7590   // or (-1) for non constant substring in which case its length
7591   // is in cnt2 register.
7592   //
7593   // Note, inline_string_indexOf() generates checks:
7594   // if (substr.count > string.count) return -1;
7595   // if (substr.count == 0) return 0;
7596   //
7597   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7598   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7599   // This method uses the pcmpestri instruction with bound registers
7600   //   inputs:
7601   //     xmm - substring
7602   //     rax - substring length (elements count)
7603   //     mem - scanned string
7604   //     rdx - string length (elements count)
7605   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7606   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7607   //   outputs:
7608   //     rcx - matched index in string
7609   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7610   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7611   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7612   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7613 
7614   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7615         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7616         FOUND_CANDIDATE;
7617 
7618   { //========================================================
7619     // We don't know where these strings are located
7620     // and we can't read beyond them. Load them through stack.
7621     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7622 
7623     movptr(tmp, rsp); // save old SP
7624 
7625     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7626       if (int_cnt2 == (1>>scale2)) { // One byte
7627         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7628         load_unsigned_byte(result, Address(str2, 0));
7629         movdl(vec, result); // move 32 bits
7630       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7631         // Not enough header space in 32-bit VM: 12+3 = 15.
7632         movl(result, Address(str2, -1));
7633         shrl(result, 8);
7634         movdl(vec, result); // move 32 bits
7635       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7636         load_unsigned_short(result, Address(str2, 0));
7637         movdl(vec, result); // move 32 bits
7638       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7639         movdl(vec, Address(str2, 0)); // move 32 bits
7640       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7641         movq(vec, Address(str2, 0));  // move 64 bits
7642       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7643         // Array header size is 12 bytes in 32-bit VM
7644         // + 6 bytes for 3 chars == 18 bytes,
7645         // enough space to load vec and shift.
7646         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7647         if (ae == StrIntrinsicNode::UL) {
7648           int tail_off = int_cnt2-8;
7649           pmovzxbw(vec, Address(str2, tail_off));
7650           psrldq(vec, -2*tail_off);
7651         }
7652         else {
7653           int tail_off = int_cnt2*(1<<scale2);
7654           movdqu(vec, Address(str2, tail_off-16));
7655           psrldq(vec, 16-tail_off);
7656         }
7657       }
7658     } else { // not constant substring
7659       cmpl(cnt2, stride);
7660       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7661 
7662       // We can read beyond string if srt+16 does not cross page boundary
7663       // since heaps are aligned and mapped by pages.
7664       assert(os::vm_page_size() < (int)G, "default page should be small");
7665       movl(result, str2); // We need only low 32 bits
7666       andl(result, (os::vm_page_size()-1));
7667       cmpl(result, (os::vm_page_size()-16));
7668       jccb(Assembler::belowEqual, CHECK_STR);
7669 
7670       // Move small strings to stack to allow load 16 bytes into vec.
7671       subptr(rsp, 16);
7672       int stk_offset = wordSize-(1<<scale2);
7673       push(cnt2);
7674 
7675       bind(COPY_SUBSTR);
7676       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7677         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7678         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7679       } else if (ae == StrIntrinsicNode::UU) {
7680         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7681         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7682       }
7683       decrement(cnt2);
7684       jccb(Assembler::notZero, COPY_SUBSTR);
7685 
7686       pop(cnt2);
7687       movptr(str2, rsp);  // New substring address
7688     } // non constant
7689 
7690     bind(CHECK_STR);
7691     cmpl(cnt1, stride);
7692     jccb(Assembler::aboveEqual, BIG_STRINGS);
7693 
7694     // Check cross page boundary.
7695     movl(result, str1); // We need only low 32 bits
7696     andl(result, (os::vm_page_size()-1));
7697     cmpl(result, (os::vm_page_size()-16));
7698     jccb(Assembler::belowEqual, BIG_STRINGS);
7699 
7700     subptr(rsp, 16);
7701     int stk_offset = -(1<<scale1);
7702     if (int_cnt2 < 0) { // not constant
7703       push(cnt2);
7704       stk_offset += wordSize;
7705     }
7706     movl(cnt2, cnt1);
7707 
7708     bind(COPY_STR);
7709     if (ae == StrIntrinsicNode::LL) {
7710       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7711       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7712     } else {
7713       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7714       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7715     }
7716     decrement(cnt2);
7717     jccb(Assembler::notZero, COPY_STR);
7718 
7719     if (int_cnt2 < 0) { // not constant
7720       pop(cnt2);
7721     }
7722     movptr(str1, rsp);  // New string address
7723 
7724     bind(BIG_STRINGS);
7725     // Load substring.
7726     if (int_cnt2 < 0) { // -1
7727       if (ae == StrIntrinsicNode::UL) {
7728         pmovzxbw(vec, Address(str2, 0));
7729       } else {
7730         movdqu(vec, Address(str2, 0));
7731       }
7732       push(cnt2);       // substr count
7733       push(str2);       // substr addr
7734       push(str1);       // string addr
7735     } else {
7736       // Small (< 8 chars) constant substrings are loaded already.
7737       movl(cnt2, int_cnt2);
7738     }
7739     push(tmp);  // original SP
7740 
7741   } // Finished loading
7742 
7743   //========================================================
7744   // Start search
7745   //
7746 
7747   movptr(result, str1); // string addr
7748 
7749   if (int_cnt2  < 0) {  // Only for non constant substring
7750     jmpb(SCAN_TO_SUBSTR);
7751 
7752     // SP saved at sp+0
7753     // String saved at sp+1*wordSize
7754     // Substr saved at sp+2*wordSize
7755     // Substr count saved at sp+3*wordSize
7756 
7757     // Reload substr for rescan, this code
7758     // is executed only for large substrings (> 8 chars)
7759     bind(RELOAD_SUBSTR);
7760     movptr(str2, Address(rsp, 2*wordSize));
7761     movl(cnt2, Address(rsp, 3*wordSize));
7762     if (ae == StrIntrinsicNode::UL) {
7763       pmovzxbw(vec, Address(str2, 0));
7764     } else {
7765       movdqu(vec, Address(str2, 0));
7766     }
7767     // We came here after the beginning of the substring was
7768     // matched but the rest of it was not so we need to search
7769     // again. Start from the next element after the previous match.
7770     subptr(str1, result); // Restore counter
7771     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7772       shrl(str1, 1);
7773     }
7774     addl(cnt1, str1);
7775     decrementl(cnt1);   // Shift to next element
7776     cmpl(cnt1, cnt2);
7777     jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7778 
7779     addptr(result, (1<<scale1));
7780   } // non constant
7781 
7782   // Scan string for start of substr in 16-byte vectors
7783   bind(SCAN_TO_SUBSTR);
7784   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7785   pcmpestri(vec, Address(result, 0), mode);
7786   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7787   subl(cnt1, stride);
7788   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7789   cmpl(cnt1, cnt2);
7790   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7791   addptr(result, 16);
7792 
7793   bind(ADJUST_STR);
7794   cmpl(cnt1, stride); // Do not read beyond string
7795   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7796   // Back-up string to avoid reading beyond string.
7797   lea(result, Address(result, cnt1, scale1, -16));
7798   movl(cnt1, stride);
7799   jmpb(SCAN_TO_SUBSTR);
7800 
7801   // Found a potential substr
7802   bind(FOUND_CANDIDATE);
7803   // After pcmpestri tmp(rcx) contains matched element index
7804 
7805   // Make sure string is still long enough
7806   subl(cnt1, tmp);
7807   cmpl(cnt1, cnt2);
7808   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7809   // Left less then substring.
7810 
7811   bind(RET_NOT_FOUND);
7812   movl(result, -1);
7813   jmpb(CLEANUP);
7814 
7815   bind(FOUND_SUBSTR);
7816   // Compute start addr of substr
7817   lea(result, Address(result, tmp, scale1));
7818   if (int_cnt2 > 0) { // Constant substring
7819     // Repeat search for small substring (< 8 chars)
7820     // from new point without reloading substring.
7821     // Have to check that we don't read beyond string.
7822     cmpl(tmp, stride-int_cnt2);
7823     jccb(Assembler::greater, ADJUST_STR);
7824     // Fall through if matched whole substring.
7825   } else { // non constant
7826     assert(int_cnt2 == -1, "should be != 0");
7827 
7828     addl(tmp, cnt2);
7829     // Found result if we matched whole substring.
7830     cmpl(tmp, stride);
7831     jccb(Assembler::lessEqual, RET_FOUND);
7832 
7833     // Repeat search for small substring (<= 8 chars)
7834     // from new point 'str1' without reloading substring.
7835     cmpl(cnt2, stride);
7836     // Have to check that we don't read beyond string.
7837     jccb(Assembler::lessEqual, ADJUST_STR);
7838 
7839     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7840     // Compare the rest of substring (> 8 chars).
7841     movptr(str1, result);
7842 
7843     cmpl(tmp, cnt2);
7844     // First 8 chars are already matched.
7845     jccb(Assembler::equal, CHECK_NEXT);
7846 
7847     bind(SCAN_SUBSTR);
7848     pcmpestri(vec, Address(str1, 0), mode);
7849     // Need to reload strings pointers if not matched whole vector
7850     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7851 
7852     bind(CHECK_NEXT);
7853     subl(cnt2, stride);
7854     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7855     addptr(str1, 16);
7856     if (ae == StrIntrinsicNode::UL) {
7857       addptr(str2, 8);
7858     } else {
7859       addptr(str2, 16);
7860     }
7861     subl(cnt1, stride);
7862     cmpl(cnt2, stride); // Do not read beyond substring
7863     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7864     // Back-up strings to avoid reading beyond substring.
7865 
7866     if (ae == StrIntrinsicNode::UL) {
7867       lea(str2, Address(str2, cnt2, scale2, -8));
7868       lea(str1, Address(str1, cnt2, scale1, -16));
7869     } else {
7870       lea(str2, Address(str2, cnt2, scale2, -16));
7871       lea(str1, Address(str1, cnt2, scale1, -16));
7872     }
7873     subl(cnt1, cnt2);
7874     movl(cnt2, stride);
7875     addl(cnt1, stride);
7876     bind(CONT_SCAN_SUBSTR);
7877     if (ae == StrIntrinsicNode::UL) {
7878       pmovzxbw(vec, Address(str2, 0));
7879     } else {
7880       movdqu(vec, Address(str2, 0));
7881     }
7882     jmpb(SCAN_SUBSTR);
7883 
7884     bind(RET_FOUND_LONG);
7885     movptr(str1, Address(rsp, wordSize));
7886   } // non constant
7887 
7888   bind(RET_FOUND);
7889   // Compute substr offset
7890   subptr(result, str1);
7891   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7892     shrl(result, 1); // index
7893   }
7894   bind(CLEANUP);
7895   pop(rsp); // restore SP
7896 
7897 } // string_indexof
7898 
7899 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7900                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7901   ShortBranchVerifier sbv(this);
7902   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7903   assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7904 
7905   int stride = 8;
7906 
7907   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7908         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7909         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7910         FOUND_SEQ_CHAR, DONE_LABEL;
7911 
7912   movptr(result, str1);
7913   if (UseAVX >= 2) {
7914     cmpl(cnt1, stride);
7915     jccb(Assembler::less, SCAN_TO_CHAR_LOOP);
7916     cmpl(cnt1, 2*stride);
7917     jccb(Assembler::less, SCAN_TO_8_CHAR_INIT);
7918     movdl(vec1, ch);
7919     vpbroadcastw(vec1, vec1);
7920     vpxor(vec2, vec2);
7921     movl(tmp, cnt1);
7922     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7923     andl(cnt1,0x0000000F);  //tail count (in chars)
7924 
7925     bind(SCAN_TO_16_CHAR_LOOP);
7926     vmovdqu(vec3, Address(result, 0));
7927     vpcmpeqw(vec3, vec3, vec1, 1);
7928     vptest(vec2, vec3);
7929     jcc(Assembler::carryClear, FOUND_CHAR);
7930     addptr(result, 32);
7931     subl(tmp, 2*stride);
7932     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7933     jmp(SCAN_TO_8_CHAR);
7934     bind(SCAN_TO_8_CHAR_INIT);
7935     movdl(vec1, ch);
7936     pshuflw(vec1, vec1, 0x00);
7937     pshufd(vec1, vec1, 0);
7938     pxor(vec2, vec2);
7939   }
7940   bind(SCAN_TO_8_CHAR);
7941   cmpl(cnt1, stride);
7942   if (UseAVX >= 2) {
7943     jccb(Assembler::less, SCAN_TO_CHAR);
7944   } else {
7945     jccb(Assembler::less, SCAN_TO_CHAR_LOOP);
7946     movdl(vec1, ch);
7947     pshuflw(vec1, vec1, 0x00);
7948     pshufd(vec1, vec1, 0);
7949     pxor(vec2, vec2);
7950   }
7951   movl(tmp, cnt1);
7952   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7953   andl(cnt1,0x00000007);  //tail count (in chars)
7954 
7955   bind(SCAN_TO_8_CHAR_LOOP);
7956   movdqu(vec3, Address(result, 0));
7957   pcmpeqw(vec3, vec1);
7958   ptest(vec2, vec3);
7959   jcc(Assembler::carryClear, FOUND_CHAR);
7960   addptr(result, 16);
7961   subl(tmp, stride);
7962   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7963   bind(SCAN_TO_CHAR);
7964   testl(cnt1, cnt1);
7965   jcc(Assembler::zero, RET_NOT_FOUND);
7966   bind(SCAN_TO_CHAR_LOOP);
7967   load_unsigned_short(tmp, Address(result, 0));
7968   cmpl(ch, tmp);
7969   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7970   addptr(result, 2);
7971   subl(cnt1, 1);
7972   jccb(Assembler::zero, RET_NOT_FOUND);
7973   jmp(SCAN_TO_CHAR_LOOP);
7974 
7975   bind(RET_NOT_FOUND);
7976   movl(result, -1);
7977   jmpb(DONE_LABEL);
7978 
7979   bind(FOUND_CHAR);
7980   if (UseAVX >= 2) {
7981     vpmovmskb(tmp, vec3);
7982   } else {
7983     pmovmskb(tmp, vec3);
7984   }
7985   bsfl(ch, tmp);
7986   addl(result, ch);
7987 
7988   bind(FOUND_SEQ_CHAR);
7989   subptr(result, str1);
7990   shrl(result, 1);
7991 
7992   bind(DONE_LABEL);
7993 } // string_indexof_char
7994 
7995 // helper function for string_compare
7996 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7997                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7998                                         Address::ScaleFactor scale2, Register index, int ae) {
7999   if (ae == StrIntrinsicNode::LL) {
8000     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
8001     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
8002   } else if (ae == StrIntrinsicNode::UU) {
8003     load_unsigned_short(elem1, Address(str1, index, scale, 0));
8004     load_unsigned_short(elem2, Address(str2, index, scale, 0));
8005   } else {
8006     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
8007     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
8008   }
8009 }
8010 
8011 // Compare strings, used for char[] and byte[].
8012 void MacroAssembler::string_compare(Register str1, Register str2,
8013                                     Register cnt1, Register cnt2, Register result,
8014                                     XMMRegister vec1, int ae) {
8015   ShortBranchVerifier sbv(this);
8016   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
8017   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
8018   Address::ScaleFactor scale, scale1, scale2;
8019 
8020   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
8021     shrl(cnt2, 1);
8022   }
8023   // Compute the minimum of the string lengths and the
8024   // difference of the string lengths (stack).
8025   // Do the conditional move stuff
8026   movl(result, cnt1);
8027   subl(cnt1, cnt2);
8028   push(cnt1);
8029   cmov32(Assembler::lessEqual, cnt2, result);
8030 
8031   // Is the minimum length zero?
8032   testl(cnt2, cnt2);
8033   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8034   if (ae == StrIntrinsicNode::LL) {
8035     // Load first bytes
8036     load_unsigned_byte(result, Address(str1, 0));
8037     load_unsigned_byte(cnt1, Address(str2, 0));
8038   } else if (ae == StrIntrinsicNode::UU) {
8039     // Load first characters
8040     load_unsigned_short(result, Address(str1, 0));
8041     load_unsigned_short(cnt1, Address(str2, 0));
8042   } else {
8043     load_unsigned_byte(result, Address(str1, 0));
8044     load_unsigned_short(cnt1, Address(str2, 0));
8045   }
8046   subl(result, cnt1);
8047   jcc(Assembler::notZero,  POP_LABEL);
8048 
8049   if (ae == StrIntrinsicNode::UU) {
8050     // Divide length by 2 to get number of chars
8051     shrl(cnt2, 1);
8052   }
8053   cmpl(cnt2, 1);
8054   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
8055 
8056   // Check if the strings start at the same location and setup scale and stride
8057   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8058     cmpptr(str1, str2);
8059     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
8060     if (ae == StrIntrinsicNode::LL) {
8061       scale = Address::times_1;
8062       stride = 16;
8063     } else {
8064       scale = Address::times_2;
8065       stride = 8;
8066     }
8067   } else {
8068     scale = Address::no_scale;  // not used
8069     scale1 = Address::times_1;
8070     scale2 = Address::times_2;
8071     stride = 8;
8072   }
8073 
8074   if (UseAVX >= 2 && UseSSE42Intrinsics) {
8075     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8076     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
8077     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
8078     Label COMPARE_TAIL_LONG;
8079     int pcmpmask = 0x19;
8080     if (ae == StrIntrinsicNode::LL) {
8081       pcmpmask &= ~0x01;
8082     }
8083 
8084     // Setup to compare 16-chars (32-bytes) vectors,
8085     // start from first character again because it has aligned address.
8086     if (ae == StrIntrinsicNode::LL) {
8087       stride2 = 32;
8088     } else {
8089       stride2 = 16;
8090     }
8091     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8092       adr_stride = stride << scale;
8093     } else {
8094       adr_stride1 = 8;  //stride << scale1;
8095       adr_stride2 = 16; //stride << scale2;
8096     }
8097 
8098     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8099     // rax and rdx are used by pcmpestri as elements counters
8100     movl(result, cnt2);
8101     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
8102     jcc(Assembler::zero, COMPARE_TAIL_LONG);
8103 
8104     // fast path : compare first 2 8-char vectors.
8105     bind(COMPARE_16_CHARS);
8106     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8107       movdqu(vec1, Address(str1, 0));
8108     } else {
8109       pmovzxbw(vec1, Address(str1, 0));
8110     }
8111     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8112     jccb(Assembler::below, COMPARE_INDEX_CHAR);
8113 
8114     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8115       movdqu(vec1, Address(str1, adr_stride));
8116       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
8117     } else {
8118       pmovzxbw(vec1, Address(str1, adr_stride1));
8119       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
8120     }
8121     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
8122     addl(cnt1, stride);
8123 
8124     // Compare the characters at index in cnt1
8125     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
8126     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8127     subl(result, cnt2);
8128     jmp(POP_LABEL);
8129 
8130     // Setup the registers to start vector comparison loop
8131     bind(COMPARE_WIDE_VECTORS);
8132     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8133       lea(str1, Address(str1, result, scale));
8134       lea(str2, Address(str2, result, scale));
8135     } else {
8136       lea(str1, Address(str1, result, scale1));
8137       lea(str2, Address(str2, result, scale2));
8138     }
8139     subl(result, stride2);
8140     subl(cnt2, stride2);
8141     jccb(Assembler::zero, COMPARE_WIDE_TAIL);
8142     negptr(result);
8143 
8144     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
8145     bind(COMPARE_WIDE_VECTORS_LOOP);
8146     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8147       vmovdqu(vec1, Address(str1, result, scale));
8148       vpxor(vec1, Address(str2, result, scale));
8149     } else {
8150       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
8151       vpxor(vec1, Address(str2, result, scale2));
8152     }
8153     vptest(vec1, vec1);
8154     jccb(Assembler::notZero, VECTOR_NOT_EQUAL);
8155     addptr(result, stride2);
8156     subl(cnt2, stride2);
8157     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
8158     // clean upper bits of YMM registers
8159     vpxor(vec1, vec1);
8160 
8161     // compare wide vectors tail
8162     bind(COMPARE_WIDE_TAIL);
8163     testptr(result, result);
8164     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
8165 
8166     movl(result, stride2);
8167     movl(cnt2, result);
8168     negptr(result);
8169     jmpb(COMPARE_WIDE_VECTORS_LOOP);
8170 
8171     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
8172     bind(VECTOR_NOT_EQUAL);
8173     // clean upper bits of YMM registers
8174     vpxor(vec1, vec1);
8175     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8176       lea(str1, Address(str1, result, scale));
8177       lea(str2, Address(str2, result, scale));
8178     } else {
8179       lea(str1, Address(str1, result, scale1));
8180       lea(str2, Address(str2, result, scale2));
8181     }
8182     jmp(COMPARE_16_CHARS);
8183 
8184     // Compare tail chars, length between 1 to 15 chars
8185     bind(COMPARE_TAIL_LONG);
8186     movl(cnt2, result);
8187     cmpl(cnt2, stride);
8188     jccb(Assembler::less, COMPARE_SMALL_STR);
8189 
8190     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8191       movdqu(vec1, Address(str1, 0));
8192     } else {
8193       pmovzxbw(vec1, Address(str1, 0));
8194     }
8195     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8196     jcc(Assembler::below, COMPARE_INDEX_CHAR);
8197     subptr(cnt2, stride);
8198     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
8199     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8200       lea(str1, Address(str1, result, scale));
8201       lea(str2, Address(str2, result, scale));
8202     } else {
8203       lea(str1, Address(str1, result, scale1));
8204       lea(str2, Address(str2, result, scale2));
8205     }
8206     negptr(cnt2);
8207     jmpb(WHILE_HEAD_LABEL);
8208 
8209     bind(COMPARE_SMALL_STR);
8210   } else if (UseSSE42Intrinsics) {
8211     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8212     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
8213     int pcmpmask = 0x19;
8214     // Setup to compare 8-char (16-byte) vectors,
8215     // start from first character again because it has aligned address.
8216     movl(result, cnt2);
8217     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
8218     if (ae == StrIntrinsicNode::LL) {
8219       pcmpmask &= ~0x01;
8220     }
8221     jccb(Assembler::zero, COMPARE_TAIL);
8222     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8223       lea(str1, Address(str1, result, scale));
8224       lea(str2, Address(str2, result, scale));
8225     } else {
8226       lea(str1, Address(str1, result, scale1));
8227       lea(str2, Address(str2, result, scale2));
8228     }
8229     negptr(result);
8230 
8231     // pcmpestri
8232     //   inputs:
8233     //     vec1- substring
8234     //     rax - negative string length (elements count)
8235     //     mem - scanned string
8236     //     rdx - string length (elements count)
8237     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
8238     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
8239     //   outputs:
8240     //     rcx - first mismatched element index
8241     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8242 
8243     bind(COMPARE_WIDE_VECTORS);
8244     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8245       movdqu(vec1, Address(str1, result, scale));
8246       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8247     } else {
8248       pmovzxbw(vec1, Address(str1, result, scale1));
8249       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8250     }
8251     // After pcmpestri cnt1(rcx) contains mismatched element index
8252 
8253     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
8254     addptr(result, stride);
8255     subptr(cnt2, stride);
8256     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
8257 
8258     // compare wide vectors tail
8259     testptr(result, result);
8260     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
8261 
8262     movl(cnt2, stride);
8263     movl(result, stride);
8264     negptr(result);
8265     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8266       movdqu(vec1, Address(str1, result, scale));
8267       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8268     } else {
8269       pmovzxbw(vec1, Address(str1, result, scale1));
8270       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8271     }
8272     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
8273 
8274     // Mismatched characters in the vectors
8275     bind(VECTOR_NOT_EQUAL);
8276     addptr(cnt1, result);
8277     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8278     subl(result, cnt2);
8279     jmpb(POP_LABEL);
8280 
8281     bind(COMPARE_TAIL); // limit is zero
8282     movl(cnt2, result);
8283     // Fallthru to tail compare
8284   }
8285   // Shift str2 and str1 to the end of the arrays, negate min
8286   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8287     lea(str1, Address(str1, cnt2, scale));
8288     lea(str2, Address(str2, cnt2, scale));
8289   } else {
8290     lea(str1, Address(str1, cnt2, scale1));
8291     lea(str2, Address(str2, cnt2, scale2));
8292   }
8293   decrementl(cnt2);  // first character was compared already
8294   negptr(cnt2);
8295 
8296   // Compare the rest of the elements
8297   bind(WHILE_HEAD_LABEL);
8298   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
8299   subl(result, cnt1);
8300   jccb(Assembler::notZero, POP_LABEL);
8301   increment(cnt2);
8302   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
8303 
8304   // Strings are equal up to min length.  Return the length difference.
8305   bind(LENGTH_DIFF_LABEL);
8306   pop(result);
8307   if (ae == StrIntrinsicNode::UU) {
8308     // Divide diff by 2 to get number of chars
8309     sarl(result, 1);
8310   }
8311   jmpb(DONE_LABEL);
8312 
8313   // Discard the stored length difference
8314   bind(POP_LABEL);
8315   pop(cnt1);
8316 
8317   // That's it
8318   bind(DONE_LABEL);
8319   if(ae == StrIntrinsicNode::UL) {
8320     negl(result);
8321   }
8322 }
8323 
8324 // Search for Non-ASCII character (Negative byte value) in a byte array,
8325 // return true if it has any and false otherwise.
8326 void MacroAssembler::has_negatives(Register ary1, Register len,
8327                                    Register result, Register tmp1,
8328                                    XMMRegister vec1, XMMRegister vec2) {
8329 
8330   // rsi: byte array
8331   // rcx: len
8332   // rax: result
8333   ShortBranchVerifier sbv(this);
8334   assert_different_registers(ary1, len, result, tmp1);
8335   assert_different_registers(vec1, vec2);
8336   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8337 
8338   // len == 0
8339   testl(len, len);
8340   jcc(Assembler::zero, FALSE_LABEL);
8341 
8342   movl(result, len); // copy
8343 
8344   if (UseAVX >= 2 && UseSSE >= 2) {
8345     // With AVX2, use 32-byte vector compare
8346     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8347 
8348     // Compare 32-byte vectors
8349     andl(result, 0x0000001f);  //   tail count (in bytes)
8350     andl(len, 0xffffffe0);   // vector count (in bytes)
8351     jccb(Assembler::zero, COMPARE_TAIL);
8352 
8353     lea(ary1, Address(ary1, len, Address::times_1));
8354     negptr(len);
8355 
8356     movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8357     movdl(vec2, tmp1);
8358     vpbroadcastd(vec2, vec2);
8359 
8360     bind(COMPARE_WIDE_VECTORS);
8361     vmovdqu(vec1, Address(ary1, len, Address::times_1));
8362     vptest(vec1, vec2);
8363     jccb(Assembler::notZero, TRUE_LABEL);
8364     addptr(len, 32);
8365     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8366 
8367     testl(result, result);
8368     jccb(Assembler::zero, FALSE_LABEL);
8369 
8370     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8371     vptest(vec1, vec2);
8372     jccb(Assembler::notZero, TRUE_LABEL);
8373     jmpb(FALSE_LABEL);
8374 
8375     bind(COMPARE_TAIL); // len is zero
8376     movl(len, result);
8377     // Fallthru to tail compare
8378   } else if (UseSSE42Intrinsics) {
8379     assert(UseSSE >= 4, "SSE4 must be  for SSE4.2 intrinsics to be available");
8380     // With SSE4.2, use double quad vector compare
8381     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8382 
8383     // Compare 16-byte vectors
8384     andl(result, 0x0000000f);  //   tail count (in bytes)
8385     andl(len, 0xfffffff0);   // vector count (in bytes)
8386     jccb(Assembler::zero, COMPARE_TAIL);
8387 
8388     lea(ary1, Address(ary1, len, Address::times_1));
8389     negptr(len);
8390 
8391     movl(tmp1, 0x80808080);
8392     movdl(vec2, tmp1);
8393     pshufd(vec2, vec2, 0);
8394 
8395     bind(COMPARE_WIDE_VECTORS);
8396     movdqu(vec1, Address(ary1, len, Address::times_1));
8397     ptest(vec1, vec2);
8398     jccb(Assembler::notZero, TRUE_LABEL);
8399     addptr(len, 16);
8400     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8401 
8402     testl(result, result);
8403     jccb(Assembler::zero, FALSE_LABEL);
8404 
8405     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8406     ptest(vec1, vec2);
8407     jccb(Assembler::notZero, TRUE_LABEL);
8408     jmpb(FALSE_LABEL);
8409 
8410     bind(COMPARE_TAIL); // len is zero
8411     movl(len, result);
8412     // Fallthru to tail compare
8413   }
8414 
8415   // Compare 4-byte vectors
8416   andl(len, 0xfffffffc); // vector count (in bytes)
8417   jccb(Assembler::zero, COMPARE_CHAR);
8418 
8419   lea(ary1, Address(ary1, len, Address::times_1));
8420   negptr(len);
8421 
8422   bind(COMPARE_VECTORS);
8423   movl(tmp1, Address(ary1, len, Address::times_1));
8424   andl(tmp1, 0x80808080);
8425   jccb(Assembler::notZero, TRUE_LABEL);
8426   addptr(len, 4);
8427   jcc(Assembler::notZero, COMPARE_VECTORS);
8428 
8429   // Compare trailing char (final 2 bytes), if any
8430   bind(COMPARE_CHAR);
8431   testl(result, 0x2);   // tail  char
8432   jccb(Assembler::zero, COMPARE_BYTE);
8433   load_unsigned_short(tmp1, Address(ary1, 0));
8434   andl(tmp1, 0x00008080);
8435   jccb(Assembler::notZero, TRUE_LABEL);
8436   subptr(result, 2);
8437   lea(ary1, Address(ary1, 2));
8438 
8439   bind(COMPARE_BYTE);
8440   testl(result, 0x1);   // tail  byte
8441   jccb(Assembler::zero, FALSE_LABEL);
8442   load_unsigned_byte(tmp1, Address(ary1, 0));
8443   andl(tmp1, 0x00000080);
8444   jccb(Assembler::notEqual, TRUE_LABEL);
8445   jmpb(FALSE_LABEL);
8446 
8447   bind(TRUE_LABEL);
8448   movl(result, 1);   // return true
8449   jmpb(DONE);
8450 
8451   bind(FALSE_LABEL);
8452   xorl(result, result); // return false
8453 
8454   // That's it
8455   bind(DONE);
8456   if (UseAVX >= 2 && UseSSE >= 2) {
8457     // clean upper bits of YMM registers
8458     vpxor(vec1, vec1);
8459     vpxor(vec2, vec2);
8460   }
8461 }
8462 
8463 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8464 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8465                                    Register limit, Register result, Register chr,
8466                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8467   ShortBranchVerifier sbv(this);
8468   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8469 
8470   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8471   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8472 
8473   if (is_array_equ) {
8474     // Check the input args
8475     cmpptr(ary1, ary2);
8476     jcc(Assembler::equal, TRUE_LABEL);
8477 
8478     // Need additional checks for arrays_equals.
8479     testptr(ary1, ary1);
8480     jcc(Assembler::zero, FALSE_LABEL);
8481     testptr(ary2, ary2);
8482     jcc(Assembler::zero, FALSE_LABEL);
8483 
8484     // Check the lengths
8485     movl(limit, Address(ary1, length_offset));
8486     cmpl(limit, Address(ary2, length_offset));
8487     jcc(Assembler::notEqual, FALSE_LABEL);
8488   }
8489 
8490   // count == 0
8491   testl(limit, limit);
8492   jcc(Assembler::zero, TRUE_LABEL);
8493 
8494   if (is_array_equ) {
8495     // Load array address
8496     lea(ary1, Address(ary1, base_offset));
8497     lea(ary2, Address(ary2, base_offset));
8498   }
8499 
8500   if (is_array_equ && is_char) {
8501     // arrays_equals when used for char[].
8502     shll(limit, 1);      // byte count != 0
8503   }
8504   movl(result, limit); // copy
8505 
8506   if (UseAVX >= 2) {
8507     // With AVX2, use 32-byte vector compare
8508     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8509 
8510     // Compare 32-byte vectors
8511     andl(result, 0x0000001f);  //   tail count (in bytes)
8512     andl(limit, 0xffffffe0);   // vector count (in bytes)
8513     jccb(Assembler::zero, COMPARE_TAIL);
8514 
8515     lea(ary1, Address(ary1, limit, Address::times_1));
8516     lea(ary2, Address(ary2, limit, Address::times_1));
8517     negptr(limit);
8518 
8519     bind(COMPARE_WIDE_VECTORS);
8520     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8521     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8522     vpxor(vec1, vec2);
8523 
8524     vptest(vec1, vec1);
8525     jccb(Assembler::notZero, FALSE_LABEL);
8526     addptr(limit, 32);
8527     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8528 
8529     testl(result, result);
8530     jccb(Assembler::zero, TRUE_LABEL);
8531 
8532     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8533     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8534     vpxor(vec1, vec2);
8535 
8536     vptest(vec1, vec1);
8537     jccb(Assembler::notZero, FALSE_LABEL);
8538     jmpb(TRUE_LABEL);
8539 
8540     bind(COMPARE_TAIL); // limit is zero
8541     movl(limit, result);
8542     // Fallthru to tail compare
8543   } else if (UseSSE42Intrinsics) {
8544     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8545     // With SSE4.2, use double quad vector compare
8546     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8547 
8548     // Compare 16-byte vectors
8549     andl(result, 0x0000000f);  //   tail count (in bytes)
8550     andl(limit, 0xfffffff0);   // vector count (in bytes)
8551     jccb(Assembler::zero, COMPARE_TAIL);
8552 
8553     lea(ary1, Address(ary1, limit, Address::times_1));
8554     lea(ary2, Address(ary2, limit, Address::times_1));
8555     negptr(limit);
8556 
8557     bind(COMPARE_WIDE_VECTORS);
8558     movdqu(vec1, Address(ary1, limit, Address::times_1));
8559     movdqu(vec2, Address(ary2, limit, Address::times_1));
8560     pxor(vec1, vec2);
8561 
8562     ptest(vec1, vec1);
8563     jccb(Assembler::notZero, FALSE_LABEL);
8564     addptr(limit, 16);
8565     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8566 
8567     testl(result, result);
8568     jccb(Assembler::zero, TRUE_LABEL);
8569 
8570     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8571     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8572     pxor(vec1, vec2);
8573 
8574     ptest(vec1, vec1);
8575     jccb(Assembler::notZero, FALSE_LABEL);
8576     jmpb(TRUE_LABEL);
8577 
8578     bind(COMPARE_TAIL); // limit is zero
8579     movl(limit, result);
8580     // Fallthru to tail compare
8581   }
8582 
8583   // Compare 4-byte vectors
8584   andl(limit, 0xfffffffc); // vector count (in bytes)
8585   jccb(Assembler::zero, COMPARE_CHAR);
8586 
8587   lea(ary1, Address(ary1, limit, Address::times_1));
8588   lea(ary2, Address(ary2, limit, Address::times_1));
8589   negptr(limit);
8590 
8591   bind(COMPARE_VECTORS);
8592   movl(chr, Address(ary1, limit, Address::times_1));
8593   cmpl(chr, Address(ary2, limit, Address::times_1));
8594   jccb(Assembler::notEqual, FALSE_LABEL);
8595   addptr(limit, 4);
8596   jcc(Assembler::notZero, COMPARE_VECTORS);
8597 
8598   // Compare trailing char (final 2 bytes), if any
8599   bind(COMPARE_CHAR);
8600   testl(result, 0x2);   // tail  char
8601   jccb(Assembler::zero, COMPARE_BYTE);
8602   load_unsigned_short(chr, Address(ary1, 0));
8603   load_unsigned_short(limit, Address(ary2, 0));
8604   cmpl(chr, limit);
8605   jccb(Assembler::notEqual, FALSE_LABEL);
8606 
8607   if (is_array_equ && is_char) {
8608     bind(COMPARE_BYTE);
8609   } else {
8610     lea(ary1, Address(ary1, 2));
8611     lea(ary2, Address(ary2, 2));
8612 
8613     bind(COMPARE_BYTE);
8614     testl(result, 0x1);   // tail  byte
8615     jccb(Assembler::zero, TRUE_LABEL);
8616     load_unsigned_byte(chr, Address(ary1, 0));
8617     load_unsigned_byte(limit, Address(ary2, 0));
8618     cmpl(chr, limit);
8619     jccb(Assembler::notEqual, FALSE_LABEL);
8620   }
8621   bind(TRUE_LABEL);
8622   movl(result, 1);   // return true
8623   jmpb(DONE);
8624 
8625   bind(FALSE_LABEL);
8626   xorl(result, result); // return false
8627 
8628   // That's it
8629   bind(DONE);
8630   if (UseAVX >= 2) {
8631     // clean upper bits of YMM registers
8632     vpxor(vec1, vec1);
8633     vpxor(vec2, vec2);
8634   }
8635 }
8636 
8637 #endif
8638 
8639 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8640                                    Register to, Register value, Register count,
8641                                    Register rtmp, XMMRegister xtmp) {
8642   ShortBranchVerifier sbv(this);
8643   assert_different_registers(to, value, count, rtmp);
8644   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8645   Label L_fill_2_bytes, L_fill_4_bytes;
8646 
8647   int shift = -1;
8648   switch (t) {
8649     case T_BYTE:
8650       shift = 2;
8651       break;
8652     case T_SHORT:
8653       shift = 1;
8654       break;
8655     case T_INT:
8656       shift = 0;
8657       break;
8658     default: ShouldNotReachHere();
8659   }
8660 
8661   if (t == T_BYTE) {
8662     andl(value, 0xff);
8663     movl(rtmp, value);
8664     shll(rtmp, 8);
8665     orl(value, rtmp);
8666   }
8667   if (t == T_SHORT) {
8668     andl(value, 0xffff);
8669   }
8670   if (t == T_BYTE || t == T_SHORT) {
8671     movl(rtmp, value);
8672     shll(rtmp, 16);
8673     orl(value, rtmp);
8674   }
8675 
8676   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8677   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8678   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8679     // align source address at 4 bytes address boundary
8680     if (t == T_BYTE) {
8681       // One byte misalignment happens only for byte arrays
8682       testptr(to, 1);
8683       jccb(Assembler::zero, L_skip_align1);
8684       movb(Address(to, 0), value);
8685       increment(to);
8686       decrement(count);
8687       BIND(L_skip_align1);
8688     }
8689     // Two bytes misalignment happens only for byte and short (char) arrays
8690     testptr(to, 2);
8691     jccb(Assembler::zero, L_skip_align2);
8692     movw(Address(to, 0), value);
8693     addptr(to, 2);
8694     subl(count, 1<<(shift-1));
8695     BIND(L_skip_align2);
8696   }
8697   if (UseSSE < 2) {
8698     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8699     // Fill 32-byte chunks
8700     subl(count, 8 << shift);
8701     jcc(Assembler::less, L_check_fill_8_bytes);
8702     align(16);
8703 
8704     BIND(L_fill_32_bytes_loop);
8705 
8706     for (int i = 0; i < 32; i += 4) {
8707       movl(Address(to, i), value);
8708     }
8709 
8710     addptr(to, 32);
8711     subl(count, 8 << shift);
8712     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8713     BIND(L_check_fill_8_bytes);
8714     addl(count, 8 << shift);
8715     jccb(Assembler::zero, L_exit);
8716     jmpb(L_fill_8_bytes);
8717 
8718     //
8719     // length is too short, just fill qwords
8720     //
8721     BIND(L_fill_8_bytes_loop);
8722     movl(Address(to, 0), value);
8723     movl(Address(to, 4), value);
8724     addptr(to, 8);
8725     BIND(L_fill_8_bytes);
8726     subl(count, 1 << (shift + 1));
8727     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8728     // fall through to fill 4 bytes
8729   } else {
8730     Label L_fill_32_bytes;
8731     if (!UseUnalignedLoadStores) {
8732       // align to 8 bytes, we know we are 4 byte aligned to start
8733       testptr(to, 4);
8734       jccb(Assembler::zero, L_fill_32_bytes);
8735       movl(Address(to, 0), value);
8736       addptr(to, 4);
8737       subl(count, 1<<shift);
8738     }
8739     BIND(L_fill_32_bytes);
8740     {
8741       assert( UseSSE >= 2, "supported cpu only" );
8742       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8743       if (UseAVX > 2) {
8744         movl(rtmp, 0xffff);
8745         kmovwl(k1, rtmp);
8746       }
8747       movdl(xtmp, value);
8748       if (UseAVX > 2 && UseUnalignedLoadStores) {
8749         // Fill 64-byte chunks
8750         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8751         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8752 
8753         subl(count, 16 << shift);
8754         jcc(Assembler::less, L_check_fill_32_bytes);
8755         align(16);
8756 
8757         BIND(L_fill_64_bytes_loop);
8758         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8759         addptr(to, 64);
8760         subl(count, 16 << shift);
8761         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8762 
8763         BIND(L_check_fill_32_bytes);
8764         addl(count, 8 << shift);
8765         jccb(Assembler::less, L_check_fill_8_bytes);
8766         vmovdqu(Address(to, 0), xtmp);
8767         addptr(to, 32);
8768         subl(count, 8 << shift);
8769 
8770         BIND(L_check_fill_8_bytes);
8771       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8772         // Fill 64-byte chunks
8773         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8774         vpbroadcastd(xtmp, xtmp);
8775 
8776         subl(count, 16 << shift);
8777         jcc(Assembler::less, L_check_fill_32_bytes);
8778         align(16);
8779 
8780         BIND(L_fill_64_bytes_loop);
8781         vmovdqu(Address(to, 0), xtmp);
8782         vmovdqu(Address(to, 32), xtmp);
8783         addptr(to, 64);
8784         subl(count, 16 << shift);
8785         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8786 
8787         BIND(L_check_fill_32_bytes);
8788         addl(count, 8 << shift);
8789         jccb(Assembler::less, L_check_fill_8_bytes);
8790         vmovdqu(Address(to, 0), xtmp);
8791         addptr(to, 32);
8792         subl(count, 8 << shift);
8793 
8794         BIND(L_check_fill_8_bytes);
8795         // clean upper bits of YMM registers
8796         movdl(xtmp, value);
8797         pshufd(xtmp, xtmp, 0);
8798       } else {
8799         // Fill 32-byte chunks
8800         pshufd(xtmp, xtmp, 0);
8801 
8802         subl(count, 8 << shift);
8803         jcc(Assembler::less, L_check_fill_8_bytes);
8804         align(16);
8805 
8806         BIND(L_fill_32_bytes_loop);
8807 
8808         if (UseUnalignedLoadStores) {
8809           movdqu(Address(to, 0), xtmp);
8810           movdqu(Address(to, 16), xtmp);
8811         } else {
8812           movq(Address(to, 0), xtmp);
8813           movq(Address(to, 8), xtmp);
8814           movq(Address(to, 16), xtmp);
8815           movq(Address(to, 24), xtmp);
8816         }
8817 
8818         addptr(to, 32);
8819         subl(count, 8 << shift);
8820         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8821 
8822         BIND(L_check_fill_8_bytes);
8823       }
8824       addl(count, 8 << shift);
8825       jccb(Assembler::zero, L_exit);
8826       jmpb(L_fill_8_bytes);
8827 
8828       //
8829       // length is too short, just fill qwords
8830       //
8831       BIND(L_fill_8_bytes_loop);
8832       movq(Address(to, 0), xtmp);
8833       addptr(to, 8);
8834       BIND(L_fill_8_bytes);
8835       subl(count, 1 << (shift + 1));
8836       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8837     }
8838   }
8839   // fill trailing 4 bytes
8840   BIND(L_fill_4_bytes);
8841   testl(count, 1<<shift);
8842   jccb(Assembler::zero, L_fill_2_bytes);
8843   movl(Address(to, 0), value);
8844   if (t == T_BYTE || t == T_SHORT) {
8845     addptr(to, 4);
8846     BIND(L_fill_2_bytes);
8847     // fill trailing 2 bytes
8848     testl(count, 1<<(shift-1));
8849     jccb(Assembler::zero, L_fill_byte);
8850     movw(Address(to, 0), value);
8851     if (t == T_BYTE) {
8852       addptr(to, 2);
8853       BIND(L_fill_byte);
8854       // fill trailing byte
8855       testl(count, 1);
8856       jccb(Assembler::zero, L_exit);
8857       movb(Address(to, 0), value);
8858     } else {
8859       BIND(L_fill_byte);
8860     }
8861   } else {
8862     BIND(L_fill_2_bytes);
8863   }
8864   BIND(L_exit);
8865 }
8866 
8867 // encode char[] to byte[] in ISO_8859_1
8868 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8869                                       XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8870                                       XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8871                                       Register tmp5, Register result) {
8872   // rsi: src
8873   // rdi: dst
8874   // rdx: len
8875   // rcx: tmp5
8876   // rax: result
8877   ShortBranchVerifier sbv(this);
8878   assert_different_registers(src, dst, len, tmp5, result);
8879   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8880 
8881   // set result
8882   xorl(result, result);
8883   // check for zero length
8884   testl(len, len);
8885   jcc(Assembler::zero, L_done);
8886   movl(result, len);
8887 
8888   // Setup pointers
8889   lea(src, Address(src, len, Address::times_2)); // char[]
8890   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8891   negptr(len);
8892 
8893   if (UseSSE42Intrinsics || UseAVX >= 2) {
8894     assert(UseSSE42Intrinsics ? UseSSE >= 4 : true, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8895     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8896     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8897 
8898     if (UseAVX >= 2) {
8899       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8900       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8901       movdl(tmp1Reg, tmp5);
8902       vpbroadcastd(tmp1Reg, tmp1Reg);
8903       jmpb(L_chars_32_check);
8904 
8905       bind(L_copy_32_chars);
8906       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8907       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8908       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8909       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8910       jccb(Assembler::notZero, L_copy_32_chars_exit);
8911       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8912       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8913       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8914 
8915       bind(L_chars_32_check);
8916       addptr(len, 32);
8917       jccb(Assembler::lessEqual, L_copy_32_chars);
8918 
8919       bind(L_copy_32_chars_exit);
8920       subptr(len, 16);
8921       jccb(Assembler::greater, L_copy_16_chars_exit);
8922 
8923     } else if (UseSSE42Intrinsics) {
8924       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8925       movdl(tmp1Reg, tmp5);
8926       pshufd(tmp1Reg, tmp1Reg, 0);
8927       jmpb(L_chars_16_check);
8928     }
8929 
8930     bind(L_copy_16_chars);
8931     if (UseAVX >= 2) {
8932       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8933       vptest(tmp2Reg, tmp1Reg);
8934       jccb(Assembler::notZero, L_copy_16_chars_exit);
8935       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8936       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8937     } else {
8938       if (UseAVX > 0) {
8939         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8940         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8941         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8942       } else {
8943         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8944         por(tmp2Reg, tmp3Reg);
8945         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8946         por(tmp2Reg, tmp4Reg);
8947       }
8948       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8949       jccb(Assembler::notZero, L_copy_16_chars_exit);
8950       packuswb(tmp3Reg, tmp4Reg);
8951     }
8952     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8953 
8954     bind(L_chars_16_check);
8955     addptr(len, 16);
8956     jccb(Assembler::lessEqual, L_copy_16_chars);
8957 
8958     bind(L_copy_16_chars_exit);
8959     if (UseAVX >= 2) {
8960       // clean upper bits of YMM registers
8961       vpxor(tmp2Reg, tmp2Reg);
8962       vpxor(tmp3Reg, tmp3Reg);
8963       vpxor(tmp4Reg, tmp4Reg);
8964       movdl(tmp1Reg, tmp5);
8965       pshufd(tmp1Reg, tmp1Reg, 0);
8966     }
8967     subptr(len, 8);
8968     jccb(Assembler::greater, L_copy_8_chars_exit);
8969 
8970     bind(L_copy_8_chars);
8971     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8972     ptest(tmp3Reg, tmp1Reg);
8973     jccb(Assembler::notZero, L_copy_8_chars_exit);
8974     packuswb(tmp3Reg, tmp1Reg);
8975     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8976     addptr(len, 8);
8977     jccb(Assembler::lessEqual, L_copy_8_chars);
8978 
8979     bind(L_copy_8_chars_exit);
8980     subptr(len, 8);
8981     jccb(Assembler::zero, L_done);
8982   }
8983 
8984   bind(L_copy_1_char);
8985   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8986   testl(tmp5, 0xff00);      // check if Unicode char
8987   jccb(Assembler::notZero, L_copy_1_char_exit);
8988   movb(Address(dst, len, Address::times_1, 0), tmp5);
8989   addptr(len, 1);
8990   jccb(Assembler::less, L_copy_1_char);
8991 
8992   bind(L_copy_1_char_exit);
8993   addptr(result, len); // len is negative count of not processed elements
8994   bind(L_done);
8995 }
8996 
8997 #ifdef _LP64
8998 /**
8999  * Helper for multiply_to_len().
9000  */
9001 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
9002   addq(dest_lo, src1);
9003   adcq(dest_hi, 0);
9004   addq(dest_lo, src2);
9005   adcq(dest_hi, 0);
9006 }
9007 
9008 /**
9009  * Multiply 64 bit by 64 bit first loop.
9010  */
9011 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
9012                                            Register y, Register y_idx, Register z,
9013                                            Register carry, Register product,
9014                                            Register idx, Register kdx) {
9015   //
9016   //  jlong carry, x[], y[], z[];
9017   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9018   //    huge_128 product = y[idx] * x[xstart] + carry;
9019   //    z[kdx] = (jlong)product;
9020   //    carry  = (jlong)(product >>> 64);
9021   //  }
9022   //  z[xstart] = carry;
9023   //
9024 
9025   Label L_first_loop, L_first_loop_exit;
9026   Label L_one_x, L_one_y, L_multiply;
9027 
9028   decrementl(xstart);
9029   jcc(Assembler::negative, L_one_x);
9030 
9031   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9032   rorq(x_xstart, 32); // convert big-endian to little-endian
9033 
9034   bind(L_first_loop);
9035   decrementl(idx);
9036   jcc(Assembler::negative, L_first_loop_exit);
9037   decrementl(idx);
9038   jcc(Assembler::negative, L_one_y);
9039   movq(y_idx, Address(y, idx, Address::times_4,  0));
9040   rorq(y_idx, 32); // convert big-endian to little-endian
9041   bind(L_multiply);
9042   movq(product, x_xstart);
9043   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
9044   addq(product, carry);
9045   adcq(rdx, 0);
9046   subl(kdx, 2);
9047   movl(Address(z, kdx, Address::times_4,  4), product);
9048   shrq(product, 32);
9049   movl(Address(z, kdx, Address::times_4,  0), product);
9050   movq(carry, rdx);
9051   jmp(L_first_loop);
9052 
9053   bind(L_one_y);
9054   movl(y_idx, Address(y,  0));
9055   jmp(L_multiply);
9056 
9057   bind(L_one_x);
9058   movl(x_xstart, Address(x,  0));
9059   jmp(L_first_loop);
9060 
9061   bind(L_first_loop_exit);
9062 }
9063 
9064 /**
9065  * Multiply 64 bit by 64 bit and add 128 bit.
9066  */
9067 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
9068                                             Register yz_idx, Register idx,
9069                                             Register carry, Register product, int offset) {
9070   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
9071   //     z[kdx] = (jlong)product;
9072 
9073   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
9074   rorq(yz_idx, 32); // convert big-endian to little-endian
9075   movq(product, x_xstart);
9076   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
9077   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
9078   rorq(yz_idx, 32); // convert big-endian to little-endian
9079 
9080   add2_with_carry(rdx, product, carry, yz_idx);
9081 
9082   movl(Address(z, idx, Address::times_4,  offset+4), product);
9083   shrq(product, 32);
9084   movl(Address(z, idx, Address::times_4,  offset), product);
9085 
9086 }
9087 
9088 /**
9089  * Multiply 128 bit by 128 bit. Unrolled inner loop.
9090  */
9091 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
9092                                              Register yz_idx, Register idx, Register jdx,
9093                                              Register carry, Register product,
9094                                              Register carry2) {
9095   //   jlong carry, x[], y[], z[];
9096   //   int kdx = ystart+1;
9097   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9098   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
9099   //     z[kdx+idx+1] = (jlong)product;
9100   //     jlong carry2  = (jlong)(product >>> 64);
9101   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
9102   //     z[kdx+idx] = (jlong)product;
9103   //     carry  = (jlong)(product >>> 64);
9104   //   }
9105   //   idx += 2;
9106   //   if (idx > 0) {
9107   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
9108   //     z[kdx+idx] = (jlong)product;
9109   //     carry  = (jlong)(product >>> 64);
9110   //   }
9111   //
9112 
9113   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9114 
9115   movl(jdx, idx);
9116   andl(jdx, 0xFFFFFFFC);
9117   shrl(jdx, 2);
9118 
9119   bind(L_third_loop);
9120   subl(jdx, 1);
9121   jcc(Assembler::negative, L_third_loop_exit);
9122   subl(idx, 4);
9123 
9124   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
9125   movq(carry2, rdx);
9126 
9127   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
9128   movq(carry, rdx);
9129   jmp(L_third_loop);
9130 
9131   bind (L_third_loop_exit);
9132 
9133   andl (idx, 0x3);
9134   jcc(Assembler::zero, L_post_third_loop_done);
9135 
9136   Label L_check_1;
9137   subl(idx, 2);
9138   jcc(Assembler::negative, L_check_1);
9139 
9140   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
9141   movq(carry, rdx);
9142 
9143   bind (L_check_1);
9144   addl (idx, 0x2);
9145   andl (idx, 0x1);
9146   subl(idx, 1);
9147   jcc(Assembler::negative, L_post_third_loop_done);
9148 
9149   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9150   movq(product, x_xstart);
9151   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9152   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9153 
9154   add2_with_carry(rdx, product, yz_idx, carry);
9155 
9156   movl(Address(z, idx, Address::times_4,  0), product);
9157   shrq(product, 32);
9158 
9159   shlq(rdx, 32);
9160   orq(product, rdx);
9161   movq(carry, product);
9162 
9163   bind(L_post_third_loop_done);
9164 }
9165 
9166 /**
9167  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9168  *
9169  */
9170 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9171                                                   Register carry, Register carry2,
9172                                                   Register idx, Register jdx,
9173                                                   Register yz_idx1, Register yz_idx2,
9174                                                   Register tmp, Register tmp3, Register tmp4) {
9175   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9176 
9177   //   jlong carry, x[], y[], z[];
9178   //   int kdx = ystart+1;
9179   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9180   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9181   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9182   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9183   //     carry  = (jlong)(tmp4 >>> 64);
9184   //     z[kdx+idx+1] = (jlong)tmp3;
9185   //     z[kdx+idx] = (jlong)tmp4;
9186   //   }
9187   //   idx += 2;
9188   //   if (idx > 0) {
9189   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9190   //     z[kdx+idx] = (jlong)yz_idx1;
9191   //     carry  = (jlong)(yz_idx1 >>> 64);
9192   //   }
9193   //
9194 
9195   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9196 
9197   movl(jdx, idx);
9198   andl(jdx, 0xFFFFFFFC);
9199   shrl(jdx, 2);
9200 
9201   bind(L_third_loop);
9202   subl(jdx, 1);
9203   jcc(Assembler::negative, L_third_loop_exit);
9204   subl(idx, 4);
9205 
9206   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9207   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9208   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9209   rorxq(yz_idx2, yz_idx2, 32);
9210 
9211   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9212   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9213 
9214   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9215   rorxq(yz_idx1, yz_idx1, 32);
9216   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9217   rorxq(yz_idx2, yz_idx2, 32);
9218 
9219   if (VM_Version::supports_adx()) {
9220     adcxq(tmp3, carry);
9221     adoxq(tmp3, yz_idx1);
9222 
9223     adcxq(tmp4, tmp);
9224     adoxq(tmp4, yz_idx2);
9225 
9226     movl(carry, 0); // does not affect flags
9227     adcxq(carry2, carry);
9228     adoxq(carry2, carry);
9229   } else {
9230     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9231     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9232   }
9233   movq(carry, carry2);
9234 
9235   movl(Address(z, idx, Address::times_4, 12), tmp3);
9236   shrq(tmp3, 32);
9237   movl(Address(z, idx, Address::times_4,  8), tmp3);
9238 
9239   movl(Address(z, idx, Address::times_4,  4), tmp4);
9240   shrq(tmp4, 32);
9241   movl(Address(z, idx, Address::times_4,  0), tmp4);
9242 
9243   jmp(L_third_loop);
9244 
9245   bind (L_third_loop_exit);
9246 
9247   andl (idx, 0x3);
9248   jcc(Assembler::zero, L_post_third_loop_done);
9249 
9250   Label L_check_1;
9251   subl(idx, 2);
9252   jcc(Assembler::negative, L_check_1);
9253 
9254   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9255   rorxq(yz_idx1, yz_idx1, 32);
9256   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9257   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9258   rorxq(yz_idx2, yz_idx2, 32);
9259 
9260   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9261 
9262   movl(Address(z, idx, Address::times_4,  4), tmp3);
9263   shrq(tmp3, 32);
9264   movl(Address(z, idx, Address::times_4,  0), tmp3);
9265   movq(carry, tmp4);
9266 
9267   bind (L_check_1);
9268   addl (idx, 0x2);
9269   andl (idx, 0x1);
9270   subl(idx, 1);
9271   jcc(Assembler::negative, L_post_third_loop_done);
9272   movl(tmp4, Address(y, idx, Address::times_4,  0));
9273   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9274   movl(tmp4, Address(z, idx, Address::times_4,  0));
9275 
9276   add2_with_carry(carry2, tmp3, tmp4, carry);
9277 
9278   movl(Address(z, idx, Address::times_4,  0), tmp3);
9279   shrq(tmp3, 32);
9280 
9281   shlq(carry2, 32);
9282   orq(tmp3, carry2);
9283   movq(carry, tmp3);
9284 
9285   bind(L_post_third_loop_done);
9286 }
9287 
9288 /**
9289  * Code for BigInteger::multiplyToLen() instrinsic.
9290  *
9291  * rdi: x
9292  * rax: xlen
9293  * rsi: y
9294  * rcx: ylen
9295  * r8:  z
9296  * r11: zlen
9297  * r12: tmp1
9298  * r13: tmp2
9299  * r14: tmp3
9300  * r15: tmp4
9301  * rbx: tmp5
9302  *
9303  */
9304 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9305                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9306   ShortBranchVerifier sbv(this);
9307   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9308 
9309   push(tmp1);
9310   push(tmp2);
9311   push(tmp3);
9312   push(tmp4);
9313   push(tmp5);
9314 
9315   push(xlen);
9316   push(zlen);
9317 
9318   const Register idx = tmp1;
9319   const Register kdx = tmp2;
9320   const Register xstart = tmp3;
9321 
9322   const Register y_idx = tmp4;
9323   const Register carry = tmp5;
9324   const Register product  = xlen;
9325   const Register x_xstart = zlen;  // reuse register
9326 
9327   // First Loop.
9328   //
9329   //  final static long LONG_MASK = 0xffffffffL;
9330   //  int xstart = xlen - 1;
9331   //  int ystart = ylen - 1;
9332   //  long carry = 0;
9333   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9334   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9335   //    z[kdx] = (int)product;
9336   //    carry = product >>> 32;
9337   //  }
9338   //  z[xstart] = (int)carry;
9339   //
9340 
9341   movl(idx, ylen);      // idx = ylen;
9342   movl(kdx, zlen);      // kdx = xlen+ylen;
9343   xorq(carry, carry);   // carry = 0;
9344 
9345   Label L_done;
9346 
9347   movl(xstart, xlen);
9348   decrementl(xstart);
9349   jcc(Assembler::negative, L_done);
9350 
9351   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9352 
9353   Label L_second_loop;
9354   testl(kdx, kdx);
9355   jcc(Assembler::zero, L_second_loop);
9356 
9357   Label L_carry;
9358   subl(kdx, 1);
9359   jcc(Assembler::zero, L_carry);
9360 
9361   movl(Address(z, kdx, Address::times_4,  0), carry);
9362   shrq(carry, 32);
9363   subl(kdx, 1);
9364 
9365   bind(L_carry);
9366   movl(Address(z, kdx, Address::times_4,  0), carry);
9367 
9368   // Second and third (nested) loops.
9369   //
9370   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9371   //   carry = 0;
9372   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9373   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9374   //                    (z[k] & LONG_MASK) + carry;
9375   //     z[k] = (int)product;
9376   //     carry = product >>> 32;
9377   //   }
9378   //   z[i] = (int)carry;
9379   // }
9380   //
9381   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9382 
9383   const Register jdx = tmp1;
9384 
9385   bind(L_second_loop);
9386   xorl(carry, carry);    // carry = 0;
9387   movl(jdx, ylen);       // j = ystart+1
9388 
9389   subl(xstart, 1);       // i = xstart-1;
9390   jcc(Assembler::negative, L_done);
9391 
9392   push (z);
9393 
9394   Label L_last_x;
9395   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9396   subl(xstart, 1);       // i = xstart-1;
9397   jcc(Assembler::negative, L_last_x);
9398 
9399   if (UseBMI2Instructions) {
9400     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9401     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9402   } else {
9403     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9404     rorq(x_xstart, 32);  // convert big-endian to little-endian
9405   }
9406 
9407   Label L_third_loop_prologue;
9408   bind(L_third_loop_prologue);
9409 
9410   push (x);
9411   push (xstart);
9412   push (ylen);
9413 
9414 
9415   if (UseBMI2Instructions) {
9416     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9417   } else { // !UseBMI2Instructions
9418     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9419   }
9420 
9421   pop(ylen);
9422   pop(xlen);
9423   pop(x);
9424   pop(z);
9425 
9426   movl(tmp3, xlen);
9427   addl(tmp3, 1);
9428   movl(Address(z, tmp3, Address::times_4,  0), carry);
9429   subl(tmp3, 1);
9430   jccb(Assembler::negative, L_done);
9431 
9432   shrq(carry, 32);
9433   movl(Address(z, tmp3, Address::times_4,  0), carry);
9434   jmp(L_second_loop);
9435 
9436   // Next infrequent code is moved outside loops.
9437   bind(L_last_x);
9438   if (UseBMI2Instructions) {
9439     movl(rdx, Address(x,  0));
9440   } else {
9441     movl(x_xstart, Address(x,  0));
9442   }
9443   jmp(L_third_loop_prologue);
9444 
9445   bind(L_done);
9446 
9447   pop(zlen);
9448   pop(xlen);
9449 
9450   pop(tmp5);
9451   pop(tmp4);
9452   pop(tmp3);
9453   pop(tmp2);
9454   pop(tmp1);
9455 }
9456 
9457 //Helper functions for square_to_len()
9458 
9459 /**
9460  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9461  * Preserves x and z and modifies rest of the registers.
9462  */
9463 
9464 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9465   // Perform square and right shift by 1
9466   // Handle odd xlen case first, then for even xlen do the following
9467   // jlong carry = 0;
9468   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9469   //     huge_128 product = x[j:j+1] * x[j:j+1];
9470   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9471   //     z[i+2:i+3] = (jlong)(product >>> 1);
9472   //     carry = (jlong)product;
9473   // }
9474 
9475   xorq(tmp5, tmp5);     // carry
9476   xorq(rdxReg, rdxReg);
9477   xorl(tmp1, tmp1);     // index for x
9478   xorl(tmp4, tmp4);     // index for z
9479 
9480   Label L_first_loop, L_first_loop_exit;
9481 
9482   testl(xlen, 1);
9483   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9484 
9485   // Square and right shift by 1 the odd element using 32 bit multiply
9486   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9487   imulq(raxReg, raxReg);
9488   shrq(raxReg, 1);
9489   adcq(tmp5, 0);
9490   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9491   incrementl(tmp1);
9492   addl(tmp4, 2);
9493 
9494   // Square and  right shift by 1 the rest using 64 bit multiply
9495   bind(L_first_loop);
9496   cmpptr(tmp1, xlen);
9497   jccb(Assembler::equal, L_first_loop_exit);
9498 
9499   // Square
9500   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9501   rorq(raxReg, 32);    // convert big-endian to little-endian
9502   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9503 
9504   // Right shift by 1 and save carry
9505   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9506   rcrq(rdxReg, 1);
9507   rcrq(raxReg, 1);
9508   adcq(tmp5, 0);
9509 
9510   // Store result in z
9511   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9512   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9513 
9514   // Update indices for x and z
9515   addl(tmp1, 2);
9516   addl(tmp4, 4);
9517   jmp(L_first_loop);
9518 
9519   bind(L_first_loop_exit);
9520 }
9521 
9522 
9523 /**
9524  * Perform the following multiply add operation using BMI2 instructions
9525  * carry:sum = sum + op1*op2 + carry
9526  * op2 should be in rdx
9527  * op2 is preserved, all other registers are modified
9528  */
9529 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9530   // assert op2 is rdx
9531   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9532   addq(sum, carry);
9533   adcq(tmp2, 0);
9534   addq(sum, op1);
9535   adcq(tmp2, 0);
9536   movq(carry, tmp2);
9537 }
9538 
9539 /**
9540  * Perform the following multiply add operation:
9541  * carry:sum = sum + op1*op2 + carry
9542  * Preserves op1, op2 and modifies rest of registers
9543  */
9544 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9545   // rdx:rax = op1 * op2
9546   movq(raxReg, op2);
9547   mulq(op1);
9548 
9549   //  rdx:rax = sum + carry + rdx:rax
9550   addq(sum, carry);
9551   adcq(rdxReg, 0);
9552   addq(sum, raxReg);
9553   adcq(rdxReg, 0);
9554 
9555   // carry:sum = rdx:sum
9556   movq(carry, rdxReg);
9557 }
9558 
9559 /**
9560  * Add 64 bit long carry into z[] with carry propogation.
9561  * Preserves z and carry register values and modifies rest of registers.
9562  *
9563  */
9564 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9565   Label L_fourth_loop, L_fourth_loop_exit;
9566 
9567   movl(tmp1, 1);
9568   subl(zlen, 2);
9569   addq(Address(z, zlen, Address::times_4, 0), carry);
9570 
9571   bind(L_fourth_loop);
9572   jccb(Assembler::carryClear, L_fourth_loop_exit);
9573   subl(zlen, 2);
9574   jccb(Assembler::negative, L_fourth_loop_exit);
9575   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9576   jmp(L_fourth_loop);
9577   bind(L_fourth_loop_exit);
9578 }
9579 
9580 /**
9581  * Shift z[] left by 1 bit.
9582  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9583  *
9584  */
9585 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9586 
9587   Label L_fifth_loop, L_fifth_loop_exit;
9588 
9589   // Fifth loop
9590   // Perform primitiveLeftShift(z, zlen, 1)
9591 
9592   const Register prev_carry = tmp1;
9593   const Register new_carry = tmp4;
9594   const Register value = tmp2;
9595   const Register zidx = tmp3;
9596 
9597   // int zidx, carry;
9598   // long value;
9599   // carry = 0;
9600   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9601   //    (carry:value)  = (z[i] << 1) | carry ;
9602   //    z[i] = value;
9603   // }
9604 
9605   movl(zidx, zlen);
9606   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9607 
9608   bind(L_fifth_loop);
9609   decl(zidx);  // Use decl to preserve carry flag
9610   decl(zidx);
9611   jccb(Assembler::negative, L_fifth_loop_exit);
9612 
9613   if (UseBMI2Instructions) {
9614      movq(value, Address(z, zidx, Address::times_4, 0));
9615      rclq(value, 1);
9616      rorxq(value, value, 32);
9617      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9618   }
9619   else {
9620     // clear new_carry
9621     xorl(new_carry, new_carry);
9622 
9623     // Shift z[i] by 1, or in previous carry and save new carry
9624     movq(value, Address(z, zidx, Address::times_4, 0));
9625     shlq(value, 1);
9626     adcl(new_carry, 0);
9627 
9628     orq(value, prev_carry);
9629     rorq(value, 0x20);
9630     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9631 
9632     // Set previous carry = new carry
9633     movl(prev_carry, new_carry);
9634   }
9635   jmp(L_fifth_loop);
9636 
9637   bind(L_fifth_loop_exit);
9638 }
9639 
9640 
9641 /**
9642  * Code for BigInteger::squareToLen() intrinsic
9643  *
9644  * rdi: x
9645  * rsi: len
9646  * r8:  z
9647  * rcx: zlen
9648  * r12: tmp1
9649  * r13: tmp2
9650  * r14: tmp3
9651  * r15: tmp4
9652  * rbx: tmp5
9653  *
9654  */
9655 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) {
9656 
9657   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;
9658   push(tmp1);
9659   push(tmp2);
9660   push(tmp3);
9661   push(tmp4);
9662   push(tmp5);
9663 
9664   // First loop
9665   // Store the squares, right shifted one bit (i.e., divided by 2).
9666   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9667 
9668   // Add in off-diagonal sums.
9669   //
9670   // Second, third (nested) and fourth loops.
9671   // zlen +=2;
9672   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9673   //    carry = 0;
9674   //    long op2 = x[xidx:xidx+1];
9675   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9676   //       k -= 2;
9677   //       long op1 = x[j:j+1];
9678   //       long sum = z[k:k+1];
9679   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9680   //       z[k:k+1] = sum;
9681   //    }
9682   //    add_one_64(z, k, carry, tmp_regs);
9683   // }
9684 
9685   const Register carry = tmp5;
9686   const Register sum = tmp3;
9687   const Register op1 = tmp4;
9688   Register op2 = tmp2;
9689 
9690   push(zlen);
9691   push(len);
9692   addl(zlen,2);
9693   bind(L_second_loop);
9694   xorq(carry, carry);
9695   subl(zlen, 4);
9696   subl(len, 2);
9697   push(zlen);
9698   push(len);
9699   cmpl(len, 0);
9700   jccb(Assembler::lessEqual, L_second_loop_exit);
9701 
9702   // Multiply an array by one 64 bit long.
9703   if (UseBMI2Instructions) {
9704     op2 = rdxReg;
9705     movq(op2, Address(x, len, Address::times_4,  0));
9706     rorxq(op2, op2, 32);
9707   }
9708   else {
9709     movq(op2, Address(x, len, Address::times_4,  0));
9710     rorq(op2, 32);
9711   }
9712 
9713   bind(L_third_loop);
9714   decrementl(len);
9715   jccb(Assembler::negative, L_third_loop_exit);
9716   decrementl(len);
9717   jccb(Assembler::negative, L_last_x);
9718 
9719   movq(op1, Address(x, len, Address::times_4,  0));
9720   rorq(op1, 32);
9721 
9722   bind(L_multiply);
9723   subl(zlen, 2);
9724   movq(sum, Address(z, zlen, Address::times_4,  0));
9725 
9726   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9727   if (UseBMI2Instructions) {
9728     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9729   }
9730   else {
9731     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9732   }
9733 
9734   movq(Address(z, zlen, Address::times_4, 0), sum);
9735 
9736   jmp(L_third_loop);
9737   bind(L_third_loop_exit);
9738 
9739   // Fourth loop
9740   // Add 64 bit long carry into z with carry propogation.
9741   // Uses offsetted zlen.
9742   add_one_64(z, zlen, carry, tmp1);
9743 
9744   pop(len);
9745   pop(zlen);
9746   jmp(L_second_loop);
9747 
9748   // Next infrequent code is moved outside loops.
9749   bind(L_last_x);
9750   movl(op1, Address(x, 0));
9751   jmp(L_multiply);
9752 
9753   bind(L_second_loop_exit);
9754   pop(len);
9755   pop(zlen);
9756   pop(len);
9757   pop(zlen);
9758 
9759   // Fifth loop
9760   // Shift z left 1 bit.
9761   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9762 
9763   // z[zlen-1] |= x[len-1] & 1;
9764   movl(tmp3, Address(x, len, Address::times_4, -4));
9765   andl(tmp3, 1);
9766   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9767 
9768   pop(tmp5);
9769   pop(tmp4);
9770   pop(tmp3);
9771   pop(tmp2);
9772   pop(tmp1);
9773 }
9774 
9775 /**
9776  * Helper function for mul_add()
9777  * Multiply the in[] by int k and add to out[] starting at offset offs using
9778  * 128 bit by 32 bit multiply and return the carry in tmp5.
9779  * Only quad int aligned length of in[] is operated on in this function.
9780  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9781  * This function preserves out, in and k registers.
9782  * len and offset point to the appropriate index in "in" & "out" correspondingly
9783  * tmp5 has the carry.
9784  * other registers are temporary and are modified.
9785  *
9786  */
9787 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9788   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9789   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9790 
9791   Label L_first_loop, L_first_loop_exit;
9792 
9793   movl(tmp1, len);
9794   shrl(tmp1, 2);
9795 
9796   bind(L_first_loop);
9797   subl(tmp1, 1);
9798   jccb(Assembler::negative, L_first_loop_exit);
9799 
9800   subl(len, 4);
9801   subl(offset, 4);
9802 
9803   Register op2 = tmp2;
9804   const Register sum = tmp3;
9805   const Register op1 = tmp4;
9806   const Register carry = tmp5;
9807 
9808   if (UseBMI2Instructions) {
9809     op2 = rdxReg;
9810   }
9811 
9812   movq(op1, Address(in, len, Address::times_4,  8));
9813   rorq(op1, 32);
9814   movq(sum, Address(out, offset, Address::times_4,  8));
9815   rorq(sum, 32);
9816   if (UseBMI2Instructions) {
9817     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9818   }
9819   else {
9820     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9821   }
9822   // Store back in big endian from little endian
9823   rorq(sum, 0x20);
9824   movq(Address(out, offset, Address::times_4,  8), sum);
9825 
9826   movq(op1, Address(in, len, Address::times_4,  0));
9827   rorq(op1, 32);
9828   movq(sum, Address(out, offset, Address::times_4,  0));
9829   rorq(sum, 32);
9830   if (UseBMI2Instructions) {
9831     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9832   }
9833   else {
9834     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9835   }
9836   // Store back in big endian from little endian
9837   rorq(sum, 0x20);
9838   movq(Address(out, offset, Address::times_4,  0), sum);
9839 
9840   jmp(L_first_loop);
9841   bind(L_first_loop_exit);
9842 }
9843 
9844 /**
9845  * Code for BigInteger::mulAdd() intrinsic
9846  *
9847  * rdi: out
9848  * rsi: in
9849  * r11: offs (out.length - offset)
9850  * rcx: len
9851  * r8:  k
9852  * r12: tmp1
9853  * r13: tmp2
9854  * r14: tmp3
9855  * r15: tmp4
9856  * rbx: tmp5
9857  * Multiply the in[] by word k and add to out[], return the carry in rax
9858  */
9859 void MacroAssembler::mul_add(Register out, Register in, Register offs,
9860    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
9861    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9862 
9863   Label L_carry, L_last_in, L_done;
9864 
9865 // carry = 0;
9866 // for (int j=len-1; j >= 0; j--) {
9867 //    long product = (in[j] & LONG_MASK) * kLong +
9868 //                   (out[offs] & LONG_MASK) + carry;
9869 //    out[offs--] = (int)product;
9870 //    carry = product >>> 32;
9871 // }
9872 //
9873   push(tmp1);
9874   push(tmp2);
9875   push(tmp3);
9876   push(tmp4);
9877   push(tmp5);
9878 
9879   Register op2 = tmp2;
9880   const Register sum = tmp3;
9881   const Register op1 = tmp4;
9882   const Register carry =  tmp5;
9883 
9884   if (UseBMI2Instructions) {
9885     op2 = rdxReg;
9886     movl(op2, k);
9887   }
9888   else {
9889     movl(op2, k);
9890   }
9891 
9892   xorq(carry, carry);
9893 
9894   //First loop
9895 
9896   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
9897   //The carry is in tmp5
9898   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
9899 
9900   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
9901   decrementl(len);
9902   jccb(Assembler::negative, L_carry);
9903   decrementl(len);
9904   jccb(Assembler::negative, L_last_in);
9905 
9906   movq(op1, Address(in, len, Address::times_4,  0));
9907   rorq(op1, 32);
9908 
9909   subl(offs, 2);
9910   movq(sum, Address(out, offs, Address::times_4,  0));
9911   rorq(sum, 32);
9912 
9913   if (UseBMI2Instructions) {
9914     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9915   }
9916   else {
9917     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9918   }
9919 
9920   // Store back in big endian from little endian
9921   rorq(sum, 0x20);
9922   movq(Address(out, offs, Address::times_4,  0), sum);
9923 
9924   testl(len, len);
9925   jccb(Assembler::zero, L_carry);
9926 
9927   //Multiply the last in[] entry, if any
9928   bind(L_last_in);
9929   movl(op1, Address(in, 0));
9930   movl(sum, Address(out, offs, Address::times_4,  -4));
9931 
9932   movl(raxReg, k);
9933   mull(op1); //tmp4 * eax -> edx:eax
9934   addl(sum, carry);
9935   adcl(rdxReg, 0);
9936   addl(sum, raxReg);
9937   adcl(rdxReg, 0);
9938   movl(carry, rdxReg);
9939 
9940   movl(Address(out, offs, Address::times_4,  -4), sum);
9941 
9942   bind(L_carry);
9943   //return tmp5/carry as carry in rax
9944   movl(rax, carry);
9945 
9946   bind(L_done);
9947   pop(tmp5);
9948   pop(tmp4);
9949   pop(tmp3);
9950   pop(tmp2);
9951   pop(tmp1);
9952 }
9953 #endif
9954 
9955 /**
9956  * Emits code to update CRC-32 with a byte value according to constants in table
9957  *
9958  * @param [in,out]crc   Register containing the crc.
9959  * @param [in]val       Register containing the byte to fold into the CRC.
9960  * @param [in]table     Register containing the table of crc constants.
9961  *
9962  * uint32_t crc;
9963  * val = crc_table[(val ^ crc) & 0xFF];
9964  * crc = val ^ (crc >> 8);
9965  *
9966  */
9967 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
9968   xorl(val, crc);
9969   andl(val, 0xFF);
9970   shrl(crc, 8); // unsigned shift
9971   xorl(crc, Address(table, val, Address::times_4, 0));
9972 }
9973 
9974 /**
9975  * Fold 128-bit data chunk
9976  */
9977 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9978   if (UseAVX > 0) {
9979     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
9980     vpclmulldq(xcrc, xK, xcrc); // [63:0]
9981     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
9982     pxor(xcrc, xtmp);
9983   } else {
9984     movdqa(xtmp, xcrc);
9985     pclmulhdq(xtmp, xK);   // [123:64]
9986     pclmulldq(xcrc, xK);   // [63:0]
9987     pxor(xcrc, xtmp);
9988     movdqu(xtmp, Address(buf, offset));
9989     pxor(xcrc, xtmp);
9990   }
9991 }
9992 
9993 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
9994   if (UseAVX > 0) {
9995     vpclmulhdq(xtmp, xK, xcrc);
9996     vpclmulldq(xcrc, xK, xcrc);
9997     pxor(xcrc, xbuf);
9998     pxor(xcrc, xtmp);
9999   } else {
10000     movdqa(xtmp, xcrc);
10001     pclmulhdq(xtmp, xK);
10002     pclmulldq(xcrc, xK);
10003     pxor(xcrc, xbuf);
10004     pxor(xcrc, xtmp);
10005   }
10006 }
10007 
10008 /**
10009  * 8-bit folds to compute 32-bit CRC
10010  *
10011  * uint64_t xcrc;
10012  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
10013  */
10014 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
10015   movdl(tmp, xcrc);
10016   andl(tmp, 0xFF);
10017   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
10018   psrldq(xcrc, 1); // unsigned shift one byte
10019   pxor(xcrc, xtmp);
10020 }
10021 
10022 /**
10023  * uint32_t crc;
10024  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10025  */
10026 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10027   movl(tmp, crc);
10028   andl(tmp, 0xFF);
10029   shrl(crc, 8);
10030   xorl(crc, Address(table, tmp, Address::times_4, 0));
10031 }
10032 
10033 /**
10034  * @param crc   register containing existing CRC (32-bit)
10035  * @param buf   register pointing to input byte buffer (byte*)
10036  * @param len   register containing number of bytes
10037  * @param table register that will contain address of CRC table
10038  * @param tmp   scratch register
10039  */
10040 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10041   assert_different_registers(crc, buf, len, table, tmp, rax);
10042 
10043   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10044   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10045 
10046   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10047   // context for the registers used, where all instructions below are using 128-bit mode
10048   // On EVEX without VL and BW, these instructions will all be AVX.
10049   if (VM_Version::supports_avx512vlbw()) {
10050     movl(tmp, 0xffff);
10051     kmovwl(k1, tmp);
10052   }
10053 
10054   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10055   notl(crc); // ~crc
10056   cmpl(len, 16);
10057   jcc(Assembler::less, L_tail);
10058 
10059   // Align buffer to 16 bytes
10060   movl(tmp, buf);
10061   andl(tmp, 0xF);
10062   jccb(Assembler::zero, L_aligned);
10063   subl(tmp,  16);
10064   addl(len, tmp);
10065 
10066   align(4);
10067   BIND(L_align_loop);
10068   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10069   update_byte_crc32(crc, rax, table);
10070   increment(buf);
10071   incrementl(tmp);
10072   jccb(Assembler::less, L_align_loop);
10073 
10074   BIND(L_aligned);
10075   movl(tmp, len); // save
10076   shrl(len, 4);
10077   jcc(Assembler::zero, L_tail_restore);
10078 
10079   // Fold crc into first bytes of vector
10080   movdqa(xmm1, Address(buf, 0));
10081   movdl(rax, xmm1);
10082   xorl(crc, rax);
10083   pinsrd(xmm1, crc, 0);
10084   addptr(buf, 16);
10085   subl(len, 4); // len > 0
10086   jcc(Assembler::less, L_fold_tail);
10087 
10088   movdqa(xmm2, Address(buf,  0));
10089   movdqa(xmm3, Address(buf, 16));
10090   movdqa(xmm4, Address(buf, 32));
10091   addptr(buf, 48);
10092   subl(len, 3);
10093   jcc(Assembler::lessEqual, L_fold_512b);
10094 
10095   // Fold total 512 bits of polynomial on each iteration,
10096   // 128 bits per each of 4 parallel streams.
10097   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10098 
10099   align(32);
10100   BIND(L_fold_512b_loop);
10101   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10102   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10103   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10104   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10105   addptr(buf, 64);
10106   subl(len, 4);
10107   jcc(Assembler::greater, L_fold_512b_loop);
10108 
10109   // Fold 512 bits to 128 bits.
10110   BIND(L_fold_512b);
10111   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10112   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10113   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10114   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10115 
10116   // Fold the rest of 128 bits data chunks
10117   BIND(L_fold_tail);
10118   addl(len, 3);
10119   jccb(Assembler::lessEqual, L_fold_128b);
10120   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10121 
10122   BIND(L_fold_tail_loop);
10123   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10124   addptr(buf, 16);
10125   decrementl(len);
10126   jccb(Assembler::greater, L_fold_tail_loop);
10127 
10128   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10129   BIND(L_fold_128b);
10130   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10131   if (UseAVX > 0) {
10132     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10133     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10134     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10135   } else {
10136     movdqa(xmm2, xmm0);
10137     pclmulqdq(xmm2, xmm1, 0x1);
10138     movdqa(xmm3, xmm0);
10139     pand(xmm3, xmm2);
10140     pclmulqdq(xmm0, xmm3, 0x1);
10141   }
10142   psrldq(xmm1, 8);
10143   psrldq(xmm2, 4);
10144   pxor(xmm0, xmm1);
10145   pxor(xmm0, xmm2);
10146 
10147   // 8 8-bit folds to compute 32-bit CRC.
10148   for (int j = 0; j < 4; j++) {
10149     fold_8bit_crc32(xmm0, table, xmm1, rax);
10150   }
10151   movdl(crc, xmm0); // mov 32 bits to general register
10152   for (int j = 0; j < 4; j++) {
10153     fold_8bit_crc32(crc, table, rax);
10154   }
10155 
10156   BIND(L_tail_restore);
10157   movl(len, tmp); // restore
10158   BIND(L_tail);
10159   andl(len, 0xf);
10160   jccb(Assembler::zero, L_exit);
10161 
10162   // Fold the rest of bytes
10163   align(4);
10164   BIND(L_tail_loop);
10165   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10166   update_byte_crc32(crc, rax, table);
10167   increment(buf);
10168   decrementl(len);
10169   jccb(Assembler::greater, L_tail_loop);
10170 
10171   BIND(L_exit);
10172   notl(crc); // ~c
10173 }
10174 
10175 #ifdef _LP64
10176 // S. Gueron / Information Processing Letters 112 (2012) 184
10177 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10178 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10179 // Output: the 64-bit carry-less product of B * CONST
10180 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10181                                      Register tmp1, Register tmp2, Register tmp3) {
10182   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10183   if (n > 0) {
10184     addq(tmp3, n * 256 * 8);
10185   }
10186   //    Q1 = TABLEExt[n][B & 0xFF];
10187   movl(tmp1, in);
10188   andl(tmp1, 0x000000FF);
10189   shll(tmp1, 3);
10190   addq(tmp1, tmp3);
10191   movq(tmp1, Address(tmp1, 0));
10192 
10193   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10194   movl(tmp2, in);
10195   shrl(tmp2, 8);
10196   andl(tmp2, 0x000000FF);
10197   shll(tmp2, 3);
10198   addq(tmp2, tmp3);
10199   movq(tmp2, Address(tmp2, 0));
10200 
10201   shlq(tmp2, 8);
10202   xorq(tmp1, tmp2);
10203 
10204   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10205   movl(tmp2, in);
10206   shrl(tmp2, 16);
10207   andl(tmp2, 0x000000FF);
10208   shll(tmp2, 3);
10209   addq(tmp2, tmp3);
10210   movq(tmp2, Address(tmp2, 0));
10211 
10212   shlq(tmp2, 16);
10213   xorq(tmp1, tmp2);
10214 
10215   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10216   shrl(in, 24);
10217   andl(in, 0x000000FF);
10218   shll(in, 3);
10219   addq(in, tmp3);
10220   movq(in, Address(in, 0));
10221 
10222   shlq(in, 24);
10223   xorq(in, tmp1);
10224   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10225 }
10226 
10227 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10228                                       Register in_out,
10229                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10230                                       XMMRegister w_xtmp2,
10231                                       Register tmp1,
10232                                       Register n_tmp2, Register n_tmp3) {
10233   if (is_pclmulqdq_supported) {
10234     movdl(w_xtmp1, in_out); // modified blindly
10235 
10236     movl(tmp1, const_or_pre_comp_const_index);
10237     movdl(w_xtmp2, tmp1);
10238     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10239 
10240     movdq(in_out, w_xtmp1);
10241   } else {
10242     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10243   }
10244 }
10245 
10246 // Recombination Alternative 2: No bit-reflections
10247 // T1 = (CRC_A * U1) << 1
10248 // T2 = (CRC_B * U2) << 1
10249 // C1 = T1 >> 32
10250 // C2 = T2 >> 32
10251 // T1 = T1 & 0xFFFFFFFF
10252 // T2 = T2 & 0xFFFFFFFF
10253 // T1 = CRC32(0, T1)
10254 // T2 = CRC32(0, T2)
10255 // C1 = C1 ^ T1
10256 // C2 = C2 ^ T2
10257 // CRC = C1 ^ C2 ^ CRC_C
10258 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,
10259                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10260                                      Register tmp1, Register tmp2,
10261                                      Register n_tmp3) {
10262   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10263   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10264   shlq(in_out, 1);
10265   movl(tmp1, in_out);
10266   shrq(in_out, 32);
10267   xorl(tmp2, tmp2);
10268   crc32(tmp2, tmp1, 4);
10269   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10270   shlq(in1, 1);
10271   movl(tmp1, in1);
10272   shrq(in1, 32);
10273   xorl(tmp2, tmp2);
10274   crc32(tmp2, tmp1, 4);
10275   xorl(in1, tmp2);
10276   xorl(in_out, in1);
10277   xorl(in_out, in2);
10278 }
10279 
10280 // Set N to predefined value
10281 // Subtract from a lenght of a buffer
10282 // execute in a loop:
10283 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10284 // for i = 1 to N do
10285 //  CRC_A = CRC32(CRC_A, A[i])
10286 //  CRC_B = CRC32(CRC_B, B[i])
10287 //  CRC_C = CRC32(CRC_C, C[i])
10288 // end for
10289 // Recombine
10290 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,
10291                                        Register in_out1, Register in_out2, Register in_out3,
10292                                        Register tmp1, Register tmp2, Register tmp3,
10293                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10294                                        Register tmp4, Register tmp5,
10295                                        Register n_tmp6) {
10296   Label L_processPartitions;
10297   Label L_processPartition;
10298   Label L_exit;
10299 
10300   bind(L_processPartitions);
10301   cmpl(in_out1, 3 * size);
10302   jcc(Assembler::less, L_exit);
10303     xorl(tmp1, tmp1);
10304     xorl(tmp2, tmp2);
10305     movq(tmp3, in_out2);
10306     addq(tmp3, size);
10307 
10308     bind(L_processPartition);
10309       crc32(in_out3, Address(in_out2, 0), 8);
10310       crc32(tmp1, Address(in_out2, size), 8);
10311       crc32(tmp2, Address(in_out2, size * 2), 8);
10312       addq(in_out2, 8);
10313       cmpq(in_out2, tmp3);
10314       jcc(Assembler::less, L_processPartition);
10315     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10316             w_xtmp1, w_xtmp2, w_xtmp3,
10317             tmp4, tmp5,
10318             n_tmp6);
10319     addq(in_out2, 2 * size);
10320     subl(in_out1, 3 * size);
10321     jmp(L_processPartitions);
10322 
10323   bind(L_exit);
10324 }
10325 #else
10326 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10327                                      Register tmp1, Register tmp2, Register tmp3,
10328                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10329   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10330   if (n > 0) {
10331     addl(tmp3, n * 256 * 8);
10332   }
10333   //    Q1 = TABLEExt[n][B & 0xFF];
10334   movl(tmp1, in_out);
10335   andl(tmp1, 0x000000FF);
10336   shll(tmp1, 3);
10337   addl(tmp1, tmp3);
10338   movq(xtmp1, Address(tmp1, 0));
10339 
10340   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10341   movl(tmp2, in_out);
10342   shrl(tmp2, 8);
10343   andl(tmp2, 0x000000FF);
10344   shll(tmp2, 3);
10345   addl(tmp2, tmp3);
10346   movq(xtmp2, Address(tmp2, 0));
10347 
10348   psllq(xtmp2, 8);
10349   pxor(xtmp1, xtmp2);
10350 
10351   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10352   movl(tmp2, in_out);
10353   shrl(tmp2, 16);
10354   andl(tmp2, 0x000000FF);
10355   shll(tmp2, 3);
10356   addl(tmp2, tmp3);
10357   movq(xtmp2, Address(tmp2, 0));
10358 
10359   psllq(xtmp2, 16);
10360   pxor(xtmp1, xtmp2);
10361 
10362   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10363   shrl(in_out, 24);
10364   andl(in_out, 0x000000FF);
10365   shll(in_out, 3);
10366   addl(in_out, tmp3);
10367   movq(xtmp2, Address(in_out, 0));
10368 
10369   psllq(xtmp2, 24);
10370   pxor(xtmp1, xtmp2); // Result in CXMM
10371   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10372 }
10373 
10374 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10375                                       Register in_out,
10376                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10377                                       XMMRegister w_xtmp2,
10378                                       Register tmp1,
10379                                       Register n_tmp2, Register n_tmp3) {
10380   if (is_pclmulqdq_supported) {
10381     movdl(w_xtmp1, in_out);
10382 
10383     movl(tmp1, const_or_pre_comp_const_index);
10384     movdl(w_xtmp2, tmp1);
10385     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10386     // Keep result in XMM since GPR is 32 bit in length
10387   } else {
10388     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10389   }
10390 }
10391 
10392 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,
10393                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10394                                      Register tmp1, Register tmp2,
10395                                      Register n_tmp3) {
10396   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10397   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10398 
10399   psllq(w_xtmp1, 1);
10400   movdl(tmp1, w_xtmp1);
10401   psrlq(w_xtmp1, 32);
10402   movdl(in_out, w_xtmp1);
10403 
10404   xorl(tmp2, tmp2);
10405   crc32(tmp2, tmp1, 4);
10406   xorl(in_out, tmp2);
10407 
10408   psllq(w_xtmp2, 1);
10409   movdl(tmp1, w_xtmp2);
10410   psrlq(w_xtmp2, 32);
10411   movdl(in1, w_xtmp2);
10412 
10413   xorl(tmp2, tmp2);
10414   crc32(tmp2, tmp1, 4);
10415   xorl(in1, tmp2);
10416   xorl(in_out, in1);
10417   xorl(in_out, in2);
10418 }
10419 
10420 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,
10421                                        Register in_out1, Register in_out2, Register in_out3,
10422                                        Register tmp1, Register tmp2, Register tmp3,
10423                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10424                                        Register tmp4, Register tmp5,
10425                                        Register n_tmp6) {
10426   Label L_processPartitions;
10427   Label L_processPartition;
10428   Label L_exit;
10429 
10430   bind(L_processPartitions);
10431   cmpl(in_out1, 3 * size);
10432   jcc(Assembler::less, L_exit);
10433     xorl(tmp1, tmp1);
10434     xorl(tmp2, tmp2);
10435     movl(tmp3, in_out2);
10436     addl(tmp3, size);
10437 
10438     bind(L_processPartition);
10439       crc32(in_out3, Address(in_out2, 0), 4);
10440       crc32(tmp1, Address(in_out2, size), 4);
10441       crc32(tmp2, Address(in_out2, size*2), 4);
10442       crc32(in_out3, Address(in_out2, 0+4), 4);
10443       crc32(tmp1, Address(in_out2, size+4), 4);
10444       crc32(tmp2, Address(in_out2, size*2+4), 4);
10445       addl(in_out2, 8);
10446       cmpl(in_out2, tmp3);
10447       jcc(Assembler::less, L_processPartition);
10448 
10449         push(tmp3);
10450         push(in_out1);
10451         push(in_out2);
10452         tmp4 = tmp3;
10453         tmp5 = in_out1;
10454         n_tmp6 = in_out2;
10455 
10456       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10457             w_xtmp1, w_xtmp2, w_xtmp3,
10458             tmp4, tmp5,
10459             n_tmp6);
10460 
10461         pop(in_out2);
10462         pop(in_out1);
10463         pop(tmp3);
10464 
10465     addl(in_out2, 2 * size);
10466     subl(in_out1, 3 * size);
10467     jmp(L_processPartitions);
10468 
10469   bind(L_exit);
10470 }
10471 #endif //LP64
10472 
10473 #ifdef _LP64
10474 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10475 // Input: A buffer I of L bytes.
10476 // Output: the CRC32C value of the buffer.
10477 // Notations:
10478 // Write L = 24N + r, with N = floor (L/24).
10479 // r = L mod 24 (0 <= r < 24).
10480 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10481 // N quadwords, and R consists of r bytes.
10482 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10483 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10484 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10485 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10486 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10487                                           Register tmp1, Register tmp2, Register tmp3,
10488                                           Register tmp4, Register tmp5, Register tmp6,
10489                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10490                                           bool is_pclmulqdq_supported) {
10491   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10492   Label L_wordByWord;
10493   Label L_byteByByteProlog;
10494   Label L_byteByByte;
10495   Label L_exit;
10496 
10497   if (is_pclmulqdq_supported ) {
10498     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10499     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10500 
10501     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10502     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10503 
10504     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10505     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10506     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10507   } else {
10508     const_or_pre_comp_const_index[0] = 1;
10509     const_or_pre_comp_const_index[1] = 0;
10510 
10511     const_or_pre_comp_const_index[2] = 3;
10512     const_or_pre_comp_const_index[3] = 2;
10513 
10514     const_or_pre_comp_const_index[4] = 5;
10515     const_or_pre_comp_const_index[5] = 4;
10516    }
10517   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10518                     in2, in1, in_out,
10519                     tmp1, tmp2, tmp3,
10520                     w_xtmp1, w_xtmp2, w_xtmp3,
10521                     tmp4, tmp5,
10522                     tmp6);
10523   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10524                     in2, in1, in_out,
10525                     tmp1, tmp2, tmp3,
10526                     w_xtmp1, w_xtmp2, w_xtmp3,
10527                     tmp4, tmp5,
10528                     tmp6);
10529   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10530                     in2, in1, in_out,
10531                     tmp1, tmp2, tmp3,
10532                     w_xtmp1, w_xtmp2, w_xtmp3,
10533                     tmp4, tmp5,
10534                     tmp6);
10535   movl(tmp1, in2);
10536   andl(tmp1, 0x00000007);
10537   negl(tmp1);
10538   addl(tmp1, in2);
10539   addq(tmp1, in1);
10540 
10541   BIND(L_wordByWord);
10542   cmpq(in1, tmp1);
10543   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10544     crc32(in_out, Address(in1, 0), 4);
10545     addq(in1, 4);
10546     jmp(L_wordByWord);
10547 
10548   BIND(L_byteByByteProlog);
10549   andl(in2, 0x00000007);
10550   movl(tmp2, 1);
10551 
10552   BIND(L_byteByByte);
10553   cmpl(tmp2, in2);
10554   jccb(Assembler::greater, L_exit);
10555     crc32(in_out, Address(in1, 0), 1);
10556     incq(in1);
10557     incl(tmp2);
10558     jmp(L_byteByByte);
10559 
10560   BIND(L_exit);
10561 }
10562 #else
10563 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10564                                           Register tmp1, Register  tmp2, Register tmp3,
10565                                           Register tmp4, Register  tmp5, Register tmp6,
10566                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10567                                           bool is_pclmulqdq_supported) {
10568   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10569   Label L_wordByWord;
10570   Label L_byteByByteProlog;
10571   Label L_byteByByte;
10572   Label L_exit;
10573 
10574   if (is_pclmulqdq_supported) {
10575     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10576     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10577 
10578     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10579     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10580 
10581     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10582     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10583   } else {
10584     const_or_pre_comp_const_index[0] = 1;
10585     const_or_pre_comp_const_index[1] = 0;
10586 
10587     const_or_pre_comp_const_index[2] = 3;
10588     const_or_pre_comp_const_index[3] = 2;
10589 
10590     const_or_pre_comp_const_index[4] = 5;
10591     const_or_pre_comp_const_index[5] = 4;
10592   }
10593   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10594                     in2, in1, in_out,
10595                     tmp1, tmp2, tmp3,
10596                     w_xtmp1, w_xtmp2, w_xtmp3,
10597                     tmp4, tmp5,
10598                     tmp6);
10599   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10600                     in2, in1, in_out,
10601                     tmp1, tmp2, tmp3,
10602                     w_xtmp1, w_xtmp2, w_xtmp3,
10603                     tmp4, tmp5,
10604                     tmp6);
10605   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10606                     in2, in1, in_out,
10607                     tmp1, tmp2, tmp3,
10608                     w_xtmp1, w_xtmp2, w_xtmp3,
10609                     tmp4, tmp5,
10610                     tmp6);
10611   movl(tmp1, in2);
10612   andl(tmp1, 0x00000007);
10613   negl(tmp1);
10614   addl(tmp1, in2);
10615   addl(tmp1, in1);
10616 
10617   BIND(L_wordByWord);
10618   cmpl(in1, tmp1);
10619   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10620     crc32(in_out, Address(in1,0), 4);
10621     addl(in1, 4);
10622     jmp(L_wordByWord);
10623 
10624   BIND(L_byteByByteProlog);
10625   andl(in2, 0x00000007);
10626   movl(tmp2, 1);
10627 
10628   BIND(L_byteByByte);
10629   cmpl(tmp2, in2);
10630   jccb(Assembler::greater, L_exit);
10631     movb(tmp1, Address(in1, 0));
10632     crc32(in_out, tmp1, 1);
10633     incl(in1);
10634     incl(tmp2);
10635     jmp(L_byteByByte);
10636 
10637   BIND(L_exit);
10638 }
10639 #endif // LP64
10640 #undef BIND
10641 #undef BLOCK_COMMENT
10642 
10643 
10644 // Compress char[] array to byte[].
10645 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10646                                          XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10647                                          XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10648                                          Register tmp5, Register result) {
10649   Label copy_chars_loop, return_length, return_zero, done;
10650 
10651   // rsi: src
10652   // rdi: dst
10653   // rdx: len
10654   // rcx: tmp5
10655   // rax: result
10656 
10657   // rsi holds start addr of source char[] to be compressed
10658   // rdi holds start addr of destination byte[]
10659   // rdx holds length
10660 
10661   assert(len != result, "");
10662 
10663   // save length for return
10664   push(len);
10665 
10666   if (UseSSE42Intrinsics) {
10667     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
10668     Label copy_32_loop, copy_16, copy_tail;
10669 
10670     movl(result, len);
10671     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
10672 
10673     // vectored compression
10674     andl(len, 0xfffffff0);    // vector count (in chars)
10675     andl(result, 0x0000000f);    // tail count (in chars)
10676     testl(len, len);
10677     jccb(Assembler::zero, copy_16);
10678 
10679     // compress 16 chars per iter
10680     movdl(tmp1Reg, tmp5);
10681     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10682     pxor(tmp4Reg, tmp4Reg);
10683 
10684     lea(src, Address(src, len, Address::times_2));
10685     lea(dst, Address(dst, len, Address::times_1));
10686     negptr(len);
10687 
10688     bind(copy_32_loop);
10689     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
10690     por(tmp4Reg, tmp2Reg);
10691     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
10692     por(tmp4Reg, tmp3Reg);
10693     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
10694     jcc(Assembler::notZero, return_zero);
10695     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
10696     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
10697     addptr(len, 16);
10698     jcc(Assembler::notZero, copy_32_loop);
10699 
10700     // compress next vector of 8 chars (if any)
10701     bind(copy_16);
10702     movl(len, result);
10703     andl(len, 0xfffffff8);    // vector count (in chars)
10704     andl(result, 0x00000007);    // tail count (in chars)
10705     testl(len, len);
10706     jccb(Assembler::zero, copy_tail);
10707 
10708     movdl(tmp1Reg, tmp5);
10709     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10710     pxor(tmp3Reg, tmp3Reg);
10711 
10712     movdqu(tmp2Reg, Address(src, 0));
10713     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
10714     jccb(Assembler::notZero, return_zero);
10715     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
10716     movq(Address(dst, 0), tmp2Reg);
10717     addptr(src, 16);
10718     addptr(dst, 8);
10719 
10720     bind(copy_tail);
10721     movl(len, result);
10722   }
10723   // compress 1 char per iter
10724   testl(len, len);
10725   jccb(Assembler::zero, return_length);
10726   lea(src, Address(src, len, Address::times_2));
10727   lea(dst, Address(dst, len, Address::times_1));
10728   negptr(len);
10729 
10730   bind(copy_chars_loop);
10731   load_unsigned_short(result, Address(src, len, Address::times_2));
10732   testl(result, 0xff00);      // check if Unicode char
10733   jccb(Assembler::notZero, return_zero);
10734   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
10735   increment(len);
10736   jcc(Assembler::notZero, copy_chars_loop);
10737 
10738   // if compression succeeded, return length
10739   bind(return_length);
10740   pop(result);
10741   jmpb(done);
10742 
10743   // if compression failed, return 0
10744   bind(return_zero);
10745   xorl(result, result);
10746   addptr(rsp, wordSize);
10747 
10748   bind(done);
10749 }
10750 
10751 // Inflate byte[] array to char[].
10752 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
10753                                         XMMRegister tmp1, Register tmp2) {
10754   Label copy_chars_loop, done;
10755 
10756   // rsi: src
10757   // rdi: dst
10758   // rdx: len
10759   // rcx: tmp2
10760 
10761   // rsi holds start addr of source byte[] to be inflated
10762   // rdi holds start addr of destination char[]
10763   // rdx holds length
10764   assert_different_registers(src, dst, len, tmp2);
10765 
10766   if (UseSSE42Intrinsics) {
10767     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
10768     Label copy_8_loop, copy_bytes, copy_tail;
10769 
10770     movl(tmp2, len);
10771     andl(tmp2, 0x00000007);   // tail count (in chars)
10772     andl(len, 0xfffffff8);    // vector count (in chars)
10773     jccb(Assembler::zero, copy_tail);
10774 
10775     // vectored inflation
10776     lea(src, Address(src, len, Address::times_1));
10777     lea(dst, Address(dst, len, Address::times_2));
10778     negptr(len);
10779 
10780     // inflate 8 chars per iter
10781     bind(copy_8_loop);
10782     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
10783     movdqu(Address(dst, len, Address::times_2), tmp1);
10784     addptr(len, 8);
10785     jcc(Assembler::notZero, copy_8_loop);
10786 
10787     bind(copy_tail);
10788     movl(len, tmp2);
10789 
10790     cmpl(len, 4);
10791     jccb(Assembler::less, copy_bytes);
10792 
10793     movdl(tmp1, Address(src, 0));  // load 4 byte chars
10794     pmovzxbw(tmp1, tmp1);
10795     movq(Address(dst, 0), tmp1);
10796     subptr(len, 4);
10797     addptr(src, 4);
10798     addptr(dst, 8);
10799 
10800     bind(copy_bytes);
10801   }
10802   testl(len, len);
10803   jccb(Assembler::zero, done);
10804   lea(src, Address(src, len, Address::times_1));
10805   lea(dst, Address(dst, len, Address::times_2));
10806   negptr(len);
10807 
10808   // inflate 1 char per iter
10809   bind(copy_chars_loop);
10810   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
10811   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
10812   increment(len);
10813   jcc(Assembler::notZero, copy_chars_loop);
10814 
10815   bind(done);
10816 }
10817 
10818 
10819 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
10820   switch (cond) {
10821     // Note some conditions are synonyms for others
10822     case Assembler::zero:         return Assembler::notZero;
10823     case Assembler::notZero:      return Assembler::zero;
10824     case Assembler::less:         return Assembler::greaterEqual;
10825     case Assembler::lessEqual:    return Assembler::greater;
10826     case Assembler::greater:      return Assembler::lessEqual;
10827     case Assembler::greaterEqual: return Assembler::less;
10828     case Assembler::below:        return Assembler::aboveEqual;
10829     case Assembler::belowEqual:   return Assembler::above;
10830     case Assembler::above:        return Assembler::belowEqual;
10831     case Assembler::aboveEqual:   return Assembler::below;
10832     case Assembler::overflow:     return Assembler::noOverflow;
10833     case Assembler::noOverflow:   return Assembler::overflow;
10834     case Assembler::negative:     return Assembler::positive;
10835     case Assembler::positive:     return Assembler::negative;
10836     case Assembler::parity:       return Assembler::noParity;
10837     case Assembler::noParity:     return Assembler::parity;
10838   }
10839   ShouldNotReachHere(); return Assembler::overflow;
10840 }
10841 
10842 SkipIfEqual::SkipIfEqual(
10843     MacroAssembler* masm, const bool* flag_addr, bool value) {
10844   _masm = masm;
10845   _masm->cmp8(ExternalAddress((address)flag_addr), value);
10846   _masm->jcc(Assembler::equal, _label);
10847 }
10848 
10849 SkipIfEqual::~SkipIfEqual() {
10850   _masm->bind(_label);
10851 }
10852 
10853 // 32-bit Windows has its own fast-path implementation
10854 // of get_thread
10855 #if !defined(WIN32) || defined(_LP64)
10856 
10857 // This is simply a call to Thread::current()
10858 void MacroAssembler::get_thread(Register thread) {
10859   if (thread != rax) {
10860     push(rax);
10861   }
10862   LP64_ONLY(push(rdi);)
10863   LP64_ONLY(push(rsi);)
10864   push(rdx);
10865   push(rcx);
10866 #ifdef _LP64
10867   push(r8);
10868   push(r9);
10869   push(r10);
10870   push(r11);
10871 #endif
10872 
10873   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
10874 
10875 #ifdef _LP64
10876   pop(r11);
10877   pop(r10);
10878   pop(r9);
10879   pop(r8);
10880 #endif
10881   pop(rcx);
10882   pop(rdx);
10883   LP64_ONLY(pop(rsi);)
10884   LP64_ONLY(pop(rdi);)
10885   if (thread != rax) {
10886     mov(thread, rax);
10887     pop(rax);
10888   }
10889 }
10890 
10891 #endif