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