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