1 /*
   2  * Copyright (c) 1997, 2021, 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 "jvm.h"
  27 #include "asm/assembler.hpp"
  28 #include "asm/assembler.inline.hpp"
  29 #include "compiler/compiler_globals.hpp"
  30 #include "compiler/disassembler.hpp"
  31 #include "gc/shared/barrierSet.hpp"
  32 #include "gc/shared/barrierSetAssembler.hpp"
  33 #include "gc/shared/collectedHeap.inline.hpp"
  34 #include "gc/shared/tlab_globals.hpp"
  35 #include "interpreter/bytecodeHistogram.hpp"
  36 #include "interpreter/interpreter.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "memory/universe.hpp"
  39 #include "oops/accessDecorators.hpp"
  40 #include "oops/compressedOops.inline.hpp"
  41 #include "oops/klass.inline.hpp"
  42 #include "prims/methodHandles.hpp"
  43 #include "runtime/flags/flagSetting.hpp"
  44 #include "runtime/interfaceSupport.inline.hpp"
  45 #include "runtime/jniHandles.hpp"
  46 #include "runtime/objectMonitor.hpp"
  47 #include "runtime/os.hpp"
  48 #include "runtime/safepoint.hpp"
  49 #include "runtime/safepointMechanism.hpp"
  50 #include "runtime/sharedRuntime.hpp"
  51 #include "runtime/stubRoutines.hpp"
  52 #include "runtime/thread.hpp"
  53 #include "utilities/macros.hpp"
  54 #include "crc32c.h"
  55 
  56 #ifdef PRODUCT
  57 #define BLOCK_COMMENT(str) /* nothing */
  58 #define STOP(error) stop(error)
  59 #else
  60 #define BLOCK_COMMENT(str) block_comment(str)
  61 #define STOP(error) block_comment(error); stop(error)
  62 #endif
  63 
  64 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  65 
  66 #ifdef ASSERT
  67 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  68 #endif
  69 
  70 static Assembler::Condition reverse[] = {
  71     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  72     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  73     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  74     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  75     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  76     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  77     Assembler::above          /* belowEqual    = 0x6 */ ,
  78     Assembler::belowEqual     /* above         = 0x7 */ ,
  79     Assembler::positive       /* negative      = 0x8 */ ,
  80     Assembler::negative       /* positive      = 0x9 */ ,
  81     Assembler::noParity       /* parity        = 0xa */ ,
  82     Assembler::parity         /* noParity      = 0xb */ ,
  83     Assembler::greaterEqual   /* less          = 0xc */ ,
  84     Assembler::less           /* greaterEqual  = 0xd */ ,
  85     Assembler::greater        /* lessEqual     = 0xe */ ,
  86     Assembler::lessEqual      /* greater       = 0xf, */
  87 
  88 };
  89 
  90 
  91 // Implementation of MacroAssembler
  92 
  93 // First all the versions that have distinct versions depending on 32/64 bit
  94 // Unless the difference is trivial (1 line or so).
  95 
  96 #ifndef _LP64
  97 
  98 // 32bit versions
  99 
 100 Address MacroAssembler::as_Address(AddressLiteral adr) {
 101   return Address(adr.target(), adr.rspec());
 102 }
 103 
 104 Address MacroAssembler::as_Address(ArrayAddress adr) {
 105   return Address::make_array(adr);
 106 }
 107 
 108 void MacroAssembler::call_VM_leaf_base(address entry_point,
 109                                        int number_of_arguments) {
 110   call(RuntimeAddress(entry_point));
 111   increment(rsp, number_of_arguments * wordSize);
 112 }
 113 
 114 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 115   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 116 }
 117 
 118 
 119 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 120   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 121 }
 122 
 123 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 124   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 125 }
 126 
 127 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 128   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 129 }
 130 
 131 void MacroAssembler::extend_sign(Register hi, Register lo) {
 132   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 133   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 134     cdql();
 135   } else {
 136     movl(hi, lo);
 137     sarl(hi, 31);
 138   }
 139 }
 140 
 141 void MacroAssembler::jC2(Register tmp, Label& L) {
 142   // set parity bit if FPU flag C2 is set (via rax)
 143   save_rax(tmp);
 144   fwait(); fnstsw_ax();
 145   sahf();
 146   restore_rax(tmp);
 147   // branch
 148   jcc(Assembler::parity, L);
 149 }
 150 
 151 void MacroAssembler::jnC2(Register tmp, Label& L) {
 152   // set parity bit if FPU flag C2 is set (via rax)
 153   save_rax(tmp);
 154   fwait(); fnstsw_ax();
 155   sahf();
 156   restore_rax(tmp);
 157   // branch
 158   jcc(Assembler::noParity, L);
 159 }
 160 
 161 // 32bit can do a case table jump in one instruction but we no longer allow the base
 162 // to be installed in the Address class
 163 void MacroAssembler::jump(ArrayAddress entry) {
 164   jmp(as_Address(entry));
 165 }
 166 
 167 // Note: y_lo will be destroyed
 168 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 169   // Long compare for Java (semantics as described in JVM spec.)
 170   Label high, low, done;
 171 
 172   cmpl(x_hi, y_hi);
 173   jcc(Assembler::less, low);
 174   jcc(Assembler::greater, high);
 175   // x_hi is the return register
 176   xorl(x_hi, x_hi);
 177   cmpl(x_lo, y_lo);
 178   jcc(Assembler::below, low);
 179   jcc(Assembler::equal, done);
 180 
 181   bind(high);
 182   xorl(x_hi, x_hi);
 183   increment(x_hi);
 184   jmp(done);
 185 
 186   bind(low);
 187   xorl(x_hi, x_hi);
 188   decrementl(x_hi);
 189 
 190   bind(done);
 191 }
 192 
 193 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 194     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 195 }
 196 
 197 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 198   // leal(dst, as_Address(adr));
 199   // see note in movl as to why we must use a move
 200   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 201 }
 202 
 203 void MacroAssembler::leave() {
 204   mov(rsp, rbp);
 205   pop(rbp);
 206 }
 207 
 208 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 209   // Multiplication of two Java long values stored on the stack
 210   // as illustrated below. Result is in rdx:rax.
 211   //
 212   // rsp ---> [  ??  ] \               \
 213   //            ....    | y_rsp_offset  |
 214   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 215   //          [ y_hi ]                  | (in bytes)
 216   //            ....                    |
 217   //          [ x_lo ]                 /
 218   //          [ x_hi ]
 219   //            ....
 220   //
 221   // Basic idea: lo(result) = lo(x_lo * y_lo)
 222   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 223   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 224   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 225   Label quick;
 226   // load x_hi, y_hi and check if quick
 227   // multiplication is possible
 228   movl(rbx, x_hi);
 229   movl(rcx, y_hi);
 230   movl(rax, rbx);
 231   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 232   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 233   // do full multiplication
 234   // 1st step
 235   mull(y_lo);                                    // x_hi * y_lo
 236   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 237   // 2nd step
 238   movl(rax, x_lo);
 239   mull(rcx);                                     // x_lo * y_hi
 240   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 241   // 3rd step
 242   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 243   movl(rax, x_lo);
 244   mull(y_lo);                                    // x_lo * y_lo
 245   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 246 }
 247 
 248 void MacroAssembler::lneg(Register hi, Register lo) {
 249   negl(lo);
 250   adcl(hi, 0);
 251   negl(hi);
 252 }
 253 
 254 void MacroAssembler::lshl(Register hi, Register lo) {
 255   // Java shift left long support (semantics as described in JVM spec., p.305)
 256   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 257   // shift value is in rcx !
 258   assert(hi != rcx, "must not use rcx");
 259   assert(lo != rcx, "must not use rcx");
 260   const Register s = rcx;                        // shift count
 261   const int      n = BitsPerWord;
 262   Label L;
 263   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 264   cmpl(s, n);                                    // if (s < n)
 265   jcc(Assembler::less, L);                       // else (s >= n)
 266   movl(hi, lo);                                  // x := x << n
 267   xorl(lo, lo);
 268   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 269   bind(L);                                       // s (mod n) < n
 270   shldl(hi, lo);                                 // x := x << s
 271   shll(lo);
 272 }
 273 
 274 
 275 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 276   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 277   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 278   assert(hi != rcx, "must not use rcx");
 279   assert(lo != rcx, "must not use rcx");
 280   const Register s = rcx;                        // shift count
 281   const int      n = BitsPerWord;
 282   Label L;
 283   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 284   cmpl(s, n);                                    // if (s < n)
 285   jcc(Assembler::less, L);                       // else (s >= n)
 286   movl(lo, hi);                                  // x := x >> n
 287   if (sign_extension) sarl(hi, 31);
 288   else                xorl(hi, hi);
 289   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 290   bind(L);                                       // s (mod n) < n
 291   shrdl(lo, hi);                                 // x := x >> s
 292   if (sign_extension) sarl(hi);
 293   else                shrl(hi);
 294 }
 295 
 296 void MacroAssembler::movoop(Register dst, jobject obj) {
 297   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 298 }
 299 
 300 void MacroAssembler::movoop(Address dst, jobject obj) {
 301   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 302 }
 303 
 304 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 305   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 306 }
 307 
 308 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 309   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 310 }
 311 
 312 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 313   // scratch register is not used,
 314   // it is defined to match parameters of 64-bit version of this method.
 315   if (src.is_lval()) {
 316     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 317   } else {
 318     movl(dst, as_Address(src));
 319   }
 320 }
 321 
 322 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 323   movl(as_Address(dst), src);
 324 }
 325 
 326 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 327   movl(dst, as_Address(src));
 328 }
 329 
 330 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 331 void MacroAssembler::movptr(Address dst, intptr_t src) {
 332   movl(dst, src);
 333 }
 334 
 335 
 336 void MacroAssembler::pop_callee_saved_registers() {
 337   pop(rcx);
 338   pop(rdx);
 339   pop(rdi);
 340   pop(rsi);
 341 }
 342 
 343 void MacroAssembler::push_callee_saved_registers() {
 344   push(rsi);
 345   push(rdi);
 346   push(rdx);
 347   push(rcx);
 348 }
 349 
 350 void MacroAssembler::pushoop(jobject obj) {
 351   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 352 }
 353 
 354 void MacroAssembler::pushklass(Metadata* obj) {
 355   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 356 }
 357 
 358 void MacroAssembler::pushptr(AddressLiteral src) {
 359   if (src.is_lval()) {
 360     push_literal32((int32_t)src.target(), src.rspec());
 361   } else {
 362     pushl(as_Address(src));
 363   }
 364 }
 365 
 366 static void pass_arg0(MacroAssembler* masm, Register arg) {
 367   masm->push(arg);
 368 }
 369 
 370 static void pass_arg1(MacroAssembler* masm, Register arg) {
 371   masm->push(arg);
 372 }
 373 
 374 static void pass_arg2(MacroAssembler* masm, Register arg) {
 375   masm->push(arg);
 376 }
 377 
 378 static void pass_arg3(MacroAssembler* masm, Register arg) {
 379   masm->push(arg);
 380 }
 381 
 382 #ifndef PRODUCT
 383 extern "C" void findpc(intptr_t x);
 384 #endif
 385 
 386 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 387   // In order to get locks to work, we need to fake a in_VM state
 388   JavaThread* thread = JavaThread::current();
 389   JavaThreadState saved_state = thread->thread_state();
 390   thread->set_thread_state(_thread_in_vm);
 391   if (ShowMessageBoxOnError) {
 392     JavaThread* thread = JavaThread::current();
 393     JavaThreadState saved_state = thread->thread_state();
 394     thread->set_thread_state(_thread_in_vm);
 395     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 396       ttyLocker ttyl;
 397       BytecodeCounter::print();
 398     }
 399     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 400     // This is the value of eip which points to where verify_oop will return.
 401     if (os::message_box(msg, "Execution stopped, print registers?")) {
 402       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 403       BREAKPOINT;
 404     }
 405   }
 406   fatal("DEBUG MESSAGE: %s", msg);
 407 }
 408 
 409 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 410   ttyLocker ttyl;
 411   FlagSetting fs(Debugging, true);
 412   tty->print_cr("eip = 0x%08x", eip);
 413 #ifndef PRODUCT
 414   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 415     tty->cr();
 416     findpc(eip);
 417     tty->cr();
 418   }
 419 #endif
 420 #define PRINT_REG(rax) \
 421   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 422   PRINT_REG(rax);
 423   PRINT_REG(rbx);
 424   PRINT_REG(rcx);
 425   PRINT_REG(rdx);
 426   PRINT_REG(rdi);
 427   PRINT_REG(rsi);
 428   PRINT_REG(rbp);
 429   PRINT_REG(rsp);
 430 #undef PRINT_REG
 431   // Print some words near top of staack.
 432   int* dump_sp = (int*) rsp;
 433   for (int col1 = 0; col1 < 8; col1++) {
 434     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 435     os::print_location(tty, *dump_sp++);
 436   }
 437   for (int row = 0; row < 16; row++) {
 438     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 439     for (int col = 0; col < 8; col++) {
 440       tty->print(" 0x%08x", *dump_sp++);
 441     }
 442     tty->cr();
 443   }
 444   // Print some instructions around pc:
 445   Disassembler::decode((address)eip-64, (address)eip);
 446   tty->print_cr("--------");
 447   Disassembler::decode((address)eip, (address)eip+32);
 448 }
 449 
 450 void MacroAssembler::stop(const char* msg) {
 451   ExternalAddress message((address)msg);
 452   // push address of message
 453   pushptr(message.addr());
 454   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 455   pusha();                                            // push registers
 456   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 457   hlt();
 458 }
 459 
 460 void MacroAssembler::warn(const char* msg) {
 461   push_CPU_state();
 462 
 463   ExternalAddress message((address) msg);
 464   // push address of message
 465   pushptr(message.addr());
 466 
 467   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 468   addl(rsp, wordSize);       // discard argument
 469   pop_CPU_state();
 470 }
 471 
 472 void MacroAssembler::print_state() {
 473   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 474   pusha();                                            // push registers
 475 
 476   push_CPU_state();
 477   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 478   pop_CPU_state();
 479 
 480   popa();
 481   addl(rsp, wordSize);
 482 }
 483 
 484 #else // _LP64
 485 
 486 // 64 bit versions
 487 
 488 Address MacroAssembler::as_Address(AddressLiteral adr) {
 489   // amd64 always does this as a pc-rel
 490   // we can be absolute or disp based on the instruction type
 491   // jmp/call are displacements others are absolute
 492   assert(!adr.is_lval(), "must be rval");
 493   assert(reachable(adr), "must be");
 494   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 495 
 496 }
 497 
 498 Address MacroAssembler::as_Address(ArrayAddress adr) {
 499   AddressLiteral base = adr.base();
 500   lea(rscratch1, base);
 501   Address index = adr.index();
 502   assert(index._disp == 0, "must not have disp"); // maybe it can?
 503   Address array(rscratch1, index._index, index._scale, index._disp);
 504   return array;
 505 }
 506 
 507 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 508   Label L, E;
 509 
 510 #ifdef _WIN64
 511   // Windows always allocates space for it's register args
 512   assert(num_args <= 4, "only register arguments supported");
 513   subq(rsp,  frame::arg_reg_save_area_bytes);
 514 #endif
 515 
 516   // Align stack if necessary
 517   testl(rsp, 15);
 518   jcc(Assembler::zero, L);
 519 
 520   subq(rsp, 8);
 521   {
 522     call(RuntimeAddress(entry_point));
 523   }
 524   addq(rsp, 8);
 525   jmp(E);
 526 
 527   bind(L);
 528   {
 529     call(RuntimeAddress(entry_point));
 530   }
 531 
 532   bind(E);
 533 
 534 #ifdef _WIN64
 535   // restore stack pointer
 536   addq(rsp, frame::arg_reg_save_area_bytes);
 537 #endif
 538 
 539 }
 540 
 541 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 542   assert(!src2.is_lval(), "should use cmpptr");
 543 
 544   if (reachable(src2)) {
 545     cmpq(src1, as_Address(src2));
 546   } else {
 547     lea(rscratch1, src2);
 548     Assembler::cmpq(src1, Address(rscratch1, 0));
 549   }
 550 }
 551 
 552 int MacroAssembler::corrected_idivq(Register reg) {
 553   // Full implementation of Java ldiv and lrem; checks for special
 554   // case as described in JVM spec., p.243 & p.271.  The function
 555   // returns the (pc) offset of the idivl instruction - may be needed
 556   // for implicit exceptions.
 557   //
 558   //         normal case                           special case
 559   //
 560   // input : rax: dividend                         min_long
 561   //         reg: divisor   (may not be eax/edx)   -1
 562   //
 563   // output: rax: quotient  (= rax idiv reg)       min_long
 564   //         rdx: remainder (= rax irem reg)       0
 565   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 566   static const int64_t min_long = 0x8000000000000000;
 567   Label normal_case, special_case;
 568 
 569   // check for special case
 570   cmp64(rax, ExternalAddress((address) &min_long));
 571   jcc(Assembler::notEqual, normal_case);
 572   xorl(rdx, rdx); // prepare rdx for possible special case (where
 573                   // remainder = 0)
 574   cmpq(reg, -1);
 575   jcc(Assembler::equal, special_case);
 576 
 577   // handle normal case
 578   bind(normal_case);
 579   cdqq();
 580   int idivq_offset = offset();
 581   idivq(reg);
 582 
 583   // normal and special case exit
 584   bind(special_case);
 585 
 586   return idivq_offset;
 587 }
 588 
 589 void MacroAssembler::decrementq(Register reg, int value) {
 590   if (value == min_jint) { subq(reg, value); return; }
 591   if (value <  0) { incrementq(reg, -value); return; }
 592   if (value == 0) {                        ; return; }
 593   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 594   /* else */      { subq(reg, value)       ; return; }
 595 }
 596 
 597 void MacroAssembler::decrementq(Address dst, int value) {
 598   if (value == min_jint) { subq(dst, value); return; }
 599   if (value <  0) { incrementq(dst, -value); return; }
 600   if (value == 0) {                        ; return; }
 601   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 602   /* else */      { subq(dst, value)       ; return; }
 603 }
 604 
 605 void MacroAssembler::incrementq(AddressLiteral dst) {
 606   if (reachable(dst)) {
 607     incrementq(as_Address(dst));
 608   } else {
 609     lea(rscratch1, dst);
 610     incrementq(Address(rscratch1, 0));
 611   }
 612 }
 613 
 614 void MacroAssembler::incrementq(Register reg, int value) {
 615   if (value == min_jint) { addq(reg, value); return; }
 616   if (value <  0) { decrementq(reg, -value); return; }
 617   if (value == 0) {                        ; return; }
 618   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 619   /* else */      { addq(reg, value)       ; return; }
 620 }
 621 
 622 void MacroAssembler::incrementq(Address dst, int value) {
 623   if (value == min_jint) { addq(dst, value); return; }
 624   if (value <  0) { decrementq(dst, -value); return; }
 625   if (value == 0) {                        ; return; }
 626   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 627   /* else */      { addq(dst, value)       ; return; }
 628 }
 629 
 630 // 32bit can do a case table jump in one instruction but we no longer allow the base
 631 // to be installed in the Address class
 632 void MacroAssembler::jump(ArrayAddress entry) {
 633   lea(rscratch1, entry.base());
 634   Address dispatch = entry.index();
 635   assert(dispatch._base == noreg, "must be");
 636   dispatch._base = rscratch1;
 637   jmp(dispatch);
 638 }
 639 
 640 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 641   ShouldNotReachHere(); // 64bit doesn't use two regs
 642   cmpq(x_lo, y_lo);
 643 }
 644 
 645 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 646     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 647 }
 648 
 649 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 650   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 651   movptr(dst, rscratch1);
 652 }
 653 
 654 void MacroAssembler::leave() {
 655   // %%% is this really better? Why not on 32bit too?
 656   emit_int8((unsigned char)0xC9); // LEAVE
 657 }
 658 
 659 void MacroAssembler::lneg(Register hi, Register lo) {
 660   ShouldNotReachHere(); // 64bit doesn't use two regs
 661   negq(lo);
 662 }
 663 
 664 void MacroAssembler::movoop(Register dst, jobject obj) {
 665   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 666 }
 667 
 668 void MacroAssembler::movoop(Address dst, jobject obj) {
 669   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 670   movq(dst, rscratch1);
 671 }
 672 
 673 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 674   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 675 }
 676 
 677 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 678   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 679   movq(dst, rscratch1);
 680 }
 681 
 682 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 683   if (src.is_lval()) {
 684     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 685   } else {
 686     if (reachable(src)) {
 687       movq(dst, as_Address(src));
 688     } else {
 689       lea(scratch, src);
 690       movq(dst, Address(scratch, 0));
 691     }
 692   }
 693 }
 694 
 695 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 696   movq(as_Address(dst), src);
 697 }
 698 
 699 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 700   movq(dst, as_Address(src));
 701 }
 702 
 703 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 704 void MacroAssembler::movptr(Address dst, intptr_t src) {
 705   if (is_simm32(src)) {
 706     movptr(dst, checked_cast<int32_t>(src));
 707   } else {
 708     mov64(rscratch1, src);
 709     movq(dst, rscratch1);
 710   }
 711 }
 712 
 713 // These are mostly for initializing NULL
 714 void MacroAssembler::movptr(Address dst, int32_t src) {
 715   movslq(dst, src);
 716 }
 717 
 718 void MacroAssembler::movptr(Register dst, int32_t src) {
 719   mov64(dst, (intptr_t)src);
 720 }
 721 
 722 void MacroAssembler::pushoop(jobject obj) {
 723   movoop(rscratch1, obj);
 724   push(rscratch1);
 725 }
 726 
 727 void MacroAssembler::pushklass(Metadata* obj) {
 728   mov_metadata(rscratch1, obj);
 729   push(rscratch1);
 730 }
 731 
 732 void MacroAssembler::pushptr(AddressLiteral src) {
 733   lea(rscratch1, src);
 734   if (src.is_lval()) {
 735     push(rscratch1);
 736   } else {
 737     pushq(Address(rscratch1, 0));
 738   }
 739 }
 740 
 741 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 742   reset_last_Java_frame(r15_thread, clear_fp);
 743 }
 744 
 745 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 746                                          Register last_java_fp,
 747                                          address  last_java_pc) {
 748   vzeroupper();
 749   // determine last_java_sp register
 750   if (!last_java_sp->is_valid()) {
 751     last_java_sp = rsp;
 752   }
 753 
 754   // last_java_fp is optional
 755   if (last_java_fp->is_valid()) {
 756     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 757            last_java_fp);
 758   }
 759 
 760   // last_java_pc is optional
 761   if (last_java_pc != NULL) {
 762     Address java_pc(r15_thread,
 763                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 764     lea(rscratch1, InternalAddress(last_java_pc));
 765     movptr(java_pc, rscratch1);
 766   }
 767 
 768   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 769 }
 770 
 771 static void pass_arg0(MacroAssembler* masm, Register arg) {
 772   if (c_rarg0 != arg ) {
 773     masm->mov(c_rarg0, arg);
 774   }
 775 }
 776 
 777 static void pass_arg1(MacroAssembler* masm, Register arg) {
 778   if (c_rarg1 != arg ) {
 779     masm->mov(c_rarg1, arg);
 780   }
 781 }
 782 
 783 static void pass_arg2(MacroAssembler* masm, Register arg) {
 784   if (c_rarg2 != arg ) {
 785     masm->mov(c_rarg2, arg);
 786   }
 787 }
 788 
 789 static void pass_arg3(MacroAssembler* masm, Register arg) {
 790   if (c_rarg3 != arg ) {
 791     masm->mov(c_rarg3, arg);
 792   }
 793 }
 794 
 795 void MacroAssembler::stop(const char* msg) {
 796   if (ShowMessageBoxOnError) {
 797     address rip = pc();
 798     pusha(); // get regs on stack
 799     lea(c_rarg1, InternalAddress(rip));
 800     movq(c_rarg2, rsp); // pass pointer to regs array
 801   }
 802   lea(c_rarg0, ExternalAddress((address) msg));
 803   andq(rsp, -16); // align stack as required by ABI
 804   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 805   hlt();
 806 }
 807 
 808 void MacroAssembler::warn(const char* msg) {
 809   push(rbp);
 810   movq(rbp, rsp);
 811   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 812   push_CPU_state();   // keeps alignment at 16 bytes
 813   lea(c_rarg0, ExternalAddress((address) msg));
 814   lea(rax, ExternalAddress(CAST_FROM_FN_PTR(address, warning)));
 815   call(rax);
 816   pop_CPU_state();
 817   mov(rsp, rbp);
 818   pop(rbp);
 819 }
 820 
 821 void MacroAssembler::print_state() {
 822   address rip = pc();
 823   pusha();            // get regs on stack
 824   push(rbp);
 825   movq(rbp, rsp);
 826   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 827   push_CPU_state();   // keeps alignment at 16 bytes
 828 
 829   lea(c_rarg0, InternalAddress(rip));
 830   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 831   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 832 
 833   pop_CPU_state();
 834   mov(rsp, rbp);
 835   pop(rbp);
 836   popa();
 837 }
 838 
 839 #ifndef PRODUCT
 840 extern "C" void findpc(intptr_t x);
 841 #endif
 842 
 843 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 844   // In order to get locks to work, we need to fake a in_VM state
 845   if (ShowMessageBoxOnError) {
 846     JavaThread* thread = JavaThread::current();
 847     JavaThreadState saved_state = thread->thread_state();
 848     thread->set_thread_state(_thread_in_vm);
 849 #ifndef PRODUCT
 850     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 851       ttyLocker ttyl;
 852       BytecodeCounter::print();
 853     }
 854 #endif
 855     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 856     // XXX correct this offset for amd64
 857     // This is the value of eip which points to where verify_oop will return.
 858     if (os::message_box(msg, "Execution stopped, print registers?")) {
 859       print_state64(pc, regs);
 860       BREAKPOINT;
 861     }
 862   }
 863   fatal("DEBUG MESSAGE: %s", msg);
 864 }
 865 
 866 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 867   ttyLocker ttyl;
 868   FlagSetting fs(Debugging, true);
 869   tty->print_cr("rip = 0x%016lx", (intptr_t)pc);
 870 #ifndef PRODUCT
 871   tty->cr();
 872   findpc(pc);
 873   tty->cr();
 874 #endif
 875 #define PRINT_REG(rax, value) \
 876   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 877   PRINT_REG(rax, regs[15]);
 878   PRINT_REG(rbx, regs[12]);
 879   PRINT_REG(rcx, regs[14]);
 880   PRINT_REG(rdx, regs[13]);
 881   PRINT_REG(rdi, regs[8]);
 882   PRINT_REG(rsi, regs[9]);
 883   PRINT_REG(rbp, regs[10]);
 884   // rsp is actually not stored by pusha(), compute the old rsp from regs (rsp after pusha): regs + 16 = old rsp
 885   PRINT_REG(rsp, (intptr_t)(&regs[16]));
 886   PRINT_REG(r8 , regs[7]);
 887   PRINT_REG(r9 , regs[6]);
 888   PRINT_REG(r10, regs[5]);
 889   PRINT_REG(r11, regs[4]);
 890   PRINT_REG(r12, regs[3]);
 891   PRINT_REG(r13, regs[2]);
 892   PRINT_REG(r14, regs[1]);
 893   PRINT_REG(r15, regs[0]);
 894 #undef PRINT_REG
 895   // Print some words near the top of the stack.
 896   int64_t* rsp = &regs[16];
 897   int64_t* dump_sp = rsp;
 898   for (int col1 = 0; col1 < 8; col1++) {
 899     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 900     os::print_location(tty, *dump_sp++);
 901   }
 902   for (int row = 0; row < 25; row++) {
 903     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 904     for (int col = 0; col < 4; col++) {
 905       tty->print(" 0x%016lx", (intptr_t)*dump_sp++);
 906     }
 907     tty->cr();
 908   }
 909   // Print some instructions around pc:
 910   Disassembler::decode((address)pc-64, (address)pc);
 911   tty->print_cr("--------");
 912   Disassembler::decode((address)pc, (address)pc+32);
 913 }
 914 
 915 // The java_calling_convention describes stack locations as ideal slots on
 916 // a frame with no abi restrictions. Since we must observe abi restrictions
 917 // (like the placement of the register window) the slots must be biased by
 918 // the following value.
 919 static int reg2offset_in(VMReg r) {
 920   // Account for saved rbp and return address
 921   // This should really be in_preserve_stack_slots
 922   return (r->reg2stack() + 4) * VMRegImpl::stack_slot_size;
 923 }
 924 
 925 static int reg2offset_out(VMReg r) {
 926   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
 927 }
 928 
 929 // A long move
 930 void MacroAssembler::long_move(VMRegPair src, VMRegPair dst) {
 931 
 932   // The calling conventions assures us that each VMregpair is either
 933   // all really one physical register or adjacent stack slots.
 934 
 935   if (src.is_single_phys_reg() ) {
 936     if (dst.is_single_phys_reg()) {
 937       if (dst.first() != src.first()) {
 938         mov(dst.first()->as_Register(), src.first()->as_Register());
 939       }
 940     } else {
 941       assert(dst.is_single_reg(), "not a stack pair");
 942       movq(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
 943     }
 944   } else if (dst.is_single_phys_reg()) {
 945     assert(src.is_single_reg(),  "not a stack pair");
 946     movq(dst.first()->as_Register(), Address(rbp, reg2offset_out(src.first())));
 947   } else {
 948     assert(src.is_single_reg() && dst.is_single_reg(), "not stack pairs");
 949     movq(rax, Address(rbp, reg2offset_in(src.first())));
 950     movq(Address(rsp, reg2offset_out(dst.first())), rax);
 951   }
 952 }
 953 
 954 // A double move
 955 void MacroAssembler::double_move(VMRegPair src, VMRegPair dst) {
 956 
 957   // The calling conventions assures us that each VMregpair is either
 958   // all really one physical register or adjacent stack slots.
 959 
 960   if (src.is_single_phys_reg() ) {
 961     if (dst.is_single_phys_reg()) {
 962       // In theory these overlap but the ordering is such that this is likely a nop
 963       if ( src.first() != dst.first()) {
 964         movdbl(dst.first()->as_XMMRegister(), src.first()->as_XMMRegister());
 965       }
 966     } else {
 967       assert(dst.is_single_reg(), "not a stack pair");
 968       movdbl(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
 969     }
 970   } else if (dst.is_single_phys_reg()) {
 971     assert(src.is_single_reg(),  "not a stack pair");
 972     movdbl(dst.first()->as_XMMRegister(), Address(rbp, reg2offset_out(src.first())));
 973   } else {
 974     assert(src.is_single_reg() && dst.is_single_reg(), "not stack pairs");
 975     movq(rax, Address(rbp, reg2offset_in(src.first())));
 976     movq(Address(rsp, reg2offset_out(dst.first())), rax);
 977   }
 978 }
 979 
 980 
 981 // A float arg may have to do float reg int reg conversion
 982 void MacroAssembler::float_move(VMRegPair src, VMRegPair dst) {
 983   assert(!src.second()->is_valid() && !dst.second()->is_valid(), "bad float_move");
 984 
 985   // The calling conventions assures us that each VMregpair is either
 986   // all really one physical register or adjacent stack slots.
 987 
 988   if (src.first()->is_stack()) {
 989     if (dst.first()->is_stack()) {
 990       movl(rax, Address(rbp, reg2offset_in(src.first())));
 991       movptr(Address(rsp, reg2offset_out(dst.first())), rax);
 992     } else {
 993       // stack to reg
 994       assert(dst.first()->is_XMMRegister(), "only expect xmm registers as parameters");
 995       movflt(dst.first()->as_XMMRegister(), Address(rbp, reg2offset_in(src.first())));
 996     }
 997   } else if (dst.first()->is_stack()) {
 998     // reg to stack
 999     assert(src.first()->is_XMMRegister(), "only expect xmm registers as parameters");
1000     movflt(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1001   } else {
1002     // reg to reg
1003     // In theory these overlap but the ordering is such that this is likely a nop
1004     if ( src.first() != dst.first()) {
1005       movdbl(dst.first()->as_XMMRegister(),  src.first()->as_XMMRegister());
1006     }
1007   }
1008 }
1009 
1010 // On 64 bit we will store integer like items to the stack as
1011 // 64 bits items (x86_32/64 abi) even though java would only store
1012 // 32bits for a parameter. On 32bit it will simply be 32 bits
1013 // So this routine will do 32->32 on 32bit and 32->64 on 64bit
1014 void MacroAssembler::move32_64(VMRegPair src, VMRegPair dst) {
1015   if (src.first()->is_stack()) {
1016     if (dst.first()->is_stack()) {
1017       // stack to stack
1018       movslq(rax, Address(rbp, reg2offset_in(src.first())));
1019       movq(Address(rsp, reg2offset_out(dst.first())), rax);
1020     } else {
1021       // stack to reg
1022       movslq(dst.first()->as_Register(), Address(rbp, reg2offset_in(src.first())));
1023     }
1024   } else if (dst.first()->is_stack()) {
1025     // reg to stack
1026     // Do we really have to sign extend???
1027     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
1028     movq(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
1029   } else {
1030     // Do we really have to sign extend???
1031     // __ movslq(dst.first()->as_Register(), src.first()->as_Register());
1032     if (dst.first() != src.first()) {
1033       movq(dst.first()->as_Register(), src.first()->as_Register());
1034     }
1035   }
1036 }
1037 
1038 void MacroAssembler::move_ptr(VMRegPair src, VMRegPair dst) {
1039   if (src.first()->is_stack()) {
1040     if (dst.first()->is_stack()) {
1041       // stack to stack
1042       movq(rax, Address(rbp, reg2offset_in(src.first())));
1043       movq(Address(rsp, reg2offset_out(dst.first())), rax);
1044     } else {
1045       // stack to reg
1046       movq(dst.first()->as_Register(), Address(rbp, reg2offset_in(src.first())));
1047     }
1048   } else if (dst.first()->is_stack()) {
1049     // reg to stack
1050     movq(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
1051   } else {
1052     if (dst.first() != src.first()) {
1053       movq(dst.first()->as_Register(), src.first()->as_Register());
1054     }
1055   }
1056 }
1057 
1058 // An oop arg. Must pass a handle not the oop itself
1059 void MacroAssembler::object_move(OopMap* map,
1060                         int oop_handle_offset,
1061                         int framesize_in_slots,
1062                         VMRegPair src,
1063                         VMRegPair dst,
1064                         bool is_receiver,
1065                         int* receiver_offset) {
1066 
1067   // must pass a handle. First figure out the location we use as a handle
1068 
1069   Register rHandle = dst.first()->is_stack() ? rax : dst.first()->as_Register();
1070 
1071   // See if oop is NULL if it is we need no handle
1072 
1073   if (src.first()->is_stack()) {
1074 
1075     // Oop is already on the stack as an argument
1076     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
1077     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
1078     if (is_receiver) {
1079       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
1080     }
1081 
1082     cmpptr(Address(rbp, reg2offset_in(src.first())), (int32_t)NULL_WORD);
1083     lea(rHandle, Address(rbp, reg2offset_in(src.first())));
1084     // conditionally move a NULL
1085     cmovptr(Assembler::equal, rHandle, Address(rbp, reg2offset_in(src.first())));
1086   } else {
1087 
1088     // Oop is in an a register we must store it to the space we reserve
1089     // on the stack for oop_handles and pass a handle if oop is non-NULL
1090 
1091     const Register rOop = src.first()->as_Register();
1092     int oop_slot;
1093     if (rOop == j_rarg0)
1094       oop_slot = 0;
1095     else if (rOop == j_rarg1)
1096       oop_slot = 1;
1097     else if (rOop == j_rarg2)
1098       oop_slot = 2;
1099     else if (rOop == j_rarg3)
1100       oop_slot = 3;
1101     else if (rOop == j_rarg4)
1102       oop_slot = 4;
1103     else {
1104       assert(rOop == j_rarg5, "wrong register");
1105       oop_slot = 5;
1106     }
1107 
1108     oop_slot = oop_slot * VMRegImpl::slots_per_word + oop_handle_offset;
1109     int offset = oop_slot*VMRegImpl::stack_slot_size;
1110 
1111     map->set_oop(VMRegImpl::stack2reg(oop_slot));
1112     // Store oop in handle area, may be NULL
1113     movptr(Address(rsp, offset), rOop);
1114     if (is_receiver) {
1115       *receiver_offset = offset;
1116     }
1117 
1118     cmpptr(rOop, (int32_t)NULL_WORD);
1119     lea(rHandle, Address(rsp, offset));
1120     // conditionally move a NULL from the handle area where it was just stored
1121     cmovptr(Assembler::equal, rHandle, Address(rsp, offset));
1122   }
1123 
1124   // If arg is on the stack then place it otherwise it is already in correct reg.
1125   if (dst.first()->is_stack()) {
1126     movptr(Address(rsp, reg2offset_out(dst.first())), rHandle);
1127   }
1128 }
1129 
1130 #endif // _LP64
1131 
1132 // Now versions that are common to 32/64 bit
1133 
1134 void MacroAssembler::addptr(Register dst, int32_t imm32) {
1135   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
1136 }
1137 
1138 void MacroAssembler::addptr(Register dst, Register src) {
1139   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
1140 }
1141 
1142 void MacroAssembler::addptr(Address dst, Register src) {
1143   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
1144 }
1145 
1146 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
1147   if (reachable(src)) {
1148     Assembler::addsd(dst, as_Address(src));
1149   } else {
1150     lea(rscratch1, src);
1151     Assembler::addsd(dst, Address(rscratch1, 0));
1152   }
1153 }
1154 
1155 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
1156   if (reachable(src)) {
1157     addss(dst, as_Address(src));
1158   } else {
1159     lea(rscratch1, src);
1160     addss(dst, Address(rscratch1, 0));
1161   }
1162 }
1163 
1164 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
1165   if (reachable(src)) {
1166     Assembler::addpd(dst, as_Address(src));
1167   } else {
1168     lea(rscratch1, src);
1169     Assembler::addpd(dst, Address(rscratch1, 0));
1170   }
1171 }
1172 
1173 // See 8273459.  Function for ensuring 64-byte alignment, intended for stubs only.
1174 // Stub code is generated once and never copied.
1175 // NMethods can't use this because they get copied and we can't force alignment > 32 bytes.
1176 void MacroAssembler::align64() {
1177   align(64, (unsigned long long) pc());
1178 }
1179 
1180 void MacroAssembler::align32() {
1181   align(32, (unsigned long long) pc());
1182 }
1183 
1184 void MacroAssembler::align(int modulus) {
1185   // 8273459: Ensure alignment is possible with current segment alignment
1186   assert(modulus <= CodeEntryAlignment, "Alignment must be <= CodeEntryAlignment");
1187   align(modulus, offset());
1188 }
1189 
1190 void MacroAssembler::align(int modulus, int target) {
1191   if (target % modulus != 0) {
1192     nop(modulus - (target % modulus));
1193   }
1194 }
1195 
1196 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src, Register scratch_reg) {
1197   // Used in sign-masking with aligned address.
1198   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1199   if (reachable(src)) {
1200     Assembler::andpd(dst, as_Address(src));
1201   } else {
1202     lea(scratch_reg, src);
1203     Assembler::andpd(dst, Address(scratch_reg, 0));
1204   }
1205 }
1206 
1207 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src, Register scratch_reg) {
1208   // Used in sign-masking with aligned address.
1209   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1210   if (reachable(src)) {
1211     Assembler::andps(dst, as_Address(src));
1212   } else {
1213     lea(scratch_reg, src);
1214     Assembler::andps(dst, Address(scratch_reg, 0));
1215   }
1216 }
1217 
1218 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1219   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1220 }
1221 
1222 void MacroAssembler::atomic_incl(Address counter_addr) {
1223   lock();
1224   incrementl(counter_addr);
1225 }
1226 
1227 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1228   if (reachable(counter_addr)) {
1229     atomic_incl(as_Address(counter_addr));
1230   } else {
1231     lea(scr, counter_addr);
1232     atomic_incl(Address(scr, 0));
1233   }
1234 }
1235 
1236 #ifdef _LP64
1237 void MacroAssembler::atomic_incq(Address counter_addr) {
1238   lock();
1239   incrementq(counter_addr);
1240 }
1241 
1242 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1243   if (reachable(counter_addr)) {
1244     atomic_incq(as_Address(counter_addr));
1245   } else {
1246     lea(scr, counter_addr);
1247     atomic_incq(Address(scr, 0));
1248   }
1249 }
1250 #endif
1251 
1252 // Writes to stack successive pages until offset reached to check for
1253 // stack overflow + shadow pages.  This clobbers tmp.
1254 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1255   movptr(tmp, rsp);
1256   // Bang stack for total size given plus shadow page size.
1257   // Bang one page at a time because large size can bang beyond yellow and
1258   // red zones.
1259   Label loop;
1260   bind(loop);
1261   movl(Address(tmp, (-os::vm_page_size())), size );
1262   subptr(tmp, os::vm_page_size());
1263   subl(size, os::vm_page_size());
1264   jcc(Assembler::greater, loop);
1265 
1266   // Bang down shadow pages too.
1267   // At this point, (tmp-0) is the last address touched, so don't
1268   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1269   // was post-decremented.)  Skip this address by starting at i=1, and
1270   // touch a few more pages below.  N.B.  It is important to touch all
1271   // the way down including all pages in the shadow zone.
1272   for (int i = 1; i < ((int)StackOverflow::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1273     // this could be any sized move but this is can be a debugging crumb
1274     // so the bigger the better.
1275     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1276   }
1277 }
1278 
1279 void MacroAssembler::reserved_stack_check() {
1280     // testing if reserved zone needs to be enabled
1281     Label no_reserved_zone_enabling;
1282     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1283     NOT_LP64(get_thread(rsi);)
1284 
1285     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1286     jcc(Assembler::below, no_reserved_zone_enabling);
1287 
1288     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1289     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1290     should_not_reach_here();
1291 
1292     bind(no_reserved_zone_enabling);
1293 }
1294 
1295 void MacroAssembler::c2bool(Register x) {
1296   // implements x == 0 ? 0 : 1
1297   // note: must only look at least-significant byte of x
1298   //       since C-style booleans are stored in one byte
1299   //       only! (was bug)
1300   andl(x, 0xFF);
1301   setb(Assembler::notZero, x);
1302 }
1303 
1304 // Wouldn't need if AddressLiteral version had new name
1305 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
1306   Assembler::call(L, rtype);
1307 }
1308 
1309 void MacroAssembler::call(Register entry) {
1310   Assembler::call(entry);
1311 }
1312 
1313 void MacroAssembler::call(AddressLiteral entry) {
1314   if (reachable(entry)) {
1315     Assembler::call_literal(entry.target(), entry.rspec());
1316   } else {
1317     lea(rscratch1, entry);
1318     Assembler::call(rscratch1);
1319   }
1320 }
1321 
1322 void MacroAssembler::ic_call(address entry, jint method_index) {
1323   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
1324   movptr(rax, (intptr_t)Universe::non_oop_word());
1325   call(AddressLiteral(entry, rh));
1326 }
1327 
1328 // Implementation of call_VM versions
1329 
1330 void MacroAssembler::call_VM(Register oop_result,
1331                              address entry_point,
1332                              bool check_exceptions) {
1333   Label C, E;
1334   call(C, relocInfo::none);
1335   jmp(E);
1336 
1337   bind(C);
1338   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
1339   ret(0);
1340 
1341   bind(E);
1342 }
1343 
1344 void MacroAssembler::call_VM(Register oop_result,
1345                              address entry_point,
1346                              Register arg_1,
1347                              bool check_exceptions) {
1348   Label C, E;
1349   call(C, relocInfo::none);
1350   jmp(E);
1351 
1352   bind(C);
1353   pass_arg1(this, arg_1);
1354   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
1355   ret(0);
1356 
1357   bind(E);
1358 }
1359 
1360 void MacroAssembler::call_VM(Register oop_result,
1361                              address entry_point,
1362                              Register arg_1,
1363                              Register arg_2,
1364                              bool check_exceptions) {
1365   Label C, E;
1366   call(C, relocInfo::none);
1367   jmp(E);
1368 
1369   bind(C);
1370 
1371   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
1372 
1373   pass_arg2(this, arg_2);
1374   pass_arg1(this, arg_1);
1375   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
1376   ret(0);
1377 
1378   bind(E);
1379 }
1380 
1381 void MacroAssembler::call_VM(Register oop_result,
1382                              address entry_point,
1383                              Register arg_1,
1384                              Register arg_2,
1385                              Register arg_3,
1386                              bool check_exceptions) {
1387   Label C, E;
1388   call(C, relocInfo::none);
1389   jmp(E);
1390 
1391   bind(C);
1392 
1393   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
1394   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
1395   pass_arg3(this, arg_3);
1396 
1397   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
1398   pass_arg2(this, arg_2);
1399 
1400   pass_arg1(this, arg_1);
1401   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
1402   ret(0);
1403 
1404   bind(E);
1405 }
1406 
1407 void MacroAssembler::call_VM(Register oop_result,
1408                              Register last_java_sp,
1409                              address entry_point,
1410                              int number_of_arguments,
1411                              bool check_exceptions) {
1412   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
1413   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
1414 }
1415 
1416 void MacroAssembler::call_VM(Register oop_result,
1417                              Register last_java_sp,
1418                              address entry_point,
1419                              Register arg_1,
1420                              bool check_exceptions) {
1421   pass_arg1(this, arg_1);
1422   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
1423 }
1424 
1425 void MacroAssembler::call_VM(Register oop_result,
1426                              Register last_java_sp,
1427                              address entry_point,
1428                              Register arg_1,
1429                              Register arg_2,
1430                              bool check_exceptions) {
1431 
1432   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
1433   pass_arg2(this, arg_2);
1434   pass_arg1(this, arg_1);
1435   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
1436 }
1437 
1438 void MacroAssembler::call_VM(Register oop_result,
1439                              Register last_java_sp,
1440                              address entry_point,
1441                              Register arg_1,
1442                              Register arg_2,
1443                              Register arg_3,
1444                              bool check_exceptions) {
1445   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
1446   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
1447   pass_arg3(this, arg_3);
1448   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
1449   pass_arg2(this, arg_2);
1450   pass_arg1(this, arg_1);
1451   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
1452 }
1453 
1454 void MacroAssembler::super_call_VM(Register oop_result,
1455                                    Register last_java_sp,
1456                                    address entry_point,
1457                                    int number_of_arguments,
1458                                    bool check_exceptions) {
1459   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
1460   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
1461 }
1462 
1463 void MacroAssembler::super_call_VM(Register oop_result,
1464                                    Register last_java_sp,
1465                                    address entry_point,
1466                                    Register arg_1,
1467                                    bool check_exceptions) {
1468   pass_arg1(this, arg_1);
1469   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
1470 }
1471 
1472 void MacroAssembler::super_call_VM(Register oop_result,
1473                                    Register last_java_sp,
1474                                    address entry_point,
1475                                    Register arg_1,
1476                                    Register arg_2,
1477                                    bool check_exceptions) {
1478 
1479   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
1480   pass_arg2(this, arg_2);
1481   pass_arg1(this, arg_1);
1482   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
1483 }
1484 
1485 void MacroAssembler::super_call_VM(Register oop_result,
1486                                    Register last_java_sp,
1487                                    address entry_point,
1488                                    Register arg_1,
1489                                    Register arg_2,
1490                                    Register arg_3,
1491                                    bool check_exceptions) {
1492   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
1493   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
1494   pass_arg3(this, arg_3);
1495   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
1496   pass_arg2(this, arg_2);
1497   pass_arg1(this, arg_1);
1498   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
1499 }
1500 
1501 void MacroAssembler::call_VM_base(Register oop_result,
1502                                   Register java_thread,
1503                                   Register last_java_sp,
1504                                   address  entry_point,
1505                                   int      number_of_arguments,
1506                                   bool     check_exceptions) {
1507   // determine java_thread register
1508   if (!java_thread->is_valid()) {
1509 #ifdef _LP64
1510     java_thread = r15_thread;
1511 #else
1512     java_thread = rdi;
1513     get_thread(java_thread);
1514 #endif // LP64
1515   }
1516   // determine last_java_sp register
1517   if (!last_java_sp->is_valid()) {
1518     last_java_sp = rsp;
1519   }
1520   // debugging support
1521   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
1522   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
1523 #ifdef ASSERT
1524   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
1525   // r12 is the heapbase.
1526   LP64_ONLY(if (UseCompressedOops && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
1527 #endif // ASSERT
1528 
1529   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
1530   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
1531 
1532   // push java thread (becomes first argument of C function)
1533 
1534   NOT_LP64(push(java_thread); number_of_arguments++);
1535   LP64_ONLY(mov(c_rarg0, r15_thread));
1536 
1537   // set last Java frame before call
1538   assert(last_java_sp != rbp, "can't use ebp/rbp");
1539 
1540   // Only interpreter should have to set fp
1541   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
1542 
1543   // do the call, remove parameters
1544   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
1545 
1546   // restore the thread (cannot use the pushed argument since arguments
1547   // may be overwritten by C code generated by an optimizing compiler);
1548   // however can use the register value directly if it is callee saved.
1549   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
1550     // rdi & rsi (also r15) are callee saved -> nothing to do
1551 #ifdef ASSERT
1552     guarantee(java_thread != rax, "change this code");
1553     push(rax);
1554     { Label L;
1555       get_thread(rax);
1556       cmpptr(java_thread, rax);
1557       jcc(Assembler::equal, L);
1558       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
1559       bind(L);
1560     }
1561     pop(rax);
1562 #endif
1563   } else {
1564     get_thread(java_thread);
1565   }
1566   // reset last Java frame
1567   // Only interpreter should have to clear fp
1568   reset_last_Java_frame(java_thread, true);
1569 
1570    // C++ interp handles this in the interpreter
1571   check_and_handle_popframe(java_thread);
1572   check_and_handle_earlyret(java_thread);
1573 
1574   if (check_exceptions) {
1575     // check for pending exceptions (java_thread is set upon return)
1576     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
1577 #ifndef _LP64
1578     jump_cc(Assembler::notEqual,
1579             RuntimeAddress(StubRoutines::forward_exception_entry()));
1580 #else
1581     // This used to conditionally jump to forward_exception however it is
1582     // possible if we relocate that the branch will not reach. So we must jump
1583     // around so we can always reach
1584 
1585     Label ok;
1586     jcc(Assembler::equal, ok);
1587     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
1588     bind(ok);
1589 #endif // LP64
1590   }
1591 
1592   // get oop result if there is one and reset the value in the thread
1593   if (oop_result->is_valid()) {
1594     get_vm_result(oop_result, java_thread);
1595   }
1596 }
1597 
1598 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
1599 
1600   // Calculate the value for last_Java_sp
1601   // somewhat subtle. call_VM does an intermediate call
1602   // which places a return address on the stack just under the
1603   // stack pointer as the user finsihed with it. This allows
1604   // use to retrieve last_Java_pc from last_Java_sp[-1].
1605   // On 32bit we then have to push additional args on the stack to accomplish
1606   // the actual requested call. On 64bit call_VM only can use register args
1607   // so the only extra space is the return address that call_VM created.
1608   // This hopefully explains the calculations here.
1609 
1610 #ifdef _LP64
1611   // We've pushed one address, correct last_Java_sp
1612   lea(rax, Address(rsp, wordSize));
1613 #else
1614   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
1615 #endif // LP64
1616 
1617   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
1618 
1619 }
1620 
1621 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
1622 void MacroAssembler::call_VM_leaf0(address entry_point) {
1623   MacroAssembler::call_VM_leaf_base(entry_point, 0);
1624 }
1625 
1626 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
1627   call_VM_leaf_base(entry_point, number_of_arguments);
1628 }
1629 
1630 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
1631   pass_arg0(this, arg_0);
1632   call_VM_leaf(entry_point, 1);
1633 }
1634 
1635 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
1636 
1637   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
1638   pass_arg1(this, arg_1);
1639   pass_arg0(this, arg_0);
1640   call_VM_leaf(entry_point, 2);
1641 }
1642 
1643 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
1644   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
1645   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
1646   pass_arg2(this, arg_2);
1647   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
1648   pass_arg1(this, arg_1);
1649   pass_arg0(this, arg_0);
1650   call_VM_leaf(entry_point, 3);
1651 }
1652 
1653 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
1654   pass_arg0(this, arg_0);
1655   MacroAssembler::call_VM_leaf_base(entry_point, 1);
1656 }
1657 
1658 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
1659 
1660   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
1661   pass_arg1(this, arg_1);
1662   pass_arg0(this, arg_0);
1663   MacroAssembler::call_VM_leaf_base(entry_point, 2);
1664 }
1665 
1666 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
1667   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
1668   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
1669   pass_arg2(this, arg_2);
1670   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
1671   pass_arg1(this, arg_1);
1672   pass_arg0(this, arg_0);
1673   MacroAssembler::call_VM_leaf_base(entry_point, 3);
1674 }
1675 
1676 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
1677   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
1678   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
1679   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
1680   pass_arg3(this, arg_3);
1681   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
1682   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
1683   pass_arg2(this, arg_2);
1684   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
1685   pass_arg1(this, arg_1);
1686   pass_arg0(this, arg_0);
1687   MacroAssembler::call_VM_leaf_base(entry_point, 4);
1688 }
1689 
1690 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
1691   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
1692   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
1693   verify_oop_msg(oop_result, "broken oop in call_VM_base");
1694 }
1695 
1696 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
1697   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
1698   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
1699 }
1700 
1701 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
1702 }
1703 
1704 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
1705 }
1706 
1707 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
1708   if (reachable(src1)) {
1709     cmpl(as_Address(src1), imm);
1710   } else {
1711     lea(rscratch1, src1);
1712     cmpl(Address(rscratch1, 0), imm);
1713   }
1714 }
1715 
1716 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
1717   assert(!src2.is_lval(), "use cmpptr");
1718   if (reachable(src2)) {
1719     cmpl(src1, as_Address(src2));
1720   } else {
1721     lea(rscratch1, src2);
1722     cmpl(src1, Address(rscratch1, 0));
1723   }
1724 }
1725 
1726 void MacroAssembler::cmp32(Register src1, int32_t imm) {
1727   Assembler::cmpl(src1, imm);
1728 }
1729 
1730 void MacroAssembler::cmp32(Register src1, Address src2) {
1731   Assembler::cmpl(src1, src2);
1732 }
1733 
1734 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
1735   ucomisd(opr1, opr2);
1736 
1737   Label L;
1738   if (unordered_is_less) {
1739     movl(dst, -1);
1740     jcc(Assembler::parity, L);
1741     jcc(Assembler::below , L);
1742     movl(dst, 0);
1743     jcc(Assembler::equal , L);
1744     increment(dst);
1745   } else { // unordered is greater
1746     movl(dst, 1);
1747     jcc(Assembler::parity, L);
1748     jcc(Assembler::above , L);
1749     movl(dst, 0);
1750     jcc(Assembler::equal , L);
1751     decrementl(dst);
1752   }
1753   bind(L);
1754 }
1755 
1756 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
1757   ucomiss(opr1, opr2);
1758 
1759   Label L;
1760   if (unordered_is_less) {
1761     movl(dst, -1);
1762     jcc(Assembler::parity, L);
1763     jcc(Assembler::below , L);
1764     movl(dst, 0);
1765     jcc(Assembler::equal , L);
1766     increment(dst);
1767   } else { // unordered is greater
1768     movl(dst, 1);
1769     jcc(Assembler::parity, L);
1770     jcc(Assembler::above , L);
1771     movl(dst, 0);
1772     jcc(Assembler::equal , L);
1773     decrementl(dst);
1774   }
1775   bind(L);
1776 }
1777 
1778 
1779 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
1780   if (reachable(src1)) {
1781     cmpb(as_Address(src1), imm);
1782   } else {
1783     lea(rscratch1, src1);
1784     cmpb(Address(rscratch1, 0), imm);
1785   }
1786 }
1787 
1788 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
1789 #ifdef _LP64
1790   if (src2.is_lval()) {
1791     movptr(rscratch1, src2);
1792     Assembler::cmpq(src1, rscratch1);
1793   } else if (reachable(src2)) {
1794     cmpq(src1, as_Address(src2));
1795   } else {
1796     lea(rscratch1, src2);
1797     Assembler::cmpq(src1, Address(rscratch1, 0));
1798   }
1799 #else
1800   if (src2.is_lval()) {
1801     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
1802   } else {
1803     cmpl(src1, as_Address(src2));
1804   }
1805 #endif // _LP64
1806 }
1807 
1808 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
1809   assert(src2.is_lval(), "not a mem-mem compare");
1810 #ifdef _LP64
1811   // moves src2's literal address
1812   movptr(rscratch1, src2);
1813   Assembler::cmpq(src1, rscratch1);
1814 #else
1815   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
1816 #endif // _LP64
1817 }
1818 
1819 void MacroAssembler::cmpoop(Register src1, Register src2) {
1820   cmpptr(src1, src2);
1821 }
1822 
1823 void MacroAssembler::cmpoop(Register src1, Address src2) {
1824   cmpptr(src1, src2);
1825 }
1826 
1827 #ifdef _LP64
1828 void MacroAssembler::cmpoop(Register src1, jobject src2) {
1829   movoop(rscratch1, src2);
1830   cmpptr(src1, rscratch1);
1831 }
1832 #endif
1833 
1834 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
1835   if (reachable(adr)) {
1836     lock();
1837     cmpxchgptr(reg, as_Address(adr));
1838   } else {
1839     lea(rscratch1, adr);
1840     lock();
1841     cmpxchgptr(reg, Address(rscratch1, 0));
1842   }
1843 }
1844 
1845 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
1846   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
1847 }
1848 
1849 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
1850   if (reachable(src)) {
1851     Assembler::comisd(dst, as_Address(src));
1852   } else {
1853     lea(rscratch1, src);
1854     Assembler::comisd(dst, Address(rscratch1, 0));
1855   }
1856 }
1857 
1858 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
1859   if (reachable(src)) {
1860     Assembler::comiss(dst, as_Address(src));
1861   } else {
1862     lea(rscratch1, src);
1863     Assembler::comiss(dst, Address(rscratch1, 0));
1864   }
1865 }
1866 
1867 
1868 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
1869   Condition negated_cond = negate_condition(cond);
1870   Label L;
1871   jcc(negated_cond, L);
1872   pushf(); // Preserve flags
1873   atomic_incl(counter_addr);
1874   popf();
1875   bind(L);
1876 }
1877 
1878 int MacroAssembler::corrected_idivl(Register reg) {
1879   // Full implementation of Java idiv and irem; checks for
1880   // special case as described in JVM spec., p.243 & p.271.
1881   // The function returns the (pc) offset of the idivl
1882   // instruction - may be needed for implicit exceptions.
1883   //
1884   //         normal case                           special case
1885   //
1886   // input : rax,: dividend                         min_int
1887   //         reg: divisor   (may not be rax,/rdx)   -1
1888   //
1889   // output: rax,: quotient  (= rax, idiv reg)       min_int
1890   //         rdx: remainder (= rax, irem reg)       0
1891   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
1892   const int min_int = 0x80000000;
1893   Label normal_case, special_case;
1894 
1895   // check for special case
1896   cmpl(rax, min_int);
1897   jcc(Assembler::notEqual, normal_case);
1898   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
1899   cmpl(reg, -1);
1900   jcc(Assembler::equal, special_case);
1901 
1902   // handle normal case
1903   bind(normal_case);
1904   cdql();
1905   int idivl_offset = offset();
1906   idivl(reg);
1907 
1908   // normal and special case exit
1909   bind(special_case);
1910 
1911   return idivl_offset;
1912 }
1913 
1914 
1915 
1916 void MacroAssembler::decrementl(Register reg, int value) {
1917   if (value == min_jint) {subl(reg, value) ; return; }
1918   if (value <  0) { incrementl(reg, -value); return; }
1919   if (value == 0) {                        ; return; }
1920   if (value == 1 && UseIncDec) { decl(reg) ; return; }
1921   /* else */      { subl(reg, value)       ; return; }
1922 }
1923 
1924 void MacroAssembler::decrementl(Address dst, int value) {
1925   if (value == min_jint) {subl(dst, value) ; return; }
1926   if (value <  0) { incrementl(dst, -value); return; }
1927   if (value == 0) {                        ; return; }
1928   if (value == 1 && UseIncDec) { decl(dst) ; return; }
1929   /* else */      { subl(dst, value)       ; return; }
1930 }
1931 
1932 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
1933   assert (shift_value > 0, "illegal shift value");
1934   Label _is_positive;
1935   testl (reg, reg);
1936   jcc (Assembler::positive, _is_positive);
1937   int offset = (1 << shift_value) - 1 ;
1938 
1939   if (offset == 1) {
1940     incrementl(reg);
1941   } else {
1942     addl(reg, offset);
1943   }
1944 
1945   bind (_is_positive);
1946   sarl(reg, shift_value);
1947 }
1948 
1949 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
1950   if (reachable(src)) {
1951     Assembler::divsd(dst, as_Address(src));
1952   } else {
1953     lea(rscratch1, src);
1954     Assembler::divsd(dst, Address(rscratch1, 0));
1955   }
1956 }
1957 
1958 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
1959   if (reachable(src)) {
1960     Assembler::divss(dst, as_Address(src));
1961   } else {
1962     lea(rscratch1, src);
1963     Assembler::divss(dst, Address(rscratch1, 0));
1964   }
1965 }
1966 
1967 void MacroAssembler::enter() {
1968   push(rbp);
1969   mov(rbp, rsp);
1970 }
1971 
1972 // A 5 byte nop that is safe for patching (see patch_verified_entry)
1973 void MacroAssembler::fat_nop() {
1974   if (UseAddressNop) {
1975     addr_nop_5();
1976   } else {
1977     emit_int8(0x26); // es:
1978     emit_int8(0x2e); // cs:
1979     emit_int8(0x64); // fs:
1980     emit_int8(0x65); // gs:
1981     emit_int8((unsigned char)0x90);
1982   }
1983 }
1984 
1985 #ifndef _LP64
1986 void MacroAssembler::fcmp(Register tmp) {
1987   fcmp(tmp, 1, true, true);
1988 }
1989 
1990 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
1991   assert(!pop_right || pop_left, "usage error");
1992   if (VM_Version::supports_cmov()) {
1993     assert(tmp == noreg, "unneeded temp");
1994     if (pop_left) {
1995       fucomip(index);
1996     } else {
1997       fucomi(index);
1998     }
1999     if (pop_right) {
2000       fpop();
2001     }
2002   } else {
2003     assert(tmp != noreg, "need temp");
2004     if (pop_left) {
2005       if (pop_right) {
2006         fcompp();
2007       } else {
2008         fcomp(index);
2009       }
2010     } else {
2011       fcom(index);
2012     }
2013     // convert FPU condition into eflags condition via rax,
2014     save_rax(tmp);
2015     fwait(); fnstsw_ax();
2016     sahf();
2017     restore_rax(tmp);
2018   }
2019   // condition codes set as follows:
2020   //
2021   // CF (corresponds to C0) if x < y
2022   // PF (corresponds to C2) if unordered
2023   // ZF (corresponds to C3) if x = y
2024 }
2025 
2026 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
2027   fcmp2int(dst, unordered_is_less, 1, true, true);
2028 }
2029 
2030 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
2031   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
2032   Label L;
2033   if (unordered_is_less) {
2034     movl(dst, -1);
2035     jcc(Assembler::parity, L);
2036     jcc(Assembler::below , L);
2037     movl(dst, 0);
2038     jcc(Assembler::equal , L);
2039     increment(dst);
2040   } else { // unordered is greater
2041     movl(dst, 1);
2042     jcc(Assembler::parity, L);
2043     jcc(Assembler::above , L);
2044     movl(dst, 0);
2045     jcc(Assembler::equal , L);
2046     decrementl(dst);
2047   }
2048   bind(L);
2049 }
2050 
2051 void MacroAssembler::fld_d(AddressLiteral src) {
2052   fld_d(as_Address(src));
2053 }
2054 
2055 void MacroAssembler::fld_s(AddressLiteral src) {
2056   fld_s(as_Address(src));
2057 }
2058 
2059 void MacroAssembler::fldcw(AddressLiteral src) {
2060   Assembler::fldcw(as_Address(src));
2061 }
2062 
2063 void MacroAssembler::fpop() {
2064   ffree();
2065   fincstp();
2066 }
2067 
2068 void MacroAssembler::fremr(Register tmp) {
2069   save_rax(tmp);
2070   { Label L;
2071     bind(L);
2072     fprem();
2073     fwait(); fnstsw_ax();
2074     sahf();
2075     jcc(Assembler::parity, L);
2076   }
2077   restore_rax(tmp);
2078   // Result is in ST0.
2079   // Note: fxch & fpop to get rid of ST1
2080   // (otherwise FPU stack could overflow eventually)
2081   fxch(1);
2082   fpop();
2083 }
2084 
2085 void MacroAssembler::empty_FPU_stack() {
2086   if (VM_Version::supports_mmx()) {
2087     emms();
2088   } else {
2089     for (int i = 8; i-- > 0; ) ffree(i);
2090   }
2091 }
2092 #endif // !LP64
2093 
2094 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
2095   if (reachable(src)) {
2096     Assembler::mulpd(dst, as_Address(src));
2097   } else {
2098     lea(rscratch1, src);
2099     Assembler::mulpd(dst, Address(rscratch1, 0));
2100   }
2101 }
2102 
2103 void MacroAssembler::load_float(Address src) {
2104 #ifdef _LP64
2105   movflt(xmm0, src);
2106 #else
2107   if (UseSSE >= 1) {
2108     movflt(xmm0, src);
2109   } else {
2110     fld_s(src);
2111   }
2112 #endif // LP64
2113 }
2114 
2115 void MacroAssembler::store_float(Address dst) {
2116 #ifdef _LP64
2117   movflt(dst, xmm0);
2118 #else
2119   if (UseSSE >= 1) {
2120     movflt(dst, xmm0);
2121   } else {
2122     fstp_s(dst);
2123   }
2124 #endif // LP64
2125 }
2126 
2127 void MacroAssembler::load_double(Address src) {
2128 #ifdef _LP64
2129   movdbl(xmm0, src);
2130 #else
2131   if (UseSSE >= 2) {
2132     movdbl(xmm0, src);
2133   } else {
2134     fld_d(src);
2135   }
2136 #endif // LP64
2137 }
2138 
2139 void MacroAssembler::store_double(Address dst) {
2140 #ifdef _LP64
2141   movdbl(dst, xmm0);
2142 #else
2143   if (UseSSE >= 2) {
2144     movdbl(dst, xmm0);
2145   } else {
2146     fstp_d(dst);
2147   }
2148 #endif // LP64
2149 }
2150 
2151 // dst = c = a * b + c
2152 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
2153   Assembler::vfmadd231sd(c, a, b);
2154   if (dst != c) {
2155     movdbl(dst, c);
2156   }
2157 }
2158 
2159 // dst = c = a * b + c
2160 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
2161   Assembler::vfmadd231ss(c, a, b);
2162   if (dst != c) {
2163     movflt(dst, c);
2164   }
2165 }
2166 
2167 // dst = c = a * b + c
2168 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
2169   Assembler::vfmadd231pd(c, a, b, vector_len);
2170   if (dst != c) {
2171     vmovdqu(dst, c);
2172   }
2173 }
2174 
2175 // dst = c = a * b + c
2176 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
2177   Assembler::vfmadd231ps(c, a, b, vector_len);
2178   if (dst != c) {
2179     vmovdqu(dst, c);
2180   }
2181 }
2182 
2183 // dst = c = a * b + c
2184 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
2185   Assembler::vfmadd231pd(c, a, b, vector_len);
2186   if (dst != c) {
2187     vmovdqu(dst, c);
2188   }
2189 }
2190 
2191 // dst = c = a * b + c
2192 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
2193   Assembler::vfmadd231ps(c, a, b, vector_len);
2194   if (dst != c) {
2195     vmovdqu(dst, c);
2196   }
2197 }
2198 
2199 void MacroAssembler::incrementl(AddressLiteral dst) {
2200   if (reachable(dst)) {
2201     incrementl(as_Address(dst));
2202   } else {
2203     lea(rscratch1, dst);
2204     incrementl(Address(rscratch1, 0));
2205   }
2206 }
2207 
2208 void MacroAssembler::incrementl(ArrayAddress dst) {
2209   incrementl(as_Address(dst));
2210 }
2211 
2212 void MacroAssembler::incrementl(Register reg, int value) {
2213   if (value == min_jint) {addl(reg, value) ; return; }
2214   if (value <  0) { decrementl(reg, -value); return; }
2215   if (value == 0) {                        ; return; }
2216   if (value == 1 && UseIncDec) { incl(reg) ; return; }
2217   /* else */      { addl(reg, value)       ; return; }
2218 }
2219 
2220 void MacroAssembler::incrementl(Address dst, int value) {
2221   if (value == min_jint) {addl(dst, value) ; return; }
2222   if (value <  0) { decrementl(dst, -value); return; }
2223   if (value == 0) {                        ; return; }
2224   if (value == 1 && UseIncDec) { incl(dst) ; return; }
2225   /* else */      { addl(dst, value)       ; return; }
2226 }
2227 
2228 void MacroAssembler::jump(AddressLiteral dst) {
2229   if (reachable(dst)) {
2230     jmp_literal(dst.target(), dst.rspec());
2231   } else {
2232     lea(rscratch1, dst);
2233     jmp(rscratch1);
2234   }
2235 }
2236 
2237 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
2238   if (reachable(dst)) {
2239     InstructionMark im(this);
2240     relocate(dst.reloc());
2241     const int short_size = 2;
2242     const int long_size = 6;
2243     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
2244     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
2245       // 0111 tttn #8-bit disp
2246       emit_int8(0x70 | cc);
2247       emit_int8((offs - short_size) & 0xFF);
2248     } else {
2249       // 0000 1111 1000 tttn #32-bit disp
2250       emit_int8(0x0F);
2251       emit_int8((unsigned char)(0x80 | cc));
2252       emit_int32(offs - long_size);
2253     }
2254   } else {
2255 #ifdef ASSERT
2256     warning("reversing conditional branch");
2257 #endif /* ASSERT */
2258     Label skip;
2259     jccb(reverse[cc], skip);
2260     lea(rscratch1, dst);
2261     Assembler::jmp(rscratch1);
2262     bind(skip);
2263   }
2264 }
2265 
2266 void MacroAssembler::fld_x(AddressLiteral src) {
2267   Assembler::fld_x(as_Address(src));
2268 }
2269 
2270 void MacroAssembler::ldmxcsr(AddressLiteral src) {
2271   if (reachable(src)) {
2272     Assembler::ldmxcsr(as_Address(src));
2273   } else {
2274     lea(rscratch1, src);
2275     Assembler::ldmxcsr(Address(rscratch1, 0));
2276   }
2277 }
2278 
2279 int MacroAssembler::load_signed_byte(Register dst, Address src) {
2280   int off;
2281   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
2282     off = offset();
2283     movsbl(dst, src); // movsxb
2284   } else {
2285     off = load_unsigned_byte(dst, src);
2286     shll(dst, 24);
2287     sarl(dst, 24);
2288   }
2289   return off;
2290 }
2291 
2292 // Note: load_signed_short used to be called load_signed_word.
2293 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
2294 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
2295 // The term "word" in HotSpot means a 32- or 64-bit machine word.
2296 int MacroAssembler::load_signed_short(Register dst, Address src) {
2297   int off;
2298   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
2299     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
2300     // version but this is what 64bit has always done. This seems to imply
2301     // that users are only using 32bits worth.
2302     off = offset();
2303     movswl(dst, src); // movsxw
2304   } else {
2305     off = load_unsigned_short(dst, src);
2306     shll(dst, 16);
2307     sarl(dst, 16);
2308   }
2309   return off;
2310 }
2311 
2312 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
2313   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
2314   // and "3.9 Partial Register Penalties", p. 22).
2315   int off;
2316   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
2317     off = offset();
2318     movzbl(dst, src); // movzxb
2319   } else {
2320     xorl(dst, dst);
2321     off = offset();
2322     movb(dst, src);
2323   }
2324   return off;
2325 }
2326 
2327 // Note: load_unsigned_short used to be called load_unsigned_word.
2328 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
2329   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
2330   // and "3.9 Partial Register Penalties", p. 22).
2331   int off;
2332   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
2333     off = offset();
2334     movzwl(dst, src); // movzxw
2335   } else {
2336     xorl(dst, dst);
2337     off = offset();
2338     movw(dst, src);
2339   }
2340   return off;
2341 }
2342 
2343 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
2344   switch (size_in_bytes) {
2345 #ifndef _LP64
2346   case  8:
2347     assert(dst2 != noreg, "second dest register required");
2348     movl(dst,  src);
2349     movl(dst2, src.plus_disp(BytesPerInt));
2350     break;
2351 #else
2352   case  8:  movq(dst, src); break;
2353 #endif
2354   case  4:  movl(dst, src); break;
2355   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
2356   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
2357   default:  ShouldNotReachHere();
2358   }
2359 }
2360 
2361 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
2362   switch (size_in_bytes) {
2363 #ifndef _LP64
2364   case  8:
2365     assert(src2 != noreg, "second source register required");
2366     movl(dst,                        src);
2367     movl(dst.plus_disp(BytesPerInt), src2);
2368     break;
2369 #else
2370   case  8:  movq(dst, src); break;
2371 #endif
2372   case  4:  movl(dst, src); break;
2373   case  2:  movw(dst, src); break;
2374   case  1:  movb(dst, src); break;
2375   default:  ShouldNotReachHere();
2376   }
2377 }
2378 
2379 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
2380   if (reachable(dst)) {
2381     movl(as_Address(dst), src);
2382   } else {
2383     lea(rscratch1, dst);
2384     movl(Address(rscratch1, 0), src);
2385   }
2386 }
2387 
2388 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
2389   if (reachable(src)) {
2390     movl(dst, as_Address(src));
2391   } else {
2392     lea(rscratch1, src);
2393     movl(dst, Address(rscratch1, 0));
2394   }
2395 }
2396 
2397 // C++ bool manipulation
2398 
2399 void MacroAssembler::movbool(Register dst, Address src) {
2400   if(sizeof(bool) == 1)
2401     movb(dst, src);
2402   else if(sizeof(bool) == 2)
2403     movw(dst, src);
2404   else if(sizeof(bool) == 4)
2405     movl(dst, src);
2406   else
2407     // unsupported
2408     ShouldNotReachHere();
2409 }
2410 
2411 void MacroAssembler::movbool(Address dst, bool boolconst) {
2412   if(sizeof(bool) == 1)
2413     movb(dst, (int) boolconst);
2414   else if(sizeof(bool) == 2)
2415     movw(dst, (int) boolconst);
2416   else if(sizeof(bool) == 4)
2417     movl(dst, (int) boolconst);
2418   else
2419     // unsupported
2420     ShouldNotReachHere();
2421 }
2422 
2423 void MacroAssembler::movbool(Address dst, Register src) {
2424   if(sizeof(bool) == 1)
2425     movb(dst, src);
2426   else if(sizeof(bool) == 2)
2427     movw(dst, src);
2428   else if(sizeof(bool) == 4)
2429     movl(dst, src);
2430   else
2431     // unsupported
2432     ShouldNotReachHere();
2433 }
2434 
2435 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
2436   movb(as_Address(dst), src);
2437 }
2438 
2439 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
2440   if (reachable(src)) {
2441     movdl(dst, as_Address(src));
2442   } else {
2443     lea(rscratch1, src);
2444     movdl(dst, Address(rscratch1, 0));
2445   }
2446 }
2447 
2448 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
2449   if (reachable(src)) {
2450     movq(dst, as_Address(src));
2451   } else {
2452     lea(rscratch1, src);
2453     movq(dst, Address(rscratch1, 0));
2454   }
2455 }
2456 
2457 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
2458   if (reachable(src)) {
2459     if (UseXmmLoadAndClearUpper) {
2460       movsd (dst, as_Address(src));
2461     } else {
2462       movlpd(dst, as_Address(src));
2463     }
2464   } else {
2465     lea(rscratch1, src);
2466     if (UseXmmLoadAndClearUpper) {
2467       movsd (dst, Address(rscratch1, 0));
2468     } else {
2469       movlpd(dst, Address(rscratch1, 0));
2470     }
2471   }
2472 }
2473 
2474 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
2475   if (reachable(src)) {
2476     movss(dst, as_Address(src));
2477   } else {
2478     lea(rscratch1, src);
2479     movss(dst, Address(rscratch1, 0));
2480   }
2481 }
2482 
2483 void MacroAssembler::movptr(Register dst, Register src) {
2484   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
2485 }
2486 
2487 void MacroAssembler::movptr(Register dst, Address src) {
2488   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
2489 }
2490 
2491 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
2492 void MacroAssembler::movptr(Register dst, intptr_t src) {
2493   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
2494 }
2495 
2496 void MacroAssembler::movptr(Address dst, Register src) {
2497   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
2498 }
2499 
2500 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
2501     assert(((src->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
2502     Assembler::movdqu(dst, src);
2503 }
2504 
2505 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
2506     assert(((dst->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
2507     Assembler::movdqu(dst, src);
2508 }
2509 
2510 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
2511     assert(((dst->encoding() < 16  && src->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
2512     Assembler::movdqu(dst, src);
2513 }
2514 
2515 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
2516   if (reachable(src)) {
2517     movdqu(dst, as_Address(src));
2518   } else {
2519     lea(scratchReg, src);
2520     movdqu(dst, Address(scratchReg, 0));
2521   }
2522 }
2523 
2524 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
2525     assert(((src->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
2526     Assembler::vmovdqu(dst, src);
2527 }
2528 
2529 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
2530     assert(((dst->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
2531     Assembler::vmovdqu(dst, src);
2532 }
2533 
2534 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
2535     assert(((dst->encoding() < 16  && src->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
2536     Assembler::vmovdqu(dst, src);
2537 }
2538 
2539 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src, Register scratch_reg) {
2540   if (reachable(src)) {
2541     vmovdqu(dst, as_Address(src));
2542   }
2543   else {
2544     lea(scratch_reg, src);
2545     vmovdqu(dst, Address(scratch_reg, 0));
2546   }
2547 }
2548 
2549 void MacroAssembler::kmov(KRegister dst, Address src) {
2550   if (VM_Version::supports_avx512bw()) {
2551     kmovql(dst, src);
2552   } else {
2553     assert(VM_Version::supports_evex(), "");
2554     kmovwl(dst, src);
2555   }
2556 }
2557 
2558 void MacroAssembler::kmov(Address dst, KRegister src) {
2559   if (VM_Version::supports_avx512bw()) {
2560     kmovql(dst, src);
2561   } else {
2562     assert(VM_Version::supports_evex(), "");
2563     kmovwl(dst, src);
2564   }
2565 }
2566 
2567 void MacroAssembler::kmov(KRegister dst, KRegister src) {
2568   if (VM_Version::supports_avx512bw()) {
2569     kmovql(dst, src);
2570   } else {
2571     assert(VM_Version::supports_evex(), "");
2572     kmovwl(dst, src);
2573   }
2574 }
2575 
2576 void MacroAssembler::kmov(Register dst, KRegister src) {
2577   if (VM_Version::supports_avx512bw()) {
2578     kmovql(dst, src);
2579   } else {
2580     assert(VM_Version::supports_evex(), "");
2581     kmovwl(dst, src);
2582   }
2583 }
2584 
2585 void MacroAssembler::kmov(KRegister dst, Register src) {
2586   if (VM_Version::supports_avx512bw()) {
2587     kmovql(dst, src);
2588   } else {
2589     assert(VM_Version::supports_evex(), "");
2590     kmovwl(dst, src);
2591   }
2592 }
2593 
2594 void MacroAssembler::kmovql(KRegister dst, AddressLiteral src, Register scratch_reg) {
2595   if (reachable(src)) {
2596     kmovql(dst, as_Address(src));
2597   } else {
2598     lea(scratch_reg, src);
2599     kmovql(dst, Address(scratch_reg, 0));
2600   }
2601 }
2602 
2603 void MacroAssembler::kmovwl(KRegister dst, AddressLiteral src, Register scratch_reg) {
2604   if (reachable(src)) {
2605     kmovwl(dst, as_Address(src));
2606   } else {
2607     lea(scratch_reg, src);
2608     kmovwl(dst, Address(scratch_reg, 0));
2609   }
2610 }
2611 
2612 void MacroAssembler::evmovdqub(XMMRegister dst, KRegister mask, AddressLiteral src, bool merge,
2613                                int vector_len, Register scratch_reg) {
2614   if (reachable(src)) {
2615     if (mask == k0) {
2616       Assembler::evmovdqub(dst, as_Address(src), merge, vector_len);
2617     } else {
2618       Assembler::evmovdqub(dst, mask, as_Address(src), merge, vector_len);
2619     }
2620   } else {
2621     lea(scratch_reg, src);
2622     if (mask == k0) {
2623       Assembler::evmovdqub(dst, Address(scratch_reg, 0), merge, vector_len);
2624     } else {
2625       Assembler::evmovdqub(dst, mask, Address(scratch_reg, 0), merge, vector_len);
2626     }
2627   }
2628 }
2629 
2630 void MacroAssembler::evmovdquw(XMMRegister dst, KRegister mask, AddressLiteral src, bool merge,
2631                                int vector_len, Register scratch_reg) {
2632   if (reachable(src)) {
2633     Assembler::evmovdquw(dst, mask, as_Address(src), merge, vector_len);
2634   } else {
2635     lea(scratch_reg, src);
2636     Assembler::evmovdquw(dst, mask, Address(scratch_reg, 0), merge, vector_len);
2637   }
2638 }
2639 
2640 void MacroAssembler::evmovdqul(XMMRegister dst, KRegister mask, AddressLiteral src, bool merge,
2641                                int vector_len, Register scratch_reg) {
2642   if (reachable(src)) {
2643     Assembler::evmovdqul(dst, mask, as_Address(src), merge, vector_len);
2644   } else {
2645     lea(scratch_reg, src);
2646     Assembler::evmovdqul(dst, mask, Address(scratch_reg, 0), merge, vector_len);
2647   }
2648 }
2649 
2650 void MacroAssembler::evmovdquq(XMMRegister dst, KRegister mask, AddressLiteral src, bool merge,
2651                                int vector_len, Register scratch_reg) {
2652   if (reachable(src)) {
2653     Assembler::evmovdquq(dst, mask, as_Address(src), merge, vector_len);
2654   } else {
2655     lea(scratch_reg, src);
2656     Assembler::evmovdquq(dst, mask, Address(scratch_reg, 0), merge, vector_len);
2657   }
2658 }
2659 
2660 void MacroAssembler::evmovdquq(XMMRegister dst, AddressLiteral src, int vector_len, Register rscratch) {
2661   if (reachable(src)) {
2662     Assembler::evmovdquq(dst, as_Address(src), vector_len);
2663   } else {
2664     lea(rscratch, src);
2665     Assembler::evmovdquq(dst, Address(rscratch, 0), vector_len);
2666   }
2667 }
2668 
2669 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
2670   if (reachable(src)) {
2671     Assembler::movdqa(dst, as_Address(src));
2672   } else {
2673     lea(rscratch1, src);
2674     Assembler::movdqa(dst, Address(rscratch1, 0));
2675   }
2676 }
2677 
2678 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
2679   if (reachable(src)) {
2680     Assembler::movsd(dst, as_Address(src));
2681   } else {
2682     lea(rscratch1, src);
2683     Assembler::movsd(dst, Address(rscratch1, 0));
2684   }
2685 }
2686 
2687 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
2688   if (reachable(src)) {
2689     Assembler::movss(dst, as_Address(src));
2690   } else {
2691     lea(rscratch1, src);
2692     Assembler::movss(dst, Address(rscratch1, 0));
2693   }
2694 }
2695 
2696 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
2697   if (reachable(src)) {
2698     Assembler::mulsd(dst, as_Address(src));
2699   } else {
2700     lea(rscratch1, src);
2701     Assembler::mulsd(dst, Address(rscratch1, 0));
2702   }
2703 }
2704 
2705 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
2706   if (reachable(src)) {
2707     Assembler::mulss(dst, as_Address(src));
2708   } else {
2709     lea(rscratch1, src);
2710     Assembler::mulss(dst, Address(rscratch1, 0));
2711   }
2712 }
2713 
2714 void MacroAssembler::null_check(Register reg, int offset) {
2715   if (needs_explicit_null_check(offset)) {
2716     // provoke OS NULL exception if reg = NULL by
2717     // accessing M[reg] w/o changing any (non-CC) registers
2718     // NOTE: cmpl is plenty here to provoke a segv
2719     cmpptr(rax, Address(reg, 0));
2720     // Note: should probably use testl(rax, Address(reg, 0));
2721     //       may be shorter code (however, this version of
2722     //       testl needs to be implemented first)
2723   } else {
2724     // nothing to do, (later) access of M[reg + offset]
2725     // will provoke OS NULL exception if reg = NULL
2726   }
2727 }
2728 
2729 void MacroAssembler::os_breakpoint() {
2730   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
2731   // (e.g., MSVC can't call ps() otherwise)
2732   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
2733 }
2734 
2735 void MacroAssembler::unimplemented(const char* what) {
2736   const char* buf = NULL;
2737   {
2738     ResourceMark rm;
2739     stringStream ss;
2740     ss.print("unimplemented: %s", what);
2741     buf = code_string(ss.as_string());
2742   }
2743   stop(buf);
2744 }
2745 
2746 #ifdef _LP64
2747 #define XSTATE_BV 0x200
2748 #endif
2749 
2750 void MacroAssembler::pop_CPU_state() {
2751   pop_FPU_state();
2752   pop_IU_state();
2753 }
2754 
2755 void MacroAssembler::pop_FPU_state() {
2756 #ifndef _LP64
2757   frstor(Address(rsp, 0));
2758 #else
2759   fxrstor(Address(rsp, 0));
2760 #endif
2761   addptr(rsp, FPUStateSizeInWords * wordSize);
2762 }
2763 
2764 void MacroAssembler::pop_IU_state() {
2765   popa();
2766   LP64_ONLY(addq(rsp, 8));
2767   popf();
2768 }
2769 
2770 // Save Integer and Float state
2771 // Warning: Stack must be 16 byte aligned (64bit)
2772 void MacroAssembler::push_CPU_state() {
2773   push_IU_state();
2774   push_FPU_state();
2775 }
2776 
2777 void MacroAssembler::push_FPU_state() {
2778   subptr(rsp, FPUStateSizeInWords * wordSize);
2779 #ifndef _LP64
2780   fnsave(Address(rsp, 0));
2781   fwait();
2782 #else
2783   fxsave(Address(rsp, 0));
2784 #endif // LP64
2785 }
2786 
2787 void MacroAssembler::push_IU_state() {
2788   // Push flags first because pusha kills them
2789   pushf();
2790   // Make sure rsp stays 16-byte aligned
2791   LP64_ONLY(subq(rsp, 8));
2792   pusha();
2793 }
2794 
2795 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
2796   if (!java_thread->is_valid()) {
2797     java_thread = rdi;
2798     get_thread(java_thread);
2799   }
2800   // we must set sp to zero to clear frame
2801   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
2802   // must clear fp, so that compiled frames are not confused; it is
2803   // possible that we need it only for debugging
2804   if (clear_fp) {
2805     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
2806   }
2807   // Always clear the pc because it could have been set by make_walkable()
2808   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
2809   vzeroupper();
2810 }
2811 
2812 void MacroAssembler::restore_rax(Register tmp) {
2813   if (tmp == noreg) pop(rax);
2814   else if (tmp != rax) mov(rax, tmp);
2815 }
2816 
2817 void MacroAssembler::round_to(Register reg, int modulus) {
2818   addptr(reg, modulus - 1);
2819   andptr(reg, -modulus);
2820 }
2821 
2822 void MacroAssembler::save_rax(Register tmp) {
2823   if (tmp == noreg) push(rax);
2824   else if (tmp != rax) mov(tmp, rax);
2825 }
2826 
2827 void MacroAssembler::safepoint_poll(Label& slow_path, Register thread_reg, bool at_return, bool in_nmethod) {
2828   if (at_return) {
2829     // Note that when in_nmethod is set, the stack pointer is incremented before the poll. Therefore,
2830     // we may safely use rsp instead to perform the stack watermark check.
2831     cmpptr(in_nmethod ? rsp : rbp, Address(thread_reg, JavaThread::polling_word_offset()));
2832     jcc(Assembler::above, slow_path);
2833     return;
2834   }
2835   testb(Address(thread_reg, JavaThread::polling_word_offset()), SafepointMechanism::poll_bit());
2836   jcc(Assembler::notZero, slow_path); // handshake bit set implies poll
2837 }
2838 
2839 // Calls to C land
2840 //
2841 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
2842 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
2843 // has to be reset to 0. This is required to allow proper stack traversal.
2844 void MacroAssembler::set_last_Java_frame(Register java_thread,
2845                                          Register last_java_sp,
2846                                          Register last_java_fp,
2847                                          address  last_java_pc) {
2848   vzeroupper();
2849   // determine java_thread register
2850   if (!java_thread->is_valid()) {
2851     java_thread = rdi;
2852     get_thread(java_thread);
2853   }
2854   // determine last_java_sp register
2855   if (!last_java_sp->is_valid()) {
2856     last_java_sp = rsp;
2857   }
2858 
2859   // last_java_fp is optional
2860 
2861   if (last_java_fp->is_valid()) {
2862     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
2863   }
2864 
2865   // last_java_pc is optional
2866 
2867   if (last_java_pc != NULL) {
2868     lea(Address(java_thread,
2869                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
2870         InternalAddress(last_java_pc));
2871 
2872   }
2873   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
2874 }
2875 
2876 void MacroAssembler::shlptr(Register dst, int imm8) {
2877   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
2878 }
2879 
2880 void MacroAssembler::shrptr(Register dst, int imm8) {
2881   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
2882 }
2883 
2884 void MacroAssembler::sign_extend_byte(Register reg) {
2885   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
2886     movsbl(reg, reg); // movsxb
2887   } else {
2888     shll(reg, 24);
2889     sarl(reg, 24);
2890   }
2891 }
2892 
2893 void MacroAssembler::sign_extend_short(Register reg) {
2894   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
2895     movswl(reg, reg); // movsxw
2896   } else {
2897     shll(reg, 16);
2898     sarl(reg, 16);
2899   }
2900 }
2901 
2902 void MacroAssembler::testl(Register dst, AddressLiteral src) {
2903   assert(reachable(src), "Address should be reachable");
2904   testl(dst, as_Address(src));
2905 }
2906 
2907 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
2908   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
2909   Assembler::pcmpeqb(dst, src);
2910 }
2911 
2912 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
2913   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
2914   Assembler::pcmpeqw(dst, src);
2915 }
2916 
2917 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
2918   assert((dst->encoding() < 16),"XMM register should be 0-15");
2919   Assembler::pcmpestri(dst, src, imm8);
2920 }
2921 
2922 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
2923   assert((dst->encoding() < 16 && src->encoding() < 16),"XMM register should be 0-15");
2924   Assembler::pcmpestri(dst, src, imm8);
2925 }
2926 
2927 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
2928   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
2929   Assembler::pmovzxbw(dst, src);
2930 }
2931 
2932 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
2933   assert(((dst->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
2934   Assembler::pmovzxbw(dst, src);
2935 }
2936 
2937 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
2938   assert((src->encoding() < 16),"XMM register should be 0-15");
2939   Assembler::pmovmskb(dst, src);
2940 }
2941 
2942 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
2943   assert((dst->encoding() < 16 && src->encoding() < 16),"XMM register should be 0-15");
2944   Assembler::ptest(dst, src);
2945 }
2946 
2947 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
2948   if (reachable(src)) {
2949     Assembler::sqrtsd(dst, as_Address(src));
2950   } else {
2951     lea(rscratch1, src);
2952     Assembler::sqrtsd(dst, Address(rscratch1, 0));
2953   }
2954 }
2955 
2956 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
2957   if (reachable(src)) {
2958     Assembler::sqrtss(dst, as_Address(src));
2959   } else {
2960     lea(rscratch1, src);
2961     Assembler::sqrtss(dst, Address(rscratch1, 0));
2962   }
2963 }
2964 
2965 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
2966   if (reachable(src)) {
2967     Assembler::subsd(dst, as_Address(src));
2968   } else {
2969     lea(rscratch1, src);
2970     Assembler::subsd(dst, Address(rscratch1, 0));
2971   }
2972 }
2973 
2974 void MacroAssembler::roundsd(XMMRegister dst, AddressLiteral src, int32_t rmode, Register scratch_reg) {
2975   if (reachable(src)) {
2976     Assembler::roundsd(dst, as_Address(src), rmode);
2977   } else {
2978     lea(scratch_reg, src);
2979     Assembler::roundsd(dst, Address(scratch_reg, 0), rmode);
2980   }
2981 }
2982 
2983 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
2984   if (reachable(src)) {
2985     Assembler::subss(dst, as_Address(src));
2986   } else {
2987     lea(rscratch1, src);
2988     Assembler::subss(dst, Address(rscratch1, 0));
2989   }
2990 }
2991 
2992 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
2993   if (reachable(src)) {
2994     Assembler::ucomisd(dst, as_Address(src));
2995   } else {
2996     lea(rscratch1, src);
2997     Assembler::ucomisd(dst, Address(rscratch1, 0));
2998   }
2999 }
3000 
3001 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
3002   if (reachable(src)) {
3003     Assembler::ucomiss(dst, as_Address(src));
3004   } else {
3005     lea(rscratch1, src);
3006     Assembler::ucomiss(dst, Address(rscratch1, 0));
3007   }
3008 }
3009 
3010 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src, Register scratch_reg) {
3011   // Used in sign-bit flipping with aligned address.
3012   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
3013   if (reachable(src)) {
3014     Assembler::xorpd(dst, as_Address(src));
3015   } else {
3016     lea(scratch_reg, src);
3017     Assembler::xorpd(dst, Address(scratch_reg, 0));
3018   }
3019 }
3020 
3021 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
3022   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
3023     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
3024   }
3025   else {
3026     Assembler::xorpd(dst, src);
3027   }
3028 }
3029 
3030 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
3031   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
3032     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
3033   } else {
3034     Assembler::xorps(dst, src);
3035   }
3036 }
3037 
3038 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src, Register scratch_reg) {
3039   // Used in sign-bit flipping with aligned address.
3040   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
3041   if (reachable(src)) {
3042     Assembler::xorps(dst, as_Address(src));
3043   } else {
3044     lea(scratch_reg, src);
3045     Assembler::xorps(dst, Address(scratch_reg, 0));
3046   }
3047 }
3048 
3049 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
3050   // Used in sign-bit flipping with aligned address.
3051   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
3052   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
3053   if (reachable(src)) {
3054     Assembler::pshufb(dst, as_Address(src));
3055   } else {
3056     lea(rscratch1, src);
3057     Assembler::pshufb(dst, Address(rscratch1, 0));
3058   }
3059 }
3060 
3061 // AVX 3-operands instructions
3062 
3063 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3064   if (reachable(src)) {
3065     vaddsd(dst, nds, as_Address(src));
3066   } else {
3067     lea(rscratch1, src);
3068     vaddsd(dst, nds, Address(rscratch1, 0));
3069   }
3070 }
3071 
3072 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3073   if (reachable(src)) {
3074     vaddss(dst, nds, as_Address(src));
3075   } else {
3076     lea(rscratch1, src);
3077     vaddss(dst, nds, Address(rscratch1, 0));
3078   }
3079 }
3080 
3081 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register rscratch) {
3082   assert(UseAVX > 0, "requires some form of AVX");
3083   if (reachable(src)) {
3084     Assembler::vpaddb(dst, nds, as_Address(src), vector_len);
3085   } else {
3086     lea(rscratch, src);
3087     Assembler::vpaddb(dst, nds, Address(rscratch, 0), vector_len);
3088   }
3089 }
3090 
3091 void MacroAssembler::vpaddd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register rscratch) {
3092   assert(UseAVX > 0, "requires some form of AVX");
3093   if (reachable(src)) {
3094     Assembler::vpaddd(dst, nds, as_Address(src), vector_len);
3095   } else {
3096     lea(rscratch, src);
3097     Assembler::vpaddd(dst, nds, Address(rscratch, 0), vector_len);
3098   }
3099 }
3100 
3101 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
3102   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
3103   vandps(dst, nds, negate_field, vector_len);
3104 }
3105 
3106 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
3107   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
3108   vandpd(dst, nds, negate_field, vector_len);
3109 }
3110 
3111 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3112   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3113   Assembler::vpaddb(dst, nds, src, vector_len);
3114 }
3115 
3116 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3117   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3118   Assembler::vpaddb(dst, nds, src, vector_len);
3119 }
3120 
3121 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3122   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3123   Assembler::vpaddw(dst, nds, src, vector_len);
3124 }
3125 
3126 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3127   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3128   Assembler::vpaddw(dst, nds, src, vector_len);
3129 }
3130 
3131 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register scratch_reg) {
3132   if (reachable(src)) {
3133     Assembler::vpand(dst, nds, as_Address(src), vector_len);
3134   } else {
3135     lea(scratch_reg, src);
3136     Assembler::vpand(dst, nds, Address(scratch_reg, 0), vector_len);
3137   }
3138 }
3139 
3140 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src, int vector_len) {
3141   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3142   Assembler::vpbroadcastw(dst, src, vector_len);
3143 }
3144 
3145 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3146   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3147   Assembler::vpcmpeqb(dst, nds, src, vector_len);
3148 }
3149 
3150 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3151   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3152   Assembler::vpcmpeqw(dst, nds, src, vector_len);
3153 }
3154 
3155 void MacroAssembler::evpcmpeqd(KRegister kdst, KRegister mask, XMMRegister nds,
3156                                AddressLiteral src, int vector_len, Register scratch_reg) {
3157   if (reachable(src)) {
3158     Assembler::evpcmpeqd(kdst, mask, nds, as_Address(src), vector_len);
3159   } else {
3160     lea(scratch_reg, src);
3161     Assembler::evpcmpeqd(kdst, mask, nds, Address(scratch_reg, 0), vector_len);
3162   }
3163 }
3164 
3165 void MacroAssembler::evpcmpd(KRegister kdst, KRegister mask, XMMRegister nds, AddressLiteral src,
3166                              int comparison, bool is_signed, int vector_len, Register scratch_reg) {
3167   if (reachable(src)) {
3168     Assembler::evpcmpd(kdst, mask, nds, as_Address(src), comparison, is_signed, vector_len);
3169   } else {
3170     lea(scratch_reg, src);
3171     Assembler::evpcmpd(kdst, mask, nds, Address(scratch_reg, 0), comparison, is_signed, vector_len);
3172   }
3173 }
3174 
3175 void MacroAssembler::evpcmpq(KRegister kdst, KRegister mask, XMMRegister nds, AddressLiteral src,
3176                              int comparison, bool is_signed, int vector_len, Register scratch_reg) {
3177   if (reachable(src)) {
3178     Assembler::evpcmpq(kdst, mask, nds, as_Address(src), comparison, is_signed, vector_len);
3179   } else {
3180     lea(scratch_reg, src);
3181     Assembler::evpcmpq(kdst, mask, nds, Address(scratch_reg, 0), comparison, is_signed, vector_len);
3182   }
3183 }
3184 
3185 void MacroAssembler::evpcmpb(KRegister kdst, KRegister mask, XMMRegister nds, AddressLiteral src,
3186                              int comparison, bool is_signed, int vector_len, Register scratch_reg) {
3187   if (reachable(src)) {
3188     Assembler::evpcmpb(kdst, mask, nds, as_Address(src), comparison, is_signed, vector_len);
3189   } else {
3190     lea(scratch_reg, src);
3191     Assembler::evpcmpb(kdst, mask, nds, Address(scratch_reg, 0), comparison, is_signed, vector_len);
3192   }
3193 }
3194 
3195 void MacroAssembler::evpcmpw(KRegister kdst, KRegister mask, XMMRegister nds, AddressLiteral src,
3196                              int comparison, bool is_signed, int vector_len, Register scratch_reg) {
3197   if (reachable(src)) {
3198     Assembler::evpcmpw(kdst, mask, nds, as_Address(src), comparison, is_signed, vector_len);
3199   } else {
3200     lea(scratch_reg, src);
3201     Assembler::evpcmpw(kdst, mask, nds, Address(scratch_reg, 0), comparison, is_signed, vector_len);
3202   }
3203 }
3204 
3205 void MacroAssembler::vpcmpCC(XMMRegister dst, XMMRegister nds, XMMRegister src, int cond_encoding, Width width, int vector_len) {
3206   if (width == Assembler::Q) {
3207     Assembler::vpcmpCCq(dst, nds, src, cond_encoding, vector_len);
3208   } else {
3209     Assembler::vpcmpCCbwd(dst, nds, src, cond_encoding, vector_len);
3210   }
3211 }
3212 
3213 void MacroAssembler::vpcmpCCW(XMMRegister dst, XMMRegister nds, XMMRegister src, ComparisonPredicate cond, Width width, int vector_len, Register scratch_reg) {
3214   int eq_cond_enc = 0x29;
3215   int gt_cond_enc = 0x37;
3216   if (width != Assembler::Q) {
3217     eq_cond_enc = 0x74 + width;
3218     gt_cond_enc = 0x64 + width;
3219   }
3220   switch (cond) {
3221   case eq:
3222     vpcmpCC(dst, nds, src, eq_cond_enc, width, vector_len);
3223     break;
3224   case neq:
3225     vpcmpCC(dst, nds, src, eq_cond_enc, width, vector_len);
3226     vpxor(dst, dst, ExternalAddress(StubRoutines::x86::vector_all_bits_set()), vector_len, scratch_reg);
3227     break;
3228   case le:
3229     vpcmpCC(dst, nds, src, gt_cond_enc, width, vector_len);
3230     vpxor(dst, dst, ExternalAddress(StubRoutines::x86::vector_all_bits_set()), vector_len, scratch_reg);
3231     break;
3232   case nlt:
3233     vpcmpCC(dst, src, nds, gt_cond_enc, width, vector_len);
3234     vpxor(dst, dst, ExternalAddress(StubRoutines::x86::vector_all_bits_set()), vector_len, scratch_reg);
3235     break;
3236   case lt:
3237     vpcmpCC(dst, src, nds, gt_cond_enc, width, vector_len);
3238     break;
3239   case nle:
3240     vpcmpCC(dst, nds, src, gt_cond_enc, width, vector_len);
3241     break;
3242   default:
3243     assert(false, "Should not reach here");
3244   }
3245 }
3246 
3247 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
3248   assert(((dst->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3249   Assembler::vpmovzxbw(dst, src, vector_len);
3250 }
3251 
3252 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src, int vector_len) {
3253   assert((src->encoding() < 16),"XMM register should be 0-15");
3254   Assembler::vpmovmskb(dst, src, vector_len);
3255 }
3256 
3257 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3258   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3259   Assembler::vpmullw(dst, nds, src, vector_len);
3260 }
3261 
3262 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3263   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3264   Assembler::vpmullw(dst, nds, src, vector_len);
3265 }
3266 
3267 void MacroAssembler::vpmulld(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register scratch_reg) {
3268   assert((UseAVX > 0), "AVX support is needed");
3269   if (reachable(src)) {
3270     Assembler::vpmulld(dst, nds, as_Address(src), vector_len);
3271   } else {
3272     lea(scratch_reg, src);
3273     Assembler::vpmulld(dst, nds, Address(scratch_reg, 0), vector_len);
3274   }
3275 }
3276 
3277 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3278   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3279   Assembler::vpsubb(dst, nds, src, vector_len);
3280 }
3281 
3282 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3283   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3284   Assembler::vpsubb(dst, nds, src, vector_len);
3285 }
3286 
3287 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3288   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3289   Assembler::vpsubw(dst, nds, src, vector_len);
3290 }
3291 
3292 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3293   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3294   Assembler::vpsubw(dst, nds, src, vector_len);
3295 }
3296 
3297 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
3298   assert(((dst->encoding() < 16 && shift->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3299   Assembler::vpsraw(dst, nds, shift, vector_len);
3300 }
3301 
3302 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
3303   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3304   Assembler::vpsraw(dst, nds, shift, vector_len);
3305 }
3306 
3307 void MacroAssembler::evpsraq(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
3308   assert(UseAVX > 2,"");
3309   if (!VM_Version::supports_avx512vl() && vector_len < 2) {
3310      vector_len = 2;
3311   }
3312   Assembler::evpsraq(dst, nds, shift, vector_len);
3313 }
3314 
3315 void MacroAssembler::evpsraq(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
3316   assert(UseAVX > 2,"");
3317   if (!VM_Version::supports_avx512vl() && vector_len < 2) {
3318      vector_len = 2;
3319   }
3320   Assembler::evpsraq(dst, nds, shift, vector_len);
3321 }
3322 
3323 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
3324   assert(((dst->encoding() < 16 && shift->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3325   Assembler::vpsrlw(dst, nds, shift, vector_len);
3326 }
3327 
3328 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
3329   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3330   Assembler::vpsrlw(dst, nds, shift, vector_len);
3331 }
3332 
3333 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
3334   assert(((dst->encoding() < 16 && shift->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3335   Assembler::vpsllw(dst, nds, shift, vector_len);
3336 }
3337 
3338 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
3339   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3340   Assembler::vpsllw(dst, nds, shift, vector_len);
3341 }
3342 
3343 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
3344   assert((dst->encoding() < 16 && src->encoding() < 16),"XMM register should be 0-15");
3345   Assembler::vptest(dst, src);
3346 }
3347 
3348 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
3349   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3350   Assembler::punpcklbw(dst, src);
3351 }
3352 
3353 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
3354   assert(((dst->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
3355   Assembler::pshufd(dst, src, mode);
3356 }
3357 
3358 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
3359   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3360   Assembler::pshuflw(dst, src, mode);
3361 }
3362 
3363 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register scratch_reg) {
3364   if (reachable(src)) {
3365     vandpd(dst, nds, as_Address(src), vector_len);
3366   } else {
3367     lea(scratch_reg, src);
3368     vandpd(dst, nds, Address(scratch_reg, 0), vector_len);
3369   }
3370 }
3371 
3372 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register scratch_reg) {
3373   if (reachable(src)) {
3374     vandps(dst, nds, as_Address(src), vector_len);
3375   } else {
3376     lea(scratch_reg, src);
3377     vandps(dst, nds, Address(scratch_reg, 0), vector_len);
3378   }
3379 }
3380 
3381 void MacroAssembler::evpord(XMMRegister dst, KRegister mask, XMMRegister nds, AddressLiteral src,
3382                             bool merge, int vector_len, Register scratch_reg) {
3383   if (reachable(src)) {
3384     Assembler::evpord(dst, mask, nds, as_Address(src), merge, vector_len);
3385   } else {
3386     lea(scratch_reg, src);
3387     Assembler::evpord(dst, mask, nds, Address(scratch_reg, 0), merge, vector_len);
3388   }
3389 }
3390 
3391 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3392   if (reachable(src)) {
3393     vdivsd(dst, nds, as_Address(src));
3394   } else {
3395     lea(rscratch1, src);
3396     vdivsd(dst, nds, Address(rscratch1, 0));
3397   }
3398 }
3399 
3400 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3401   if (reachable(src)) {
3402     vdivss(dst, nds, as_Address(src));
3403   } else {
3404     lea(rscratch1, src);
3405     vdivss(dst, nds, Address(rscratch1, 0));
3406   }
3407 }
3408 
3409 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3410   if (reachable(src)) {
3411     vmulsd(dst, nds, as_Address(src));
3412   } else {
3413     lea(rscratch1, src);
3414     vmulsd(dst, nds, Address(rscratch1, 0));
3415   }
3416 }
3417 
3418 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3419   if (reachable(src)) {
3420     vmulss(dst, nds, as_Address(src));
3421   } else {
3422     lea(rscratch1, src);
3423     vmulss(dst, nds, Address(rscratch1, 0));
3424   }
3425 }
3426 
3427 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3428   if (reachable(src)) {
3429     vsubsd(dst, nds, as_Address(src));
3430   } else {
3431     lea(rscratch1, src);
3432     vsubsd(dst, nds, Address(rscratch1, 0));
3433   }
3434 }
3435 
3436 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3437   if (reachable(src)) {
3438     vsubss(dst, nds, as_Address(src));
3439   } else {
3440     lea(rscratch1, src);
3441     vsubss(dst, nds, Address(rscratch1, 0));
3442   }
3443 }
3444 
3445 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3446   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
3447   vxorps(dst, nds, src, Assembler::AVX_128bit);
3448 }
3449 
3450 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3451   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
3452   vxorpd(dst, nds, src, Assembler::AVX_128bit);
3453 }
3454 
3455 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register scratch_reg) {
3456   if (reachable(src)) {
3457     vxorpd(dst, nds, as_Address(src), vector_len);
3458   } else {
3459     lea(scratch_reg, src);
3460     vxorpd(dst, nds, Address(scratch_reg, 0), vector_len);
3461   }
3462 }
3463 
3464 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register scratch_reg) {
3465   if (reachable(src)) {
3466     vxorps(dst, nds, as_Address(src), vector_len);
3467   } else {
3468     lea(scratch_reg, src);
3469     vxorps(dst, nds, Address(scratch_reg, 0), vector_len);
3470   }
3471 }
3472 
3473 void MacroAssembler::vpxor(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register scratch_reg) {
3474   if (UseAVX > 1 || (vector_len < 1)) {
3475     if (reachable(src)) {
3476       Assembler::vpxor(dst, nds, as_Address(src), vector_len);
3477     } else {
3478       lea(scratch_reg, src);
3479       Assembler::vpxor(dst, nds, Address(scratch_reg, 0), vector_len);
3480     }
3481   }
3482   else {
3483     MacroAssembler::vxorpd(dst, nds, src, vector_len, scratch_reg);
3484   }
3485 }
3486 
3487 void MacroAssembler::vpermd(XMMRegister dst,  XMMRegister nds, AddressLiteral src, int vector_len, Register scratch_reg) {
3488   if (reachable(src)) {
3489     Assembler::vpermd(dst, nds, as_Address(src), vector_len);
3490   } else {
3491     lea(scratch_reg, src);
3492     Assembler::vpermd(dst, nds, Address(scratch_reg, 0), vector_len);
3493   }
3494 }
3495 
3496 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
3497   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
3498   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
3499   // The inverted mask is sign-extended
3500   andptr(possibly_jweak, inverted_jweak_mask);
3501 }
3502 
3503 void MacroAssembler::resolve_jobject(Register value,
3504                                      Register thread,
3505                                      Register tmp) {
3506   assert_different_registers(value, thread, tmp);
3507   Label done, not_weak;
3508   testptr(value, value);
3509   jcc(Assembler::zero, done);                // Use NULL as-is.
3510   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
3511   jcc(Assembler::zero, not_weak);
3512   // Resolve jweak.
3513   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
3514                  value, Address(value, -JNIHandles::weak_tag_value), tmp, thread);
3515   verify_oop(value);
3516   jmp(done);
3517   bind(not_weak);
3518   // Resolve (untagged) jobject.
3519   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, 0), tmp, thread);
3520   verify_oop(value);
3521   bind(done);
3522 }
3523 
3524 void MacroAssembler::subptr(Register dst, int32_t imm32) {
3525   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
3526 }
3527 
3528 // Force generation of a 4 byte immediate value even if it fits into 8bit
3529 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
3530   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
3531 }
3532 
3533 void MacroAssembler::subptr(Register dst, Register src) {
3534   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
3535 }
3536 
3537 // C++ bool manipulation
3538 void MacroAssembler::testbool(Register dst) {
3539   if(sizeof(bool) == 1)
3540     testb(dst, 0xff);
3541   else if(sizeof(bool) == 2) {
3542     // testw implementation needed for two byte bools
3543     ShouldNotReachHere();
3544   } else if(sizeof(bool) == 4)
3545     testl(dst, dst);
3546   else
3547     // unsupported
3548     ShouldNotReachHere();
3549 }
3550 
3551 void MacroAssembler::testptr(Register dst, Register src) {
3552   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
3553 }
3554 
3555 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
3556 void MacroAssembler::tlab_allocate(Register thread, Register obj,
3557                                    Register var_size_in_bytes,
3558                                    int con_size_in_bytes,
3559                                    Register t1,
3560                                    Register t2,
3561                                    Label& slow_case) {
3562   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
3563   bs->tlab_allocate(this, thread, obj, var_size_in_bytes, con_size_in_bytes, t1, t2, slow_case);
3564 }
3565 
3566 // Defines obj, preserves var_size_in_bytes
3567 void MacroAssembler::eden_allocate(Register thread, Register obj,
3568                                    Register var_size_in_bytes,
3569                                    int con_size_in_bytes,
3570                                    Register t1,
3571                                    Label& slow_case) {
3572   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
3573   bs->eden_allocate(this, thread, obj, var_size_in_bytes, con_size_in_bytes, t1, slow_case);
3574 }
3575 
3576 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
3577 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
3578   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
3579   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
3580   Label done;
3581 
3582   testptr(length_in_bytes, length_in_bytes);
3583   jcc(Assembler::zero, done);
3584 
3585   // initialize topmost word, divide index by 2, check if odd and test if zero
3586   // note: for the remaining code to work, index must be a multiple of BytesPerWord
3587 #ifdef ASSERT
3588   {
3589     Label L;
3590     testptr(length_in_bytes, BytesPerWord - 1);
3591     jcc(Assembler::zero, L);
3592     stop("length must be a multiple of BytesPerWord");
3593     bind(L);
3594   }
3595 #endif
3596   Register index = length_in_bytes;
3597   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
3598   if (UseIncDec) {
3599     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
3600   } else {
3601     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
3602     shrptr(index, 1);
3603   }
3604 #ifndef _LP64
3605   // index could have not been a multiple of 8 (i.e., bit 2 was set)
3606   {
3607     Label even;
3608     // note: if index was a multiple of 8, then it cannot
3609     //       be 0 now otherwise it must have been 0 before
3610     //       => if it is even, we don't need to check for 0 again
3611     jcc(Assembler::carryClear, even);
3612     // clear topmost word (no jump would be needed if conditional assignment worked here)
3613     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
3614     // index could be 0 now, must check again
3615     jcc(Assembler::zero, done);
3616     bind(even);
3617   }
3618 #endif // !_LP64
3619   // initialize remaining object fields: index is a multiple of 2 now
3620   {
3621     Label loop;
3622     bind(loop);
3623     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
3624     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
3625     decrement(index);
3626     jcc(Assembler::notZero, loop);
3627   }
3628 
3629   bind(done);
3630 }
3631 
3632 // Look up the method for a megamorphic invokeinterface call.
3633 // The target method is determined by <intf_klass, itable_index>.
3634 // The receiver klass is in recv_klass.
3635 // On success, the result will be in method_result, and execution falls through.
3636 // On failure, execution transfers to the given label.
3637 void MacroAssembler::lookup_interface_method(Register recv_klass,
3638                                              Register intf_klass,
3639                                              RegisterOrConstant itable_index,
3640                                              Register method_result,
3641                                              Register scan_temp,
3642                                              Label& L_no_such_interface,
3643                                              bool return_method) {
3644   assert_different_registers(recv_klass, intf_klass, scan_temp);
3645   assert_different_registers(method_result, intf_klass, scan_temp);
3646   assert(recv_klass != method_result || !return_method,
3647          "recv_klass can be destroyed when method isn't needed");
3648 
3649   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
3650          "caller must use same register for non-constant itable index as for method");
3651 
3652   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
3653   int vtable_base = in_bytes(Klass::vtable_start_offset());
3654   int itentry_off = itableMethodEntry::method_offset_in_bytes();
3655   int scan_step   = itableOffsetEntry::size() * wordSize;
3656   int vte_size    = vtableEntry::size_in_bytes();
3657   Address::ScaleFactor times_vte_scale = Address::times_ptr;
3658   assert(vte_size == wordSize, "else adjust times_vte_scale");
3659 
3660   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
3661 
3662   // %%% Could store the aligned, prescaled offset in the klassoop.
3663   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
3664 
3665   if (return_method) {
3666     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
3667     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
3668     lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
3669   }
3670 
3671   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
3672   //   if (scan->interface() == intf) {
3673   //     result = (klass + scan->offset() + itable_index);
3674   //   }
3675   // }
3676   Label search, found_method;
3677 
3678   for (int peel = 1; peel >= 0; peel--) {
3679     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
3680     cmpptr(intf_klass, method_result);
3681 
3682     if (peel) {
3683       jccb(Assembler::equal, found_method);
3684     } else {
3685       jccb(Assembler::notEqual, search);
3686       // (invert the test to fall through to found_method...)
3687     }
3688 
3689     if (!peel)  break;
3690 
3691     bind(search);
3692 
3693     // Check that the previous entry is non-null.  A null entry means that
3694     // the receiver class doesn't implement the interface, and wasn't the
3695     // same as when the caller was compiled.
3696     testptr(method_result, method_result);
3697     jcc(Assembler::zero, L_no_such_interface);
3698     addptr(scan_temp, scan_step);
3699   }
3700 
3701   bind(found_method);
3702 
3703   if (return_method) {
3704     // Got a hit.
3705     movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
3706     movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
3707   }
3708 }
3709 
3710 
3711 // virtual method calling
3712 void MacroAssembler::lookup_virtual_method(Register recv_klass,
3713                                            RegisterOrConstant vtable_index,
3714                                            Register method_result) {
3715   const int base = in_bytes(Klass::vtable_start_offset());
3716   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
3717   Address vtable_entry_addr(recv_klass,
3718                             vtable_index, Address::times_ptr,
3719                             base + vtableEntry::method_offset_in_bytes());
3720   movptr(method_result, vtable_entry_addr);
3721 }
3722 
3723 
3724 void MacroAssembler::check_klass_subtype(Register sub_klass,
3725                            Register super_klass,
3726                            Register temp_reg,
3727                            Label& L_success) {
3728   Label L_failure;
3729   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
3730   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
3731   bind(L_failure);
3732 }
3733 
3734 
3735 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
3736                                                    Register super_klass,
3737                                                    Register temp_reg,
3738                                                    Label* L_success,
3739                                                    Label* L_failure,
3740                                                    Label* L_slow_path,
3741                                         RegisterOrConstant super_check_offset) {
3742   assert_different_registers(sub_klass, super_klass, temp_reg);
3743   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
3744   if (super_check_offset.is_register()) {
3745     assert_different_registers(sub_klass, super_klass,
3746                                super_check_offset.as_register());
3747   } else if (must_load_sco) {
3748     assert(temp_reg != noreg, "supply either a temp or a register offset");
3749   }
3750 
3751   Label L_fallthrough;
3752   int label_nulls = 0;
3753   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
3754   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
3755   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
3756   assert(label_nulls <= 1, "at most one NULL in the batch");
3757 
3758   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
3759   int sco_offset = in_bytes(Klass::super_check_offset_offset());
3760   Address super_check_offset_addr(super_klass, sco_offset);
3761 
3762   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
3763   // range of a jccb.  If this routine grows larger, reconsider at
3764   // least some of these.
3765 #define local_jcc(assembler_cond, label)                                \
3766   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
3767   else                             jcc( assembler_cond, label) /*omit semi*/
3768 
3769   // Hacked jmp, which may only be used just before L_fallthrough.
3770 #define final_jmp(label)                                                \
3771   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
3772   else                            jmp(label)                /*omit semi*/
3773 
3774   // If the pointers are equal, we are done (e.g., String[] elements).
3775   // This self-check enables sharing of secondary supertype arrays among
3776   // non-primary types such as array-of-interface.  Otherwise, each such
3777   // type would need its own customized SSA.
3778   // We move this check to the front of the fast path because many
3779   // type checks are in fact trivially successful in this manner,
3780   // so we get a nicely predicted branch right at the start of the check.
3781   cmpptr(sub_klass, super_klass);
3782   local_jcc(Assembler::equal, *L_success);
3783 
3784   // Check the supertype display:
3785   if (must_load_sco) {
3786     // Positive movl does right thing on LP64.
3787     movl(temp_reg, super_check_offset_addr);
3788     super_check_offset = RegisterOrConstant(temp_reg);
3789   }
3790   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
3791   cmpptr(super_klass, super_check_addr); // load displayed supertype
3792 
3793   // This check has worked decisively for primary supers.
3794   // Secondary supers are sought in the super_cache ('super_cache_addr').
3795   // (Secondary supers are interfaces and very deeply nested subtypes.)
3796   // This works in the same check above because of a tricky aliasing
3797   // between the super_cache and the primary super display elements.
3798   // (The 'super_check_addr' can address either, as the case requires.)
3799   // Note that the cache is updated below if it does not help us find
3800   // what we need immediately.
3801   // So if it was a primary super, we can just fail immediately.
3802   // Otherwise, it's the slow path for us (no success at this point).
3803 
3804   if (super_check_offset.is_register()) {
3805     local_jcc(Assembler::equal, *L_success);
3806     cmpl(super_check_offset.as_register(), sc_offset);
3807     if (L_failure == &L_fallthrough) {
3808       local_jcc(Assembler::equal, *L_slow_path);
3809     } else {
3810       local_jcc(Assembler::notEqual, *L_failure);
3811       final_jmp(*L_slow_path);
3812     }
3813   } else if (super_check_offset.as_constant() == sc_offset) {
3814     // Need a slow path; fast failure is impossible.
3815     if (L_slow_path == &L_fallthrough) {
3816       local_jcc(Assembler::equal, *L_success);
3817     } else {
3818       local_jcc(Assembler::notEqual, *L_slow_path);
3819       final_jmp(*L_success);
3820     }
3821   } else {
3822     // No slow path; it's a fast decision.
3823     if (L_failure == &L_fallthrough) {
3824       local_jcc(Assembler::equal, *L_success);
3825     } else {
3826       local_jcc(Assembler::notEqual, *L_failure);
3827       final_jmp(*L_success);
3828     }
3829   }
3830 
3831   bind(L_fallthrough);
3832 
3833 #undef local_jcc
3834 #undef final_jmp
3835 }
3836 
3837 
3838 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
3839                                                    Register super_klass,
3840                                                    Register temp_reg,
3841                                                    Register temp2_reg,
3842                                                    Label* L_success,
3843                                                    Label* L_failure,
3844                                                    bool set_cond_codes) {
3845   assert_different_registers(sub_klass, super_klass, temp_reg);
3846   if (temp2_reg != noreg)
3847     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
3848 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
3849 
3850   Label L_fallthrough;
3851   int label_nulls = 0;
3852   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
3853   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
3854   assert(label_nulls <= 1, "at most one NULL in the batch");
3855 
3856   // a couple of useful fields in sub_klass:
3857   int ss_offset = in_bytes(Klass::secondary_supers_offset());
3858   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
3859   Address secondary_supers_addr(sub_klass, ss_offset);
3860   Address super_cache_addr(     sub_klass, sc_offset);
3861 
3862   // Do a linear scan of the secondary super-klass chain.
3863   // This code is rarely used, so simplicity is a virtue here.
3864   // The repne_scan instruction uses fixed registers, which we must spill.
3865   // Don't worry too much about pre-existing connections with the input regs.
3866 
3867   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
3868   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
3869 
3870   // Get super_klass value into rax (even if it was in rdi or rcx).
3871   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
3872   if (super_klass != rax || UseCompressedOops) {
3873     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
3874     mov(rax, super_klass);
3875   }
3876   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
3877   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
3878 
3879 #ifndef PRODUCT
3880   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
3881   ExternalAddress pst_counter_addr((address) pst_counter);
3882   NOT_LP64(  incrementl(pst_counter_addr) );
3883   LP64_ONLY( lea(rcx, pst_counter_addr) );
3884   LP64_ONLY( incrementl(Address(rcx, 0)) );
3885 #endif //PRODUCT
3886 
3887   // We will consult the secondary-super array.
3888   movptr(rdi, secondary_supers_addr);
3889   // Load the array length.  (Positive movl does right thing on LP64.)
3890   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
3891   // Skip to start of data.
3892   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
3893 
3894   // Scan RCX words at [RDI] for an occurrence of RAX.
3895   // Set NZ/Z based on last compare.
3896   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
3897   // not change flags (only scas instruction which is repeated sets flags).
3898   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
3899 
3900     testptr(rax,rax); // Set Z = 0
3901     repne_scan();
3902 
3903   // Unspill the temp. registers:
3904   if (pushed_rdi)  pop(rdi);
3905   if (pushed_rcx)  pop(rcx);
3906   if (pushed_rax)  pop(rax);
3907 
3908   if (set_cond_codes) {
3909     // Special hack for the AD files:  rdi is guaranteed non-zero.
3910     assert(!pushed_rdi, "rdi must be left non-NULL");
3911     // Also, the condition codes are properly set Z/NZ on succeed/failure.
3912   }
3913 
3914   if (L_failure == &L_fallthrough)
3915         jccb(Assembler::notEqual, *L_failure);
3916   else  jcc(Assembler::notEqual, *L_failure);
3917 
3918   // Success.  Cache the super we found and proceed in triumph.
3919   movptr(super_cache_addr, super_klass);
3920 
3921   if (L_success != &L_fallthrough) {
3922     jmp(*L_success);
3923   }
3924 
3925 #undef IS_A_TEMP
3926 
3927   bind(L_fallthrough);
3928 }
3929 
3930 void MacroAssembler::clinit_barrier(Register klass, Register thread, Label* L_fast_path, Label* L_slow_path) {
3931   assert(L_fast_path != NULL || L_slow_path != NULL, "at least one is required");
3932 
3933   Label L_fallthrough;
3934   if (L_fast_path == NULL) {
3935     L_fast_path = &L_fallthrough;
3936   } else if (L_slow_path == NULL) {
3937     L_slow_path = &L_fallthrough;
3938   }
3939 
3940   // Fast path check: class is fully initialized
3941   cmpb(Address(klass, InstanceKlass::init_state_offset()), InstanceKlass::fully_initialized);
3942   jcc(Assembler::equal, *L_fast_path);
3943 
3944   // Fast path check: current thread is initializer thread
3945   cmpptr(thread, Address(klass, InstanceKlass::init_thread_offset()));
3946   if (L_slow_path == &L_fallthrough) {
3947     jcc(Assembler::equal, *L_fast_path);
3948     bind(*L_slow_path);
3949   } else if (L_fast_path == &L_fallthrough) {
3950     jcc(Assembler::notEqual, *L_slow_path);
3951     bind(*L_fast_path);
3952   } else {
3953     Unimplemented();
3954   }
3955 }
3956 
3957 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
3958   if (VM_Version::supports_cmov()) {
3959     cmovl(cc, dst, src);
3960   } else {
3961     Label L;
3962     jccb(negate_condition(cc), L);
3963     movl(dst, src);
3964     bind(L);
3965   }
3966 }
3967 
3968 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
3969   if (VM_Version::supports_cmov()) {
3970     cmovl(cc, dst, src);
3971   } else {
3972     Label L;
3973     jccb(negate_condition(cc), L);
3974     movl(dst, src);
3975     bind(L);
3976   }
3977 }
3978 
3979 void MacroAssembler::_verify_oop(Register reg, const char* s, const char* file, int line) {
3980   if (!VerifyOops) return;
3981 
3982   // Pass register number to verify_oop_subroutine
3983   const char* b = NULL;
3984   {
3985     ResourceMark rm;
3986     stringStream ss;
3987     ss.print("verify_oop: %s: %s (%s:%d)", reg->name(), s, file, line);
3988     b = code_string(ss.as_string());
3989   }
3990   BLOCK_COMMENT("verify_oop {");
3991 #ifdef _LP64
3992   push(rscratch1);                    // save r10, trashed by movptr()
3993 #endif
3994   push(rax);                          // save rax,
3995   push(reg);                          // pass register argument
3996   ExternalAddress buffer((address) b);
3997   // avoid using pushptr, as it modifies scratch registers
3998   // and our contract is not to modify anything
3999   movptr(rax, buffer.addr());
4000   push(rax);
4001   // call indirectly to solve generation ordering problem
4002   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
4003   call(rax);
4004   // Caller pops the arguments (oop, message) and restores rax, r10
4005   BLOCK_COMMENT("} verify_oop");
4006 }
4007 
4008 void MacroAssembler::vallones(XMMRegister dst, int vector_len) {
4009   if (UseAVX > 2 && (vector_len == Assembler::AVX_512bit || VM_Version::supports_avx512vl())) {
4010     vpternlogd(dst, 0xFF, dst, dst, vector_len);
4011   } else {
4012     assert(UseAVX > 0, "");
4013     vpcmpeqb(dst, dst, dst, vector_len);
4014   }
4015 }
4016 
4017 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
4018                                          int extra_slot_offset) {
4019   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
4020   int stackElementSize = Interpreter::stackElementSize;
4021   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
4022 #ifdef ASSERT
4023   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
4024   assert(offset1 - offset == stackElementSize, "correct arithmetic");
4025 #endif
4026   Register             scale_reg    = noreg;
4027   Address::ScaleFactor scale_factor = Address::no_scale;
4028   if (arg_slot.is_constant()) {
4029     offset += arg_slot.as_constant() * stackElementSize;
4030   } else {
4031     scale_reg    = arg_slot.as_register();
4032     scale_factor = Address::times(stackElementSize);
4033   }
4034   offset += wordSize;           // return PC is on stack
4035   return Address(rsp, scale_reg, scale_factor, offset);
4036 }
4037 
4038 void MacroAssembler::_verify_oop_addr(Address addr, const char* s, const char* file, int line) {
4039   if (!VerifyOops) return;
4040 
4041   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
4042   // Pass register number to verify_oop_subroutine
4043   const char* b = NULL;
4044   {
4045     ResourceMark rm;
4046     stringStream ss;
4047     ss.print("verify_oop_addr: %s (%s:%d)", s, file, line);
4048     b = code_string(ss.as_string());
4049   }
4050 #ifdef _LP64
4051   push(rscratch1);                    // save r10, trashed by movptr()
4052 #endif
4053   push(rax);                          // save rax,
4054   // addr may contain rsp so we will have to adjust it based on the push
4055   // we just did (and on 64 bit we do two pushes)
4056   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
4057   // stores rax into addr which is backwards of what was intended.
4058   if (addr.uses(rsp)) {
4059     lea(rax, addr);
4060     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
4061   } else {
4062     pushptr(addr);
4063   }
4064 
4065   ExternalAddress buffer((address) b);
4066   // pass msg argument
4067   // avoid using pushptr, as it modifies scratch registers
4068   // and our contract is not to modify anything
4069   movptr(rax, buffer.addr());
4070   push(rax);
4071 
4072   // call indirectly to solve generation ordering problem
4073   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
4074   call(rax);
4075   // Caller pops the arguments (addr, message) and restores rax, r10.
4076 }
4077 
4078 void MacroAssembler::verify_tlab() {
4079 #ifdef ASSERT
4080   if (UseTLAB && VerifyOops) {
4081     Label next, ok;
4082     Register t1 = rsi;
4083     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
4084 
4085     push(t1);
4086     NOT_LP64(push(thread_reg));
4087     NOT_LP64(get_thread(thread_reg));
4088 
4089     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
4090     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
4091     jcc(Assembler::aboveEqual, next);
4092     STOP("assert(top >= start)");
4093     should_not_reach_here();
4094 
4095     bind(next);
4096     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
4097     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
4098     jcc(Assembler::aboveEqual, ok);
4099     STOP("assert(top <= end)");
4100     should_not_reach_here();
4101 
4102     bind(ok);
4103     NOT_LP64(pop(thread_reg));
4104     pop(t1);
4105   }
4106 #endif
4107 }
4108 
4109 class ControlWord {
4110  public:
4111   int32_t _value;
4112 
4113   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
4114   int  precision_control() const       { return  (_value >>  8) & 3      ; }
4115   bool precision() const               { return ((_value >>  5) & 1) != 0; }
4116   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
4117   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
4118   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
4119   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
4120   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
4121 
4122   void print() const {
4123     // rounding control
4124     const char* rc;
4125     switch (rounding_control()) {
4126       case 0: rc = "round near"; break;
4127       case 1: rc = "round down"; break;
4128       case 2: rc = "round up  "; break;
4129       case 3: rc = "chop      "; break;
4130       default:
4131         rc = NULL; // silence compiler warnings
4132         fatal("Unknown rounding control: %d", rounding_control());
4133     };
4134     // precision control
4135     const char* pc;
4136     switch (precision_control()) {
4137       case 0: pc = "24 bits "; break;
4138       case 1: pc = "reserved"; break;
4139       case 2: pc = "53 bits "; break;
4140       case 3: pc = "64 bits "; break;
4141       default:
4142         pc = NULL; // silence compiler warnings
4143         fatal("Unknown precision control: %d", precision_control());
4144     };
4145     // flags
4146     char f[9];
4147     f[0] = ' ';
4148     f[1] = ' ';
4149     f[2] = (precision   ()) ? 'P' : 'p';
4150     f[3] = (underflow   ()) ? 'U' : 'u';
4151     f[4] = (overflow    ()) ? 'O' : 'o';
4152     f[5] = (zero_divide ()) ? 'Z' : 'z';
4153     f[6] = (denormalized()) ? 'D' : 'd';
4154     f[7] = (invalid     ()) ? 'I' : 'i';
4155     f[8] = '\x0';
4156     // output
4157     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
4158   }
4159 
4160 };
4161 
4162 class StatusWord {
4163  public:
4164   int32_t _value;
4165 
4166   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
4167   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
4168   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
4169   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
4170   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
4171   int  top() const                     { return  (_value >> 11) & 7      ; }
4172   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
4173   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
4174   bool precision() const               { return ((_value >>  5) & 1) != 0; }
4175   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
4176   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
4177   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
4178   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
4179   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
4180 
4181   void print() const {
4182     // condition codes
4183     char c[5];
4184     c[0] = (C3()) ? '3' : '-';
4185     c[1] = (C2()) ? '2' : '-';
4186     c[2] = (C1()) ? '1' : '-';
4187     c[3] = (C0()) ? '0' : '-';
4188     c[4] = '\x0';
4189     // flags
4190     char f[9];
4191     f[0] = (error_status()) ? 'E' : '-';
4192     f[1] = (stack_fault ()) ? 'S' : '-';
4193     f[2] = (precision   ()) ? 'P' : '-';
4194     f[3] = (underflow   ()) ? 'U' : '-';
4195     f[4] = (overflow    ()) ? 'O' : '-';
4196     f[5] = (zero_divide ()) ? 'Z' : '-';
4197     f[6] = (denormalized()) ? 'D' : '-';
4198     f[7] = (invalid     ()) ? 'I' : '-';
4199     f[8] = '\x0';
4200     // output
4201     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
4202   }
4203 
4204 };
4205 
4206 class TagWord {
4207  public:
4208   int32_t _value;
4209 
4210   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
4211 
4212   void print() const {
4213     printf("%04x", _value & 0xFFFF);
4214   }
4215 
4216 };
4217 
4218 class FPU_Register {
4219  public:
4220   int32_t _m0;
4221   int32_t _m1;
4222   int16_t _ex;
4223 
4224   bool is_indefinite() const           {
4225     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
4226   }
4227 
4228   void print() const {
4229     char  sign = (_ex < 0) ? '-' : '+';
4230     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
4231     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
4232   };
4233 
4234 };
4235 
4236 class FPU_State {
4237  public:
4238   enum {
4239     register_size       = 10,
4240     number_of_registers =  8,
4241     register_mask       =  7
4242   };
4243 
4244   ControlWord  _control_word;
4245   StatusWord   _status_word;
4246   TagWord      _tag_word;
4247   int32_t      _error_offset;
4248   int32_t      _error_selector;
4249   int32_t      _data_offset;
4250   int32_t      _data_selector;
4251   int8_t       _register[register_size * number_of_registers];
4252 
4253   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
4254   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
4255 
4256   const char* tag_as_string(int tag) const {
4257     switch (tag) {
4258       case 0: return "valid";
4259       case 1: return "zero";
4260       case 2: return "special";
4261       case 3: return "empty";
4262     }
4263     ShouldNotReachHere();
4264     return NULL;
4265   }
4266 
4267   void print() const {
4268     // print computation registers
4269     { int t = _status_word.top();
4270       for (int i = 0; i < number_of_registers; i++) {
4271         int j = (i - t) & register_mask;
4272         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
4273         st(j)->print();
4274         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
4275       }
4276     }
4277     printf("\n");
4278     // print control registers
4279     printf("ctrl = "); _control_word.print(); printf("\n");
4280     printf("stat = "); _status_word .print(); printf("\n");
4281     printf("tags = "); _tag_word    .print(); printf("\n");
4282   }
4283 
4284 };
4285 
4286 class Flag_Register {
4287  public:
4288   int32_t _value;
4289 
4290   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
4291   bool direction() const               { return ((_value >> 10) & 1) != 0; }
4292   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
4293   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
4294   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
4295   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
4296   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
4297 
4298   void print() const {
4299     // flags
4300     char f[8];
4301     f[0] = (overflow       ()) ? 'O' : '-';
4302     f[1] = (direction      ()) ? 'D' : '-';
4303     f[2] = (sign           ()) ? 'S' : '-';
4304     f[3] = (zero           ()) ? 'Z' : '-';
4305     f[4] = (auxiliary_carry()) ? 'A' : '-';
4306     f[5] = (parity         ()) ? 'P' : '-';
4307     f[6] = (carry          ()) ? 'C' : '-';
4308     f[7] = '\x0';
4309     // output
4310     printf("%08x  flags = %s", _value, f);
4311   }
4312 
4313 };
4314 
4315 class IU_Register {
4316  public:
4317   int32_t _value;
4318 
4319   void print() const {
4320     printf("%08x  %11d", _value, _value);
4321   }
4322 
4323 };
4324 
4325 class IU_State {
4326  public:
4327   Flag_Register _eflags;
4328   IU_Register   _rdi;
4329   IU_Register   _rsi;
4330   IU_Register   _rbp;
4331   IU_Register   _rsp;
4332   IU_Register   _rbx;
4333   IU_Register   _rdx;
4334   IU_Register   _rcx;
4335   IU_Register   _rax;
4336 
4337   void print() const {
4338     // computation registers
4339     printf("rax,  = "); _rax.print(); printf("\n");
4340     printf("rbx,  = "); _rbx.print(); printf("\n");
4341     printf("rcx  = "); _rcx.print(); printf("\n");
4342     printf("rdx  = "); _rdx.print(); printf("\n");
4343     printf("rdi  = "); _rdi.print(); printf("\n");
4344     printf("rsi  = "); _rsi.print(); printf("\n");
4345     printf("rbp,  = "); _rbp.print(); printf("\n");
4346     printf("rsp  = "); _rsp.print(); printf("\n");
4347     printf("\n");
4348     // control registers
4349     printf("flgs = "); _eflags.print(); printf("\n");
4350   }
4351 };
4352 
4353 
4354 class CPU_State {
4355  public:
4356   FPU_State _fpu_state;
4357   IU_State  _iu_state;
4358 
4359   void print() const {
4360     printf("--------------------------------------------------\n");
4361     _iu_state .print();
4362     printf("\n");
4363     _fpu_state.print();
4364     printf("--------------------------------------------------\n");
4365   }
4366 
4367 };
4368 
4369 
4370 static void _print_CPU_state(CPU_State* state) {
4371   state->print();
4372 };
4373 
4374 
4375 void MacroAssembler::print_CPU_state() {
4376   push_CPU_state();
4377   push(rsp);                // pass CPU state
4378   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
4379   addptr(rsp, wordSize);       // discard argument
4380   pop_CPU_state();
4381 }
4382 
4383 
4384 #ifndef _LP64
4385 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
4386   static int counter = 0;
4387   FPU_State* fs = &state->_fpu_state;
4388   counter++;
4389   // For leaf calls, only verify that the top few elements remain empty.
4390   // We only need 1 empty at the top for C2 code.
4391   if( stack_depth < 0 ) {
4392     if( fs->tag_for_st(7) != 3 ) {
4393       printf("FPR7 not empty\n");
4394       state->print();
4395       assert(false, "error");
4396       return false;
4397     }
4398     return true;                // All other stack states do not matter
4399   }
4400 
4401   assert((fs->_control_word._value & 0xffff) == StubRoutines::x86::fpu_cntrl_wrd_std(),
4402          "bad FPU control word");
4403 
4404   // compute stack depth
4405   int i = 0;
4406   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
4407   int d = i;
4408   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
4409   // verify findings
4410   if (i != FPU_State::number_of_registers) {
4411     // stack not contiguous
4412     printf("%s: stack not contiguous at ST%d\n", s, i);
4413     state->print();
4414     assert(false, "error");
4415     return false;
4416   }
4417   // check if computed stack depth corresponds to expected stack depth
4418   if (stack_depth < 0) {
4419     // expected stack depth is -stack_depth or less
4420     if (d > -stack_depth) {
4421       // too many elements on the stack
4422       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
4423       state->print();
4424       assert(false, "error");
4425       return false;
4426     }
4427   } else {
4428     // expected stack depth is stack_depth
4429     if (d != stack_depth) {
4430       // wrong stack depth
4431       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
4432       state->print();
4433       assert(false, "error");
4434       return false;
4435     }
4436   }
4437   // everything is cool
4438   return true;
4439 }
4440 
4441 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
4442   if (!VerifyFPU) return;
4443   push_CPU_state();
4444   push(rsp);                // pass CPU state
4445   ExternalAddress msg((address) s);
4446   // pass message string s
4447   pushptr(msg.addr());
4448   push(stack_depth);        // pass stack depth
4449   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
4450   addptr(rsp, 3 * wordSize);   // discard arguments
4451   // check for error
4452   { Label L;
4453     testl(rax, rax);
4454     jcc(Assembler::notZero, L);
4455     int3();                  // break if error condition
4456     bind(L);
4457   }
4458   pop_CPU_state();
4459 }
4460 #endif // _LP64
4461 
4462 void MacroAssembler::restore_cpu_control_state_after_jni() {
4463   // Either restore the MXCSR register after returning from the JNI Call
4464   // or verify that it wasn't changed (with -Xcheck:jni flag).
4465   if (VM_Version::supports_sse()) {
4466     if (RestoreMXCSROnJNICalls) {
4467       ldmxcsr(ExternalAddress(StubRoutines::x86::addr_mxcsr_std()));
4468     } else if (CheckJNICalls) {
4469       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
4470     }
4471   }
4472   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
4473   vzeroupper();
4474   // Reset k1 to 0xffff.
4475 
4476 #ifdef COMPILER2
4477   if (PostLoopMultiversioning && VM_Version::supports_evex()) {
4478     push(rcx);
4479     movl(rcx, 0xffff);
4480     kmovwl(k1, rcx);
4481     pop(rcx);
4482   }
4483 #endif // COMPILER2
4484 
4485 #ifndef _LP64
4486   // Either restore the x87 floating pointer control word after returning
4487   // from the JNI call or verify that it wasn't changed.
4488   if (CheckJNICalls) {
4489     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
4490   }
4491 #endif // _LP64
4492 }
4493 
4494 // ((OopHandle)result).resolve();
4495 void MacroAssembler::resolve_oop_handle(Register result, Register tmp) {
4496   assert_different_registers(result, tmp);
4497 
4498   // Only 64 bit platforms support GCs that require a tmp register
4499   // Only IN_HEAP loads require a thread_tmp register
4500   // OopHandle::resolve is an indirection like jobject.
4501   access_load_at(T_OBJECT, IN_NATIVE,
4502                  result, Address(result, 0), tmp, /*tmp_thread*/noreg);
4503 }
4504 
4505 // ((WeakHandle)result).resolve();
4506 void MacroAssembler::resolve_weak_handle(Register rresult, Register rtmp) {
4507   assert_different_registers(rresult, rtmp);
4508   Label resolved;
4509 
4510   // A null weak handle resolves to null.
4511   cmpptr(rresult, 0);
4512   jcc(Assembler::equal, resolved);
4513 
4514   // Only 64 bit platforms support GCs that require a tmp register
4515   // Only IN_HEAP loads require a thread_tmp register
4516   // WeakHandle::resolve is an indirection like jweak.
4517   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
4518                  rresult, Address(rresult, 0), rtmp, /*tmp_thread*/noreg);
4519   bind(resolved);
4520 }
4521 
4522 void MacroAssembler::load_mirror(Register mirror, Register method, Register tmp) {
4523   // get mirror
4524   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
4525   load_method_holder(mirror, method);
4526   movptr(mirror, Address(mirror, mirror_offset));
4527   resolve_oop_handle(mirror, tmp);
4528 }
4529 
4530 void MacroAssembler::load_method_holder_cld(Register rresult, Register rmethod) {
4531   load_method_holder(rresult, rmethod);
4532   movptr(rresult, Address(rresult, InstanceKlass::class_loader_data_offset()));
4533 }
4534 
4535 void MacroAssembler::load_method_holder(Register holder, Register method) {
4536   movptr(holder, Address(method, Method::const_offset()));                      // ConstMethod*
4537   movptr(holder, Address(holder, ConstMethod::constants_offset()));             // ConstantPool*
4538   movptr(holder, Address(holder, ConstantPool::pool_holder_offset_in_bytes())); // InstanceKlass*
4539 }
4540 
4541 void MacroAssembler::load_klass(Register dst, Register src, Register tmp) {
4542   assert_different_registers(src, tmp);
4543   assert_different_registers(dst, tmp);
4544 #ifdef _LP64
4545   if (UseCompressedClassPointers) {
4546     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
4547     decode_klass_not_null(dst, tmp);
4548   } else
4549 #endif
4550     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
4551 }
4552 
4553 void MacroAssembler::store_klass(Register dst, Register src, Register tmp) {
4554   assert_different_registers(src, tmp);
4555   assert_different_registers(dst, tmp);
4556 #ifdef _LP64
4557   if (UseCompressedClassPointers) {
4558     encode_klass_not_null(src, tmp);
4559     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
4560   } else
4561 #endif
4562     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
4563 }
4564 
4565 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators, Register dst, Address src,
4566                                     Register tmp1, Register thread_tmp) {
4567   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
4568   decorators = AccessInternal::decorator_fixup(decorators);
4569   bool as_raw = (decorators & AS_RAW) != 0;
4570   if (as_raw) {
4571     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
4572   } else {
4573     bs->load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
4574   }
4575 }
4576 
4577 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators, Address dst, Register src,
4578                                      Register tmp1, Register tmp2) {
4579   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
4580   decorators = AccessInternal::decorator_fixup(decorators);
4581   bool as_raw = (decorators & AS_RAW) != 0;
4582   if (as_raw) {
4583     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, src, tmp1, tmp2);
4584   } else {
4585     bs->store_at(this, decorators, type, dst, src, tmp1, tmp2);
4586   }
4587 }
4588 
4589 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
4590                                    Register thread_tmp, DecoratorSet decorators) {
4591   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, thread_tmp);
4592 }
4593 
4594 // Doesn't do verfication, generates fixed size code
4595 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
4596                                             Register thread_tmp, DecoratorSet decorators) {
4597   access_load_at(T_OBJECT, IN_HEAP | IS_NOT_NULL | decorators, dst, src, tmp1, thread_tmp);
4598 }
4599 
4600 void MacroAssembler::store_heap_oop(Address dst, Register src, Register tmp1,
4601                                     Register tmp2, DecoratorSet decorators) {
4602   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2);
4603 }
4604 
4605 // Used for storing NULLs.
4606 void MacroAssembler::store_heap_oop_null(Address dst) {
4607   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg);
4608 }
4609 
4610 #ifdef _LP64
4611 void MacroAssembler::store_klass_gap(Register dst, Register src) {
4612   if (UseCompressedClassPointers) {
4613     // Store to klass gap in destination
4614     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
4615   }
4616 }
4617 
4618 #ifdef ASSERT
4619 void MacroAssembler::verify_heapbase(const char* msg) {
4620   assert (UseCompressedOops, "should be compressed");
4621   assert (Universe::heap() != NULL, "java heap should be initialized");
4622   if (CheckCompressedOops) {
4623     Label ok;
4624     push(rscratch1); // cmpptr trashes rscratch1
4625     cmpptr(r12_heapbase, ExternalAddress((address)CompressedOops::ptrs_base_addr()));
4626     jcc(Assembler::equal, ok);
4627     STOP(msg);
4628     bind(ok);
4629     pop(rscratch1);
4630   }
4631 }
4632 #endif
4633 
4634 // Algorithm must match oop.inline.hpp encode_heap_oop.
4635 void MacroAssembler::encode_heap_oop(Register r) {
4636 #ifdef ASSERT
4637   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
4638 #endif
4639   verify_oop_msg(r, "broken oop in encode_heap_oop");
4640   if (CompressedOops::base() == NULL) {
4641     if (CompressedOops::shift() != 0) {
4642       assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4643       shrq(r, LogMinObjAlignmentInBytes);
4644     }
4645     return;
4646   }
4647   testq(r, r);
4648   cmovq(Assembler::equal, r, r12_heapbase);
4649   subq(r, r12_heapbase);
4650   shrq(r, LogMinObjAlignmentInBytes);
4651 }
4652 
4653 void MacroAssembler::encode_heap_oop_not_null(Register r) {
4654 #ifdef ASSERT
4655   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
4656   if (CheckCompressedOops) {
4657     Label ok;
4658     testq(r, r);
4659     jcc(Assembler::notEqual, ok);
4660     STOP("null oop passed to encode_heap_oop_not_null");
4661     bind(ok);
4662   }
4663 #endif
4664   verify_oop_msg(r, "broken oop in encode_heap_oop_not_null");
4665   if (CompressedOops::base() != NULL) {
4666     subq(r, r12_heapbase);
4667   }
4668   if (CompressedOops::shift() != 0) {
4669     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4670     shrq(r, LogMinObjAlignmentInBytes);
4671   }
4672 }
4673 
4674 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
4675 #ifdef ASSERT
4676   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
4677   if (CheckCompressedOops) {
4678     Label ok;
4679     testq(src, src);
4680     jcc(Assembler::notEqual, ok);
4681     STOP("null oop passed to encode_heap_oop_not_null2");
4682     bind(ok);
4683   }
4684 #endif
4685   verify_oop_msg(src, "broken oop in encode_heap_oop_not_null2");
4686   if (dst != src) {
4687     movq(dst, src);
4688   }
4689   if (CompressedOops::base() != NULL) {
4690     subq(dst, r12_heapbase);
4691   }
4692   if (CompressedOops::shift() != 0) {
4693     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4694     shrq(dst, LogMinObjAlignmentInBytes);
4695   }
4696 }
4697 
4698 void  MacroAssembler::decode_heap_oop(Register r) {
4699 #ifdef ASSERT
4700   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
4701 #endif
4702   if (CompressedOops::base() == NULL) {
4703     if (CompressedOops::shift() != 0) {
4704       assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4705       shlq(r, LogMinObjAlignmentInBytes);
4706     }
4707   } else {
4708     Label done;
4709     shlq(r, LogMinObjAlignmentInBytes);
4710     jccb(Assembler::equal, done);
4711     addq(r, r12_heapbase);
4712     bind(done);
4713   }
4714   verify_oop_msg(r, "broken oop in decode_heap_oop");
4715 }
4716 
4717 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
4718   // Note: it will change flags
4719   assert (UseCompressedOops, "should only be used for compressed headers");
4720   assert (Universe::heap() != NULL, "java heap should be initialized");
4721   // Cannot assert, unverified entry point counts instructions (see .ad file)
4722   // vtableStubs also counts instructions in pd_code_size_limit.
4723   // Also do not verify_oop as this is called by verify_oop.
4724   if (CompressedOops::shift() != 0) {
4725     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4726     shlq(r, LogMinObjAlignmentInBytes);
4727     if (CompressedOops::base() != NULL) {
4728       addq(r, r12_heapbase);
4729     }
4730   } else {
4731     assert (CompressedOops::base() == NULL, "sanity");
4732   }
4733 }
4734 
4735 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
4736   // Note: it will change flags
4737   assert (UseCompressedOops, "should only be used for compressed headers");
4738   assert (Universe::heap() != NULL, "java heap should be initialized");
4739   // Cannot assert, unverified entry point counts instructions (see .ad file)
4740   // vtableStubs also counts instructions in pd_code_size_limit.
4741   // Also do not verify_oop as this is called by verify_oop.
4742   if (CompressedOops::shift() != 0) {
4743     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4744     if (LogMinObjAlignmentInBytes == Address::times_8) {
4745       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
4746     } else {
4747       if (dst != src) {
4748         movq(dst, src);
4749       }
4750       shlq(dst, LogMinObjAlignmentInBytes);
4751       if (CompressedOops::base() != NULL) {
4752         addq(dst, r12_heapbase);
4753       }
4754     }
4755   } else {
4756     assert (CompressedOops::base() == NULL, "sanity");
4757     if (dst != src) {
4758       movq(dst, src);
4759     }
4760   }
4761 }
4762 
4763 void MacroAssembler::encode_klass_not_null(Register r, Register tmp) {
4764   assert_different_registers(r, tmp);
4765   if (CompressedKlassPointers::base() != NULL) {
4766     mov64(tmp, (int64_t)CompressedKlassPointers::base());
4767     subq(r, tmp);
4768   }
4769   if (CompressedKlassPointers::shift() != 0) {
4770     assert (LogKlassAlignmentInBytes == CompressedKlassPointers::shift(), "decode alg wrong");
4771     shrq(r, LogKlassAlignmentInBytes);
4772   }
4773 }
4774 
4775 void MacroAssembler::encode_and_move_klass_not_null(Register dst, Register src) {
4776   assert_different_registers(src, dst);
4777   if (CompressedKlassPointers::base() != NULL) {
4778     mov64(dst, -(int64_t)CompressedKlassPointers::base());
4779     addq(dst, src);
4780   } else {
4781     movptr(dst, src);
4782   }
4783   if (CompressedKlassPointers::shift() != 0) {
4784     assert (LogKlassAlignmentInBytes == CompressedKlassPointers::shift(), "decode alg wrong");
4785     shrq(dst, LogKlassAlignmentInBytes);
4786   }
4787 }
4788 
4789 // !!! If the instructions that get generated here change then function
4790 // instr_size_for_decode_klass_not_null() needs to get updated.
4791 void  MacroAssembler::decode_klass_not_null(Register r, Register tmp) {
4792   assert_different_registers(r, tmp);
4793   // Note: it will change flags
4794   assert(UseCompressedClassPointers, "should only be used for compressed headers");
4795   // Cannot assert, unverified entry point counts instructions (see .ad file)
4796   // vtableStubs also counts instructions in pd_code_size_limit.
4797   // Also do not verify_oop as this is called by verify_oop.
4798   if (CompressedKlassPointers::shift() != 0) {
4799     assert(LogKlassAlignmentInBytes == CompressedKlassPointers::shift(), "decode alg wrong");
4800     shlq(r, LogKlassAlignmentInBytes);
4801   }
4802   if (CompressedKlassPointers::base() != NULL) {
4803     mov64(tmp, (int64_t)CompressedKlassPointers::base());
4804     addq(r, tmp);
4805   }
4806 }
4807 
4808 void  MacroAssembler::decode_and_move_klass_not_null(Register dst, Register src) {
4809   assert_different_registers(src, dst);
4810   // Note: it will change flags
4811   assert (UseCompressedClassPointers, "should only be used for compressed headers");
4812   // Cannot assert, unverified entry point counts instructions (see .ad file)
4813   // vtableStubs also counts instructions in pd_code_size_limit.
4814   // Also do not verify_oop as this is called by verify_oop.
4815 
4816   if (CompressedKlassPointers::base() == NULL &&
4817       CompressedKlassPointers::shift() == 0) {
4818     // The best case scenario is that there is no base or shift. Then it is already
4819     // a pointer that needs nothing but a register rename.
4820     movl(dst, src);
4821   } else {
4822     if (CompressedKlassPointers::base() != NULL) {
4823       mov64(dst, (int64_t)CompressedKlassPointers::base());
4824     } else {
4825       xorq(dst, dst);
4826     }
4827     if (CompressedKlassPointers::shift() != 0) {
4828       assert(LogKlassAlignmentInBytes == CompressedKlassPointers::shift(), "decode alg wrong");
4829       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
4830       leaq(dst, Address(dst, src, Address::times_8, 0));
4831     } else {
4832       addq(dst, src);
4833     }
4834   }
4835 }
4836 
4837 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
4838   assert (UseCompressedOops, "should only be used for compressed headers");
4839   assert (Universe::heap() != NULL, "java heap should be initialized");
4840   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
4841   int oop_index = oop_recorder()->find_index(obj);
4842   RelocationHolder rspec = oop_Relocation::spec(oop_index);
4843   mov_narrow_oop(dst, oop_index, rspec);
4844 }
4845 
4846 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
4847   assert (UseCompressedOops, "should only be used for compressed headers");
4848   assert (Universe::heap() != NULL, "java heap should be initialized");
4849   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
4850   int oop_index = oop_recorder()->find_index(obj);
4851   RelocationHolder rspec = oop_Relocation::spec(oop_index);
4852   mov_narrow_oop(dst, oop_index, rspec);
4853 }
4854 
4855 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
4856   assert (UseCompressedClassPointers, "should only be used for compressed headers");
4857   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
4858   int klass_index = oop_recorder()->find_index(k);
4859   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
4860   mov_narrow_oop(dst, CompressedKlassPointers::encode(k), rspec);
4861 }
4862 
4863 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
4864   assert (UseCompressedClassPointers, "should only be used for compressed headers");
4865   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
4866   int klass_index = oop_recorder()->find_index(k);
4867   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
4868   mov_narrow_oop(dst, CompressedKlassPointers::encode(k), rspec);
4869 }
4870 
4871 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
4872   assert (UseCompressedOops, "should only be used for compressed headers");
4873   assert (Universe::heap() != NULL, "java heap should be initialized");
4874   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
4875   int oop_index = oop_recorder()->find_index(obj);
4876   RelocationHolder rspec = oop_Relocation::spec(oop_index);
4877   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
4878 }
4879 
4880 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
4881   assert (UseCompressedOops, "should only be used for compressed headers");
4882   assert (Universe::heap() != NULL, "java heap should be initialized");
4883   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
4884   int oop_index = oop_recorder()->find_index(obj);
4885   RelocationHolder rspec = oop_Relocation::spec(oop_index);
4886   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
4887 }
4888 
4889 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
4890   assert (UseCompressedClassPointers, "should only be used for compressed headers");
4891   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
4892   int klass_index = oop_recorder()->find_index(k);
4893   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
4894   Assembler::cmp_narrow_oop(dst, CompressedKlassPointers::encode(k), rspec);
4895 }
4896 
4897 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
4898   assert (UseCompressedClassPointers, "should only be used for compressed headers");
4899   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
4900   int klass_index = oop_recorder()->find_index(k);
4901   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
4902   Assembler::cmp_narrow_oop(dst, CompressedKlassPointers::encode(k), rspec);
4903 }
4904 
4905 void MacroAssembler::reinit_heapbase() {
4906   if (UseCompressedOops) {
4907     if (Universe::heap() != NULL) {
4908       if (CompressedOops::base() == NULL) {
4909         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
4910       } else {
4911         mov64(r12_heapbase, (int64_t)CompressedOops::ptrs_base());
4912       }
4913     } else {
4914       movptr(r12_heapbase, ExternalAddress((address)CompressedOops::ptrs_base_addr()));
4915     }
4916   }
4917 }
4918 
4919 #endif // _LP64
4920 
4921 // C2 compiled method's prolog code.
4922 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b, bool is_stub) {
4923 
4924   // WARNING: Initial instruction MUST be 5 bytes or longer so that
4925   // NativeJump::patch_verified_entry will be able to patch out the entry
4926   // code safely. The push to verify stack depth is ok at 5 bytes,
4927   // the frame allocation can be either 3 or 6 bytes. So if we don't do
4928   // stack bang then we must use the 6 byte frame allocation even if
4929   // we have no frame. :-(
4930   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
4931 
4932   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
4933   // Remove word for return addr
4934   framesize -= wordSize;
4935   stack_bang_size -= wordSize;
4936 
4937   // Calls to C2R adapters often do not accept exceptional returns.
4938   // We require that their callers must bang for them.  But be careful, because
4939   // some VM calls (such as call site linkage) can use several kilobytes of
4940   // stack.  But the stack safety zone should account for that.
4941   // See bugs 4446381, 4468289, 4497237.
4942   if (stack_bang_size > 0) {
4943     generate_stack_overflow_check(stack_bang_size);
4944 
4945     // We always push rbp, so that on return to interpreter rbp, will be
4946     // restored correctly and we can correct the stack.
4947     push(rbp);
4948     // Save caller's stack pointer into RBP if the frame pointer is preserved.
4949     if (PreserveFramePointer) {
4950       mov(rbp, rsp);
4951     }
4952     // Remove word for ebp
4953     framesize -= wordSize;
4954 
4955     // Create frame
4956     if (framesize) {
4957       subptr(rsp, framesize);
4958     }
4959   } else {
4960     // Create frame (force generation of a 4 byte immediate value)
4961     subptr_imm32(rsp, framesize);
4962 
4963     // Save RBP register now.
4964     framesize -= wordSize;
4965     movptr(Address(rsp, framesize), rbp);
4966     // Save caller's stack pointer into RBP if the frame pointer is preserved.
4967     if (PreserveFramePointer) {
4968       movptr(rbp, rsp);
4969       if (framesize > 0) {
4970         addptr(rbp, framesize);
4971       }
4972     }
4973   }
4974 
4975   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
4976     framesize -= wordSize;
4977     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
4978   }
4979 
4980 #ifndef _LP64
4981   // If method sets FPU control word do it now
4982   if (fp_mode_24b) {
4983     fldcw(ExternalAddress(StubRoutines::x86::addr_fpu_cntrl_wrd_24()));
4984   }
4985   if (UseSSE >= 2 && VerifyFPU) {
4986     verify_FPU(0, "FPU stack must be clean on entry");
4987   }
4988 #endif
4989 
4990 #ifdef ASSERT
4991   if (VerifyStackAtCalls) {
4992     Label L;
4993     push(rax);
4994     mov(rax, rsp);
4995     andptr(rax, StackAlignmentInBytes-1);
4996     cmpptr(rax, StackAlignmentInBytes-wordSize);
4997     pop(rax);
4998     jcc(Assembler::equal, L);
4999     STOP("Stack is not properly aligned!");
5000     bind(L);
5001   }
5002 #endif
5003 
5004   if (!is_stub) {
5005     BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5006     bs->nmethod_entry_barrier(this);
5007   }
5008 }
5009 
5010 #if COMPILER2_OR_JVMCI
5011 
5012 // clear memory of size 'cnt' qwords, starting at 'base' using XMM/YMM/ZMM registers
5013 void MacroAssembler::xmm_clear_mem(Register base, Register cnt, Register rtmp, XMMRegister xtmp, KRegister mask) {
5014   // cnt - number of qwords (8-byte words).
5015   // base - start address, qword aligned.
5016   Label L_zero_64_bytes, L_loop, L_sloop, L_tail, L_end;
5017   bool use64byteVector = MaxVectorSize == 64 && AVX3Threshold == 0;
5018   if (use64byteVector) {
5019     vpxor(xtmp, xtmp, xtmp, AVX_512bit);
5020   } else if (MaxVectorSize >= 32) {
5021     vpxor(xtmp, xtmp, xtmp, AVX_256bit);
5022   } else {
5023     pxor(xtmp, xtmp);
5024   }
5025   jmp(L_zero_64_bytes);
5026 
5027   BIND(L_loop);
5028   if (MaxVectorSize >= 32) {
5029     fill64_avx(base, 0, xtmp, use64byteVector);
5030   } else {
5031     movdqu(Address(base,  0), xtmp);
5032     movdqu(Address(base, 16), xtmp);
5033     movdqu(Address(base, 32), xtmp);
5034     movdqu(Address(base, 48), xtmp);
5035   }
5036   addptr(base, 64);
5037 
5038   BIND(L_zero_64_bytes);
5039   subptr(cnt, 8);
5040   jccb(Assembler::greaterEqual, L_loop);
5041 
5042   // Copy trailing 64 bytes
5043   if (use64byteVector) {
5044     addptr(cnt, 8);
5045     jccb(Assembler::equal, L_end);
5046     fill64_masked_avx(3, base, 0, xtmp, mask, cnt, rtmp, true);
5047     jmp(L_end);
5048   } else {
5049     addptr(cnt, 4);
5050     jccb(Assembler::less, L_tail);
5051     if (MaxVectorSize >= 32) {
5052       vmovdqu(Address(base, 0), xtmp);
5053     } else {
5054       movdqu(Address(base,  0), xtmp);
5055       movdqu(Address(base, 16), xtmp);
5056     }
5057   }
5058   addptr(base, 32);
5059   subptr(cnt, 4);
5060 
5061   BIND(L_tail);
5062   addptr(cnt, 4);
5063   jccb(Assembler::lessEqual, L_end);
5064   if (UseAVX > 2 && MaxVectorSize >= 32 && VM_Version::supports_avx512vl()) {
5065     fill32_masked_avx(3, base, 0, xtmp, mask, cnt, rtmp);
5066   } else {
5067     decrement(cnt);
5068 
5069     BIND(L_sloop);
5070     movq(Address(base, 0), xtmp);
5071     addptr(base, 8);
5072     decrement(cnt);
5073     jccb(Assembler::greaterEqual, L_sloop);
5074   }
5075   BIND(L_end);
5076 }
5077 
5078 // Clearing constant sized memory using YMM/ZMM registers.
5079 void MacroAssembler::clear_mem(Register base, int cnt, Register rtmp, XMMRegister xtmp, KRegister mask) {
5080   assert(UseAVX > 2 && VM_Version::supports_avx512vlbw(), "");
5081   bool use64byteVector = MaxVectorSize > 32 && AVX3Threshold == 0;
5082 
5083   int vector64_count = (cnt & (~0x7)) >> 3;
5084   cnt = cnt & 0x7;
5085 
5086   // 64 byte initialization loop.
5087   vpxor(xtmp, xtmp, xtmp, use64byteVector ? AVX_512bit : AVX_256bit);
5088   for (int i = 0; i < vector64_count; i++) {
5089     fill64_avx(base, i * 64, xtmp, use64byteVector);
5090   }
5091 
5092   // Clear remaining 64 byte tail.
5093   int disp = vector64_count * 64;
5094   if (cnt) {
5095     switch (cnt) {
5096       case 1:
5097         movq(Address(base, disp), xtmp);
5098         break;
5099       case 2:
5100         evmovdqu(T_LONG, k0, Address(base, disp), xtmp, Assembler::AVX_128bit);
5101         break;
5102       case 3:
5103         movl(rtmp, 0x7);
5104         kmovwl(mask, rtmp);
5105         evmovdqu(T_LONG, mask, Address(base, disp), xtmp, Assembler::AVX_256bit);
5106         break;
5107       case 4:
5108         evmovdqu(T_LONG, k0, Address(base, disp), xtmp, Assembler::AVX_256bit);
5109         break;
5110       case 5:
5111         if (use64byteVector) {
5112           movl(rtmp, 0x1F);
5113           kmovwl(mask, rtmp);
5114           evmovdqu(T_LONG, mask, Address(base, disp), xtmp, Assembler::AVX_512bit);
5115         } else {
5116           evmovdqu(T_LONG, k0, Address(base, disp), xtmp, Assembler::AVX_256bit);
5117           movq(Address(base, disp + 32), xtmp);
5118         }
5119         break;
5120       case 6:
5121         if (use64byteVector) {
5122           movl(rtmp, 0x3F);
5123           kmovwl(mask, rtmp);
5124           evmovdqu(T_LONG, mask, Address(base, disp), xtmp, Assembler::AVX_512bit);
5125         } else {
5126           evmovdqu(T_LONG, k0, Address(base, disp), xtmp, Assembler::AVX_256bit);
5127           evmovdqu(T_LONG, k0, Address(base, disp + 32), xtmp, Assembler::AVX_128bit);
5128         }
5129         break;
5130       case 7:
5131         if (use64byteVector) {
5132           movl(rtmp, 0x7F);
5133           kmovwl(mask, rtmp);
5134           evmovdqu(T_LONG, mask, Address(base, disp), xtmp, Assembler::AVX_512bit);
5135         } else {
5136           evmovdqu(T_LONG, k0, Address(base, disp), xtmp, Assembler::AVX_256bit);
5137           movl(rtmp, 0x7);
5138           kmovwl(mask, rtmp);
5139           evmovdqu(T_LONG, mask, Address(base, disp + 32), xtmp, Assembler::AVX_256bit);
5140         }
5141         break;
5142       default:
5143         fatal("Unexpected length : %d\n",cnt);
5144         break;
5145     }
5146   }
5147 }
5148 
5149 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, XMMRegister xtmp,
5150                                bool is_large, KRegister mask) {
5151   // cnt      - number of qwords (8-byte words).
5152   // base     - start address, qword aligned.
5153   // is_large - if optimizers know cnt is larger than InitArrayShortSize
5154   assert(base==rdi, "base register must be edi for rep stos");
5155   assert(tmp==rax,   "tmp register must be eax for rep stos");
5156   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
5157   assert(InitArrayShortSize % BytesPerLong == 0,
5158     "InitArrayShortSize should be the multiple of BytesPerLong");
5159 
5160   Label DONE;
5161   if (!is_large || !UseXMMForObjInit) {
5162     xorptr(tmp, tmp);
5163   }
5164 
5165   if (!is_large) {
5166     Label LOOP, LONG;
5167     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
5168     jccb(Assembler::greater, LONG);
5169 
5170     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
5171 
5172     decrement(cnt);
5173     jccb(Assembler::negative, DONE); // Zero length
5174 
5175     // Use individual pointer-sized stores for small counts:
5176     BIND(LOOP);
5177     movptr(Address(base, cnt, Address::times_ptr), tmp);
5178     decrement(cnt);
5179     jccb(Assembler::greaterEqual, LOOP);
5180     jmpb(DONE);
5181 
5182     BIND(LONG);
5183   }
5184 
5185   // Use longer rep-prefixed ops for non-small counts:
5186   if (UseFastStosb) {
5187     shlptr(cnt, 3); // convert to number of bytes
5188     rep_stosb();
5189   } else if (UseXMMForObjInit) {
5190     xmm_clear_mem(base, cnt, tmp, xtmp, mask);
5191   } else {
5192     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
5193     rep_stos();
5194   }
5195 
5196   BIND(DONE);
5197 }
5198 
5199 #endif //COMPILER2_OR_JVMCI
5200 
5201 
5202 void MacroAssembler::generate_fill(BasicType t, bool aligned,
5203                                    Register to, Register value, Register count,
5204                                    Register rtmp, XMMRegister xtmp) {
5205   ShortBranchVerifier sbv(this);
5206   assert_different_registers(to, value, count, rtmp);
5207   Label L_exit;
5208   Label L_fill_2_bytes, L_fill_4_bytes;
5209 
5210   int shift = -1;
5211   switch (t) {
5212     case T_BYTE:
5213       shift = 2;
5214       break;
5215     case T_SHORT:
5216       shift = 1;
5217       break;
5218     case T_INT:
5219       shift = 0;
5220       break;
5221     default: ShouldNotReachHere();
5222   }
5223 
5224   if (t == T_BYTE) {
5225     andl(value, 0xff);
5226     movl(rtmp, value);
5227     shll(rtmp, 8);
5228     orl(value, rtmp);
5229   }
5230   if (t == T_SHORT) {
5231     andl(value, 0xffff);
5232   }
5233   if (t == T_BYTE || t == T_SHORT) {
5234     movl(rtmp, value);
5235     shll(rtmp, 16);
5236     orl(value, rtmp);
5237   }
5238 
5239   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
5240   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
5241   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
5242     Label L_skip_align2;
5243     // align source address at 4 bytes address boundary
5244     if (t == T_BYTE) {
5245       Label L_skip_align1;
5246       // One byte misalignment happens only for byte arrays
5247       testptr(to, 1);
5248       jccb(Assembler::zero, L_skip_align1);
5249       movb(Address(to, 0), value);
5250       increment(to);
5251       decrement(count);
5252       BIND(L_skip_align1);
5253     }
5254     // Two bytes misalignment happens only for byte and short (char) arrays
5255     testptr(to, 2);
5256     jccb(Assembler::zero, L_skip_align2);
5257     movw(Address(to, 0), value);
5258     addptr(to, 2);
5259     subl(count, 1<<(shift-1));
5260     BIND(L_skip_align2);
5261   }
5262   if (UseSSE < 2) {
5263     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
5264     // Fill 32-byte chunks
5265     subl(count, 8 << shift);
5266     jcc(Assembler::less, L_check_fill_8_bytes);
5267     align(16);
5268 
5269     BIND(L_fill_32_bytes_loop);
5270 
5271     for (int i = 0; i < 32; i += 4) {
5272       movl(Address(to, i), value);
5273     }
5274 
5275     addptr(to, 32);
5276     subl(count, 8 << shift);
5277     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
5278     BIND(L_check_fill_8_bytes);
5279     addl(count, 8 << shift);
5280     jccb(Assembler::zero, L_exit);
5281     jmpb(L_fill_8_bytes);
5282 
5283     //
5284     // length is too short, just fill qwords
5285     //
5286     BIND(L_fill_8_bytes_loop);
5287     movl(Address(to, 0), value);
5288     movl(Address(to, 4), value);
5289     addptr(to, 8);
5290     BIND(L_fill_8_bytes);
5291     subl(count, 1 << (shift + 1));
5292     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
5293     // fall through to fill 4 bytes
5294   } else {
5295     Label L_fill_32_bytes;
5296     if (!UseUnalignedLoadStores) {
5297       // align to 8 bytes, we know we are 4 byte aligned to start
5298       testptr(to, 4);
5299       jccb(Assembler::zero, L_fill_32_bytes);
5300       movl(Address(to, 0), value);
5301       addptr(to, 4);
5302       subl(count, 1<<shift);
5303     }
5304     BIND(L_fill_32_bytes);
5305     {
5306       assert( UseSSE >= 2, "supported cpu only" );
5307       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
5308       movdl(xtmp, value);
5309       if (UseAVX >= 2 && UseUnalignedLoadStores) {
5310         Label L_check_fill_32_bytes;
5311         if (UseAVX > 2) {
5312           // Fill 64-byte chunks
5313           Label L_fill_64_bytes_loop_avx3, L_check_fill_64_bytes_avx2;
5314 
5315           // If number of bytes to fill < AVX3Threshold, perform fill using AVX2
5316           cmpl(count, AVX3Threshold);
5317           jccb(Assembler::below, L_check_fill_64_bytes_avx2);
5318 
5319           vpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
5320 
5321           subl(count, 16 << shift);
5322           jccb(Assembler::less, L_check_fill_32_bytes);
5323           align(16);
5324 
5325           BIND(L_fill_64_bytes_loop_avx3);
5326           evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
5327           addptr(to, 64);
5328           subl(count, 16 << shift);
5329           jcc(Assembler::greaterEqual, L_fill_64_bytes_loop_avx3);
5330           jmpb(L_check_fill_32_bytes);
5331 
5332           BIND(L_check_fill_64_bytes_avx2);
5333         }
5334         // Fill 64-byte chunks
5335         Label L_fill_64_bytes_loop;
5336         vpbroadcastd(xtmp, xtmp, Assembler::AVX_256bit);
5337 
5338         subl(count, 16 << shift);
5339         jcc(Assembler::less, L_check_fill_32_bytes);
5340         align(16);
5341 
5342         BIND(L_fill_64_bytes_loop);
5343         vmovdqu(Address(to, 0), xtmp);
5344         vmovdqu(Address(to, 32), xtmp);
5345         addptr(to, 64);
5346         subl(count, 16 << shift);
5347         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
5348 
5349         BIND(L_check_fill_32_bytes);
5350         addl(count, 8 << shift);
5351         jccb(Assembler::less, L_check_fill_8_bytes);
5352         vmovdqu(Address(to, 0), xtmp);
5353         addptr(to, 32);
5354         subl(count, 8 << shift);
5355 
5356         BIND(L_check_fill_8_bytes);
5357         // clean upper bits of YMM registers
5358         movdl(xtmp, value);
5359         pshufd(xtmp, xtmp, 0);
5360       } else {
5361         // Fill 32-byte chunks
5362         pshufd(xtmp, xtmp, 0);
5363 
5364         subl(count, 8 << shift);
5365         jcc(Assembler::less, L_check_fill_8_bytes);
5366         align(16);
5367 
5368         BIND(L_fill_32_bytes_loop);
5369 
5370         if (UseUnalignedLoadStores) {
5371           movdqu(Address(to, 0), xtmp);
5372           movdqu(Address(to, 16), xtmp);
5373         } else {
5374           movq(Address(to, 0), xtmp);
5375           movq(Address(to, 8), xtmp);
5376           movq(Address(to, 16), xtmp);
5377           movq(Address(to, 24), xtmp);
5378         }
5379 
5380         addptr(to, 32);
5381         subl(count, 8 << shift);
5382         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
5383 
5384         BIND(L_check_fill_8_bytes);
5385       }
5386       addl(count, 8 << shift);
5387       jccb(Assembler::zero, L_exit);
5388       jmpb(L_fill_8_bytes);
5389 
5390       //
5391       // length is too short, just fill qwords
5392       //
5393       BIND(L_fill_8_bytes_loop);
5394       movq(Address(to, 0), xtmp);
5395       addptr(to, 8);
5396       BIND(L_fill_8_bytes);
5397       subl(count, 1 << (shift + 1));
5398       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
5399     }
5400   }
5401   // fill trailing 4 bytes
5402   BIND(L_fill_4_bytes);
5403   testl(count, 1<<shift);
5404   jccb(Assembler::zero, L_fill_2_bytes);
5405   movl(Address(to, 0), value);
5406   if (t == T_BYTE || t == T_SHORT) {
5407     Label L_fill_byte;
5408     addptr(to, 4);
5409     BIND(L_fill_2_bytes);
5410     // fill trailing 2 bytes
5411     testl(count, 1<<(shift-1));
5412     jccb(Assembler::zero, L_fill_byte);
5413     movw(Address(to, 0), value);
5414     if (t == T_BYTE) {
5415       addptr(to, 2);
5416       BIND(L_fill_byte);
5417       // fill trailing byte
5418       testl(count, 1);
5419       jccb(Assembler::zero, L_exit);
5420       movb(Address(to, 0), value);
5421     } else {
5422       BIND(L_fill_byte);
5423     }
5424   } else {
5425     BIND(L_fill_2_bytes);
5426   }
5427   BIND(L_exit);
5428 }
5429 
5430 // encode char[] to byte[] in ISO_8859_1 or ASCII
5431    //@IntrinsicCandidate
5432    //private static int implEncodeISOArray(byte[] sa, int sp,
5433    //byte[] da, int dp, int len) {
5434    //  int i = 0;
5435    //  for (; i < len; i++) {
5436    //    char c = StringUTF16.getChar(sa, sp++);
5437    //    if (c > '\u00FF')
5438    //      break;
5439    //    da[dp++] = (byte)c;
5440    //  }
5441    //  return i;
5442    //}
5443    //
5444    //@IntrinsicCandidate
5445    //private static int implEncodeAsciiArray(char[] sa, int sp,
5446    //    byte[] da, int dp, int len) {
5447    //  int i = 0;
5448    //  for (; i < len; i++) {
5449    //    char c = sa[sp++];
5450    //    if (c >= '\u0080')
5451    //      break;
5452    //    da[dp++] = (byte)c;
5453    //  }
5454    //  return i;
5455    //}
5456 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
5457   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
5458   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
5459   Register tmp5, Register result, bool ascii) {
5460 
5461   // rsi: src
5462   // rdi: dst
5463   // rdx: len
5464   // rcx: tmp5
5465   // rax: result
5466   ShortBranchVerifier sbv(this);
5467   assert_different_registers(src, dst, len, tmp5, result);
5468   Label L_done, L_copy_1_char, L_copy_1_char_exit;
5469 
5470   int mask = ascii ? 0xff80ff80 : 0xff00ff00;
5471   int short_mask = ascii ? 0xff80 : 0xff00;
5472 
5473   // set result
5474   xorl(result, result);
5475   // check for zero length
5476   testl(len, len);
5477   jcc(Assembler::zero, L_done);
5478 
5479   movl(result, len);
5480 
5481   // Setup pointers
5482   lea(src, Address(src, len, Address::times_2)); // char[]
5483   lea(dst, Address(dst, len, Address::times_1)); // byte[]
5484   negptr(len);
5485 
5486   if (UseSSE42Intrinsics || UseAVX >= 2) {
5487     Label L_copy_8_chars, L_copy_8_chars_exit;
5488     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
5489 
5490     if (UseAVX >= 2) {
5491       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
5492       movl(tmp5, mask);   // create mask to test for Unicode or non-ASCII chars in vector
5493       movdl(tmp1Reg, tmp5);
5494       vpbroadcastd(tmp1Reg, tmp1Reg, Assembler::AVX_256bit);
5495       jmp(L_chars_32_check);
5496 
5497       bind(L_copy_32_chars);
5498       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
5499       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
5500       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
5501       vptest(tmp2Reg, tmp1Reg);       // check for Unicode or non-ASCII chars in vector
5502       jccb(Assembler::notZero, L_copy_32_chars_exit);
5503       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
5504       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
5505       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
5506 
5507       bind(L_chars_32_check);
5508       addptr(len, 32);
5509       jcc(Assembler::lessEqual, L_copy_32_chars);
5510 
5511       bind(L_copy_32_chars_exit);
5512       subptr(len, 16);
5513       jccb(Assembler::greater, L_copy_16_chars_exit);
5514 
5515     } else if (UseSSE42Intrinsics) {
5516       movl(tmp5, mask);   // create mask to test for Unicode or non-ASCII chars in vector
5517       movdl(tmp1Reg, tmp5);
5518       pshufd(tmp1Reg, tmp1Reg, 0);
5519       jmpb(L_chars_16_check);
5520     }
5521 
5522     bind(L_copy_16_chars);
5523     if (UseAVX >= 2) {
5524       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
5525       vptest(tmp2Reg, tmp1Reg);
5526       jcc(Assembler::notZero, L_copy_16_chars_exit);
5527       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
5528       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
5529     } else {
5530       if (UseAVX > 0) {
5531         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
5532         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
5533         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
5534       } else {
5535         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
5536         por(tmp2Reg, tmp3Reg);
5537         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
5538         por(tmp2Reg, tmp4Reg);
5539       }
5540       ptest(tmp2Reg, tmp1Reg);       // check for Unicode or non-ASCII chars in vector
5541       jccb(Assembler::notZero, L_copy_16_chars_exit);
5542       packuswb(tmp3Reg, tmp4Reg);
5543     }
5544     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
5545 
5546     bind(L_chars_16_check);
5547     addptr(len, 16);
5548     jcc(Assembler::lessEqual, L_copy_16_chars);
5549 
5550     bind(L_copy_16_chars_exit);
5551     if (UseAVX >= 2) {
5552       // clean upper bits of YMM registers
5553       vpxor(tmp2Reg, tmp2Reg);
5554       vpxor(tmp3Reg, tmp3Reg);
5555       vpxor(tmp4Reg, tmp4Reg);
5556       movdl(tmp1Reg, tmp5);
5557       pshufd(tmp1Reg, tmp1Reg, 0);
5558     }
5559     subptr(len, 8);
5560     jccb(Assembler::greater, L_copy_8_chars_exit);
5561 
5562     bind(L_copy_8_chars);
5563     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
5564     ptest(tmp3Reg, tmp1Reg);
5565     jccb(Assembler::notZero, L_copy_8_chars_exit);
5566     packuswb(tmp3Reg, tmp1Reg);
5567     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
5568     addptr(len, 8);
5569     jccb(Assembler::lessEqual, L_copy_8_chars);
5570 
5571     bind(L_copy_8_chars_exit);
5572     subptr(len, 8);
5573     jccb(Assembler::zero, L_done);
5574   }
5575 
5576   bind(L_copy_1_char);
5577   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
5578   testl(tmp5, short_mask);      // check if Unicode or non-ASCII char
5579   jccb(Assembler::notZero, L_copy_1_char_exit);
5580   movb(Address(dst, len, Address::times_1, 0), tmp5);
5581   addptr(len, 1);
5582   jccb(Assembler::less, L_copy_1_char);
5583 
5584   bind(L_copy_1_char_exit);
5585   addptr(result, len); // len is negative count of not processed elements
5586 
5587   bind(L_done);
5588 }
5589 
5590 #ifdef _LP64
5591 /**
5592  * Helper for multiply_to_len().
5593  */
5594 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
5595   addq(dest_lo, src1);
5596   adcq(dest_hi, 0);
5597   addq(dest_lo, src2);
5598   adcq(dest_hi, 0);
5599 }
5600 
5601 /**
5602  * Multiply 64 bit by 64 bit first loop.
5603  */
5604 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
5605                                            Register y, Register y_idx, Register z,
5606                                            Register carry, Register product,
5607                                            Register idx, Register kdx) {
5608   //
5609   //  jlong carry, x[], y[], z[];
5610   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
5611   //    huge_128 product = y[idx] * x[xstart] + carry;
5612   //    z[kdx] = (jlong)product;
5613   //    carry  = (jlong)(product >>> 64);
5614   //  }
5615   //  z[xstart] = carry;
5616   //
5617 
5618   Label L_first_loop, L_first_loop_exit;
5619   Label L_one_x, L_one_y, L_multiply;
5620 
5621   decrementl(xstart);
5622   jcc(Assembler::negative, L_one_x);
5623 
5624   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
5625   rorq(x_xstart, 32); // convert big-endian to little-endian
5626 
5627   bind(L_first_loop);
5628   decrementl(idx);
5629   jcc(Assembler::negative, L_first_loop_exit);
5630   decrementl(idx);
5631   jcc(Assembler::negative, L_one_y);
5632   movq(y_idx, Address(y, idx, Address::times_4,  0));
5633   rorq(y_idx, 32); // convert big-endian to little-endian
5634   bind(L_multiply);
5635   movq(product, x_xstart);
5636   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
5637   addq(product, carry);
5638   adcq(rdx, 0);
5639   subl(kdx, 2);
5640   movl(Address(z, kdx, Address::times_4,  4), product);
5641   shrq(product, 32);
5642   movl(Address(z, kdx, Address::times_4,  0), product);
5643   movq(carry, rdx);
5644   jmp(L_first_loop);
5645 
5646   bind(L_one_y);
5647   movl(y_idx, Address(y,  0));
5648   jmp(L_multiply);
5649 
5650   bind(L_one_x);
5651   movl(x_xstart, Address(x,  0));
5652   jmp(L_first_loop);
5653 
5654   bind(L_first_loop_exit);
5655 }
5656 
5657 /**
5658  * Multiply 64 bit by 64 bit and add 128 bit.
5659  */
5660 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
5661                                             Register yz_idx, Register idx,
5662                                             Register carry, Register product, int offset) {
5663   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
5664   //     z[kdx] = (jlong)product;
5665 
5666   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
5667   rorq(yz_idx, 32); // convert big-endian to little-endian
5668   movq(product, x_xstart);
5669   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
5670   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
5671   rorq(yz_idx, 32); // convert big-endian to little-endian
5672 
5673   add2_with_carry(rdx, product, carry, yz_idx);
5674 
5675   movl(Address(z, idx, Address::times_4,  offset+4), product);
5676   shrq(product, 32);
5677   movl(Address(z, idx, Address::times_4,  offset), product);
5678 
5679 }
5680 
5681 /**
5682  * Multiply 128 bit by 128 bit. Unrolled inner loop.
5683  */
5684 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
5685                                              Register yz_idx, Register idx, Register jdx,
5686                                              Register carry, Register product,
5687                                              Register carry2) {
5688   //   jlong carry, x[], y[], z[];
5689   //   int kdx = ystart+1;
5690   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
5691   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
5692   //     z[kdx+idx+1] = (jlong)product;
5693   //     jlong carry2  = (jlong)(product >>> 64);
5694   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
5695   //     z[kdx+idx] = (jlong)product;
5696   //     carry  = (jlong)(product >>> 64);
5697   //   }
5698   //   idx += 2;
5699   //   if (idx > 0) {
5700   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
5701   //     z[kdx+idx] = (jlong)product;
5702   //     carry  = (jlong)(product >>> 64);
5703   //   }
5704   //
5705 
5706   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
5707 
5708   movl(jdx, idx);
5709   andl(jdx, 0xFFFFFFFC);
5710   shrl(jdx, 2);
5711 
5712   bind(L_third_loop);
5713   subl(jdx, 1);
5714   jcc(Assembler::negative, L_third_loop_exit);
5715   subl(idx, 4);
5716 
5717   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
5718   movq(carry2, rdx);
5719 
5720   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
5721   movq(carry, rdx);
5722   jmp(L_third_loop);
5723 
5724   bind (L_third_loop_exit);
5725 
5726   andl (idx, 0x3);
5727   jcc(Assembler::zero, L_post_third_loop_done);
5728 
5729   Label L_check_1;
5730   subl(idx, 2);
5731   jcc(Assembler::negative, L_check_1);
5732 
5733   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
5734   movq(carry, rdx);
5735 
5736   bind (L_check_1);
5737   addl (idx, 0x2);
5738   andl (idx, 0x1);
5739   subl(idx, 1);
5740   jcc(Assembler::negative, L_post_third_loop_done);
5741 
5742   movl(yz_idx, Address(y, idx, Address::times_4,  0));
5743   movq(product, x_xstart);
5744   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
5745   movl(yz_idx, Address(z, idx, Address::times_4,  0));
5746 
5747   add2_with_carry(rdx, product, yz_idx, carry);
5748 
5749   movl(Address(z, idx, Address::times_4,  0), product);
5750   shrq(product, 32);
5751 
5752   shlq(rdx, 32);
5753   orq(product, rdx);
5754   movq(carry, product);
5755 
5756   bind(L_post_third_loop_done);
5757 }
5758 
5759 /**
5760  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
5761  *
5762  */
5763 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
5764                                                   Register carry, Register carry2,
5765                                                   Register idx, Register jdx,
5766                                                   Register yz_idx1, Register yz_idx2,
5767                                                   Register tmp, Register tmp3, Register tmp4) {
5768   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
5769 
5770   //   jlong carry, x[], y[], z[];
5771   //   int kdx = ystart+1;
5772   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
5773   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
5774   //     jlong carry2  = (jlong)(tmp3 >>> 64);
5775   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
5776   //     carry  = (jlong)(tmp4 >>> 64);
5777   //     z[kdx+idx+1] = (jlong)tmp3;
5778   //     z[kdx+idx] = (jlong)tmp4;
5779   //   }
5780   //   idx += 2;
5781   //   if (idx > 0) {
5782   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
5783   //     z[kdx+idx] = (jlong)yz_idx1;
5784   //     carry  = (jlong)(yz_idx1 >>> 64);
5785   //   }
5786   //
5787 
5788   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
5789 
5790   movl(jdx, idx);
5791   andl(jdx, 0xFFFFFFFC);
5792   shrl(jdx, 2);
5793 
5794   bind(L_third_loop);
5795   subl(jdx, 1);
5796   jcc(Assembler::negative, L_third_loop_exit);
5797   subl(idx, 4);
5798 
5799   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
5800   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
5801   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
5802   rorxq(yz_idx2, yz_idx2, 32);
5803 
5804   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
5805   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
5806 
5807   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
5808   rorxq(yz_idx1, yz_idx1, 32);
5809   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
5810   rorxq(yz_idx2, yz_idx2, 32);
5811 
5812   if (VM_Version::supports_adx()) {
5813     adcxq(tmp3, carry);
5814     adoxq(tmp3, yz_idx1);
5815 
5816     adcxq(tmp4, tmp);
5817     adoxq(tmp4, yz_idx2);
5818 
5819     movl(carry, 0); // does not affect flags
5820     adcxq(carry2, carry);
5821     adoxq(carry2, carry);
5822   } else {
5823     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
5824     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
5825   }
5826   movq(carry, carry2);
5827 
5828   movl(Address(z, idx, Address::times_4, 12), tmp3);
5829   shrq(tmp3, 32);
5830   movl(Address(z, idx, Address::times_4,  8), tmp3);
5831 
5832   movl(Address(z, idx, Address::times_4,  4), tmp4);
5833   shrq(tmp4, 32);
5834   movl(Address(z, idx, Address::times_4,  0), tmp4);
5835 
5836   jmp(L_third_loop);
5837 
5838   bind (L_third_loop_exit);
5839 
5840   andl (idx, 0x3);
5841   jcc(Assembler::zero, L_post_third_loop_done);
5842 
5843   Label L_check_1;
5844   subl(idx, 2);
5845   jcc(Assembler::negative, L_check_1);
5846 
5847   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
5848   rorxq(yz_idx1, yz_idx1, 32);
5849   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
5850   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
5851   rorxq(yz_idx2, yz_idx2, 32);
5852 
5853   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
5854 
5855   movl(Address(z, idx, Address::times_4,  4), tmp3);
5856   shrq(tmp3, 32);
5857   movl(Address(z, idx, Address::times_4,  0), tmp3);
5858   movq(carry, tmp4);
5859 
5860   bind (L_check_1);
5861   addl (idx, 0x2);
5862   andl (idx, 0x1);
5863   subl(idx, 1);
5864   jcc(Assembler::negative, L_post_third_loop_done);
5865   movl(tmp4, Address(y, idx, Address::times_4,  0));
5866   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
5867   movl(tmp4, Address(z, idx, Address::times_4,  0));
5868 
5869   add2_with_carry(carry2, tmp3, tmp4, carry);
5870 
5871   movl(Address(z, idx, Address::times_4,  0), tmp3);
5872   shrq(tmp3, 32);
5873 
5874   shlq(carry2, 32);
5875   orq(tmp3, carry2);
5876   movq(carry, tmp3);
5877 
5878   bind(L_post_third_loop_done);
5879 }
5880 
5881 /**
5882  * Code for BigInteger::multiplyToLen() instrinsic.
5883  *
5884  * rdi: x
5885  * rax: xlen
5886  * rsi: y
5887  * rcx: ylen
5888  * r8:  z
5889  * r11: zlen
5890  * r12: tmp1
5891  * r13: tmp2
5892  * r14: tmp3
5893  * r15: tmp4
5894  * rbx: tmp5
5895  *
5896  */
5897 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
5898                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
5899   ShortBranchVerifier sbv(this);
5900   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
5901 
5902   push(tmp1);
5903   push(tmp2);
5904   push(tmp3);
5905   push(tmp4);
5906   push(tmp5);
5907 
5908   push(xlen);
5909   push(zlen);
5910 
5911   const Register idx = tmp1;
5912   const Register kdx = tmp2;
5913   const Register xstart = tmp3;
5914 
5915   const Register y_idx = tmp4;
5916   const Register carry = tmp5;
5917   const Register product  = xlen;
5918   const Register x_xstart = zlen;  // reuse register
5919 
5920   // First Loop.
5921   //
5922   //  final static long LONG_MASK = 0xffffffffL;
5923   //  int xstart = xlen - 1;
5924   //  int ystart = ylen - 1;
5925   //  long carry = 0;
5926   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
5927   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
5928   //    z[kdx] = (int)product;
5929   //    carry = product >>> 32;
5930   //  }
5931   //  z[xstart] = (int)carry;
5932   //
5933 
5934   movl(idx, ylen);      // idx = ylen;
5935   movl(kdx, zlen);      // kdx = xlen+ylen;
5936   xorq(carry, carry);   // carry = 0;
5937 
5938   Label L_done;
5939 
5940   movl(xstart, xlen);
5941   decrementl(xstart);
5942   jcc(Assembler::negative, L_done);
5943 
5944   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
5945 
5946   Label L_second_loop;
5947   testl(kdx, kdx);
5948   jcc(Assembler::zero, L_second_loop);
5949 
5950   Label L_carry;
5951   subl(kdx, 1);
5952   jcc(Assembler::zero, L_carry);
5953 
5954   movl(Address(z, kdx, Address::times_4,  0), carry);
5955   shrq(carry, 32);
5956   subl(kdx, 1);
5957 
5958   bind(L_carry);
5959   movl(Address(z, kdx, Address::times_4,  0), carry);
5960 
5961   // Second and third (nested) loops.
5962   //
5963   // for (int i = xstart-1; i >= 0; i--) { // Second loop
5964   //   carry = 0;
5965   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
5966   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
5967   //                    (z[k] & LONG_MASK) + carry;
5968   //     z[k] = (int)product;
5969   //     carry = product >>> 32;
5970   //   }
5971   //   z[i] = (int)carry;
5972   // }
5973   //
5974   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
5975 
5976   const Register jdx = tmp1;
5977 
5978   bind(L_second_loop);
5979   xorl(carry, carry);    // carry = 0;
5980   movl(jdx, ylen);       // j = ystart+1
5981 
5982   subl(xstart, 1);       // i = xstart-1;
5983   jcc(Assembler::negative, L_done);
5984 
5985   push (z);
5986 
5987   Label L_last_x;
5988   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
5989   subl(xstart, 1);       // i = xstart-1;
5990   jcc(Assembler::negative, L_last_x);
5991 
5992   if (UseBMI2Instructions) {
5993     movq(rdx,  Address(x, xstart, Address::times_4,  0));
5994     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
5995   } else {
5996     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
5997     rorq(x_xstart, 32);  // convert big-endian to little-endian
5998   }
5999 
6000   Label L_third_loop_prologue;
6001   bind(L_third_loop_prologue);
6002 
6003   push (x);
6004   push (xstart);
6005   push (ylen);
6006 
6007 
6008   if (UseBMI2Instructions) {
6009     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
6010   } else { // !UseBMI2Instructions
6011     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
6012   }
6013 
6014   pop(ylen);
6015   pop(xlen);
6016   pop(x);
6017   pop(z);
6018 
6019   movl(tmp3, xlen);
6020   addl(tmp3, 1);
6021   movl(Address(z, tmp3, Address::times_4,  0), carry);
6022   subl(tmp3, 1);
6023   jccb(Assembler::negative, L_done);
6024 
6025   shrq(carry, 32);
6026   movl(Address(z, tmp3, Address::times_4,  0), carry);
6027   jmp(L_second_loop);
6028 
6029   // Next infrequent code is moved outside loops.
6030   bind(L_last_x);
6031   if (UseBMI2Instructions) {
6032     movl(rdx, Address(x,  0));
6033   } else {
6034     movl(x_xstart, Address(x,  0));
6035   }
6036   jmp(L_third_loop_prologue);
6037 
6038   bind(L_done);
6039 
6040   pop(zlen);
6041   pop(xlen);
6042 
6043   pop(tmp5);
6044   pop(tmp4);
6045   pop(tmp3);
6046   pop(tmp2);
6047   pop(tmp1);
6048 }
6049 
6050 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
6051   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
6052   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
6053   Label VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
6054   Label VECTOR8_TAIL, VECTOR4_TAIL;
6055   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
6056   Label SAME_TILL_END, DONE;
6057   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
6058 
6059   //scale is in rcx in both Win64 and Unix
6060   ShortBranchVerifier sbv(this);
6061 
6062   shlq(length);
6063   xorq(result, result);
6064 
6065   if ((AVX3Threshold == 0) && (UseAVX > 2) &&
6066       VM_Version::supports_avx512vlbw()) {
6067     Label VECTOR64_LOOP, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
6068 
6069     cmpq(length, 64);
6070     jcc(Assembler::less, VECTOR32_TAIL);
6071 
6072     movq(tmp1, length);
6073     andq(tmp1, 0x3F);      // tail count
6074     andq(length, ~(0x3F)); //vector count
6075 
6076     bind(VECTOR64_LOOP);
6077     // AVX512 code to compare 64 byte vectors.
6078     evmovdqub(rymm0, Address(obja, result), false, Assembler::AVX_512bit);
6079     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
6080     kortestql(k7, k7);
6081     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
6082     addq(result, 64);
6083     subq(length, 64);
6084     jccb(Assembler::notZero, VECTOR64_LOOP);
6085 
6086     //bind(VECTOR64_TAIL);
6087     testq(tmp1, tmp1);
6088     jcc(Assembler::zero, SAME_TILL_END);
6089 
6090     //bind(VECTOR64_TAIL);
6091     // AVX512 code to compare upto 63 byte vectors.
6092     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
6093     shlxq(tmp2, tmp2, tmp1);
6094     notq(tmp2);
6095     kmovql(k3, tmp2);
6096 
6097     evmovdqub(rymm0, k3, Address(obja, result), false, Assembler::AVX_512bit);
6098     evpcmpeqb(k7, k3, rymm0, Address(objb, result), Assembler::AVX_512bit);
6099 
6100     ktestql(k7, k3);
6101     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
6102 
6103     bind(VECTOR64_NOT_EQUAL);
6104     kmovql(tmp1, k7);
6105     notq(tmp1);
6106     tzcntq(tmp1, tmp1);
6107     addq(result, tmp1);
6108     shrq(result);
6109     jmp(DONE);
6110     bind(VECTOR32_TAIL);
6111   }
6112 
6113   cmpq(length, 8);
6114   jcc(Assembler::equal, VECTOR8_LOOP);
6115   jcc(Assembler::less, VECTOR4_TAIL);
6116 
6117   if (UseAVX >= 2) {
6118     Label VECTOR16_TAIL, VECTOR32_LOOP;
6119 
6120     cmpq(length, 16);
6121     jcc(Assembler::equal, VECTOR16_LOOP);
6122     jcc(Assembler::less, VECTOR8_LOOP);
6123 
6124     cmpq(length, 32);
6125     jccb(Assembler::less, VECTOR16_TAIL);
6126 
6127     subq(length, 32);
6128     bind(VECTOR32_LOOP);
6129     vmovdqu(rymm0, Address(obja, result));
6130     vmovdqu(rymm1, Address(objb, result));
6131     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
6132     vptest(rymm2, rymm2);
6133     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
6134     addq(result, 32);
6135     subq(length, 32);
6136     jcc(Assembler::greaterEqual, VECTOR32_LOOP);
6137     addq(length, 32);
6138     jcc(Assembler::equal, SAME_TILL_END);
6139     //falling through if less than 32 bytes left //close the branch here.
6140 
6141     bind(VECTOR16_TAIL);
6142     cmpq(length, 16);
6143     jccb(Assembler::less, VECTOR8_TAIL);
6144     bind(VECTOR16_LOOP);
6145     movdqu(rymm0, Address(obja, result));
6146     movdqu(rymm1, Address(objb, result));
6147     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
6148     ptest(rymm2, rymm2);
6149     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
6150     addq(result, 16);
6151     subq(length, 16);
6152     jcc(Assembler::equal, SAME_TILL_END);
6153     //falling through if less than 16 bytes left
6154   } else {//regular intrinsics
6155 
6156     cmpq(length, 16);
6157     jccb(Assembler::less, VECTOR8_TAIL);
6158 
6159     subq(length, 16);
6160     bind(VECTOR16_LOOP);
6161     movdqu(rymm0, Address(obja, result));
6162     movdqu(rymm1, Address(objb, result));
6163     pxor(rymm0, rymm1);
6164     ptest(rymm0, rymm0);
6165     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
6166     addq(result, 16);
6167     subq(length, 16);
6168     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
6169     addq(length, 16);
6170     jcc(Assembler::equal, SAME_TILL_END);
6171     //falling through if less than 16 bytes left
6172   }
6173 
6174   bind(VECTOR8_TAIL);
6175   cmpq(length, 8);
6176   jccb(Assembler::less, VECTOR4_TAIL);
6177   bind(VECTOR8_LOOP);
6178   movq(tmp1, Address(obja, result));
6179   movq(tmp2, Address(objb, result));
6180   xorq(tmp1, tmp2);
6181   testq(tmp1, tmp1);
6182   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
6183   addq(result, 8);
6184   subq(length, 8);
6185   jcc(Assembler::equal, SAME_TILL_END);
6186   //falling through if less than 8 bytes left
6187 
6188   bind(VECTOR4_TAIL);
6189   cmpq(length, 4);
6190   jccb(Assembler::less, BYTES_TAIL);
6191   bind(VECTOR4_LOOP);
6192   movl(tmp1, Address(obja, result));
6193   xorl(tmp1, Address(objb, result));
6194   testl(tmp1, tmp1);
6195   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
6196   addq(result, 4);
6197   subq(length, 4);
6198   jcc(Assembler::equal, SAME_TILL_END);
6199   //falling through if less than 4 bytes left
6200 
6201   bind(BYTES_TAIL);
6202   bind(BYTES_LOOP);
6203   load_unsigned_byte(tmp1, Address(obja, result));
6204   load_unsigned_byte(tmp2, Address(objb, result));
6205   xorl(tmp1, tmp2);
6206   testl(tmp1, tmp1);
6207   jcc(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
6208   decq(length);
6209   jcc(Assembler::zero, SAME_TILL_END);
6210   incq(result);
6211   load_unsigned_byte(tmp1, Address(obja, result));
6212   load_unsigned_byte(tmp2, Address(objb, result));
6213   xorl(tmp1, tmp2);
6214   testl(tmp1, tmp1);
6215   jcc(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
6216   decq(length);
6217   jcc(Assembler::zero, SAME_TILL_END);
6218   incq(result);
6219   load_unsigned_byte(tmp1, Address(obja, result));
6220   load_unsigned_byte(tmp2, Address(objb, result));
6221   xorl(tmp1, tmp2);
6222   testl(tmp1, tmp1);
6223   jcc(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
6224   jmp(SAME_TILL_END);
6225 
6226   if (UseAVX >= 2) {
6227     bind(VECTOR32_NOT_EQUAL);
6228     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
6229     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
6230     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
6231     vpmovmskb(tmp1, rymm0);
6232     bsfq(tmp1, tmp1);
6233     addq(result, tmp1);
6234     shrq(result);
6235     jmp(DONE);
6236   }
6237 
6238   bind(VECTOR16_NOT_EQUAL);
6239   if (UseAVX >= 2) {
6240     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
6241     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
6242     pxor(rymm0, rymm2);
6243   } else {
6244     pcmpeqb(rymm2, rymm2);
6245     pxor(rymm0, rymm1);
6246     pcmpeqb(rymm0, rymm1);
6247     pxor(rymm0, rymm2);
6248   }
6249   pmovmskb(tmp1, rymm0);
6250   bsfq(tmp1, tmp1);
6251   addq(result, tmp1);
6252   shrq(result);
6253   jmpb(DONE);
6254 
6255   bind(VECTOR8_NOT_EQUAL);
6256   bind(VECTOR4_NOT_EQUAL);
6257   bsfq(tmp1, tmp1);
6258   shrq(tmp1, 3);
6259   addq(result, tmp1);
6260   bind(BYTES_NOT_EQUAL);
6261   shrq(result);
6262   jmpb(DONE);
6263 
6264   bind(SAME_TILL_END);
6265   mov64(result, -1);
6266 
6267   bind(DONE);
6268 }
6269 
6270 //Helper functions for square_to_len()
6271 
6272 /**
6273  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
6274  * Preserves x and z and modifies rest of the registers.
6275  */
6276 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
6277   // Perform square and right shift by 1
6278   // Handle odd xlen case first, then for even xlen do the following
6279   // jlong carry = 0;
6280   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
6281   //     huge_128 product = x[j:j+1] * x[j:j+1];
6282   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
6283   //     z[i+2:i+3] = (jlong)(product >>> 1);
6284   //     carry = (jlong)product;
6285   // }
6286 
6287   xorq(tmp5, tmp5);     // carry
6288   xorq(rdxReg, rdxReg);
6289   xorl(tmp1, tmp1);     // index for x
6290   xorl(tmp4, tmp4);     // index for z
6291 
6292   Label L_first_loop, L_first_loop_exit;
6293 
6294   testl(xlen, 1);
6295   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
6296 
6297   // Square and right shift by 1 the odd element using 32 bit multiply
6298   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
6299   imulq(raxReg, raxReg);
6300   shrq(raxReg, 1);
6301   adcq(tmp5, 0);
6302   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
6303   incrementl(tmp1);
6304   addl(tmp4, 2);
6305 
6306   // Square and  right shift by 1 the rest using 64 bit multiply
6307   bind(L_first_loop);
6308   cmpptr(tmp1, xlen);
6309   jccb(Assembler::equal, L_first_loop_exit);
6310 
6311   // Square
6312   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
6313   rorq(raxReg, 32);    // convert big-endian to little-endian
6314   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
6315 
6316   // Right shift by 1 and save carry
6317   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
6318   rcrq(rdxReg, 1);
6319   rcrq(raxReg, 1);
6320   adcq(tmp5, 0);
6321 
6322   // Store result in z
6323   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
6324   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
6325 
6326   // Update indices for x and z
6327   addl(tmp1, 2);
6328   addl(tmp4, 4);
6329   jmp(L_first_loop);
6330 
6331   bind(L_first_loop_exit);
6332 }
6333 
6334 
6335 /**
6336  * Perform the following multiply add operation using BMI2 instructions
6337  * carry:sum = sum + op1*op2 + carry
6338  * op2 should be in rdx
6339  * op2 is preserved, all other registers are modified
6340  */
6341 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
6342   // assert op2 is rdx
6343   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
6344   addq(sum, carry);
6345   adcq(tmp2, 0);
6346   addq(sum, op1);
6347   adcq(tmp2, 0);
6348   movq(carry, tmp2);
6349 }
6350 
6351 /**
6352  * Perform the following multiply add operation:
6353  * carry:sum = sum + op1*op2 + carry
6354  * Preserves op1, op2 and modifies rest of registers
6355  */
6356 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
6357   // rdx:rax = op1 * op2
6358   movq(raxReg, op2);
6359   mulq(op1);
6360 
6361   //  rdx:rax = sum + carry + rdx:rax
6362   addq(sum, carry);
6363   adcq(rdxReg, 0);
6364   addq(sum, raxReg);
6365   adcq(rdxReg, 0);
6366 
6367   // carry:sum = rdx:sum
6368   movq(carry, rdxReg);
6369 }
6370 
6371 /**
6372  * Add 64 bit long carry into z[] with carry propogation.
6373  * Preserves z and carry register values and modifies rest of registers.
6374  *
6375  */
6376 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
6377   Label L_fourth_loop, L_fourth_loop_exit;
6378 
6379   movl(tmp1, 1);
6380   subl(zlen, 2);
6381   addq(Address(z, zlen, Address::times_4, 0), carry);
6382 
6383   bind(L_fourth_loop);
6384   jccb(Assembler::carryClear, L_fourth_loop_exit);
6385   subl(zlen, 2);
6386   jccb(Assembler::negative, L_fourth_loop_exit);
6387   addq(Address(z, zlen, Address::times_4, 0), tmp1);
6388   jmp(L_fourth_loop);
6389   bind(L_fourth_loop_exit);
6390 }
6391 
6392 /**
6393  * Shift z[] left by 1 bit.
6394  * Preserves x, len, z and zlen registers and modifies rest of the registers.
6395  *
6396  */
6397 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
6398 
6399   Label L_fifth_loop, L_fifth_loop_exit;
6400 
6401   // Fifth loop
6402   // Perform primitiveLeftShift(z, zlen, 1)
6403 
6404   const Register prev_carry = tmp1;
6405   const Register new_carry = tmp4;
6406   const Register value = tmp2;
6407   const Register zidx = tmp3;
6408 
6409   // int zidx, carry;
6410   // long value;
6411   // carry = 0;
6412   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
6413   //    (carry:value)  = (z[i] << 1) | carry ;
6414   //    z[i] = value;
6415   // }
6416 
6417   movl(zidx, zlen);
6418   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
6419 
6420   bind(L_fifth_loop);
6421   decl(zidx);  // Use decl to preserve carry flag
6422   decl(zidx);
6423   jccb(Assembler::negative, L_fifth_loop_exit);
6424 
6425   if (UseBMI2Instructions) {
6426      movq(value, Address(z, zidx, Address::times_4, 0));
6427      rclq(value, 1);
6428      rorxq(value, value, 32);
6429      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
6430   }
6431   else {
6432     // clear new_carry
6433     xorl(new_carry, new_carry);
6434 
6435     // Shift z[i] by 1, or in previous carry and save new carry
6436     movq(value, Address(z, zidx, Address::times_4, 0));
6437     shlq(value, 1);
6438     adcl(new_carry, 0);
6439 
6440     orq(value, prev_carry);
6441     rorq(value, 0x20);
6442     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
6443 
6444     // Set previous carry = new carry
6445     movl(prev_carry, new_carry);
6446   }
6447   jmp(L_fifth_loop);
6448 
6449   bind(L_fifth_loop_exit);
6450 }
6451 
6452 
6453 /**
6454  * Code for BigInteger::squareToLen() intrinsic
6455  *
6456  * rdi: x
6457  * rsi: len
6458  * r8:  z
6459  * rcx: zlen
6460  * r12: tmp1
6461  * r13: tmp2
6462  * r14: tmp3
6463  * r15: tmp4
6464  * rbx: tmp5
6465  *
6466  */
6467 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) {
6468 
6469   Label L_second_loop, L_second_loop_exit, L_third_loop, L_third_loop_exit, L_last_x, L_multiply;
6470   push(tmp1);
6471   push(tmp2);
6472   push(tmp3);
6473   push(tmp4);
6474   push(tmp5);
6475 
6476   // First loop
6477   // Store the squares, right shifted one bit (i.e., divided by 2).
6478   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
6479 
6480   // Add in off-diagonal sums.
6481   //
6482   // Second, third (nested) and fourth loops.
6483   // zlen +=2;
6484   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
6485   //    carry = 0;
6486   //    long op2 = x[xidx:xidx+1];
6487   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
6488   //       k -= 2;
6489   //       long op1 = x[j:j+1];
6490   //       long sum = z[k:k+1];
6491   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
6492   //       z[k:k+1] = sum;
6493   //    }
6494   //    add_one_64(z, k, carry, tmp_regs);
6495   // }
6496 
6497   const Register carry = tmp5;
6498   const Register sum = tmp3;
6499   const Register op1 = tmp4;
6500   Register op2 = tmp2;
6501 
6502   push(zlen);
6503   push(len);
6504   addl(zlen,2);
6505   bind(L_second_loop);
6506   xorq(carry, carry);
6507   subl(zlen, 4);
6508   subl(len, 2);
6509   push(zlen);
6510   push(len);
6511   cmpl(len, 0);
6512   jccb(Assembler::lessEqual, L_second_loop_exit);
6513 
6514   // Multiply an array by one 64 bit long.
6515   if (UseBMI2Instructions) {
6516     op2 = rdxReg;
6517     movq(op2, Address(x, len, Address::times_4,  0));
6518     rorxq(op2, op2, 32);
6519   }
6520   else {
6521     movq(op2, Address(x, len, Address::times_4,  0));
6522     rorq(op2, 32);
6523   }
6524 
6525   bind(L_third_loop);
6526   decrementl(len);
6527   jccb(Assembler::negative, L_third_loop_exit);
6528   decrementl(len);
6529   jccb(Assembler::negative, L_last_x);
6530 
6531   movq(op1, Address(x, len, Address::times_4,  0));
6532   rorq(op1, 32);
6533 
6534   bind(L_multiply);
6535   subl(zlen, 2);
6536   movq(sum, Address(z, zlen, Address::times_4,  0));
6537 
6538   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
6539   if (UseBMI2Instructions) {
6540     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
6541   }
6542   else {
6543     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
6544   }
6545 
6546   movq(Address(z, zlen, Address::times_4, 0), sum);
6547 
6548   jmp(L_third_loop);
6549   bind(L_third_loop_exit);
6550 
6551   // Fourth loop
6552   // Add 64 bit long carry into z with carry propogation.
6553   // Uses offsetted zlen.
6554   add_one_64(z, zlen, carry, tmp1);
6555 
6556   pop(len);
6557   pop(zlen);
6558   jmp(L_second_loop);
6559 
6560   // Next infrequent code is moved outside loops.
6561   bind(L_last_x);
6562   movl(op1, Address(x, 0));
6563   jmp(L_multiply);
6564 
6565   bind(L_second_loop_exit);
6566   pop(len);
6567   pop(zlen);
6568   pop(len);
6569   pop(zlen);
6570 
6571   // Fifth loop
6572   // Shift z left 1 bit.
6573   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
6574 
6575   // z[zlen-1] |= x[len-1] & 1;
6576   movl(tmp3, Address(x, len, Address::times_4, -4));
6577   andl(tmp3, 1);
6578   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
6579 
6580   pop(tmp5);
6581   pop(tmp4);
6582   pop(tmp3);
6583   pop(tmp2);
6584   pop(tmp1);
6585 }
6586 
6587 /**
6588  * Helper function for mul_add()
6589  * Multiply the in[] by int k and add to out[] starting at offset offs using
6590  * 128 bit by 32 bit multiply and return the carry in tmp5.
6591  * Only quad int aligned length of in[] is operated on in this function.
6592  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
6593  * This function preserves out, in and k registers.
6594  * len and offset point to the appropriate index in "in" & "out" correspondingly
6595  * tmp5 has the carry.
6596  * other registers are temporary and are modified.
6597  *
6598  */
6599 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
6600   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
6601   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
6602 
6603   Label L_first_loop, L_first_loop_exit;
6604 
6605   movl(tmp1, len);
6606   shrl(tmp1, 2);
6607 
6608   bind(L_first_loop);
6609   subl(tmp1, 1);
6610   jccb(Assembler::negative, L_first_loop_exit);
6611 
6612   subl(len, 4);
6613   subl(offset, 4);
6614 
6615   Register op2 = tmp2;
6616   const Register sum = tmp3;
6617   const Register op1 = tmp4;
6618   const Register carry = tmp5;
6619 
6620   if (UseBMI2Instructions) {
6621     op2 = rdxReg;
6622   }
6623 
6624   movq(op1, Address(in, len, Address::times_4,  8));
6625   rorq(op1, 32);
6626   movq(sum, Address(out, offset, Address::times_4,  8));
6627   rorq(sum, 32);
6628   if (UseBMI2Instructions) {
6629     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
6630   }
6631   else {
6632     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
6633   }
6634   // Store back in big endian from little endian
6635   rorq(sum, 0x20);
6636   movq(Address(out, offset, Address::times_4,  8), sum);
6637 
6638   movq(op1, Address(in, len, Address::times_4,  0));
6639   rorq(op1, 32);
6640   movq(sum, Address(out, offset, Address::times_4,  0));
6641   rorq(sum, 32);
6642   if (UseBMI2Instructions) {
6643     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
6644   }
6645   else {
6646     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
6647   }
6648   // Store back in big endian from little endian
6649   rorq(sum, 0x20);
6650   movq(Address(out, offset, Address::times_4,  0), sum);
6651 
6652   jmp(L_first_loop);
6653   bind(L_first_loop_exit);
6654 }
6655 
6656 /**
6657  * Code for BigInteger::mulAdd() intrinsic
6658  *
6659  * rdi: out
6660  * rsi: in
6661  * r11: offs (out.length - offset)
6662  * rcx: len
6663  * r8:  k
6664  * r12: tmp1
6665  * r13: tmp2
6666  * r14: tmp3
6667  * r15: tmp4
6668  * rbx: tmp5
6669  * Multiply the in[] by word k and add to out[], return the carry in rax
6670  */
6671 void MacroAssembler::mul_add(Register out, Register in, Register offs,
6672    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
6673    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
6674 
6675   Label L_carry, L_last_in, L_done;
6676 
6677 // carry = 0;
6678 // for (int j=len-1; j >= 0; j--) {
6679 //    long product = (in[j] & LONG_MASK) * kLong +
6680 //                   (out[offs] & LONG_MASK) + carry;
6681 //    out[offs--] = (int)product;
6682 //    carry = product >>> 32;
6683 // }
6684 //
6685   push(tmp1);
6686   push(tmp2);
6687   push(tmp3);
6688   push(tmp4);
6689   push(tmp5);
6690 
6691   Register op2 = tmp2;
6692   const Register sum = tmp3;
6693   const Register op1 = tmp4;
6694   const Register carry =  tmp5;
6695 
6696   if (UseBMI2Instructions) {
6697     op2 = rdxReg;
6698     movl(op2, k);
6699   }
6700   else {
6701     movl(op2, k);
6702   }
6703 
6704   xorq(carry, carry);
6705 
6706   //First loop
6707 
6708   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
6709   //The carry is in tmp5
6710   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
6711 
6712   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
6713   decrementl(len);
6714   jccb(Assembler::negative, L_carry);
6715   decrementl(len);
6716   jccb(Assembler::negative, L_last_in);
6717 
6718   movq(op1, Address(in, len, Address::times_4,  0));
6719   rorq(op1, 32);
6720 
6721   subl(offs, 2);
6722   movq(sum, Address(out, offs, Address::times_4,  0));
6723   rorq(sum, 32);
6724 
6725   if (UseBMI2Instructions) {
6726     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
6727   }
6728   else {
6729     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
6730   }
6731 
6732   // Store back in big endian from little endian
6733   rorq(sum, 0x20);
6734   movq(Address(out, offs, Address::times_4,  0), sum);
6735 
6736   testl(len, len);
6737   jccb(Assembler::zero, L_carry);
6738 
6739   //Multiply the last in[] entry, if any
6740   bind(L_last_in);
6741   movl(op1, Address(in, 0));
6742   movl(sum, Address(out, offs, Address::times_4,  -4));
6743 
6744   movl(raxReg, k);
6745   mull(op1); //tmp4 * eax -> edx:eax
6746   addl(sum, carry);
6747   adcl(rdxReg, 0);
6748   addl(sum, raxReg);
6749   adcl(rdxReg, 0);
6750   movl(carry, rdxReg);
6751 
6752   movl(Address(out, offs, Address::times_4,  -4), sum);
6753 
6754   bind(L_carry);
6755   //return tmp5/carry as carry in rax
6756   movl(rax, carry);
6757 
6758   bind(L_done);
6759   pop(tmp5);
6760   pop(tmp4);
6761   pop(tmp3);
6762   pop(tmp2);
6763   pop(tmp1);
6764 }
6765 #endif
6766 
6767 /**
6768  * Emits code to update CRC-32 with a byte value according to constants in table
6769  *
6770  * @param [in,out]crc   Register containing the crc.
6771  * @param [in]val       Register containing the byte to fold into the CRC.
6772  * @param [in]table     Register containing the table of crc constants.
6773  *
6774  * uint32_t crc;
6775  * val = crc_table[(val ^ crc) & 0xFF];
6776  * crc = val ^ (crc >> 8);
6777  *
6778  */
6779 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
6780   xorl(val, crc);
6781   andl(val, 0xFF);
6782   shrl(crc, 8); // unsigned shift
6783   xorl(crc, Address(table, val, Address::times_4, 0));
6784 }
6785 
6786 /**
6787  * Fold 128-bit data chunk
6788  */
6789 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
6790   if (UseAVX > 0) {
6791     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
6792     vpclmulldq(xcrc, xK, xcrc); // [63:0]
6793     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
6794     pxor(xcrc, xtmp);
6795   } else {
6796     movdqa(xtmp, xcrc);
6797     pclmulhdq(xtmp, xK);   // [123:64]
6798     pclmulldq(xcrc, xK);   // [63:0]
6799     pxor(xcrc, xtmp);
6800     movdqu(xtmp, Address(buf, offset));
6801     pxor(xcrc, xtmp);
6802   }
6803 }
6804 
6805 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
6806   if (UseAVX > 0) {
6807     vpclmulhdq(xtmp, xK, xcrc);
6808     vpclmulldq(xcrc, xK, xcrc);
6809     pxor(xcrc, xbuf);
6810     pxor(xcrc, xtmp);
6811   } else {
6812     movdqa(xtmp, xcrc);
6813     pclmulhdq(xtmp, xK);
6814     pclmulldq(xcrc, xK);
6815     pxor(xcrc, xbuf);
6816     pxor(xcrc, xtmp);
6817   }
6818 }
6819 
6820 /**
6821  * 8-bit folds to compute 32-bit CRC
6822  *
6823  * uint64_t xcrc;
6824  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
6825  */
6826 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
6827   movdl(tmp, xcrc);
6828   andl(tmp, 0xFF);
6829   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
6830   psrldq(xcrc, 1); // unsigned shift one byte
6831   pxor(xcrc, xtmp);
6832 }
6833 
6834 /**
6835  * uint32_t crc;
6836  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
6837  */
6838 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
6839   movl(tmp, crc);
6840   andl(tmp, 0xFF);
6841   shrl(crc, 8);
6842   xorl(crc, Address(table, tmp, Address::times_4, 0));
6843 }
6844 
6845 /**
6846  * @param crc   register containing existing CRC (32-bit)
6847  * @param buf   register pointing to input byte buffer (byte*)
6848  * @param len   register containing number of bytes
6849  * @param table register that will contain address of CRC table
6850  * @param tmp   scratch register
6851  */
6852 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
6853   assert_different_registers(crc, buf, len, table, tmp, rax);
6854 
6855   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
6856   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
6857 
6858   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
6859   // context for the registers used, where all instructions below are using 128-bit mode
6860   // On EVEX without VL and BW, these instructions will all be AVX.
6861   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
6862   notl(crc); // ~crc
6863   cmpl(len, 16);
6864   jcc(Assembler::less, L_tail);
6865 
6866   // Align buffer to 16 bytes
6867   movl(tmp, buf);
6868   andl(tmp, 0xF);
6869   jccb(Assembler::zero, L_aligned);
6870   subl(tmp,  16);
6871   addl(len, tmp);
6872 
6873   align(4);
6874   BIND(L_align_loop);
6875   movsbl(rax, Address(buf, 0)); // load byte with sign extension
6876   update_byte_crc32(crc, rax, table);
6877   increment(buf);
6878   incrementl(tmp);
6879   jccb(Assembler::less, L_align_loop);
6880 
6881   BIND(L_aligned);
6882   movl(tmp, len); // save
6883   shrl(len, 4);
6884   jcc(Assembler::zero, L_tail_restore);
6885 
6886   // Fold crc into first bytes of vector
6887   movdqa(xmm1, Address(buf, 0));
6888   movdl(rax, xmm1);
6889   xorl(crc, rax);
6890   if (VM_Version::supports_sse4_1()) {
6891     pinsrd(xmm1, crc, 0);
6892   } else {
6893     pinsrw(xmm1, crc, 0);
6894     shrl(crc, 16);
6895     pinsrw(xmm1, crc, 1);
6896   }
6897   addptr(buf, 16);
6898   subl(len, 4); // len > 0
6899   jcc(Assembler::less, L_fold_tail);
6900 
6901   movdqa(xmm2, Address(buf,  0));
6902   movdqa(xmm3, Address(buf, 16));
6903   movdqa(xmm4, Address(buf, 32));
6904   addptr(buf, 48);
6905   subl(len, 3);
6906   jcc(Assembler::lessEqual, L_fold_512b);
6907 
6908   // Fold total 512 bits of polynomial on each iteration,
6909   // 128 bits per each of 4 parallel streams.
6910   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
6911 
6912   align32();
6913   BIND(L_fold_512b_loop);
6914   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
6915   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
6916   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
6917   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
6918   addptr(buf, 64);
6919   subl(len, 4);
6920   jcc(Assembler::greater, L_fold_512b_loop);
6921 
6922   // Fold 512 bits to 128 bits.
6923   BIND(L_fold_512b);
6924   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
6925   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
6926   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
6927   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
6928 
6929   // Fold the rest of 128 bits data chunks
6930   BIND(L_fold_tail);
6931   addl(len, 3);
6932   jccb(Assembler::lessEqual, L_fold_128b);
6933   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
6934 
6935   BIND(L_fold_tail_loop);
6936   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
6937   addptr(buf, 16);
6938   decrementl(len);
6939   jccb(Assembler::greater, L_fold_tail_loop);
6940 
6941   // Fold 128 bits in xmm1 down into 32 bits in crc register.
6942   BIND(L_fold_128b);
6943   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
6944   if (UseAVX > 0) {
6945     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
6946     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
6947     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
6948   } else {
6949     movdqa(xmm2, xmm0);
6950     pclmulqdq(xmm2, xmm1, 0x1);
6951     movdqa(xmm3, xmm0);
6952     pand(xmm3, xmm2);
6953     pclmulqdq(xmm0, xmm3, 0x1);
6954   }
6955   psrldq(xmm1, 8);
6956   psrldq(xmm2, 4);
6957   pxor(xmm0, xmm1);
6958   pxor(xmm0, xmm2);
6959 
6960   // 8 8-bit folds to compute 32-bit CRC.
6961   for (int j = 0; j < 4; j++) {
6962     fold_8bit_crc32(xmm0, table, xmm1, rax);
6963   }
6964   movdl(crc, xmm0); // mov 32 bits to general register
6965   for (int j = 0; j < 4; j++) {
6966     fold_8bit_crc32(crc, table, rax);
6967   }
6968 
6969   BIND(L_tail_restore);
6970   movl(len, tmp); // restore
6971   BIND(L_tail);
6972   andl(len, 0xf);
6973   jccb(Assembler::zero, L_exit);
6974 
6975   // Fold the rest of bytes
6976   align(4);
6977   BIND(L_tail_loop);
6978   movsbl(rax, Address(buf, 0)); // load byte with sign extension
6979   update_byte_crc32(crc, rax, table);
6980   increment(buf);
6981   decrementl(len);
6982   jccb(Assembler::greater, L_tail_loop);
6983 
6984   BIND(L_exit);
6985   notl(crc); // ~c
6986 }
6987 
6988 #ifdef _LP64
6989 // Helper function for AVX 512 CRC32
6990 // Fold 512-bit data chunks
6991 void MacroAssembler::fold512bit_crc32_avx512(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf,
6992                                              Register pos, int offset) {
6993   evmovdquq(xmm3, Address(buf, pos, Address::times_1, offset), Assembler::AVX_512bit);
6994   evpclmulqdq(xtmp, xcrc, xK, 0x10, Assembler::AVX_512bit); // [123:64]
6995   evpclmulqdq(xmm2, xcrc, xK, 0x01, Assembler::AVX_512bit); // [63:0]
6996   evpxorq(xcrc, xtmp, xmm2, Assembler::AVX_512bit /* vector_len */);
6997   evpxorq(xcrc, xcrc, xmm3, Assembler::AVX_512bit /* vector_len */);
6998 }
6999 
7000 // Helper function for AVX 512 CRC32
7001 // Compute CRC32 for < 256B buffers
7002 void MacroAssembler::kernel_crc32_avx512_256B(Register crc, Register buf, Register len, Register key, Register pos,
7003                                               Register tmp1, Register tmp2, Label& L_barrett, Label& L_16B_reduction_loop,
7004                                               Label& L_get_last_two_xmms, Label& L_128_done, Label& L_cleanup) {
7005 
7006   Label L_less_than_32, L_exact_16_left, L_less_than_16_left;
7007   Label L_less_than_8_left, L_less_than_4_left, L_less_than_2_left, L_zero_left;
7008   Label L_only_less_than_4, L_only_less_than_3, L_only_less_than_2;
7009 
7010   // check if there is enough buffer to be able to fold 16B at a time
7011   cmpl(len, 32);
7012   jcc(Assembler::less, L_less_than_32);
7013 
7014   // if there is, load the constants
7015   movdqu(xmm10, Address(key, 1 * 16));    //rk1 and rk2 in xmm10
7016   movdl(xmm0, crc);                        // get the initial crc value
7017   movdqu(xmm7, Address(buf, pos, Address::times_1, 0 * 16)); //load the plaintext
7018   pxor(xmm7, xmm0);
7019 
7020   // update the buffer pointer
7021   addl(pos, 16);
7022   //update the counter.subtract 32 instead of 16 to save one instruction from the loop
7023   subl(len, 32);
7024   jmp(L_16B_reduction_loop);
7025 
7026   bind(L_less_than_32);
7027   //mov initial crc to the return value. this is necessary for zero - length buffers.
7028   movl(rax, crc);
7029   testl(len, len);
7030   jcc(Assembler::equal, L_cleanup);
7031 
7032   movdl(xmm0, crc);                        //get the initial crc value
7033 
7034   cmpl(len, 16);
7035   jcc(Assembler::equal, L_exact_16_left);
7036   jcc(Assembler::less, L_less_than_16_left);
7037 
7038   movdqu(xmm7, Address(buf, pos, Address::times_1, 0 * 16)); //load the plaintext
7039   pxor(xmm7, xmm0);                       //xor the initial crc value
7040   addl(pos, 16);
7041   subl(len, 16);
7042   movdqu(xmm10, Address(key, 1 * 16));    // rk1 and rk2 in xmm10
7043   jmp(L_get_last_two_xmms);
7044 
7045   bind(L_less_than_16_left);
7046   //use stack space to load data less than 16 bytes, zero - out the 16B in memory first.
7047   pxor(xmm1, xmm1);
7048   movptr(tmp1, rsp);
7049   movdqu(Address(tmp1, 0 * 16), xmm1);
7050 
7051   cmpl(len, 4);
7052   jcc(Assembler::less, L_only_less_than_4);
7053 
7054   //backup the counter value
7055   movl(tmp2, len);
7056   cmpl(len, 8);
7057   jcc(Assembler::less, L_less_than_8_left);
7058 
7059   //load 8 Bytes
7060   movq(rax, Address(buf, pos, Address::times_1, 0 * 16));
7061   movq(Address(tmp1, 0 * 16), rax);
7062   addptr(tmp1, 8);
7063   subl(len, 8);
7064   addl(pos, 8);
7065 
7066   bind(L_less_than_8_left);
7067   cmpl(len, 4);
7068   jcc(Assembler::less, L_less_than_4_left);
7069 
7070   //load 4 Bytes
7071   movl(rax, Address(buf, pos, Address::times_1, 0));
7072   movl(Address(tmp1, 0 * 16), rax);
7073   addptr(tmp1, 4);
7074   subl(len, 4);
7075   addl(pos, 4);
7076 
7077   bind(L_less_than_4_left);
7078   cmpl(len, 2);
7079   jcc(Assembler::less, L_less_than_2_left);
7080 
7081   // load 2 Bytes
7082   movw(rax, Address(buf, pos, Address::times_1, 0));
7083   movl(Address(tmp1, 0 * 16), rax);
7084   addptr(tmp1, 2);
7085   subl(len, 2);
7086   addl(pos, 2);
7087 
7088   bind(L_less_than_2_left);
7089   cmpl(len, 1);
7090   jcc(Assembler::less, L_zero_left);
7091 
7092   // load 1 Byte
7093   movb(rax, Address(buf, pos, Address::times_1, 0));
7094   movb(Address(tmp1, 0 * 16), rax);
7095 
7096   bind(L_zero_left);
7097   movdqu(xmm7, Address(rsp, 0));
7098   pxor(xmm7, xmm0);                       //xor the initial crc value
7099 
7100   lea(rax, ExternalAddress(StubRoutines::x86::shuf_table_crc32_avx512_addr()));
7101   movdqu(xmm0, Address(rax, tmp2));
7102   pshufb(xmm7, xmm0);
7103   jmp(L_128_done);
7104 
7105   bind(L_exact_16_left);
7106   movdqu(xmm7, Address(buf, pos, Address::times_1, 0));
7107   pxor(xmm7, xmm0);                       //xor the initial crc value
7108   jmp(L_128_done);
7109 
7110   bind(L_only_less_than_4);
7111   cmpl(len, 3);
7112   jcc(Assembler::less, L_only_less_than_3);
7113 
7114   // load 3 Bytes
7115   movb(rax, Address(buf, pos, Address::times_1, 0));
7116   movb(Address(tmp1, 0), rax);
7117 
7118   movb(rax, Address(buf, pos, Address::times_1, 1));
7119   movb(Address(tmp1, 1), rax);
7120 
7121   movb(rax, Address(buf, pos, Address::times_1, 2));
7122   movb(Address(tmp1, 2), rax);
7123 
7124   movdqu(xmm7, Address(rsp, 0));
7125   pxor(xmm7, xmm0);                     //xor the initial crc value
7126 
7127   pslldq(xmm7, 0x5);
7128   jmp(L_barrett);
7129   bind(L_only_less_than_3);
7130   cmpl(len, 2);
7131   jcc(Assembler::less, L_only_less_than_2);
7132 
7133   // load 2 Bytes
7134   movb(rax, Address(buf, pos, Address::times_1, 0));
7135   movb(Address(tmp1, 0), rax);
7136 
7137   movb(rax, Address(buf, pos, Address::times_1, 1));
7138   movb(Address(tmp1, 1), rax);
7139 
7140   movdqu(xmm7, Address(rsp, 0));
7141   pxor(xmm7, xmm0);                     //xor the initial crc value
7142 
7143   pslldq(xmm7, 0x6);
7144   jmp(L_barrett);
7145 
7146   bind(L_only_less_than_2);
7147   //load 1 Byte
7148   movb(rax, Address(buf, pos, Address::times_1, 0));
7149   movb(Address(tmp1, 0), rax);
7150 
7151   movdqu(xmm7, Address(rsp, 0));
7152   pxor(xmm7, xmm0);                     //xor the initial crc value
7153 
7154   pslldq(xmm7, 0x7);
7155 }
7156 
7157 /**
7158 * Compute CRC32 using AVX512 instructions
7159 * param crc   register containing existing CRC (32-bit)
7160 * param buf   register pointing to input byte buffer (byte*)
7161 * param len   register containing number of bytes
7162 * param tmp1  scratch register
7163 * param tmp2  scratch register
7164 * return rax  result register
7165 */
7166 void MacroAssembler::kernel_crc32_avx512(Register crc, Register buf, Register len, Register key, Register tmp1, Register tmp2) {
7167   assert_different_registers(crc, buf, len, key, tmp1, tmp2, rax);
7168 
7169   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
7170   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
7171   Label L_less_than_256, L_fold_128_B_loop, L_fold_256_B_loop;
7172   Label L_fold_128_B_register, L_final_reduction_for_128, L_16B_reduction_loop;
7173   Label L_128_done, L_get_last_two_xmms, L_barrett, L_cleanup;
7174 
7175   const Register pos = r12;
7176   push(r12);
7177   subptr(rsp, 16 * 2 + 8);
7178 
7179   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
7180   // context for the registers used, where all instructions below are using 128-bit mode
7181   // On EVEX without VL and BW, these instructions will all be AVX.
7182   lea(key, ExternalAddress(StubRoutines::x86::crc_table_avx512_addr()));
7183   notl(crc);
7184   movl(pos, 0);
7185 
7186   // check if smaller than 256B
7187   cmpl(len, 256);
7188   jcc(Assembler::less, L_less_than_256);
7189 
7190   // load the initial crc value
7191   movdl(xmm10, crc);
7192 
7193   // receive the initial 64B data, xor the initial crc value
7194   evmovdquq(xmm0, Address(buf, pos, Address::times_1, 0 * 64), Assembler::AVX_512bit);
7195   evmovdquq(xmm4, Address(buf, pos, Address::times_1, 1 * 64), Assembler::AVX_512bit);
7196   evpxorq(xmm0, xmm0, xmm10, Assembler::AVX_512bit);
7197   evbroadcasti32x4(xmm10, Address(key, 2 * 16), Assembler::AVX_512bit); //zmm10 has rk3 and rk4
7198 
7199   subl(len, 256);
7200   cmpl(len, 256);
7201   jcc(Assembler::less, L_fold_128_B_loop);
7202 
7203   evmovdquq(xmm7, Address(buf, pos, Address::times_1, 2 * 64), Assembler::AVX_512bit);
7204   evmovdquq(xmm8, Address(buf, pos, Address::times_1, 3 * 64), Assembler::AVX_512bit);
7205   evbroadcasti32x4(xmm16, Address(key, 0 * 16), Assembler::AVX_512bit); //zmm16 has rk-1 and rk-2
7206   subl(len, 256);
7207 
7208   bind(L_fold_256_B_loop);
7209   addl(pos, 256);
7210   fold512bit_crc32_avx512(xmm0, xmm16, xmm1, buf, pos, 0 * 64);
7211   fold512bit_crc32_avx512(xmm4, xmm16, xmm1, buf, pos, 1 * 64);
7212   fold512bit_crc32_avx512(xmm7, xmm16, xmm1, buf, pos, 2 * 64);
7213   fold512bit_crc32_avx512(xmm8, xmm16, xmm1, buf, pos, 3 * 64);
7214 
7215   subl(len, 256);
7216   jcc(Assembler::greaterEqual, L_fold_256_B_loop);
7217 
7218   // Fold 256 into 128
7219   addl(pos, 256);
7220   evpclmulqdq(xmm1, xmm0, xmm10, 0x01, Assembler::AVX_512bit);
7221   evpclmulqdq(xmm2, xmm0, xmm10, 0x10, Assembler::AVX_512bit);
7222   vpternlogq(xmm7, 0x96, xmm1, xmm2, Assembler::AVX_512bit); // xor ABC
7223 
7224   evpclmulqdq(xmm5, xmm4, xmm10, 0x01, Assembler::AVX_512bit);
7225   evpclmulqdq(xmm6, xmm4, xmm10, 0x10, Assembler::AVX_512bit);
7226   vpternlogq(xmm8, 0x96, xmm5, xmm6, Assembler::AVX_512bit); // xor ABC
7227 
7228   evmovdquq(xmm0, xmm7, Assembler::AVX_512bit);
7229   evmovdquq(xmm4, xmm8, Assembler::AVX_512bit);
7230 
7231   addl(len, 128);
7232   jmp(L_fold_128_B_register);
7233 
7234   // at this section of the code, there is 128 * x + y(0 <= y<128) bytes of buffer.The fold_128_B_loop
7235   // loop will fold 128B at a time until we have 128 + y Bytes of buffer
7236 
7237   // fold 128B at a time.This section of the code folds 8 xmm registers in parallel
7238   bind(L_fold_128_B_loop);
7239   addl(pos, 128);
7240   fold512bit_crc32_avx512(xmm0, xmm10, xmm1, buf, pos, 0 * 64);
7241   fold512bit_crc32_avx512(xmm4, xmm10, xmm1, buf, pos, 1 * 64);
7242 
7243   subl(len, 128);
7244   jcc(Assembler::greaterEqual, L_fold_128_B_loop);
7245 
7246   addl(pos, 128);
7247 
7248   // at this point, the buffer pointer is pointing at the last y Bytes of the buffer, where 0 <= y < 128
7249   // the 128B of folded data is in 8 of the xmm registers : xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7
7250   bind(L_fold_128_B_register);
7251   evmovdquq(xmm16, Address(key, 5 * 16), Assembler::AVX_512bit); // multiply by rk9-rk16
7252   evmovdquq(xmm11, Address(key, 9 * 16), Assembler::AVX_512bit); // multiply by rk17-rk20, rk1,rk2, 0,0
7253   evpclmulqdq(xmm1, xmm0, xmm16, 0x01, Assembler::AVX_512bit);
7254   evpclmulqdq(xmm2, xmm0, xmm16, 0x10, Assembler::AVX_512bit);
7255   // save last that has no multiplicand
7256   vextracti64x2(xmm7, xmm4, 3);
7257 
7258   evpclmulqdq(xmm5, xmm4, xmm11, 0x01, Assembler::AVX_512bit);
7259   evpclmulqdq(xmm6, xmm4, xmm11, 0x10, Assembler::AVX_512bit);
7260   // Needed later in reduction loop
7261   movdqu(xmm10, Address(key, 1 * 16));
7262   vpternlogq(xmm1, 0x96, xmm2, xmm5, Assembler::AVX_512bit); // xor ABC
7263   vpternlogq(xmm1, 0x96, xmm6, xmm7, Assembler::AVX_512bit); // xor ABC
7264 
7265   // Swap 1,0,3,2 - 01 00 11 10
7266   evshufi64x2(xmm8, xmm1, xmm1, 0x4e, Assembler::AVX_512bit);
7267   evpxorq(xmm8, xmm8, xmm1, Assembler::AVX_256bit);
7268   vextracti128(xmm5, xmm8, 1);
7269   evpxorq(xmm7, xmm5, xmm8, Assembler::AVX_128bit);
7270 
7271   // instead of 128, we add 128 - 16 to the loop counter to save 1 instruction from the loop
7272   // instead of a cmp instruction, we use the negative flag with the jl instruction
7273   addl(len, 128 - 16);
7274   jcc(Assembler::less, L_final_reduction_for_128);
7275 
7276   bind(L_16B_reduction_loop);
7277   vpclmulqdq(xmm8, xmm7, xmm10, 0x1);
7278   vpclmulqdq(xmm7, xmm7, xmm10, 0x10);
7279   vpxor(xmm7, xmm7, xmm8, Assembler::AVX_128bit);
7280   movdqu(xmm0, Address(buf, pos, Address::times_1, 0 * 16));
7281   vpxor(xmm7, xmm7, xmm0, Assembler::AVX_128bit);
7282   addl(pos, 16);
7283   subl(len, 16);
7284   jcc(Assembler::greaterEqual, L_16B_reduction_loop);
7285 
7286   bind(L_final_reduction_for_128);
7287   addl(len, 16);
7288   jcc(Assembler::equal, L_128_done);
7289 
7290   bind(L_get_last_two_xmms);
7291   movdqu(xmm2, xmm7);
7292   addl(pos, len);
7293   movdqu(xmm1, Address(buf, pos, Address::times_1, -16));
7294   subl(pos, len);
7295 
7296   // get rid of the extra data that was loaded before
7297   // load the shift constant
7298   lea(rax, ExternalAddress(StubRoutines::x86::shuf_table_crc32_avx512_addr()));
7299   movdqu(xmm0, Address(rax, len));
7300   addl(rax, len);
7301 
7302   vpshufb(xmm7, xmm7, xmm0, Assembler::AVX_128bit);
7303   //Change mask to 512
7304   vpxor(xmm0, xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_avx512_addr() + 2 * 16), Assembler::AVX_128bit, tmp2);
7305   vpshufb(xmm2, xmm2, xmm0, Assembler::AVX_128bit);
7306 
7307   blendvpb(xmm2, xmm2, xmm1, xmm0, Assembler::AVX_128bit);
7308   vpclmulqdq(xmm8, xmm7, xmm10, 0x1);
7309   vpclmulqdq(xmm7, xmm7, xmm10, 0x10);
7310   vpxor(xmm7, xmm7, xmm8, Assembler::AVX_128bit);
7311   vpxor(xmm7, xmm7, xmm2, Assembler::AVX_128bit);
7312 
7313   bind(L_128_done);
7314   // compute crc of a 128-bit value
7315   movdqu(xmm10, Address(key, 3 * 16));
7316   movdqu(xmm0, xmm7);
7317 
7318   // 64b fold
7319   vpclmulqdq(xmm7, xmm7, xmm10, 0x0);
7320   vpsrldq(xmm0, xmm0, 0x8, Assembler::AVX_128bit);
7321   vpxor(xmm7, xmm7, xmm0, Assembler::AVX_128bit);
7322 
7323   // 32b fold
7324   movdqu(xmm0, xmm7);
7325   vpslldq(xmm7, xmm7, 0x4, Assembler::AVX_128bit);
7326   vpclmulqdq(xmm7, xmm7, xmm10, 0x10);
7327   vpxor(xmm7, xmm7, xmm0, Assembler::AVX_128bit);
7328   jmp(L_barrett);
7329 
7330   bind(L_less_than_256);
7331   kernel_crc32_avx512_256B(crc, buf, len, key, pos, tmp1, tmp2, L_barrett, L_16B_reduction_loop, L_get_last_two_xmms, L_128_done, L_cleanup);
7332 
7333   //barrett reduction
7334   bind(L_barrett);
7335   vpand(xmm7, xmm7, ExternalAddress(StubRoutines::x86::crc_by128_masks_avx512_addr() + 1 * 16), Assembler::AVX_128bit, tmp2);
7336   movdqu(xmm1, xmm7);
7337   movdqu(xmm2, xmm7);
7338   movdqu(xmm10, Address(key, 4 * 16));
7339 
7340   pclmulqdq(xmm7, xmm10, 0x0);
7341   pxor(xmm7, xmm2);
7342   vpand(xmm7, xmm7, ExternalAddress(StubRoutines::x86::crc_by128_masks_avx512_addr()), Assembler::AVX_128bit, tmp2);
7343   movdqu(xmm2, xmm7);
7344   pclmulqdq(xmm7, xmm10, 0x10);
7345   pxor(xmm7, xmm2);
7346   pxor(xmm7, xmm1);
7347   pextrd(crc, xmm7, 2);
7348 
7349   bind(L_cleanup);
7350   notl(crc); // ~c
7351   addptr(rsp, 16 * 2 + 8);
7352   pop(r12);
7353 }
7354 
7355 // S. Gueron / Information Processing Letters 112 (2012) 184
7356 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
7357 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
7358 // Output: the 64-bit carry-less product of B * CONST
7359 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
7360                                      Register tmp1, Register tmp2, Register tmp3) {
7361   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
7362   if (n > 0) {
7363     addq(tmp3, n * 256 * 8);
7364   }
7365   //    Q1 = TABLEExt[n][B & 0xFF];
7366   movl(tmp1, in);
7367   andl(tmp1, 0x000000FF);
7368   shll(tmp1, 3);
7369   addq(tmp1, tmp3);
7370   movq(tmp1, Address(tmp1, 0));
7371 
7372   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
7373   movl(tmp2, in);
7374   shrl(tmp2, 8);
7375   andl(tmp2, 0x000000FF);
7376   shll(tmp2, 3);
7377   addq(tmp2, tmp3);
7378   movq(tmp2, Address(tmp2, 0));
7379 
7380   shlq(tmp2, 8);
7381   xorq(tmp1, tmp2);
7382 
7383   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
7384   movl(tmp2, in);
7385   shrl(tmp2, 16);
7386   andl(tmp2, 0x000000FF);
7387   shll(tmp2, 3);
7388   addq(tmp2, tmp3);
7389   movq(tmp2, Address(tmp2, 0));
7390 
7391   shlq(tmp2, 16);
7392   xorq(tmp1, tmp2);
7393 
7394   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
7395   shrl(in, 24);
7396   andl(in, 0x000000FF);
7397   shll(in, 3);
7398   addq(in, tmp3);
7399   movq(in, Address(in, 0));
7400 
7401   shlq(in, 24);
7402   xorq(in, tmp1);
7403   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
7404 }
7405 
7406 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
7407                                       Register in_out,
7408                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
7409                                       XMMRegister w_xtmp2,
7410                                       Register tmp1,
7411                                       Register n_tmp2, Register n_tmp3) {
7412   if (is_pclmulqdq_supported) {
7413     movdl(w_xtmp1, in_out); // modified blindly
7414 
7415     movl(tmp1, const_or_pre_comp_const_index);
7416     movdl(w_xtmp2, tmp1);
7417     pclmulqdq(w_xtmp1, w_xtmp2, 0);
7418 
7419     movdq(in_out, w_xtmp1);
7420   } else {
7421     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
7422   }
7423 }
7424 
7425 // Recombination Alternative 2: No bit-reflections
7426 // T1 = (CRC_A * U1) << 1
7427 // T2 = (CRC_B * U2) << 1
7428 // C1 = T1 >> 32
7429 // C2 = T2 >> 32
7430 // T1 = T1 & 0xFFFFFFFF
7431 // T2 = T2 & 0xFFFFFFFF
7432 // T1 = CRC32(0, T1)
7433 // T2 = CRC32(0, T2)
7434 // C1 = C1 ^ T1
7435 // C2 = C2 ^ T2
7436 // CRC = C1 ^ C2 ^ CRC_C
7437 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,
7438                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
7439                                      Register tmp1, Register tmp2,
7440                                      Register n_tmp3) {
7441   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
7442   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
7443   shlq(in_out, 1);
7444   movl(tmp1, in_out);
7445   shrq(in_out, 32);
7446   xorl(tmp2, tmp2);
7447   crc32(tmp2, tmp1, 4);
7448   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
7449   shlq(in1, 1);
7450   movl(tmp1, in1);
7451   shrq(in1, 32);
7452   xorl(tmp2, tmp2);
7453   crc32(tmp2, tmp1, 4);
7454   xorl(in1, tmp2);
7455   xorl(in_out, in1);
7456   xorl(in_out, in2);
7457 }
7458 
7459 // Set N to predefined value
7460 // Subtract from a lenght of a buffer
7461 // execute in a loop:
7462 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
7463 // for i = 1 to N do
7464 //  CRC_A = CRC32(CRC_A, A[i])
7465 //  CRC_B = CRC32(CRC_B, B[i])
7466 //  CRC_C = CRC32(CRC_C, C[i])
7467 // end for
7468 // Recombine
7469 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,
7470                                        Register in_out1, Register in_out2, Register in_out3,
7471                                        Register tmp1, Register tmp2, Register tmp3,
7472                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
7473                                        Register tmp4, Register tmp5,
7474                                        Register n_tmp6) {
7475   Label L_processPartitions;
7476   Label L_processPartition;
7477   Label L_exit;
7478 
7479   bind(L_processPartitions);
7480   cmpl(in_out1, 3 * size);
7481   jcc(Assembler::less, L_exit);
7482     xorl(tmp1, tmp1);
7483     xorl(tmp2, tmp2);
7484     movq(tmp3, in_out2);
7485     addq(tmp3, size);
7486 
7487     bind(L_processPartition);
7488       crc32(in_out3, Address(in_out2, 0), 8);
7489       crc32(tmp1, Address(in_out2, size), 8);
7490       crc32(tmp2, Address(in_out2, size * 2), 8);
7491       addq(in_out2, 8);
7492       cmpq(in_out2, tmp3);
7493       jcc(Assembler::less, L_processPartition);
7494     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
7495             w_xtmp1, w_xtmp2, w_xtmp3,
7496             tmp4, tmp5,
7497             n_tmp6);
7498     addq(in_out2, 2 * size);
7499     subl(in_out1, 3 * size);
7500     jmp(L_processPartitions);
7501 
7502   bind(L_exit);
7503 }
7504 #else
7505 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
7506                                      Register tmp1, Register tmp2, Register tmp3,
7507                                      XMMRegister xtmp1, XMMRegister xtmp2) {
7508   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
7509   if (n > 0) {
7510     addl(tmp3, n * 256 * 8);
7511   }
7512   //    Q1 = TABLEExt[n][B & 0xFF];
7513   movl(tmp1, in_out);
7514   andl(tmp1, 0x000000FF);
7515   shll(tmp1, 3);
7516   addl(tmp1, tmp3);
7517   movq(xtmp1, Address(tmp1, 0));
7518 
7519   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
7520   movl(tmp2, in_out);
7521   shrl(tmp2, 8);
7522   andl(tmp2, 0x000000FF);
7523   shll(tmp2, 3);
7524   addl(tmp2, tmp3);
7525   movq(xtmp2, Address(tmp2, 0));
7526 
7527   psllq(xtmp2, 8);
7528   pxor(xtmp1, xtmp2);
7529 
7530   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
7531   movl(tmp2, in_out);
7532   shrl(tmp2, 16);
7533   andl(tmp2, 0x000000FF);
7534   shll(tmp2, 3);
7535   addl(tmp2, tmp3);
7536   movq(xtmp2, Address(tmp2, 0));
7537 
7538   psllq(xtmp2, 16);
7539   pxor(xtmp1, xtmp2);
7540 
7541   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
7542   shrl(in_out, 24);
7543   andl(in_out, 0x000000FF);
7544   shll(in_out, 3);
7545   addl(in_out, tmp3);
7546   movq(xtmp2, Address(in_out, 0));
7547 
7548   psllq(xtmp2, 24);
7549   pxor(xtmp1, xtmp2); // Result in CXMM
7550   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
7551 }
7552 
7553 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
7554                                       Register in_out,
7555                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
7556                                       XMMRegister w_xtmp2,
7557                                       Register tmp1,
7558                                       Register n_tmp2, Register n_tmp3) {
7559   if (is_pclmulqdq_supported) {
7560     movdl(w_xtmp1, in_out);
7561 
7562     movl(tmp1, const_or_pre_comp_const_index);
7563     movdl(w_xtmp2, tmp1);
7564     pclmulqdq(w_xtmp1, w_xtmp2, 0);
7565     // Keep result in XMM since GPR is 32 bit in length
7566   } else {
7567     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
7568   }
7569 }
7570 
7571 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,
7572                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
7573                                      Register tmp1, Register tmp2,
7574                                      Register n_tmp3) {
7575   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
7576   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
7577 
7578   psllq(w_xtmp1, 1);
7579   movdl(tmp1, w_xtmp1);
7580   psrlq(w_xtmp1, 32);
7581   movdl(in_out, w_xtmp1);
7582 
7583   xorl(tmp2, tmp2);
7584   crc32(tmp2, tmp1, 4);
7585   xorl(in_out, tmp2);
7586 
7587   psllq(w_xtmp2, 1);
7588   movdl(tmp1, w_xtmp2);
7589   psrlq(w_xtmp2, 32);
7590   movdl(in1, w_xtmp2);
7591 
7592   xorl(tmp2, tmp2);
7593   crc32(tmp2, tmp1, 4);
7594   xorl(in1, tmp2);
7595   xorl(in_out, in1);
7596   xorl(in_out, in2);
7597 }
7598 
7599 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,
7600                                        Register in_out1, Register in_out2, Register in_out3,
7601                                        Register tmp1, Register tmp2, Register tmp3,
7602                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
7603                                        Register tmp4, Register tmp5,
7604                                        Register n_tmp6) {
7605   Label L_processPartitions;
7606   Label L_processPartition;
7607   Label L_exit;
7608 
7609   bind(L_processPartitions);
7610   cmpl(in_out1, 3 * size);
7611   jcc(Assembler::less, L_exit);
7612     xorl(tmp1, tmp1);
7613     xorl(tmp2, tmp2);
7614     movl(tmp3, in_out2);
7615     addl(tmp3, size);
7616 
7617     bind(L_processPartition);
7618       crc32(in_out3, Address(in_out2, 0), 4);
7619       crc32(tmp1, Address(in_out2, size), 4);
7620       crc32(tmp2, Address(in_out2, size*2), 4);
7621       crc32(in_out3, Address(in_out2, 0+4), 4);
7622       crc32(tmp1, Address(in_out2, size+4), 4);
7623       crc32(tmp2, Address(in_out2, size*2+4), 4);
7624       addl(in_out2, 8);
7625       cmpl(in_out2, tmp3);
7626       jcc(Assembler::less, L_processPartition);
7627 
7628         push(tmp3);
7629         push(in_out1);
7630         push(in_out2);
7631         tmp4 = tmp3;
7632         tmp5 = in_out1;
7633         n_tmp6 = in_out2;
7634 
7635       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
7636             w_xtmp1, w_xtmp2, w_xtmp3,
7637             tmp4, tmp5,
7638             n_tmp6);
7639 
7640         pop(in_out2);
7641         pop(in_out1);
7642         pop(tmp3);
7643 
7644     addl(in_out2, 2 * size);
7645     subl(in_out1, 3 * size);
7646     jmp(L_processPartitions);
7647 
7648   bind(L_exit);
7649 }
7650 #endif //LP64
7651 
7652 #ifdef _LP64
7653 // Algorithm 2: Pipelined usage of the CRC32 instruction.
7654 // Input: A buffer I of L bytes.
7655 // Output: the CRC32C value of the buffer.
7656 // Notations:
7657 // Write L = 24N + r, with N = floor (L/24).
7658 // r = L mod 24 (0 <= r < 24).
7659 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
7660 // N quadwords, and R consists of r bytes.
7661 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
7662 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
7663 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
7664 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
7665 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
7666                                           Register tmp1, Register tmp2, Register tmp3,
7667                                           Register tmp4, Register tmp5, Register tmp6,
7668                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
7669                                           bool is_pclmulqdq_supported) {
7670   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
7671   Label L_wordByWord;
7672   Label L_byteByByteProlog;
7673   Label L_byteByByte;
7674   Label L_exit;
7675 
7676   if (is_pclmulqdq_supported ) {
7677     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
7678     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
7679 
7680     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
7681     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
7682 
7683     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
7684     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
7685     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
7686   } else {
7687     const_or_pre_comp_const_index[0] = 1;
7688     const_or_pre_comp_const_index[1] = 0;
7689 
7690     const_or_pre_comp_const_index[2] = 3;
7691     const_or_pre_comp_const_index[3] = 2;
7692 
7693     const_or_pre_comp_const_index[4] = 5;
7694     const_or_pre_comp_const_index[5] = 4;
7695    }
7696   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
7697                     in2, in1, in_out,
7698                     tmp1, tmp2, tmp3,
7699                     w_xtmp1, w_xtmp2, w_xtmp3,
7700                     tmp4, tmp5,
7701                     tmp6);
7702   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
7703                     in2, in1, in_out,
7704                     tmp1, tmp2, tmp3,
7705                     w_xtmp1, w_xtmp2, w_xtmp3,
7706                     tmp4, tmp5,
7707                     tmp6);
7708   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
7709                     in2, in1, in_out,
7710                     tmp1, tmp2, tmp3,
7711                     w_xtmp1, w_xtmp2, w_xtmp3,
7712                     tmp4, tmp5,
7713                     tmp6);
7714   movl(tmp1, in2);
7715   andl(tmp1, 0x00000007);
7716   negl(tmp1);
7717   addl(tmp1, in2);
7718   addq(tmp1, in1);
7719 
7720   BIND(L_wordByWord);
7721   cmpq(in1, tmp1);
7722   jcc(Assembler::greaterEqual, L_byteByByteProlog);
7723     crc32(in_out, Address(in1, 0), 4);
7724     addq(in1, 4);
7725     jmp(L_wordByWord);
7726 
7727   BIND(L_byteByByteProlog);
7728   andl(in2, 0x00000007);
7729   movl(tmp2, 1);
7730 
7731   BIND(L_byteByByte);
7732   cmpl(tmp2, in2);
7733   jccb(Assembler::greater, L_exit);
7734     crc32(in_out, Address(in1, 0), 1);
7735     incq(in1);
7736     incl(tmp2);
7737     jmp(L_byteByByte);
7738 
7739   BIND(L_exit);
7740 }
7741 #else
7742 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
7743                                           Register tmp1, Register  tmp2, Register tmp3,
7744                                           Register tmp4, Register  tmp5, Register tmp6,
7745                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
7746                                           bool is_pclmulqdq_supported) {
7747   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
7748   Label L_wordByWord;
7749   Label L_byteByByteProlog;
7750   Label L_byteByByte;
7751   Label L_exit;
7752 
7753   if (is_pclmulqdq_supported) {
7754     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
7755     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
7756 
7757     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
7758     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
7759 
7760     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
7761     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
7762   } else {
7763     const_or_pre_comp_const_index[0] = 1;
7764     const_or_pre_comp_const_index[1] = 0;
7765 
7766     const_or_pre_comp_const_index[2] = 3;
7767     const_or_pre_comp_const_index[3] = 2;
7768 
7769     const_or_pre_comp_const_index[4] = 5;
7770     const_or_pre_comp_const_index[5] = 4;
7771   }
7772   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
7773                     in2, in1, in_out,
7774                     tmp1, tmp2, tmp3,
7775                     w_xtmp1, w_xtmp2, w_xtmp3,
7776                     tmp4, tmp5,
7777                     tmp6);
7778   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
7779                     in2, in1, in_out,
7780                     tmp1, tmp2, tmp3,
7781                     w_xtmp1, w_xtmp2, w_xtmp3,
7782                     tmp4, tmp5,
7783                     tmp6);
7784   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
7785                     in2, in1, in_out,
7786                     tmp1, tmp2, tmp3,
7787                     w_xtmp1, w_xtmp2, w_xtmp3,
7788                     tmp4, tmp5,
7789                     tmp6);
7790   movl(tmp1, in2);
7791   andl(tmp1, 0x00000007);
7792   negl(tmp1);
7793   addl(tmp1, in2);
7794   addl(tmp1, in1);
7795 
7796   BIND(L_wordByWord);
7797   cmpl(in1, tmp1);
7798   jcc(Assembler::greaterEqual, L_byteByByteProlog);
7799     crc32(in_out, Address(in1,0), 4);
7800     addl(in1, 4);
7801     jmp(L_wordByWord);
7802 
7803   BIND(L_byteByByteProlog);
7804   andl(in2, 0x00000007);
7805   movl(tmp2, 1);
7806 
7807   BIND(L_byteByByte);
7808   cmpl(tmp2, in2);
7809   jccb(Assembler::greater, L_exit);
7810     movb(tmp1, Address(in1, 0));
7811     crc32(in_out, tmp1, 1);
7812     incl(in1);
7813     incl(tmp2);
7814     jmp(L_byteByByte);
7815 
7816   BIND(L_exit);
7817 }
7818 #endif // LP64
7819 #undef BIND
7820 #undef BLOCK_COMMENT
7821 
7822 // Compress char[] array to byte[].
7823 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
7824 //   @IntrinsicCandidate
7825 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
7826 //     for (int i = 0; i < len; i++) {
7827 //       int c = src[srcOff++];
7828 //       if (c >>> 8 != 0) {
7829 //         return 0;
7830 //       }
7831 //       dst[dstOff++] = (byte)c;
7832 //     }
7833 //     return len;
7834 //   }
7835 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
7836   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
7837   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
7838   Register tmp5, Register result, KRegister mask1, KRegister mask2) {
7839   Label copy_chars_loop, return_length, return_zero, done;
7840 
7841   // rsi: src
7842   // rdi: dst
7843   // rdx: len
7844   // rcx: tmp5
7845   // rax: result
7846 
7847   // rsi holds start addr of source char[] to be compressed
7848   // rdi holds start addr of destination byte[]
7849   // rdx holds length
7850 
7851   assert(len != result, "");
7852 
7853   // save length for return
7854   push(len);
7855 
7856   if ((AVX3Threshold == 0) && (UseAVX > 2) && // AVX512
7857     VM_Version::supports_avx512vlbw() &&
7858     VM_Version::supports_bmi2()) {
7859 
7860     Label copy_32_loop, copy_loop_tail, below_threshold;
7861 
7862     // alignment
7863     Label post_alignment;
7864 
7865     // if length of the string is less than 16, handle it in an old fashioned way
7866     testl(len, -32);
7867     jcc(Assembler::zero, below_threshold);
7868 
7869     // First check whether a character is compressable ( <= 0xFF).
7870     // Create mask to test for Unicode chars inside zmm vector
7871     movl(result, 0x00FF);
7872     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
7873 
7874     testl(len, -64);
7875     jcc(Assembler::zero, post_alignment);
7876 
7877     movl(tmp5, dst);
7878     andl(tmp5, (32 - 1));
7879     negl(tmp5);
7880     andl(tmp5, (32 - 1));
7881 
7882     // bail out when there is nothing to be done
7883     testl(tmp5, 0xFFFFFFFF);
7884     jcc(Assembler::zero, post_alignment);
7885 
7886     // ~(~0 << len), where len is the # of remaining elements to process
7887     movl(result, 0xFFFFFFFF);
7888     shlxl(result, result, tmp5);
7889     notl(result);
7890     kmovdl(mask2, result);
7891 
7892     evmovdquw(tmp1Reg, mask2, Address(src, 0), /*merge*/ false, Assembler::AVX_512bit);
7893     evpcmpw(mask1, mask2, tmp1Reg, tmp2Reg, Assembler::le, /*signed*/ false, Assembler::AVX_512bit);
7894     ktestd(mask1, mask2);
7895     jcc(Assembler::carryClear, return_zero);
7896 
7897     evpmovwb(Address(dst, 0), mask2, tmp1Reg, Assembler::AVX_512bit);
7898 
7899     addptr(src, tmp5);
7900     addptr(src, tmp5);
7901     addptr(dst, tmp5);
7902     subl(len, tmp5);
7903 
7904     bind(post_alignment);
7905     // end of alignment
7906 
7907     movl(tmp5, len);
7908     andl(tmp5, (32 - 1));    // tail count (in chars)
7909     andl(len, ~(32 - 1));    // vector count (in chars)
7910     jcc(Assembler::zero, copy_loop_tail);
7911 
7912     lea(src, Address(src, len, Address::times_2));
7913     lea(dst, Address(dst, len, Address::times_1));
7914     negptr(len);
7915 
7916     bind(copy_32_loop);
7917     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), /*merge*/ false, Assembler::AVX_512bit);
7918     evpcmpuw(mask1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
7919     kortestdl(mask1, mask1);
7920     jcc(Assembler::carryClear, return_zero);
7921 
7922     // All elements in current processed chunk are valid candidates for
7923     // compression. Write a truncated byte elements to the memory.
7924     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
7925     addptr(len, 32);
7926     jcc(Assembler::notZero, copy_32_loop);
7927 
7928     bind(copy_loop_tail);
7929     // bail out when there is nothing to be done
7930     testl(tmp5, 0xFFFFFFFF);
7931     jcc(Assembler::zero, return_length);
7932 
7933     movl(len, tmp5);
7934 
7935     // ~(~0 << len), where len is the # of remaining elements to process
7936     movl(result, 0xFFFFFFFF);
7937     shlxl(result, result, len);
7938     notl(result);
7939 
7940     kmovdl(mask2, result);
7941 
7942     evmovdquw(tmp1Reg, mask2, Address(src, 0), /*merge*/ false, Assembler::AVX_512bit);
7943     evpcmpw(mask1, mask2, tmp1Reg, tmp2Reg, Assembler::le, /*signed*/ false, Assembler::AVX_512bit);
7944     ktestd(mask1, mask2);
7945     jcc(Assembler::carryClear, return_zero);
7946 
7947     evpmovwb(Address(dst, 0), mask2, tmp1Reg, Assembler::AVX_512bit);
7948     jmp(return_length);
7949 
7950     bind(below_threshold);
7951   }
7952 
7953   if (UseSSE42Intrinsics) {
7954     Label copy_32_loop, copy_16, copy_tail;
7955 
7956     movl(result, len);
7957 
7958     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
7959 
7960     // vectored compression
7961     andl(len, 0xfffffff0);    // vector count (in chars)
7962     andl(result, 0x0000000f);    // tail count (in chars)
7963     testl(len, len);
7964     jcc(Assembler::zero, copy_16);
7965 
7966     // compress 16 chars per iter
7967     movdl(tmp1Reg, tmp5);
7968     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
7969     pxor(tmp4Reg, tmp4Reg);
7970 
7971     lea(src, Address(src, len, Address::times_2));
7972     lea(dst, Address(dst, len, Address::times_1));
7973     negptr(len);
7974 
7975     bind(copy_32_loop);
7976     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
7977     por(tmp4Reg, tmp2Reg);
7978     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
7979     por(tmp4Reg, tmp3Reg);
7980     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
7981     jcc(Assembler::notZero, return_zero);
7982     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
7983     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
7984     addptr(len, 16);
7985     jcc(Assembler::notZero, copy_32_loop);
7986 
7987     // compress next vector of 8 chars (if any)
7988     bind(copy_16);
7989     movl(len, result);
7990     andl(len, 0xfffffff8);    // vector count (in chars)
7991     andl(result, 0x00000007);    // tail count (in chars)
7992     testl(len, len);
7993     jccb(Assembler::zero, copy_tail);
7994 
7995     movdl(tmp1Reg, tmp5);
7996     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
7997     pxor(tmp3Reg, tmp3Reg);
7998 
7999     movdqu(tmp2Reg, Address(src, 0));
8000     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
8001     jccb(Assembler::notZero, return_zero);
8002     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
8003     movq(Address(dst, 0), tmp2Reg);
8004     addptr(src, 16);
8005     addptr(dst, 8);
8006 
8007     bind(copy_tail);
8008     movl(len, result);
8009   }
8010   // compress 1 char per iter
8011   testl(len, len);
8012   jccb(Assembler::zero, return_length);
8013   lea(src, Address(src, len, Address::times_2));
8014   lea(dst, Address(dst, len, Address::times_1));
8015   negptr(len);
8016 
8017   bind(copy_chars_loop);
8018   load_unsigned_short(result, Address(src, len, Address::times_2));
8019   testl(result, 0xff00);      // check if Unicode char
8020   jccb(Assembler::notZero, return_zero);
8021   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
8022   increment(len);
8023   jcc(Assembler::notZero, copy_chars_loop);
8024 
8025   // if compression succeeded, return length
8026   bind(return_length);
8027   pop(result);
8028   jmpb(done);
8029 
8030   // if compression failed, return 0
8031   bind(return_zero);
8032   xorl(result, result);
8033   addptr(rsp, wordSize);
8034 
8035   bind(done);
8036 }
8037 
8038 // Inflate byte[] array to char[].
8039 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
8040 //   @IntrinsicCandidate
8041 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
8042 //     for (int i = 0; i < len; i++) {
8043 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
8044 //     }
8045 //   }
8046 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
8047   XMMRegister tmp1, Register tmp2, KRegister mask) {
8048   Label copy_chars_loop, done, below_threshold, avx3_threshold;
8049   // rsi: src
8050   // rdi: dst
8051   // rdx: len
8052   // rcx: tmp2
8053 
8054   // rsi holds start addr of source byte[] to be inflated
8055   // rdi holds start addr of destination char[]
8056   // rdx holds length
8057   assert_different_registers(src, dst, len, tmp2);
8058   movl(tmp2, len);
8059   if ((UseAVX > 2) && // AVX512
8060     VM_Version::supports_avx512vlbw() &&
8061     VM_Version::supports_bmi2()) {
8062 
8063     Label copy_32_loop, copy_tail;
8064     Register tmp3_aliased = len;
8065 
8066     // if length of the string is less than 16, handle it in an old fashioned way
8067     testl(len, -16);
8068     jcc(Assembler::zero, below_threshold);
8069 
8070     testl(len, -1 * AVX3Threshold);
8071     jcc(Assembler::zero, avx3_threshold);
8072 
8073     // In order to use only one arithmetic operation for the main loop we use
8074     // this pre-calculation
8075     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
8076     andl(len, -32);     // vector count
8077     jccb(Assembler::zero, copy_tail);
8078 
8079     lea(src, Address(src, len, Address::times_1));
8080     lea(dst, Address(dst, len, Address::times_2));
8081     negptr(len);
8082 
8083 
8084     // inflate 32 chars per iter
8085     bind(copy_32_loop);
8086     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
8087     evmovdquw(Address(dst, len, Address::times_2), tmp1, /*merge*/ false, Assembler::AVX_512bit);
8088     addptr(len, 32);
8089     jcc(Assembler::notZero, copy_32_loop);
8090 
8091     bind(copy_tail);
8092     // bail out when there is nothing to be done
8093     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
8094     jcc(Assembler::zero, done);
8095 
8096     // ~(~0 << length), where length is the # of remaining elements to process
8097     movl(tmp3_aliased, -1);
8098     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
8099     notl(tmp3_aliased);
8100     kmovdl(mask, tmp3_aliased);
8101     evpmovzxbw(tmp1, mask, Address(src, 0), Assembler::AVX_512bit);
8102     evmovdquw(Address(dst, 0), mask, tmp1, /*merge*/ true, Assembler::AVX_512bit);
8103 
8104     jmp(done);
8105     bind(avx3_threshold);
8106   }
8107   if (UseSSE42Intrinsics) {
8108     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
8109 
8110     if (UseAVX > 1) {
8111       andl(tmp2, (16 - 1));
8112       andl(len, -16);
8113       jccb(Assembler::zero, copy_new_tail);
8114     } else {
8115       andl(tmp2, 0x00000007);   // tail count (in chars)
8116       andl(len, 0xfffffff8);    // vector count (in chars)
8117       jccb(Assembler::zero, copy_tail);
8118     }
8119 
8120     // vectored inflation
8121     lea(src, Address(src, len, Address::times_1));
8122     lea(dst, Address(dst, len, Address::times_2));
8123     negptr(len);
8124 
8125     if (UseAVX > 1) {
8126       bind(copy_16_loop);
8127       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
8128       vmovdqu(Address(dst, len, Address::times_2), tmp1);
8129       addptr(len, 16);
8130       jcc(Assembler::notZero, copy_16_loop);
8131 
8132       bind(below_threshold);
8133       bind(copy_new_tail);
8134       movl(len, tmp2);
8135       andl(tmp2, 0x00000007);
8136       andl(len, 0xFFFFFFF8);
8137       jccb(Assembler::zero, copy_tail);
8138 
8139       pmovzxbw(tmp1, Address(src, 0));
8140       movdqu(Address(dst, 0), tmp1);
8141       addptr(src, 8);
8142       addptr(dst, 2 * 8);
8143 
8144       jmp(copy_tail, true);
8145     }
8146 
8147     // inflate 8 chars per iter
8148     bind(copy_8_loop);
8149     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
8150     movdqu(Address(dst, len, Address::times_2), tmp1);
8151     addptr(len, 8);
8152     jcc(Assembler::notZero, copy_8_loop);
8153 
8154     bind(copy_tail);
8155     movl(len, tmp2);
8156 
8157     cmpl(len, 4);
8158     jccb(Assembler::less, copy_bytes);
8159 
8160     movdl(tmp1, Address(src, 0));  // load 4 byte chars
8161     pmovzxbw(tmp1, tmp1);
8162     movq(Address(dst, 0), tmp1);
8163     subptr(len, 4);
8164     addptr(src, 4);
8165     addptr(dst, 8);
8166 
8167     bind(copy_bytes);
8168   } else {
8169     bind(below_threshold);
8170   }
8171 
8172   testl(len, len);
8173   jccb(Assembler::zero, done);
8174   lea(src, Address(src, len, Address::times_1));
8175   lea(dst, Address(dst, len, Address::times_2));
8176   negptr(len);
8177 
8178   // inflate 1 char per iter
8179   bind(copy_chars_loop);
8180   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
8181   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
8182   increment(len);
8183   jcc(Assembler::notZero, copy_chars_loop);
8184 
8185   bind(done);
8186 }
8187 
8188 
8189 void MacroAssembler::evmovdqu(BasicType type, KRegister kmask, XMMRegister dst, Address src, int vector_len) {
8190   switch(type) {
8191     case T_BYTE:
8192     case T_BOOLEAN:
8193       evmovdqub(dst, kmask, src, false, vector_len);
8194       break;
8195     case T_CHAR:
8196     case T_SHORT:
8197       evmovdquw(dst, kmask, src, false, vector_len);
8198       break;
8199     case T_INT:
8200     case T_FLOAT:
8201       evmovdqul(dst, kmask, src, false, vector_len);
8202       break;
8203     case T_LONG:
8204     case T_DOUBLE:
8205       evmovdquq(dst, kmask, src, false, vector_len);
8206       break;
8207     default:
8208       fatal("Unexpected type argument %s", type2name(type));
8209       break;
8210   }
8211 }
8212 
8213 void MacroAssembler::evmovdqu(BasicType type, KRegister kmask, Address dst, XMMRegister src, int vector_len) {
8214   switch(type) {
8215     case T_BYTE:
8216     case T_BOOLEAN:
8217       evmovdqub(dst, kmask, src, true, vector_len);
8218       break;
8219     case T_CHAR:
8220     case T_SHORT:
8221       evmovdquw(dst, kmask, src, true, vector_len);
8222       break;
8223     case T_INT:
8224     case T_FLOAT:
8225       evmovdqul(dst, kmask, src, true, vector_len);
8226       break;
8227     case T_LONG:
8228     case T_DOUBLE:
8229       evmovdquq(dst, kmask, src, true, vector_len);
8230       break;
8231     default:
8232       fatal("Unexpected type argument %s", type2name(type));
8233       break;
8234   }
8235 }
8236 
8237 #if COMPILER2_OR_JVMCI
8238 
8239 
8240 // Set memory operation for length "less than" 64 bytes.
8241 void MacroAssembler::fill64_masked_avx(uint shift, Register dst, int disp,
8242                                        XMMRegister xmm, KRegister mask, Register length,
8243                                        Register temp, bool use64byteVector) {
8244   assert(MaxVectorSize >= 32, "vector length should be >= 32");
8245   assert(shift != 0, "shift value should be 1 (short),2(int) or 3(long)");
8246   BasicType type[] = { T_BYTE, T_SHORT,  T_INT,   T_LONG};
8247   if (!use64byteVector) {
8248     fill32_avx(dst, disp, xmm);
8249     subptr(length, 32 >> shift);
8250     fill32_masked_avx(shift, dst, disp + 32, xmm, mask, length, temp);
8251   } else {
8252     assert(MaxVectorSize == 64, "vector length != 64");
8253     movl(temp, 1);
8254     shlxl(temp, temp, length);
8255     subptr(temp, 1);
8256     kmovwl(mask, temp);
8257     evmovdqu(type[shift], mask, Address(dst, disp), xmm, Assembler::AVX_512bit);
8258   }
8259 }
8260 
8261 
8262 void MacroAssembler::fill32_masked_avx(uint shift, Register dst, int disp,
8263                                        XMMRegister xmm, KRegister mask, Register length,
8264                                        Register temp) {
8265   assert(MaxVectorSize >= 32, "vector length should be >= 32");
8266   assert(shift != 0, "shift value should be 1 (short), 2(int) or 3(long)");
8267   BasicType type[] = { T_BYTE, T_SHORT,  T_INT,   T_LONG};
8268   movl(temp, 1);
8269   shlxl(temp, temp, length);
8270   subptr(temp, 1);
8271   kmovwl(mask, temp);
8272   evmovdqu(type[shift], mask, Address(dst, disp), xmm, Assembler::AVX_256bit);
8273 }
8274 
8275 
8276 void MacroAssembler::fill32_avx(Register dst, int disp, XMMRegister xmm) {
8277   assert(MaxVectorSize >= 32, "vector length should be >= 32");
8278   vmovdqu(Address(dst, disp), xmm);
8279 }
8280 
8281 void MacroAssembler::fill64_avx(Register dst, int disp, XMMRegister xmm, bool use64byteVector) {
8282   assert(MaxVectorSize >= 32, "vector length should be >= 32");
8283   BasicType type[] = {T_BYTE,  T_SHORT,  T_INT,   T_LONG};
8284   if (!use64byteVector) {
8285     fill32_avx(dst, disp, xmm);
8286     fill32_avx(dst, disp + 32, xmm);
8287   } else {
8288     evmovdquq(Address(dst, disp), xmm, Assembler::AVX_512bit);
8289   }
8290 }
8291 
8292 #endif //COMPILER2_OR_JVMCI
8293 
8294 
8295 #ifdef _LP64
8296 void MacroAssembler::convert_f2i(Register dst, XMMRegister src) {
8297   Label done;
8298   cvttss2sil(dst, src);
8299   // Conversion instructions do not match JLS for overflow, underflow and NaN -> fixup in stub
8300   cmpl(dst, 0x80000000); // float_sign_flip
8301   jccb(Assembler::notEqual, done);
8302   subptr(rsp, 8);
8303   movflt(Address(rsp, 0), src);
8304   call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::x86::f2i_fixup())));
8305   pop(dst);
8306   bind(done);
8307 }
8308 
8309 void MacroAssembler::convert_d2i(Register dst, XMMRegister src) {
8310   Label done;
8311   cvttsd2sil(dst, src);
8312   // Conversion instructions do not match JLS for overflow, underflow and NaN -> fixup in stub
8313   cmpl(dst, 0x80000000); // float_sign_flip
8314   jccb(Assembler::notEqual, done);
8315   subptr(rsp, 8);
8316   movdbl(Address(rsp, 0), src);
8317   call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::x86::d2i_fixup())));
8318   pop(dst);
8319   bind(done);
8320 }
8321 
8322 void MacroAssembler::convert_f2l(Register dst, XMMRegister src) {
8323   Label done;
8324   cvttss2siq(dst, src);
8325   cmp64(dst, ExternalAddress((address) StubRoutines::x86::double_sign_flip()));
8326   jccb(Assembler::notEqual, done);
8327   subptr(rsp, 8);
8328   movflt(Address(rsp, 0), src);
8329   call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::x86::f2l_fixup())));
8330   pop(dst);
8331   bind(done);
8332 }
8333 
8334 void MacroAssembler::convert_d2l(Register dst, XMMRegister src) {
8335   Label done;
8336   cvttsd2siq(dst, src);
8337   cmp64(dst, ExternalAddress((address) StubRoutines::x86::double_sign_flip()));
8338   jccb(Assembler::notEqual, done);
8339   subptr(rsp, 8);
8340   movdbl(Address(rsp, 0), src);
8341   call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::x86::d2l_fixup())));
8342   pop(dst);
8343   bind(done);
8344 }
8345 
8346 void MacroAssembler::cache_wb(Address line)
8347 {
8348   // 64 bit cpus always support clflush
8349   assert(VM_Version::supports_clflush(), "clflush should be available");
8350   bool optimized = VM_Version::supports_clflushopt();
8351   bool no_evict = VM_Version::supports_clwb();
8352 
8353   // prefer clwb (writeback without evict) otherwise
8354   // prefer clflushopt (potentially parallel writeback with evict)
8355   // otherwise fallback on clflush (serial writeback with evict)
8356 
8357   if (optimized) {
8358     if (no_evict) {
8359       clwb(line);
8360     } else {
8361       clflushopt(line);
8362     }
8363   } else {
8364     // no need for fence when using CLFLUSH
8365     clflush(line);
8366   }
8367 }
8368 
8369 void MacroAssembler::cache_wbsync(bool is_pre)
8370 {
8371   assert(VM_Version::supports_clflush(), "clflush should be available");
8372   bool optimized = VM_Version::supports_clflushopt();
8373   bool no_evict = VM_Version::supports_clwb();
8374 
8375   // pick the correct implementation
8376 
8377   if (!is_pre && (optimized || no_evict)) {
8378     // need an sfence for post flush when using clflushopt or clwb
8379     // otherwise no no need for any synchroniaztion
8380 
8381     sfence();
8382   }
8383 }
8384 
8385 #endif // _LP64
8386 
8387 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
8388   switch (cond) {
8389     // Note some conditions are synonyms for others
8390     case Assembler::zero:         return Assembler::notZero;
8391     case Assembler::notZero:      return Assembler::zero;
8392     case Assembler::less:         return Assembler::greaterEqual;
8393     case Assembler::lessEqual:    return Assembler::greater;
8394     case Assembler::greater:      return Assembler::lessEqual;
8395     case Assembler::greaterEqual: return Assembler::less;
8396     case Assembler::below:        return Assembler::aboveEqual;
8397     case Assembler::belowEqual:   return Assembler::above;
8398     case Assembler::above:        return Assembler::belowEqual;
8399     case Assembler::aboveEqual:   return Assembler::below;
8400     case Assembler::overflow:     return Assembler::noOverflow;
8401     case Assembler::noOverflow:   return Assembler::overflow;
8402     case Assembler::negative:     return Assembler::positive;
8403     case Assembler::positive:     return Assembler::negative;
8404     case Assembler::parity:       return Assembler::noParity;
8405     case Assembler::noParity:     return Assembler::parity;
8406   }
8407   ShouldNotReachHere(); return Assembler::overflow;
8408 }
8409 
8410 SkipIfEqual::SkipIfEqual(
8411     MacroAssembler* masm, const bool* flag_addr, bool value) {
8412   _masm = masm;
8413   _masm->cmp8(ExternalAddress((address)flag_addr), value);
8414   _masm->jcc(Assembler::equal, _label);
8415 }
8416 
8417 SkipIfEqual::~SkipIfEqual() {
8418   _masm->bind(_label);
8419 }
8420 
8421 // 32-bit Windows has its own fast-path implementation
8422 // of get_thread
8423 #if !defined(WIN32) || defined(_LP64)
8424 
8425 // This is simply a call to Thread::current()
8426 void MacroAssembler::get_thread(Register thread) {
8427   if (thread != rax) {
8428     push(rax);
8429   }
8430   LP64_ONLY(push(rdi);)
8431   LP64_ONLY(push(rsi);)
8432   push(rdx);
8433   push(rcx);
8434 #ifdef _LP64
8435   push(r8);
8436   push(r9);
8437   push(r10);
8438   push(r11);
8439 #endif
8440 
8441   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
8442 
8443 #ifdef _LP64
8444   pop(r11);
8445   pop(r10);
8446   pop(r9);
8447   pop(r8);
8448 #endif
8449   pop(rcx);
8450   pop(rdx);
8451   LP64_ONLY(pop(rsi);)
8452   LP64_ONLY(pop(rdi);)
8453   if (thread != rax) {
8454     mov(thread, rax);
8455     pop(rax);
8456   }
8457 }
8458 
8459 #endif // !WIN32 || _LP64