1 /*
  2  * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
  3  * Copyright (c) 2018, 2020, Red Hat, Inc. All rights reserved.
  4  * Copyright (c) 2020, 2021, Huawei Technologies Co., Ltd. All rights reserved.
  5  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  6  *
  7  * This code is free software; you can redistribute it and/or modify it
  8  * under the terms of the GNU General Public License version 2 only, as
  9  * published by the Free Software Foundation.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  *
 25  */
 26 
 27 #include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
 28 #include "gc/shenandoah/mode/shenandoahMode.hpp"
 29 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
 30 #include "gc/shenandoah/shenandoahBarrierSetAssembler.hpp"
 31 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
 32 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
 33 #include "gc/shenandoah/shenandoahNMethod.inline.hpp"
 34 #include "gc/shenandoah/shenandoahRuntime.hpp"
 35 #include "gc/shenandoah/shenandoahThreadLocalData.hpp"
 36 #include "interpreter/interp_masm.hpp"
 37 #include "interpreter/interpreter.hpp"
 38 #include "nativeInst_riscv.hpp"
 39 #include "runtime/javaThread.hpp"
 40 #include "runtime/sharedRuntime.hpp"
 41 #ifdef COMPILER1
 42 #include "c1/c1_LIRAssembler.hpp"
 43 #include "c1/c1_MacroAssembler.hpp"
 44 #include "gc/shenandoah/c1/shenandoahBarrierSetC1.hpp"
 45 #endif
 46 #ifdef COMPILER2
 47 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
 48 #include "opto/output.hpp"
 49 #endif
 50 
 51 #define __ masm->
 52 
 53 void ShenandoahBarrierSetAssembler::arraycopy_prologue(MacroAssembler* masm, DecoratorSet decorators, bool is_oop,
 54                                                        Register src, Register dst, Register count, RegSet saved_regs) {
 55   if (is_oop) {
 56     bool dest_uninitialized = (decorators & IS_DEST_UNINITIALIZED) != 0;
 57     if ((ShenandoahSATBBarrier && !dest_uninitialized) || ShenandoahLoadRefBarrier) {
 58 
 59       Label done;
 60 
 61       // Avoid calling runtime if count == 0
 62       __ beqz(count, done);
 63 
 64       // Is GC active?
 65       Address gc_state(xthread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 66       assert_different_registers(src, dst, count, t0);
 67 
 68       assert(!saved_regs.contains(t0), "Sanity: about to clobber t0");
 69 
 70       __ lbu(t0, gc_state);
 71       if (ShenandoahSATBBarrier && dest_uninitialized) {
 72         __ test_bit(t0, t0, ShenandoahHeap::HAS_FORWARDED_BITPOS);
 73         __ beqz(t0, done);
 74       } else {
 75         __ andi(t0, t0, ShenandoahHeap::HAS_FORWARDED | ShenandoahHeap::MARKING);
 76         __ beqz(t0, done);
 77       }
 78 
 79       __ push_call_clobbered_registers();
 80       // If arguments are not in proper places, shuffle them.
 81       // Doing this via the stack is the most straight-forward way to avoid
 82       // accidentally smashing any register.
 83       if (c_rarg0 != src || c_rarg1 != dst || c_rarg2 != count) {
 84         __ push_reg(RegSet::of(src), sp);
 85         __ push_reg(RegSet::of(dst), sp);
 86         __ push_reg(RegSet::of(count), sp);
 87         __ pop_reg(RegSet::of(c_rarg2), sp);
 88         __ pop_reg(RegSet::of(c_rarg1), sp);
 89         __ pop_reg(RegSet::of(c_rarg0), sp);
 90       }
 91       address target = nullptr;
 92       if (UseCompressedOops) {
 93         target = CAST_FROM_FN_PTR(address, ShenandoahRuntime::arraycopy_barrier_narrow_oop);
 94       } else {
 95         target = CAST_FROM_FN_PTR(address, ShenandoahRuntime::arraycopy_barrier_oop);
 96       }
 97       __ call_VM_leaf(target, 3);
 98       __ pop_call_clobbered_registers();
 99       __ bind(done);
100     }
101   }
102 }
103 
104 void ShenandoahBarrierSetAssembler::arraycopy_epilogue(MacroAssembler* masm, DecoratorSet decorators, bool is_oop,
105                                                        Register start, Register count, Register tmp) {
106   if (ShenandoahCardBarrier && is_oop) {
107     gen_write_ref_array_post_barrier(masm, decorators, start, count, tmp);
108   }
109 }
110 
111 void ShenandoahBarrierSetAssembler::satb_barrier(MacroAssembler* masm,
112                                                  Register obj,
113                                                  Register pre_val,
114                                                  Register thread,
115                                                  Register tmp1,
116                                                  Register tmp2) {
117   assert(ShenandoahSATBBarrier, "Should be checked by caller");
118   assert(thread == xthread, "must be");
119 
120   Label done;
121   Label runtime;
122 
123   assert_different_registers(obj, pre_val, tmp1, tmp2);
124   assert(pre_val != noreg && tmp1 != noreg && tmp2 != noreg, "expecting a register");
125 
126   Address index(thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset()));
127   Address buffer(thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset()));
128 
129   // Is marking active?
130   Address gc_state(xthread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
131   __ lbu(t1, gc_state);
132   __ test_bit(t1, t1, ShenandoahHeap::MARKING_BITPOS);
133   __ beqz(t1, done);
134 
135   // Do we need to load the previous value?
136   if (obj != noreg) {
137     if (UseCompressedOops) {
138       __ lwu(pre_val, Address(obj, 0));
139       __ decode_heap_oop(pre_val);
140     } else {
141       __ ld(pre_val, Address(obj, 0));
142     }
143   }
144 
145   // Is the previous value null?
146   __ beqz(pre_val, done);
147 
148   // Can we store original value in the thread's buffer?
149   // Is index == 0?
150   // (The index field is typed as size_t.)
151   __ ld(tmp1, index);                  // tmp := *index_adr
152   __ beqz(tmp1, runtime);              // tmp == 0? If yes, goto runtime
153 
154   __ subi(tmp1, tmp1, wordSize);       // tmp := tmp - wordSize
155   __ sd(tmp1, index);                  // *index_adr := tmp
156   __ ld(tmp2, buffer);
157   __ add(tmp1, tmp1, tmp2);            // tmp := tmp + *buffer_adr
158 
159   // Record the previous value
160   __ sd(pre_val, Address(tmp1, 0));
161   __ j(done);
162 
163   // Slow-path call.
164   __ bind(runtime);
165   __ enter();
166   __ push_call_clobbered_registers();
167   if (c_rarg0 != pre_val) {
168     __ mv(c_rarg0, pre_val);
169   }
170   // Calling with super_call_VM_leaf with c_rarg0 bypasses interpreter checks and avoids any moves.
171   __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_barrier_pre), c_rarg0);
172   __ pop_call_clobbered_registers();
173   __ leave();
174 
175   __ bind(done);
176 }
177 
178 void ShenandoahBarrierSetAssembler::load_reference_barrier(MacroAssembler* masm,
179                                                            Register dst,
180                                                            Address load_addr,
181                                                            DecoratorSet decorators) {
182   assert(ShenandoahLoadRefBarrier, "Should be enabled");
183   assert(dst != t1 && load_addr.base() != t1, "need t1");
184   assert_different_registers(load_addr.base(), t0, t1);
185 
186   bool is_strong  = ShenandoahBarrierSet::is_strong_access(decorators);
187   bool is_weak    = ShenandoahBarrierSet::is_weak_access(decorators);
188   bool is_phantom = ShenandoahBarrierSet::is_phantom_access(decorators);
189   bool is_native  = ShenandoahBarrierSet::is_native_access(decorators);
190   bool is_narrow  = UseCompressedOops && !is_native;
191 
192   Label heap_stable, not_cset;
193   Address gc_state(xthread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
194   __ lbu(t1, gc_state);
195 
196   // Check for heap stability
197   if (is_strong) {
198     __ test_bit(t1, t1, ShenandoahHeap::HAS_FORWARDED_BITPOS);
199     __ beqz(t1, heap_stable);
200   } else {
201     Label lrb;
202     __ test_bit(t0, t1, ShenandoahHeap::WEAK_ROOTS_BITPOS);
203     __ bnez(t0, lrb);
204     __ test_bit(t0, t1, ShenandoahHeap::HAS_FORWARDED_BITPOS);
205     __ beqz(t0, heap_stable);
206     __ bind(lrb);
207   }
208 
209   // use x11 for load address
210   Register result_dst = dst;
211   if (dst == x11) {
212     __ mv(t1, dst);
213     dst = t1;
214   }
215 
216   // Save x10 and x11, unless it is an output register
217   RegSet saved_regs = RegSet::of(x10, x11) - result_dst;
218   __ push_reg(saved_regs, sp);
219   __ la(x11, load_addr);
220   __ mv(x10, dst);
221 
222   // Test for in-cset
223   if (is_strong) {
224     __ mv(t1, ShenandoahHeap::in_cset_fast_test_addr());
225     __ srli(t0, x10, ShenandoahHeapRegion::region_size_bytes_shift_jint());
226     __ add(t1, t1, t0);
227     __ lbu(t1, Address(t1));
228     __ test_bit(t0, t1, 0);
229     __ beqz(t0, not_cset);
230   }
231 
232   // Slow-path call
233   __ enter();
234   __ push_call_clobbered_registers();
235   address target = nullptr;
236   if (is_strong) {
237     if (is_narrow) {
238       target = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong_narrow);
239     } else {
240       target = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong);
241     }
242   } else if (is_weak) {
243     if (is_narrow) {
244       target = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak_narrow);
245     } else {
246       target = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak);
247     }
248   } else {
249     assert(is_phantom, "only remaining strength");
250     assert(!is_narrow, "phantom access cannot be narrow");
251     target = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom);
252   }
253   // Calling with super_call_VM_leaf with c_rarg0/1 bypasses interpreter checks and avoids any moves.
254   __ super_call_VM_leaf(target, c_rarg0, c_rarg1);
255   __ mv(t0, x10);
256   __ pop_call_clobbered_registers();
257   __ mv(x10, t0);
258   __ leave();
259 
260   __ bind(not_cset);
261   __ mv(result_dst, x10);
262   __ pop_reg(saved_regs, sp);
263 
264   __ bind(heap_stable);
265 }
266 
267 //
268 // Arguments:
269 //
270 // Inputs:
271 //   src:        oop location to load from, might be clobbered
272 //
273 // Output:
274 //   dst:        oop loaded from src location
275 //
276 // Kill:
277 //   x30 (tmp reg)
278 //
279 // Alias:
280 //   dst: x30 (might use x30 as temporary output register to avoid clobbering src)
281 //
282 void ShenandoahBarrierSetAssembler::load_at(MacroAssembler* masm,
283                                             DecoratorSet decorators,
284                                             BasicType type,
285                                             Register dst,
286                                             Address src,
287                                             Register tmp1,
288                                             Register tmp2) {
289   // 1: non-reference load, no additional barrier is needed
290   if (!is_reference_type(type)) {
291     BarrierSetAssembler::load_at(masm, decorators, type, dst, src, tmp1, tmp2);
292     return;
293   }
294 
295   // 2: load a reference from src location and apply LRB if needed
296   if (ShenandoahBarrierSet::need_load_reference_barrier(decorators, type)) {
297     Register result_dst = dst;
298 
299     // Preserve src location for LRB
300     RegSet saved_regs;
301     if (dst == src.base()) {
302       dst = (src.base() == x28) ? x29 : x28;
303       saved_regs = RegSet::of(dst);
304       __ push_reg(saved_regs, sp);
305     }
306     assert_different_registers(dst, src.base());
307 
308     BarrierSetAssembler::load_at(masm, decorators, type, dst, src, tmp1, tmp2);
309 
310     load_reference_barrier(masm, dst, src, decorators);
311 
312     if (dst != result_dst) {
313       __ mv(result_dst, dst);
314       dst = result_dst;
315     }
316 
317     if (saved_regs.bits() != 0) {
318       __ pop_reg(saved_regs, sp);
319     }
320   } else {
321     BarrierSetAssembler::load_at(masm, decorators, type, dst, src, tmp1, tmp2);
322   }
323 
324   // 3: apply keep-alive barrier if needed
325   if (ShenandoahBarrierSet::need_keep_alive_barrier(decorators, type)) {
326     satb_barrier(masm /* masm */,
327                  noreg /* obj */,
328                  dst /* pre_val */,
329                  xthread /* thread */,
330                  tmp1 /* tmp1 */,
331                  tmp2 /* tmp2 */);
332   }
333 }
334 
335 void ShenandoahBarrierSetAssembler::card_barrier(MacroAssembler* masm, Register obj) {
336   assert(ShenandoahCardBarrier, "Should have been checked by caller");
337 
338   __ srli(obj, obj, CardTable::card_shift());
339 
340   assert(CardTable::dirty_card_val() == 0, "must be");
341 
342   Address curr_ct_holder_addr(xthread, in_bytes(ShenandoahThreadLocalData::card_table_offset()));
343   __ ld(t1, curr_ct_holder_addr);
344   __ add(t1, obj, t1);
345 
346   if (UseCondCardMark) {
347     Label L_already_dirty;
348     __ lbu(t0, Address(t1));
349     __ beqz(t0, L_already_dirty);
350     __ sb(zr, Address(t1));
351     __ bind(L_already_dirty);
352   } else {
353     __ sb(zr, Address(t1));
354   }
355 }
356 
357 void ShenandoahBarrierSetAssembler::store_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
358                                              Address dst, Register val, Register tmp1, Register tmp2, Register tmp3) {
359   // 1: non-reference types require no barriers
360   if (!is_reference_type(type)) {
361     BarrierSetAssembler::store_at(masm, decorators, type, dst, val, tmp1, tmp2, tmp3);
362     return;
363   }
364 
365   // Flatten object address right away for simplicity: likely needed by barriers
366   if (dst.offset() == 0) {
367     if (dst.base() != tmp3) {
368       __ mv(tmp3, dst.base());
369     }
370   } else {
371     __ la(tmp3, dst);
372   }
373 
374   // 2: pre-barrier: SATB needs the previous value
375   if (ShenandoahBarrierSet::need_satb_barrier(decorators, type)) {
376     satb_barrier(masm,
377                  tmp3 /* obj */,
378                  tmp2 /* pre_val */,
379                  xthread /* thread */,
380                  tmp1 /* tmp */,
381                  t0 /* tmp2 */);
382   }
383 
384   // Store!
385   BarrierSetAssembler::store_at(masm, decorators, type, Address(tmp3, 0), val, noreg, noreg, noreg);
386 
387   // 3: post-barrier: card barrier needs store address
388   bool storing_non_null = (val != noreg);
389   if (ShenandoahBarrierSet::need_card_barrier(decorators, type) && storing_non_null) {
390     card_barrier(masm, tmp3);
391   }
392 }
393 
394 void ShenandoahBarrierSetAssembler::try_resolve_jobject_in_native(MacroAssembler* masm, Register jni_env,
395                                                                   Register obj, Register tmp, Label& slowpath) {
396   Label done;
397   // Resolve jobject
398   BarrierSetAssembler::try_resolve_jobject_in_native(masm, jni_env, obj, tmp, slowpath);
399 
400   // Check for null.
401   __ beqz(obj, done);
402 
403   assert(obj != t1, "need t1");
404   Address gc_state(jni_env, ShenandoahThreadLocalData::gc_state_offset() - JavaThread::jni_environment_offset());
405   __ lbu(t1, gc_state);
406 
407   // Check for heap in evacuation phase
408   __ test_bit(t0, t1, ShenandoahHeap::EVACUATION_BITPOS);
409   __ bnez(t0, slowpath);
410 
411   __ bind(done);
412 }
413 
414 void ShenandoahBarrierSetAssembler::try_peek_weak_handle_in_nmethod(MacroAssembler *masm, Register weak_handle,
415                                                                     Register obj, Register tmp, Label& slow_path) {
416   assert_different_registers(weak_handle, tmp, noreg);
417   assert_different_registers(obj, tmp, noreg);
418 
419 
420   Label done;
421 
422   // Peek weak handle using the standard implementation.
423   BarrierSetAssembler::try_peek_weak_handle_in_nmethod(masm, weak_handle, obj, tmp, slow_path);
424 
425   // Check if the reference is null, and if it is, take the fast path.
426   __ beqz(obj, done);
427 
428   Address gc_state(xthread, ShenandoahThreadLocalData::gc_state_offset());
429   __ lbu(tmp, gc_state);
430 
431   // Check if the heap is under weak-reference/roots processing, in
432   // which case we need to take the slow path.
433   __ test_bit(tmp, tmp, ShenandoahHeap::WEAK_ROOTS_BITPOS);
434   __ bnez(tmp, slow_path);
435   __ bind(done);
436 }
437 
438 void ShenandoahBarrierSetAssembler::check_oop(MacroAssembler* masm, Register obj, Register tmp1, Register tmp2, Label& L_error) {
439   // Check if the oop is in the right area of memory
440   __ mv(tmp2, (intptr_t) Universe::verify_oop_mask());
441   __ andr(tmp1, obj, tmp2);
442   __ mv(tmp2, (intptr_t) Universe::verify_oop_bits());
443 
444   // Compare tmp1 and tmp2.
445   __ bne(tmp1, tmp2, L_error);
446 
447   // This routine is sometimes called before applying GC barriers.
448   // With +COH, loading the klass may end up loading forwarding pointer instead.
449   Label L_skip;
450   if (UseCompactObjectHeaders) {
451     Address gc_state(xthread, ShenandoahThreadLocalData::gc_state_offset());
452     __ lbu(tmp1, gc_state);
453     __ test_bit(tmp1, tmp1, ShenandoahHeap::HAS_FORWARDED_BITPOS);
454     __ bnez(tmp1, L_skip);
455   }
456 
457   // Make sure klass is 'reasonable', which is not zero.
458   __ load_narrow_klass(tmp1, obj);
459   __ beqz(tmp1, L_error);
460 
461   __ bind(L_skip);
462 }
463 
464 void ShenandoahBarrierSetAssembler::gen_write_ref_array_post_barrier(MacroAssembler* masm, DecoratorSet decorators,
465                                                                      Register start, Register count, Register tmp) {
466   assert(ShenandoahCardBarrier, "Did you mean to enable ShenandoahCardBarrier?");
467 
468   Label L_loop, L_done;
469   const Register end = count;
470 
471   // Zero count? Nothing to do.
472   __ beqz(count, L_done);
473 
474   // end = start + count << LogBytesPerHeapOop
475   // last element address to make inclusive
476   __ shadd(end, count, start, tmp, LogBytesPerHeapOop);
477   __ subi(end, end, BytesPerHeapOop);
478   __ srli(start, start, CardTable::card_shift());
479   __ srli(end, end, CardTable::card_shift());
480 
481   // number of bytes to copy
482   __ sub(count, end, start);
483 
484   Address curr_ct_holder_addr(xthread, in_bytes(ShenandoahThreadLocalData::card_table_offset()));
485   __ ld(tmp, curr_ct_holder_addr);
486   __ add(start, start, tmp);
487 
488   __ bind(L_loop);
489   __ add(tmp, start, count);
490   __ sb(zr, Address(tmp));
491   __ subi(count, count, 1);
492   __ bgez(count, L_loop);
493   __ bind(L_done);
494 }
495 
496 #undef __
497 
498 address ShenandoahBarrierSetAssembler::parse_jump_address(address pc) {
499   NativeInstruction* ni = nativeInstruction_at(pc);
500   assert(ni->is_jump(), "Must be a jump");
501   NativeJump* jmp = nativeJump_at(pc);
502   return jmp->jump_destination();
503 }
504 
505 static uint32_t encode_patchable_nop() {
506   return 0x00000013;
507 }
508 
509 static uint32_t encode_patchable_jump(address pc, address target_pc) {
510   int32_t disp = checked_cast<int32_t>((intptr_t)target_pc - (intptr_t)pc);
511   return Assembler::encode_jal(x0, disp);
512 }
513 
514 void ShenandoahBarrierSetAssembler::insert_patchable_nop(address pc) {
515   *((uint32_t*)pc) = encode_patchable_nop();
516 }
517 
518 void ShenandoahBarrierSetAssembler::insert_patchable_jump(address pc, address target_pc) {
519   *((uint32_t*)pc) = encode_patchable_jump(pc, target_pc);
520 }
521 
522 bool ShenandoahBarrierSetAssembler::is_patchable_nop(address pc) {
523   return *((uint32_t*)pc) == encode_patchable_nop();
524 }
525 
526 bool ShenandoahBarrierSetAssembler::is_patchable_jump(address pc, address target_pc) {
527   return *((uint32_t*)pc) == encode_patchable_jump(pc, target_pc);
528 }
529 
530 #ifdef COMPILER1
531 
532 #define __ ce->masm()->
533 
534 void ShenandoahBarrierSetAssembler::keepalive_barrier_c1_stub(LIR_Assembler* ce, ShenandoahKeepaliveBarrierStub* stub) {
535   __ bind(*stub->entry());
536 
537   ShenandoahBarrierSetC1* bs = (ShenandoahBarrierSetC1*)BarrierSet::barrier_set()->barrier_set_c1();
538 
539   Register obj = stub->obj()->as_register();
540 
541   if (stub->do_load()) {
542     ce->mem2reg(stub->addr(), stub->obj(), T_OBJECT, lir_patch_none, nullptr, false /* wide */);
543   }
544   __ beqz(obj, *stub->continuation(), /* is_far */ true);
545 
546   ce->store_parameter(obj, 0);
547   __ far_call(RuntimeAddress(bs->keepalive_barrier_stub()));
548   __ j(*stub->continuation());
549 }
550 
551 void ShenandoahBarrierSetAssembler::load_reference_barrier_c1_stub(LIR_Assembler* ce, ShenandoahLoadReferenceBarrierStub* stub) {
552   __ bind(*stub->entry());
553 
554   ShenandoahBarrierSetC1* bs = (ShenandoahBarrierSetC1*) BarrierSet::barrier_set()->barrier_set_c1();
555 
556   Register obj = stub->obj()->as_register();
557   Register addr = stub->addr()->as_pointer_register();
558   Register slow_result = stub->slow_result()->as_register();
559   assert_different_registers(obj, addr, slow_result);
560   assert(slow_result == x10, "C1 must know about our slow call result register");
561 
562   ce->store_parameter(obj, 0);
563   ce->store_parameter(addr, 1);
564   __ far_call(RuntimeAddress(bs->load_reference_barrier_stub(stub->decorators())));
565   if (obj != slow_result) {
566     __ mv(obj, slow_result);
567   }
568 
569   __ j(*stub->continuation());
570 }
571 
572 #undef __
573 
574 #define __ sasm->
575 
576 void ShenandoahBarrierSetAssembler::keepalive_barrier_c1_runtime_stub(StubAssembler* sasm) {
577   __ prologue("shenandoah_keepalive_barrier", false);
578   const Register tmp_obj = x10;
579   const Register tmp1 = x11;
580   const Register tmp2 = x12;
581   __ push_reg(RegSet::of(tmp1, tmp2, tmp_obj), sp);
582   __ load_parameter(0, tmp_obj);
583   satb_barrier(sasm, noreg, tmp_obj, xthread, tmp1, tmp2);
584   __ pop_reg(RegSet::of(tmp1, tmp2, tmp_obj), sp);
585   __ epilogue();
586 }
587 
588 void ShenandoahBarrierSetAssembler::load_reference_barrier_c1_runtime_stub(StubAssembler* sasm, DecoratorSet decorators) {
589   __ prologue("shenandoah_load_reference_barrier", false);
590   const Register tmp_obj = x10;
591   const Register tmp_addr = x11;
592   __ push_reg(RegSet::of(tmp_addr), sp);
593   __ load_parameter(0, tmp_obj);
594   __ load_parameter(1, tmp_addr);
595   load_reference_barrier(sasm, tmp_obj, Address(tmp_addr, 0), decorators);
596   __ pop_reg(RegSet::of(tmp_addr), sp);
597   __ epilogue();
598 }
599 
600 #undef __
601 
602 #endif // COMPILER1
603 
604 #ifdef COMPILER2
605 
606 #undef __
607 #define __ masm->
608 
609 void ShenandoahBarrierSetAssembler::load_c2(const MachNode* node, MacroAssembler* masm, Register dst, Address src, Register tmp1, Register tmp2, bool is_narrow) {
610   // Do the actual load. This load is the candidate for implicit null check, and MUST come first.
611   if (is_narrow) {
612     __ lwu(dst, src);
613   } else {
614     __ ld(dst, src);
615   }
616 
617   ShenandoahBarrierStubC2::load_post(masm, node, dst, src, tmp1, tmp2, is_narrow);
618 }
619 
620 void ShenandoahBarrierSetAssembler::store_c2(const MachNode* node, MacroAssembler* masm, Address dst, bool dst_narrow,
621     Register src, bool src_narrow, Register tmp1, Register tmp2, Register tmp3) {
622 
623   ShenandoahBarrierStubC2::store_pre(masm, node, dst, tmp1, tmp2, tmp3, dst_narrow);
624 
625   // Do the actual store
626   if (dst_narrow) {
627     if (!src_narrow) {
628       // Need to encode into tmp, because we cannot clobber src.
629       assert(tmp1 != noreg, "need temp register");
630       if ((node->barrier_data() & ShenandoahBitNotNull) == 0) {
631         __ encode_heap_oop(tmp1, src);
632       } else {
633         __ encode_heap_oop_not_null(tmp1, src);
634       }
635       src = tmp1;
636     }
637     __ sw(src, dst);
638   } else {
639     __ sd(src, dst);
640   }
641 
642   ShenandoahBarrierStubC2::store_post(masm, node, dst, tmp2, tmp3);
643 }
644 
645 void ShenandoahBarrierSetAssembler::compare_and_set_c2(const MachNode* node, MacroAssembler* masm, Register res, Register addr,
646     Register oldval, Register newval, Register tmp1, Register tmp2, Register tmp3, bool exchange, bool narrow, bool is_acquire) {
647   const Assembler::Aqrl acquire = is_acquire ? Assembler::aq : Assembler::relaxed;
648   const Assembler::Aqrl release = Assembler::rl;
649   const Assembler::operand_size size = narrow ? Assembler::uint32 : Assembler::int64;
650 
651   ShenandoahBarrierStubC2::load_store_pre(masm, node, Address(addr), tmp1, tmp2, tmp3, narrow);
652 
653   // CAS!
654   __ cmpxchg(addr, oldval, newval, size, acquire, release, /* result */ res, !exchange /* result_as_bool */);
655 
656   ShenandoahBarrierStubC2::load_store_post(masm, node, Address(addr, 0), tmp2, tmp3);
657 }
658 
659 void ShenandoahBarrierSetAssembler::get_and_set_c2(const MachNode* node, MacroAssembler* masm, Register preval,
660     Register newval, Register addr, Register tmp1, Register tmp2, Register tmp3, bool is_acquire) {
661   const bool is_narrow = node->bottom_type()->isa_narrowoop();
662 
663   ShenandoahBarrierStubC2::load_store_pre(masm, node, Address(addr, 0), tmp1, tmp2, tmp3, is_narrow);
664 
665   if (is_narrow) {
666     if (is_acquire) {
667       __ atomic_xchgalwu(preval, newval, addr);
668     } else {
669       __ atomic_xchgwu(preval, newval, addr);
670     }
671   } else {
672     if (is_acquire) {
673       __ atomic_xchgal(preval, newval, addr);
674     } else {
675       __ atomic_xchg(preval, newval, addr);
676     }
677   }
678 
679   ShenandoahBarrierStubC2::load_store_post(masm, node, Address(addr, 0), tmp2, tmp3);
680 }
681 
682 #undef __
683 #define __ masm.
684 
685 void ShenandoahBarrierStubC2::cardtable(MacroAssembler& masm, Address address, Register tmp1, Register tmp2) {
686   assert(CardTable::dirty_card_val() == 0, "must be");
687   Assembler::InlineSkippedInstructionsCounter skip_counter(&masm);
688 
689   // tmp1 = card table base (holder)
690   Address curr_ct_holder_addr(xthread, in_bytes(ShenandoahThreadLocalData::card_table_offset()));
691   __ ld(tmp1, curr_ct_holder_addr);
692 
693   // tmp1 = effective address
694   __ la(tmp2, address);
695 
696   // tmp2 = &card_table[ addr >> CardTable::card_shift() ] ; card index
697   __ srli(tmp2, tmp2, CardTable::card_shift());
698   __ add(tmp2, tmp2, tmp1);
699 
700   if (UseCondCardMark) {
701     Label L_already_dirty;
702     __ lbu(tmp1, Address(tmp2));
703     __ beqz(tmp1, L_already_dirty);
704     __ sb(zr, Address(tmp2));
705     __ bind(L_already_dirty);
706   } else {
707     __ sb(zr, Address(tmp2));
708   }
709 }
710 
711 void ShenandoahBarrierStubC2::patchable_jump(MacroAssembler& masm, const char gc_state, bool jump_when_state, Label* L_target) {
712   PhaseOutput* const output = Compile::current()->output();
713   if (output->in_scratch_emit_size()) {
714     // Avoid binding L_target in scratch emits.
715     // We know the patched check is exactly one incompressible instruction long.
716     Assembler::IncompressibleScope scope(&masm);
717     __ nop();
718     return;
719   }
720 
721   // Emit the unconditional branch in the first version of the method.
722   // Let the rest of runtime figure out how to manage it.
723   __ relocate(patchable_barrier_Relocation::spec(ShenandoahNMethod::encode_to_reloc(gc_state, jump_when_state)));
724   __ j(*L_target);
725 }
726 
727 void ShenandoahBarrierStubC2::enter_if_gc_state(MacroAssembler& masm, const char test_state) {
728   Assembler::InlineSkippedInstructionsCounter skip_counter(&masm);
729   patchable_jump_if_gc_state(masm, test_state, entry());
730   __ bind(*continuation());
731 }
732 
733 void ShenandoahBarrierStubC2::emit_code(MacroAssembler& masm) {
734   Assembler::InlineSkippedInstructionsCounter skip_counter(&masm);
735   assert(_needs_keep_alive_barrier || _needs_load_ref_barrier, "Why are you here?");
736 
737   __ bind(*entry());
738 
739   // If we need to load ourselves, do it here.
740   if (_do_load) {
741     if (_narrow) {
742       __ lwu(_obj, _addr);
743     } else {
744       __ ld(_obj, _addr);
745     }
746   }
747 
748   // If the object is null, there is no point in applying barriers.
749   maybe_far_jump_if_zero(masm, _obj);
750 
751   // We need to make sure that loads done by callers survive across slow-path calls.
752   // For self-loads, we need to care about the case when both KA and LRB are enabled (rare).
753   bool needs_both_barriers = _needs_keep_alive_barrier && _needs_load_ref_barrier;
754   if (!_do_load || needs_both_barriers) {
755     preserve(_obj);
756   }
757 
758   // Go for barriers. Barriers can return straight to continuation, as long
759   // as another barrier is not needed and we can reach the fastpath.
760   if (needs_both_barriers) {
761     keepalive(masm, nullptr);
762     lrb(masm);
763   } else if (_needs_keep_alive_barrier) {
764     keepalive(masm, continuation());
765   } else if (_needs_load_ref_barrier) {
766     lrb(masm);
767   } else {
768     ShouldNotReachHere();
769   }
770 }
771 
772 void ShenandoahBarrierStubC2::maybe_far_jump_if_zero(MacroAssembler& masm, Register reg) {
773   Label L_short_jump;
774   __ bnez(reg, L_short_jump);
775   __ j(*continuation());
776   __ bind(L_short_jump);
777 }
778 
779 void ShenandoahBarrierStubC2::keepalive(MacroAssembler& masm, Label* L_done) {
780   Address index(xthread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset()));
781   Address buffer(xthread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset()));
782   Label L_through, L_slowpath;
783 
784   // If another barrier is enabled as well, do a check for a specific barrier.
785   if (_needs_load_ref_barrier) {
786     assert(L_done == nullptr, "Should be");
787     char state_to_check = ShenandoahHeap::MARKING;
788     patchable_jump_if_not_gc_state(masm, state_to_check, &L_through);
789   }
790 
791   // Fast-path: put object into buffer.
792   // If buffer is already full, go slow.
793   __ ld(_tmp1, index);
794   __ beqz(_tmp1, L_slowpath);
795   __ subi(_tmp1, _tmp1, wordSize);
796   __ sd(_tmp1, index);
797   __ ld(_tmp2, buffer);
798 
799   // Store the object in queue.
800   // If object is narrow, we need to decode it before inserting.
801   __ add(_tmp1, _tmp1, _tmp2);
802   if (_narrow) {
803     __ decode_heap_oop_not_null(_tmp2, _obj);
804     __ sd(_tmp2, Address(_tmp1));
805   } else {
806     __ sd(_obj, Address(_tmp1));
807   }
808 
809   // Fast-path exits here.
810   if (L_done != nullptr) {
811     __ j(*L_done);
812   } else {
813     __ j(L_through);
814   }
815 
816   // Slow-path: call runtime to handle.
817   __ bind(L_slowpath);
818 
819   {
820     SaveLiveRegisters slr(&masm, this);
821 
822     // Go to runtime and handle the rest there.
823     __ mv(c_rarg0, _obj);
824     __ la(ra, RuntimeAddress(keepalive_runtime_entry_addr()));
825     __ jalr(ra);
826   }
827   if (L_done != nullptr) {
828     __ j(*L_done);
829   } else {
830     __ bind(L_through);
831   }
832 }
833 
834 void ShenandoahBarrierStubC2::lrb(MacroAssembler& masm) {
835   Label L_slow;
836 
837   // If another barrier is enabled as well, do a check for a specific barrier.
838   if (_needs_keep_alive_barrier) {
839     char state_to_check = ShenandoahHeap::HAS_FORWARDED | (_needs_load_ref_weak_barrier ? ShenandoahHeap::WEAK_ROOTS : 0);
840     patchable_jump_if_not_gc_state(masm, state_to_check, continuation());
841   }
842 
843   // If weak references are being processed, weak/phantom loads need to go slow,
844   // regardless of their cset status.
845   if (_needs_load_ref_weak_barrier) {
846     char state_to_check = ShenandoahHeap::WEAK_ROOTS;
847     patchable_jump_if_gc_state(masm, state_to_check, &L_slow);
848   }
849 
850   // Cset-check. Fall-through to slow if in collection set.
851   if (_narrow) {
852     __ decode_heap_oop_not_null(_tmp2, _obj);
853   } else {
854     __ mv(_tmp2, _obj);
855   }
856 
857   __ mv(_tmp1, ShenandoahHeap::in_cset_fast_test_addr());
858   __ srli(_tmp2, _tmp2, ShenandoahHeapRegion::region_size_bytes_shift_jint());
859   __ add(_tmp1, _tmp1, _tmp2);
860   __ lbu(_tmp1, Address(_tmp1, 0));
861   maybe_far_jump_if_zero(masm, _tmp1);
862 
863   // Slow path
864   __ bind(L_slow);
865 
866   // Obj is the result, need to temporarily stop preserving it.
867   bool is_obj_preserved = is_preserved(_obj);
868   if (is_obj_preserved) {
869     dont_preserve(_obj);
870   }
871   {
872     SaveLiveRegisters slr(&masm, this);
873 
874     // Shuffle in the arguments. The end result should be:
875     //   c_rarg0 <- obj
876     //   c_rarg1 <- lea(addr)
877     if (c_rarg0 == _obj) {
878       __ la(c_rarg1, _addr);
879     } else if (c_rarg1 == _obj) {
880       __ mv(_tmp1, c_rarg1);
881       __ la(c_rarg1, _addr);
882       __ mv(c_rarg0, _tmp1);
883     } else {
884       assert_different_registers(c_rarg1, _obj);
885       __ la(c_rarg1, _addr);
886       __ mv(c_rarg0, _obj);
887     }
888 
889     // Go to runtime and handle the rest there.
890     __ la(ra, RuntimeAddress(lrb_runtime_entry_addr()));
891     __ jalr(ra);
892 
893     // Save the result where needed. Narrow entries return narrowOop (32 bits)
894     // we need to zero the upper 32 bits of x10.
895     if (_narrow) {
896       __ zext_w(_obj, x10);
897     } else {
898       __ mv(_obj, x10);
899     }
900   }
901   if (is_obj_preserved) {
902     preserve(_obj);
903   }
904 
905   __ j(*continuation());
906 }
907 
908 int ShenandoahBarrierStubC2::available_gp_registers() {
909   Unimplemented(); // Not used
910   return 0;
911 }
912 
913 bool ShenandoahBarrierStubC2::is_special_register(Register r) {
914   Unimplemented(); // Not used
915   return true;
916 }
917 
918 void ShenandoahBarrierStubC2::post_init() {
919   // Do nothing.
920 }
921 
922 #endif // COMPILER2