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