< prev index next >

src/hotspot/share/gc/shenandoah/c2/shenandoahBarrierSetC2.cpp

Print this page

   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 "classfile/javaClasses.hpp"
  27 #include "gc/shared/barrierSet.hpp"
  28 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
  29 #include "gc/shenandoah/c2/shenandoahSupport.hpp"
  30 #include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
  31 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
  32 #include "gc/shenandoah/shenandoahCardTable.hpp"
  33 #include "gc/shenandoah/shenandoahForwarding.hpp"
  34 #include "gc/shenandoah/shenandoahHeap.hpp"
  35 #include "gc/shenandoah/shenandoahRuntime.hpp"
  36 #include "gc/shenandoah/shenandoahThreadLocalData.hpp"
  37 #include "opto/arraycopynode.hpp"
  38 #include "opto/escape.hpp"
  39 #include "opto/graphKit.hpp"
  40 #include "opto/idealKit.hpp"
  41 #include "opto/macro.hpp"
  42 #include "opto/movenode.hpp"
  43 #include "opto/narrowptrnode.hpp"

  44 #include "opto/rootnode.hpp"
  45 #include "opto/runtime.hpp"
  46 
  47 ShenandoahBarrierSetC2* ShenandoahBarrierSetC2::bsc2() {
  48   return reinterpret_cast<ShenandoahBarrierSetC2*>(BarrierSet::barrier_set()->barrier_set_c2());
  49 }
  50 
  51 ShenandoahBarrierSetC2State::ShenandoahBarrierSetC2State(Arena* comp_arena)
  52   : _load_reference_barriers(new (comp_arena) GrowableArray<ShenandoahLoadReferenceBarrierNode*>(comp_arena, 8,  0, nullptr)) {




  53 }
  54 
  55 int ShenandoahBarrierSetC2State::load_reference_barriers_count() const {
  56   return _load_reference_barriers->length();
  57 }
  58 
  59 ShenandoahLoadReferenceBarrierNode* ShenandoahBarrierSetC2State::load_reference_barrier(int idx) const {
  60   return _load_reference_barriers->at(idx);
  61 }
  62 
  63 void ShenandoahBarrierSetC2State::add_load_reference_barrier(ShenandoahLoadReferenceBarrierNode * n) {
  64   assert(!_load_reference_barriers->contains(n), "duplicate entry in barrier list");
  65   _load_reference_barriers->append(n);
  66 }
  67 
  68 void ShenandoahBarrierSetC2State::remove_load_reference_barrier(ShenandoahLoadReferenceBarrierNode * n) {
  69   if (_load_reference_barriers->contains(n)) {
  70     _load_reference_barriers->remove(n);
  71   }
  72 }
  73 
  74 #define __ kit->
  75 
  76 bool ShenandoahBarrierSetC2::satb_can_remove_pre_barrier(GraphKit* kit, PhaseGVN* phase, Node* adr,
  77                                                          BasicType bt, uint adr_idx) const {
  78   intptr_t offset = 0;
  79   Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset);
  80   AllocateNode* alloc = AllocateNode::Ideal_allocation(base);
  81 
  82   if (offset == Type::OffsetBot) {
  83     return false; // cannot unalias unless there are precise offsets
  84   }
  85 
  86   if (alloc == nullptr) {
  87     return false; // No allocation found

  88   }
  89 
  90   intptr_t size_in_bytes = type2aelembytes(bt);
  91 
  92   Node* mem = __ memory(adr_idx); // start searching here...
  93 
  94   for (int cnt = 0; cnt < 50; cnt++) {
  95 
  96     if (mem->is_Store()) {
  97 
  98       Node* st_adr = mem->in(MemNode::Address);
  99       intptr_t st_offset = 0;
 100       Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset);
 101 
 102       if (st_base == nullptr) {
 103         break; // inscrutable pointer
 104       }
 105 
 106       // Break we have found a store with same base and offset as ours so break
 107       if (st_base == base && st_offset == offset) {
 108         break;
 109       }
 110 
 111       if (st_offset != offset && st_offset != Type::OffsetBot) {
 112         const int MAX_STORE = BytesPerLong;
 113         if (st_offset >= offset + size_in_bytes ||
 114             st_offset <= offset - MAX_STORE ||
 115             st_offset <= offset - mem->as_Store()->memory_size()) {
 116           // Success:  The offsets are provably independent.
 117           // (You may ask, why not just test st_offset != offset and be done?
 118           // The answer is that stores of different sizes can co-exist
 119           // in the same sequence of RawMem effects.  We sometimes initialize
 120           // a whole 'tile' of array elements with a single jint or jlong.)
 121           mem = mem->in(MemNode::Memory);
 122           continue; // advance through independent store memory
 123         }
 124       }
 125 
 126       if (st_base != base
 127           && MemNode::detect_ptr_independence(base, alloc, st_base,
 128                                               AllocateNode::Ideal_allocation(st_base),
 129                                               phase)) {
 130         // Success:  The bases are provably independent.
 131         mem = mem->in(MemNode::Memory);
 132         continue; // advance through independent store memory
 133       }
 134     } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) {
 135 
 136       InitializeNode* st_init = mem->in(0)->as_Initialize();
 137       AllocateNode* st_alloc = st_init->allocation();
 138 
 139       // Make sure that we are looking at the same allocation site.
 140       // The alloc variable is guaranteed to not be null here from earlier check.
 141       if (alloc == st_alloc) {
 142         // Check that the initialization is storing null so that no previous store
 143         // has been moved up and directly write a reference
 144         Node* captured_store = st_init->find_captured_store(offset,
 145                                                             type2aelembytes(T_OBJECT),
 146                                                             phase);
 147         if (captured_store == nullptr || captured_store == st_init->zero_memory()) {
 148           return true;
 149         }
 150       }
 151     }
 152 
 153     // Unless there is an explicit 'continue', we must bail out here,
 154     // because 'mem' is an inscrutable memory state (e.g., a call).
 155     break;
 156   }
 157 
 158   return false;
 159 }
 160 
 161 #undef __
 162 #define __ ideal.
 163 
 164 void ShenandoahBarrierSetC2::satb_write_barrier_pre(GraphKit* kit,
 165                                                     bool do_load,
 166                                                     Node* obj,
 167                                                     Node* adr,
 168                                                     uint alias_idx,
 169                                                     Node* val,
 170                                                     const TypeOopPtr* val_type,
 171                                                     Node* pre_val,
 172                                                     BasicType bt) const {
 173   // Some sanity checks
 174   // Note: val is unused in this routine.
 175 
 176   if (do_load) {
 177     // We need to generate the load of the previous value
 178     assert(adr != nullptr, "where are loading from?");
 179     assert(pre_val == nullptr, "loaded already?");
 180     assert(val_type != nullptr, "need a type");
 181 
 182     if (ReduceInitialCardMarks
 183         && satb_can_remove_pre_barrier(kit, &kit->gvn(), adr, bt, alias_idx)) {
 184       return;
 185     }
 186 
 187   } else {
 188     // In this case both val_type and alias_idx are unused.
 189     assert(pre_val != nullptr, "must be loaded already");
 190     // Nothing to be done if pre_val is null.
 191     if (pre_val->bottom_type() == TypePtr::NULL_PTR) return;
 192     assert(pre_val->bottom_type()->basic_type() == T_OBJECT, "or we shouldn't be here");
 193   }
 194   assert(bt == T_OBJECT, "or we shouldn't be here");
 195 
 196   IdealKit ideal(kit, true);
 197 
 198   Node* tls = __ thread(); // ThreadLocalStorage
 199 
 200   Node* no_base = __ top();
 201   Node* zero  = __ ConI(0);
 202   Node* zeroX = __ ConX(0);
 203 
 204   float likely  = PROB_LIKELY(0.999);
 205   float unlikely  = PROB_UNLIKELY(0.999);
 206 
 207   // Offsets into the thread
 208   const int index_offset   = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset());
 209   const int buffer_offset  = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset());
 210 
 211   // Now the actual pointers into the thread
 212   Node* buffer_adr  = __ AddP(no_base, tls, __ ConX(buffer_offset));
 213   Node* index_adr   = __ AddP(no_base, tls, __ ConX(index_offset));
 214 
 215   // Now some of the values
 216   Node* marking;
 217   Node* gc_state = __ AddP(no_base, tls, __ ConX(in_bytes(ShenandoahThreadLocalData::gc_state_offset())));
 218   Node* ld = __ load(__ ctrl(), gc_state, TypeInt::BYTE, T_BYTE, Compile::AliasIdxRaw);
 219   marking = __ AndI(ld, __ ConI(ShenandoahHeap::MARKING));
 220   assert(ShenandoahBarrierC2Support::is_gc_state_load(ld), "Should match the shape");
 221 
 222   // if (!marking)
 223   __ if_then(marking, BoolTest::ne, zero, unlikely); {
 224     BasicType index_bt = TypeX_X->basic_type();
 225     assert(sizeof(size_t) == type2aelembytes(index_bt), "Loading Shenandoah SATBMarkQueue::_index with wrong size.");
 226     Node* index   = __ load(__ ctrl(), index_adr, TypeX_X, index_bt, Compile::AliasIdxRaw);
 227 
 228     if (do_load) {
 229       // load original value
 230       // alias_idx correct??
 231       pre_val = __ load(__ ctrl(), adr, val_type, bt, alias_idx);
 232     }
 233 
 234     // if (pre_val != nullptr)
 235     __ if_then(pre_val, BoolTest::ne, kit->null()); {
 236       Node* buffer  = __ load(__ ctrl(), buffer_adr, TypeRawPtr::NOTNULL, T_ADDRESS, Compile::AliasIdxRaw);
 237 
 238       // is the queue for this thread full?
 239       __ if_then(index, BoolTest::ne, zeroX, likely); {



 240 
 241         // decrement the index
 242         Node* next_index = kit->gvn().transform(new SubXNode(index, __ ConX(sizeof(intptr_t))));
 243 
 244         // Now get the buffer location we will log the previous value into and store it
 245         Node *log_addr = __ AddP(no_base, buffer, next_index);
 246         __ store(__ ctrl(), log_addr, pre_val, T_OBJECT, Compile::AliasIdxRaw, MemNode::unordered);
 247         // update the index
 248         __ store(__ ctrl(), index_adr, next_index, index_bt, Compile::AliasIdxRaw, MemNode::unordered);






 249 
 250       } __ else_(); {

 251 
 252         // logging buffer is full, call the runtime
 253         const TypeFunc *tf = ShenandoahBarrierSetC2::write_barrier_pre_Type();
 254         __ make_leaf_call(tf, CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_barrier_pre), "shenandoah_wb_pre", pre_val);
 255       } __ end_if();  // (!index)
 256     } __ end_if();  // (pre_val != nullptr)
 257   } __ end_if();  // (!marking)
 258 
 259   // Final sync IdealKit and GraphKit.
 260   kit->final_sync(ideal);
 261 
 262   if (ShenandoahSATBBarrier && adr != nullptr) {
 263     Node* c = kit->control();
 264     Node* call = c->in(1)->in(1)->in(1)->in(0);
 265     assert(is_shenandoah_wb_pre_call(call), "shenandoah_wb_pre call expected");
 266     call->add_req(adr);
 267   }
 268 }
 269 
 270 bool ShenandoahBarrierSetC2::is_shenandoah_wb_pre_call(Node* call) {
 271   return call->is_CallLeaf() &&
 272          call->as_CallLeaf()->entry_point() == CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_barrier_pre);
 273 }
 274 
 275 bool ShenandoahBarrierSetC2::is_shenandoah_clone_call(Node* call) {
 276   return call->is_CallLeaf() &&
 277          call->as_CallLeaf()->entry_point() == CAST_FROM_FN_PTR(address, ShenandoahRuntime::clone_barrier);

 278 }
 279 
 280 bool ShenandoahBarrierSetC2::is_shenandoah_lrb_call(Node* call) {
 281   if (!call->is_CallLeaf()) {
 282     return false;
 283   }
 284 
 285   address entry_point = call->as_CallLeaf()->entry_point();
 286   return (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong)) ||
 287          (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong_narrow)) ||
 288          (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak)) ||
 289          (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak_narrow)) ||
 290          (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom)) ||
 291          (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom_narrow));
 292 }
 293 
 294 bool ShenandoahBarrierSetC2::is_shenandoah_marking_if(PhaseValues* phase, Node* n) {
 295   if (n->Opcode() != Op_If) {
 296     return false;
 297   }
 298 
 299   Node* bol = n->in(1);
 300   assert(bol->is_Bool(), "");
 301   Node* cmpx = bol->in(1);
 302   if (bol->as_Bool()->_test._test == BoolTest::ne &&
 303       cmpx->is_Cmp() && cmpx->in(2) == phase->intcon(0) &&
 304       is_shenandoah_state_load(cmpx->in(1)->in(1)) &&
 305       cmpx->in(1)->in(2)->is_Con() &&
 306       cmpx->in(1)->in(2) == phase->intcon(ShenandoahHeap::MARKING)) {
 307     return true;
 308   }
 309 
 310   return false;
 311 }
 312 
 313 bool ShenandoahBarrierSetC2::is_shenandoah_state_load(Node* n) {
 314   if (!n->is_Load()) return false;
 315   const int state_offset = in_bytes(ShenandoahThreadLocalData::gc_state_offset());
 316   return n->in(2)->is_AddP() && n->in(2)->in(2)->Opcode() == Op_ThreadLocal
 317          && n->in(2)->in(3)->is_Con()
 318          && n->in(2)->in(3)->bottom_type()->is_intptr_t()->get_con() == state_offset;


 319 }
 320 
 321 void ShenandoahBarrierSetC2::shenandoah_write_barrier_pre(GraphKit* kit,
 322                                                           bool do_load,
 323                                                           Node* obj,
 324                                                           Node* adr,
 325                                                           uint alias_idx,
 326                                                           Node* val,
 327                                                           const TypeOopPtr* val_type,
 328                                                           Node* pre_val,
 329                                                           BasicType bt) const {
 330   if (ShenandoahSATBBarrier) {
 331     IdealKit ideal(kit);
 332     kit->sync_kit(ideal);
 333 
 334     satb_write_barrier_pre(kit, do_load, obj, adr, alias_idx, val, val_type, pre_val, bt);
 335 
 336     ideal.sync_kit(kit);
 337     kit->final_sync(ideal);
 338   }
 339 }
 340 
 341 // Helper that guards and inserts a pre-barrier.
 342 void ShenandoahBarrierSetC2::insert_pre_barrier(GraphKit* kit, Node* base_oop, Node* offset,
 343                                                 Node* pre_val, bool need_mem_bar) const {
 344   // We could be accessing the referent field of a reference object. If so, when Shenandoah
 345   // is enabled, we need to log the value in the referent field in an SATB buffer.
 346   // This routine performs some compile time filters and generates suitable
 347   // runtime filters that guard the pre-barrier code.
 348   // Also add memory barrier for non volatile load from the referent field
 349   // to prevent commoning of loads across safepoint.
 350 
 351   // Some compile time checks.
 352 
 353   // If offset is a constant, is it java_lang_ref_Reference::_reference_offset?
 354   const TypeX* otype = offset->find_intptr_t_type();
 355   if (otype != nullptr && otype->is_con() &&
 356       otype->get_con() != java_lang_ref_Reference::referent_offset()) {
 357     // Constant offset but not the reference_offset so just return
 358     return;
 359   }
 360 
 361   // We only need to generate the runtime guards for instances.
 362   const TypeOopPtr* btype = base_oop->bottom_type()->isa_oopptr();
 363   if (btype != nullptr) {
 364     if (btype->isa_aryptr()) {
 365       // Array type so nothing to do
 366       return;
 367     }
 368 
 369     const TypeInstPtr* itype = btype->isa_instptr();
 370     if (itype != nullptr) {
 371       // Can the klass of base_oop be statically determined to be
 372       // _not_ a sub-class of Reference and _not_ Object?
 373       ciKlass* klass = itype->instance_klass();
 374       if (klass->is_loaded() &&
 375           !klass->is_subtype_of(kit->env()->Reference_klass()) &&
 376           !kit->env()->Object_klass()->is_subtype_of(klass)) {
 377         return;
 378       }
 379     }
 380   }
 381 
 382   // The compile time filters did not reject base_oop/offset so
 383   // we need to generate the following runtime filters
 384   //
 385   // if (offset == java_lang_ref_Reference::_reference_offset) {
 386   //   if (instance_of(base, java.lang.ref.Reference)) {
 387   //     pre_barrier(_, pre_val, ...);
 388   //   }
 389   // }
 390 
 391   float likely   = PROB_LIKELY(  0.999);
 392   float unlikely = PROB_UNLIKELY(0.999);
 393 
 394   IdealKit ideal(kit);
 395 
 396   Node* referent_off = __ ConX(java_lang_ref_Reference::referent_offset());
 397 
 398   __ if_then(offset, BoolTest::eq, referent_off, unlikely); {
 399       // Update graphKit memory and control from IdealKit.
 400       kit->sync_kit(ideal);
 401 
 402       Node* ref_klass_con = kit->makecon(TypeKlassPtr::make(kit->env()->Reference_klass()));
 403       Node* is_instof = kit->gen_instanceof(base_oop, ref_klass_con);
 404 
 405       // Update IdealKit memory and control from graphKit.
 406       __ sync_kit(kit);
 407 
 408       Node* one = __ ConI(1);
 409       // is_instof == 0 if base_oop == nullptr
 410       __ if_then(is_instof, BoolTest::eq, one, unlikely); {
 411 
 412         // Update graphKit from IdeakKit.
 413         kit->sync_kit(ideal);


 414 
 415         // Use the pre-barrier to record the value in the referent field
 416         satb_write_barrier_pre(kit, false /* do_load */,
 417                                nullptr /* obj */, nullptr /* adr */, max_juint /* alias_idx */, nullptr /* val */, nullptr /* val_type */,
 418                                pre_val /* pre_val */,
 419                                T_OBJECT);
 420         if (need_mem_bar) {
 421           // Add memory barrier to prevent commoning reads from this field
 422           // across safepoint since GC can change its value.
 423           kit->insert_mem_bar(Op_MemBarCPUOrder);
 424         }
 425         // Update IdealKit from graphKit.
 426         __ sync_kit(kit);
 427 
 428       } __ end_if(); // _ref_type != ref_none
 429   } __ end_if(); // offset == referent_offset






 430 
 431   // Final sync IdealKit and GraphKit.
 432   kit->final_sync(ideal);
 433 }












 434 
 435 void ShenandoahBarrierSetC2::post_barrier(GraphKit* kit,
 436                                           Node* ctl,
 437                                           Node* oop_store,
 438                                           Node* obj,
 439                                           Node* adr,
 440                                           uint  adr_idx,
 441                                           Node* val,
 442                                           BasicType bt,
 443                                           bool use_precise) const {
 444   assert(ShenandoahCardBarrier, "Should have been checked by caller");
 445 
 446   // No store check needed if we're storing a null.
 447   if (val != nullptr && val->is_Con()) {
 448     // must be either an oop or null
 449     const Type* t = val->bottom_type();
 450     if (t == TypePtr::NULL_PTR || t == Type::TOP)
 451       return;
 452   }
 453 
 454   if (ReduceInitialCardMarks && obj == kit->just_allocated_object(kit->control())) {
 455     // We use card marks to track old to young references in Generational Shenandoah;
 456     // see flag ShenandoahCardBarrier above.
 457     // Objects are always allocated in the young generation and initialized
 458     // before they are promoted. There's always a safepoint (e.g. at final mark)
 459     // before an object is promoted from young to old. Promotion entails dirtying of
 460     // the cards backing promoted objects, so they will be guaranteed to be scanned
 461     // at the next remembered set scan of the old generation.
 462     // Thus, we can safely skip card-marking of initializing stores on a
 463     // freshly-allocated object. If any of the assumptions above change in
 464     // the future, this code will need to be re-examined; see check in
 465     // ShenandoahCardBarrier::on_slowpath_allocation_exit().
 466     return;
 467   }
 468 
 469   if (!use_precise) {
 470     // All card marks for a (non-array) instance are in one place:
 471     adr = obj;



 472   }
 473   // (Else it's an array (or unknown), and we want more precise card marks.)
 474   assert(adr != nullptr, "");
 475 
 476   IdealKit ideal(kit, true);
 477 
 478   Node* tls = __ thread(); // ThreadLocalStorage
 479 
 480   // Convert the pointer to an int prior to doing math on it
 481   Node* cast = __ CastPX(__ ctrl(), adr);
 482 
 483   Node* curr_ct_holder_offset = __ ConX(in_bytes(ShenandoahThreadLocalData::card_table_offset()));
 484   Node* curr_ct_holder_addr  = __ AddP(__ top(), tls, curr_ct_holder_offset);
 485   Node* curr_ct_base_addr = __ load( __ ctrl(), curr_ct_holder_addr, TypeRawPtr::NOTNULL, T_ADDRESS, Compile::AliasIdxRaw);
 486 
 487   // Divide by card size
 488   Node* card_offset = __ URShiftX( cast, __ ConI(CardTable::card_shift()) );
 489 
 490   // Combine card table base and card offset
 491   Node* card_adr = __ AddP(__ top(), curr_ct_base_addr, card_offset);
 492 
 493   // Get the alias_index for raw card-mark memory
 494   int adr_type = Compile::AliasIdxRaw;
 495   Node*   zero = __ ConI(0); // Dirty card value
 496 
 497   if (UseCondCardMark) {
 498     // The classic GC reference write barrier is typically implemented
 499     // as a store into the global card mark table.  Unfortunately
 500     // unconditional stores can result in false sharing and excessive
 501     // coherence traffic as well as false transactional aborts.
 502     // UseCondCardMark enables MP "polite" conditional card mark
 503     // stores.  In theory we could relax the load from ctrl() to
 504     // no_ctrl, but that doesn't buy much latitude.
 505     Node* card_val = __ load( __ ctrl(), card_adr, TypeInt::BYTE, T_BYTE, adr_type);
 506     __ if_then(card_val, BoolTest::ne, zero);
 507   }
 508 
 509   // Smash zero into card
 510   __ store(__ ctrl(), card_adr, zero, T_BYTE, adr_type, MemNode::unordered);
 511 
 512   if (UseCondCardMark) {
 513     __ end_if();
 514   }
 515 
 516   // Final sync IdealKit and GraphKit.
 517   kit->final_sync(ideal);
 518 }
 519 
 520 #undef __
 521 
 522 const TypeFunc* ShenandoahBarrierSetC2::_write_barrier_pre_Type              = nullptr;
 523 const TypeFunc* ShenandoahBarrierSetC2::_clone_barrier_Type                  = nullptr;
 524 const TypeFunc* ShenandoahBarrierSetC2::_load_reference_barrier_Type         = nullptr;
 525 
 526 inline const TypeFunc* ShenandoahBarrierSetC2::write_barrier_pre_Type() {
 527   assert(ShenandoahBarrierSetC2::_write_barrier_pre_Type != nullptr, "should be initialized");
 528   return ShenandoahBarrierSetC2::_write_barrier_pre_Type;
 529 }
 530 
 531 inline const TypeFunc* ShenandoahBarrierSetC2::clone_barrier_Type() {
 532   assert(ShenandoahBarrierSetC2::_clone_barrier_Type != nullptr, "should be initialized");
 533   return ShenandoahBarrierSetC2::_clone_barrier_Type;
 534 }
 535 
 536 const TypeFunc* ShenandoahBarrierSetC2::load_reference_barrier_Type() {
 537   assert(ShenandoahBarrierSetC2::_load_reference_barrier_Type != nullptr, "should be initialized");
 538   return ShenandoahBarrierSetC2::_load_reference_barrier_Type;
 539 }
 540 
 541 void ShenandoahBarrierSetC2::init() {
 542   ShenandoahBarrierSetC2::make_write_barrier_pre_Type();
 543   ShenandoahBarrierSetC2::make_clone_barrier_Type();
 544   ShenandoahBarrierSetC2::make_load_reference_barrier_Type();
 545 }
 546 
 547 void ShenandoahBarrierSetC2::make_write_barrier_pre_Type() {
 548   assert(ShenandoahBarrierSetC2::_write_barrier_pre_Type == nullptr, "should be");
 549   const Type **fields = TypeTuple::fields(1);
 550   fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL; // original field value
 551   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+1, fields);
 552 
 553   // create result type (range)
 554   fields = TypeTuple::fields(0);
 555   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0, fields);
 556 
 557   ShenandoahBarrierSetC2::_write_barrier_pre_Type = TypeFunc::make(domain, range);
 558 }
 559 
 560 void ShenandoahBarrierSetC2::make_clone_barrier_Type() {
 561   assert(ShenandoahBarrierSetC2::_clone_barrier_Type == nullptr, "should be");
 562   const Type **fields = TypeTuple::fields(1);
 563   fields[TypeFunc::Parms+0] = TypeOopPtr::NOTNULL; // src oop
 564   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+1, fields);
 565 
 566   // create result type (range)
 567   fields = TypeTuple::fields(0);
 568   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0, fields);
 569 
 570   ShenandoahBarrierSetC2::_clone_barrier_Type = TypeFunc::make(domain, range);
 571 }
 572 
 573 void ShenandoahBarrierSetC2::make_load_reference_barrier_Type() {
 574   assert(ShenandoahBarrierSetC2::_load_reference_barrier_Type == nullptr, "should be");
 575   const Type **fields = TypeTuple::fields(2);
 576   fields[TypeFunc::Parms+0] = TypeOopPtr::BOTTOM; // original field value
 577   fields[TypeFunc::Parms+1] = TypeRawPtr::BOTTOM; // original load address
 578 
 579   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
 580 
 581   // create result type (range)
 582   fields = TypeTuple::fields(1);
 583   fields[TypeFunc::Parms+0] = TypeOopPtr::BOTTOM;
 584   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+1, fields);











 585 
 586   ShenandoahBarrierSetC2::_load_reference_barrier_Type = TypeFunc::make(domain, range);
 587 }
 588 
 589 Node* ShenandoahBarrierSetC2::store_at_resolved(C2Access& access, C2AccessValue& val) const {
 590   DecoratorSet decorators = access.decorators();

 591 
 592   const TypePtr* adr_type = access.addr().type();
 593   Node* adr = access.addr().node();
 594 
 595   bool no_keepalive = (decorators & AS_NO_KEEPALIVE) != 0;
 596 
 597   if (!access.is_oop()) {
 598     return BarrierSetC2::store_at_resolved(access, val);
 599   }
 600 
 601   if (no_keepalive) {
 602     // No keep-alive means no need for the pre-barrier.
 603     return BarrierSetC2::store_at_resolved(access, val);
 604   }
 605 
 606   if (access.is_parse_access()) {
 607     C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(access);
 608     GraphKit* kit = parse_access.kit();
 609 
 610     uint adr_idx = kit->C->get_alias_index(adr_type);
 611     assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
 612     shenandoah_write_barrier_pre(kit, true /* do_load */, /*kit->control(),*/ access.base(), adr, adr_idx, val.node(),
 613                                  static_cast<const TypeOopPtr*>(val.type()), nullptr /* pre_val */, access.type());
 614 
 615     Node* result = BarrierSetC2::store_at_resolved(access, val);



 616 
 617     if (ShenandoahCardBarrier) {
 618       const bool anonymous = (decorators & ON_UNKNOWN_OOP_REF) != 0;
 619       const bool is_array = (decorators & IS_ARRAY) != 0;
 620       const bool use_precise = is_array || anonymous;
 621       post_barrier(kit, kit->control(), access.raw_access(), access.base(),
 622                    adr, adr_idx, val.node(), access.type(), use_precise);
 623     }
 624     return result;
 625   } else {
 626     assert(access.is_opt_access(), "only for optimization passes");
 627     assert(((decorators & C2_TIGHTLY_COUPLED_ALLOC) != 0 || !ShenandoahSATBBarrier) && (decorators & C2_ARRAY_COPY) != 0, "unexpected caller of this code");
 628     return BarrierSetC2::store_at_resolved(access, val);
 629   }
 630 }
 631 
 632 Node* ShenandoahBarrierSetC2::load_at_resolved(C2Access& access, const Type* val_type) const {
 633   // 1: non-reference load, no additional barrier is needed
 634   if (!access.is_oop()) {
 635     return BarrierSetC2::load_at_resolved(access, val_type);
 636   }
 637 
 638   Node* load = BarrierSetC2::load_at_resolved(access, val_type);
 639   DecoratorSet decorators = access.decorators();
 640   BasicType type = access.type();


 641 
 642   // 2: apply LRB if needed
 643   if (ShenandoahBarrierSet::need_load_reference_barrier(decorators, type)) {
 644     load = new ShenandoahLoadReferenceBarrierNode(nullptr, load, decorators);
 645     if (access.is_parse_access()) {
 646       load = static_cast<C2ParseAccess &>(access).kit()->gvn().transform(load);
 647     } else {
 648       load = static_cast<C2OptAccess &>(access).gvn().transform(load);
 649     }
 650   }
 651 
 652   // 3: apply keep-alive barrier for java.lang.ref.Reference if needed
 653   if (ShenandoahBarrierSet::need_keep_alive_barrier(decorators, type)) {
 654     Node* top = Compile::current()->top();
 655     Node* adr = access.addr().node();
 656     Node* offset = adr->is_AddP() ? adr->in(AddPNode::Offset) : top;
 657     Node* obj = access.base();
 658 
 659     bool unknown = (decorators & ON_UNKNOWN_OOP_REF) != 0;
 660     bool on_weak_ref = (decorators & (ON_WEAK_OOP_REF | ON_PHANTOM_OOP_REF)) != 0;
 661     bool keep_alive = (decorators & AS_NO_KEEPALIVE) == 0;
 662 
 663     // If we are reading the value of the referent field of a Reference
 664     // object (either by using Unsafe directly or through reflection)
 665     // then, if SATB is enabled, we need to record the referent in an
 666     // SATB log buffer using the pre-barrier mechanism.
 667     // Also we need to add memory barrier to prevent commoning reads
 668     // from this field across safepoint since GC can change its value.
 669     if (!on_weak_ref || (unknown && (offset == top || obj == top)) || !keep_alive) {
 670       return load;
 671     }
 672 
 673     assert(access.is_parse_access(), "entry not supported at optimization time");
 674     C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(access);
 675     GraphKit* kit = parse_access.kit();
 676     bool mismatched = (decorators & C2_MISMATCHED) != 0;
 677     bool is_unordered = (decorators & MO_UNORDERED) != 0;
 678     bool in_native = (decorators & IN_NATIVE) != 0;
 679     bool need_cpu_mem_bar = !is_unordered || mismatched || in_native;
 680 
 681     if (on_weak_ref) {
 682       // Use the pre-barrier to record the value in the referent field
 683       satb_write_barrier_pre(kit, false /* do_load */,
 684                              nullptr /* obj */, nullptr /* adr */, max_juint /* alias_idx */, nullptr /* val */, nullptr /* val_type */,
 685                              load /* pre_val */, T_OBJECT);
 686       // Add memory barrier to prevent commoning reads from this field
 687       // across safepoint since GC can change its value.
 688       kit->insert_mem_bar(Op_MemBarCPUOrder);
 689     } else if (unknown) {
 690       // We do not require a mem bar inside pre_barrier if need_mem_bar
 691       // is set: the barriers would be emitted by us.
 692       insert_pre_barrier(kit, obj, offset, load, !need_cpu_mem_bar);
 693     }
 694   }

 695 
 696   return load;








 697 }
 698 
 699 Node* ShenandoahBarrierSetC2::atomic_cmpxchg_val_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
 700                                                              Node* new_val, const Type* value_type) const {
 701   GraphKit* kit = access.kit();
 702   if (access.is_oop()) {
 703     shenandoah_write_barrier_pre(kit, false /* do_load */,
 704                                  nullptr, nullptr, max_juint, nullptr, nullptr,
 705                                  expected_val /* pre_val */, T_OBJECT);
 706 
 707     MemNode::MemOrd mo = access.mem_node_mo();
 708     Node* mem = access.memory();
 709     Node* adr = access.addr().node();
 710     const TypePtr* adr_type = access.addr().type();
 711     Node* load_store = nullptr;
 712 
 713 #ifdef _LP64
 714     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 715       Node *newval_enc = kit->gvn().transform(new EncodePNode(new_val, new_val->bottom_type()->make_narrowoop()));
 716       Node *oldval_enc = kit->gvn().transform(new EncodePNode(expected_val, expected_val->bottom_type()->make_narrowoop()));
 717       if (ShenandoahCASBarrier) {
 718         load_store = kit->gvn().transform(new ShenandoahCompareAndExchangeNNode(kit->control(), mem, adr, newval_enc, oldval_enc, adr_type, value_type->make_narrowoop(), mo));
 719       } else {
 720         load_store = kit->gvn().transform(new CompareAndExchangeNNode(kit->control(), mem, adr, newval_enc, oldval_enc, adr_type, value_type->make_narrowoop(), mo));
 721       }
 722     } else
 723 #endif
 724     {
 725       if (ShenandoahCASBarrier) {
 726         load_store = kit->gvn().transform(new ShenandoahCompareAndExchangePNode(kit->control(), mem, adr, new_val, expected_val, adr_type, value_type->is_oopptr(), mo));
 727       } else {
 728         load_store = kit->gvn().transform(new CompareAndExchangePNode(kit->control(), mem, adr, new_val, expected_val, adr_type, value_type->is_oopptr(), mo));
 729       }
 730     }
 731 
 732     access.set_raw_access(load_store);
 733     pin_atomic_op(access);
 734 
 735 #ifdef _LP64
 736     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 737       load_store = kit->gvn().transform(new DecodeNNode(load_store, load_store->get_ptr_type()));


 738     }
 739 #endif
 740     load_store = kit->gvn().transform(new ShenandoahLoadReferenceBarrierNode(nullptr, load_store, access.decorators()));
 741     if (ShenandoahCardBarrier) {
 742       post_barrier(kit, kit->control(), access.raw_access(), access.base(),
 743                    access.addr().node(), access.alias_idx(), new_val, T_OBJECT, true);
 744     }
 745     return load_store;
 746   }
 747   return BarrierSetC2::atomic_cmpxchg_val_at_resolved(access, expected_val, new_val, value_type);
 748 }
 749 
 750 Node* ShenandoahBarrierSetC2::atomic_cmpxchg_bool_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
 751                                                               Node* new_val, const Type* value_type) const {
 752   GraphKit* kit = access.kit();
 753   if (access.is_oop()) {
 754     shenandoah_write_barrier_pre(kit, false /* do_load */,
 755                                  nullptr, nullptr, max_juint, nullptr, nullptr,
 756                                  expected_val /* pre_val */, T_OBJECT);
 757     DecoratorSet decorators = access.decorators();
 758     MemNode::MemOrd mo = access.mem_node_mo();
 759     Node* mem = access.memory();
 760     bool is_weak_cas = (decorators & C2_WEAK_CMPXCHG) != 0;
 761     Node* load_store = nullptr;
 762     Node* adr = access.addr().node();
 763 #ifdef _LP64
 764     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 765       Node *newval_enc = kit->gvn().transform(new EncodePNode(new_val, new_val->bottom_type()->make_narrowoop()));
 766       Node *oldval_enc = kit->gvn().transform(new EncodePNode(expected_val, expected_val->bottom_type()->make_narrowoop()));
 767       if (ShenandoahCASBarrier) {
 768         if (is_weak_cas) {
 769           load_store = kit->gvn().transform(new ShenandoahWeakCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 770         } else {
 771           load_store = kit->gvn().transform(new ShenandoahCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 772         }
 773       } else {
 774         if (is_weak_cas) {
 775           load_store = kit->gvn().transform(new WeakCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 776         } else {
 777           load_store = kit->gvn().transform(new CompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 778         }
 779       }
 780     } else
 781 #endif
 782     {
 783       if (ShenandoahCASBarrier) {
 784         if (is_weak_cas) {
 785           load_store = kit->gvn().transform(new ShenandoahWeakCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 786         } else {
 787           load_store = kit->gvn().transform(new ShenandoahCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 788         }
 789       } else {
 790         if (is_weak_cas) {
 791           load_store = kit->gvn().transform(new WeakCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 792         } else {
 793           load_store = kit->gvn().transform(new CompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 794         }
 795       }
 796     }
 797     access.set_raw_access(load_store);
 798     pin_atomic_op(access);
 799     if (ShenandoahCardBarrier) {
 800       post_barrier(kit, kit->control(), access.raw_access(), access.base(),
 801                    access.addr().node(), access.alias_idx(), new_val, T_OBJECT, true);
 802     }
 803     return load_store;
 804   }
 805   return BarrierSetC2::atomic_cmpxchg_bool_at_resolved(access, expected_val, new_val, value_type);
 806 }
 807 
 808 Node* ShenandoahBarrierSetC2::atomic_xchg_at_resolved(C2AtomicParseAccess& access, Node* val, const Type* value_type) const {
 809   GraphKit* kit = access.kit();
 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 bool ShenandoahBarrierSetC2::is_gc_barrier_node(Node* node) const {
 830   return (node->Opcode() == Op_ShenandoahLoadReferenceBarrier) ||
 831          is_shenandoah_lrb_call(node) ||
 832          is_shenandoah_wb_pre_call(node) ||
 833          is_shenandoah_clone_call(node);
 834 }
 835 
 836 Node* ShenandoahBarrierSetC2::step_over_gc_barrier(Node* c) const {
 837   if (c == nullptr) {
 838     return c;
 839   }
 840   if (c->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
 841     return c->in(ShenandoahLoadReferenceBarrierNode::ValueIn);














 842   }
 843   return c;
 844 }
 845 
 846 bool ShenandoahBarrierSetC2::expand_barriers(Compile* C, PhaseIterGVN& igvn) const {
 847   return !ShenandoahBarrierC2Support::expand(C, igvn);
 848 }
 849 
 850 bool ShenandoahBarrierSetC2::optimize_loops(PhaseIdealLoop* phase, LoopOptsMode mode, VectorSet& visited, Node_Stack& nstack, Node_List& worklist) const {
 851   if (mode == LoopOptsShenandoahExpand) {
 852     assert(UseShenandoahGC, "only for shenandoah");
 853     ShenandoahBarrierC2Support::pin_and_expand(phase);
 854     return true;
 855   }
 856   return false;

 857 }
 858 
 859 bool ShenandoahBarrierSetC2::array_copy_requires_gc_barriers(bool tightly_coupled_alloc, BasicType type, bool is_clone, bool is_clone_instance, ArrayCopyPhase phase) const {
 860   bool is_oop = is_reference_type(type);
 861   if (!is_oop) {
 862     return false;
 863   }
 864   if (ShenandoahSATBBarrier && tightly_coupled_alloc) {
 865     if (phase == Optimization) {
 866       return false;
 867     }
 868     return !is_clone;
 869   }
 870   return true;
 871 }
 872 
 873 bool ShenandoahBarrierSetC2::clone_needs_barrier(Node* src, PhaseGVN& gvn) {
 874   const TypeOopPtr* src_type = gvn.type(src)->is_oopptr();



 875   if (src_type->isa_instptr() != nullptr) {

 876     ciInstanceKlass* ik = src_type->is_instptr()->instance_klass();
 877     if ((src_type->klass_is_exact() || !ik->has_subklass()) && !ik->has_injected_fields()) {
 878       if (ik->has_object_fields()) {
 879         return true;
 880       } else {
 881         if (!src_type->klass_is_exact()) {
 882           Compile::current()->dependencies()->assert_leaf_type(ik);
 883         }
 884       }
 885     } else {
 886       return true;
 887         }
 888   } else if (src_type->isa_aryptr()) {
 889     BasicType src_elem = src_type->isa_aryptr()->elem()->array_element_basic_type();
 890     if (is_reference_type(src_elem, true)) {
 891       return true;


 892     }




































 893   } else {
 894     return true;
 895   }
 896   return false;
 897 }
 898 
 899 void ShenandoahBarrierSetC2::clone_at_expansion(PhaseMacroExpand* phase, ArrayCopyNode* ac) const {
 900   Node* ctrl = ac->in(TypeFunc::Control);
 901   Node* mem = ac->in(TypeFunc::Memory);
 902   Node* src_base = ac->in(ArrayCopyNode::Src);
 903   Node* src_offset = ac->in(ArrayCopyNode::SrcPos);
 904   Node* dest_base = ac->in(ArrayCopyNode::Dest);
 905   Node* dest_offset = ac->in(ArrayCopyNode::DestPos);
 906   Node* length = ac->in(ArrayCopyNode::Length);
 907 
 908   Node* src = phase->basic_plus_adr(src_base, src_offset);
 909   Node* dest = phase->basic_plus_adr(dest_base, dest_offset);
 910 
 911   if (ShenandoahCloneBarrier && clone_needs_barrier(src, phase->igvn())) {
 912     // Check if heap is has forwarded objects. If it does, we need to call into the special
 913     // routine that would fix up source references before we can continue.
 914 
 915     enum { _heap_stable = 1, _heap_unstable, PATH_LIMIT };
 916     Node* region = new RegionNode(PATH_LIMIT);
 917     Node* mem_phi = new PhiNode(region, Type::MEMORY, TypeRawPtr::BOTTOM);
 918 
 919     Node* thread = phase->transform_later(new ThreadLocalNode());
 920     Node* offset = phase->igvn().MakeConX(in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 921     Node* gc_state_addr = phase->transform_later(AddPNode::make_off_heap(thread, offset));
 922 
 923     uint gc_state_idx = Compile::AliasIdxRaw;
 924     const TypePtr* gc_state_adr_type = nullptr; // debug-mode-only argument
 925     DEBUG_ONLY(gc_state_adr_type = phase->C->get_adr_type(gc_state_idx));
 926 
 927     Node* gc_state    = phase->transform_later(new LoadBNode(ctrl, mem, gc_state_addr, gc_state_adr_type, TypeInt::BYTE, MemNode::unordered));
 928     Node* stable_and  = phase->transform_later(new AndINode(gc_state, phase->igvn().intcon(ShenandoahHeap::HAS_FORWARDED)));
 929     Node* stable_cmp  = phase->transform_later(new CmpINode(stable_and, phase->igvn().zerocon(T_INT)));
 930     Node* stable_test = phase->transform_later(new BoolNode(stable_cmp, BoolTest::ne));
 931 
 932     IfNode* stable_iff  = phase->transform_later(new IfNode(ctrl, stable_test, PROB_UNLIKELY(0.999), COUNT_UNKNOWN))->as_If();
 933     Node* stable_ctrl   = phase->transform_later(new IfFalseNode(stable_iff));
 934     Node* unstable_ctrl = phase->transform_later(new IfTrueNode(stable_iff));
 935 
 936     // Heap is stable, no need to do anything additional
 937     region->init_req(_heap_stable, stable_ctrl);
 938     mem_phi->init_req(_heap_stable, mem);
 939 
 940     // Heap is unstable, call into clone barrier stub
 941     Node* call = phase->make_leaf_call(unstable_ctrl, mem,
 942                                        ShenandoahBarrierSetC2::clone_barrier_Type(),
 943                                        CAST_FROM_FN_PTR(address, ShenandoahRuntime::clone_barrier),
 944                                        "shenandoah_clone",
 945                                        TypeRawPtr::BOTTOM,
 946                                        src_base);
 947     call = phase->transform_later(call);
 948 
 949     ctrl = phase->transform_later(new ProjNode(call, TypeFunc::Control));
 950     mem = phase->transform_later(new ProjNode(call, TypeFunc::Memory));
 951     region->init_req(_heap_unstable, ctrl);
 952     mem_phi->init_req(_heap_unstable, mem);
 953 
 954     // Wire up the actual arraycopy stub now
 955     ctrl = phase->transform_later(region);
 956     mem = phase->transform_later(mem_phi);
 957 
 958     const char* name = "arraycopy";
 959     call = phase->make_leaf_call(ctrl, mem,
 960                                  OptoRuntime::fast_arraycopy_Type(),
 961                                  phase->basictype2arraycopy(T_LONG, nullptr, nullptr, true, name, true),
 962                                  name, TypeRawPtr::BOTTOM,
 963                                  src, dest, length
 964                                  LP64_ONLY(COMMA phase->top()));
 965     call = phase->transform_later(call);
 966 
 967     // Hook up the whole thing into the graph
 968     phase->igvn().replace_node(ac, call);
 969   } else {
 970     BarrierSetC2::clone_at_expansion(phase, ac);

 971   }

































 972 }
 973 



 974 
 975 // Support for macro expanded GC barriers
 976 void ShenandoahBarrierSetC2::register_potential_barrier_node(Node* node) const {
 977   if (node->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
 978     state()->add_load_reference_barrier((ShenandoahLoadReferenceBarrierNode*) node);
 979   }
 980 }
 981 
 982 void ShenandoahBarrierSetC2::unregister_potential_barrier_node(Node* node) const {
 983   if (node->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
 984     state()->remove_load_reference_barrier((ShenandoahLoadReferenceBarrierNode*) node);


 985   }
 986 }
 987 
 988 void ShenandoahBarrierSetC2::eliminate_gc_barrier(PhaseMacroExpand* macro, Node* node) const {
 989   if (is_shenandoah_wb_pre_call(node)) {
 990     shenandoah_eliminate_wb_pre(node, &macro->igvn());
 991   }
 992   if (ShenandoahCardBarrier && node->Opcode() == Op_CastP2X) {
 993     for (DUIterator_Last imin, i = node->last_outs(imin); i >= imin; --i) {
 994       Node* shift = node->last_out(i);
 995       for (DUIterator_Last kmin, k = shift->last_outs(kmin); k >= kmin; --k) {
 996         Node* addp = shift->last_out(k);
 997         for (DUIterator_Last jmin, j = addp->last_outs(jmin); j >= jmin; --j) {
 998           Node* mem = addp->last_out(j);
 999           if (UseCondCardMark && mem->is_Load()) {
1000             assert(mem->Opcode() == Op_LoadB, "unexpected code shape");
1001             // The load is checking if the card has been written so
1002             // replace it with zero to fold the test.
1003             macro->replace_node(mem, macro->intcon(0));
1004             continue;
1005           }
1006           assert(mem->is_Store(), "store required");
1007           macro->replace_node(mem, mem->in(MemNode::Memory));
1008         }
1009       }
1010     }
1011   }
1012 }
1013 
1014 void ShenandoahBarrierSetC2::shenandoah_eliminate_wb_pre(Node* call, PhaseIterGVN* igvn) const {
1015   assert(UseShenandoahGC && is_shenandoah_wb_pre_call(call), "");
1016   Node* c = call->as_Call()->proj_out(TypeFunc::Control);
1017   c = c->unique_ctrl_out();
1018   assert(c->is_Region() && c->req() == 3, "where's the pre barrier control flow?");
1019   c = c->unique_ctrl_out();
1020   assert(c->is_Region() && c->req() == 3, "where's the pre barrier control flow?");
1021   Node* iff = c->in(1)->is_IfProj() ? c->in(1)->in(0) : c->in(2)->in(0);
1022   assert(iff->is_If(), "expect test");
1023   if (!is_shenandoah_marking_if(igvn, iff)) {
1024     c = c->unique_ctrl_out();
1025     assert(c->is_Region() && c->req() == 3, "where's the pre barrier control flow?");
1026     iff = c->in(1)->is_IfProj() ? c->in(1)->in(0) : c->in(2)->in(0);
1027     assert(is_shenandoah_marking_if(igvn, iff), "expect marking test");
1028   }
1029   Node* cmpx = iff->in(1)->in(1);
1030   igvn->replace_node(cmpx, igvn->makecon(TypeInt::CC_EQ));
1031   igvn->rehash_node_delayed(call);
1032   call->del_req(call->req()-1);
1033 }
1034 
1035 void ShenandoahBarrierSetC2::enqueue_useful_gc_barrier(PhaseIterGVN* igvn, Node* node) const {
1036   if (node->Opcode() == Op_AddP && ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(node)) {
1037     igvn->add_users_to_worklist(node);
1038   }
1039 }
1040 
1041 void ShenandoahBarrierSetC2::eliminate_useless_gc_barriers(Unique_Node_List &useful, Compile* C) const {
1042   for (uint i = 0; i < useful.size(); i++) {
1043     Node* n = useful.at(i);
1044     if (n->Opcode() == Op_AddP && ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(n)) {
1045       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1046         C->record_for_igvn(n->fast_out(i));
1047       }
1048     }
1049   }
1050 
1051   for (int i = state()->load_reference_barriers_count() - 1; i >= 0; i--) {
1052     ShenandoahLoadReferenceBarrierNode* n = state()->load_reference_barrier(i);
1053     if (!useful.member(n)) {
1054       state()->remove_load_reference_barrier(n);
1055     }
1056   }
1057 }
1058 
1059 void* ShenandoahBarrierSetC2::create_barrier_state(Arena* comp_arena) const {
1060   return new(comp_arena) ShenandoahBarrierSetC2State(comp_arena);
1061 }

1062 
1063 ShenandoahBarrierSetC2State* ShenandoahBarrierSetC2::state() const {
1064   return reinterpret_cast<ShenandoahBarrierSetC2State*>(Compile::current()->barrier_set_state());











1065 }
1066 
1067 // If the BarrierSetC2 state has kept macro nodes in its compilation unit state to be
1068 // expanded later, then now is the time to do so.
1069 bool ShenandoahBarrierSetC2::expand_macro_nodes(PhaseMacroExpand* macro) const { return false; }
1070 
1071 #ifdef ASSERT












1072 void ShenandoahBarrierSetC2::verify_gc_barriers(Compile* compile, CompilePhase phase) const {
1073   if (ShenandoahVerifyOptoBarriers && phase == BarrierSetC2::BeforeMacroExpand) {
1074     ShenandoahBarrierC2Support::verify(Compile::current()->root());
1075   } else if (phase == BarrierSetC2::BeforeCodeGen) {
1076     // Verify Shenandoah pre-barriers
1077     const int gc_state_offset = in_bytes(ShenandoahThreadLocalData::gc_state_offset());
1078 
1079     Unique_Node_List visited;
1080     Node_List worklist;
1081     // We're going to walk control flow backwards starting from the Root
1082     worklist.push(compile->root());
1083     while (worklist.size() > 0) {
1084       Node *x = worklist.pop();
1085       if (x == nullptr || x == compile->top()) {
1086         continue;
1087       }
1088 
1089       if (visited.member(x)) {
1090         continue;
1091       } else {
1092         visited.push(x);
1093       }
















































1094 
1095       if (x->is_Region()) {
1096         for (uint i = 1; i < x->req(); i++) {
1097           worklist.push(x->in(i));













1098         }
1099       } else {
1100         worklist.push(x->in(0));
1101         // We are looking for the pattern:
1102         //                            /->ThreadLocal
1103         // If->Bool->CmpI->LoadB->AddP->ConL(marking_offset)
1104         //              \->ConI(0)
1105         // We want to verify that the If and the LoadB have the same control
1106         // See GraphKit::g1_write_barrier_pre()
1107         if (x->is_If()) {
1108           IfNode *iff = x->as_If();
1109           if (iff->in(1)->is_Bool() && iff->in(1)->in(1)->is_Cmp()) {
1110             CmpNode *cmp = iff->in(1)->in(1)->as_Cmp();
1111             if (cmp->Opcode() == Op_CmpI && cmp->in(2)->is_Con() && cmp->in(2)->bottom_type()->is_int()->get_con() == 0
1112                 && cmp->in(1)->is_Load()) {
1113               LoadNode *load = cmp->in(1)->as_Load();
1114               if (load->Opcode() == Op_LoadB && load->in(2)->is_AddP() && load->in(2)->in(2)->Opcode() == Op_ThreadLocal
1115                   && load->in(2)->in(3)->is_Con()
1116                   && load->in(2)->in(3)->bottom_type()->is_intptr_t()->get_con() == gc_state_offset) {
1117 
1118                 Node *if_ctrl = iff->in(0);
1119                 Node *load_ctrl = load->in(0);
1120 
1121                 if (if_ctrl != load_ctrl) {
1122                   // Skip possible CProj->NeverBranch in infinite loops
1123                   if ((if_ctrl->is_Proj() && if_ctrl->Opcode() == Op_CProj)
1124                       && if_ctrl->in(0)->is_NeverBranch()) {
1125                     if_ctrl = if_ctrl->in(0)->in(0);
1126                   }
1127                 }
1128                 assert(load_ctrl != nullptr && if_ctrl == load_ctrl, "controls must match");
1129               }
1130             }
1131           }
1132         }















1133       }
1134     }
1135   }
1136 }
1137 #endif
1138 
1139 Node* ShenandoahBarrierSetC2::ideal_node(PhaseGVN* phase, Node* n, bool can_reshape) const {
1140   if (is_shenandoah_wb_pre_call(n)) {
1141     uint cnt = ShenandoahBarrierSetC2::write_barrier_pre_Type()->domain()->cnt();
1142     if (n->req() > cnt) {
1143       Node* addp = n->in(cnt);
1144       if (has_only_shenandoah_wb_pre_uses(addp)) {
1145         n->del_req(cnt);
1146         if (can_reshape) {
1147           phase->is_IterGVN()->_worklist.push(addp);
1148         }
1149         return n;
1150       }



















1151     }

1152   }
1153   if (n->Opcode() == Op_CmpP) {
1154     Node* in1 = n->in(1);
1155     Node* in2 = n->in(2);
1156 
1157     // If one input is null, then step over the strong LRB barriers on the other input
1158     if (in1->bottom_type() == TypePtr::NULL_PTR &&
1159         !((in2->Opcode() == Op_ShenandoahLoadReferenceBarrier) &&
1160           !ShenandoahBarrierSet::is_strong_access(((ShenandoahLoadReferenceBarrierNode*)in2)->decorators()))) {
1161       in2 = step_over_gc_barrier(in2);
1162     }
1163     if (in2->bottom_type() == TypePtr::NULL_PTR &&
1164         !((in1->Opcode() == Op_ShenandoahLoadReferenceBarrier) &&
1165           !ShenandoahBarrierSet::is_strong_access(((ShenandoahLoadReferenceBarrierNode*)in1)->decorators()))) {
1166       in1 = step_over_gc_barrier(in1);
1167     }
1168 
1169     if (in1 != n->in(1)) {
1170       n->set_req_X(1, in1, phase);
1171       assert(in2 == n->in(2), "only one change");
1172       return n;
1173     }
1174     if (in2 != n->in(2)) {
1175       n->set_req_X(2, in2, phase);
1176       return n;
1177     }
1178   } else if (can_reshape &&
1179              n->Opcode() == Op_If &&
1180              ShenandoahBarrierC2Support::is_heap_stable_test(n) &&
1181              n->in(0) != nullptr &&
1182              n->outcnt() == 2) {
1183     Node* dom = n->in(0);
1184     Node* prev_dom = n;
1185     int op = n->Opcode();
1186     int dist = 16;
1187     // Search up the dominator tree for another heap stable test
1188     while (dom->Opcode() != op    ||  // Not same opcode?
1189            !ShenandoahBarrierC2Support::is_heap_stable_test(dom) ||  // Not same input 1?
1190            prev_dom->in(0) != dom) {  // One path of test does not dominate?
1191       if (dist < 0) return nullptr;
1192 
1193       dist--;
1194       prev_dom = dom;
1195       dom = IfNode::up_one_dom(dom);
1196       if (!dom) return nullptr;
1197     }
1198 
1199     // Check that we did not follow a loop back to ourselves
1200     if (n == dom) {
1201       return nullptr;
1202     }
1203 
1204     return n->as_If()->dominated_by(prev_dom, phase->is_IterGVN(), false);


1205   }

1206 
1207   return nullptr;



1208 }
1209 
1210 bool ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(Node* n) {
1211   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1212     Node* u = n->fast_out(i);
1213     if (!is_shenandoah_wb_pre_call(u)) {
1214       return false;
1215     }






1216   }
1217   return n->outcnt() > 0;
1218 }
1219 
1220 bool ShenandoahBarrierSetC2::final_graph_reshaping(Compile* compile, Node* n, uint opcode, Unique_Node_List& dead_nodes) const {
1221   switch (opcode) {
1222     case Op_CallLeaf:
1223     case Op_CallLeafNoFP: {
1224       assert (n->is_Call(), "");
1225       CallNode *call = n->as_Call();
1226       if (ShenandoahBarrierSetC2::is_shenandoah_wb_pre_call(call)) {
1227         uint cnt = ShenandoahBarrierSetC2::write_barrier_pre_Type()->domain()->cnt();
1228         if (call->req() > cnt) {
1229           assert(call->req() == cnt + 1, "only one extra input");
1230           Node *addp = call->in(cnt);
1231           assert(!ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(addp), "useless address computation?");
1232           call->del_req(cnt);
1233         }
1234       }
1235       return false;
1236     }
1237     case Op_ShenandoahCompareAndSwapP:
1238     case Op_ShenandoahCompareAndSwapN:
1239     case Op_ShenandoahWeakCompareAndSwapN:
1240     case Op_ShenandoahWeakCompareAndSwapP:
1241     case Op_ShenandoahCompareAndExchangeP:
1242     case Op_ShenandoahCompareAndExchangeN:
1243       return true;
1244     case Op_ShenandoahLoadReferenceBarrier:
1245       assert(false, "should have been expanded already");
1246       return true;
1247     default:
1248       return false;
1249   }
1250 }
1251 
1252 bool ShenandoahBarrierSetC2::escape_add_to_con_graph(ConnectionGraph* conn_graph, PhaseGVN* gvn, Unique_Node_List* delayed_worklist, Node* n, uint opcode) const {
1253   switch (opcode) {
1254     case Op_ShenandoahCompareAndExchangeP:
1255     case Op_ShenandoahCompareAndExchangeN:
1256       conn_graph->add_objload_to_connection_graph(n, delayed_worklist);
1257       // fallthrough
1258     case Op_ShenandoahWeakCompareAndSwapP:
1259     case Op_ShenandoahWeakCompareAndSwapN:
1260     case Op_ShenandoahCompareAndSwapP:
1261     case Op_ShenandoahCompareAndSwapN:
1262       conn_graph->add_to_congraph_unsafe_access(n, opcode, delayed_worklist);
1263       return true;
1264     case Op_StoreP: {
1265       Node* adr = n->in(MemNode::Address);
1266       const Type* adr_type = gvn->type(adr);
1267       // Pointer stores in Shenandoah barriers looks like unsafe access.
1268       // Ignore such stores to be able scalar replace non-escaping
1269       // allocations.
1270       if (adr_type->isa_rawptr() && adr->is_AddP()) {
1271         Node* base = conn_graph->get_addp_base(adr);
1272         if (base->Opcode() == Op_LoadP &&
1273           base->in(MemNode::Address)->is_AddP()) {
1274           adr = base->in(MemNode::Address);
1275           Node* tls = conn_graph->get_addp_base(adr);
1276           if (tls->Opcode() == Op_ThreadLocal) {
1277              int offs = (int) gvn->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
1278              const int buf_offset = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset());
1279              if (offs == buf_offset) {
1280                return true; // Pre barrier previous oop value store.
1281              }
1282           }
1283         }
1284       }
1285       return false;
1286     }
1287     case Op_ShenandoahLoadReferenceBarrier:
1288       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(ShenandoahLoadReferenceBarrierNode::ValueIn), delayed_worklist);
1289       return true;
1290     default:
1291       // Nothing
1292       break;
1293   }
1294   return false;
1295 }
1296 
1297 bool ShenandoahBarrierSetC2::escape_add_final_edges(ConnectionGraph* conn_graph, PhaseGVN* gvn, Node* n, uint opcode) const {
1298   switch (opcode) {
1299     case Op_ShenandoahCompareAndExchangeP:
1300     case Op_ShenandoahCompareAndExchangeN: {
1301       Node *adr = n->in(MemNode::Address);
1302       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, adr, nullptr);
1303       // fallthrough
1304     }
1305     case Op_ShenandoahCompareAndSwapP:
1306     case Op_ShenandoahCompareAndSwapN:
1307     case Op_ShenandoahWeakCompareAndSwapP:
1308     case Op_ShenandoahWeakCompareAndSwapN:
1309       return conn_graph->add_final_edges_unsafe_access(n, opcode);
1310     case Op_ShenandoahLoadReferenceBarrier:
1311       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(ShenandoahLoadReferenceBarrierNode::ValueIn), nullptr);
1312       return true;
1313     default:
1314       // Nothing
1315       break;
1316   }
1317   return false;
1318 }
1319 
1320 bool ShenandoahBarrierSetC2::escape_has_out_with_unsafe_object(Node* n) const {
1321   return n->has_out_with(Op_ShenandoahCompareAndExchangeP) || n->has_out_with(Op_ShenandoahCompareAndExchangeN) ||
1322          n->has_out_with(Op_ShenandoahCompareAndSwapP, Op_ShenandoahCompareAndSwapN, Op_ShenandoahWeakCompareAndSwapP, Op_ShenandoahWeakCompareAndSwapN);
1323 


1324 }
1325 
1326 bool ShenandoahBarrierSetC2::matcher_find_shared_post_visit(Matcher* matcher, Node* n, uint opcode) const {
1327   switch (opcode) {
1328     case Op_ShenandoahCompareAndExchangeP:
1329     case Op_ShenandoahCompareAndExchangeN:
1330     case Op_ShenandoahWeakCompareAndSwapP:
1331     case Op_ShenandoahWeakCompareAndSwapN:
1332     case Op_ShenandoahCompareAndSwapP:
1333     case Op_ShenandoahCompareAndSwapN: {   // Convert trinary to binary-tree
1334       Node* newval = n->in(MemNode::ValueIn);
1335       Node* oldval = n->in(LoadStoreConditionalNode::ExpectedIn);
1336       Node* pair = new BinaryNode(oldval, newval);
1337       n->set_req(MemNode::ValueIn,pair);
1338       n->del_req(LoadStoreConditionalNode::ExpectedIn);
1339       return true;

















































1340     }
1341     default:
1342       break;
1343   }
1344   return false;


1345 }
1346 
1347 bool ShenandoahBarrierSetC2::matcher_is_store_load_barrier(Node* x, uint xop) const {
1348   return xop == Op_ShenandoahCompareAndExchangeP ||
1349          xop == Op_ShenandoahCompareAndExchangeN ||
1350          xop == Op_ShenandoahWeakCompareAndSwapP ||
1351          xop == Op_ShenandoahWeakCompareAndSwapN ||
1352          xop == Op_ShenandoahCompareAndSwapN ||
1353          xop == Op_ShenandoahCompareAndSwapP;
1354 }

   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 "classfile/javaClasses.inline.hpp"
  27 #include "gc/shared/barrierSet.hpp"
  28 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"

  29 #include "gc/shenandoah/heuristics/shenandoahHeuristics.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 "opto/arraycopynode.hpp"
  35 #include "opto/escape.hpp"
  36 #include "opto/graphKit.hpp"
  37 #include "opto/idealKit.hpp"
  38 #include "opto/macro.hpp"

  39 #include "opto/narrowptrnode.hpp"
  40 #include "opto/output.hpp"
  41 #include "opto/rootnode.hpp"
  42 #include "opto/runtime.hpp"
  43 
  44 ShenandoahBarrierSetC2* ShenandoahBarrierSetC2::bsc2() {
  45   return reinterpret_cast<ShenandoahBarrierSetC2*>(BarrierSet::barrier_set()->barrier_set_c2());
  46 }
  47 
  48 ShenandoahBarrierSetC2State::ShenandoahBarrierSetC2State(Arena* comp_arena) :
  49     BarrierSetC2State(comp_arena),
  50     _stubs(new (comp_arena) GrowableArray<ShenandoahBarrierStubC2*>(comp_arena, 8,  0, nullptr)),
  51     _trampoline_stubs_count(0),
  52     _stubs_start_offset(0),
  53     _stubs_current_total_size(0) {
  54 }
  55 
  56 static void set_barrier_data(C2Access& access, bool load, bool store) {
  57   if (!access.is_oop()) {
  58     return;













  59   }



  60 
  61   DecoratorSet decorators = access.decorators();
  62   bool tightly_coupled = (decorators & C2_TIGHTLY_COUPLED_ALLOC) != 0;
  63   bool in_heap = (decorators & IN_HEAP) != 0;
  64   bool on_weak = (decorators & ON_WEAK_OOP_REF) != 0;
  65   bool on_phantom = (decorators & ON_PHANTOM_OOP_REF) != 0;




  66 
  67   if (tightly_coupled) {
  68     access.set_barrier_data(ShenandoahBitElided);
  69     return;
  70   }
  71 
  72   uint8_t barrier_data = 0;


































  73 
  74   if (load) {
  75     if (ShenandoahLoadRefBarrier) {
  76       if (on_phantom) {
  77         barrier_data |= ShenandoahBitPhantom;
  78       } else if (on_weak) {
  79         barrier_data |= ShenandoahBitWeak;
  80       } else {
  81         barrier_data |= ShenandoahBitStrong;
















  82       }
  83     }




  84   }
  85 
  86   if (store) {
  87     if (ShenandoahSATBBarrier) {
  88       barrier_data |= ShenandoahBitKeepAlive;
  89     }
  90     if (ShenandoahCardBarrier && in_heap) {
  91       barrier_data |= ShenandoahBitCardMark;





















  92     }







  93   }





  94 
  95   if (!in_heap) {
  96     barrier_data |= ShenandoahBitNative;
  97   }






























  98 
  99   access.set_barrier_data(barrier_data);
 100 }

 101 
 102 Node* ShenandoahBarrierSetC2::load_at_resolved(C2Access& access, const Type* val_type) const {
 103   // 1: Non-reference load, no additional barrier is needed
 104   if (!access.is_oop()) {
 105     return BarrierSetC2::load_at_resolved(access, val_type);
 106   }
 107 
 108   // 2. Set barrier data for load
 109   set_barrier_data(access, /* load = */ true, /* store = */ false);
 110 
 111   // 3. Correction: If we are reading the value of the referent field of
 112   // a Reference object, we need to record the referent resurrection.
 113   DecoratorSet decorators = access.decorators();
 114   bool on_weak = (decorators & ON_WEAK_OOP_REF) != 0;
 115   bool on_phantom = (decorators & ON_PHANTOM_OOP_REF) != 0;
 116   bool no_keepalive = (decorators & AS_NO_KEEPALIVE) != 0;
 117   bool needs_keepalive = ((on_weak || on_phantom) && !no_keepalive);
 118   if (needs_keepalive) {
 119     uint8_t barriers = access.barrier_data() | (ShenandoahSATBBarrier ? ShenandoahBitKeepAlive : 0);
 120     access.set_barrier_data(barriers);
 121   }
 122 
 123   return BarrierSetC2::load_at_resolved(access, val_type);
 124 }
 125 
 126 Node* ShenandoahBarrierSetC2::store_at_resolved(C2Access& access, C2AccessValue& val) const {
 127   // 1: Non-reference store, no additional barrier is needed
 128   if (!access.is_oop()) {
 129     return BarrierSetC2::store_at_resolved(access, val);
 130   }

 131 
 132   // 2. Set barrier data for store
 133   set_barrier_data(access, /* load = */ false, /* store = */ true);
 134 
 135   // 3. Correction: avoid keep-alive barriers that should not do keep-alive.
 136   DecoratorSet decorators = access.decorators();
 137   bool no_keepalive = (decorators & AS_NO_KEEPALIVE) != 0;
 138   if (no_keepalive) {
 139     access.set_barrier_data(access.barrier_data() & ~ShenandoahBitKeepAlive);
 140   }

 141 
 142   return BarrierSetC2::store_at_resolved(access, val);


 143 }
 144 
 145 Node* ShenandoahBarrierSetC2::atomic_cmpxchg_val_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
 146                                                              Node* new_val, const Type* value_type) const {
 147   set_barrier_data(access, /* load = */ true, /* store = */ true);
 148   return BarrierSetC2::atomic_cmpxchg_val_at_resolved(access, expected_val, new_val, value_type);
 149 }
 150 
 151 Node* ShenandoahBarrierSetC2::atomic_cmpxchg_bool_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
 152                                                               Node* new_val, const Type* value_type) const {
 153   set_barrier_data(access, /* load = */ true, /* store = */ true);
 154   return BarrierSetC2::atomic_cmpxchg_bool_at_resolved(access, expected_val, new_val, value_type);








 155 }
 156 
 157 Node* ShenandoahBarrierSetC2::atomic_xchg_at_resolved(C2AtomicParseAccess& access, Node* val, const Type* value_type) const {
 158   set_barrier_data(access, /* load = */ true, /* store = */ true);
 159   return BarrierSetC2::atomic_xchg_at_resolved(access, val, value_type);
 160 }
 161 
 162 bool ShenandoahBarrierSetC2::is_Load(int opcode) {
 163   switch (opcode) {
 164     case Op_LoadN:
 165     case Op_LoadP:
 166       return true;
 167     default:
 168       return false;


 169   }


 170 }
 171 
 172 bool ShenandoahBarrierSetC2::is_Store(int opcode) {
 173   switch (opcode) {
 174     case Op_StoreN:
 175     case Op_StoreP:
 176       return true;
 177     default:
 178       return false;
 179   }
 180 }
 181 
 182 bool ShenandoahBarrierSetC2::is_LoadStore(int opcode) {
 183   switch (opcode) {
 184     case Op_CompareAndExchangeN:
 185     case Op_CompareAndExchangeP:
 186     case Op_WeakCompareAndSwapN:
 187     case Op_WeakCompareAndSwapP:
 188     case Op_CompareAndSwapN:
 189     case Op_CompareAndSwapP:
 190     case Op_GetAndSetP:
 191     case Op_GetAndSetN:
 192       return true;
 193     default:
 194       return false;




 195   }
 196 }
 197 
 198 bool ShenandoahBarrierSetC2::can_remove_load_barrier(Node* root) {
 199   // Check if all outs feed into nodes that do not expose the oops to the rest
 200   // of the runtime system. In this case, we can elide the LRB barrier. We bail
 201   // out with false at the first sight of trouble.















 202 
 203   ResourceMark rm;
 204   VectorSet visited;
 205   Node_List worklist;
 206   worklist.push(root);



 207 
 208   while (worklist.size() > 0) {
 209     Node* n = worklist.pop();
 210     if (visited.test_set(n->_idx)) {
 211       continue;






 212     }













 213 
 214     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
 215       Node* out = n->fast_out(i);
 216       switch (out->Opcode()) {
 217         case Op_Phi:
 218         case Op_EncodeP:
 219         case Op_DecodeN:
 220         case Op_CastPP:
 221         case Op_CheckCastPP:
 222         case Op_AddP: {
 223           // Transitive node, check if any other outs are doing anything troublesome.
 224           worklist.push(out);
 225           break;
 226         }




 227 
 228         case Op_LoadRange: {
 229           // Array length is the same in all copies.
 230           break;
 231         }
 232 
 233         case Op_LoadKlass: {
 234           // Klass is the same in all copies.
 235           // We would have liked to assert -UCOH, but there are legitimate klass
 236           // loads from native Klass* instances, which are also safe under +UCOH.
 237           break;




 238         }


 239 
 240         case Op_LoadNKlass: {
 241           // Similar to above, but LoadNKlass is only safe without +UCOH.
 242           // With +UCOH, it loads from mark word, which clashes with forwarding pointers.
 243           if (!UseCompactObjectHeaders) {
 244             break;
 245           }
 246           return false;
 247         }
 248 
 249         case Op_CmpN: {
 250           if (out->in(1) == n &&
 251               out->in(2)->Opcode() == Op_ConN &&
 252               out->in(2)->get_narrowcon() == 0) {
 253             // Null check, no oop is exposed.
 254             break;
 255           }
 256           if (out->in(2) == n &&
 257               out->in(1)->Opcode() == Op_ConN &&
 258               out->in(1)->get_narrowcon() == 0) {
 259             // Null check, no oop is exposed.
 260             break;
 261           }
 262           return false;
 263         }
 264 
 265         case Op_CmpP: {
 266           if (out->in(1) == n &&
 267               out->in(2)->Opcode() == Op_ConP &&
 268               out->in(2)->get_ptr() == 0) {
 269             // Null check, no oop is exposed.
 270             break;
 271           }
 272           if (out->in(2) == n &&
 273               out->in(1)->Opcode() == Op_ConP &&
 274               out->in(1)->get_ptr() == 0) {
 275             // Null check, no oop is exposed.
 276             break;
 277           }
 278           return false;
 279         }



 280 
 281         case Op_CallStaticJava: {
 282           if (out->as_CallStaticJava()->is_uncommon_trap()) {
 283             // Local feeds into uncommon trap. Deopt machinery handles barriers itself.
 284             break;
 285           }
 286           return false;
 287         }







 288 
 289         default: {
 290           // Paranoidly distrust any other nodes.
 291           return false;
 292         }
 293       }
 294     }
 295   }


 296 
 297   // Nothing troublesome found.
 298   return true;
 299 }













 300 
 301 uint8_t ShenandoahBarrierSetC2::refine_load(Node* n, uint8_t bd) {
 302   assert(ShenandoahElideIdealBarriers, "Checked by caller");
 303   assert(bd != 0, "Checked by caller");
 304 
 305   // Do not touch weak loads at all: they are responsible for shielding from
 306   // Reference.referent resurrection.
 307   if ((bd & (ShenandoahBitWeak | ShenandoahBitPhantom)) != 0) {
 308     return bd;






 309   }
 310 
 311   if (((bd & ShenandoahBitStrong) != 0) && can_remove_load_barrier(n)) {
 312     bd &= ~ShenandoahBitStrong;



 313   }
 314 
 315   return bd;






















































 316 }
 317 
 318 uint8_t ShenandoahBarrierSetC2::refine_store(Node* n, uint8_t bd) {
 319   assert(ShenandoahElideIdealBarriers, "Checked by caller");
 320   assert(bd != 0, "Checked by caller");
 321   assert(n->is_Mem() || n->is_LoadStore(), "Sanity");
 322 
 323   const Node* newval = n->in(MemNode::ValueIn);
 324   assert(newval != nullptr, "Should be present");
 325 
 326   // Type system tells us something about nullity?
 327   const Type* newval_bottom = newval->bottom_type();
 328   assert(newval_bottom->isa_oopptr() || newval_bottom->isa_narrowoop() ||
 329          newval_bottom == TypePtr::NULL_PTR, "Should be an oop store");
 330   const TypePtr* newval_type = newval_bottom->make_ptr();
 331   assert(newval_type != nullptr, "Should have been filtered before");
 332   TypePtr::PTR newval_type_ptr = newval_type->ptr();
 333   if (newval_type_ptr == TypePtr::Null) {
 334     bd &= ~ShenandoahBitNotNull;
 335     // Card table barrier is not needed if we store null.
 336     bd &= ~ShenandoahBitCardMark;
 337   } else if (newval_type_ptr == TypePtr::NotNull) {
 338     // Definitely not null.
 339     bd |= ShenandoahBitNotNull;
 340   }
 341 
 342   return bd;
 343 }
 344 
 345 void ShenandoahBarrierSetC2::final_refinement(Compile* compile) const {
 346   ResourceMark rm;
 347   Unique_Node_List wq;
 348 
 349   RootNode* root = compile->root();
 350   wq.push(root);
 351 
 352   // Also seed the outs to capture nodes are not reachable from in()-s, e.g. endless loops.
 353   for (DUIterator_Fast imax, i = root->fast_outs(imax); i < imax; i++) {
 354     Node* m = root->fast_out(i);
 355     wq.push(m);
 356   }
 357 
 358   for (uint next = 0; next < wq.size(); next++) {
 359     Node* n = wq.at(next);






 360 
 361     assert(!n->is_Mach(), "No Mach nodes here yet");



 362 
 363     int opc = n->Opcode();
 364     bool is_load = is_Load(opc);
 365     bool is_store = is_Store(opc);
 366     bool is_load_store = is_LoadStore(opc);
 367 
 368     uint8_t orig_bd = 0;
 369     if (is_load_store) {
 370       orig_bd = n->as_LoadStore()->barrier_data();
 371     } else if (is_load || is_store) {
 372       orig_bd = n->as_Mem()->barrier_data();

 373     }







 374 
 375     uint8_t bd = orig_bd;
 376     if (ShenandoahElideIdealBarriers && bd != 0) {
 377       // Note: we cannot apply load optimizations to LoadStores,
 378       // because their load barriers are needed for fixups.
 379       if (is_load) {
 380         bd = refine_load(n, bd);
 381       }
 382       if (is_store || is_load_store) {
 383         bd = refine_store(n, bd);
 384       }
 385     }
 386 
 387     // If there are no real barrier flags on the node, strip away additional fluff.
 388     // Matcher does not care about this, and we would like to avoid invoking "barrier_data() != 0"
 389     // rules when the only flags are the irrelevant fluff.
 390     if ((bd != 0) && (bd & ShenandoahBitsReal) == 0) {
 391       bd = 0;


 392     }

 393 
 394     if (bd != orig_bd) {
 395       if (is_load_store) {
 396         n->as_LoadStore()->set_barrier_data(bd);
 397       } else {
 398         n->as_Mem()->set_barrier_data(bd);
 399       }













 400     }
 401 
 402     for (uint j = 0; j < n->req(); j++) {
 403       Node* in = n->in(j);
 404       if (in != nullptr) {
 405         wq.push(in);
 406       }















 407     }
 408   }
 409 }
 410 
 411 // Support for macro expanded GC barriers
 412 void ShenandoahBarrierSetC2::eliminate_gc_barrier_data(Node* node) const {
 413   if (node->is_LoadStore()) {
 414     LoadStoreNode* loadstore = node->as_LoadStore();
 415     loadstore->set_barrier_data(0);
 416   } else if (node->is_Mem()) {
 417     MemNode* mem = node->as_Mem();
 418     mem->set_barrier_data(0);
 419   }
 420 }
 421 
 422 void ShenandoahBarrierSetC2::eliminate_gc_barrier(PhaseMacroExpand* macro, Node* node) const {
 423   eliminate_gc_barrier_data(node);
 424 }
 425 
 426 void ShenandoahBarrierSetC2::elide_dominated_barrier(MachNode* node, MachNode* dominator) const {
 427   uint8_t orig_bd = node->barrier_data();
 428   if (orig_bd == 0) {
 429     // Nothing to do.
 430     return;
 431   }






















 432 
 433   uint8_t bd = orig_bd;
 434   int node_opcode = node->ideal_Opcode();
 435 
 436   if (dominator == nullptr) {
 437     // Must be allocation node.
 438     if (is_Load(node_opcode) || is_LoadStore(node_opcode)) {
 439       // Loads from recent allocations do not need LRBs.
 440       bd &= ~ShenandoahBitStrong;
 441     }
 442     if (is_Store(node_opcode) || is_LoadStore(node_opcode)) {
 443       // Stores to recent allocations do not need KA or CM.
 444       bd &= ~ShenandoahBitKeepAlive;
 445       bd &= ~ShenandoahBitCardMark;

 446     }
 447   } else {
 448     // LoadStores do not get these optimizations, since their LRBs
 449     // are required for fixups.
 450     if (is_Load(node_opcode) || is_Store(node_opcode)) {
 451       int dom_opcode = dominator->ideal_Opcode();
 452       uint8_t dom_bd = dominator->barrier_data();
 453 
 454       if (is_Load(dom_opcode) || is_LoadStore(dom_opcode)) {
 455         // If dominating load is set up to perform LRB fixups, no further LRB is needed.
 456         if ((dom_bd & ShenandoahBitStrong) != 0) {
 457           bd &= ~ShenandoahBitStrong;






















 458         }
 459       }
 460       if (is_Store(dom_opcode)) {
 461         // Dominating store has stored the good ref, no LRB is needed.
 462         bd &= ~ShenandoahBitStrong;












 463       }
 464     }







 465   }


 466 
 467   if (orig_bd != bd) {
 468     // We are already in final output.
 469     // Strip the extra barrier data if no real bits are left.
 470     if ((bd & ShenandoahBitsReal) != 0) {
 471       node->set_barrier_data(bd);
 472     } else {
 473       node->set_barrier_data(0);




 474     }
 475   }

 476 }
 477 
 478 void ShenandoahBarrierSetC2::analyze_dominating_barriers() const {
 479   if (!ShenandoahElideMachBarriers) {
 480     return;
 481   }
 482 
 483   ResourceMark rm;
 484   Node_List accesses, dominators;

 485 
 486   PhaseCFG* const cfg = Compile::current()->cfg();
 487   for (uint i = 0; i < cfg->number_of_blocks(); ++i) {
 488     const Block* const block = cfg->get_block(i);
 489     for (uint j = 0; j < block->number_of_nodes(); ++j) {
 490       Node* const node = block->get_node(j);

 491 
 492       // Everything that happens in allocations does not need barriers.
 493       // Record them for dominance analysis.
 494       if (node->is_Phi() && is_allocation(node)) {
 495         dominators.push(node);
 496         continue;
 497       }
 498 
 499       if (!node->is_Mach()) {
 500         continue;
 501       }
 502 
 503       MachNode* const mach = node->as_Mach();
 504       int opcode = mach->ideal_Opcode();
 505       if (is_Load(opcode) || is_Store(opcode) || is_LoadStore(opcode)) {
 506         if ((mach->barrier_data() & ShenandoahBitsReal) != 0) {
 507           accesses.push(mach);
 508           dominators.push(mach);
 509         }
 510       }
 511     }
 512   }


 513 
 514   elide_dominated_barriers(accesses, dominators);

 515 }
 516 
 517 uint ShenandoahBarrierSetC2::estimated_barrier_size(const Node* node) const {
 518   // Barrier impact on fast-path is driven by GC state checks emitted very late.
 519   // These checks are tight load-test-branch sequences, with no impact on C2 graph
 520   // size. Limiting unrolling in presence of GC barriers might turn some loops
 521   // tighter than with default unrolling, which may benefit performance due to denser
 522   // code. Testing shows it is still counter-productive.
 523   // Therefore, we report zero barrier size to let C2 do its normal thing.
 524   return 0;
 525 }
 526 
 527 bool ShenandoahBarrierSetC2::array_copy_requires_gc_barriers(bool tightly_coupled_alloc, BasicType type, bool is_clone, bool is_clone_instance, ArrayCopyPhase phase) const {
 528   bool is_oop = is_reference_type(type);
 529   if (!is_oop) {
 530     return false;
 531   }
 532   if (ShenandoahSATBBarrier && tightly_coupled_alloc) {
 533     if (phase == Optimization) {
 534       return false;
 535     }
 536     return !is_clone;
 537   }
 538   return true;
 539 }
 540 
 541 bool ShenandoahBarrierSetC2::clone_needs_barrier(const TypeOopPtr* src_type, bool& is_oop_array) {
 542   if (!ShenandoahCloneBarrier) {
 543     return false;
 544   }
 545 
 546   if (src_type->isa_instptr() != nullptr) {
 547     // Instance: need barrier only if there is a possibility of having an oop anywhere in it.
 548     ciInstanceKlass* ik = src_type->is_instptr()->instance_klass();
 549     if ((src_type->klass_is_exact() || !ik->has_subklass()) &&
 550         !ik->has_injected_fields() && !ik->has_object_fields()) {
 551       if (!src_type->klass_is_exact()) {
 552         // Class is *currently* the leaf in the hierarchy.
 553         // Record the dependency so that we deopt if this does not hold in future.
 554         Compile::current()->dependencies()->assert_leaf_type(ik);

 555       }
 556       return false;
 557     }
 558   } else if (src_type->isa_aryptr() != nullptr) {
 559     // Array: need barrier only if array is oop-bearing.
 560     BasicType src_elem = src_type->isa_aryptr()->elem()->array_element_basic_type();
 561     if (is_reference_type(src_elem, true)) {
 562       is_oop_array = true;
 563     } else {
 564       return false;
 565     }
 566   }
 567 
 568   // Assume the worst.
 569   return true;
 570 }
 571 
 572 void ShenandoahBarrierSetC2::clone(GraphKit* kit, Node* src_base, Node* dst_base, Node* size, bool is_array) const {
 573   const TypeOopPtr* src_type = kit->gvn().type(src_base)->is_oopptr();
 574 
 575   bool is_oop_array = false;
 576   if (!clone_needs_barrier(src_type, is_oop_array)) {
 577     // No barrier is needed? Just do what common BarrierSetC2 wants with it.
 578     BarrierSetC2::clone(kit, src_base, dst_base, size, is_array);
 579     return;
 580   }
 581 
 582   if (ShenandoahCloneRuntime || !is_array || !is_oop_array) {
 583     // Looks like an instance? Prepare the instance clone. This would either
 584     // be exploded into individual accesses or be left as runtime call.
 585     // Common BarrierSetC2 prepares everything for both cases.
 586     BarrierSetC2::clone(kit, src_base, dst_base, size, is_array);
 587     return;
 588   }
 589 
 590   // We are cloning the oop array. Prepare to call the normal arraycopy stub
 591   // after the expansion. Normal stub takes the number of actual type-sized
 592   // elements to copy after the base, compute the count here.
 593   Node* offset = kit->MakeConX(arrayOopDesc::base_offset_in_bytes(UseCompressedOops ? T_NARROWOOP : T_OBJECT));
 594   size = kit->gvn().transform(new SubXNode(size, offset));
 595   size = kit->gvn().transform(new URShiftXNode(size, kit->intcon(LogBytesPerHeapOop)));
 596   ArrayCopyNode* ac = ArrayCopyNode::make(kit, false, src_base, offset, dst_base, offset, size, true, false);
 597   ac->set_clone_array();
 598   Node* n = kit->gvn().transform(ac);
 599   if (n == ac) {
 600     ac->set_adr_type(TypeRawPtr::BOTTOM);
 601     kit->set_predefined_output_for_runtime_call(ac, ac->in(TypeFunc::Memory), TypeRawPtr::BOTTOM);
 602   } else {
 603     kit->set_all_memory(n);
 604   }

 605 }
 606 
 607 void ShenandoahBarrierSetC2::clone_at_expansion(PhaseMacroExpand* phase, ArrayCopyNode* ac) const {
 608   Node* const ctrl        = ac->in(TypeFunc::Control);
 609   Node* const mem         = ac->in(TypeFunc::Memory);
 610   Node* const src         = ac->in(ArrayCopyNode::Src);
 611   Node* const src_offset  = ac->in(ArrayCopyNode::SrcPos);
 612   Node* const dest        = ac->in(ArrayCopyNode::Dest);
 613   Node* const dest_offset = ac->in(ArrayCopyNode::DestPos);
 614   Node* length            = ac->in(ArrayCopyNode::Length);
 615 
 616   const TypeOopPtr* src_type = phase->igvn().type(src)->is_oopptr();
 617 
 618   bool is_oop_array = false;
 619   if (!clone_needs_barrier(src_type, is_oop_array)) {
 620     // No barrier is needed? Expand to normal HeapWord-sized arraycopy.

























































 621     BarrierSetC2::clone_at_expansion(phase, ac);
 622     return;
 623   }
 624 
 625   if (ShenandoahCloneRuntime || !ac->is_clone_array() || !is_oop_array) {
 626     // Still looks like an instance? Likely a large instance or reflective
 627     // clone with unknown length. Go to runtime and handle it there.
 628     clone_in_runtime(phase, ac, ShenandoahRuntime::clone_addr(), "ShenandoahRuntime::clone");
 629     return;
 630   }
 631 
 632   // We are cloning the oop array. Call into normal oop array copy stubs.
 633   // Those stubs would call BarrierSetAssembler to handle GC barriers.
 634 
 635   // This is the full clone, so offsets should equal each other and be at array base.
 636   assert(src_offset == dest_offset, "should be equal");
 637   const jlong offset = src_offset->get_long();
 638   const TypeAryPtr* const ary_ptr = src->get_ptr_type()->isa_aryptr();
 639   BasicType bt = ary_ptr->elem()->array_element_basic_type();
 640   assert(offset == arrayOopDesc::base_offset_in_bytes(bt), "should match");
 641 
 642   const char*   copyfunc_name = "arraycopy";
 643   const address copyfunc_addr = phase->basictype2arraycopy(T_OBJECT, nullptr, nullptr, true, copyfunc_name, true);
 644 
 645   Node* const call = phase->make_leaf_call(ctrl, mem,
 646       OptoRuntime::fast_arraycopy_Type(),
 647       copyfunc_addr, copyfunc_name,
 648       TypeRawPtr::BOTTOM,
 649       phase->basic_plus_adr(src, src_offset),
 650       phase->basic_plus_adr(dest, dest_offset),
 651       length,
 652       phase->top()
 653   );
 654   phase->transform_later(call);
 655 
 656   phase->igvn().replace_node(ac, call);
 657 }
 658 
 659 void* ShenandoahBarrierSetC2::create_barrier_state(Arena* comp_arena) const {
 660   return new(comp_arena) ShenandoahBarrierSetC2State(comp_arena);
 661 }
 662 
 663 ShenandoahBarrierSetC2State* ShenandoahBarrierSetC2::state() const {
 664   return reinterpret_cast<ShenandoahBarrierSetC2State*>(Compile::current()->barrier_set_state());



 665 }
 666 
 667 void ShenandoahBarrierSetC2::print_barrier_data(outputStream* os, uint8_t data) {
 668   os->print(" Node barriers: ");
 669   if ((data & ShenandoahBitStrong) != 0) {
 670     data &= ~ShenandoahBitStrong;
 671     os->print("strong ");
 672   }

 673 
 674   if ((data & ShenandoahBitWeak) != 0) {
 675     data &= ~ShenandoahBitWeak;
 676     os->print("weak ");
 677   }
 678 
 679   if ((data & ShenandoahBitPhantom) != 0) {
 680     data &= ~ShenandoahBitPhantom;
 681     os->print("phantom ");















 682   }

 683 
 684   if ((data & ShenandoahBitKeepAlive) != 0) {
 685     data &= ~ShenandoahBitKeepAlive;
 686     os->print("keepalive ");











 687   }





 688 
 689   if ((data & ShenandoahBitCardMark) != 0) {
 690     data &= ~ShenandoahBitCardMark;
 691     os->print("cardmark ");
 692   }

 693 
 694   if ((data & ShenandoahBitNative) != 0) {
 695     data &= ~ShenandoahBitNative;
 696     os->print("native ");





 697   }
 698 
 699   if ((data & ShenandoahBitNotNull) != 0) {
 700     data &= ~ShenandoahBitNotNull;
 701     os->print("not-null ");


 702   }

 703 
 704   if ((data & ShenandoahBitElided) != 0) {
 705     data &= ~ShenandoahBitElided;
 706     os->print("elided ");
 707   }
 708 
 709   os->cr();
 710 
 711   if (data > 0) {
 712     fatal("Unknown bit!");
 713   }
 714 
 715   os->print_cr(" GC configuration: %sLRB %sSATB %sCAS %sClone %sCard",
 716     (ShenandoahLoadRefBarrier ? "+" : "-"),
 717     (ShenandoahSATBBarrier    ? "+" : "-"),
 718     (ShenandoahCASBarrier     ? "+" : "-"),
 719     (ShenandoahCloneBarrier   ? "+" : "-"),
 720     (ShenandoahCardBarrier    ? "+" : "-")
 721   );
 722 }
 723 



 724 
 725 #ifdef ASSERT
 726 void ShenandoahBarrierSetC2::verify_gc_barrier_assert(bool cond, const char* msg, uint8_t bd, Node* n) {
 727   if (!cond) {
 728     stringStream ss;
 729     ss.print_cr("%s", msg);
 730     ss.print_cr("-----------------");
 731     print_barrier_data(&ss, bd);
 732     ss.print_cr("-----------------");
 733     n->dump_bfs(1, nullptr, "", &ss);
 734     report_vm_error(__FILE__, __LINE__, ss.as_string());
 735   }
 736 }
 737 
 738 void ShenandoahBarrierSetC2::verify_gc_barriers(Compile* compile, CompilePhase phase) const {
 739   if (!ShenandoahVerifyOptoBarriers) {
 740     return;
 741   }












 742 
 743   // Verify depending on the barriers actually enabled, allowing verification in passive mode.
 744   // Normally, we have _some_ bits set on all accesses. Optimizations may drop some bits,
 745   // but only the last optimization step eliminates all remaining metadata flags. Only then
 746   // the access data can be completely blank.
 747   bool final_phase = (phase == BeforeCodeGen);
 748   bool expect_load_barriers       = !final_phase && ShenandoahLoadRefBarrier;
 749   bool expect_store_barriers      = !final_phase && (ShenandoahSATBBarrier || ShenandoahCardBarrier);
 750   bool expect_load_store_barriers = expect_load_barriers || expect_store_barriers;
 751   bool expect_some_real           = final_phase;
 752 
 753   Unique_Node_List wq;
 754 
 755   RootNode* root = compile->root();
 756   wq.push(root);
 757 
 758   // Also seed the outs to capture nodes are not reachable from in()-s, e.g. endless loops.
 759   for (DUIterator_Fast imax, i = root->fast_outs(imax); i < imax; i++) {
 760     Node* m = root->fast_out(i);
 761     wq.push(m);
 762   }
 763 
 764   for (uint next = 0; next < wq.size(); next++) {
 765     Node *n = wq.at(next);
 766     assert(!n->is_Mach(), "No Mach nodes here yet");
 767 
 768     int opc = n->Opcode();
 769 
 770     uint8_t bd = 0;
 771     const TypePtr* adr_type = nullptr;
 772     if (is_Load(opc)) {
 773       bd = n->as_Load()->barrier_data();
 774       adr_type = n->as_Load()->adr_type();
 775     } else if (is_Store(opc)) {
 776       bd = n->as_Store()->barrier_data();
 777       adr_type = n->as_Store()->adr_type();
 778     } else if (is_LoadStore(opc)) {
 779       bd = n->as_LoadStore()->barrier_data();
 780       adr_type = n->as_LoadStore()->adr_type();
 781     } else if (n->is_Mem()) {
 782       bd = MemNode::barrier_data(n);
 783       verify_gc_barrier_assert(bd == 0, "Other mem nodes should have no barrier data", bd, n);
 784     }
 785 
 786     bool is_weak   = (bd & (ShenandoahBitWeak | ShenandoahBitPhantom)) != 0;
 787     bool is_native = (bd & ShenandoahBitNative) != 0;
 788 
 789     bool is_referent = adr_type != nullptr &&
 790                        adr_type->isa_instptr() &&
 791                        adr_type->is_instptr()->instance_klass()->is_subtype_of(Compile::current()->env()->Reference_klass()) &&
 792                        adr_type->is_instptr()->offset() == java_lang_ref_Reference::referent_offset();
 793 
 794     bool is_oop_addr = (adr_type != nullptr) && (adr_type->isa_oopptr() || adr_type->isa_narrowoop());
 795     bool is_raw_addr = (adr_type != nullptr) && (adr_type->isa_rawptr() || adr_type->isa_klassptr());
 796 
 797     verify_gc_barrier_assert(!expect_some_real || (bd == 0) || (bd & ShenandoahBitsReal) != 0, "Without real barriers, metadata should be stripped at this point", bd, n);
 798 
 799     if (is_oop_addr) {
 800       if (is_Load(opc)) {
 801         verify_gc_barrier_assert(!expect_load_barriers || (bd != 0), "Oop load should have barrier data", bd, n);
 802         verify_gc_barrier_assert(!is_weak || is_referent, "Weak load only for Reference.referent", bd, n);
 803       } else if (is_Store(opc)) {
 804         // Reference.referent stores can be without barriers.
 805         verify_gc_barrier_assert(!expect_store_barriers || is_referent || (bd != 0), "Oop store should have barrier data", bd, n);
 806       } else if (is_LoadStore(opc)) {
 807         verify_gc_barrier_assert(!expect_load_store_barriers || (bd != 0), "Oop load-store should have barrier data", bd, n);
 808       }
 809     } else if (is_raw_addr) {
 810       if (is_native) {
 811         if (is_Load(opc)) {
 812           verify_gc_barrier_assert(!expect_load_barriers || (bd != 0), "Native oop load should have barrier data", bd, n);
 813         }
 814         if (is_Store(opc)) {
 815           verify_gc_barrier_assert(!expect_store_barriers || (bd != 0), "Native oop store should have barrier data", bd, n);
 816         }
 817         if (is_LoadStore(opc)) {
 818           verify_gc_barrier_assert(!expect_load_store_barriers || (bd != 0), "Native oop load-store should have barrier data", bd, n);




























 819         }
 820       } else {
 821         // Some Load/Stores are used for T_ADDRESS and/or raw stores, which are supposed not to have barriers.
 822         // Some other Load/Stores are emitted for real oops, but on raw addresses via Unsafe.
 823         // The distinction on this level is lost, so we cannot really verify this.
 824       }
 825     } else {
 826       if (is_Load(opc) || is_Store(opc) || is_LoadStore(opc)) {
 827         verify_gc_barrier_assert(false, "Unclassified access type", bd, n);
 828       }
 829     }
 830 
 831     for (uint j = 0; j < n->req(); j++) {
 832       Node* in = n->in(j);
 833       if (in != nullptr) {
 834         wq.push(in);
 835       }
 836     }
 837   }
 838 }
 839 #endif
 840 
 841 static ShenandoahBarrierSetC2State* barrier_set_state() {
 842   return reinterpret_cast<ShenandoahBarrierSetC2State*>(Compile::current()->barrier_set_state());
 843 }
 844 
 845 int ShenandoahBarrierSetC2::estimate_stub_size() const {
 846   GrowableArray<ShenandoahBarrierStubC2*>* const stubs = barrier_set_state()->stubs();
 847   assert(stubs->is_empty(), "Lifecycle: no stubs were yet created");
 848   return 0;
 849 }
 850 
 851 void ShenandoahBarrierSetC2::emit_stubs(CodeBuffer& cb) const {
 852   MacroAssembler masm(&cb);
 853 
 854   PhaseOutput* const output = Compile::current()->output();
 855   assert(masm.offset() <= output->buffer_sizing_data()->_code,
 856          "Stubs are assumed to be emitted directly after code and code_size is a hard limit on where it can start");
 857   barrier_set_state()->set_stubs_start_offset(masm.offset());
 858 
 859   // Stub generation counts all stubs as skipped for the sake of inlining policy.
 860   // This is critical for performance, check it.
 861 #ifdef ASSERT
 862   int offset_before = masm.offset();
 863   int skipped_before = cb.total_skipped_instructions_size();
 864 #endif
 865 
 866   GrowableArray<ShenandoahBarrierStubC2*>* const stubs = barrier_set_state()->stubs();
 867   for (int i = 0; i < stubs->length(); i++) {
 868     // Make sure there is enough space in the code buffer
 869     if (cb.insts()->maybe_expand_to_ensure_remaining(PhaseOutput::MAX_inst_size) && cb.blob() == nullptr) {
 870       ciEnv::current()->record_failure("CodeCache is full");
 871       return;
 872     }
 873     stubs->at(i)->emit_code(masm);
 874   }















 875 
 876 #ifdef ASSERT
 877   int offset_after = masm.offset();
 878   int skipped_after = cb.total_skipped_instructions_size();
 879   assert(offset_after - offset_before == skipped_after - skipped_before,
 880          "All stubs are counted as skipped. masm: %d - %d = %d, cb: %d - %d = %d",
 881         offset_after, offset_before, offset_after - offset_before,
 882         skipped_after, skipped_before, skipped_after - skipped_before);
 883 #endif





















 884 
 885   masm.flush();
 886 }


 887 
 888 void ShenandoahBarrierStubC2::register_stub(ShenandoahBarrierStubC2* stub) {
 889   if (!Compile::current()->output()->in_scratch_emit_size()) {
 890     barrier_set_state()->stubs()->append(stub);
 891   }
 892 }
 893 
 894 ShenandoahBarrierStubC2* ShenandoahBarrierStubC2::create(const MachNode* node, Register obj, Address addr, Register tmp1, Register tmp2, bool narrow, bool do_load) {
 895   auto* stub = new (Compile::current()->comp_arena()) ShenandoahBarrierStubC2(node, obj, addr, tmp1, tmp2, narrow, do_load);
 896   register_stub(stub);
 897   return stub;
 898 }
 899 
 900 void ShenandoahBarrierStubC2::load_post(MacroAssembler* masm, const MachNode* node, Register obj, Address addr, Register tmp1, Register tmp2, bool narrow) {
 901   // Load post-barrier:
 902   //  a. Satisfies the need for LRB for normal loads
 903   //  b. Passes a weak load through LRB-weak
 904   //  c. Keep-alives a weak load
 905   if (needs_slow_barrier(node)) {
 906     ShenandoahBarrierStubC2* const stub = create(node, obj, addr, tmp1, tmp2, narrow, /* do_load = */ false);
 907     char check = 0;
 908     check |= needs_keep_alive_barrier(node)    ? ShenandoahHeap::MARKING : 0;
 909     check |= needs_load_ref_barrier(node)      ? ShenandoahHeap::HAS_FORWARDED : 0;
 910     check |= needs_load_ref_barrier_weak(node) ? ShenandoahHeap::WEAK_ROOTS : 0;
 911     stub->enter_if_gc_state(*masm, check, tmp1);
 912   }

 913 }
 914 
 915 void ShenandoahBarrierStubC2::store_pre(MacroAssembler* masm, const MachNode* node, Register obj, Address addr, Register tmp1, Register tmp2, bool narrow) {
 916   // Store pre-barrier: SATB, keep-alive the current memory value.
 917   if (needs_slow_barrier(node)) {
 918     assert(!needs_load_ref_barrier(node), "Should not be required for stores");
 919     ShenandoahBarrierStubC2* const stub = create(node, obj, addr, tmp1, tmp2, narrow, /* do_load = */ true);
 920     stub->enter_if_gc_state(*masm, ShenandoahHeap::MARKING, tmp1);























 921   }
 922 }
 923 
 924 void ShenandoahBarrierStubC2::load_store_pre(MacroAssembler* masm, const MachNode* node, Register obj, Address addr, Register tmp1, Register tmp2, bool narrow) {
 925   // Load/Store pre-barrier:
 926   //  a. Avoids false positives from CAS encountering to-space memory values.
 927   //  b. Satisfies the need for LRB for the CAE result.
 928   //  c. Records old value for the sake of SATB.
 929   //
 930   // (a) and (b) are covered because load barrier does memory location fixup.
 931   // (c) is covered by KA on the current memory value.
 932   if (needs_slow_barrier(node)) {
 933     ShenandoahBarrierStubC2* const stub = create(node, obj, addr, tmp1, tmp2, narrow, /* do_load = */ true);
 934     char check = 0;
 935     check |= needs_keep_alive_barrier(node) ? ShenandoahHeap::MARKING : 0;
 936     check |= needs_load_ref_barrier(node)   ? ShenandoahHeap::HAS_FORWARDED : 0;
 937     assert(!needs_load_ref_barrier_weak(node), "Not supported for Load/Stores");
 938     stub->enter_if_gc_state(*masm, check, tmp1);


























 939   }

 940 }
 941 
 942 void ShenandoahBarrierStubC2::store_post(MacroAssembler* masm, const MachNode* node, Address addr, Register tmp1, Register tmp2) {
 943   if (needs_card_barrier(node)) {
 944     cardtable(*masm, addr, tmp1, tmp2);
















 945   }

 946 }
 947 
 948 void ShenandoahBarrierStubC2::load_store_post(MacroAssembler* masm, const MachNode* node, Address addr, Register tmp1, Register tmp2) {
 949   store_post(masm, node, addr, tmp1, tmp2);
 950 }
 951 
 952 bool ShenandoahBarrierStubC2::is_live_register(Register reg) {
 953   return preserve_set().member(OptoReg::as_OptoReg(reg->as_VMReg()));
 954 }
 955 
 956 Register ShenandoahBarrierStubC2::select_temp_register(bool& selected_live, Register skip_reg1, Register skip_reg2) {
 957   Register tmp = noreg;
 958   Register fallback_live = noreg;
 959 
 960   // Try to select non-live first:
 961   for (int i = 0; i < available_gp_registers(); i++) {
 962     Register r = as_Register(i);
 963     if (r != _obj && r != _addr.base() && r != _addr.index() &&
 964         r != skip_reg1 && r != skip_reg2 && !is_special_register(r)) {
 965       if (!is_live_register(r)) {
 966         tmp = r;
 967         break;
 968       } else if (fallback_live == noreg) {
 969         fallback_live = r;
 970       }
 971     }
 972   }
 973 
 974   // If we could not find a non-live register, select the live fallback:
 975   if (tmp == noreg) {
 976     tmp = fallback_live;
 977     selected_live = true;
 978   } else {
 979     selected_live = false;
 980   }
 981 
 982   assert(tmp != noreg, "successfully selected");
 983   assert_different_registers(tmp, skip_reg1);
 984   assert_different_registers(tmp, skip_reg2);
 985   assert_different_registers(tmp, _obj);
 986   assert_different_registers(tmp, _addr.base());
 987   assert_different_registers(tmp, _addr.index());
 988   return tmp;
 989 }
 990 
 991 address ShenandoahBarrierStubC2::keepalive_runtime_entry_addr() {
 992   if (_narrow) {
 993     return CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_barrier_pre_narrow);
 994   } else {
 995     return CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_barrier_pre);
 996   }
 997 }
 998 
 999 address ShenandoahBarrierStubC2::lrb_runtime_entry_addr() {
1000   bool is_strong  = (_node->barrier_data() & ShenandoahBitStrong)  != 0;
1001   bool is_weak    = (_node->barrier_data() & ShenandoahBitWeak)    != 0;
1002   bool is_phantom = (_node->barrier_data() & ShenandoahBitPhantom) != 0;
1003 
1004   if (_narrow) {
1005     if (is_strong) {
1006       return CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong_narrow_narrow);
1007     } else if (is_weak) {
1008       return CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak_narrow_narrow);
1009     } else if (is_phantom) {
1010       return CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom_narrow_narrow);
1011     }
1012   } else {
1013     if (is_strong) {
1014       return CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong);
1015     } else if (is_weak) {
1016       return CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak);
1017     } else if (is_phantom) {
1018       return CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom);
1019     }


1020   }
1021 
1022   ShouldNotReachHere();
1023   return nullptr;
1024 }
1025 
1026 bool ShenandoahBarrierSetC2State::needs_liveness_data(const MachNode* mach) const {
1027   // Nodes that require slow-path stubs need liveness data.
1028   return ShenandoahBarrierStubC2::needs_slow_barrier(mach);
1029 }
1030 
1031 bool ShenandoahBarrierSetC2State::needs_livein_data() const {
1032   return true;
1033 }
< prev index next >