1 /*
   2  * Copyright (c) 2018, 2019, Red Hat, Inc. All rights reserved.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.
   7  *
   8  * This code is distributed in the hope that it will be useful, but WITHOUT
   9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  11  * version 2 for more details (a copy is included in the LICENSE file that
  12  * accompanied this code).
  13  *
  14  * You should have received a copy of the GNU General Public License version
  15  * 2 along with this work; if not, write to the Free Software Foundation,
  16  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  17  *
  18  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  19  * or visit www.oracle.com if you need additional information or have any
  20  * questions.
  21  *
  22  */
  23 
  24 #include "precompiled.hpp"
  25 #include "gc/shared/barrierSet.hpp"
  26 #include "gc/shenandoah/shenandoahForwarding.hpp"
  27 #include "gc/shenandoah/shenandoahHeap.hpp"
  28 #include "gc/shenandoah/shenandoahHeuristics.hpp"
  29 #include "gc/shenandoah/shenandoahRuntime.hpp"
  30 #include "gc/shenandoah/shenandoahThreadLocalData.hpp"
  31 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
  32 #include "gc/shenandoah/c2/shenandoahSupport.hpp"
  33 #include "opto/arraycopynode.hpp"
  34 #include "opto/escape.hpp"
  35 #include "opto/graphKit.hpp"
  36 #include "opto/idealKit.hpp"
  37 #include "opto/macro.hpp"
  38 #include "opto/movenode.hpp"
  39 #include "opto/narrowptrnode.hpp"
  40 #include "opto/rootnode.hpp"
  41 #include "opto/runtime.hpp"
  42 
  43 ShenandoahBarrierSetC2* ShenandoahBarrierSetC2::bsc2() {
  44   return reinterpret_cast<ShenandoahBarrierSetC2*>(BarrierSet::barrier_set()->barrier_set_c2());
  45 }
  46 
  47 ShenandoahBarrierSetC2State::ShenandoahBarrierSetC2State(Arena* comp_arena)
  48   : _enqueue_barriers(new (comp_arena) GrowableArray<ShenandoahEnqueueBarrierNode*>(comp_arena, 8,  0, NULL)),
  49     _load_reference_barriers(new (comp_arena) GrowableArray<ShenandoahLoadReferenceBarrierNode*>(comp_arena, 8,  0, NULL)) {
  50 }
  51 
  52 int ShenandoahBarrierSetC2State::enqueue_barriers_count() const {
  53   return _enqueue_barriers->length();
  54 }
  55 
  56 ShenandoahEnqueueBarrierNode* ShenandoahBarrierSetC2State::enqueue_barrier(int idx) const {
  57   return _enqueue_barriers->at(idx);
  58 }
  59 
  60 void ShenandoahBarrierSetC2State::add_enqueue_barrier(ShenandoahEnqueueBarrierNode * n) {
  61   assert(!_enqueue_barriers->contains(n), "duplicate entry in barrier list");
  62   _enqueue_barriers->append(n);
  63 }
  64 
  65 void ShenandoahBarrierSetC2State::remove_enqueue_barrier(ShenandoahEnqueueBarrierNode * n) {
  66   if (_enqueue_barriers->contains(n)) {
  67     _enqueue_barriers->remove(n);
  68   }
  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   return call->is_CallLeaf() &&
 301           call->as_CallLeaf()->entry_point() == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier);
 302 }
 303 
 304 bool ShenandoahBarrierSetC2::is_shenandoah_marking_if(PhaseTransform *phase, Node* n) {
 305   if (n->Opcode() != Op_If) {
 306     return false;
 307   }
 308 
 309   Node* bol = n->in(1);
 310   assert(bol->is_Bool(), "");
 311   Node* cmpx = bol->in(1);
 312   if (bol->as_Bool()->_test._test == BoolTest::ne &&
 313       cmpx->is_Cmp() && cmpx->in(2) == phase->intcon(0) &&
 314       is_shenandoah_state_load(cmpx->in(1)->in(1)) &&
 315       cmpx->in(1)->in(2)->is_Con() &&
 316       cmpx->in(1)->in(2) == phase->intcon(ShenandoahHeap::MARKING)) {
 317     return true;
 318   }
 319 
 320   return false;
 321 }
 322 
 323 bool ShenandoahBarrierSetC2::is_shenandoah_state_load(Node* n) {
 324   if (!n->is_Load()) return false;
 325   const int state_offset = in_bytes(ShenandoahThreadLocalData::gc_state_offset());
 326   return n->in(2)->is_AddP() && n->in(2)->in(2)->Opcode() == Op_ThreadLocal
 327          && n->in(2)->in(3)->is_Con()
 328          && n->in(2)->in(3)->bottom_type()->is_intptr_t()->get_con() == state_offset;
 329 }
 330 
 331 void ShenandoahBarrierSetC2::shenandoah_write_barrier_pre(GraphKit* kit,
 332                                                           bool do_load,
 333                                                           Node* obj,
 334                                                           Node* adr,
 335                                                           uint alias_idx,
 336                                                           Node* val,
 337                                                           const TypeOopPtr* val_type,
 338                                                           Node* pre_val,
 339                                                           BasicType bt) const {
 340   if (ShenandoahSATBBarrier) {
 341     IdealKit ideal(kit);
 342     kit->sync_kit(ideal);
 343 
 344     satb_write_barrier_pre(kit, do_load, obj, adr, alias_idx, val, val_type, pre_val, bt);
 345 
 346     ideal.sync_kit(kit);
 347     kit->final_sync(ideal);
 348   }
 349 }
 350 
 351 Node* ShenandoahBarrierSetC2::shenandoah_enqueue_barrier(GraphKit* kit, Node* pre_val) const {
 352   return kit->gvn().transform(new ShenandoahEnqueueBarrierNode(pre_val));
 353 }
 354 
 355 // Helper that guards and inserts a pre-barrier.
 356 void ShenandoahBarrierSetC2::insert_pre_barrier(GraphKit* kit, Node* base_oop, Node* offset,
 357                                                 Node* pre_val, bool need_mem_bar) const {
 358   // We could be accessing the referent field of a reference object. If so, when G1
 359   // is enabled, we need to log the value in the referent field in an SATB buffer.
 360   // This routine performs some compile time filters and generates suitable
 361   // runtime filters that guard the pre-barrier code.
 362   // Also add memory barrier for non volatile load from the referent field
 363   // to prevent commoning of loads across safepoint.
 364 
 365   // Some compile time checks.
 366 
 367   // If offset is a constant, is it java_lang_ref_Reference::_reference_offset?
 368   const TypeX* otype = offset->find_intptr_t_type();
 369   if (otype != NULL && otype->is_con() &&
 370       otype->get_con() != java_lang_ref_Reference::referent_offset) {
 371     // Constant offset but not the reference_offset so just return
 372     return;
 373   }
 374 
 375   // We only need to generate the runtime guards for instances.
 376   const TypeOopPtr* btype = base_oop->bottom_type()->isa_oopptr();
 377   if (btype != NULL) {
 378     if (btype->isa_aryptr()) {
 379       // Array type so nothing to do
 380       return;
 381     }
 382 
 383     const TypeInstPtr* itype = btype->isa_instptr();
 384     if (itype != NULL) {
 385       // Can the klass of base_oop be statically determined to be
 386       // _not_ a sub-class of Reference and _not_ Object?
 387       ciKlass* klass = itype->klass();
 388       if ( klass->is_loaded() &&
 389           !klass->is_subtype_of(kit->env()->Reference_klass()) &&
 390           !kit->env()->Object_klass()->is_subtype_of(klass)) {
 391         return;
 392       }
 393     }
 394   }
 395 
 396   // The compile time filters did not reject base_oop/offset so
 397   // we need to generate the following runtime filters
 398   //
 399   // if (offset == java_lang_ref_Reference::_reference_offset) {
 400   //   if (instance_of(base, java.lang.ref.Reference)) {
 401   //     pre_barrier(_, pre_val, ...);
 402   //   }
 403   // }
 404 
 405   float likely   = PROB_LIKELY(  0.999);
 406   float unlikely = PROB_UNLIKELY(0.999);
 407 
 408   IdealKit ideal(kit);
 409 
 410   Node* referent_off = __ ConX(java_lang_ref_Reference::referent_offset);
 411 
 412   __ if_then(offset, BoolTest::eq, referent_off, unlikely); {
 413       // Update graphKit memory and control from IdealKit.
 414       kit->sync_kit(ideal);
 415 
 416       Node* ref_klass_con = kit->makecon(TypeKlassPtr::make(kit->env()->Reference_klass()));
 417       Node* is_instof = kit->gen_instanceof(base_oop, ref_klass_con);
 418 
 419       // Update IdealKit memory and control from graphKit.
 420       __ sync_kit(kit);
 421 
 422       Node* one = __ ConI(1);
 423       // is_instof == 0 if base_oop == NULL
 424       __ if_then(is_instof, BoolTest::eq, one, unlikely); {
 425 
 426         // Update graphKit from IdeakKit.
 427         kit->sync_kit(ideal);
 428 
 429         // Use the pre-barrier to record the value in the referent field
 430         satb_write_barrier_pre(kit, false /* do_load */,
 431                                NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
 432                                pre_val /* pre_val */,
 433                                T_OBJECT);
 434         if (need_mem_bar) {
 435           // Add memory barrier to prevent commoning reads from this field
 436           // across safepoint since GC can change its value.
 437           kit->insert_mem_bar(Op_MemBarCPUOrder);
 438         }
 439         // Update IdealKit from graphKit.
 440         __ sync_kit(kit);
 441 
 442       } __ end_if(); // _ref_type != ref_none
 443   } __ end_if(); // offset == referent_offset
 444 
 445   // Final sync IdealKit and GraphKit.
 446   kit->final_sync(ideal);
 447 }
 448 
 449 #undef __
 450 
 451 const TypeFunc* ShenandoahBarrierSetC2::write_ref_field_pre_entry_Type() {
 452   const Type **fields = TypeTuple::fields(2);
 453   fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL; // original field value
 454   fields[TypeFunc::Parms+1] = TypeRawPtr::NOTNULL; // thread
 455   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
 456 
 457   // create result type (range)
 458   fields = TypeTuple::fields(0);
 459   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0, fields);
 460 
 461   return TypeFunc::make(domain, range);
 462 }
 463 
 464 const TypeFunc* ShenandoahBarrierSetC2::shenandoah_clone_barrier_Type() {
 465   const Type **fields = TypeTuple::fields(1);
 466   fields[TypeFunc::Parms+0] = TypeOopPtr::NOTNULL; // src oop
 467   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+1, fields);


 468 
 469   // create result type (range)
 470   fields = TypeTuple::fields(0);
 471   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0, fields);
 472 
 473   return TypeFunc::make(domain, range);
 474 }
 475 
 476 const TypeFunc* ShenandoahBarrierSetC2::shenandoah_load_reference_barrier_Type() {
 477   const Type **fields = TypeTuple::fields(2);
 478   fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL; // original field value
 479   fields[TypeFunc::Parms+1] = TypeRawPtr::BOTTOM;   // original load address
 480 
 481   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
 482 
 483   // create result type (range)
 484   fields = TypeTuple::fields(1);
 485   fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL;
 486   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+1, fields);
 487 
 488   return TypeFunc::make(domain, range);
 489 }
 490 
 491 Node* ShenandoahBarrierSetC2::store_at_resolved(C2Access& access, C2AccessValue& val) const {
 492   DecoratorSet decorators = access.decorators();
 493 
 494   const TypePtr* adr_type = access.addr().type();
 495   Node* adr = access.addr().node();
 496 
 497   bool anonymous = (decorators & ON_UNKNOWN_OOP_REF) != 0;
 498   bool on_heap = (decorators & IN_HEAP) != 0;
 499 
 500   if (!access.is_oop() || (!on_heap && !anonymous)) {
 501     return BarrierSetC2::store_at_resolved(access, val);
 502   }
 503 
 504   if (access.is_parse_access()) {
 505     C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(access);
 506     GraphKit* kit = parse_access.kit();
 507 
 508     uint adr_idx = kit->C->get_alias_index(adr_type);
 509     assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
 510     Node* value = val.node();
 511     value = shenandoah_storeval_barrier(kit, value);
 512     val.set_node(value);
 513     shenandoah_write_barrier_pre(kit, true /* do_load */, /*kit->control(),*/ access.base(), adr, adr_idx, val.node(),
 514                                  static_cast<const TypeOopPtr*>(val.type()), NULL /* pre_val */, access.type());
 515   } else {
 516     assert(access.is_opt_access(), "only for optimization passes");
 517     assert(((decorators & C2_TIGHTLY_COUPLED_ALLOC) != 0 || !ShenandoahSATBBarrier) && (decorators & C2_ARRAY_COPY) != 0, "unexpected caller of this code");
 518     C2OptAccess& opt_access = static_cast<C2OptAccess&>(access);
 519     PhaseGVN& gvn =  opt_access.gvn();
 520     MergeMemNode* mm = opt_access.mem();
 521 
 522     if (ShenandoahStoreValEnqueueBarrier) {
 523       Node* enqueue = gvn.transform(new ShenandoahEnqueueBarrierNode(val.node()));
 524       val.set_node(enqueue);
 525     }
 526   }
 527   return BarrierSetC2::store_at_resolved(access, val);
 528 }
 529 
 530 Node* ShenandoahBarrierSetC2::load_at_resolved(C2Access& access, const Type* val_type) const {
 531   DecoratorSet decorators = access.decorators();
 532 
 533   Node* adr = access.addr().node();
 534   Node* obj = access.base();
 535 
 536   bool mismatched = (decorators & C2_MISMATCHED) != 0;
 537   bool unknown = (decorators & ON_UNKNOWN_OOP_REF) != 0;
 538   bool on_heap = (decorators & IN_HEAP) != 0;
 539   bool on_weak = (decorators & ON_WEAK_OOP_REF) != 0;
 540   bool is_unordered = (decorators & MO_UNORDERED) != 0;
 541   bool need_cpu_mem_bar = !is_unordered || mismatched || !on_heap;
 542 
 543   Node* top = Compile::current()->top();
 544 
 545   Node* offset = adr->is_AddP() ? adr->in(AddPNode::Offset) : top;
 546   Node* load = BarrierSetC2::load_at_resolved(access, val_type);
 547 
 548   if (access.is_oop()) {
 549     if (ShenandoahLoadRefBarrier) {
 550       load = new ShenandoahLoadReferenceBarrierNode(NULL, load, (decorators & IN_NATIVE) != 0);
 551       if (access.is_parse_access()) {
 552         load = static_cast<C2ParseAccess &>(access).kit()->gvn().transform(load);
 553       } else {
 554         load = static_cast<C2OptAccess &>(access).gvn().transform(load);
 555       }
 556     }
 557   }
 558 
 559   // If we are reading the value of the referent field of a Reference
 560   // object (either by using Unsafe directly or through reflection)
 561   // then, if SATB is enabled, we need to record the referent in an
 562   // SATB log buffer using the pre-barrier mechanism.
 563   // Also we need to add memory barrier to prevent commoning reads
 564   // from this field across safepoint since GC can change its value.
 565   bool need_read_barrier = ShenandoahKeepAliveBarrier &&
 566     (on_heap && (on_weak || (unknown && offset != top && obj != top)));
 567 
 568   if (!access.is_oop() || !need_read_barrier) {
 569     return load;
 570   }
 571 
 572   assert(access.is_parse_access(), "entry not supported at optimization time");
 573   C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(access);
 574   GraphKit* kit = parse_access.kit();
 575 
 576   if (on_weak) {
 577     // Use the pre-barrier to record the value in the referent field
 578     satb_write_barrier_pre(kit, false /* do_load */,
 579                            NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
 580                            load /* pre_val */, T_OBJECT);
 581     // Add memory barrier to prevent commoning reads from this field
 582     // across safepoint since GC can change its value.
 583     kit->insert_mem_bar(Op_MemBarCPUOrder);
 584   } else if (unknown) {
 585     // We do not require a mem bar inside pre_barrier if need_mem_bar
 586     // is set: the barriers would be emitted by us.
 587     insert_pre_barrier(kit, obj, offset, load, !need_cpu_mem_bar);
 588   }
 589 
 590   return load;
 591 }
 592 
 593 Node* ShenandoahBarrierSetC2::atomic_cmpxchg_val_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
 594                                                    Node* new_val, const Type* value_type) const {
 595   GraphKit* kit = access.kit();
 596   if (access.is_oop()) {
 597     new_val = shenandoah_storeval_barrier(kit, new_val);
 598     shenandoah_write_barrier_pre(kit, false /* do_load */,
 599                                  NULL, NULL, max_juint, NULL, NULL,
 600                                  expected_val /* pre_val */, T_OBJECT);
 601 
 602     MemNode::MemOrd mo = access.mem_node_mo();
 603     Node* mem = access.memory();
 604     Node* adr = access.addr().node();
 605     const TypePtr* adr_type = access.addr().type();
 606     Node* load_store = NULL;
 607 
 608 #ifdef _LP64
 609     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 610       Node *newval_enc = kit->gvn().transform(new EncodePNode(new_val, new_val->bottom_type()->make_narrowoop()));
 611       Node *oldval_enc = kit->gvn().transform(new EncodePNode(expected_val, expected_val->bottom_type()->make_narrowoop()));
 612       if (ShenandoahCASBarrier) {
 613         load_store = kit->gvn().transform(new ShenandoahCompareAndExchangeNNode(kit->control(), mem, adr, newval_enc, oldval_enc, adr_type, value_type->make_narrowoop(), mo));
 614       } else {
 615         load_store = kit->gvn().transform(new CompareAndExchangeNNode(kit->control(), mem, adr, newval_enc, oldval_enc, adr_type, value_type->make_narrowoop(), mo));
 616       }
 617     } else
 618 #endif
 619     {
 620       if (ShenandoahCASBarrier) {
 621         load_store = kit->gvn().transform(new ShenandoahCompareAndExchangePNode(kit->control(), mem, adr, new_val, expected_val, adr_type, value_type->is_oopptr(), mo));
 622       } else {
 623         load_store = kit->gvn().transform(new CompareAndExchangePNode(kit->control(), mem, adr, new_val, expected_val, adr_type, value_type->is_oopptr(), mo));
 624       }
 625     }
 626 
 627     access.set_raw_access(load_store);
 628     pin_atomic_op(access);
 629 
 630 #ifdef _LP64
 631     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 632       load_store = kit->gvn().transform(new DecodeNNode(load_store, load_store->get_ptr_type()));
 633     }
 634 #endif
 635     load_store = kit->gvn().transform(new ShenandoahLoadReferenceBarrierNode(NULL, load_store, false));
 636     return load_store;
 637   }
 638   return BarrierSetC2::atomic_cmpxchg_val_at_resolved(access, expected_val, new_val, value_type);
 639 }
 640 
 641 Node* ShenandoahBarrierSetC2::atomic_cmpxchg_bool_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
 642                                                               Node* new_val, const Type* value_type) const {
 643   GraphKit* kit = access.kit();
 644   if (access.is_oop()) {
 645     new_val = shenandoah_storeval_barrier(kit, new_val);
 646     shenandoah_write_barrier_pre(kit, false /* do_load */,
 647                                  NULL, NULL, max_juint, NULL, NULL,
 648                                  expected_val /* pre_val */, T_OBJECT);
 649     DecoratorSet decorators = access.decorators();
 650     MemNode::MemOrd mo = access.mem_node_mo();
 651     Node* mem = access.memory();
 652     bool is_weak_cas = (decorators & C2_WEAK_CMPXCHG) != 0;
 653     Node* load_store = NULL;
 654     Node* adr = access.addr().node();
 655 #ifdef _LP64
 656     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 657       Node *newval_enc = kit->gvn().transform(new EncodePNode(new_val, new_val->bottom_type()->make_narrowoop()));
 658       Node *oldval_enc = kit->gvn().transform(new EncodePNode(expected_val, expected_val->bottom_type()->make_narrowoop()));
 659       if (ShenandoahCASBarrier) {
 660         if (is_weak_cas) {
 661           load_store = kit->gvn().transform(new ShenandoahWeakCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 662         } else {
 663           load_store = kit->gvn().transform(new ShenandoahCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 664         }
 665       } else {
 666         if (is_weak_cas) {
 667           load_store = kit->gvn().transform(new WeakCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 668         } else {
 669           load_store = kit->gvn().transform(new CompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 670         }
 671       }
 672     } else
 673 #endif
 674     {
 675       if (ShenandoahCASBarrier) {
 676         if (is_weak_cas) {
 677           load_store = kit->gvn().transform(new ShenandoahWeakCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 678         } else {
 679           load_store = kit->gvn().transform(new ShenandoahCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 680         }
 681       } else {
 682         if (is_weak_cas) {
 683           load_store = kit->gvn().transform(new WeakCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 684         } else {
 685           load_store = kit->gvn().transform(new CompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 686         }
 687       }
 688     }
 689     access.set_raw_access(load_store);
 690     pin_atomic_op(access);
 691     return load_store;
 692   }
 693   return BarrierSetC2::atomic_cmpxchg_bool_at_resolved(access, expected_val, new_val, value_type);
 694 }
 695 
 696 Node* ShenandoahBarrierSetC2::atomic_xchg_at_resolved(C2AtomicParseAccess& access, Node* val, const Type* value_type) const {
 697   GraphKit* kit = access.kit();
 698   if (access.is_oop()) {
 699     val = shenandoah_storeval_barrier(kit, val);
 700   }
 701   Node* result = BarrierSetC2::atomic_xchg_at_resolved(access, val, value_type);
 702   if (access.is_oop()) {
 703     result = kit->gvn().transform(new ShenandoahLoadReferenceBarrierNode(NULL, result, false));
 704     shenandoah_write_barrier_pre(kit, false /* do_load */,
 705                                  NULL, NULL, max_juint, NULL, NULL,
 706                                  result /* pre_val */, T_OBJECT);
 707   }
 708   return result;
 709 }
 710 
 711 // Support for GC barriers emitted during parsing
 712 bool ShenandoahBarrierSetC2::is_gc_barrier_node(Node* node) const {
 713   if (node->Opcode() == Op_ShenandoahLoadReferenceBarrier) return true;
 714   if (node->Opcode() != Op_CallLeaf && node->Opcode() != Op_CallLeafNoFP) {
 715     return false;
 716   }
 717   CallLeafNode *call = node->as_CallLeaf();
 718   if (call->_name == NULL) {
 719     return false;
 720   }
 721 
 722   return strcmp(call->_name, "shenandoah_clone_barrier") == 0 ||
 723          strcmp(call->_name, "shenandoah_cas_obj") == 0 ||
 724          strcmp(call->_name, "shenandoah_wb_pre") == 0;
 725 }
 726 
 727 Node* ShenandoahBarrierSetC2::step_over_gc_barrier(Node* c) const {
 728   if (c->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
 729     return c->in(ShenandoahLoadReferenceBarrierNode::ValueIn);
 730   }
 731   if (c->Opcode() == Op_ShenandoahEnqueueBarrier) {
 732     c = c->in(1);
 733   }
 734   return c;
 735 }
 736 
 737 bool ShenandoahBarrierSetC2::expand_barriers(Compile* C, PhaseIterGVN& igvn) const {
 738   return !ShenandoahBarrierC2Support::expand(C, igvn);
 739 }
 740 
 741 bool ShenandoahBarrierSetC2::optimize_loops(PhaseIdealLoop* phase, LoopOptsMode mode, VectorSet& visited, Node_Stack& nstack, Node_List& worklist) const {
 742   if (mode == LoopOptsShenandoahExpand) {
 743     assert(UseShenandoahGC, "only for shenandoah");
 744     ShenandoahBarrierC2Support::pin_and_expand(phase);
 745     return true;
 746   } else if (mode == LoopOptsShenandoahPostExpand) {
 747     assert(UseShenandoahGC, "only for shenandoah");
 748     visited.Clear();
 749     ShenandoahBarrierC2Support::optimize_after_expansion(visited, nstack, worklist, phase);
 750     return true;
 751   }
 752   return false;
 753 }
 754 
 755 bool ShenandoahBarrierSetC2::array_copy_requires_gc_barriers(bool tightly_coupled_alloc, BasicType type, bool is_clone, ArrayCopyPhase phase) const {
 756   bool is_oop = type == T_OBJECT || type == T_ARRAY;
 757   if (!is_oop) {
 758     return false;
 759   }
 760   if (tightly_coupled_alloc) {
 761     if (phase == Optimization) {
 762       return false;
 763     }
 764     return !is_clone;
 765   }
 766   if (phase == Optimization) {
 767     return !ShenandoahStoreValEnqueueBarrier;
 768   }
 769   return true;
 770 }
 771 
 772 bool ShenandoahBarrierSetC2::clone_needs_barrier(Node* src, PhaseGVN& gvn) {
 773   const TypeOopPtr* src_type = gvn.type(src)->is_oopptr();
 774   if (src_type->isa_instptr() != NULL) {
 775     ciInstanceKlass* ik = src_type->klass()->as_instance_klass();
 776     if ((src_type->klass_is_exact() || (!ik->is_interface() && !ik->has_subklass())) && !ik->has_injected_fields()) {
 777       if (ik->has_object_fields()) {
 778         return true;
 779       } else {
 780         if (!src_type->klass_is_exact()) {
 781           Compile::current()->dependencies()->assert_leaf_type(ik);
 782         }
 783       }
 784     } else {
 785       return true;
 786         }
 787   } else if (src_type->isa_aryptr()) {
 788     BasicType src_elem  = src_type->klass()->as_array_klass()->element_type()->basic_type();
 789     if (src_elem == T_OBJECT || src_elem == T_ARRAY) {
 790       return true;
 791     }
 792   } else {
 793     return true;
 794   }
 795   return false;
 796 }
 797 


 798 void ShenandoahBarrierSetC2::clone_at_expansion(PhaseMacroExpand* phase, ArrayCopyNode* ac) const {
 799   Node* ctrl = ac->in(TypeFunc::Control);
 800   Node* mem = ac->in(TypeFunc::Memory);
 801   Node* src = ac->in(ArrayCopyNode::Src);
 802   Node* src_offset = ac->in(ArrayCopyNode::SrcPos);
 803   Node* dest = ac->in(ArrayCopyNode::Dest);
 804   Node* dest_offset = ac->in(ArrayCopyNode::DestPos);
 805   Node* length = ac->in(ArrayCopyNode::Length);
 806   assert (src_offset == NULL && dest_offset == NULL, "for clone offsets should be null");
 807   assert (src->is_AddP(), "for clone the src should be the interior ptr");
 808   assert (dest->is_AddP(), "for clone the dst should be the interior ptr");
 809 
 810   if (ShenandoahCloneBarrier && clone_needs_barrier(src, phase->igvn())) {
 811     // Check if heap is has forwarded objects. If it does, we need to call into the special
 812     // routine that would fix up source references before we can continue.
 813 
 814     enum { _heap_stable = 1, _heap_unstable, PATH_LIMIT };
 815     Node* region = new RegionNode(PATH_LIMIT);
 816     Node* mem_phi = new PhiNode(region, Type::MEMORY, TypeRawPtr::BOTTOM);
 817 
 818     Node* thread = phase->transform_later(new ThreadLocalNode());
 819     Node* offset = phase->igvn().MakeConX(in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 820     Node* gc_state_addr = phase->transform_later(new AddPNode(phase->C->top(), thread, offset));
 821 
 822     uint gc_state_idx = Compile::AliasIdxRaw;
 823     const TypePtr* gc_state_adr_type = NULL; // debug-mode-only argument
 824     debug_only(gc_state_adr_type = phase->C->get_adr_type(gc_state_idx));
 825 
 826     Node* gc_state    = phase->transform_later(new LoadBNode(ctrl, mem, gc_state_addr, gc_state_adr_type, TypeInt::BYTE, MemNode::unordered));
 827     Node* stable_and  = phase->transform_later(new AndINode(gc_state, phase->igvn().intcon(ShenandoahHeap::HAS_FORWARDED)));
 828     Node* stable_cmp  = phase->transform_later(new CmpINode(stable_and, phase->igvn().zerocon(T_INT)));
 829     Node* stable_test = phase->transform_later(new BoolNode(stable_cmp, BoolTest::ne));
 830 
 831     IfNode* stable_iff  = phase->transform_later(new IfNode(ctrl, stable_test, PROB_UNLIKELY(0.999), COUNT_UNKNOWN))->as_If();
 832     Node* stable_ctrl   = phase->transform_later(new IfFalseNode(stable_iff));
 833     Node* unstable_ctrl = phase->transform_later(new IfTrueNode(stable_iff));
 834 
 835     // Heap is stable, no need to do anything additional
 836     region->init_req(_heap_stable, stable_ctrl);
 837     mem_phi->init_req(_heap_stable, mem);
 838 
 839     // Heap is unstable, call into clone barrier stub
 840     Node* call = phase->make_leaf_call(unstable_ctrl, mem,
 841                     ShenandoahBarrierSetC2::shenandoah_clone_barrier_Type(),
 842                     CAST_FROM_FN_PTR(address, ShenandoahRuntime::shenandoah_clone_barrier),
 843                     "shenandoah_clone",
 844                     TypeRawPtr::BOTTOM,
 845                     src->in(AddPNode::Base));
 846     call = phase->transform_later(call);
 847 
 848     ctrl = phase->transform_later(new ProjNode(call, TypeFunc::Control));
 849     mem = phase->transform_later(new ProjNode(call, TypeFunc::Memory));
 850     region->init_req(_heap_unstable, ctrl);
 851     mem_phi->init_req(_heap_unstable, mem);
 852 
 853     // Wire up the actual arraycopy stub now
 854     ctrl = phase->transform_later(region);
 855     mem = phase->transform_later(mem_phi);
 856 
 857     const char* name = "arraycopy";
 858     call = phase->make_leaf_call(ctrl, mem,
 859                                  OptoRuntime::fast_arraycopy_Type(),
 860                                  phase->basictype2arraycopy(T_LONG, NULL, NULL, true, name, true),
 861                                  name, TypeRawPtr::BOTTOM,
 862                                  src, dest, length
 863                                  LP64_ONLY(COMMA phase->top()));
 864     call = phase->transform_later(call);
 865 
 866     // Hook up the whole thing into the graph
 867     phase->igvn().replace_node(ac, call);
 868   } else {
 869     BarrierSetC2::clone_at_expansion(phase, ac);
 870   }
 871 }
 872 
 873 
 874 // Support for macro expanded GC barriers
 875 void ShenandoahBarrierSetC2::register_potential_barrier_node(Node* node) const {
 876   if (node->Opcode() == Op_ShenandoahEnqueueBarrier) {
 877     state()->add_enqueue_barrier((ShenandoahEnqueueBarrierNode*) node);
 878   }
 879   if (node->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
 880     state()->add_load_reference_barrier((ShenandoahLoadReferenceBarrierNode*) node);
 881   }
 882 }
 883 
 884 void ShenandoahBarrierSetC2::unregister_potential_barrier_node(Node* node) const {
 885   if (node->Opcode() == Op_ShenandoahEnqueueBarrier) {
 886     state()->remove_enqueue_barrier((ShenandoahEnqueueBarrierNode*) node);
 887   }
 888   if (node->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
 889     state()->remove_load_reference_barrier((ShenandoahLoadReferenceBarrierNode*) node);
 890   }
 891 }
 892 
 893 void ShenandoahBarrierSetC2::eliminate_gc_barrier(PhaseMacroExpand* macro, Node* n) const {
 894   if (is_shenandoah_wb_pre_call(n)) {
 895     shenandoah_eliminate_wb_pre(n, &macro->igvn());
 896   }
 897 }
 898 
 899 void ShenandoahBarrierSetC2::shenandoah_eliminate_wb_pre(Node* call, PhaseIterGVN* igvn) const {
 900   assert(UseShenandoahGC && is_shenandoah_wb_pre_call(call), "");
 901   Node* c = call->as_Call()->proj_out(TypeFunc::Control);
 902   c = c->unique_ctrl_out();
 903   assert(c->is_Region() && c->req() == 3, "where's the pre barrier control flow?");
 904   c = c->unique_ctrl_out();
 905   assert(c->is_Region() && c->req() == 3, "where's the pre barrier control flow?");
 906   Node* iff = c->in(1)->is_IfProj() ? c->in(1)->in(0) : c->in(2)->in(0);
 907   assert(iff->is_If(), "expect test");
 908   if (!is_shenandoah_marking_if(igvn, iff)) {
 909     c = c->unique_ctrl_out();
 910     assert(c->is_Region() && c->req() == 3, "where's the pre barrier control flow?");
 911     iff = c->in(1)->is_IfProj() ? c->in(1)->in(0) : c->in(2)->in(0);
 912     assert(is_shenandoah_marking_if(igvn, iff), "expect marking test");
 913   }
 914   Node* cmpx = iff->in(1)->in(1);
 915   igvn->replace_node(cmpx, igvn->makecon(TypeInt::CC_EQ));
 916   igvn->rehash_node_delayed(call);
 917   call->del_req(call->req()-1);
 918 }
 919 
 920 void ShenandoahBarrierSetC2::enqueue_useful_gc_barrier(PhaseIterGVN* igvn, Node* node) const {
 921   if (node->Opcode() == Op_AddP && ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(node)) {
 922     igvn->add_users_to_worklist(node);
 923   }
 924 }
 925 
 926 void ShenandoahBarrierSetC2::eliminate_useless_gc_barriers(Unique_Node_List &useful, Compile* C) const {
 927   for (uint i = 0; i < useful.size(); i++) {
 928     Node* n = useful.at(i);
 929     if (n->Opcode() == Op_AddP && ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(n)) {
 930       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
 931         C->record_for_igvn(n->fast_out(i));
 932       }
 933     }
 934   }
 935   for (int i = state()->enqueue_barriers_count() - 1; i >= 0; i--) {
 936     ShenandoahEnqueueBarrierNode* n = state()->enqueue_barrier(i);
 937     if (!useful.member(n)) {
 938       state()->remove_enqueue_barrier(n);
 939     }
 940   }
 941   for (int i = state()->load_reference_barriers_count() - 1; i >= 0; i--) {
 942     ShenandoahLoadReferenceBarrierNode* n = state()->load_reference_barrier(i);
 943     if (!useful.member(n)) {
 944       state()->remove_load_reference_barrier(n);
 945     }
 946   }
 947 }
 948 
 949 void* ShenandoahBarrierSetC2::create_barrier_state(Arena* comp_arena) const {
 950   return new(comp_arena) ShenandoahBarrierSetC2State(comp_arena);
 951 }
 952 
 953 ShenandoahBarrierSetC2State* ShenandoahBarrierSetC2::state() const {
 954   return reinterpret_cast<ShenandoahBarrierSetC2State*>(Compile::current()->barrier_set_state());
 955 }
 956 
 957 // If the BarrierSetC2 state has kept macro nodes in its compilation unit state to be
 958 // expanded later, then now is the time to do so.
 959 bool ShenandoahBarrierSetC2::expand_macro_nodes(PhaseMacroExpand* macro) const { return false; }
 960 
 961 #ifdef ASSERT
 962 void ShenandoahBarrierSetC2::verify_gc_barriers(Compile* compile, CompilePhase phase) const {
 963   if (ShenandoahVerifyOptoBarriers && phase == BarrierSetC2::BeforeMacroExpand) {
 964     ShenandoahBarrierC2Support::verify(Compile::current()->root());
 965   } else if (phase == BarrierSetC2::BeforeCodeGen) {
 966     // Verify G1 pre-barriers
 967     const int marking_offset = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_active_offset());
 968 
 969     ResourceArea *area = Thread::current()->resource_area();
 970     Unique_Node_List visited(area);
 971     Node_List worklist(area);
 972     // We're going to walk control flow backwards starting from the Root
 973     worklist.push(compile->root());
 974     while (worklist.size() > 0) {
 975       Node *x = worklist.pop();
 976       if (x == NULL || x == compile->top()) continue;
 977       if (visited.member(x)) {
 978         continue;
 979       } else {
 980         visited.push(x);
 981       }
 982 
 983       if (x->is_Region()) {
 984         for (uint i = 1; i < x->req(); i++) {
 985           worklist.push(x->in(i));
 986         }
 987       } else {
 988         worklist.push(x->in(0));
 989         // We are looking for the pattern:
 990         //                            /->ThreadLocal
 991         // If->Bool->CmpI->LoadB->AddP->ConL(marking_offset)
 992         //              \->ConI(0)
 993         // We want to verify that the If and the LoadB have the same control
 994         // See GraphKit::g1_write_barrier_pre()
 995         if (x->is_If()) {
 996           IfNode *iff = x->as_If();
 997           if (iff->in(1)->is_Bool() && iff->in(1)->in(1)->is_Cmp()) {
 998             CmpNode *cmp = iff->in(1)->in(1)->as_Cmp();
 999             if (cmp->Opcode() == Op_CmpI && cmp->in(2)->is_Con() && cmp->in(2)->bottom_type()->is_int()->get_con() == 0
1000                 && cmp->in(1)->is_Load()) {
1001               LoadNode *load = cmp->in(1)->as_Load();
1002               if (load->Opcode() == Op_LoadB && load->in(2)->is_AddP() && load->in(2)->in(2)->Opcode() == Op_ThreadLocal
1003                   && load->in(2)->in(3)->is_Con()
1004                   && load->in(2)->in(3)->bottom_type()->is_intptr_t()->get_con() == marking_offset) {
1005 
1006                 Node *if_ctrl = iff->in(0);
1007                 Node *load_ctrl = load->in(0);
1008 
1009                 if (if_ctrl != load_ctrl) {
1010                   // Skip possible CProj->NeverBranch in infinite loops
1011                   if ((if_ctrl->is_Proj() && if_ctrl->Opcode() == Op_CProj)
1012                       && (if_ctrl->in(0)->is_MultiBranch() && if_ctrl->in(0)->Opcode() == Op_NeverBranch)) {
1013                     if_ctrl = if_ctrl->in(0)->in(0);
1014                   }
1015                 }
1016                 assert(load_ctrl != NULL && if_ctrl == load_ctrl, "controls must match");
1017               }
1018             }
1019           }
1020         }
1021       }
1022     }
1023   }
1024 }
1025 #endif
1026 
1027 Node* ShenandoahBarrierSetC2::ideal_node(PhaseGVN* phase, Node* n, bool can_reshape) const {
1028   if (is_shenandoah_wb_pre_call(n)) {
1029     uint cnt = ShenandoahBarrierSetC2::write_ref_field_pre_entry_Type()->domain()->cnt();
1030     if (n->req() > cnt) {
1031       Node* addp = n->in(cnt);
1032       if (has_only_shenandoah_wb_pre_uses(addp)) {
1033         n->del_req(cnt);
1034         if (can_reshape) {
1035           phase->is_IterGVN()->_worklist.push(addp);
1036         }
1037         return n;
1038       }
1039     }
1040   }
1041   if (n->Opcode() == Op_CmpP) {
1042     Node* in1 = n->in(1);
1043     Node* in2 = n->in(2);
1044     if (in1->bottom_type() == TypePtr::NULL_PTR) {
1045       in2 = step_over_gc_barrier(in2);
1046     }
1047     if (in2->bottom_type() == TypePtr::NULL_PTR) {
1048       in1 = step_over_gc_barrier(in1);
1049     }
1050     PhaseIterGVN* igvn = phase->is_IterGVN();
1051     if (in1 != n->in(1)) {
1052       if (igvn != NULL) {
1053         n->set_req_X(1, in1, igvn);
1054       } else {
1055         n->set_req(1, in1);
1056       }
1057       assert(in2 == n->in(2), "only one change");
1058       return n;
1059     }
1060     if (in2 != n->in(2)) {
1061       if (igvn != NULL) {
1062         n->set_req_X(2, in2, igvn);
1063       } else {
1064         n->set_req(2, in2);
1065       }
1066       return n;
1067     }
1068   } else if (can_reshape &&
1069              n->Opcode() == Op_If &&
1070              ShenandoahBarrierC2Support::is_heap_stable_test(n) &&
1071              n->in(0) != NULL) {
1072     Node* dom = n->in(0);
1073     Node* prev_dom = n;
1074     int op = n->Opcode();
1075     int dist = 16;
1076     // Search up the dominator tree for another heap stable test
1077     while (dom->Opcode() != op    ||  // Not same opcode?
1078            !ShenandoahBarrierC2Support::is_heap_stable_test(dom) ||  // Not same input 1?
1079            prev_dom->in(0) != dom) {  // One path of test does not dominate?
1080       if (dist < 0) return NULL;
1081 
1082       dist--;
1083       prev_dom = dom;
1084       dom = IfNode::up_one_dom(dom);
1085       if (!dom) return NULL;
1086     }
1087 
1088     // Check that we did not follow a loop back to ourselves
1089     if (n == dom) {
1090       return NULL;
1091     }
1092 
1093     return n->as_If()->dominated_by(prev_dom, phase->is_IterGVN());
1094   }
1095 
1096   return NULL;
1097 }
1098 
1099 bool ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(Node* n) {
1100   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1101     Node* u = n->fast_out(i);
1102     if (!is_shenandoah_wb_pre_call(u)) {
1103       return false;
1104     }
1105   }
1106   return n->outcnt() > 0;
1107 }
1108 
1109 bool ShenandoahBarrierSetC2::final_graph_reshaping(Compile* compile, Node* n, uint opcode) const {
1110   switch (opcode) {
1111     case Op_CallLeaf:
1112     case Op_CallLeafNoFP: {
1113       assert (n->is_Call(), "");
1114       CallNode *call = n->as_Call();
1115       if (ShenandoahBarrierSetC2::is_shenandoah_wb_pre_call(call)) {
1116         uint cnt = ShenandoahBarrierSetC2::write_ref_field_pre_entry_Type()->domain()->cnt();
1117         if (call->req() > cnt) {
1118           assert(call->req() == cnt + 1, "only one extra input");
1119           Node *addp = call->in(cnt);
1120           assert(!ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(addp), "useless address computation?");
1121           call->del_req(cnt);
1122         }
1123       }
1124       return false;
1125     }
1126     case Op_ShenandoahCompareAndSwapP:
1127     case Op_ShenandoahCompareAndSwapN:
1128     case Op_ShenandoahWeakCompareAndSwapN:
1129     case Op_ShenandoahWeakCompareAndSwapP:
1130     case Op_ShenandoahCompareAndExchangeP:
1131     case Op_ShenandoahCompareAndExchangeN:
1132 #ifdef ASSERT
1133       if( VerifyOptoOopOffsets ) {
1134         MemNode* mem  = n->as_Mem();
1135         // Check to see if address types have grounded out somehow.
1136         const TypeInstPtr *tp = mem->in(MemNode::Address)->bottom_type()->isa_instptr();
1137         ciInstanceKlass *k = tp->klass()->as_instance_klass();
1138         bool oop_offset_is_sane = k->contains_field_offset(tp->offset());
1139         assert( !tp || oop_offset_is_sane, "" );
1140       }
1141 #endif
1142       return true;
1143     case Op_ShenandoahLoadReferenceBarrier:
1144       assert(false, "should have been expanded already");
1145       return true;
1146     default:
1147       return false;
1148   }
1149 }
1150 
1151 bool ShenandoahBarrierSetC2::escape_add_to_con_graph(ConnectionGraph* conn_graph, PhaseGVN* gvn, Unique_Node_List* delayed_worklist, Node* n, uint opcode) const {
1152   switch (opcode) {
1153     case Op_ShenandoahCompareAndExchangeP:
1154     case Op_ShenandoahCompareAndExchangeN:
1155       conn_graph->add_objload_to_connection_graph(n, delayed_worklist);
1156       // fallthrough
1157     case Op_ShenandoahWeakCompareAndSwapP:
1158     case Op_ShenandoahWeakCompareAndSwapN:
1159     case Op_ShenandoahCompareAndSwapP:
1160     case Op_ShenandoahCompareAndSwapN:
1161       conn_graph->add_to_congraph_unsafe_access(n, opcode, delayed_worklist);
1162       return true;
1163     case Op_StoreP: {
1164       Node* adr = n->in(MemNode::Address);
1165       const Type* adr_type = gvn->type(adr);
1166       // Pointer stores in G1 barriers looks like unsafe access.
1167       // Ignore such stores to be able scalar replace non-escaping
1168       // allocations.
1169       if (adr_type->isa_rawptr() && adr->is_AddP()) {
1170         Node* base = conn_graph->get_addp_base(adr);
1171         if (base->Opcode() == Op_LoadP &&
1172           base->in(MemNode::Address)->is_AddP()) {
1173           adr = base->in(MemNode::Address);
1174           Node* tls = conn_graph->get_addp_base(adr);
1175           if (tls->Opcode() == Op_ThreadLocal) {
1176              int offs = (int) gvn->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
1177              const int buf_offset = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset());
1178              if (offs == buf_offset) {
1179                return true; // Pre barrier previous oop value store.
1180              }
1181           }
1182         }
1183       }
1184       return false;
1185     }
1186     case Op_ShenandoahEnqueueBarrier:
1187       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), delayed_worklist);
1188       break;
1189     case Op_ShenandoahLoadReferenceBarrier:
1190       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(ShenandoahLoadReferenceBarrierNode::ValueIn), delayed_worklist);
1191       return true;
1192     default:
1193       // Nothing
1194       break;
1195   }
1196   return false;
1197 }
1198 
1199 bool ShenandoahBarrierSetC2::escape_add_final_edges(ConnectionGraph* conn_graph, PhaseGVN* gvn, Node* n, uint opcode) const {
1200   switch (opcode) {
1201     case Op_ShenandoahCompareAndExchangeP:
1202     case Op_ShenandoahCompareAndExchangeN: {
1203       Node *adr = n->in(MemNode::Address);
1204       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, adr, NULL);
1205       // fallthrough
1206     }
1207     case Op_ShenandoahCompareAndSwapP:
1208     case Op_ShenandoahCompareAndSwapN:
1209     case Op_ShenandoahWeakCompareAndSwapP:
1210     case Op_ShenandoahWeakCompareAndSwapN:
1211       return conn_graph->add_final_edges_unsafe_access(n, opcode);
1212     case Op_ShenandoahEnqueueBarrier:
1213       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), NULL);
1214       return true;
1215     case Op_ShenandoahLoadReferenceBarrier:
1216       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(ShenandoahLoadReferenceBarrierNode::ValueIn), NULL);
1217       return true;
1218     default:
1219       // Nothing
1220       break;
1221   }
1222   return false;
1223 }
1224 
1225 bool ShenandoahBarrierSetC2::escape_has_out_with_unsafe_object(Node* n) const {
1226   return n->has_out_with(Op_ShenandoahCompareAndExchangeP) || n->has_out_with(Op_ShenandoahCompareAndExchangeN) ||
1227          n->has_out_with(Op_ShenandoahCompareAndSwapP, Op_ShenandoahCompareAndSwapN, Op_ShenandoahWeakCompareAndSwapP, Op_ShenandoahWeakCompareAndSwapN);
1228 
1229 }
1230 
1231 bool ShenandoahBarrierSetC2::matcher_find_shared_post_visit(Matcher* matcher, Node* n, uint opcode) const {
1232   switch (opcode) {
1233     case Op_ShenandoahCompareAndExchangeP:
1234     case Op_ShenandoahCompareAndExchangeN:
1235     case Op_ShenandoahWeakCompareAndSwapP:
1236     case Op_ShenandoahWeakCompareAndSwapN:
1237     case Op_ShenandoahCompareAndSwapP:
1238     case Op_ShenandoahCompareAndSwapN: {   // Convert trinary to binary-tree
1239       Node* newval = n->in(MemNode::ValueIn);
1240       Node* oldval = n->in(LoadStoreConditionalNode::ExpectedIn);
1241       Node* pair = new BinaryNode(oldval, newval);
1242       n->set_req(MemNode::ValueIn,pair);
1243       n->del_req(LoadStoreConditionalNode::ExpectedIn);
1244       return true;
1245     }
1246     default:
1247       break;
1248   }
1249   return false;
1250 }
1251 
1252 bool ShenandoahBarrierSetC2::matcher_is_store_load_barrier(Node* x, uint xop) const {
1253   return xop == Op_ShenandoahCompareAndExchangeP ||
1254          xop == Op_ShenandoahCompareAndExchangeN ||
1255          xop == Op_ShenandoahWeakCompareAndSwapP ||
1256          xop == Op_ShenandoahWeakCompareAndSwapN ||
1257          xop == Op_ShenandoahCompareAndSwapN ||
1258          xop == Op_ShenandoahCompareAndSwapP;
1259 }
--- EOF ---