1 /*
  2  * Copyright (c) 2018, 2026, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "asm/macroAssembler.inline.hpp"
 26 #include "code/aotCodeCache.hpp"
 27 #include "gc/g1/g1BarrierSet.hpp"
 28 #include "gc/g1/g1BarrierSetAssembler.hpp"
 29 #include "gc/g1/g1BarrierSetRuntime.hpp"
 30 #include "gc/g1/g1CardTable.hpp"
 31 #include "gc/g1/g1HeapRegion.hpp"
 32 #include "gc/g1/g1ThreadLocalData.hpp"
 33 #include "interpreter/interp_masm.hpp"
 34 #include "runtime/arguments.hpp"
 35 #include "runtime/sharedRuntime.hpp"
 36 #include "utilities/debug.hpp"
 37 #include "utilities/macros.hpp"
 38 #ifdef COMPILER1
 39 #include "c1/c1_LIRAssembler.hpp"
 40 #include "c1/c1_MacroAssembler.hpp"
 41 #include "gc/g1/c1/g1BarrierSetC1.hpp"
 42 #endif // COMPILER1
 43 #ifdef COMPILER2
 44 #include "gc/g1/c2/g1BarrierSetC2.hpp"
 45 #endif // COMPILER2
 46 
 47 #define __ masm->
 48 
 49 void G1BarrierSetAssembler::gen_write_ref_array_pre_barrier(MacroAssembler* masm, DecoratorSet decorators,
 50                                                             Register addr, Register count) {
 51   bool dest_uninitialized = (decorators & IS_DEST_UNINITIALIZED) != 0;
 52 
 53   if (!dest_uninitialized) {
 54     Register thread = r15_thread;
 55 
 56     Label filtered;
 57     Address in_progress(thread, in_bytes(G1ThreadLocalData::satb_mark_queue_active_offset()));
 58     // Is marking active?
 59     if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
 60       __ cmpl(in_progress, 0);
 61     } else {
 62       assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
 63       __ cmpb(in_progress, 0);
 64     }
 65 
 66     __ jcc(Assembler::equal, filtered);
 67 
 68     __ push_call_clobbered_registers(false /* save_fpu */);
 69     if (count == c_rarg0) {
 70       if (addr == c_rarg1) {
 71         // exactly backwards!!
 72         __ xchgptr(c_rarg1, c_rarg0);
 73       } else {
 74         __ movptr(c_rarg1, count);
 75         __ movptr(c_rarg0, addr);
 76       }
 77     } else {
 78       __ movptr(c_rarg0, addr);
 79       __ movptr(c_rarg1, count);
 80     }
 81     if (UseCompressedOops) {
 82       __ call_VM_leaf(CAST_FROM_FN_PTR(address, G1BarrierSetRuntime::write_ref_array_pre_narrow_oop_entry), 2);
 83     } else {
 84       __ call_VM_leaf(CAST_FROM_FN_PTR(address, G1BarrierSetRuntime::write_ref_array_pre_oop_entry), 2);
 85     }
 86     __ pop_call_clobbered_registers(false /* save_fpu */);
 87 
 88     __ bind(filtered);
 89   }
 90 }
 91 
 92 void G1BarrierSetAssembler::gen_write_ref_array_post_barrier(MacroAssembler* masm, DecoratorSet decorators,
 93                                                              Register addr, Register count, Register tmp) {
 94   Label L_done;
 95 
 96   __ testptr(count, count);
 97   __ jccb(Assembler::zero, L_done);
 98 
 99   // Calculate end address in "count".
100   Address::ScaleFactor scale = UseCompressedOops ? Address::times_4 : Address::times_8;
101   __ leaq(count, Address(addr, count, scale));
102 
103   // Calculate start card address in "addr".
104   __ shrptr(addr, CardTable::card_shift());
105 
106   Register thread = r15_thread;
107 
108   __ movptr(tmp, Address(thread, in_bytes(G1ThreadLocalData::card_table_base_offset())));
109   __ addptr(addr, tmp);
110 
111   // Calculate address of card of last word in the array.
112   __ subptr(count, 1);
113   __ shrptr(count, CardTable::card_shift());
114   __ addptr(count, tmp);
115 
116   Label L_loop;
117   // Iterate from start card to end card (inclusive).
118   __ bind(L_loop);
119 
120   Label L_is_clean_card;
121   if (UseCondCardMark) {
122     __ cmpb(Address(addr, 0), G1CardTable::clean_card_val());
123     __ jccb(Assembler::equal, L_is_clean_card);
124   } else {
125    __ movb(Address(addr, 0), G1CardTable::dirty_card_val());
126   }
127 
128   Label L_next_card;
129   __ bind(L_next_card);
130   __ addptr(addr, sizeof(CardTable::CardValue));
131   __ cmpptr(addr, count);
132   __ jccb(Assembler::belowEqual, L_loop);
133   __ jmpb(L_done);
134 
135   __ bind(L_is_clean_card);
136   // Card was clean. Dirty card and go to next.
137   __ movb(Address(addr, 0), G1CardTable::dirty_card_val());
138   __ jmpb(L_next_card);
139 
140   __ bind(L_done);
141 }
142 
143 void G1BarrierSetAssembler::load_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
144                                     Register dst, Address src, Register tmp1) {
145   bool on_oop = is_reference_type(type);
146   bool on_weak = (decorators & ON_WEAK_OOP_REF) != 0;
147   bool on_phantom = (decorators & ON_PHANTOM_OOP_REF) != 0;
148   bool on_reference = on_weak || on_phantom;
149   CardTableBarrierSetAssembler::load_at(masm, decorators, type, dst, src, tmp1);
150   if (on_oop && on_reference) {
151     // Generate the G1 pre-barrier code to log the value of
152     // the referent field in an SATB buffer.
153     g1_write_barrier_pre(masm /* masm */,
154                          noreg /* obj */,
155                          dst /* pre_val */,
156                          tmp1 /* tmp */,
157                          true /* tosca_live */,
158                          true /* expand_call */);
159   }
160 }
161 
162 static void generate_pre_barrier_fast_path(MacroAssembler* masm,
163                                            const Register thread) {
164   Address in_progress(thread, in_bytes(G1ThreadLocalData::satb_mark_queue_active_offset()));
165   // Is marking active?
166   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
167     __ cmpl(in_progress, 0);
168   } else {
169     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
170     __ cmpb(in_progress, 0);
171   }
172 }
173 
174 static void generate_pre_barrier_slow_path(MacroAssembler* masm,
175                                            const Register obj,
176                                            const Register pre_val,
177                                            const Register thread,
178                                            const Register tmp,
179                                            Label& L_done) {
180   Address index_addr(thread, in_bytes(G1ThreadLocalData::satb_mark_queue_index_offset()));
181   Address buffer_addr(thread, in_bytes(G1ThreadLocalData::satb_mark_queue_buffer_offset()));
182 
183   // This code assumes that buffer index is pointer sized.
184   STATIC_ASSERT(in_bytes(SATBMarkQueue::byte_width_of_index()) == sizeof(intptr_t));
185 
186   Label L_runtime;
187 
188   // Do we need to load the previous value?
189   if (obj != noreg) {
190     __ load_heap_oop(pre_val, Address(obj, 0), noreg, AS_RAW);
191   }
192 
193   // Is the previous value null?
194   __ testptr(pre_val, pre_val);
195   __ jcc(Assembler::equal, L_done);
196 
197   // Can we store a value in the given thread's buffer?
198   // (The index field is typed as size_t.)
199   __ movptr(tmp, index_addr);             // temp := *(index address)
200   __ testptr(tmp, tmp);                   // index == 0?
201   __ jccb(Assembler::zero, L_runtime);    // jump to runtime if index == 0 (full buffer)
202 
203   // The buffer is not full, store value into it.
204   __ subptr(tmp, wordSize);               // temp := next index
205   __ movptr(index_addr, tmp);             // *(index address) := next index
206   __ addptr(tmp, buffer_addr);            // temp := buffer address + next index
207   __ movptr(Address(tmp, 0), pre_val);    // *(buffer address + next index) := value
208 
209   // Jump out if done, or fall-through to runtime.
210   // "L_done" is far away, so jump cannot be short.
211   __ jmp(L_done);
212   __ bind(L_runtime);
213 }
214 
215 void G1BarrierSetAssembler::g1_write_barrier_pre(MacroAssembler* masm,
216                                                  Register obj,
217                                                  Register pre_val,
218                                                  Register tmp,
219                                                  bool tosca_live,
220                                                  bool expand_call) {
221   // If expand_call is true then we expand the call_VM_leaf macro
222   // directly to skip generating the check by
223   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
224   const Register thread = r15_thread;
225 
226   Label done;
227 
228   assert(pre_val != noreg, "check this code");
229 
230   if (obj != noreg) {
231     assert_different_registers(obj, pre_val, tmp);
232     assert(pre_val != rax, "check this code");
233   }
234 
235   generate_pre_barrier_fast_path(masm, thread);
236   // If marking is not active (*(mark queue active address) == 0), jump to done
237   __ jcc(Assembler::equal, done);
238   generate_pre_barrier_slow_path(masm, obj, pre_val, thread, tmp, done);
239 
240   // Determine and save the live input values
241   __ push_call_clobbered_registers();
242 
243   // Calling the runtime using the regular call_VM_leaf mechanism generates
244   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
245   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == nullptr.
246   //
247   // If we care generating the pre-barrier without a frame (e.g. in the
248   // intrinsified Reference.get() routine) then ebp might be pointing to
249   // the caller frame and so this check will most likely fail at runtime.
250   //
251   // Expanding the call directly bypasses the generation of the check.
252   // So when we do not have have a full interpreter frame on the stack
253   // expand_call should be passed true.
254 
255   if (expand_call) {
256     assert(pre_val != c_rarg1, "smashed arg");
257     if (c_rarg1 != thread) {
258       __ mov(c_rarg1, thread);
259     }
260     if (c_rarg0 != pre_val) {
261       __ mov(c_rarg0, pre_val);
262     }
263     __ MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, G1BarrierSetRuntime::write_ref_field_pre_entry), 2);
264   } else {
265     __ call_VM_leaf(CAST_FROM_FN_PTR(address, G1BarrierSetRuntime::write_ref_field_pre_entry), pre_val, thread);
266   }
267 
268   __ pop_call_clobbered_registers();
269 
270   __ bind(done);
271 }
272 
273 #if INCLUDE_CDS
274 // return a register that differs from reg1, reg2, reg3 and reg4
275 
276 static Register pick_different_reg(Register reg1, Register reg2 = noreg, Register reg3= noreg, Register reg4 = noreg) {
277   RegSet available = (RegSet::of(rscratch1, rscratch2, rax, rbx) + rdx -
278                       RegSet::of(reg1, reg2, reg3, reg4));
279   return *(available.begin());
280 }
281 #endif // INCLUDE_CDS
282 
283 static void generate_post_barrier(MacroAssembler* masm,
284                                   const Register store_addr,
285                                   const Register new_val,
286                                   const Register tmp1,
287                                   bool new_val_may_be_null) {
288 
289   assert_different_registers(store_addr, new_val, tmp1, noreg);
290 
291   Register thread = r15_thread;
292 
293   Label L_done;
294   // Does store cross heap regions?
295 #if INCLUDE_CDS
296   // AOT code needs to load the barrier grain shift from the aot
297   // runtime constants area in the code cache otherwise we can compile
298   // it as an immediate operand
299 
300   if (AOTCodeCache::is_on_for_dump()) {
301     address grain_shift_addr = AOTRuntimeConstants::grain_shift_address();
302     Register save = pick_different_reg(rcx, tmp1, new_val, store_addr);
303     __ push(save);
304     __ movptr(save, store_addr);
305     __ xorptr(save, new_val);
306     __ push(rcx);
307     __ lea(rcx, ExternalAddress(grain_shift_addr));
308     __ movl(rcx, Address(rcx, 0));
309     __ shrptr(save);
310     __ pop(rcx);
311     __ pop(save);
312     __ jcc(Assembler::equal, L_done);
313   } else
314 #endif // INCLUDE_CDS
315   {
316     __ movptr(tmp1, store_addr);                                    // tmp1 := store address
317     __ xorptr(tmp1, new_val);                                       // tmp1 := store address ^ new value
318     __ shrptr(tmp1, G1HeapRegion::LogOfHRGrainBytes);               // ((store address ^ new value) >> LogOfHRGrainBytes) == 0?
319     __ jccb(Assembler::equal, L_done);
320   }
321 
322   // Crosses regions, storing null?
323   if (new_val_may_be_null) {
324     __ testptr(new_val, new_val);                                 // new value == null?
325     __ jccb(Assembler::equal, L_done);
326   }
327 
328   __ movptr(tmp1, store_addr);                                    // tmp1 := store address
329   __ shrptr(tmp1, CardTable::card_shift());                       // tmp1 := card address relative to card table base
330 
331   Address card_table_addr(thread, in_bytes(G1ThreadLocalData::card_table_base_offset()));
332   __ addptr(tmp1, card_table_addr);                               // tmp1 := card address
333   if (UseCondCardMark) {
334     __ cmpb(Address(tmp1, 0), G1CardTable::clean_card_val());     // *(card address) == clean_card_val?
335     __ jccb(Assembler::notEqual, L_done);
336   }
337   // Storing a region crossing, non-null oop, card is clean.
338   // Dirty card.
339   __ movb(Address(tmp1, 0), G1CardTable::dirty_card_val());       // *(card address) := dirty_card_val
340   __ bind(L_done);
341 }
342 
343 void G1BarrierSetAssembler::g1_write_barrier_post(MacroAssembler* masm,
344                                                   Register store_addr,
345                                                   Register new_val,
346                                                   Register tmp) {
347   generate_post_barrier(masm, store_addr, new_val, tmp, true /* new_val_may_be_null */);
348 }
349 
350 #if defined(COMPILER2)
351 
352 static void generate_c2_barrier_runtime_call(MacroAssembler* masm, G1BarrierStubC2* stub, const Register arg, const address runtime_path) {
353   SaveLiveRegisters save_registers(masm, stub);
354   if (c_rarg0 != arg) {
355     __ mov(c_rarg0, arg);
356   }
357   __ mov(c_rarg1, r15_thread);
358   // rax is a caller-saved, non-argument-passing register, so it does not
359   // interfere with c_rarg0 or c_rarg1. If it contained any live value before
360   // entering this stub, it is saved at this point, and restored after the
361   // call. If it did not contain any live value, it is free to be used. In
362   // either case, it is safe to use it here as a call scratch register.
363   __ call(RuntimeAddress(runtime_path), rax);
364 }
365 
366 void G1BarrierSetAssembler::g1_write_barrier_pre_c2(MacroAssembler* masm,
367                                                     Register obj,
368                                                     Register pre_val,
369                                                     Register tmp,
370                                                     G1PreBarrierStubC2* stub) {
371   const Register thread = r15_thread;
372 
373   assert(pre_val != noreg, "check this code");
374   if (obj != noreg) {
375     assert_different_registers(obj, pre_val, tmp);
376   }
377 
378   stub->initialize_registers(obj, pre_val, thread, tmp);
379 
380   generate_pre_barrier_fast_path(masm, thread);
381   // If marking is active (*(mark queue active address) != 0), jump to stub (slow path)
382   __ jcc(Assembler::notEqual, *stub->entry());
383 
384   __ bind(*stub->continuation());
385 }
386 
387 void G1BarrierSetAssembler::generate_c2_pre_barrier_stub(MacroAssembler* masm,
388                                                          G1PreBarrierStubC2* stub) const {
389   Assembler::InlineSkippedInstructionsCounter skip_counter(masm);
390   Register obj = stub->obj();
391   Register pre_val = stub->pre_val();
392   Register thread = stub->thread();
393   Register tmp = stub->tmp1();
394   assert(stub->tmp2() == noreg, "not needed in this platform");
395 
396   __ bind(*stub->entry());
397   generate_pre_barrier_slow_path(masm, obj, pre_val, thread, tmp, *stub->continuation());
398 
399   generate_c2_barrier_runtime_call(masm, stub, pre_val, CAST_FROM_FN_PTR(address, G1BarrierSetRuntime::write_ref_field_pre_entry));
400   __ jmp(*stub->continuation());
401 }
402 
403 void G1BarrierSetAssembler::g1_write_barrier_post_c2(MacroAssembler* masm,
404                                                      Register store_addr,
405                                                      Register new_val,
406                                                      Register tmp,
407                                                      bool new_val_may_be_null) {
408   generate_post_barrier(masm, store_addr, new_val, tmp, new_val_may_be_null);
409 }
410 
411 #endif // COMPILER2
412 
413 void G1BarrierSetAssembler::oop_store_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
414                                          Address dst, Register val, Register tmp1, Register tmp2, Register tmp3) {
415   bool in_heap = (decorators & IN_HEAP) != 0;
416   bool as_normal = (decorators & AS_NORMAL) != 0;
417   bool dest_uninitialized = (decorators & IS_DEST_UNINITIALIZED) != 0;
418 
419   bool needs_pre_barrier = as_normal && !dest_uninitialized;
420   bool needs_post_barrier = val != noreg && in_heap;
421 
422   // flatten object address if needed
423   // We do it regardless of precise because we need the registers
424   if (dst.index() == noreg && dst.disp() == 0) {
425     if (dst.base() != tmp1) {
426       __ movptr(tmp1, dst.base());
427     }
428   } else {
429     __ lea(tmp1, dst);
430   }
431 
432   if (needs_pre_barrier) {
433     g1_write_barrier_pre(masm /*masm*/,
434                          tmp1 /* obj */,
435                          tmp2 /* pre_val */,
436                          tmp3  /* tmp */,
437                          val != noreg /* tosca_live */,
438                          false /* expand_call */);
439   }
440   if (val == noreg) {
441     BarrierSetAssembler::store_at(masm, decorators, type, Address(tmp1, 0), val, noreg, noreg, noreg);
442   } else {
443     Register new_val = val;
444     if (needs_post_barrier) {
445       // G1 barrier needs uncompressed oop for region cross check.
446       if (UseCompressedOops) {
447         new_val = tmp2;
448         __ movptr(new_val, val);
449       }
450     }
451     BarrierSetAssembler::store_at(masm, decorators, type, Address(tmp1, 0), val, noreg, noreg, noreg);
452     if (needs_post_barrier) {
453       g1_write_barrier_post(masm /*masm*/,
454                             tmp1 /* store_adr */,
455                             new_val /* new_val */,
456                             tmp3 /* tmp */);
457     }
458   }
459 }
460 
461 #ifdef COMPILER1
462 
463 #undef __
464 #define __ ce->masm()->
465 
466 void G1BarrierSetAssembler::gen_pre_barrier_stub(LIR_Assembler* ce, G1PreBarrierStub* stub) {
467   G1BarrierSetC1* bs = (G1BarrierSetC1*)BarrierSet::barrier_set()->barrier_set_c1();
468   // At this point we know that marking is in progress.
469   // If do_load() is true then we have to emit the
470   // load of the previous value; otherwise it has already
471   // been loaded into _pre_val.
472 
473   __ bind(*stub->entry());
474   assert(stub->pre_val()->is_register(), "Precondition.");
475 
476   Register pre_val_reg = stub->pre_val()->as_register();
477 
478   if (stub->do_load()) {
479     ce->mem2reg(stub->addr(), stub->pre_val(), T_OBJECT, stub->patch_code(), stub->info(), false /*wide*/);
480   }
481 
482   __ testptr(pre_val_reg, pre_val_reg);
483   __ jcc(Assembler::equal, *stub->continuation());
484   ce->store_parameter(stub->pre_val()->as_register(), 0);
485   __ call(RuntimeAddress(bs->pre_barrier_c1_runtime_code_blob()->code_begin()));
486   __ jmp(*stub->continuation());
487 
488 }
489 
490 #undef __
491 
492 void G1BarrierSetAssembler::g1_write_barrier_post_c1(MacroAssembler* masm,
493                                                      Register store_addr,
494                                                      Register new_val,
495                                                      Register thread,
496                                                      Register tmp1,
497                                                      Register tmp2 /* unused on x86 */) {
498   generate_post_barrier(masm, store_addr, new_val, tmp1, true /* new_val_may_be_null */);
499 }
500 
501 #define __ sasm->
502 
503 void G1BarrierSetAssembler::generate_c1_pre_barrier_runtime_stub(StubAssembler* sasm) {
504   // Generated code assumes that buffer index is pointer sized.
505   STATIC_ASSERT(in_bytes(SATBMarkQueue::byte_width_of_index()) == sizeof(intptr_t));
506 
507   __ prologue("g1_pre_barrier", false);
508   // arg0 : previous value of memory
509 
510   __ push_ppx(rax);
511   __ push_ppx(rdx);
512 
513   const Register pre_val = rax;
514   const Register thread = r15_thread;
515   const Register tmp = rdx;
516 
517   Address queue_active(thread, in_bytes(G1ThreadLocalData::satb_mark_queue_active_offset()));
518   Address queue_index(thread, in_bytes(G1ThreadLocalData::satb_mark_queue_index_offset()));
519   Address buffer(thread, in_bytes(G1ThreadLocalData::satb_mark_queue_buffer_offset()));
520 
521   Label L_done, L_runtime;
522 
523   // Is marking still active?
524   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
525     __ cmpl(queue_active, 0);
526   } else {
527     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
528     __ cmpb(queue_active, 0);
529   }
530   __ jcc(Assembler::equal, L_done);
531 
532   // Can we store original value in the thread's buffer?
533 
534   __ movptr(tmp, queue_index);
535   __ testptr(tmp, tmp);
536   __ jccb(Assembler::zero, L_runtime);
537   __ subptr(tmp, wordSize);
538   __ movptr(queue_index, tmp);
539   __ addptr(tmp, buffer);
540 
541   // prev_val (rax)
542   __ load_parameter(0, pre_val);
543   __ movptr(Address(tmp, 0), pre_val);
544   __ jmp(L_done);
545 
546   __ bind(L_runtime);
547 
548   __ push_call_clobbered_registers();
549 
550   // load the pre-value
551   __ load_parameter(0, rcx);
552   __ call_VM_leaf(CAST_FROM_FN_PTR(address, G1BarrierSetRuntime::write_ref_field_pre_entry), rcx, thread);
553 
554   __ pop_call_clobbered_registers();
555 
556   __ bind(L_done);
557 
558   __ pop_ppx(rdx);
559   __ pop_ppx(rax);
560 
561   __ epilogue();
562 }
563 
564 #undef __
565 
566 #endif // COMPILER1