1 /*
   2  * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2018, 2021, Red Hat, Inc. All rights reserved.
   4  * Copyright Amazon.com Inc. or its affiliates. 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/interpreter.hpp"
  37 #include "nativeInst_x86.hpp"
  38 #include "runtime/javaThread.hpp"
  39 #include "runtime/sharedRuntime.hpp"
  40 #include "utilities/macros.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, BasicType type,
  54                                                        Register src, Register dst, Register count) {
  55 
  56   bool dest_uninitialized = (decorators & IS_DEST_UNINITIALIZED) != 0;
  57 
  58   if (is_reference_type(type)) {
  59     if (ShenandoahCardBarrier) {
  60       bool checkcast = (decorators & ARRAYCOPY_CHECKCAST) != 0;
  61       bool disjoint = (decorators & ARRAYCOPY_DISJOINT) != 0;
  62       bool obj_int = (type == T_OBJECT) && UseCompressedOops;
  63 
  64       // We need to save the original element count because the array copy stub
  65       // will destroy the value and we need it for the card marking barrier.
  66       if (!checkcast) {
  67         if (!obj_int) {
  68           // Save count for barrier
  69           __ movptr(r11, count);
  70         } else if (disjoint) {
  71           // Save dst in r11 in the disjoint case
  72           __ movq(r11, dst);
  73         }
  74       }
  75     }
  76 
  77     if ((ShenandoahSATBBarrier && !dest_uninitialized) || ShenandoahLoadRefBarrier) {
  78       Register thread = r15_thread;
  79       assert_different_registers(src, dst, count, thread);
  80 
  81       Label L_done;
  82       // Short-circuit if count == 0.
  83       __ testptr(count, count);
  84       __ jcc(Assembler::zero, L_done);
  85 
  86       // Avoid runtime call when not active.
  87       Address gc_state(thread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
  88       int flags;
  89       if (ShenandoahSATBBarrier && dest_uninitialized) {
  90         flags = ShenandoahHeap::HAS_FORWARDED;
  91       } else {
  92         flags = ShenandoahHeap::HAS_FORWARDED | ShenandoahHeap::MARKING;
  93       }
  94       __ testb(gc_state, flags);
  95       __ jcc(Assembler::zero, L_done);
  96 
  97       __ push_call_clobbered_registers(/* save_fpu = */ false);
  98       // If arguments are not in proper places, shuffle them.
  99       // Doing this via the stack is the most straight-forward way to avoid
 100       // accidentally smashing any register.
 101       if (c_rarg0 != src || c_rarg1 != dst || c_rarg2 != count) {
 102         __ push(src);
 103         __ push(dst);
 104         __ push(count);
 105         __ pop(c_rarg2);
 106         __ pop(c_rarg1);
 107         __ pop(c_rarg0);
 108       }
 109       address target = nullptr;
 110       if (UseCompressedOops) {
 111         target = CAST_FROM_FN_PTR(address, ShenandoahRuntime::arraycopy_barrier_narrow_oop);
 112       } else {
 113         target = CAST_FROM_FN_PTR(address, ShenandoahRuntime::arraycopy_barrier_oop);
 114       }
 115       __ call_VM_leaf(target, 3);
 116 
 117       __ pop_call_clobbered_registers(/* restore_fpu = */ false);
 118 
 119       __ bind(L_done);
 120     }
 121   }
 122 
 123 }
 124 
 125 void ShenandoahBarrierSetAssembler::arraycopy_epilogue(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
 126                                                        Register src, Register dst, Register count) {
 127 
 128   if (ShenandoahCardBarrier && is_reference_type(type)) {
 129     bool checkcast = (decorators & ARRAYCOPY_CHECKCAST) != 0;
 130     bool disjoint = (decorators & ARRAYCOPY_DISJOINT) != 0;
 131     bool obj_int = (type == T_OBJECT) && UseCompressedOops;
 132     Register tmp = rax;
 133 
 134     if (!checkcast) {
 135       if (!obj_int) {
 136         // Save count for barrier
 137         count = r11;
 138       } else if (disjoint) {
 139         // Use the saved dst in the disjoint case
 140         dst = r11;
 141       }
 142     } else {
 143       tmp = rscratch1;
 144     }
 145     gen_write_ref_array_post_barrier(masm, decorators, dst, count, tmp);
 146   }
 147 }
 148 
 149 void ShenandoahBarrierSetAssembler::satb_barrier(MacroAssembler* masm,
 150                                                  Register obj,
 151                                                  Register pre_val,
 152                                                  Register tmp) {
 153   assert(ShenandoahSATBBarrier, "Should be checked by caller");
 154   const Register thread = r15_thread;
 155 
 156   Label done;
 157   Label runtime;
 158 
 159   assert(pre_val != noreg, "check this code");
 160   assert_different_registers(obj, pre_val, tmp);
 161 
 162   Address index(thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset()));
 163   Address buffer(thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset()));
 164 
 165   Address gc_state(thread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 166   __ testb(gc_state, ShenandoahHeap::MARKING);
 167   __ jcc(Assembler::zero, done);
 168 
 169   // Do we need to load the previous value?
 170   if (obj != noreg) {
 171     if (UseCompressedOops) {
 172       __ movl(pre_val, Address(obj, 0));
 173       __ decode_heap_oop(pre_val);
 174     } else {
 175       __ movq(pre_val, Address(obj, 0));
 176     }
 177   }
 178 
 179   // Is the previous value null?
 180   __ cmpptr(pre_val, NULL_WORD);
 181   __ jcc(Assembler::equal, done);
 182 
 183   // Can we store original value in the thread's buffer?
 184   // Is index == 0?
 185   // (The index field is typed as size_t.)
 186 
 187   __ movptr(tmp, index);                   // tmp := *index_adr
 188   __ cmpptr(tmp, 0);                       // tmp == 0?
 189   __ jcc(Assembler::equal, runtime);       // If yes, goto runtime
 190 
 191   __ subptr(tmp, wordSize);                // tmp := tmp - wordSize
 192   __ movptr(index, tmp);                   // *index_adr := tmp
 193   __ addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
 194 
 195   // Record the previous value
 196   __ movptr(Address(tmp, 0), pre_val);
 197   __ jmp(done);
 198 
 199   __ bind(runtime);
 200 
 201   // Slow-path call.
 202   // Some paths can be reached from the c2i adapter with live fp arguments in registers.
 203   __ enter();
 204   __ push_call_clobbered_registers(/* save_fpu = */ true);
 205 
 206   assert(thread != c_rarg0, "smashed arg");
 207   if (c_rarg0 != pre_val) {
 208     __ mov(c_rarg0, pre_val);
 209   }
 210 
 211   // Calling with super_call_VM_leaf with c_rarg0 bypasses interpreter checks and avoids any moves.
 212   __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_barrier_pre), c_rarg0);
 213 
 214   __ pop_call_clobbered_registers(/* restore_fpu = */ true);
 215   __ leave();
 216 
 217   __ bind(done);
 218 }
 219 
 220 void ShenandoahBarrierSetAssembler::load_reference_barrier(MacroAssembler* masm, Register dst, Address src, DecoratorSet decorators) {
 221   assert(ShenandoahLoadRefBarrier, "Should be enabled");
 222 
 223   bool is_strong  = ShenandoahBarrierSet::is_strong_access(decorators);
 224   bool is_weak    = ShenandoahBarrierSet::is_weak_access(decorators);
 225   bool is_phantom = ShenandoahBarrierSet::is_phantom_access(decorators);
 226   bool is_native  = ShenandoahBarrierSet::is_native_access(decorators);
 227   bool is_narrow  = UseCompressedOops && !is_native;
 228 
 229   Label heap_stable, not_cset;
 230 
 231   __ block_comment("load_reference_barrier { ");
 232 
 233   // Check if GC is active
 234   Register thread = r15_thread;
 235 
 236   Address gc_state(thread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 237   int flags = ShenandoahHeap::HAS_FORWARDED;
 238   if (!is_strong) {
 239     flags |= ShenandoahHeap::WEAK_ROOTS;
 240   }
 241   __ testb(gc_state, flags);
 242   __ jcc(Assembler::zero, heap_stable);
 243 
 244   Register tmp1 = noreg, tmp2 = noreg;
 245   if (is_strong) {
 246     // Test for object in cset
 247     // Allocate temporary registers
 248     for (int i = 0; i < Register::available_gp_registers(); i++) {
 249       Register r = as_Register(i);
 250       if (r != rsp && r != rbp && r != rcx && r != dst && r != src.base() && r != src.index() ) {
 251         if (tmp1 == noreg) {
 252           tmp1 = r;
 253         } else {
 254           tmp2 = r;
 255           break;
 256         }
 257       }
 258     }
 259     assert(tmp1 != noreg, "tmp1 allocated");
 260     assert(tmp2 != noreg, "tmp2 allocated");
 261     assert_different_registers(tmp1, tmp2, src.base(), src.index());
 262     assert_different_registers(tmp1, tmp2, dst);
 263 
 264     __ push(tmp1);
 265     __ push(tmp2);
 266 
 267     // Optimized cset-test
 268     __ movptr(tmp1, dst);
 269     if (AOTCodeCache::is_on_for_dump()) {
 270       assert_different_registers(tmp1, tmp2, rcx);
 271       __ lea(tmp2, ExternalAddress(AOTRuntimeConstants::grain_shift_address()));
 272       __ push(rcx);
 273       __ movb(rcx, Address(tmp2));
 274       __ shrptr(tmp1);
 275       __ pop(rcx);
 276       __ lea(tmp2, ExternalAddress(AOTRuntimeConstants::cset_base_address()));
 277       __ movptr(tmp2, Address(tmp2));
 278     } else {
 279       __ shrptr(tmp1, ShenandoahHeapRegion::region_size_bytes_shift_jint());
 280       __ movptr(tmp2, (intptr_t) ShenandoahHeap::in_cset_fast_test_addr());
 281     }
 282     __ movbool(tmp1, Address(tmp1, tmp2, Address::times_1));
 283     __ testbool(tmp1);
 284     __ jcc(Assembler::zero, not_cset);
 285   }
 286 
 287   // Slow-path call.
 288   // Save registers that can be clobbered by call.
 289   // Some paths can be reached from the c2i adapter with live fp arguments in registers.
 290   __ enter();
 291   if (dst != rax) {
 292     __ push(rax);
 293   }
 294   __ push_call_clobbered_registers_except(rax, /* save_fpu = */ true);
 295 
 296   // Shuffle registers such that dst is in c_rarg0 and addr in c_rarg1.
 297   if (dst == c_rarg1) {
 298     __ lea(c_rarg0, src);
 299     __ xchgptr(c_rarg1, c_rarg0);
 300   } else {
 301     __ lea(c_rarg1, src);
 302     __ movptr(c_rarg0, dst);
 303   }
 304 
 305   address target = nullptr;
 306   if (is_strong) {
 307     if (is_narrow) {
 308       target = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong_narrow);
 309     } else {
 310       target = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong);
 311     }
 312   } else if (is_weak) {
 313     if (is_narrow) {
 314       target = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak_narrow);
 315     } else {
 316       target = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak);
 317     }
 318   } else {
 319     assert(is_phantom, "only remaining strength");
 320     assert(!is_narrow, "phantom access cannot be narrow");
 321     target = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom);
 322   }
 323 
 324   // Calling with super_call_VM_leaf with c_rarg0/1 bypasses interpreter checks and avoids any moves.
 325   __ super_call_VM_leaf(target, c_rarg0, c_rarg1);
 326   __ pop_call_clobbered_registers_except(rax, /* restore_fpu = */ true);
 327   if (dst != rax) {
 328     __ movptr(dst, rax);
 329     __ pop(rax);
 330   }
 331   __ leave();
 332 
 333   __ bind(not_cset);
 334 
 335   if  (is_strong) {
 336     __ pop(tmp2);
 337     __ pop(tmp1);
 338   }
 339 
 340   __ bind(heap_stable);
 341 
 342   __ block_comment("} load_reference_barrier");
 343 }
 344 
 345 //
 346 // Arguments:
 347 //
 348 // Inputs:
 349 //   src:        oop location, might be clobbered
 350 //   tmp1:       scratch register, might not be valid.
 351 //
 352 // Output:
 353 //   dst:        oop loaded from src location
 354 //
 355 // Kill:
 356 //   tmp1 (if it is valid)
 357 //
 358 void ShenandoahBarrierSetAssembler::load_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
 359              Register dst, Address src, Register tmp1) {
 360   // 1: non-reference load, no additional barrier is needed
 361   if (!is_reference_type(type)) {
 362     BarrierSetAssembler::load_at(masm, decorators, type, dst, src, tmp1);
 363     return;
 364   }
 365 
 366   assert((decorators & ON_UNKNOWN_OOP_REF) == 0, "Not expected");
 367 
 368   // 2: load a reference from src location and apply LRB if needed
 369   if (ShenandoahBarrierSet::need_load_reference_barrier(decorators, type)) {
 370     Register result_dst = dst;
 371     bool use_tmp1_for_dst = false;
 372 
 373     // Preserve src location for LRB
 374     if (dst == src.base() || dst == src.index()) {
 375     // Use tmp1 for dst if possible, as it is not used in BarrierAssembler::load_at()
 376       if (tmp1->is_valid() && tmp1 != src.base() && tmp1 != src.index()) {
 377         dst = tmp1;
 378         use_tmp1_for_dst = true;
 379       } else {
 380         dst = rdi;
 381         __ push(dst);
 382       }
 383       assert_different_registers(dst, src.base(), src.index());
 384     }
 385 
 386     BarrierSetAssembler::load_at(masm, decorators, type, dst, src, tmp1);
 387 
 388     load_reference_barrier(masm, dst, src, decorators);
 389 
 390     // Move loaded oop to final destination
 391     if (dst != result_dst) {
 392       __ movptr(result_dst, dst);
 393 
 394       if (!use_tmp1_for_dst) {
 395         __ pop(dst);
 396       }
 397 
 398       dst = result_dst;
 399     }
 400   } else {
 401     BarrierSetAssembler::load_at(masm, decorators, type, dst, src, tmp1);
 402   }
 403 
 404   // 3: apply keep-alive barrier if needed
 405   if (ShenandoahBarrierSet::need_keep_alive_barrier(decorators, type)) {
 406     satb_barrier(masm /* masm */,
 407                  noreg /* obj */,
 408                  dst /* pre_val */,
 409                  tmp1 /* tmp */);
 410   }
 411 }
 412 
 413 void ShenandoahBarrierSetAssembler::card_barrier(MacroAssembler* masm, Register obj, Register tmp) {
 414   assert(ShenandoahCardBarrier, "Should have been checked by caller");
 415   assert_different_registers(obj, tmp);
 416 
 417   // Does a store check for the oop in register obj. The content of
 418   // register obj is destroyed afterwards.
 419   __ shrptr(obj, CardTable::card_shift());
 420 
 421   Address curr_ct_holder_addr(r15_thread, in_bytes(ShenandoahThreadLocalData::card_table_offset()));
 422   __ movptr(tmp, curr_ct_holder_addr);
 423   Address card_addr(tmp, obj, Address::times_1);
 424 
 425   int dirty = CardTable::dirty_card_val();
 426   if (UseCondCardMark) {
 427     Label L_already_dirty;
 428     __ cmpb(card_addr, dirty);
 429     __ jccb(Assembler::equal, L_already_dirty);
 430     __ movb(card_addr, dirty);
 431     __ bind(L_already_dirty);
 432   } else {
 433     __ movb(card_addr, dirty);
 434   }
 435 }
 436 
 437 void ShenandoahBarrierSetAssembler::store_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
 438               Address dst, Register val, Register tmp1, Register tmp2, Register tmp3) {
 439 
 440   // 1: non-reference types require no barriers
 441   if (!is_reference_type(type)) {
 442     BarrierSetAssembler::store_at(masm, decorators, type, dst, val, tmp1, tmp2, tmp3);
 443     return;
 444   }
 445 
 446   // Flatten object address right away for simplicity: likely needed by barriers
 447   assert_different_registers(val, tmp1, tmp2, tmp3, r15_thread);
 448   if (dst.index() == noreg && dst.disp() == 0) {
 449     if (dst.base() != tmp1) {
 450       __ movptr(tmp1, dst.base());
 451     }
 452   } else {
 453     __ lea(tmp1, dst);
 454   }
 455 
 456   // 2: pre-barrier: SATB needs the previous value
 457   if (ShenandoahBarrierSet::need_satb_barrier(decorators, type)) {
 458     satb_barrier(masm,
 459                  tmp1 /* obj */,
 460                  tmp2 /* pre_val */,
 461                  tmp3 /* tmp */);
 462   }
 463 
 464   // Store!
 465   BarrierSetAssembler::store_at(masm, decorators, type, Address(tmp1, 0), val, noreg, noreg, noreg);
 466 
 467   // 3: post-barrier: card barrier needs store address
 468   bool storing_non_null = (val != noreg);
 469   if (ShenandoahBarrierSet::need_card_barrier(decorators, type) && storing_non_null) {
 470     card_barrier(masm, tmp1, tmp2);
 471   }
 472 }
 473 
 474 void ShenandoahBarrierSetAssembler::try_resolve_jobject_in_native(MacroAssembler* masm, Register jni_env,
 475                                                                   Register obj, Register tmp, Label& slowpath) {
 476   Label done;
 477   // Resolve jobject
 478   BarrierSetAssembler::try_resolve_jobject_in_native(masm, jni_env, obj, tmp, slowpath);
 479 
 480   // Check for null.
 481   __ testptr(obj, obj);
 482   __ jcc(Assembler::zero, done);
 483 
 484   Address gc_state(jni_env, ShenandoahThreadLocalData::gc_state_offset() - JavaThread::jni_environment_offset());
 485   __ testb(gc_state, ShenandoahHeap::EVACUATION);
 486   __ jccb(Assembler::notZero, slowpath);
 487   __ bind(done);
 488 }
 489 
 490 void ShenandoahBarrierSetAssembler::try_peek_weak_handle_in_nmethod(MacroAssembler* masm, Register weak_handle, Register obj, Label& slowpath) {
 491   Label done;
 492 
 493   // Peek weak handle using the standard implementation.
 494   BarrierSetAssembler::try_peek_weak_handle_in_nmethod(masm, weak_handle, obj, slowpath);
 495 
 496   // Check if the reference is null, and if it is, take the fast path.
 497   __ testptr(obj, obj);
 498   __ jcc(Assembler::zero, done);
 499 
 500   Address gc_state(r15_thread, ShenandoahThreadLocalData::gc_state_offset());
 501 
 502   // Check if the heap is under weak-reference/roots processing, in
 503   // which case we need to take the slow path.
 504   __ testb(gc_state, ShenandoahHeap::WEAK_ROOTS);
 505   __ jcc(Assembler::notZero, slowpath);
 506   __ bind(done);
 507 }
 508 
 509 void ShenandoahBarrierSetAssembler::check_oop(MacroAssembler* masm, Register obj, Register tmp1, Register tmp2, Label& L_error) {
 510   // Check if the oop is in the right area of memory
 511   __ movptr(tmp1, obj);
 512   __ movptr(tmp2, (intptr_t) Universe::verify_oop_mask());
 513   __ andptr(tmp1, tmp2);
 514   __ movptr(tmp2, (intptr_t) Universe::verify_oop_bits());
 515   __ cmpptr(tmp1, tmp2);
 516   __ jcc(Assembler::notZero, L_error);
 517 
 518   // This routine is sometimes called before applying GC barriers.
 519   // With +COH, loading the klass may end up loading forwarding pointer instead.
 520   Label L_skip;
 521   if (UseCompactObjectHeaders) {
 522     Address gc_state(r15_thread, ShenandoahThreadLocalData::gc_state_offset());
 523     __ testb(gc_state, ShenandoahHeap::HAS_FORWARDED);
 524     __ jcc(Assembler::notZero, L_skip);
 525   }
 526 
 527   // Make sure klass is 'reasonable', which is not zero.
 528   __ load_narrow_klass(tmp1, obj);
 529   __ testl(tmp1, tmp1);
 530   __ jcc(Assembler::zero, L_error);
 531 
 532   __ bind(L_skip);
 533 }
 534 
 535 #ifdef PRODUCT
 536 #define BLOCK_COMMENT(str) /* nothing */
 537 #else
 538 #define BLOCK_COMMENT(str) __ block_comment(str)
 539 #endif
 540 
 541 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
 542 
 543 #define TIMES_OOP (UseCompressedOops ? Address::times_4 : Address::times_8)
 544 
 545 void ShenandoahBarrierSetAssembler::gen_write_ref_array_post_barrier(MacroAssembler* masm, DecoratorSet decorators,
 546                                                                      Register addr, Register count,
 547                                                                      Register tmp) {
 548   assert(ShenandoahCardBarrier, "Should have been checked by caller");
 549 
 550   Label L_loop, L_done;
 551   const Register end = count;
 552   assert_different_registers(addr, end);
 553 
 554   // Zero count? Nothing to do.
 555   __ testl(count, count);
 556   __ jccb(Assembler::zero, L_done);
 557 
 558   const Register thread = r15_thread;
 559   Address curr_ct_holder_addr(thread, in_bytes(ShenandoahThreadLocalData::card_table_offset()));
 560   __ movptr(tmp, curr_ct_holder_addr);
 561 
 562   __ leaq(end, Address(addr, count, TIMES_OOP, 0));  // end == addr+count*oop_size
 563   __ subptr(end, BytesPerHeapOop); // end - 1 to make inclusive
 564   __ shrptr(addr, CardTable::card_shift());
 565   __ shrptr(end, CardTable::card_shift());
 566   __ subptr(end, addr); // end --> cards count
 567 
 568   __ addptr(addr, tmp);
 569 
 570   __ BIND(L_loop);
 571   __ movb(Address(addr, count, Address::times_1), 0);
 572   __ decrement(count);
 573   __ jccb(Assembler::greaterEqual, L_loop);
 574 
 575   __ BIND(L_done);
 576 }
 577 
 578 #undef __
 579 
 580 address ShenandoahBarrierSetAssembler::parse_jump_address(address pc) {
 581   NativeInstruction* ni = nativeInstruction_at(pc);
 582   assert(ni->is_jump(), "Must be a jump");
 583   NativeJump* jmp = nativeJump_at(pc);
 584   return jmp->jump_destination();
 585 }
 586 
 587 void ShenandoahBarrierSetAssembler::insert_patchable_nop(address pc) {
 588   *(pc + 0) = 0x0F;
 589   *(pc + 1) = 0x1F;
 590   *(pc + 2) = 0x44;
 591   *(pc + 3) = 0x00;
 592   *(pc + 4) = 0x00;
 593 }
 594 
 595 bool ShenandoahBarrierSetAssembler::is_patchable_nop(address pc) {
 596   if (*(pc + 0) != 0x0F) return false;
 597   if (*(pc + 1) != 0x1F) return false;
 598   if (*(pc + 2) != 0x44) return false;
 599   if (*(pc + 3) != 0x00) return false;
 600   if (*(pc + 4) != 0x00) return false;
 601   return true;
 602 }
 603 
 604 void ShenandoahBarrierSetAssembler::insert_patchable_jump(address pc, address target_pc) {
 605   int32_t disp = checked_cast<int32_t>((intptr_t)target_pc - ((intptr_t)pc + 5));
 606 
 607   *(pc + 0) = 0xE9;
 608   *(pc + 1) = (disp >>  0) & 0xFF;
 609   *(pc + 2) = (disp >>  8) & 0xFF;
 610   *(pc + 3) = (disp >> 16) & 0xFF;
 611   *(pc + 4) = (disp >> 24) & 0xFF;
 612 }
 613 
 614 bool ShenandoahBarrierSetAssembler::is_patchable_jump(address pc, address target_pc) {
 615   int32_t disp = checked_cast<int32_t>((intptr_t)target_pc - ((intptr_t)pc + 5));
 616 
 617   if (*(pc + 0) != 0xE9) return false;
 618   if (*(pc + 1) != ((disp >>  0) & 0xFF)) return false;
 619   if (*(pc + 2) != ((disp >>  8) & 0xFF)) return false;
 620   if (*(pc + 3) != ((disp >> 16) & 0xFF)) return false;
 621   if (*(pc + 4) != ((disp >> 24) & 0xFF)) return false;
 622   return true;
 623 }
 624 
 625 #ifdef COMPILER1
 626 
 627 #define __ ce->masm()->
 628 
 629 void ShenandoahBarrierSetAssembler::keepalive_barrier_c1_stub(LIR_Assembler* ce, ShenandoahKeepaliveBarrierStub* stub) {
 630   __ bind(*stub->entry());
 631 
 632   ShenandoahBarrierSetC1* bs = (ShenandoahBarrierSetC1*)BarrierSet::barrier_set()->barrier_set_c1();
 633 
 634   Register obj = stub->obj()->as_register();
 635 
 636   if (stub->do_load()) {
 637     ce->mem2reg(stub->addr(), stub->obj(), T_OBJECT, lir_patch_none, nullptr, /* wide = */ false);
 638   }
 639   __ cmpptr(obj, NULL_WORD);
 640   __ jcc(Assembler::equal, *stub->continuation());
 641 
 642   ce->store_parameter(obj, 0);
 643   __ call(RuntimeAddress(bs->keepalive_barrier_stub()));
 644   __ jmp(*stub->continuation());
 645 }
 646 
 647 void ShenandoahBarrierSetAssembler::load_reference_barrier_c1_stub(LIR_Assembler* ce, ShenandoahLoadReferenceBarrierStub* stub) {
 648   __ bind(*stub->entry());
 649 
 650   ShenandoahBarrierSetC1* bs = (ShenandoahBarrierSetC1*)BarrierSet::barrier_set()->barrier_set_c1();
 651 
 652   Register obj = stub->obj()->as_register();
 653   Register addr = stub->addr()->as_pointer_register();
 654   Register slow_result = stub->slow_result()->as_register();
 655   assert_different_registers(obj, addr, slow_result);
 656   assert(slow_result == rax, "C1 must know about our slow call result register");
 657 
 658   ce->store_parameter(obj, 0);
 659   ce->store_parameter(addr, 1);
 660   __ call(RuntimeAddress(bs->load_reference_barrier_stub(stub->decorators())));
 661   if (obj != slow_result) {
 662     __ mov(obj, slow_result);
 663   }
 664 
 665   __ jmp(*stub->continuation());
 666 }
 667 
 668 #undef __
 669 
 670 #define __ sasm->
 671 
 672 void ShenandoahBarrierSetAssembler::keepalive_barrier_c1_runtime_stub(StubAssembler* sasm) {
 673   __ prologue("shenandoah_keepalive_barrier", false);
 674   const Register tmp_obj = rax;
 675   const Register tmp = rdx;
 676   __ push(tmp);
 677   __ push(tmp_obj);
 678   __ load_parameter(0, tmp_obj);
 679   satb_barrier(sasm, noreg, tmp_obj, tmp);
 680   __ pop(tmp_obj);
 681   __ pop(tmp);
 682   __ epilogue();
 683 }
 684 
 685 void ShenandoahBarrierSetAssembler::load_reference_barrier_c1_runtime_stub(StubAssembler* sasm, DecoratorSet decorators) {
 686   __ prologue("shenandoah_load_reference_barrier", false);
 687   const Register tmp_obj = rax;
 688   const Register tmp_addr = rdx;
 689   __ push(tmp_addr);
 690   __ load_parameter(0, tmp_obj);
 691   __ load_parameter(1, tmp_addr);
 692   load_reference_barrier(sasm, tmp_obj, Address(tmp_addr, 0), decorators);
 693   __ pop(tmp_addr);
 694   __ epilogue();
 695 }
 696 
 697 #undef __
 698 
 699 #endif // COMPILER1
 700 
 701 #ifdef COMPILER2
 702 
 703 #undef __
 704 #define __ masm->
 705 
 706 void ShenandoahBarrierSetAssembler::load_c2(const MachNode* node, MacroAssembler* masm, Register dst, Address src, bool narrow) {
 707   // Do the actual load. This load is the candidate for implicit null check, and MUST come first.
 708   if (narrow) {
 709     __ movl(dst, src);
 710   } else {
 711     __ movq(dst, src);
 712   }
 713 
 714   ShenandoahBarrierStubC2::load_post(masm, node, dst, src, noreg, noreg, narrow);
 715 }
 716 
 717 void ShenandoahBarrierSetAssembler::store_c2(const MachNode* node, MacroAssembler* masm,
 718                                              Address dst, bool dst_narrow,
 719                                              Register src, bool src_narrow,
 720                                              Register tmp) {
 721 
 722   ShenandoahBarrierStubC2::store_pre(masm, node, dst, tmp, noreg, noreg, dst_narrow);
 723 
 724   // Need to encode into tmp, because we cannot clobber src.
 725   if (dst_narrow && !src_narrow) {
 726     __ movq(tmp, src);
 727     if ((node->barrier_data() & ShenandoahBitNotNull) == 0) {
 728       __ encode_heap_oop(tmp);
 729     } else {
 730       __ encode_heap_oop_not_null(tmp);
 731     }
 732     src = tmp;
 733   }
 734 
 735   // Do the actual store
 736   if (dst_narrow) {
 737     __ movl(dst, src);
 738   } else {
 739     __ movq(dst, src);
 740   }
 741 
 742   ShenandoahBarrierStubC2::store_post(masm, node, dst, tmp, noreg);
 743 }
 744 
 745 void ShenandoahBarrierSetAssembler::compare_and_set_c2(const MachNode* node, MacroAssembler* masm,
 746                                                        Register res, Address addr,
 747                                                        Register oldval, Register newval, Register tmp,
 748                                                        bool narrow) {
 749 
 750   assert(oldval == rax, "must be in rax for implicit use in cmpxchg");
 751 
 752   // Oldval and newval cannot be clobbered by aliasing with tmp.
 753   assert_different_registers(oldval, tmp);
 754   assert_different_registers(newval, tmp);
 755 
 756   ShenandoahBarrierStubC2::load_store_pre(masm, node, addr, tmp, noreg, noreg, narrow);
 757 
 758   // CAS!
 759   __ lock();
 760   if (narrow) {
 761     __ cmpxchgl(newval, addr);
 762   } else {
 763     __ cmpxchgptr(newval, addr);
 764   }
 765 
 766   // If we need a boolean result out of CAS, set the flag appropriately and promote the result.
 767   if (res != noreg) {
 768     __ setcc(Assembler::equal, res);
 769   }
 770 
 771   ShenandoahBarrierStubC2::load_store_post(masm, node, addr, tmp, noreg);
 772 }
 773 
 774 void ShenandoahBarrierSetAssembler::get_and_set_c2(const MachNode* node, MacroAssembler* masm, Register newval, Address addr, Register tmp, bool narrow) {
 775   assert_different_registers(newval, tmp);
 776 
 777   ShenandoahBarrierStubC2::load_store_pre(masm, node, addr, tmp, noreg, noreg, narrow);
 778 
 779   if (narrow) {
 780     __ xchgl(newval, addr);
 781   } else {
 782     __ xchgq(newval, addr);
 783   }
 784 
 785   ShenandoahBarrierStubC2::load_store_post(masm, node, addr, tmp, noreg);
 786 }
 787 
 788 #undef __
 789 #define __ masm.
 790 
 791 void ShenandoahBarrierStubC2::cardtable(MacroAssembler& masm, Address addr, Register tmp1, Register tmp2) {
 792   Assembler::InlineSkippedInstructionsCounter skip_counter(&masm);
 793 
 794   __ lea(tmp1, addr);
 795   __ shrptr(tmp1, CardTable::card_shift());
 796   __ addptr(tmp1, Address(r15_thread, in_bytes(ShenandoahThreadLocalData::card_table_offset())));
 797   Address card_address(tmp1, 0);
 798 
 799   assert(CardTable::dirty_card_val() == 0, "Encoding assumption");
 800   Label L_done;
 801   if (UseCondCardMark) {
 802     __ cmpb(card_address, 0);
 803     __ jccb(Assembler::equal, L_done);
 804   }
 805   if (UseCompressedOops && CompressedOops::base() == nullptr) {
 806     __ movb(card_address, r12);
 807   } else {
 808     __ movb(card_address, 0);
 809   }
 810   __ bind(L_done);
 811 }
 812 
 813 void ShenandoahBarrierStubC2::patchable_jump(MacroAssembler& masm, const char gc_state, bool jump_when_state, Label* L_target) {
 814   Label L_fake_entry, L_real_entry, L_skip;
 815   Address gc_state_addr(r15_thread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 816 
 817   // Emit the unconditional branch in the first version of the method.
 818   // Let the rest of runtime figure out how to manage it.
 819 
 820   PhaseOutput* const output = Compile::current()->output();
 821   if (!output->in_scratch_emit_size()) {
 822     __ relocate(patchable_barrier_Relocation::spec(ShenandoahNMethod::encode_to_reloc(gc_state, jump_when_state)));
 823   }
 824 
 825 #ifdef ASSERT
 826   // Emit the secondary jump and use it to cross-check against the actual GC state.
 827   // This also checks that all interesting GC state transitions are done non-racily
 828   // from the perspective of the thread executing the nmethod.
 829   __ jmp(L_fake_entry, /* maybe_short = */ false);
 830 
 831   // Currently hot-patched to NOP.
 832   __ testb(gc_state_addr, gc_state);
 833   __ jcc(jump_when_state ? Assembler::zero : Assembler::notZero, L_skip);
 834   __ hlt();
 835 
 836   // Currently hot-patched to JUMP.
 837   __ bind(L_fake_entry);
 838   __ testb(gc_state_addr, gc_state);
 839   __ jcc(jump_when_state ? Assembler::notZero : Assembler::zero, L_real_entry);
 840   __ hlt();
 841 
 842   __ bind(L_real_entry);
 843 #endif
 844 
 845   if (!output->in_scratch_emit_size()) {
 846     __ jmp(*L_target, /* maybe_short = */ false);
 847   } else {
 848     // Avoid binding L_target in scratch emits.
 849     // We know the patchable check is exactly 5 bytes long.
 850     __ nop(5);
 851   }
 852 
 853 #ifdef ASSERT
 854   __ bind(L_skip);
 855 #endif
 856 }
 857 
 858 void ShenandoahBarrierStubC2::enter_if_gc_state(MacroAssembler& masm, const char test_state) {
 859   Assembler::InlineSkippedInstructionsCounter skip_counter(&masm);
 860   patchable_jump_if_gc_state(masm, test_state, entry());
 861   __ bind(*continuation());
 862 }
 863 
 864 
 865 void ShenandoahBarrierStubC2::emit_code(MacroAssembler& masm) {
 866   Assembler::InlineSkippedInstructionsCounter skip_counter(&masm);
 867   assert(_needs_keep_alive_barrier || _needs_load_ref_barrier, "Why are you here?");
 868 
 869   // On x86, there is a significant penalty with unaligned branch target, for example
 870   // when the target instruction straggles the fetch line. It makes (performance) sense
 871   // to spend some code size to align the target better.
 872   __ align(16);
 873   __ bind(*entry());
 874 
 875   // If we need to load ourselves, do it here.
 876   if (_do_load) {
 877     if (_narrow) {
 878       __ movl(_obj, _addr);
 879     } else {
 880       __ movq(_obj, _addr);
 881     }
 882   }
 883 
 884   // If the object is null, there is no point in applying barriers.
 885   maybe_far_jump_if_zero(masm, _obj);
 886 
 887   // We need to make sure that loads done by callers survive across slow-path calls.
 888   // For self-loads, we need to care about the case when both KA and LRB are enabled (rare).
 889   bool needs_both_barriers = _needs_keep_alive_barrier && _needs_load_ref_barrier;
 890   if (!_do_load || needs_both_barriers) {
 891     preserve(_obj);
 892   }
 893 
 894   // Go for barriers. Barriers can return straight to continuation, as long
 895   // as another barrier is not needed.
 896   if (needs_both_barriers) {
 897     keepalive(masm, nullptr);
 898     lrb(masm);
 899   } else if (_needs_keep_alive_barrier) {
 900     keepalive(masm, continuation());
 901   } else if (_needs_load_ref_barrier) {
 902     lrb(masm);
 903   } else {
 904     ShouldNotReachHere();
 905   }
 906 }
 907 
 908 void ShenandoahBarrierStubC2::keepalive(MacroAssembler& masm, Label* L_done) {
 909   Address index(r15_thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset()));
 910   Address buffer(r15_thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset()));
 911 
 912   Label L_through, L_pop_and_slow;
 913 
 914   // If another barrier is enabled as well, do a check for a specific barrier.
 915   if (_needs_load_ref_barrier) {
 916     assert(L_done == nullptr, "Should be");
 917     char state_to_check = ShenandoahHeap::MARKING;
 918     patchable_jump_if_not_gc_state(masm, state_to_check, &L_through);
 919   }
 920 
 921   // Need temp to work, allocate one now.
 922   bool tmp_live;
 923   Register tmp = select_temp_register(tmp_live);
 924   if (tmp_live) {
 925     __ push(tmp);
 926   }
 927 
 928   // Fast-path: put object into buffer.
 929   // If buffer is already full, go slow.
 930   __ movptr(tmp, index);
 931   __ subptr(tmp, wordSize);
 932   __ jccb(Assembler::below, L_pop_and_slow);
 933   __ movptr(index, tmp);
 934   __ addptr(tmp, buffer);
 935 
 936   // Store the object in queue.
 937   // If object is narrow, we need to decode it before inserting.
 938   // We can skip the re-encoding if we know that object is not preserved.
 939   if (_narrow) {
 940     __ decode_heap_oop_not_null(_obj);
 941   }
 942   __ movptr(Address(tmp, 0), _obj);
 943   if (_narrow && is_preserved(_obj)) {
 944     __ encode_heap_oop_not_null(_obj);
 945   }
 946 
 947   // Fast-path exits here.
 948   if (tmp_live) {
 949     __ pop(tmp);
 950   }
 951 
 952   if (L_done != nullptr) {
 953     __ jmp(*L_done);
 954   } else {
 955     __ jmp(L_through);
 956   }
 957 
 958   // Slow-path: call runtime to handle.
 959   // Need to pop tmp immediately for stack to remain aligned.
 960   __ bind(L_pop_and_slow);
 961   if (tmp_live) {
 962     __ pop(tmp);
 963   }
 964   {
 965     SaveLiveRegisters slr(&masm, this);
 966 
 967     // Shuffle in the arguments. The end result should be:
 968     //   c_rarg0 <-- obj
 969     if (c_rarg0 != _obj) {
 970       __ mov(c_rarg0, _obj);
 971     }
 972 
 973     // Go to runtime and handle the rest there.
 974     // Use rax as scratch, as it will be saved if live.
 975     __ call(RuntimeAddress(keepalive_runtime_entry_addr()), rax);
 976   }
 977   if (L_done != nullptr) {
 978     __ jmp(*L_done);
 979   } else {
 980     __ bind(L_through);
 981   }
 982 }
 983 
 984 void ShenandoahBarrierStubC2::lrb(MacroAssembler& masm) {
 985   Label L_pop_and_slow, L_slow;
 986 
 987   // If another barrier is enabled as well, do a check for a specific barrier.
 988   if (_needs_keep_alive_barrier) {
 989     char state_to_check = ShenandoahHeap::HAS_FORWARDED | (_needs_load_ref_weak_barrier ? ShenandoahHeap::WEAK_ROOTS : 0);
 990     patchable_jump_if_not_gc_state(masm, state_to_check, continuation());
 991   }
 992 
 993   // If weak references are being processed, weak/phantom loads need to go slow,
 994   // regardless of their cset status.
 995   if (_needs_load_ref_weak_barrier) {
 996     char state_to_check = ShenandoahHeap::WEAK_ROOTS;
 997     patchable_jump_if_gc_state(masm, state_to_check, &L_slow);
 998   }
 999 
1000   bool is_aot = AOTCodeCache::is_on_for_dump();
1001 
1002   // Need temp to work, allocate one now.
1003   bool tmp_live;
1004   Register tmp = select_temp_register(tmp_live, /* skip_reg1 = */ is_aot ? rcx : noreg);
1005   if (tmp_live) {
1006     __ push(tmp);
1007   }
1008 
1009   // Compute the cset bitmap index
1010   if (_narrow) {
1011     __ decode_heap_oop_not_null(tmp, _obj);
1012   } else {
1013     __ movptr(tmp, _obj);
1014   }
1015 
1016   Address cset_addr_arg;
1017   intptr_t cset_addr = reinterpret_cast<intptr_t>(ShenandoahHeap::in_cset_fast_test_addr());
1018   if (!is_aot && cset_addr < INT32_MAX) {
1019     // Cset bitmap is at easily encodeable address. Just use it as displacement.
1020     __ shrptr(tmp, ShenandoahHeapRegion::region_size_bytes_shift_jint());
1021     cset_addr_arg = Address(tmp, checked_cast<int>(cset_addr));
1022   } else {
1023     bool tmp2_live;
1024     Register tmp2 = select_temp_register(tmp2_live, /* skip_reg1 = */ tmp, /* skip_reg2 = */ is_aot ? rcx : noreg);
1025     if (tmp2_live) {
1026       __ push(tmp2);
1027     }
1028     if (is_aot) {
1029       // Generating AOT code, pull the cset bitmap and region shift from AOT table.
1030       assert_different_registers(tmp, tmp2, rcx);
1031       __ push(rcx);
1032       __ lea(rcx, ExternalAddress(AOTRuntimeConstants::grain_shift_address()));
1033       __ movl(rcx, Address(rcx));
1034       __ shrptr(tmp);
1035       __ pop(rcx);
1036       __ lea(tmp2, ExternalAddress(AOTRuntimeConstants::cset_base_address()));
1037       __ addptr(tmp, Address(tmp2));
1038     } else {
1039       // Cset bitmap is far away. Add its address fully.
1040       __ shrptr(tmp, ShenandoahHeapRegion::region_size_bytes_shift_jint());
1041       __ movptr(tmp2, cset_addr);
1042       __ addptr(tmp, tmp2);
1043     }
1044     if (tmp2_live) {
1045       __ pop(tmp2);
1046     }
1047     cset_addr_arg = Address(tmp, 0);
1048   }
1049 
1050   // Cset-check. Fall-through to slow if in collection set.
1051   __ cmpb(cset_addr_arg, 0);
1052   if (tmp_live) {
1053     __ jccb(Assembler::notEqual, L_pop_and_slow);
1054     __ pop(tmp);
1055     __ jmp(*continuation());
1056   } else {
1057     // Nothing else to do, jump back
1058     __ jcc(Assembler::equal, *continuation());
1059   }
1060 
1061   // Slow path
1062   __ bind(L_pop_and_slow);
1063   // Need to pop tmp immediately for stack to remain aligned.
1064   if (tmp_live) {
1065     __ pop(tmp);
1066   }
1067   __ bind(L_slow);
1068 
1069   // Obj is the result, need to temporarily stop preserving it.
1070   bool is_obj_preserved = is_preserved(_obj);
1071   if (is_obj_preserved) {
1072     dont_preserve(_obj);
1073   }
1074   {
1075     SaveLiveRegisters slr(&masm, this);
1076 
1077     assert_different_registers(rax, c_rarg0, c_rarg1);
1078 
1079     // Shuffle in the arguments. The end result should be:
1080     //   c_rarg0 <-- obj
1081     //   c_rarg1 <-- lea(addr)
1082     if (_obj == c_rarg0) {
1083       __ lea(c_rarg1, _addr);
1084     } else if (_obj == c_rarg1) {
1085       // Set up arguments in reverse, and then flip them
1086       __ lea(c_rarg0, _addr);
1087       __ xchgptr(c_rarg0, c_rarg1);
1088     } else {
1089       assert_different_registers(_obj, c_rarg0, c_rarg1);
1090       __ lea(c_rarg1, _addr);
1091       __ movptr(c_rarg0, _obj);
1092     }
1093 
1094     // Go to runtime and handle the rest there.
1095     // Use rax as scratch, as it will be clobbered by result anyway.
1096     __ call(RuntimeAddress(lrb_runtime_entry_addr()), rax);
1097 
1098     // Save the result where needed.
1099     if (_narrow) {
1100       __ movl(_obj, rax);
1101     } else if (_obj != rax) {
1102       __ movptr(_obj, rax);
1103     }
1104   }
1105   if (is_obj_preserved) {
1106     preserve(_obj);
1107   }
1108 
1109   __ jmp(*continuation());
1110 }
1111 
1112 int ShenandoahBarrierStubC2::available_gp_registers() {
1113   return Register::available_gp_registers();
1114 }
1115 
1116 bool ShenandoahBarrierStubC2::is_special_register(Register r) {
1117   return r == rsp || r == rbp || r == r12_heapbase || r == r15_thread;
1118 }
1119 
1120 void ShenandoahBarrierStubC2::post_init() {
1121   // Do nothing.
1122 }
1123 
1124 void ShenandoahBarrierStubC2::maybe_far_jump_if_zero(MacroAssembler& masm, Register reg) {
1125   if (_narrow) {
1126     __ testl(reg, reg);
1127   } else {
1128     __ testq(reg, reg);
1129   }
1130   __ jcc(Assembler::zero, *continuation());
1131 }
1132 
1133 #endif // COMPILER2