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