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