1 /*
   2  * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "asm/assembler.hpp"
  28 #include "asm/assembler.inline.hpp"
  29 #include "compiler/disassembler.hpp"
  30 #include "gc/shared/barrierSet.hpp"
  31 #include "gc/shared/barrierSetAssembler.hpp"
  32 #include "gc/shared/collectedHeap.inline.hpp"
  33 #include "interpreter/interpreter.hpp"
  34 #include "memory/resourceArea.hpp"
  35 #include "memory/universe.hpp"
  36 #include "oops/accessDecorators.hpp"
  37 #include "oops/compressedOops.inline.hpp"
  38 #include "oops/klass.inline.hpp"
  39 #include "prims/methodHandles.hpp"
  40 #include "runtime/biasedLocking.hpp"
  41 #include "runtime/flags/flagSetting.hpp"
  42 #include "runtime/interfaceSupport.inline.hpp"
  43 #include "runtime/objectMonitor.hpp"
  44 #include "runtime/os.hpp"
  45 #include "runtime/safepoint.hpp"
  46 #include "runtime/safepointMechanism.hpp"
  47 #include "runtime/sharedRuntime.hpp"
  48 #include "runtime/stubRoutines.hpp"
  49 #include "runtime/thread.hpp"
  50 #include "utilities/macros.hpp"
  51 #include "vmreg_x86.inline.hpp"
  52 #include "crc32c.h"
  53 #ifdef COMPILER2
  54 #include "opto/intrinsicnode.hpp"
  55 #endif
  56 
  57 #ifdef PRODUCT
  58 #define BLOCK_COMMENT(str) /* nothing */
  59 #define STOP(error) stop(error)
  60 #else
  61 #define BLOCK_COMMENT(str) block_comment(str)
  62 #define STOP(error) block_comment(error); stop(error)
  63 #endif
  64 
  65 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  66 
  67 #ifdef ASSERT
  68 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  69 #endif
  70 
  71 static Assembler::Condition reverse[] = {
  72     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  73     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  74     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  75     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  76     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  77     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  78     Assembler::above          /* belowEqual    = 0x6 */ ,
  79     Assembler::belowEqual     /* above         = 0x7 */ ,
  80     Assembler::positive       /* negative      = 0x8 */ ,
  81     Assembler::negative       /* positive      = 0x9 */ ,
  82     Assembler::noParity       /* parity        = 0xa */ ,
  83     Assembler::parity         /* noParity      = 0xb */ ,
  84     Assembler::greaterEqual   /* less          = 0xc */ ,
  85     Assembler::less           /* greaterEqual  = 0xd */ ,
  86     Assembler::greater        /* lessEqual     = 0xe */ ,
  87     Assembler::lessEqual      /* greater       = 0xf, */
  88 
  89 };
  90 
  91 
  92 // Implementation of MacroAssembler
  93 
  94 // First all the versions that have distinct versions depending on 32/64 bit
  95 // Unless the difference is trivial (1 line or so).
  96 
  97 #ifndef _LP64
  98 
  99 // 32bit versions
 100 
 101 Address MacroAssembler::as_Address(AddressLiteral adr) {
 102   return Address(adr.target(), adr.rspec());
 103 }
 104 
 105 Address MacroAssembler::as_Address(ArrayAddress adr) {
 106   return Address::make_array(adr);
 107 }
 108 
 109 void MacroAssembler::call_VM_leaf_base(address entry_point,
 110                                        int number_of_arguments) {
 111   call(RuntimeAddress(entry_point));
 112   increment(rsp, number_of_arguments * wordSize);
 113 }
 114 
 115 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 116   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 117 }
 118 
 119 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 120   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 121 }
 122 
 123 void MacroAssembler::cmpoop_raw(Address src1, jobject obj) {
 124   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 125 }
 126 
 127 void MacroAssembler::cmpoop_raw(Register src1, jobject obj) {
 128   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 129 }
 130 
 131 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 132   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
 133   bs->obj_equals(this, src1, obj);
 134 }
 135 
 136 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 137   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
 138   bs->obj_equals(this, src1, obj);
 139 }
 140 
 141 void MacroAssembler::extend_sign(Register hi, Register lo) {
 142   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 143   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 144     cdql();
 145   } else {
 146     movl(hi, lo);
 147     sarl(hi, 31);
 148   }
 149 }
 150 
 151 void MacroAssembler::jC2(Register tmp, Label& L) {
 152   // set parity bit if FPU flag C2 is set (via rax)
 153   save_rax(tmp);
 154   fwait(); fnstsw_ax();
 155   sahf();
 156   restore_rax(tmp);
 157   // branch
 158   jcc(Assembler::parity, L);
 159 }
 160 
 161 void MacroAssembler::jnC2(Register tmp, Label& L) {
 162   // set parity bit if FPU flag C2 is set (via rax)
 163   save_rax(tmp);
 164   fwait(); fnstsw_ax();
 165   sahf();
 166   restore_rax(tmp);
 167   // branch
 168   jcc(Assembler::noParity, L);
 169 }
 170 
 171 // 32bit can do a case table jump in one instruction but we no longer allow the base
 172 // to be installed in the Address class
 173 void MacroAssembler::jump(ArrayAddress entry) {
 174   jmp(as_Address(entry));
 175 }
 176 
 177 // Note: y_lo will be destroyed
 178 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 179   // Long compare for Java (semantics as described in JVM spec.)
 180   Label high, low, done;
 181 
 182   cmpl(x_hi, y_hi);
 183   jcc(Assembler::less, low);
 184   jcc(Assembler::greater, high);
 185   // x_hi is the return register
 186   xorl(x_hi, x_hi);
 187   cmpl(x_lo, y_lo);
 188   jcc(Assembler::below, low);
 189   jcc(Assembler::equal, done);
 190 
 191   bind(high);
 192   xorl(x_hi, x_hi);
 193   increment(x_hi);
 194   jmp(done);
 195 
 196   bind(low);
 197   xorl(x_hi, x_hi);
 198   decrementl(x_hi);
 199 
 200   bind(done);
 201 }
 202 
 203 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 204     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 205 }
 206 
 207 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 208   // leal(dst, as_Address(adr));
 209   // see note in movl as to why we must use a move
 210   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 211 }
 212 
 213 void MacroAssembler::leave() {
 214   mov(rsp, rbp);
 215   pop(rbp);
 216 }
 217 
 218 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 219   // Multiplication of two Java long values stored on the stack
 220   // as illustrated below. Result is in rdx:rax.
 221   //
 222   // rsp ---> [  ??  ] \               \
 223   //            ....    | y_rsp_offset  |
 224   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 225   //          [ y_hi ]                  | (in bytes)
 226   //            ....                    |
 227   //          [ x_lo ]                 /
 228   //          [ x_hi ]
 229   //            ....
 230   //
 231   // Basic idea: lo(result) = lo(x_lo * y_lo)
 232   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 233   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 234   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 235   Label quick;
 236   // load x_hi, y_hi and check if quick
 237   // multiplication is possible
 238   movl(rbx, x_hi);
 239   movl(rcx, y_hi);
 240   movl(rax, rbx);
 241   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 242   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 243   // do full multiplication
 244   // 1st step
 245   mull(y_lo);                                    // x_hi * y_lo
 246   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 247   // 2nd step
 248   movl(rax, x_lo);
 249   mull(rcx);                                     // x_lo * y_hi
 250   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 251   // 3rd step
 252   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 253   movl(rax, x_lo);
 254   mull(y_lo);                                    // x_lo * y_lo
 255   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 256 }
 257 
 258 void MacroAssembler::lneg(Register hi, Register lo) {
 259   negl(lo);
 260   adcl(hi, 0);
 261   negl(hi);
 262 }
 263 
 264 void MacroAssembler::lshl(Register hi, Register lo) {
 265   // Java shift left long support (semantics as described in JVM spec., p.305)
 266   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 267   // shift value is in rcx !
 268   assert(hi != rcx, "must not use rcx");
 269   assert(lo != rcx, "must not use rcx");
 270   const Register s = rcx;                        // shift count
 271   const int      n = BitsPerWord;
 272   Label L;
 273   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 274   cmpl(s, n);                                    // if (s < n)
 275   jcc(Assembler::less, L);                       // else (s >= n)
 276   movl(hi, lo);                                  // x := x << n
 277   xorl(lo, lo);
 278   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 279   bind(L);                                       // s (mod n) < n
 280   shldl(hi, lo);                                 // x := x << s
 281   shll(lo);
 282 }
 283 
 284 
 285 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 286   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 287   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 288   assert(hi != rcx, "must not use rcx");
 289   assert(lo != rcx, "must not use rcx");
 290   const Register s = rcx;                        // shift count
 291   const int      n = BitsPerWord;
 292   Label L;
 293   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 294   cmpl(s, n);                                    // if (s < n)
 295   jcc(Assembler::less, L);                       // else (s >= n)
 296   movl(lo, hi);                                  // x := x >> n
 297   if (sign_extension) sarl(hi, 31);
 298   else                xorl(hi, hi);
 299   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 300   bind(L);                                       // s (mod n) < n
 301   shrdl(lo, hi);                                 // x := x >> s
 302   if (sign_extension) sarl(hi);
 303   else                shrl(hi);
 304 }
 305 
 306 void MacroAssembler::movoop(Register dst, jobject obj) {
 307   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 308 }
 309 
 310 void MacroAssembler::movoop(Address dst, jobject obj) {
 311   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 312 }
 313 
 314 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 315   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 316 }
 317 
 318 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 319   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 320 }
 321 
 322 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 323   // scratch register is not used,
 324   // it is defined to match parameters of 64-bit version of this method.
 325   if (src.is_lval()) {
 326     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 327   } else {
 328     movl(dst, as_Address(src));
 329   }
 330 }
 331 
 332 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 333   movl(as_Address(dst), src);
 334 }
 335 
 336 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 337   movl(dst, as_Address(src));
 338 }
 339 
 340 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 341 void MacroAssembler::movptr(Address dst, intptr_t src) {
 342   movl(dst, src);
 343 }
 344 
 345 
 346 void MacroAssembler::pop_callee_saved_registers() {
 347   pop(rcx);
 348   pop(rdx);
 349   pop(rdi);
 350   pop(rsi);
 351 }
 352 
 353 void MacroAssembler::pop_fTOS() {
 354   fld_d(Address(rsp, 0));
 355   addl(rsp, 2 * wordSize);
 356 }
 357 
 358 void MacroAssembler::push_callee_saved_registers() {
 359   push(rsi);
 360   push(rdi);
 361   push(rdx);
 362   push(rcx);
 363 }
 364 
 365 void MacroAssembler::push_fTOS() {
 366   subl(rsp, 2 * wordSize);
 367   fstp_d(Address(rsp, 0));
 368 }
 369 
 370 
 371 void MacroAssembler::pushoop(jobject obj) {
 372   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 373 }
 374 
 375 void MacroAssembler::pushklass(Metadata* obj) {
 376   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 377 }
 378 
 379 void MacroAssembler::pushptr(AddressLiteral src) {
 380   if (src.is_lval()) {
 381     push_literal32((int32_t)src.target(), src.rspec());
 382   } else {
 383     pushl(as_Address(src));
 384   }
 385 }
 386 
 387 void MacroAssembler::set_word_if_not_zero(Register dst) {
 388   xorl(dst, dst);
 389   set_byte_if_not_zero(dst);
 390 }
 391 
 392 static void pass_arg0(MacroAssembler* masm, Register arg) {
 393   masm->push(arg);
 394 }
 395 
 396 static void pass_arg1(MacroAssembler* masm, Register arg) {
 397   masm->push(arg);
 398 }
 399 
 400 static void pass_arg2(MacroAssembler* masm, Register arg) {
 401   masm->push(arg);
 402 }
 403 
 404 static void pass_arg3(MacroAssembler* masm, Register arg) {
 405   masm->push(arg);
 406 }
 407 
 408 #ifndef PRODUCT
 409 extern "C" void findpc(intptr_t x);
 410 #endif
 411 
 412 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 413   // In order to get locks to work, we need to fake a in_VM state
 414   JavaThread* thread = JavaThread::current();
 415   JavaThreadState saved_state = thread->thread_state();
 416   thread->set_thread_state(_thread_in_vm);
 417   if (ShowMessageBoxOnError) {
 418     JavaThread* thread = JavaThread::current();
 419     JavaThreadState saved_state = thread->thread_state();
 420     thread->set_thread_state(_thread_in_vm);
 421     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 422       ttyLocker ttyl;
 423       BytecodeCounter::print();
 424     }
 425     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 426     // This is the value of eip which points to where verify_oop will return.
 427     if (os::message_box(msg, "Execution stopped, print registers?")) {
 428       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 429       BREAKPOINT;
 430     }
 431   } else {
 432     ttyLocker ttyl;
 433     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 434   }
 435   // Don't assert holding the ttyLock
 436     assert(false, "DEBUG MESSAGE: %s", msg);
 437   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 438 }
 439 
 440 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 441   ttyLocker ttyl;
 442   FlagSetting fs(Debugging, true);
 443   tty->print_cr("eip = 0x%08x", eip);
 444 #ifndef PRODUCT
 445   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 446     tty->cr();
 447     findpc(eip);
 448     tty->cr();
 449   }
 450 #endif
 451 #define PRINT_REG(rax) \
 452   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 453   PRINT_REG(rax);
 454   PRINT_REG(rbx);
 455   PRINT_REG(rcx);
 456   PRINT_REG(rdx);
 457   PRINT_REG(rdi);
 458   PRINT_REG(rsi);
 459   PRINT_REG(rbp);
 460   PRINT_REG(rsp);
 461 #undef PRINT_REG
 462   // Print some words near top of staack.
 463   int* dump_sp = (int*) rsp;
 464   for (int col1 = 0; col1 < 8; col1++) {
 465     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 466     os::print_location(tty, *dump_sp++);
 467   }
 468   for (int row = 0; row < 16; row++) {
 469     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 470     for (int col = 0; col < 8; col++) {
 471       tty->print(" 0x%08x", *dump_sp++);
 472     }
 473     tty->cr();
 474   }
 475   // Print some instructions around pc:
 476   Disassembler::decode((address)eip-64, (address)eip);
 477   tty->print_cr("--------");
 478   Disassembler::decode((address)eip, (address)eip+32);
 479 }
 480 
 481 void MacroAssembler::stop(const char* msg) {
 482   ExternalAddress message((address)msg);
 483   // push address of message
 484   pushptr(message.addr());
 485   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 486   pusha();                                            // push registers
 487   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 488   hlt();
 489 }
 490 
 491 void MacroAssembler::warn(const char* msg) {
 492   push_CPU_state();
 493 
 494   ExternalAddress message((address) msg);
 495   // push address of message
 496   pushptr(message.addr());
 497 
 498   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 499   addl(rsp, wordSize);       // discard argument
 500   pop_CPU_state();
 501 }
 502 
 503 void MacroAssembler::print_state() {
 504   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 505   pusha();                                            // push registers
 506 
 507   push_CPU_state();
 508   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 509   pop_CPU_state();
 510 
 511   popa();
 512   addl(rsp, wordSize);
 513 }
 514 
 515 #else // _LP64
 516 
 517 // 64 bit versions
 518 
 519 Address MacroAssembler::as_Address(AddressLiteral adr) {
 520   // amd64 always does this as a pc-rel
 521   // we can be absolute or disp based on the instruction type
 522   // jmp/call are displacements others are absolute
 523   assert(!adr.is_lval(), "must be rval");
 524   assert(reachable(adr), "must be");
 525   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 526 
 527 }
 528 
 529 Address MacroAssembler::as_Address(ArrayAddress adr) {
 530   AddressLiteral base = adr.base();
 531   lea(rscratch1, base);
 532   Address index = adr.index();
 533   assert(index._disp == 0, "must not have disp"); // maybe it can?
 534   Address array(rscratch1, index._index, index._scale, index._disp);
 535   return array;
 536 }
 537 
 538 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 539   Label L, E;
 540 
 541 #ifdef _WIN64
 542   // Windows always allocates space for it's register args
 543   assert(num_args <= 4, "only register arguments supported");
 544   subq(rsp,  frame::arg_reg_save_area_bytes);
 545 #endif
 546 
 547   // Align stack if necessary
 548   testl(rsp, 15);
 549   jcc(Assembler::zero, L);
 550 
 551   subq(rsp, 8);
 552   {
 553     call(RuntimeAddress(entry_point));
 554   }
 555   addq(rsp, 8);
 556   jmp(E);
 557 
 558   bind(L);
 559   {
 560     call(RuntimeAddress(entry_point));
 561   }
 562 
 563   bind(E);
 564 
 565 #ifdef _WIN64
 566   // restore stack pointer
 567   addq(rsp, frame::arg_reg_save_area_bytes);
 568 #endif
 569 
 570 }
 571 
 572 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 573   assert(!src2.is_lval(), "should use cmpptr");
 574 
 575   if (reachable(src2)) {
 576     cmpq(src1, as_Address(src2));
 577   } else {
 578     lea(rscratch1, src2);
 579     Assembler::cmpq(src1, Address(rscratch1, 0));
 580   }
 581 }
 582 
 583 int MacroAssembler::corrected_idivq(Register reg) {
 584   // Full implementation of Java ldiv and lrem; checks for special
 585   // case as described in JVM spec., p.243 & p.271.  The function
 586   // returns the (pc) offset of the idivl instruction - may be needed
 587   // for implicit exceptions.
 588   //
 589   //         normal case                           special case
 590   //
 591   // input : rax: dividend                         min_long
 592   //         reg: divisor   (may not be eax/edx)   -1
 593   //
 594   // output: rax: quotient  (= rax idiv reg)       min_long
 595   //         rdx: remainder (= rax irem reg)       0
 596   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 597   static const int64_t min_long = 0x8000000000000000;
 598   Label normal_case, special_case;
 599 
 600   // check for special case
 601   cmp64(rax, ExternalAddress((address) &min_long));
 602   jcc(Assembler::notEqual, normal_case);
 603   xorl(rdx, rdx); // prepare rdx for possible special case (where
 604                   // remainder = 0)
 605   cmpq(reg, -1);
 606   jcc(Assembler::equal, special_case);
 607 
 608   // handle normal case
 609   bind(normal_case);
 610   cdqq();
 611   int idivq_offset = offset();
 612   idivq(reg);
 613 
 614   // normal and special case exit
 615   bind(special_case);
 616 
 617   return idivq_offset;
 618 }
 619 
 620 void MacroAssembler::decrementq(Register reg, int value) {
 621   if (value == min_jint) { subq(reg, value); return; }
 622   if (value <  0) { incrementq(reg, -value); return; }
 623   if (value == 0) {                        ; return; }
 624   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 625   /* else */      { subq(reg, value)       ; return; }
 626 }
 627 
 628 void MacroAssembler::decrementq(Address dst, int value) {
 629   if (value == min_jint) { subq(dst, value); return; }
 630   if (value <  0) { incrementq(dst, -value); return; }
 631   if (value == 0) {                        ; return; }
 632   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 633   /* else */      { subq(dst, value)       ; return; }
 634 }
 635 
 636 void MacroAssembler::incrementq(AddressLiteral dst) {
 637   if (reachable(dst)) {
 638     incrementq(as_Address(dst));
 639   } else {
 640     lea(rscratch1, dst);
 641     incrementq(Address(rscratch1, 0));
 642   }
 643 }
 644 
 645 void MacroAssembler::incrementq(Register reg, int value) {
 646   if (value == min_jint) { addq(reg, value); return; }
 647   if (value <  0) { decrementq(reg, -value); return; }
 648   if (value == 0) {                        ; return; }
 649   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 650   /* else */      { addq(reg, value)       ; return; }
 651 }
 652 
 653 void MacroAssembler::incrementq(Address dst, int value) {
 654   if (value == min_jint) { addq(dst, value); return; }
 655   if (value <  0) { decrementq(dst, -value); return; }
 656   if (value == 0) {                        ; return; }
 657   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 658   /* else */      { addq(dst, value)       ; return; }
 659 }
 660 
 661 // 32bit can do a case table jump in one instruction but we no longer allow the base
 662 // to be installed in the Address class
 663 void MacroAssembler::jump(ArrayAddress entry) {
 664   lea(rscratch1, entry.base());
 665   Address dispatch = entry.index();
 666   assert(dispatch._base == noreg, "must be");
 667   dispatch._base = rscratch1;
 668   jmp(dispatch);
 669 }
 670 
 671 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 672   ShouldNotReachHere(); // 64bit doesn't use two regs
 673   cmpq(x_lo, y_lo);
 674 }
 675 
 676 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 677     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 678 }
 679 
 680 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 681   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 682   movptr(dst, rscratch1);
 683 }
 684 
 685 void MacroAssembler::leave() {
 686   // %%% is this really better? Why not on 32bit too?
 687   emit_int8((unsigned char)0xC9); // LEAVE
 688 }
 689 
 690 void MacroAssembler::lneg(Register hi, Register lo) {
 691   ShouldNotReachHere(); // 64bit doesn't use two regs
 692   negq(lo);
 693 }
 694 
 695 void MacroAssembler::movoop(Register dst, jobject obj) {
 696   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 697 }
 698 
 699 void MacroAssembler::movoop(Address dst, jobject obj) {
 700   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 701   movq(dst, rscratch1);
 702 }
 703 
 704 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 705   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 706 }
 707 
 708 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 709   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 710   movq(dst, rscratch1);
 711 }
 712 
 713 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 714   if (src.is_lval()) {
 715     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 716   } else {
 717     if (reachable(src)) {
 718       movq(dst, as_Address(src));
 719     } else {
 720       lea(scratch, src);
 721       movq(dst, Address(scratch, 0));
 722     }
 723   }
 724 }
 725 
 726 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 727   movq(as_Address(dst), src);
 728 }
 729 
 730 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 731   movq(dst, as_Address(src));
 732 }
 733 
 734 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 735 void MacroAssembler::movptr(Address dst, intptr_t src) {
 736   mov64(rscratch1, src);
 737   movq(dst, rscratch1);
 738 }
 739 
 740 // These are mostly for initializing NULL
 741 void MacroAssembler::movptr(Address dst, int32_t src) {
 742   movslq(dst, src);
 743 }
 744 
 745 void MacroAssembler::movptr(Register dst, int32_t src) {
 746   mov64(dst, (intptr_t)src);
 747 }
 748 
 749 void MacroAssembler::pushoop(jobject obj) {
 750   movoop(rscratch1, obj);
 751   push(rscratch1);
 752 }
 753 
 754 void MacroAssembler::pushklass(Metadata* obj) {
 755   mov_metadata(rscratch1, obj);
 756   push(rscratch1);
 757 }
 758 
 759 void MacroAssembler::pushptr(AddressLiteral src) {
 760   lea(rscratch1, src);
 761   if (src.is_lval()) {
 762     push(rscratch1);
 763   } else {
 764     pushq(Address(rscratch1, 0));
 765   }
 766 }
 767 
 768 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 769   // we must set sp to zero to clear frame
 770   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 771   // must clear fp, so that compiled frames are not confused; it is
 772   // possible that we need it only for debugging
 773   if (clear_fp) {
 774     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 775   }
 776 
 777   // Always clear the pc because it could have been set by make_walkable()
 778   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 779   vzeroupper();
 780 }
 781 
 782 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 783                                          Register last_java_fp,
 784                                          address  last_java_pc) {
 785   vzeroupper();
 786   // determine last_java_sp register
 787   if (!last_java_sp->is_valid()) {
 788     last_java_sp = rsp;
 789   }
 790 
 791   // last_java_fp is optional
 792   if (last_java_fp->is_valid()) {
 793     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 794            last_java_fp);
 795   }
 796 
 797   // last_java_pc is optional
 798   if (last_java_pc != NULL) {
 799     Address java_pc(r15_thread,
 800                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 801     lea(rscratch1, InternalAddress(last_java_pc));
 802     movptr(java_pc, rscratch1);
 803   }
 804 
 805   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 806 }
 807 
 808 static void pass_arg0(MacroAssembler* masm, Register arg) {
 809   if (c_rarg0 != arg ) {
 810     masm->mov(c_rarg0, arg);
 811   }
 812 }
 813 
 814 static void pass_arg1(MacroAssembler* masm, Register arg) {
 815   if (c_rarg1 != arg ) {
 816     masm->mov(c_rarg1, arg);
 817   }
 818 }
 819 
 820 static void pass_arg2(MacroAssembler* masm, Register arg) {
 821   if (c_rarg2 != arg ) {
 822     masm->mov(c_rarg2, arg);
 823   }
 824 }
 825 
 826 static void pass_arg3(MacroAssembler* masm, Register arg) {
 827   if (c_rarg3 != arg ) {
 828     masm->mov(c_rarg3, arg);
 829   }
 830 }
 831 
 832 void MacroAssembler::stop(const char* msg) {
 833   address rip = pc();
 834   pusha(); // get regs on stack
 835   lea(c_rarg0, ExternalAddress((address) msg));
 836   lea(c_rarg1, InternalAddress(rip));
 837   movq(c_rarg2, rsp); // pass pointer to regs array
 838   andq(rsp, -16); // align stack as required by ABI
 839   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 840   hlt();
 841 }
 842 
 843 void MacroAssembler::warn(const char* msg) {
 844   push(rbp);
 845   movq(rbp, rsp);
 846   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 847   push_CPU_state();   // keeps alignment at 16 bytes
 848   lea(c_rarg0, ExternalAddress((address) msg));
 849   lea(rax, ExternalAddress(CAST_FROM_FN_PTR(address, warning)));
 850   call(rax);
 851   pop_CPU_state();
 852   mov(rsp, rbp);
 853   pop(rbp);
 854 }
 855 
 856 void MacroAssembler::print_state() {
 857   address rip = pc();
 858   pusha();            // get regs on stack
 859   push(rbp);
 860   movq(rbp, rsp);
 861   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 862   push_CPU_state();   // keeps alignment at 16 bytes
 863 
 864   lea(c_rarg0, InternalAddress(rip));
 865   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 866   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 867 
 868   pop_CPU_state();
 869   mov(rsp, rbp);
 870   pop(rbp);
 871   popa();
 872 }
 873 
 874 #ifndef PRODUCT
 875 extern "C" void findpc(intptr_t x);
 876 #endif
 877 
 878 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 879   // In order to get locks to work, we need to fake a in_VM state
 880   if (ShowMessageBoxOnError) {
 881     JavaThread* thread = JavaThread::current();
 882     JavaThreadState saved_state = thread->thread_state();
 883     thread->set_thread_state(_thread_in_vm);
 884 #ifndef PRODUCT
 885     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 886       ttyLocker ttyl;
 887       BytecodeCounter::print();
 888     }
 889 #endif
 890     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 891     // XXX correct this offset for amd64
 892     // This is the value of eip which points to where verify_oop will return.
 893     if (os::message_box(msg, "Execution stopped, print registers?")) {
 894       print_state64(pc, regs);
 895       BREAKPOINT;
 896       assert(false, "start up GDB");
 897     }
 898     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 899   } else {
 900     ttyLocker ttyl;
 901     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 902                     msg);
 903     assert(false, "DEBUG MESSAGE: %s", msg);
 904   }
 905 }
 906 
 907 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 908   ttyLocker ttyl;
 909   FlagSetting fs(Debugging, true);
 910   tty->print_cr("rip = 0x%016lx", (intptr_t)pc);
 911 #ifndef PRODUCT
 912   tty->cr();
 913   findpc(pc);
 914   tty->cr();
 915 #endif
 916 #define PRINT_REG(rax, value) \
 917   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 918   PRINT_REG(rax, regs[15]);
 919   PRINT_REG(rbx, regs[12]);
 920   PRINT_REG(rcx, regs[14]);
 921   PRINT_REG(rdx, regs[13]);
 922   PRINT_REG(rdi, regs[8]);
 923   PRINT_REG(rsi, regs[9]);
 924   PRINT_REG(rbp, regs[10]);
 925   PRINT_REG(rsp, regs[11]);
 926   PRINT_REG(r8 , regs[7]);
 927   PRINT_REG(r9 , regs[6]);
 928   PRINT_REG(r10, regs[5]);
 929   PRINT_REG(r11, regs[4]);
 930   PRINT_REG(r12, regs[3]);
 931   PRINT_REG(r13, regs[2]);
 932   PRINT_REG(r14, regs[1]);
 933   PRINT_REG(r15, regs[0]);
 934 #undef PRINT_REG
 935   // Print some words near top of staack.
 936   int64_t* rsp = (int64_t*) regs[11];
 937   int64_t* dump_sp = rsp;
 938   for (int col1 = 0; col1 < 8; col1++) {
 939     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 940     os::print_location(tty, *dump_sp++);
 941   }
 942   for (int row = 0; row < 25; row++) {
 943     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 944     for (int col = 0; col < 4; col++) {
 945       tty->print(" 0x%016lx", (intptr_t)*dump_sp++);
 946     }
 947     tty->cr();
 948   }
 949   // Print some instructions around pc:
 950   Disassembler::decode((address)pc-64, (address)pc);
 951   tty->print_cr("--------");
 952   Disassembler::decode((address)pc, (address)pc+32);
 953 }
 954 
 955 #endif // _LP64
 956 
 957 // Now versions that are common to 32/64 bit
 958 
 959 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 960   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 961 }
 962 
 963 void MacroAssembler::addptr(Register dst, Register src) {
 964   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 965 }
 966 
 967 void MacroAssembler::addptr(Address dst, Register src) {
 968   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 969 }
 970 
 971 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 972   if (reachable(src)) {
 973     Assembler::addsd(dst, as_Address(src));
 974   } else {
 975     lea(rscratch1, src);
 976     Assembler::addsd(dst, Address(rscratch1, 0));
 977   }
 978 }
 979 
 980 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 981   if (reachable(src)) {
 982     addss(dst, as_Address(src));
 983   } else {
 984     lea(rscratch1, src);
 985     addss(dst, Address(rscratch1, 0));
 986   }
 987 }
 988 
 989 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 990   if (reachable(src)) {
 991     Assembler::addpd(dst, as_Address(src));
 992   } else {
 993     lea(rscratch1, src);
 994     Assembler::addpd(dst, Address(rscratch1, 0));
 995   }
 996 }
 997 
 998 void MacroAssembler::align(int modulus) {
 999   align(modulus, offset());
1000 }
1001 
1002 void MacroAssembler::align(int modulus, int target) {
1003   if (target % modulus != 0) {
1004     nop(modulus - (target % modulus));
1005   }
1006 }
1007 
1008 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src, Register scratch_reg) {
1009   // Used in sign-masking with aligned address.
1010   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1011   if (reachable(src)) {
1012     Assembler::andpd(dst, as_Address(src));
1013   } else {
1014     lea(scratch_reg, src);
1015     Assembler::andpd(dst, Address(scratch_reg, 0));
1016   }
1017 }
1018 
1019 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src, Register scratch_reg) {
1020   // Used in sign-masking with aligned address.
1021   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1022   if (reachable(src)) {
1023     Assembler::andps(dst, as_Address(src));
1024   } else {
1025     lea(scratch_reg, src);
1026     Assembler::andps(dst, Address(scratch_reg, 0));
1027   }
1028 }
1029 
1030 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1031   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1032 }
1033 
1034 void MacroAssembler::atomic_incl(Address counter_addr) {
1035   lock();
1036   incrementl(counter_addr);
1037 }
1038 
1039 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1040   if (reachable(counter_addr)) {
1041     atomic_incl(as_Address(counter_addr));
1042   } else {
1043     lea(scr, counter_addr);
1044     atomic_incl(Address(scr, 0));
1045   }
1046 }
1047 
1048 #ifdef _LP64
1049 void MacroAssembler::atomic_incq(Address counter_addr) {
1050   lock();
1051   incrementq(counter_addr);
1052 }
1053 
1054 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1055   if (reachable(counter_addr)) {
1056     atomic_incq(as_Address(counter_addr));
1057   } else {
1058     lea(scr, counter_addr);
1059     atomic_incq(Address(scr, 0));
1060   }
1061 }
1062 #endif
1063 
1064 // Writes to stack successive pages until offset reached to check for
1065 // stack overflow + shadow pages.  This clobbers tmp.
1066 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1067   movptr(tmp, rsp);
1068   // Bang stack for total size given plus shadow page size.
1069   // Bang one page at a time because large size can bang beyond yellow and
1070   // red zones.
1071   Label loop;
1072   bind(loop);
1073   movl(Address(tmp, (-os::vm_page_size())), size );
1074   subptr(tmp, os::vm_page_size());
1075   subl(size, os::vm_page_size());
1076   jcc(Assembler::greater, loop);
1077 
1078   // Bang down shadow pages too.
1079   // At this point, (tmp-0) is the last address touched, so don't
1080   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1081   // was post-decremented.)  Skip this address by starting at i=1, and
1082   // touch a few more pages below.  N.B.  It is important to touch all
1083   // the way down including all pages in the shadow zone.
1084   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1085     // this could be any sized move but this is can be a debugging crumb
1086     // so the bigger the better.
1087     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1088   }
1089 }
1090 
1091 void MacroAssembler::reserved_stack_check() {
1092     // testing if reserved zone needs to be enabled
1093     Label no_reserved_zone_enabling;
1094     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1095     NOT_LP64(get_thread(rsi);)
1096 
1097     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1098     jcc(Assembler::below, no_reserved_zone_enabling);
1099 
1100     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1101     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1102     should_not_reach_here();
1103 
1104     bind(no_reserved_zone_enabling);
1105 }
1106 
1107 int MacroAssembler::biased_locking_enter(Register lock_reg,
1108                                          Register obj_reg,
1109                                          Register swap_reg,
1110                                          Register tmp_reg,
1111                                          bool swap_reg_contains_mark,
1112                                          Label& done,
1113                                          Label* slow_case,
1114                                          BiasedLockingCounters* counters) {
1115   assert(UseBiasedLocking, "why call this otherwise?");
1116   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1117   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1118   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1119   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1120   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1121   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1122 
1123   if (PrintBiasedLockingStatistics && counters == NULL) {
1124     counters = BiasedLocking::counters();
1125   }
1126   // Biased locking
1127   // See whether the lock is currently biased toward our thread and
1128   // whether the epoch is still valid
1129   // Note that the runtime guarantees sufficient alignment of JavaThread
1130   // pointers to allow age to be placed into low bits
1131   // First check to see whether biasing is even enabled for this object
1132   Label cas_label;
1133   int null_check_offset = -1;
1134   if (!swap_reg_contains_mark) {
1135     null_check_offset = offset();
1136     movptr(swap_reg, mark_addr);
1137   }
1138   movptr(tmp_reg, swap_reg);
1139   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1140   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1141   jcc(Assembler::notEqual, cas_label);
1142   // The bias pattern is present in the object's header. Need to check
1143   // whether the bias owner and the epoch are both still current.
1144 #ifndef _LP64
1145   // Note that because there is no current thread register on x86_32 we
1146   // need to store off the mark word we read out of the object to
1147   // avoid reloading it and needing to recheck invariants below. This
1148   // store is unfortunate but it makes the overall code shorter and
1149   // simpler.
1150   movptr(saved_mark_addr, swap_reg);
1151 #endif
1152   if (swap_reg_contains_mark) {
1153     null_check_offset = offset();
1154   }
1155   load_prototype_header(tmp_reg, obj_reg);
1156 #ifdef _LP64
1157   orptr(tmp_reg, r15_thread);
1158   xorptr(tmp_reg, swap_reg);
1159   Register header_reg = tmp_reg;
1160 #else
1161   xorptr(tmp_reg, swap_reg);
1162   get_thread(swap_reg);
1163   xorptr(swap_reg, tmp_reg);
1164   Register header_reg = swap_reg;
1165 #endif
1166   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1167   if (counters != NULL) {
1168     cond_inc32(Assembler::zero,
1169                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1170   }
1171   jcc(Assembler::equal, done);
1172 
1173   Label try_revoke_bias;
1174   Label try_rebias;
1175 
1176   // At this point we know that the header has the bias pattern and
1177   // that we are not the bias owner in the current epoch. We need to
1178   // figure out more details about the state of the header in order to
1179   // know what operations can be legally performed on the object's
1180   // header.
1181 
1182   // If the low three bits in the xor result aren't clear, that means
1183   // the prototype header is no longer biased and we have to revoke
1184   // the bias on this object.
1185   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1186   jccb(Assembler::notZero, try_revoke_bias);
1187 
1188   // Biasing is still enabled for this data type. See whether the
1189   // epoch of the current bias is still valid, meaning that the epoch
1190   // bits of the mark word are equal to the epoch bits of the
1191   // prototype header. (Note that the prototype header's epoch bits
1192   // only change at a safepoint.) If not, attempt to rebias the object
1193   // toward the current thread. Note that we must be absolutely sure
1194   // that the current epoch is invalid in order to do this because
1195   // otherwise the manipulations it performs on the mark word are
1196   // illegal.
1197   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1198   jccb(Assembler::notZero, try_rebias);
1199 
1200   // The epoch of the current bias is still valid but we know nothing
1201   // about the owner; it might be set or it might be clear. Try to
1202   // acquire the bias of the object using an atomic operation. If this
1203   // fails we will go in to the runtime to revoke the object's bias.
1204   // Note that we first construct the presumed unbiased header so we
1205   // don't accidentally blow away another thread's valid bias.
1206   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1207   andptr(swap_reg,
1208          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1209 #ifdef _LP64
1210   movptr(tmp_reg, swap_reg);
1211   orptr(tmp_reg, r15_thread);
1212 #else
1213   get_thread(tmp_reg);
1214   orptr(tmp_reg, swap_reg);
1215 #endif
1216   lock();
1217   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1218   // If the biasing toward our thread failed, this means that
1219   // another thread succeeded in biasing it toward itself and we
1220   // need to revoke that bias. The revocation will occur in the
1221   // interpreter runtime in the slow case.
1222   if (counters != NULL) {
1223     cond_inc32(Assembler::zero,
1224                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1225   }
1226   if (slow_case != NULL) {
1227     jcc(Assembler::notZero, *slow_case);
1228   }
1229   jmp(done);
1230 
1231   bind(try_rebias);
1232   // At this point we know the epoch has expired, meaning that the
1233   // current "bias owner", if any, is actually invalid. Under these
1234   // circumstances _only_, we are allowed to use the current header's
1235   // value as the comparison value when doing the cas to acquire the
1236   // bias in the current epoch. In other words, we allow transfer of
1237   // the bias from one thread to another directly in this situation.
1238   //
1239   // FIXME: due to a lack of registers we currently blow away the age
1240   // bits in this situation. Should attempt to preserve them.
1241   load_prototype_header(tmp_reg, obj_reg);
1242 #ifdef _LP64
1243   orptr(tmp_reg, r15_thread);
1244 #else
1245   get_thread(swap_reg);
1246   orptr(tmp_reg, swap_reg);
1247   movptr(swap_reg, saved_mark_addr);
1248 #endif
1249   lock();
1250   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1251   // If the biasing toward our thread failed, then another thread
1252   // succeeded in biasing it toward itself and we need to revoke that
1253   // bias. The revocation will occur in the runtime in the slow case.
1254   if (counters != NULL) {
1255     cond_inc32(Assembler::zero,
1256                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1257   }
1258   if (slow_case != NULL) {
1259     jcc(Assembler::notZero, *slow_case);
1260   }
1261   jmp(done);
1262 
1263   bind(try_revoke_bias);
1264   // The prototype mark in the klass doesn't have the bias bit set any
1265   // more, indicating that objects of this data type are not supposed
1266   // to be biased any more. We are going to try to reset the mark of
1267   // this object to the prototype value and fall through to the
1268   // CAS-based locking scheme. Note that if our CAS fails, it means
1269   // that another thread raced us for the privilege of revoking the
1270   // bias of this particular object, so it's okay to continue in the
1271   // normal locking code.
1272   //
1273   // FIXME: due to a lack of registers we currently blow away the age
1274   // bits in this situation. Should attempt to preserve them.
1275   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1276   load_prototype_header(tmp_reg, obj_reg);
1277   lock();
1278   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1279   // Fall through to the normal CAS-based lock, because no matter what
1280   // the result of the above CAS, some thread must have succeeded in
1281   // removing the bias bit from the object's header.
1282   if (counters != NULL) {
1283     cond_inc32(Assembler::zero,
1284                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1285   }
1286 
1287   bind(cas_label);
1288 
1289   return null_check_offset;
1290 }
1291 
1292 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1293   assert(UseBiasedLocking, "why call this otherwise?");
1294 
1295   // Check for biased locking unlock case, which is a no-op
1296   // Note: we do not have to check the thread ID for two reasons.
1297   // First, the interpreter checks for IllegalMonitorStateException at
1298   // a higher level. Second, if the bias was revoked while we held the
1299   // lock, the object could not be rebiased toward another thread, so
1300   // the bias bit would be clear.
1301   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1302   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1303   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1304   jcc(Assembler::equal, done);
1305 }
1306 
1307 #ifdef COMPILER2
1308 
1309 #if INCLUDE_RTM_OPT
1310 
1311 // Update rtm_counters based on abort status
1312 // input: abort_status
1313 //        rtm_counters (RTMLockingCounters*)
1314 // flags are killed
1315 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1316 
1317   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1318   if (PrintPreciseRTMLockingStatistics) {
1319     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1320       Label check_abort;
1321       testl(abort_status, (1<<i));
1322       jccb(Assembler::equal, check_abort);
1323       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1324       bind(check_abort);
1325     }
1326   }
1327 }
1328 
1329 // Branch if (random & (count-1) != 0), count is 2^n
1330 // tmp, scr and flags are killed
1331 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1332   assert(tmp == rax, "");
1333   assert(scr == rdx, "");
1334   rdtsc(); // modifies EDX:EAX
1335   andptr(tmp, count-1);
1336   jccb(Assembler::notZero, brLabel);
1337 }
1338 
1339 // Perform abort ratio calculation, set no_rtm bit if high ratio
1340 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1341 // tmpReg, rtm_counters_Reg and flags are killed
1342 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1343                                                  Register rtm_counters_Reg,
1344                                                  RTMLockingCounters* rtm_counters,
1345                                                  Metadata* method_data) {
1346   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1347 
1348   if (RTMLockingCalculationDelay > 0) {
1349     // Delay calculation
1350     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1351     testptr(tmpReg, tmpReg);
1352     jccb(Assembler::equal, L_done);
1353   }
1354   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1355   //   Aborted transactions = abort_count * 100
1356   //   All transactions = total_count *  RTMTotalCountIncrRate
1357   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1358 
1359   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1360   cmpptr(tmpReg, RTMAbortThreshold);
1361   jccb(Assembler::below, L_check_always_rtm2);
1362   imulptr(tmpReg, tmpReg, 100);
1363 
1364   Register scrReg = rtm_counters_Reg;
1365   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1366   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1367   imulptr(scrReg, scrReg, RTMAbortRatio);
1368   cmpptr(tmpReg, scrReg);
1369   jccb(Assembler::below, L_check_always_rtm1);
1370   if (method_data != NULL) {
1371     // set rtm_state to "no rtm" in MDO
1372     mov_metadata(tmpReg, method_data);
1373     lock();
1374     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1375   }
1376   jmpb(L_done);
1377   bind(L_check_always_rtm1);
1378   // Reload RTMLockingCounters* address
1379   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1380   bind(L_check_always_rtm2);
1381   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1382   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1383   jccb(Assembler::below, L_done);
1384   if (method_data != NULL) {
1385     // set rtm_state to "always rtm" in MDO
1386     mov_metadata(tmpReg, method_data);
1387     lock();
1388     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1389   }
1390   bind(L_done);
1391 }
1392 
1393 // Update counters and perform abort ratio calculation
1394 // input:  abort_status_Reg
1395 // rtm_counters_Reg, flags are killed
1396 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1397                                    Register rtm_counters_Reg,
1398                                    RTMLockingCounters* rtm_counters,
1399                                    Metadata* method_data,
1400                                    bool profile_rtm) {
1401 
1402   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1403   // update rtm counters based on rax value at abort
1404   // reads abort_status_Reg, updates flags
1405   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1406   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1407   if (profile_rtm) {
1408     // Save abort status because abort_status_Reg is used by following code.
1409     if (RTMRetryCount > 0) {
1410       push(abort_status_Reg);
1411     }
1412     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1413     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1414     // restore abort status
1415     if (RTMRetryCount > 0) {
1416       pop(abort_status_Reg);
1417     }
1418   }
1419 }
1420 
1421 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1422 // inputs: retry_count_Reg
1423 //       : abort_status_Reg
1424 // output: retry_count_Reg decremented by 1
1425 // flags are killed
1426 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1427   Label doneRetry;
1428   assert(abort_status_Reg == rax, "");
1429   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1430   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1431   // if reason is in 0x6 and retry count != 0 then retry
1432   andptr(abort_status_Reg, 0x6);
1433   jccb(Assembler::zero, doneRetry);
1434   testl(retry_count_Reg, retry_count_Reg);
1435   jccb(Assembler::zero, doneRetry);
1436   pause();
1437   decrementl(retry_count_Reg);
1438   jmp(retryLabel);
1439   bind(doneRetry);
1440 }
1441 
1442 // Spin and retry if lock is busy,
1443 // inputs: box_Reg (monitor address)
1444 //       : retry_count_Reg
1445 // output: retry_count_Reg decremented by 1
1446 //       : clear z flag if retry count exceeded
1447 // tmp_Reg, scr_Reg, flags are killed
1448 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1449                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1450   Label SpinLoop, SpinExit, doneRetry;
1451   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1452 
1453   testl(retry_count_Reg, retry_count_Reg);
1454   jccb(Assembler::zero, doneRetry);
1455   decrementl(retry_count_Reg);
1456   movptr(scr_Reg, RTMSpinLoopCount);
1457 
1458   bind(SpinLoop);
1459   pause();
1460   decrementl(scr_Reg);
1461   jccb(Assembler::lessEqual, SpinExit);
1462   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1463   testptr(tmp_Reg, tmp_Reg);
1464   jccb(Assembler::notZero, SpinLoop);
1465 
1466   bind(SpinExit);
1467   jmp(retryLabel);
1468   bind(doneRetry);
1469   incrementl(retry_count_Reg); // clear z flag
1470 }
1471 
1472 // Use RTM for normal stack locks
1473 // Input: objReg (object to lock)
1474 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1475                                        Register retry_on_abort_count_Reg,
1476                                        RTMLockingCounters* stack_rtm_counters,
1477                                        Metadata* method_data, bool profile_rtm,
1478                                        Label& DONE_LABEL, Label& IsInflated) {
1479   assert(UseRTMForStackLocks, "why call this otherwise?");
1480   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1481   assert(tmpReg == rax, "");
1482   assert(scrReg == rdx, "");
1483   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1484 
1485   if (RTMRetryCount > 0) {
1486     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1487     bind(L_rtm_retry);
1488   }
1489   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1490   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1491   jcc(Assembler::notZero, IsInflated);
1492 
1493   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1494     Label L_noincrement;
1495     if (RTMTotalCountIncrRate > 1) {
1496       // tmpReg, scrReg and flags are killed
1497       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1498     }
1499     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1500     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1501     bind(L_noincrement);
1502   }
1503   xbegin(L_on_abort);
1504   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));       // fetch markword
1505   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1506   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1507   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1508 
1509   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1510   if (UseRTMXendForLockBusy) {
1511     xend();
1512     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1513     jmp(L_decrement_retry);
1514   }
1515   else {
1516     xabort(0);
1517   }
1518   bind(L_on_abort);
1519   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1520     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1521   }
1522   bind(L_decrement_retry);
1523   if (RTMRetryCount > 0) {
1524     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1525     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1526   }
1527 }
1528 
1529 // Use RTM for inflating locks
1530 // inputs: objReg (object to lock)
1531 //         boxReg (on-stack box address (displaced header location) - KILLED)
1532 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1533 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1534                                           Register scrReg, Register retry_on_busy_count_Reg,
1535                                           Register retry_on_abort_count_Reg,
1536                                           RTMLockingCounters* rtm_counters,
1537                                           Metadata* method_data, bool profile_rtm,
1538                                           Label& DONE_LABEL) {
1539   assert(UseRTMLocking, "why call this otherwise?");
1540   assert(tmpReg == rax, "");
1541   assert(scrReg == rdx, "");
1542   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1543   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1544 
1545   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1546   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1547   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1548 
1549   if (RTMRetryCount > 0) {
1550     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1551     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1552     bind(L_rtm_retry);
1553   }
1554   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1555     Label L_noincrement;
1556     if (RTMTotalCountIncrRate > 1) {
1557       // tmpReg, scrReg and flags are killed
1558       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1559     }
1560     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1561     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1562     bind(L_noincrement);
1563   }
1564   xbegin(L_on_abort);
1565   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1566   movptr(tmpReg, Address(tmpReg, owner_offset));
1567   testptr(tmpReg, tmpReg);
1568   jcc(Assembler::zero, DONE_LABEL);
1569   if (UseRTMXendForLockBusy) {
1570     xend();
1571     jmp(L_decrement_retry);
1572   }
1573   else {
1574     xabort(0);
1575   }
1576   bind(L_on_abort);
1577   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1578   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1579     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1580   }
1581   if (RTMRetryCount > 0) {
1582     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1583     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1584   }
1585 
1586   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1587   testptr(tmpReg, tmpReg) ;
1588   jccb(Assembler::notZero, L_decrement_retry) ;
1589 
1590   // Appears unlocked - try to swing _owner from null to non-null.
1591   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1592 #ifdef _LP64
1593   Register threadReg = r15_thread;
1594 #else
1595   get_thread(scrReg);
1596   Register threadReg = scrReg;
1597 #endif
1598   lock();
1599   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1600 
1601   if (RTMRetryCount > 0) {
1602     // success done else retry
1603     jccb(Assembler::equal, DONE_LABEL) ;
1604     bind(L_decrement_retry);
1605     // Spin and retry if lock is busy.
1606     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1607   }
1608   else {
1609     bind(L_decrement_retry);
1610   }
1611 }
1612 
1613 #endif //  INCLUDE_RTM_OPT
1614 
1615 // Fast_Lock and Fast_Unlock used by C2
1616 
1617 // Because the transitions from emitted code to the runtime
1618 // monitorenter/exit helper stubs are so slow it's critical that
1619 // we inline both the stack-locking fast-path and the inflated fast path.
1620 //
1621 // See also: cmpFastLock and cmpFastUnlock.
1622 //
1623 // What follows is a specialized inline transliteration of the code
1624 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1625 // another option would be to emit TrySlowEnter and TrySlowExit methods
1626 // at startup-time.  These methods would accept arguments as
1627 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1628 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1629 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1630 // In practice, however, the # of lock sites is bounded and is usually small.
1631 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1632 // if the processor uses simple bimodal branch predictors keyed by EIP
1633 // Since the helper routines would be called from multiple synchronization
1634 // sites.
1635 //
1636 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1637 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1638 // to those specialized methods.  That'd give us a mostly platform-independent
1639 // implementation that the JITs could optimize and inline at their pleasure.
1640 // Done correctly, the only time we'd need to cross to native could would be
1641 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1642 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1643 // (b) explicit barriers or fence operations.
1644 //
1645 // TODO:
1646 //
1647 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1648 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1649 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1650 //    the lock operators would typically be faster than reifying Self.
1651 //
1652 // *  Ideally I'd define the primitives as:
1653 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1654 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1655 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1656 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1657 //    Furthermore the register assignments are overconstrained, possibly resulting in
1658 //    sub-optimal code near the synchronization site.
1659 //
1660 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1661 //    Alternately, use a better sp-proximity test.
1662 //
1663 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1664 //    Either one is sufficient to uniquely identify a thread.
1665 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1666 //
1667 // *  Intrinsify notify() and notifyAll() for the common cases where the
1668 //    object is locked by the calling thread but the waitlist is empty.
1669 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1670 //
1671 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1672 //    But beware of excessive branch density on AMD Opterons.
1673 //
1674 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1675 //    or failure of the fast-path.  If the fast-path fails then we pass
1676 //    control to the slow-path, typically in C.  In Fast_Lock and
1677 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1678 //    will emit a conditional branch immediately after the node.
1679 //    So we have branches to branches and lots of ICC.ZF games.
1680 //    Instead, it might be better to have C2 pass a "FailureLabel"
1681 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1682 //    will drop through the node.  ICC.ZF is undefined at exit.
1683 //    In the case of failure, the node will branch directly to the
1684 //    FailureLabel
1685 
1686 
1687 // obj: object to lock
1688 // box: on-stack box address (displaced header location) - KILLED
1689 // rax,: tmp -- KILLED
1690 // scr: tmp -- KILLED
1691 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1692                                Register scrReg, Register cx1Reg, Register cx2Reg,
1693                                BiasedLockingCounters* counters,
1694                                RTMLockingCounters* rtm_counters,
1695                                RTMLockingCounters* stack_rtm_counters,
1696                                Metadata* method_data,
1697                                bool use_rtm, bool profile_rtm) {
1698   // Ensure the register assignments are disjoint
1699   assert(tmpReg == rax, "");
1700 
1701   if (use_rtm) {
1702     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1703   } else {
1704     assert(cx1Reg == noreg, "");
1705     assert(cx2Reg == noreg, "");
1706     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1707   }
1708 
1709   if (counters != NULL) {
1710     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1711   }
1712 
1713   // Possible cases that we'll encounter in fast_lock
1714   // ------------------------------------------------
1715   // * Inflated
1716   //    -- unlocked
1717   //    -- Locked
1718   //       = by self
1719   //       = by other
1720   // * biased
1721   //    -- by Self
1722   //    -- by other
1723   // * neutral
1724   // * stack-locked
1725   //    -- by self
1726   //       = sp-proximity test hits
1727   //       = sp-proximity test generates false-negative
1728   //    -- by other
1729   //
1730 
1731   Label IsInflated, DONE_LABEL;
1732 
1733   // it's stack-locked, biased or neutral
1734   // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1735   // order to reduce the number of conditional branches in the most common cases.
1736   // Beware -- there's a subtle invariant that fetch of the markword
1737   // at [FETCH], below, will never observe a biased encoding (*101b).
1738   // If this invariant is not held we risk exclusion (safety) failure.
1739   if (UseBiasedLocking && !UseOptoBiasInlining) {
1740     biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1741   }
1742 
1743 #if INCLUDE_RTM_OPT
1744   if (UseRTMForStackLocks && use_rtm) {
1745     rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1746                       stack_rtm_counters, method_data, profile_rtm,
1747                       DONE_LABEL, IsInflated);
1748   }
1749 #endif // INCLUDE_RTM_OPT
1750 
1751   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));          // [FETCH]
1752   testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1753   jccb(Assembler::notZero, IsInflated);
1754 
1755   // Attempt stack-locking ...
1756   orptr (tmpReg, markOopDesc::unlocked_value);
1757   if (EnableValhalla && !UseBiasedLocking) {
1758     // Mask always_locked bit such that we go to the slow path if object is a value type
1759     andptr(tmpReg, ~markOopDesc::biased_lock_bit_in_place);
1760   }
1761   movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1762   lock();
1763   cmpxchgptr(boxReg, Address(objReg, oopDesc::mark_offset_in_bytes()));      // Updates tmpReg
1764   if (counters != NULL) {
1765     cond_inc32(Assembler::equal,
1766                ExternalAddress((address)counters->fast_path_entry_count_addr()));
1767   }
1768   jcc(Assembler::equal, DONE_LABEL);           // Success
1769 
1770   // Recursive locking.
1771   // The object is stack-locked: markword contains stack pointer to BasicLock.
1772   // Locked by current thread if difference with current SP is less than one page.
1773   subptr(tmpReg, rsp);
1774   // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1775   andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1776   movptr(Address(boxReg, 0), tmpReg);
1777   if (counters != NULL) {
1778     cond_inc32(Assembler::equal,
1779                ExternalAddress((address)counters->fast_path_entry_count_addr()));
1780   }
1781   jmp(DONE_LABEL);
1782 
1783   bind(IsInflated);
1784   // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1785 
1786 #if INCLUDE_RTM_OPT
1787   // Use the same RTM locking code in 32- and 64-bit VM.
1788   if (use_rtm) {
1789     rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1790                          rtm_counters, method_data, profile_rtm, DONE_LABEL);
1791   } else {
1792 #endif // INCLUDE_RTM_OPT
1793 
1794 #ifndef _LP64
1795   // The object is inflated.
1796 
1797   // boxReg refers to the on-stack BasicLock in the current frame.
1798   // We'd like to write:
1799   //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1800   // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1801   // additional latency as we have another ST in the store buffer that must drain.
1802 
1803   // avoid ST-before-CAS
1804   // register juggle because we need tmpReg for cmpxchgptr below
1805   movptr(scrReg, boxReg);
1806   movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1807 
1808   // Optimistic form: consider XORL tmpReg,tmpReg
1809   movptr(tmpReg, NULL_WORD);
1810 
1811   // Appears unlocked - try to swing _owner from null to non-null.
1812   // Ideally, I'd manifest "Self" with get_thread and then attempt
1813   // to CAS the register containing Self into m->Owner.
1814   // But we don't have enough registers, so instead we can either try to CAS
1815   // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1816   // we later store "Self" into m->Owner.  Transiently storing a stack address
1817   // (rsp or the address of the box) into  m->owner is harmless.
1818   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1819   lock();
1820   cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1821   movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1822   // If we weren't able to swing _owner from NULL to the BasicLock
1823   // then take the slow path.
1824   jccb  (Assembler::notZero, DONE_LABEL);
1825   // update _owner from BasicLock to thread
1826   get_thread (scrReg);                    // beware: clobbers ICCs
1827   movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1828   xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1829 
1830   // If the CAS fails we can either retry or pass control to the slow-path.
1831   // We use the latter tactic.
1832   // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1833   // If the CAS was successful ...
1834   //   Self has acquired the lock
1835   //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1836   // Intentional fall-through into DONE_LABEL ...
1837 #else // _LP64
1838   // It's inflated
1839   movq(scrReg, tmpReg);
1840   xorq(tmpReg, tmpReg);
1841 
1842   lock();
1843   cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1844   // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1845   // Without cast to int32_t movptr will destroy r10 which is typically obj.
1846   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1847   // Intentional fall-through into DONE_LABEL ...
1848   // Propagate ICC.ZF from CAS above into DONE_LABEL.
1849 #endif // _LP64
1850 #if INCLUDE_RTM_OPT
1851   } // use_rtm()
1852 #endif
1853   // DONE_LABEL is a hot target - we'd really like to place it at the
1854   // start of cache line by padding with NOPs.
1855   // See the AMD and Intel software optimization manuals for the
1856   // most efficient "long" NOP encodings.
1857   // Unfortunately none of our alignment mechanisms suffice.
1858   bind(DONE_LABEL);
1859 
1860   // At DONE_LABEL the icc ZFlag is set as follows ...
1861   // Fast_Unlock uses the same protocol.
1862   // ZFlag == 1 -> Success
1863   // ZFlag == 0 -> Failure - force control through the slow-path
1864 }
1865 
1866 // obj: object to unlock
1867 // box: box address (displaced header location), killed.  Must be EAX.
1868 // tmp: killed, cannot be obj nor box.
1869 //
1870 // Some commentary on balanced locking:
1871 //
1872 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1873 // Methods that don't have provably balanced locking are forced to run in the
1874 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1875 // The interpreter provides two properties:
1876 // I1:  At return-time the interpreter automatically and quietly unlocks any
1877 //      objects acquired the current activation (frame).  Recall that the
1878 //      interpreter maintains an on-stack list of locks currently held by
1879 //      a frame.
1880 // I2:  If a method attempts to unlock an object that is not held by the
1881 //      the frame the interpreter throws IMSX.
1882 //
1883 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1884 // B() doesn't have provably balanced locking so it runs in the interpreter.
1885 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1886 // is still locked by A().
1887 //
1888 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1889 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1890 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1891 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1892 // Arguably given that the spec legislates the JNI case as undefined our implementation
1893 // could reasonably *avoid* checking owner in Fast_Unlock().
1894 // In the interest of performance we elide m->Owner==Self check in unlock.
1895 // A perfectly viable alternative is to elide the owner check except when
1896 // Xcheck:jni is enabled.
1897 
1898 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1899   assert(boxReg == rax, "");
1900   assert_different_registers(objReg, boxReg, tmpReg);
1901 
1902   Label DONE_LABEL, Stacked, CheckSucc;
1903 
1904   // Critically, the biased locking test must have precedence over
1905   // and appear before the (box->dhw == 0) recursive stack-lock test.
1906   if (UseBiasedLocking && !UseOptoBiasInlining) {
1907     biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1908   }
1909 
1910 #if INCLUDE_RTM_OPT
1911   if (UseRTMForStackLocks && use_rtm) {
1912     assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1913     Label L_regular_unlock;
1914     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));           // fetch markword
1915     andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1916     cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1917     jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1918     xend();                                       // otherwise end...
1919     jmp(DONE_LABEL);                              // ... and we're done
1920     bind(L_regular_unlock);
1921   }
1922 #endif
1923 
1924   cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
1925   jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
1926   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));             // Examine the object's markword
1927   testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
1928   jccb  (Assembler::zero, Stacked);
1929 
1930   // It's inflated.
1931 #if INCLUDE_RTM_OPT
1932   if (use_rtm) {
1933     Label L_regular_inflated_unlock;
1934     int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1935     movptr(boxReg, Address(tmpReg, owner_offset));
1936     testptr(boxReg, boxReg);
1937     jccb(Assembler::notZero, L_regular_inflated_unlock);
1938     xend();
1939     jmpb(DONE_LABEL);
1940     bind(L_regular_inflated_unlock);
1941   }
1942 #endif
1943 
1944   // Despite our balanced locking property we still check that m->_owner == Self
1945   // as java routines or native JNI code called by this thread might
1946   // have released the lock.
1947   // Refer to the comments in synchronizer.cpp for how we might encode extra
1948   // state in _succ so we can avoid fetching EntryList|cxq.
1949   //
1950   // I'd like to add more cases in fast_lock() and fast_unlock() --
1951   // such as recursive enter and exit -- but we have to be wary of
1952   // I$ bloat, T$ effects and BP$ effects.
1953   //
1954   // If there's no contention try a 1-0 exit.  That is, exit without
1955   // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
1956   // we detect and recover from the race that the 1-0 exit admits.
1957   //
1958   // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
1959   // before it STs null into _owner, releasing the lock.  Updates
1960   // to data protected by the critical section must be visible before
1961   // we drop the lock (and thus before any other thread could acquire
1962   // the lock and observe the fields protected by the lock).
1963   // IA32's memory-model is SPO, so STs are ordered with respect to
1964   // each other and there's no need for an explicit barrier (fence).
1965   // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
1966 #ifndef _LP64
1967   get_thread (boxReg);
1968 
1969   // Note that we could employ various encoding schemes to reduce
1970   // the number of loads below (currently 4) to just 2 or 3.
1971   // Refer to the comments in synchronizer.cpp.
1972   // In practice the chain of fetches doesn't seem to impact performance, however.
1973   xorptr(boxReg, boxReg);
1974   orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
1975   jccb  (Assembler::notZero, DONE_LABEL);
1976   movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
1977   orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
1978   jccb  (Assembler::notZero, CheckSucc);
1979   movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
1980   jmpb  (DONE_LABEL);
1981 
1982   bind (Stacked);
1983   // It's not inflated and it's not recursively stack-locked and it's not biased.
1984   // It must be stack-locked.
1985   // Try to reset the header to displaced header.
1986   // The "box" value on the stack is stable, so we can reload
1987   // and be assured we observe the same value as above.
1988   movptr(tmpReg, Address(boxReg, 0));
1989   lock();
1990   cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
1991   // Intention fall-thru into DONE_LABEL
1992 
1993   // DONE_LABEL is a hot target - we'd really like to place it at the
1994   // start of cache line by padding with NOPs.
1995   // See the AMD and Intel software optimization manuals for the
1996   // most efficient "long" NOP encodings.
1997   // Unfortunately none of our alignment mechanisms suffice.
1998   bind (CheckSucc);
1999 #else // _LP64
2000   // It's inflated
2001   xorptr(boxReg, boxReg);
2002   orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2003   jccb  (Assembler::notZero, DONE_LABEL);
2004   movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2005   orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2006   jccb  (Assembler::notZero, CheckSucc);
2007   movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2008   jmpb  (DONE_LABEL);
2009 
2010   // Try to avoid passing control into the slow_path ...
2011   Label LSuccess, LGoSlowPath ;
2012   bind  (CheckSucc);
2013 
2014   // The following optional optimization can be elided if necessary
2015   // Effectively: if (succ == null) goto SlowPath
2016   // The code reduces the window for a race, however,
2017   // and thus benefits performance.
2018   cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2019   jccb  (Assembler::zero, LGoSlowPath);
2020 
2021   xorptr(boxReg, boxReg);
2022   movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2023 
2024   // Memory barrier/fence
2025   // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2026   // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2027   // This is faster on Nehalem and AMD Shanghai/Barcelona.
2028   // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2029   // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2030   // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2031   lock(); addl(Address(rsp, 0), 0);
2032 
2033   cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2034   jccb  (Assembler::notZero, LSuccess);
2035 
2036   // Rare inopportune interleaving - race.
2037   // The successor vanished in the small window above.
2038   // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2039   // We need to ensure progress and succession.
2040   // Try to reacquire the lock.
2041   // If that fails then the new owner is responsible for succession and this
2042   // thread needs to take no further action and can exit via the fast path (success).
2043   // If the re-acquire succeeds then pass control into the slow path.
2044   // As implemented, this latter mode is horrible because we generated more
2045   // coherence traffic on the lock *and* artifically extended the critical section
2046   // length while by virtue of passing control into the slow path.
2047 
2048   // box is really RAX -- the following CMPXCHG depends on that binding
2049   // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2050   lock();
2051   cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2052   // There's no successor so we tried to regrab the lock.
2053   // If that didn't work, then another thread grabbed the
2054   // lock so we're done (and exit was a success).
2055   jccb  (Assembler::notEqual, LSuccess);
2056   // Intentional fall-through into slow-path
2057 
2058   bind  (LGoSlowPath);
2059   orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2060   jmpb  (DONE_LABEL);
2061 
2062   bind  (LSuccess);
2063   testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2064   jmpb  (DONE_LABEL);
2065 
2066   bind  (Stacked);
2067   movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2068   lock();
2069   cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2070 
2071 #endif
2072   bind(DONE_LABEL);
2073 }
2074 #endif // COMPILER2
2075 
2076 void MacroAssembler::c2bool(Register x) {
2077   // implements x == 0 ? 0 : 1
2078   // note: must only look at least-significant byte of x
2079   //       since C-style booleans are stored in one byte
2080   //       only! (was bug)
2081   andl(x, 0xFF);
2082   setb(Assembler::notZero, x);
2083 }
2084 
2085 // Wouldn't need if AddressLiteral version had new name
2086 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2087   Assembler::call(L, rtype);
2088 }
2089 
2090 void MacroAssembler::call(Register entry) {
2091   Assembler::call(entry);
2092 }
2093 
2094 void MacroAssembler::call(AddressLiteral entry) {
2095   if (reachable(entry)) {
2096     Assembler::call_literal(entry.target(), entry.rspec());
2097   } else {
2098     lea(rscratch1, entry);
2099     Assembler::call(rscratch1);
2100   }
2101 }
2102 
2103 void MacroAssembler::ic_call(address entry, jint method_index) {
2104   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2105   movptr(rax, (intptr_t)Universe::non_oop_word());
2106   call(AddressLiteral(entry, rh));
2107 }
2108 
2109 // Implementation of call_VM versions
2110 
2111 void MacroAssembler::call_VM(Register oop_result,
2112                              address entry_point,
2113                              bool check_exceptions) {
2114   Label C, E;
2115   call(C, relocInfo::none);
2116   jmp(E);
2117 
2118   bind(C);
2119   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2120   ret(0);
2121 
2122   bind(E);
2123 }
2124 
2125 void MacroAssembler::call_VM(Register oop_result,
2126                              address entry_point,
2127                              Register arg_1,
2128                              bool check_exceptions) {
2129   Label C, E;
2130   call(C, relocInfo::none);
2131   jmp(E);
2132 
2133   bind(C);
2134   pass_arg1(this, arg_1);
2135   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2136   ret(0);
2137 
2138   bind(E);
2139 }
2140 
2141 void MacroAssembler::call_VM(Register oop_result,
2142                              address entry_point,
2143                              Register arg_1,
2144                              Register arg_2,
2145                              bool check_exceptions) {
2146   Label C, E;
2147   call(C, relocInfo::none);
2148   jmp(E);
2149 
2150   bind(C);
2151 
2152   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2153 
2154   pass_arg2(this, arg_2);
2155   pass_arg1(this, arg_1);
2156   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2157   ret(0);
2158 
2159   bind(E);
2160 }
2161 
2162 void MacroAssembler::call_VM(Register oop_result,
2163                              address entry_point,
2164                              Register arg_1,
2165                              Register arg_2,
2166                              Register arg_3,
2167                              bool check_exceptions) {
2168   Label C, E;
2169   call(C, relocInfo::none);
2170   jmp(E);
2171 
2172   bind(C);
2173 
2174   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2175   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2176   pass_arg3(this, arg_3);
2177 
2178   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2179   pass_arg2(this, arg_2);
2180 
2181   pass_arg1(this, arg_1);
2182   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2183   ret(0);
2184 
2185   bind(E);
2186 }
2187 
2188 void MacroAssembler::call_VM(Register oop_result,
2189                              Register last_java_sp,
2190                              address entry_point,
2191                              int number_of_arguments,
2192                              bool check_exceptions) {
2193   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2194   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2195 }
2196 
2197 void MacroAssembler::call_VM(Register oop_result,
2198                              Register last_java_sp,
2199                              address entry_point,
2200                              Register arg_1,
2201                              bool check_exceptions) {
2202   pass_arg1(this, arg_1);
2203   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2204 }
2205 
2206 void MacroAssembler::call_VM(Register oop_result,
2207                              Register last_java_sp,
2208                              address entry_point,
2209                              Register arg_1,
2210                              Register arg_2,
2211                              bool check_exceptions) {
2212 
2213   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2214   pass_arg2(this, arg_2);
2215   pass_arg1(this, arg_1);
2216   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2217 }
2218 
2219 void MacroAssembler::call_VM(Register oop_result,
2220                              Register last_java_sp,
2221                              address entry_point,
2222                              Register arg_1,
2223                              Register arg_2,
2224                              Register arg_3,
2225                              bool check_exceptions) {
2226   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2227   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2228   pass_arg3(this, arg_3);
2229   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2230   pass_arg2(this, arg_2);
2231   pass_arg1(this, arg_1);
2232   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2233 }
2234 
2235 void MacroAssembler::super_call_VM(Register oop_result,
2236                                    Register last_java_sp,
2237                                    address entry_point,
2238                                    int number_of_arguments,
2239                                    bool check_exceptions) {
2240   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2241   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2242 }
2243 
2244 void MacroAssembler::super_call_VM(Register oop_result,
2245                                    Register last_java_sp,
2246                                    address entry_point,
2247                                    Register arg_1,
2248                                    bool check_exceptions) {
2249   pass_arg1(this, arg_1);
2250   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2251 }
2252 
2253 void MacroAssembler::super_call_VM(Register oop_result,
2254                                    Register last_java_sp,
2255                                    address entry_point,
2256                                    Register arg_1,
2257                                    Register arg_2,
2258                                    bool check_exceptions) {
2259 
2260   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2261   pass_arg2(this, arg_2);
2262   pass_arg1(this, arg_1);
2263   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2264 }
2265 
2266 void MacroAssembler::super_call_VM(Register oop_result,
2267                                    Register last_java_sp,
2268                                    address entry_point,
2269                                    Register arg_1,
2270                                    Register arg_2,
2271                                    Register arg_3,
2272                                    bool check_exceptions) {
2273   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2274   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2275   pass_arg3(this, arg_3);
2276   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2277   pass_arg2(this, arg_2);
2278   pass_arg1(this, arg_1);
2279   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2280 }
2281 
2282 void MacroAssembler::call_VM_base(Register oop_result,
2283                                   Register java_thread,
2284                                   Register last_java_sp,
2285                                   address  entry_point,
2286                                   int      number_of_arguments,
2287                                   bool     check_exceptions) {
2288   // determine java_thread register
2289   if (!java_thread->is_valid()) {
2290 #ifdef _LP64
2291     java_thread = r15_thread;
2292 #else
2293     java_thread = rdi;
2294     get_thread(java_thread);
2295 #endif // LP64
2296   }
2297   // determine last_java_sp register
2298   if (!last_java_sp->is_valid()) {
2299     last_java_sp = rsp;
2300   }
2301   // debugging support
2302   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2303   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2304 #ifdef ASSERT
2305   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2306   // r12 is the heapbase.
2307   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2308 #endif // ASSERT
2309 
2310   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2311   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2312 
2313   // push java thread (becomes first argument of C function)
2314 
2315   NOT_LP64(push(java_thread); number_of_arguments++);
2316   LP64_ONLY(mov(c_rarg0, r15_thread));
2317 
2318   // set last Java frame before call
2319   assert(last_java_sp != rbp, "can't use ebp/rbp");
2320 
2321   // Only interpreter should have to set fp
2322   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2323 
2324   // do the call, remove parameters
2325   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2326 
2327   // restore the thread (cannot use the pushed argument since arguments
2328   // may be overwritten by C code generated by an optimizing compiler);
2329   // however can use the register value directly if it is callee saved.
2330   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2331     // rdi & rsi (also r15) are callee saved -> nothing to do
2332 #ifdef ASSERT
2333     guarantee(java_thread != rax, "change this code");
2334     push(rax);
2335     { Label L;
2336       get_thread(rax);
2337       cmpptr(java_thread, rax);
2338       jcc(Assembler::equal, L);
2339       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2340       bind(L);
2341     }
2342     pop(rax);
2343 #endif
2344   } else {
2345     get_thread(java_thread);
2346   }
2347   // reset last Java frame
2348   // Only interpreter should have to clear fp
2349   reset_last_Java_frame(java_thread, true);
2350 
2351    // C++ interp handles this in the interpreter
2352   check_and_handle_popframe(java_thread);
2353   check_and_handle_earlyret(java_thread);
2354 
2355   if (check_exceptions) {
2356     // check for pending exceptions (java_thread is set upon return)
2357     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2358 #ifndef _LP64
2359     jump_cc(Assembler::notEqual,
2360             RuntimeAddress(StubRoutines::forward_exception_entry()));
2361 #else
2362     // This used to conditionally jump to forward_exception however it is
2363     // possible if we relocate that the branch will not reach. So we must jump
2364     // around so we can always reach
2365 
2366     Label ok;
2367     jcc(Assembler::equal, ok);
2368     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2369     bind(ok);
2370 #endif // LP64
2371   }
2372 
2373   // get oop result if there is one and reset the value in the thread
2374   if (oop_result->is_valid()) {
2375     get_vm_result(oop_result, java_thread);
2376   }
2377 }
2378 
2379 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2380 
2381   // Calculate the value for last_Java_sp
2382   // somewhat subtle. call_VM does an intermediate call
2383   // which places a return address on the stack just under the
2384   // stack pointer as the user finsihed with it. This allows
2385   // use to retrieve last_Java_pc from last_Java_sp[-1].
2386   // On 32bit we then have to push additional args on the stack to accomplish
2387   // the actual requested call. On 64bit call_VM only can use register args
2388   // so the only extra space is the return address that call_VM created.
2389   // This hopefully explains the calculations here.
2390 
2391 #ifdef _LP64
2392   // We've pushed one address, correct last_Java_sp
2393   lea(rax, Address(rsp, wordSize));
2394 #else
2395   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2396 #endif // LP64
2397 
2398   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2399 
2400 }
2401 
2402 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2403 void MacroAssembler::call_VM_leaf0(address entry_point) {
2404   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2405 }
2406 
2407 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2408   call_VM_leaf_base(entry_point, number_of_arguments);
2409 }
2410 
2411 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2412   pass_arg0(this, arg_0);
2413   call_VM_leaf(entry_point, 1);
2414 }
2415 
2416 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2417 
2418   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2419   pass_arg1(this, arg_1);
2420   pass_arg0(this, arg_0);
2421   call_VM_leaf(entry_point, 2);
2422 }
2423 
2424 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2425   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2426   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2427   pass_arg2(this, arg_2);
2428   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2429   pass_arg1(this, arg_1);
2430   pass_arg0(this, arg_0);
2431   call_VM_leaf(entry_point, 3);
2432 }
2433 
2434 void MacroAssembler::super_call_VM_leaf(address entry_point) {
2435   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2436 }
2437 
2438 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2439   pass_arg0(this, arg_0);
2440   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2441 }
2442 
2443 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2444 
2445   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2446   pass_arg1(this, arg_1);
2447   pass_arg0(this, arg_0);
2448   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2449 }
2450 
2451 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2452   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2453   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2454   pass_arg2(this, arg_2);
2455   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2456   pass_arg1(this, arg_1);
2457   pass_arg0(this, arg_0);
2458   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2459 }
2460 
2461 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2462   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2463   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2464   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2465   pass_arg3(this, arg_3);
2466   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2467   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2468   pass_arg2(this, arg_2);
2469   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2470   pass_arg1(this, arg_1);
2471   pass_arg0(this, arg_0);
2472   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2473 }
2474 
2475 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2476   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2477   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2478   verify_oop(oop_result, "broken oop in call_VM_base");
2479 }
2480 
2481 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2482   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2483   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2484 }
2485 
2486 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2487 }
2488 
2489 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2490 }
2491 
2492 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2493   if (reachable(src1)) {
2494     cmpl(as_Address(src1), imm);
2495   } else {
2496     lea(rscratch1, src1);
2497     cmpl(Address(rscratch1, 0), imm);
2498   }
2499 }
2500 
2501 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2502   assert(!src2.is_lval(), "use cmpptr");
2503   if (reachable(src2)) {
2504     cmpl(src1, as_Address(src2));
2505   } else {
2506     lea(rscratch1, src2);
2507     cmpl(src1, Address(rscratch1, 0));
2508   }
2509 }
2510 
2511 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2512   Assembler::cmpl(src1, imm);
2513 }
2514 
2515 void MacroAssembler::cmp32(Register src1, Address src2) {
2516   Assembler::cmpl(src1, src2);
2517 }
2518 
2519 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2520   ucomisd(opr1, opr2);
2521 
2522   Label L;
2523   if (unordered_is_less) {
2524     movl(dst, -1);
2525     jcc(Assembler::parity, L);
2526     jcc(Assembler::below , L);
2527     movl(dst, 0);
2528     jcc(Assembler::equal , L);
2529     increment(dst);
2530   } else { // unordered is greater
2531     movl(dst, 1);
2532     jcc(Assembler::parity, L);
2533     jcc(Assembler::above , L);
2534     movl(dst, 0);
2535     jcc(Assembler::equal , L);
2536     decrementl(dst);
2537   }
2538   bind(L);
2539 }
2540 
2541 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2542   ucomiss(opr1, opr2);
2543 
2544   Label L;
2545   if (unordered_is_less) {
2546     movl(dst, -1);
2547     jcc(Assembler::parity, L);
2548     jcc(Assembler::below , L);
2549     movl(dst, 0);
2550     jcc(Assembler::equal , L);
2551     increment(dst);
2552   } else { // unordered is greater
2553     movl(dst, 1);
2554     jcc(Assembler::parity, L);
2555     jcc(Assembler::above , L);
2556     movl(dst, 0);
2557     jcc(Assembler::equal , L);
2558     decrementl(dst);
2559   }
2560   bind(L);
2561 }
2562 
2563 
2564 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2565   if (reachable(src1)) {
2566     cmpb(as_Address(src1), imm);
2567   } else {
2568     lea(rscratch1, src1);
2569     cmpb(Address(rscratch1, 0), imm);
2570   }
2571 }
2572 
2573 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2574 #ifdef _LP64
2575   if (src2.is_lval()) {
2576     movptr(rscratch1, src2);
2577     Assembler::cmpq(src1, rscratch1);
2578   } else if (reachable(src2)) {
2579     cmpq(src1, as_Address(src2));
2580   } else {
2581     lea(rscratch1, src2);
2582     Assembler::cmpq(src1, Address(rscratch1, 0));
2583   }
2584 #else
2585   if (src2.is_lval()) {
2586     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2587   } else {
2588     cmpl(src1, as_Address(src2));
2589   }
2590 #endif // _LP64
2591 }
2592 
2593 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2594   assert(src2.is_lval(), "not a mem-mem compare");
2595 #ifdef _LP64
2596   // moves src2's literal address
2597   movptr(rscratch1, src2);
2598   Assembler::cmpq(src1, rscratch1);
2599 #else
2600   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2601 #endif // _LP64
2602 }
2603 
2604 void MacroAssembler::cmpoop(Register src1, Register src2) {
2605   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
2606   bs->obj_equals(this, src1, src2);
2607 }
2608 
2609 void MacroAssembler::cmpoop(Register src1, Address src2) {
2610   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
2611   bs->obj_equals(this, src1, src2);
2612 }
2613 
2614 #ifdef _LP64
2615 void MacroAssembler::cmpoop(Register src1, jobject src2) {
2616   movoop(rscratch1, src2);
2617   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
2618   bs->obj_equals(this, src1, rscratch1);
2619 }
2620 #endif
2621 
2622 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2623   if (reachable(adr)) {
2624     lock();
2625     cmpxchgptr(reg, as_Address(adr));
2626   } else {
2627     lea(rscratch1, adr);
2628     lock();
2629     cmpxchgptr(reg, Address(rscratch1, 0));
2630   }
2631 }
2632 
2633 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2634   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2635 }
2636 
2637 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2638   if (reachable(src)) {
2639     Assembler::comisd(dst, as_Address(src));
2640   } else {
2641     lea(rscratch1, src);
2642     Assembler::comisd(dst, Address(rscratch1, 0));
2643   }
2644 }
2645 
2646 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2647   if (reachable(src)) {
2648     Assembler::comiss(dst, as_Address(src));
2649   } else {
2650     lea(rscratch1, src);
2651     Assembler::comiss(dst, Address(rscratch1, 0));
2652   }
2653 }
2654 
2655 
2656 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2657   Condition negated_cond = negate_condition(cond);
2658   Label L;
2659   jcc(negated_cond, L);
2660   pushf(); // Preserve flags
2661   atomic_incl(counter_addr);
2662   popf();
2663   bind(L);
2664 }
2665 
2666 int MacroAssembler::corrected_idivl(Register reg) {
2667   // Full implementation of Java idiv and irem; checks for
2668   // special case as described in JVM spec., p.243 & p.271.
2669   // The function returns the (pc) offset of the idivl
2670   // instruction - may be needed for implicit exceptions.
2671   //
2672   //         normal case                           special case
2673   //
2674   // input : rax,: dividend                         min_int
2675   //         reg: divisor   (may not be rax,/rdx)   -1
2676   //
2677   // output: rax,: quotient  (= rax, idiv reg)       min_int
2678   //         rdx: remainder (= rax, irem reg)       0
2679   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2680   const int min_int = 0x80000000;
2681   Label normal_case, special_case;
2682 
2683   // check for special case
2684   cmpl(rax, min_int);
2685   jcc(Assembler::notEqual, normal_case);
2686   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2687   cmpl(reg, -1);
2688   jcc(Assembler::equal, special_case);
2689 
2690   // handle normal case
2691   bind(normal_case);
2692   cdql();
2693   int idivl_offset = offset();
2694   idivl(reg);
2695 
2696   // normal and special case exit
2697   bind(special_case);
2698 
2699   return idivl_offset;
2700 }
2701 
2702 
2703 
2704 void MacroAssembler::decrementl(Register reg, int value) {
2705   if (value == min_jint) {subl(reg, value) ; return; }
2706   if (value <  0) { incrementl(reg, -value); return; }
2707   if (value == 0) {                        ; return; }
2708   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2709   /* else */      { subl(reg, value)       ; return; }
2710 }
2711 
2712 void MacroAssembler::decrementl(Address dst, int value) {
2713   if (value == min_jint) {subl(dst, value) ; return; }
2714   if (value <  0) { incrementl(dst, -value); return; }
2715   if (value == 0) {                        ; return; }
2716   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2717   /* else */      { subl(dst, value)       ; return; }
2718 }
2719 
2720 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2721   assert (shift_value > 0, "illegal shift value");
2722   Label _is_positive;
2723   testl (reg, reg);
2724   jcc (Assembler::positive, _is_positive);
2725   int offset = (1 << shift_value) - 1 ;
2726 
2727   if (offset == 1) {
2728     incrementl(reg);
2729   } else {
2730     addl(reg, offset);
2731   }
2732 
2733   bind (_is_positive);
2734   sarl(reg, shift_value);
2735 }
2736 
2737 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2738   if (reachable(src)) {
2739     Assembler::divsd(dst, as_Address(src));
2740   } else {
2741     lea(rscratch1, src);
2742     Assembler::divsd(dst, Address(rscratch1, 0));
2743   }
2744 }
2745 
2746 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2747   if (reachable(src)) {
2748     Assembler::divss(dst, as_Address(src));
2749   } else {
2750     lea(rscratch1, src);
2751     Assembler::divss(dst, Address(rscratch1, 0));
2752   }
2753 }
2754 
2755 // !defined(COMPILER2) is because of stupid core builds
2756 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2757 void MacroAssembler::empty_FPU_stack() {
2758   if (VM_Version::supports_mmx()) {
2759     emms();
2760   } else {
2761     for (int i = 8; i-- > 0; ) ffree(i);
2762   }
2763 }
2764 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2765 
2766 
2767 void MacroAssembler::enter() {
2768   push(rbp);
2769   mov(rbp, rsp);
2770 }
2771 
2772 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2773 void MacroAssembler::fat_nop() {
2774   if (UseAddressNop) {
2775     addr_nop_5();
2776   } else {
2777     emit_int8(0x26); // es:
2778     emit_int8(0x2e); // cs:
2779     emit_int8(0x64); // fs:
2780     emit_int8(0x65); // gs:
2781     emit_int8((unsigned char)0x90);
2782   }
2783 }
2784 
2785 void MacroAssembler::fcmp(Register tmp) {
2786   fcmp(tmp, 1, true, true);
2787 }
2788 
2789 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
2790   assert(!pop_right || pop_left, "usage error");
2791   if (VM_Version::supports_cmov()) {
2792     assert(tmp == noreg, "unneeded temp");
2793     if (pop_left) {
2794       fucomip(index);
2795     } else {
2796       fucomi(index);
2797     }
2798     if (pop_right) {
2799       fpop();
2800     }
2801   } else {
2802     assert(tmp != noreg, "need temp");
2803     if (pop_left) {
2804       if (pop_right) {
2805         fcompp();
2806       } else {
2807         fcomp(index);
2808       }
2809     } else {
2810       fcom(index);
2811     }
2812     // convert FPU condition into eflags condition via rax,
2813     save_rax(tmp);
2814     fwait(); fnstsw_ax();
2815     sahf();
2816     restore_rax(tmp);
2817   }
2818   // condition codes set as follows:
2819   //
2820   // CF (corresponds to C0) if x < y
2821   // PF (corresponds to C2) if unordered
2822   // ZF (corresponds to C3) if x = y
2823 }
2824 
2825 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
2826   fcmp2int(dst, unordered_is_less, 1, true, true);
2827 }
2828 
2829 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
2830   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
2831   Label L;
2832   if (unordered_is_less) {
2833     movl(dst, -1);
2834     jcc(Assembler::parity, L);
2835     jcc(Assembler::below , L);
2836     movl(dst, 0);
2837     jcc(Assembler::equal , L);
2838     increment(dst);
2839   } else { // unordered is greater
2840     movl(dst, 1);
2841     jcc(Assembler::parity, L);
2842     jcc(Assembler::above , L);
2843     movl(dst, 0);
2844     jcc(Assembler::equal , L);
2845     decrementl(dst);
2846   }
2847   bind(L);
2848 }
2849 
2850 void MacroAssembler::fld_d(AddressLiteral src) {
2851   fld_d(as_Address(src));
2852 }
2853 
2854 void MacroAssembler::fld_s(AddressLiteral src) {
2855   fld_s(as_Address(src));
2856 }
2857 
2858 void MacroAssembler::fld_x(AddressLiteral src) {
2859   Assembler::fld_x(as_Address(src));
2860 }
2861 
2862 void MacroAssembler::fldcw(AddressLiteral src) {
2863   Assembler::fldcw(as_Address(src));
2864 }
2865 
2866 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
2867   if (reachable(src)) {
2868     Assembler::mulpd(dst, as_Address(src));
2869   } else {
2870     lea(rscratch1, src);
2871     Assembler::mulpd(dst, Address(rscratch1, 0));
2872   }
2873 }
2874 
2875 void MacroAssembler::increase_precision() {
2876   subptr(rsp, BytesPerWord);
2877   fnstcw(Address(rsp, 0));
2878   movl(rax, Address(rsp, 0));
2879   orl(rax, 0x300);
2880   push(rax);
2881   fldcw(Address(rsp, 0));
2882   pop(rax);
2883 }
2884 
2885 void MacroAssembler::restore_precision() {
2886   fldcw(Address(rsp, 0));
2887   addptr(rsp, BytesPerWord);
2888 }
2889 
2890 void MacroAssembler::fpop() {
2891   ffree();
2892   fincstp();
2893 }
2894 
2895 void MacroAssembler::load_float(Address src) {
2896   if (UseSSE >= 1) {
2897     movflt(xmm0, src);
2898   } else {
2899     LP64_ONLY(ShouldNotReachHere());
2900     NOT_LP64(fld_s(src));
2901   }
2902 }
2903 
2904 void MacroAssembler::store_float(Address dst) {
2905   if (UseSSE >= 1) {
2906     movflt(dst, xmm0);
2907   } else {
2908     LP64_ONLY(ShouldNotReachHere());
2909     NOT_LP64(fstp_s(dst));
2910   }
2911 }
2912 
2913 void MacroAssembler::load_double(Address src) {
2914   if (UseSSE >= 2) {
2915     movdbl(xmm0, src);
2916   } else {
2917     LP64_ONLY(ShouldNotReachHere());
2918     NOT_LP64(fld_d(src));
2919   }
2920 }
2921 
2922 void MacroAssembler::store_double(Address dst) {
2923   if (UseSSE >= 2) {
2924     movdbl(dst, xmm0);
2925   } else {
2926     LP64_ONLY(ShouldNotReachHere());
2927     NOT_LP64(fstp_d(dst));
2928   }
2929 }
2930 
2931 void MacroAssembler::fremr(Register tmp) {
2932   save_rax(tmp);
2933   { Label L;
2934     bind(L);
2935     fprem();
2936     fwait(); fnstsw_ax();
2937 #ifdef _LP64
2938     testl(rax, 0x400);
2939     jcc(Assembler::notEqual, L);
2940 #else
2941     sahf();
2942     jcc(Assembler::parity, L);
2943 #endif // _LP64
2944   }
2945   restore_rax(tmp);
2946   // Result is in ST0.
2947   // Note: fxch & fpop to get rid of ST1
2948   // (otherwise FPU stack could overflow eventually)
2949   fxch(1);
2950   fpop();
2951 }
2952 
2953 // dst = c = a * b + c
2954 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
2955   Assembler::vfmadd231sd(c, a, b);
2956   if (dst != c) {
2957     movdbl(dst, c);
2958   }
2959 }
2960 
2961 // dst = c = a * b + c
2962 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
2963   Assembler::vfmadd231ss(c, a, b);
2964   if (dst != c) {
2965     movflt(dst, c);
2966   }
2967 }
2968 
2969 // dst = c = a * b + c
2970 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
2971   Assembler::vfmadd231pd(c, a, b, vector_len);
2972   if (dst != c) {
2973     vmovdqu(dst, c);
2974   }
2975 }
2976 
2977 // dst = c = a * b + c
2978 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
2979   Assembler::vfmadd231ps(c, a, b, vector_len);
2980   if (dst != c) {
2981     vmovdqu(dst, c);
2982   }
2983 }
2984 
2985 // dst = c = a * b + c
2986 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
2987   Assembler::vfmadd231pd(c, a, b, vector_len);
2988   if (dst != c) {
2989     vmovdqu(dst, c);
2990   }
2991 }
2992 
2993 // dst = c = a * b + c
2994 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
2995   Assembler::vfmadd231ps(c, a, b, vector_len);
2996   if (dst != c) {
2997     vmovdqu(dst, c);
2998   }
2999 }
3000 
3001 void MacroAssembler::incrementl(AddressLiteral dst) {
3002   if (reachable(dst)) {
3003     incrementl(as_Address(dst));
3004   } else {
3005     lea(rscratch1, dst);
3006     incrementl(Address(rscratch1, 0));
3007   }
3008 }
3009 
3010 void MacroAssembler::incrementl(ArrayAddress dst) {
3011   incrementl(as_Address(dst));
3012 }
3013 
3014 void MacroAssembler::incrementl(Register reg, int value) {
3015   if (value == min_jint) {addl(reg, value) ; return; }
3016   if (value <  0) { decrementl(reg, -value); return; }
3017   if (value == 0) {                        ; return; }
3018   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3019   /* else */      { addl(reg, value)       ; return; }
3020 }
3021 
3022 void MacroAssembler::incrementl(Address dst, int value) {
3023   if (value == min_jint) {addl(dst, value) ; return; }
3024   if (value <  0) { decrementl(dst, -value); return; }
3025   if (value == 0) {                        ; return; }
3026   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3027   /* else */      { addl(dst, value)       ; return; }
3028 }
3029 
3030 void MacroAssembler::jump(AddressLiteral dst) {
3031   if (reachable(dst)) {
3032     jmp_literal(dst.target(), dst.rspec());
3033   } else {
3034     lea(rscratch1, dst);
3035     jmp(rscratch1);
3036   }
3037 }
3038 
3039 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3040   if (reachable(dst)) {
3041     InstructionMark im(this);
3042     relocate(dst.reloc());
3043     const int short_size = 2;
3044     const int long_size = 6;
3045     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3046     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3047       // 0111 tttn #8-bit disp
3048       emit_int8(0x70 | cc);
3049       emit_int8((offs - short_size) & 0xFF);
3050     } else {
3051       // 0000 1111 1000 tttn #32-bit disp
3052       emit_int8(0x0F);
3053       emit_int8((unsigned char)(0x80 | cc));
3054       emit_int32(offs - long_size);
3055     }
3056   } else {
3057 #ifdef ASSERT
3058     warning("reversing conditional branch");
3059 #endif /* ASSERT */
3060     Label skip;
3061     jccb(reverse[cc], skip);
3062     lea(rscratch1, dst);
3063     Assembler::jmp(rscratch1);
3064     bind(skip);
3065   }
3066 }
3067 
3068 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3069   if (reachable(src)) {
3070     Assembler::ldmxcsr(as_Address(src));
3071   } else {
3072     lea(rscratch1, src);
3073     Assembler::ldmxcsr(Address(rscratch1, 0));
3074   }
3075 }
3076 
3077 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3078   int off;
3079   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3080     off = offset();
3081     movsbl(dst, src); // movsxb
3082   } else {
3083     off = load_unsigned_byte(dst, src);
3084     shll(dst, 24);
3085     sarl(dst, 24);
3086   }
3087   return off;
3088 }
3089 
3090 // Note: load_signed_short used to be called load_signed_word.
3091 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3092 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3093 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3094 int MacroAssembler::load_signed_short(Register dst, Address src) {
3095   int off;
3096   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3097     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3098     // version but this is what 64bit has always done. This seems to imply
3099     // that users are only using 32bits worth.
3100     off = offset();
3101     movswl(dst, src); // movsxw
3102   } else {
3103     off = load_unsigned_short(dst, src);
3104     shll(dst, 16);
3105     sarl(dst, 16);
3106   }
3107   return off;
3108 }
3109 
3110 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3111   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3112   // and "3.9 Partial Register Penalties", p. 22).
3113   int off;
3114   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3115     off = offset();
3116     movzbl(dst, src); // movzxb
3117   } else {
3118     xorl(dst, dst);
3119     off = offset();
3120     movb(dst, src);
3121   }
3122   return off;
3123 }
3124 
3125 // Note: load_unsigned_short used to be called load_unsigned_word.
3126 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3127   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3128   // and "3.9 Partial Register Penalties", p. 22).
3129   int off;
3130   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3131     off = offset();
3132     movzwl(dst, src); // movzxw
3133   } else {
3134     xorl(dst, dst);
3135     off = offset();
3136     movw(dst, src);
3137   }
3138   return off;
3139 }
3140 
3141 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3142   switch (size_in_bytes) {
3143 #ifndef _LP64
3144   case  8:
3145     assert(dst2 != noreg, "second dest register required");
3146     movl(dst,  src);
3147     movl(dst2, src.plus_disp(BytesPerInt));
3148     break;
3149 #else
3150   case  8:  movq(dst, src); break;
3151 #endif
3152   case  4:  movl(dst, src); break;
3153   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3154   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3155   default:  ShouldNotReachHere();
3156   }
3157 }
3158 
3159 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3160   switch (size_in_bytes) {
3161 #ifndef _LP64
3162   case  8:
3163     assert(src2 != noreg, "second source register required");
3164     movl(dst,                        src);
3165     movl(dst.plus_disp(BytesPerInt), src2);
3166     break;
3167 #else
3168   case  8:  movq(dst, src); break;
3169 #endif
3170   case  4:  movl(dst, src); break;
3171   case  2:  movw(dst, src); break;
3172   case  1:  movb(dst, src); break;
3173   default:  ShouldNotReachHere();
3174   }
3175 }
3176 
3177 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3178   if (reachable(dst)) {
3179     movl(as_Address(dst), src);
3180   } else {
3181     lea(rscratch1, dst);
3182     movl(Address(rscratch1, 0), src);
3183   }
3184 }
3185 
3186 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3187   if (reachable(src)) {
3188     movl(dst, as_Address(src));
3189   } else {
3190     lea(rscratch1, src);
3191     movl(dst, Address(rscratch1, 0));
3192   }
3193 }
3194 
3195 // C++ bool manipulation
3196 
3197 void MacroAssembler::movbool(Register dst, Address src) {
3198   if(sizeof(bool) == 1)
3199     movb(dst, src);
3200   else if(sizeof(bool) == 2)
3201     movw(dst, src);
3202   else if(sizeof(bool) == 4)
3203     movl(dst, src);
3204   else
3205     // unsupported
3206     ShouldNotReachHere();
3207 }
3208 
3209 void MacroAssembler::movbool(Address dst, bool boolconst) {
3210   if(sizeof(bool) == 1)
3211     movb(dst, (int) boolconst);
3212   else if(sizeof(bool) == 2)
3213     movw(dst, (int) boolconst);
3214   else if(sizeof(bool) == 4)
3215     movl(dst, (int) boolconst);
3216   else
3217     // unsupported
3218     ShouldNotReachHere();
3219 }
3220 
3221 void MacroAssembler::movbool(Address dst, Register src) {
3222   if(sizeof(bool) == 1)
3223     movb(dst, src);
3224   else if(sizeof(bool) == 2)
3225     movw(dst, src);
3226   else if(sizeof(bool) == 4)
3227     movl(dst, src);
3228   else
3229     // unsupported
3230     ShouldNotReachHere();
3231 }
3232 
3233 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3234   movb(as_Address(dst), src);
3235 }
3236 
3237 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3238   if (reachable(src)) {
3239     movdl(dst, as_Address(src));
3240   } else {
3241     lea(rscratch1, src);
3242     movdl(dst, Address(rscratch1, 0));
3243   }
3244 }
3245 
3246 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3247   if (reachable(src)) {
3248     movq(dst, as_Address(src));
3249   } else {
3250     lea(rscratch1, src);
3251     movq(dst, Address(rscratch1, 0));
3252   }
3253 }
3254 
3255 #ifdef COMPILER2
3256 void MacroAssembler::setvectmask(Register dst, Register src) {
3257   guarantee(PostLoopMultiversioning, "must be");
3258   Assembler::movl(dst, 1);
3259   Assembler::shlxl(dst, dst, src);
3260   Assembler::decl(dst);
3261   Assembler::kmovdl(k1, dst);
3262   Assembler::movl(dst, src);
3263 }
3264 
3265 void MacroAssembler::restorevectmask() {
3266   guarantee(PostLoopMultiversioning, "must be");
3267   Assembler::knotwl(k1, k0);
3268 }
3269 #endif // COMPILER2
3270 
3271 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3272   if (reachable(src)) {
3273     if (UseXmmLoadAndClearUpper) {
3274       movsd (dst, as_Address(src));
3275     } else {
3276       movlpd(dst, as_Address(src));
3277     }
3278   } else {
3279     lea(rscratch1, src);
3280     if (UseXmmLoadAndClearUpper) {
3281       movsd (dst, Address(rscratch1, 0));
3282     } else {
3283       movlpd(dst, Address(rscratch1, 0));
3284     }
3285   }
3286 }
3287 
3288 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3289   if (reachable(src)) {
3290     movss(dst, as_Address(src));
3291   } else {
3292     lea(rscratch1, src);
3293     movss(dst, Address(rscratch1, 0));
3294   }
3295 }
3296 
3297 void MacroAssembler::movptr(Register dst, Register src) {
3298   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3299 }
3300 
3301 void MacroAssembler::movptr(Register dst, Address src) {
3302   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3303 }
3304 
3305 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3306 void MacroAssembler::movptr(Register dst, intptr_t src) {
3307   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3308 }
3309 
3310 void MacroAssembler::movptr(Address dst, Register src) {
3311   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3312 }
3313 
3314 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3315     assert(((src->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
3316     Assembler::movdqu(dst, src);
3317 }
3318 
3319 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3320     assert(((dst->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
3321     Assembler::movdqu(dst, src);
3322 }
3323 
3324 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3325     assert(((dst->encoding() < 16  && src->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
3326     Assembler::movdqu(dst, src);
3327 }
3328 
3329 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3330   if (reachable(src)) {
3331     movdqu(dst, as_Address(src));
3332   } else {
3333     lea(scratchReg, src);
3334     movdqu(dst, Address(scratchReg, 0));
3335   }
3336 }
3337 
3338 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3339     assert(((src->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
3340     Assembler::vmovdqu(dst, src);
3341 }
3342 
3343 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3344     assert(((dst->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
3345     Assembler::vmovdqu(dst, src);
3346 }
3347 
3348 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3349     assert(((dst->encoding() < 16  && src->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
3350     Assembler::vmovdqu(dst, src);
3351 }
3352 
3353 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src, Register scratch_reg) {
3354   if (reachable(src)) {
3355     vmovdqu(dst, as_Address(src));
3356   }
3357   else {
3358     lea(scratch_reg, src);
3359     vmovdqu(dst, Address(scratch_reg, 0));
3360   }
3361 }
3362 
3363 void MacroAssembler::evmovdquq(XMMRegister dst, AddressLiteral src, int vector_len, Register rscratch) {
3364   if (reachable(src)) {
3365     Assembler::evmovdquq(dst, as_Address(src), vector_len);
3366   } else {
3367     lea(rscratch, src);
3368     Assembler::evmovdquq(dst, Address(rscratch, 0), vector_len);
3369   }
3370 }
3371 
3372 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3373   if (reachable(src)) {
3374     Assembler::movdqa(dst, as_Address(src));
3375   } else {
3376     lea(rscratch1, src);
3377     Assembler::movdqa(dst, Address(rscratch1, 0));
3378   }
3379 }
3380 
3381 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3382   if (reachable(src)) {
3383     Assembler::movsd(dst, as_Address(src));
3384   } else {
3385     lea(rscratch1, src);
3386     Assembler::movsd(dst, Address(rscratch1, 0));
3387   }
3388 }
3389 
3390 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3391   if (reachable(src)) {
3392     Assembler::movss(dst, as_Address(src));
3393   } else {
3394     lea(rscratch1, src);
3395     Assembler::movss(dst, Address(rscratch1, 0));
3396   }
3397 }
3398 
3399 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3400   if (reachable(src)) {
3401     Assembler::mulsd(dst, as_Address(src));
3402   } else {
3403     lea(rscratch1, src);
3404     Assembler::mulsd(dst, Address(rscratch1, 0));
3405   }
3406 }
3407 
3408 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3409   if (reachable(src)) {
3410     Assembler::mulss(dst, as_Address(src));
3411   } else {
3412     lea(rscratch1, src);
3413     Assembler::mulss(dst, Address(rscratch1, 0));
3414   }
3415 }
3416 
3417 void MacroAssembler::null_check(Register reg, int offset) {
3418   if (needs_explicit_null_check(offset)) {
3419     // provoke OS NULL exception if reg = NULL by
3420     // accessing M[reg] w/o changing any (non-CC) registers
3421     // NOTE: cmpl is plenty here to provoke a segv
3422     cmpptr(rax, Address(reg, 0));
3423     // Note: should probably use testl(rax, Address(reg, 0));
3424     //       may be shorter code (however, this version of
3425     //       testl needs to be implemented first)
3426   } else {
3427     // nothing to do, (later) access of M[reg + offset]
3428     // will provoke OS NULL exception if reg = NULL
3429   }
3430 }
3431 
3432 void MacroAssembler::test_klass_is_value(Register klass, Register temp_reg, Label& is_value) {
3433   movl(temp_reg, Address(klass, Klass::access_flags_offset()));
3434   testl(temp_reg, JVM_ACC_VALUE);
3435   jcc(Assembler::notZero, is_value);
3436 }
3437 
3438 void MacroAssembler::test_field_is_flattenable(Register flags, Register temp_reg, Label& is_flattenable) {
3439   movl(temp_reg, flags);
3440   shrl(temp_reg, ConstantPoolCacheEntry::is_flattenable_field_shift);
3441   andl(temp_reg, 0x1);
3442   testl(temp_reg, temp_reg);
3443   jcc(Assembler::notZero, is_flattenable);
3444 }
3445 
3446 void MacroAssembler::test_field_is_not_flattenable(Register flags, Register temp_reg, Label& notFlattenable) {
3447   movl(temp_reg, flags);
3448   shrl(temp_reg, ConstantPoolCacheEntry::is_flattenable_field_shift);
3449   andl(temp_reg, 0x1);
3450   testl(temp_reg, temp_reg);
3451   jcc(Assembler::zero, notFlattenable);
3452 }
3453 
3454 void MacroAssembler::test_field_is_flattened(Register flags, Register temp_reg, Label& is_flattened) {
3455   movl(temp_reg, flags);
3456   shrl(temp_reg, ConstantPoolCacheEntry::is_flattened_field_shift);
3457   andl(temp_reg, 0x1);
3458   testl(temp_reg, temp_reg);
3459   jcc(Assembler::notZero, is_flattened);
3460 }
3461 
3462 void MacroAssembler::test_flattened_array_oop(Register oop, Register temp_reg,
3463                                               Label&is_flattened_array) {
3464   load_storage_props(temp_reg, oop);
3465   testb(temp_reg, ArrayStorageProperties::flattened_value);
3466   jcc(Assembler::notZero, is_flattened_array);
3467 }
3468 
3469 void MacroAssembler::test_null_free_array_oop(Register oop, Register temp_reg, Label&is_null_free_array) {
3470   load_storage_props(temp_reg, oop);
3471   testb(temp_reg, ArrayStorageProperties::null_free_value);
3472   jcc(Assembler::notZero, is_null_free_array);
3473 }
3474 
3475 void MacroAssembler::os_breakpoint() {
3476   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3477   // (e.g., MSVC can't call ps() otherwise)
3478   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3479 }
3480 
3481 void MacroAssembler::unimplemented(const char* what) {
3482   const char* buf = NULL;
3483   {
3484     ResourceMark rm;
3485     stringStream ss;
3486     ss.print("unimplemented: %s", what);
3487     buf = code_string(ss.as_string());
3488   }
3489   stop(buf);
3490 }
3491 
3492 #ifdef _LP64
3493 #define XSTATE_BV 0x200
3494 #endif
3495 
3496 void MacroAssembler::pop_CPU_state() {
3497   pop_FPU_state();
3498   pop_IU_state();
3499 }
3500 
3501 void MacroAssembler::pop_FPU_state() {
3502 #ifndef _LP64
3503   frstor(Address(rsp, 0));
3504 #else
3505   fxrstor(Address(rsp, 0));
3506 #endif
3507   addptr(rsp, FPUStateSizeInWords * wordSize);
3508 }
3509 
3510 void MacroAssembler::pop_IU_state() {
3511   popa();
3512   LP64_ONLY(addq(rsp, 8));
3513   popf();
3514 }
3515 
3516 // Save Integer and Float state
3517 // Warning: Stack must be 16 byte aligned (64bit)
3518 void MacroAssembler::push_CPU_state() {
3519   push_IU_state();
3520   push_FPU_state();
3521 }
3522 
3523 void MacroAssembler::push_FPU_state() {
3524   subptr(rsp, FPUStateSizeInWords * wordSize);
3525 #ifndef _LP64
3526   fnsave(Address(rsp, 0));
3527   fwait();
3528 #else
3529   fxsave(Address(rsp, 0));
3530 #endif // LP64
3531 }
3532 
3533 void MacroAssembler::push_IU_state() {
3534   // Push flags first because pusha kills them
3535   pushf();
3536   // Make sure rsp stays 16-byte aligned
3537   LP64_ONLY(subq(rsp, 8));
3538   pusha();
3539 }
3540 
3541 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3542   if (!java_thread->is_valid()) {
3543     java_thread = rdi;
3544     get_thread(java_thread);
3545   }
3546   // we must set sp to zero to clear frame
3547   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3548   if (clear_fp) {
3549     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3550   }
3551 
3552   // Always clear the pc because it could have been set by make_walkable()
3553   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3554 
3555   vzeroupper();
3556 }
3557 
3558 void MacroAssembler::restore_rax(Register tmp) {
3559   if (tmp == noreg) pop(rax);
3560   else if (tmp != rax) mov(rax, tmp);
3561 }
3562 
3563 void MacroAssembler::round_to(Register reg, int modulus) {
3564   addptr(reg, modulus - 1);
3565   andptr(reg, -modulus);
3566 }
3567 
3568 void MacroAssembler::save_rax(Register tmp) {
3569   if (tmp == noreg) push(rax);
3570   else if (tmp != rax) mov(tmp, rax);
3571 }
3572 
3573 void MacroAssembler::safepoint_poll(Label& slow_path, Register thread_reg, Register temp_reg) {
3574   if (SafepointMechanism::uses_thread_local_poll()) {
3575 #ifdef _LP64
3576     assert(thread_reg == r15_thread, "should be");
3577 #else
3578     if (thread_reg == noreg) {
3579       thread_reg = temp_reg;
3580       get_thread(thread_reg);
3581     }
3582 #endif
3583     testb(Address(thread_reg, Thread::polling_page_offset()), SafepointMechanism::poll_bit());
3584     jcc(Assembler::notZero, slow_path); // handshake bit set implies poll
3585   } else {
3586     cmp32(ExternalAddress(SafepointSynchronize::address_of_state()),
3587         SafepointSynchronize::_not_synchronized);
3588     jcc(Assembler::notEqual, slow_path);
3589   }
3590 }
3591 
3592 // Calls to C land
3593 //
3594 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3595 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3596 // has to be reset to 0. This is required to allow proper stack traversal.
3597 void MacroAssembler::set_last_Java_frame(Register java_thread,
3598                                          Register last_java_sp,
3599                                          Register last_java_fp,
3600                                          address  last_java_pc) {
3601   vzeroupper();
3602   // determine java_thread register
3603   if (!java_thread->is_valid()) {
3604     java_thread = rdi;
3605     get_thread(java_thread);
3606   }
3607   // determine last_java_sp register
3608   if (!last_java_sp->is_valid()) {
3609     last_java_sp = rsp;
3610   }
3611 
3612   // last_java_fp is optional
3613 
3614   if (last_java_fp->is_valid()) {
3615     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3616   }
3617 
3618   // last_java_pc is optional
3619 
3620   if (last_java_pc != NULL) {
3621     lea(Address(java_thread,
3622                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3623         InternalAddress(last_java_pc));
3624 
3625   }
3626   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3627 }
3628 
3629 void MacroAssembler::shlptr(Register dst, int imm8) {
3630   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3631 }
3632 
3633 void MacroAssembler::shrptr(Register dst, int imm8) {
3634   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3635 }
3636 
3637 void MacroAssembler::sign_extend_byte(Register reg) {
3638   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3639     movsbl(reg, reg); // movsxb
3640   } else {
3641     shll(reg, 24);
3642     sarl(reg, 24);
3643   }
3644 }
3645 
3646 void MacroAssembler::sign_extend_short(Register reg) {
3647   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3648     movswl(reg, reg); // movsxw
3649   } else {
3650     shll(reg, 16);
3651     sarl(reg, 16);
3652   }
3653 }
3654 
3655 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3656   assert(reachable(src), "Address should be reachable");
3657   testl(dst, as_Address(src));
3658 }
3659 
3660 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3661   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3662   Assembler::pcmpeqb(dst, src);
3663 }
3664 
3665 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3666   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3667   Assembler::pcmpeqw(dst, src);
3668 }
3669 
3670 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3671   assert((dst->encoding() < 16),"XMM register should be 0-15");
3672   Assembler::pcmpestri(dst, src, imm8);
3673 }
3674 
3675 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3676   assert((dst->encoding() < 16 && src->encoding() < 16),"XMM register should be 0-15");
3677   Assembler::pcmpestri(dst, src, imm8);
3678 }
3679 
3680 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
3681   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3682   Assembler::pmovzxbw(dst, src);
3683 }
3684 
3685 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
3686   assert(((dst->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3687   Assembler::pmovzxbw(dst, src);
3688 }
3689 
3690 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
3691   assert((src->encoding() < 16),"XMM register should be 0-15");
3692   Assembler::pmovmskb(dst, src);
3693 }
3694 
3695 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
3696   assert((dst->encoding() < 16 && src->encoding() < 16),"XMM register should be 0-15");
3697   Assembler::ptest(dst, src);
3698 }
3699 
3700 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
3701   if (reachable(src)) {
3702     Assembler::sqrtsd(dst, as_Address(src));
3703   } else {
3704     lea(rscratch1, src);
3705     Assembler::sqrtsd(dst, Address(rscratch1, 0));
3706   }
3707 }
3708 
3709 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
3710   if (reachable(src)) {
3711     Assembler::sqrtss(dst, as_Address(src));
3712   } else {
3713     lea(rscratch1, src);
3714     Assembler::sqrtss(dst, Address(rscratch1, 0));
3715   }
3716 }
3717 
3718 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
3719   if (reachable(src)) {
3720     Assembler::subsd(dst, as_Address(src));
3721   } else {
3722     lea(rscratch1, src);
3723     Assembler::subsd(dst, Address(rscratch1, 0));
3724   }
3725 }
3726 
3727 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
3728   if (reachable(src)) {
3729     Assembler::subss(dst, as_Address(src));
3730   } else {
3731     lea(rscratch1, src);
3732     Assembler::subss(dst, Address(rscratch1, 0));
3733   }
3734 }
3735 
3736 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
3737   if (reachable(src)) {
3738     Assembler::ucomisd(dst, as_Address(src));
3739   } else {
3740     lea(rscratch1, src);
3741     Assembler::ucomisd(dst, Address(rscratch1, 0));
3742   }
3743 }
3744 
3745 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
3746   if (reachable(src)) {
3747     Assembler::ucomiss(dst, as_Address(src));
3748   } else {
3749     lea(rscratch1, src);
3750     Assembler::ucomiss(dst, Address(rscratch1, 0));
3751   }
3752 }
3753 
3754 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src, Register scratch_reg) {
3755   // Used in sign-bit flipping with aligned address.
3756   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
3757   if (reachable(src)) {
3758     Assembler::xorpd(dst, as_Address(src));
3759   } else {
3760     lea(scratch_reg, src);
3761     Assembler::xorpd(dst, Address(scratch_reg, 0));
3762   }
3763 }
3764 
3765 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
3766   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
3767     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
3768   }
3769   else {
3770     Assembler::xorpd(dst, src);
3771   }
3772 }
3773 
3774 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
3775   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
3776     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
3777   } else {
3778     Assembler::xorps(dst, src);
3779   }
3780 }
3781 
3782 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src, Register scratch_reg) {
3783   // Used in sign-bit flipping with aligned address.
3784   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
3785   if (reachable(src)) {
3786     Assembler::xorps(dst, as_Address(src));
3787   } else {
3788     lea(scratch_reg, src);
3789     Assembler::xorps(dst, Address(scratch_reg, 0));
3790   }
3791 }
3792 
3793 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
3794   // Used in sign-bit flipping with aligned address.
3795   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
3796   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
3797   if (reachable(src)) {
3798     Assembler::pshufb(dst, as_Address(src));
3799   } else {
3800     lea(rscratch1, src);
3801     Assembler::pshufb(dst, Address(rscratch1, 0));
3802   }
3803 }
3804 
3805 // AVX 3-operands instructions
3806 
3807 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3808   if (reachable(src)) {
3809     vaddsd(dst, nds, as_Address(src));
3810   } else {
3811     lea(rscratch1, src);
3812     vaddsd(dst, nds, Address(rscratch1, 0));
3813   }
3814 }
3815 
3816 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3817   if (reachable(src)) {
3818     vaddss(dst, nds, as_Address(src));
3819   } else {
3820     lea(rscratch1, src);
3821     vaddss(dst, nds, Address(rscratch1, 0));
3822   }
3823 }
3824 
3825 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
3826   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
3827   vandps(dst, nds, negate_field, vector_len);
3828 }
3829 
3830 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
3831   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
3832   vandpd(dst, nds, negate_field, vector_len);
3833 }
3834 
3835 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3836   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3837   Assembler::vpaddb(dst, nds, src, vector_len);
3838 }
3839 
3840 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3841   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3842   Assembler::vpaddb(dst, nds, src, vector_len);
3843 }
3844 
3845 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3846   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3847   Assembler::vpaddw(dst, nds, src, vector_len);
3848 }
3849 
3850 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3851   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3852   Assembler::vpaddw(dst, nds, src, vector_len);
3853 }
3854 
3855 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register scratch_reg) {
3856   if (reachable(src)) {
3857     Assembler::vpand(dst, nds, as_Address(src), vector_len);
3858   } else {
3859     lea(scratch_reg, src);
3860     Assembler::vpand(dst, nds, Address(scratch_reg, 0), vector_len);
3861   }
3862 }
3863 
3864 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src, int vector_len) {
3865   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3866   Assembler::vpbroadcastw(dst, src, vector_len);
3867 }
3868 
3869 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3870   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3871   Assembler::vpcmpeqb(dst, nds, src, vector_len);
3872 }
3873 
3874 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3875   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3876   Assembler::vpcmpeqw(dst, nds, src, vector_len);
3877 }
3878 
3879 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
3880   assert(((dst->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3881   Assembler::vpmovzxbw(dst, src, vector_len);
3882 }
3883 
3884 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
3885   assert((src->encoding() < 16),"XMM register should be 0-15");
3886   Assembler::vpmovmskb(dst, src);
3887 }
3888 
3889 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3890   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3891   Assembler::vpmullw(dst, nds, src, vector_len);
3892 }
3893 
3894 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3895   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3896   Assembler::vpmullw(dst, nds, src, vector_len);
3897 }
3898 
3899 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3900   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3901   Assembler::vpsubb(dst, nds, src, vector_len);
3902 }
3903 
3904 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3905   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3906   Assembler::vpsubb(dst, nds, src, vector_len);
3907 }
3908 
3909 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3910   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3911   Assembler::vpsubw(dst, nds, src, vector_len);
3912 }
3913 
3914 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3915   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3916   Assembler::vpsubw(dst, nds, src, vector_len);
3917 }
3918 
3919 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
3920   assert(((dst->encoding() < 16 && shift->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3921   Assembler::vpsraw(dst, nds, shift, vector_len);
3922 }
3923 
3924 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
3925   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3926   Assembler::vpsraw(dst, nds, shift, vector_len);
3927 }
3928 
3929 void MacroAssembler::evpsraq(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
3930   assert(UseAVX > 2,"");
3931   if (!VM_Version::supports_avx512vl() && vector_len < 2) {
3932      vector_len = 2;
3933   }
3934   Assembler::evpsraq(dst, nds, shift, vector_len);
3935 }
3936 
3937 void MacroAssembler::evpsraq(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
3938   assert(UseAVX > 2,"");
3939   if (!VM_Version::supports_avx512vl() && vector_len < 2) {
3940      vector_len = 2;
3941   }
3942   Assembler::evpsraq(dst, nds, shift, vector_len);
3943 }
3944 
3945 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
3946   assert(((dst->encoding() < 16 && shift->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3947   Assembler::vpsrlw(dst, nds, shift, vector_len);
3948 }
3949 
3950 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
3951   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3952   Assembler::vpsrlw(dst, nds, shift, vector_len);
3953 }
3954 
3955 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
3956   assert(((dst->encoding() < 16 && shift->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3957   Assembler::vpsllw(dst, nds, shift, vector_len);
3958 }
3959 
3960 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
3961   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3962   Assembler::vpsllw(dst, nds, shift, vector_len);
3963 }
3964 
3965 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
3966   assert((dst->encoding() < 16 && src->encoding() < 16),"XMM register should be 0-15");
3967   Assembler::vptest(dst, src);
3968 }
3969 
3970 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
3971   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3972   Assembler::punpcklbw(dst, src);
3973 }
3974 
3975 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
3976   assert(((dst->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
3977   Assembler::pshufd(dst, src, mode);
3978 }
3979 
3980 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
3981   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3982   Assembler::pshuflw(dst, src, mode);
3983 }
3984 
3985 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register scratch_reg) {
3986   if (reachable(src)) {
3987     vandpd(dst, nds, as_Address(src), vector_len);
3988   } else {
3989     lea(scratch_reg, src);
3990     vandpd(dst, nds, Address(scratch_reg, 0), vector_len);
3991   }
3992 }
3993 
3994 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register scratch_reg) {
3995   if (reachable(src)) {
3996     vandps(dst, nds, as_Address(src), vector_len);
3997   } else {
3998     lea(scratch_reg, src);
3999     vandps(dst, nds, Address(scratch_reg, 0), vector_len);
4000   }
4001 }
4002 
4003 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4004   if (reachable(src)) {
4005     vdivsd(dst, nds, as_Address(src));
4006   } else {
4007     lea(rscratch1, src);
4008     vdivsd(dst, nds, Address(rscratch1, 0));
4009   }
4010 }
4011 
4012 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4013   if (reachable(src)) {
4014     vdivss(dst, nds, as_Address(src));
4015   } else {
4016     lea(rscratch1, src);
4017     vdivss(dst, nds, Address(rscratch1, 0));
4018   }
4019 }
4020 
4021 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4022   if (reachable(src)) {
4023     vmulsd(dst, nds, as_Address(src));
4024   } else {
4025     lea(rscratch1, src);
4026     vmulsd(dst, nds, Address(rscratch1, 0));
4027   }
4028 }
4029 
4030 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4031   if (reachable(src)) {
4032     vmulss(dst, nds, as_Address(src));
4033   } else {
4034     lea(rscratch1, src);
4035     vmulss(dst, nds, Address(rscratch1, 0));
4036   }
4037 }
4038 
4039 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4040   if (reachable(src)) {
4041     vsubsd(dst, nds, as_Address(src));
4042   } else {
4043     lea(rscratch1, src);
4044     vsubsd(dst, nds, Address(rscratch1, 0));
4045   }
4046 }
4047 
4048 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4049   if (reachable(src)) {
4050     vsubss(dst, nds, as_Address(src));
4051   } else {
4052     lea(rscratch1, src);
4053     vsubss(dst, nds, Address(rscratch1, 0));
4054   }
4055 }
4056 
4057 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4058   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
4059   vxorps(dst, nds, src, Assembler::AVX_128bit);
4060 }
4061 
4062 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4063   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
4064   vxorpd(dst, nds, src, Assembler::AVX_128bit);
4065 }
4066 
4067 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register scratch_reg) {
4068   if (reachable(src)) {
4069     vxorpd(dst, nds, as_Address(src), vector_len);
4070   } else {
4071     lea(scratch_reg, src);
4072     vxorpd(dst, nds, Address(scratch_reg, 0), vector_len);
4073   }
4074 }
4075 
4076 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register scratch_reg) {
4077   if (reachable(src)) {
4078     vxorps(dst, nds, as_Address(src), vector_len);
4079   } else {
4080     lea(scratch_reg, src);
4081     vxorps(dst, nds, Address(scratch_reg, 0), vector_len);
4082   }
4083 }
4084 
4085 void MacroAssembler::vpxor(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register scratch_reg) {
4086   if (UseAVX > 1 || (vector_len < 1)) {
4087     if (reachable(src)) {
4088       Assembler::vpxor(dst, nds, as_Address(src), vector_len);
4089     } else {
4090       lea(scratch_reg, src);
4091       Assembler::vpxor(dst, nds, Address(scratch_reg, 0), vector_len);
4092     }
4093   }
4094   else {
4095     MacroAssembler::vxorpd(dst, nds, src, vector_len, scratch_reg);
4096   }
4097 }
4098 
4099 //-------------------------------------------------------------------------------------------
4100 #ifdef COMPILER2
4101 // Generic instructions support for use in .ad files C2 code generation
4102 
4103 void MacroAssembler::vabsnegd(int opcode, XMMRegister dst, Register scr) {
4104   if (opcode == Op_AbsVD) {
4105     andpd(dst, ExternalAddress(StubRoutines::x86::vector_double_sign_mask()), scr);
4106   } else {
4107     assert((opcode == Op_NegVD),"opcode should be Op_NegD");
4108     xorpd(dst, ExternalAddress(StubRoutines::x86::vector_double_sign_flip()), scr);
4109   }
4110 }
4111 
4112 void MacroAssembler::vabsnegd(int opcode, XMMRegister dst, XMMRegister src, int vector_len, Register scr) {
4113   if (opcode == Op_AbsVD) {
4114     vandpd(dst, src, ExternalAddress(StubRoutines::x86::vector_double_sign_mask()), vector_len, scr);
4115   } else {
4116     assert((opcode == Op_NegVD),"opcode should be Op_NegD");
4117     vxorpd(dst, src, ExternalAddress(StubRoutines::x86::vector_double_sign_flip()), vector_len, scr);
4118   }
4119 }
4120 
4121 void MacroAssembler::vabsnegf(int opcode, XMMRegister dst, Register scr) {
4122   if (opcode == Op_AbsVF) {
4123     andps(dst, ExternalAddress(StubRoutines::x86::vector_float_sign_mask()), scr);
4124   } else {
4125     assert((opcode == Op_NegVF),"opcode should be Op_NegF");
4126     xorps(dst, ExternalAddress(StubRoutines::x86::vector_float_sign_flip()), scr);
4127   }
4128 }
4129 
4130 void MacroAssembler::vabsnegf(int opcode, XMMRegister dst, XMMRegister src, int vector_len, Register scr) {
4131   if (opcode == Op_AbsVF) {
4132     vandps(dst, src, ExternalAddress(StubRoutines::x86::vector_float_sign_mask()), vector_len, scr);
4133   } else {
4134     assert((opcode == Op_NegVF),"opcode should be Op_NegF");
4135     vxorps(dst, src, ExternalAddress(StubRoutines::x86::vector_float_sign_flip()), vector_len, scr);
4136   }
4137 }
4138 
4139 void MacroAssembler::vextendbw(bool sign, XMMRegister dst, XMMRegister src) {
4140   if (sign) {
4141     pmovsxbw(dst, src);
4142   } else {
4143     pmovzxbw(dst, src);
4144   }
4145 }
4146 
4147 void MacroAssembler::vextendbw(bool sign, XMMRegister dst, XMMRegister src, int vector_len) {
4148   if (sign) {
4149     vpmovsxbw(dst, src, vector_len);
4150   } else {
4151     vpmovzxbw(dst, src, vector_len);
4152   }
4153 }
4154 
4155 void MacroAssembler::vshiftd(int opcode, XMMRegister dst, XMMRegister src) {
4156   if (opcode == Op_RShiftVI) {
4157     psrad(dst, src);
4158   } else if (opcode == Op_LShiftVI) {
4159     pslld(dst, src);
4160   } else {
4161     assert((opcode == Op_URShiftVI),"opcode should be Op_URShiftVI");
4162     psrld(dst, src);
4163   }
4164 }
4165 
4166 void MacroAssembler::vshiftd(int opcode, XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4167   if (opcode == Op_RShiftVI) {
4168     vpsrad(dst, nds, src, vector_len);
4169   } else if (opcode == Op_LShiftVI) {
4170     vpslld(dst, nds, src, vector_len);
4171   } else {
4172     assert((opcode == Op_URShiftVI),"opcode should be Op_URShiftVI");
4173     vpsrld(dst, nds, src, vector_len);
4174   }
4175 }
4176 
4177 void MacroAssembler::vshiftw(int opcode, XMMRegister dst, XMMRegister src) {
4178   if ((opcode == Op_RShiftVS) || (opcode == Op_RShiftVB)) {
4179     psraw(dst, src);
4180   } else if ((opcode == Op_LShiftVS) || (opcode == Op_LShiftVB)) {
4181     psllw(dst, src);
4182   } else {
4183     assert(((opcode == Op_URShiftVS) || (opcode == Op_URShiftVB)),"opcode should be one of Op_URShiftVS or Op_URShiftVB");
4184     psrlw(dst, src);
4185   }
4186 }
4187 
4188 void MacroAssembler::vshiftw(int opcode, XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4189   if ((opcode == Op_RShiftVS) || (opcode == Op_RShiftVB)) {
4190     vpsraw(dst, nds, src, vector_len);
4191   } else if ((opcode == Op_LShiftVS) || (opcode == Op_LShiftVB)) {
4192     vpsllw(dst, nds, src, vector_len);
4193   } else {
4194     assert(((opcode == Op_URShiftVS) || (opcode == Op_URShiftVB)),"opcode should be one of Op_URShiftVS or Op_URShiftVB");
4195     vpsrlw(dst, nds, src, vector_len);
4196   }
4197 }
4198 
4199 void MacroAssembler::vshiftq(int opcode, XMMRegister dst, XMMRegister src) {
4200   if (opcode == Op_RShiftVL) {
4201     psrlq(dst, src);  // using srl to implement sra on pre-avs512 systems
4202   } else if (opcode == Op_LShiftVL) {
4203     psllq(dst, src);
4204   } else {
4205     assert((opcode == Op_URShiftVL),"opcode should be Op_URShiftVL");
4206     psrlq(dst, src);
4207   }
4208 }
4209 
4210 void MacroAssembler::vshiftq(int opcode, XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4211   if (opcode == Op_RShiftVL) {
4212     evpsraq(dst, nds, src, vector_len);
4213   } else if (opcode == Op_LShiftVL) {
4214     vpsllq(dst, nds, src, vector_len);
4215   } else {
4216     assert((opcode == Op_URShiftVL),"opcode should be Op_URShiftVL");
4217     vpsrlq(dst, nds, src, vector_len);
4218   }
4219 }
4220 #endif
4221 //-------------------------------------------------------------------------------------------
4222 
4223 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
4224   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
4225   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
4226   // The inverted mask is sign-extended
4227   andptr(possibly_jweak, inverted_jweak_mask);
4228 }
4229 
4230 void MacroAssembler::resolve_jobject(Register value,
4231                                      Register thread,
4232                                      Register tmp) {
4233   assert_different_registers(value, thread, tmp);
4234   Label done, not_weak;
4235   testptr(value, value);
4236   jcc(Assembler::zero, done);                // Use NULL as-is.
4237   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
4238   jcc(Assembler::zero, not_weak);
4239   // Resolve jweak.
4240   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
4241                  value, Address(value, -JNIHandles::weak_tag_value), tmp, thread);
4242   verify_oop(value);
4243   jmp(done);
4244   bind(not_weak);
4245   // Resolve (untagged) jobject.
4246   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, 0), tmp, thread);
4247   verify_oop(value);
4248   bind(done);
4249 }
4250 
4251 void MacroAssembler::subptr(Register dst, int32_t imm32) {
4252   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
4253 }
4254 
4255 // Force generation of a 4 byte immediate value even if it fits into 8bit
4256 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
4257   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
4258 }
4259 
4260 void MacroAssembler::subptr(Register dst, Register src) {
4261   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
4262 }
4263 
4264 // C++ bool manipulation
4265 void MacroAssembler::testbool(Register dst) {
4266   if(sizeof(bool) == 1)
4267     testb(dst, 0xff);
4268   else if(sizeof(bool) == 2) {
4269     // testw implementation needed for two byte bools
4270     ShouldNotReachHere();
4271   } else if(sizeof(bool) == 4)
4272     testl(dst, dst);
4273   else
4274     // unsupported
4275     ShouldNotReachHere();
4276 }
4277 
4278 void MacroAssembler::testptr(Register dst, Register src) {
4279   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
4280 }
4281 
4282 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
4283 void MacroAssembler::tlab_allocate(Register thread, Register obj,
4284                                    Register var_size_in_bytes,
4285                                    int con_size_in_bytes,
4286                                    Register t1,
4287                                    Register t2,
4288                                    Label& slow_case) {
4289   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
4290   bs->tlab_allocate(this, thread, obj, var_size_in_bytes, con_size_in_bytes, t1, t2, slow_case);
4291 }
4292 
4293 // Defines obj, preserves var_size_in_bytes
4294 void MacroAssembler::eden_allocate(Register thread, Register obj,
4295                                    Register var_size_in_bytes,
4296                                    int con_size_in_bytes,
4297                                    Register t1,
4298                                    Label& slow_case) {
4299   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
4300   bs->eden_allocate(this, thread, obj, var_size_in_bytes, con_size_in_bytes, t1, slow_case);
4301 }
4302 
4303 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
4304 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
4305   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
4306   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
4307   Label done;
4308 
4309   testptr(length_in_bytes, length_in_bytes);
4310   jcc(Assembler::zero, done);
4311 
4312   // initialize topmost word, divide index by 2, check if odd and test if zero
4313   // note: for the remaining code to work, index must be a multiple of BytesPerWord
4314 #ifdef ASSERT
4315   {
4316     Label L;
4317     testptr(length_in_bytes, BytesPerWord - 1);
4318     jcc(Assembler::zero, L);
4319     stop("length must be a multiple of BytesPerWord");
4320     bind(L);
4321   }
4322 #endif
4323   Register index = length_in_bytes;
4324   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
4325   if (UseIncDec) {
4326     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
4327   } else {
4328     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
4329     shrptr(index, 1);
4330   }
4331 #ifndef _LP64
4332   // index could have not been a multiple of 8 (i.e., bit 2 was set)
4333   {
4334     Label even;
4335     // note: if index was a multiple of 8, then it cannot
4336     //       be 0 now otherwise it must have been 0 before
4337     //       => if it is even, we don't need to check for 0 again
4338     jcc(Assembler::carryClear, even);
4339     // clear topmost word (no jump would be needed if conditional assignment worked here)
4340     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
4341     // index could be 0 now, must check again
4342     jcc(Assembler::zero, done);
4343     bind(even);
4344   }
4345 #endif // !_LP64
4346   // initialize remaining object fields: index is a multiple of 2 now
4347   {
4348     Label loop;
4349     bind(loop);
4350     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
4351     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
4352     decrement(index);
4353     jcc(Assembler::notZero, loop);
4354   }
4355 
4356   bind(done);
4357 }
4358 
4359 // Look up the method for a megamorphic invokeinterface call.
4360 // The target method is determined by <intf_klass, itable_index>.
4361 // The receiver klass is in recv_klass.
4362 // On success, the result will be in method_result, and execution falls through.
4363 // On failure, execution transfers to the given label.
4364 void MacroAssembler::lookup_interface_method(Register recv_klass,
4365                                              Register intf_klass,
4366                                              RegisterOrConstant itable_index,
4367                                              Register method_result,
4368                                              Register scan_temp,
4369                                              Label& L_no_such_interface,
4370                                              bool return_method) {
4371   assert_different_registers(recv_klass, intf_klass, scan_temp);
4372   assert_different_registers(method_result, intf_klass, scan_temp);
4373   assert(recv_klass != method_result || !return_method,
4374          "recv_klass can be destroyed when method isn't needed");
4375 
4376   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
4377          "caller must use same register for non-constant itable index as for method");
4378 
4379   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
4380   int vtable_base = in_bytes(Klass::vtable_start_offset());
4381   int itentry_off = itableMethodEntry::method_offset_in_bytes();
4382   int scan_step   = itableOffsetEntry::size() * wordSize;
4383   int vte_size    = vtableEntry::size_in_bytes();
4384   Address::ScaleFactor times_vte_scale = Address::times_ptr;
4385   assert(vte_size == wordSize, "else adjust times_vte_scale");
4386 
4387   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
4388 
4389   // %%% Could store the aligned, prescaled offset in the klassoop.
4390   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
4391 
4392   if (return_method) {
4393     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
4394     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
4395     lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
4396   }
4397 
4398   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
4399   //   if (scan->interface() == intf) {
4400   //     result = (klass + scan->offset() + itable_index);
4401   //   }
4402   // }
4403   Label search, found_method;
4404 
4405   for (int peel = 1; peel >= 0; peel--) {
4406     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
4407     cmpptr(intf_klass, method_result);
4408 
4409     if (peel) {
4410       jccb(Assembler::equal, found_method);
4411     } else {
4412       jccb(Assembler::notEqual, search);
4413       // (invert the test to fall through to found_method...)
4414     }
4415 
4416     if (!peel)  break;
4417 
4418     bind(search);
4419 
4420     // Check that the previous entry is non-null.  A null entry means that
4421     // the receiver class doesn't implement the interface, and wasn't the
4422     // same as when the caller was compiled.
4423     testptr(method_result, method_result);
4424     jcc(Assembler::zero, L_no_such_interface);
4425     addptr(scan_temp, scan_step);
4426   }
4427 
4428   bind(found_method);
4429 
4430   if (return_method) {
4431     // Got a hit.
4432     movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
4433     movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
4434   }
4435 }
4436 
4437 
4438 // virtual method calling
4439 void MacroAssembler::lookup_virtual_method(Register recv_klass,
4440                                            RegisterOrConstant vtable_index,
4441                                            Register method_result) {
4442   const int base = in_bytes(Klass::vtable_start_offset());
4443   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
4444   Address vtable_entry_addr(recv_klass,
4445                             vtable_index, Address::times_ptr,
4446                             base + vtableEntry::method_offset_in_bytes());
4447   movptr(method_result, vtable_entry_addr);
4448 }
4449 
4450 
4451 void MacroAssembler::check_klass_subtype(Register sub_klass,
4452                            Register super_klass,
4453                            Register temp_reg,
4454                            Label& L_success) {
4455   Label L_failure;
4456   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
4457   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
4458   bind(L_failure);
4459 }
4460 
4461 
4462 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
4463                                                    Register super_klass,
4464                                                    Register temp_reg,
4465                                                    Label* L_success,
4466                                                    Label* L_failure,
4467                                                    Label* L_slow_path,
4468                                         RegisterOrConstant super_check_offset) {
4469   assert_different_registers(sub_klass, super_klass, temp_reg);
4470   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
4471   if (super_check_offset.is_register()) {
4472     assert_different_registers(sub_klass, super_klass,
4473                                super_check_offset.as_register());
4474   } else if (must_load_sco) {
4475     assert(temp_reg != noreg, "supply either a temp or a register offset");
4476   }
4477 
4478   Label L_fallthrough;
4479   int label_nulls = 0;
4480   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
4481   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
4482   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
4483   assert(label_nulls <= 1, "at most one NULL in the batch");
4484 
4485   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
4486   int sco_offset = in_bytes(Klass::super_check_offset_offset());
4487   Address super_check_offset_addr(super_klass, sco_offset);
4488 
4489   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
4490   // range of a jccb.  If this routine grows larger, reconsider at
4491   // least some of these.
4492 #define local_jcc(assembler_cond, label)                                \
4493   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
4494   else                             jcc( assembler_cond, label) /*omit semi*/
4495 
4496   // Hacked jmp, which may only be used just before L_fallthrough.
4497 #define final_jmp(label)                                                \
4498   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
4499   else                            jmp(label)                /*omit semi*/
4500 
4501   // If the pointers are equal, we are done (e.g., String[] elements).
4502   // This self-check enables sharing of secondary supertype arrays among
4503   // non-primary types such as array-of-interface.  Otherwise, each such
4504   // type would need its own customized SSA.
4505   // We move this check to the front of the fast path because many
4506   // type checks are in fact trivially successful in this manner,
4507   // so we get a nicely predicted branch right at the start of the check.
4508   cmpptr(sub_klass, super_klass);
4509   local_jcc(Assembler::equal, *L_success);
4510 
4511   // Check the supertype display:
4512   if (must_load_sco) {
4513     // Positive movl does right thing on LP64.
4514     movl(temp_reg, super_check_offset_addr);
4515     super_check_offset = RegisterOrConstant(temp_reg);
4516   }
4517   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
4518   cmpptr(super_klass, super_check_addr); // load displayed supertype
4519 
4520   // This check has worked decisively for primary supers.
4521   // Secondary supers are sought in the super_cache ('super_cache_addr').
4522   // (Secondary supers are interfaces and very deeply nested subtypes.)
4523   // This works in the same check above because of a tricky aliasing
4524   // between the super_cache and the primary super display elements.
4525   // (The 'super_check_addr' can address either, as the case requires.)
4526   // Note that the cache is updated below if it does not help us find
4527   // what we need immediately.
4528   // So if it was a primary super, we can just fail immediately.
4529   // Otherwise, it's the slow path for us (no success at this point).
4530 
4531   if (super_check_offset.is_register()) {
4532     local_jcc(Assembler::equal, *L_success);
4533     cmpl(super_check_offset.as_register(), sc_offset);
4534     if (L_failure == &L_fallthrough) {
4535       local_jcc(Assembler::equal, *L_slow_path);
4536     } else {
4537       local_jcc(Assembler::notEqual, *L_failure);
4538       final_jmp(*L_slow_path);
4539     }
4540   } else if (super_check_offset.as_constant() == sc_offset) {
4541     // Need a slow path; fast failure is impossible.
4542     if (L_slow_path == &L_fallthrough) {
4543       local_jcc(Assembler::equal, *L_success);
4544     } else {
4545       local_jcc(Assembler::notEqual, *L_slow_path);
4546       final_jmp(*L_success);
4547     }
4548   } else {
4549     // No slow path; it's a fast decision.
4550     if (L_failure == &L_fallthrough) {
4551       local_jcc(Assembler::equal, *L_success);
4552     } else {
4553       local_jcc(Assembler::notEqual, *L_failure);
4554       final_jmp(*L_success);
4555     }
4556   }
4557 
4558   bind(L_fallthrough);
4559 
4560 #undef local_jcc
4561 #undef final_jmp
4562 }
4563 
4564 
4565 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
4566                                                    Register super_klass,
4567                                                    Register temp_reg,
4568                                                    Register temp2_reg,
4569                                                    Label* L_success,
4570                                                    Label* L_failure,
4571                                                    bool set_cond_codes) {
4572   assert_different_registers(sub_klass, super_klass, temp_reg);
4573   if (temp2_reg != noreg)
4574     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
4575 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
4576 
4577   Label L_fallthrough;
4578   int label_nulls = 0;
4579   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
4580   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
4581   assert(label_nulls <= 1, "at most one NULL in the batch");
4582 
4583   // a couple of useful fields in sub_klass:
4584   int ss_offset = in_bytes(Klass::secondary_supers_offset());
4585   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
4586   Address secondary_supers_addr(sub_klass, ss_offset);
4587   Address super_cache_addr(     sub_klass, sc_offset);
4588 
4589   // Do a linear scan of the secondary super-klass chain.
4590   // This code is rarely used, so simplicity is a virtue here.
4591   // The repne_scan instruction uses fixed registers, which we must spill.
4592   // Don't worry too much about pre-existing connections with the input regs.
4593 
4594   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
4595   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
4596 
4597   // Get super_klass value into rax (even if it was in rdi or rcx).
4598   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
4599   if (super_klass != rax || UseCompressedOops) {
4600     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
4601     mov(rax, super_klass);
4602   }
4603   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
4604   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
4605 
4606 #ifndef PRODUCT
4607   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
4608   ExternalAddress pst_counter_addr((address) pst_counter);
4609   NOT_LP64(  incrementl(pst_counter_addr) );
4610   LP64_ONLY( lea(rcx, pst_counter_addr) );
4611   LP64_ONLY( incrementl(Address(rcx, 0)) );
4612 #endif //PRODUCT
4613 
4614   // We will consult the secondary-super array.
4615   movptr(rdi, secondary_supers_addr);
4616   // Load the array length.  (Positive movl does right thing on LP64.)
4617   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
4618   // Skip to start of data.
4619   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
4620 
4621   // Scan RCX words at [RDI] for an occurrence of RAX.
4622   // Set NZ/Z based on last compare.
4623   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
4624   // not change flags (only scas instruction which is repeated sets flags).
4625   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
4626 
4627     testptr(rax,rax); // Set Z = 0
4628     repne_scan();
4629 
4630   // Unspill the temp. registers:
4631   if (pushed_rdi)  pop(rdi);
4632   if (pushed_rcx)  pop(rcx);
4633   if (pushed_rax)  pop(rax);
4634 
4635   if (set_cond_codes) {
4636     // Special hack for the AD files:  rdi is guaranteed non-zero.
4637     assert(!pushed_rdi, "rdi must be left non-NULL");
4638     // Also, the condition codes are properly set Z/NZ on succeed/failure.
4639   }
4640 
4641   if (L_failure == &L_fallthrough)
4642         jccb(Assembler::notEqual, *L_failure);
4643   else  jcc(Assembler::notEqual, *L_failure);
4644 
4645   // Success.  Cache the super we found and proceed in triumph.
4646   movptr(super_cache_addr, super_klass);
4647 
4648   if (L_success != &L_fallthrough) {
4649     jmp(*L_success);
4650   }
4651 
4652 #undef IS_A_TEMP
4653 
4654   bind(L_fallthrough);
4655 }
4656 
4657 void MacroAssembler::clinit_barrier(Register klass, Register thread, Label* L_fast_path, Label* L_slow_path) {
4658   assert(L_fast_path != NULL || L_slow_path != NULL, "at least one is required");
4659 
4660   Label L_fallthrough;
4661   if (L_fast_path == NULL) {
4662     L_fast_path = &L_fallthrough;
4663   } else if (L_slow_path == NULL) {
4664     L_slow_path = &L_fallthrough;
4665   }
4666 
4667   // Fast path check: class is fully initialized
4668   cmpb(Address(klass, InstanceKlass::init_state_offset()), InstanceKlass::fully_initialized);
4669   jcc(Assembler::equal, *L_fast_path);
4670 
4671   // Fast path check: current thread is initializer thread
4672   cmpptr(thread, Address(klass, InstanceKlass::init_thread_offset()));
4673   if (L_slow_path == &L_fallthrough) {
4674     jcc(Assembler::equal, *L_fast_path);
4675     bind(*L_slow_path);
4676   } else if (L_fast_path == &L_fallthrough) {
4677     jcc(Assembler::notEqual, *L_slow_path);
4678     bind(*L_fast_path);
4679   } else {
4680     Unimplemented();
4681   }
4682 }
4683 
4684 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
4685   if (VM_Version::supports_cmov()) {
4686     cmovl(cc, dst, src);
4687   } else {
4688     Label L;
4689     jccb(negate_condition(cc), L);
4690     movl(dst, src);
4691     bind(L);
4692   }
4693 }
4694 
4695 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
4696   if (VM_Version::supports_cmov()) {
4697     cmovl(cc, dst, src);
4698   } else {
4699     Label L;
4700     jccb(negate_condition(cc), L);
4701     movl(dst, src);
4702     bind(L);
4703   }
4704 }
4705 
4706 void MacroAssembler::verify_oop(Register reg, const char* s) {
4707   if (!VerifyOops || VerifyAdapterSharing) {
4708     // Below address of the code string confuses VerifyAdapterSharing
4709     // because it may differ between otherwise equivalent adapters.
4710     return;
4711   }
4712 
4713   // Pass register number to verify_oop_subroutine
4714   const char* b = NULL;
4715   {
4716     ResourceMark rm;
4717     stringStream ss;
4718     ss.print("verify_oop: %s: %s", reg->name(), s);
4719     b = code_string(ss.as_string());
4720   }
4721   BLOCK_COMMENT("verify_oop {");
4722 #ifdef _LP64
4723   push(rscratch1);                    // save r10, trashed by movptr()
4724 #endif
4725   push(rax);                          // save rax,
4726   push(reg);                          // pass register argument
4727   ExternalAddress buffer((address) b);
4728   // avoid using pushptr, as it modifies scratch registers
4729   // and our contract is not to modify anything
4730   movptr(rax, buffer.addr());
4731   push(rax);
4732   // call indirectly to solve generation ordering problem
4733   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
4734   call(rax);
4735   // Caller pops the arguments (oop, message) and restores rax, r10
4736   BLOCK_COMMENT("} verify_oop");
4737 }
4738 
4739 
4740 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
4741                                                       Register tmp,
4742                                                       int offset) {
4743   intptr_t value = *delayed_value_addr;
4744   if (value != 0)
4745     return RegisterOrConstant(value + offset);
4746 
4747   // load indirectly to solve generation ordering problem
4748   movptr(tmp, ExternalAddress((address) delayed_value_addr));
4749 
4750 #ifdef ASSERT
4751   { Label L;
4752     testptr(tmp, tmp);
4753     if (WizardMode) {
4754       const char* buf = NULL;
4755       {
4756         ResourceMark rm;
4757         stringStream ss;
4758         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
4759         buf = code_string(ss.as_string());
4760       }
4761       jcc(Assembler::notZero, L);
4762       STOP(buf);
4763     } else {
4764       jccb(Assembler::notZero, L);
4765       hlt();
4766     }
4767     bind(L);
4768   }
4769 #endif
4770 
4771   if (offset != 0)
4772     addptr(tmp, offset);
4773 
4774   return RegisterOrConstant(tmp);
4775 }
4776 
4777 
4778 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
4779                                          int extra_slot_offset) {
4780   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
4781   int stackElementSize = Interpreter::stackElementSize;
4782   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
4783 #ifdef ASSERT
4784   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
4785   assert(offset1 - offset == stackElementSize, "correct arithmetic");
4786 #endif
4787   Register             scale_reg    = noreg;
4788   Address::ScaleFactor scale_factor = Address::no_scale;
4789   if (arg_slot.is_constant()) {
4790     offset += arg_slot.as_constant() * stackElementSize;
4791   } else {
4792     scale_reg    = arg_slot.as_register();
4793     scale_factor = Address::times(stackElementSize);
4794   }
4795   offset += wordSize;           // return PC is on stack
4796   return Address(rsp, scale_reg, scale_factor, offset);
4797 }
4798 
4799 
4800 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
4801   if (!VerifyOops || VerifyAdapterSharing) {
4802     // Below address of the code string confuses VerifyAdapterSharing
4803     // because it may differ between otherwise equivalent adapters.
4804     return;
4805   }
4806 
4807   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
4808   // Pass register number to verify_oop_subroutine
4809   const char* b = NULL;
4810   {
4811     ResourceMark rm;
4812     stringStream ss;
4813     ss.print("verify_oop_addr: %s", s);
4814     b = code_string(ss.as_string());
4815   }
4816 #ifdef _LP64
4817   push(rscratch1);                    // save r10, trashed by movptr()
4818 #endif
4819   push(rax);                          // save rax,
4820   // addr may contain rsp so we will have to adjust it based on the push
4821   // we just did (and on 64 bit we do two pushes)
4822   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
4823   // stores rax into addr which is backwards of what was intended.
4824   if (addr.uses(rsp)) {
4825     lea(rax, addr);
4826     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
4827   } else {
4828     pushptr(addr);
4829   }
4830 
4831   ExternalAddress buffer((address) b);
4832   // pass msg argument
4833   // avoid using pushptr, as it modifies scratch registers
4834   // and our contract is not to modify anything
4835   movptr(rax, buffer.addr());
4836   push(rax);
4837 
4838   // call indirectly to solve generation ordering problem
4839   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
4840   call(rax);
4841   // Caller pops the arguments (addr, message) and restores rax, r10.
4842 }
4843 
4844 void MacroAssembler::verify_tlab() {
4845 #ifdef ASSERT
4846   if (UseTLAB && VerifyOops) {
4847     Label next, ok;
4848     Register t1 = rsi;
4849     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
4850 
4851     push(t1);
4852     NOT_LP64(push(thread_reg));
4853     NOT_LP64(get_thread(thread_reg));
4854 
4855     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
4856     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
4857     jcc(Assembler::aboveEqual, next);
4858     STOP("assert(top >= start)");
4859     should_not_reach_here();
4860 
4861     bind(next);
4862     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
4863     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
4864     jcc(Assembler::aboveEqual, ok);
4865     STOP("assert(top <= end)");
4866     should_not_reach_here();
4867 
4868     bind(ok);
4869     NOT_LP64(pop(thread_reg));
4870     pop(t1);
4871   }
4872 #endif
4873 }
4874 
4875 class ControlWord {
4876  public:
4877   int32_t _value;
4878 
4879   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
4880   int  precision_control() const       { return  (_value >>  8) & 3      ; }
4881   bool precision() const               { return ((_value >>  5) & 1) != 0; }
4882   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
4883   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
4884   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
4885   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
4886   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
4887 
4888   void print() const {
4889     // rounding control
4890     const char* rc;
4891     switch (rounding_control()) {
4892       case 0: rc = "round near"; break;
4893       case 1: rc = "round down"; break;
4894       case 2: rc = "round up  "; break;
4895       case 3: rc = "chop      "; break;
4896     };
4897     // precision control
4898     const char* pc;
4899     switch (precision_control()) {
4900       case 0: pc = "24 bits "; break;
4901       case 1: pc = "reserved"; break;
4902       case 2: pc = "53 bits "; break;
4903       case 3: pc = "64 bits "; break;
4904     };
4905     // flags
4906     char f[9];
4907     f[0] = ' ';
4908     f[1] = ' ';
4909     f[2] = (precision   ()) ? 'P' : 'p';
4910     f[3] = (underflow   ()) ? 'U' : 'u';
4911     f[4] = (overflow    ()) ? 'O' : 'o';
4912     f[5] = (zero_divide ()) ? 'Z' : 'z';
4913     f[6] = (denormalized()) ? 'D' : 'd';
4914     f[7] = (invalid     ()) ? 'I' : 'i';
4915     f[8] = '\x0';
4916     // output
4917     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
4918   }
4919 
4920 };
4921 
4922 class StatusWord {
4923  public:
4924   int32_t _value;
4925 
4926   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
4927   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
4928   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
4929   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
4930   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
4931   int  top() const                     { return  (_value >> 11) & 7      ; }
4932   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
4933   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
4934   bool precision() const               { return ((_value >>  5) & 1) != 0; }
4935   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
4936   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
4937   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
4938   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
4939   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
4940 
4941   void print() const {
4942     // condition codes
4943     char c[5];
4944     c[0] = (C3()) ? '3' : '-';
4945     c[1] = (C2()) ? '2' : '-';
4946     c[2] = (C1()) ? '1' : '-';
4947     c[3] = (C0()) ? '0' : '-';
4948     c[4] = '\x0';
4949     // flags
4950     char f[9];
4951     f[0] = (error_status()) ? 'E' : '-';
4952     f[1] = (stack_fault ()) ? 'S' : '-';
4953     f[2] = (precision   ()) ? 'P' : '-';
4954     f[3] = (underflow   ()) ? 'U' : '-';
4955     f[4] = (overflow    ()) ? 'O' : '-';
4956     f[5] = (zero_divide ()) ? 'Z' : '-';
4957     f[6] = (denormalized()) ? 'D' : '-';
4958     f[7] = (invalid     ()) ? 'I' : '-';
4959     f[8] = '\x0';
4960     // output
4961     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
4962   }
4963 
4964 };
4965 
4966 class TagWord {
4967  public:
4968   int32_t _value;
4969 
4970   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
4971 
4972   void print() const {
4973     printf("%04x", _value & 0xFFFF);
4974   }
4975 
4976 };
4977 
4978 class FPU_Register {
4979  public:
4980   int32_t _m0;
4981   int32_t _m1;
4982   int16_t _ex;
4983 
4984   bool is_indefinite() const           {
4985     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
4986   }
4987 
4988   void print() const {
4989     char  sign = (_ex < 0) ? '-' : '+';
4990     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
4991     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
4992   };
4993 
4994 };
4995 
4996 class FPU_State {
4997  public:
4998   enum {
4999     register_size       = 10,
5000     number_of_registers =  8,
5001     register_mask       =  7
5002   };
5003 
5004   ControlWord  _control_word;
5005   StatusWord   _status_word;
5006   TagWord      _tag_word;
5007   int32_t      _error_offset;
5008   int32_t      _error_selector;
5009   int32_t      _data_offset;
5010   int32_t      _data_selector;
5011   int8_t       _register[register_size * number_of_registers];
5012 
5013   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
5014   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
5015 
5016   const char* tag_as_string(int tag) const {
5017     switch (tag) {
5018       case 0: return "valid";
5019       case 1: return "zero";
5020       case 2: return "special";
5021       case 3: return "empty";
5022     }
5023     ShouldNotReachHere();
5024     return NULL;
5025   }
5026 
5027   void print() const {
5028     // print computation registers
5029     { int t = _status_word.top();
5030       for (int i = 0; i < number_of_registers; i++) {
5031         int j = (i - t) & register_mask;
5032         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
5033         st(j)->print();
5034         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
5035       }
5036     }
5037     printf("\n");
5038     // print control registers
5039     printf("ctrl = "); _control_word.print(); printf("\n");
5040     printf("stat = "); _status_word .print(); printf("\n");
5041     printf("tags = "); _tag_word    .print(); printf("\n");
5042   }
5043 
5044 };
5045 
5046 class Flag_Register {
5047  public:
5048   int32_t _value;
5049 
5050   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
5051   bool direction() const               { return ((_value >> 10) & 1) != 0; }
5052   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
5053   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
5054   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
5055   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
5056   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
5057 
5058   void print() const {
5059     // flags
5060     char f[8];
5061     f[0] = (overflow       ()) ? 'O' : '-';
5062     f[1] = (direction      ()) ? 'D' : '-';
5063     f[2] = (sign           ()) ? 'S' : '-';
5064     f[3] = (zero           ()) ? 'Z' : '-';
5065     f[4] = (auxiliary_carry()) ? 'A' : '-';
5066     f[5] = (parity         ()) ? 'P' : '-';
5067     f[6] = (carry          ()) ? 'C' : '-';
5068     f[7] = '\x0';
5069     // output
5070     printf("%08x  flags = %s", _value, f);
5071   }
5072 
5073 };
5074 
5075 class IU_Register {
5076  public:
5077   int32_t _value;
5078 
5079   void print() const {
5080     printf("%08x  %11d", _value, _value);
5081   }
5082 
5083 };
5084 
5085 class IU_State {
5086  public:
5087   Flag_Register _eflags;
5088   IU_Register   _rdi;
5089   IU_Register   _rsi;
5090   IU_Register   _rbp;
5091   IU_Register   _rsp;
5092   IU_Register   _rbx;
5093   IU_Register   _rdx;
5094   IU_Register   _rcx;
5095   IU_Register   _rax;
5096 
5097   void print() const {
5098     // computation registers
5099     printf("rax,  = "); _rax.print(); printf("\n");
5100     printf("rbx,  = "); _rbx.print(); printf("\n");
5101     printf("rcx  = "); _rcx.print(); printf("\n");
5102     printf("rdx  = "); _rdx.print(); printf("\n");
5103     printf("rdi  = "); _rdi.print(); printf("\n");
5104     printf("rsi  = "); _rsi.print(); printf("\n");
5105     printf("rbp,  = "); _rbp.print(); printf("\n");
5106     printf("rsp  = "); _rsp.print(); printf("\n");
5107     printf("\n");
5108     // control registers
5109     printf("flgs = "); _eflags.print(); printf("\n");
5110   }
5111 };
5112 
5113 
5114 class CPU_State {
5115  public:
5116   FPU_State _fpu_state;
5117   IU_State  _iu_state;
5118 
5119   void print() const {
5120     printf("--------------------------------------------------\n");
5121     _iu_state .print();
5122     printf("\n");
5123     _fpu_state.print();
5124     printf("--------------------------------------------------\n");
5125   }
5126 
5127 };
5128 
5129 
5130 static void _print_CPU_state(CPU_State* state) {
5131   state->print();
5132 };
5133 
5134 
5135 void MacroAssembler::print_CPU_state() {
5136   push_CPU_state();
5137   push(rsp);                // pass CPU state
5138   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
5139   addptr(rsp, wordSize);       // discard argument
5140   pop_CPU_state();
5141 }
5142 
5143 
5144 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
5145   static int counter = 0;
5146   FPU_State* fs = &state->_fpu_state;
5147   counter++;
5148   // For leaf calls, only verify that the top few elements remain empty.
5149   // We only need 1 empty at the top for C2 code.
5150   if( stack_depth < 0 ) {
5151     if( fs->tag_for_st(7) != 3 ) {
5152       printf("FPR7 not empty\n");
5153       state->print();
5154       assert(false, "error");
5155       return false;
5156     }
5157     return true;                // All other stack states do not matter
5158   }
5159 
5160   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
5161          "bad FPU control word");
5162 
5163   // compute stack depth
5164   int i = 0;
5165   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
5166   int d = i;
5167   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
5168   // verify findings
5169   if (i != FPU_State::number_of_registers) {
5170     // stack not contiguous
5171     printf("%s: stack not contiguous at ST%d\n", s, i);
5172     state->print();
5173     assert(false, "error");
5174     return false;
5175   }
5176   // check if computed stack depth corresponds to expected stack depth
5177   if (stack_depth < 0) {
5178     // expected stack depth is -stack_depth or less
5179     if (d > -stack_depth) {
5180       // too many elements on the stack
5181       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
5182       state->print();
5183       assert(false, "error");
5184       return false;
5185     }
5186   } else {
5187     // expected stack depth is stack_depth
5188     if (d != stack_depth) {
5189       // wrong stack depth
5190       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
5191       state->print();
5192       assert(false, "error");
5193       return false;
5194     }
5195   }
5196   // everything is cool
5197   return true;
5198 }
5199 
5200 
5201 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
5202   if (!VerifyFPU) return;
5203   push_CPU_state();
5204   push(rsp);                // pass CPU state
5205   ExternalAddress msg((address) s);
5206   // pass message string s
5207   pushptr(msg.addr());
5208   push(stack_depth);        // pass stack depth
5209   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
5210   addptr(rsp, 3 * wordSize);   // discard arguments
5211   // check for error
5212   { Label L;
5213     testl(rax, rax);
5214     jcc(Assembler::notZero, L);
5215     int3();                  // break if error condition
5216     bind(L);
5217   }
5218   pop_CPU_state();
5219 }
5220 
5221 void MacroAssembler::restore_cpu_control_state_after_jni() {
5222   // Either restore the MXCSR register after returning from the JNI Call
5223   // or verify that it wasn't changed (with -Xcheck:jni flag).
5224   if (VM_Version::supports_sse()) {
5225     if (RestoreMXCSROnJNICalls) {
5226       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
5227     } else if (CheckJNICalls) {
5228       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
5229     }
5230   }
5231   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
5232   vzeroupper();
5233   // Reset k1 to 0xffff.
5234 
5235 #ifdef COMPILER2
5236   if (PostLoopMultiversioning && VM_Version::supports_evex()) {
5237     push(rcx);
5238     movl(rcx, 0xffff);
5239     kmovwl(k1, rcx);
5240     pop(rcx);
5241   }
5242 #endif // COMPILER2
5243 
5244 #ifndef _LP64
5245   // Either restore the x87 floating pointer control word after returning
5246   // from the JNI call or verify that it wasn't changed.
5247   if (CheckJNICalls) {
5248     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
5249   }
5250 #endif // _LP64
5251 }
5252 
5253 // ((OopHandle)result).resolve();
5254 void MacroAssembler::resolve_oop_handle(Register result, Register tmp) {
5255   assert_different_registers(result, tmp);
5256 
5257   // Only 64 bit platforms support GCs that require a tmp register
5258   // Only IN_HEAP loads require a thread_tmp register
5259   // OopHandle::resolve is an indirection like jobject.
5260   access_load_at(T_OBJECT, IN_NATIVE,
5261                  result, Address(result, 0), tmp, /*tmp_thread*/noreg);
5262 }
5263 
5264 // ((WeakHandle)result).resolve();
5265 void MacroAssembler::resolve_weak_handle(Register rresult, Register rtmp) {
5266   assert_different_registers(rresult, rtmp);
5267   Label resolved;
5268 
5269   // A null weak handle resolves to null.
5270   cmpptr(rresult, 0);
5271   jcc(Assembler::equal, resolved);
5272 
5273   // Only 64 bit platforms support GCs that require a tmp register
5274   // Only IN_HEAP loads require a thread_tmp register
5275   // WeakHandle::resolve is an indirection like jweak.
5276   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
5277                  rresult, Address(rresult, 0), rtmp, /*tmp_thread*/noreg);
5278   bind(resolved);
5279 }
5280 
5281 void MacroAssembler::load_mirror(Register mirror, Register method, Register tmp) {
5282   // get mirror
5283   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
5284   load_method_holder(mirror, method);
5285   movptr(mirror, Address(mirror, mirror_offset));
5286   resolve_oop_handle(mirror, tmp);
5287 }
5288 
5289 void MacroAssembler::load_method_holder_cld(Register rresult, Register rmethod) {
5290   load_method_holder(rresult, rmethod);
5291   movptr(rresult, Address(rresult, InstanceKlass::class_loader_data_offset()));
5292 }
5293 
5294 void MacroAssembler::load_metadata(Register dst, Register src) {
5295   if (UseCompressedClassPointers) {
5296     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5297   } else {
5298     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5299   }
5300 }
5301 
5302 void MacroAssembler::load_storage_props(Register dst, Register src) {
5303   load_metadata(dst, src);
5304   if (UseCompressedClassPointers) {
5305     shrl(dst, oopDesc::narrow_storage_props_shift);
5306   } else {
5307     shrq(dst, oopDesc::wide_storage_props_shift);
5308   }
5309 }
5310 
5311 void MacroAssembler::load_method_holder(Register holder, Register method) {
5312   movptr(holder, Address(method, Method::const_offset()));                      // ConstMethod*
5313   movptr(holder, Address(holder, ConstMethod::constants_offset()));             // ConstantPool*
5314   movptr(holder, Address(holder, ConstantPool::pool_holder_offset_in_bytes())); // InstanceKlass*
5315 }
5316 
5317 void MacroAssembler::load_klass(Register dst, Register src) {
5318   load_metadata(dst, src);
5319 #ifdef _LP64
5320   if (UseCompressedClassPointers) {
5321     andl(dst, oopDesc::compressed_klass_mask());
5322     decode_klass_not_null(dst);
5323   } else
5324 #endif
5325   {
5326 #ifdef _LP64
5327     shlq(dst, oopDesc::storage_props_nof_bits);
5328     shrq(dst, oopDesc::storage_props_nof_bits);
5329 #else
5330     andl(dst, oopDesc::wide_klass_mask());
5331 #endif
5332   }
5333 }
5334 
5335 void MacroAssembler::load_prototype_header(Register dst, Register src) {
5336   load_klass(dst, src);
5337   movptr(dst, Address(dst, Klass::prototype_header_offset()));
5338 }
5339 
5340 void MacroAssembler::store_klass(Register dst, Register src) {
5341 #ifdef _LP64
5342   if (UseCompressedClassPointers) {
5343     encode_klass_not_null(src);
5344     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
5345   } else
5346 #endif
5347     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
5348 }
5349 
5350 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators, Register dst, Address src,
5351                                     Register tmp1, Register thread_tmp) {
5352   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5353   decorators = AccessInternal::decorator_fixup(decorators);
5354   bool as_raw = (decorators & AS_RAW) != 0;
5355   if (as_raw) {
5356     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
5357   } else {
5358     bs->load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
5359   }
5360 }
5361 
5362 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators, Address dst, Register src,
5363                                      Register tmp1, Register tmp2, Register tmp3) {
5364   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5365   decorators = AccessInternal::decorator_fixup(decorators);
5366   bool as_raw = (decorators & AS_RAW) != 0;
5367   if (as_raw) {
5368     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, src, tmp1, tmp2, tmp3);
5369   } else {
5370     bs->store_at(this, decorators, type, dst, src, tmp1, tmp2, tmp3);
5371   }
5372 }
5373 
5374 void MacroAssembler::resolve(DecoratorSet decorators, Register obj) {
5375   // Use stronger ACCESS_WRITE|ACCESS_READ by default.
5376   if ((decorators & (ACCESS_READ | ACCESS_WRITE)) == 0) {
5377     decorators |= ACCESS_READ | ACCESS_WRITE;
5378   }
5379   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5380   return bs->resolve(this, decorators, obj);
5381 }
5382 
5383 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
5384                                    Register thread_tmp, DecoratorSet decorators) {
5385   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, thread_tmp);
5386 }
5387 
5388 // Doesn't do verfication, generates fixed size code
5389 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
5390                                             Register thread_tmp, DecoratorSet decorators) {
5391   access_load_at(T_OBJECT, IN_HEAP | IS_NOT_NULL | decorators, dst, src, tmp1, thread_tmp);
5392 }
5393 
5394 void MacroAssembler::store_heap_oop(Address dst, Register src, Register tmp1,
5395                                     Register tmp2, Register tmp3, DecoratorSet decorators) {
5396   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2, tmp3);
5397 }
5398 
5399 // Used for storing NULLs.
5400 void MacroAssembler::store_heap_oop_null(Address dst) {
5401   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg, noreg);
5402 }
5403 
5404 #ifdef _LP64
5405 void MacroAssembler::store_klass_gap(Register dst, Register src) {
5406   if (UseCompressedClassPointers) {
5407     // Store to klass gap in destination
5408     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
5409   }
5410 }
5411 
5412 #ifdef ASSERT
5413 void MacroAssembler::verify_heapbase(const char* msg) {
5414   assert (UseCompressedOops, "should be compressed");
5415   assert (Universe::heap() != NULL, "java heap should be initialized");
5416   if (CheckCompressedOops) {
5417     Label ok;
5418     push(rscratch1); // cmpptr trashes rscratch1
5419     cmpptr(r12_heapbase, ExternalAddress((address)CompressedOops::ptrs_base_addr()));
5420     jcc(Assembler::equal, ok);
5421     STOP(msg);
5422     bind(ok);
5423     pop(rscratch1);
5424   }
5425 }
5426 #endif
5427 
5428 // Algorithm must match oop.inline.hpp encode_heap_oop.
5429 void MacroAssembler::encode_heap_oop(Register r) {
5430 #ifdef ASSERT
5431   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
5432 #endif
5433   verify_oop(r, "broken oop in encode_heap_oop");
5434   if (CompressedOops::base() == NULL) {
5435     if (CompressedOops::shift() != 0) {
5436       assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5437       shrq(r, LogMinObjAlignmentInBytes);
5438     }
5439     return;
5440   }
5441   testq(r, r);
5442   cmovq(Assembler::equal, r, r12_heapbase);
5443   subq(r, r12_heapbase);
5444   shrq(r, LogMinObjAlignmentInBytes);
5445 }
5446 
5447 void MacroAssembler::encode_heap_oop_not_null(Register r) {
5448 #ifdef ASSERT
5449   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
5450   if (CheckCompressedOops) {
5451     Label ok;
5452     testq(r, r);
5453     jcc(Assembler::notEqual, ok);
5454     STOP("null oop passed to encode_heap_oop_not_null");
5455     bind(ok);
5456   }
5457 #endif
5458   verify_oop(r, "broken oop in encode_heap_oop_not_null");
5459   if (CompressedOops::base() != NULL) {
5460     subq(r, r12_heapbase);
5461   }
5462   if (CompressedOops::shift() != 0) {
5463     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5464     shrq(r, LogMinObjAlignmentInBytes);
5465   }
5466 }
5467 
5468 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
5469 #ifdef ASSERT
5470   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
5471   if (CheckCompressedOops) {
5472     Label ok;
5473     testq(src, src);
5474     jcc(Assembler::notEqual, ok);
5475     STOP("null oop passed to encode_heap_oop_not_null2");
5476     bind(ok);
5477   }
5478 #endif
5479   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
5480   if (dst != src) {
5481     movq(dst, src);
5482   }
5483   if (CompressedOops::base() != NULL) {
5484     subq(dst, r12_heapbase);
5485   }
5486   if (CompressedOops::shift() != 0) {
5487     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5488     shrq(dst, LogMinObjAlignmentInBytes);
5489   }
5490 }
5491 
5492 void  MacroAssembler::decode_heap_oop(Register r) {
5493 #ifdef ASSERT
5494   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
5495 #endif
5496   if (CompressedOops::base() == NULL) {
5497     if (CompressedOops::shift() != 0) {
5498       assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5499       shlq(r, LogMinObjAlignmentInBytes);
5500     }
5501   } else {
5502     Label done;
5503     shlq(r, LogMinObjAlignmentInBytes);
5504     jccb(Assembler::equal, done);
5505     addq(r, r12_heapbase);
5506     bind(done);
5507   }
5508   verify_oop(r, "broken oop in decode_heap_oop");
5509 }
5510 
5511 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
5512   // Note: it will change flags
5513   assert (UseCompressedOops, "should only be used for compressed headers");
5514   assert (Universe::heap() != NULL, "java heap should be initialized");
5515   // Cannot assert, unverified entry point counts instructions (see .ad file)
5516   // vtableStubs also counts instructions in pd_code_size_limit.
5517   // Also do not verify_oop as this is called by verify_oop.
5518   if (CompressedOops::shift() != 0) {
5519     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5520     shlq(r, LogMinObjAlignmentInBytes);
5521     if (CompressedOops::base() != NULL) {
5522       addq(r, r12_heapbase);
5523     }
5524   } else {
5525     assert (CompressedOops::base() == NULL, "sanity");
5526   }
5527 }
5528 
5529 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
5530   // Note: it will change flags
5531   assert (UseCompressedOops, "should only be used for compressed headers");
5532   assert (Universe::heap() != NULL, "java heap should be initialized");
5533   // Cannot assert, unverified entry point counts instructions (see .ad file)
5534   // vtableStubs also counts instructions in pd_code_size_limit.
5535   // Also do not verify_oop as this is called by verify_oop.
5536   if (CompressedOops::shift() != 0) {
5537     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5538     if (LogMinObjAlignmentInBytes == Address::times_8) {
5539       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
5540     } else {
5541       if (dst != src) {
5542         movq(dst, src);
5543       }
5544       shlq(dst, LogMinObjAlignmentInBytes);
5545       if (CompressedOops::base() != NULL) {
5546         addq(dst, r12_heapbase);
5547       }
5548     }
5549   } else {
5550     assert (CompressedOops::base() == NULL, "sanity");
5551     if (dst != src) {
5552       movq(dst, src);
5553     }
5554   }
5555 }
5556 
5557 void MacroAssembler::encode_klass_not_null(Register r) {
5558   if (CompressedKlassPointers::base() != NULL) {
5559     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
5560     assert(r != r12_heapbase, "Encoding a klass in r12");
5561     mov64(r12_heapbase, (int64_t)CompressedKlassPointers::base());
5562     subq(r, r12_heapbase);
5563   }
5564   if (CompressedKlassPointers::shift() != 0) {
5565     assert (LogKlassAlignmentInBytes == CompressedKlassPointers::shift(), "decode alg wrong");
5566     shrq(r, LogKlassAlignmentInBytes);
5567   }
5568   if (CompressedKlassPointers::base() != NULL) {
5569     reinit_heapbase();
5570   }
5571 }
5572 
5573 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
5574   if (dst == src) {
5575     encode_klass_not_null(src);
5576   } else {
5577     if (CompressedKlassPointers::base() != NULL) {
5578       mov64(dst, (int64_t)CompressedKlassPointers::base());
5579       negq(dst);
5580       addq(dst, src);
5581     } else {
5582       movptr(dst, src);
5583     }
5584     if (CompressedKlassPointers::shift() != 0) {
5585       assert (LogKlassAlignmentInBytes == CompressedKlassPointers::shift(), "decode alg wrong");
5586       shrq(dst, LogKlassAlignmentInBytes);
5587     }
5588   }
5589 }
5590 
5591 // Function instr_size_for_decode_klass_not_null() counts the instructions
5592 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
5593 // when (Universe::heap() != NULL).  Hence, if the instructions they
5594 // generate change, then this method needs to be updated.
5595 int MacroAssembler::instr_size_for_decode_klass_not_null() {
5596   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
5597   if (CompressedKlassPointers::base() != NULL) {
5598     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
5599     return (CompressedKlassPointers::shift() == 0 ? 20 : 24);
5600   } else {
5601     // longest load decode klass function, mov64, leaq
5602     return 16;
5603   }
5604 }
5605 
5606 // !!! If the instructions that get generated here change then function
5607 // instr_size_for_decode_klass_not_null() needs to get updated.
5608 void  MacroAssembler::decode_klass_not_null(Register r) {
5609   // Note: it will change flags
5610   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5611   assert(r != r12_heapbase, "Decoding a klass in r12");
5612   // Cannot assert, unverified entry point counts instructions (see .ad file)
5613   // vtableStubs also counts instructions in pd_code_size_limit.
5614   // Also do not verify_oop as this is called by verify_oop.
5615   if (CompressedKlassPointers::shift() != 0) {
5616     assert(LogKlassAlignmentInBytes == CompressedKlassPointers::shift(), "decode alg wrong");
5617     shlq(r, LogKlassAlignmentInBytes);
5618   }
5619   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
5620   if (CompressedKlassPointers::base() != NULL) {
5621     mov64(r12_heapbase, (int64_t)CompressedKlassPointers::base());
5622     addq(r, r12_heapbase);
5623     reinit_heapbase();
5624   }
5625 }
5626 
5627 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
5628   // Note: it will change flags
5629   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5630   if (dst == src) {
5631     decode_klass_not_null(dst);
5632   } else {
5633     // Cannot assert, unverified entry point counts instructions (see .ad file)
5634     // vtableStubs also counts instructions in pd_code_size_limit.
5635     // Also do not verify_oop as this is called by verify_oop.
5636     mov64(dst, (int64_t)CompressedKlassPointers::base());
5637     if (CompressedKlassPointers::shift() != 0) {
5638       assert(LogKlassAlignmentInBytes == CompressedKlassPointers::shift(), "decode alg wrong");
5639       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
5640       leaq(dst, Address(dst, src, Address::times_8, 0));
5641     } else {
5642       addq(dst, src);
5643     }
5644   }
5645 }
5646 
5647 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
5648   assert (UseCompressedOops, "should only be used for compressed headers");
5649   assert (Universe::heap() != NULL, "java heap should be initialized");
5650   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5651   int oop_index = oop_recorder()->find_index(obj);
5652   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5653   mov_narrow_oop(dst, oop_index, rspec);
5654 }
5655 
5656 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
5657   assert (UseCompressedOops, "should only be used for compressed headers");
5658   assert (Universe::heap() != NULL, "java heap should be initialized");
5659   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5660   int oop_index = oop_recorder()->find_index(obj);
5661   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5662   mov_narrow_oop(dst, oop_index, rspec);
5663 }
5664 
5665 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
5666   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5667   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5668   int klass_index = oop_recorder()->find_index(k);
5669   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5670   mov_narrow_oop(dst, CompressedKlassPointers::encode(k), rspec);
5671 }
5672 
5673 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
5674   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5675   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5676   int klass_index = oop_recorder()->find_index(k);
5677   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5678   mov_narrow_oop(dst, CompressedKlassPointers::encode(k), rspec);
5679 }
5680 
5681 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
5682   assert (UseCompressedOops, "should only be used for compressed headers");
5683   assert (Universe::heap() != NULL, "java heap should be initialized");
5684   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5685   int oop_index = oop_recorder()->find_index(obj);
5686   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5687   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
5688 }
5689 
5690 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
5691   assert (UseCompressedOops, "should only be used for compressed headers");
5692   assert (Universe::heap() != NULL, "java heap should be initialized");
5693   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5694   int oop_index = oop_recorder()->find_index(obj);
5695   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5696   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
5697 }
5698 
5699 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
5700   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5701   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5702   int klass_index = oop_recorder()->find_index(k);
5703   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5704   Assembler::cmp_narrow_oop(dst, CompressedKlassPointers::encode(k), rspec);
5705 }
5706 
5707 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
5708   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5709   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5710   int klass_index = oop_recorder()->find_index(k);
5711   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5712   Assembler::cmp_narrow_oop(dst, CompressedKlassPointers::encode(k), rspec);
5713 }
5714 
5715 void MacroAssembler::reinit_heapbase() {
5716   if (UseCompressedOops || UseCompressedClassPointers) {
5717     if (Universe::heap() != NULL) {
5718       if (CompressedOops::base() == NULL) {
5719         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
5720       } else {
5721         mov64(r12_heapbase, (int64_t)CompressedOops::ptrs_base());
5722       }
5723     } else {
5724       movptr(r12_heapbase, ExternalAddress((address)CompressedOops::ptrs_base_addr()));
5725     }
5726   }
5727 }
5728 
5729 #endif // _LP64
5730 
5731 // C2 compiled method's prolog code.
5732 void MacroAssembler::verified_entry(Compile* C, int sp_inc) {
5733   int framesize = C->frame_size_in_bytes();
5734   int bangsize = C->bang_size_in_bytes();
5735   bool fp_mode_24b = C->in_24_bit_fp_mode();
5736   int stack_bang_size = C->need_stack_bang(bangsize) ? bangsize : 0;
5737   bool is_stub = C->stub_function() != NULL;
5738 
5739   // WARNING: Initial instruction MUST be 5 bytes or longer so that
5740   // NativeJump::patch_verified_entry will be able to patch out the entry
5741   // code safely. The push to verify stack depth is ok at 5 bytes,
5742   // the frame allocation can be either 3 or 6 bytes. So if we don't do
5743   // stack bang then we must use the 6 byte frame allocation even if
5744   // we have no frame. :-(
5745   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
5746 
5747   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
5748   // Remove word for return addr
5749   framesize -= wordSize;
5750   stack_bang_size -= wordSize;
5751 
5752   // Calls to C2R adapters often do not accept exceptional returns.
5753   // We require that their callers must bang for them.  But be careful, because
5754   // some VM calls (such as call site linkage) can use several kilobytes of
5755   // stack.  But the stack safety zone should account for that.
5756   // See bugs 4446381, 4468289, 4497237.
5757   if (stack_bang_size > 0) {
5758     generate_stack_overflow_check(stack_bang_size);
5759 
5760     // We always push rbp, so that on return to interpreter rbp, will be
5761     // restored correctly and we can correct the stack.
5762     push(rbp);
5763     // Save caller's stack pointer into RBP if the frame pointer is preserved.
5764     if (PreserveFramePointer) {
5765       mov(rbp, rsp);
5766     }
5767     // Remove word for ebp
5768     framesize -= wordSize;
5769 
5770     // Create frame
5771     if (framesize) {
5772       subptr(rsp, framesize);
5773     }
5774   } else {
5775     // Create frame (force generation of a 4 byte immediate value)
5776     subptr_imm32(rsp, framesize);
5777 
5778     // Save RBP register now.
5779     framesize -= wordSize;
5780     movptr(Address(rsp, framesize), rbp);
5781     // Save caller's stack pointer into RBP if the frame pointer is preserved.
5782     if (PreserveFramePointer) {
5783       movptr(rbp, rsp);
5784       if (framesize > 0) {
5785         addptr(rbp, framesize);
5786       }
5787     }
5788   }
5789 
5790   if (C->needs_stack_repair()) {
5791     // Save stack increment (also account for fixed framesize and rbp)
5792     assert((sp_inc & (StackAlignmentInBytes-1)) == 0, "stack increment not aligned");
5793     movptr(Address(rsp, C->sp_inc_offset()), sp_inc + framesize + wordSize);
5794   }
5795 
5796   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
5797     framesize -= wordSize;
5798     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
5799   }
5800 
5801 #ifndef _LP64
5802   // If method sets FPU control word do it now
5803   if (fp_mode_24b) {
5804     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
5805   }
5806   if (UseSSE >= 2 && VerifyFPU) {
5807     verify_FPU(0, "FPU stack must be clean on entry");
5808   }
5809 #endif
5810 
5811 #ifdef ASSERT
5812   if (VerifyStackAtCalls) {
5813     Label L;
5814     push(rax);
5815     mov(rax, rsp);
5816     andptr(rax, StackAlignmentInBytes-1);
5817     cmpptr(rax, StackAlignmentInBytes-wordSize);
5818     pop(rax);
5819     jcc(Assembler::equal, L);
5820     STOP("Stack is not properly aligned!");
5821     bind(L);
5822   }
5823 #endif
5824 
5825   if (!is_stub) {
5826     BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5827     bs->nmethod_entry_barrier(this);
5828   }
5829 }
5830 
5831 // clear memory of size 'cnt' qwords, starting at 'base' using XMM/YMM registers
5832 void MacroAssembler::xmm_clear_mem(Register base, Register cnt, Register val, XMMRegister xtmp) {
5833   // cnt - number of qwords (8-byte words).
5834   // base - start address, qword aligned.
5835   Label L_zero_64_bytes, L_loop, L_sloop, L_tail, L_end;
5836   movdq(xtmp, val);
5837   if (UseAVX >= 2) {
5838     punpcklqdq(xtmp, xtmp);
5839     vinserti128_high(xtmp, xtmp);
5840   } else {
5841     punpcklqdq(xtmp, xtmp);
5842   }
5843   jmp(L_zero_64_bytes);
5844 
5845   BIND(L_loop);
5846   if (UseAVX >= 2) {
5847     vmovdqu(Address(base,  0), xtmp);
5848     vmovdqu(Address(base, 32), xtmp);
5849   } else {
5850     movdqu(Address(base,  0), xtmp);
5851     movdqu(Address(base, 16), xtmp);
5852     movdqu(Address(base, 32), xtmp);
5853     movdqu(Address(base, 48), xtmp);
5854   }
5855   addptr(base, 64);
5856 
5857   BIND(L_zero_64_bytes);
5858   subptr(cnt, 8);
5859   jccb(Assembler::greaterEqual, L_loop);
5860   addptr(cnt, 4);
5861   jccb(Assembler::less, L_tail);
5862   // Copy trailing 32 bytes
5863   if (UseAVX >= 2) {
5864     vmovdqu(Address(base, 0), xtmp);
5865   } else {
5866     movdqu(Address(base,  0), xtmp);
5867     movdqu(Address(base, 16), xtmp);
5868   }
5869   addptr(base, 32);
5870   subptr(cnt, 4);
5871 
5872   BIND(L_tail);
5873   addptr(cnt, 4);
5874   jccb(Assembler::lessEqual, L_end);
5875   decrement(cnt);
5876 
5877   BIND(L_sloop);
5878   movq(Address(base, 0), xtmp);
5879   addptr(base, 8);
5880   decrement(cnt);
5881   jccb(Assembler::greaterEqual, L_sloop);
5882   BIND(L_end);
5883 }
5884 
5885 void MacroAssembler::store_value_type_fields_to_buf(ciValueKlass* vk) {
5886 #ifndef _LP64
5887   super_call_VM_leaf(StubRoutines::store_value_type_fields_to_buf());
5888 #else
5889   // A value type might be returned. If fields are in registers we
5890   // need to allocate a value type instance and initialize it with
5891   // the value of the fields.
5892   Label skip, slow_case;
5893   // We only need a new buffered value if a new one is not returned
5894   testptr(rax, 1);
5895   jcc(Assembler::zero, skip);
5896 
5897   // Try to allocate a new buffered value (from the heap)
5898   if (UseTLAB) {
5899     // FIXME -- for smaller code, the inline allocation (and the slow case) should be moved inside the pack handler.
5900     if (vk != NULL) {
5901       // Called from C1, where the return type is statically known.
5902       movptr(rbx, (intptr_t)vk->get_ValueKlass());
5903       jint lh = vk->layout_helper();
5904       assert(lh != Klass::_lh_neutral_value, "inline class in return type must have been resolved");
5905       movl(r14, lh);
5906     } else {
5907       // Call from interpreter. RAX contains ((the ValueKlass* of the return type) | 0x01)
5908       mov(rbx, rax);
5909       andptr(rbx, -2);
5910       movl(r14, Address(rbx, Klass::layout_helper_offset()));
5911     }
5912 
5913     movptr(r13, Address(r15_thread, in_bytes(JavaThread::tlab_top_offset())));
5914     lea(r14, Address(r13, r14, Address::times_1));
5915     cmpptr(r14, Address(r15_thread, in_bytes(JavaThread::tlab_end_offset())));
5916     jcc(Assembler::above, slow_case);
5917     movptr(Address(r15_thread, in_bytes(JavaThread::tlab_top_offset())), r14);
5918     movptr(Address(r13, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::always_locked_prototype());
5919 
5920     xorl(rax, rax); // use zero reg to clear memory (shorter code)
5921     store_klass_gap(r13, rax);  // zero klass gap for compressed oops
5922 
5923     if (vk == NULL) {
5924       // store_klass corrupts rbx, so save it in rax for later use (interpreter case only).
5925       mov(rax, rbx);
5926     }
5927     store_klass(r13, rbx);  // klass
5928 
5929     // We have our new buffered value, initialize its fields with a
5930     // value class specific handler
5931     if (vk != NULL) {
5932       // FIXME -- do the packing in-line to avoid the runtime call
5933       mov(rax, r13);
5934       call(RuntimeAddress(vk->pack_handler()));
5935     } else {
5936       movptr(rbx, Address(rax, InstanceKlass::adr_valueklass_fixed_block_offset()));
5937       movptr(rbx, Address(rbx, ValueKlass::pack_handler_offset()));
5938       mov(rax, r13);
5939       call(rbx);
5940     }
5941     jmp(skip);
5942   }
5943 
5944   bind(slow_case);
5945   // We failed to allocate a new value, fall back to a runtime
5946   // call. Some oop field may be live in some registers but we can't
5947   // tell. That runtime call will take care of preserving them
5948   // across a GC if there's one.
5949   super_call_VM_leaf(StubRoutines::store_value_type_fields_to_buf());
5950   bind(skip);
5951 #endif
5952 }
5953 
5954 
5955 // Move a value between registers/stack slots and update the reg_state
5956 bool MacroAssembler::move_helper(VMReg from, VMReg to, BasicType bt, RegState reg_state[], int ret_off, int extra_stack_offset) {
5957   if (reg_state[to->value()] == reg_written) {
5958     return true; // Already written
5959   }
5960   if (from != to && bt != T_VOID) {
5961     if (reg_state[to->value()] == reg_readonly) {
5962       return false; // Not yet writable
5963     }
5964     if (from->is_reg()) {
5965       if (to->is_reg()) {
5966         if (from->is_XMMRegister()) {
5967           if (bt == T_DOUBLE) {
5968             movdbl(to->as_XMMRegister(), from->as_XMMRegister());
5969           } else {
5970             assert(bt == T_FLOAT, "must be float");
5971             movflt(to->as_XMMRegister(), from->as_XMMRegister());
5972           }
5973         } else {
5974           movq(to->as_Register(), from->as_Register());
5975         }
5976       } else {
5977         int st_off = to->reg2stack() * VMRegImpl::stack_slot_size + extra_stack_offset;
5978         assert(st_off != ret_off, "overwriting return address at %d", st_off);
5979         Address to_addr = Address(rsp, st_off);
5980         if (from->is_XMMRegister()) {
5981           if (bt == T_DOUBLE) {
5982             movdbl(to_addr, from->as_XMMRegister());
5983           } else {
5984             assert(bt == T_FLOAT, "must be float");
5985             movflt(to_addr, from->as_XMMRegister());
5986           }
5987         } else {
5988           movq(to_addr, from->as_Register());
5989         }
5990       }
5991     } else {
5992       Address from_addr = Address(rsp, from->reg2stack() * VMRegImpl::stack_slot_size + extra_stack_offset);
5993       if (to->is_reg()) {
5994         if (to->is_XMMRegister()) {
5995           if (bt == T_DOUBLE) {
5996             movdbl(to->as_XMMRegister(), from_addr);
5997           } else {
5998             assert(bt == T_FLOAT, "must be float");
5999             movflt(to->as_XMMRegister(), from_addr);
6000           }
6001         } else {
6002           movq(to->as_Register(), from_addr);
6003         }
6004       } else {
6005         int st_off = to->reg2stack() * VMRegImpl::stack_slot_size + extra_stack_offset;
6006         assert(st_off != ret_off, "overwriting return address at %d", st_off);
6007         movq(r13, from_addr);
6008         movq(Address(rsp, st_off), r13);
6009       }
6010     }
6011   }
6012   // Update register states
6013   reg_state[from->value()] = reg_writable;
6014   reg_state[to->value()] = reg_written;
6015   return true;
6016 }
6017 
6018 // Read all fields from a value type oop and store the values in registers/stack slots
6019 bool MacroAssembler::unpack_value_helper(const GrowableArray<SigEntry>* sig, int& sig_index, VMReg from, VMRegPair* regs_to,
6020                                          int& to_index, RegState reg_state[], int ret_off, int extra_stack_offset) {
6021   Register fromReg = from->is_reg() ? from->as_Register() : noreg;
6022   assert(sig->at(sig_index)._bt == T_VOID, "should be at end delimiter");
6023 
6024   int vt = 1;
6025   bool done = true;
6026   bool mark_done = true;
6027   do {
6028     sig_index--;
6029     BasicType bt = sig->at(sig_index)._bt;
6030     if (bt == T_VALUETYPE) {
6031       vt--;
6032     } else if (bt == T_VOID &&
6033                sig->at(sig_index-1)._bt != T_LONG &&
6034                sig->at(sig_index-1)._bt != T_DOUBLE) {
6035       vt++;
6036     } else if (SigEntry::is_reserved_entry(sig, sig_index)) {
6037       to_index--; // Ignore this
6038     } else {
6039       assert(to_index >= 0, "invalid to_index");
6040       VMRegPair pair_to = regs_to[to_index--];
6041       VMReg to = pair_to.first();
6042 
6043       if (bt == T_VOID) continue;
6044 
6045       int idx = (int)to->value();
6046       if (reg_state[idx] == reg_readonly) {
6047          if (idx != from->value()) {
6048            mark_done = false;
6049          }
6050          done = false;
6051          continue;
6052       } else if (reg_state[idx] == reg_written) {
6053         continue;
6054       } else {
6055         assert(reg_state[idx] == reg_writable, "must be writable");
6056         reg_state[idx] = reg_written;
6057        }
6058 
6059       if (fromReg == noreg) {
6060         int st_off = from->reg2stack() * VMRegImpl::stack_slot_size + extra_stack_offset;
6061         movq(r10, Address(rsp, st_off));
6062         fromReg = r10;
6063       }
6064 
6065       int off = sig->at(sig_index)._offset;
6066       assert(off > 0, "offset in object should be positive");
6067       bool is_oop = (bt == T_OBJECT || bt == T_ARRAY);
6068 
6069       Address fromAddr = Address(fromReg, off);
6070       bool is_signed = (bt != T_CHAR) && (bt != T_BOOLEAN);
6071       if (!to->is_XMMRegister()) {
6072         Register dst = to->is_stack() ? r13 : to->as_Register();
6073         if (is_oop) {
6074           load_heap_oop(dst, fromAddr);
6075         } else {
6076           load_sized_value(dst, fromAddr, type2aelembytes(bt), is_signed);
6077         }
6078         if (to->is_stack()) {
6079           int st_off = to->reg2stack() * VMRegImpl::stack_slot_size + extra_stack_offset;
6080           assert(st_off != ret_off, "overwriting return address at %d", st_off);
6081           movq(Address(rsp, st_off), dst);
6082         }
6083       } else {
6084         if (bt == T_DOUBLE) {
6085           movdbl(to->as_XMMRegister(), fromAddr);
6086         } else {
6087           assert(bt == T_FLOAT, "must be float");
6088           movflt(to->as_XMMRegister(), fromAddr);
6089         }
6090       }
6091     }
6092   } while (vt != 0);
6093   if (mark_done && reg_state[from->value()] != reg_written) {
6094     // This is okay because no one else will write to that slot
6095     reg_state[from->value()] = reg_writable;
6096   }
6097   return done;
6098 }
6099 
6100 class ScalarizedValueArgsStream : public StackObj {
6101   const GrowableArray<SigEntry>* _sig_cc;
6102   int _sig_cc_index;
6103   const VMRegPair* _regs_cc;
6104   int _regs_cc_count;
6105   int _regs_cc_index;
6106   int _vt;
6107   DEBUG_ONLY(bool _finished);
6108 public:
6109   ScalarizedValueArgsStream(const GrowableArray<SigEntry>* sig_cc, int sig_cc_index, VMRegPair* regs_cc, int regs_cc_count, int regs_cc_index) :
6110     _sig_cc(sig_cc), _sig_cc_index(sig_cc_index), _regs_cc(regs_cc), _regs_cc_count(regs_cc_count), _regs_cc_index(regs_cc_index) {
6111     assert(_sig_cc->at(_sig_cc_index)._bt == T_VALUETYPE, "should be at end delimiter");
6112     _vt = 1;
6113     DEBUG_ONLY(_finished = false);
6114   }
6115 
6116   bool next(VMRegPair& pair, BasicType& bt) {
6117     assert(!_finished, "sanity");
6118     do {
6119       _sig_cc_index++;
6120       bt = _sig_cc->at(_sig_cc_index)._bt;
6121       if (bt == T_VALUETYPE) {
6122         _vt++;
6123       } else if (bt == T_VOID &&
6124                  _sig_cc->at(_sig_cc_index-1)._bt != T_LONG &&
6125                  _sig_cc->at(_sig_cc_index-1)._bt != T_DOUBLE) {
6126         _vt--;
6127       } else if (SigEntry::is_reserved_entry(_sig_cc, _sig_cc_index)) {
6128         _regs_cc_index++;
6129       } else {
6130         assert(_regs_cc_index < _regs_cc_count, "must be");
6131         pair = _regs_cc[_regs_cc_index++];
6132         VMReg r1 = pair.first();
6133         VMReg r2 = pair.second();
6134 
6135         if (!r1->is_valid()) {
6136           assert(!r2->is_valid(), "must be invalid");
6137         } else {
6138           return true;
6139         }
6140       }
6141     } while (_vt != 0);
6142 
6143     DEBUG_ONLY(_finished = true);
6144     return false;
6145   }
6146 
6147   int sig_cc_index() {return _sig_cc_index;}
6148   int regs_cc_index() {return _regs_cc_index;}
6149 };
6150 
6151 static void skip_unpacked_fields(const GrowableArray<SigEntry>* sig, int& sig_index, VMRegPair* regs_from, int regs_from_count, int& from_index) {
6152   ScalarizedValueArgsStream stream(sig, sig_index, regs_from, regs_from_count, from_index);
6153   VMRegPair from_pair;
6154   BasicType bt;
6155   while (stream.next(from_pair, bt)) {}
6156   sig_index = stream.sig_cc_index();
6157   from_index = stream.regs_cc_index();
6158 }
6159 
6160 static bool is_reg_in_unpacked_fields(const GrowableArray<SigEntry>* sig, int sig_index, VMReg to, VMRegPair* regs_from, int regs_from_count, int from_index) {
6161   ScalarizedValueArgsStream stream(sig, sig_index, regs_from, regs_from_count, from_index);
6162   VMRegPair from_pair;
6163   BasicType bt;
6164   while (stream.next(from_pair, bt)) {
6165     if (from_pair.first() == to) {
6166       return true;
6167     }
6168   }
6169 
6170   return false;
6171 }
6172 
6173 // Pack fields back into a value type oop
6174 bool MacroAssembler::pack_value_helper(const GrowableArray<SigEntry>* sig, int& sig_index, int vtarg_index,
6175                                        VMReg to, VMRegPair* regs_from, int regs_from_count, int& from_index, RegState reg_state[],
6176                                        int ret_off, int extra_stack_offset) {
6177   assert(sig->at(sig_index)._bt == T_VALUETYPE, "should be at end delimiter");
6178   assert(to->is_valid(), "must be");
6179 
6180   if (reg_state[to->value()] == reg_written) {
6181     skip_unpacked_fields(sig, sig_index, regs_from, regs_from_count, from_index);
6182     return true; // Already written
6183   }
6184 
6185   Register val_array = rax;
6186   Register val_obj_tmp = r11;
6187   Register from_reg_tmp = r10;
6188   Register tmp1 = r14;
6189   Register tmp2 = r13;
6190   Register tmp3 = rbx;
6191   Register val_obj = to->is_stack() ? val_obj_tmp : to->as_Register();
6192 
6193   if (reg_state[to->value()] == reg_readonly) {
6194     if (!is_reg_in_unpacked_fields(sig, sig_index, to, regs_from, regs_from_count, from_index)) {
6195       skip_unpacked_fields(sig, sig_index, regs_from, regs_from_count, from_index);
6196       return false; // Not yet writable
6197     }
6198     val_obj = val_obj_tmp;
6199   }
6200 
6201   int index = arrayOopDesc::base_offset_in_bytes(T_OBJECT) + vtarg_index * type2aelembytes(T_VALUETYPE);
6202   load_heap_oop(val_obj, Address(val_array, index));
6203 
6204   ScalarizedValueArgsStream stream(sig, sig_index, regs_from, regs_from_count, from_index);
6205   VMRegPair from_pair;
6206   BasicType bt;
6207   while (stream.next(from_pair, bt)) {
6208     int off = sig->at(stream.sig_cc_index())._offset;
6209     assert(off > 0, "offset in object should be positive");
6210     bool is_oop = (bt == T_OBJECT || bt == T_ARRAY);
6211     size_t size_in_bytes = is_java_primitive(bt) ? type2aelembytes(bt) : wordSize;
6212 
6213     VMReg from_r1 = from_pair.first();
6214     VMReg from_r2 = from_pair.second();
6215 
6216     // Pack the scalarized field into the value object.
6217     Address dst(val_obj, off);
6218     if (!from_r1->is_XMMRegister()) {
6219       Register from_reg;
6220 
6221       if (from_r1->is_stack()) {
6222         from_reg = from_reg_tmp;
6223         int ld_off = from_r1->reg2stack() * VMRegImpl::stack_slot_size + extra_stack_offset;
6224         load_sized_value(from_reg, Address(rsp, ld_off), size_in_bytes, /* is_signed */ false);
6225       } else {
6226         from_reg = from_r1->as_Register();
6227       }
6228 
6229       if (is_oop) {
6230         DecoratorSet decorators = IN_HEAP | ACCESS_WRITE;
6231         store_heap_oop(dst, from_reg, tmp1, tmp2, tmp3, decorators);
6232       } else {
6233         store_sized_value(dst, from_reg, size_in_bytes);
6234       }
6235     } else {
6236       if (from_r2->is_valid()) {
6237         movdbl(dst, from_r1->as_XMMRegister());
6238       } else {
6239         movflt(dst, from_r1->as_XMMRegister());
6240       }
6241     }
6242     reg_state[from_r1->value()] = reg_writable;
6243   }
6244   sig_index = stream.sig_cc_index();
6245   from_index = stream.regs_cc_index();
6246 
6247   assert(reg_state[to->value()] == reg_writable, "must have already been read");
6248   bool success = move_helper(val_obj->as_VMReg(), to, T_OBJECT, reg_state, ret_off, extra_stack_offset);
6249   assert(success, "to register must be writeable");
6250 
6251   return true;
6252 }
6253 
6254 // Unpack all value type arguments passed as oops
6255 void MacroAssembler::unpack_value_args(Compile* C, bool receiver_only) {
6256   assert(C->has_scalarized_args(), "value type argument scalarization is disabled");
6257   Method* method = C->method()->get_Method();
6258   const GrowableArray<SigEntry>* sig_cc = method->adapter()->get_sig_cc();
6259   assert(sig_cc != NULL, "must have scalarized signature");
6260 
6261   // Get unscalarized calling convention
6262   BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sig_cc->length()); // FIXME - may underflow if we support values with no fields!
6263   int args_passed = 0;
6264   if (!method->is_static()) {
6265     sig_bt[args_passed++] = T_OBJECT;
6266   }
6267   if (!receiver_only) {
6268     for (SignatureStream ss(method->signature()); !ss.at_return_type(); ss.next()) {
6269       BasicType bt = ss.type();
6270       sig_bt[args_passed++] = bt;
6271       if (type2size[bt] == 2) {
6272         sig_bt[args_passed++] = T_VOID;
6273       }
6274     }
6275   } else {
6276     // Only unpack the receiver, all other arguments are already scalarized
6277     InstanceKlass* holder = method->method_holder();
6278     int rec_len = holder->is_value() ? ValueKlass::cast(holder)->extended_sig()->length() : 1;
6279     // Copy scalarized signature but skip receiver, value type delimiters and reserved entries
6280     for (int i = 0; i < sig_cc->length(); i++) {
6281       if (!SigEntry::is_reserved_entry(sig_cc, i)) {
6282         if (SigEntry::skip_value_delimiters(sig_cc, i) && rec_len <= 0) {
6283           sig_bt[args_passed++] = sig_cc->at(i)._bt;
6284         }
6285         rec_len--;
6286       }
6287     }
6288   }
6289   VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, args_passed);
6290   int args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, args_passed, false);
6291 
6292   // Get scalarized calling convention
6293   int args_passed_cc = SigEntry::fill_sig_bt(sig_cc, sig_bt);
6294   VMRegPair* regs_cc = NEW_RESOURCE_ARRAY(VMRegPair, sig_cc->length());
6295   int args_on_stack_cc = SharedRuntime::java_calling_convention(sig_bt, regs_cc, args_passed_cc, false);
6296 
6297   int extra_stack_offset = wordSize; // stack has the returned address
6298   int sp_inc = shuffle_value_args(false, receiver_only, extra_stack_offset, sig_bt, sig_cc,
6299                                   args_passed, args_on_stack, regs,
6300                                   args_passed_cc, args_on_stack_cc, regs_cc);
6301   // Emit code for verified entry and save increment for stack repair on return
6302   verified_entry(C, sp_inc);
6303 }
6304 
6305 static void mark_reg_writable(const VMRegPair* regs, int num_regs, int reg_index, MacroAssembler::RegState* reg_state) {
6306   assert(0 <= reg_index && reg_index < num_regs, "sanity");
6307   VMReg from_reg = regs[reg_index].first();
6308   if (from_reg->is_valid()) {
6309     assert(from_reg->is_stack(), "reserved entries must be stack");
6310     reg_state[from_reg->value()] = MacroAssembler::reg_writable;
6311   }
6312 }
6313 
6314 static void mark_reserved_entries_writable(const GrowableArray<SigEntry>* sig_cc, const VMRegPair* regs, int num_regs, MacroAssembler::RegState* reg_state) {
6315   int reg_index = 0;
6316   for (int sig_index = 0; sig_index <sig_cc->length(); sig_index ++) {
6317     if (SigEntry::is_reserved_entry(sig_cc, sig_index)) {
6318       mark_reg_writable(regs, num_regs, reg_index, reg_state);
6319       reg_index ++;
6320     } else if (SigEntry::skip_value_delimiters(sig_cc, sig_index)) {
6321       reg_index ++;
6322     } else {
6323       int vt = 1;
6324       do {
6325         sig_index++;
6326         BasicType bt = sig_cc->at(sig_index)._bt;
6327         if (bt == T_VALUETYPE) {
6328           vt++;
6329         } else if (bt == T_VOID &&
6330                    sig_cc->at(sig_index-1)._bt != T_LONG &&
6331                    sig_cc->at(sig_index-1)._bt != T_DOUBLE) {
6332           vt--;
6333         } else if (SigEntry::is_reserved_entry(sig_cc, sig_index)) {
6334           mark_reg_writable(regs, num_regs, reg_index, reg_state);
6335           reg_index++;
6336         } else {
6337           reg_index++;
6338         }
6339       } while (vt != 0);
6340     }
6341   }
6342 }
6343 
6344 static MacroAssembler::RegState* init_reg_state(bool is_packing, const GrowableArray<SigEntry>* sig_cc,
6345                                                 VMRegPair* regs, int num_regs, int sp_inc, int max_stack) {
6346   int max_reg = VMRegImpl::stack2reg(max_stack)->value();
6347   MacroAssembler::RegState* reg_state = NEW_RESOURCE_ARRAY(MacroAssembler::RegState, max_reg);
6348 
6349   // Make all writable
6350   for (int i = 0; i < max_reg; ++i) {
6351     reg_state[i] = MacroAssembler::reg_writable;
6352   }
6353   // Set all source registers/stack slots to readonly to prevent accidental overwriting
6354   for (int i = 0; i < num_regs; ++i) {
6355     VMReg reg = regs[i].first();
6356     if (!reg->is_valid()) continue;
6357     if (reg->is_stack()) {
6358       // Update source stack location by adding stack increment
6359       reg = VMRegImpl::stack2reg(reg->reg2stack() + sp_inc/VMRegImpl::stack_slot_size);
6360       regs[i] = reg;
6361     }
6362     assert(reg->value() >= 0 && reg->value() < max_reg, "reg value out of bounds");
6363     reg_state[reg->value()] = MacroAssembler::reg_readonly;
6364   }
6365   if (is_packing) {
6366     // The reserved entries are not used by the packed args, so make them writable
6367     mark_reserved_entries_writable(sig_cc, regs, num_regs, reg_state);
6368   }
6369 
6370   return reg_state;
6371 }
6372 
6373 int MacroAssembler::shuffle_value_args(bool is_packing, bool receiver_only, int extra_stack_offset,
6374                                        BasicType* sig_bt, const GrowableArray<SigEntry>* sig_cc,
6375                                        int args_passed, int args_on_stack, VMRegPair* regs,            // from
6376                                        int args_passed_to, int args_on_stack_to, VMRegPair* regs_to) { // to
6377   // Check if we need to extend the stack for unpacking
6378   int sp_inc = (args_on_stack_to - args_on_stack) * VMRegImpl::stack_slot_size;
6379   if (sp_inc > 0) {
6380     // Save the return address, adjust the stack (make sure it is properly
6381     // 16-byte aligned) and copy the return address to the new top of the stack.
6382     pop(r13);
6383     sp_inc = align_up(sp_inc, StackAlignmentInBytes);
6384     subptr(rsp, sp_inc);
6385     push(r13);
6386   } else {
6387     // The scalarized calling convention needs less stack space than the unscalarized one.
6388     // No need to extend the stack, the caller will take care of these adjustments.
6389     sp_inc = 0;
6390   }
6391 
6392   int ret_off; // make sure we don't overwrite the return address
6393   if (is_packing) {
6394     // For C1 code, the VVEP doesn't have reserved slots, so we store the returned address at
6395     // rsp[0] during shuffling.
6396     ret_off = 0;
6397   } else {
6398     // C2 code ensures that sp_inc is a reserved slot.
6399     ret_off = sp_inc;
6400   }
6401 
6402   int max_stack = MAX2(args_on_stack + sp_inc/VMRegImpl::stack_slot_size, args_on_stack_to);
6403   RegState* reg_state = init_reg_state(is_packing, sig_cc, regs, args_passed, sp_inc, max_stack);
6404 
6405   // Emit code for packing/unpacking value type arguments
6406   // We try multiple times and eventually start spilling to resolve (circular) dependencies
6407   bool done = false;
6408   for (int i = 0; i < 2*args_passed_to && !done; ++i) {
6409     done = true;
6410     bool spill = (i > args_passed_to); // Start spilling?
6411     // Iterate over all arguments (when unpacking, do in reverse)
6412     int step = is_packing ? 1 : -1;
6413     int from_index    = is_packing ? 0 : args_passed      - 1;
6414     int to_index      = is_packing ? 0 : args_passed_to   - 1;
6415     int sig_index     = is_packing ? 0 : sig_cc->length() - 1;
6416     int sig_index_end = is_packing ? sig_cc->length() : -1;
6417     int vtarg_index = 0;
6418     for (; sig_index != sig_index_end; sig_index += step) {
6419       assert(0 <= sig_index && sig_index < sig_cc->length(), "index out of bounds");
6420       if (SigEntry::is_reserved_entry(sig_cc, sig_index)) {
6421         if (is_packing) {
6422           from_index += step;
6423         } else {
6424           to_index += step;
6425         }
6426       } else {
6427         assert(0 <= from_index && from_index < args_passed, "index out of bounds");
6428         assert(0 <= to_index && to_index < args_passed_to, "index out of bounds");
6429         if (spill) {
6430           // This call returns true IFF we should keep trying to spill in this round.
6431           spill = shuffle_value_args_spill(is_packing, sig_cc, sig_index, regs, from_index, args_passed,
6432                                            reg_state, ret_off, extra_stack_offset);
6433         }
6434         BasicType bt = sig_cc->at(sig_index)._bt;
6435         if (SigEntry::skip_value_delimiters(sig_cc, sig_index)) {
6436           VMReg from_reg = regs[from_index].first();
6437           done &= move_helper(from_reg, regs_to[to_index].first(), bt, reg_state, ret_off, extra_stack_offset);
6438           to_index += step;
6439         } else if (is_packing || !receiver_only || (from_index == 0 && bt == T_VOID)) {
6440           if (is_packing) {
6441             VMReg reg_to = regs_to[to_index].first();
6442             done &= pack_value_helper(sig_cc, sig_index, vtarg_index, reg_to, regs, args_passed, from_index,
6443                                       reg_state, ret_off, extra_stack_offset);
6444             vtarg_index ++;
6445             to_index ++;
6446             continue; // from_index already adjusted
6447           } else {
6448             VMReg from_reg = regs[from_index].first();
6449             done &= unpack_value_helper(sig_cc, sig_index, from_reg, regs_to, to_index, reg_state, ret_off, extra_stack_offset);
6450           }
6451         } else {
6452           continue;
6453         }
6454         from_index += step;
6455       }
6456     }
6457   }
6458   guarantee(done, "Could not resolve circular dependency when shuffling value type arguments");
6459   return sp_inc;
6460 }
6461 
6462 bool MacroAssembler::shuffle_value_args_spill(bool is_packing, const GrowableArray<SigEntry>* sig_cc, int sig_cc_index,
6463                                               VMRegPair* regs_from, int from_index, int regs_from_count,
6464                                               RegState* reg_state, int ret_off, int extra_stack_offset) {
6465   VMReg reg;
6466 
6467   if (!is_packing || SigEntry::skip_value_delimiters(sig_cc, sig_cc_index)) {
6468     reg = regs_from[from_index].first();
6469     if (!reg->is_valid() || reg_state[reg->value()] != reg_readonly) {
6470       // Spilling this won't break circles
6471       return true;
6472     }
6473   } else {
6474     ScalarizedValueArgsStream stream(sig_cc, sig_cc_index, regs_from, regs_from_count, from_index);
6475     VMRegPair from_pair;
6476     BasicType bt;
6477     bool found = false;
6478     while (stream.next(from_pair, bt)) {
6479       reg = from_pair.first();
6480       assert(reg->is_valid(), "must be");
6481       if (reg_state[reg->value()] == reg_readonly) {
6482         found = true;
6483         break;
6484       }
6485     }
6486     if (!found) {
6487       // Spilling fields in this value arg won't break circles
6488       return true;
6489     }
6490   }
6491 
6492   // Spill argument to be able to write the source and resolve circular dependencies
6493   VMReg spill_reg = reg->is_XMMRegister() ? xmm8->as_VMReg() : r14->as_VMReg();
6494   if (reg_state[spill_reg->value()] == reg_readonly) {
6495     // We have already spilled (in previous round). The spilled register should be consumed by this round.
6496   } else {
6497     bool res = move_helper(reg, spill_reg, T_DOUBLE, reg_state, ret_off, extra_stack_offset);
6498     assert(res, "Spilling should not fail");
6499     // Set spill_reg as new source and update state
6500     reg = spill_reg;
6501     regs_from[from_index].set1(reg);
6502     reg_state[reg->value()] = reg_readonly;
6503   }
6504 
6505   return false; // Do not spill again in this round
6506 }
6507 
6508 // Restores the stack on return
6509 void MacroAssembler::restore_stack(Compile* C) {
6510   int framesize = C->frame_size_in_bytes();
6511   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
6512   // Remove word for return addr already pushed and RBP
6513   framesize -= 2*wordSize;
6514 
6515   if (C->needs_stack_repair()) {
6516     // Restore rbp and repair rsp by adding the stack increment
6517     movq(rbp, Address(rsp, framesize));
6518     addq(rsp, Address(rsp, C->sp_inc_offset()));
6519   } else {
6520     if (framesize > 0) {
6521       addq(rsp, framesize);
6522     }
6523     pop(rbp);
6524   }
6525 }
6526 
6527 void MacroAssembler::clear_mem(Register base, Register cnt, Register val, XMMRegister xtmp, bool is_large, bool word_copy_only) {
6528   // cnt - number of qwords (8-byte words).
6529   // base - start address, qword aligned.
6530   // is_large - if optimizers know cnt is larger than InitArrayShortSize
6531   assert(base==rdi, "base register must be edi for rep stos");
6532   assert(val==rax,   "tmp register must be eax for rep stos");
6533   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
6534   assert(InitArrayShortSize % BytesPerLong == 0,
6535     "InitArrayShortSize should be the multiple of BytesPerLong");
6536 
6537   Label DONE;
6538 
6539   if (!is_large) {
6540     Label LOOP, LONG;
6541     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
6542     jccb(Assembler::greater, LONG);
6543 
6544     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6545 
6546     decrement(cnt);
6547     jccb(Assembler::negative, DONE); // Zero length
6548 
6549     // Use individual pointer-sized stores for small counts:
6550     BIND(LOOP);
6551     movptr(Address(base, cnt, Address::times_ptr), val);
6552     decrement(cnt);
6553     jccb(Assembler::greaterEqual, LOOP);
6554     jmpb(DONE);
6555 
6556     BIND(LONG);
6557   }
6558 
6559   // Use longer rep-prefixed ops for non-small counts:
6560   if (UseFastStosb && !word_copy_only) {
6561     shlptr(cnt, 3); // convert to number of bytes
6562     rep_stosb();
6563   } else if (UseXMMForObjInit) {
6564     xmm_clear_mem(base, cnt, val, xtmp);
6565   } else {
6566     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6567     rep_stos();
6568   }
6569 
6570   BIND(DONE);
6571 }
6572 
6573 #ifdef COMPILER2
6574 
6575 // IndexOf for constant substrings with size >= 8 chars
6576 // which don't need to be loaded through stack.
6577 void MacroAssembler::string_indexofC8(Register str1, Register str2,
6578                                       Register cnt1, Register cnt2,
6579                                       int int_cnt2,  Register result,
6580                                       XMMRegister vec, Register tmp,
6581                                       int ae) {
6582   ShortBranchVerifier sbv(this);
6583   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
6584   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
6585 
6586   // This method uses the pcmpestri instruction with bound registers
6587   //   inputs:
6588   //     xmm - substring
6589   //     rax - substring length (elements count)
6590   //     mem - scanned string
6591   //     rdx - string length (elements count)
6592   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
6593   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
6594   //   outputs:
6595   //     rcx - matched index in string
6596   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6597   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
6598   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
6599   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
6600   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
6601 
6602   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
6603         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
6604         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
6605 
6606   // Note, inline_string_indexOf() generates checks:
6607   // if (substr.count > string.count) return -1;
6608   // if (substr.count == 0) return 0;
6609   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
6610 
6611   // Load substring.
6612   if (ae == StrIntrinsicNode::UL) {
6613     pmovzxbw(vec, Address(str2, 0));
6614   } else {
6615     movdqu(vec, Address(str2, 0));
6616   }
6617   movl(cnt2, int_cnt2);
6618   movptr(result, str1); // string addr
6619 
6620   if (int_cnt2 > stride) {
6621     jmpb(SCAN_TO_SUBSTR);
6622 
6623     // Reload substr for rescan, this code
6624     // is executed only for large substrings (> 8 chars)
6625     bind(RELOAD_SUBSTR);
6626     if (ae == StrIntrinsicNode::UL) {
6627       pmovzxbw(vec, Address(str2, 0));
6628     } else {
6629       movdqu(vec, Address(str2, 0));
6630     }
6631     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
6632 
6633     bind(RELOAD_STR);
6634     // We came here after the beginning of the substring was
6635     // matched but the rest of it was not so we need to search
6636     // again. Start from the next element after the previous match.
6637 
6638     // cnt2 is number of substring reminding elements and
6639     // cnt1 is number of string reminding elements when cmp failed.
6640     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
6641     subl(cnt1, cnt2);
6642     addl(cnt1, int_cnt2);
6643     movl(cnt2, int_cnt2); // Now restore cnt2
6644 
6645     decrementl(cnt1);     // Shift to next element
6646     cmpl(cnt1, cnt2);
6647     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6648 
6649     addptr(result, (1<<scale1));
6650 
6651   } // (int_cnt2 > 8)
6652 
6653   // Scan string for start of substr in 16-byte vectors
6654   bind(SCAN_TO_SUBSTR);
6655   pcmpestri(vec, Address(result, 0), mode);
6656   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
6657   subl(cnt1, stride);
6658   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
6659   cmpl(cnt1, cnt2);
6660   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6661   addptr(result, 16);
6662   jmpb(SCAN_TO_SUBSTR);
6663 
6664   // Found a potential substr
6665   bind(FOUND_CANDIDATE);
6666   // Matched whole vector if first element matched (tmp(rcx) == 0).
6667   if (int_cnt2 == stride) {
6668     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
6669   } else { // int_cnt2 > 8
6670     jccb(Assembler::overflow, FOUND_SUBSTR);
6671   }
6672   // After pcmpestri tmp(rcx) contains matched element index
6673   // Compute start addr of substr
6674   lea(result, Address(result, tmp, scale1));
6675 
6676   // Make sure string is still long enough
6677   subl(cnt1, tmp);
6678   cmpl(cnt1, cnt2);
6679   if (int_cnt2 == stride) {
6680     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
6681   } else { // int_cnt2 > 8
6682     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
6683   }
6684   // Left less then substring.
6685 
6686   bind(RET_NOT_FOUND);
6687   movl(result, -1);
6688   jmp(EXIT);
6689 
6690   if (int_cnt2 > stride) {
6691     // This code is optimized for the case when whole substring
6692     // is matched if its head is matched.
6693     bind(MATCH_SUBSTR_HEAD);
6694     pcmpestri(vec, Address(result, 0), mode);
6695     // Reload only string if does not match
6696     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
6697 
6698     Label CONT_SCAN_SUBSTR;
6699     // Compare the rest of substring (> 8 chars).
6700     bind(FOUND_SUBSTR);
6701     // First 8 chars are already matched.
6702     negptr(cnt2);
6703     addptr(cnt2, stride);
6704 
6705     bind(SCAN_SUBSTR);
6706     subl(cnt1, stride);
6707     cmpl(cnt2, -stride); // Do not read beyond substring
6708     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
6709     // Back-up strings to avoid reading beyond substring:
6710     // cnt1 = cnt1 - cnt2 + 8
6711     addl(cnt1, cnt2); // cnt2 is negative
6712     addl(cnt1, stride);
6713     movl(cnt2, stride); negptr(cnt2);
6714     bind(CONT_SCAN_SUBSTR);
6715     if (int_cnt2 < (int)G) {
6716       int tail_off1 = int_cnt2<<scale1;
6717       int tail_off2 = int_cnt2<<scale2;
6718       if (ae == StrIntrinsicNode::UL) {
6719         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
6720       } else {
6721         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
6722       }
6723       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
6724     } else {
6725       // calculate index in register to avoid integer overflow (int_cnt2*2)
6726       movl(tmp, int_cnt2);
6727       addptr(tmp, cnt2);
6728       if (ae == StrIntrinsicNode::UL) {
6729         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
6730       } else {
6731         movdqu(vec, Address(str2, tmp, scale2, 0));
6732       }
6733       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
6734     }
6735     // Need to reload strings pointers if not matched whole vector
6736     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
6737     addptr(cnt2, stride);
6738     jcc(Assembler::negative, SCAN_SUBSTR);
6739     // Fall through if found full substring
6740 
6741   } // (int_cnt2 > 8)
6742 
6743   bind(RET_FOUND);
6744   // Found result if we matched full small substring.
6745   // Compute substr offset
6746   subptr(result, str1);
6747   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
6748     shrl(result, 1); // index
6749   }
6750   bind(EXIT);
6751 
6752 } // string_indexofC8
6753 
6754 // Small strings are loaded through stack if they cross page boundary.
6755 void MacroAssembler::string_indexof(Register str1, Register str2,
6756                                     Register cnt1, Register cnt2,
6757                                     int int_cnt2,  Register result,
6758                                     XMMRegister vec, Register tmp,
6759                                     int ae) {
6760   ShortBranchVerifier sbv(this);
6761   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
6762   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
6763 
6764   //
6765   // int_cnt2 is length of small (< 8 chars) constant substring
6766   // or (-1) for non constant substring in which case its length
6767   // is in cnt2 register.
6768   //
6769   // Note, inline_string_indexOf() generates checks:
6770   // if (substr.count > string.count) return -1;
6771   // if (substr.count == 0) return 0;
6772   //
6773   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
6774   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
6775   // This method uses the pcmpestri instruction with bound registers
6776   //   inputs:
6777   //     xmm - substring
6778   //     rax - substring length (elements count)
6779   //     mem - scanned string
6780   //     rdx - string length (elements count)
6781   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
6782   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
6783   //   outputs:
6784   //     rcx - matched index in string
6785   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6786   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
6787   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
6788   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
6789 
6790   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
6791         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
6792         FOUND_CANDIDATE;
6793 
6794   { //========================================================
6795     // We don't know where these strings are located
6796     // and we can't read beyond them. Load them through stack.
6797     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
6798 
6799     movptr(tmp, rsp); // save old SP
6800 
6801     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
6802       if (int_cnt2 == (1>>scale2)) { // One byte
6803         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
6804         load_unsigned_byte(result, Address(str2, 0));
6805         movdl(vec, result); // move 32 bits
6806       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
6807         // Not enough header space in 32-bit VM: 12+3 = 15.
6808         movl(result, Address(str2, -1));
6809         shrl(result, 8);
6810         movdl(vec, result); // move 32 bits
6811       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
6812         load_unsigned_short(result, Address(str2, 0));
6813         movdl(vec, result); // move 32 bits
6814       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
6815         movdl(vec, Address(str2, 0)); // move 32 bits
6816       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
6817         movq(vec, Address(str2, 0));  // move 64 bits
6818       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
6819         // Array header size is 12 bytes in 32-bit VM
6820         // + 6 bytes for 3 chars == 18 bytes,
6821         // enough space to load vec and shift.
6822         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
6823         if (ae == StrIntrinsicNode::UL) {
6824           int tail_off = int_cnt2-8;
6825           pmovzxbw(vec, Address(str2, tail_off));
6826           psrldq(vec, -2*tail_off);
6827         }
6828         else {
6829           int tail_off = int_cnt2*(1<<scale2);
6830           movdqu(vec, Address(str2, tail_off-16));
6831           psrldq(vec, 16-tail_off);
6832         }
6833       }
6834     } else { // not constant substring
6835       cmpl(cnt2, stride);
6836       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
6837 
6838       // We can read beyond string if srt+16 does not cross page boundary
6839       // since heaps are aligned and mapped by pages.
6840       assert(os::vm_page_size() < (int)G, "default page should be small");
6841       movl(result, str2); // We need only low 32 bits
6842       andl(result, (os::vm_page_size()-1));
6843       cmpl(result, (os::vm_page_size()-16));
6844       jccb(Assembler::belowEqual, CHECK_STR);
6845 
6846       // Move small strings to stack to allow load 16 bytes into vec.
6847       subptr(rsp, 16);
6848       int stk_offset = wordSize-(1<<scale2);
6849       push(cnt2);
6850 
6851       bind(COPY_SUBSTR);
6852       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
6853         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
6854         movb(Address(rsp, cnt2, scale2, stk_offset), result);
6855       } else if (ae == StrIntrinsicNode::UU) {
6856         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
6857         movw(Address(rsp, cnt2, scale2, stk_offset), result);
6858       }
6859       decrement(cnt2);
6860       jccb(Assembler::notZero, COPY_SUBSTR);
6861 
6862       pop(cnt2);
6863       movptr(str2, rsp);  // New substring address
6864     } // non constant
6865 
6866     bind(CHECK_STR);
6867     cmpl(cnt1, stride);
6868     jccb(Assembler::aboveEqual, BIG_STRINGS);
6869 
6870     // Check cross page boundary.
6871     movl(result, str1); // We need only low 32 bits
6872     andl(result, (os::vm_page_size()-1));
6873     cmpl(result, (os::vm_page_size()-16));
6874     jccb(Assembler::belowEqual, BIG_STRINGS);
6875 
6876     subptr(rsp, 16);
6877     int stk_offset = -(1<<scale1);
6878     if (int_cnt2 < 0) { // not constant
6879       push(cnt2);
6880       stk_offset += wordSize;
6881     }
6882     movl(cnt2, cnt1);
6883 
6884     bind(COPY_STR);
6885     if (ae == StrIntrinsicNode::LL) {
6886       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
6887       movb(Address(rsp, cnt2, scale1, stk_offset), result);
6888     } else {
6889       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
6890       movw(Address(rsp, cnt2, scale1, stk_offset), result);
6891     }
6892     decrement(cnt2);
6893     jccb(Assembler::notZero, COPY_STR);
6894 
6895     if (int_cnt2 < 0) { // not constant
6896       pop(cnt2);
6897     }
6898     movptr(str1, rsp);  // New string address
6899 
6900     bind(BIG_STRINGS);
6901     // Load substring.
6902     if (int_cnt2 < 0) { // -1
6903       if (ae == StrIntrinsicNode::UL) {
6904         pmovzxbw(vec, Address(str2, 0));
6905       } else {
6906         movdqu(vec, Address(str2, 0));
6907       }
6908       push(cnt2);       // substr count
6909       push(str2);       // substr addr
6910       push(str1);       // string addr
6911     } else {
6912       // Small (< 8 chars) constant substrings are loaded already.
6913       movl(cnt2, int_cnt2);
6914     }
6915     push(tmp);  // original SP
6916 
6917   } // Finished loading
6918 
6919   //========================================================
6920   // Start search
6921   //
6922 
6923   movptr(result, str1); // string addr
6924 
6925   if (int_cnt2  < 0) {  // Only for non constant substring
6926     jmpb(SCAN_TO_SUBSTR);
6927 
6928     // SP saved at sp+0
6929     // String saved at sp+1*wordSize
6930     // Substr saved at sp+2*wordSize
6931     // Substr count saved at sp+3*wordSize
6932 
6933     // Reload substr for rescan, this code
6934     // is executed only for large substrings (> 8 chars)
6935     bind(RELOAD_SUBSTR);
6936     movptr(str2, Address(rsp, 2*wordSize));
6937     movl(cnt2, Address(rsp, 3*wordSize));
6938     if (ae == StrIntrinsicNode::UL) {
6939       pmovzxbw(vec, Address(str2, 0));
6940     } else {
6941       movdqu(vec, Address(str2, 0));
6942     }
6943     // We came here after the beginning of the substring was
6944     // matched but the rest of it was not so we need to search
6945     // again. Start from the next element after the previous match.
6946     subptr(str1, result); // Restore counter
6947     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
6948       shrl(str1, 1);
6949     }
6950     addl(cnt1, str1);
6951     decrementl(cnt1);   // Shift to next element
6952     cmpl(cnt1, cnt2);
6953     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6954 
6955     addptr(result, (1<<scale1));
6956   } // non constant
6957 
6958   // Scan string for start of substr in 16-byte vectors
6959   bind(SCAN_TO_SUBSTR);
6960   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6961   pcmpestri(vec, Address(result, 0), mode);
6962   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
6963   subl(cnt1, stride);
6964   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
6965   cmpl(cnt1, cnt2);
6966   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6967   addptr(result, 16);
6968 
6969   bind(ADJUST_STR);
6970   cmpl(cnt1, stride); // Do not read beyond string
6971   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
6972   // Back-up string to avoid reading beyond string.
6973   lea(result, Address(result, cnt1, scale1, -16));
6974   movl(cnt1, stride);
6975   jmpb(SCAN_TO_SUBSTR);
6976 
6977   // Found a potential substr
6978   bind(FOUND_CANDIDATE);
6979   // After pcmpestri tmp(rcx) contains matched element index
6980 
6981   // Make sure string is still long enough
6982   subl(cnt1, tmp);
6983   cmpl(cnt1, cnt2);
6984   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
6985   // Left less then substring.
6986 
6987   bind(RET_NOT_FOUND);
6988   movl(result, -1);
6989   jmp(CLEANUP);
6990 
6991   bind(FOUND_SUBSTR);
6992   // Compute start addr of substr
6993   lea(result, Address(result, tmp, scale1));
6994   if (int_cnt2 > 0) { // Constant substring
6995     // Repeat search for small substring (< 8 chars)
6996     // from new point without reloading substring.
6997     // Have to check that we don't read beyond string.
6998     cmpl(tmp, stride-int_cnt2);
6999     jccb(Assembler::greater, ADJUST_STR);
7000     // Fall through if matched whole substring.
7001   } else { // non constant
7002     assert(int_cnt2 == -1, "should be != 0");
7003 
7004     addl(tmp, cnt2);
7005     // Found result if we matched whole substring.
7006     cmpl(tmp, stride);
7007     jcc(Assembler::lessEqual, RET_FOUND);
7008 
7009     // Repeat search for small substring (<= 8 chars)
7010     // from new point 'str1' without reloading substring.
7011     cmpl(cnt2, stride);
7012     // Have to check that we don't read beyond string.
7013     jccb(Assembler::lessEqual, ADJUST_STR);
7014 
7015     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7016     // Compare the rest of substring (> 8 chars).
7017     movptr(str1, result);
7018 
7019     cmpl(tmp, cnt2);
7020     // First 8 chars are already matched.
7021     jccb(Assembler::equal, CHECK_NEXT);
7022 
7023     bind(SCAN_SUBSTR);
7024     pcmpestri(vec, Address(str1, 0), mode);
7025     // Need to reload strings pointers if not matched whole vector
7026     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7027 
7028     bind(CHECK_NEXT);
7029     subl(cnt2, stride);
7030     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7031     addptr(str1, 16);
7032     if (ae == StrIntrinsicNode::UL) {
7033       addptr(str2, 8);
7034     } else {
7035       addptr(str2, 16);
7036     }
7037     subl(cnt1, stride);
7038     cmpl(cnt2, stride); // Do not read beyond substring
7039     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7040     // Back-up strings to avoid reading beyond substring.
7041 
7042     if (ae == StrIntrinsicNode::UL) {
7043       lea(str2, Address(str2, cnt2, scale2, -8));
7044       lea(str1, Address(str1, cnt2, scale1, -16));
7045     } else {
7046       lea(str2, Address(str2, cnt2, scale2, -16));
7047       lea(str1, Address(str1, cnt2, scale1, -16));
7048     }
7049     subl(cnt1, cnt2);
7050     movl(cnt2, stride);
7051     addl(cnt1, stride);
7052     bind(CONT_SCAN_SUBSTR);
7053     if (ae == StrIntrinsicNode::UL) {
7054       pmovzxbw(vec, Address(str2, 0));
7055     } else {
7056       movdqu(vec, Address(str2, 0));
7057     }
7058     jmp(SCAN_SUBSTR);
7059 
7060     bind(RET_FOUND_LONG);
7061     movptr(str1, Address(rsp, wordSize));
7062   } // non constant
7063 
7064   bind(RET_FOUND);
7065   // Compute substr offset
7066   subptr(result, str1);
7067   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7068     shrl(result, 1); // index
7069   }
7070   bind(CLEANUP);
7071   pop(rsp); // restore SP
7072 
7073 } // string_indexof
7074 
7075 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7076                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7077   ShortBranchVerifier sbv(this);
7078   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7079 
7080   int stride = 8;
7081 
7082   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7083         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7084         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7085         FOUND_SEQ_CHAR, DONE_LABEL;
7086 
7087   movptr(result, str1);
7088   if (UseAVX >= 2) {
7089     cmpl(cnt1, stride);
7090     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7091     cmpl(cnt1, 2*stride);
7092     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7093     movdl(vec1, ch);
7094     vpbroadcastw(vec1, vec1, Assembler::AVX_256bit);
7095     vpxor(vec2, vec2);
7096     movl(tmp, cnt1);
7097     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7098     andl(cnt1,0x0000000F);  //tail count (in chars)
7099 
7100     bind(SCAN_TO_16_CHAR_LOOP);
7101     vmovdqu(vec3, Address(result, 0));
7102     vpcmpeqw(vec3, vec3, vec1, 1);
7103     vptest(vec2, vec3);
7104     jcc(Assembler::carryClear, FOUND_CHAR);
7105     addptr(result, 32);
7106     subl(tmp, 2*stride);
7107     jcc(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7108     jmp(SCAN_TO_8_CHAR);
7109     bind(SCAN_TO_8_CHAR_INIT);
7110     movdl(vec1, ch);
7111     pshuflw(vec1, vec1, 0x00);
7112     pshufd(vec1, vec1, 0);
7113     pxor(vec2, vec2);
7114   }
7115   bind(SCAN_TO_8_CHAR);
7116   cmpl(cnt1, stride);
7117   if (UseAVX >= 2) {
7118     jcc(Assembler::less, SCAN_TO_CHAR);
7119   } else {
7120     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7121     movdl(vec1, ch);
7122     pshuflw(vec1, vec1, 0x00);
7123     pshufd(vec1, vec1, 0);
7124     pxor(vec2, vec2);
7125   }
7126   movl(tmp, cnt1);
7127   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7128   andl(cnt1,0x00000007);  //tail count (in chars)
7129 
7130   bind(SCAN_TO_8_CHAR_LOOP);
7131   movdqu(vec3, Address(result, 0));
7132   pcmpeqw(vec3, vec1);
7133   ptest(vec2, vec3);
7134   jcc(Assembler::carryClear, FOUND_CHAR);
7135   addptr(result, 16);
7136   subl(tmp, stride);
7137   jcc(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7138   bind(SCAN_TO_CHAR);
7139   testl(cnt1, cnt1);
7140   jcc(Assembler::zero, RET_NOT_FOUND);
7141   bind(SCAN_TO_CHAR_LOOP);
7142   load_unsigned_short(tmp, Address(result, 0));
7143   cmpl(ch, tmp);
7144   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7145   addptr(result, 2);
7146   subl(cnt1, 1);
7147   jccb(Assembler::zero, RET_NOT_FOUND);
7148   jmp(SCAN_TO_CHAR_LOOP);
7149 
7150   bind(RET_NOT_FOUND);
7151   movl(result, -1);
7152   jmpb(DONE_LABEL);
7153 
7154   bind(FOUND_CHAR);
7155   if (UseAVX >= 2) {
7156     vpmovmskb(tmp, vec3);
7157   } else {
7158     pmovmskb(tmp, vec3);
7159   }
7160   bsfl(ch, tmp);
7161   addl(result, ch);
7162 
7163   bind(FOUND_SEQ_CHAR);
7164   subptr(result, str1);
7165   shrl(result, 1);
7166 
7167   bind(DONE_LABEL);
7168 } // string_indexof_char
7169 
7170 // helper function for string_compare
7171 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7172                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7173                                         Address::ScaleFactor scale2, Register index, int ae) {
7174   if (ae == StrIntrinsicNode::LL) {
7175     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7176     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7177   } else if (ae == StrIntrinsicNode::UU) {
7178     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7179     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7180   } else {
7181     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7182     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7183   }
7184 }
7185 
7186 // Compare strings, used for char[] and byte[].
7187 void MacroAssembler::string_compare(Register str1, Register str2,
7188                                     Register cnt1, Register cnt2, Register result,
7189                                     XMMRegister vec1, int ae) {
7190   ShortBranchVerifier sbv(this);
7191   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7192   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7193   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7194   int stride2x2 = 0x40;
7195   Address::ScaleFactor scale = Address::no_scale;
7196   Address::ScaleFactor scale1 = Address::no_scale;
7197   Address::ScaleFactor scale2 = Address::no_scale;
7198 
7199   if (ae != StrIntrinsicNode::LL) {
7200     stride2x2 = 0x20;
7201   }
7202 
7203   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7204     shrl(cnt2, 1);
7205   }
7206   // Compute the minimum of the string lengths and the
7207   // difference of the string lengths (stack).
7208   // Do the conditional move stuff
7209   movl(result, cnt1);
7210   subl(cnt1, cnt2);
7211   push(cnt1);
7212   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7213 
7214   // Is the minimum length zero?
7215   testl(cnt2, cnt2);
7216   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7217   if (ae == StrIntrinsicNode::LL) {
7218     // Load first bytes
7219     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7220     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7221   } else if (ae == StrIntrinsicNode::UU) {
7222     // Load first characters
7223     load_unsigned_short(result, Address(str1, 0));
7224     load_unsigned_short(cnt1, Address(str2, 0));
7225   } else {
7226     load_unsigned_byte(result, Address(str1, 0));
7227     load_unsigned_short(cnt1, Address(str2, 0));
7228   }
7229   subl(result, cnt1);
7230   jcc(Assembler::notZero,  POP_LABEL);
7231 
7232   if (ae == StrIntrinsicNode::UU) {
7233     // Divide length by 2 to get number of chars
7234     shrl(cnt2, 1);
7235   }
7236   cmpl(cnt2, 1);
7237   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7238 
7239   // Check if the strings start at the same location and setup scale and stride
7240   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7241     cmpptr(str1, str2);
7242     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7243     if (ae == StrIntrinsicNode::LL) {
7244       scale = Address::times_1;
7245       stride = 16;
7246     } else {
7247       scale = Address::times_2;
7248       stride = 8;
7249     }
7250   } else {
7251     scale1 = Address::times_1;
7252     scale2 = Address::times_2;
7253     // scale not used
7254     stride = 8;
7255   }
7256 
7257   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7258     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7259     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7260     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7261     Label COMPARE_TAIL_LONG;
7262     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7263 
7264     int pcmpmask = 0x19;
7265     if (ae == StrIntrinsicNode::LL) {
7266       pcmpmask &= ~0x01;
7267     }
7268 
7269     // Setup to compare 16-chars (32-bytes) vectors,
7270     // start from first character again because it has aligned address.
7271     if (ae == StrIntrinsicNode::LL) {
7272       stride2 = 32;
7273     } else {
7274       stride2 = 16;
7275     }
7276     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7277       adr_stride = stride << scale;
7278     } else {
7279       adr_stride1 = 8;  //stride << scale1;
7280       adr_stride2 = 16; //stride << scale2;
7281     }
7282 
7283     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7284     // rax and rdx are used by pcmpestri as elements counters
7285     movl(result, cnt2);
7286     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7287     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7288 
7289     // fast path : compare first 2 8-char vectors.
7290     bind(COMPARE_16_CHARS);
7291     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7292       movdqu(vec1, Address(str1, 0));
7293     } else {
7294       pmovzxbw(vec1, Address(str1, 0));
7295     }
7296     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7297     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7298 
7299     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7300       movdqu(vec1, Address(str1, adr_stride));
7301       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7302     } else {
7303       pmovzxbw(vec1, Address(str1, adr_stride1));
7304       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7305     }
7306     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7307     addl(cnt1, stride);
7308 
7309     // Compare the characters at index in cnt1
7310     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
7311     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7312     subl(result, cnt2);
7313     jmp(POP_LABEL);
7314 
7315     // Setup the registers to start vector comparison loop
7316     bind(COMPARE_WIDE_VECTORS);
7317     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7318       lea(str1, Address(str1, result, scale));
7319       lea(str2, Address(str2, result, scale));
7320     } else {
7321       lea(str1, Address(str1, result, scale1));
7322       lea(str2, Address(str2, result, scale2));
7323     }
7324     subl(result, stride2);
7325     subl(cnt2, stride2);
7326     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
7327     negptr(result);
7328 
7329     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7330     bind(COMPARE_WIDE_VECTORS_LOOP);
7331 
7332 #ifdef _LP64
7333     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7334       cmpl(cnt2, stride2x2);
7335       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7336       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
7337       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
7338 
7339       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7340       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7341         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
7342         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7343       } else {
7344         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
7345         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7346       }
7347       kortestql(k7, k7);
7348       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
7349       addptr(result, stride2x2);  // update since we already compared at this addr
7350       subl(cnt2, stride2x2);      // and sub the size too
7351       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7352 
7353       vpxor(vec1, vec1);
7354       jmpb(COMPARE_WIDE_TAIL);
7355     }//if (VM_Version::supports_avx512vlbw())
7356 #endif // _LP64
7357 
7358 
7359     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7360     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7361       vmovdqu(vec1, Address(str1, result, scale));
7362       vpxor(vec1, Address(str2, result, scale));
7363     } else {
7364       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
7365       vpxor(vec1, Address(str2, result, scale2));
7366     }
7367     vptest(vec1, vec1);
7368     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
7369     addptr(result, stride2);
7370     subl(cnt2, stride2);
7371     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
7372     // clean upper bits of YMM registers
7373     vpxor(vec1, vec1);
7374 
7375     // compare wide vectors tail
7376     bind(COMPARE_WIDE_TAIL);
7377     testptr(result, result);
7378     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7379 
7380     movl(result, stride2);
7381     movl(cnt2, result);
7382     negptr(result);
7383     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7384 
7385     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
7386     bind(VECTOR_NOT_EQUAL);
7387     // clean upper bits of YMM registers
7388     vpxor(vec1, vec1);
7389     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7390       lea(str1, Address(str1, result, scale));
7391       lea(str2, Address(str2, result, scale));
7392     } else {
7393       lea(str1, Address(str1, result, scale1));
7394       lea(str2, Address(str2, result, scale2));
7395     }
7396     jmp(COMPARE_16_CHARS);
7397 
7398     // Compare tail chars, length between 1 to 15 chars
7399     bind(COMPARE_TAIL_LONG);
7400     movl(cnt2, result);
7401     cmpl(cnt2, stride);
7402     jcc(Assembler::less, COMPARE_SMALL_STR);
7403 
7404     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7405       movdqu(vec1, Address(str1, 0));
7406     } else {
7407       pmovzxbw(vec1, Address(str1, 0));
7408     }
7409     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7410     jcc(Assembler::below, COMPARE_INDEX_CHAR);
7411     subptr(cnt2, stride);
7412     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7413     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7414       lea(str1, Address(str1, result, scale));
7415       lea(str2, Address(str2, result, scale));
7416     } else {
7417       lea(str1, Address(str1, result, scale1));
7418       lea(str2, Address(str2, result, scale2));
7419     }
7420     negptr(cnt2);
7421     jmpb(WHILE_HEAD_LABEL);
7422 
7423     bind(COMPARE_SMALL_STR);
7424   } else if (UseSSE42Intrinsics) {
7425     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
7426     int pcmpmask = 0x19;
7427     // Setup to compare 8-char (16-byte) vectors,
7428     // start from first character again because it has aligned address.
7429     movl(result, cnt2);
7430     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
7431     if (ae == StrIntrinsicNode::LL) {
7432       pcmpmask &= ~0x01;
7433     }
7434     jcc(Assembler::zero, COMPARE_TAIL);
7435     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7436       lea(str1, Address(str1, result, scale));
7437       lea(str2, Address(str2, result, scale));
7438     } else {
7439       lea(str1, Address(str1, result, scale1));
7440       lea(str2, Address(str2, result, scale2));
7441     }
7442     negptr(result);
7443 
7444     // pcmpestri
7445     //   inputs:
7446     //     vec1- substring
7447     //     rax - negative string length (elements count)
7448     //     mem - scanned string
7449     //     rdx - string length (elements count)
7450     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
7451     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
7452     //   outputs:
7453     //     rcx - first mismatched element index
7454     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7455 
7456     bind(COMPARE_WIDE_VECTORS);
7457     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7458       movdqu(vec1, Address(str1, result, scale));
7459       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7460     } else {
7461       pmovzxbw(vec1, Address(str1, result, scale1));
7462       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7463     }
7464     // After pcmpestri cnt1(rcx) contains mismatched element index
7465 
7466     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
7467     addptr(result, stride);
7468     subptr(cnt2, stride);
7469     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
7470 
7471     // compare wide vectors tail
7472     testptr(result, result);
7473     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7474 
7475     movl(cnt2, stride);
7476     movl(result, stride);
7477     negptr(result);
7478     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7479       movdqu(vec1, Address(str1, result, scale));
7480       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7481     } else {
7482       pmovzxbw(vec1, Address(str1, result, scale1));
7483       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7484     }
7485     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
7486 
7487     // Mismatched characters in the vectors
7488     bind(VECTOR_NOT_EQUAL);
7489     addptr(cnt1, result);
7490     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7491     subl(result, cnt2);
7492     jmpb(POP_LABEL);
7493 
7494     bind(COMPARE_TAIL); // limit is zero
7495     movl(cnt2, result);
7496     // Fallthru to tail compare
7497   }
7498   // Shift str2 and str1 to the end of the arrays, negate min
7499   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7500     lea(str1, Address(str1, cnt2, scale));
7501     lea(str2, Address(str2, cnt2, scale));
7502   } else {
7503     lea(str1, Address(str1, cnt2, scale1));
7504     lea(str2, Address(str2, cnt2, scale2));
7505   }
7506   decrementl(cnt2);  // first character was compared already
7507   negptr(cnt2);
7508 
7509   // Compare the rest of the elements
7510   bind(WHILE_HEAD_LABEL);
7511   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
7512   subl(result, cnt1);
7513   jccb(Assembler::notZero, POP_LABEL);
7514   increment(cnt2);
7515   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
7516 
7517   // Strings are equal up to min length.  Return the length difference.
7518   bind(LENGTH_DIFF_LABEL);
7519   pop(result);
7520   if (ae == StrIntrinsicNode::UU) {
7521     // Divide diff by 2 to get number of chars
7522     sarl(result, 1);
7523   }
7524   jmpb(DONE_LABEL);
7525 
7526 #ifdef _LP64
7527   if (VM_Version::supports_avx512vlbw()) {
7528 
7529     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
7530 
7531     kmovql(cnt1, k7);
7532     notq(cnt1);
7533     bsfq(cnt2, cnt1);
7534     if (ae != StrIntrinsicNode::LL) {
7535       // Divide diff by 2 to get number of chars
7536       sarl(cnt2, 1);
7537     }
7538     addq(result, cnt2);
7539     if (ae == StrIntrinsicNode::LL) {
7540       load_unsigned_byte(cnt1, Address(str2, result));
7541       load_unsigned_byte(result, Address(str1, result));
7542     } else if (ae == StrIntrinsicNode::UU) {
7543       load_unsigned_short(cnt1, Address(str2, result, scale));
7544       load_unsigned_short(result, Address(str1, result, scale));
7545     } else {
7546       load_unsigned_short(cnt1, Address(str2, result, scale2));
7547       load_unsigned_byte(result, Address(str1, result, scale1));
7548     }
7549     subl(result, cnt1);
7550     jmpb(POP_LABEL);
7551   }//if (VM_Version::supports_avx512vlbw())
7552 #endif // _LP64
7553 
7554   // Discard the stored length difference
7555   bind(POP_LABEL);
7556   pop(cnt1);
7557 
7558   // That's it
7559   bind(DONE_LABEL);
7560   if(ae == StrIntrinsicNode::UL) {
7561     negl(result);
7562   }
7563 
7564 }
7565 
7566 // Search for Non-ASCII character (Negative byte value) in a byte array,
7567 // return true if it has any and false otherwise.
7568 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
7569 //   @HotSpotIntrinsicCandidate
7570 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
7571 //     for (int i = off; i < off + len; i++) {
7572 //       if (ba[i] < 0) {
7573 //         return true;
7574 //       }
7575 //     }
7576 //     return false;
7577 //   }
7578 void MacroAssembler::has_negatives(Register ary1, Register len,
7579   Register result, Register tmp1,
7580   XMMRegister vec1, XMMRegister vec2) {
7581   // rsi: byte array
7582   // rcx: len
7583   // rax: result
7584   ShortBranchVerifier sbv(this);
7585   assert_different_registers(ary1, len, result, tmp1);
7586   assert_different_registers(vec1, vec2);
7587   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
7588 
7589   // len == 0
7590   testl(len, len);
7591   jcc(Assembler::zero, FALSE_LABEL);
7592 
7593   if ((UseAVX > 2) && // AVX512
7594     VM_Version::supports_avx512vlbw() &&
7595     VM_Version::supports_bmi2()) {
7596 
7597     Label test_64_loop, test_tail;
7598     Register tmp3_aliased = len;
7599 
7600     movl(tmp1, len);
7601     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
7602 
7603     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
7604     andl(len, ~(64 - 1));    // vector count (in chars)
7605     jccb(Assembler::zero, test_tail);
7606 
7607     lea(ary1, Address(ary1, len, Address::times_1));
7608     negptr(len);
7609 
7610     bind(test_64_loop);
7611     // Check whether our 64 elements of size byte contain negatives
7612     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
7613     kortestql(k2, k2);
7614     jcc(Assembler::notZero, TRUE_LABEL);
7615 
7616     addptr(len, 64);
7617     jccb(Assembler::notZero, test_64_loop);
7618 
7619 
7620     bind(test_tail);
7621     // bail out when there is nothing to be done
7622     testl(tmp1, -1);
7623     jcc(Assembler::zero, FALSE_LABEL);
7624 
7625     // ~(~0 << len) applied up to two times (for 32-bit scenario)
7626 #ifdef _LP64
7627     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
7628     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
7629     notq(tmp3_aliased);
7630     kmovql(k3, tmp3_aliased);
7631 #else
7632     Label k_init;
7633     jmp(k_init);
7634 
7635     // We could not read 64-bits from a general purpose register thus we move
7636     // data required to compose 64 1's to the instruction stream
7637     // We emit 64 byte wide series of elements from 0..63 which later on would
7638     // be used as a compare targets with tail count contained in tmp1 register.
7639     // Result would be a k register having tmp1 consecutive number or 1
7640     // counting from least significant bit.
7641     address tmp = pc();
7642     emit_int64(0x0706050403020100);
7643     emit_int64(0x0F0E0D0C0B0A0908);
7644     emit_int64(0x1716151413121110);
7645     emit_int64(0x1F1E1D1C1B1A1918);
7646     emit_int64(0x2726252423222120);
7647     emit_int64(0x2F2E2D2C2B2A2928);
7648     emit_int64(0x3736353433323130);
7649     emit_int64(0x3F3E3D3C3B3A3938);
7650 
7651     bind(k_init);
7652     lea(len, InternalAddress(tmp));
7653     // create mask to test for negative byte inside a vector
7654     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
7655     evpcmpgtb(k3, vec1, Address(len, 0), Assembler::AVX_512bit);
7656 
7657 #endif
7658     evpcmpgtb(k2, k3, vec2, Address(ary1, 0), Assembler::AVX_512bit);
7659     ktestq(k2, k3);
7660     jcc(Assembler::notZero, TRUE_LABEL);
7661 
7662     jmp(FALSE_LABEL);
7663   } else {
7664     movl(result, len); // copy
7665 
7666     if (UseAVX == 2 && UseSSE >= 2) {
7667       // With AVX2, use 32-byte vector compare
7668       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7669 
7670       // Compare 32-byte vectors
7671       andl(result, 0x0000001f);  //   tail count (in bytes)
7672       andl(len, 0xffffffe0);   // vector count (in bytes)
7673       jccb(Assembler::zero, COMPARE_TAIL);
7674 
7675       lea(ary1, Address(ary1, len, Address::times_1));
7676       negptr(len);
7677 
7678       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
7679       movdl(vec2, tmp1);
7680       vpbroadcastd(vec2, vec2, Assembler::AVX_256bit);
7681 
7682       bind(COMPARE_WIDE_VECTORS);
7683       vmovdqu(vec1, Address(ary1, len, Address::times_1));
7684       vptest(vec1, vec2);
7685       jccb(Assembler::notZero, TRUE_LABEL);
7686       addptr(len, 32);
7687       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7688 
7689       testl(result, result);
7690       jccb(Assembler::zero, FALSE_LABEL);
7691 
7692       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
7693       vptest(vec1, vec2);
7694       jccb(Assembler::notZero, TRUE_LABEL);
7695       jmpb(FALSE_LABEL);
7696 
7697       bind(COMPARE_TAIL); // len is zero
7698       movl(len, result);
7699       // Fallthru to tail compare
7700     } else if (UseSSE42Intrinsics) {
7701       // With SSE4.2, use double quad vector compare
7702       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7703 
7704       // Compare 16-byte vectors
7705       andl(result, 0x0000000f);  //   tail count (in bytes)
7706       andl(len, 0xfffffff0);   // vector count (in bytes)
7707       jcc(Assembler::zero, COMPARE_TAIL);
7708 
7709       lea(ary1, Address(ary1, len, Address::times_1));
7710       negptr(len);
7711 
7712       movl(tmp1, 0x80808080);
7713       movdl(vec2, tmp1);
7714       pshufd(vec2, vec2, 0);
7715 
7716       bind(COMPARE_WIDE_VECTORS);
7717       movdqu(vec1, Address(ary1, len, Address::times_1));
7718       ptest(vec1, vec2);
7719       jcc(Assembler::notZero, TRUE_LABEL);
7720       addptr(len, 16);
7721       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7722 
7723       testl(result, result);
7724       jcc(Assembler::zero, FALSE_LABEL);
7725 
7726       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
7727       ptest(vec1, vec2);
7728       jccb(Assembler::notZero, TRUE_LABEL);
7729       jmpb(FALSE_LABEL);
7730 
7731       bind(COMPARE_TAIL); // len is zero
7732       movl(len, result);
7733       // Fallthru to tail compare
7734     }
7735   }
7736   // Compare 4-byte vectors
7737   andl(len, 0xfffffffc); // vector count (in bytes)
7738   jccb(Assembler::zero, COMPARE_CHAR);
7739 
7740   lea(ary1, Address(ary1, len, Address::times_1));
7741   negptr(len);
7742 
7743   bind(COMPARE_VECTORS);
7744   movl(tmp1, Address(ary1, len, Address::times_1));
7745   andl(tmp1, 0x80808080);
7746   jccb(Assembler::notZero, TRUE_LABEL);
7747   addptr(len, 4);
7748   jcc(Assembler::notZero, COMPARE_VECTORS);
7749 
7750   // Compare trailing char (final 2 bytes), if any
7751   bind(COMPARE_CHAR);
7752   testl(result, 0x2);   // tail  char
7753   jccb(Assembler::zero, COMPARE_BYTE);
7754   load_unsigned_short(tmp1, Address(ary1, 0));
7755   andl(tmp1, 0x00008080);
7756   jccb(Assembler::notZero, TRUE_LABEL);
7757   subptr(result, 2);
7758   lea(ary1, Address(ary1, 2));
7759 
7760   bind(COMPARE_BYTE);
7761   testl(result, 0x1);   // tail  byte
7762   jccb(Assembler::zero, FALSE_LABEL);
7763   load_unsigned_byte(tmp1, Address(ary1, 0));
7764   andl(tmp1, 0x00000080);
7765   jccb(Assembler::notEqual, TRUE_LABEL);
7766   jmpb(FALSE_LABEL);
7767 
7768   bind(TRUE_LABEL);
7769   movl(result, 1);   // return true
7770   jmpb(DONE);
7771 
7772   bind(FALSE_LABEL);
7773   xorl(result, result); // return false
7774 
7775   // That's it
7776   bind(DONE);
7777   if (UseAVX >= 2 && UseSSE >= 2) {
7778     // clean upper bits of YMM registers
7779     vpxor(vec1, vec1);
7780     vpxor(vec2, vec2);
7781   }
7782 }
7783 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
7784 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
7785                                    Register limit, Register result, Register chr,
7786                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
7787   ShortBranchVerifier sbv(this);
7788   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
7789 
7790   int length_offset  = arrayOopDesc::length_offset_in_bytes();
7791   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
7792 
7793   if (is_array_equ) {
7794     // Check the input args
7795     cmpoop(ary1, ary2);
7796     jcc(Assembler::equal, TRUE_LABEL);
7797 
7798     // Need additional checks for arrays_equals.
7799     testptr(ary1, ary1);
7800     jcc(Assembler::zero, FALSE_LABEL);
7801     testptr(ary2, ary2);
7802     jcc(Assembler::zero, FALSE_LABEL);
7803 
7804     // Check the lengths
7805     movl(limit, Address(ary1, length_offset));
7806     cmpl(limit, Address(ary2, length_offset));
7807     jcc(Assembler::notEqual, FALSE_LABEL);
7808   }
7809 
7810   // count == 0
7811   testl(limit, limit);
7812   jcc(Assembler::zero, TRUE_LABEL);
7813 
7814   if (is_array_equ) {
7815     // Load array address
7816     lea(ary1, Address(ary1, base_offset));
7817     lea(ary2, Address(ary2, base_offset));
7818   }
7819 
7820   if (is_array_equ && is_char) {
7821     // arrays_equals when used for char[].
7822     shll(limit, 1);      // byte count != 0
7823   }
7824   movl(result, limit); // copy
7825 
7826   if (UseAVX >= 2) {
7827     // With AVX2, use 32-byte vector compare
7828     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7829 
7830     // Compare 32-byte vectors
7831     andl(result, 0x0000001f);  //   tail count (in bytes)
7832     andl(limit, 0xffffffe0);   // vector count (in bytes)
7833     jcc(Assembler::zero, COMPARE_TAIL);
7834 
7835     lea(ary1, Address(ary1, limit, Address::times_1));
7836     lea(ary2, Address(ary2, limit, Address::times_1));
7837     negptr(limit);
7838 
7839     bind(COMPARE_WIDE_VECTORS);
7840 
7841 #ifdef _LP64
7842     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7843       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
7844 
7845       cmpl(limit, -64);
7846       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7847 
7848       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7849 
7850       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
7851       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
7852       kortestql(k7, k7);
7853       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
7854       addptr(limit, 64);  // update since we already compared at this addr
7855       cmpl(limit, -64);
7856       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7857 
7858       // At this point we may still need to compare -limit+result bytes.
7859       // We could execute the next two instruction and just continue via non-wide path:
7860       //  cmpl(limit, 0);
7861       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
7862       // But since we stopped at the points ary{1,2}+limit which are
7863       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
7864       // (|limit| <= 32 and result < 32),
7865       // we may just compare the last 64 bytes.
7866       //
7867       addptr(result, -64);   // it is safe, bc we just came from this area
7868       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
7869       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
7870       kortestql(k7, k7);
7871       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
7872 
7873       jmp(TRUE_LABEL);
7874 
7875       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7876 
7877     }//if (VM_Version::supports_avx512vlbw())
7878 #endif //_LP64
7879 
7880     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
7881     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
7882     vpxor(vec1, vec2);
7883 
7884     vptest(vec1, vec1);
7885     jcc(Assembler::notZero, FALSE_LABEL);
7886     addptr(limit, 32);
7887     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7888 
7889     testl(result, result);
7890     jcc(Assembler::zero, TRUE_LABEL);
7891 
7892     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
7893     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
7894     vpxor(vec1, vec2);
7895 
7896     vptest(vec1, vec1);
7897     jccb(Assembler::notZero, FALSE_LABEL);
7898     jmpb(TRUE_LABEL);
7899 
7900     bind(COMPARE_TAIL); // limit is zero
7901     movl(limit, result);
7902     // Fallthru to tail compare
7903   } else if (UseSSE42Intrinsics) {
7904     // With SSE4.2, use double quad vector compare
7905     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7906 
7907     // Compare 16-byte vectors
7908     andl(result, 0x0000000f);  //   tail count (in bytes)
7909     andl(limit, 0xfffffff0);   // vector count (in bytes)
7910     jcc(Assembler::zero, COMPARE_TAIL);
7911 
7912     lea(ary1, Address(ary1, limit, Address::times_1));
7913     lea(ary2, Address(ary2, limit, Address::times_1));
7914     negptr(limit);
7915 
7916     bind(COMPARE_WIDE_VECTORS);
7917     movdqu(vec1, Address(ary1, limit, Address::times_1));
7918     movdqu(vec2, Address(ary2, limit, Address::times_1));
7919     pxor(vec1, vec2);
7920 
7921     ptest(vec1, vec1);
7922     jcc(Assembler::notZero, FALSE_LABEL);
7923     addptr(limit, 16);
7924     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7925 
7926     testl(result, result);
7927     jcc(Assembler::zero, TRUE_LABEL);
7928 
7929     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
7930     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
7931     pxor(vec1, vec2);
7932 
7933     ptest(vec1, vec1);
7934     jccb(Assembler::notZero, FALSE_LABEL);
7935     jmpb(TRUE_LABEL);
7936 
7937     bind(COMPARE_TAIL); // limit is zero
7938     movl(limit, result);
7939     // Fallthru to tail compare
7940   }
7941 
7942   // Compare 4-byte vectors
7943   andl(limit, 0xfffffffc); // vector count (in bytes)
7944   jccb(Assembler::zero, COMPARE_CHAR);
7945 
7946   lea(ary1, Address(ary1, limit, Address::times_1));
7947   lea(ary2, Address(ary2, limit, Address::times_1));
7948   negptr(limit);
7949 
7950   bind(COMPARE_VECTORS);
7951   movl(chr, Address(ary1, limit, Address::times_1));
7952   cmpl(chr, Address(ary2, limit, Address::times_1));
7953   jccb(Assembler::notEqual, FALSE_LABEL);
7954   addptr(limit, 4);
7955   jcc(Assembler::notZero, COMPARE_VECTORS);
7956 
7957   // Compare trailing char (final 2 bytes), if any
7958   bind(COMPARE_CHAR);
7959   testl(result, 0x2);   // tail  char
7960   jccb(Assembler::zero, COMPARE_BYTE);
7961   load_unsigned_short(chr, Address(ary1, 0));
7962   load_unsigned_short(limit, Address(ary2, 0));
7963   cmpl(chr, limit);
7964   jccb(Assembler::notEqual, FALSE_LABEL);
7965 
7966   if (is_array_equ && is_char) {
7967     bind(COMPARE_BYTE);
7968   } else {
7969     lea(ary1, Address(ary1, 2));
7970     lea(ary2, Address(ary2, 2));
7971 
7972     bind(COMPARE_BYTE);
7973     testl(result, 0x1);   // tail  byte
7974     jccb(Assembler::zero, TRUE_LABEL);
7975     load_unsigned_byte(chr, Address(ary1, 0));
7976     load_unsigned_byte(limit, Address(ary2, 0));
7977     cmpl(chr, limit);
7978     jccb(Assembler::notEqual, FALSE_LABEL);
7979   }
7980   bind(TRUE_LABEL);
7981   movl(result, 1);   // return true
7982   jmpb(DONE);
7983 
7984   bind(FALSE_LABEL);
7985   xorl(result, result); // return false
7986 
7987   // That's it
7988   bind(DONE);
7989   if (UseAVX >= 2) {
7990     // clean upper bits of YMM registers
7991     vpxor(vec1, vec1);
7992     vpxor(vec2, vec2);
7993   }
7994 }
7995 
7996 #endif
7997 
7998 void MacroAssembler::generate_fill(BasicType t, bool aligned,
7999                                    Register to, Register value, Register count,
8000                                    Register rtmp, XMMRegister xtmp) {
8001   ShortBranchVerifier sbv(this);
8002   assert_different_registers(to, value, count, rtmp);
8003   Label L_exit;
8004   Label L_fill_2_bytes, L_fill_4_bytes;
8005 
8006   int shift = -1;
8007   switch (t) {
8008     case T_BYTE:
8009       shift = 2;
8010       break;
8011     case T_SHORT:
8012       shift = 1;
8013       break;
8014     case T_INT:
8015       shift = 0;
8016       break;
8017     default: ShouldNotReachHere();
8018   }
8019 
8020   if (t == T_BYTE) {
8021     andl(value, 0xff);
8022     movl(rtmp, value);
8023     shll(rtmp, 8);
8024     orl(value, rtmp);
8025   }
8026   if (t == T_SHORT) {
8027     andl(value, 0xffff);
8028   }
8029   if (t == T_BYTE || t == T_SHORT) {
8030     movl(rtmp, value);
8031     shll(rtmp, 16);
8032     orl(value, rtmp);
8033   }
8034 
8035   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8036   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8037   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8038     Label L_skip_align2;
8039     // align source address at 4 bytes address boundary
8040     if (t == T_BYTE) {
8041       Label L_skip_align1;
8042       // One byte misalignment happens only for byte arrays
8043       testptr(to, 1);
8044       jccb(Assembler::zero, L_skip_align1);
8045       movb(Address(to, 0), value);
8046       increment(to);
8047       decrement(count);
8048       BIND(L_skip_align1);
8049     }
8050     // Two bytes misalignment happens only for byte and short (char) arrays
8051     testptr(to, 2);
8052     jccb(Assembler::zero, L_skip_align2);
8053     movw(Address(to, 0), value);
8054     addptr(to, 2);
8055     subl(count, 1<<(shift-1));
8056     BIND(L_skip_align2);
8057   }
8058   if (UseSSE < 2) {
8059     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8060     // Fill 32-byte chunks
8061     subl(count, 8 << shift);
8062     jcc(Assembler::less, L_check_fill_8_bytes);
8063     align(16);
8064 
8065     BIND(L_fill_32_bytes_loop);
8066 
8067     for (int i = 0; i < 32; i += 4) {
8068       movl(Address(to, i), value);
8069     }
8070 
8071     addptr(to, 32);
8072     subl(count, 8 << shift);
8073     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8074     BIND(L_check_fill_8_bytes);
8075     addl(count, 8 << shift);
8076     jccb(Assembler::zero, L_exit);
8077     jmpb(L_fill_8_bytes);
8078 
8079     //
8080     // length is too short, just fill qwords
8081     //
8082     BIND(L_fill_8_bytes_loop);
8083     movl(Address(to, 0), value);
8084     movl(Address(to, 4), value);
8085     addptr(to, 8);
8086     BIND(L_fill_8_bytes);
8087     subl(count, 1 << (shift + 1));
8088     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8089     // fall through to fill 4 bytes
8090   } else {
8091     Label L_fill_32_bytes;
8092     if (!UseUnalignedLoadStores) {
8093       // align to 8 bytes, we know we are 4 byte aligned to start
8094       testptr(to, 4);
8095       jccb(Assembler::zero, L_fill_32_bytes);
8096       movl(Address(to, 0), value);
8097       addptr(to, 4);
8098       subl(count, 1<<shift);
8099     }
8100     BIND(L_fill_32_bytes);
8101     {
8102       assert( UseSSE >= 2, "supported cpu only" );
8103       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8104       movdl(xtmp, value);
8105       if (UseAVX > 2 && UseUnalignedLoadStores) {
8106         // Fill 64-byte chunks
8107         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8108         vpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8109 
8110         subl(count, 16 << shift);
8111         jcc(Assembler::less, L_check_fill_32_bytes);
8112         align(16);
8113 
8114         BIND(L_fill_64_bytes_loop);
8115         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8116         addptr(to, 64);
8117         subl(count, 16 << shift);
8118         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8119 
8120         BIND(L_check_fill_32_bytes);
8121         addl(count, 8 << shift);
8122         jccb(Assembler::less, L_check_fill_8_bytes);
8123         vmovdqu(Address(to, 0), xtmp);
8124         addptr(to, 32);
8125         subl(count, 8 << shift);
8126 
8127         BIND(L_check_fill_8_bytes);
8128       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8129         // Fill 64-byte chunks
8130         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8131         vpbroadcastd(xtmp, xtmp, Assembler::AVX_256bit);
8132 
8133         subl(count, 16 << shift);
8134         jcc(Assembler::less, L_check_fill_32_bytes);
8135         align(16);
8136 
8137         BIND(L_fill_64_bytes_loop);
8138         vmovdqu(Address(to, 0), xtmp);
8139         vmovdqu(Address(to, 32), xtmp);
8140         addptr(to, 64);
8141         subl(count, 16 << shift);
8142         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8143 
8144         BIND(L_check_fill_32_bytes);
8145         addl(count, 8 << shift);
8146         jccb(Assembler::less, L_check_fill_8_bytes);
8147         vmovdqu(Address(to, 0), xtmp);
8148         addptr(to, 32);
8149         subl(count, 8 << shift);
8150 
8151         BIND(L_check_fill_8_bytes);
8152         // clean upper bits of YMM registers
8153         movdl(xtmp, value);
8154         pshufd(xtmp, xtmp, 0);
8155       } else {
8156         // Fill 32-byte chunks
8157         pshufd(xtmp, xtmp, 0);
8158 
8159         subl(count, 8 << shift);
8160         jcc(Assembler::less, L_check_fill_8_bytes);
8161         align(16);
8162 
8163         BIND(L_fill_32_bytes_loop);
8164 
8165         if (UseUnalignedLoadStores) {
8166           movdqu(Address(to, 0), xtmp);
8167           movdqu(Address(to, 16), xtmp);
8168         } else {
8169           movq(Address(to, 0), xtmp);
8170           movq(Address(to, 8), xtmp);
8171           movq(Address(to, 16), xtmp);
8172           movq(Address(to, 24), xtmp);
8173         }
8174 
8175         addptr(to, 32);
8176         subl(count, 8 << shift);
8177         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8178 
8179         BIND(L_check_fill_8_bytes);
8180       }
8181       addl(count, 8 << shift);
8182       jccb(Assembler::zero, L_exit);
8183       jmpb(L_fill_8_bytes);
8184 
8185       //
8186       // length is too short, just fill qwords
8187       //
8188       BIND(L_fill_8_bytes_loop);
8189       movq(Address(to, 0), xtmp);
8190       addptr(to, 8);
8191       BIND(L_fill_8_bytes);
8192       subl(count, 1 << (shift + 1));
8193       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8194     }
8195   }
8196   // fill trailing 4 bytes
8197   BIND(L_fill_4_bytes);
8198   testl(count, 1<<shift);
8199   jccb(Assembler::zero, L_fill_2_bytes);
8200   movl(Address(to, 0), value);
8201   if (t == T_BYTE || t == T_SHORT) {
8202     Label L_fill_byte;
8203     addptr(to, 4);
8204     BIND(L_fill_2_bytes);
8205     // fill trailing 2 bytes
8206     testl(count, 1<<(shift-1));
8207     jccb(Assembler::zero, L_fill_byte);
8208     movw(Address(to, 0), value);
8209     if (t == T_BYTE) {
8210       addptr(to, 2);
8211       BIND(L_fill_byte);
8212       // fill trailing byte
8213       testl(count, 1);
8214       jccb(Assembler::zero, L_exit);
8215       movb(Address(to, 0), value);
8216     } else {
8217       BIND(L_fill_byte);
8218     }
8219   } else {
8220     BIND(L_fill_2_bytes);
8221   }
8222   BIND(L_exit);
8223 }
8224 
8225 // encode char[] to byte[] in ISO_8859_1
8226    //@HotSpotIntrinsicCandidate
8227    //private static int implEncodeISOArray(byte[] sa, int sp,
8228    //byte[] da, int dp, int len) {
8229    //  int i = 0;
8230    //  for (; i < len; i++) {
8231    //    char c = StringUTF16.getChar(sa, sp++);
8232    //    if (c > '\u00FF')
8233    //      break;
8234    //    da[dp++] = (byte)c;
8235    //  }
8236    //  return i;
8237    //}
8238 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8239   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8240   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8241   Register tmp5, Register result) {
8242 
8243   // rsi: src
8244   // rdi: dst
8245   // rdx: len
8246   // rcx: tmp5
8247   // rax: result
8248   ShortBranchVerifier sbv(this);
8249   assert_different_registers(src, dst, len, tmp5, result);
8250   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8251 
8252   // set result
8253   xorl(result, result);
8254   // check for zero length
8255   testl(len, len);
8256   jcc(Assembler::zero, L_done);
8257 
8258   movl(result, len);
8259 
8260   // Setup pointers
8261   lea(src, Address(src, len, Address::times_2)); // char[]
8262   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8263   negptr(len);
8264 
8265   if (UseSSE42Intrinsics || UseAVX >= 2) {
8266     Label L_copy_8_chars, L_copy_8_chars_exit;
8267     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8268 
8269     if (UseAVX >= 2) {
8270       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8271       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8272       movdl(tmp1Reg, tmp5);
8273       vpbroadcastd(tmp1Reg, tmp1Reg, Assembler::AVX_256bit);
8274       jmp(L_chars_32_check);
8275 
8276       bind(L_copy_32_chars);
8277       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8278       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8279       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8280       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8281       jccb(Assembler::notZero, L_copy_32_chars_exit);
8282       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8283       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8284       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8285 
8286       bind(L_chars_32_check);
8287       addptr(len, 32);
8288       jcc(Assembler::lessEqual, L_copy_32_chars);
8289 
8290       bind(L_copy_32_chars_exit);
8291       subptr(len, 16);
8292       jccb(Assembler::greater, L_copy_16_chars_exit);
8293 
8294     } else if (UseSSE42Intrinsics) {
8295       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8296       movdl(tmp1Reg, tmp5);
8297       pshufd(tmp1Reg, tmp1Reg, 0);
8298       jmpb(L_chars_16_check);
8299     }
8300 
8301     bind(L_copy_16_chars);
8302     if (UseAVX >= 2) {
8303       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8304       vptest(tmp2Reg, tmp1Reg);
8305       jcc(Assembler::notZero, L_copy_16_chars_exit);
8306       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8307       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8308     } else {
8309       if (UseAVX > 0) {
8310         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8311         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8312         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8313       } else {
8314         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8315         por(tmp2Reg, tmp3Reg);
8316         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8317         por(tmp2Reg, tmp4Reg);
8318       }
8319       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8320       jccb(Assembler::notZero, L_copy_16_chars_exit);
8321       packuswb(tmp3Reg, tmp4Reg);
8322     }
8323     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8324 
8325     bind(L_chars_16_check);
8326     addptr(len, 16);
8327     jcc(Assembler::lessEqual, L_copy_16_chars);
8328 
8329     bind(L_copy_16_chars_exit);
8330     if (UseAVX >= 2) {
8331       // clean upper bits of YMM registers
8332       vpxor(tmp2Reg, tmp2Reg);
8333       vpxor(tmp3Reg, tmp3Reg);
8334       vpxor(tmp4Reg, tmp4Reg);
8335       movdl(tmp1Reg, tmp5);
8336       pshufd(tmp1Reg, tmp1Reg, 0);
8337     }
8338     subptr(len, 8);
8339     jccb(Assembler::greater, L_copy_8_chars_exit);
8340 
8341     bind(L_copy_8_chars);
8342     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8343     ptest(tmp3Reg, tmp1Reg);
8344     jccb(Assembler::notZero, L_copy_8_chars_exit);
8345     packuswb(tmp3Reg, tmp1Reg);
8346     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8347     addptr(len, 8);
8348     jccb(Assembler::lessEqual, L_copy_8_chars);
8349 
8350     bind(L_copy_8_chars_exit);
8351     subptr(len, 8);
8352     jccb(Assembler::zero, L_done);
8353   }
8354 
8355   bind(L_copy_1_char);
8356   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8357   testl(tmp5, 0xff00);      // check if Unicode char
8358   jccb(Assembler::notZero, L_copy_1_char_exit);
8359   movb(Address(dst, len, Address::times_1, 0), tmp5);
8360   addptr(len, 1);
8361   jccb(Assembler::less, L_copy_1_char);
8362 
8363   bind(L_copy_1_char_exit);
8364   addptr(result, len); // len is negative count of not processed elements
8365 
8366   bind(L_done);
8367 }
8368 
8369 #ifdef _LP64
8370 /**
8371  * Helper for multiply_to_len().
8372  */
8373 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8374   addq(dest_lo, src1);
8375   adcq(dest_hi, 0);
8376   addq(dest_lo, src2);
8377   adcq(dest_hi, 0);
8378 }
8379 
8380 /**
8381  * Multiply 64 bit by 64 bit first loop.
8382  */
8383 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8384                                            Register y, Register y_idx, Register z,
8385                                            Register carry, Register product,
8386                                            Register idx, Register kdx) {
8387   //
8388   //  jlong carry, x[], y[], z[];
8389   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8390   //    huge_128 product = y[idx] * x[xstart] + carry;
8391   //    z[kdx] = (jlong)product;
8392   //    carry  = (jlong)(product >>> 64);
8393   //  }
8394   //  z[xstart] = carry;
8395   //
8396 
8397   Label L_first_loop, L_first_loop_exit;
8398   Label L_one_x, L_one_y, L_multiply;
8399 
8400   decrementl(xstart);
8401   jcc(Assembler::negative, L_one_x);
8402 
8403   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8404   rorq(x_xstart, 32); // convert big-endian to little-endian
8405 
8406   bind(L_first_loop);
8407   decrementl(idx);
8408   jcc(Assembler::negative, L_first_loop_exit);
8409   decrementl(idx);
8410   jcc(Assembler::negative, L_one_y);
8411   movq(y_idx, Address(y, idx, Address::times_4,  0));
8412   rorq(y_idx, 32); // convert big-endian to little-endian
8413   bind(L_multiply);
8414   movq(product, x_xstart);
8415   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
8416   addq(product, carry);
8417   adcq(rdx, 0);
8418   subl(kdx, 2);
8419   movl(Address(z, kdx, Address::times_4,  4), product);
8420   shrq(product, 32);
8421   movl(Address(z, kdx, Address::times_4,  0), product);
8422   movq(carry, rdx);
8423   jmp(L_first_loop);
8424 
8425   bind(L_one_y);
8426   movl(y_idx, Address(y,  0));
8427   jmp(L_multiply);
8428 
8429   bind(L_one_x);
8430   movl(x_xstart, Address(x,  0));
8431   jmp(L_first_loop);
8432 
8433   bind(L_first_loop_exit);
8434 }
8435 
8436 /**
8437  * Multiply 64 bit by 64 bit and add 128 bit.
8438  */
8439 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
8440                                             Register yz_idx, Register idx,
8441                                             Register carry, Register product, int offset) {
8442   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
8443   //     z[kdx] = (jlong)product;
8444 
8445   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
8446   rorq(yz_idx, 32); // convert big-endian to little-endian
8447   movq(product, x_xstart);
8448   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
8449   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
8450   rorq(yz_idx, 32); // convert big-endian to little-endian
8451 
8452   add2_with_carry(rdx, product, carry, yz_idx);
8453 
8454   movl(Address(z, idx, Address::times_4,  offset+4), product);
8455   shrq(product, 32);
8456   movl(Address(z, idx, Address::times_4,  offset), product);
8457 
8458 }
8459 
8460 /**
8461  * Multiply 128 bit by 128 bit. Unrolled inner loop.
8462  */
8463 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
8464                                              Register yz_idx, Register idx, Register jdx,
8465                                              Register carry, Register product,
8466                                              Register carry2) {
8467   //   jlong carry, x[], y[], z[];
8468   //   int kdx = ystart+1;
8469   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8470   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
8471   //     z[kdx+idx+1] = (jlong)product;
8472   //     jlong carry2  = (jlong)(product >>> 64);
8473   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
8474   //     z[kdx+idx] = (jlong)product;
8475   //     carry  = (jlong)(product >>> 64);
8476   //   }
8477   //   idx += 2;
8478   //   if (idx > 0) {
8479   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
8480   //     z[kdx+idx] = (jlong)product;
8481   //     carry  = (jlong)(product >>> 64);
8482   //   }
8483   //
8484 
8485   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8486 
8487   movl(jdx, idx);
8488   andl(jdx, 0xFFFFFFFC);
8489   shrl(jdx, 2);
8490 
8491   bind(L_third_loop);
8492   subl(jdx, 1);
8493   jcc(Assembler::negative, L_third_loop_exit);
8494   subl(idx, 4);
8495 
8496   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
8497   movq(carry2, rdx);
8498 
8499   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
8500   movq(carry, rdx);
8501   jmp(L_third_loop);
8502 
8503   bind (L_third_loop_exit);
8504 
8505   andl (idx, 0x3);
8506   jcc(Assembler::zero, L_post_third_loop_done);
8507 
8508   Label L_check_1;
8509   subl(idx, 2);
8510   jcc(Assembler::negative, L_check_1);
8511 
8512   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
8513   movq(carry, rdx);
8514 
8515   bind (L_check_1);
8516   addl (idx, 0x2);
8517   andl (idx, 0x1);
8518   subl(idx, 1);
8519   jcc(Assembler::negative, L_post_third_loop_done);
8520 
8521   movl(yz_idx, Address(y, idx, Address::times_4,  0));
8522   movq(product, x_xstart);
8523   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
8524   movl(yz_idx, Address(z, idx, Address::times_4,  0));
8525 
8526   add2_with_carry(rdx, product, yz_idx, carry);
8527 
8528   movl(Address(z, idx, Address::times_4,  0), product);
8529   shrq(product, 32);
8530 
8531   shlq(rdx, 32);
8532   orq(product, rdx);
8533   movq(carry, product);
8534 
8535   bind(L_post_third_loop_done);
8536 }
8537 
8538 /**
8539  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
8540  *
8541  */
8542 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
8543                                                   Register carry, Register carry2,
8544                                                   Register idx, Register jdx,
8545                                                   Register yz_idx1, Register yz_idx2,
8546                                                   Register tmp, Register tmp3, Register tmp4) {
8547   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
8548 
8549   //   jlong carry, x[], y[], z[];
8550   //   int kdx = ystart+1;
8551   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8552   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
8553   //     jlong carry2  = (jlong)(tmp3 >>> 64);
8554   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
8555   //     carry  = (jlong)(tmp4 >>> 64);
8556   //     z[kdx+idx+1] = (jlong)tmp3;
8557   //     z[kdx+idx] = (jlong)tmp4;
8558   //   }
8559   //   idx += 2;
8560   //   if (idx > 0) {
8561   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
8562   //     z[kdx+idx] = (jlong)yz_idx1;
8563   //     carry  = (jlong)(yz_idx1 >>> 64);
8564   //   }
8565   //
8566 
8567   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8568 
8569   movl(jdx, idx);
8570   andl(jdx, 0xFFFFFFFC);
8571   shrl(jdx, 2);
8572 
8573   bind(L_third_loop);
8574   subl(jdx, 1);
8575   jcc(Assembler::negative, L_third_loop_exit);
8576   subl(idx, 4);
8577 
8578   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
8579   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
8580   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
8581   rorxq(yz_idx2, yz_idx2, 32);
8582 
8583   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
8584   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
8585 
8586   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
8587   rorxq(yz_idx1, yz_idx1, 32);
8588   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8589   rorxq(yz_idx2, yz_idx2, 32);
8590 
8591   if (VM_Version::supports_adx()) {
8592     adcxq(tmp3, carry);
8593     adoxq(tmp3, yz_idx1);
8594 
8595     adcxq(tmp4, tmp);
8596     adoxq(tmp4, yz_idx2);
8597 
8598     movl(carry, 0); // does not affect flags
8599     adcxq(carry2, carry);
8600     adoxq(carry2, carry);
8601   } else {
8602     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
8603     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
8604   }
8605   movq(carry, carry2);
8606 
8607   movl(Address(z, idx, Address::times_4, 12), tmp3);
8608   shrq(tmp3, 32);
8609   movl(Address(z, idx, Address::times_4,  8), tmp3);
8610 
8611   movl(Address(z, idx, Address::times_4,  4), tmp4);
8612   shrq(tmp4, 32);
8613   movl(Address(z, idx, Address::times_4,  0), tmp4);
8614 
8615   jmp(L_third_loop);
8616 
8617   bind (L_third_loop_exit);
8618 
8619   andl (idx, 0x3);
8620   jcc(Assembler::zero, L_post_third_loop_done);
8621 
8622   Label L_check_1;
8623   subl(idx, 2);
8624   jcc(Assembler::negative, L_check_1);
8625 
8626   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
8627   rorxq(yz_idx1, yz_idx1, 32);
8628   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
8629   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8630   rorxq(yz_idx2, yz_idx2, 32);
8631 
8632   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
8633 
8634   movl(Address(z, idx, Address::times_4,  4), tmp3);
8635   shrq(tmp3, 32);
8636   movl(Address(z, idx, Address::times_4,  0), tmp3);
8637   movq(carry, tmp4);
8638 
8639   bind (L_check_1);
8640   addl (idx, 0x2);
8641   andl (idx, 0x1);
8642   subl(idx, 1);
8643   jcc(Assembler::negative, L_post_third_loop_done);
8644   movl(tmp4, Address(y, idx, Address::times_4,  0));
8645   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
8646   movl(tmp4, Address(z, idx, Address::times_4,  0));
8647 
8648   add2_with_carry(carry2, tmp3, tmp4, carry);
8649 
8650   movl(Address(z, idx, Address::times_4,  0), tmp3);
8651   shrq(tmp3, 32);
8652 
8653   shlq(carry2, 32);
8654   orq(tmp3, carry2);
8655   movq(carry, tmp3);
8656 
8657   bind(L_post_third_loop_done);
8658 }
8659 
8660 /**
8661  * Code for BigInteger::multiplyToLen() instrinsic.
8662  *
8663  * rdi: x
8664  * rax: xlen
8665  * rsi: y
8666  * rcx: ylen
8667  * r8:  z
8668  * r11: zlen
8669  * r12: tmp1
8670  * r13: tmp2
8671  * r14: tmp3
8672  * r15: tmp4
8673  * rbx: tmp5
8674  *
8675  */
8676 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
8677                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
8678   ShortBranchVerifier sbv(this);
8679   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
8680 
8681   push(tmp1);
8682   push(tmp2);
8683   push(tmp3);
8684   push(tmp4);
8685   push(tmp5);
8686 
8687   push(xlen);
8688   push(zlen);
8689 
8690   const Register idx = tmp1;
8691   const Register kdx = tmp2;
8692   const Register xstart = tmp3;
8693 
8694   const Register y_idx = tmp4;
8695   const Register carry = tmp5;
8696   const Register product  = xlen;
8697   const Register x_xstart = zlen;  // reuse register
8698 
8699   // First Loop.
8700   //
8701   //  final static long LONG_MASK = 0xffffffffL;
8702   //  int xstart = xlen - 1;
8703   //  int ystart = ylen - 1;
8704   //  long carry = 0;
8705   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8706   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
8707   //    z[kdx] = (int)product;
8708   //    carry = product >>> 32;
8709   //  }
8710   //  z[xstart] = (int)carry;
8711   //
8712 
8713   movl(idx, ylen);      // idx = ylen;
8714   movl(kdx, zlen);      // kdx = xlen+ylen;
8715   xorq(carry, carry);   // carry = 0;
8716 
8717   Label L_done;
8718 
8719   movl(xstart, xlen);
8720   decrementl(xstart);
8721   jcc(Assembler::negative, L_done);
8722 
8723   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
8724 
8725   Label L_second_loop;
8726   testl(kdx, kdx);
8727   jcc(Assembler::zero, L_second_loop);
8728 
8729   Label L_carry;
8730   subl(kdx, 1);
8731   jcc(Assembler::zero, L_carry);
8732 
8733   movl(Address(z, kdx, Address::times_4,  0), carry);
8734   shrq(carry, 32);
8735   subl(kdx, 1);
8736 
8737   bind(L_carry);
8738   movl(Address(z, kdx, Address::times_4,  0), carry);
8739 
8740   // Second and third (nested) loops.
8741   //
8742   // for (int i = xstart-1; i >= 0; i--) { // Second loop
8743   //   carry = 0;
8744   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
8745   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
8746   //                    (z[k] & LONG_MASK) + carry;
8747   //     z[k] = (int)product;
8748   //     carry = product >>> 32;
8749   //   }
8750   //   z[i] = (int)carry;
8751   // }
8752   //
8753   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
8754 
8755   const Register jdx = tmp1;
8756 
8757   bind(L_second_loop);
8758   xorl(carry, carry);    // carry = 0;
8759   movl(jdx, ylen);       // j = ystart+1
8760 
8761   subl(xstart, 1);       // i = xstart-1;
8762   jcc(Assembler::negative, L_done);
8763 
8764   push (z);
8765 
8766   Label L_last_x;
8767   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
8768   subl(xstart, 1);       // i = xstart-1;
8769   jcc(Assembler::negative, L_last_x);
8770 
8771   if (UseBMI2Instructions) {
8772     movq(rdx,  Address(x, xstart, Address::times_4,  0));
8773     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
8774   } else {
8775     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8776     rorq(x_xstart, 32);  // convert big-endian to little-endian
8777   }
8778 
8779   Label L_third_loop_prologue;
8780   bind(L_third_loop_prologue);
8781 
8782   push (x);
8783   push (xstart);
8784   push (ylen);
8785 
8786 
8787   if (UseBMI2Instructions) {
8788     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
8789   } else { // !UseBMI2Instructions
8790     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
8791   }
8792 
8793   pop(ylen);
8794   pop(xlen);
8795   pop(x);
8796   pop(z);
8797 
8798   movl(tmp3, xlen);
8799   addl(tmp3, 1);
8800   movl(Address(z, tmp3, Address::times_4,  0), carry);
8801   subl(tmp3, 1);
8802   jccb(Assembler::negative, L_done);
8803 
8804   shrq(carry, 32);
8805   movl(Address(z, tmp3, Address::times_4,  0), carry);
8806   jmp(L_second_loop);
8807 
8808   // Next infrequent code is moved outside loops.
8809   bind(L_last_x);
8810   if (UseBMI2Instructions) {
8811     movl(rdx, Address(x,  0));
8812   } else {
8813     movl(x_xstart, Address(x,  0));
8814   }
8815   jmp(L_third_loop_prologue);
8816 
8817   bind(L_done);
8818 
8819   pop(zlen);
8820   pop(xlen);
8821 
8822   pop(tmp5);
8823   pop(tmp4);
8824   pop(tmp3);
8825   pop(tmp2);
8826   pop(tmp1);
8827 }
8828 
8829 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
8830   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
8831   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
8832   Label VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
8833   Label VECTOR8_TAIL, VECTOR4_TAIL;
8834   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
8835   Label SAME_TILL_END, DONE;
8836   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
8837 
8838   //scale is in rcx in both Win64 and Unix
8839   ShortBranchVerifier sbv(this);
8840 
8841   shlq(length);
8842   xorq(result, result);
8843 
8844   if ((UseAVX > 2) &&
8845       VM_Version::supports_avx512vlbw()) {
8846     Label VECTOR64_LOOP, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
8847 
8848     cmpq(length, 64);
8849     jcc(Assembler::less, VECTOR32_TAIL);
8850     movq(tmp1, length);
8851     andq(tmp1, 0x3F);      // tail count
8852     andq(length, ~(0x3F)); //vector count
8853 
8854     bind(VECTOR64_LOOP);
8855     // AVX512 code to compare 64 byte vectors.
8856     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
8857     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
8858     kortestql(k7, k7);
8859     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
8860     addq(result, 64);
8861     subq(length, 64);
8862     jccb(Assembler::notZero, VECTOR64_LOOP);
8863 
8864     //bind(VECTOR64_TAIL);
8865     testq(tmp1, tmp1);
8866     jcc(Assembler::zero, SAME_TILL_END);
8867 
8868     //bind(VECTOR64_TAIL);
8869     // AVX512 code to compare upto 63 byte vectors.
8870     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
8871     shlxq(tmp2, tmp2, tmp1);
8872     notq(tmp2);
8873     kmovql(k3, tmp2);
8874 
8875     evmovdqub(rymm0, k3, Address(obja, result), Assembler::AVX_512bit);
8876     evpcmpeqb(k7, k3, rymm0, Address(objb, result), Assembler::AVX_512bit);
8877 
8878     ktestql(k7, k3);
8879     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
8880 
8881     bind(VECTOR64_NOT_EQUAL);
8882     kmovql(tmp1, k7);
8883     notq(tmp1);
8884     tzcntq(tmp1, tmp1);
8885     addq(result, tmp1);
8886     shrq(result);
8887     jmp(DONE);
8888     bind(VECTOR32_TAIL);
8889   }
8890 
8891   cmpq(length, 8);
8892   jcc(Assembler::equal, VECTOR8_LOOP);
8893   jcc(Assembler::less, VECTOR4_TAIL);
8894 
8895   if (UseAVX >= 2) {
8896     Label VECTOR16_TAIL, VECTOR32_LOOP;
8897 
8898     cmpq(length, 16);
8899     jcc(Assembler::equal, VECTOR16_LOOP);
8900     jcc(Assembler::less, VECTOR8_LOOP);
8901 
8902     cmpq(length, 32);
8903     jccb(Assembler::less, VECTOR16_TAIL);
8904 
8905     subq(length, 32);
8906     bind(VECTOR32_LOOP);
8907     vmovdqu(rymm0, Address(obja, result));
8908     vmovdqu(rymm1, Address(objb, result));
8909     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
8910     vptest(rymm2, rymm2);
8911     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
8912     addq(result, 32);
8913     subq(length, 32);
8914     jcc(Assembler::greaterEqual, VECTOR32_LOOP);
8915     addq(length, 32);
8916     jcc(Assembler::equal, SAME_TILL_END);
8917     //falling through if less than 32 bytes left //close the branch here.
8918 
8919     bind(VECTOR16_TAIL);
8920     cmpq(length, 16);
8921     jccb(Assembler::less, VECTOR8_TAIL);
8922     bind(VECTOR16_LOOP);
8923     movdqu(rymm0, Address(obja, result));
8924     movdqu(rymm1, Address(objb, result));
8925     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
8926     ptest(rymm2, rymm2);
8927     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
8928     addq(result, 16);
8929     subq(length, 16);
8930     jcc(Assembler::equal, SAME_TILL_END);
8931     //falling through if less than 16 bytes left
8932   } else {//regular intrinsics
8933 
8934     cmpq(length, 16);
8935     jccb(Assembler::less, VECTOR8_TAIL);
8936 
8937     subq(length, 16);
8938     bind(VECTOR16_LOOP);
8939     movdqu(rymm0, Address(obja, result));
8940     movdqu(rymm1, Address(objb, result));
8941     pxor(rymm0, rymm1);
8942     ptest(rymm0, rymm0);
8943     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
8944     addq(result, 16);
8945     subq(length, 16);
8946     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
8947     addq(length, 16);
8948     jcc(Assembler::equal, SAME_TILL_END);
8949     //falling through if less than 16 bytes left
8950   }
8951 
8952   bind(VECTOR8_TAIL);
8953   cmpq(length, 8);
8954   jccb(Assembler::less, VECTOR4_TAIL);
8955   bind(VECTOR8_LOOP);
8956   movq(tmp1, Address(obja, result));
8957   movq(tmp2, Address(objb, result));
8958   xorq(tmp1, tmp2);
8959   testq(tmp1, tmp1);
8960   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
8961   addq(result, 8);
8962   subq(length, 8);
8963   jcc(Assembler::equal, SAME_TILL_END);
8964   //falling through if less than 8 bytes left
8965 
8966   bind(VECTOR4_TAIL);
8967   cmpq(length, 4);
8968   jccb(Assembler::less, BYTES_TAIL);
8969   bind(VECTOR4_LOOP);
8970   movl(tmp1, Address(obja, result));
8971   xorl(tmp1, Address(objb, result));
8972   testl(tmp1, tmp1);
8973   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
8974   addq(result, 4);
8975   subq(length, 4);
8976   jcc(Assembler::equal, SAME_TILL_END);
8977   //falling through if less than 4 bytes left
8978 
8979   bind(BYTES_TAIL);
8980   bind(BYTES_LOOP);
8981   load_unsigned_byte(tmp1, Address(obja, result));
8982   load_unsigned_byte(tmp2, Address(objb, result));
8983   xorl(tmp1, tmp2);
8984   testl(tmp1, tmp1);
8985   jcc(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
8986   decq(length);
8987   jcc(Assembler::zero, SAME_TILL_END);
8988   incq(result);
8989   load_unsigned_byte(tmp1, Address(obja, result));
8990   load_unsigned_byte(tmp2, Address(objb, result));
8991   xorl(tmp1, tmp2);
8992   testl(tmp1, tmp1);
8993   jcc(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
8994   decq(length);
8995   jcc(Assembler::zero, SAME_TILL_END);
8996   incq(result);
8997   load_unsigned_byte(tmp1, Address(obja, result));
8998   load_unsigned_byte(tmp2, Address(objb, result));
8999   xorl(tmp1, tmp2);
9000   testl(tmp1, tmp1);
9001   jcc(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9002   jmp(SAME_TILL_END);
9003 
9004   if (UseAVX >= 2) {
9005     bind(VECTOR32_NOT_EQUAL);
9006     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9007     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9008     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9009     vpmovmskb(tmp1, rymm0);
9010     bsfq(tmp1, tmp1);
9011     addq(result, tmp1);
9012     shrq(result);
9013     jmp(DONE);
9014   }
9015 
9016   bind(VECTOR16_NOT_EQUAL);
9017   if (UseAVX >= 2) {
9018     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9019     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9020     pxor(rymm0, rymm2);
9021   } else {
9022     pcmpeqb(rymm2, rymm2);
9023     pxor(rymm0, rymm1);
9024     pcmpeqb(rymm0, rymm1);
9025     pxor(rymm0, rymm2);
9026   }
9027   pmovmskb(tmp1, rymm0);
9028   bsfq(tmp1, tmp1);
9029   addq(result, tmp1);
9030   shrq(result);
9031   jmpb(DONE);
9032 
9033   bind(VECTOR8_NOT_EQUAL);
9034   bind(VECTOR4_NOT_EQUAL);
9035   bsfq(tmp1, tmp1);
9036   shrq(tmp1, 3);
9037   addq(result, tmp1);
9038   bind(BYTES_NOT_EQUAL);
9039   shrq(result);
9040   jmpb(DONE);
9041 
9042   bind(SAME_TILL_END);
9043   mov64(result, -1);
9044 
9045   bind(DONE);
9046 }
9047 
9048 //Helper functions for square_to_len()
9049 
9050 /**
9051  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9052  * Preserves x and z and modifies rest of the registers.
9053  */
9054 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9055   // Perform square and right shift by 1
9056   // Handle odd xlen case first, then for even xlen do the following
9057   // jlong carry = 0;
9058   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9059   //     huge_128 product = x[j:j+1] * x[j:j+1];
9060   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9061   //     z[i+2:i+3] = (jlong)(product >>> 1);
9062   //     carry = (jlong)product;
9063   // }
9064 
9065   xorq(tmp5, tmp5);     // carry
9066   xorq(rdxReg, rdxReg);
9067   xorl(tmp1, tmp1);     // index for x
9068   xorl(tmp4, tmp4);     // index for z
9069 
9070   Label L_first_loop, L_first_loop_exit;
9071 
9072   testl(xlen, 1);
9073   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9074 
9075   // Square and right shift by 1 the odd element using 32 bit multiply
9076   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9077   imulq(raxReg, raxReg);
9078   shrq(raxReg, 1);
9079   adcq(tmp5, 0);
9080   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9081   incrementl(tmp1);
9082   addl(tmp4, 2);
9083 
9084   // Square and  right shift by 1 the rest using 64 bit multiply
9085   bind(L_first_loop);
9086   cmpptr(tmp1, xlen);
9087   jccb(Assembler::equal, L_first_loop_exit);
9088 
9089   // Square
9090   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9091   rorq(raxReg, 32);    // convert big-endian to little-endian
9092   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9093 
9094   // Right shift by 1 and save carry
9095   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9096   rcrq(rdxReg, 1);
9097   rcrq(raxReg, 1);
9098   adcq(tmp5, 0);
9099 
9100   // Store result in z
9101   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9102   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9103 
9104   // Update indices for x and z
9105   addl(tmp1, 2);
9106   addl(tmp4, 4);
9107   jmp(L_first_loop);
9108 
9109   bind(L_first_loop_exit);
9110 }
9111 
9112 
9113 /**
9114  * Perform the following multiply add operation using BMI2 instructions
9115  * carry:sum = sum + op1*op2 + carry
9116  * op2 should be in rdx
9117  * op2 is preserved, all other registers are modified
9118  */
9119 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9120   // assert op2 is rdx
9121   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9122   addq(sum, carry);
9123   adcq(tmp2, 0);
9124   addq(sum, op1);
9125   adcq(tmp2, 0);
9126   movq(carry, tmp2);
9127 }
9128 
9129 /**
9130  * Perform the following multiply add operation:
9131  * carry:sum = sum + op1*op2 + carry
9132  * Preserves op1, op2 and modifies rest of registers
9133  */
9134 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9135   // rdx:rax = op1 * op2
9136   movq(raxReg, op2);
9137   mulq(op1);
9138 
9139   //  rdx:rax = sum + carry + rdx:rax
9140   addq(sum, carry);
9141   adcq(rdxReg, 0);
9142   addq(sum, raxReg);
9143   adcq(rdxReg, 0);
9144 
9145   // carry:sum = rdx:sum
9146   movq(carry, rdxReg);
9147 }
9148 
9149 /**
9150  * Add 64 bit long carry into z[] with carry propogation.
9151  * Preserves z and carry register values and modifies rest of registers.
9152  *
9153  */
9154 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9155   Label L_fourth_loop, L_fourth_loop_exit;
9156 
9157   movl(tmp1, 1);
9158   subl(zlen, 2);
9159   addq(Address(z, zlen, Address::times_4, 0), carry);
9160 
9161   bind(L_fourth_loop);
9162   jccb(Assembler::carryClear, L_fourth_loop_exit);
9163   subl(zlen, 2);
9164   jccb(Assembler::negative, L_fourth_loop_exit);
9165   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9166   jmp(L_fourth_loop);
9167   bind(L_fourth_loop_exit);
9168 }
9169 
9170 /**
9171  * Shift z[] left by 1 bit.
9172  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9173  *
9174  */
9175 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9176 
9177   Label L_fifth_loop, L_fifth_loop_exit;
9178 
9179   // Fifth loop
9180   // Perform primitiveLeftShift(z, zlen, 1)
9181 
9182   const Register prev_carry = tmp1;
9183   const Register new_carry = tmp4;
9184   const Register value = tmp2;
9185   const Register zidx = tmp3;
9186 
9187   // int zidx, carry;
9188   // long value;
9189   // carry = 0;
9190   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9191   //    (carry:value)  = (z[i] << 1) | carry ;
9192   //    z[i] = value;
9193   // }
9194 
9195   movl(zidx, zlen);
9196   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9197 
9198   bind(L_fifth_loop);
9199   decl(zidx);  // Use decl to preserve carry flag
9200   decl(zidx);
9201   jccb(Assembler::negative, L_fifth_loop_exit);
9202 
9203   if (UseBMI2Instructions) {
9204      movq(value, Address(z, zidx, Address::times_4, 0));
9205      rclq(value, 1);
9206      rorxq(value, value, 32);
9207      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9208   }
9209   else {
9210     // clear new_carry
9211     xorl(new_carry, new_carry);
9212 
9213     // Shift z[i] by 1, or in previous carry and save new carry
9214     movq(value, Address(z, zidx, Address::times_4, 0));
9215     shlq(value, 1);
9216     adcl(new_carry, 0);
9217 
9218     orq(value, prev_carry);
9219     rorq(value, 0x20);
9220     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9221 
9222     // Set previous carry = new carry
9223     movl(prev_carry, new_carry);
9224   }
9225   jmp(L_fifth_loop);
9226 
9227   bind(L_fifth_loop_exit);
9228 }
9229 
9230 
9231 /**
9232  * Code for BigInteger::squareToLen() intrinsic
9233  *
9234  * rdi: x
9235  * rsi: len
9236  * r8:  z
9237  * rcx: zlen
9238  * r12: tmp1
9239  * r13: tmp2
9240  * r14: tmp3
9241  * r15: tmp4
9242  * rbx: tmp5
9243  *
9244  */
9245 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) {
9246 
9247   Label L_second_loop, L_second_loop_exit, L_third_loop, L_third_loop_exit, L_last_x, L_multiply;
9248   push(tmp1);
9249   push(tmp2);
9250   push(tmp3);
9251   push(tmp4);
9252   push(tmp5);
9253 
9254   // First loop
9255   // Store the squares, right shifted one bit (i.e., divided by 2).
9256   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9257 
9258   // Add in off-diagonal sums.
9259   //
9260   // Second, third (nested) and fourth loops.
9261   // zlen +=2;
9262   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9263   //    carry = 0;
9264   //    long op2 = x[xidx:xidx+1];
9265   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9266   //       k -= 2;
9267   //       long op1 = x[j:j+1];
9268   //       long sum = z[k:k+1];
9269   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9270   //       z[k:k+1] = sum;
9271   //    }
9272   //    add_one_64(z, k, carry, tmp_regs);
9273   // }
9274 
9275   const Register carry = tmp5;
9276   const Register sum = tmp3;
9277   const Register op1 = tmp4;
9278   Register op2 = tmp2;
9279 
9280   push(zlen);
9281   push(len);
9282   addl(zlen,2);
9283   bind(L_second_loop);
9284   xorq(carry, carry);
9285   subl(zlen, 4);
9286   subl(len, 2);
9287   push(zlen);
9288   push(len);
9289   cmpl(len, 0);
9290   jccb(Assembler::lessEqual, L_second_loop_exit);
9291 
9292   // Multiply an array by one 64 bit long.
9293   if (UseBMI2Instructions) {
9294     op2 = rdxReg;
9295     movq(op2, Address(x, len, Address::times_4,  0));
9296     rorxq(op2, op2, 32);
9297   }
9298   else {
9299     movq(op2, Address(x, len, Address::times_4,  0));
9300     rorq(op2, 32);
9301   }
9302 
9303   bind(L_third_loop);
9304   decrementl(len);
9305   jccb(Assembler::negative, L_third_loop_exit);
9306   decrementl(len);
9307   jccb(Assembler::negative, L_last_x);
9308 
9309   movq(op1, Address(x, len, Address::times_4,  0));
9310   rorq(op1, 32);
9311 
9312   bind(L_multiply);
9313   subl(zlen, 2);
9314   movq(sum, Address(z, zlen, Address::times_4,  0));
9315 
9316   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9317   if (UseBMI2Instructions) {
9318     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9319   }
9320   else {
9321     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9322   }
9323 
9324   movq(Address(z, zlen, Address::times_4, 0), sum);
9325 
9326   jmp(L_third_loop);
9327   bind(L_third_loop_exit);
9328 
9329   // Fourth loop
9330   // Add 64 bit long carry into z with carry propogation.
9331   // Uses offsetted zlen.
9332   add_one_64(z, zlen, carry, tmp1);
9333 
9334   pop(len);
9335   pop(zlen);
9336   jmp(L_second_loop);
9337 
9338   // Next infrequent code is moved outside loops.
9339   bind(L_last_x);
9340   movl(op1, Address(x, 0));
9341   jmp(L_multiply);
9342 
9343   bind(L_second_loop_exit);
9344   pop(len);
9345   pop(zlen);
9346   pop(len);
9347   pop(zlen);
9348 
9349   // Fifth loop
9350   // Shift z left 1 bit.
9351   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9352 
9353   // z[zlen-1] |= x[len-1] & 1;
9354   movl(tmp3, Address(x, len, Address::times_4, -4));
9355   andl(tmp3, 1);
9356   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9357 
9358   pop(tmp5);
9359   pop(tmp4);
9360   pop(tmp3);
9361   pop(tmp2);
9362   pop(tmp1);
9363 }
9364 
9365 /**
9366  * Helper function for mul_add()
9367  * Multiply the in[] by int k and add to out[] starting at offset offs using
9368  * 128 bit by 32 bit multiply and return the carry in tmp5.
9369  * Only quad int aligned length of in[] is operated on in this function.
9370  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9371  * This function preserves out, in and k registers.
9372  * len and offset point to the appropriate index in "in" & "out" correspondingly
9373  * tmp5 has the carry.
9374  * other registers are temporary and are modified.
9375  *
9376  */
9377 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9378   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9379   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9380 
9381   Label L_first_loop, L_first_loop_exit;
9382 
9383   movl(tmp1, len);
9384   shrl(tmp1, 2);
9385 
9386   bind(L_first_loop);
9387   subl(tmp1, 1);
9388   jccb(Assembler::negative, L_first_loop_exit);
9389 
9390   subl(len, 4);
9391   subl(offset, 4);
9392 
9393   Register op2 = tmp2;
9394   const Register sum = tmp3;
9395   const Register op1 = tmp4;
9396   const Register carry = tmp5;
9397 
9398   if (UseBMI2Instructions) {
9399     op2 = rdxReg;
9400   }
9401 
9402   movq(op1, Address(in, len, Address::times_4,  8));
9403   rorq(op1, 32);
9404   movq(sum, Address(out, offset, Address::times_4,  8));
9405   rorq(sum, 32);
9406   if (UseBMI2Instructions) {
9407     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9408   }
9409   else {
9410     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9411   }
9412   // Store back in big endian from little endian
9413   rorq(sum, 0x20);
9414   movq(Address(out, offset, Address::times_4,  8), sum);
9415 
9416   movq(op1, Address(in, len, Address::times_4,  0));
9417   rorq(op1, 32);
9418   movq(sum, Address(out, offset, Address::times_4,  0));
9419   rorq(sum, 32);
9420   if (UseBMI2Instructions) {
9421     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9422   }
9423   else {
9424     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9425   }
9426   // Store back in big endian from little endian
9427   rorq(sum, 0x20);
9428   movq(Address(out, offset, Address::times_4,  0), sum);
9429 
9430   jmp(L_first_loop);
9431   bind(L_first_loop_exit);
9432 }
9433 
9434 /**
9435  * Code for BigInteger::mulAdd() intrinsic
9436  *
9437  * rdi: out
9438  * rsi: in
9439  * r11: offs (out.length - offset)
9440  * rcx: len
9441  * r8:  k
9442  * r12: tmp1
9443  * r13: tmp2
9444  * r14: tmp3
9445  * r15: tmp4
9446  * rbx: tmp5
9447  * Multiply the in[] by word k and add to out[], return the carry in rax
9448  */
9449 void MacroAssembler::mul_add(Register out, Register in, Register offs,
9450    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
9451    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9452 
9453   Label L_carry, L_last_in, L_done;
9454 
9455 // carry = 0;
9456 // for (int j=len-1; j >= 0; j--) {
9457 //    long product = (in[j] & LONG_MASK) * kLong +
9458 //                   (out[offs] & LONG_MASK) + carry;
9459 //    out[offs--] = (int)product;
9460 //    carry = product >>> 32;
9461 // }
9462 //
9463   push(tmp1);
9464   push(tmp2);
9465   push(tmp3);
9466   push(tmp4);
9467   push(tmp5);
9468 
9469   Register op2 = tmp2;
9470   const Register sum = tmp3;
9471   const Register op1 = tmp4;
9472   const Register carry =  tmp5;
9473 
9474   if (UseBMI2Instructions) {
9475     op2 = rdxReg;
9476     movl(op2, k);
9477   }
9478   else {
9479     movl(op2, k);
9480   }
9481 
9482   xorq(carry, carry);
9483 
9484   //First loop
9485 
9486   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
9487   //The carry is in tmp5
9488   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
9489 
9490   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
9491   decrementl(len);
9492   jccb(Assembler::negative, L_carry);
9493   decrementl(len);
9494   jccb(Assembler::negative, L_last_in);
9495 
9496   movq(op1, Address(in, len, Address::times_4,  0));
9497   rorq(op1, 32);
9498 
9499   subl(offs, 2);
9500   movq(sum, Address(out, offs, Address::times_4,  0));
9501   rorq(sum, 32);
9502 
9503   if (UseBMI2Instructions) {
9504     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9505   }
9506   else {
9507     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9508   }
9509 
9510   // Store back in big endian from little endian
9511   rorq(sum, 0x20);
9512   movq(Address(out, offs, Address::times_4,  0), sum);
9513 
9514   testl(len, len);
9515   jccb(Assembler::zero, L_carry);
9516 
9517   //Multiply the last in[] entry, if any
9518   bind(L_last_in);
9519   movl(op1, Address(in, 0));
9520   movl(sum, Address(out, offs, Address::times_4,  -4));
9521 
9522   movl(raxReg, k);
9523   mull(op1); //tmp4 * eax -> edx:eax
9524   addl(sum, carry);
9525   adcl(rdxReg, 0);
9526   addl(sum, raxReg);
9527   adcl(rdxReg, 0);
9528   movl(carry, rdxReg);
9529 
9530   movl(Address(out, offs, Address::times_4,  -4), sum);
9531 
9532   bind(L_carry);
9533   //return tmp5/carry as carry in rax
9534   movl(rax, carry);
9535 
9536   bind(L_done);
9537   pop(tmp5);
9538   pop(tmp4);
9539   pop(tmp3);
9540   pop(tmp2);
9541   pop(tmp1);
9542 }
9543 #endif
9544 
9545 /**
9546  * Emits code to update CRC-32 with a byte value according to constants in table
9547  *
9548  * @param [in,out]crc   Register containing the crc.
9549  * @param [in]val       Register containing the byte to fold into the CRC.
9550  * @param [in]table     Register containing the table of crc constants.
9551  *
9552  * uint32_t crc;
9553  * val = crc_table[(val ^ crc) & 0xFF];
9554  * crc = val ^ (crc >> 8);
9555  *
9556  */
9557 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
9558   xorl(val, crc);
9559   andl(val, 0xFF);
9560   shrl(crc, 8); // unsigned shift
9561   xorl(crc, Address(table, val, Address::times_4, 0));
9562 }
9563 
9564 /**
9565 * Fold four 128-bit data chunks
9566 */
9567 void MacroAssembler::fold_128bit_crc32_avx512(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9568   evpclmulhdq(xtmp, xK, xcrc, Assembler::AVX_512bit); // [123:64]
9569   evpclmulldq(xcrc, xK, xcrc, Assembler::AVX_512bit); // [63:0]
9570   evpxorq(xcrc, xcrc, Address(buf, offset), Assembler::AVX_512bit /* vector_len */);
9571   evpxorq(xcrc, xcrc, xtmp, Assembler::AVX_512bit /* vector_len */);
9572 }
9573 
9574 /**
9575  * Fold 128-bit data chunk
9576  */
9577 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9578   if (UseAVX > 0) {
9579     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
9580     vpclmulldq(xcrc, xK, xcrc); // [63:0]
9581     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
9582     pxor(xcrc, xtmp);
9583   } else {
9584     movdqa(xtmp, xcrc);
9585     pclmulhdq(xtmp, xK);   // [123:64]
9586     pclmulldq(xcrc, xK);   // [63:0]
9587     pxor(xcrc, xtmp);
9588     movdqu(xtmp, Address(buf, offset));
9589     pxor(xcrc, xtmp);
9590   }
9591 }
9592 
9593 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
9594   if (UseAVX > 0) {
9595     vpclmulhdq(xtmp, xK, xcrc);
9596     vpclmulldq(xcrc, xK, xcrc);
9597     pxor(xcrc, xbuf);
9598     pxor(xcrc, xtmp);
9599   } else {
9600     movdqa(xtmp, xcrc);
9601     pclmulhdq(xtmp, xK);
9602     pclmulldq(xcrc, xK);
9603     pxor(xcrc, xbuf);
9604     pxor(xcrc, xtmp);
9605   }
9606 }
9607 
9608 /**
9609  * 8-bit folds to compute 32-bit CRC
9610  *
9611  * uint64_t xcrc;
9612  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
9613  */
9614 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
9615   movdl(tmp, xcrc);
9616   andl(tmp, 0xFF);
9617   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
9618   psrldq(xcrc, 1); // unsigned shift one byte
9619   pxor(xcrc, xtmp);
9620 }
9621 
9622 /**
9623  * uint32_t crc;
9624  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
9625  */
9626 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
9627   movl(tmp, crc);
9628   andl(tmp, 0xFF);
9629   shrl(crc, 8);
9630   xorl(crc, Address(table, tmp, Address::times_4, 0));
9631 }
9632 
9633 /**
9634  * @param crc   register containing existing CRC (32-bit)
9635  * @param buf   register pointing to input byte buffer (byte*)
9636  * @param len   register containing number of bytes
9637  * @param table register that will contain address of CRC table
9638  * @param tmp   scratch register
9639  */
9640 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
9641   assert_different_registers(crc, buf, len, table, tmp, rax);
9642 
9643   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
9644   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
9645 
9646   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
9647   // context for the registers used, where all instructions below are using 128-bit mode
9648   // On EVEX without VL and BW, these instructions will all be AVX.
9649   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
9650   notl(crc); // ~crc
9651   cmpl(len, 16);
9652   jcc(Assembler::less, L_tail);
9653 
9654   // Align buffer to 16 bytes
9655   movl(tmp, buf);
9656   andl(tmp, 0xF);
9657   jccb(Assembler::zero, L_aligned);
9658   subl(tmp,  16);
9659   addl(len, tmp);
9660 
9661   align(4);
9662   BIND(L_align_loop);
9663   movsbl(rax, Address(buf, 0)); // load byte with sign extension
9664   update_byte_crc32(crc, rax, table);
9665   increment(buf);
9666   incrementl(tmp);
9667   jccb(Assembler::less, L_align_loop);
9668 
9669   BIND(L_aligned);
9670   movl(tmp, len); // save
9671   shrl(len, 4);
9672   jcc(Assembler::zero, L_tail_restore);
9673 
9674   // Fold total 512 bits of polynomial on each iteration
9675   if (VM_Version::supports_vpclmulqdq()) {
9676     Label Parallel_loop, L_No_Parallel;
9677 
9678     cmpl(len, 8);
9679     jccb(Assembler::less, L_No_Parallel);
9680 
9681     movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9682     evmovdquq(xmm1, Address(buf, 0), Assembler::AVX_512bit);
9683     movdl(xmm5, crc);
9684     evpxorq(xmm1, xmm1, xmm5, Assembler::AVX_512bit);
9685     addptr(buf, 64);
9686     subl(len, 7);
9687     evshufi64x2(xmm0, xmm0, xmm0, 0x00, Assembler::AVX_512bit); //propagate the mask from 128 bits to 512 bits
9688 
9689     BIND(Parallel_loop);
9690     fold_128bit_crc32_avx512(xmm1, xmm0, xmm5, buf, 0);
9691     addptr(buf, 64);
9692     subl(len, 4);
9693     jcc(Assembler::greater, Parallel_loop);
9694 
9695     vextracti64x2(xmm2, xmm1, 0x01);
9696     vextracti64x2(xmm3, xmm1, 0x02);
9697     vextracti64x2(xmm4, xmm1, 0x03);
9698     jmp(L_fold_512b);
9699 
9700     BIND(L_No_Parallel);
9701   }
9702   // Fold crc into first bytes of vector
9703   movdqa(xmm1, Address(buf, 0));
9704   movdl(rax, xmm1);
9705   xorl(crc, rax);
9706   if (VM_Version::supports_sse4_1()) {
9707     pinsrd(xmm1, crc, 0);
9708   } else {
9709     pinsrw(xmm1, crc, 0);
9710     shrl(crc, 16);
9711     pinsrw(xmm1, crc, 1);
9712   }
9713   addptr(buf, 16);
9714   subl(len, 4); // len > 0
9715   jcc(Assembler::less, L_fold_tail);
9716 
9717   movdqa(xmm2, Address(buf,  0));
9718   movdqa(xmm3, Address(buf, 16));
9719   movdqa(xmm4, Address(buf, 32));
9720   addptr(buf, 48);
9721   subl(len, 3);
9722   jcc(Assembler::lessEqual, L_fold_512b);
9723 
9724   // Fold total 512 bits of polynomial on each iteration,
9725   // 128 bits per each of 4 parallel streams.
9726   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9727 
9728   align(32);
9729   BIND(L_fold_512b_loop);
9730   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
9731   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
9732   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
9733   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
9734   addptr(buf, 64);
9735   subl(len, 4);
9736   jcc(Assembler::greater, L_fold_512b_loop);
9737 
9738   // Fold 512 bits to 128 bits.
9739   BIND(L_fold_512b);
9740   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
9741   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
9742   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
9743   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
9744 
9745   // Fold the rest of 128 bits data chunks
9746   BIND(L_fold_tail);
9747   addl(len, 3);
9748   jccb(Assembler::lessEqual, L_fold_128b);
9749   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
9750 
9751   BIND(L_fold_tail_loop);
9752   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
9753   addptr(buf, 16);
9754   decrementl(len);
9755   jccb(Assembler::greater, L_fold_tail_loop);
9756 
9757   // Fold 128 bits in xmm1 down into 32 bits in crc register.
9758   BIND(L_fold_128b);
9759   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
9760   if (UseAVX > 0) {
9761     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
9762     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
9763     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
9764   } else {
9765     movdqa(xmm2, xmm0);
9766     pclmulqdq(xmm2, xmm1, 0x1);
9767     movdqa(xmm3, xmm0);
9768     pand(xmm3, xmm2);
9769     pclmulqdq(xmm0, xmm3, 0x1);
9770   }
9771   psrldq(xmm1, 8);
9772   psrldq(xmm2, 4);
9773   pxor(xmm0, xmm1);
9774   pxor(xmm0, xmm2);
9775 
9776   // 8 8-bit folds to compute 32-bit CRC.
9777   for (int j = 0; j < 4; j++) {
9778     fold_8bit_crc32(xmm0, table, xmm1, rax);
9779   }
9780   movdl(crc, xmm0); // mov 32 bits to general register
9781   for (int j = 0; j < 4; j++) {
9782     fold_8bit_crc32(crc, table, rax);
9783   }
9784 
9785   BIND(L_tail_restore);
9786   movl(len, tmp); // restore
9787   BIND(L_tail);
9788   andl(len, 0xf);
9789   jccb(Assembler::zero, L_exit);
9790 
9791   // Fold the rest of bytes
9792   align(4);
9793   BIND(L_tail_loop);
9794   movsbl(rax, Address(buf, 0)); // load byte with sign extension
9795   update_byte_crc32(crc, rax, table);
9796   increment(buf);
9797   decrementl(len);
9798   jccb(Assembler::greater, L_tail_loop);
9799 
9800   BIND(L_exit);
9801   notl(crc); // ~c
9802 }
9803 
9804 #ifdef _LP64
9805 // S. Gueron / Information Processing Letters 112 (2012) 184
9806 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
9807 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
9808 // Output: the 64-bit carry-less product of B * CONST
9809 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
9810                                      Register tmp1, Register tmp2, Register tmp3) {
9811   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
9812   if (n > 0) {
9813     addq(tmp3, n * 256 * 8);
9814   }
9815   //    Q1 = TABLEExt[n][B & 0xFF];
9816   movl(tmp1, in);
9817   andl(tmp1, 0x000000FF);
9818   shll(tmp1, 3);
9819   addq(tmp1, tmp3);
9820   movq(tmp1, Address(tmp1, 0));
9821 
9822   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
9823   movl(tmp2, in);
9824   shrl(tmp2, 8);
9825   andl(tmp2, 0x000000FF);
9826   shll(tmp2, 3);
9827   addq(tmp2, tmp3);
9828   movq(tmp2, Address(tmp2, 0));
9829 
9830   shlq(tmp2, 8);
9831   xorq(tmp1, tmp2);
9832 
9833   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
9834   movl(tmp2, in);
9835   shrl(tmp2, 16);
9836   andl(tmp2, 0x000000FF);
9837   shll(tmp2, 3);
9838   addq(tmp2, tmp3);
9839   movq(tmp2, Address(tmp2, 0));
9840 
9841   shlq(tmp2, 16);
9842   xorq(tmp1, tmp2);
9843 
9844   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
9845   shrl(in, 24);
9846   andl(in, 0x000000FF);
9847   shll(in, 3);
9848   addq(in, tmp3);
9849   movq(in, Address(in, 0));
9850 
9851   shlq(in, 24);
9852   xorq(in, tmp1);
9853   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
9854 }
9855 
9856 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
9857                                       Register in_out,
9858                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
9859                                       XMMRegister w_xtmp2,
9860                                       Register tmp1,
9861                                       Register n_tmp2, Register n_tmp3) {
9862   if (is_pclmulqdq_supported) {
9863     movdl(w_xtmp1, in_out); // modified blindly
9864 
9865     movl(tmp1, const_or_pre_comp_const_index);
9866     movdl(w_xtmp2, tmp1);
9867     pclmulqdq(w_xtmp1, w_xtmp2, 0);
9868 
9869     movdq(in_out, w_xtmp1);
9870   } else {
9871     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
9872   }
9873 }
9874 
9875 // Recombination Alternative 2: No bit-reflections
9876 // T1 = (CRC_A * U1) << 1
9877 // T2 = (CRC_B * U2) << 1
9878 // C1 = T1 >> 32
9879 // C2 = T2 >> 32
9880 // T1 = T1 & 0xFFFFFFFF
9881 // T2 = T2 & 0xFFFFFFFF
9882 // T1 = CRC32(0, T1)
9883 // T2 = CRC32(0, T2)
9884 // C1 = C1 ^ T1
9885 // C2 = C2 ^ T2
9886 // CRC = C1 ^ C2 ^ CRC_C
9887 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,
9888                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9889                                      Register tmp1, Register tmp2,
9890                                      Register n_tmp3) {
9891   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9892   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9893   shlq(in_out, 1);
9894   movl(tmp1, in_out);
9895   shrq(in_out, 32);
9896   xorl(tmp2, tmp2);
9897   crc32(tmp2, tmp1, 4);
9898   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
9899   shlq(in1, 1);
9900   movl(tmp1, in1);
9901   shrq(in1, 32);
9902   xorl(tmp2, tmp2);
9903   crc32(tmp2, tmp1, 4);
9904   xorl(in1, tmp2);
9905   xorl(in_out, in1);
9906   xorl(in_out, in2);
9907 }
9908 
9909 // Set N to predefined value
9910 // Subtract from a lenght of a buffer
9911 // execute in a loop:
9912 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
9913 // for i = 1 to N do
9914 //  CRC_A = CRC32(CRC_A, A[i])
9915 //  CRC_B = CRC32(CRC_B, B[i])
9916 //  CRC_C = CRC32(CRC_C, C[i])
9917 // end for
9918 // Recombine
9919 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,
9920                                        Register in_out1, Register in_out2, Register in_out3,
9921                                        Register tmp1, Register tmp2, Register tmp3,
9922                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9923                                        Register tmp4, Register tmp5,
9924                                        Register n_tmp6) {
9925   Label L_processPartitions;
9926   Label L_processPartition;
9927   Label L_exit;
9928 
9929   bind(L_processPartitions);
9930   cmpl(in_out1, 3 * size);
9931   jcc(Assembler::less, L_exit);
9932     xorl(tmp1, tmp1);
9933     xorl(tmp2, tmp2);
9934     movq(tmp3, in_out2);
9935     addq(tmp3, size);
9936 
9937     bind(L_processPartition);
9938       crc32(in_out3, Address(in_out2, 0), 8);
9939       crc32(tmp1, Address(in_out2, size), 8);
9940       crc32(tmp2, Address(in_out2, size * 2), 8);
9941       addq(in_out2, 8);
9942       cmpq(in_out2, tmp3);
9943       jcc(Assembler::less, L_processPartition);
9944     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
9945             w_xtmp1, w_xtmp2, w_xtmp3,
9946             tmp4, tmp5,
9947             n_tmp6);
9948     addq(in_out2, 2 * size);
9949     subl(in_out1, 3 * size);
9950     jmp(L_processPartitions);
9951 
9952   bind(L_exit);
9953 }
9954 #else
9955 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
9956                                      Register tmp1, Register tmp2, Register tmp3,
9957                                      XMMRegister xtmp1, XMMRegister xtmp2) {
9958   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
9959   if (n > 0) {
9960     addl(tmp3, n * 256 * 8);
9961   }
9962   //    Q1 = TABLEExt[n][B & 0xFF];
9963   movl(tmp1, in_out);
9964   andl(tmp1, 0x000000FF);
9965   shll(tmp1, 3);
9966   addl(tmp1, tmp3);
9967   movq(xtmp1, Address(tmp1, 0));
9968 
9969   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
9970   movl(tmp2, in_out);
9971   shrl(tmp2, 8);
9972   andl(tmp2, 0x000000FF);
9973   shll(tmp2, 3);
9974   addl(tmp2, tmp3);
9975   movq(xtmp2, Address(tmp2, 0));
9976 
9977   psllq(xtmp2, 8);
9978   pxor(xtmp1, xtmp2);
9979 
9980   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
9981   movl(tmp2, in_out);
9982   shrl(tmp2, 16);
9983   andl(tmp2, 0x000000FF);
9984   shll(tmp2, 3);
9985   addl(tmp2, tmp3);
9986   movq(xtmp2, Address(tmp2, 0));
9987 
9988   psllq(xtmp2, 16);
9989   pxor(xtmp1, xtmp2);
9990 
9991   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
9992   shrl(in_out, 24);
9993   andl(in_out, 0x000000FF);
9994   shll(in_out, 3);
9995   addl(in_out, tmp3);
9996   movq(xtmp2, Address(in_out, 0));
9997 
9998   psllq(xtmp2, 24);
9999   pxor(xtmp1, xtmp2); // Result in CXMM
10000   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10001 }
10002 
10003 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10004                                       Register in_out,
10005                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10006                                       XMMRegister w_xtmp2,
10007                                       Register tmp1,
10008                                       Register n_tmp2, Register n_tmp3) {
10009   if (is_pclmulqdq_supported) {
10010     movdl(w_xtmp1, in_out);
10011 
10012     movl(tmp1, const_or_pre_comp_const_index);
10013     movdl(w_xtmp2, tmp1);
10014     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10015     // Keep result in XMM since GPR is 32 bit in length
10016   } else {
10017     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10018   }
10019 }
10020 
10021 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,
10022                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10023                                      Register tmp1, Register tmp2,
10024                                      Register n_tmp3) {
10025   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10026   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10027 
10028   psllq(w_xtmp1, 1);
10029   movdl(tmp1, w_xtmp1);
10030   psrlq(w_xtmp1, 32);
10031   movdl(in_out, w_xtmp1);
10032 
10033   xorl(tmp2, tmp2);
10034   crc32(tmp2, tmp1, 4);
10035   xorl(in_out, tmp2);
10036 
10037   psllq(w_xtmp2, 1);
10038   movdl(tmp1, w_xtmp2);
10039   psrlq(w_xtmp2, 32);
10040   movdl(in1, w_xtmp2);
10041 
10042   xorl(tmp2, tmp2);
10043   crc32(tmp2, tmp1, 4);
10044   xorl(in1, tmp2);
10045   xorl(in_out, in1);
10046   xorl(in_out, in2);
10047 }
10048 
10049 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,
10050                                        Register in_out1, Register in_out2, Register in_out3,
10051                                        Register tmp1, Register tmp2, Register tmp3,
10052                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10053                                        Register tmp4, Register tmp5,
10054                                        Register n_tmp6) {
10055   Label L_processPartitions;
10056   Label L_processPartition;
10057   Label L_exit;
10058 
10059   bind(L_processPartitions);
10060   cmpl(in_out1, 3 * size);
10061   jcc(Assembler::less, L_exit);
10062     xorl(tmp1, tmp1);
10063     xorl(tmp2, tmp2);
10064     movl(tmp3, in_out2);
10065     addl(tmp3, size);
10066 
10067     bind(L_processPartition);
10068       crc32(in_out3, Address(in_out2, 0), 4);
10069       crc32(tmp1, Address(in_out2, size), 4);
10070       crc32(tmp2, Address(in_out2, size*2), 4);
10071       crc32(in_out3, Address(in_out2, 0+4), 4);
10072       crc32(tmp1, Address(in_out2, size+4), 4);
10073       crc32(tmp2, Address(in_out2, size*2+4), 4);
10074       addl(in_out2, 8);
10075       cmpl(in_out2, tmp3);
10076       jcc(Assembler::less, L_processPartition);
10077 
10078         push(tmp3);
10079         push(in_out1);
10080         push(in_out2);
10081         tmp4 = tmp3;
10082         tmp5 = in_out1;
10083         n_tmp6 = in_out2;
10084 
10085       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10086             w_xtmp1, w_xtmp2, w_xtmp3,
10087             tmp4, tmp5,
10088             n_tmp6);
10089 
10090         pop(in_out2);
10091         pop(in_out1);
10092         pop(tmp3);
10093 
10094     addl(in_out2, 2 * size);
10095     subl(in_out1, 3 * size);
10096     jmp(L_processPartitions);
10097 
10098   bind(L_exit);
10099 }
10100 #endif //LP64
10101 
10102 #ifdef _LP64
10103 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10104 // Input: A buffer I of L bytes.
10105 // Output: the CRC32C value of the buffer.
10106 // Notations:
10107 // Write L = 24N + r, with N = floor (L/24).
10108 // r = L mod 24 (0 <= r < 24).
10109 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10110 // N quadwords, and R consists of r bytes.
10111 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10112 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10113 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10114 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10115 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10116                                           Register tmp1, Register tmp2, Register tmp3,
10117                                           Register tmp4, Register tmp5, Register tmp6,
10118                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10119                                           bool is_pclmulqdq_supported) {
10120   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10121   Label L_wordByWord;
10122   Label L_byteByByteProlog;
10123   Label L_byteByByte;
10124   Label L_exit;
10125 
10126   if (is_pclmulqdq_supported ) {
10127     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10128     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10129 
10130     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10131     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10132 
10133     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10134     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10135     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10136   } else {
10137     const_or_pre_comp_const_index[0] = 1;
10138     const_or_pre_comp_const_index[1] = 0;
10139 
10140     const_or_pre_comp_const_index[2] = 3;
10141     const_or_pre_comp_const_index[3] = 2;
10142 
10143     const_or_pre_comp_const_index[4] = 5;
10144     const_or_pre_comp_const_index[5] = 4;
10145    }
10146   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10147                     in2, in1, in_out,
10148                     tmp1, tmp2, tmp3,
10149                     w_xtmp1, w_xtmp2, w_xtmp3,
10150                     tmp4, tmp5,
10151                     tmp6);
10152   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10153                     in2, in1, in_out,
10154                     tmp1, tmp2, tmp3,
10155                     w_xtmp1, w_xtmp2, w_xtmp3,
10156                     tmp4, tmp5,
10157                     tmp6);
10158   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10159                     in2, in1, in_out,
10160                     tmp1, tmp2, tmp3,
10161                     w_xtmp1, w_xtmp2, w_xtmp3,
10162                     tmp4, tmp5,
10163                     tmp6);
10164   movl(tmp1, in2);
10165   andl(tmp1, 0x00000007);
10166   negl(tmp1);
10167   addl(tmp1, in2);
10168   addq(tmp1, in1);
10169 
10170   BIND(L_wordByWord);
10171   cmpq(in1, tmp1);
10172   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10173     crc32(in_out, Address(in1, 0), 4);
10174     addq(in1, 4);
10175     jmp(L_wordByWord);
10176 
10177   BIND(L_byteByByteProlog);
10178   andl(in2, 0x00000007);
10179   movl(tmp2, 1);
10180 
10181   BIND(L_byteByByte);
10182   cmpl(tmp2, in2);
10183   jccb(Assembler::greater, L_exit);
10184     crc32(in_out, Address(in1, 0), 1);
10185     incq(in1);
10186     incl(tmp2);
10187     jmp(L_byteByByte);
10188 
10189   BIND(L_exit);
10190 }
10191 #else
10192 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10193                                           Register tmp1, Register  tmp2, Register tmp3,
10194                                           Register tmp4, Register  tmp5, Register tmp6,
10195                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10196                                           bool is_pclmulqdq_supported) {
10197   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10198   Label L_wordByWord;
10199   Label L_byteByByteProlog;
10200   Label L_byteByByte;
10201   Label L_exit;
10202 
10203   if (is_pclmulqdq_supported) {
10204     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10205     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10206 
10207     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10208     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10209 
10210     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10211     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10212   } else {
10213     const_or_pre_comp_const_index[0] = 1;
10214     const_or_pre_comp_const_index[1] = 0;
10215 
10216     const_or_pre_comp_const_index[2] = 3;
10217     const_or_pre_comp_const_index[3] = 2;
10218 
10219     const_or_pre_comp_const_index[4] = 5;
10220     const_or_pre_comp_const_index[5] = 4;
10221   }
10222   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10223                     in2, in1, in_out,
10224                     tmp1, tmp2, tmp3,
10225                     w_xtmp1, w_xtmp2, w_xtmp3,
10226                     tmp4, tmp5,
10227                     tmp6);
10228   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10229                     in2, in1, in_out,
10230                     tmp1, tmp2, tmp3,
10231                     w_xtmp1, w_xtmp2, w_xtmp3,
10232                     tmp4, tmp5,
10233                     tmp6);
10234   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10235                     in2, in1, in_out,
10236                     tmp1, tmp2, tmp3,
10237                     w_xtmp1, w_xtmp2, w_xtmp3,
10238                     tmp4, tmp5,
10239                     tmp6);
10240   movl(tmp1, in2);
10241   andl(tmp1, 0x00000007);
10242   negl(tmp1);
10243   addl(tmp1, in2);
10244   addl(tmp1, in1);
10245 
10246   BIND(L_wordByWord);
10247   cmpl(in1, tmp1);
10248   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10249     crc32(in_out, Address(in1,0), 4);
10250     addl(in1, 4);
10251     jmp(L_wordByWord);
10252 
10253   BIND(L_byteByByteProlog);
10254   andl(in2, 0x00000007);
10255   movl(tmp2, 1);
10256 
10257   BIND(L_byteByByte);
10258   cmpl(tmp2, in2);
10259   jccb(Assembler::greater, L_exit);
10260     movb(tmp1, Address(in1, 0));
10261     crc32(in_out, tmp1, 1);
10262     incl(in1);
10263     incl(tmp2);
10264     jmp(L_byteByByte);
10265 
10266   BIND(L_exit);
10267 }
10268 #endif // LP64
10269 #undef BIND
10270 #undef BLOCK_COMMENT
10271 
10272 // Compress char[] array to byte[].
10273 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10274 //   @HotSpotIntrinsicCandidate
10275 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
10276 //     for (int i = 0; i < len; i++) {
10277 //       int c = src[srcOff++];
10278 //       if (c >>> 8 != 0) {
10279 //         return 0;
10280 //       }
10281 //       dst[dstOff++] = (byte)c;
10282 //     }
10283 //     return len;
10284 //   }
10285 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10286   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10287   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10288   Register tmp5, Register result) {
10289   Label copy_chars_loop, return_length, return_zero, done;
10290 
10291   // rsi: src
10292   // rdi: dst
10293   // rdx: len
10294   // rcx: tmp5
10295   // rax: result
10296 
10297   // rsi holds start addr of source char[] to be compressed
10298   // rdi holds start addr of destination byte[]
10299   // rdx holds length
10300 
10301   assert(len != result, "");
10302 
10303   // save length for return
10304   push(len);
10305 
10306   if ((UseAVX > 2) && // AVX512
10307     VM_Version::supports_avx512vlbw() &&
10308     VM_Version::supports_bmi2()) {
10309 
10310     Label copy_32_loop, copy_loop_tail, below_threshold;
10311 
10312     // alignment
10313     Label post_alignment;
10314 
10315     // if length of the string is less than 16, handle it in an old fashioned way
10316     testl(len, -32);
10317     jcc(Assembler::zero, below_threshold);
10318 
10319     // First check whether a character is compressable ( <= 0xFF).
10320     // Create mask to test for Unicode chars inside zmm vector
10321     movl(result, 0x00FF);
10322     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
10323 
10324     testl(len, -64);
10325     jcc(Assembler::zero, post_alignment);
10326 
10327     movl(tmp5, dst);
10328     andl(tmp5, (32 - 1));
10329     negl(tmp5);
10330     andl(tmp5, (32 - 1));
10331 
10332     // bail out when there is nothing to be done
10333     testl(tmp5, 0xFFFFFFFF);
10334     jcc(Assembler::zero, post_alignment);
10335 
10336     // ~(~0 << len), where len is the # of remaining elements to process
10337     movl(result, 0xFFFFFFFF);
10338     shlxl(result, result, tmp5);
10339     notl(result);
10340     kmovdl(k3, result);
10341 
10342     evmovdquw(tmp1Reg, k3, Address(src, 0), Assembler::AVX_512bit);
10343     evpcmpuw(k2, k3, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10344     ktestd(k2, k3);
10345     jcc(Assembler::carryClear, return_zero);
10346 
10347     evpmovwb(Address(dst, 0), k3, tmp1Reg, Assembler::AVX_512bit);
10348 
10349     addptr(src, tmp5);
10350     addptr(src, tmp5);
10351     addptr(dst, tmp5);
10352     subl(len, tmp5);
10353 
10354     bind(post_alignment);
10355     // end of alignment
10356 
10357     movl(tmp5, len);
10358     andl(tmp5, (32 - 1));    // tail count (in chars)
10359     andl(len, ~(32 - 1));    // vector count (in chars)
10360     jcc(Assembler::zero, copy_loop_tail);
10361 
10362     lea(src, Address(src, len, Address::times_2));
10363     lea(dst, Address(dst, len, Address::times_1));
10364     negptr(len);
10365 
10366     bind(copy_32_loop);
10367     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
10368     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10369     kortestdl(k2, k2);
10370     jcc(Assembler::carryClear, return_zero);
10371 
10372     // All elements in current processed chunk are valid candidates for
10373     // compression. Write a truncated byte elements to the memory.
10374     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
10375     addptr(len, 32);
10376     jcc(Assembler::notZero, copy_32_loop);
10377 
10378     bind(copy_loop_tail);
10379     // bail out when there is nothing to be done
10380     testl(tmp5, 0xFFFFFFFF);
10381     jcc(Assembler::zero, return_length);
10382 
10383     movl(len, tmp5);
10384 
10385     // ~(~0 << len), where len is the # of remaining elements to process
10386     movl(result, 0xFFFFFFFF);
10387     shlxl(result, result, len);
10388     notl(result);
10389 
10390     kmovdl(k3, result);
10391 
10392     evmovdquw(tmp1Reg, k3, Address(src, 0), Assembler::AVX_512bit);
10393     evpcmpuw(k2, k3, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10394     ktestd(k2, k3);
10395     jcc(Assembler::carryClear, return_zero);
10396 
10397     evpmovwb(Address(dst, 0), k3, tmp1Reg, Assembler::AVX_512bit);
10398     jmp(return_length);
10399 
10400     bind(below_threshold);
10401   }
10402 
10403   if (UseSSE42Intrinsics) {
10404     Label copy_32_loop, copy_16, copy_tail;
10405 
10406     movl(result, len);
10407 
10408     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
10409 
10410     // vectored compression
10411     andl(len, 0xfffffff0);    // vector count (in chars)
10412     andl(result, 0x0000000f);    // tail count (in chars)
10413     testl(len, len);
10414     jcc(Assembler::zero, copy_16);
10415 
10416     // compress 16 chars per iter
10417     movdl(tmp1Reg, tmp5);
10418     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10419     pxor(tmp4Reg, tmp4Reg);
10420 
10421     lea(src, Address(src, len, Address::times_2));
10422     lea(dst, Address(dst, len, Address::times_1));
10423     negptr(len);
10424 
10425     bind(copy_32_loop);
10426     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
10427     por(tmp4Reg, tmp2Reg);
10428     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
10429     por(tmp4Reg, tmp3Reg);
10430     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
10431     jcc(Assembler::notZero, return_zero);
10432     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
10433     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
10434     addptr(len, 16);
10435     jcc(Assembler::notZero, copy_32_loop);
10436 
10437     // compress next vector of 8 chars (if any)
10438     bind(copy_16);
10439     movl(len, result);
10440     andl(len, 0xfffffff8);    // vector count (in chars)
10441     andl(result, 0x00000007);    // tail count (in chars)
10442     testl(len, len);
10443     jccb(Assembler::zero, copy_tail);
10444 
10445     movdl(tmp1Reg, tmp5);
10446     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10447     pxor(tmp3Reg, tmp3Reg);
10448 
10449     movdqu(tmp2Reg, Address(src, 0));
10450     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
10451     jccb(Assembler::notZero, return_zero);
10452     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
10453     movq(Address(dst, 0), tmp2Reg);
10454     addptr(src, 16);
10455     addptr(dst, 8);
10456 
10457     bind(copy_tail);
10458     movl(len, result);
10459   }
10460   // compress 1 char per iter
10461   testl(len, len);
10462   jccb(Assembler::zero, return_length);
10463   lea(src, Address(src, len, Address::times_2));
10464   lea(dst, Address(dst, len, Address::times_1));
10465   negptr(len);
10466 
10467   bind(copy_chars_loop);
10468   load_unsigned_short(result, Address(src, len, Address::times_2));
10469   testl(result, 0xff00);      // check if Unicode char
10470   jccb(Assembler::notZero, return_zero);
10471   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
10472   increment(len);
10473   jcc(Assembler::notZero, copy_chars_loop);
10474 
10475   // if compression succeeded, return length
10476   bind(return_length);
10477   pop(result);
10478   jmpb(done);
10479 
10480   // if compression failed, return 0
10481   bind(return_zero);
10482   xorl(result, result);
10483   addptr(rsp, wordSize);
10484 
10485   bind(done);
10486 }
10487 
10488 // Inflate byte[] array to char[].
10489 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
10490 //   @HotSpotIntrinsicCandidate
10491 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
10492 //     for (int i = 0; i < len; i++) {
10493 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
10494 //     }
10495 //   }
10496 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
10497   XMMRegister tmp1, Register tmp2) {
10498   Label copy_chars_loop, done, below_threshold;
10499   // rsi: src
10500   // rdi: dst
10501   // rdx: len
10502   // rcx: tmp2
10503 
10504   // rsi holds start addr of source byte[] to be inflated
10505   // rdi holds start addr of destination char[]
10506   // rdx holds length
10507   assert_different_registers(src, dst, len, tmp2);
10508 
10509   if ((UseAVX > 2) && // AVX512
10510     VM_Version::supports_avx512vlbw() &&
10511     VM_Version::supports_bmi2()) {
10512 
10513     Label copy_32_loop, copy_tail;
10514     Register tmp3_aliased = len;
10515 
10516     // if length of the string is less than 16, handle it in an old fashioned way
10517     testl(len, -16);
10518     jcc(Assembler::zero, below_threshold);
10519 
10520     // In order to use only one arithmetic operation for the main loop we use
10521     // this pre-calculation
10522     movl(tmp2, len);
10523     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
10524     andl(len, -32);     // vector count
10525     jccb(Assembler::zero, copy_tail);
10526 
10527     lea(src, Address(src, len, Address::times_1));
10528     lea(dst, Address(dst, len, Address::times_2));
10529     negptr(len);
10530 
10531 
10532     // inflate 32 chars per iter
10533     bind(copy_32_loop);
10534     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
10535     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
10536     addptr(len, 32);
10537     jcc(Assembler::notZero, copy_32_loop);
10538 
10539     bind(copy_tail);
10540     // bail out when there is nothing to be done
10541     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
10542     jcc(Assembler::zero, done);
10543 
10544     // ~(~0 << length), where length is the # of remaining elements to process
10545     movl(tmp3_aliased, -1);
10546     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
10547     notl(tmp3_aliased);
10548     kmovdl(k2, tmp3_aliased);
10549     evpmovzxbw(tmp1, k2, Address(src, 0), Assembler::AVX_512bit);
10550     evmovdquw(Address(dst, 0), k2, tmp1, Assembler::AVX_512bit);
10551 
10552     jmp(done);
10553   }
10554   if (UseSSE42Intrinsics) {
10555     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
10556 
10557     movl(tmp2, len);
10558 
10559     if (UseAVX > 1) {
10560       andl(tmp2, (16 - 1));
10561       andl(len, -16);
10562       jccb(Assembler::zero, copy_new_tail);
10563     } else {
10564       andl(tmp2, 0x00000007);   // tail count (in chars)
10565       andl(len, 0xfffffff8);    // vector count (in chars)
10566       jccb(Assembler::zero, copy_tail);
10567     }
10568 
10569     // vectored inflation
10570     lea(src, Address(src, len, Address::times_1));
10571     lea(dst, Address(dst, len, Address::times_2));
10572     negptr(len);
10573 
10574     if (UseAVX > 1) {
10575       bind(copy_16_loop);
10576       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
10577       vmovdqu(Address(dst, len, Address::times_2), tmp1);
10578       addptr(len, 16);
10579       jcc(Assembler::notZero, copy_16_loop);
10580 
10581       bind(below_threshold);
10582       bind(copy_new_tail);
10583       if ((UseAVX > 2) &&
10584         VM_Version::supports_avx512vlbw() &&
10585         VM_Version::supports_bmi2()) {
10586         movl(tmp2, len);
10587       } else {
10588         movl(len, tmp2);
10589       }
10590       andl(tmp2, 0x00000007);
10591       andl(len, 0xFFFFFFF8);
10592       jccb(Assembler::zero, copy_tail);
10593 
10594       pmovzxbw(tmp1, Address(src, 0));
10595       movdqu(Address(dst, 0), tmp1);
10596       addptr(src, 8);
10597       addptr(dst, 2 * 8);
10598 
10599       jmp(copy_tail, true);
10600     }
10601 
10602     // inflate 8 chars per iter
10603     bind(copy_8_loop);
10604     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
10605     movdqu(Address(dst, len, Address::times_2), tmp1);
10606     addptr(len, 8);
10607     jcc(Assembler::notZero, copy_8_loop);
10608 
10609     bind(copy_tail);
10610     movl(len, tmp2);
10611 
10612     cmpl(len, 4);
10613     jccb(Assembler::less, copy_bytes);
10614 
10615     movdl(tmp1, Address(src, 0));  // load 4 byte chars
10616     pmovzxbw(tmp1, tmp1);
10617     movq(Address(dst, 0), tmp1);
10618     subptr(len, 4);
10619     addptr(src, 4);
10620     addptr(dst, 8);
10621 
10622     bind(copy_bytes);
10623   } else {
10624     bind(below_threshold);
10625   }
10626 
10627   testl(len, len);
10628   jccb(Assembler::zero, done);
10629   lea(src, Address(src, len, Address::times_1));
10630   lea(dst, Address(dst, len, Address::times_2));
10631   negptr(len);
10632 
10633   // inflate 1 char per iter
10634   bind(copy_chars_loop);
10635   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
10636   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
10637   increment(len);
10638   jcc(Assembler::notZero, copy_chars_loop);
10639 
10640   bind(done);
10641 }
10642 
10643 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
10644   switch (cond) {
10645     // Note some conditions are synonyms for others
10646     case Assembler::zero:         return Assembler::notZero;
10647     case Assembler::notZero:      return Assembler::zero;
10648     case Assembler::less:         return Assembler::greaterEqual;
10649     case Assembler::lessEqual:    return Assembler::greater;
10650     case Assembler::greater:      return Assembler::lessEqual;
10651     case Assembler::greaterEqual: return Assembler::less;
10652     case Assembler::below:        return Assembler::aboveEqual;
10653     case Assembler::belowEqual:   return Assembler::above;
10654     case Assembler::above:        return Assembler::belowEqual;
10655     case Assembler::aboveEqual:   return Assembler::below;
10656     case Assembler::overflow:     return Assembler::noOverflow;
10657     case Assembler::noOverflow:   return Assembler::overflow;
10658     case Assembler::negative:     return Assembler::positive;
10659     case Assembler::positive:     return Assembler::negative;
10660     case Assembler::parity:       return Assembler::noParity;
10661     case Assembler::noParity:     return Assembler::parity;
10662   }
10663   ShouldNotReachHere(); return Assembler::overflow;
10664 }
10665 
10666 SkipIfEqual::SkipIfEqual(
10667     MacroAssembler* masm, const bool* flag_addr, bool value) {
10668   _masm = masm;
10669   _masm->cmp8(ExternalAddress((address)flag_addr), value);
10670   _masm->jcc(Assembler::equal, _label);
10671 }
10672 
10673 SkipIfEqual::~SkipIfEqual() {
10674   _masm->bind(_label);
10675 }
10676 
10677 // 32-bit Windows has its own fast-path implementation
10678 // of get_thread
10679 #if !defined(WIN32) || defined(_LP64)
10680 
10681 // This is simply a call to Thread::current()
10682 void MacroAssembler::get_thread(Register thread) {
10683   if (thread != rax) {
10684     push(rax);
10685   }
10686   LP64_ONLY(push(rdi);)
10687   LP64_ONLY(push(rsi);)
10688   push(rdx);
10689   push(rcx);
10690 #ifdef _LP64
10691   push(r8);
10692   push(r9);
10693   push(r10);
10694   push(r11);
10695 #endif
10696 
10697   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
10698 
10699 #ifdef _LP64
10700   pop(r11);
10701   pop(r10);
10702   pop(r9);
10703   pop(r8);
10704 #endif
10705   pop(rcx);
10706   pop(rdx);
10707   LP64_ONLY(pop(rsi);)
10708   LP64_ONLY(pop(rdi);)
10709   if (thread != rax) {
10710     mov(thread, rax);
10711     pop(rax);
10712   }
10713 }
10714 
10715 #endif