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