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, Register tmp1, Register tmp2) {
336   assert(ShenandoahCardBarrier, "Should have been checked by caller");
337   assert(CardTable::dirty_card_val() == 0, "must be");
338   assert_different_registers(obj, tmp1, tmp2);
339 
340   __ srli(obj, obj, CardTable::card_shift());
341 
342   Address curr_ct_holder_addr(xthread, in_bytes(ShenandoahThreadLocalData::card_table_offset()));
343   __ ld(tmp1, curr_ct_holder_addr);
344   __ add(tmp1, obj, tmp1);
345 
346   if (UseCondCardMark) {
347     Label L_already_dirty;
348     __ lbu(tmp2, Address(tmp1));
349     __ beqz(tmp2, L_already_dirty);
350     __ sb(zr, Address(tmp1));
351     __ bind(L_already_dirty);
352   } else {
353     __ sb(zr, Address(tmp1));
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, tmp1, tmp2);
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   assert(nativeInstruction_at(pc)->is_nop(), "Sanity");
517 }
518 
519 void ShenandoahBarrierSetAssembler::insert_patchable_jump(address pc, address target_pc) {
520   *((uint32_t*)pc) = encode_patchable_jump(pc, target_pc);
521 }
522 
523 bool ShenandoahBarrierSetAssembler::is_patchable_nop(address pc) {
524   return *((uint32_t*)pc) == encode_patchable_nop();
525 }
526 
527 bool ShenandoahBarrierSetAssembler::is_patchable_jump(address pc, address target_pc) {
528   return *((uint32_t*)pc) == encode_patchable_jump(pc, target_pc);
529 }
530 
531 #ifdef COMPILER1
532 
533 #define __ ce->masm()->
534 
535 void ShenandoahBarrierSetAssembler::keepalive_barrier_c1_stub(LIR_Assembler* ce, ShenandoahKeepaliveBarrierStub* stub) {
536   __ bind(*stub->entry());
537 
538   ShenandoahBarrierSetC1* bs = (ShenandoahBarrierSetC1*)BarrierSet::barrier_set()->barrier_set_c1();
539 
540   Register obj = stub->obj()->as_register();
541 
542   if (stub->do_load()) {
543     ce->mem2reg(stub->addr(), stub->obj(), T_OBJECT, lir_patch_none, nullptr, false /* wide */);
544   }
545   __ beqz(obj, *stub->continuation(), /* is_far */ true);
546 
547   ce->store_parameter(obj, 0);
548   __ far_call(RuntimeAddress(bs->keepalive_barrier_stub()));
549   __ j(*stub->continuation());
550 }
551 
552 void ShenandoahBarrierSetAssembler::load_reference_barrier_c1_stub(LIR_Assembler* ce, ShenandoahLoadReferenceBarrierStub* stub) {
553   __ bind(*stub->entry());
554 
555   ShenandoahBarrierSetC1* bs = (ShenandoahBarrierSetC1*) BarrierSet::barrier_set()->barrier_set_c1();
556 
557   Register obj = stub->obj()->as_register();
558   Register addr = stub->addr()->as_pointer_register();
559   Register slow_result = stub->slow_result()->as_register();
560   assert_different_registers(obj, addr, slow_result);
561   assert(slow_result == x10, "C1 must know about our slow call result register");
562 
563   ce->store_parameter(obj, 0);
564   ce->store_parameter(addr, 1);
565   __ far_call(RuntimeAddress(bs->load_reference_barrier_stub(stub->decorators())));
566   if (obj != slow_result) {
567     __ mv(obj, slow_result);
568   }
569 
570   __ j(*stub->continuation());
571 }
572 
573 #undef __
574 
575 #define __ sasm->
576 
577 void ShenandoahBarrierSetAssembler::keepalive_barrier_c1_runtime_stub(StubAssembler* sasm) {
578   __ prologue("shenandoah_keepalive_barrier", false);
579   const Register tmp_obj = x10;
580   const Register tmp1 = x11;
581   const Register tmp2 = x12;
582   __ push_reg(RegSet::of(tmp1, tmp2, tmp_obj), sp);
583   __ load_parameter(0, tmp_obj);
584   satb_barrier(sasm, noreg, tmp_obj, xthread, tmp1, tmp2);
585   __ pop_reg(RegSet::of(tmp1, tmp2, tmp_obj), sp);
586   __ epilogue();
587 }
588 
589 void ShenandoahBarrierSetAssembler::load_reference_barrier_c1_runtime_stub(StubAssembler* sasm, DecoratorSet decorators) {
590   __ prologue("shenandoah_load_reference_barrier", false);
591   const Register tmp_obj = x10;
592   const Register tmp_addr = x11;
593   __ push_reg(RegSet::of(tmp_addr), sp);
594   __ load_parameter(0, tmp_obj);
595   __ load_parameter(1, tmp_addr);
596   load_reference_barrier(sasm, tmp_obj, Address(tmp_addr, 0), decorators);
597   __ pop_reg(RegSet::of(tmp_addr), sp);
598   __ epilogue();
599 }
600 
601 #undef __
602 
603 #endif // COMPILER1
604 
605 #ifdef COMPILER2
606 
607 #undef __
608 #define __ masm->
609 
610 void ShenandoahBarrierSetAssembler::load_c2(const MachNode* node, MacroAssembler* masm, Register dst, Address src, Register tmp1, Register tmp2, bool is_narrow) {
611   // Do the actual load. This load is the candidate for implicit null check, and MUST come first.
612   if (is_narrow) {
613     __ lwu(dst, src);
614   } else {
615     __ ld(dst, src);
616   }
617 
618   ShenandoahBarrierStubC2::load_post(masm, node, dst, src, tmp1, tmp2, is_narrow);
619 }
620 
621 void ShenandoahBarrierSetAssembler::store_c2(const MachNode* node, MacroAssembler* masm, Address dst, bool dst_narrow,
622     Register src, bool src_narrow, Register tmp1, Register tmp2, Register tmp3) {
623 
624   ShenandoahBarrierStubC2::store_pre(masm, node, dst, tmp1, tmp2, tmp3, dst_narrow);
625 
626   // Do the actual store
627   if (dst_narrow) {
628     if (!src_narrow) {
629       // Need to encode into tmp, because we cannot clobber src.
630       assert(tmp1 != noreg, "need temp register");
631       if ((node->barrier_data() & ShenandoahBitNotNull) == 0) {
632         __ encode_heap_oop(tmp1, src);
633       } else {
634         __ encode_heap_oop_not_null(tmp1, src);
635       }
636       src = tmp1;
637     }
638     __ sw(src, dst);
639   } else {
640     __ sd(src, dst);
641   }
642 
643   ShenandoahBarrierStubC2::store_post(masm, node, dst, tmp2, tmp3);
644 }
645 
646 void ShenandoahBarrierSetAssembler::compare_and_set_c2(const MachNode* node, MacroAssembler* masm, Register res, Register addr,
647     Register oldval, Register newval, Register tmp1, Register tmp2, Register tmp3, bool exchange, bool narrow, bool is_acquire) {
648   const Assembler::Aqrl acquire = is_acquire ? Assembler::aq : Assembler::relaxed;
649   const Assembler::Aqrl release = Assembler::rl;
650   const Assembler::operand_size size = narrow ? Assembler::uint32 : Assembler::int64;
651 
652   ShenandoahBarrierStubC2::load_store_pre(masm, node, Address(addr), tmp1, tmp2, tmp3, narrow);
653 
654   // CAS!
655   __ cmpxchg(addr, oldval, newval, size, acquire, release, /* result */ res, !exchange /* result_as_bool */);
656 
657   ShenandoahBarrierStubC2::load_store_post(masm, node, Address(addr, 0), tmp2, tmp3);
658 }
659 
660 void ShenandoahBarrierSetAssembler::get_and_set_c2(const MachNode* node, MacroAssembler* masm, Register preval,
661     Register newval, Register addr, Register tmp1, Register tmp2, Register tmp3, bool is_acquire) {
662   const bool is_narrow = node->bottom_type()->isa_narrowoop();
663 
664   ShenandoahBarrierStubC2::load_store_pre(masm, node, Address(addr, 0), tmp1, tmp2, tmp3, is_narrow);
665 
666   if (is_narrow) {
667     if (is_acquire) {
668       __ atomic_xchgalwu(preval, newval, addr);
669     } else {
670       __ atomic_xchgwu(preval, newval, addr);
671     }
672   } else {
673     if (is_acquire) {
674       __ atomic_xchgal(preval, newval, addr);
675     } else {
676       __ atomic_xchg(preval, newval, addr);
677     }
678   }
679 
680   ShenandoahBarrierStubC2::load_store_post(masm, node, Address(addr, 0), tmp2, tmp3);
681 }
682 
683 #undef __
684 #define __ masm.
685 
686 void ShenandoahBarrierStubC2::cardtable(MacroAssembler& masm, Address address, Register tmp1, Register tmp2) {
687   assert(CardTable::dirty_card_val() == 0, "must be");
688   Assembler::InlineSkippedInstructionsCounter skip_counter(&masm);
689 
690   // tmp1 = card table base (holder)
691   Address curr_ct_holder_addr(xthread, in_bytes(ShenandoahThreadLocalData::card_table_offset()));
692   __ ld(tmp1, curr_ct_holder_addr);
693 
694   // tmp1 = effective address
695   __ la(tmp2, address);
696 
697   // tmp2 = &card_table[ addr >> CardTable::card_shift() ] ; card index
698   __ srli(tmp2, tmp2, CardTable::card_shift());
699   __ add(tmp2, tmp2, tmp1);
700 
701   if (UseCondCardMark) {
702     Label L_already_dirty;
703     __ lbu(tmp1, Address(tmp2));
704     __ beqz(tmp1, L_already_dirty);
705     __ sb(zr, Address(tmp2));
706     __ bind(L_already_dirty);
707   } else {
708     __ sb(zr, Address(tmp2));
709   }
710 }
711 
712 void ShenandoahBarrierStubC2::patchable_jump(MacroAssembler& masm, const char gc_state, bool jump_when_state, Label* L_target) {
713   PhaseOutput* const output = Compile::current()->output();
714   if (output->in_scratch_emit_size()) {
715     // Avoid binding L_target in scratch emits.
716     // We know the patched check is exactly one incompressible instruction long.
717     Assembler::IncompressibleScope scope(&masm);
718     __ nop();
719     return;
720   }
721 
722   // Emit the unconditional branch in the first version of the method.
723   // Let the rest of runtime figure out how to manage it.
724   __ relocate(patchable_barrier_Relocation::spec(ShenandoahNMethod::encode_to_reloc(gc_state, jump_when_state)));
725   __ j(*L_target);
726 }
727 
728 void ShenandoahBarrierStubC2::enter_if_gc_state(MacroAssembler& masm, const char test_state) {
729   Assembler::InlineSkippedInstructionsCounter skip_counter(&masm);
730   patchable_jump_if_gc_state(masm, test_state, entry());
731   __ bind(*continuation());
732 }
733 
734 void ShenandoahBarrierStubC2::emit_code(MacroAssembler& masm) {
735   Assembler::InlineSkippedInstructionsCounter skip_counter(&masm);
736   assert(_needs_keep_alive_barrier || _needs_load_ref_barrier, "Why are you here?");
737 
738   __ bind(*entry());
739 
740   // If we need to load ourselves, do it here.
741   if (_do_load) {
742     if (_narrow) {
743       __ lwu(_obj, _addr);
744     } else {
745       __ ld(_obj, _addr);
746     }
747   }
748 
749   // If the object is null, there is no point in applying barriers.
750   maybe_far_jump_if_zero(masm, _obj);
751 
752   // We need to make sure that loads done by callers survive across slow-path calls.
753   // For self-loads, we need to care about the case when both KA and LRB are enabled (rare).
754   bool needs_both_barriers = _needs_keep_alive_barrier && _needs_load_ref_barrier;
755   if (!_do_load || needs_both_barriers) {
756     preserve(_obj);
757   }
758 
759   // Go for barriers. Barriers can return straight to continuation, as long
760   // as another barrier is not needed and we can reach the fastpath.
761   if (needs_both_barriers) {
762     keepalive(masm, nullptr);
763     lrb(masm);
764   } else if (_needs_keep_alive_barrier) {
765     keepalive(masm, continuation());
766   } else if (_needs_load_ref_barrier) {
767     lrb(masm);
768   } else {
769     ShouldNotReachHere();
770   }
771 }
772 
773 void ShenandoahBarrierStubC2::maybe_far_jump_if_zero(MacroAssembler& masm, Register reg) {
774   Label L_short_jump;
775   __ bnez(reg, L_short_jump);
776   __ j(*continuation());
777   __ bind(L_short_jump);
778 }
779 
780 void ShenandoahBarrierStubC2::keepalive(MacroAssembler& masm, Label* L_done) {
781   Address index(xthread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset()));
782   Address buffer(xthread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset()));
783   Label L_through, L_slowpath;
784 
785   // If another barrier is enabled as well, do a check for a specific barrier.
786   if (_needs_load_ref_barrier) {
787     assert(L_done == nullptr, "Should be");
788     char state_to_check = ShenandoahHeap::MARKING;
789     patchable_jump_if_not_gc_state(masm, state_to_check, &L_through);
790   }
791 
792   // Fast-path: put object into buffer.
793   // If buffer is already full, go slow.
794   __ ld(_tmp1, index);
795   __ beqz(_tmp1, L_slowpath);
796   __ subi(_tmp1, _tmp1, wordSize);
797   __ sd(_tmp1, index);
798   __ ld(_tmp2, buffer);
799 
800   // Store the object in queue.
801   // If object is narrow, we need to decode it before inserting.
802   __ add(_tmp1, _tmp1, _tmp2);
803   if (_narrow) {
804     __ decode_heap_oop_not_null(_tmp2, _obj);
805     __ sd(_tmp2, Address(_tmp1));
806   } else {
807     __ sd(_obj, Address(_tmp1));
808   }
809 
810   // Fast-path exits here.
811   if (L_done != nullptr) {
812     __ j(*L_done);
813   } else {
814     __ j(L_through);
815   }
816 
817   // Slow-path: call runtime to handle.
818   __ bind(L_slowpath);
819 
820   {
821     SaveLiveRegisters slr(&masm, this);
822 
823     // Go to runtime and handle the rest there.
824     __ mv(c_rarg0, _obj);
825     __ la(ra, RuntimeAddress(keepalive_runtime_entry_addr()));
826     __ jalr(ra);
827   }
828   if (L_done != nullptr) {
829     __ j(*L_done);
830   } else {
831     __ bind(L_through);
832   }
833 }
834 
835 void ShenandoahBarrierStubC2::lrb(MacroAssembler& masm) {
836   Label L_slow;
837 
838   // If another barrier is enabled as well, do a check for a specific barrier.
839   if (_needs_keep_alive_barrier) {
840     char state_to_check = ShenandoahHeap::HAS_FORWARDED | (_needs_load_ref_weak_barrier ? ShenandoahHeap::WEAK_ROOTS : 0);
841     patchable_jump_if_not_gc_state(masm, state_to_check, continuation());
842   }
843 
844   // If weak references are being processed, weak/phantom loads need to go slow,
845   // regardless of their cset status.
846   if (_needs_load_ref_weak_barrier) {
847     char state_to_check = ShenandoahHeap::WEAK_ROOTS;
848     patchable_jump_if_gc_state(masm, state_to_check, &L_slow);
849   }
850 
851   // Cset-check. Fall-through to slow if in collection set.
852   if (_narrow) {
853     __ decode_heap_oop_not_null(_tmp2, _obj);
854   } else {
855     __ mv(_tmp2, _obj);
856   }
857 
858   __ mv(_tmp1, ShenandoahHeap::in_cset_fast_test_addr());
859   __ srli(_tmp2, _tmp2, ShenandoahHeapRegion::region_size_bytes_shift_jint());
860   __ add(_tmp1, _tmp1, _tmp2);
861   __ lbu(_tmp1, Address(_tmp1, 0));
862   maybe_far_jump_if_zero(masm, _tmp1);
863 
864   // Slow path
865   __ bind(L_slow);
866 
867   // Obj is the result, need to temporarily stop preserving it.
868   bool is_obj_preserved = is_preserved(_obj);
869   if (is_obj_preserved) {
870     dont_preserve(_obj);
871   }
872   {
873     SaveLiveRegisters slr(&masm, this);
874 
875     // Shuffle in the arguments. The end result should be:
876     //   c_rarg0 <- obj
877     //   c_rarg1 <- lea(addr)
878     if (c_rarg0 == _obj) {
879       __ la(c_rarg1, _addr);
880     } else if (c_rarg1 == _obj) {
881       __ mv(_tmp1, c_rarg1);
882       __ la(c_rarg1, _addr);
883       __ mv(c_rarg0, _tmp1);
884     } else {
885       assert_different_registers(c_rarg1, _obj);
886       __ la(c_rarg1, _addr);
887       __ mv(c_rarg0, _obj);
888     }
889 
890     // Go to runtime and handle the rest there.
891     __ la(ra, RuntimeAddress(lrb_runtime_entry_addr()));
892     __ jalr(ra);
893 
894     // Save the result where needed. Narrow entries return narrowOop (32 bits)
895     // we need to zero the upper 32 bits of x10.
896     if (_narrow) {
897       __ zext_w(_obj, x10);
898     } else {
899       __ mv(_obj, x10);
900     }
901   }
902   if (is_obj_preserved) {
903     preserve(_obj);
904   }
905 
906   __ j(*continuation());
907 }
908 
909 int ShenandoahBarrierStubC2::available_gp_registers() {
910   Unimplemented(); // Not used
911   return 0;
912 }
913 
914 bool ShenandoahBarrierStubC2::is_special_register(Register r) {
915   Unimplemented(); // Not used
916   return true;
917 }
918 
919 void ShenandoahBarrierStubC2::post_init() {
920   // Do nothing.
921 }
922 
923 #endif // COMPILER2