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