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