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