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