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