1 /*
   2  * Copyright (c) 2018, 2023, Red Hat, Inc. All rights reserved.
   3  * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 #include "classfile/javaClasses.hpp"
  28 #include "gc/shared/barrierSet.hpp"
  29 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
  30 #include "gc/shenandoah/shenandoahForwarding.hpp"
  31 #include "gc/shenandoah/shenandoahHeap.hpp"
  32 #include "gc/shenandoah/shenandoahRuntime.hpp"
  33 #include "gc/shenandoah/shenandoahThreadLocalData.hpp"
  34 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
  35 #include "gc/shenandoah/c2/shenandoahSupport.hpp"
  36 #include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
  37 #include "gc/shenandoah/mode/shenandoahMode.hpp"
  38 #include "opto/arraycopynode.hpp"
  39 #include "opto/escape.hpp"
  40 #include "opto/graphKit.hpp"
  41 #include "opto/idealKit.hpp"
  42 #include "opto/macro.hpp"
  43 #include "opto/movenode.hpp"
  44 #include "opto/narrowptrnode.hpp"
  45 #include "opto/rootnode.hpp"
  46 #include "opto/runtime.hpp"
  47 
  48 ShenandoahBarrierSetC2* ShenandoahBarrierSetC2::bsc2() {
  49   return reinterpret_cast<ShenandoahBarrierSetC2*>(BarrierSet::barrier_set()->barrier_set_c2());
  50 }
  51 
  52 ShenandoahBarrierSetC2State::ShenandoahBarrierSetC2State(Arena* comp_arena)
  53   : _iu_barriers(new (comp_arena) GrowableArray<ShenandoahIUBarrierNode*>(comp_arena, 8,  0, nullptr)),
  54     _load_reference_barriers(new (comp_arena) GrowableArray<ShenandoahLoadReferenceBarrierNode*>(comp_arena, 8,  0, nullptr)) {
  55 }
  56 
  57 int ShenandoahBarrierSetC2State::iu_barriers_count() const {
  58   return _iu_barriers->length();
  59 }
  60 
  61 ShenandoahIUBarrierNode* ShenandoahBarrierSetC2State::iu_barrier(int idx) const {
  62   return _iu_barriers->at(idx);
  63 }
  64 
  65 void ShenandoahBarrierSetC2State::add_iu_barrier(ShenandoahIUBarrierNode* n) {
  66   assert(!_iu_barriers->contains(n), "duplicate entry in barrier list");
  67   _iu_barriers->append(n);
  68 }
  69 
  70 void ShenandoahBarrierSetC2State::remove_iu_barrier(ShenandoahIUBarrierNode* n) {
  71   _iu_barriers->remove_if_existing(n);
  72 }
  73 
  74 int ShenandoahBarrierSetC2State::load_reference_barriers_count() const {
  75   return _load_reference_barriers->length();
  76 }
  77 
  78 ShenandoahLoadReferenceBarrierNode* ShenandoahBarrierSetC2State::load_reference_barrier(int idx) const {
  79   return _load_reference_barriers->at(idx);
  80 }
  81 
  82 void ShenandoahBarrierSetC2State::add_load_reference_barrier(ShenandoahLoadReferenceBarrierNode * n) {
  83   assert(!_load_reference_barriers->contains(n), "duplicate entry in barrier list");
  84   _load_reference_barriers->append(n);
  85 }
  86 
  87 void ShenandoahBarrierSetC2State::remove_load_reference_barrier(ShenandoahLoadReferenceBarrierNode * n) {
  88   if (_load_reference_barriers->contains(n)) {
  89     _load_reference_barriers->remove(n);
  90   }
  91 }
  92 
  93 Node* ShenandoahBarrierSetC2::shenandoah_iu_barrier(GraphKit* kit, Node* obj) const {
  94   if (ShenandoahIUBarrier) {
  95     return kit->gvn().transform(new ShenandoahIUBarrierNode(obj));
  96   }
  97   return obj;
  98 }
  99 
 100 #define __ kit->
 101 
 102 bool ShenandoahBarrierSetC2::satb_can_remove_pre_barrier(GraphKit* kit, PhaseValues* phase, Node* adr,
 103                                                          BasicType bt, uint adr_idx) const {
 104   intptr_t offset = 0;
 105   Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset);
 106   AllocateNode* alloc = AllocateNode::Ideal_allocation(base, phase);
 107 
 108   if (offset == Type::OffsetBot) {
 109     return false; // cannot unalias unless there are precise offsets
 110   }
 111 
 112   if (alloc == nullptr) {
 113     return false; // No allocation found
 114   }
 115 
 116   intptr_t size_in_bytes = type2aelembytes(bt);
 117 
 118   Node* mem = __ memory(adr_idx); // start searching here...
 119 
 120   for (int cnt = 0; cnt < 50; cnt++) {
 121 
 122     if (mem->is_Store()) {
 123 
 124       Node* st_adr = mem->in(MemNode::Address);
 125       intptr_t st_offset = 0;
 126       Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset);
 127 
 128       if (st_base == nullptr) {
 129         break; // inscrutable pointer
 130       }
 131 
 132       // Break we have found a store with same base and offset as ours so break
 133       if (st_base == base && st_offset == offset) {
 134         break;
 135       }
 136 
 137       if (st_offset != offset && st_offset != Type::OffsetBot) {
 138         const int MAX_STORE = BytesPerLong;
 139         if (st_offset >= offset + size_in_bytes ||
 140             st_offset <= offset - MAX_STORE ||
 141             st_offset <= offset - mem->as_Store()->memory_size()) {
 142           // Success:  The offsets are provably independent.
 143           // (You may ask, why not just test st_offset != offset and be done?
 144           // The answer is that stores of different sizes can co-exist
 145           // in the same sequence of RawMem effects.  We sometimes initialize
 146           // a whole 'tile' of array elements with a single jint or jlong.)
 147           mem = mem->in(MemNode::Memory);
 148           continue; // advance through independent store memory
 149         }
 150       }
 151 
 152       if (st_base != base
 153           && MemNode::detect_ptr_independence(base, alloc, st_base,
 154                                               AllocateNode::Ideal_allocation(st_base, phase),
 155                                               phase)) {
 156         // Success:  The bases are provably independent.
 157         mem = mem->in(MemNode::Memory);
 158         continue; // advance through independent store memory
 159       }
 160     } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) {
 161 
 162       InitializeNode* st_init = mem->in(0)->as_Initialize();
 163       AllocateNode* st_alloc = st_init->allocation();
 164 
 165       // Make sure that we are looking at the same allocation site.
 166       // The alloc variable is guaranteed to not be null here from earlier check.
 167       if (alloc == st_alloc) {
 168         // Check that the initialization is storing null so that no previous store
 169         // has been moved up and directly write a reference
 170         Node* captured_store = st_init->find_captured_store(offset,
 171                                                             type2aelembytes(T_OBJECT),
 172                                                             phase);
 173         if (captured_store == nullptr || captured_store == st_init->zero_memory()) {
 174           return true;
 175         }
 176       }
 177     }
 178 
 179     // Unless there is an explicit 'continue', we must bail out here,
 180     // because 'mem' is an inscrutable memory state (e.g., a call).
 181     break;
 182   }
 183 
 184   return false;
 185 }
 186 
 187 #undef __
 188 #define __ ideal.
 189 
 190 void ShenandoahBarrierSetC2::satb_write_barrier_pre(GraphKit* kit,
 191                                                     bool do_load,
 192                                                     Node* obj,
 193                                                     Node* adr,
 194                                                     uint alias_idx,
 195                                                     Node* val,
 196                                                     const TypeOopPtr* val_type,
 197                                                     Node* pre_val,
 198                                                     BasicType bt) const {
 199   // Some sanity checks
 200   // Note: val is unused in this routine.
 201 
 202   if (do_load) {
 203     // We need to generate the load of the previous value
 204     assert(adr != nullptr, "where are loading from?");
 205     assert(pre_val == nullptr, "loaded already?");
 206     assert(val_type != nullptr, "need a type");
 207 
 208     if (ReduceInitialCardMarks
 209         && satb_can_remove_pre_barrier(kit, &kit->gvn(), adr, bt, alias_idx)) {
 210       return;
 211     }
 212 
 213   } else {
 214     // In this case both val_type and alias_idx are unused.
 215     assert(pre_val != nullptr, "must be loaded already");
 216     // Nothing to be done if pre_val is null.
 217     if (pre_val->bottom_type() == TypePtr::NULL_PTR) return;
 218     assert(pre_val->bottom_type()->basic_type() == T_OBJECT, "or we shouldn't be here");
 219   }
 220   assert(bt == T_OBJECT, "or we shouldn't be here");
 221 
 222   IdealKit ideal(kit, true);
 223 
 224   Node* tls = __ thread(); // ThreadLocalStorage
 225 
 226   Node* no_base = __ top();
 227   Node* zero  = __ ConI(0);
 228   Node* zeroX = __ ConX(0);
 229 
 230   float likely  = PROB_LIKELY(0.999);
 231   float unlikely  = PROB_UNLIKELY(0.999);
 232 
 233   // Offsets into the thread
 234   const int index_offset   = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset());
 235   const int buffer_offset  = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset());
 236 
 237   // Now the actual pointers into the thread
 238   Node* buffer_adr  = __ AddP(no_base, tls, __ ConX(buffer_offset));
 239   Node* index_adr   = __ AddP(no_base, tls, __ ConX(index_offset));
 240 
 241   // Now some of the values
 242   Node* marking;
 243   Node* gc_state = __ AddP(no_base, tls, __ ConX(in_bytes(ShenandoahThreadLocalData::gc_state_offset())));
 244   Node* ld = __ load(__ ctrl(), gc_state, TypeInt::BYTE, T_BYTE, Compile::AliasIdxRaw);
 245   marking = __ AndI(ld, __ ConI(ShenandoahHeap::MARKING));
 246   assert(ShenandoahBarrierC2Support::is_gc_state_load(ld), "Should match the shape");
 247 
 248   // if (!marking)
 249   __ if_then(marking, BoolTest::ne, zero, unlikely); {
 250     BasicType index_bt = TypeX_X->basic_type();
 251     assert(sizeof(size_t) == type2aelembytes(index_bt), "Loading Shenandoah SATBMarkQueue::_index with wrong size.");
 252     Node* index   = __ load(__ ctrl(), index_adr, TypeX_X, index_bt, Compile::AliasIdxRaw);
 253 
 254     if (do_load) {
 255       // load original value
 256       // alias_idx correct??
 257       pre_val = __ load(__ ctrl(), adr, val_type, bt, alias_idx);
 258     }
 259 
 260     // if (pre_val != nullptr)
 261     __ if_then(pre_val, BoolTest::ne, kit->null()); {
 262       Node* buffer  = __ load(__ ctrl(), buffer_adr, TypeRawPtr::NOTNULL, T_ADDRESS, Compile::AliasIdxRaw);
 263 
 264       // is the queue for this thread full?
 265       __ if_then(index, BoolTest::ne, zeroX, likely); {
 266 
 267         // decrement the index
 268         Node* next_index = kit->gvn().transform(new SubXNode(index, __ ConX(sizeof(intptr_t))));
 269 
 270         // Now get the buffer location we will log the previous value into and store it
 271         Node *log_addr = __ AddP(no_base, buffer, next_index);
 272         __ store(__ ctrl(), log_addr, pre_val, T_OBJECT, Compile::AliasIdxRaw, MemNode::unordered);
 273         // update the index
 274         __ store(__ ctrl(), index_adr, next_index, index_bt, Compile::AliasIdxRaw, MemNode::unordered);
 275 
 276       } __ else_(); {
 277 
 278         // logging buffer is full, call the runtime
 279         const TypeFunc *tf = ShenandoahBarrierSetC2::write_ref_field_pre_entry_Type();
 280         __ make_leaf_call(tf, CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_ref_field_pre_entry), "shenandoah_wb_pre", pre_val, tls);
 281       } __ end_if();  // (!index)
 282     } __ end_if();  // (pre_val != nullptr)
 283   } __ end_if();  // (!marking)
 284 
 285   // Final sync IdealKit and GraphKit.
 286   kit->final_sync(ideal);
 287 
 288   if (ShenandoahSATBBarrier && adr != nullptr) {
 289     Node* c = kit->control();
 290     Node* call = c->in(1)->in(1)->in(1)->in(0);
 291     assert(is_shenandoah_wb_pre_call(call), "shenandoah_wb_pre call expected");
 292     call->add_req(adr);
 293   }
 294 }
 295 
 296 bool ShenandoahBarrierSetC2::is_shenandoah_wb_pre_call(Node* call) {
 297   return call->is_CallLeaf() &&
 298          call->as_CallLeaf()->entry_point() == CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_ref_field_pre_entry);
 299 }
 300 
 301 bool ShenandoahBarrierSetC2::is_shenandoah_lrb_call(Node* call) {
 302   if (!call->is_CallLeaf()) {
 303     return false;
 304   }
 305 
 306   address entry_point = call->as_CallLeaf()->entry_point();
 307   return (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong)) ||
 308          (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong_narrow)) ||
 309          (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak)) ||
 310          (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak_narrow)) ||
 311          (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom));
 312 }
 313 
 314 bool ShenandoahBarrierSetC2::is_shenandoah_marking_if(PhaseValues* phase, Node* n) {
 315   if (n->Opcode() != Op_If) {
 316     return false;
 317   }
 318 
 319   Node* bol = n->in(1);
 320   assert(bol->is_Bool(), "");
 321   Node* cmpx = bol->in(1);
 322   if (bol->as_Bool()->_test._test == BoolTest::ne &&
 323       cmpx->is_Cmp() && cmpx->in(2) == phase->intcon(0) &&
 324       is_shenandoah_state_load(cmpx->in(1)->in(1)) &&
 325       cmpx->in(1)->in(2)->is_Con() &&
 326       cmpx->in(1)->in(2) == phase->intcon(ShenandoahHeap::MARKING)) {
 327     return true;
 328   }
 329 
 330   return false;
 331 }
 332 
 333 bool ShenandoahBarrierSetC2::is_shenandoah_state_load(Node* n) {
 334   if (!n->is_Load()) return false;
 335   const int state_offset = in_bytes(ShenandoahThreadLocalData::gc_state_offset());
 336   return n->in(2)->is_AddP() && n->in(2)->in(2)->Opcode() == Op_ThreadLocal
 337          && n->in(2)->in(3)->is_Con()
 338          && n->in(2)->in(3)->bottom_type()->is_intptr_t()->get_con() == state_offset;
 339 }
 340 
 341 void ShenandoahBarrierSetC2::shenandoah_write_barrier_pre(GraphKit* kit,
 342                                                           bool do_load,
 343                                                           Node* obj,
 344                                                           Node* adr,
 345                                                           uint alias_idx,
 346                                                           Node* val,
 347                                                           const TypeOopPtr* val_type,
 348                                                           Node* pre_val,
 349                                                           BasicType bt) const {
 350   if (ShenandoahSATBBarrier) {
 351     IdealKit ideal(kit);
 352     kit->sync_kit(ideal);
 353 
 354     satb_write_barrier_pre(kit, do_load, obj, adr, alias_idx, val, val_type, pre_val, bt);
 355 
 356     ideal.sync_kit(kit);
 357     kit->final_sync(ideal);
 358   }
 359 }
 360 
 361 // Helper that guards and inserts a pre-barrier.
 362 void ShenandoahBarrierSetC2::insert_pre_barrier(GraphKit* kit, Node* base_oop, Node* offset,
 363                                                 Node* pre_val, bool need_mem_bar) const {
 364   // We could be accessing the referent field of a reference object. If so, when Shenandoah
 365   // is enabled, we need to log the value in the referent field in an SATB buffer.
 366   // This routine performs some compile time filters and generates suitable
 367   // runtime filters that guard the pre-barrier code.
 368   // Also add memory barrier for non volatile load from the referent field
 369   // to prevent commoning of loads across safepoint.
 370 
 371   // Some compile time checks.
 372 
 373   // If offset is a constant, is it java_lang_ref_Reference::_reference_offset?
 374   const TypeX* otype = offset->find_intptr_t_type();
 375   if (otype != nullptr && otype->is_con() &&
 376       otype->get_con() != java_lang_ref_Reference::referent_offset()) {
 377     // Constant offset but not the reference_offset so just return
 378     return;
 379   }
 380 
 381   // We only need to generate the runtime guards for instances.
 382   const TypeOopPtr* btype = base_oop->bottom_type()->isa_oopptr();
 383   if (btype != nullptr) {
 384     if (btype->isa_aryptr()) {
 385       // Array type so nothing to do
 386       return;
 387     }
 388 
 389     const TypeInstPtr* itype = btype->isa_instptr();
 390     if (itype != nullptr) {
 391       // Can the klass of base_oop be statically determined to be
 392       // _not_ a sub-class of Reference and _not_ Object?
 393       ciKlass* klass = itype->instance_klass();
 394       if (klass->is_loaded() &&
 395           !klass->is_subtype_of(kit->env()->Reference_klass()) &&
 396           !kit->env()->Object_klass()->is_subtype_of(klass)) {
 397         return;
 398       }
 399     }
 400   }
 401 
 402   // The compile time filters did not reject base_oop/offset so
 403   // we need to generate the following runtime filters
 404   //
 405   // if (offset == java_lang_ref_Reference::_reference_offset) {
 406   //   if (instance_of(base, java.lang.ref.Reference)) {
 407   //     pre_barrier(_, pre_val, ...);
 408   //   }
 409   // }
 410 
 411   float likely   = PROB_LIKELY(  0.999);
 412   float unlikely = PROB_UNLIKELY(0.999);
 413 
 414   IdealKit ideal(kit);
 415 
 416   Node* referent_off = __ ConX(java_lang_ref_Reference::referent_offset());
 417 
 418   __ if_then(offset, BoolTest::eq, referent_off, unlikely); {
 419       // Update graphKit memory and control from IdealKit.
 420       kit->sync_kit(ideal);
 421 
 422       Node* ref_klass_con = kit->makecon(TypeKlassPtr::make(kit->env()->Reference_klass()));
 423       Node* is_instof = kit->gen_instanceof(base_oop, ref_klass_con);
 424 
 425       // Update IdealKit memory and control from graphKit.
 426       __ sync_kit(kit);
 427 
 428       Node* one = __ ConI(1);
 429       // is_instof == 0 if base_oop == nullptr
 430       __ if_then(is_instof, BoolTest::eq, one, unlikely); {
 431 
 432         // Update graphKit from IdeakKit.
 433         kit->sync_kit(ideal);
 434 
 435         // Use the pre-barrier to record the value in the referent field
 436         satb_write_barrier_pre(kit, false /* do_load */,
 437                                nullptr /* obj */, nullptr /* adr */, max_juint /* alias_idx */, nullptr /* val */, nullptr /* val_type */,
 438                                pre_val /* pre_val */,
 439                                T_OBJECT);
 440         if (need_mem_bar) {
 441           // Add memory barrier to prevent commoning reads from this field
 442           // across safepoint since GC can change its value.
 443           kit->insert_mem_bar(Op_MemBarCPUOrder);
 444         }
 445         // Update IdealKit from graphKit.
 446         __ sync_kit(kit);
 447 
 448       } __ end_if(); // _ref_type != ref_none
 449   } __ end_if(); // offset == referent_offset
 450 
 451   // Final sync IdealKit and GraphKit.
 452   kit->final_sync(ideal);
 453 }
 454 
 455 Node* ShenandoahBarrierSetC2::byte_map_base_node(GraphKit* kit) const {
 456   BarrierSet* bs = BarrierSet::barrier_set();
 457   ShenandoahBarrierSet* ctbs = barrier_set_cast<ShenandoahBarrierSet>(bs);
 458   CardTable::CardValue* card_table_base = ctbs->card_table()->byte_map_base();
 459   if (card_table_base != nullptr) {
 460     return kit->makecon(TypeRawPtr::make((address)card_table_base));
 461   } else {
 462     return kit->null();
 463   }
 464 }
 465 
 466 void ShenandoahBarrierSetC2::post_barrier(GraphKit* kit,
 467                                           Node* ctl,
 468                                           Node* oop_store,
 469                                           Node* obj,
 470                                           Node* adr,
 471                                           uint  adr_idx,
 472                                           Node* val,
 473                                           BasicType bt,
 474                                           bool use_precise) const {
 475   assert(ShenandoahCardBarrier, "Did you mean to enable ShenandoahCardBarrier?");
 476 
 477   // No store check needed if we're storing a null.
 478   if (val != nullptr && val->is_Con()) {
 479     // must be either an oop or NULL
 480     const Type* t = val->bottom_type();
 481     if (t == TypePtr::NULL_PTR || t == Type::TOP)
 482       return;
 483   }
 484 
 485   if (ReduceInitialCardMarks && obj == kit->just_allocated_object(kit->control())) {
 486     // We can skip marks on a freshly-allocated object in Eden.
 487     // Keep this code in sync with new_deferred_store_barrier() in runtime.cpp.
 488     // That routine informs GC to take appropriate compensating steps,
 489     // upon a slow-path allocation, so as to make this card-mark
 490     // elision safe.
 491     return;
 492   }
 493 
 494   if (!use_precise) {
 495     // All card marks for a (non-array) instance are in one place:
 496     adr = obj;
 497   }
 498   // (Else it's an array (or unknown), and we want more precise card marks.)
 499   assert(adr != nullptr, "");
 500 
 501   IdealKit ideal(kit, true);
 502 
 503   // Convert the pointer to an int prior to doing math on it
 504   Node* cast = __ CastPX(__ ctrl(), adr);
 505 
 506   // Divide by card size
 507   Node* card_offset = __ URShiftX( cast, __ ConI(CardTable::card_shift()) );
 508 
 509   // Combine card table base and card offset
 510   Node* card_adr = __ AddP(__ top(), byte_map_base_node(kit), card_offset );
 511 
 512   // Get the alias_index for raw card-mark memory
 513   int adr_type = Compile::AliasIdxRaw;
 514   Node*   zero = __ ConI(0); // Dirty card value
 515 
 516   if (UseCondCardMark) {
 517     // The classic GC reference write barrier is typically implemented
 518     // as a store into the global card mark table.  Unfortunately
 519     // unconditional stores can result in false sharing and excessive
 520     // coherence traffic as well as false transactional aborts.
 521     // UseCondCardMark enables MP "polite" conditional card mark
 522     // stores.  In theory we could relax the load from ctrl() to
 523     // no_ctrl, but that doesn't buy much latitude.
 524     Node* card_val = __ load( __ ctrl(), card_adr, TypeInt::BYTE, T_BYTE, adr_type);
 525     __ if_then(card_val, BoolTest::ne, zero);
 526   }
 527 
 528   // Smash zero into card
 529   __ store(__ ctrl(), card_adr, zero, T_BYTE, adr_type, MemNode::unordered);
 530 
 531   if (UseCondCardMark) {
 532     __ end_if();
 533   }
 534 
 535   // Final sync IdealKit and GraphKit.
 536   kit->final_sync(ideal);
 537 }
 538 
 539 #undef __
 540 
 541 const TypeFunc* ShenandoahBarrierSetC2::write_ref_field_pre_entry_Type() {
 542   const Type **fields = TypeTuple::fields(2);
 543   fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL; // original field value
 544   fields[TypeFunc::Parms+1] = TypeRawPtr::NOTNULL; // thread
 545   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
 546 
 547   // create result type (range)
 548   fields = TypeTuple::fields(0);
 549   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0, fields);
 550 
 551   return TypeFunc::make(domain, range);
 552 }
 553 
 554 const TypeFunc* ShenandoahBarrierSetC2::shenandoah_clone_barrier_Type() {
 555   const Type **fields = TypeTuple::fields(1);
 556   fields[TypeFunc::Parms+0] = TypeOopPtr::NOTNULL; // src oop
 557   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+1, fields);
 558 
 559   // create result type (range)
 560   fields = TypeTuple::fields(0);
 561   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0, fields);
 562 
 563   return TypeFunc::make(domain, range);
 564 }
 565 
 566 const TypeFunc* ShenandoahBarrierSetC2::shenandoah_load_reference_barrier_Type() {
 567   const Type **fields = TypeTuple::fields(2);
 568   fields[TypeFunc::Parms+0] = TypeOopPtr::BOTTOM; // original field value
 569   fields[TypeFunc::Parms+1] = TypeRawPtr::BOTTOM; // original load address
 570 
 571   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
 572 
 573   // create result type (range)
 574   fields = TypeTuple::fields(1);
 575   fields[TypeFunc::Parms+0] = TypeOopPtr::BOTTOM;
 576   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+1, fields);
 577 
 578   return TypeFunc::make(domain, range);
 579 }
 580 
 581 Node* ShenandoahBarrierSetC2::store_at_resolved(C2Access& access, C2AccessValue& val) const {
 582   DecoratorSet decorators = access.decorators();
 583 
 584   const TypePtr* adr_type = access.addr().type();
 585   Node* adr = access.addr().node();
 586 
 587   if (!access.is_oop()) {
 588     return BarrierSetC2::store_at_resolved(access, val);
 589   }
 590 
 591   if (access.is_parse_access()) {
 592     C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(access);
 593     GraphKit* kit = parse_access.kit();
 594 
 595     uint adr_idx = kit->C->get_alias_index(adr_type);
 596     assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
 597     Node* value = val.node();
 598     value = shenandoah_iu_barrier(kit, value);
 599     val.set_node(value);
 600     shenandoah_write_barrier_pre(kit, true /* do_load */, /*kit->control(),*/ access.base(), adr, adr_idx, val.node(),
 601                                  static_cast<const TypeOopPtr*>(val.type()), nullptr /* pre_val */, access.type());
 602 
 603     Node* result = BarrierSetC2::store_at_resolved(access, val);
 604 
 605     if (ShenandoahCardBarrier) {
 606       const bool anonymous = (decorators & ON_UNKNOWN_OOP_REF) != 0;
 607       const bool is_array = (decorators & IS_ARRAY) != 0;
 608       const bool use_precise = is_array || anonymous;
 609       post_barrier(kit, kit->control(), access.raw_access(), access.base(),
 610                    adr, adr_idx, val.node(), access.type(), use_precise);
 611     }
 612     return result;
 613   } else {
 614     assert(access.is_opt_access(), "only for optimization passes");
 615     assert(((decorators & C2_TIGHTLY_COUPLED_ALLOC) != 0 || !ShenandoahSATBBarrier) && (decorators & C2_ARRAY_COPY) != 0, "unexpected caller of this code");
 616     C2OptAccess& opt_access = static_cast<C2OptAccess&>(access);
 617     PhaseGVN& gvn =  opt_access.gvn();
 618 
 619     if (ShenandoahIUBarrier) {
 620       Node* enqueue = gvn.transform(new ShenandoahIUBarrierNode(val.node()));
 621       val.set_node(enqueue);
 622     }
 623     return BarrierSetC2::store_at_resolved(access, val);
 624   }
 625 }
 626 
 627 Node* ShenandoahBarrierSetC2::load_at_resolved(C2Access& access, const Type* val_type) const {
 628   // 1: non-reference load, no additional barrier is needed
 629   if (!access.is_oop()) {
 630     return BarrierSetC2::load_at_resolved(access, val_type);
 631   }
 632 
 633   Node* load = BarrierSetC2::load_at_resolved(access, val_type);
 634   DecoratorSet decorators = access.decorators();
 635   BasicType type = access.type();
 636 
 637   // 2: apply LRB if needed
 638   if (ShenandoahBarrierSet::need_load_reference_barrier(decorators, type)) {
 639     load = new ShenandoahLoadReferenceBarrierNode(nullptr, load, decorators);
 640     if (access.is_parse_access()) {
 641       load = static_cast<C2ParseAccess &>(access).kit()->gvn().transform(load);
 642     } else {
 643       load = static_cast<C2OptAccess &>(access).gvn().transform(load);
 644     }
 645   }
 646 
 647   // 3: apply keep-alive barrier for java.lang.ref.Reference if needed
 648   if (ShenandoahBarrierSet::need_keep_alive_barrier(decorators, type)) {
 649     Node* top = Compile::current()->top();
 650     Node* adr = access.addr().node();
 651     Node* offset = adr->is_AddP() ? adr->in(AddPNode::Offset) : top;
 652     Node* obj = access.base();
 653 
 654     bool unknown = (decorators & ON_UNKNOWN_OOP_REF) != 0;
 655     bool on_weak_ref = (decorators & (ON_WEAK_OOP_REF | ON_PHANTOM_OOP_REF)) != 0;
 656     bool keep_alive = (decorators & AS_NO_KEEPALIVE) == 0;
 657 
 658     // If we are reading the value of the referent field of a Reference
 659     // object (either by using Unsafe directly or through reflection)
 660     // then, if SATB is enabled, we need to record the referent in an
 661     // SATB log buffer using the pre-barrier mechanism.
 662     // Also we need to add memory barrier to prevent commoning reads
 663     // from this field across safepoint since GC can change its value.
 664     if (!on_weak_ref || (unknown && (offset == top || obj == top)) || !keep_alive) {
 665       return load;
 666     }
 667 
 668     assert(access.is_parse_access(), "entry not supported at optimization time");
 669     C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(access);
 670     GraphKit* kit = parse_access.kit();
 671     bool mismatched = (decorators & C2_MISMATCHED) != 0;
 672     bool is_unordered = (decorators & MO_UNORDERED) != 0;
 673     bool in_native = (decorators & IN_NATIVE) != 0;
 674     bool need_cpu_mem_bar = !is_unordered || mismatched || in_native;
 675 
 676     if (on_weak_ref) {
 677       // Use the pre-barrier to record the value in the referent field
 678       satb_write_barrier_pre(kit, false /* do_load */,
 679                              nullptr /* obj */, nullptr /* adr */, max_juint /* alias_idx */, nullptr /* val */, nullptr /* val_type */,
 680                              load /* pre_val */, T_OBJECT);
 681       // Add memory barrier to prevent commoning reads from this field
 682       // across safepoint since GC can change its value.
 683       kit->insert_mem_bar(Op_MemBarCPUOrder);
 684     } else if (unknown) {
 685       // We do not require a mem bar inside pre_barrier if need_mem_bar
 686       // is set: the barriers would be emitted by us.
 687       insert_pre_barrier(kit, obj, offset, load, !need_cpu_mem_bar);
 688     }
 689   }
 690 
 691   return load;
 692 }
 693 
 694 Node* ShenandoahBarrierSetC2::atomic_cmpxchg_val_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
 695                                                              Node* new_val, const Type* value_type) const {
 696   GraphKit* kit = access.kit();
 697   if (access.is_oop()) {
 698     new_val = shenandoah_iu_barrier(kit, new_val);
 699     shenandoah_write_barrier_pre(kit, false /* do_load */,
 700                                  nullptr, nullptr, max_juint, nullptr, nullptr,
 701                                  expected_val /* pre_val */, T_OBJECT);
 702 
 703     MemNode::MemOrd mo = access.mem_node_mo();
 704     Node* mem = access.memory();
 705     Node* adr = access.addr().node();
 706     const TypePtr* adr_type = access.addr().type();
 707     Node* load_store = nullptr;
 708 
 709 #ifdef _LP64
 710     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 711       Node *newval_enc = kit->gvn().transform(new EncodePNode(new_val, new_val->bottom_type()->make_narrowoop()));
 712       Node *oldval_enc = kit->gvn().transform(new EncodePNode(expected_val, expected_val->bottom_type()->make_narrowoop()));
 713       if (ShenandoahCASBarrier) {
 714         load_store = kit->gvn().transform(new ShenandoahCompareAndExchangeNNode(kit->control(), mem, adr, newval_enc, oldval_enc, adr_type, value_type->make_narrowoop(), mo));
 715       } else {
 716         load_store = kit->gvn().transform(new CompareAndExchangeNNode(kit->control(), mem, adr, newval_enc, oldval_enc, adr_type, value_type->make_narrowoop(), mo));
 717       }
 718     } else
 719 #endif
 720     {
 721       if (ShenandoahCASBarrier) {
 722         load_store = kit->gvn().transform(new ShenandoahCompareAndExchangePNode(kit->control(), mem, adr, new_val, expected_val, adr_type, value_type->is_oopptr(), mo));
 723       } else {
 724         load_store = kit->gvn().transform(new CompareAndExchangePNode(kit->control(), mem, adr, new_val, expected_val, adr_type, value_type->is_oopptr(), mo));
 725       }
 726     }
 727 
 728     access.set_raw_access(load_store);
 729     pin_atomic_op(access);
 730 
 731 #ifdef _LP64
 732     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 733       load_store = kit->gvn().transform(new DecodeNNode(load_store, load_store->get_ptr_type()));
 734     }
 735 #endif
 736     load_store = kit->gvn().transform(new ShenandoahLoadReferenceBarrierNode(nullptr, load_store, access.decorators()));
 737     if (ShenandoahCardBarrier) {
 738       post_barrier(kit, kit->control(), access.raw_access(), access.base(),
 739                    access.addr().node(), access.alias_idx(), new_val, T_OBJECT, true);
 740     }
 741     return load_store;
 742   }
 743   return BarrierSetC2::atomic_cmpxchg_val_at_resolved(access, expected_val, new_val, value_type);
 744 }
 745 
 746 Node* ShenandoahBarrierSetC2::atomic_cmpxchg_bool_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
 747                                                               Node* new_val, const Type* value_type) const {
 748   GraphKit* kit = access.kit();
 749   if (access.is_oop()) {
 750     new_val = shenandoah_iu_barrier(kit, new_val);
 751     shenandoah_write_barrier_pre(kit, false /* do_load */,
 752                                  nullptr, nullptr, max_juint, nullptr, nullptr,
 753                                  expected_val /* pre_val */, T_OBJECT);
 754     DecoratorSet decorators = access.decorators();
 755     MemNode::MemOrd mo = access.mem_node_mo();
 756     Node* mem = access.memory();
 757     bool is_weak_cas = (decorators & C2_WEAK_CMPXCHG) != 0;
 758     Node* load_store = nullptr;
 759     Node* adr = access.addr().node();
 760 #ifdef _LP64
 761     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 762       Node *newval_enc = kit->gvn().transform(new EncodePNode(new_val, new_val->bottom_type()->make_narrowoop()));
 763       Node *oldval_enc = kit->gvn().transform(new EncodePNode(expected_val, expected_val->bottom_type()->make_narrowoop()));
 764       if (ShenandoahCASBarrier) {
 765         if (is_weak_cas) {
 766           load_store = kit->gvn().transform(new ShenandoahWeakCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 767         } else {
 768           load_store = kit->gvn().transform(new ShenandoahCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 769         }
 770       } else {
 771         if (is_weak_cas) {
 772           load_store = kit->gvn().transform(new WeakCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 773         } else {
 774           load_store = kit->gvn().transform(new CompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 775         }
 776       }
 777     } else
 778 #endif
 779     {
 780       if (ShenandoahCASBarrier) {
 781         if (is_weak_cas) {
 782           load_store = kit->gvn().transform(new ShenandoahWeakCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 783         } else {
 784           load_store = kit->gvn().transform(new ShenandoahCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 785         }
 786       } else {
 787         if (is_weak_cas) {
 788           load_store = kit->gvn().transform(new WeakCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 789         } else {
 790           load_store = kit->gvn().transform(new CompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 791         }
 792       }
 793     }
 794     access.set_raw_access(load_store);
 795     pin_atomic_op(access);
 796     if (ShenandoahCardBarrier) {
 797       post_barrier(kit, kit->control(), access.raw_access(), access.base(),
 798                    access.addr().node(), access.alias_idx(), new_val, T_OBJECT, true);
 799     }
 800     return load_store;
 801   }
 802   return BarrierSetC2::atomic_cmpxchg_bool_at_resolved(access, expected_val, new_val, value_type);
 803 }
 804 
 805 Node* ShenandoahBarrierSetC2::atomic_xchg_at_resolved(C2AtomicParseAccess& access, Node* val, const Type* value_type) const {
 806   GraphKit* kit = access.kit();
 807   if (access.is_oop()) {
 808     val = shenandoah_iu_barrier(kit, val);
 809   }
 810   Node* result = BarrierSetC2::atomic_xchg_at_resolved(access, val, value_type);
 811   if (access.is_oop()) {
 812     result = kit->gvn().transform(new ShenandoahLoadReferenceBarrierNode(nullptr, result, access.decorators()));
 813     shenandoah_write_barrier_pre(kit, false /* do_load */,
 814                                  nullptr, nullptr, max_juint, nullptr, nullptr,
 815                                  result /* pre_val */, T_OBJECT);
 816     if (ShenandoahCardBarrier) {
 817       post_barrier(kit, kit->control(), access.raw_access(), access.base(),
 818                    access.addr().node(), access.alias_idx(), val, T_OBJECT, true);
 819     }
 820   }
 821   return result;
 822 }
 823 
 824 
 825 bool ShenandoahBarrierSetC2::is_gc_pre_barrier_node(Node* node) const {
 826   return is_shenandoah_wb_pre_call(node);
 827 }
 828 
 829 // Support for GC barriers emitted during parsing
 830 bool ShenandoahBarrierSetC2::is_gc_barrier_node(Node* node) const {
 831   if (node->Opcode() == Op_ShenandoahLoadReferenceBarrier || node->Opcode() == Op_ShenandoahIUBarrier) return true;
 832   if (node->Opcode() != Op_CallLeaf && node->Opcode() != Op_CallLeafNoFP) {
 833     return false;
 834   }
 835   CallLeafNode *call = node->as_CallLeaf();
 836   if (call->_name == nullptr) {
 837     return false;
 838   }
 839 
 840   return strcmp(call->_name, "shenandoah_clone_barrier") == 0 ||
 841          strcmp(call->_name, "shenandoah_cas_obj") == 0 ||
 842          strcmp(call->_name, "shenandoah_wb_pre") == 0;
 843 }
 844 
 845 Node* ShenandoahBarrierSetC2::step_over_gc_barrier(Node* c) const {
 846   if (c == nullptr) {
 847     return c;
 848   }
 849   if (c->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
 850     return c->in(ShenandoahLoadReferenceBarrierNode::ValueIn);
 851   }
 852   if (c->Opcode() == Op_ShenandoahIUBarrier) {
 853     c = c->in(1);
 854   }
 855   return c;
 856 }
 857 
 858 bool ShenandoahBarrierSetC2::expand_barriers(Compile* C, PhaseIterGVN& igvn) const {
 859   return !ShenandoahBarrierC2Support::expand(C, igvn);
 860 }
 861 
 862 bool ShenandoahBarrierSetC2::optimize_loops(PhaseIdealLoop* phase, LoopOptsMode mode, VectorSet& visited, Node_Stack& nstack, Node_List& worklist) const {
 863   if (mode == LoopOptsShenandoahExpand) {
 864     assert(UseShenandoahGC, "only for shenandoah");
 865     ShenandoahBarrierC2Support::pin_and_expand(phase);
 866     return true;
 867   } else if (mode == LoopOptsShenandoahPostExpand) {
 868     assert(UseShenandoahGC, "only for shenandoah");
 869     visited.clear();
 870     ShenandoahBarrierC2Support::optimize_after_expansion(visited, nstack, worklist, phase);
 871     return true;
 872   }
 873   return false;
 874 }
 875 
 876 bool ShenandoahBarrierSetC2::array_copy_requires_gc_barriers(bool tightly_coupled_alloc, BasicType type, bool is_clone, bool is_clone_instance, ArrayCopyPhase phase) const {
 877   bool is_oop = is_reference_type(type);
 878   if (!is_oop) {
 879     return false;
 880   }
 881   if (ShenandoahSATBBarrier && tightly_coupled_alloc) {
 882     if (phase == Optimization) {
 883       return false;
 884     }
 885     return !is_clone;
 886   }
 887   if (phase == Optimization) {
 888     return !ShenandoahIUBarrier;
 889   }
 890   return true;
 891 }
 892 
 893 bool ShenandoahBarrierSetC2::clone_needs_barrier(Node* src, PhaseGVN& gvn) {
 894   const TypeOopPtr* src_type = gvn.type(src)->is_oopptr();
 895   if (src_type->isa_instptr() != nullptr) {
 896     ciInstanceKlass* ik = src_type->is_instptr()->instance_klass();
 897     if ((src_type->klass_is_exact() || !ik->has_subklass()) && !ik->has_injected_fields()) {
 898       if (ik->has_object_fields()) {
 899         return true;
 900       } else {
 901         if (!src_type->klass_is_exact()) {
 902           Compile::current()->dependencies()->assert_leaf_type(ik);
 903         }
 904       }
 905     } else {
 906       return true;
 907         }
 908   } else if (src_type->isa_aryptr()) {
 909     BasicType src_elem = src_type->isa_aryptr()->elem()->array_element_basic_type();
 910     if (is_reference_type(src_elem, true)) {
 911       return true;
 912     }
 913   } else {
 914     return true;
 915   }
 916   return false;
 917 }
 918 
 919 void ShenandoahBarrierSetC2::clone_at_expansion(PhaseMacroExpand* phase, ArrayCopyNode* ac) const {
 920   Node* ctrl = ac->in(TypeFunc::Control);
 921   Node* mem = ac->in(TypeFunc::Memory);
 922   Node* src_base = ac->in(ArrayCopyNode::Src);
 923   Node* src_offset = ac->in(ArrayCopyNode::SrcPos);
 924   Node* dest_base = ac->in(ArrayCopyNode::Dest);
 925   Node* dest_offset = ac->in(ArrayCopyNode::DestPos);
 926   Node* length = ac->in(ArrayCopyNode::Length);
 927 
 928   Node* src = phase->basic_plus_adr(src_base, src_offset);
 929   Node* dest = phase->basic_plus_adr(dest_base, dest_offset);
 930 
 931   if (ShenandoahCloneBarrier && clone_needs_barrier(src, phase->igvn())) {
 932     // Check if heap is has forwarded objects. If it does, we need to call into the special
 933     // routine that would fix up source references before we can continue.
 934 
 935     enum { _heap_stable = 1, _heap_unstable, PATH_LIMIT };
 936     Node* region = new RegionNode(PATH_LIMIT);
 937     Node* mem_phi = new PhiNode(region, Type::MEMORY, TypeRawPtr::BOTTOM);
 938 
 939     Node* thread = phase->transform_later(new ThreadLocalNode());
 940     Node* offset = phase->igvn().MakeConX(in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 941     Node* gc_state_addr = phase->transform_later(new AddPNode(phase->C->top(), thread, offset));
 942 
 943     uint gc_state_idx = Compile::AliasIdxRaw;
 944     const TypePtr* gc_state_adr_type = nullptr; // debug-mode-only argument
 945     debug_only(gc_state_adr_type = phase->C->get_adr_type(gc_state_idx));
 946 
 947     Node* gc_state    = phase->transform_later(new LoadBNode(ctrl, mem, gc_state_addr, gc_state_adr_type, TypeInt::BYTE, MemNode::unordered));
 948     int flags = ShenandoahHeap::HAS_FORWARDED;
 949     if (ShenandoahIUBarrier) {
 950       flags |= ShenandoahHeap::MARKING;
 951     }
 952     Node* stable_and  = phase->transform_later(new AndINode(gc_state, phase->igvn().intcon(flags)));
 953     Node* stable_cmp  = phase->transform_later(new CmpINode(stable_and, phase->igvn().zerocon(T_INT)));
 954     Node* stable_test = phase->transform_later(new BoolNode(stable_cmp, BoolTest::ne));
 955 
 956     IfNode* stable_iff  = phase->transform_later(new IfNode(ctrl, stable_test, PROB_UNLIKELY(0.999), COUNT_UNKNOWN))->as_If();
 957     Node* stable_ctrl   = phase->transform_later(new IfFalseNode(stable_iff));
 958     Node* unstable_ctrl = phase->transform_later(new IfTrueNode(stable_iff));
 959 
 960     // Heap is stable, no need to do anything additional
 961     region->init_req(_heap_stable, stable_ctrl);
 962     mem_phi->init_req(_heap_stable, mem);
 963 
 964     // Heap is unstable, call into clone barrier stub
 965     Node* call = phase->make_leaf_call(unstable_ctrl, mem,
 966                     ShenandoahBarrierSetC2::shenandoah_clone_barrier_Type(),
 967                     CAST_FROM_FN_PTR(address, ShenandoahRuntime::shenandoah_clone_barrier),
 968                     "shenandoah_clone",
 969                     TypeRawPtr::BOTTOM,
 970                     src_base);
 971     call = phase->transform_later(call);
 972 
 973     ctrl = phase->transform_later(new ProjNode(call, TypeFunc::Control));
 974     mem = phase->transform_later(new ProjNode(call, TypeFunc::Memory));
 975     region->init_req(_heap_unstable, ctrl);
 976     mem_phi->init_req(_heap_unstable, mem);
 977 
 978     // Wire up the actual arraycopy stub now
 979     ctrl = phase->transform_later(region);
 980     mem = phase->transform_later(mem_phi);
 981 
 982     const char* name = "arraycopy";
 983     call = phase->make_leaf_call(ctrl, mem,
 984                                  OptoRuntime::fast_arraycopy_Type(),
 985                                  phase->basictype2arraycopy(T_LONG, nullptr, nullptr, true, name, true),
 986                                  name, TypeRawPtr::BOTTOM,
 987                                  src, dest, length
 988                                  LP64_ONLY(COMMA phase->top()));
 989     call = phase->transform_later(call);
 990 
 991     // Hook up the whole thing into the graph
 992     phase->igvn().replace_node(ac, call);
 993   } else {
 994     BarrierSetC2::clone_at_expansion(phase, ac);
 995   }
 996 }
 997 
 998 
 999 // Support for macro expanded GC barriers
1000 void ShenandoahBarrierSetC2::register_potential_barrier_node(Node* node) const {
1001   if (node->Opcode() == Op_ShenandoahIUBarrier) {
1002     state()->add_iu_barrier((ShenandoahIUBarrierNode*) node);
1003   }
1004   if (node->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
1005     state()->add_load_reference_barrier((ShenandoahLoadReferenceBarrierNode*) node);
1006   }
1007 }
1008 
1009 void ShenandoahBarrierSetC2::unregister_potential_barrier_node(Node* node) const {
1010   if (node->Opcode() == Op_ShenandoahIUBarrier) {
1011     state()->remove_iu_barrier((ShenandoahIUBarrierNode*) node);
1012   }
1013   if (node->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
1014     state()->remove_load_reference_barrier((ShenandoahLoadReferenceBarrierNode*) node);
1015   }
1016 }
1017 
1018 void ShenandoahBarrierSetC2::eliminate_gc_barrier(PhaseMacroExpand* macro, Node* node) const {
1019   if (is_shenandoah_wb_pre_call(node)) {
1020     shenandoah_eliminate_wb_pre(node, &macro->igvn());
1021   }
1022   if (ShenandoahCardBarrier && node->Opcode() == Op_CastP2X) {
1023     Node* shift = node->unique_out();
1024     Node* addp = shift->unique_out();
1025     for (DUIterator_Last jmin, j = addp->last_outs(jmin); j >= jmin; --j) {
1026       Node* mem = addp->last_out(j);
1027       if (UseCondCardMark && mem->is_Load()) {
1028         assert(mem->Opcode() == Op_LoadB, "unexpected code shape");
1029         // The load is checking if the card has been written so
1030         // replace it with zero to fold the test.
1031         macro->replace_node(mem, macro->intcon(0));
1032         continue;
1033       }
1034       assert(mem->is_Store(), "store required");
1035       macro->replace_node(mem, mem->in(MemNode::Memory));
1036     }
1037   }
1038 }
1039 
1040 void ShenandoahBarrierSetC2::shenandoah_eliminate_wb_pre(Node* call, PhaseIterGVN* igvn) const {
1041   assert(UseShenandoahGC && is_shenandoah_wb_pre_call(call), "");
1042   Node* c = call->as_Call()->proj_out(TypeFunc::Control);
1043   c = c->unique_ctrl_out();
1044   assert(c->is_Region() && c->req() == 3, "where's the pre barrier control flow?");
1045   c = c->unique_ctrl_out();
1046   assert(c->is_Region() && c->req() == 3, "where's the pre barrier control flow?");
1047   Node* iff = c->in(1)->is_IfProj() ? c->in(1)->in(0) : c->in(2)->in(0);
1048   assert(iff->is_If(), "expect test");
1049   if (!is_shenandoah_marking_if(igvn, iff)) {
1050     c = c->unique_ctrl_out();
1051     assert(c->is_Region() && c->req() == 3, "where's the pre barrier control flow?");
1052     iff = c->in(1)->is_IfProj() ? c->in(1)->in(0) : c->in(2)->in(0);
1053     assert(is_shenandoah_marking_if(igvn, iff), "expect marking test");
1054   }
1055   Node* cmpx = iff->in(1)->in(1);
1056   igvn->replace_node(cmpx, igvn->makecon(TypeInt::CC_EQ));
1057   igvn->rehash_node_delayed(call);
1058   call->del_req(call->req()-1);
1059 }
1060 
1061 void ShenandoahBarrierSetC2::enqueue_useful_gc_barrier(PhaseIterGVN* igvn, Node* node) const {
1062   if (node->Opcode() == Op_AddP && ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(node)) {
1063     igvn->add_users_to_worklist(node);
1064   }
1065 }
1066 
1067 void ShenandoahBarrierSetC2::eliminate_useless_gc_barriers(Unique_Node_List &useful, Compile* C) const {
1068   for (uint i = 0; i < useful.size(); i++) {
1069     Node* n = useful.at(i);
1070     if (n->Opcode() == Op_AddP && ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(n)) {
1071       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1072         C->record_for_igvn(n->fast_out(i));
1073       }
1074     }
1075   }
1076   for (int i = state()->iu_barriers_count() - 1; i >= 0; i--) {
1077     ShenandoahIUBarrierNode* n = state()->iu_barrier(i);
1078     if (!useful.member(n)) {
1079       state()->remove_iu_barrier(n);
1080     }
1081   }
1082   for (int i = state()->load_reference_barriers_count() - 1; i >= 0; i--) {
1083     ShenandoahLoadReferenceBarrierNode* n = state()->load_reference_barrier(i);
1084     if (!useful.member(n)) {
1085       state()->remove_load_reference_barrier(n);
1086     }
1087   }
1088 }
1089 
1090 void* ShenandoahBarrierSetC2::create_barrier_state(Arena* comp_arena) const {
1091   return new(comp_arena) ShenandoahBarrierSetC2State(comp_arena);
1092 }
1093 
1094 ShenandoahBarrierSetC2State* ShenandoahBarrierSetC2::state() const {
1095   return reinterpret_cast<ShenandoahBarrierSetC2State*>(Compile::current()->barrier_set_state());
1096 }
1097 
1098 // If the BarrierSetC2 state has kept macro nodes in its compilation unit state to be
1099 // expanded later, then now is the time to do so.
1100 bool ShenandoahBarrierSetC2::expand_macro_nodes(PhaseMacroExpand* macro) const { return false; }
1101 
1102 #ifdef ASSERT
1103 void ShenandoahBarrierSetC2::verify_gc_barriers(Compile* compile, CompilePhase phase) const {
1104   if (ShenandoahVerifyOptoBarriers && phase == BarrierSetC2::BeforeMacroExpand) {
1105     ShenandoahBarrierC2Support::verify(Compile::current()->root());
1106   } else if (phase == BarrierSetC2::BeforeCodeGen) {
1107     // Verify Shenandoah pre-barriers
1108     const int marking_offset = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_active_offset());
1109 
1110     Unique_Node_List visited;
1111     Node_List worklist;
1112     // We're going to walk control flow backwards starting from the Root
1113     worklist.push(compile->root());
1114     while (worklist.size() > 0) {
1115       Node *x = worklist.pop();
1116       if (x == nullptr || x == compile->top()) continue;
1117       if (visited.member(x)) {
1118         continue;
1119       } else {
1120         visited.push(x);
1121       }
1122 
1123       if (x->is_Region()) {
1124         for (uint i = 1; i < x->req(); i++) {
1125           worklist.push(x->in(i));
1126         }
1127       } else {
1128         worklist.push(x->in(0));
1129         // We are looking for the pattern:
1130         //                            /->ThreadLocal
1131         // If->Bool->CmpI->LoadB->AddP->ConL(marking_offset)
1132         //              \->ConI(0)
1133         // We want to verify that the If and the LoadB have the same control
1134         // See GraphKit::g1_write_barrier_pre()
1135         if (x->is_If()) {
1136           IfNode *iff = x->as_If();
1137           if (iff->in(1)->is_Bool() && iff->in(1)->in(1)->is_Cmp()) {
1138             CmpNode *cmp = iff->in(1)->in(1)->as_Cmp();
1139             if (cmp->Opcode() == Op_CmpI && cmp->in(2)->is_Con() && cmp->in(2)->bottom_type()->is_int()->get_con() == 0
1140                 && cmp->in(1)->is_Load()) {
1141               LoadNode *load = cmp->in(1)->as_Load();
1142               if (load->Opcode() == Op_LoadB && load->in(2)->is_AddP() && load->in(2)->in(2)->Opcode() == Op_ThreadLocal
1143                   && load->in(2)->in(3)->is_Con()
1144                   && load->in(2)->in(3)->bottom_type()->is_intptr_t()->get_con() == marking_offset) {
1145 
1146                 Node *if_ctrl = iff->in(0);
1147                 Node *load_ctrl = load->in(0);
1148 
1149                 if (if_ctrl != load_ctrl) {
1150                   // Skip possible CProj->NeverBranch in infinite loops
1151                   if ((if_ctrl->is_Proj() && if_ctrl->Opcode() == Op_CProj)
1152                       && if_ctrl->in(0)->is_NeverBranch()) {
1153                     if_ctrl = if_ctrl->in(0)->in(0);
1154                   }
1155                 }
1156                 assert(load_ctrl != nullptr && if_ctrl == load_ctrl, "controls must match");
1157               }
1158             }
1159           }
1160         }
1161       }
1162     }
1163   }
1164 }
1165 #endif
1166 
1167 Node* ShenandoahBarrierSetC2::ideal_node(PhaseGVN* phase, Node* n, bool can_reshape) const {
1168   if (is_shenandoah_wb_pre_call(n)) {
1169     uint cnt = ShenandoahBarrierSetC2::write_ref_field_pre_entry_Type()->domain()->cnt();
1170     if (n->req() > cnt) {
1171       Node* addp = n->in(cnt);
1172       if (has_only_shenandoah_wb_pre_uses(addp)) {
1173         n->del_req(cnt);
1174         if (can_reshape) {
1175           phase->is_IterGVN()->_worklist.push(addp);
1176         }
1177         return n;
1178       }
1179     }
1180   }
1181   if (n->Opcode() == Op_CmpP) {
1182     Node* in1 = n->in(1);
1183     Node* in2 = n->in(2);
1184 
1185     // If one input is null, then step over the strong LRB barriers on the other input
1186     if (in1->bottom_type() == TypePtr::NULL_PTR &&
1187         !((in2->Opcode() == Op_ShenandoahLoadReferenceBarrier) &&
1188           !ShenandoahBarrierSet::is_strong_access(((ShenandoahLoadReferenceBarrierNode*)in2)->decorators()))) {
1189       in2 = step_over_gc_barrier(in2);
1190     }
1191     if (in2->bottom_type() == TypePtr::NULL_PTR &&
1192         !((in1->Opcode() == Op_ShenandoahLoadReferenceBarrier) &&
1193           !ShenandoahBarrierSet::is_strong_access(((ShenandoahLoadReferenceBarrierNode*)in1)->decorators()))) {
1194       in1 = step_over_gc_barrier(in1);
1195     }
1196 
1197     if (in1 != n->in(1)) {
1198       n->set_req_X(1, in1, phase);
1199       assert(in2 == n->in(2), "only one change");
1200       return n;
1201     }
1202     if (in2 != n->in(2)) {
1203       n->set_req_X(2, in2, phase);
1204       return n;
1205     }
1206   } else if (can_reshape &&
1207              n->Opcode() == Op_If &&
1208              ShenandoahBarrierC2Support::is_heap_stable_test(n) &&
1209              n->in(0) != nullptr &&
1210              n->outcnt() == 2) {
1211     Node* dom = n->in(0);
1212     Node* prev_dom = n;
1213     int op = n->Opcode();
1214     int dist = 16;
1215     // Search up the dominator tree for another heap stable test
1216     while (dom->Opcode() != op    ||  // Not same opcode?
1217            !ShenandoahBarrierC2Support::is_heap_stable_test(dom) ||  // Not same input 1?
1218            prev_dom->in(0) != dom) {  // One path of test does not dominate?
1219       if (dist < 0) return nullptr;
1220 
1221       dist--;
1222       prev_dom = dom;
1223       dom = IfNode::up_one_dom(dom);
1224       if (!dom) return nullptr;
1225     }
1226 
1227     // Check that we did not follow a loop back to ourselves
1228     if (n == dom) {
1229       return nullptr;
1230     }
1231 
1232     return n->as_If()->dominated_by(prev_dom, phase->is_IterGVN());
1233   }
1234 
1235   return nullptr;
1236 }
1237 
1238 bool ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(Node* n) {
1239   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1240     Node* u = n->fast_out(i);
1241     if (!is_shenandoah_wb_pre_call(u)) {
1242       return false;
1243     }
1244   }
1245   return n->outcnt() > 0;
1246 }
1247 
1248 bool ShenandoahBarrierSetC2::final_graph_reshaping(Compile* compile, Node* n, uint opcode, Unique_Node_List& dead_nodes) const {
1249   switch (opcode) {
1250     case Op_CallLeaf:
1251     case Op_CallLeafNoFP: {
1252       assert (n->is_Call(), "");
1253       CallNode *call = n->as_Call();
1254       if (ShenandoahBarrierSetC2::is_shenandoah_wb_pre_call(call)) {
1255         uint cnt = ShenandoahBarrierSetC2::write_ref_field_pre_entry_Type()->domain()->cnt();
1256         if (call->req() > cnt) {
1257           assert(call->req() == cnt + 1, "only one extra input");
1258           Node *addp = call->in(cnt);
1259           assert(!ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(addp), "useless address computation?");
1260           call->del_req(cnt);
1261         }
1262       }
1263       return false;
1264     }
1265     case Op_ShenandoahCompareAndSwapP:
1266     case Op_ShenandoahCompareAndSwapN:
1267     case Op_ShenandoahWeakCompareAndSwapN:
1268     case Op_ShenandoahWeakCompareAndSwapP:
1269     case Op_ShenandoahCompareAndExchangeP:
1270     case Op_ShenandoahCompareAndExchangeN:
1271       return true;
1272     case Op_ShenandoahLoadReferenceBarrier:
1273       assert(false, "should have been expanded already");
1274       return true;
1275     default:
1276       return false;
1277   }
1278 }
1279 
1280 bool ShenandoahBarrierSetC2::escape_add_to_con_graph(ConnectionGraph* conn_graph, PhaseGVN* gvn, Unique_Node_List* delayed_worklist, Node* n, uint opcode) const {
1281   switch (opcode) {
1282     case Op_ShenandoahCompareAndExchangeP:
1283     case Op_ShenandoahCompareAndExchangeN:
1284       conn_graph->add_objload_to_connection_graph(n, delayed_worklist);
1285       // fallthrough
1286     case Op_ShenandoahWeakCompareAndSwapP:
1287     case Op_ShenandoahWeakCompareAndSwapN:
1288     case Op_ShenandoahCompareAndSwapP:
1289     case Op_ShenandoahCompareAndSwapN:
1290       conn_graph->add_to_congraph_unsafe_access(n, opcode, delayed_worklist);
1291       return true;
1292     case Op_StoreP: {
1293       Node* adr = n->in(MemNode::Address);
1294       const Type* adr_type = gvn->type(adr);
1295       // Pointer stores in Shenandoah barriers looks like unsafe access.
1296       // Ignore such stores to be able scalar replace non-escaping
1297       // allocations.
1298       if (adr_type->isa_rawptr() && adr->is_AddP()) {
1299         Node* base = conn_graph->get_addp_base(adr);
1300         if (base->Opcode() == Op_LoadP &&
1301           base->in(MemNode::Address)->is_AddP()) {
1302           adr = base->in(MemNode::Address);
1303           Node* tls = conn_graph->get_addp_base(adr);
1304           if (tls->Opcode() == Op_ThreadLocal) {
1305              int offs = (int) gvn->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
1306              const int buf_offset = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset());
1307              if (offs == buf_offset) {
1308                return true; // Pre barrier previous oop value store.
1309              }
1310           }
1311         }
1312       }
1313       return false;
1314     }
1315     case Op_ShenandoahIUBarrier:
1316       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), delayed_worklist);
1317       break;
1318     case Op_ShenandoahLoadReferenceBarrier:
1319       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(ShenandoahLoadReferenceBarrierNode::ValueIn), delayed_worklist);
1320       return true;
1321     default:
1322       // Nothing
1323       break;
1324   }
1325   return false;
1326 }
1327 
1328 bool ShenandoahBarrierSetC2::escape_add_final_edges(ConnectionGraph* conn_graph, PhaseGVN* gvn, Node* n, uint opcode) const {
1329   switch (opcode) {
1330     case Op_ShenandoahCompareAndExchangeP:
1331     case Op_ShenandoahCompareAndExchangeN: {
1332       Node *adr = n->in(MemNode::Address);
1333       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, adr, nullptr);
1334       // fallthrough
1335     }
1336     case Op_ShenandoahCompareAndSwapP:
1337     case Op_ShenandoahCompareAndSwapN:
1338     case Op_ShenandoahWeakCompareAndSwapP:
1339     case Op_ShenandoahWeakCompareAndSwapN:
1340       return conn_graph->add_final_edges_unsafe_access(n, opcode);
1341     case Op_ShenandoahIUBarrier:
1342       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), nullptr);
1343       return true;
1344     case Op_ShenandoahLoadReferenceBarrier:
1345       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(ShenandoahLoadReferenceBarrierNode::ValueIn), nullptr);
1346       return true;
1347     default:
1348       // Nothing
1349       break;
1350   }
1351   return false;
1352 }
1353 
1354 bool ShenandoahBarrierSetC2::escape_has_out_with_unsafe_object(Node* n) const {
1355   return n->has_out_with(Op_ShenandoahCompareAndExchangeP) || n->has_out_with(Op_ShenandoahCompareAndExchangeN) ||
1356          n->has_out_with(Op_ShenandoahCompareAndSwapP, Op_ShenandoahCompareAndSwapN, Op_ShenandoahWeakCompareAndSwapP, Op_ShenandoahWeakCompareAndSwapN);
1357 
1358 }
1359 
1360 bool ShenandoahBarrierSetC2::matcher_find_shared_post_visit(Matcher* matcher, Node* n, uint opcode) const {
1361   switch (opcode) {
1362     case Op_ShenandoahCompareAndExchangeP:
1363     case Op_ShenandoahCompareAndExchangeN:
1364     case Op_ShenandoahWeakCompareAndSwapP:
1365     case Op_ShenandoahWeakCompareAndSwapN:
1366     case Op_ShenandoahCompareAndSwapP:
1367     case Op_ShenandoahCompareAndSwapN: {   // Convert trinary to binary-tree
1368       Node* newval = n->in(MemNode::ValueIn);
1369       Node* oldval = n->in(LoadStoreConditionalNode::ExpectedIn);
1370       Node* pair = new BinaryNode(oldval, newval);
1371       n->set_req(MemNode::ValueIn,pair);
1372       n->del_req(LoadStoreConditionalNode::ExpectedIn);
1373       return true;
1374     }
1375     default:
1376       break;
1377   }
1378   return false;
1379 }
1380 
1381 bool ShenandoahBarrierSetC2::matcher_is_store_load_barrier(Node* x, uint xop) const {
1382   return xop == Op_ShenandoahCompareAndExchangeP ||
1383          xop == Op_ShenandoahCompareAndExchangeN ||
1384          xop == Op_ShenandoahWeakCompareAndSwapP ||
1385          xop == Op_ShenandoahWeakCompareAndSwapN ||
1386          xop == Op_ShenandoahCompareAndSwapN ||
1387          xop == Op_ShenandoahCompareAndSwapP;
1388 }