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