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