1 /*
   2  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "asm/macroAssembler.inline.hpp"
  28 #include "compiler/disassembler.hpp"
  29 #include "gc/shared/cardTable.hpp"
  30 #include "gc/shared/cardTableBarrierSet.hpp"
  31 #include "gc/shared/collectedHeap.inline.hpp"
  32 #include "interpreter/interpreter.hpp"
  33 #include "memory/resourceArea.hpp"
  34 #include "memory/universe.hpp"
  35 #include "oops/klass.inline.hpp"
  36 #include "prims/methodHandles.hpp"
  37 #include "runtime/biasedLocking.hpp"
  38 #include "runtime/interfaceSupport.inline.hpp"
  39 #include "runtime/jniHandles.inline.hpp"
  40 #include "runtime/objectMonitor.hpp"
  41 #include "runtime/os.inline.hpp"
  42 #include "runtime/safepoint.hpp"
  43 #include "runtime/safepointMechanism.hpp"
  44 #include "runtime/sharedRuntime.hpp"
  45 #include "runtime/stubRoutines.hpp"
  46 #include "utilities/align.hpp"
  47 #include "utilities/macros.hpp"
  48 #if INCLUDE_ALL_GCS
  49 #include "gc/g1/g1BarrierSet.hpp"
  50 #include "gc/g1/g1CardTable.hpp"
  51 #include "gc/g1/g1CollectedHeap.inline.hpp"
  52 #include "gc/g1/heapRegion.hpp"
  53 #endif // INCLUDE_ALL_GCS
  54 #ifdef COMPILER2
  55 #include "opto/intrinsicnode.hpp"
  56 #endif
  57 
  58 #ifdef PRODUCT
  59 #define BLOCK_COMMENT(str) /* nothing */
  60 #define STOP(error) stop(error)
  61 #else
  62 #define BLOCK_COMMENT(str) block_comment(str)
  63 #define STOP(error) block_comment(error); stop(error)
  64 #endif
  65 
  66 // Convert the raw encoding form into the form expected by the
  67 // constructor for Address.
  68 Address Address::make_raw(int base, int index, int scale, int disp, relocInfo::relocType disp_reloc) {
  69   assert(scale == 0, "not supported");
  70   RelocationHolder rspec;
  71   if (disp_reloc != relocInfo::none) {
  72     rspec = Relocation::spec_simple(disp_reloc);
  73   }
  74 
  75   Register rindex = as_Register(index);
  76   if (rindex != G0) {
  77     Address madr(as_Register(base), rindex);
  78     madr._rspec = rspec;
  79     return madr;
  80   } else {
  81     Address madr(as_Register(base), disp);
  82     madr._rspec = rspec;
  83     return madr;
  84   }
  85 }
  86 
  87 Address Argument::address_in_frame() const {
  88   // Warning: In LP64 mode disp will occupy more than 10 bits, but
  89   //          op codes such as ld or ldx, only access disp() to get
  90   //          their simm13 argument.
  91   int disp = ((_number - Argument::n_register_parameters + frame::memory_parameter_word_sp_offset) * BytesPerWord) + STACK_BIAS;
  92   if (is_in())
  93     return Address(FP, disp); // In argument.
  94   else
  95     return Address(SP, disp); // Out argument.
  96 }
  97 
  98 static const char* argumentNames[][2] = {
  99   {"A0","P0"}, {"A1","P1"}, {"A2","P2"}, {"A3","P3"}, {"A4","P4"},
 100   {"A5","P5"}, {"A6","P6"}, {"A7","P7"}, {"A8","P8"}, {"A9","P9"},
 101   {"A(n>9)","P(n>9)"}
 102 };
 103 
 104 const char* Argument::name() const {
 105   int nofArgs = sizeof argumentNames / sizeof argumentNames[0];
 106   int num = number();
 107   if (num >= nofArgs)  num = nofArgs - 1;
 108   return argumentNames[num][is_in() ? 1 : 0];
 109 }
 110 
 111 #ifdef ASSERT
 112 // On RISC, there's no benefit to verifying instruction boundaries.
 113 bool AbstractAssembler::pd_check_instruction_mark() { return false; }
 114 #endif
 115 
 116 // Patch instruction inst at offset inst_pos to refer to dest_pos
 117 // and return the resulting instruction.
 118 // We should have pcs, not offsets, but since all is relative, it will work out
 119 // OK.
 120 int MacroAssembler::patched_branch(int dest_pos, int inst, int inst_pos) {
 121   int m; // mask for displacement field
 122   int v; // new value for displacement field
 123   const int word_aligned_ones = -4;
 124   switch (inv_op(inst)) {
 125   default: ShouldNotReachHere();
 126   case call_op:    m = wdisp(word_aligned_ones, 0, 30);  v = wdisp(dest_pos, inst_pos, 30); break;
 127   case branch_op:
 128     switch (inv_op2(inst)) {
 129       case fbp_op2:    m = wdisp(  word_aligned_ones, 0, 19);  v = wdisp(  dest_pos, inst_pos, 19); break;
 130       case bp_op2:     m = wdisp(  word_aligned_ones, 0, 19);  v = wdisp(  dest_pos, inst_pos, 19); break;
 131       case fb_op2:     m = wdisp(  word_aligned_ones, 0, 22);  v = wdisp(  dest_pos, inst_pos, 22); break;
 132       case br_op2:     m = wdisp(  word_aligned_ones, 0, 22);  v = wdisp(  dest_pos, inst_pos, 22); break;
 133       case bpr_op2: {
 134         if (is_cbcond(inst)) {
 135           m = wdisp10(word_aligned_ones, 0);
 136           v = wdisp10(dest_pos, inst_pos);
 137         } else {
 138           m = wdisp16(word_aligned_ones, 0);
 139           v = wdisp16(dest_pos, inst_pos);
 140         }
 141         break;
 142       }
 143       default: ShouldNotReachHere();
 144     }
 145   }
 146   return  inst & ~m  |  v;
 147 }
 148 
 149 // Return the offset of the branch destionation of instruction inst
 150 // at offset pos.
 151 // Should have pcs, but since all is relative, it works out.
 152 int MacroAssembler::branch_destination(int inst, int pos) {
 153   int r;
 154   switch (inv_op(inst)) {
 155   default: ShouldNotReachHere();
 156   case call_op:        r = inv_wdisp(inst, pos, 30);  break;
 157   case branch_op:
 158     switch (inv_op2(inst)) {
 159       case fbp_op2:    r = inv_wdisp(  inst, pos, 19);  break;
 160       case bp_op2:     r = inv_wdisp(  inst, pos, 19);  break;
 161       case fb_op2:     r = inv_wdisp(  inst, pos, 22);  break;
 162       case br_op2:     r = inv_wdisp(  inst, pos, 22);  break;
 163       case bpr_op2: {
 164         if (is_cbcond(inst)) {
 165           r = inv_wdisp10(inst, pos);
 166         } else {
 167           r = inv_wdisp16(inst, pos);
 168         }
 169         break;
 170       }
 171       default: ShouldNotReachHere();
 172     }
 173   }
 174   return r;
 175 }
 176 
 177 void MacroAssembler::null_check(Register reg, int offset) {
 178   if (needs_explicit_null_check((intptr_t)offset)) {
 179     // provoke OS NULL exception if reg = NULL by
 180     // accessing M[reg] w/o changing any registers
 181     ld_ptr(reg, 0, G0);
 182   }
 183   else {
 184     // nothing to do, (later) access of M[reg + offset]
 185     // will provoke OS NULL exception if reg = NULL
 186   }
 187 }
 188 
 189 // Ring buffer jumps
 190 
 191 
 192 void MacroAssembler::jmp2(Register r1, Register r2, const char* file, int line ) {
 193   assert_not_delayed();
 194   jmpl(r1, r2, G0);
 195 }
 196 void MacroAssembler::jmp(Register r1, int offset, const char* file, int line ) {
 197   assert_not_delayed();
 198   jmp(r1, offset);
 199 }
 200 
 201 // This code sequence is relocatable to any address, even on LP64.
 202 void MacroAssembler::jumpl(const AddressLiteral& addrlit, Register temp, Register d, int offset, const char* file, int line) {
 203   assert_not_delayed();
 204   // Force fixed length sethi because NativeJump and NativeFarCall don't handle
 205   // variable length instruction streams.
 206   patchable_sethi(addrlit, temp);
 207   Address a(temp, addrlit.low10() + offset);  // Add the offset to the displacement.
 208   jmpl(a.base(), a.disp(), d);
 209 }
 210 
 211 void MacroAssembler::jump(const AddressLiteral& addrlit, Register temp, int offset, const char* file, int line) {
 212   jumpl(addrlit, temp, G0, offset, file, line);
 213 }
 214 
 215 
 216 // Conditional breakpoint (for assertion checks in assembly code)
 217 void MacroAssembler::breakpoint_trap(Condition c, CC cc) {
 218   trap(c, cc, G0, ST_RESERVED_FOR_USER_0);
 219 }
 220 
 221 // We want to use ST_BREAKPOINT here, but the debugger is confused by it.
 222 void MacroAssembler::breakpoint_trap() {
 223   trap(ST_RESERVED_FOR_USER_0);
 224 }
 225 
 226 // Write serialization page so VM thread can do a pseudo remote membar
 227 // We use the current thread pointer to calculate a thread specific
 228 // offset to write to within the page. This minimizes bus traffic
 229 // due to cache line collision.
 230 void MacroAssembler::serialize_memory(Register thread, Register tmp1, Register tmp2) {
 231   srl(thread, os::get_serialize_page_shift_count(), tmp2);
 232   if (Assembler::is_simm13(os::vm_page_size())) {
 233     and3(tmp2, (os::vm_page_size() - sizeof(int)), tmp2);
 234   }
 235   else {
 236     set((os::vm_page_size() - sizeof(int)), tmp1);
 237     and3(tmp2, tmp1, tmp2);
 238   }
 239   set(os::get_memory_serialize_page(), tmp1);
 240   st(G0, tmp1, tmp2);
 241 }
 242 
 243 
 244 void MacroAssembler::safepoint_poll(Label& slow_path, bool a, Register thread_reg, Register temp_reg) {
 245   if (SafepointMechanism::uses_thread_local_poll()) {
 246     ldx(Address(thread_reg, Thread::polling_page_offset()), temp_reg, 0);
 247     // Armed page has poll bit set.
 248     and3(temp_reg, SafepointMechanism::poll_bit(), temp_reg);
 249     br_notnull(temp_reg, a, Assembler::pn, slow_path);
 250   } else {
 251     AddressLiteral sync_state(SafepointSynchronize::address_of_state());
 252 
 253     load_contents(sync_state, temp_reg);
 254     cmp(temp_reg, SafepointSynchronize::_not_synchronized);
 255     br(Assembler::notEqual, a, Assembler::pn, slow_path);
 256   }
 257 }
 258 
 259 void MacroAssembler::enter() {
 260   Unimplemented();
 261 }
 262 
 263 void MacroAssembler::leave() {
 264   Unimplemented();
 265 }
 266 
 267 // Calls to C land
 268 
 269 #ifdef ASSERT
 270 // a hook for debugging
 271 static Thread* reinitialize_thread() {
 272   return Thread::current();
 273 }
 274 #else
 275 #define reinitialize_thread Thread::current
 276 #endif
 277 
 278 #ifdef ASSERT
 279 address last_get_thread = NULL;
 280 #endif
 281 
 282 // call this when G2_thread is not known to be valid
 283 void MacroAssembler::get_thread() {
 284   save_frame(0);                // to avoid clobbering O0
 285   mov(G1, L0);                  // avoid clobbering G1
 286   mov(G5_method, L1);           // avoid clobbering G5
 287   mov(G3, L2);                  // avoid clobbering G3 also
 288   mov(G4, L5);                  // avoid clobbering G4
 289 #ifdef ASSERT
 290   AddressLiteral last_get_thread_addrlit(&last_get_thread);
 291   set(last_get_thread_addrlit, L3);
 292   rdpc(L4);
 293   inc(L4, 3 * BytesPerInstWord); // skip rdpc + inc + st_ptr to point L4 at call  st_ptr(L4, L3, 0);
 294 #endif
 295   call(CAST_FROM_FN_PTR(address, reinitialize_thread), relocInfo::runtime_call_type);
 296   delayed()->nop();
 297   mov(L0, G1);
 298   mov(L1, G5_method);
 299   mov(L2, G3);
 300   mov(L5, G4);
 301   restore(O0, 0, G2_thread);
 302 }
 303 
 304 static Thread* verify_thread_subroutine(Thread* gthread_value) {
 305   Thread* correct_value = Thread::current();
 306   guarantee(gthread_value == correct_value, "G2_thread value must be the thread");
 307   return correct_value;
 308 }
 309 
 310 void MacroAssembler::verify_thread() {
 311   if (VerifyThread) {
 312     // NOTE: this chops off the heads of the 64-bit O registers.
 313     // make sure G2_thread contains the right value
 314     save_frame_and_mov(0, Lmethod, Lmethod);   // to avoid clobbering O0 (and propagate Lmethod)
 315     mov(G1, L1);                // avoid clobbering G1
 316     // G2 saved below
 317     mov(G3, L3);                // avoid clobbering G3
 318     mov(G4, L4);                // avoid clobbering G4
 319     mov(G5_method, L5);         // avoid clobbering G5_method
 320     call(CAST_FROM_FN_PTR(address,verify_thread_subroutine), relocInfo::runtime_call_type);
 321     delayed()->mov(G2_thread, O0);
 322 
 323     mov(L1, G1);                // Restore G1
 324     // G2 restored below
 325     mov(L3, G3);                // restore G3
 326     mov(L4, G4);                // restore G4
 327     mov(L5, G5_method);         // restore G5_method
 328     restore(O0, 0, G2_thread);
 329   }
 330 }
 331 
 332 
 333 void MacroAssembler::save_thread(const Register thread_cache) {
 334   verify_thread();
 335   if (thread_cache->is_valid()) {
 336     assert(thread_cache->is_local() || thread_cache->is_in(), "bad volatile");
 337     mov(G2_thread, thread_cache);
 338   }
 339   if (VerifyThread) {
 340     // smash G2_thread, as if the VM were about to anyway
 341     set(0x67676767, G2_thread);
 342   }
 343 }
 344 
 345 
 346 void MacroAssembler::restore_thread(const Register thread_cache) {
 347   if (thread_cache->is_valid()) {
 348     assert(thread_cache->is_local() || thread_cache->is_in(), "bad volatile");
 349     mov(thread_cache, G2_thread);
 350     verify_thread();
 351   } else {
 352     // do it the slow way
 353     get_thread();
 354   }
 355 }
 356 
 357 
 358 // %%% maybe get rid of [re]set_last_Java_frame
 359 void MacroAssembler::set_last_Java_frame(Register last_java_sp, Register last_Java_pc) {
 360   assert_not_delayed();
 361   Address flags(G2_thread, JavaThread::frame_anchor_offset() +
 362                            JavaFrameAnchor::flags_offset());
 363   Address pc_addr(G2_thread, JavaThread::last_Java_pc_offset());
 364 
 365   // Always set last_Java_pc and flags first because once last_Java_sp is visible
 366   // has_last_Java_frame is true and users will look at the rest of the fields.
 367   // (Note: flags should always be zero before we get here so doesn't need to be set.)
 368 
 369 #ifdef ASSERT
 370   // Verify that flags was zeroed on return to Java
 371   Label PcOk;
 372   save_frame(0);                // to avoid clobbering O0
 373   ld_ptr(pc_addr, L0);
 374   br_null_short(L0, Assembler::pt, PcOk);
 375   STOP("last_Java_pc not zeroed before leaving Java");
 376   bind(PcOk);
 377 
 378   // Verify that flags was zeroed on return to Java
 379   Label FlagsOk;
 380   ld(flags, L0);
 381   tst(L0);
 382   br(Assembler::zero, false, Assembler::pt, FlagsOk);
 383   delayed() -> restore();
 384   STOP("flags not zeroed before leaving Java");
 385   bind(FlagsOk);
 386 #endif /* ASSERT */
 387   //
 388   // When returning from calling out from Java mode the frame anchor's last_Java_pc
 389   // will always be set to NULL. It is set here so that if we are doing a call to
 390   // native (not VM) that we capture the known pc and don't have to rely on the
 391   // native call having a standard frame linkage where we can find the pc.
 392 
 393   if (last_Java_pc->is_valid()) {
 394     st_ptr(last_Java_pc, pc_addr);
 395   }
 396 
 397 #ifdef ASSERT
 398   // Make sure that we have an odd stack
 399   Label StackOk;
 400   andcc(last_java_sp, 0x01, G0);
 401   br(Assembler::notZero, false, Assembler::pt, StackOk);
 402   delayed()->nop();
 403   STOP("Stack Not Biased in set_last_Java_frame");
 404   bind(StackOk);
 405 #endif // ASSERT
 406   assert( last_java_sp != G4_scratch, "bad register usage in set_last_Java_frame");
 407   add( last_java_sp, STACK_BIAS, G4_scratch );
 408   st_ptr(G4_scratch, G2_thread, JavaThread::last_Java_sp_offset());
 409 }
 410 
 411 void MacroAssembler::reset_last_Java_frame(void) {
 412   assert_not_delayed();
 413 
 414   Address sp_addr(G2_thread, JavaThread::last_Java_sp_offset());
 415   Address pc_addr(G2_thread, JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 416   Address flags  (G2_thread, JavaThread::frame_anchor_offset() + JavaFrameAnchor::flags_offset());
 417 
 418 #ifdef ASSERT
 419   // check that it WAS previously set
 420     save_frame_and_mov(0, Lmethod, Lmethod);     // Propagate Lmethod to helper frame
 421     ld_ptr(sp_addr, L0);
 422     tst(L0);
 423     breakpoint_trap(Assembler::zero, Assembler::ptr_cc);
 424     restore();
 425 #endif // ASSERT
 426 
 427   st_ptr(G0, sp_addr);
 428   // Always return last_Java_pc to zero
 429   st_ptr(G0, pc_addr);
 430   // Always null flags after return to Java
 431   st(G0, flags);
 432 }
 433 
 434 
 435 void MacroAssembler::call_VM_base(
 436   Register        oop_result,
 437   Register        thread_cache,
 438   Register        last_java_sp,
 439   address         entry_point,
 440   int             number_of_arguments,
 441   bool            check_exceptions)
 442 {
 443   assert_not_delayed();
 444 
 445   // determine last_java_sp register
 446   if (!last_java_sp->is_valid()) {
 447     last_java_sp = SP;
 448   }
 449   // debugging support
 450   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
 451 
 452   // 64-bit last_java_sp is biased!
 453   set_last_Java_frame(last_java_sp, noreg);
 454   if (VerifyThread)  mov(G2_thread, O0); // about to be smashed; pass early
 455   save_thread(thread_cache);
 456   // do the call
 457   call(entry_point, relocInfo::runtime_call_type);
 458   if (!VerifyThread)
 459     delayed()->mov(G2_thread, O0);  // pass thread as first argument
 460   else
 461     delayed()->nop();             // (thread already passed)
 462   restore_thread(thread_cache);
 463   reset_last_Java_frame();
 464 
 465   // check for pending exceptions. use Gtemp as scratch register.
 466   if (check_exceptions) {
 467     check_and_forward_exception(Gtemp);
 468   }
 469 
 470 #ifdef ASSERT
 471   set(badHeapWordVal, G3);
 472   set(badHeapWordVal, G4);
 473   set(badHeapWordVal, G5);
 474 #endif
 475 
 476   // get oop result if there is one and reset the value in the thread
 477   if (oop_result->is_valid()) {
 478     get_vm_result(oop_result);
 479   }
 480 }
 481 
 482 void MacroAssembler::check_and_forward_exception(Register scratch_reg)
 483 {
 484   Label L;
 485 
 486   check_and_handle_popframe(scratch_reg);
 487   check_and_handle_earlyret(scratch_reg);
 488 
 489   Address exception_addr(G2_thread, Thread::pending_exception_offset());
 490   ld_ptr(exception_addr, scratch_reg);
 491   br_null_short(scratch_reg, pt, L);
 492   // we use O7 linkage so that forward_exception_entry has the issuing PC
 493   call(StubRoutines::forward_exception_entry(), relocInfo::runtime_call_type);
 494   delayed()->nop();
 495   bind(L);
 496 }
 497 
 498 
 499 void MacroAssembler::check_and_handle_popframe(Register scratch_reg) {
 500 }
 501 
 502 
 503 void MacroAssembler::check_and_handle_earlyret(Register scratch_reg) {
 504 }
 505 
 506 
 507 void MacroAssembler::call_VM(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
 508   call_VM_base(oop_result, noreg, noreg, entry_point, number_of_arguments, check_exceptions);
 509 }
 510 
 511 
 512 void MacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1, bool check_exceptions) {
 513   // O0 is reserved for the thread
 514   mov(arg_1, O1);
 515   call_VM(oop_result, entry_point, 1, check_exceptions);
 516 }
 517 
 518 
 519 void MacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1, Register arg_2, bool check_exceptions) {
 520   // O0 is reserved for the thread
 521   mov(arg_1, O1);
 522   mov(arg_2, O2); assert(arg_2 != O1, "smashed argument");
 523   call_VM(oop_result, entry_point, 2, check_exceptions);
 524 }
 525 
 526 
 527 void MacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1, Register arg_2, Register arg_3, bool check_exceptions) {
 528   // O0 is reserved for the thread
 529   mov(arg_1, O1);
 530   mov(arg_2, O2); assert(arg_2 != O1,                "smashed argument");
 531   mov(arg_3, O3); assert(arg_3 != O1 && arg_3 != O2, "smashed argument");
 532   call_VM(oop_result, entry_point, 3, check_exceptions);
 533 }
 534 
 535 
 536 
 537 // Note: The following call_VM overloadings are useful when a "save"
 538 // has already been performed by a stub, and the last Java frame is
 539 // the previous one.  In that case, last_java_sp must be passed as FP
 540 // instead of SP.
 541 
 542 
 543 void MacroAssembler::call_VM(Register oop_result, Register last_java_sp, address entry_point, int number_of_arguments, bool check_exceptions) {
 544   call_VM_base(oop_result, noreg, last_java_sp, entry_point, number_of_arguments, check_exceptions);
 545 }
 546 
 547 
 548 void MacroAssembler::call_VM(Register oop_result, Register last_java_sp, address entry_point, Register arg_1, bool check_exceptions) {
 549   // O0 is reserved for the thread
 550   mov(arg_1, O1);
 551   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
 552 }
 553 
 554 
 555 void MacroAssembler::call_VM(Register oop_result, Register last_java_sp, address entry_point, Register arg_1, Register arg_2, bool check_exceptions) {
 556   // O0 is reserved for the thread
 557   mov(arg_1, O1);
 558   mov(arg_2, O2); assert(arg_2 != O1, "smashed argument");
 559   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
 560 }
 561 
 562 
 563 void MacroAssembler::call_VM(Register oop_result, Register last_java_sp, address entry_point, Register arg_1, Register arg_2, Register arg_3, bool check_exceptions) {
 564   // O0 is reserved for the thread
 565   mov(arg_1, O1);
 566   mov(arg_2, O2); assert(arg_2 != O1,                "smashed argument");
 567   mov(arg_3, O3); assert(arg_3 != O1 && arg_3 != O2, "smashed argument");
 568   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
 569 }
 570 
 571 
 572 
 573 void MacroAssembler::call_VM_leaf_base(Register thread_cache, address entry_point, int number_of_arguments) {
 574   assert_not_delayed();
 575   save_thread(thread_cache);
 576   // do the call
 577   call(entry_point, relocInfo::runtime_call_type);
 578   delayed()->nop();
 579   restore_thread(thread_cache);
 580 #ifdef ASSERT
 581   set(badHeapWordVal, G3);
 582   set(badHeapWordVal, G4);
 583   set(badHeapWordVal, G5);
 584 #endif
 585 }
 586 
 587 
 588 void MacroAssembler::call_VM_leaf(Register thread_cache, address entry_point, int number_of_arguments) {
 589   call_VM_leaf_base(thread_cache, entry_point, number_of_arguments);
 590 }
 591 
 592 
 593 void MacroAssembler::call_VM_leaf(Register thread_cache, address entry_point, Register arg_1) {
 594   mov(arg_1, O0);
 595   call_VM_leaf(thread_cache, entry_point, 1);
 596 }
 597 
 598 
 599 void MacroAssembler::call_VM_leaf(Register thread_cache, address entry_point, Register arg_1, Register arg_2) {
 600   mov(arg_1, O0);
 601   mov(arg_2, O1); assert(arg_2 != O0, "smashed argument");
 602   call_VM_leaf(thread_cache, entry_point, 2);
 603 }
 604 
 605 
 606 void MacroAssembler::call_VM_leaf(Register thread_cache, address entry_point, Register arg_1, Register arg_2, Register arg_3) {
 607   mov(arg_1, O0);
 608   mov(arg_2, O1); assert(arg_2 != O0,                "smashed argument");
 609   mov(arg_3, O2); assert(arg_3 != O0 && arg_3 != O1, "smashed argument");
 610   call_VM_leaf(thread_cache, entry_point, 3);
 611 }
 612 
 613 
 614 void MacroAssembler::get_vm_result(Register oop_result) {
 615   verify_thread();
 616   Address vm_result_addr(G2_thread, JavaThread::vm_result_offset());
 617   ld_ptr(    vm_result_addr, oop_result);
 618   st_ptr(G0, vm_result_addr);
 619   verify_oop(oop_result);
 620 }
 621 
 622 
 623 void MacroAssembler::get_vm_result_2(Register metadata_result) {
 624   verify_thread();
 625   Address vm_result_addr_2(G2_thread, JavaThread::vm_result_2_offset());
 626   ld_ptr(vm_result_addr_2, metadata_result);
 627   st_ptr(G0, vm_result_addr_2);
 628 }
 629 
 630 
 631 // We require that C code which does not return a value in vm_result will
 632 // leave it undisturbed.
 633 void MacroAssembler::set_vm_result(Register oop_result) {
 634   verify_thread();
 635   Address vm_result_addr(G2_thread, JavaThread::vm_result_offset());
 636   verify_oop(oop_result);
 637 
 638 # ifdef ASSERT
 639     // Check that we are not overwriting any other oop.
 640     save_frame_and_mov(0, Lmethod, Lmethod);     // Propagate Lmethod
 641     ld_ptr(vm_result_addr, L0);
 642     tst(L0);
 643     restore();
 644     breakpoint_trap(notZero, Assembler::ptr_cc);
 645     // }
 646 # endif
 647 
 648   st_ptr(oop_result, vm_result_addr);
 649 }
 650 
 651 
 652 void MacroAssembler::ic_call(address entry, bool emit_delay, jint method_index) {
 653   RelocationHolder rspec = virtual_call_Relocation::spec(pc(), method_index);
 654   patchable_set((intptr_t)Universe::non_oop_word(), G5_inline_cache_reg);
 655   relocate(rspec);
 656   call(entry, relocInfo::none);
 657   if (emit_delay) {
 658     delayed()->nop();
 659   }
 660 }
 661 
 662 void MacroAssembler::card_table_write(jbyte* byte_map_base,
 663                                       Register tmp, Register obj) {
 664   srlx(obj, CardTable::card_shift, obj);
 665   assert(tmp != obj, "need separate temp reg");
 666   set((address) byte_map_base, tmp);
 667   stb(G0, tmp, obj);
 668 }
 669 
 670 
 671 void MacroAssembler::internal_sethi(const AddressLiteral& addrlit, Register d, bool ForceRelocatable) {
 672   address save_pc;
 673   int shiftcnt;
 674 #ifdef VALIDATE_PIPELINE
 675   assert_no_delay("Cannot put two instructions in delay-slot.");
 676 #endif
 677   v9_dep();
 678   save_pc = pc();
 679 
 680   int msb32 = (int) (addrlit.value() >> 32);
 681   int lsb32 = (int) (addrlit.value());
 682 
 683   if (msb32 == 0 && lsb32 >= 0) {
 684     Assembler::sethi(lsb32, d, addrlit.rspec());
 685   }
 686   else if (msb32 == -1) {
 687     Assembler::sethi(~lsb32, d, addrlit.rspec());
 688     xor3(d, ~low10(~0), d);
 689   }
 690   else {
 691     Assembler::sethi(msb32, d, addrlit.rspec());  // msb 22-bits
 692     if (msb32 & 0x3ff)                            // Any bits?
 693       or3(d, msb32 & 0x3ff, d);                   // msb 32-bits are now in lsb 32
 694     if (lsb32 & 0xFFFFFC00) {                     // done?
 695       if ((lsb32 >> 20) & 0xfff) {                // Any bits set?
 696         sllx(d, 12, d);                           // Make room for next 12 bits
 697         or3(d, (lsb32 >> 20) & 0xfff, d);         // Or in next 12
 698         shiftcnt = 0;                             // We already shifted
 699       }
 700       else
 701         shiftcnt = 12;
 702       if ((lsb32 >> 10) & 0x3ff) {
 703         sllx(d, shiftcnt + 10, d);                // Make room for last 10 bits
 704         or3(d, (lsb32 >> 10) & 0x3ff, d);         // Or in next 10
 705         shiftcnt = 0;
 706       }
 707       else
 708         shiftcnt = 10;
 709       sllx(d, shiftcnt + 10, d);                  // Shift leaving disp field 0'd
 710     }
 711     else
 712       sllx(d, 32, d);
 713   }
 714   // Pad out the instruction sequence so it can be patched later.
 715   if (ForceRelocatable || (addrlit.rtype() != relocInfo::none &&
 716                            addrlit.rtype() != relocInfo::runtime_call_type)) {
 717     while (pc() < (save_pc + (7 * BytesPerInstWord)))
 718       nop();
 719   }
 720 }
 721 
 722 
 723 void MacroAssembler::sethi(const AddressLiteral& addrlit, Register d) {
 724   internal_sethi(addrlit, d, false);
 725 }
 726 
 727 
 728 void MacroAssembler::patchable_sethi(const AddressLiteral& addrlit, Register d) {
 729   internal_sethi(addrlit, d, true);
 730 }
 731 
 732 
 733 int MacroAssembler::insts_for_sethi(address a, bool worst_case) {
 734   if (worst_case)  return 7;
 735   intptr_t iaddr = (intptr_t) a;
 736   int msb32 = (int) (iaddr >> 32);
 737   int lsb32 = (int) (iaddr);
 738   int count;
 739   if (msb32 == 0 && lsb32 >= 0)
 740     count = 1;
 741   else if (msb32 == -1)
 742     count = 2;
 743   else {
 744     count = 2;
 745     if (msb32 & 0x3ff)
 746       count++;
 747     if (lsb32 & 0xFFFFFC00 ) {
 748       if ((lsb32 >> 20) & 0xfff)  count += 2;
 749       if ((lsb32 >> 10) & 0x3ff)  count += 2;
 750     }
 751   }
 752   return count;
 753 }
 754 
 755 int MacroAssembler::worst_case_insts_for_set() {
 756   return insts_for_sethi(NULL, true) + 1;
 757 }
 758 
 759 
 760 // Keep in sync with MacroAssembler::insts_for_internal_set
 761 void MacroAssembler::internal_set(const AddressLiteral& addrlit, Register d, bool ForceRelocatable) {
 762   intptr_t value = addrlit.value();
 763 
 764   if (!ForceRelocatable && addrlit.rspec().type() == relocInfo::none) {
 765     // can optimize
 766     if (-4096 <= value && value <= 4095) {
 767       or3(G0, value, d); // setsw (this leaves upper 32 bits sign-extended)
 768       return;
 769     }
 770     if (inv_hi22(hi22(value)) == value) {
 771       sethi(addrlit, d);
 772       return;
 773     }
 774   }
 775   assert_no_delay("Cannot put two instructions in delay-slot.");
 776   internal_sethi(addrlit, d, ForceRelocatable);
 777   if (ForceRelocatable || addrlit.rspec().type() != relocInfo::none || addrlit.low10() != 0) {
 778     add(d, addrlit.low10(), d, addrlit.rspec());
 779   }
 780 }
 781 
 782 // Keep in sync with MacroAssembler::internal_set
 783 int MacroAssembler::insts_for_internal_set(intptr_t value) {
 784   // can optimize
 785   if (-4096 <= value && value <= 4095) {
 786     return 1;
 787   }
 788   if (inv_hi22(hi22(value)) == value) {
 789     return insts_for_sethi((address) value);
 790   }
 791   int count = insts_for_sethi((address) value);
 792   AddressLiteral al(value);
 793   if (al.low10() != 0) {
 794     count++;
 795   }
 796   return count;
 797 }
 798 
 799 void MacroAssembler::set(const AddressLiteral& al, Register d) {
 800   internal_set(al, d, false);
 801 }
 802 
 803 void MacroAssembler::set(intptr_t value, Register d) {
 804   AddressLiteral al(value);
 805   internal_set(al, d, false);
 806 }
 807 
 808 void MacroAssembler::set(address addr, Register d, RelocationHolder const& rspec) {
 809   AddressLiteral al(addr, rspec);
 810   internal_set(al, d, false);
 811 }
 812 
 813 void MacroAssembler::patchable_set(const AddressLiteral& al, Register d) {
 814   internal_set(al, d, true);
 815 }
 816 
 817 void MacroAssembler::patchable_set(intptr_t value, Register d) {
 818   AddressLiteral al(value);
 819   internal_set(al, d, true);
 820 }
 821 
 822 
 823 void MacroAssembler::set64(jlong value, Register d, Register tmp) {
 824   assert_not_delayed();
 825   v9_dep();
 826 
 827   int hi = (int)(value >> 32);
 828   int lo = (int)(value & ~0);
 829   int bits_33to2 = (int)((value >> 2) & ~0);
 830   // (Matcher::isSimpleConstant64 knows about the following optimizations.)
 831   if (Assembler::is_simm13(lo) && value == lo) {
 832     or3(G0, lo, d);
 833   } else if (hi == 0) {
 834     Assembler::sethi(lo, d);   // hardware version zero-extends to upper 32
 835     if (low10(lo) != 0)
 836       or3(d, low10(lo), d);
 837   }
 838   else if ((hi >> 2) == 0) {
 839     Assembler::sethi(bits_33to2, d);  // hardware version zero-extends to upper 32
 840     sllx(d, 2, d);
 841     if (low12(lo) != 0)
 842       or3(d, low12(lo), d);
 843   }
 844   else if (hi == -1) {
 845     Assembler::sethi(~lo, d);  // hardware version zero-extends to upper 32
 846     xor3(d, low10(lo) ^ ~low10(~0), d);
 847   }
 848   else if (lo == 0) {
 849     if (Assembler::is_simm13(hi)) {
 850       or3(G0, hi, d);
 851     } else {
 852       Assembler::sethi(hi, d);   // hardware version zero-extends to upper 32
 853       if (low10(hi) != 0)
 854         or3(d, low10(hi), d);
 855     }
 856     sllx(d, 32, d);
 857   }
 858   else {
 859     Assembler::sethi(hi, tmp);
 860     Assembler::sethi(lo,   d); // macro assembler version sign-extends
 861     if (low10(hi) != 0)
 862       or3 (tmp, low10(hi), tmp);
 863     if (low10(lo) != 0)
 864       or3 (  d, low10(lo),   d);
 865     sllx(tmp, 32, tmp);
 866     or3 (d, tmp, d);
 867   }
 868 }
 869 
 870 int MacroAssembler::insts_for_set64(jlong value) {
 871   v9_dep();
 872 
 873   int hi = (int) (value >> 32);
 874   int lo = (int) (value & ~0);
 875   int count = 0;
 876 
 877   // (Matcher::isSimpleConstant64 knows about the following optimizations.)
 878   if (Assembler::is_simm13(lo) && value == lo) {
 879     count++;
 880   } else if (hi == 0) {
 881     count++;
 882     if (low10(lo) != 0)
 883       count++;
 884   }
 885   else if (hi == -1) {
 886     count += 2;
 887   }
 888   else if (lo == 0) {
 889     if (Assembler::is_simm13(hi)) {
 890       count++;
 891     } else {
 892       count++;
 893       if (low10(hi) != 0)
 894         count++;
 895     }
 896     count++;
 897   }
 898   else {
 899     count += 2;
 900     if (low10(hi) != 0)
 901       count++;
 902     if (low10(lo) != 0)
 903       count++;
 904     count += 2;
 905   }
 906   return count;
 907 }
 908 
 909 // compute size in bytes of sparc frame, given
 910 // number of extraWords
 911 int MacroAssembler::total_frame_size_in_bytes(int extraWords) {
 912 
 913   int nWords = frame::memory_parameter_word_sp_offset;
 914 
 915   nWords += extraWords;
 916 
 917   if (nWords & 1) ++nWords; // round up to double-word
 918 
 919   return nWords * BytesPerWord;
 920 }
 921 
 922 
 923 // save_frame: given number of "extra" words in frame,
 924 // issue approp. save instruction (p 200, v8 manual)
 925 
 926 void MacroAssembler::save_frame(int extraWords) {
 927   int delta = -total_frame_size_in_bytes(extraWords);
 928   if (is_simm13(delta)) {
 929     save(SP, delta, SP);
 930   } else {
 931     set(delta, G3_scratch);
 932     save(SP, G3_scratch, SP);
 933   }
 934 }
 935 
 936 
 937 void MacroAssembler::save_frame_c1(int size_in_bytes) {
 938   if (is_simm13(-size_in_bytes)) {
 939     save(SP, -size_in_bytes, SP);
 940   } else {
 941     set(-size_in_bytes, G3_scratch);
 942     save(SP, G3_scratch, SP);
 943   }
 944 }
 945 
 946 
 947 void MacroAssembler::save_frame_and_mov(int extraWords,
 948                                         Register s1, Register d1,
 949                                         Register s2, Register d2) {
 950   assert_not_delayed();
 951 
 952   // The trick here is to use precisely the same memory word
 953   // that trap handlers also use to save the register.
 954   // This word cannot be used for any other purpose, but
 955   // it works fine to save the register's value, whether or not
 956   // an interrupt flushes register windows at any given moment!
 957   Address s1_addr;
 958   if (s1->is_valid() && (s1->is_in() || s1->is_local())) {
 959     s1_addr = s1->address_in_saved_window();
 960     st_ptr(s1, s1_addr);
 961   }
 962 
 963   Address s2_addr;
 964   if (s2->is_valid() && (s2->is_in() || s2->is_local())) {
 965     s2_addr = s2->address_in_saved_window();
 966     st_ptr(s2, s2_addr);
 967   }
 968 
 969   save_frame(extraWords);
 970 
 971   if (s1_addr.base() == SP) {
 972     ld_ptr(s1_addr.after_save(), d1);
 973   } else if (s1->is_valid()) {
 974     mov(s1->after_save(), d1);
 975   }
 976 
 977   if (s2_addr.base() == SP) {
 978     ld_ptr(s2_addr.after_save(), d2);
 979   } else if (s2->is_valid()) {
 980     mov(s2->after_save(), d2);
 981   }
 982 }
 983 
 984 
 985 AddressLiteral MacroAssembler::allocate_metadata_address(Metadata* obj) {
 986   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
 987   int index = oop_recorder()->allocate_metadata_index(obj);
 988   RelocationHolder rspec = metadata_Relocation::spec(index);
 989   return AddressLiteral((address)obj, rspec);
 990 }
 991 
 992 AddressLiteral MacroAssembler::constant_metadata_address(Metadata* obj) {
 993   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
 994   int index = oop_recorder()->find_index(obj);
 995   RelocationHolder rspec = metadata_Relocation::spec(index);
 996   return AddressLiteral((address)obj, rspec);
 997 }
 998 
 999 
1000 AddressLiteral MacroAssembler::constant_oop_address(jobject obj) {
1001   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
1002   assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "not an oop");
1003   int oop_index = oop_recorder()->find_index(obj);
1004   return AddressLiteral(obj, oop_Relocation::spec(oop_index));
1005 }
1006 
1007 void  MacroAssembler::set_narrow_oop(jobject obj, Register d) {
1008   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
1009   int oop_index = oop_recorder()->find_index(obj);
1010   RelocationHolder rspec = oop_Relocation::spec(oop_index);
1011 
1012   assert_not_delayed();
1013   // Relocation with special format (see relocInfo_sparc.hpp).
1014   relocate(rspec, 1);
1015   // Assembler::sethi(0x3fffff, d);
1016   emit_int32( op(branch_op) | rd(d) | op2(sethi_op2) | hi22(0x3fffff) );
1017   // Don't add relocation for 'add'. Do patching during 'sethi' processing.
1018   add(d, 0x3ff, d);
1019 
1020 }
1021 
1022 void  MacroAssembler::set_narrow_klass(Klass* k, Register d) {
1023   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
1024   int klass_index = oop_recorder()->find_index(k);
1025   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
1026   narrowOop encoded_k = Klass::encode_klass(k);
1027 
1028   assert_not_delayed();
1029   // Relocation with special format (see relocInfo_sparc.hpp).
1030   relocate(rspec, 1);
1031   // Assembler::sethi(encoded_k, d);
1032   emit_int32( op(branch_op) | rd(d) | op2(sethi_op2) | hi22(encoded_k) );
1033   // Don't add relocation for 'add'. Do patching during 'sethi' processing.
1034   add(d, low10(encoded_k), d);
1035 
1036 }
1037 
1038 void MacroAssembler::align(int modulus) {
1039   while (offset() % modulus != 0) nop();
1040 }
1041 
1042 void RegistersForDebugging::print(outputStream* s) {
1043   FlagSetting fs(Debugging, true);
1044   int j;
1045   for (j = 0; j < 8; ++j) {
1046     if (j != 6) { s->print("i%d = ", j); os::print_location(s, i[j]); }
1047     else        { s->print( "fp = "   ); os::print_location(s, i[j]); }
1048   }
1049   s->cr();
1050 
1051   for (j = 0;  j < 8;  ++j) {
1052     s->print("l%d = ", j); os::print_location(s, l[j]);
1053   }
1054   s->cr();
1055 
1056   for (j = 0; j < 8; ++j) {
1057     if (j != 6) { s->print("o%d = ", j); os::print_location(s, o[j]); }
1058     else        { s->print( "sp = "   ); os::print_location(s, o[j]); }
1059   }
1060   s->cr();
1061 
1062   for (j = 0; j < 8; ++j) {
1063     s->print("g%d = ", j); os::print_location(s, g[j]);
1064   }
1065   s->cr();
1066 
1067   // print out floats with compression
1068   for (j = 0; j < 32; ) {
1069     jfloat val = f[j];
1070     int last = j;
1071     for ( ;  last+1 < 32;  ++last ) {
1072       char b1[1024], b2[1024];
1073       sprintf(b1, "%f", val);
1074       sprintf(b2, "%f", f[last+1]);
1075       if (strcmp(b1, b2))
1076         break;
1077     }
1078     s->print("f%d", j);
1079     if ( j != last )  s->print(" - f%d", last);
1080     s->print(" = %f", val);
1081     s->fill_to(25);
1082     s->print_cr(" (0x%x)", *(int*)&val);
1083     j = last + 1;
1084   }
1085   s->cr();
1086 
1087   // and doubles (evens only)
1088   for (j = 0; j < 32; ) {
1089     jdouble val = d[j];
1090     int last = j;
1091     for ( ;  last+1 < 32;  ++last ) {
1092       char b1[1024], b2[1024];
1093       sprintf(b1, "%f", val);
1094       sprintf(b2, "%f", d[last+1]);
1095       if (strcmp(b1, b2))
1096         break;
1097     }
1098     s->print("d%d", 2 * j);
1099     if ( j != last )  s->print(" - d%d", last);
1100     s->print(" = %f", val);
1101     s->fill_to(30);
1102     s->print("(0x%x)", *(int*)&val);
1103     s->fill_to(42);
1104     s->print_cr("(0x%x)", *(1 + (int*)&val));
1105     j = last + 1;
1106   }
1107   s->cr();
1108 }
1109 
1110 void RegistersForDebugging::save_registers(MacroAssembler* a) {
1111   a->sub(FP, align_up(sizeof(RegistersForDebugging), sizeof(jdouble)) - STACK_BIAS, O0);
1112   a->flushw();
1113   int i;
1114   for (i = 0; i < 8; ++i) {
1115     a->ld_ptr(as_iRegister(i)->address_in_saved_window().after_save(), L1);  a->st_ptr( L1, O0, i_offset(i));
1116     a->ld_ptr(as_lRegister(i)->address_in_saved_window().after_save(), L1);  a->st_ptr( L1, O0, l_offset(i));
1117     a->st_ptr(as_oRegister(i)->after_save(), O0, o_offset(i));
1118     a->st_ptr(as_gRegister(i)->after_save(), O0, g_offset(i));
1119   }
1120   for (i = 0;  i < 32; ++i) {
1121     a->stf(FloatRegisterImpl::S, as_FloatRegister(i), O0, f_offset(i));
1122   }
1123   for (i = 0; i < 64; i += 2) {
1124     a->stf(FloatRegisterImpl::D, as_FloatRegister(i), O0, d_offset(i));
1125   }
1126 }
1127 
1128 void RegistersForDebugging::restore_registers(MacroAssembler* a, Register r) {
1129   for (int i = 1; i < 8;  ++i) {
1130     a->ld_ptr(r, g_offset(i), as_gRegister(i));
1131   }
1132   for (int j = 0; j < 32; ++j) {
1133     a->ldf(FloatRegisterImpl::S, O0, f_offset(j), as_FloatRegister(j));
1134   }
1135   for (int k = 0; k < 64; k += 2) {
1136     a->ldf(FloatRegisterImpl::D, O0, d_offset(k), as_FloatRegister(k));
1137   }
1138 }
1139 
1140 
1141 // pushes double TOS element of FPU stack on CPU stack; pops from FPU stack
1142 void MacroAssembler::push_fTOS() {
1143   // %%%%%% need to implement this
1144 }
1145 
1146 // pops double TOS element from CPU stack and pushes on FPU stack
1147 void MacroAssembler::pop_fTOS() {
1148   // %%%%%% need to implement this
1149 }
1150 
1151 void MacroAssembler::empty_FPU_stack() {
1152   // %%%%%% need to implement this
1153 }
1154 
1155 void MacroAssembler::_verify_oop(Register reg, const char* msg, const char * file, int line) {
1156   // plausibility check for oops
1157   if (!VerifyOops) return;
1158 
1159   if (reg == G0)  return;       // always NULL, which is always an oop
1160 
1161   BLOCK_COMMENT("verify_oop {");
1162   char buffer[64];
1163 #ifdef COMPILER1
1164   if (CommentedAssembly) {
1165     snprintf(buffer, sizeof(buffer), "verify_oop at %d", offset());
1166     block_comment(buffer);
1167   }
1168 #endif
1169 
1170   const char* real_msg = NULL;
1171   {
1172     ResourceMark rm;
1173     stringStream ss;
1174     ss.print("%s at offset %d (%s:%d)", msg, offset(), file, line);
1175     real_msg = code_string(ss.as_string());
1176   }
1177 
1178   // Call indirectly to solve generation ordering problem
1179   AddressLiteral a(StubRoutines::verify_oop_subroutine_entry_address());
1180 
1181   // Make some space on stack above the current register window.
1182   // Enough to hold 8 64-bit registers.
1183   add(SP,-8*8,SP);
1184 
1185   // Save some 64-bit registers; a normal 'save' chops the heads off
1186   // of 64-bit longs in the 32-bit build.
1187   stx(O0,SP,frame::register_save_words*wordSize+STACK_BIAS+0*8);
1188   stx(O1,SP,frame::register_save_words*wordSize+STACK_BIAS+1*8);
1189   mov(reg,O0); // Move arg into O0; arg might be in O7 which is about to be crushed
1190   stx(O7,SP,frame::register_save_words*wordSize+STACK_BIAS+7*8);
1191 
1192   // Size of set() should stay the same
1193   patchable_set((intptr_t)real_msg, O1);
1194   // Load address to call to into O7
1195   load_ptr_contents(a, O7);
1196   // Register call to verify_oop_subroutine
1197   callr(O7, G0);
1198   delayed()->nop();
1199   // recover frame size
1200   add(SP, 8*8,SP);
1201   BLOCK_COMMENT("} verify_oop");
1202 }
1203 
1204 void MacroAssembler::_verify_oop_addr(Address addr, const char* msg, const char * file, int line) {
1205   // plausibility check for oops
1206   if (!VerifyOops) return;
1207 
1208   const char* real_msg = NULL;
1209   {
1210     ResourceMark rm;
1211     stringStream ss;
1212     ss.print("%s at SP+%d (%s:%d)", msg, addr.disp(), file, line);
1213     real_msg = code_string(ss.as_string());
1214   }
1215 
1216   // Call indirectly to solve generation ordering problem
1217   AddressLiteral a(StubRoutines::verify_oop_subroutine_entry_address());
1218 
1219   // Make some space on stack above the current register window.
1220   // Enough to hold 8 64-bit registers.
1221   add(SP,-8*8,SP);
1222 
1223   // Save some 64-bit registers; a normal 'save' chops the heads off
1224   // of 64-bit longs in the 32-bit build.
1225   stx(O0,SP,frame::register_save_words*wordSize+STACK_BIAS+0*8);
1226   stx(O1,SP,frame::register_save_words*wordSize+STACK_BIAS+1*8);
1227   ld_ptr(addr.base(), addr.disp() + 8*8, O0); // Load arg into O0; arg might be in O7 which is about to be crushed
1228   stx(O7,SP,frame::register_save_words*wordSize+STACK_BIAS+7*8);
1229 
1230   // Size of set() should stay the same
1231   patchable_set((intptr_t)real_msg, O1);
1232   // Load address to call to into O7
1233   load_ptr_contents(a, O7);
1234   // Register call to verify_oop_subroutine
1235   callr(O7, G0);
1236   delayed()->nop();
1237   // recover frame size
1238   add(SP, 8*8,SP);
1239 }
1240 
1241 // side-door communication with signalHandler in os_solaris.cpp
1242 address MacroAssembler::_verify_oop_implicit_branch[3] = { NULL };
1243 
1244 // This macro is expanded just once; it creates shared code.  Contract:
1245 // receives an oop in O0.  Must restore O0 & O7 from TLS.  Must not smash ANY
1246 // registers, including flags.  May not use a register 'save', as this blows
1247 // the high bits of the O-regs if they contain Long values.  Acts as a 'leaf'
1248 // call.
1249 void MacroAssembler::verify_oop_subroutine() {
1250   // Leaf call; no frame.
1251   Label succeed, fail, null_or_fail;
1252 
1253   // O0 and O7 were saved already (O0 in O0's TLS home, O7 in O5's TLS home).
1254   // O0 is now the oop to be checked.  O7 is the return address.
1255   Register O0_obj = O0;
1256 
1257   // Save some more registers for temps.
1258   stx(O2,SP,frame::register_save_words*wordSize+STACK_BIAS+2*8);
1259   stx(O3,SP,frame::register_save_words*wordSize+STACK_BIAS+3*8);
1260   stx(O4,SP,frame::register_save_words*wordSize+STACK_BIAS+4*8);
1261   stx(O5,SP,frame::register_save_words*wordSize+STACK_BIAS+5*8);
1262 
1263   // Save flags
1264   Register O5_save_flags = O5;
1265   rdccr( O5_save_flags );
1266 
1267   { // count number of verifies
1268     Register O2_adr   = O2;
1269     Register O3_accum = O3;
1270     inc_counter(StubRoutines::verify_oop_count_addr(), O2_adr, O3_accum);
1271   }
1272 
1273   Register O2_mask = O2;
1274   Register O3_bits = O3;
1275   Register O4_temp = O4;
1276 
1277   // mark lower end of faulting range
1278   assert(_verify_oop_implicit_branch[0] == NULL, "set once");
1279   _verify_oop_implicit_branch[0] = pc();
1280 
1281   // We can't check the mark oop because it could be in the process of
1282   // locking or unlocking while this is running.
1283   set(Universe::verify_oop_mask (), O2_mask);
1284   set(Universe::verify_oop_bits (), O3_bits);
1285 
1286   // assert((obj & oop_mask) == oop_bits);
1287   and3(O0_obj, O2_mask, O4_temp);
1288   cmp_and_brx_short(O4_temp, O3_bits, notEqual, pn, null_or_fail);
1289 
1290   if ((NULL_WORD & Universe::verify_oop_mask()) == Universe::verify_oop_bits()) {
1291     // the null_or_fail case is useless; must test for null separately
1292     br_null_short(O0_obj, pn, succeed);
1293   }
1294 
1295   // Check the Klass* of this object for being in the right area of memory.
1296   // Cannot do the load in the delay above slot in case O0 is null
1297   load_klass(O0_obj, O0_obj);
1298   // assert((klass != NULL)
1299   br_null_short(O0_obj, pn, fail);
1300 
1301   wrccr( O5_save_flags ); // Restore CCR's
1302 
1303   // mark upper end of faulting range
1304   _verify_oop_implicit_branch[1] = pc();
1305 
1306   //-----------------------
1307   // all tests pass
1308   bind(succeed);
1309 
1310   // Restore prior 64-bit registers
1311   ldx(SP,frame::register_save_words*wordSize+STACK_BIAS+0*8,O0);
1312   ldx(SP,frame::register_save_words*wordSize+STACK_BIAS+1*8,O1);
1313   ldx(SP,frame::register_save_words*wordSize+STACK_BIAS+2*8,O2);
1314   ldx(SP,frame::register_save_words*wordSize+STACK_BIAS+3*8,O3);
1315   ldx(SP,frame::register_save_words*wordSize+STACK_BIAS+4*8,O4);
1316   ldx(SP,frame::register_save_words*wordSize+STACK_BIAS+5*8,O5);
1317 
1318   retl();                       // Leaf return; restore prior O7 in delay slot
1319   delayed()->ldx(SP,frame::register_save_words*wordSize+STACK_BIAS+7*8,O7);
1320 
1321   //-----------------------
1322   bind(null_or_fail);           // nulls are less common but OK
1323   br_null(O0_obj, false, pt, succeed);
1324   delayed()->wrccr( O5_save_flags ); // Restore CCR's
1325 
1326   //-----------------------
1327   // report failure:
1328   bind(fail);
1329   _verify_oop_implicit_branch[2] = pc();
1330 
1331   wrccr( O5_save_flags ); // Restore CCR's
1332 
1333   save_frame(align_up(sizeof(RegistersForDebugging) / BytesPerWord, 2));
1334 
1335   // stop_subroutine expects message pointer in I1.
1336   mov(I1, O1);
1337 
1338   // Restore prior 64-bit registers
1339   ldx(FP,frame::register_save_words*wordSize+STACK_BIAS+0*8,I0);
1340   ldx(FP,frame::register_save_words*wordSize+STACK_BIAS+1*8,I1);
1341   ldx(FP,frame::register_save_words*wordSize+STACK_BIAS+2*8,I2);
1342   ldx(FP,frame::register_save_words*wordSize+STACK_BIAS+3*8,I3);
1343   ldx(FP,frame::register_save_words*wordSize+STACK_BIAS+4*8,I4);
1344   ldx(FP,frame::register_save_words*wordSize+STACK_BIAS+5*8,I5);
1345 
1346   // factor long stop-sequence into subroutine to save space
1347   assert(StubRoutines::Sparc::stop_subroutine_entry_address(), "hasn't been generated yet");
1348 
1349   // call indirectly to solve generation ordering problem
1350   AddressLiteral al(StubRoutines::Sparc::stop_subroutine_entry_address());
1351   load_ptr_contents(al, O5);
1352   jmpl(O5, 0, O7);
1353   delayed()->nop();
1354 }
1355 
1356 
1357 void MacroAssembler::stop(const char* msg) {
1358   // save frame first to get O7 for return address
1359   // add one word to size in case struct is odd number of words long
1360   // It must be doubleword-aligned for storing doubles into it.
1361 
1362     save_frame(align_up(sizeof(RegistersForDebugging) / BytesPerWord, 2));
1363 
1364     // stop_subroutine expects message pointer in I1.
1365     // Size of set() should stay the same
1366     patchable_set((intptr_t)msg, O1);
1367 
1368     // factor long stop-sequence into subroutine to save space
1369     assert(StubRoutines::Sparc::stop_subroutine_entry_address(), "hasn't been generated yet");
1370 
1371     // call indirectly to solve generation ordering problem
1372     AddressLiteral a(StubRoutines::Sparc::stop_subroutine_entry_address());
1373     load_ptr_contents(a, O5);
1374     jmpl(O5, 0, O7);
1375     delayed()->nop();
1376 
1377     breakpoint_trap();   // make stop actually stop rather than writing
1378                          // unnoticeable results in the output files.
1379 
1380     // restore(); done in callee to save space!
1381 }
1382 
1383 
1384 void MacroAssembler::warn(const char* msg) {
1385   save_frame(align_up(sizeof(RegistersForDebugging) / BytesPerWord, 2));
1386   RegistersForDebugging::save_registers(this);
1387   mov(O0, L0);
1388   // Size of set() should stay the same
1389   patchable_set((intptr_t)msg, O0);
1390   call( CAST_FROM_FN_PTR(address, warning) );
1391   delayed()->nop();
1392 //  ret();
1393 //  delayed()->restore();
1394   RegistersForDebugging::restore_registers(this, L0);
1395   restore();
1396 }
1397 
1398 
1399 void MacroAssembler::untested(const char* what) {
1400   // We must be able to turn interactive prompting off
1401   // in order to run automated test scripts on the VM
1402   // Use the flag ShowMessageBoxOnError
1403 
1404   const char* b = NULL;
1405   {
1406     ResourceMark rm;
1407     stringStream ss;
1408     ss.print("untested: %s", what);
1409     b = code_string(ss.as_string());
1410   }
1411   if (ShowMessageBoxOnError) { STOP(b); }
1412   else                       { warn(b); }
1413 }
1414 
1415 
1416 void MacroAssembler::unimplemented(const char* what) {
1417   const char* buf = NULL;
1418   {
1419     ResourceMark rm;
1420     stringStream ss;
1421     ss.print("unimplemented: %s", what);
1422     buf = code_string(ss.as_string());
1423   }
1424   stop(buf);
1425 }
1426 
1427 
1428 void MacroAssembler::stop_subroutine() {
1429   RegistersForDebugging::save_registers(this);
1430 
1431   // for the sake of the debugger, stick a PC on the current frame
1432   // (this assumes that the caller has performed an extra "save")
1433   mov(I7, L7);
1434   add(O7, -7 * BytesPerInt, I7);
1435 
1436   save_frame(); // one more save to free up another O7 register
1437   mov(I0, O1); // addr of reg save area
1438 
1439   // We expect pointer to message in I1. Caller must set it up in O1
1440   mov(I1, O0); // get msg
1441   call (CAST_FROM_FN_PTR(address, MacroAssembler::debug), relocInfo::runtime_call_type);
1442   delayed()->nop();
1443 
1444   restore();
1445 
1446   RegistersForDebugging::restore_registers(this, O0);
1447 
1448   save_frame(0);
1449   call(CAST_FROM_FN_PTR(address,breakpoint));
1450   delayed()->nop();
1451   restore();
1452 
1453   mov(L7, I7);
1454   retl();
1455   delayed()->restore(); // see stop above
1456 }
1457 
1458 
1459 void MacroAssembler::debug(char* msg, RegistersForDebugging* regs) {
1460   if ( ShowMessageBoxOnError ) {
1461     JavaThread* thread = JavaThread::current();
1462     JavaThreadState saved_state = thread->thread_state();
1463     thread->set_thread_state(_thread_in_vm);
1464       {
1465         // In order to get locks work, we need to fake a in_VM state
1466         ttyLocker ttyl;
1467         ::tty->print_cr("EXECUTION STOPPED: %s\n", msg);
1468         if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
1469         BytecodeCounter::print();
1470         }
1471         if (os::message_box(msg, "Execution stopped, print registers?"))
1472           regs->print(::tty);
1473       }
1474     BREAKPOINT;
1475       ThreadStateTransition::transition(JavaThread::current(), _thread_in_vm, saved_state);
1476   }
1477   else {
1478      ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
1479   }
1480   assert(false, "DEBUG MESSAGE: %s", msg);
1481 }
1482 
1483 
1484 void MacroAssembler::calc_mem_param_words(Register Rparam_words, Register Rresult) {
1485   subcc( Rparam_words, Argument::n_register_parameters, Rresult); // how many mem words?
1486   Label no_extras;
1487   br( negative, true, pt, no_extras ); // if neg, clear reg
1488   delayed()->set(0, Rresult);          // annuled, so only if taken
1489   bind( no_extras );
1490 }
1491 
1492 
1493 void MacroAssembler::calc_frame_size(Register Rextra_words, Register Rresult) {
1494   add(Rextra_words, frame::memory_parameter_word_sp_offset, Rresult);
1495   bclr(1, Rresult);
1496   sll(Rresult, LogBytesPerWord, Rresult);  // Rresult has total frame bytes
1497 }
1498 
1499 
1500 void MacroAssembler::calc_frame_size_and_save(Register Rextra_words, Register Rresult) {
1501   calc_frame_size(Rextra_words, Rresult);
1502   neg(Rresult);
1503   save(SP, Rresult, SP);
1504 }
1505 
1506 
1507 // ---------------------------------------------------------
1508 Assembler::RCondition cond2rcond(Assembler::Condition c) {
1509   switch (c) {
1510     /*case zero: */
1511     case Assembler::equal:        return Assembler::rc_z;
1512     case Assembler::lessEqual:    return Assembler::rc_lez;
1513     case Assembler::less:         return Assembler::rc_lz;
1514     /*case notZero:*/
1515     case Assembler::notEqual:     return Assembler::rc_nz;
1516     case Assembler::greater:      return Assembler::rc_gz;
1517     case Assembler::greaterEqual: return Assembler::rc_gez;
1518   }
1519   ShouldNotReachHere();
1520   return Assembler::rc_z;
1521 }
1522 
1523 // compares (32 bit) register with zero and branches.  NOT FOR USE WITH 64-bit POINTERS
1524 void MacroAssembler::cmp_zero_and_br(Condition c, Register s1, Label& L, bool a, Predict p) {
1525   tst(s1);
1526   br (c, a, p, L);
1527 }
1528 
1529 // Compares a pointer register with zero and branches on null.
1530 // Does a test & branch on 32-bit systems and a register-branch on 64-bit.
1531 void MacroAssembler::br_null( Register s1, bool a, Predict p, Label& L ) {
1532   assert_not_delayed();
1533   bpr( rc_z, a, p, s1, L );
1534 }
1535 
1536 void MacroAssembler::br_notnull( Register s1, bool a, Predict p, Label& L ) {
1537   assert_not_delayed();
1538   bpr( rc_nz, a, p, s1, L );
1539 }
1540 
1541 // Compare registers and branch with nop in delay slot or cbcond without delay slot.
1542 
1543 // Compare integer (32 bit) values (icc only).
1544 void MacroAssembler::cmp_and_br_short(Register s1, Register s2, Condition c,
1545                                       Predict p, Label& L) {
1546   assert_not_delayed();
1547   if (use_cbcond(L)) {
1548     Assembler::cbcond(c, icc, s1, s2, L);
1549   } else {
1550     cmp(s1, s2);
1551     br(c, false, p, L);
1552     delayed()->nop();
1553   }
1554 }
1555 
1556 // Compare integer (32 bit) values (icc only).
1557 void MacroAssembler::cmp_and_br_short(Register s1, int simm13a, Condition c,
1558                                       Predict p, Label& L) {
1559   assert_not_delayed();
1560   if (is_simm(simm13a,5) && use_cbcond(L)) {
1561     Assembler::cbcond(c, icc, s1, simm13a, L);
1562   } else {
1563     cmp(s1, simm13a);
1564     br(c, false, p, L);
1565     delayed()->nop();
1566   }
1567 }
1568 
1569 // Branch that tests xcc in LP64 and icc in !LP64
1570 void MacroAssembler::cmp_and_brx_short(Register s1, Register s2, Condition c,
1571                                        Predict p, Label& L) {
1572   assert_not_delayed();
1573   if (use_cbcond(L)) {
1574     Assembler::cbcond(c, ptr_cc, s1, s2, L);
1575   } else {
1576     cmp(s1, s2);
1577     brx(c, false, p, L);
1578     delayed()->nop();
1579   }
1580 }
1581 
1582 // Branch that tests xcc in LP64 and icc in !LP64
1583 void MacroAssembler::cmp_and_brx_short(Register s1, int simm13a, Condition c,
1584                                        Predict p, Label& L) {
1585   assert_not_delayed();
1586   if (is_simm(simm13a,5) && use_cbcond(L)) {
1587     Assembler::cbcond(c, ptr_cc, s1, simm13a, L);
1588   } else {
1589     cmp(s1, simm13a);
1590     brx(c, false, p, L);
1591     delayed()->nop();
1592   }
1593 }
1594 
1595 // Short branch version for compares a pointer with zero.
1596 
1597 void MacroAssembler::br_null_short(Register s1, Predict p, Label& L) {
1598   assert_not_delayed();
1599   if (use_cbcond(L)) {
1600     Assembler::cbcond(zero, ptr_cc, s1, 0, L);
1601   } else {
1602     br_null(s1, false, p, L);
1603     delayed()->nop();
1604   }
1605 }
1606 
1607 void MacroAssembler::br_notnull_short(Register s1, Predict p, Label& L) {
1608   assert_not_delayed();
1609   if (use_cbcond(L)) {
1610     Assembler::cbcond(notZero, ptr_cc, s1, 0, L);
1611   } else {
1612     br_notnull(s1, false, p, L);
1613     delayed()->nop();
1614   }
1615 }
1616 
1617 // Unconditional short branch
1618 void MacroAssembler::ba_short(Label& L) {
1619   assert_not_delayed();
1620   if (use_cbcond(L)) {
1621     Assembler::cbcond(equal, icc, G0, G0, L);
1622   } else {
1623     br(always, false, pt, L);
1624     delayed()->nop();
1625   }
1626 }
1627 
1628 // Branch if 'icc' says zero or not (i.e. icc.z == 1|0).
1629 
1630 void MacroAssembler::br_icc_zero(bool iszero, Predict p, Label &L) {
1631   assert_not_delayed();
1632   Condition cf = (iszero ? Assembler::zero : Assembler::notZero);
1633   br(cf, false, p, L);
1634   delayed()->nop();
1635 }
1636 
1637 // instruction sequences factored across compiler & interpreter
1638 
1639 
1640 void MacroAssembler::lcmp( Register Ra_hi, Register Ra_low,
1641                            Register Rb_hi, Register Rb_low,
1642                            Register Rresult) {
1643 
1644   Label check_low_parts, done;
1645 
1646   cmp(Ra_hi, Rb_hi );  // compare hi parts
1647   br(equal, true, pt, check_low_parts);
1648   delayed()->cmp(Ra_low, Rb_low); // test low parts
1649 
1650   // And, with an unsigned comparison, it does not matter if the numbers
1651   // are negative or not.
1652   // E.g., -2 cmp -1: the low parts are 0xfffffffe and 0xffffffff.
1653   // The second one is bigger (unsignedly).
1654 
1655   // Other notes:  The first move in each triplet can be unconditional
1656   // (and therefore probably prefetchable).
1657   // And the equals case for the high part does not need testing,
1658   // since that triplet is reached only after finding the high halves differ.
1659 
1660   mov(-1, Rresult);
1661   ba(done);
1662   delayed()->movcc(greater, false, icc,  1, Rresult);
1663 
1664   bind(check_low_parts);
1665 
1666   mov(                               -1, Rresult);
1667   movcc(equal,           false, icc,  0, Rresult);
1668   movcc(greaterUnsigned, false, icc,  1, Rresult);
1669 
1670   bind(done);
1671 }
1672 
1673 void MacroAssembler::lneg( Register Rhi, Register Rlow ) {
1674   subcc(  G0, Rlow, Rlow );
1675   subc(   G0, Rhi,  Rhi  );
1676 }
1677 
1678 void MacroAssembler::lshl( Register Rin_high,  Register Rin_low,
1679                            Register Rcount,
1680                            Register Rout_high, Register Rout_low,
1681                            Register Rtemp ) {
1682 
1683 
1684   Register Ralt_count = Rtemp;
1685   Register Rxfer_bits = Rtemp;
1686 
1687   assert( Ralt_count != Rin_high
1688       &&  Ralt_count != Rin_low
1689       &&  Ralt_count != Rcount
1690       &&  Rxfer_bits != Rin_low
1691       &&  Rxfer_bits != Rin_high
1692       &&  Rxfer_bits != Rcount
1693       &&  Rxfer_bits != Rout_low
1694       &&  Rout_low   != Rin_high,
1695         "register alias checks");
1696 
1697   Label big_shift, done;
1698 
1699   // This code can be optimized to use the 64 bit shifts in V9.
1700   // Here we use the 32 bit shifts.
1701 
1702   and3( Rcount, 0x3f, Rcount);     // take least significant 6 bits
1703   subcc(Rcount,   31, Ralt_count);
1704   br(greater, true, pn, big_shift);
1705   delayed()->dec(Ralt_count);
1706 
1707   // shift < 32 bits, Ralt_count = Rcount-31
1708 
1709   // We get the transfer bits by shifting right by 32-count the low
1710   // register. This is done by shifting right by 31-count and then by one
1711   // more to take care of the special (rare) case where count is zero
1712   // (shifting by 32 would not work).
1713 
1714   neg(Ralt_count);
1715 
1716   // The order of the next two instructions is critical in the case where
1717   // Rin and Rout are the same and should not be reversed.
1718 
1719   srl(Rin_low, Ralt_count, Rxfer_bits); // shift right by 31-count
1720   if (Rcount != Rout_low) {
1721     sll(Rin_low, Rcount, Rout_low); // low half
1722   }
1723   sll(Rin_high, Rcount, Rout_high);
1724   if (Rcount == Rout_low) {
1725     sll(Rin_low, Rcount, Rout_low); // low half
1726   }
1727   srl(Rxfer_bits, 1, Rxfer_bits ); // shift right by one more
1728   ba(done);
1729   delayed()->or3(Rout_high, Rxfer_bits, Rout_high);   // new hi value: or in shifted old hi part and xfer from low
1730 
1731   // shift >= 32 bits, Ralt_count = Rcount-32
1732   bind(big_shift);
1733   sll(Rin_low, Ralt_count, Rout_high  );
1734   clr(Rout_low);
1735 
1736   bind(done);
1737 }
1738 
1739 
1740 void MacroAssembler::lshr( Register Rin_high,  Register Rin_low,
1741                            Register Rcount,
1742                            Register Rout_high, Register Rout_low,
1743                            Register Rtemp ) {
1744 
1745   Register Ralt_count = Rtemp;
1746   Register Rxfer_bits = Rtemp;
1747 
1748   assert( Ralt_count != Rin_high
1749       &&  Ralt_count != Rin_low
1750       &&  Ralt_count != Rcount
1751       &&  Rxfer_bits != Rin_low
1752       &&  Rxfer_bits != Rin_high
1753       &&  Rxfer_bits != Rcount
1754       &&  Rxfer_bits != Rout_high
1755       &&  Rout_high  != Rin_low,
1756         "register alias checks");
1757 
1758   Label big_shift, done;
1759 
1760   // This code can be optimized to use the 64 bit shifts in V9.
1761   // Here we use the 32 bit shifts.
1762 
1763   and3( Rcount, 0x3f, Rcount);     // take least significant 6 bits
1764   subcc(Rcount,   31, Ralt_count);
1765   br(greater, true, pn, big_shift);
1766   delayed()->dec(Ralt_count);
1767 
1768   // shift < 32 bits, Ralt_count = Rcount-31
1769 
1770   // We get the transfer bits by shifting left by 32-count the high
1771   // register. This is done by shifting left by 31-count and then by one
1772   // more to take care of the special (rare) case where count is zero
1773   // (shifting by 32 would not work).
1774 
1775   neg(Ralt_count);
1776   if (Rcount != Rout_low) {
1777     srl(Rin_low, Rcount, Rout_low);
1778   }
1779 
1780   // The order of the next two instructions is critical in the case where
1781   // Rin and Rout are the same and should not be reversed.
1782 
1783   sll(Rin_high, Ralt_count, Rxfer_bits); // shift left by 31-count
1784   sra(Rin_high,     Rcount, Rout_high ); // high half
1785   sll(Rxfer_bits,        1, Rxfer_bits); // shift left by one more
1786   if (Rcount == Rout_low) {
1787     srl(Rin_low, Rcount, Rout_low);
1788   }
1789   ba(done);
1790   delayed()->or3(Rout_low, Rxfer_bits, Rout_low); // new low value: or shifted old low part and xfer from high
1791 
1792   // shift >= 32 bits, Ralt_count = Rcount-32
1793   bind(big_shift);
1794 
1795   sra(Rin_high, Ralt_count, Rout_low);
1796   sra(Rin_high,         31, Rout_high); // sign into hi
1797 
1798   bind( done );
1799 }
1800 
1801 
1802 
1803 void MacroAssembler::lushr( Register Rin_high,  Register Rin_low,
1804                             Register Rcount,
1805                             Register Rout_high, Register Rout_low,
1806                             Register Rtemp ) {
1807 
1808   Register Ralt_count = Rtemp;
1809   Register Rxfer_bits = Rtemp;
1810 
1811   assert( Ralt_count != Rin_high
1812       &&  Ralt_count != Rin_low
1813       &&  Ralt_count != Rcount
1814       &&  Rxfer_bits != Rin_low
1815       &&  Rxfer_bits != Rin_high
1816       &&  Rxfer_bits != Rcount
1817       &&  Rxfer_bits != Rout_high
1818       &&  Rout_high  != Rin_low,
1819         "register alias checks");
1820 
1821   Label big_shift, done;
1822 
1823   // This code can be optimized to use the 64 bit shifts in V9.
1824   // Here we use the 32 bit shifts.
1825 
1826   and3( Rcount, 0x3f, Rcount);     // take least significant 6 bits
1827   subcc(Rcount,   31, Ralt_count);
1828   br(greater, true, pn, big_shift);
1829   delayed()->dec(Ralt_count);
1830 
1831   // shift < 32 bits, Ralt_count = Rcount-31
1832 
1833   // We get the transfer bits by shifting left by 32-count the high
1834   // register. This is done by shifting left by 31-count and then by one
1835   // more to take care of the special (rare) case where count is zero
1836   // (shifting by 32 would not work).
1837 
1838   neg(Ralt_count);
1839   if (Rcount != Rout_low) {
1840     srl(Rin_low, Rcount, Rout_low);
1841   }
1842 
1843   // The order of the next two instructions is critical in the case where
1844   // Rin and Rout are the same and should not be reversed.
1845 
1846   sll(Rin_high, Ralt_count, Rxfer_bits); // shift left by 31-count
1847   srl(Rin_high,     Rcount, Rout_high ); // high half
1848   sll(Rxfer_bits,        1, Rxfer_bits); // shift left by one more
1849   if (Rcount == Rout_low) {
1850     srl(Rin_low, Rcount, Rout_low);
1851   }
1852   ba(done);
1853   delayed()->or3(Rout_low, Rxfer_bits, Rout_low); // new low value: or shifted old low part and xfer from high
1854 
1855   // shift >= 32 bits, Ralt_count = Rcount-32
1856   bind(big_shift);
1857 
1858   srl(Rin_high, Ralt_count, Rout_low);
1859   clr(Rout_high);
1860 
1861   bind( done );
1862 }
1863 
1864 void MacroAssembler::lcmp( Register Ra, Register Rb, Register Rresult) {
1865   cmp(Ra, Rb);
1866   mov(-1, Rresult);
1867   movcc(equal,   false, xcc,  0, Rresult);
1868   movcc(greater, false, xcc,  1, Rresult);
1869 }
1870 
1871 
1872 void MacroAssembler::load_sized_value(Address src, Register dst, size_t size_in_bytes, bool is_signed) {
1873   switch (size_in_bytes) {
1874   case  8:  ld_long(src, dst); break;
1875   case  4:  ld(     src, dst); break;
1876   case  2:  is_signed ? ldsh(src, dst) : lduh(src, dst); break;
1877   case  1:  is_signed ? ldsb(src, dst) : ldub(src, dst); break;
1878   default:  ShouldNotReachHere();
1879   }
1880 }
1881 
1882 void MacroAssembler::store_sized_value(Register src, Address dst, size_t size_in_bytes) {
1883   switch (size_in_bytes) {
1884   case  8:  st_long(src, dst); break;
1885   case  4:  st(     src, dst); break;
1886   case  2:  sth(    src, dst); break;
1887   case  1:  stb(    src, dst); break;
1888   default:  ShouldNotReachHere();
1889   }
1890 }
1891 
1892 
1893 void MacroAssembler::float_cmp( bool is_float, int unordered_result,
1894                                 FloatRegister Fa, FloatRegister Fb,
1895                                 Register Rresult) {
1896   if (is_float) {
1897     fcmp(FloatRegisterImpl::S, fcc0, Fa, Fb);
1898   } else {
1899     fcmp(FloatRegisterImpl::D, fcc0, Fa, Fb);
1900   }
1901 
1902   if (unordered_result == 1) {
1903     mov(                                    -1, Rresult);
1904     movcc(f_equal,              true, fcc0,  0, Rresult);
1905     movcc(f_unorderedOrGreater, true, fcc0,  1, Rresult);
1906   } else {
1907     mov(                                    -1, Rresult);
1908     movcc(f_equal,              true, fcc0,  0, Rresult);
1909     movcc(f_greater,            true, fcc0,  1, Rresult);
1910   }
1911 }
1912 
1913 
1914 void MacroAssembler::save_all_globals_into_locals() {
1915   mov(G1,L1);
1916   mov(G2,L2);
1917   mov(G3,L3);
1918   mov(G4,L4);
1919   mov(G5,L5);
1920   mov(G6,L6);
1921   mov(G7,L7);
1922 }
1923 
1924 void MacroAssembler::restore_globals_from_locals() {
1925   mov(L1,G1);
1926   mov(L2,G2);
1927   mov(L3,G3);
1928   mov(L4,G4);
1929   mov(L5,G5);
1930   mov(L6,G6);
1931   mov(L7,G7);
1932 }
1933 
1934 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
1935                                                       Register tmp,
1936                                                       int offset) {
1937   intptr_t value = *delayed_value_addr;
1938   if (value != 0)
1939     return RegisterOrConstant(value + offset);
1940 
1941   // load indirectly to solve generation ordering problem
1942   AddressLiteral a(delayed_value_addr);
1943   load_ptr_contents(a, tmp);
1944 
1945 #ifdef ASSERT
1946   tst(tmp);
1947   breakpoint_trap(zero, xcc);
1948 #endif
1949 
1950   if (offset != 0)
1951     add(tmp, offset, tmp);
1952 
1953   return RegisterOrConstant(tmp);
1954 }
1955 
1956 
1957 RegisterOrConstant MacroAssembler::regcon_andn_ptr(RegisterOrConstant s1, RegisterOrConstant s2, RegisterOrConstant d, Register temp) {
1958   assert(d.register_or_noreg() != G0, "lost side effect");
1959   if ((s2.is_constant() && s2.as_constant() == 0) ||
1960       (s2.is_register() && s2.as_register() == G0)) {
1961     // Do nothing, just move value.
1962     if (s1.is_register()) {
1963       if (d.is_constant())  d = temp;
1964       mov(s1.as_register(), d.as_register());
1965       return d;
1966     } else {
1967       return s1;
1968     }
1969   }
1970 
1971   if (s1.is_register()) {
1972     assert_different_registers(s1.as_register(), temp);
1973     if (d.is_constant())  d = temp;
1974     andn(s1.as_register(), ensure_simm13_or_reg(s2, temp), d.as_register());
1975     return d;
1976   } else {
1977     if (s2.is_register()) {
1978       assert_different_registers(s2.as_register(), temp);
1979       if (d.is_constant())  d = temp;
1980       set(s1.as_constant(), temp);
1981       andn(temp, s2.as_register(), d.as_register());
1982       return d;
1983     } else {
1984       intptr_t res = s1.as_constant() & ~s2.as_constant();
1985       return res;
1986     }
1987   }
1988 }
1989 
1990 RegisterOrConstant MacroAssembler::regcon_inc_ptr(RegisterOrConstant s1, RegisterOrConstant s2, RegisterOrConstant d, Register temp) {
1991   assert(d.register_or_noreg() != G0, "lost side effect");
1992   if ((s2.is_constant() && s2.as_constant() == 0) ||
1993       (s2.is_register() && s2.as_register() == G0)) {
1994     // Do nothing, just move value.
1995     if (s1.is_register()) {
1996       if (d.is_constant())  d = temp;
1997       mov(s1.as_register(), d.as_register());
1998       return d;
1999     } else {
2000       return s1;
2001     }
2002   }
2003 
2004   if (s1.is_register()) {
2005     assert_different_registers(s1.as_register(), temp);
2006     if (d.is_constant())  d = temp;
2007     add(s1.as_register(), ensure_simm13_or_reg(s2, temp), d.as_register());
2008     return d;
2009   } else {
2010     if (s2.is_register()) {
2011       assert_different_registers(s2.as_register(), temp);
2012       if (d.is_constant())  d = temp;
2013       add(s2.as_register(), ensure_simm13_or_reg(s1, temp), d.as_register());
2014       return d;
2015     } else {
2016       intptr_t res = s1.as_constant() + s2.as_constant();
2017       return res;
2018     }
2019   }
2020 }
2021 
2022 RegisterOrConstant MacroAssembler::regcon_sll_ptr(RegisterOrConstant s1, RegisterOrConstant s2, RegisterOrConstant d, Register temp) {
2023   assert(d.register_or_noreg() != G0, "lost side effect");
2024   if (!is_simm13(s2.constant_or_zero()))
2025     s2 = (s2.as_constant() & 0xFF);
2026   if ((s2.is_constant() && s2.as_constant() == 0) ||
2027       (s2.is_register() && s2.as_register() == G0)) {
2028     // Do nothing, just move value.
2029     if (s1.is_register()) {
2030       if (d.is_constant())  d = temp;
2031       mov(s1.as_register(), d.as_register());
2032       return d;
2033     } else {
2034       return s1;
2035     }
2036   }
2037 
2038   if (s1.is_register()) {
2039     assert_different_registers(s1.as_register(), temp);
2040     if (d.is_constant())  d = temp;
2041     sll_ptr(s1.as_register(), ensure_simm13_or_reg(s2, temp), d.as_register());
2042     return d;
2043   } else {
2044     if (s2.is_register()) {
2045       assert_different_registers(s2.as_register(), temp);
2046       if (d.is_constant())  d = temp;
2047       set(s1.as_constant(), temp);
2048       sll_ptr(temp, s2.as_register(), d.as_register());
2049       return d;
2050     } else {
2051       intptr_t res = s1.as_constant() << s2.as_constant();
2052       return res;
2053     }
2054   }
2055 }
2056 
2057 
2058 // Look up the method for a megamorphic invokeinterface call.
2059 // The target method is determined by <intf_klass, itable_index>.
2060 // The receiver klass is in recv_klass.
2061 // On success, the result will be in method_result, and execution falls through.
2062 // On failure, execution transfers to the given label.
2063 void MacroAssembler::lookup_interface_method(Register recv_klass,
2064                                              Register intf_klass,
2065                                              RegisterOrConstant itable_index,
2066                                              Register method_result,
2067                                              Register scan_temp,
2068                                              Register sethi_temp,
2069                                              Label& L_no_such_interface,
2070                                              bool return_method) {
2071   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
2072   assert(!return_method || itable_index.is_constant() || itable_index.as_register() == method_result,
2073          "caller must use same register for non-constant itable index as for method");
2074 
2075   Label L_no_such_interface_restore;
2076   bool did_save = false;
2077   if (scan_temp == noreg || sethi_temp == noreg) {
2078     Register recv_2 = recv_klass->is_global() ? recv_klass : L0;
2079     Register intf_2 = intf_klass->is_global() ? intf_klass : L1;
2080     assert(method_result->is_global(), "must be able to return value");
2081     scan_temp  = L2;
2082     sethi_temp = L3;
2083     save_frame_and_mov(0, recv_klass, recv_2, intf_klass, intf_2);
2084     recv_klass = recv_2;
2085     intf_klass = intf_2;
2086     did_save = true;
2087   }
2088 
2089   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
2090   int vtable_base = in_bytes(Klass::vtable_start_offset());
2091   int scan_step   = itableOffsetEntry::size() * wordSize;
2092   int vte_size    = vtableEntry::size_in_bytes();
2093 
2094   lduw(recv_klass, in_bytes(Klass::vtable_length_offset()), scan_temp);
2095   // %%% We should store the aligned, prescaled offset in the klassoop.
2096   // Then the next several instructions would fold away.
2097 
2098   int itb_offset = vtable_base;
2099   int itb_scale = exact_log2(vtableEntry::size_in_bytes());
2100   sll(scan_temp, itb_scale,  scan_temp);
2101   add(scan_temp, itb_offset, scan_temp);
2102   add(recv_klass, scan_temp, scan_temp);
2103 
2104   if (return_method) {
2105     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
2106     RegisterOrConstant itable_offset = itable_index;
2107     itable_offset = regcon_sll_ptr(itable_index, exact_log2(itableMethodEntry::size() * wordSize), itable_offset);
2108     itable_offset = regcon_inc_ptr(itable_offset, itableMethodEntry::method_offset_in_bytes(), itable_offset);
2109     add(recv_klass, ensure_simm13_or_reg(itable_offset, sethi_temp), recv_klass);
2110   }
2111 
2112   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
2113   //   if (scan->interface() == intf) {
2114   //     result = (klass + scan->offset() + itable_index);
2115   //   }
2116   // }
2117   Label L_search, L_found_method;
2118 
2119   for (int peel = 1; peel >= 0; peel--) {
2120     // %%%% Could load both offset and interface in one ldx, if they were
2121     // in the opposite order.  This would save a load.
2122     ld_ptr(scan_temp, itableOffsetEntry::interface_offset_in_bytes(), method_result);
2123 
2124     // Check that this entry is non-null.  A null entry means that
2125     // the receiver class doesn't implement the interface, and wasn't the
2126     // same as when the caller was compiled.
2127     bpr(Assembler::rc_z, false, Assembler::pn, method_result, did_save ? L_no_such_interface_restore : L_no_such_interface);
2128     delayed()->cmp(method_result, intf_klass);
2129 
2130     if (peel) {
2131       brx(Assembler::equal,    false, Assembler::pt, L_found_method);
2132     } else {
2133       brx(Assembler::notEqual, false, Assembler::pn, L_search);
2134       // (invert the test to fall through to found_method...)
2135     }
2136     delayed()->add(scan_temp, scan_step, scan_temp);
2137 
2138     if (!peel)  break;
2139 
2140     bind(L_search);
2141   }
2142 
2143   bind(L_found_method);
2144 
2145   if (return_method) {
2146     // Got a hit.
2147     int ito_offset = itableOffsetEntry::offset_offset_in_bytes();
2148     // scan_temp[-scan_step] points to the vtable offset we need
2149     ito_offset -= scan_step;
2150     lduw(scan_temp, ito_offset, scan_temp);
2151     ld_ptr(recv_klass, scan_temp, method_result);
2152   }
2153 
2154   if (did_save) {
2155     Label L_done;
2156     ba(L_done);
2157     delayed()->restore();
2158 
2159     bind(L_no_such_interface_restore);
2160     ba(L_no_such_interface);
2161     delayed()->restore();
2162 
2163     bind(L_done);
2164   }
2165 }
2166 
2167 
2168 // virtual method calling
2169 void MacroAssembler::lookup_virtual_method(Register recv_klass,
2170                                            RegisterOrConstant vtable_index,
2171                                            Register method_result) {
2172   assert_different_registers(recv_klass, method_result, vtable_index.register_or_noreg());
2173   Register sethi_temp = method_result;
2174   const int base = in_bytes(Klass::vtable_start_offset()) +
2175                    // method pointer offset within the vtable entry:
2176                    vtableEntry::method_offset_in_bytes();
2177   RegisterOrConstant vtable_offset = vtable_index;
2178   // Each of the following three lines potentially generates an instruction.
2179   // But the total number of address formation instructions will always be
2180   // at most two, and will often be zero.  In any case, it will be optimal.
2181   // If vtable_index is a register, we will have (sll_ptr N,x; inc_ptr B,x; ld_ptr k,x).
2182   // If vtable_index is a constant, we will have at most (set B+X<<N,t; ld_ptr k,t).
2183   vtable_offset = regcon_sll_ptr(vtable_index, exact_log2(vtableEntry::size_in_bytes()), vtable_offset);
2184   vtable_offset = regcon_inc_ptr(vtable_offset, base, vtable_offset, sethi_temp);
2185   Address vtable_entry_addr(recv_klass, ensure_simm13_or_reg(vtable_offset, sethi_temp));
2186   ld_ptr(vtable_entry_addr, method_result);
2187 }
2188 
2189 
2190 void MacroAssembler::check_klass_subtype(Register sub_klass,
2191                                          Register super_klass,
2192                                          Register temp_reg,
2193                                          Register temp2_reg,
2194                                          Label& L_success) {
2195   Register sub_2 = sub_klass;
2196   Register sup_2 = super_klass;
2197   if (!sub_2->is_global())  sub_2 = L0;
2198   if (!sup_2->is_global())  sup_2 = L1;
2199   bool did_save = false;
2200   if (temp_reg == noreg || temp2_reg == noreg) {
2201     temp_reg = L2;
2202     temp2_reg = L3;
2203     save_frame_and_mov(0, sub_klass, sub_2, super_klass, sup_2);
2204     sub_klass = sub_2;
2205     super_klass = sup_2;
2206     did_save = true;
2207   }
2208   Label L_failure, L_pop_to_failure, L_pop_to_success;
2209   check_klass_subtype_fast_path(sub_klass, super_klass,
2210                                 temp_reg, temp2_reg,
2211                                 (did_save ? &L_pop_to_success : &L_success),
2212                                 (did_save ? &L_pop_to_failure : &L_failure), NULL);
2213 
2214   if (!did_save)
2215     save_frame_and_mov(0, sub_klass, sub_2, super_klass, sup_2);
2216   check_klass_subtype_slow_path(sub_2, sup_2,
2217                                 L2, L3, L4, L5,
2218                                 NULL, &L_pop_to_failure);
2219 
2220   // on success:
2221   bind(L_pop_to_success);
2222   restore();
2223   ba_short(L_success);
2224 
2225   // on failure:
2226   bind(L_pop_to_failure);
2227   restore();
2228   bind(L_failure);
2229 }
2230 
2231 
2232 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
2233                                                    Register super_klass,
2234                                                    Register temp_reg,
2235                                                    Register temp2_reg,
2236                                                    Label* L_success,
2237                                                    Label* L_failure,
2238                                                    Label* L_slow_path,
2239                                         RegisterOrConstant super_check_offset) {
2240   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
2241   int sco_offset = in_bytes(Klass::super_check_offset_offset());
2242 
2243   bool must_load_sco  = (super_check_offset.constant_or_zero() == -1);
2244   bool need_slow_path = (must_load_sco ||
2245                          super_check_offset.constant_or_zero() == sco_offset);
2246 
2247   assert_different_registers(sub_klass, super_klass, temp_reg);
2248   if (super_check_offset.is_register()) {
2249     assert_different_registers(sub_klass, super_klass, temp_reg,
2250                                super_check_offset.as_register());
2251   } else if (must_load_sco) {
2252     assert(temp2_reg != noreg, "supply either a temp or a register offset");
2253   }
2254 
2255   Label L_fallthrough;
2256   int label_nulls = 0;
2257   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
2258   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
2259   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
2260   assert(label_nulls <= 1 ||
2261          (L_slow_path == &L_fallthrough && label_nulls <= 2 && !need_slow_path),
2262          "at most one NULL in the batch, usually");
2263 
2264   // If the pointers are equal, we are done (e.g., String[] elements).
2265   // This self-check enables sharing of secondary supertype arrays among
2266   // non-primary types such as array-of-interface.  Otherwise, each such
2267   // type would need its own customized SSA.
2268   // We move this check to the front of the fast path because many
2269   // type checks are in fact trivially successful in this manner,
2270   // so we get a nicely predicted branch right at the start of the check.
2271   cmp(super_klass, sub_klass);
2272   brx(Assembler::equal, false, Assembler::pn, *L_success);
2273   delayed()->nop();
2274 
2275   // Check the supertype display:
2276   if (must_load_sco) {
2277     // The super check offset is always positive...
2278     lduw(super_klass, sco_offset, temp2_reg);
2279     super_check_offset = RegisterOrConstant(temp2_reg);
2280     // super_check_offset is register.
2281     assert_different_registers(sub_klass, super_klass, temp_reg, super_check_offset.as_register());
2282   }
2283   ld_ptr(sub_klass, super_check_offset, temp_reg);
2284   cmp(super_klass, temp_reg);
2285 
2286   // This check has worked decisively for primary supers.
2287   // Secondary supers are sought in the super_cache ('super_cache_addr').
2288   // (Secondary supers are interfaces and very deeply nested subtypes.)
2289   // This works in the same check above because of a tricky aliasing
2290   // between the super_cache and the primary super display elements.
2291   // (The 'super_check_addr' can address either, as the case requires.)
2292   // Note that the cache is updated below if it does not help us find
2293   // what we need immediately.
2294   // So if it was a primary super, we can just fail immediately.
2295   // Otherwise, it's the slow path for us (no success at this point).
2296 
2297   // Hacked ba(), which may only be used just before L_fallthrough.
2298 #define FINAL_JUMP(label)            \
2299   if (&(label) != &L_fallthrough) {  \
2300     ba(label);  delayed()->nop();    \
2301   }
2302 
2303   if (super_check_offset.is_register()) {
2304     brx(Assembler::equal, false, Assembler::pn, *L_success);
2305     delayed()->cmp(super_check_offset.as_register(), sc_offset);
2306 
2307     if (L_failure == &L_fallthrough) {
2308       brx(Assembler::equal, false, Assembler::pt, *L_slow_path);
2309       delayed()->nop();
2310     } else {
2311       brx(Assembler::notEqual, false, Assembler::pn, *L_failure);
2312       delayed()->nop();
2313       FINAL_JUMP(*L_slow_path);
2314     }
2315   } else if (super_check_offset.as_constant() == sc_offset) {
2316     // Need a slow path; fast failure is impossible.
2317     if (L_slow_path == &L_fallthrough) {
2318       brx(Assembler::equal, false, Assembler::pt, *L_success);
2319       delayed()->nop();
2320     } else {
2321       brx(Assembler::notEqual, false, Assembler::pn, *L_slow_path);
2322       delayed()->nop();
2323       FINAL_JUMP(*L_success);
2324     }
2325   } else {
2326     // No slow path; it's a fast decision.
2327     if (L_failure == &L_fallthrough) {
2328       brx(Assembler::equal, false, Assembler::pt, *L_success);
2329       delayed()->nop();
2330     } else {
2331       brx(Assembler::notEqual, false, Assembler::pn, *L_failure);
2332       delayed()->nop();
2333       FINAL_JUMP(*L_success);
2334     }
2335   }
2336 
2337   bind(L_fallthrough);
2338 
2339 #undef FINAL_JUMP
2340 }
2341 
2342 
2343 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
2344                                                    Register super_klass,
2345                                                    Register count_temp,
2346                                                    Register scan_temp,
2347                                                    Register scratch_reg,
2348                                                    Register coop_reg,
2349                                                    Label* L_success,
2350                                                    Label* L_failure) {
2351   assert_different_registers(sub_klass, super_klass,
2352                              count_temp, scan_temp, scratch_reg, coop_reg);
2353 
2354   Label L_fallthrough, L_loop;
2355   int label_nulls = 0;
2356   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
2357   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
2358   assert(label_nulls <= 1, "at most one NULL in the batch");
2359 
2360   // a couple of useful fields in sub_klass:
2361   int ss_offset = in_bytes(Klass::secondary_supers_offset());
2362   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
2363 
2364   // Do a linear scan of the secondary super-klass chain.
2365   // This code is rarely used, so simplicity is a virtue here.
2366 
2367 #ifndef PRODUCT
2368   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
2369   inc_counter((address) pst_counter, count_temp, scan_temp);
2370 #endif
2371 
2372   // We will consult the secondary-super array.
2373   ld_ptr(sub_klass, ss_offset, scan_temp);
2374 
2375   Register search_key = super_klass;
2376 
2377   // Load the array length.  (Positive movl does right thing on LP64.)
2378   lduw(scan_temp, Array<Klass*>::length_offset_in_bytes(), count_temp);
2379 
2380   // Check for empty secondary super list
2381   tst(count_temp);
2382 
2383   // In the array of super classes elements are pointer sized.
2384   int element_size = wordSize;
2385 
2386   // Top of search loop
2387   bind(L_loop);
2388   br(Assembler::equal, false, Assembler::pn, *L_failure);
2389   delayed()->add(scan_temp, element_size, scan_temp);
2390 
2391   // Skip the array header in all array accesses.
2392   int elem_offset = Array<Klass*>::base_offset_in_bytes();
2393   elem_offset -= element_size;   // the scan pointer was pre-incremented also
2394 
2395   // Load next super to check
2396     ld_ptr( scan_temp, elem_offset, scratch_reg );
2397 
2398   // Look for Rsuper_klass on Rsub_klass's secondary super-class-overflow list
2399   cmp(scratch_reg, search_key);
2400 
2401   // A miss means we are NOT a subtype and need to keep looping
2402   brx(Assembler::notEqual, false, Assembler::pn, L_loop);
2403   delayed()->deccc(count_temp); // decrement trip counter in delay slot
2404 
2405   // Success.  Cache the super we found and proceed in triumph.
2406   st_ptr(super_klass, sub_klass, sc_offset);
2407 
2408   if (L_success != &L_fallthrough) {
2409     ba(*L_success);
2410     delayed()->nop();
2411   }
2412 
2413   bind(L_fallthrough);
2414 }
2415 
2416 
2417 RegisterOrConstant MacroAssembler::argument_offset(RegisterOrConstant arg_slot,
2418                                                    Register temp_reg,
2419                                                    int extra_slot_offset) {
2420   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
2421   int stackElementSize = Interpreter::stackElementSize;
2422   int offset = extra_slot_offset * stackElementSize;
2423   if (arg_slot.is_constant()) {
2424     offset += arg_slot.as_constant() * stackElementSize;
2425     return offset;
2426   } else {
2427     assert(temp_reg != noreg, "must specify");
2428     sll_ptr(arg_slot.as_register(), exact_log2(stackElementSize), temp_reg);
2429     if (offset != 0)
2430       add(temp_reg, offset, temp_reg);
2431     return temp_reg;
2432   }
2433 }
2434 
2435 
2436 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
2437                                          Register temp_reg,
2438                                          int extra_slot_offset) {
2439   return Address(Gargs, argument_offset(arg_slot, temp_reg, extra_slot_offset));
2440 }
2441 
2442 
2443 void MacroAssembler::biased_locking_enter(Register obj_reg, Register mark_reg,
2444                                           Register temp_reg,
2445                                           Label& done, Label* slow_case,
2446                                           BiasedLockingCounters* counters) {
2447   assert(UseBiasedLocking, "why call this otherwise?");
2448 
2449   if (PrintBiasedLockingStatistics) {
2450     assert_different_registers(obj_reg, mark_reg, temp_reg, O7);
2451     if (counters == NULL)
2452       counters = BiasedLocking::counters();
2453   }
2454 
2455   Label cas_label;
2456 
2457   // Biased locking
2458   // See whether the lock is currently biased toward our thread and
2459   // whether the epoch is still valid
2460   // Note that the runtime guarantees sufficient alignment of JavaThread
2461   // pointers to allow age to be placed into low bits
2462   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
2463   and3(mark_reg, markOopDesc::biased_lock_mask_in_place, temp_reg);
2464   cmp_and_brx_short(temp_reg, markOopDesc::biased_lock_pattern, Assembler::notEqual, Assembler::pn, cas_label);
2465 
2466   load_klass(obj_reg, temp_reg);
2467   ld_ptr(Address(temp_reg, Klass::prototype_header_offset()), temp_reg);
2468   or3(G2_thread, temp_reg, temp_reg);
2469   xor3(mark_reg, temp_reg, temp_reg);
2470   andcc(temp_reg, ~((int) markOopDesc::age_mask_in_place), temp_reg);
2471   if (counters != NULL) {
2472     cond_inc(Assembler::equal, (address) counters->biased_lock_entry_count_addr(), mark_reg, temp_reg);
2473     // Reload mark_reg as we may need it later
2474     ld_ptr(Address(obj_reg, oopDesc::mark_offset_in_bytes()), mark_reg);
2475   }
2476   brx(Assembler::equal, true, Assembler::pt, done);
2477   delayed()->nop();
2478 
2479   Label try_revoke_bias;
2480   Label try_rebias;
2481   Address mark_addr = Address(obj_reg, oopDesc::mark_offset_in_bytes());
2482   assert(mark_addr.disp() == 0, "cas must take a zero displacement");
2483 
2484   // At this point we know that the header has the bias pattern and
2485   // that we are not the bias owner in the current epoch. We need to
2486   // figure out more details about the state of the header in order to
2487   // know what operations can be legally performed on the object's
2488   // header.
2489 
2490   // If the low three bits in the xor result aren't clear, that means
2491   // the prototype header is no longer biased and we have to revoke
2492   // the bias on this object.
2493   btst(markOopDesc::biased_lock_mask_in_place, temp_reg);
2494   brx(Assembler::notZero, false, Assembler::pn, try_revoke_bias);
2495 
2496   // Biasing is still enabled for this data type. See whether the
2497   // epoch of the current bias is still valid, meaning that the epoch
2498   // bits of the mark word are equal to the epoch bits of the
2499   // prototype header. (Note that the prototype header's epoch bits
2500   // only change at a safepoint.) If not, attempt to rebias the object
2501   // toward the current thread. Note that we must be absolutely sure
2502   // that the current epoch is invalid in order to do this because
2503   // otherwise the manipulations it performs on the mark word are
2504   // illegal.
2505   delayed()->btst(markOopDesc::epoch_mask_in_place, temp_reg);
2506   brx(Assembler::notZero, false, Assembler::pn, try_rebias);
2507 
2508   // The epoch of the current bias is still valid but we know nothing
2509   // about the owner; it might be set or it might be clear. Try to
2510   // acquire the bias of the object using an atomic operation. If this
2511   // fails we will go in to the runtime to revoke the object's bias.
2512   // Note that we first construct the presumed unbiased header so we
2513   // don't accidentally blow away another thread's valid bias.
2514   delayed()->and3(mark_reg,
2515                   markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place,
2516                   mark_reg);
2517   or3(G2_thread, mark_reg, temp_reg);
2518   cas_ptr(mark_addr.base(), mark_reg, temp_reg);
2519   // If the biasing toward our thread failed, this means that
2520   // another thread succeeded in biasing it toward itself and we
2521   // need to revoke that bias. The revocation will occur in the
2522   // interpreter runtime in the slow case.
2523   cmp(mark_reg, temp_reg);
2524   if (counters != NULL) {
2525     cond_inc(Assembler::zero, (address) counters->anonymously_biased_lock_entry_count_addr(), mark_reg, temp_reg);
2526   }
2527   if (slow_case != NULL) {
2528     brx(Assembler::notEqual, true, Assembler::pn, *slow_case);
2529     delayed()->nop();
2530   }
2531   ba_short(done);
2532 
2533   bind(try_rebias);
2534   // At this point we know the epoch has expired, meaning that the
2535   // current "bias owner", if any, is actually invalid. Under these
2536   // circumstances _only_, we are allowed to use the current header's
2537   // value as the comparison value when doing the cas to acquire the
2538   // bias in the current epoch. In other words, we allow transfer of
2539   // the bias from one thread to another directly in this situation.
2540   //
2541   // FIXME: due to a lack of registers we currently blow away the age
2542   // bits in this situation. Should attempt to preserve them.
2543   load_klass(obj_reg, temp_reg);
2544   ld_ptr(Address(temp_reg, Klass::prototype_header_offset()), temp_reg);
2545   or3(G2_thread, temp_reg, temp_reg);
2546   cas_ptr(mark_addr.base(), mark_reg, temp_reg);
2547   // If the biasing toward our thread failed, this means that
2548   // another thread succeeded in biasing it toward itself and we
2549   // need to revoke that bias. The revocation will occur in the
2550   // interpreter runtime in the slow case.
2551   cmp(mark_reg, temp_reg);
2552   if (counters != NULL) {
2553     cond_inc(Assembler::zero, (address) counters->rebiased_lock_entry_count_addr(), mark_reg, temp_reg);
2554   }
2555   if (slow_case != NULL) {
2556     brx(Assembler::notEqual, true, Assembler::pn, *slow_case);
2557     delayed()->nop();
2558   }
2559   ba_short(done);
2560 
2561   bind(try_revoke_bias);
2562   // The prototype mark in the klass doesn't have the bias bit set any
2563   // more, indicating that objects of this data type are not supposed
2564   // to be biased any more. We are going to try to reset the mark of
2565   // this object to the prototype value and fall through to the
2566   // CAS-based locking scheme. Note that if our CAS fails, it means
2567   // that another thread raced us for the privilege of revoking the
2568   // bias of this particular object, so it's okay to continue in the
2569   // normal locking code.
2570   //
2571   // FIXME: due to a lack of registers we currently blow away the age
2572   // bits in this situation. Should attempt to preserve them.
2573   load_klass(obj_reg, temp_reg);
2574   ld_ptr(Address(temp_reg, Klass::prototype_header_offset()), temp_reg);
2575   cas_ptr(mark_addr.base(), mark_reg, temp_reg);
2576   // Fall through to the normal CAS-based lock, because no matter what
2577   // the result of the above CAS, some thread must have succeeded in
2578   // removing the bias bit from the object's header.
2579   if (counters != NULL) {
2580     cmp(mark_reg, temp_reg);
2581     cond_inc(Assembler::zero, (address) counters->revoked_lock_entry_count_addr(), mark_reg, temp_reg);
2582   }
2583 
2584   bind(cas_label);
2585 }
2586 
2587 void MacroAssembler::biased_locking_exit (Address mark_addr, Register temp_reg, Label& done,
2588                                           bool allow_delay_slot_filling) {
2589   // Check for biased locking unlock case, which is a no-op
2590   // Note: we do not have to check the thread ID for two reasons.
2591   // First, the interpreter checks for IllegalMonitorStateException at
2592   // a higher level. Second, if the bias was revoked while we held the
2593   // lock, the object could not be rebiased toward another thread, so
2594   // the bias bit would be clear.
2595   ld_ptr(mark_addr, temp_reg);
2596   and3(temp_reg, markOopDesc::biased_lock_mask_in_place, temp_reg);
2597   cmp(temp_reg, markOopDesc::biased_lock_pattern);
2598   brx(Assembler::equal, allow_delay_slot_filling, Assembler::pt, done);
2599   delayed();
2600   if (!allow_delay_slot_filling) {
2601     nop();
2602   }
2603 }
2604 
2605 
2606 // compiler_lock_object() and compiler_unlock_object() are direct transliterations
2607 // of i486.ad fast_lock() and fast_unlock().  See those methods for detailed comments.
2608 // The code could be tightened up considerably.
2609 //
2610 // box->dhw disposition - post-conditions at DONE_LABEL.
2611 // -   Successful inflated lock:  box->dhw != 0.
2612 //     Any non-zero value suffices.
2613 //     Consider G2_thread, rsp, boxReg, or markOopDesc::unused_mark()
2614 // -   Successful Stack-lock: box->dhw == mark.
2615 //     box->dhw must contain the displaced mark word value
2616 // -   Failure -- icc.ZFlag == 0 and box->dhw is undefined.
2617 //     The slow-path fast_enter() and slow_enter() operators
2618 //     are responsible for setting box->dhw = NonZero (typically markOopDesc::unused_mark()).
2619 // -   Biased: box->dhw is undefined
2620 //
2621 // SPARC refworkload performance - specifically jetstream and scimark - are
2622 // extremely sensitive to the size of the code emitted by compiler_lock_object
2623 // and compiler_unlock_object.  Critically, the key factor is code size, not path
2624 // length.  (Simply experiments to pad CLO with unexecuted NOPs demonstrte the
2625 // effect).
2626 
2627 
2628 void MacroAssembler::compiler_lock_object(Register Roop, Register Rmark,
2629                                           Register Rbox, Register Rscratch,
2630                                           BiasedLockingCounters* counters,
2631                                           bool try_bias) {
2632    Address mark_addr(Roop, oopDesc::mark_offset_in_bytes());
2633 
2634    verify_oop(Roop);
2635    Label done ;
2636 
2637    if (counters != NULL) {
2638      inc_counter((address) counters->total_entry_count_addr(), Rmark, Rscratch);
2639    }
2640 
2641    if (EmitSync & 1) {
2642      mov(3, Rscratch);
2643      st_ptr(Rscratch, Rbox, BasicLock::displaced_header_offset_in_bytes());
2644      cmp(SP, G0);
2645      return ;
2646    }
2647 
2648    if (EmitSync & 2) {
2649 
2650      // Fetch object's markword
2651      ld_ptr(mark_addr, Rmark);
2652 
2653      if (try_bias) {
2654         biased_locking_enter(Roop, Rmark, Rscratch, done, NULL, counters);
2655      }
2656 
2657      // Save Rbox in Rscratch to be used for the cas operation
2658      mov(Rbox, Rscratch);
2659 
2660      // set Rmark to markOop | markOopDesc::unlocked_value
2661      or3(Rmark, markOopDesc::unlocked_value, Rmark);
2662 
2663      // Initialize the box.  (Must happen before we update the object mark!)
2664      st_ptr(Rmark, Rbox, BasicLock::displaced_header_offset_in_bytes());
2665 
2666      // compare object markOop with Rmark and if equal exchange Rscratch with object markOop
2667      assert(mark_addr.disp() == 0, "cas must take a zero displacement");
2668      cas_ptr(mark_addr.base(), Rmark, Rscratch);
2669 
2670      // if compare/exchange succeeded we found an unlocked object and we now have locked it
2671      // hence we are done
2672      cmp(Rmark, Rscratch);
2673      sub(Rscratch, STACK_BIAS, Rscratch);
2674      brx(Assembler::equal, false, Assembler::pt, done);
2675      delayed()->sub(Rscratch, SP, Rscratch);  //pull next instruction into delay slot
2676 
2677      // we did not find an unlocked object so see if this is a recursive case
2678      // sub(Rscratch, SP, Rscratch);
2679      assert(os::vm_page_size() > 0xfff, "page size too small - change the constant");
2680      andcc(Rscratch, 0xfffff003, Rscratch);
2681      st_ptr(Rscratch, Rbox, BasicLock::displaced_header_offset_in_bytes());
2682      bind (done);
2683      return ;
2684    }
2685 
2686    Label Egress ;
2687 
2688    if (EmitSync & 256) {
2689       Label IsInflated ;
2690 
2691       ld_ptr(mark_addr, Rmark);           // fetch obj->mark
2692       // Triage: biased, stack-locked, neutral, inflated
2693       if (try_bias) {
2694         biased_locking_enter(Roop, Rmark, Rscratch, done, NULL, counters);
2695         // Invariant: if control reaches this point in the emitted stream
2696         // then Rmark has not been modified.
2697       }
2698 
2699       // Store mark into displaced mark field in the on-stack basic-lock "box"
2700       // Critically, this must happen before the CAS
2701       // Maximize the ST-CAS distance to minimize the ST-before-CAS penalty.
2702       st_ptr(Rmark, Rbox, BasicLock::displaced_header_offset_in_bytes());
2703       andcc(Rmark, 2, G0);
2704       brx(Assembler::notZero, false, Assembler::pn, IsInflated);
2705       delayed()->
2706 
2707       // Try stack-lock acquisition.
2708       // Beware: the 1st instruction is in a delay slot
2709       mov(Rbox,  Rscratch);
2710       or3(Rmark, markOopDesc::unlocked_value, Rmark);
2711       assert(mark_addr.disp() == 0, "cas must take a zero displacement");
2712       cas_ptr(mark_addr.base(), Rmark, Rscratch);
2713       cmp(Rmark, Rscratch);
2714       brx(Assembler::equal, false, Assembler::pt, done);
2715       delayed()->sub(Rscratch, SP, Rscratch);
2716 
2717       // Stack-lock attempt failed - check for recursive stack-lock.
2718       // See the comments below about how we might remove this case.
2719       sub(Rscratch, STACK_BIAS, Rscratch);
2720       assert(os::vm_page_size() > 0xfff, "page size too small - change the constant");
2721       andcc(Rscratch, 0xfffff003, Rscratch);
2722       br(Assembler::always, false, Assembler::pt, done);
2723       delayed()-> st_ptr(Rscratch, Rbox, BasicLock::displaced_header_offset_in_bytes());
2724 
2725       bind(IsInflated);
2726       if (EmitSync & 64) {
2727          // If m->owner != null goto IsLocked
2728          // Pessimistic form: Test-and-CAS vs CAS
2729          // The optimistic form avoids RTS->RTO cache line upgrades.
2730          ld_ptr(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner), Rscratch);
2731          andcc(Rscratch, Rscratch, G0);
2732          brx(Assembler::notZero, false, Assembler::pn, done);
2733          delayed()->nop();
2734          // m->owner == null : it's unlocked.
2735       }
2736 
2737       // Try to CAS m->owner from null to Self
2738       // Invariant: if we acquire the lock then _recursions should be 0.
2739       add(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner), Rmark);
2740       mov(G2_thread, Rscratch);
2741       cas_ptr(Rmark, G0, Rscratch);
2742       cmp(Rscratch, G0);
2743       // Intentional fall-through into done
2744    } else {
2745       // Aggressively avoid the Store-before-CAS penalty
2746       // Defer the store into box->dhw until after the CAS
2747       Label IsInflated, Recursive ;
2748 
2749 // Anticipate CAS -- Avoid RTS->RTO upgrade
2750 // prefetch (mark_addr, Assembler::severalWritesAndPossiblyReads);
2751 
2752       ld_ptr(mark_addr, Rmark);           // fetch obj->mark
2753       // Triage: biased, stack-locked, neutral, inflated
2754 
2755       if (try_bias) {
2756         biased_locking_enter(Roop, Rmark, Rscratch, done, NULL, counters);
2757         // Invariant: if control reaches this point in the emitted stream
2758         // then Rmark has not been modified.
2759       }
2760       andcc(Rmark, 2, G0);
2761       brx(Assembler::notZero, false, Assembler::pn, IsInflated);
2762       delayed()->                         // Beware - dangling delay-slot
2763 
2764       // Try stack-lock acquisition.
2765       // Transiently install BUSY (0) encoding in the mark word.
2766       // if the CAS of 0 into the mark was successful then we execute:
2767       //   ST box->dhw  = mark   -- save fetched mark in on-stack basiclock box
2768       //   ST obj->mark = box    -- overwrite transient 0 value
2769       // This presumes TSO, of course.
2770 
2771       mov(0, Rscratch);
2772       or3(Rmark, markOopDesc::unlocked_value, Rmark);
2773       assert(mark_addr.disp() == 0, "cas must take a zero displacement");
2774       cas_ptr(mark_addr.base(), Rmark, Rscratch);
2775 // prefetch (mark_addr, Assembler::severalWritesAndPossiblyReads);
2776       cmp(Rscratch, Rmark);
2777       brx(Assembler::notZero, false, Assembler::pn, Recursive);
2778       delayed()->st_ptr(Rmark, Rbox, BasicLock::displaced_header_offset_in_bytes());
2779       if (counters != NULL) {
2780         cond_inc(Assembler::equal, (address) counters->fast_path_entry_count_addr(), Rmark, Rscratch);
2781       }
2782       ba(done);
2783       delayed()->st_ptr(Rbox, mark_addr);
2784 
2785       bind(Recursive);
2786       // Stack-lock attempt failed - check for recursive stack-lock.
2787       // Tests show that we can remove the recursive case with no impact
2788       // on refworkload 0.83.  If we need to reduce the size of the code
2789       // emitted by compiler_lock_object() the recursive case is perfect
2790       // candidate.
2791       //
2792       // A more extreme idea is to always inflate on stack-lock recursion.
2793       // This lets us eliminate the recursive checks in compiler_lock_object
2794       // and compiler_unlock_object and the (box->dhw == 0) encoding.
2795       // A brief experiment - requiring changes to synchronizer.cpp, interpreter,
2796       // and showed a performance *increase*.  In the same experiment I eliminated
2797       // the fast-path stack-lock code from the interpreter and always passed
2798       // control to the "slow" operators in synchronizer.cpp.
2799 
2800       // RScratch contains the fetched obj->mark value from the failed CAS.
2801       sub(Rscratch, STACK_BIAS, Rscratch);
2802       sub(Rscratch, SP, Rscratch);
2803       assert(os::vm_page_size() > 0xfff, "page size too small - change the constant");
2804       andcc(Rscratch, 0xfffff003, Rscratch);
2805       if (counters != NULL) {
2806         // Accounting needs the Rscratch register
2807         st_ptr(Rscratch, Rbox, BasicLock::displaced_header_offset_in_bytes());
2808         cond_inc(Assembler::equal, (address) counters->fast_path_entry_count_addr(), Rmark, Rscratch);
2809         ba_short(done);
2810       } else {
2811         ba(done);
2812         delayed()->st_ptr(Rscratch, Rbox, BasicLock::displaced_header_offset_in_bytes());
2813       }
2814 
2815       bind   (IsInflated);
2816 
2817       // Try to CAS m->owner from null to Self
2818       // Invariant: if we acquire the lock then _recursions should be 0.
2819       add(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner), Rmark);
2820       mov(G2_thread, Rscratch);
2821       cas_ptr(Rmark, G0, Rscratch);
2822       andcc(Rscratch, Rscratch, G0);             // set ICCs for done: icc.zf iff success
2823       // set icc.zf : 1=success 0=failure
2824       // ST box->displaced_header = NonZero.
2825       // Any non-zero value suffices:
2826       //    markOopDesc::unused_mark(), G2_thread, RBox, RScratch, rsp, etc.
2827       st_ptr(Rbox, Rbox, BasicLock::displaced_header_offset_in_bytes());
2828       // Intentional fall-through into done
2829    }
2830 
2831    bind   (done);
2832 }
2833 
2834 void MacroAssembler::compiler_unlock_object(Register Roop, Register Rmark,
2835                                             Register Rbox, Register Rscratch,
2836                                             bool try_bias) {
2837    Address mark_addr(Roop, oopDesc::mark_offset_in_bytes());
2838 
2839    Label done ;
2840 
2841    if (EmitSync & 4) {
2842      cmp(SP, G0);
2843      return ;
2844    }
2845 
2846    if (EmitSync & 8) {
2847      if (try_bias) {
2848         biased_locking_exit(mark_addr, Rscratch, done);
2849      }
2850 
2851      // Test first if it is a fast recursive unlock
2852      ld_ptr(Rbox, BasicLock::displaced_header_offset_in_bytes(), Rmark);
2853      br_null_short(Rmark, Assembler::pt, done);
2854 
2855      // Check if it is still a light weight lock, this is is true if we see
2856      // the stack address of the basicLock in the markOop of the object
2857      assert(mark_addr.disp() == 0, "cas must take a zero displacement");
2858      cas_ptr(mark_addr.base(), Rbox, Rmark);
2859      ba(done);
2860      delayed()->cmp(Rbox, Rmark);
2861      bind(done);
2862      return ;
2863    }
2864 
2865    // Beware ... If the aggregate size of the code emitted by CLO and CUO is
2866    // is too large performance rolls abruptly off a cliff.
2867    // This could be related to inlining policies, code cache management, or
2868    // I$ effects.
2869    Label LStacked ;
2870 
2871    if (try_bias) {
2872       // TODO: eliminate redundant LDs of obj->mark
2873       biased_locking_exit(mark_addr, Rscratch, done);
2874    }
2875 
2876    ld_ptr(Roop, oopDesc::mark_offset_in_bytes(), Rmark);
2877    ld_ptr(Rbox, BasicLock::displaced_header_offset_in_bytes(), Rscratch);
2878    andcc(Rscratch, Rscratch, G0);
2879    brx(Assembler::zero, false, Assembler::pn, done);
2880    delayed()->nop();      // consider: relocate fetch of mark, above, into this DS
2881    andcc(Rmark, 2, G0);
2882    brx(Assembler::zero, false, Assembler::pt, LStacked);
2883    delayed()->nop();
2884 
2885    // It's inflated
2886    // Conceptually we need a #loadstore|#storestore "release" MEMBAR before
2887    // the ST of 0 into _owner which releases the lock.  This prevents loads
2888    // and stores within the critical section from reordering (floating)
2889    // past the store that releases the lock.  But TSO is a strong memory model
2890    // and that particular flavor of barrier is a noop, so we can safely elide it.
2891    // Note that we use 1-0 locking by default for the inflated case.  We
2892    // close the resultant (and rare) race by having contended threads in
2893    // monitorenter periodically poll _owner.
2894 
2895    if (EmitSync & 1024) {
2896      // Emit code to check that _owner == Self
2897      // We could fold the _owner test into subsequent code more efficiently
2898      // than using a stand-alone check, but since _owner checking is off by
2899      // default we don't bother. We also might consider predicating the
2900      // _owner==Self check on Xcheck:jni or running on a debug build.
2901      ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), Rscratch);
2902      orcc(Rscratch, G0, G0);
2903      brx(Assembler::notZero, false, Assembler::pn, done);
2904      delayed()->nop();
2905    }
2906 
2907    if (EmitSync & 512) {
2908      // classic lock release code absent 1-0 locking
2909      //   m->Owner = null;
2910      //   membar #storeload
2911      //   if (m->cxq|m->EntryList) == null goto Success
2912      //   if (m->succ != null) goto Success
2913      //   if CAS (&m->Owner,0,Self) != 0 goto Success
2914      //   goto SlowPath
2915      ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)), Rbox);
2916      orcc(Rbox, G0, G0);
2917      brx(Assembler::notZero, false, Assembler::pn, done);
2918      delayed()->nop();
2919      st_ptr(G0, Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2920      if (os::is_MP()) { membar(StoreLoad); }
2921      ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)), Rscratch);
2922      ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)), Rbox);
2923      orcc(Rbox, Rscratch, G0);
2924      brx(Assembler::zero, false, Assembler::pt, done);
2925      delayed()->
2926      ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), Rscratch);
2927      andcc(Rscratch, Rscratch, G0);
2928      brx(Assembler::notZero, false, Assembler::pt, done);
2929      delayed()->andcc(G0, G0, G0);
2930      add(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner), Rmark);
2931      mov(G2_thread, Rscratch);
2932      cas_ptr(Rmark, G0, Rscratch);
2933      cmp(Rscratch, G0);
2934      // invert icc.zf and goto done
2935      brx(Assembler::notZero, false, Assembler::pt, done);
2936      delayed()->cmp(G0, G0);
2937      br(Assembler::always, false, Assembler::pt, done);
2938      delayed()->cmp(G0, 1);
2939    } else {
2940      // 1-0 form : avoids CAS and MEMBAR in the common case
2941      // Do not bother to ratify that m->Owner == Self.
2942      ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)), Rbox);
2943      orcc(Rbox, G0, G0);
2944      brx(Assembler::notZero, false, Assembler::pn, done);
2945      delayed()->
2946      ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)), Rscratch);
2947      ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)), Rbox);
2948      orcc(Rbox, Rscratch, G0);
2949      if (EmitSync & 16384) {
2950        // As an optional optimization, if (EntryList|cxq) != null and _succ is null then
2951        // we should transfer control directly to the slow-path.
2952        // This test makes the reacquire operation below very infrequent.
2953        // The logic is equivalent to :
2954        //   if (cxq|EntryList) == null : Owner=null; goto Success
2955        //   if succ == null : goto SlowPath
2956        //   Owner=null; membar #storeload
2957        //   if succ != null : goto Success
2958        //   if CAS(&Owner,null,Self) != null goto Success
2959        //   goto SlowPath
2960        brx(Assembler::zero, true, Assembler::pt, done);
2961        delayed()->
2962        st_ptr(G0, Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2963        ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), Rscratch);
2964        andcc(Rscratch, Rscratch, G0) ;
2965        brx(Assembler::zero, false, Assembler::pt, done);
2966        delayed()->orcc(G0, 1, G0);
2967        st_ptr(G0, Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2968      } else {
2969        brx(Assembler::zero, false, Assembler::pt, done);
2970        delayed()->
2971        st_ptr(G0, Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2972      }
2973      if (os::is_MP()) { membar(StoreLoad); }
2974      // Check that _succ is (or remains) non-zero
2975      ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), Rscratch);
2976      andcc(Rscratch, Rscratch, G0);
2977      brx(Assembler::notZero, false, Assembler::pt, done);
2978      delayed()->andcc(G0, G0, G0);
2979      add(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner), Rmark);
2980      mov(G2_thread, Rscratch);
2981      cas_ptr(Rmark, G0, Rscratch);
2982      cmp(Rscratch, G0);
2983      // invert icc.zf and goto done
2984      // A slightly better v8+/v9 idiom would be the following:
2985      //   movrnz Rscratch,1,Rscratch
2986      //   ba done
2987      //   xorcc Rscratch,1,G0
2988      // In v8+ mode the idiom would be valid IFF Rscratch was a G or O register
2989      brx(Assembler::notZero, false, Assembler::pt, done);
2990      delayed()->cmp(G0, G0);
2991      br(Assembler::always, false, Assembler::pt, done);
2992      delayed()->cmp(G0, 1);
2993    }
2994 
2995    bind   (LStacked);
2996    // Consider: we could replace the expensive CAS in the exit
2997    // path with a simple ST of the displaced mark value fetched from
2998    // the on-stack basiclock box.  That admits a race where a thread T2
2999    // in the slow lock path -- inflating with monitor M -- could race a
3000    // thread T1 in the fast unlock path, resulting in a missed wakeup for T2.
3001    // More precisely T1 in the stack-lock unlock path could "stomp" the
3002    // inflated mark value M installed by T2, resulting in an orphan
3003    // object monitor M and T2 becoming stranded.  We can remedy that situation
3004    // by having T2 periodically poll the object's mark word using timed wait
3005    // operations.  If T2 discovers that a stomp has occurred it vacates
3006    // the monitor M and wakes any other threads stranded on the now-orphan M.
3007    // In addition the monitor scavenger, which performs deflation,
3008    // would also need to check for orpan monitors and stranded threads.
3009    //
3010    // Finally, inflation is also used when T2 needs to assign a hashCode
3011    // to O and O is stack-locked by T1.  The "stomp" race could cause
3012    // an assigned hashCode value to be lost.  We can avoid that condition
3013    // and provide the necessary hashCode stability invariants by ensuring
3014    // that hashCode generation is idempotent between copying GCs.
3015    // For example we could compute the hashCode of an object O as
3016    // O's heap address XOR some high quality RNG value that is refreshed
3017    // at GC-time.  The monitor scavenger would install the hashCode
3018    // found in any orphan monitors.  Again, the mechanism admits a
3019    // lost-update "stomp" WAW race but detects and recovers as needed.
3020    //
3021    // A prototype implementation showed excellent results, although
3022    // the scavenger and timeout code was rather involved.
3023 
3024    cas_ptr(mark_addr.base(), Rbox, Rscratch);
3025    cmp(Rbox, Rscratch);
3026    // Intentional fall through into done ...
3027 
3028    bind(done);
3029 }
3030 
3031 
3032 
3033 void MacroAssembler::print_CPU_state() {
3034   // %%%%% need to implement this
3035 }
3036 
3037 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
3038   // %%%%% need to implement this
3039 }
3040 
3041 void MacroAssembler::push_IU_state() {
3042   // %%%%% need to implement this
3043 }
3044 
3045 
3046 void MacroAssembler::pop_IU_state() {
3047   // %%%%% need to implement this
3048 }
3049 
3050 
3051 void MacroAssembler::push_FPU_state() {
3052   // %%%%% need to implement this
3053 }
3054 
3055 
3056 void MacroAssembler::pop_FPU_state() {
3057   // %%%%% need to implement this
3058 }
3059 
3060 
3061 void MacroAssembler::push_CPU_state() {
3062   // %%%%% need to implement this
3063 }
3064 
3065 
3066 void MacroAssembler::pop_CPU_state() {
3067   // %%%%% need to implement this
3068 }
3069 
3070 
3071 
3072 void MacroAssembler::verify_tlab() {
3073 #ifdef ASSERT
3074   if (UseTLAB && VerifyOops) {
3075     Label next, next2, ok;
3076     Register t1 = L0;
3077     Register t2 = L1;
3078     Register t3 = L2;
3079 
3080     save_frame(0);
3081     ld_ptr(G2_thread, in_bytes(JavaThread::tlab_top_offset()), t1);
3082     ld_ptr(G2_thread, in_bytes(JavaThread::tlab_start_offset()), t2);
3083     or3(t1, t2, t3);
3084     cmp_and_br_short(t1, t2, Assembler::greaterEqual, Assembler::pn, next);
3085     STOP("assert(top >= start)");
3086     should_not_reach_here();
3087 
3088     bind(next);
3089     ld_ptr(G2_thread, in_bytes(JavaThread::tlab_top_offset()), t1);
3090     ld_ptr(G2_thread, in_bytes(JavaThread::tlab_end_offset()), t2);
3091     or3(t3, t2, t3);
3092     cmp_and_br_short(t1, t2, Assembler::lessEqual, Assembler::pn, next2);
3093     STOP("assert(top <= end)");
3094     should_not_reach_here();
3095 
3096     bind(next2);
3097     and3(t3, MinObjAlignmentInBytesMask, t3);
3098     cmp_and_br_short(t3, 0, Assembler::lessEqual, Assembler::pn, ok);
3099     STOP("assert(aligned)");
3100     should_not_reach_here();
3101 
3102     bind(ok);
3103     restore();
3104   }
3105 #endif
3106 }
3107 
3108 
3109 void MacroAssembler::eden_allocate(
3110   Register obj,                        // result: pointer to object after successful allocation
3111   Register var_size_in_bytes,          // object size in bytes if unknown at compile time; invalid otherwise
3112   int      con_size_in_bytes,          // object size in bytes if   known at compile time
3113   Register t1,                         // temp register
3114   Register t2,                         // temp register
3115   Label&   slow_case                   // continuation point if fast allocation fails
3116 ){
3117   // make sure arguments make sense
3118   assert_different_registers(obj, var_size_in_bytes, t1, t2);
3119   assert(0 <= con_size_in_bytes && Assembler::is_simm13(con_size_in_bytes), "illegal object size");
3120   assert((con_size_in_bytes & MinObjAlignmentInBytesMask) == 0, "object size is not multiple of alignment");
3121 
3122   if (!Universe::heap()->supports_inline_contig_alloc()) {
3123     // No allocation in the shared eden.
3124     ba(slow_case);
3125     delayed()->nop();
3126   } else {
3127     // get eden boundaries
3128     // note: we need both top & top_addr!
3129     const Register top_addr = t1;
3130     const Register end      = t2;
3131 
3132     CollectedHeap* ch = Universe::heap();
3133     set((intx)ch->top_addr(), top_addr);
3134     intx delta = (intx)ch->end_addr() - (intx)ch->top_addr();
3135     ld_ptr(top_addr, delta, end);
3136     ld_ptr(top_addr, 0, obj);
3137 
3138     // try to allocate
3139     Label retry;
3140     bind(retry);
3141 #ifdef ASSERT
3142     // make sure eden top is properly aligned
3143     {
3144       Label L;
3145       btst(MinObjAlignmentInBytesMask, obj);
3146       br(Assembler::zero, false, Assembler::pt, L);
3147       delayed()->nop();
3148       STOP("eden top is not properly aligned");
3149       bind(L);
3150     }
3151 #endif // ASSERT
3152     const Register free = end;
3153     sub(end, obj, free);                                   // compute amount of free space
3154     if (var_size_in_bytes->is_valid()) {
3155       // size is unknown at compile time
3156       cmp(free, var_size_in_bytes);
3157       brx(Assembler::lessUnsigned, false, Assembler::pn, slow_case); // if there is not enough space go the slow case
3158       delayed()->add(obj, var_size_in_bytes, end);
3159     } else {
3160       // size is known at compile time
3161       cmp(free, con_size_in_bytes);
3162       brx(Assembler::lessUnsigned, false, Assembler::pn, slow_case); // if there is not enough space go the slow case
3163       delayed()->add(obj, con_size_in_bytes, end);
3164     }
3165     // Compare obj with the value at top_addr; if still equal, swap the value of
3166     // end with the value at top_addr. If not equal, read the value at top_addr
3167     // into end.
3168     cas_ptr(top_addr, obj, end);
3169     // if someone beat us on the allocation, try again, otherwise continue
3170     cmp(obj, end);
3171     brx(Assembler::notEqual, false, Assembler::pn, retry);
3172     delayed()->mov(end, obj);                              // nop if successfull since obj == end
3173 
3174 #ifdef ASSERT
3175     // make sure eden top is properly aligned
3176     {
3177       Label L;
3178       const Register top_addr = t1;
3179 
3180       set((intx)ch->top_addr(), top_addr);
3181       ld_ptr(top_addr, 0, top_addr);
3182       btst(MinObjAlignmentInBytesMask, top_addr);
3183       br(Assembler::zero, false, Assembler::pt, L);
3184       delayed()->nop();
3185       STOP("eden top is not properly aligned");
3186       bind(L);
3187     }
3188 #endif // ASSERT
3189   }
3190 }
3191 
3192 
3193 void MacroAssembler::tlab_allocate(
3194   Register obj,                        // result: pointer to object after successful allocation
3195   Register var_size_in_bytes,          // object size in bytes if unknown at compile time; invalid otherwise
3196   int      con_size_in_bytes,          // object size in bytes if   known at compile time
3197   Register t1,                         // temp register
3198   Label&   slow_case                   // continuation point if fast allocation fails
3199 ){
3200   // make sure arguments make sense
3201   assert_different_registers(obj, var_size_in_bytes, t1);
3202   assert(0 <= con_size_in_bytes && is_simm13(con_size_in_bytes), "illegal object size");
3203   assert((con_size_in_bytes & MinObjAlignmentInBytesMask) == 0, "object size is not multiple of alignment");
3204 
3205   const Register free  = t1;
3206 
3207   verify_tlab();
3208 
3209   ld_ptr(G2_thread, in_bytes(JavaThread::tlab_top_offset()), obj);
3210 
3211   // calculate amount of free space
3212   ld_ptr(G2_thread, in_bytes(JavaThread::tlab_end_offset()), free);
3213   sub(free, obj, free);
3214 
3215   Label done;
3216   if (var_size_in_bytes == noreg) {
3217     cmp(free, con_size_in_bytes);
3218   } else {
3219     cmp(free, var_size_in_bytes);
3220   }
3221   br(Assembler::less, false, Assembler::pn, slow_case);
3222   // calculate the new top pointer
3223   if (var_size_in_bytes == noreg) {
3224     delayed()->add(obj, con_size_in_bytes, free);
3225   } else {
3226     delayed()->add(obj, var_size_in_bytes, free);
3227   }
3228 
3229   bind(done);
3230 
3231 #ifdef ASSERT
3232   // make sure new free pointer is properly aligned
3233   {
3234     Label L;
3235     btst(MinObjAlignmentInBytesMask, free);
3236     br(Assembler::zero, false, Assembler::pt, L);
3237     delayed()->nop();
3238     STOP("updated TLAB free is not properly aligned");
3239     bind(L);
3240   }
3241 #endif // ASSERT
3242 
3243   // update the tlab top pointer
3244   st_ptr(free, G2_thread, in_bytes(JavaThread::tlab_top_offset()));
3245   verify_tlab();
3246 }
3247 
3248 void MacroAssembler::zero_memory(Register base, Register index) {
3249   assert_different_registers(base, index);
3250   Label loop;
3251   bind(loop);
3252   subcc(index, HeapWordSize, index);
3253   brx(Assembler::greaterEqual, true, Assembler::pt, loop);
3254   delayed()->st_ptr(G0, base, index);
3255 }
3256 
3257 void MacroAssembler::incr_allocated_bytes(RegisterOrConstant size_in_bytes,
3258                                           Register t1, Register t2) {
3259   // Bump total bytes allocated by this thread
3260   assert(t1->is_global(), "must be global reg"); // so all 64 bits are saved on a context switch
3261   assert_different_registers(size_in_bytes.register_or_noreg(), t1, t2);
3262   // v8 support has gone the way of the dodo
3263   ldx(G2_thread, in_bytes(JavaThread::allocated_bytes_offset()), t1);
3264   add(t1, ensure_simm13_or_reg(size_in_bytes, t2), t1);
3265   stx(t1, G2_thread, in_bytes(JavaThread::allocated_bytes_offset()));
3266 }
3267 
3268 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
3269   switch (cond) {
3270     // Note some conditions are synonyms for others
3271     case Assembler::never:                return Assembler::always;
3272     case Assembler::zero:                 return Assembler::notZero;
3273     case Assembler::lessEqual:            return Assembler::greater;
3274     case Assembler::less:                 return Assembler::greaterEqual;
3275     case Assembler::lessEqualUnsigned:    return Assembler::greaterUnsigned;
3276     case Assembler::lessUnsigned:         return Assembler::greaterEqualUnsigned;
3277     case Assembler::negative:             return Assembler::positive;
3278     case Assembler::overflowSet:          return Assembler::overflowClear;
3279     case Assembler::always:               return Assembler::never;
3280     case Assembler::notZero:              return Assembler::zero;
3281     case Assembler::greater:              return Assembler::lessEqual;
3282     case Assembler::greaterEqual:         return Assembler::less;
3283     case Assembler::greaterUnsigned:      return Assembler::lessEqualUnsigned;
3284     case Assembler::greaterEqualUnsigned: return Assembler::lessUnsigned;
3285     case Assembler::positive:             return Assembler::negative;
3286     case Assembler::overflowClear:        return Assembler::overflowSet;
3287   }
3288 
3289   ShouldNotReachHere(); return Assembler::overflowClear;
3290 }
3291 
3292 void MacroAssembler::cond_inc(Assembler::Condition cond, address counter_ptr,
3293                               Register Rtmp1, Register Rtmp2 /*, Register Rtmp3, Register Rtmp4 */) {
3294   Condition negated_cond = negate_condition(cond);
3295   Label L;
3296   brx(negated_cond, false, Assembler::pt, L);
3297   delayed()->nop();
3298   inc_counter(counter_ptr, Rtmp1, Rtmp2);
3299   bind(L);
3300 }
3301 
3302 void MacroAssembler::inc_counter(address counter_addr, Register Rtmp1, Register Rtmp2) {
3303   AddressLiteral addrlit(counter_addr);
3304   sethi(addrlit, Rtmp1);                 // Move hi22 bits into temporary register.
3305   Address addr(Rtmp1, addrlit.low10());  // Build an address with low10 bits.
3306   ld(addr, Rtmp2);
3307   inc(Rtmp2);
3308   st(Rtmp2, addr);
3309 }
3310 
3311 void MacroAssembler::inc_counter(int* counter_addr, Register Rtmp1, Register Rtmp2) {
3312   inc_counter((address) counter_addr, Rtmp1, Rtmp2);
3313 }
3314 
3315 SkipIfEqual::SkipIfEqual(
3316     MacroAssembler* masm, Register temp, const bool* flag_addr,
3317     Assembler::Condition condition) {
3318   _masm = masm;
3319   AddressLiteral flag(flag_addr);
3320   _masm->sethi(flag, temp);
3321   _masm->ldub(temp, flag.low10(), temp);
3322   _masm->tst(temp);
3323   _masm->br(condition, false, Assembler::pt, _label);
3324   _masm->delayed()->nop();
3325 }
3326 
3327 SkipIfEqual::~SkipIfEqual() {
3328   _masm->bind(_label);
3329 }
3330 
3331 
3332 // Writes to stack successive pages until offset reached to check for
3333 // stack overflow + shadow pages.  This clobbers tsp and scratch.
3334 void MacroAssembler::bang_stack_size(Register Rsize, Register Rtsp,
3335                                      Register Rscratch) {
3336   // Use stack pointer in temp stack pointer
3337   mov(SP, Rtsp);
3338 
3339   // Bang stack for total size given plus stack shadow page size.
3340   // Bang one page at a time because a large size can overflow yellow and
3341   // red zones (the bang will fail but stack overflow handling can't tell that
3342   // it was a stack overflow bang vs a regular segv).
3343   int offset = os::vm_page_size();
3344   Register Roffset = Rscratch;
3345 
3346   Label loop;
3347   bind(loop);
3348   set((-offset)+STACK_BIAS, Rscratch);
3349   st(G0, Rtsp, Rscratch);
3350   set(offset, Roffset);
3351   sub(Rsize, Roffset, Rsize);
3352   cmp(Rsize, G0);
3353   br(Assembler::greater, false, Assembler::pn, loop);
3354   delayed()->sub(Rtsp, Roffset, Rtsp);
3355 
3356   // Bang down shadow pages too.
3357   // At this point, (tmp-0) is the last address touched, so don't
3358   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
3359   // was post-decremented.)  Skip this address by starting at i=1, and
3360   // touch a few more pages below.  N.B.  It is important to touch all
3361   // the way down to and including i=StackShadowPages.
3362   for (int i = 1; i < JavaThread::stack_shadow_zone_size() / os::vm_page_size(); i++) {
3363     set((-i*offset)+STACK_BIAS, Rscratch);
3364     st(G0, Rtsp, Rscratch);
3365   }
3366 }
3367 
3368 void MacroAssembler::reserved_stack_check() {
3369   // testing if reserved zone needs to be enabled
3370   Label no_reserved_zone_enabling;
3371 
3372   ld_ptr(G2_thread, JavaThread::reserved_stack_activation_offset(), G4_scratch);
3373   cmp_and_brx_short(SP, G4_scratch, Assembler::lessUnsigned, Assembler::pt, no_reserved_zone_enabling);
3374 
3375   call_VM_leaf(L0, CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), G2_thread);
3376 
3377   AddressLiteral stub(StubRoutines::throw_delayed_StackOverflowError_entry());
3378   jump_to(stub, G4_scratch);
3379   delayed()->restore();
3380 
3381   should_not_reach_here();
3382 
3383   bind(no_reserved_zone_enabling);
3384 }
3385 
3386 ///////////////////////////////////////////////////////////////////////////////////
3387 #if INCLUDE_ALL_GCS
3388 
3389 static address satb_log_enqueue_with_frame = NULL;
3390 static u_char* satb_log_enqueue_with_frame_end = NULL;
3391 
3392 static address satb_log_enqueue_frameless = NULL;
3393 static u_char* satb_log_enqueue_frameless_end = NULL;
3394 
3395 static int EnqueueCodeSize = 128 DEBUG_ONLY( + 256); // Instructions?
3396 
3397 static void generate_satb_log_enqueue(bool with_frame) {
3398   BufferBlob* bb = BufferBlob::create("enqueue_with_frame", EnqueueCodeSize);
3399   CodeBuffer buf(bb);
3400   MacroAssembler masm(&buf);
3401 
3402 #define __ masm.
3403 
3404   address start = __ pc();
3405   Register pre_val;
3406 
3407   Label refill, restart;
3408   if (with_frame) {
3409     __ save_frame(0);
3410     pre_val = I0;  // Was O0 before the save.
3411   } else {
3412     pre_val = O0;
3413   }
3414 
3415   int satb_q_index_byte_offset =
3416     in_bytes(JavaThread::satb_mark_queue_offset() +
3417              SATBMarkQueue::byte_offset_of_index());
3418 
3419   int satb_q_buf_byte_offset =
3420     in_bytes(JavaThread::satb_mark_queue_offset() +
3421              SATBMarkQueue::byte_offset_of_buf());
3422 
3423   assert(in_bytes(SATBMarkQueue::byte_width_of_index()) == sizeof(intptr_t) &&
3424          in_bytes(SATBMarkQueue::byte_width_of_buf()) == sizeof(intptr_t),
3425          "check sizes in assembly below");
3426 
3427   __ bind(restart);
3428 
3429   // Load the index into the SATB buffer. SATBMarkQueue::_index is a size_t
3430   // so ld_ptr is appropriate.
3431   __ ld_ptr(G2_thread, satb_q_index_byte_offset, L0);
3432 
3433   // index == 0?
3434   __ cmp_and_brx_short(L0, G0, Assembler::equal, Assembler::pn, refill);
3435 
3436   __ ld_ptr(G2_thread, satb_q_buf_byte_offset, L1);
3437   __ sub(L0, oopSize, L0);
3438 
3439   __ st_ptr(pre_val, L1, L0);  // [_buf + index] := I0
3440   if (!with_frame) {
3441     // Use return-from-leaf
3442     __ retl();
3443     __ delayed()->st_ptr(L0, G2_thread, satb_q_index_byte_offset);
3444   } else {
3445     // Not delayed.
3446     __ st_ptr(L0, G2_thread, satb_q_index_byte_offset);
3447   }
3448   if (with_frame) {
3449     __ ret();
3450     __ delayed()->restore();
3451   }
3452   __ bind(refill);
3453 
3454   address handle_zero =
3455     CAST_FROM_FN_PTR(address,
3456                      &SATBMarkQueueSet::handle_zero_index_for_thread);
3457   // This should be rare enough that we can afford to save all the
3458   // scratch registers that the calling context might be using.
3459   __ mov(G1_scratch, L0);
3460   __ mov(G3_scratch, L1);
3461   __ mov(G4, L2);
3462   // We need the value of O0 above (for the write into the buffer), so we
3463   // save and restore it.
3464   __ mov(O0, L3);
3465   // Since the call will overwrite O7, we save and restore that, as well.
3466   __ mov(O7, L4);
3467   __ call_VM_leaf(L5, handle_zero, G2_thread);
3468   __ mov(L0, G1_scratch);
3469   __ mov(L1, G3_scratch);
3470   __ mov(L2, G4);
3471   __ mov(L3, O0);
3472   __ br(Assembler::always, /*annul*/false, Assembler::pt, restart);
3473   __ delayed()->mov(L4, O7);
3474 
3475   if (with_frame) {
3476     satb_log_enqueue_with_frame = start;
3477     satb_log_enqueue_with_frame_end = __ pc();
3478   } else {
3479     satb_log_enqueue_frameless = start;
3480     satb_log_enqueue_frameless_end = __ pc();
3481   }
3482 
3483 #undef __
3484 }
3485 
3486 void MacroAssembler::g1_write_barrier_pre(Register obj,
3487                                           Register index,
3488                                           int offset,
3489                                           Register pre_val,
3490                                           Register tmp,
3491                                           bool preserve_o_regs) {
3492   Label filtered;
3493 
3494   if (obj == noreg) {
3495     // We are not loading the previous value so make
3496     // sure that we don't trash the value in pre_val
3497     // with the code below.
3498     assert_different_registers(pre_val, tmp);
3499   } else {
3500     // We will be loading the previous value
3501     // in this code so...
3502     assert(offset == 0 || index == noreg, "choose one");
3503     assert(pre_val == noreg, "check this code");
3504   }
3505 
3506   // Is marking active?
3507   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
3508     ld(G2,
3509        in_bytes(JavaThread::satb_mark_queue_offset() +
3510                 SATBMarkQueue::byte_offset_of_active()),
3511        tmp);
3512   } else {
3513     guarantee(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1,
3514               "Assumption");
3515     ldsb(G2,
3516          in_bytes(JavaThread::satb_mark_queue_offset() +
3517                   SATBMarkQueue::byte_offset_of_active()),
3518          tmp);
3519   }
3520 
3521   // Is marking active?
3522   cmp_and_br_short(tmp, G0, Assembler::equal, Assembler::pt, filtered);
3523 
3524   // Do we need to load the previous value?
3525   if (obj != noreg) {
3526     // Load the previous value...
3527     if (index == noreg) {
3528       if (Assembler::is_simm13(offset)) {
3529         load_heap_oop(obj, offset, tmp);
3530       } else {
3531         set(offset, tmp);
3532         load_heap_oop(obj, tmp, tmp);
3533       }
3534     } else {
3535       load_heap_oop(obj, index, tmp);
3536     }
3537     // Previous value has been loaded into tmp
3538     pre_val = tmp;
3539   }
3540 
3541   assert(pre_val != noreg, "must have a real register");
3542 
3543   // Is the previous value null?
3544   cmp_and_brx_short(pre_val, G0, Assembler::equal, Assembler::pt, filtered);
3545 
3546   // OK, it's not filtered, so we'll need to call enqueue.  In the normal
3547   // case, pre_val will be a scratch G-reg, but there are some cases in
3548   // which it's an O-reg.  In the first case, do a normal call.  In the
3549   // latter, do a save here and call the frameless version.
3550 
3551   guarantee(pre_val->is_global() || pre_val->is_out(),
3552             "Or we need to think harder.");
3553 
3554   if (pre_val->is_global() && !preserve_o_regs) {
3555     call(satb_log_enqueue_with_frame);
3556     delayed()->mov(pre_val, O0);
3557   } else {
3558     save_frame(0);
3559     call(satb_log_enqueue_frameless);
3560     delayed()->mov(pre_val->after_save(), O0);
3561     restore();
3562   }
3563 
3564   bind(filtered);
3565 }
3566 
3567 static address dirty_card_log_enqueue = 0;
3568 static u_char* dirty_card_log_enqueue_end = 0;
3569 
3570 // This gets to assume that o0 contains the object address.
3571 static void generate_dirty_card_log_enqueue(jbyte* byte_map_base) {
3572   BufferBlob* bb = BufferBlob::create("dirty_card_enqueue", EnqueueCodeSize*2);
3573   CodeBuffer buf(bb);
3574   MacroAssembler masm(&buf);
3575 #define __ masm.
3576   address start = __ pc();
3577 
3578   Label not_already_dirty, restart, refill, young_card;
3579 
3580   __ srlx(O0, CardTable::card_shift, O0);
3581   AddressLiteral addrlit(byte_map_base);
3582   __ set(addrlit, O1); // O1 := <card table base>
3583   __ ldub(O0, O1, O2); // O2 := [O0 + O1]
3584 
3585   __ cmp_and_br_short(O2, G1CardTable::g1_young_card_val(), Assembler::equal, Assembler::pt, young_card);
3586 
3587   __ membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
3588   __ ldub(O0, O1, O2); // O2 := [O0 + O1]
3589 
3590   assert(CardTable::dirty_card_val() == 0, "otherwise check this code");
3591   __ cmp_and_br_short(O2, G0, Assembler::notEqual, Assembler::pt, not_already_dirty);
3592 
3593   __ bind(young_card);
3594   // We didn't take the branch, so we're already dirty: return.
3595   // Use return-from-leaf
3596   __ retl();
3597   __ delayed()->nop();
3598 
3599   // Not dirty.
3600   __ bind(not_already_dirty);
3601 
3602   // Get O0 + O1 into a reg by itself
3603   __ add(O0, O1, O3);
3604 
3605   // First, dirty it.
3606   __ stb(G0, O3, G0);  // [cardPtr] := 0  (i.e., dirty).
3607 
3608   int dirty_card_q_index_byte_offset =
3609     in_bytes(JavaThread::dirty_card_queue_offset() +
3610              DirtyCardQueue::byte_offset_of_index());
3611   int dirty_card_q_buf_byte_offset =
3612     in_bytes(JavaThread::dirty_card_queue_offset() +
3613              DirtyCardQueue::byte_offset_of_buf());
3614   __ bind(restart);
3615 
3616   // Load the index into the update buffer. DirtyCardQueue::_index is
3617   // a size_t so ld_ptr is appropriate here.
3618   __ ld_ptr(G2_thread, dirty_card_q_index_byte_offset, L0);
3619 
3620   // index == 0?
3621   __ cmp_and_brx_short(L0, G0, Assembler::equal, Assembler::pn, refill);
3622 
3623   __ ld_ptr(G2_thread, dirty_card_q_buf_byte_offset, L1);
3624   __ sub(L0, oopSize, L0);
3625 
3626   __ st_ptr(O3, L1, L0);  // [_buf + index] := I0
3627   // Use return-from-leaf
3628   __ retl();
3629   __ delayed()->st_ptr(L0, G2_thread, dirty_card_q_index_byte_offset);
3630 
3631   __ bind(refill);
3632   address handle_zero =
3633     CAST_FROM_FN_PTR(address,
3634                      &DirtyCardQueueSet::handle_zero_index_for_thread);
3635   // This should be rare enough that we can afford to save all the
3636   // scratch registers that the calling context might be using.
3637   __ mov(G1_scratch, L3);
3638   __ mov(G3_scratch, L5);
3639   // We need the value of O3 above (for the write into the buffer), so we
3640   // save and restore it.
3641   __ mov(O3, L6);
3642   // Since the call will overwrite O7, we save and restore that, as well.
3643   __ mov(O7, L4);
3644 
3645   __ call_VM_leaf(L7_thread_cache, handle_zero, G2_thread);
3646   __ mov(L3, G1_scratch);
3647   __ mov(L5, G3_scratch);
3648   __ mov(L6, O3);
3649   __ br(Assembler::always, /*annul*/false, Assembler::pt, restart);
3650   __ delayed()->mov(L4, O7);
3651 
3652   dirty_card_log_enqueue = start;
3653   dirty_card_log_enqueue_end = __ pc();
3654   // XXX Should have a guarantee here about not going off the end!
3655   // Does it already do so?  Do an experiment...
3656 
3657 #undef __
3658 
3659 }
3660 
3661 void MacroAssembler::g1_write_barrier_post(Register store_addr, Register new_val, Register tmp) {
3662 
3663   Label filtered;
3664   MacroAssembler* post_filter_masm = this;
3665 
3666   if (new_val == G0) return;
3667 
3668   G1BarrierSet* bs =
3669     barrier_set_cast<G1BarrierSet>(Universe::heap()->barrier_set());
3670   CardTable* ct = bs->card_table();
3671 
3672   if (G1RSBarrierRegionFilter) {
3673     xor3(store_addr, new_val, tmp);
3674     srlx(tmp, HeapRegion::LogOfHRGrainBytes, tmp);
3675 
3676     // XXX Should I predict this taken or not?  Does it matter?
3677     cmp_and_brx_short(tmp, G0, Assembler::equal, Assembler::pt, filtered);
3678   }
3679 
3680   // If the "store_addr" register is an "in" or "local" register, move it to
3681   // a scratch reg so we can pass it as an argument.
3682   bool use_scr = !(store_addr->is_global() || store_addr->is_out());
3683   // Pick a scratch register different from "tmp".
3684   Register scr = (tmp == G1_scratch ? G3_scratch : G1_scratch);
3685   // Make sure we use up the delay slot!
3686   if (use_scr) {
3687     post_filter_masm->mov(store_addr, scr);
3688   } else {
3689     post_filter_masm->nop();
3690   }
3691   save_frame(0);
3692   call(dirty_card_log_enqueue);
3693   if (use_scr) {
3694     delayed()->mov(scr, O0);
3695   } else {
3696     delayed()->mov(store_addr->after_save(), O0);
3697   }
3698   restore();
3699 
3700   bind(filtered);
3701 }
3702 
3703 // Called from init_globals() after universe_init() and before interpreter_init()
3704 void g1_barrier_stubs_init() {
3705   CollectedHeap* heap = Universe::heap();
3706   if (heap->kind() == CollectedHeap::G1CollectedHeap) {
3707     // Only needed for G1
3708     if (dirty_card_log_enqueue == 0) {
3709       G1BarrierSet* bs =
3710         barrier_set_cast<G1BarrierSet>(heap->barrier_set());
3711       CardTable *ct = bs->card_table();
3712       generate_dirty_card_log_enqueue(ct->byte_map_base());
3713       assert(dirty_card_log_enqueue != 0, "postcondition.");
3714     }
3715     if (satb_log_enqueue_with_frame == 0) {
3716       generate_satb_log_enqueue(true);
3717       assert(satb_log_enqueue_with_frame != 0, "postcondition.");
3718     }
3719     if (satb_log_enqueue_frameless == 0) {
3720       generate_satb_log_enqueue(false);
3721       assert(satb_log_enqueue_frameless != 0, "postcondition.");
3722     }
3723   }
3724 }
3725 
3726 #endif // INCLUDE_ALL_GCS
3727 ///////////////////////////////////////////////////////////////////////////////////
3728 
3729 void MacroAssembler::card_write_barrier_post(Register store_addr, Register new_val, Register tmp) {
3730   // If we're writing constant NULL, we can skip the write barrier.
3731   if (new_val == G0) return;
3732   CardTableBarrierSet* bs =
3733     barrier_set_cast<CardTableBarrierSet>(Universe::heap()->barrier_set());
3734   CardTable* ct = bs->card_table();
3735 
3736   assert(bs->kind() == BarrierSet::CardTableBarrierSet, "wrong barrier");
3737   card_table_write(ct->byte_map_base(), tmp, store_addr);
3738 }
3739 
3740 // ((OopHandle)result).resolve();
3741 void MacroAssembler::resolve_oop_handle(Register result) {
3742   // OopHandle::resolve is an indirection.
3743   ld_ptr(result, 0, result);
3744 }
3745 
3746 void MacroAssembler::load_mirror(Register mirror, Register method) {
3747   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
3748   ld_ptr(method, in_bytes(Method::const_offset()), mirror);
3749   ld_ptr(mirror, in_bytes(ConstMethod::constants_offset()), mirror);
3750   ld_ptr(mirror, ConstantPool::pool_holder_offset_in_bytes(), mirror);
3751   ld_ptr(mirror, mirror_offset, mirror);
3752   resolve_oop_handle(mirror);
3753 }
3754 
3755 void MacroAssembler::load_klass(Register src_oop, Register klass) {
3756   // The number of bytes in this code is used by
3757   // MachCallDynamicJavaNode::ret_addr_offset()
3758   // if this changes, change that.
3759   if (UseCompressedClassPointers) {
3760     lduw(src_oop, oopDesc::klass_offset_in_bytes(), klass);
3761     decode_klass_not_null(klass);
3762   } else {
3763     ld_ptr(src_oop, oopDesc::klass_offset_in_bytes(), klass);
3764   }
3765 }
3766 
3767 void MacroAssembler::store_klass(Register klass, Register dst_oop) {
3768   if (UseCompressedClassPointers) {
3769     assert(dst_oop != klass, "not enough registers");
3770     encode_klass_not_null(klass);
3771     st(klass, dst_oop, oopDesc::klass_offset_in_bytes());
3772   } else {
3773     st_ptr(klass, dst_oop, oopDesc::klass_offset_in_bytes());
3774   }
3775 }
3776 
3777 void MacroAssembler::store_klass_gap(Register s, Register d) {
3778   if (UseCompressedClassPointers) {
3779     assert(s != d, "not enough registers");
3780     st(s, d, oopDesc::klass_gap_offset_in_bytes());
3781   }
3782 }
3783 
3784 void MacroAssembler::load_heap_oop(const Address& s, Register d) {
3785   if (UseCompressedOops) {
3786     lduw(s, d);
3787     decode_heap_oop(d);
3788   } else {
3789     ld_ptr(s, d);
3790   }
3791 }
3792 
3793 void MacroAssembler::load_heap_oop(Register s1, Register s2, Register d) {
3794    if (UseCompressedOops) {
3795     lduw(s1, s2, d);
3796     decode_heap_oop(d, d);
3797   } else {
3798     ld_ptr(s1, s2, d);
3799   }
3800 }
3801 
3802 void MacroAssembler::load_heap_oop(Register s1, int simm13a, Register d) {
3803    if (UseCompressedOops) {
3804     lduw(s1, simm13a, d);
3805     decode_heap_oop(d, d);
3806   } else {
3807     ld_ptr(s1, simm13a, d);
3808   }
3809 }
3810 
3811 void MacroAssembler::load_heap_oop(Register s1, RegisterOrConstant s2, Register d) {
3812   if (s2.is_constant())  load_heap_oop(s1, s2.as_constant(), d);
3813   else                   load_heap_oop(s1, s2.as_register(), d);
3814 }
3815 
3816 void MacroAssembler::store_heap_oop(Register d, Register s1, Register s2) {
3817   if (UseCompressedOops) {
3818     assert(s1 != d && s2 != d, "not enough registers");
3819     encode_heap_oop(d);
3820     st(d, s1, s2);
3821   } else {
3822     st_ptr(d, s1, s2);
3823   }
3824 }
3825 
3826 void MacroAssembler::store_heap_oop(Register d, Register s1, int simm13a) {
3827   if (UseCompressedOops) {
3828     assert(s1 != d, "not enough registers");
3829     encode_heap_oop(d);
3830     st(d, s1, simm13a);
3831   } else {
3832     st_ptr(d, s1, simm13a);
3833   }
3834 }
3835 
3836 void MacroAssembler::store_heap_oop(Register d, const Address& a, int offset) {
3837   if (UseCompressedOops) {
3838     assert(a.base() != d, "not enough registers");
3839     encode_heap_oop(d);
3840     st(d, a, offset);
3841   } else {
3842     st_ptr(d, a, offset);
3843   }
3844 }
3845 
3846 
3847 void MacroAssembler::encode_heap_oop(Register src, Register dst) {
3848   assert (UseCompressedOops, "must be compressed");
3849   assert (Universe::heap() != NULL, "java heap should be initialized");
3850   assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3851   verify_oop(src);
3852   if (Universe::narrow_oop_base() == NULL) {
3853     srlx(src, LogMinObjAlignmentInBytes, dst);
3854     return;
3855   }
3856   Label done;
3857   if (src == dst) {
3858     // optimize for frequent case src == dst
3859     bpr(rc_nz, true, Assembler::pt, src, done);
3860     delayed() -> sub(src, G6_heapbase, dst); // annuled if not taken
3861     bind(done);
3862     srlx(src, LogMinObjAlignmentInBytes, dst);
3863   } else {
3864     bpr(rc_z, false, Assembler::pn, src, done);
3865     delayed() -> mov(G0, dst);
3866     // could be moved before branch, and annulate delay,
3867     // but may add some unneeded work decoding null
3868     sub(src, G6_heapbase, dst);
3869     srlx(dst, LogMinObjAlignmentInBytes, dst);
3870     bind(done);
3871   }
3872 }
3873 
3874 
3875 void MacroAssembler::encode_heap_oop_not_null(Register r) {
3876   assert (UseCompressedOops, "must be compressed");
3877   assert (Universe::heap() != NULL, "java heap should be initialized");
3878   assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3879   verify_oop(r);
3880   if (Universe::narrow_oop_base() != NULL)
3881     sub(r, G6_heapbase, r);
3882   srlx(r, LogMinObjAlignmentInBytes, r);
3883 }
3884 
3885 void MacroAssembler::encode_heap_oop_not_null(Register src, Register dst) {
3886   assert (UseCompressedOops, "must be compressed");
3887   assert (Universe::heap() != NULL, "java heap should be initialized");
3888   assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3889   verify_oop(src);
3890   if (Universe::narrow_oop_base() == NULL) {
3891     srlx(src, LogMinObjAlignmentInBytes, dst);
3892   } else {
3893     sub(src, G6_heapbase, dst);
3894     srlx(dst, LogMinObjAlignmentInBytes, dst);
3895   }
3896 }
3897 
3898 // Same algorithm as oops.inline.hpp decode_heap_oop.
3899 void  MacroAssembler::decode_heap_oop(Register src, Register dst) {
3900   assert (UseCompressedOops, "must be compressed");
3901   assert (Universe::heap() != NULL, "java heap should be initialized");
3902   assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3903   sllx(src, LogMinObjAlignmentInBytes, dst);
3904   if (Universe::narrow_oop_base() != NULL) {
3905     Label done;
3906     bpr(rc_nz, true, Assembler::pt, dst, done);
3907     delayed() -> add(dst, G6_heapbase, dst); // annuled if not taken
3908     bind(done);
3909   }
3910   verify_oop(dst);
3911 }
3912 
3913 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
3914   // Do not add assert code to this unless you change vtableStubs_sparc.cpp
3915   // pd_code_size_limit.
3916   // Also do not verify_oop as this is called by verify_oop.
3917   assert (UseCompressedOops, "must be compressed");
3918   assert (Universe::heap() != NULL, "java heap should be initialized");
3919   assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3920   sllx(r, LogMinObjAlignmentInBytes, r);
3921   if (Universe::narrow_oop_base() != NULL)
3922     add(r, G6_heapbase, r);
3923 }
3924 
3925 void  MacroAssembler::decode_heap_oop_not_null(Register src, Register dst) {
3926   // Do not add assert code to this unless you change vtableStubs_sparc.cpp
3927   // pd_code_size_limit.
3928   // Also do not verify_oop as this is called by verify_oop.
3929   assert (UseCompressedOops, "must be compressed");
3930   assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3931   sllx(src, LogMinObjAlignmentInBytes, dst);
3932   if (Universe::narrow_oop_base() != NULL)
3933     add(dst, G6_heapbase, dst);
3934 }
3935 
3936 void MacroAssembler::encode_klass_not_null(Register r) {
3937   assert (UseCompressedClassPointers, "must be compressed");
3938   if (Universe::narrow_klass_base() != NULL) {
3939     assert(r != G6_heapbase, "bad register choice");
3940     set((intptr_t)Universe::narrow_klass_base(), G6_heapbase);
3941     sub(r, G6_heapbase, r);
3942     if (Universe::narrow_klass_shift() != 0) {
3943       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3944       srlx(r, LogKlassAlignmentInBytes, r);
3945     }
3946     reinit_heapbase();
3947   } else {
3948     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift() || Universe::narrow_klass_shift() == 0, "decode alg wrong");
3949     srlx(r, Universe::narrow_klass_shift(), r);
3950   }
3951 }
3952 
3953 void MacroAssembler::encode_klass_not_null(Register src, Register dst) {
3954   if (src == dst) {
3955     encode_klass_not_null(src);
3956   } else {
3957     assert (UseCompressedClassPointers, "must be compressed");
3958     if (Universe::narrow_klass_base() != NULL) {
3959       set((intptr_t)Universe::narrow_klass_base(), dst);
3960       sub(src, dst, dst);
3961       if (Universe::narrow_klass_shift() != 0) {
3962         srlx(dst, LogKlassAlignmentInBytes, dst);
3963       }
3964     } else {
3965       // shift src into dst
3966       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift() || Universe::narrow_klass_shift() == 0, "decode alg wrong");
3967       srlx(src, Universe::narrow_klass_shift(), dst);
3968     }
3969   }
3970 }
3971 
3972 // Function instr_size_for_decode_klass_not_null() counts the instructions
3973 // generated by decode_klass_not_null() and reinit_heapbase().  Hence, if
3974 // the instructions they generate change, then this method needs to be updated.
3975 int MacroAssembler::instr_size_for_decode_klass_not_null() {
3976   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
3977   int num_instrs = 1;  // shift src,dst or add
3978   if (Universe::narrow_klass_base() != NULL) {
3979     // set + add + set
3980     num_instrs += insts_for_internal_set((intptr_t)Universe::narrow_klass_base()) +
3981                   insts_for_internal_set((intptr_t)Universe::narrow_ptrs_base());
3982     if (Universe::narrow_klass_shift() != 0) {
3983       num_instrs += 1;  // sllx
3984     }
3985   }
3986   return num_instrs * BytesPerInstWord;
3987 }
3988 
3989 // !!! If the instructions that get generated here change then function
3990 // instr_size_for_decode_klass_not_null() needs to get updated.
3991 void  MacroAssembler::decode_klass_not_null(Register r) {
3992   // Do not add assert code to this unless you change vtableStubs_sparc.cpp
3993   // pd_code_size_limit.
3994   assert (UseCompressedClassPointers, "must be compressed");
3995   if (Universe::narrow_klass_base() != NULL) {
3996     assert(r != G6_heapbase, "bad register choice");
3997     set((intptr_t)Universe::narrow_klass_base(), G6_heapbase);
3998     if (Universe::narrow_klass_shift() != 0)
3999       sllx(r, LogKlassAlignmentInBytes, r);
4000     add(r, G6_heapbase, r);
4001     reinit_heapbase();
4002   } else {
4003     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift() || Universe::narrow_klass_shift() == 0, "decode alg wrong");
4004     sllx(r, Universe::narrow_klass_shift(), r);
4005   }
4006 }
4007 
4008 void  MacroAssembler::decode_klass_not_null(Register src, Register dst) {
4009   if (src == dst) {
4010     decode_klass_not_null(src);
4011   } else {
4012     // Do not add assert code to this unless you change vtableStubs_sparc.cpp
4013     // pd_code_size_limit.
4014     assert (UseCompressedClassPointers, "must be compressed");
4015     if (Universe::narrow_klass_base() != NULL) {
4016       if (Universe::narrow_klass_shift() != 0) {
4017         assert((src != G6_heapbase) && (dst != G6_heapbase), "bad register choice");
4018         set((intptr_t)Universe::narrow_klass_base(), G6_heapbase);
4019         sllx(src, LogKlassAlignmentInBytes, dst);
4020         add(dst, G6_heapbase, dst);
4021         reinit_heapbase();
4022       } else {
4023         set((intptr_t)Universe::narrow_klass_base(), dst);
4024         add(src, dst, dst);
4025       }
4026     } else {
4027       // shift/mov src into dst.
4028       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift() || Universe::narrow_klass_shift() == 0, "decode alg wrong");
4029       sllx(src, Universe::narrow_klass_shift(), dst);
4030     }
4031   }
4032 }
4033 
4034 void MacroAssembler::reinit_heapbase() {
4035   if (UseCompressedOops || UseCompressedClassPointers) {
4036     if (Universe::heap() != NULL) {
4037       set((intptr_t)Universe::narrow_ptrs_base(), G6_heapbase);
4038     } else {
4039       AddressLiteral base(Universe::narrow_ptrs_base_addr());
4040       load_ptr_contents(base, G6_heapbase);
4041     }
4042   }
4043 }
4044 
4045 #ifdef COMPILER2
4046 
4047 // Compress char[] to byte[] by compressing 16 bytes at once. Return 0 on failure.
4048 void MacroAssembler::string_compress_16(Register src, Register dst, Register cnt, Register result,
4049                                         Register tmp1, Register tmp2, Register tmp3, Register tmp4,
4050                                         FloatRegister ftmp1, FloatRegister ftmp2, FloatRegister ftmp3, Label& Ldone) {
4051   Label Lloop, Lslow;
4052   assert(UseVIS >= 3, "VIS3 is required");
4053   assert_different_registers(src, dst, cnt, tmp1, tmp2, tmp3, tmp4, result);
4054   assert_different_registers(ftmp1, ftmp2, ftmp3);
4055 
4056   // Check if cnt >= 8 (= 16 bytes)
4057   cmp(cnt, 8);
4058   br(Assembler::less, false, Assembler::pn, Lslow);
4059   delayed()->mov(cnt, result); // copy count
4060 
4061   // Check for 8-byte alignment of src and dst
4062   or3(src, dst, tmp1);
4063   andcc(tmp1, 7, G0);
4064   br(Assembler::notZero, false, Assembler::pn, Lslow);
4065   delayed()->nop();
4066 
4067   // Set mask for bshuffle instruction
4068   Register mask = tmp4;
4069   set(0x13579bdf, mask);
4070   bmask(mask, G0, G0);
4071 
4072   // Set mask to 0xff00 ff00 ff00 ff00 to check for non-latin1 characters
4073   Assembler::sethi(0xff00fc00, mask); // mask = 0x0000 0000 ff00 fc00
4074   add(mask, 0x300, mask);             // mask = 0x0000 0000 ff00 ff00
4075   sllx(mask, 32, tmp1);               // tmp1 = 0xff00 ff00 0000 0000
4076   or3(mask, tmp1, mask);              // mask = 0xff00 ff00 ff00 ff00
4077 
4078   // Load first 8 bytes
4079   ldx(src, 0, tmp1);
4080 
4081   bind(Lloop);
4082   // Load next 8 bytes
4083   ldx(src, 8, tmp2);
4084 
4085   // Check for non-latin1 character by testing if the most significant byte of a char is set.
4086   // Although we have to move the data between integer and floating point registers, this is
4087   // still faster than the corresponding VIS instructions (ford/fand/fcmpd).
4088   or3(tmp1, tmp2, tmp3);
4089   btst(tmp3, mask);
4090   // annul zeroing if branch is not taken to preserve original count
4091   brx(Assembler::notZero, true, Assembler::pn, Ldone);
4092   delayed()->mov(G0, result); // 0 - failed
4093 
4094   // Move bytes into float register
4095   movxtod(tmp1, ftmp1);
4096   movxtod(tmp2, ftmp2);
4097 
4098   // Compress by copying one byte per char from ftmp1 and ftmp2 to ftmp3
4099   bshuffle(ftmp1, ftmp2, ftmp3);
4100   stf(FloatRegisterImpl::D, ftmp3, dst, 0);
4101 
4102   // Increment addresses and decrement count
4103   inc(src, 16);
4104   inc(dst, 8);
4105   dec(cnt, 8);
4106 
4107   cmp(cnt, 8);
4108   // annul LDX if branch is not taken to prevent access past end of string
4109   br(Assembler::greaterEqual, true, Assembler::pt, Lloop);
4110   delayed()->ldx(src, 0, tmp1);
4111 
4112   // Fallback to slow version
4113   bind(Lslow);
4114 }
4115 
4116 // Compress char[] to byte[]. Return 0 on failure.
4117 void MacroAssembler::string_compress(Register src, Register dst, Register cnt, Register result, Register tmp, Label& Ldone) {
4118   Label Lloop;
4119   assert_different_registers(src, dst, cnt, tmp, result);
4120 
4121   lduh(src, 0, tmp);
4122 
4123   bind(Lloop);
4124   inc(src, sizeof(jchar));
4125   cmp(tmp, 0xff);
4126   // annul zeroing if branch is not taken to preserve original count
4127   br(Assembler::greater, true, Assembler::pn, Ldone); // don't check xcc
4128   delayed()->mov(G0, result); // 0 - failed
4129   deccc(cnt);
4130   stb(tmp, dst, 0);
4131   inc(dst);
4132   // annul LDUH if branch is not taken to prevent access past end of string
4133   br(Assembler::notZero, true, Assembler::pt, Lloop);
4134   delayed()->lduh(src, 0, tmp); // hoisted
4135 }
4136 
4137 // Inflate byte[] to char[] by inflating 16 bytes at once.
4138 void MacroAssembler::string_inflate_16(Register src, Register dst, Register cnt, Register tmp,
4139                                        FloatRegister ftmp1, FloatRegister ftmp2, FloatRegister ftmp3, FloatRegister ftmp4, Label& Ldone) {
4140   Label Lloop, Lslow;
4141   assert(UseVIS >= 3, "VIS3 is required");
4142   assert_different_registers(src, dst, cnt, tmp);
4143   assert_different_registers(ftmp1, ftmp2, ftmp3, ftmp4);
4144 
4145   // Check if cnt >= 8 (= 16 bytes)
4146   cmp(cnt, 8);
4147   br(Assembler::less, false, Assembler::pn, Lslow);
4148   delayed()->nop();
4149 
4150   // Check for 8-byte alignment of src and dst
4151   or3(src, dst, tmp);
4152   andcc(tmp, 7, G0);
4153   br(Assembler::notZero, false, Assembler::pn, Lslow);
4154   // Initialize float register to zero
4155   FloatRegister zerof = ftmp4;
4156   delayed()->fzero(FloatRegisterImpl::D, zerof);
4157 
4158   // Load first 8 bytes
4159   ldf(FloatRegisterImpl::D, src, 0, ftmp1);
4160 
4161   bind(Lloop);
4162   inc(src, 8);
4163   dec(cnt, 8);
4164 
4165   // Inflate the string by interleaving each byte from the source array
4166   // with a zero byte and storing the result in the destination array.
4167   fpmerge(zerof, ftmp1->successor(), ftmp2);
4168   stf(FloatRegisterImpl::D, ftmp2, dst, 8);
4169   fpmerge(zerof, ftmp1, ftmp3);
4170   stf(FloatRegisterImpl::D, ftmp3, dst, 0);
4171 
4172   inc(dst, 16);
4173 
4174   cmp(cnt, 8);
4175   // annul LDX if branch is not taken to prevent access past end of string
4176   br(Assembler::greaterEqual, true, Assembler::pt, Lloop);
4177   delayed()->ldf(FloatRegisterImpl::D, src, 0, ftmp1);
4178 
4179   // Fallback to slow version
4180   bind(Lslow);
4181 }
4182 
4183 // Inflate byte[] to char[].
4184 void MacroAssembler::string_inflate(Register src, Register dst, Register cnt, Register tmp, Label& Ldone) {
4185   Label Loop;
4186   assert_different_registers(src, dst, cnt, tmp);
4187 
4188   ldub(src, 0, tmp);
4189   bind(Loop);
4190   inc(src);
4191   deccc(cnt);
4192   sth(tmp, dst, 0);
4193   inc(dst, sizeof(jchar));
4194   // annul LDUB if branch is not taken to prevent access past end of string
4195   br(Assembler::notZero, true, Assembler::pt, Loop);
4196   delayed()->ldub(src, 0, tmp); // hoisted
4197 }
4198 
4199 void MacroAssembler::string_compare(Register str1, Register str2,
4200                                     Register cnt1, Register cnt2,
4201                                     Register tmp1, Register tmp2,
4202                                     Register result, int ae) {
4203   Label Ldone, Lloop;
4204   assert_different_registers(str1, str2, cnt1, cnt2, tmp1, result);
4205   int stride1, stride2;
4206 
4207   // Note: Making use of the fact that compareTo(a, b) == -compareTo(b, a)
4208   // we interchange str1 and str2 in the UL case and negate the result.
4209   // Like this, str1 is always latin1 encoded, expect for the UU case.
4210 
4211   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
4212     srl(cnt2, 1, cnt2);
4213   }
4214 
4215   // See if the lengths are different, and calculate min in cnt1.
4216   // Save diff in case we need it for a tie-breaker.
4217   Label Lskip;
4218   Register diff = tmp1;
4219   subcc(cnt1, cnt2, diff);
4220   br(Assembler::greater, true, Assembler::pt, Lskip);
4221   // cnt2 is shorter, so use its count:
4222   delayed()->mov(cnt2, cnt1);
4223   bind(Lskip);
4224 
4225   // Rename registers
4226   Register limit1 = cnt1;
4227   Register limit2 = limit1;
4228   Register chr1   = result;
4229   Register chr2   = cnt2;
4230   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
4231     // We need an additional register to keep track of two limits
4232     assert_different_registers(str1, str2, cnt1, cnt2, tmp1, tmp2, result);
4233     limit2 = tmp2;
4234   }
4235 
4236   // Is the minimum length zero?
4237   cmp(limit1, (int)0); // use cast to resolve overloading ambiguity
4238   br(Assembler::equal, true, Assembler::pn, Ldone);
4239   // result is difference in lengths
4240   if (ae == StrIntrinsicNode::UU) {
4241     delayed()->sra(diff, 1, result);  // Divide by 2 to get number of chars
4242   } else {
4243     delayed()->mov(diff, result);
4244   }
4245 
4246   // Load first characters
4247   if (ae == StrIntrinsicNode::LL) {
4248     stride1 = stride2 = sizeof(jbyte);
4249     ldub(str1, 0, chr1);
4250     ldub(str2, 0, chr2);
4251   } else if (ae == StrIntrinsicNode::UU) {
4252     stride1 = stride2 = sizeof(jchar);
4253     lduh(str1, 0, chr1);
4254     lduh(str2, 0, chr2);
4255   } else {
4256     stride1 = sizeof(jbyte);
4257     stride2 = sizeof(jchar);
4258     ldub(str1, 0, chr1);
4259     lduh(str2, 0, chr2);
4260   }
4261 
4262   // Compare first characters
4263   subcc(chr1, chr2, chr1);
4264   br(Assembler::notZero, false, Assembler::pt, Ldone);
4265   assert(chr1 == result, "result must be pre-placed");
4266   delayed()->nop();
4267 
4268   // Check if the strings start at same location
4269   cmp(str1, str2);
4270   brx(Assembler::equal, true, Assembler::pn, Ldone);
4271   delayed()->mov(G0, result);  // result is zero
4272 
4273   // We have no guarantee that on 64 bit the higher half of limit is 0
4274   signx(limit1);
4275 
4276   // Get limit
4277   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
4278     sll(limit1, 1, limit2);
4279     subcc(limit2, stride2, chr2);
4280   }
4281   subcc(limit1, stride1, chr1);
4282   br(Assembler::zero, true, Assembler::pn, Ldone);
4283   // result is difference in lengths
4284   if (ae == StrIntrinsicNode::UU) {
4285     delayed()->sra(diff, 1, result);  // Divide by 2 to get number of chars
4286   } else {
4287     delayed()->mov(diff, result);
4288   }
4289 
4290   // Shift str1 and str2 to the end of the arrays, negate limit
4291   add(str1, limit1, str1);
4292   add(str2, limit2, str2);
4293   neg(chr1, limit1);  // limit1 = -(limit1-stride1)
4294   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
4295     neg(chr2, limit2);  // limit2 = -(limit2-stride2)
4296   }
4297 
4298   // Compare the rest of the characters
4299   load_sized_value(Address(str1, limit1), chr1, (ae == StrIntrinsicNode::UU) ? 2 : 1, false);
4300 
4301   bind(Lloop);
4302   load_sized_value(Address(str2, limit2), chr2, (ae == StrIntrinsicNode::LL) ? 1 : 2, false);
4303 
4304   subcc(chr1, chr2, chr1);
4305   br(Assembler::notZero, false, Assembler::pt, Ldone);
4306   assert(chr1 == result, "result must be pre-placed");
4307   delayed()->inccc(limit1, stride1);
4308   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
4309     inccc(limit2, stride2);
4310   }
4311 
4312   // annul LDUB if branch is not taken to prevent access past end of string
4313   br(Assembler::notZero, true, Assembler::pt, Lloop);
4314   delayed()->load_sized_value(Address(str1, limit1), chr1, (ae == StrIntrinsicNode::UU) ? 2 : 1, false);
4315 
4316   // If strings are equal up to min length, return the length difference.
4317   if (ae == StrIntrinsicNode::UU) {
4318     // Divide by 2 to get number of chars
4319     sra(diff, 1, result);
4320   } else {
4321     mov(diff, result);
4322   }
4323 
4324   // Otherwise, return the difference between the first mismatched chars.
4325   bind(Ldone);
4326   if(ae == StrIntrinsicNode::UL) {
4327     // Negate result (see note above)
4328     neg(result);
4329   }
4330 }
4331 
4332 void MacroAssembler::array_equals(bool is_array_equ, Register ary1, Register ary2,
4333                                   Register limit, Register tmp, Register result, bool is_byte) {
4334   Label Ldone, Lloop, Lremaining;
4335   assert_different_registers(ary1, ary2, limit, tmp, result);
4336 
4337   int length_offset  = arrayOopDesc::length_offset_in_bytes();
4338   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_byte ? T_BYTE : T_CHAR);
4339   assert(base_offset % 8 == 0, "Base offset must be 8-byte aligned");
4340 
4341   if (is_array_equ) {
4342     // return true if the same array
4343     cmp(ary1, ary2);
4344     brx(Assembler::equal, true, Assembler::pn, Ldone);
4345     delayed()->mov(1, result);  // equal
4346 
4347     br_null(ary1, true, Assembler::pn, Ldone);
4348     delayed()->clr(result);     // not equal
4349 
4350     br_null(ary2, true, Assembler::pn, Ldone);
4351     delayed()->clr(result);     // not equal
4352 
4353     // load the lengths of arrays
4354     ld(Address(ary1, length_offset), limit);
4355     ld(Address(ary2, length_offset), tmp);
4356 
4357     // return false if the two arrays are not equal length
4358     cmp(limit, tmp);
4359     br(Assembler::notEqual, true, Assembler::pn, Ldone);
4360     delayed()->clr(result);     // not equal
4361   }
4362 
4363   cmp_zero_and_br(Assembler::zero, limit, Ldone, true, Assembler::pn);
4364   delayed()->mov(1, result); // zero-length arrays are equal
4365 
4366   if (is_array_equ) {
4367     // load array addresses
4368     add(ary1, base_offset, ary1);
4369     add(ary2, base_offset, ary2);
4370     // set byte count
4371     if (!is_byte) {
4372       sll(limit, exact_log2(sizeof(jchar)), limit);
4373     }
4374   } else {
4375     // We have no guarantee that on 64 bit the higher half of limit is 0
4376     signx(limit);
4377   }
4378 
4379 #ifdef ASSERT
4380   // Sanity check for doubleword (8-byte) alignment of ary1 and ary2.
4381   // Guaranteed on 64-bit systems (see arrayOopDesc::header_size_in_bytes()).
4382   Label Laligned;
4383   or3(ary1, ary2, tmp);
4384   andcc(tmp, 7, tmp);
4385   br_null_short(tmp, Assembler::pn, Laligned);
4386   STOP("First array element is not 8-byte aligned.");
4387   should_not_reach_here();
4388   bind(Laligned);
4389 #endif
4390 
4391   // Shift ary1 and ary2 to the end of the arrays, negate limit
4392   add(ary1, limit, ary1);
4393   add(ary2, limit, ary2);
4394   neg(limit, limit);
4395 
4396   // MAIN LOOP
4397   // Load and compare array elements of size 'byte_width' until the elements are not
4398   // equal or we reached the end of the arrays. If the size of the arrays is not a
4399   // multiple of 'byte_width', we simply read over the end of the array, bail out and
4400   // compare the remaining bytes below by skipping the garbage bytes.
4401   ldx(ary1, limit, result);
4402   bind(Lloop);
4403   ldx(ary2, limit, tmp);
4404   inccc(limit, 8);
4405   // Bail out if we reached the end (but still do the comparison)
4406   br(Assembler::positive, false, Assembler::pn, Lremaining);
4407   delayed()->cmp(result, tmp);
4408   // Check equality of elements
4409   brx(Assembler::equal, false, Assembler::pt, target(Lloop));
4410   delayed()->ldx(ary1, limit, result);
4411 
4412   ba(Ldone);
4413   delayed()->clr(result); // not equal
4414 
4415   // TAIL COMPARISON
4416   // We got here because we reached the end of the arrays. 'limit' is the number of
4417   // garbage bytes we may have compared by reading over the end of the arrays. Shift
4418   // out the garbage and compare the remaining elements.
4419   bind(Lremaining);
4420   // Optimistic shortcut: elements potentially including garbage are equal
4421   brx(Assembler::equal, true, Assembler::pt, target(Ldone));
4422   delayed()->mov(1, result); // equal
4423   // Shift 'limit' bytes to the right and compare
4424   sll(limit, 3, limit); // bytes to bits
4425   srlx(result, limit, result);
4426   srlx(tmp, limit, tmp);
4427   cmp(result, tmp);
4428   clr(result);
4429   movcc(Assembler::equal, false, xcc, 1, result);
4430 
4431   bind(Ldone);
4432 }
4433 
4434 void MacroAssembler::has_negatives(Register inp, Register size, Register result, Register t2, Register t3, Register t4, Register t5) {
4435 
4436   // test for negative bytes in input string of a given size
4437   // result 1 if found, 0 otherwise.
4438 
4439   Label Lcore, Ltail, Lreturn, Lcore_rpt;
4440 
4441   assert_different_registers(inp, size, t2, t3, t4, t5, result);
4442 
4443   Register i     = result;  // result used as integer index i until very end
4444   Register lmask = t2;      // t2 is aliased to lmask
4445 
4446   // INITIALIZATION
4447   // ===========================================================
4448   // initialize highbits mask -> lmask = 0x8080808080808080  (8B/64b)
4449   // compute unaligned offset -> i
4450   // compute core end index   -> t5
4451   Assembler::sethi(0x80808000, t2);   //! sethi macro fails to emit optimal
4452   add(t2, 0x80, t2);
4453   sllx(t2, 32, t3);
4454   or3(t3, t2, lmask);                 // 0x8080808080808080 -> lmask
4455   sra(size,0,size);
4456   andcc(inp, 0x7, i);                 // unaligned offset -> i
4457   br(Assembler::zero, true, Assembler::pn, Lcore); // starts 8B aligned?
4458   delayed()->add(size, -8, t5);       // (annuled) core end index -> t5
4459 
4460   // ===========================================================
4461 
4462   // UNALIGNED HEAD
4463   // ===========================================================
4464   // * unaligned head handling: grab aligned 8B containing unaligned inp(ut)
4465   // * obliterate (ignore) bytes outside string by shifting off reg ends
4466   // * compare with bitmask, short circuit return true if one or more high
4467   //   bits set.
4468   cmp(size, 0);
4469   br(Assembler::zero, true, Assembler::pn, Lreturn); // short-circuit?
4470   delayed()->mov(0,result);      // annuled so i not clobbered for following
4471   neg(i, t4);
4472   add(i, size, t5);
4473   ldx(inp, t4, t3);  // raw aligned 8B containing unaligned head -> t3
4474   mov(8, t4);
4475   sub(t4, t5, t4);
4476   sra(t4, 31, t5);
4477   andn(t4, t5, t5);
4478   add(i, t5, t4);
4479   sll(t5, 3, t5);
4480   sll(t4, 3, t4);   // # bits to shift right, left -> t5,t4
4481   srlx(t3, t5, t3);
4482   sllx(t3, t4, t3); // bytes outside string in 8B header obliterated -> t3
4483   andcc(lmask, t3, G0);
4484   brx(Assembler::notZero, true, Assembler::pn, Lreturn); // short circuit?
4485   delayed()->mov(1,result);      // annuled so i not clobbered for following
4486   add(size, -8, t5);             // core end index -> t5
4487   mov(8, t4);
4488   sub(t4, i, i);                 // # bytes examined in unalgn head (<8) -> i
4489   // ===========================================================
4490 
4491   // ALIGNED CORE
4492   // ===========================================================
4493   // * iterate index i over aligned 8B sections of core, comparing with
4494   //   bitmask, short circuit return true if one or more high bits set
4495   // t5 contains core end index/loop limit which is the index
4496   //     of the MSB of last (unaligned) 8B fully contained in the string.
4497   // inp   contains address of first byte in string/array
4498   // lmask contains 8B high bit mask for comparison
4499   // i     contains next index to be processed (adr. inp+i is on 8B boundary)
4500   bind(Lcore);
4501   cmp_and_br_short(i, t5, Assembler::greater, Assembler::pn, Ltail);
4502   bind(Lcore_rpt);
4503   ldx(inp, i, t3);
4504   andcc(t3, lmask, G0);
4505   brx(Assembler::notZero, true, Assembler::pn, Lreturn);
4506   delayed()->mov(1, result);    // annuled so i not clobbered for following
4507   add(i, 8, i);
4508   cmp_and_br_short(i, t5, Assembler::lessEqual, Assembler::pn, Lcore_rpt);
4509   // ===========================================================
4510 
4511   // ALIGNED TAIL (<8B)
4512   // ===========================================================
4513   // handle aligned tail of 7B or less as complete 8B, obliterating end of
4514   // string bytes by shifting them off end, compare what's left with bitmask
4515   // inp   contains address of first byte in string/array
4516   // lmask contains 8B high bit mask for comparison
4517   // i     contains next index to be processed (adr. inp+i is on 8B boundary)
4518   bind(Ltail);
4519   subcc(size, i, t4);   // # of remaining bytes in string -> t4
4520   // return 0 if no more remaining bytes
4521   br(Assembler::lessEqual, true, Assembler::pn, Lreturn);
4522   delayed()->mov(0, result); // annuled so i not clobbered for following
4523   ldx(inp, i, t3);       // load final 8B (aligned) containing tail -> t3
4524   mov(8, t5);
4525   sub(t5, t4, t4);
4526   mov(0, result);        // ** i clobbered at this point
4527   sll(t4, 3, t4);        // bits beyond end of string          -> t4
4528   srlx(t3, t4, t3);      // bytes beyond end now obliterated   -> t3
4529   andcc(lmask, t3, G0);
4530   movcc(Assembler::notZero, false, xcc,  1, result);
4531   bind(Lreturn);
4532 }
4533 
4534 #endif
4535 
4536 
4537 // Use BIS for zeroing (count is in bytes).
4538 void MacroAssembler::bis_zeroing(Register to, Register count, Register temp, Label& Ldone) {
4539   assert(UseBlockZeroing && VM_Version::has_blk_zeroing(), "only works with BIS zeroing");
4540   Register end = count;
4541   int cache_line_size = VM_Version::prefetch_data_size();
4542   assert(cache_line_size > 0, "cache line size should be known for this code");
4543   // Minimum count when BIS zeroing can be used since
4544   // it needs membar which is expensive.
4545   int block_zero_size  = MAX2(cache_line_size*3, (int)BlockZeroingLowLimit);
4546 
4547   Label small_loop;
4548   // Check if count is negative (dead code) or zero.
4549   // Note, count uses 64bit in 64 bit VM.
4550   cmp_and_brx_short(count, 0, Assembler::lessEqual, Assembler::pn, Ldone);
4551 
4552   // Use BIS zeroing only for big arrays since it requires membar.
4553   if (Assembler::is_simm13(block_zero_size)) { // < 4096
4554     cmp(count, block_zero_size);
4555   } else {
4556     set(block_zero_size, temp);
4557     cmp(count, temp);
4558   }
4559   br(Assembler::lessUnsigned, false, Assembler::pt, small_loop);
4560   delayed()->add(to, count, end);
4561 
4562   // Note: size is >= three (32 bytes) cache lines.
4563 
4564   // Clean the beginning of space up to next cache line.
4565   for (int offs = 0; offs < cache_line_size; offs += 8) {
4566     stx(G0, to, offs);
4567   }
4568 
4569   // align to next cache line
4570   add(to, cache_line_size, to);
4571   and3(to, -cache_line_size, to);
4572 
4573   // Note: size left >= two (32 bytes) cache lines.
4574 
4575   // BIS should not be used to zero tail (64 bytes)
4576   // to avoid zeroing a header of the following object.
4577   sub(end, (cache_line_size*2)-8, end);
4578 
4579   Label bis_loop;
4580   bind(bis_loop);
4581   stxa(G0, to, G0, Assembler::ASI_ST_BLKINIT_PRIMARY);
4582   add(to, cache_line_size, to);
4583   cmp_and_brx_short(to, end, Assembler::lessUnsigned, Assembler::pt, bis_loop);
4584 
4585   // BIS needs membar.
4586   membar(Assembler::StoreLoad);
4587 
4588   add(end, (cache_line_size*2)-8, end); // restore end
4589   cmp_and_brx_short(to, end, Assembler::greaterEqualUnsigned, Assembler::pn, Ldone);
4590 
4591   // Clean the tail.
4592   bind(small_loop);
4593   stx(G0, to, 0);
4594   add(to, 8, to);
4595   cmp_and_brx_short(to, end, Assembler::lessUnsigned, Assembler::pt, small_loop);
4596   nop(); // Separate short branches
4597 }
4598 
4599 /**
4600  * Update CRC-32[C] with a byte value according to constants in table
4601  *
4602  * @param [in,out]crc   Register containing the crc.
4603  * @param [in]val       Register containing the byte to fold into the CRC.
4604  * @param [in]table     Register containing the table of crc constants.
4605  *
4606  * uint32_t crc;
4607  * val = crc_table[(val ^ crc) & 0xFF];
4608  * crc = val ^ (crc >> 8);
4609  */
4610 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
4611   xor3(val, crc, val);
4612   and3(val, 0xFF, val);
4613   sllx(val, 2, val);
4614   lduw(table, val, val);
4615   srlx(crc, 8, crc);
4616   xor3(val, crc, crc);
4617 }
4618 
4619 // Reverse byte order of lower 32 bits, assuming upper 32 bits all zeros
4620 void MacroAssembler::reverse_bytes_32(Register src, Register dst, Register tmp) {
4621     srlx(src, 24, dst);
4622 
4623     sllx(src, 32+8, tmp);
4624     srlx(tmp, 32+24, tmp);
4625     sllx(tmp, 8, tmp);
4626     or3(dst, tmp, dst);
4627 
4628     sllx(src, 32+16, tmp);
4629     srlx(tmp, 32+24, tmp);
4630     sllx(tmp, 16, tmp);
4631     or3(dst, tmp, dst);
4632 
4633     sllx(src, 32+24, tmp);
4634     srlx(tmp, 32, tmp);
4635     or3(dst, tmp, dst);
4636 }
4637 
4638 void MacroAssembler::movitof_revbytes(Register src, FloatRegister dst, Register tmp1, Register tmp2) {
4639   reverse_bytes_32(src, tmp1, tmp2);
4640   movxtod(tmp1, dst);
4641 }
4642 
4643 void MacroAssembler::movftoi_revbytes(FloatRegister src, Register dst, Register tmp1, Register tmp2) {
4644   movdtox(src, tmp1);
4645   reverse_bytes_32(tmp1, dst, tmp2);
4646 }
4647 
4648 void MacroAssembler::fold_128bit_crc32(Register xcrc_hi, Register xcrc_lo, Register xK_hi, Register xK_lo, Register xtmp_hi, Register xtmp_lo, Register buf, int offset) {
4649   xmulx(xcrc_hi, xK_hi, xtmp_lo);
4650   xmulxhi(xcrc_hi, xK_hi, xtmp_hi);
4651   xmulxhi(xcrc_lo, xK_lo, xcrc_hi);
4652   xmulx(xcrc_lo, xK_lo, xcrc_lo);
4653   xor3(xcrc_lo, xtmp_lo, xcrc_lo);
4654   xor3(xcrc_hi, xtmp_hi, xcrc_hi);
4655   ldxl(buf, G0, xtmp_lo);
4656   inc(buf, 8);
4657   ldxl(buf, G0, xtmp_hi);
4658   inc(buf, 8);
4659   xor3(xcrc_lo, xtmp_lo, xcrc_lo);
4660   xor3(xcrc_hi, xtmp_hi, xcrc_hi);
4661 }
4662 
4663 void MacroAssembler::fold_128bit_crc32(Register xcrc_hi, Register xcrc_lo, Register xK_hi, Register xK_lo, Register xtmp_hi, Register xtmp_lo, Register xbuf_hi, Register xbuf_lo) {
4664   mov(xcrc_lo, xtmp_lo);
4665   mov(xcrc_hi, xtmp_hi);
4666   xmulx(xtmp_hi, xK_hi, xtmp_lo);
4667   xmulxhi(xtmp_hi, xK_hi, xtmp_hi);
4668   xmulxhi(xcrc_lo, xK_lo, xcrc_hi);
4669   xmulx(xcrc_lo, xK_lo, xcrc_lo);
4670   xor3(xcrc_lo, xbuf_lo, xcrc_lo);
4671   xor3(xcrc_hi, xbuf_hi, xcrc_hi);
4672   xor3(xcrc_lo, xtmp_lo, xcrc_lo);
4673   xor3(xcrc_hi, xtmp_hi, xcrc_hi);
4674 }
4675 
4676 void MacroAssembler::fold_8bit_crc32(Register xcrc, Register table, Register xtmp, Register tmp) {
4677   and3(xcrc, 0xFF, tmp);
4678   sllx(tmp, 2, tmp);
4679   lduw(table, tmp, xtmp);
4680   srlx(xcrc, 8, xcrc);
4681   xor3(xtmp, xcrc, xcrc);
4682 }
4683 
4684 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
4685   and3(crc, 0xFF, tmp);
4686   srlx(crc, 8, crc);
4687   sllx(tmp, 2, tmp);
4688   lduw(table, tmp, tmp);
4689   xor3(tmp, crc, crc);
4690 }
4691 
4692 #define CRC32_TMP_REG_NUM 18
4693 
4694 #define CRC32_CONST_64  0x163cd6124
4695 #define CRC32_CONST_96  0x0ccaa009e
4696 #define CRC32_CONST_160 0x1751997d0
4697 #define CRC32_CONST_480 0x1c6e41596
4698 #define CRC32_CONST_544 0x154442bd4
4699 
4700 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table) {
4701 
4702   Label L_cleanup_loop, L_cleanup_check, L_align_loop, L_align_check;
4703   Label L_main_loop_prologue;
4704   Label L_fold_512b, L_fold_512b_loop, L_fold_128b;
4705   Label L_fold_tail, L_fold_tail_loop;
4706   Label L_8byte_fold_loop, L_8byte_fold_check;
4707 
4708   const Register tmp[CRC32_TMP_REG_NUM] = {L0, L1, L2, L3, L4, L5, L6, G1, I0, I1, I2, I3, I4, I5, I7, O4, O5, G3};
4709 
4710   Register const_64  = tmp[CRC32_TMP_REG_NUM-1];
4711   Register const_96  = tmp[CRC32_TMP_REG_NUM-1];
4712   Register const_160 = tmp[CRC32_TMP_REG_NUM-2];
4713   Register const_480 = tmp[CRC32_TMP_REG_NUM-1];
4714   Register const_544 = tmp[CRC32_TMP_REG_NUM-2];
4715 
4716   set(ExternalAddress(StubRoutines::crc_table_addr()), table);
4717 
4718   not1(crc); // ~c
4719   clruwu(crc); // clear upper 32 bits of crc
4720 
4721   // Check if below cutoff, proceed directly to cleanup code
4722   mov(31, G4);
4723   cmp_and_br_short(len, G4, Assembler::lessEqualUnsigned, Assembler::pt, L_cleanup_check);
4724 
4725   // Align buffer to 8 byte boundry
4726   mov(8, O5);
4727   and3(buf, 0x7, O4);
4728   sub(O5, O4, O5);
4729   and3(O5, 0x7, O5);
4730   sub(len, O5, len);
4731   ba(L_align_check);
4732   delayed()->nop();
4733 
4734   // Alignment loop, table look up method for up to 7 bytes
4735   bind(L_align_loop);
4736   ldub(buf, 0, O4);
4737   inc(buf);
4738   dec(O5);
4739   xor3(O4, crc, O4);
4740   and3(O4, 0xFF, O4);
4741   sllx(O4, 2, O4);
4742   lduw(table, O4, O4);
4743   srlx(crc, 8, crc);
4744   xor3(O4, crc, crc);
4745   bind(L_align_check);
4746   nop();
4747   cmp_and_br_short(O5, 0, Assembler::notEqual, Assembler::pt, L_align_loop);
4748 
4749   // Aligned on 64-bit (8-byte) boundry at this point
4750   // Check if still above cutoff (31-bytes)
4751   mov(31, G4);
4752   cmp_and_br_short(len, G4, Assembler::lessEqualUnsigned, Assembler::pt, L_cleanup_check);
4753   // At least 32 bytes left to process
4754 
4755   // Free up registers by storing them to FP registers
4756   for (int i = 0; i < CRC32_TMP_REG_NUM; i++) {
4757     movxtod(tmp[i], as_FloatRegister(2*i));
4758   }
4759 
4760   // Determine which loop to enter
4761   // Shared prologue
4762   ldxl(buf, G0, tmp[0]);
4763   inc(buf, 8);
4764   ldxl(buf, G0, tmp[1]);
4765   inc(buf, 8);
4766   xor3(tmp[0], crc, tmp[0]); // Fold CRC into first few bytes
4767   and3(crc, 0, crc); // Clear out the crc register
4768   // Main loop needs 128-bytes at least
4769   mov(128, G4);
4770   mov(64, tmp[2]);
4771   cmp_and_br_short(len, G4, Assembler::greaterEqualUnsigned, Assembler::pt, L_main_loop_prologue);
4772   // Less than 64 bytes
4773   nop();
4774   cmp_and_br_short(len, tmp[2], Assembler::lessUnsigned, Assembler::pt, L_fold_tail);
4775   // Between 64 and 127 bytes
4776   set64(CRC32_CONST_96,  const_96,  tmp[8]);
4777   set64(CRC32_CONST_160, const_160, tmp[9]);
4778   fold_128bit_crc32(tmp[1], tmp[0], const_96, const_160, tmp[2], tmp[3], buf, 0);
4779   fold_128bit_crc32(tmp[1], tmp[0], const_96, const_160, tmp[4], tmp[5], buf, 16);
4780   fold_128bit_crc32(tmp[1], tmp[0], const_96, const_160, tmp[6], tmp[7], buf, 32);
4781   dec(len, 48);
4782   ba(L_fold_tail);
4783   delayed()->nop();
4784 
4785   bind(L_main_loop_prologue);
4786   for (int i = 2; i < 8; i++) {
4787     ldxl(buf, G0, tmp[i]);
4788     inc(buf, 8);
4789   }
4790 
4791   // Fold total 512 bits of polynomial on each iteration,
4792   // 128 bits per each of 4 parallel streams
4793   set64(CRC32_CONST_480, const_480, tmp[8]);
4794   set64(CRC32_CONST_544, const_544, tmp[9]);
4795 
4796   mov(128, G4);
4797   bind(L_fold_512b_loop);
4798   fold_128bit_crc32(tmp[1], tmp[0], const_480, const_544, tmp[9],  tmp[8],  buf,  0);
4799   fold_128bit_crc32(tmp[3], tmp[2], const_480, const_544, tmp[11], tmp[10], buf, 16);
4800   fold_128bit_crc32(tmp[5], tmp[4], const_480, const_544, tmp[13], tmp[12], buf, 32);
4801   fold_128bit_crc32(tmp[7], tmp[6], const_480, const_544, tmp[15], tmp[14], buf, 64);
4802   dec(len, 64);
4803   cmp_and_br_short(len, G4, Assembler::greaterEqualUnsigned, Assembler::pt, L_fold_512b_loop);
4804 
4805   // Fold 512 bits to 128 bits
4806   bind(L_fold_512b);
4807   set64(CRC32_CONST_96,  const_96,  tmp[8]);
4808   set64(CRC32_CONST_160, const_160, tmp[9]);
4809 
4810   fold_128bit_crc32(tmp[1], tmp[0], const_96, const_160, tmp[8], tmp[9], tmp[3], tmp[2]);
4811   fold_128bit_crc32(tmp[1], tmp[0], const_96, const_160, tmp[8], tmp[9], tmp[5], tmp[4]);
4812   fold_128bit_crc32(tmp[1], tmp[0], const_96, const_160, tmp[8], tmp[9], tmp[7], tmp[6]);
4813   dec(len, 48);
4814 
4815   // Fold the rest of 128 bits data chunks
4816   bind(L_fold_tail);
4817   mov(32, G4);
4818   cmp_and_br_short(len, G4, Assembler::lessEqualUnsigned, Assembler::pt, L_fold_128b);
4819 
4820   set64(CRC32_CONST_96,  const_96,  tmp[8]);
4821   set64(CRC32_CONST_160, const_160, tmp[9]);
4822 
4823   bind(L_fold_tail_loop);
4824   fold_128bit_crc32(tmp[1], tmp[0], const_96, const_160, tmp[2], tmp[3], buf, 0);
4825   sub(len, 16, len);
4826   cmp_and_br_short(len, G4, Assembler::greaterEqualUnsigned, Assembler::pt, L_fold_tail_loop);
4827 
4828   // Fold the 128 bits in tmps 0 - 1 into tmp 1
4829   bind(L_fold_128b);
4830 
4831   set64(CRC32_CONST_64, const_64, tmp[4]);
4832 
4833   xmulx(const_64, tmp[0], tmp[2]);
4834   xmulxhi(const_64, tmp[0], tmp[3]);
4835 
4836   srl(tmp[2], G0, tmp[4]);
4837   xmulx(const_64, tmp[4], tmp[4]);
4838 
4839   srlx(tmp[2], 32, tmp[2]);
4840   sllx(tmp[3], 32, tmp[3]);
4841   or3(tmp[2], tmp[3], tmp[2]);
4842 
4843   xor3(tmp[4], tmp[1], tmp[4]);
4844   xor3(tmp[4], tmp[2], tmp[1]);
4845   dec(len, 8);
4846 
4847   // Use table lookup for the 8 bytes left in tmp[1]
4848   dec(len, 8);
4849 
4850   // 8 8-bit folds to compute 32-bit CRC.
4851   for (int j = 0; j < 4; j++) {
4852     fold_8bit_crc32(tmp[1], table, tmp[2], tmp[3]);
4853   }
4854   srl(tmp[1], G0, crc); // move 32 bits to general register
4855   for (int j = 0; j < 4; j++) {
4856     fold_8bit_crc32(crc, table, tmp[3]);
4857   }
4858 
4859   bind(L_8byte_fold_check);
4860 
4861   // Restore int registers saved in FP registers
4862   for (int i = 0; i < CRC32_TMP_REG_NUM; i++) {
4863     movdtox(as_FloatRegister(2*i), tmp[i]);
4864   }
4865 
4866   ba(L_cleanup_check);
4867   delayed()->nop();
4868 
4869   // Table look-up method for the remaining few bytes
4870   bind(L_cleanup_loop);
4871   ldub(buf, 0, O4);
4872   inc(buf);
4873   dec(len);
4874   xor3(O4, crc, O4);
4875   and3(O4, 0xFF, O4);
4876   sllx(O4, 2, O4);
4877   lduw(table, O4, O4);
4878   srlx(crc, 8, crc);
4879   xor3(O4, crc, crc);
4880   bind(L_cleanup_check);
4881   nop();
4882   cmp_and_br_short(len, 0, Assembler::greaterUnsigned, Assembler::pt, L_cleanup_loop);
4883 
4884   not1(crc);
4885 }
4886 
4887 #define CHUNK_LEN   128          /* 128 x 8B = 1KB */
4888 #define CHUNK_K1    0x1307a0206  /* reverseBits(pow(x, CHUNK_LEN*8*8*3 - 32) mod P(x)) << 1 */
4889 #define CHUNK_K2    0x1a0f717c4  /* reverseBits(pow(x, CHUNK_LEN*8*8*2 - 32) mod P(x)) << 1 */
4890 #define CHUNK_K3    0x0170076fa  /* reverseBits(pow(x, CHUNK_LEN*8*8*1 - 32) mod P(x)) << 1 */
4891 
4892 void MacroAssembler::kernel_crc32c(Register crc, Register buf, Register len, Register table) {
4893 
4894   Label L_crc32c_head, L_crc32c_aligned;
4895   Label L_crc32c_parallel, L_crc32c_parallel_loop;
4896   Label L_crc32c_serial, L_crc32c_x32_loop, L_crc32c_x8, L_crc32c_x8_loop;
4897   Label L_crc32c_done, L_crc32c_tail, L_crc32c_return;
4898 
4899   set(ExternalAddress(StubRoutines::crc32c_table_addr()), table);
4900 
4901   cmp_and_br_short(len, 0, Assembler::lessEqual, Assembler::pn, L_crc32c_return);
4902 
4903   // clear upper 32 bits of crc
4904   clruwu(crc);
4905 
4906   and3(buf, 7, G4);
4907   cmp_and_brx_short(G4, 0, Assembler::equal, Assembler::pt, L_crc32c_aligned);
4908 
4909   mov(8, G1);
4910   sub(G1, G4, G4);
4911 
4912   // ------ process the misaligned head (7 bytes or less) ------
4913   bind(L_crc32c_head);
4914 
4915   // crc = (crc >>> 8) ^ byteTable[(crc ^ b) & 0xFF];
4916   ldub(buf, 0, G1);
4917   update_byte_crc32(crc, G1, table);
4918 
4919   inc(buf);
4920   dec(len);
4921   cmp_and_br_short(len, 0, Assembler::equal, Assembler::pn, L_crc32c_return);
4922   dec(G4);
4923   cmp_and_br_short(G4, 0, Assembler::greater, Assembler::pt, L_crc32c_head);
4924 
4925   // ------ process the 8-byte-aligned body ------
4926   bind(L_crc32c_aligned);
4927   nop();
4928   cmp_and_br_short(len, 8, Assembler::less, Assembler::pn, L_crc32c_tail);
4929 
4930   // reverse the byte order of lower 32 bits to big endian, and move to FP side
4931   movitof_revbytes(crc, F0, G1, G3);
4932 
4933   set(CHUNK_LEN*8*4, G4);
4934   cmp_and_br_short(len, G4, Assembler::less, Assembler::pt, L_crc32c_serial);
4935 
4936   // ------ process four 1KB chunks in parallel ------
4937   bind(L_crc32c_parallel);
4938 
4939   fzero(FloatRegisterImpl::D, F2);
4940   fzero(FloatRegisterImpl::D, F4);
4941   fzero(FloatRegisterImpl::D, F6);
4942 
4943   mov(CHUNK_LEN - 1, G4);
4944   bind(L_crc32c_parallel_loop);
4945   // schedule ldf's ahead of crc32c's to hide the load-use latency
4946   ldf(FloatRegisterImpl::D, buf, 0,            F8);
4947   ldf(FloatRegisterImpl::D, buf, CHUNK_LEN*8,  F10);
4948   ldf(FloatRegisterImpl::D, buf, CHUNK_LEN*16, F12);
4949   ldf(FloatRegisterImpl::D, buf, CHUNK_LEN*24, F14);
4950   crc32c(F0, F8,  F0);
4951   crc32c(F2, F10, F2);
4952   crc32c(F4, F12, F4);
4953   crc32c(F6, F14, F6);
4954   inc(buf, 8);
4955   dec(G4);
4956   cmp_and_br_short(G4, 0, Assembler::greater, Assembler::pt, L_crc32c_parallel_loop);
4957 
4958   ldf(FloatRegisterImpl::D, buf, 0,            F8);
4959   ldf(FloatRegisterImpl::D, buf, CHUNK_LEN*8,  F10);
4960   ldf(FloatRegisterImpl::D, buf, CHUNK_LEN*16, F12);
4961   crc32c(F0, F8,  F0);
4962   crc32c(F2, F10, F2);
4963   crc32c(F4, F12, F4);
4964 
4965   inc(buf, CHUNK_LEN*24);
4966   ldfl(FloatRegisterImpl::D, buf, G0, F14);  // load in little endian
4967   inc(buf, 8);
4968 
4969   prefetch(buf, 0,            Assembler::severalReads);
4970   prefetch(buf, CHUNK_LEN*8,  Assembler::severalReads);
4971   prefetch(buf, CHUNK_LEN*16, Assembler::severalReads);
4972   prefetch(buf, CHUNK_LEN*24, Assembler::severalReads);
4973 
4974   // move to INT side, and reverse the byte order of lower 32 bits to little endian
4975   movftoi_revbytes(F0, O4, G1, G4);
4976   movftoi_revbytes(F2, O5, G1, G4);
4977   movftoi_revbytes(F4, G5, G1, G4);
4978 
4979   // combine the results of 4 chunks
4980   set64(CHUNK_K1, G3, G1);
4981   xmulx(O4, G3, O4);
4982   set64(CHUNK_K2, G3, G1);
4983   xmulx(O5, G3, O5);
4984   set64(CHUNK_K3, G3, G1);
4985   xmulx(G5, G3, G5);
4986 
4987   movdtox(F14, G4);
4988   xor3(O4, O5, O5);
4989   xor3(G5, O5, O5);
4990   xor3(G4, O5, O5);
4991 
4992   // reverse the byte order to big endian, via stack, and move to FP side
4993   // TODO: use new revb instruction
4994   add(SP, -8, G1);
4995   srlx(G1, 3, G1);
4996   sllx(G1, 3, G1);
4997   stx(O5, G1, G0);
4998   ldfl(FloatRegisterImpl::D, G1, G0, F2);  // load in little endian
4999 
5000   crc32c(F6, F2, F0);
5001 
5002   set(CHUNK_LEN*8*4, G4);
5003   sub(len, G4, len);
5004   cmp_and_br_short(len, G4, Assembler::greaterEqual, Assembler::pt, L_crc32c_parallel);
5005   nop();
5006   cmp_and_br_short(len, 0, Assembler::equal, Assembler::pt, L_crc32c_done);
5007 
5008   bind(L_crc32c_serial);
5009 
5010   mov(32, G4);
5011   cmp_and_br_short(len, G4, Assembler::less, Assembler::pn, L_crc32c_x8);
5012 
5013   // ------ process 32B chunks ------
5014   bind(L_crc32c_x32_loop);
5015   ldf(FloatRegisterImpl::D, buf, 0, F2);
5016   crc32c(F0, F2, F0);
5017   ldf(FloatRegisterImpl::D, buf, 8, F2);
5018   crc32c(F0, F2, F0);
5019   ldf(FloatRegisterImpl::D, buf, 16, F2);
5020   crc32c(F0, F2, F0);
5021   ldf(FloatRegisterImpl::D, buf, 24, F2);
5022   inc(buf, 32);
5023   crc32c(F0, F2, F0);
5024   dec(len, 32);
5025   cmp_and_br_short(len, G4, Assembler::greaterEqual, Assembler::pt, L_crc32c_x32_loop);
5026 
5027   bind(L_crc32c_x8);
5028   nop();
5029   cmp_and_br_short(len, 8, Assembler::less, Assembler::pt, L_crc32c_done);
5030 
5031   // ------ process 8B chunks ------
5032   bind(L_crc32c_x8_loop);
5033   ldf(FloatRegisterImpl::D, buf, 0, F2);
5034   inc(buf, 8);
5035   crc32c(F0, F2, F0);
5036   dec(len, 8);
5037   cmp_and_br_short(len, 8, Assembler::greaterEqual, Assembler::pt, L_crc32c_x8_loop);
5038 
5039   bind(L_crc32c_done);
5040 
5041   // move to INT side, and reverse the byte order of lower 32 bits to little endian
5042   movftoi_revbytes(F0, crc, G1, G3);
5043 
5044   cmp_and_br_short(len, 0, Assembler::equal, Assembler::pt, L_crc32c_return);
5045 
5046   // ------ process the misaligned tail (7 bytes or less) ------
5047   bind(L_crc32c_tail);
5048 
5049   // crc = (crc >>> 8) ^ byteTable[(crc ^ b) & 0xFF];
5050   ldub(buf, 0, G1);
5051   update_byte_crc32(crc, G1, table);
5052 
5053   inc(buf);
5054   dec(len);
5055   cmp_and_br_short(len, 0, Assembler::greater, Assembler::pt, L_crc32c_tail);
5056 
5057   bind(L_crc32c_return);
5058   nop();
5059 }