1 /*
  2  * Copyright (c) 2018, 2022, Red Hat, Inc. All rights reserved.
  3  * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
  4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  5  *
  6  * This code is free software; you can redistribute it and/or modify it
  7  * under the terms of the GNU General Public License version 2 only, as
  8  * published by the Free Software Foundation.
  9  *
 10  * This code is distributed in the hope that it will be useful, but WITHOUT
 11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 13  * version 2 for more details (a copy is included in the LICENSE file that
 14  * accompanied this code).
 15  *
 16  * You should have received a copy of the GNU General Public License version
 17  * 2 along with this work; if not, write to the Free Software Foundation,
 18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 19  *
 20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 21  * or visit www.oracle.com if you need additional information or have any
 22  * questions.
 23  *
 24  */
 25 
 26 #include "precompiled.hpp"
 27 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
 28 #include "gc/shenandoah/shenandoahBarrierSetAssembler.hpp"
 29 #include "gc/shenandoah/shenandoahForwarding.hpp"
 30 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
 31 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
 32 #include "gc/shenandoah/shenandoahRuntime.hpp"
 33 #include "gc/shenandoah/shenandoahThreadLocalData.hpp"
 34 #include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
 35 #include "gc/shenandoah/mode/shenandoahMode.hpp"
 36 #include "interpreter/interpreter.hpp"
 37 #include "interpreter/interp_masm.hpp"
 38 #include "runtime/javaThread.hpp"
 39 #include "runtime/sharedRuntime.hpp"
 40 #ifdef COMPILER1
 41 #include "c1/c1_LIRAssembler.hpp"
 42 #include "c1/c1_MacroAssembler.hpp"
 43 #include "gc/shenandoah/c1/shenandoahBarrierSetC1.hpp"
 44 #endif
 45 
 46 #define __ masm->
 47 
 48 void ShenandoahBarrierSetAssembler::arraycopy_prologue(MacroAssembler* masm, DecoratorSet decorators, bool is_oop,
 49                                                        Register src, Register dst, Register count, RegSet saved_regs) {
 50   if (is_oop) {
 51     bool dest_uninitialized = (decorators & IS_DEST_UNINITIALIZED) != 0;
 52     if ((ShenandoahSATBBarrier && !dest_uninitialized) || ShenandoahIUBarrier || ShenandoahLoadRefBarrier) {
 53 
 54       Label done;
 55 
 56       // Avoid calling runtime if count == 0
 57       __ cbz(count, done);
 58 
 59       // Is GC active?
 60       Address gc_state(rthread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 61       __ ldrb(rscratch1, gc_state);
 62       if (ShenandoahSATBBarrier && dest_uninitialized) {
 63         __ tbz(rscratch1, ShenandoahHeap::HAS_FORWARDED_BITPOS, done);
 64       } else {
 65         __ mov(rscratch2, ShenandoahHeap::HAS_FORWARDED | ShenandoahHeap::MARKING);
 66         __ tst(rscratch1, rscratch2);
 67         __ br(Assembler::EQ, done);
 68       }
 69 
 70       __ push(saved_regs, sp);
 71       if (UseCompressedOops) {
 72         __ call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::arraycopy_barrier_narrow_oop_entry), src, dst, count);
 73       } else {
 74         __ call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::arraycopy_barrier_oop_entry), src, dst, count);
 75       }
 76       __ pop(saved_regs, sp);
 77       __ bind(done);
 78     }
 79   }
 80 }
 81 
 82 void ShenandoahBarrierSetAssembler::arraycopy_epilogue(MacroAssembler* masm, DecoratorSet decorators, bool is_oop,
 83                                                        Register start, Register count, Register tmp, RegSet saved_regs) {
 84   if (ShenandoahCardBarrier && is_oop) {
 85     gen_write_ref_array_post_barrier(masm, decorators, start, count, tmp, saved_regs);
 86   }
 87 }
 88 
 89 void ShenandoahBarrierSetAssembler::shenandoah_write_barrier_pre(MacroAssembler* masm,
 90                                                                  Register obj,
 91                                                                  Register pre_val,
 92                                                                  Register thread,
 93                                                                  Register tmp,
 94                                                                  bool tosca_live,
 95                                                                  bool expand_call) {
 96   if (ShenandoahSATBBarrier) {
 97     satb_write_barrier_pre(masm, obj, pre_val, thread, tmp, rscratch1, tosca_live, expand_call);
 98   }
 99 }
100 
101 void ShenandoahBarrierSetAssembler::satb_write_barrier_pre(MacroAssembler* masm,
102                                                            Register obj,
103                                                            Register pre_val,
104                                                            Register thread,
105                                                            Register tmp1,
106                                                            Register tmp2,
107                                                            bool tosca_live,
108                                                            bool expand_call) {
109   // If expand_call is true then we expand the call_VM_leaf macro
110   // directly to skip generating the check by
111   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
112 
113   assert(thread == rthread, "must be");
114 
115   Label done;
116   Label runtime;
117 
118   assert_different_registers(obj, pre_val, tmp1, tmp2);
119   assert(pre_val != noreg && tmp1 != noreg && tmp2 != noreg, "expecting a register");
120 
121   Address in_progress(thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_active_offset()));
122   Address index(thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset()));
123   Address buffer(thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset()));
124 
125   // Is marking active?
126   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
127     __ ldrw(tmp1, in_progress);
128   } else {
129     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
130     __ ldrb(tmp1, in_progress);
131   }
132   __ cbzw(tmp1, done);
133 
134   // Do we need to load the previous value?
135   if (obj != noreg) {
136     __ load_heap_oop(pre_val, Address(obj, 0), noreg, noreg, AS_RAW);
137   }
138 
139   // Is the previous value null?
140   __ cbz(pre_val, done);
141 
142   // Can we store original value in the thread's buffer?
143   // Is index == 0?
144   // (The index field is typed as size_t.)
145 
146   __ ldr(tmp1, index);                      // tmp := *index_adr
147   __ cbz(tmp1, runtime);                    // tmp == 0?
148                                         // If yes, goto runtime
149 
150   __ sub(tmp1, tmp1, wordSize);             // tmp := tmp - wordSize
151   __ str(tmp1, index);                      // *index_adr := tmp
152   __ ldr(tmp2, buffer);
153   __ add(tmp1, tmp1, tmp2);                 // tmp := tmp + *buffer_adr
154 
155   // Record the previous value
156   __ str(pre_val, Address(tmp1, 0));
157   __ b(done);
158 
159   __ bind(runtime);
160   // save the live input values
161   RegSet saved = RegSet::of(pre_val);
162   if (tosca_live) saved += RegSet::of(r0);
163   if (obj != noreg) saved += RegSet::of(obj);
164 
165   __ push(saved, sp);
166 
167   // Calling the runtime using the regular call_VM_leaf mechanism generates
168   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
169   // that checks that the *(rfp+frame::interpreter_frame_last_sp) == nullptr.
170   //
171   // If we care generating the pre-barrier without a frame (e.g. in the
172   // intrinsified Reference.get() routine) then rfp might be pointing to
173   // the caller frame and so this check will most likely fail at runtime.
174   //
175   // Expanding the call directly bypasses the generation of the check.
176   // So when we do not have have a full interpreter frame on the stack
177   // expand_call should be passed true.
178 
179   if (expand_call) {
180     assert(pre_val != c_rarg1, "smashed arg");
181     __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_ref_field_pre_entry), pre_val, thread);
182   } else {
183     __ call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_ref_field_pre_entry), pre_val, thread);
184   }
185 
186   __ pop(saved, sp);
187 
188   __ bind(done);
189 }
190 
191 void ShenandoahBarrierSetAssembler::resolve_forward_pointer(MacroAssembler* masm, Register dst, Register tmp) {
192   assert(ShenandoahLoadRefBarrier || ShenandoahCASBarrier, "Should be enabled");
193   Label is_null;
194   __ cbz(dst, is_null);
195   resolve_forward_pointer_not_null(masm, dst, tmp);
196   __ bind(is_null);
197 }
198 
199 // IMPORTANT: This must preserve all registers, even rscratch1 and rscratch2, except those explicitly
200 // passed in.
201 void ShenandoahBarrierSetAssembler::resolve_forward_pointer_not_null(MacroAssembler* masm, Register dst, Register tmp) {
202   assert(ShenandoahLoadRefBarrier || ShenandoahCASBarrier, "Should be enabled");
203   // The below loads the mark word, checks if the lowest two bits are
204   // set, and if so, clear the lowest two bits and copy the result
205   // to dst. Otherwise it leaves dst alone.
206   // Implementing this is surprisingly awkward. I do it here by:
207   // - Inverting the mark word
208   // - Test lowest two bits == 0
209   // - If so, set the lowest two bits
210   // - Invert the result back, and copy to dst
211 
212   bool borrow_reg = (tmp == noreg);
213   if (borrow_reg) {
214     // No free registers available. Make one useful.
215     tmp = rscratch1;
216     if (tmp == dst) {
217       tmp = rscratch2;
218     }
219     __ push(RegSet::of(tmp), sp);
220   }
221 
222   assert_different_registers(tmp, dst);
223 
224   Label done;
225   __ ldr(tmp, Address(dst, oopDesc::mark_offset_in_bytes()));
226   __ eon(tmp, tmp, zr);
227   __ ands(zr, tmp, markWord::lock_mask_in_place);
228   __ br(Assembler::NE, done);
229   __ orr(tmp, tmp, markWord::marked_value);
230   __ eon(dst, tmp, zr);
231   __ bind(done);
232 
233   if (borrow_reg) {
234     __ pop(RegSet::of(tmp), sp);
235   }
236 }
237 
238 void ShenandoahBarrierSetAssembler::load_reference_barrier(MacroAssembler* masm, Register dst, Address load_addr, DecoratorSet decorators) {
239   assert(ShenandoahLoadRefBarrier, "Should be enabled");
240   assert(dst != rscratch2, "need rscratch2");
241   assert_different_registers(load_addr.base(), load_addr.index(), rscratch1, rscratch2);
242 
243   bool is_strong  = ShenandoahBarrierSet::is_strong_access(decorators);
244   bool is_weak    = ShenandoahBarrierSet::is_weak_access(decorators);
245   bool is_phantom = ShenandoahBarrierSet::is_phantom_access(decorators);
246   bool is_native  = ShenandoahBarrierSet::is_native_access(decorators);
247   bool is_narrow  = UseCompressedOops && !is_native;
248 
249   Label heap_stable, not_cset;
250   __ enter(/*strip_ret_addr*/true);
251   Address gc_state(rthread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
252   __ ldrb(rscratch2, gc_state);
253 
254   // Check for heap stability
255   if (is_strong) {
256     __ tbz(rscratch2, ShenandoahHeap::HAS_FORWARDED_BITPOS, heap_stable);
257   } else {
258     Label lrb;
259     __ tbnz(rscratch2, ShenandoahHeap::WEAK_ROOTS_BITPOS, lrb);
260     __ tbz(rscratch2, ShenandoahHeap::HAS_FORWARDED_BITPOS, heap_stable);
261     __ bind(lrb);
262   }
263 
264   // use r1 for load address
265   Register result_dst = dst;
266   if (dst == r1) {
267     __ mov(rscratch1, dst);
268     dst = rscratch1;
269   }
270 
271   // Save r0 and r1, unless it is an output register
272   RegSet to_save = RegSet::of(r0, r1) - result_dst;
273   __ push(to_save, sp);
274   __ lea(r1, load_addr);
275   __ mov(r0, dst);
276 
277   // Test for in-cset
278   if (is_strong) {
279     __ mov(rscratch2, ShenandoahHeap::in_cset_fast_test_addr());
280     __ lsr(rscratch1, r0, ShenandoahHeapRegion::region_size_bytes_shift_jint());
281     __ ldrb(rscratch2, Address(rscratch2, rscratch1));
282     __ tbz(rscratch2, 0, not_cset);
283   }
284 
285   __ push_call_clobbered_registers();
286   if (is_strong) {
287     if (is_narrow) {
288       __ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong_narrow));
289     } else {
290       __ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong));
291     }
292   } else if (is_weak) {
293     if (is_narrow) {
294       __ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak_narrow));
295     } else {
296       __ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak));
297     }
298   } else {
299     assert(is_phantom, "only remaining strength");
300     assert(!is_narrow, "phantom access cannot be narrow");
301     __ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom));
302   }
303   __ blr(lr);
304   __ mov(rscratch1, r0);
305   __ pop_call_clobbered_registers();
306   __ mov(r0, rscratch1);
307 
308   __ bind(not_cset);
309 
310   __ mov(result_dst, r0);
311   __ pop(to_save, sp);
312 
313   __ bind(heap_stable);
314   __ leave();
315 }
316 
317 void ShenandoahBarrierSetAssembler::iu_barrier(MacroAssembler* masm, Register dst, Register tmp) {
318   if (ShenandoahIUBarrier) {
319     __ push_call_clobbered_registers();
320     satb_write_barrier_pre(masm, noreg, dst, rthread, tmp, rscratch1, true, false);
321     __ pop_call_clobbered_registers();
322   }
323 }
324 
325 //
326 // Arguments:
327 //
328 // Inputs:
329 //   src:        oop location to load from, might be clobbered
330 //
331 // Output:
332 //   dst:        oop loaded from src location
333 //
334 // Kill:
335 //   rscratch1 (scratch reg)
336 //
337 // Alias:
338 //   dst: rscratch1 (might use rscratch1 as temporary output register to avoid clobbering src)
339 //
340 void ShenandoahBarrierSetAssembler::load_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
341                                             Register dst, Address src, Register tmp1, Register tmp2) {
342   // 1: non-reference load, no additional barrier is needed
343   if (!is_reference_type(type)) {
344     BarrierSetAssembler::load_at(masm, decorators, type, dst, src, tmp1, tmp2);
345     return;
346   }
347 
348   // 2: load a reference from src location and apply LRB if needed
349   if (ShenandoahBarrierSet::need_load_reference_barrier(decorators, type)) {
350     Register result_dst = dst;
351 
352     // Preserve src location for LRB
353     if (dst == src.base() || dst == src.index()) {
354       dst = rscratch1;
355     }
356     assert_different_registers(dst, src.base(), src.index());
357 
358     BarrierSetAssembler::load_at(masm, decorators, type, dst, src, tmp1, tmp2);
359 
360     load_reference_barrier(masm, dst, src, decorators);
361 
362     if (dst != result_dst) {
363       __ mov(result_dst, dst);
364       dst = result_dst;
365     }
366   } else {
367     BarrierSetAssembler::load_at(masm, decorators, type, dst, src, tmp1, tmp2);
368   }
369 
370   // 3: apply keep-alive barrier if needed
371   if (ShenandoahBarrierSet::need_keep_alive_barrier(decorators, type)) {
372     __ enter(/*strip_ret_addr*/true);
373     __ push_call_clobbered_registers();
374     satb_write_barrier_pre(masm /* masm */,
375                            noreg /* obj */,
376                            dst /* pre_val */,
377                            rthread /* thread */,
378                            tmp1 /* tmp1 */,
379                            tmp2 /* tmp2 */,
380                            true /* tosca_live */,
381                            true /* expand_call */);
382     __ pop_call_clobbered_registers();
383     __ leave();
384   }
385 }
386 
387 void ShenandoahBarrierSetAssembler::store_check(MacroAssembler* masm, Register obj) {
388   assert(ShenandoahCardBarrier, "Should have been checked by caller");
389 
390   __ lsr(obj, obj, CardTable::card_shift());
391 
392   assert(CardTable::dirty_card_val() == 0, "must be");
393 
394   __ load_byte_map_base(rscratch1);
395 
396   if (UseCondCardMark) {
397     Label L_already_dirty;
398     __ ldrb(rscratch2, Address(obj, rscratch1));
399     __ cbz(rscratch2, L_already_dirty);
400     __ strb(zr, Address(obj, rscratch1));
401     __ bind(L_already_dirty);
402   } else {
403     __ strb(zr, Address(obj, rscratch1));
404   }
405 }
406 
407 void ShenandoahBarrierSetAssembler::store_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
408                                              Address dst, Register val, Register tmp1, Register tmp2, Register tmp3) {
409   bool on_oop = is_reference_type(type);
410   if (!on_oop) {
411     BarrierSetAssembler::store_at(masm, decorators, type, dst, val, tmp1, tmp2, tmp3);
412     return;
413   }
414 
415   // flatten object address if needed
416   if (dst.index() == noreg && dst.offset() == 0) {
417     if (dst.base() != tmp3) {
418       __ mov(tmp3, dst.base());
419     }
420   } else {
421     __ lea(tmp3, dst);
422   }
423 
424   shenandoah_write_barrier_pre(masm,
425                                tmp3 /* obj */,
426                                tmp2 /* pre_val */,
427                                rthread /* thread */,
428                                tmp1  /* tmp */,
429                                val != noreg /* tosca_live */,
430                                false /* expand_call */);
431 
432   if (val == noreg) {
433     BarrierSetAssembler::store_at(masm, decorators, type, Address(tmp3, 0), noreg, noreg, noreg, noreg);
434   } else {
435     iu_barrier(masm, val, tmp1);
436     // G1 barrier needs uncompressed oop for region cross check.
437     Register new_val = val;
438     if (UseCompressedOops) {
439       new_val = rscratch2;
440       __ mov(new_val, val);
441     }
442     BarrierSetAssembler::store_at(masm, decorators, type, Address(tmp3, 0), val, noreg, noreg, noreg);
443     if (ShenandoahCardBarrier) {
444       store_check(masm, tmp3);
445     }
446   }
447 
448 }
449 
450 void ShenandoahBarrierSetAssembler::try_resolve_jobject_in_native(MacroAssembler* masm, Register jni_env,
451                                                                   Register obj, Register tmp, Label& slowpath) {
452   Label done;
453   // Resolve jobject
454   BarrierSetAssembler::try_resolve_jobject_in_native(masm, jni_env, obj, tmp, slowpath);
455 
456   // Check for null.
457   __ cbz(obj, done);
458 
459   assert(obj != rscratch2, "need rscratch2");
460   Address gc_state(jni_env, ShenandoahThreadLocalData::gc_state_offset() - JavaThread::jni_environment_offset());
461   __ lea(rscratch2, gc_state);
462   __ ldrb(rscratch2, Address(rscratch2));
463 
464   // Check for heap in evacuation phase
465   __ tbnz(rscratch2, ShenandoahHeap::EVACUATION_BITPOS, slowpath);
466 
467   __ bind(done);
468 }
469 
470 // Special Shenandoah CAS implementation that handles false negatives due
471 // to concurrent evacuation.  The service is more complex than a
472 // traditional CAS operation because the CAS operation is intended to
473 // succeed if the reference at addr exactly matches expected or if the
474 // reference at addr holds a pointer to a from-space object that has
475 // been relocated to the location named by expected.  There are two
476 // races that must be addressed:
477 //  a) A parallel thread may mutate the contents of addr so that it points
478 //     to a different object.  In this case, the CAS operation should fail.
479 //  b) A parallel thread may heal the contents of addr, replacing a
480 //     from-space pointer held in addr with the to-space pointer
481 //     representing the new location of the object.
482 // Upon entry to cmpxchg_oop, it is assured that new_val equals null
483 // or it refers to an object that is not being evacuated out of
484 // from-space, or it refers to the to-space version of an object that
485 // is being evacuated out of from-space.
486 //
487 // By default the value held in the result register following execution
488 // of the generated code sequence is 0 to indicate failure of CAS,
489 // non-zero to indicate success. If is_cae, the result is the value most
490 // recently fetched from addr rather than a boolean success indicator.
491 //
492 // Clobbers rscratch1, rscratch2
493 void ShenandoahBarrierSetAssembler::cmpxchg_oop(MacroAssembler* masm,
494                                                 Register addr,
495                                                 Register expected,
496                                                 Register new_val,
497                                                 bool acquire, bool release,
498                                                 bool is_cae,
499                                                 Register result) {
500   Register tmp1 = rscratch1;
501   Register tmp2 = rscratch2;
502   bool is_narrow = UseCompressedOops;
503   Assembler::operand_size size = is_narrow ? Assembler::word : Assembler::xword;
504 
505   assert_different_registers(addr, expected, tmp1, tmp2);
506   assert_different_registers(addr, new_val,  tmp1, tmp2);
507 
508   Label step4, done;
509 
510   // There are two ways to reach this label.  Initial entry into the
511   // cmpxchg_oop code expansion starts at step1 (which is equivalent
512   // to label step4).  Additionally, in the rare case that four steps
513   // are required to perform the requested operation, the fourth step
514   // is the same as the first.  On a second pass through step 1,
515   // control may flow through step 2 on its way to failure.  It will
516   // not flow from step 2 to step 3 since we are assured that the
517   // memory at addr no longer holds a from-space pointer.
518   //
519   // The comments that immediately follow the step4 label apply only
520   // to the case in which control reaches this label by branch from
521   // step 3.
522 
523   __ bind (step4);
524 
525   // Step 4. CAS has failed because the value most recently fetched
526   // from addr is no longer the from-space pointer held in tmp2.  If a
527   // different thread replaced the in-memory value with its equivalent
528   // to-space pointer, then CAS may still be able to succeed.  The
529   // value held in the expected register has not changed.
530   //
531   // It is extremely rare we reach this point.  For this reason, the
532   // implementation opts for smaller rather than potentially faster
533   // code.  Ultimately, smaller code for this rare case most likely
534   // delivers higher overall throughput by enabling improved icache
535   // performance.
536 
537   // Step 1. Fast-path.
538   //
539   // Try to CAS with given arguments.  If successful, then we are done.
540   //
541   // No label required for step 1.
542 
543   __ cmpxchg(addr, expected, new_val, size, acquire, release, false, tmp2);
544   // EQ flag set iff success.  tmp2 holds value fetched.
545 
546   // If expected equals null but tmp2 does not equal null, the
547   // following branches to done to report failure of CAS.  If both
548   // expected and tmp2 equal null, the following branches to done to
549   // report success of CAS.  There's no need for a special test of
550   // expected equal to null.
551 
552   __ br(Assembler::EQ, done);
553   // if CAS failed, fall through to step 2
554 
555   // Step 2. CAS has failed because the value held at addr does not
556   // match expected.  This may be a false negative because the value fetched
557   // from addr (now held in tmp2) may be a from-space pointer to the
558   // original copy of same object referenced by to-space pointer expected.
559   //
560   // To resolve this, it suffices to find the forward pointer associated
561   // with fetched value.  If this matches expected, retry CAS with new
562   // parameters.  If this mismatches, then we have a legitimate
563   // failure, and we're done.
564   //
565   // No need for step2 label.
566 
567   // overwrite tmp1 with from-space pointer fetched from memory
568   __ mov(tmp1, tmp2);
569 
570   if (is_narrow) {
571     // Decode tmp1 in order to resolve its forward pointer
572     __ decode_heap_oop(tmp1, tmp1);
573   }
574   resolve_forward_pointer(masm, tmp1);
575   // Encode tmp1 to compare against expected.
576   __ encode_heap_oop(tmp1, tmp1);
577 
578   // Does forwarded value of fetched from-space pointer match original
579   // value of expected?  If tmp1 holds null, this comparison will fail
580   // because we know from step1 that expected is not null.  There is
581   // no need for a separate test for tmp1 (the value originally held
582   // in memory) equal to null.
583   __ cmp(tmp1, expected);
584 
585   // If not, then the failure was legitimate and we're done.
586   // Branching to done with NE condition denotes failure.
587   __ br(Assembler::NE, done);
588 
589   // Fall through to step 3.  No need for step3 label.
590 
591   // Step 3.  We've confirmed that the value originally held in memory
592   // (now held in tmp2) pointed to from-space version of original
593   // expected value.  Try the CAS again with the from-space expected
594   // value.  If it now succeeds, we're good.
595   //
596   // Note: tmp2 holds encoded from-space pointer that matches to-space
597   // object residing at expected.  tmp2 is the new "expected".
598 
599   // Note that macro implementation of __cmpxchg cannot use same register
600   // tmp2 for result and expected since it overwrites result before it
601   // compares result with expected.
602   __ cmpxchg(addr, tmp2, new_val, size, acquire, release, false, noreg);
603   // EQ flag set iff success.  tmp2 holds value fetched, tmp1 (rscratch1) clobbered.
604 
605   // If fetched value did not equal the new expected, this could
606   // still be a false negative because some other thread may have
607   // newly overwritten the memory value with its to-space equivalent.
608   __ br(Assembler::NE, step4);
609 
610   if (is_cae) {
611     // We're falling through to done to indicate success.  Success
612     // with is_cae is denoted by returning the value of expected as
613     // result.
614     __ mov(tmp2, expected);
615   }
616 
617   __ bind(done);
618   // At entry to done, the Z (EQ) flag is on iff if the CAS
619   // operation was successful.  Additionally, if is_cae, tmp2 holds
620   // the value most recently fetched from addr. In this case, success
621   // is denoted by tmp2 matching expected.
622 
623   if (is_cae) {
624     __ mov(result, tmp2);
625   } else {
626     __ cset(result, Assembler::EQ);
627   }
628 }
629 
630 void ShenandoahBarrierSetAssembler::gen_write_ref_array_post_barrier(MacroAssembler* masm, DecoratorSet decorators,
631                                                                      Register start, Register count, Register scratch, RegSet saved_regs) {
632   assert(ShenandoahCardBarrier, "Should have been checked by caller");
633 
634   Label L_loop, L_done;
635   const Register end = count;
636 
637   // Zero count? Nothing to do.
638   __ cbz(count, L_done);
639 
640   // end = start + count << LogBytesPerHeapOop
641   // last element address to make inclusive
642   __ lea(end, Address(start, count, Address::lsl(LogBytesPerHeapOop)));
643   __ sub(end, end, BytesPerHeapOop);
644   __ lsr(start, start, CardTable::card_shift());
645   __ lsr(end, end, CardTable::card_shift());
646 
647   // number of bytes to copy
648   __ sub(count, end, start);
649 
650   __ load_byte_map_base(scratch);
651   __ add(start, start, scratch);
652   __ bind(L_loop);
653   __ strb(zr, Address(start, count));
654   __ subs(count, count, 1);
655   __ br(Assembler::GE, L_loop);
656   __ bind(L_done);
657 }
658 
659 #undef __
660 
661 #ifdef COMPILER1
662 
663 #define __ ce->masm()->
664 
665 void ShenandoahBarrierSetAssembler::gen_pre_barrier_stub(LIR_Assembler* ce, ShenandoahPreBarrierStub* stub) {
666   ShenandoahBarrierSetC1* bs = (ShenandoahBarrierSetC1*)BarrierSet::barrier_set()->barrier_set_c1();
667   // At this point we know that marking is in progress.
668   // If do_load() is true then we have to emit the
669   // load of the previous value; otherwise it has already
670   // been loaded into _pre_val.
671 
672   __ bind(*stub->entry());
673 
674   assert(stub->pre_val()->is_register(), "Precondition.");
675 
676   Register pre_val_reg = stub->pre_val()->as_register();
677 
678   if (stub->do_load()) {
679     ce->mem2reg(stub->addr(), stub->pre_val(), T_OBJECT, stub->patch_code(), stub->info(), false /*wide*/);
680   }
681   __ cbz(pre_val_reg, *stub->continuation());
682   ce->store_parameter(stub->pre_val()->as_register(), 0);
683   __ far_call(RuntimeAddress(bs->pre_barrier_c1_runtime_code_blob()->code_begin()));
684   __ b(*stub->continuation());
685 }
686 
687 void ShenandoahBarrierSetAssembler::gen_load_reference_barrier_stub(LIR_Assembler* ce, ShenandoahLoadReferenceBarrierStub* stub) {
688   ShenandoahBarrierSetC1* bs = (ShenandoahBarrierSetC1*)BarrierSet::barrier_set()->barrier_set_c1();
689   __ bind(*stub->entry());
690 
691   DecoratorSet decorators = stub->decorators();
692   bool is_strong  = ShenandoahBarrierSet::is_strong_access(decorators);
693   bool is_weak    = ShenandoahBarrierSet::is_weak_access(decorators);
694   bool is_phantom = ShenandoahBarrierSet::is_phantom_access(decorators);
695   bool is_native  = ShenandoahBarrierSet::is_native_access(decorators);
696 
697   Register obj = stub->obj()->as_register();
698   Register res = stub->result()->as_register();
699   Register addr = stub->addr()->as_pointer_register();
700   Register tmp1 = stub->tmp1()->as_register();
701   Register tmp2 = stub->tmp2()->as_register();
702 
703   assert(res == r0, "result must arrive in r0");
704 
705   if (res != obj) {
706     __ mov(res, obj);
707   }
708 
709   if (is_strong) {
710     // Check for object in cset.
711     __ mov(tmp2, ShenandoahHeap::in_cset_fast_test_addr());
712     __ lsr(tmp1, res, ShenandoahHeapRegion::region_size_bytes_shift_jint());
713     __ ldrb(tmp2, Address(tmp2, tmp1));
714     __ cbz(tmp2, *stub->continuation());
715   }
716 
717   ce->store_parameter(res, 0);
718   ce->store_parameter(addr, 1);
719   if (is_strong) {
720     if (is_native) {
721       __ far_call(RuntimeAddress(bs->load_reference_barrier_strong_native_rt_code_blob()->code_begin()));
722     } else {
723       __ far_call(RuntimeAddress(bs->load_reference_barrier_strong_rt_code_blob()->code_begin()));
724     }
725   } else if (is_weak) {
726     __ far_call(RuntimeAddress(bs->load_reference_barrier_weak_rt_code_blob()->code_begin()));
727   } else {
728     assert(is_phantom, "only remaining strength");
729     __ far_call(RuntimeAddress(bs->load_reference_barrier_phantom_rt_code_blob()->code_begin()));
730   }
731 
732   __ b(*stub->continuation());
733 }
734 
735 #undef __
736 
737 #define __ sasm->
738 
739 void ShenandoahBarrierSetAssembler::generate_c1_pre_barrier_runtime_stub(StubAssembler* sasm) {
740   __ prologue("shenandoah_pre_barrier", false);
741 
742   // arg0 : previous value of memory
743 
744   BarrierSet* bs = BarrierSet::barrier_set();
745 
746   const Register pre_val = r0;
747   const Register thread = rthread;
748   const Register tmp = rscratch1;
749 
750   Address queue_index(thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset()));
751   Address buffer(thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset()));
752 
753   Label done;
754   Label runtime;
755 
756   // Is marking still active?
757   Address gc_state(thread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
758   __ ldrb(tmp, gc_state);
759   __ tbz(tmp, ShenandoahHeap::MARKING_BITPOS, done);
760 
761   // Can we store original value in the thread's buffer?
762   __ ldr(tmp, queue_index);
763   __ cbz(tmp, runtime);
764 
765   __ sub(tmp, tmp, wordSize);
766   __ str(tmp, queue_index);
767   __ ldr(rscratch2, buffer);
768   __ add(tmp, tmp, rscratch2);
769   __ load_parameter(0, rscratch2);
770   __ str(rscratch2, Address(tmp, 0));
771   __ b(done);
772 
773   __ bind(runtime);
774   __ push_call_clobbered_registers();
775   __ load_parameter(0, pre_val);
776   __ call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_ref_field_pre_entry), pre_val, thread);
777   __ pop_call_clobbered_registers();
778   __ bind(done);
779 
780   __ epilogue();
781 }
782 
783 void ShenandoahBarrierSetAssembler::generate_c1_load_reference_barrier_runtime_stub(StubAssembler* sasm, DecoratorSet decorators) {
784   __ prologue("shenandoah_load_reference_barrier", false);
785   // arg0 : object to be resolved
786 
787   __ push_call_clobbered_registers();
788   __ load_parameter(0, r0);
789   __ load_parameter(1, r1);
790 
791   bool is_strong  = ShenandoahBarrierSet::is_strong_access(decorators);
792   bool is_weak    = ShenandoahBarrierSet::is_weak_access(decorators);
793   bool is_phantom = ShenandoahBarrierSet::is_phantom_access(decorators);
794   bool is_native  = ShenandoahBarrierSet::is_native_access(decorators);
795   if (is_strong) {
796     if (is_native) {
797       __ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong));
798     } else {
799       if (UseCompressedOops) {
800         __ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong_narrow));
801       } else {
802         __ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong));
803       }
804     }
805   } else if (is_weak) {
806     assert(!is_native, "weak must not be called off-heap");
807     if (UseCompressedOops) {
808       __ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak_narrow));
809     } else {
810       __ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak));
811     }
812   } else {
813     assert(is_phantom, "only remaining strength");
814     assert(is_native, "phantom must only be called off-heap");
815     __ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom));
816   }
817   __ blr(lr);
818   __ mov(rscratch1, r0);
819   __ pop_call_clobbered_registers();
820   __ mov(r0, rscratch1);
821 
822   __ epilogue();
823 }
824 
825 #undef __
826 
827 #endif // COMPILER1