1 /*
   2  * Copyright (c) 2015, 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 
  26 #include "gc/shenandoah/c2/shenandoahSupport.hpp"
  27 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
  28 #include "gc/shenandoah/shenandoahBarrierSetAssembler.hpp"
  29 #include "gc/shenandoah/shenandoahForwarding.hpp"
  30 #include "gc/shenandoah/shenandoahHeap.hpp"
  31 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
  32 #include "gc/shenandoah/shenandoahRuntime.hpp"
  33 #include "gc/shenandoah/shenandoahThreadLocalData.hpp"
  34 #include "opto/arraycopynode.hpp"
  35 #include "opto/block.hpp"
  36 #include "opto/callnode.hpp"
  37 #include "opto/castnode.hpp"
  38 #include "opto/movenode.hpp"
  39 #include "opto/phaseX.hpp"
  40 #include "opto/rootnode.hpp"
  41 #include "opto/runtime.hpp"
  42 #include "opto/subnode.hpp"
  43 
  44 bool ShenandoahBarrierC2Support::expand(Compile* C, PhaseIterGVN& igvn) {
  45   ShenandoahBarrierSetC2State* state = ShenandoahBarrierSetC2::bsc2()->state();
  46   if ((state->enqueue_barriers_count() +
  47        state->load_reference_barriers_count()) > 0) {
  48     bool attempt_more_loopopts = ShenandoahLoopOptsAfterExpansion;
  49     C->clear_major_progress();
  50     PhaseIdealLoop ideal_loop(igvn, LoopOptsShenandoahExpand);
  51     if (C->failing()) return false;
  52     PhaseIdealLoop::verify(igvn);
  53     DEBUG_ONLY(verify_raw_mem(C->root());)
  54     if (attempt_more_loopopts) {
  55       C->set_major_progress();
  56       if (!C->optimize_loops(igvn, LoopOptsShenandoahPostExpand)) {
  57         return false;
  58       }
  59       C->clear_major_progress();
  60     }
  61   }
  62   return true;
  63 }
  64 
  65 bool ShenandoahBarrierC2Support::is_heap_state_test(Node* iff, int mask) {
  66   if (!UseShenandoahGC) {
  67     return false;
  68   }
  69   assert(iff->is_If(), "bad input");
  70   if (iff->Opcode() != Op_If) {
  71     return false;
  72   }
  73   Node* bol = iff->in(1);
  74   if (!bol->is_Bool() || bol->as_Bool()->_test._test != BoolTest::ne) {
  75     return false;
  76   }
  77   Node* cmp = bol->in(1);
  78   if (cmp->Opcode() != Op_CmpI) {
  79     return false;
  80   }
  81   Node* in1 = cmp->in(1);
  82   Node* in2 = cmp->in(2);
  83   if (in2->find_int_con(-1) != 0) {
  84     return false;
  85   }
  86   if (in1->Opcode() != Op_AndI) {
  87     return false;
  88   }
  89   in2 = in1->in(2);
  90   if (in2->find_int_con(-1) != mask) {
  91     return false;
  92   }
  93   in1 = in1->in(1);
  94 
  95   return is_gc_state_load(in1);
  96 }
  97 
  98 bool ShenandoahBarrierC2Support::is_heap_stable_test(Node* iff) {
  99   return is_heap_state_test(iff, ShenandoahHeap::HAS_FORWARDED);
 100 }
 101 
 102 bool ShenandoahBarrierC2Support::is_gc_state_load(Node *n) {
 103   if (!UseShenandoahGC) {
 104     return false;
 105   }
 106   if (n->Opcode() != Op_LoadB && n->Opcode() != Op_LoadUB) {
 107     return false;
 108   }
 109   Node* addp = n->in(MemNode::Address);
 110   if (!addp->is_AddP()) {
 111     return false;
 112   }
 113   Node* base = addp->in(AddPNode::Address);
 114   Node* off = addp->in(AddPNode::Offset);
 115   if (base->Opcode() != Op_ThreadLocal) {
 116     return false;
 117   }
 118   if (off->find_intptr_t_con(-1) != in_bytes(ShenandoahThreadLocalData::gc_state_offset())) {
 119     return false;
 120   }
 121   return true;
 122 }
 123 
 124 bool ShenandoahBarrierC2Support::has_safepoint_between(Node* start, Node* stop, PhaseIdealLoop *phase) {
 125   assert(phase->is_dominator(stop, start), "bad inputs");
 126   ResourceMark rm;
 127   Unique_Node_List wq;
 128   wq.push(start);
 129   for (uint next = 0; next < wq.size(); next++) {
 130     Node *m = wq.at(next);
 131     if (m == stop) {
 132       continue;
 133     }
 134     if (m->is_SafePoint() && !m->is_CallLeaf()) {
 135       return true;
 136     }
 137     if (m->is_Region()) {
 138       for (uint i = 1; i < m->req(); i++) {
 139         wq.push(m->in(i));
 140       }
 141     } else {
 142       wq.push(m->in(0));
 143     }
 144   }
 145   return false;
 146 }
 147 
 148 bool ShenandoahBarrierC2Support::try_common_gc_state_load(Node *n, PhaseIdealLoop *phase) {
 149   assert(is_gc_state_load(n), "inconsistent");
 150   Node* addp = n->in(MemNode::Address);
 151   Node* dominator = NULL;
 152   for (DUIterator_Fast imax, i = addp->fast_outs(imax); i < imax; i++) {
 153     Node* u = addp->fast_out(i);
 154     assert(is_gc_state_load(u), "inconsistent");
 155     if (u != n && phase->is_dominator(u->in(0), n->in(0))) {
 156       if (dominator == NULL) {
 157         dominator = u;
 158       } else {
 159         if (phase->dom_depth(u->in(0)) < phase->dom_depth(dominator->in(0))) {
 160           dominator = u;
 161         }
 162       }
 163     }
 164   }
 165   if (dominator == NULL || has_safepoint_between(n->in(0), dominator->in(0), phase)) {
 166     return false;
 167   }
 168   phase->igvn().replace_node(n, dominator);
 169 
 170   return true;
 171 }
 172 
 173 #ifdef ASSERT
 174 bool ShenandoahBarrierC2Support::verify_helper(Node* in, Node_Stack& phis, VectorSet& visited, verify_type t, bool trace, Unique_Node_List& barriers_used) {
 175   assert(phis.size() == 0, "");
 176 
 177   while (true) {
 178     if (in->bottom_type() == TypePtr::NULL_PTR) {
 179       if (trace) {tty->print_cr("NULL");}
 180     } else if (!in->bottom_type()->make_ptr()->make_oopptr()) {
 181       if (trace) {tty->print_cr("Non oop");}
 182     } else if (t == ShenandoahLoad && ShenandoahOptimizeStableFinals &&
 183                in->bottom_type()->make_ptr()->isa_aryptr() &&
 184                in->bottom_type()->make_ptr()->is_aryptr()->is_stable()) {
 185       if (trace) {tty->print_cr("Stable array load");}
 186     } else {
 187       if (in->is_ConstraintCast()) {
 188         in = in->in(1);
 189         continue;
 190       } else if (in->is_AddP()) {
 191         assert(!in->in(AddPNode::Address)->is_top(), "no raw memory access");
 192         in = in->in(AddPNode::Address);
 193         continue;
 194       } else if (in->is_Con()) {
 195         if (trace) {
 196           tty->print("Found constant");
 197           in->dump();
 198         }
 199       } else if (in->Opcode() == Op_Parm) {
 200         if (trace) {
 201           tty->print("Found argument");
 202         }
 203       } else if (in->Opcode() == Op_CreateEx) {
 204         if (trace) {
 205           tty->print("Found create-exception");
 206         }
 207       } else if (in->Opcode() == Op_LoadP && in->adr_type() == TypeRawPtr::BOTTOM) {
 208         if (trace) {
 209           tty->print("Found raw LoadP (OSR argument?)");
 210         }
 211       } else if (in->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
 212         if (t == ShenandoahOopStore) {
 213           uint i = 0;
 214           for (; i < phis.size(); i++) {
 215             Node* n = phis.node_at(i);
 216             if (n->Opcode() == Op_ShenandoahEnqueueBarrier) {
 217               break;
 218             }
 219           }
 220           if (i == phis.size()) {
 221             return false;
 222           }
 223         }
 224         barriers_used.push(in);
 225         if (trace) {tty->print("Found barrier"); in->dump();}
 226       } else if (in->Opcode() == Op_ShenandoahEnqueueBarrier) {
 227         if (t != ShenandoahOopStore) {
 228           in = in->in(1);
 229           continue;
 230         }
 231         if (trace) {tty->print("Found enqueue barrier"); in->dump();}
 232         phis.push(in, in->req());
 233         in = in->in(1);
 234         continue;
 235       } else if (in->is_Proj() && in->in(0)->is_Allocate()) {
 236         if (trace) {
 237           tty->print("Found alloc");
 238           in->in(0)->dump();
 239         }
 240       } else if (in->is_Proj() && (in->in(0)->Opcode() == Op_CallStaticJava || in->in(0)->Opcode() == Op_CallDynamicJava)) {
 241         if (trace) {
 242           tty->print("Found Java call");
 243         }
 244       } else if (in->is_Phi()) {
 245         if (!visited.test_set(in->_idx)) {
 246           if (trace) {tty->print("Pushed phi:"); in->dump();}
 247           phis.push(in, 2);
 248           in = in->in(1);
 249           continue;
 250         }
 251         if (trace) {tty->print("Already seen phi:"); in->dump();}
 252       } else if (in->Opcode() == Op_CMoveP || in->Opcode() == Op_CMoveN) {
 253         if (!visited.test_set(in->_idx)) {
 254           if (trace) {tty->print("Pushed cmovep:"); in->dump();}
 255           phis.push(in, CMoveNode::IfTrue);
 256           in = in->in(CMoveNode::IfFalse);
 257           continue;
 258         }
 259         if (trace) {tty->print("Already seen cmovep:"); in->dump();}
 260       } else if (in->Opcode() == Op_EncodeP || in->Opcode() == Op_DecodeN) {
 261         in = in->in(1);
 262         continue;
 263       } else {
 264         return false;
 265       }
 266     }
 267     bool cont = false;
 268     while (phis.is_nonempty()) {
 269       uint idx = phis.index();
 270       Node* phi = phis.node();
 271       if (idx >= phi->req()) {
 272         if (trace) {tty->print("Popped phi:"); phi->dump();}
 273         phis.pop();
 274         continue;
 275       }
 276       if (trace) {tty->print("Next entry(%d) for phi:", idx); phi->dump();}
 277       in = phi->in(idx);
 278       phis.set_index(idx+1);
 279       cont = true;
 280       break;
 281     }
 282     if (!cont) {
 283       break;
 284     }
 285   }
 286   return true;
 287 }
 288 
 289 void ShenandoahBarrierC2Support::report_verify_failure(const char* msg, Node* n1, Node* n2) {
 290   if (n1 != NULL) {
 291     n1->dump(+10);
 292   }
 293   if (n2 != NULL) {
 294     n2->dump(+10);
 295   }
 296   fatal("%s", msg);
 297 }
 298 
 299 void ShenandoahBarrierC2Support::verify(RootNode* root) {
 300   ResourceMark rm;
 301   Unique_Node_List wq;
 302   GrowableArray<Node*> barriers;
 303   Unique_Node_List barriers_used;
 304   Node_Stack phis(0);
 305   VectorSet visited(Thread::current()->resource_area());
 306   const bool trace = false;
 307   const bool verify_no_useless_barrier = false;
 308 
 309   wq.push(root);
 310   for (uint next = 0; next < wq.size(); next++) {
 311     Node *n = wq.at(next);
 312     if (n->is_Load()) {
 313       const bool trace = false;
 314       if (trace) {tty->print("Verifying"); n->dump();}
 315       if (n->Opcode() == Op_LoadRange || n->Opcode() == Op_LoadKlass || n->Opcode() == Op_LoadNKlass) {
 316         if (trace) {tty->print_cr("Load range/klass");}
 317       } else {
 318         const TypePtr* adr_type = n->as_Load()->adr_type();
 319 
 320         if (adr_type->isa_oopptr() && adr_type->is_oopptr()->offset() == oopDesc::mark_offset_in_bytes()) {
 321           if (trace) {tty->print_cr("Mark load");}
 322         } else if (adr_type->isa_instptr() &&
 323                    adr_type->is_instptr()->klass()->is_subtype_of(Compile::current()->env()->Reference_klass()) &&
 324                    adr_type->is_instptr()->offset() == java_lang_ref_Reference::referent_offset) {
 325           if (trace) {tty->print_cr("Reference.get()");}
 326         } else {
 327           bool verify = true;
 328           if (adr_type->isa_instptr()) {
 329             const TypeInstPtr* tinst = adr_type->is_instptr();
 330             ciKlass* k = tinst->klass();
 331             assert(k->is_instance_klass(), "");
 332             ciInstanceKlass* ik = (ciInstanceKlass*)k;
 333             int offset = adr_type->offset();
 334 
 335             if ((ik->debug_final_field_at(offset) && ShenandoahOptimizeInstanceFinals) ||
 336                 (ik->debug_stable_field_at(offset) && ShenandoahOptimizeStableFinals)) {
 337               if (trace) {tty->print_cr("Final/stable");}
 338               verify = false;
 339             } else if (k == ciEnv::current()->Class_klass() &&
 340                        tinst->const_oop() != NULL &&
 341                        tinst->offset() >= (ik->size_helper() * wordSize)) {
 342               ciInstanceKlass* k = tinst->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
 343               ciField* field = k->get_field_by_offset(tinst->offset(), true);
 344               if ((ShenandoahOptimizeStaticFinals && field->is_final()) ||
 345                   (ShenandoahOptimizeStableFinals && field->is_stable())) {
 346                 verify = false;
 347               }
 348             }
 349           }
 350 
 351           if (verify && !verify_helper(n->in(MemNode::Address), phis, visited, ShenandoahLoad, trace, barriers_used)) {
 352             report_verify_failure("Shenandoah verification: Load should have barriers", n);
 353           }
 354         }
 355       }
 356     } else if (n->is_Store()) {
 357       const bool trace = false;
 358 
 359       if (trace) {tty->print("Verifying"); n->dump();}
 360       if (n->in(MemNode::ValueIn)->bottom_type()->make_oopptr()) {
 361         Node* adr = n->in(MemNode::Address);
 362         bool verify = true;
 363 
 364         if (adr->is_AddP() && adr->in(AddPNode::Base)->is_top()) {
 365           adr = adr->in(AddPNode::Address);
 366           if (adr->is_AddP()) {
 367             assert(adr->in(AddPNode::Base)->is_top(), "");
 368             adr = adr->in(AddPNode::Address);
 369             if (adr->Opcode() == Op_LoadP &&
 370                 adr->in(MemNode::Address)->in(AddPNode::Base)->is_top() &&
 371                 adr->in(MemNode::Address)->in(AddPNode::Address)->Opcode() == Op_ThreadLocal &&
 372                 adr->in(MemNode::Address)->in(AddPNode::Offset)->find_intptr_t_con(-1) == in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset())) {
 373               if (trace) {tty->print_cr("SATB prebarrier");}
 374               verify = false;
 375             }
 376           }
 377         }
 378 
 379         if (verify && !verify_helper(n->in(MemNode::ValueIn), phis, visited, ShenandoahStoreValEnqueueBarrier ? ShenandoahOopStore : ShenandoahValue, trace, barriers_used)) {
 380           report_verify_failure("Shenandoah verification: Store should have barriers", n);
 381         }
 382       }
 383       if (!verify_helper(n->in(MemNode::Address), phis, visited, ShenandoahStore, trace, barriers_used)) {
 384         report_verify_failure("Shenandoah verification: Store (address) should have barriers", n);
 385       }
 386     } else if (n->Opcode() == Op_CmpP) {
 387       const bool trace = false;
 388 
 389       Node* in1 = n->in(1);
 390       Node* in2 = n->in(2);
 391       if (in1->bottom_type()->isa_oopptr()) {
 392         if (trace) {tty->print("Verifying"); n->dump();}
 393 
 394         bool mark_inputs = false;
 395         if (in1->bottom_type() == TypePtr::NULL_PTR || in2->bottom_type() == TypePtr::NULL_PTR ||
 396             (in1->is_Con() || in2->is_Con())) {
 397           if (trace) {tty->print_cr("Comparison against a constant");}
 398           mark_inputs = true;
 399         } else if ((in1->is_CheckCastPP() && in1->in(1)->is_Proj() && in1->in(1)->in(0)->is_Allocate()) ||
 400                    (in2->is_CheckCastPP() && in2->in(1)->is_Proj() && in2->in(1)->in(0)->is_Allocate())) {
 401           if (trace) {tty->print_cr("Comparison with newly alloc'ed object");}
 402           mark_inputs = true;
 403         } else {
 404           assert(in2->bottom_type()->isa_oopptr(), "");
 405 
 406           if (!verify_helper(in1, phis, visited, ShenandoahStore, trace, barriers_used) ||
 407               !verify_helper(in2, phis, visited, ShenandoahStore, trace, barriers_used)) {
 408             report_verify_failure("Shenandoah verification: Cmp should have barriers", n);
 409           }
 410         }
 411         if (verify_no_useless_barrier &&
 412             mark_inputs &&
 413             (!verify_helper(in1, phis, visited, ShenandoahValue, trace, barriers_used) ||
 414              !verify_helper(in2, phis, visited, ShenandoahValue, trace, barriers_used))) {
 415           phis.clear();
 416           visited.Reset();
 417         }
 418       }
 419     } else if (n->is_LoadStore()) {
 420       if (n->in(MemNode::ValueIn)->bottom_type()->make_ptr() &&
 421           !verify_helper(n->in(MemNode::ValueIn), phis, visited, ShenandoahStoreValEnqueueBarrier ? ShenandoahOopStore : ShenandoahValue, trace, barriers_used)) {
 422         report_verify_failure("Shenandoah verification: LoadStore (value) should have barriers", n);
 423       }
 424 
 425       if (n->in(MemNode::Address)->bottom_type()->make_oopptr() && !verify_helper(n->in(MemNode::Address), phis, visited, ShenandoahStore, trace, barriers_used)) {
 426         report_verify_failure("Shenandoah verification: LoadStore (address) should have barriers", n);
 427       }
 428     } else if (n->Opcode() == Op_CallLeafNoFP || n->Opcode() == Op_CallLeaf) {
 429       CallNode* call = n->as_Call();
 430 
 431       static struct {
 432         const char* name;
 433         struct {
 434           int pos;
 435           verify_type t;
 436         } args[6];
 437       } calls[] = {
 438         "aescrypt_encryptBlock",
 439         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 440           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 441         "aescrypt_decryptBlock",
 442         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 443           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 444         "multiplyToLen",
 445         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+2, ShenandoahLoad },   { TypeFunc::Parms+4, ShenandoahStore },
 446           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 447         "squareToLen",
 448         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+2, ShenandoahLoad },   { -1,  ShenandoahNone},
 449           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 450         "montgomery_multiply",
 451         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahLoad },   { TypeFunc::Parms+2, ShenandoahLoad },
 452           { TypeFunc::Parms+6, ShenandoahStore }, { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 453         "montgomery_square",
 454         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahLoad },   { TypeFunc::Parms+5, ShenandoahStore },
 455           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 456         "mulAdd",
 457         { { TypeFunc::Parms, ShenandoahStore },  { TypeFunc::Parms+1, ShenandoahLoad },   { -1,  ShenandoahNone},
 458           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 459         "vectorizedMismatch",
 460         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahLoad },   { -1,  ShenandoahNone},
 461           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 462         "updateBytesCRC32",
 463         { { TypeFunc::Parms+1, ShenandoahLoad }, { -1,  ShenandoahNone},                  { -1,  ShenandoahNone},
 464           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 465         "updateBytesAdler32",
 466         { { TypeFunc::Parms+1, ShenandoahLoad }, { -1,  ShenandoahNone},                  { -1,  ShenandoahNone},
 467           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 468         "updateBytesCRC32C",
 469         { { TypeFunc::Parms+1, ShenandoahLoad }, { TypeFunc::Parms+3, ShenandoahLoad},    { -1,  ShenandoahNone},
 470           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 471         "counterMode_AESCrypt",
 472         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 473           { TypeFunc::Parms+3, ShenandoahStore }, { TypeFunc::Parms+5, ShenandoahStore }, { TypeFunc::Parms+6, ShenandoahStore } },
 474         "cipherBlockChaining_encryptAESCrypt",
 475         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 476           { TypeFunc::Parms+3, ShenandoahLoad },  { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 477         "cipherBlockChaining_decryptAESCrypt",
 478         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 479           { TypeFunc::Parms+3, ShenandoahLoad },  { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 480         "shenandoah_clone_barrier",
 481         { { TypeFunc::Parms, ShenandoahLoad },   { -1,  ShenandoahNone},                  { -1,  ShenandoahNone},
 482           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 483         "ghash_processBlocks",
 484         { { TypeFunc::Parms, ShenandoahStore },  { TypeFunc::Parms+1, ShenandoahLoad },   { TypeFunc::Parms+2, ShenandoahLoad },
 485           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 486         "sha1_implCompress",
 487         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
 488           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 489         "sha256_implCompress",
 490         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
 491           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 492         "sha512_implCompress",
 493         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
 494           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 495         "sha1_implCompressMB",
 496         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
 497           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 498         "sha256_implCompressMB",
 499         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
 500           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 501         "sha512_implCompressMB",
 502         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
 503           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 504         "encodeBlock",
 505         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+3, ShenandoahStore },   { -1, ShenandoahNone },
 506           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 507       };
 508 
 509       if (call->is_call_to_arraycopystub()) {
 510         Node* dest = NULL;
 511         const TypeTuple* args = n->as_Call()->_tf->domain_sig();
 512         for (uint i = TypeFunc::Parms, j = 0; i < args->cnt(); i++) {
 513           if (args->field_at(i)->isa_ptr()) {
 514             j++;
 515             if (j == 2) {
 516               dest = n->in(i);
 517               break;
 518             }
 519           }
 520         }
 521         if (!verify_helper(n->in(TypeFunc::Parms), phis, visited, ShenandoahLoad, trace, barriers_used) ||
 522             !verify_helper(dest, phis, visited, ShenandoahStore, trace, barriers_used)) {
 523           report_verify_failure("Shenandoah verification: ArrayCopy should have barriers", n);
 524         }
 525       } else if (strlen(call->_name) > 5 &&
 526                  !strcmp(call->_name + strlen(call->_name) - 5, "_fill")) {
 527         if (!verify_helper(n->in(TypeFunc::Parms), phis, visited, ShenandoahStore, trace, barriers_used)) {
 528           report_verify_failure("Shenandoah verification: _fill should have barriers", n);
 529         }
 530       } else if (!strcmp(call->_name, "shenandoah_wb_pre")) {
 531         // skip
 532       } else {
 533         const int calls_len = sizeof(calls) / sizeof(calls[0]);
 534         int i = 0;
 535         for (; i < calls_len; i++) {
 536           if (!strcmp(calls[i].name, call->_name)) {
 537             break;
 538           }
 539         }
 540         if (i != calls_len) {
 541           const uint args_len = sizeof(calls[0].args) / sizeof(calls[0].args[0]);
 542           for (uint j = 0; j < args_len; j++) {
 543             int pos = calls[i].args[j].pos;
 544             if (pos == -1) {
 545               break;
 546             }
 547             if (!verify_helper(call->in(pos), phis, visited, calls[i].args[j].t, trace, barriers_used)) {
 548               report_verify_failure("Shenandoah verification: intrinsic calls should have barriers", n);
 549             }
 550           }
 551           for (uint j = TypeFunc::Parms; j < call->req(); j++) {
 552             if (call->in(j)->bottom_type()->make_ptr() &&
 553                 call->in(j)->bottom_type()->make_ptr()->isa_oopptr()) {
 554               uint k = 0;
 555               for (; k < args_len && calls[i].args[k].pos != (int)j; k++);
 556               if (k == args_len) {
 557                 fatal("arg %d for call %s not covered", j, call->_name);
 558               }
 559             }
 560           }
 561         } else {
 562           for (uint j = TypeFunc::Parms; j < call->req(); j++) {
 563             if (call->in(j)->bottom_type()->make_ptr() &&
 564                 call->in(j)->bottom_type()->make_ptr()->isa_oopptr()) {
 565               fatal("%s not covered", call->_name);
 566             }
 567           }
 568         }
 569       }
 570     } else if (n->Opcode() == Op_ShenandoahEnqueueBarrier || n->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
 571       // skip
 572     } else if (n->is_AddP()
 573                || n->is_Phi()
 574                || n->is_ConstraintCast()
 575                || n->Opcode() == Op_Return
 576                || n->Opcode() == Op_CMoveP
 577                || n->Opcode() == Op_CMoveN
 578                || n->Opcode() == Op_Rethrow
 579                || n->is_MemBar()
 580                || n->Opcode() == Op_Conv2B
 581                || n->Opcode() == Op_SafePoint
 582                || n->is_CallJava()
 583                || n->Opcode() == Op_Unlock
 584                || n->Opcode() == Op_EncodeP
 585                || n->Opcode() == Op_DecodeN) {
 586       // nothing to do
 587     } else {
 588       static struct {
 589         int opcode;
 590         struct {
 591           int pos;
 592           verify_type t;
 593         } inputs[2];
 594       } others[] = {
 595         Op_FastLock,
 596         { { 1, ShenandoahLoad },                  { -1, ShenandoahNone} },
 597         Op_Lock,
 598         { { TypeFunc::Parms, ShenandoahLoad },    { -1, ShenandoahNone} },
 599         Op_ArrayCopy,
 600         { { ArrayCopyNode::Src, ShenandoahLoad }, { ArrayCopyNode::Dest, ShenandoahStore } },
 601         Op_StrCompressedCopy,
 602         { { 2, ShenandoahLoad },                  { 3, ShenandoahStore } },
 603         Op_StrInflatedCopy,
 604         { { 2, ShenandoahLoad },                  { 3, ShenandoahStore } },
 605         Op_AryEq,
 606         { { 2, ShenandoahLoad },                  { 3, ShenandoahLoad } },
 607         Op_StrIndexOf,
 608         { { 2, ShenandoahLoad },                  { 4, ShenandoahLoad } },
 609         Op_StrComp,
 610         { { 2, ShenandoahLoad },                  { 4, ShenandoahLoad } },
 611         Op_StrEquals,
 612         { { 2, ShenandoahLoad },                  { 3, ShenandoahLoad } },
 613         Op_EncodeISOArray,
 614         { { 2, ShenandoahLoad },                  { 3, ShenandoahStore } },
 615         Op_HasNegatives,
 616         { { 2, ShenandoahLoad },                  { -1, ShenandoahNone} },
 617         Op_CastP2X,
 618         { { 1, ShenandoahLoad },                  { -1, ShenandoahNone} },
 619         Op_StrIndexOfChar,
 620         { { 2, ShenandoahLoad },                  { -1, ShenandoahNone } },
 621       };
 622 
 623       const int others_len = sizeof(others) / sizeof(others[0]);
 624       int i = 0;
 625       for (; i < others_len; i++) {
 626         if (others[i].opcode == n->Opcode()) {
 627           break;
 628         }
 629       }
 630       uint stop = n->is_Call() ? n->as_Call()->tf()->domain_sig()->cnt() : n->req();
 631       if (i != others_len) {
 632         const uint inputs_len = sizeof(others[0].inputs) / sizeof(others[0].inputs[0]);
 633         for (uint j = 0; j < inputs_len; j++) {
 634           int pos = others[i].inputs[j].pos;
 635           if (pos == -1) {
 636             break;
 637           }
 638           if (!verify_helper(n->in(pos), phis, visited, others[i].inputs[j].t, trace, barriers_used)) {
 639             report_verify_failure("Shenandoah verification: intrinsic calls should have barriers", n);
 640           }
 641         }
 642         for (uint j = 1; j < stop; j++) {
 643           if (n->in(j) != NULL && n->in(j)->bottom_type()->make_ptr() &&
 644               n->in(j)->bottom_type()->make_ptr()->make_oopptr()) {
 645             uint k = 0;
 646             for (; k < inputs_len && others[i].inputs[k].pos != (int)j; k++);
 647             if (k == inputs_len) {
 648               fatal("arg %d for node %s not covered", j, n->Name());
 649             }
 650           }
 651         }
 652       } else {
 653         for (uint j = 1; j < stop; j++) {
 654           if (n->in(j) != NULL && n->in(j)->bottom_type()->make_ptr() &&
 655               n->in(j)->bottom_type()->make_ptr()->make_oopptr()) {
 656             fatal("%s not covered", n->Name());
 657           }
 658         }
 659       }
 660     }
 661 
 662     if (n->is_SafePoint()) {
 663       SafePointNode* sfpt = n->as_SafePoint();
 664       if (verify_no_useless_barrier && sfpt->jvms() != NULL) {
 665         for (uint i = sfpt->jvms()->scloff(); i < sfpt->jvms()->endoff(); i++) {
 666           if (!verify_helper(sfpt->in(i), phis, visited, ShenandoahLoad, trace, barriers_used)) {
 667             phis.clear();
 668             visited.Reset();
 669           }
 670         }
 671       }
 672     }
 673     for( uint i = 0; i < n->len(); ++i ) {
 674       Node *m = n->in(i);
 675       if (m == NULL) continue;
 676 
 677       // In most cases, inputs should be known to be non null. If it's
 678       // not the case, it could be a missing cast_not_null() in an
 679       // intrinsic or support might be needed in AddPNode::Ideal() to
 680       // avoid a NULL+offset input.
 681       if (!(n->is_Phi() ||
 682             (n->is_SafePoint() && (!n->is_CallRuntime() || !strcmp(n->as_Call()->_name, "shenandoah_wb_pre") || !strcmp(n->as_Call()->_name, "unsafe_arraycopy"))) ||
 683             n->Opcode() == Op_CmpP ||
 684             n->Opcode() == Op_CmpN ||
 685             (n->Opcode() == Op_StoreP && i == StoreNode::ValueIn) ||
 686             (n->Opcode() == Op_StoreN && i == StoreNode::ValueIn) ||
 687             n->is_ConstraintCast() ||
 688             n->Opcode() == Op_Return ||
 689             n->Opcode() == Op_Conv2B ||
 690             n->is_AddP() ||
 691             n->Opcode() == Op_CMoveP ||
 692             n->Opcode() == Op_CMoveN ||
 693             n->Opcode() == Op_Rethrow ||
 694             n->is_MemBar() ||
 695             n->is_Mem() ||
 696             n->Opcode() == Op_AryEq ||
 697             n->Opcode() == Op_SCMemProj ||
 698             n->Opcode() == Op_EncodeP ||
 699             n->Opcode() == Op_DecodeN ||
 700             n->Opcode() == Op_ShenandoahEnqueueBarrier ||
 701             n->Opcode() == Op_ShenandoahLoadReferenceBarrier)) {
 702         if (m->bottom_type()->make_oopptr() && m->bottom_type()->make_oopptr()->meet(TypePtr::NULL_PTR) == m->bottom_type()) {
 703           report_verify_failure("Shenandoah verification: null input", n, m);
 704         }
 705       }
 706 
 707       wq.push(m);
 708     }
 709   }
 710 
 711   if (verify_no_useless_barrier) {
 712     for (int i = 0; i < barriers.length(); i++) {
 713       Node* n = barriers.at(i);
 714       if (!barriers_used.member(n)) {
 715         tty->print("XXX useless barrier"); n->dump(-2);
 716         ShouldNotReachHere();
 717       }
 718     }
 719   }
 720 }
 721 #endif
 722 
 723 bool ShenandoahBarrierC2Support::is_dominator_same_ctrl(Node* c, Node* d, Node* n, PhaseIdealLoop* phase) {
 724   // That both nodes have the same control is not sufficient to prove
 725   // domination, verify that there's no path from d to n
 726   ResourceMark rm;
 727   Unique_Node_List wq;
 728   wq.push(d);
 729   for (uint next = 0; next < wq.size(); next++) {
 730     Node *m = wq.at(next);
 731     if (m == n) {
 732       return false;
 733     }
 734     if (m->is_Phi() && m->in(0)->is_Loop()) {
 735       assert(phase->ctrl_or_self(m->in(LoopNode::EntryControl)) != c, "following loop entry should lead to new control");
 736     } else {
 737       for (uint i = 0; i < m->req(); i++) {
 738         if (m->in(i) != NULL && phase->ctrl_or_self(m->in(i)) == c) {
 739           wq.push(m->in(i));
 740         }
 741       }
 742     }
 743   }
 744   return true;
 745 }
 746 
 747 bool ShenandoahBarrierC2Support::is_dominator(Node* d_c, Node* n_c, Node* d, Node* n, PhaseIdealLoop* phase) {
 748   if (d_c != n_c) {
 749     return phase->is_dominator(d_c, n_c);
 750   }
 751   return is_dominator_same_ctrl(d_c, d, n, phase);
 752 }
 753 
 754 Node* next_mem(Node* mem, int alias) {
 755   Node* res = NULL;
 756   if (mem->is_Proj()) {
 757     res = mem->in(0);
 758   } else if (mem->is_SafePoint() || mem->is_MemBar()) {
 759     res = mem->in(TypeFunc::Memory);
 760   } else if (mem->is_Phi()) {
 761     res = mem->in(1);
 762   } else if (mem->is_MergeMem()) {
 763     res = mem->as_MergeMem()->memory_at(alias);
 764   } else if (mem->is_Store() || mem->is_LoadStore() || mem->is_ClearArray()) {
 765     assert(alias = Compile::AliasIdxRaw, "following raw memory can't lead to a barrier");
 766     res = mem->in(MemNode::Memory);
 767   } else {
 768 #ifdef ASSERT
 769     mem->dump();
 770 #endif
 771     ShouldNotReachHere();
 772   }
 773   return res;
 774 }
 775 
 776 Node* ShenandoahBarrierC2Support::no_branches(Node* c, Node* dom, bool allow_one_proj, PhaseIdealLoop* phase) {
 777   Node* iffproj = NULL;
 778   while (c != dom) {
 779     Node* next = phase->idom(c);
 780     assert(next->unique_ctrl_out() == c || c->is_Proj() || c->is_Region(), "multiple control flow out but no proj or region?");
 781     if (c->is_Region()) {
 782       ResourceMark rm;
 783       Unique_Node_List wq;
 784       wq.push(c);
 785       for (uint i = 0; i < wq.size(); i++) {
 786         Node *n = wq.at(i);
 787         if (n == next) {
 788           continue;
 789         }
 790         if (n->is_Region()) {
 791           for (uint j = 1; j < n->req(); j++) {
 792             wq.push(n->in(j));
 793           }
 794         } else {
 795           wq.push(n->in(0));
 796         }
 797       }
 798       for (uint i = 0; i < wq.size(); i++) {
 799         Node *n = wq.at(i);
 800         assert(n->is_CFG(), "");
 801         if (n->is_Multi()) {
 802           for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
 803             Node* u = n->fast_out(j);
 804             if (u->is_CFG()) {
 805               if (!wq.member(u) && !u->as_Proj()->is_uncommon_trap_proj(Deoptimization::Reason_none)) {
 806                 return NodeSentinel;
 807               }
 808             }
 809           }
 810         }
 811       }
 812     } else  if (c->is_Proj()) {
 813       if (c->is_IfProj()) {
 814         if (c->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none) != NULL) {
 815           // continue;
 816         } else {
 817           if (!allow_one_proj) {
 818             return NodeSentinel;
 819           }
 820           if (iffproj == NULL) {
 821             iffproj = c;
 822           } else {
 823             return NodeSentinel;
 824           }
 825         }
 826       } else if (c->Opcode() == Op_JumpProj) {
 827         return NodeSentinel; // unsupported
 828       } else if (c->Opcode() == Op_CatchProj) {
 829         return NodeSentinel; // unsupported
 830       } else if (c->Opcode() == Op_CProj && next->Opcode() == Op_NeverBranch) {
 831         return NodeSentinel; // unsupported
 832       } else {
 833         assert(next->unique_ctrl_out() == c, "unsupported branch pattern");
 834       }
 835     }
 836     c = next;
 837   }
 838   return iffproj;
 839 }
 840 
 841 Node* ShenandoahBarrierC2Support::dom_mem(Node* mem, Node* ctrl, int alias, Node*& mem_ctrl, PhaseIdealLoop* phase) {
 842   ResourceMark rm;
 843   VectorSet wq(Thread::current()->resource_area());
 844   wq.set(mem->_idx);
 845   mem_ctrl = phase->ctrl_or_self(mem);
 846   while (!phase->is_dominator(mem_ctrl, ctrl) || mem_ctrl == ctrl) {
 847     mem = next_mem(mem, alias);
 848     if (wq.test_set(mem->_idx)) {
 849       return NULL;
 850     }
 851     mem_ctrl = phase->ctrl_or_self(mem);
 852   }
 853   if (mem->is_MergeMem()) {
 854     mem = mem->as_MergeMem()->memory_at(alias);
 855     mem_ctrl = phase->ctrl_or_self(mem);
 856   }
 857   return mem;
 858 }
 859 
 860 Node* ShenandoahBarrierC2Support::find_bottom_mem(Node* ctrl, PhaseIdealLoop* phase) {
 861   Node* mem = NULL;
 862   Node* c = ctrl;
 863   do {
 864     if (c->is_Region()) {
 865       Node* phi_bottom = NULL;
 866       for (DUIterator_Fast imax, i = c->fast_outs(imax); i < imax && mem == NULL; i++) {
 867         Node* u = c->fast_out(i);
 868         if (u->is_Phi() && u->bottom_type() == Type::MEMORY) {
 869           if (u->adr_type() == TypePtr::BOTTOM) {
 870             mem = u;
 871           }
 872         }
 873       }
 874     } else {
 875       if (c->is_Call() && c->as_Call()->adr_type() != NULL) {
 876         CallProjections* projs = c->as_Call()->extract_projections(true, false);
 877         if (projs->fallthrough_memproj != NULL) {
 878           if (projs->fallthrough_memproj->adr_type() == TypePtr::BOTTOM) {
 879             if (projs->catchall_memproj == NULL) {
 880               mem = projs->fallthrough_memproj;
 881             } else {
 882               if (phase->is_dominator(projs->fallthrough_catchproj, ctrl)) {
 883                 mem = projs->fallthrough_memproj;
 884               } else {
 885                 assert(phase->is_dominator(projs->catchall_catchproj, ctrl), "one proj must dominate barrier");
 886                 mem = projs->catchall_memproj;
 887               }
 888             }
 889           }
 890         } else {
 891           Node* proj = c->as_Call()->proj_out(TypeFunc::Memory);
 892           if (proj != NULL &&
 893               proj->adr_type() == TypePtr::BOTTOM) {
 894             mem = proj;
 895           }
 896         }
 897       } else {
 898         for (DUIterator_Fast imax, i = c->fast_outs(imax); i < imax; i++) {
 899           Node* u = c->fast_out(i);
 900           if (u->is_Proj() &&
 901               u->bottom_type() == Type::MEMORY &&
 902               u->adr_type() == TypePtr::BOTTOM) {
 903               assert(c->is_SafePoint() || c->is_MemBar() || c->is_Start(), "");
 904               assert(mem == NULL, "only one proj");
 905               mem = u;
 906           }
 907         }
 908         assert(!c->is_Call() || c->as_Call()->adr_type() != NULL || mem == NULL, "no mem projection expected");
 909       }
 910     }
 911     c = phase->idom(c);
 912   } while (mem == NULL);
 913   return mem;
 914 }
 915 
 916 void ShenandoahBarrierC2Support::follow_barrier_uses(Node* n, Node* ctrl, Unique_Node_List& uses, PhaseIdealLoop* phase) {
 917   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
 918     Node* u = n->fast_out(i);
 919     if (!u->is_CFG() && phase->get_ctrl(u) == ctrl && (!u->is_Phi() || !u->in(0)->is_Loop() || u->in(LoopNode::LoopBackControl) != n)) {
 920       uses.push(u);
 921     }
 922   }
 923 }
 924 
 925 static void hide_strip_mined_loop(OuterStripMinedLoopNode* outer, CountedLoopNode* inner, PhaseIdealLoop* phase) {
 926   OuterStripMinedLoopEndNode* le = inner->outer_loop_end();
 927   Node* new_outer = new LoopNode(outer->in(LoopNode::EntryControl), outer->in(LoopNode::LoopBackControl));
 928   phase->register_control(new_outer, phase->get_loop(outer), outer->in(LoopNode::EntryControl));
 929   Node* new_le = new IfNode(le->in(0), le->in(1), le->_prob, le->_fcnt);
 930   phase->register_control(new_le, phase->get_loop(le), le->in(0));
 931   phase->lazy_replace(outer, new_outer);
 932   phase->lazy_replace(le, new_le);
 933   inner->clear_strip_mined();
 934 }
 935 
 936 void ShenandoahBarrierC2Support::test_heap_stable(Node*& ctrl, Node* raw_mem, Node*& heap_stable_ctrl,
 937                                                   PhaseIdealLoop* phase) {
 938   IdealLoopTree* loop = phase->get_loop(ctrl);
 939   Node* thread = new ThreadLocalNode();
 940   phase->register_new_node(thread, ctrl);
 941   Node* offset = phase->igvn().MakeConX(in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 942   phase->set_ctrl(offset, phase->C->root());
 943   Node* gc_state_addr = new AddPNode(phase->C->top(), thread, offset);
 944   phase->register_new_node(gc_state_addr, ctrl);
 945   uint gc_state_idx = Compile::AliasIdxRaw;
 946   const TypePtr* gc_state_adr_type = NULL; // debug-mode-only argument
 947   debug_only(gc_state_adr_type = phase->C->get_adr_type(gc_state_idx));
 948 
 949   Node* gc_state = new LoadBNode(ctrl, raw_mem, gc_state_addr, gc_state_adr_type, TypeInt::BYTE, MemNode::unordered);
 950   phase->register_new_node(gc_state, ctrl);
 951   Node* heap_stable_and = new AndINode(gc_state, phase->igvn().intcon(ShenandoahHeap::HAS_FORWARDED));
 952   phase->register_new_node(heap_stable_and, ctrl);
 953   Node* heap_stable_cmp = new CmpINode(heap_stable_and, phase->igvn().zerocon(T_INT));
 954   phase->register_new_node(heap_stable_cmp, ctrl);
 955   Node* heap_stable_test = new BoolNode(heap_stable_cmp, BoolTest::ne);
 956   phase->register_new_node(heap_stable_test, ctrl);
 957   IfNode* heap_stable_iff = new IfNode(ctrl, heap_stable_test, PROB_UNLIKELY(0.999), COUNT_UNKNOWN);
 958   phase->register_control(heap_stable_iff, loop, ctrl);
 959 
 960   heap_stable_ctrl = new IfFalseNode(heap_stable_iff);
 961   phase->register_control(heap_stable_ctrl, loop, heap_stable_iff);
 962   ctrl = new IfTrueNode(heap_stable_iff);
 963   phase->register_control(ctrl, loop, heap_stable_iff);
 964 
 965   assert(is_heap_stable_test(heap_stable_iff), "Should match the shape");
 966 }
 967 
 968 void ShenandoahBarrierC2Support::test_null(Node*& ctrl, Node* val, Node*& null_ctrl, PhaseIdealLoop* phase) {
 969   const Type* val_t = phase->igvn().type(val);
 970   if (val_t->meet(TypePtr::NULL_PTR) == val_t) {
 971     IdealLoopTree* loop = phase->get_loop(ctrl);
 972     Node* null_cmp = new CmpPNode(val, phase->igvn().zerocon(T_OBJECT));
 973     phase->register_new_node(null_cmp, ctrl);
 974     Node* null_test = new BoolNode(null_cmp, BoolTest::ne);
 975     phase->register_new_node(null_test, ctrl);
 976     IfNode* null_iff = new IfNode(ctrl, null_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
 977     phase->register_control(null_iff, loop, ctrl);
 978     ctrl = new IfTrueNode(null_iff);
 979     phase->register_control(ctrl, loop, null_iff);
 980     null_ctrl = new IfFalseNode(null_iff);
 981     phase->register_control(null_ctrl, loop, null_iff);
 982   }
 983 }
 984 
 985 Node* ShenandoahBarrierC2Support::clone_null_check(Node*& c, Node* val, Node* unc_ctrl, PhaseIdealLoop* phase) {
 986   IdealLoopTree *loop = phase->get_loop(c);
 987   Node* iff = unc_ctrl->in(0);
 988   assert(iff->is_If(), "broken");
 989   Node* new_iff = iff->clone();
 990   new_iff->set_req(0, c);
 991   phase->register_control(new_iff, loop, c);
 992   Node* iffalse = new IfFalseNode(new_iff->as_If());
 993   phase->register_control(iffalse, loop, new_iff);
 994   Node* iftrue = new IfTrueNode(new_iff->as_If());
 995   phase->register_control(iftrue, loop, new_iff);
 996   c = iftrue;
 997   const Type *t = phase->igvn().type(val);
 998   assert(val->Opcode() == Op_CastPP, "expect cast to non null here");
 999   Node* uncasted_val = val->in(1);
1000   val = new CastPPNode(uncasted_val, t);
1001   val->init_req(0, c);
1002   phase->register_new_node(val, c);
1003   return val;
1004 }
1005 
1006 void ShenandoahBarrierC2Support::fix_null_check(Node* unc, Node* unc_ctrl, Node* new_unc_ctrl,
1007                                                 Unique_Node_List& uses, PhaseIdealLoop* phase) {
1008   IfNode* iff = unc_ctrl->in(0)->as_If();
1009   Node* proj = iff->proj_out(0);
1010   assert(proj != unc_ctrl, "bad projection");
1011   Node* use = proj->unique_ctrl_out();
1012 
1013   assert(use == unc || use->is_Region(), "what else?");
1014 
1015   uses.clear();
1016   if (use == unc) {
1017     phase->set_idom(use, new_unc_ctrl, phase->dom_depth(use));
1018     for (uint i = 1; i < unc->req(); i++) {
1019       Node* n = unc->in(i);
1020       if (phase->has_ctrl(n) && phase->get_ctrl(n) == proj) {
1021         uses.push(n);
1022       }
1023     }
1024   } else {
1025     assert(use->is_Region(), "what else?");
1026     uint idx = 1;
1027     for (; use->in(idx) != proj; idx++);
1028     for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
1029       Node* u = use->fast_out(i);
1030       if (u->is_Phi() && phase->get_ctrl(u->in(idx)) == proj) {
1031         uses.push(u->in(idx));
1032       }
1033     }
1034   }
1035   for(uint next = 0; next < uses.size(); next++ ) {
1036     Node *n = uses.at(next);
1037     assert(phase->get_ctrl(n) == proj, "bad control");
1038     phase->set_ctrl_and_loop(n, new_unc_ctrl);
1039     if (n->in(0) == proj) {
1040       phase->igvn().replace_input_of(n, 0, new_unc_ctrl);
1041     }
1042     for (uint i = 0; i < n->req(); i++) {
1043       Node* m = n->in(i);
1044       if (m != NULL && phase->has_ctrl(m) && phase->get_ctrl(m) == proj) {
1045         uses.push(m);
1046       }
1047     }
1048   }
1049 
1050   phase->igvn().rehash_node_delayed(use);
1051   int nb = use->replace_edge(proj, new_unc_ctrl);
1052   assert(nb == 1, "only use expected");
1053 }
1054 
1055 void ShenandoahBarrierC2Support::in_cset_fast_test(Node*& ctrl, Node*& not_cset_ctrl, Node* val, Node* raw_mem, PhaseIdealLoop* phase) {
1056   IdealLoopTree *loop = phase->get_loop(ctrl);
1057   Node* raw_rbtrue = new CastP2XNode(ctrl, val);
1058   phase->register_new_node(raw_rbtrue, ctrl);
1059   Node* cset_offset = new URShiftXNode(raw_rbtrue, phase->igvn().intcon(ShenandoahHeapRegion::region_size_bytes_shift_jint()));
1060   phase->register_new_node(cset_offset, ctrl);
1061   Node* in_cset_fast_test_base_addr = phase->igvn().makecon(TypeRawPtr::make(ShenandoahHeap::in_cset_fast_test_addr()));
1062   phase->set_ctrl(in_cset_fast_test_base_addr, phase->C->root());
1063   Node* in_cset_fast_test_adr = new AddPNode(phase->C->top(), in_cset_fast_test_base_addr, cset_offset);
1064   phase->register_new_node(in_cset_fast_test_adr, ctrl);
1065   uint in_cset_fast_test_idx = Compile::AliasIdxRaw;
1066   const TypePtr* in_cset_fast_test_adr_type = NULL; // debug-mode-only argument
1067   debug_only(in_cset_fast_test_adr_type = phase->C->get_adr_type(in_cset_fast_test_idx));
1068   Node* in_cset_fast_test_load = new LoadBNode(ctrl, raw_mem, in_cset_fast_test_adr, in_cset_fast_test_adr_type, TypeInt::BYTE, MemNode::unordered);
1069   phase->register_new_node(in_cset_fast_test_load, ctrl);
1070   Node* in_cset_fast_test_cmp = new CmpINode(in_cset_fast_test_load, phase->igvn().zerocon(T_INT));
1071   phase->register_new_node(in_cset_fast_test_cmp, ctrl);
1072   Node* in_cset_fast_test_test = new BoolNode(in_cset_fast_test_cmp, BoolTest::eq);
1073   phase->register_new_node(in_cset_fast_test_test, ctrl);
1074   IfNode* in_cset_fast_test_iff = new IfNode(ctrl, in_cset_fast_test_test, PROB_UNLIKELY(0.999), COUNT_UNKNOWN);
1075   phase->register_control(in_cset_fast_test_iff, loop, ctrl);
1076 
1077   not_cset_ctrl = new IfTrueNode(in_cset_fast_test_iff);
1078   phase->register_control(not_cset_ctrl, loop, in_cset_fast_test_iff);
1079 
1080   ctrl = new IfFalseNode(in_cset_fast_test_iff);
1081   phase->register_control(ctrl, loop, in_cset_fast_test_iff);
1082 }
1083 
1084 void ShenandoahBarrierC2Support::call_lrb_stub(Node*& ctrl, Node*& val, Node*& result_mem, Node* raw_mem, PhaseIdealLoop* phase) {
1085   IdealLoopTree*loop = phase->get_loop(ctrl);
1086   const TypePtr* obj_type = phase->igvn().type(val)->is_oopptr()->cast_to_nonconst();
1087 
1088   // The slow path stub consumes and produces raw memory in addition
1089   // to the existing memory edges
1090   Node* base = find_bottom_mem(ctrl, phase);
1091   MergeMemNode* mm = MergeMemNode::make(base);
1092   mm->set_memory_at(Compile::AliasIdxRaw, raw_mem);
1093   phase->register_new_node(mm, ctrl);
1094 
1095   Node* call = new CallLeafNode(ShenandoahBarrierSetC2::shenandoah_write_barrier_Type(), CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_JRT), "shenandoah_write_barrier", TypeRawPtr::BOTTOM);
1096   call->init_req(TypeFunc::Control, ctrl);
1097   call->init_req(TypeFunc::I_O, phase->C->top());
1098   call->init_req(TypeFunc::Memory, mm);
1099   call->init_req(TypeFunc::FramePtr, phase->C->top());
1100   call->init_req(TypeFunc::ReturnAdr, phase->C->top());
1101   call->init_req(TypeFunc::Parms, val);
1102   phase->register_control(call, loop, ctrl);
1103   ctrl = new ProjNode(call, TypeFunc::Control);
1104   phase->register_control(ctrl, loop, call);
1105   result_mem = new ProjNode(call, TypeFunc::Memory);
1106   phase->register_new_node(result_mem, call);
1107   val = new ProjNode(call, TypeFunc::Parms);
1108   phase->register_new_node(val, call);
1109   val = new CheckCastPPNode(ctrl, val, obj_type);
1110   phase->register_new_node(val, ctrl);
1111 }
1112 
1113 void ShenandoahBarrierC2Support::fix_ctrl(Node* barrier, Node* region, const MemoryGraphFixer& fixer, Unique_Node_List& uses, Unique_Node_List& uses_to_ignore, uint last, PhaseIdealLoop* phase) {
1114   Node* ctrl = phase->get_ctrl(barrier);
1115   Node* init_raw_mem = fixer.find_mem(ctrl, barrier);
1116 
1117   // Update the control of all nodes that should be after the
1118   // barrier control flow
1119   uses.clear();
1120   // Every node that is control dependent on the barrier's input
1121   // control will be after the expanded barrier. The raw memory (if
1122   // its memory is control dependent on the barrier's input control)
1123   // must stay above the barrier.
1124   uses_to_ignore.clear();
1125   if (phase->has_ctrl(init_raw_mem) && phase->get_ctrl(init_raw_mem) == ctrl && !init_raw_mem->is_Phi()) {
1126     uses_to_ignore.push(init_raw_mem);
1127   }
1128   for (uint next = 0; next < uses_to_ignore.size(); next++) {
1129     Node *n = uses_to_ignore.at(next);
1130     for (uint i = 0; i < n->req(); i++) {
1131       Node* in = n->in(i);
1132       if (in != NULL && phase->has_ctrl(in) && phase->get_ctrl(in) == ctrl) {
1133         uses_to_ignore.push(in);
1134       }
1135     }
1136   }
1137   for (DUIterator_Fast imax, i = ctrl->fast_outs(imax); i < imax; i++) {
1138     Node* u = ctrl->fast_out(i);
1139     if (u->_idx < last &&
1140         u != barrier &&
1141         !uses_to_ignore.member(u) &&
1142         (u->in(0) != ctrl || (!u->is_Region() && !u->is_Phi())) &&
1143         (ctrl->Opcode() != Op_CatchProj || u->Opcode() != Op_CreateEx)) {
1144       Node* old_c = phase->ctrl_or_self(u);
1145       Node* c = old_c;
1146       if (c != ctrl ||
1147           is_dominator_same_ctrl(old_c, barrier, u, phase) ||
1148           ShenandoahBarrierSetC2::is_shenandoah_state_load(u)) {
1149         phase->igvn().rehash_node_delayed(u);
1150         int nb = u->replace_edge(ctrl, region);
1151         if (u->is_CFG()) {
1152           if (phase->idom(u) == ctrl) {
1153             phase->set_idom(u, region, phase->dom_depth(region));
1154           }
1155         } else if (phase->get_ctrl(u) == ctrl) {
1156           assert(u != init_raw_mem, "should leave input raw mem above the barrier");
1157           uses.push(u);
1158         }
1159         assert(nb == 1, "more than 1 ctrl input?");
1160         --i, imax -= nb;
1161       }
1162     }
1163   }
1164 }
1165 
1166 static Node* create_phis_on_call_return(Node* ctrl, Node* c, Node* n, Node* n_clone, const CallProjections* projs, PhaseIdealLoop* phase) {
1167   Node* region = NULL;
1168   while (c != ctrl) {
1169     if (c->is_Region()) {
1170       region = c;
1171     }
1172     c = phase->idom(c);
1173   }
1174   assert(region != NULL, "");
1175   Node* phi = new PhiNode(region, n->bottom_type());
1176   for (uint j = 1; j < region->req(); j++) {
1177     Node* in = region->in(j);
1178     if (phase->is_dominator(projs->fallthrough_catchproj, in)) {
1179       phi->init_req(j, n);
1180     } else if (phase->is_dominator(projs->catchall_catchproj, in)) {
1181       phi->init_req(j, n_clone);
1182     } else {
1183       phi->init_req(j, create_phis_on_call_return(ctrl, in, n, n_clone, projs, phase));
1184     }
1185   }
1186   phase->register_new_node(phi, region);
1187   return phi;
1188 }
1189 
1190 void ShenandoahBarrierC2Support::pin_and_expand(PhaseIdealLoop* phase) {
1191   ShenandoahBarrierSetC2State* state = ShenandoahBarrierSetC2::bsc2()->state();
1192 
1193   // Collect raw memory state at CFG points in the entire graph and
1194   // record it in memory_nodes. Optimize the raw memory graph in the
1195   // process. Optimizing the memory graph also makes the memory graph
1196   // simpler.
1197   GrowableArray<MemoryGraphFixer*> memory_graph_fixers;
1198 
1199   Unique_Node_List uses;
1200   for (int i = 0; i < state->enqueue_barriers_count(); i++) {
1201     Node* barrier = state->enqueue_barrier(i);
1202     Node* ctrl = phase->get_ctrl(barrier);
1203     IdealLoopTree* loop = phase->get_loop(ctrl);
1204     if (loop->_head->is_OuterStripMinedLoop()) {
1205       // Expanding a barrier here will break loop strip mining
1206       // verification. Transform the loop so the loop nest doesn't
1207       // appear as strip mined.
1208       OuterStripMinedLoopNode* outer = loop->_head->as_OuterStripMinedLoop();
1209       hide_strip_mined_loop(outer, outer->unique_ctrl_out()->as_CountedLoop(), phase);
1210     }
1211   }
1212 
1213   Node_Stack stack(0);
1214   Node_List clones;
1215   for (int i = state->load_reference_barriers_count() - 1; i >= 0; i--) {
1216     ShenandoahLoadReferenceBarrierNode* lrb = state->load_reference_barrier(i);
1217     if (lrb->get_barrier_strength() == ShenandoahLoadReferenceBarrierNode::NONE) {
1218       continue;
1219     }
1220 
1221     Node* ctrl = phase->get_ctrl(lrb);
1222     Node* val = lrb->in(ShenandoahLoadReferenceBarrierNode::ValueIn);
1223 
1224     CallStaticJavaNode* unc = NULL;
1225     Node* unc_ctrl = NULL;
1226     Node* uncasted_val = val;
1227 
1228     for (DUIterator_Fast imax, i = lrb->fast_outs(imax); i < imax; i++) {
1229       Node* u = lrb->fast_out(i);
1230       if (u->Opcode() == Op_CastPP &&
1231           u->in(0) != NULL &&
1232           phase->is_dominator(u->in(0), ctrl)) {
1233         const Type* u_t = phase->igvn().type(u);
1234 
1235         if (u_t->meet(TypePtr::NULL_PTR) != u_t &&
1236             u->in(0)->Opcode() == Op_IfTrue &&
1237             u->in(0)->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none) &&
1238             u->in(0)->in(0)->is_If() &&
1239             u->in(0)->in(0)->in(1)->Opcode() == Op_Bool &&
1240             u->in(0)->in(0)->in(1)->as_Bool()->_test._test == BoolTest::ne &&
1241             u->in(0)->in(0)->in(1)->in(1)->Opcode() == Op_CmpP &&
1242             u->in(0)->in(0)->in(1)->in(1)->in(1) == val &&
1243             u->in(0)->in(0)->in(1)->in(1)->in(2)->bottom_type() == TypePtr::NULL_PTR) {
1244           IdealLoopTree* loop = phase->get_loop(ctrl);
1245           IdealLoopTree* unc_loop = phase->get_loop(u->in(0));
1246 
1247           if (!unc_loop->is_member(loop)) {
1248             continue;
1249           }
1250 
1251           Node* branch = no_branches(ctrl, u->in(0), false, phase);
1252           assert(branch == NULL || branch == NodeSentinel, "was not looking for a branch");
1253           if (branch == NodeSentinel) {
1254             continue;
1255           }
1256 
1257           phase->igvn().replace_input_of(u, 1, val);
1258           phase->igvn().replace_input_of(lrb, ShenandoahLoadReferenceBarrierNode::ValueIn, u);
1259           phase->set_ctrl(u, u->in(0));
1260           phase->set_ctrl(lrb, u->in(0));
1261           unc = u->in(0)->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none);
1262           unc_ctrl = u->in(0);
1263           val = u;
1264 
1265           for (DUIterator_Fast jmax, j = val->fast_outs(jmax); j < jmax; j++) {
1266             Node* u = val->fast_out(j);
1267             if (u == lrb) continue;
1268             phase->igvn().rehash_node_delayed(u);
1269             int nb = u->replace_edge(val, lrb);
1270             --j; jmax -= nb;
1271           }
1272 
1273           RegionNode* r = new RegionNode(3);
1274           IfNode* iff = unc_ctrl->in(0)->as_If();
1275 
1276           Node* ctrl_use = unc_ctrl->unique_ctrl_out();
1277           Node* unc_ctrl_clone = unc_ctrl->clone();
1278           phase->register_control(unc_ctrl_clone, loop, iff);
1279           Node* c = unc_ctrl_clone;
1280           Node* new_cast = clone_null_check(c, val, unc_ctrl_clone, phase);
1281           r->init_req(1, new_cast->in(0)->in(0)->as_If()->proj_out(0));
1282 
1283           phase->igvn().replace_input_of(unc_ctrl, 0, c->in(0));
1284           phase->set_idom(unc_ctrl, c->in(0), phase->dom_depth(unc_ctrl));
1285           phase->lazy_replace(c, unc_ctrl);
1286           c = NULL;;
1287           phase->igvn().replace_input_of(val, 0, unc_ctrl_clone);
1288           phase->set_ctrl(val, unc_ctrl_clone);
1289 
1290           IfNode* new_iff = new_cast->in(0)->in(0)->as_If();
1291           fix_null_check(unc, unc_ctrl_clone, r, uses, phase);
1292           Node* iff_proj = iff->proj_out(0);
1293           r->init_req(2, iff_proj);
1294           phase->register_control(r, phase->ltree_root(), iff);
1295 
1296           Node* new_bol = new_iff->in(1)->clone();
1297           Node* new_cmp = new_bol->in(1)->clone();
1298           assert(new_cmp->Opcode() == Op_CmpP, "broken");
1299           assert(new_cmp->in(1) == val->in(1), "broken");
1300           new_bol->set_req(1, new_cmp);
1301           new_cmp->set_req(1, lrb);
1302           phase->register_new_node(new_bol, new_iff->in(0));
1303           phase->register_new_node(new_cmp, new_iff->in(0));
1304           phase->igvn().replace_input_of(new_iff, 1, new_bol);
1305           phase->igvn().replace_input_of(new_cast, 1, lrb);
1306 
1307           for (DUIterator_Fast imax, i = lrb->fast_outs(imax); i < imax; i++) {
1308             Node* u = lrb->fast_out(i);
1309             if (u == new_cast || u == new_cmp) {
1310               continue;
1311             }
1312             phase->igvn().rehash_node_delayed(u);
1313             int nb = u->replace_edge(lrb, new_cast);
1314             assert(nb > 0, "no update?");
1315             --i; imax -= nb;
1316           }
1317 
1318           for (DUIterator_Fast imax, i = val->fast_outs(imax); i < imax; i++) {
1319             Node* u = val->fast_out(i);
1320             if (u == lrb) {
1321               continue;
1322             }
1323             phase->igvn().rehash_node_delayed(u);
1324             int nb = u->replace_edge(val, new_cast);
1325             assert(nb > 0, "no update?");
1326             --i; imax -= nb;
1327           }
1328 
1329           ctrl = unc_ctrl_clone;
1330           phase->set_ctrl_and_loop(lrb, ctrl);
1331           break;
1332         }
1333       }
1334     }
1335     if ((ctrl->is_Proj() && ctrl->in(0)->is_CallJava()) || ctrl->is_CallJava()) {
1336       CallNode* call = ctrl->is_Proj() ? ctrl->in(0)->as_CallJava() : ctrl->as_CallJava();
1337       CallProjections* projs = call->extract_projections(false, false);
1338 
1339       Node* lrb_clone = lrb->clone();
1340       phase->register_new_node(lrb_clone, projs->catchall_catchproj);
1341       phase->set_ctrl(lrb, projs->fallthrough_catchproj);
1342 
1343       stack.push(lrb, 0);
1344       clones.push(lrb_clone);
1345 
1346       do {
1347         assert(stack.size() == clones.size(), "");
1348         Node* n = stack.node();
1349 #ifdef ASSERT
1350         if (n->is_Load()) {
1351           Node* mem = n->in(MemNode::Memory);
1352           for (DUIterator_Fast jmax, j = mem->fast_outs(jmax); j < jmax; j++) {
1353             Node* u = mem->fast_out(j);
1354             assert(!u->is_Store() || !u->is_LoadStore() || phase->get_ctrl(u) != ctrl, "anti dependent store?");
1355           }
1356         }
1357 #endif
1358         uint idx = stack.index();
1359         Node* n_clone = clones.at(clones.size()-1);
1360         if (idx < n->outcnt()) {
1361           Node* u = n->raw_out(idx);
1362           Node* c = phase->ctrl_or_self(u);
1363           if (phase->is_dominator(call, c) && phase->is_dominator(c, projs.fallthrough_proj)) {
1364             stack.set_index(idx+1);
1365             assert(!u->is_CFG(), "");
1366             stack.push(u, 0);
1367             Node* u_clone = u->clone();
1368             int nb = u_clone->replace_edge(n, n_clone);
1369             assert(nb > 0, "should have replaced some uses");
1370             phase->register_new_node(u_clone, projs->catchall_catchproj);
1371             clones.push(u_clone);
1372             phase->set_ctrl(u, projs->fallthrough_catchproj);
1373           } else {
1374             bool replaced = false;
1375             if (u->is_Phi()) {
1376               for (uint k = 1; k < u->req(); k++) {
1377                 if (u->in(k) == n) {
1378                   if (phase->is_dominator(projs->catchall_catchproj, u->in(0)->in(k))) {
1379                     phase->igvn().replace_input_of(u, k, n_clone);
1380                     replaced = true;
1381                   } else if (!phase->is_dominator(projs->fallthrough_catchproj, u->in(0)->in(k))) {
1382                     phase->igvn().replace_input_of(u, k, create_phis_on_call_return(ctrl, u->in(0)->in(k), n, n_clone, projs, phase));
1383                     replaced = true;
1384                   }
1385                 }
1386               }
1387             } else {
1388               if (phase->is_dominator(projs->catchall_catchproj, c)) {
1389                 phase->igvn().rehash_node_delayed(u);
1390                 int nb = u->replace_edge(n, n_clone);
1391                 assert(nb > 0, "should have replaced some uses");
1392                 replaced = true;
1393               } else if (!phase->is_dominator(projs->fallthrough_catchproj, c)) {
1394                 phase->igvn().rehash_node_delayed(u);
1395                 int nb = u->replace_edge(n, create_phis_on_call_return(ctrl, c, n, n_clone, projs, phase));
1396                 assert(nb > 0, "should have replaced some uses");
1397                 replaced = true;
1398               }
1399             }
1400             if (!replaced) {
1401               stack.set_index(idx+1);
1402             }
1403           }
1404         } else {
1405           stack.pop();
1406           clones.pop();
1407         }
1408       } while (stack.size() > 0);
1409       assert(stack.size() == 0 && clones.size() == 0, "");
1410     }
1411   }
1412 
1413   // Expand load-reference-barriers
1414   MemoryGraphFixer fixer(Compile::AliasIdxRaw, true, phase);
1415   Unique_Node_List uses_to_ignore;
1416   for (int i = state->load_reference_barriers_count() - 1; i >= 0; i--) {
1417     ShenandoahLoadReferenceBarrierNode* lrb = state->load_reference_barrier(i);
1418     if (lrb->get_barrier_strength() == ShenandoahLoadReferenceBarrierNode::NONE) {
1419       phase->igvn().replace_node(lrb, lrb->in(ShenandoahLoadReferenceBarrierNode::ValueIn));
1420       continue;
1421     }
1422     uint last = phase->C->unique();
1423     Node* ctrl = phase->get_ctrl(lrb);
1424     Node* val = lrb->in(ShenandoahLoadReferenceBarrierNode::ValueIn);
1425 
1426 
1427     Node* orig_ctrl = ctrl;
1428 
1429     Node* raw_mem = fixer.find_mem(ctrl, lrb);
1430     Node* init_raw_mem = raw_mem;
1431     Node* raw_mem_for_ctrl = fixer.find_mem(ctrl, NULL);
1432     // int alias = phase->C->get_alias_index(lrb->adr_type());
1433 
1434     IdealLoopTree *loop = phase->get_loop(ctrl);
1435     CallStaticJavaNode* unc = lrb->pin_and_expand_null_check(phase->igvn());
1436     Node* unc_ctrl = NULL;
1437     if (unc != NULL) {
1438       if (val->in(ShenandoahLoadReferenceBarrierNode::Control) != ctrl) {
1439         unc = NULL;
1440       } else {
1441         unc_ctrl = val->in(ShenandoahLoadReferenceBarrierNode::Control);
1442       }
1443     }
1444 
1445     Node* uncasted_val = val;
1446     if (unc != NULL) {
1447       uncasted_val = val->in(1);
1448     }
1449 
1450     Node* heap_stable_ctrl = NULL;
1451     Node* null_ctrl = NULL;
1452 
1453     assert(val->bottom_type()->make_oopptr(), "need oop");
1454     assert(val->bottom_type()->make_oopptr()->const_oop() == NULL, "expect non-constant");
1455 
1456     enum { _heap_stable = 1, _not_cset, _not_equal, _evac_path, _null_path, PATH_LIMIT };
1457     Node* region = new RegionNode(PATH_LIMIT);
1458     Node* val_phi = new PhiNode(region, uncasted_val->bottom_type()->is_oopptr());
1459     Node* raw_mem_phi = PhiNode::make(region, raw_mem, Type::MEMORY, TypeRawPtr::BOTTOM);
1460 
1461     // Stable path.
1462     test_heap_stable(ctrl, raw_mem, heap_stable_ctrl, phase);
1463     IfNode* heap_stable_iff = heap_stable_ctrl->in(0)->as_If();
1464 
1465     // Heap stable case
1466     region->init_req(_heap_stable, heap_stable_ctrl);
1467     val_phi->init_req(_heap_stable, uncasted_val);
1468     raw_mem_phi->init_req(_heap_stable, raw_mem);
1469 
1470     Node* reg2_ctrl = NULL;
1471     // Null case
1472     test_null(ctrl, val, null_ctrl, phase);
1473     if (null_ctrl != NULL) {
1474       reg2_ctrl = null_ctrl->in(0);
1475       region->init_req(_null_path, null_ctrl);
1476       val_phi->init_req(_null_path, uncasted_val);
1477       raw_mem_phi->init_req(_null_path, raw_mem);
1478     } else {
1479       region->del_req(_null_path);
1480       val_phi->del_req(_null_path);
1481       raw_mem_phi->del_req(_null_path);
1482     }
1483 
1484     // Test for in-cset.
1485     // Wires !in_cset(obj) to slot 2 of region and phis
1486     Node* not_cset_ctrl = NULL;
1487     in_cset_fast_test(ctrl, not_cset_ctrl, uncasted_val, raw_mem, phase);
1488     if (not_cset_ctrl != NULL) {
1489       if (reg2_ctrl == NULL) reg2_ctrl = not_cset_ctrl->in(0);
1490       region->init_req(_not_cset, not_cset_ctrl);
1491       val_phi->init_req(_not_cset, uncasted_val);
1492       raw_mem_phi->init_req(_not_cset, raw_mem);
1493     }
1494 
1495     // Resolve object when orig-value is in cset.
1496     // Make the unconditional resolve for fwdptr.
1497     Node* new_val = uncasted_val;
1498     if (unc_ctrl != NULL) {
1499       // Clone the null check in this branch to allow implicit null check
1500       new_val = clone_null_check(ctrl, val, unc_ctrl, phase);
1501       fix_null_check(unc, unc_ctrl, ctrl->in(0)->as_If()->proj_out(0), uses, phase);
1502 
1503       IfNode* iff = unc_ctrl->in(0)->as_If();
1504       phase->igvn().replace_input_of(iff, 1, phase->igvn().intcon(1));
1505     }
1506     Node* addr = new AddPNode(new_val, uncasted_val, phase->igvn().MakeConX(ShenandoahForwarding::byte_offset()));
1507     phase->register_new_node(addr, ctrl);
1508     assert(val->bottom_type()->isa_oopptr(), "what else?");
1509     const TypePtr* obj_type =  val->bottom_type()->is_oopptr();
1510     const TypePtr* adr_type = TypeRawPtr::BOTTOM;
1511     Node* fwd = new LoadPNode(ctrl, raw_mem, addr, adr_type, obj_type, MemNode::unordered);
1512     phase->register_new_node(fwd, ctrl);
1513 
1514     // Only branch to LRB stub if object is not forwarded; otherwise reply with fwd ptr
1515     Node* cmp = new CmpPNode(fwd, new_val);
1516     phase->register_new_node(cmp, ctrl);
1517     Node* bol = new BoolNode(cmp, BoolTest::eq);
1518     phase->register_new_node(bol, ctrl);
1519 
1520     IfNode* iff = new IfNode(ctrl, bol, PROB_UNLIKELY(0.999), COUNT_UNKNOWN);
1521     if (reg2_ctrl == NULL) reg2_ctrl = iff;
1522     phase->register_control(iff, loop, ctrl);
1523     Node* if_not_eq = new IfFalseNode(iff);
1524     phase->register_control(if_not_eq, loop, iff);
1525     Node* if_eq = new IfTrueNode(iff);
1526     phase->register_control(if_eq, loop, iff);
1527 
1528     // Wire up not-equal-path in slots 3.
1529     region->init_req(_not_equal, if_not_eq);
1530     val_phi->init_req(_not_equal, fwd);
1531     raw_mem_phi->init_req(_not_equal, raw_mem);
1532 
1533     // Call wb-stub and wire up that path in slots 4
1534     Node* result_mem = NULL;
1535     ctrl = if_eq;
1536     call_lrb_stub(ctrl, fwd, result_mem, raw_mem, phase);
1537     region->init_req(_evac_path, ctrl);
1538     val_phi->init_req(_evac_path, fwd);
1539     raw_mem_phi->init_req(_evac_path, result_mem);
1540 
1541     phase->register_control(region, loop, heap_stable_iff);
1542     Node* out_val = val_phi;
1543     phase->register_new_node(val_phi, region);
1544     phase->register_new_node(raw_mem_phi, region);
1545 
1546     fix_ctrl(lrb, region, fixer, uses, uses_to_ignore, last, phase);
1547 
1548     ctrl = orig_ctrl;
1549 
1550     if (unc != NULL) {
1551       for (DUIterator_Fast imax, i = val->fast_outs(imax); i < imax; i++) {
1552         Node* u = val->fast_out(i);
1553         Node* c = phase->ctrl_or_self(u);
1554         if (u != lrb && (c != ctrl || is_dominator_same_ctrl(c, lrb, u, phase))) {
1555           phase->igvn().rehash_node_delayed(u);
1556           int nb = u->replace_edge(val, out_val);
1557           --i, imax -= nb;
1558         }
1559       }
1560       if (val->outcnt() == 0) {
1561         phase->igvn()._worklist.push(val);
1562       }
1563     }
1564     phase->igvn().replace_node(lrb, out_val);
1565 
1566     follow_barrier_uses(out_val, ctrl, uses, phase);
1567 
1568     for(uint next = 0; next < uses.size(); next++ ) {
1569       Node *n = uses.at(next);
1570       assert(phase->get_ctrl(n) == ctrl, "bad control");
1571       assert(n != init_raw_mem, "should leave input raw mem above the barrier");
1572       phase->set_ctrl(n, region);
1573       follow_barrier_uses(n, ctrl, uses, phase);
1574     }
1575 
1576     // The slow path call produces memory: hook the raw memory phi
1577     // from the expanded load reference barrier with the rest of the graph
1578     // which may require adding memory phis at every post dominated
1579     // region and at enclosing loop heads. Use the memory state
1580     // collected in memory_nodes to fix the memory graph. Update that
1581     // memory state as we go.
1582     fixer.fix_mem(ctrl, region, init_raw_mem, raw_mem_for_ctrl, raw_mem_phi, uses);
1583   }
1584   // Done expanding load-reference-barriers.
1585   assert(ShenandoahBarrierSetC2::bsc2()->state()->load_reference_barriers_count() == 0, "all load reference barrier nodes should have been replaced");
1586 
1587   for (int i = state->enqueue_barriers_count() - 1; i >= 0; i--) {
1588     Node* barrier = state->enqueue_barrier(i);
1589     Node* pre_val = barrier->in(1);
1590 
1591     if (phase->igvn().type(pre_val)->higher_equal(TypePtr::NULL_PTR)) {
1592       ShouldNotReachHere();
1593       continue;
1594     }
1595 
1596     Node* ctrl = phase->get_ctrl(barrier);
1597 
1598     if (ctrl->is_Proj() && ctrl->in(0)->is_CallJava()) {
1599       assert(is_dominator(phase->get_ctrl(pre_val), ctrl->in(0)->in(0), pre_val, ctrl->in(0), phase), "can't move");
1600       ctrl = ctrl->in(0)->in(0);
1601       phase->set_ctrl(barrier, ctrl);
1602     } else if (ctrl->is_CallRuntime()) {
1603       assert(is_dominator(phase->get_ctrl(pre_val), ctrl->in(0), pre_val, ctrl, phase), "can't move");
1604       ctrl = ctrl->in(0);
1605       phase->set_ctrl(barrier, ctrl);
1606     }
1607 
1608     Node* init_ctrl = ctrl;
1609     IdealLoopTree* loop = phase->get_loop(ctrl);
1610     Node* raw_mem = fixer.find_mem(ctrl, barrier);
1611     Node* init_raw_mem = raw_mem;
1612     Node* raw_mem_for_ctrl = fixer.find_mem(ctrl, NULL);
1613     Node* heap_stable_ctrl = NULL;
1614     Node* null_ctrl = NULL;
1615     uint last = phase->C->unique();
1616 
1617     enum { _heap_stable = 1, _heap_unstable, PATH_LIMIT };
1618     Node* region = new RegionNode(PATH_LIMIT);
1619     Node* phi = PhiNode::make(region, raw_mem, Type::MEMORY, TypeRawPtr::BOTTOM);
1620 
1621     enum { _fast_path = 1, _slow_path, _null_path, PATH_LIMIT2 };
1622     Node* region2 = new RegionNode(PATH_LIMIT2);
1623     Node* phi2 = PhiNode::make(region2, raw_mem, Type::MEMORY, TypeRawPtr::BOTTOM);
1624 
1625     // Stable path.
1626     test_heap_stable(ctrl, raw_mem, heap_stable_ctrl, phase);
1627     region->init_req(_heap_stable, heap_stable_ctrl);
1628     phi->init_req(_heap_stable, raw_mem);
1629 
1630     // Null path
1631     Node* reg2_ctrl = NULL;
1632     test_null(ctrl, pre_val, null_ctrl, phase);
1633     if (null_ctrl != NULL) {
1634       reg2_ctrl = null_ctrl->in(0);
1635       region2->init_req(_null_path, null_ctrl);
1636       phi2->init_req(_null_path, raw_mem);
1637     } else {
1638       region2->del_req(_null_path);
1639       phi2->del_req(_null_path);
1640     }
1641 
1642     const int index_offset = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset());
1643     const int buffer_offset = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset());
1644     Node* thread = new ThreadLocalNode();
1645     phase->register_new_node(thread, ctrl);
1646     Node* buffer_adr = new AddPNode(phase->C->top(), thread, phase->igvn().MakeConX(buffer_offset));
1647     phase->register_new_node(buffer_adr, ctrl);
1648     Node* index_adr = new AddPNode(phase->C->top(), thread, phase->igvn().MakeConX(index_offset));
1649     phase->register_new_node(index_adr, ctrl);
1650 
1651     BasicType index_bt = TypeX_X->basic_type();
1652     assert(sizeof(size_t) == type2aelembytes(index_bt), "Loading G1 SATBMarkQueue::_index with wrong size.");
1653     const TypePtr* adr_type = TypeRawPtr::BOTTOM;
1654     Node* index = new LoadXNode(ctrl, raw_mem, index_adr, adr_type, TypeX_X, MemNode::unordered);
1655     phase->register_new_node(index, ctrl);
1656     Node* index_cmp = new CmpXNode(index, phase->igvn().MakeConX(0));
1657     phase->register_new_node(index_cmp, ctrl);
1658     Node* index_test = new BoolNode(index_cmp, BoolTest::ne);
1659     phase->register_new_node(index_test, ctrl);
1660     IfNode* queue_full_iff = new IfNode(ctrl, index_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
1661     if (reg2_ctrl == NULL) reg2_ctrl = queue_full_iff;
1662     phase->register_control(queue_full_iff, loop, ctrl);
1663     Node* not_full = new IfTrueNode(queue_full_iff);
1664     phase->register_control(not_full, loop, queue_full_iff);
1665     Node* full = new IfFalseNode(queue_full_iff);
1666     phase->register_control(full, loop, queue_full_iff);
1667 
1668     ctrl = not_full;
1669 
1670     Node* next_index = new SubXNode(index, phase->igvn().MakeConX(sizeof(intptr_t)));
1671     phase->register_new_node(next_index, ctrl);
1672 
1673     Node* buffer  = new LoadPNode(ctrl, raw_mem, buffer_adr, adr_type, TypeRawPtr::NOTNULL, MemNode::unordered);
1674     phase->register_new_node(buffer, ctrl);
1675     Node *log_addr = new AddPNode(phase->C->top(), buffer, next_index);
1676     phase->register_new_node(log_addr, ctrl);
1677     Node* log_store = new StorePNode(ctrl, raw_mem, log_addr, adr_type, pre_val, MemNode::unordered);
1678     phase->register_new_node(log_store, ctrl);
1679     // update the index
1680     Node* index_update = new StoreXNode(ctrl, log_store, index_adr, adr_type, next_index, MemNode::unordered);
1681     phase->register_new_node(index_update, ctrl);
1682 
1683     // Fast-path case
1684     region2->init_req(_fast_path, ctrl);
1685     phi2->init_req(_fast_path, index_update);
1686 
1687     ctrl = full;
1688 
1689     Node* base = find_bottom_mem(ctrl, phase);
1690 
1691     MergeMemNode* mm = MergeMemNode::make(base);
1692     mm->set_memory_at(Compile::AliasIdxRaw, raw_mem);
1693     phase->register_new_node(mm, ctrl);
1694 
1695     Node* call = new CallLeafNode(ShenandoahBarrierSetC2::write_ref_field_pre_entry_Type(), CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_ref_field_pre_entry), "shenandoah_wb_pre", TypeRawPtr::BOTTOM);
1696     call->init_req(TypeFunc::Control, ctrl);
1697     call->init_req(TypeFunc::I_O, phase->C->top());
1698     call->init_req(TypeFunc::Memory, mm);
1699     call->init_req(TypeFunc::FramePtr, phase->C->top());
1700     call->init_req(TypeFunc::ReturnAdr, phase->C->top());
1701     call->init_req(TypeFunc::Parms, pre_val);
1702     call->init_req(TypeFunc::Parms+1, thread);
1703     phase->register_control(call, loop, ctrl);
1704 
1705     Node* ctrl_proj = new ProjNode(call, TypeFunc::Control);
1706     phase->register_control(ctrl_proj, loop, call);
1707     Node* mem_proj = new ProjNode(call, TypeFunc::Memory);
1708     phase->register_new_node(mem_proj, call);
1709 
1710     // Slow-path case
1711     region2->init_req(_slow_path, ctrl_proj);
1712     phi2->init_req(_slow_path, mem_proj);
1713 
1714     phase->register_control(region2, loop, reg2_ctrl);
1715     phase->register_new_node(phi2, region2);
1716 
1717     region->init_req(_heap_unstable, region2);
1718     phi->init_req(_heap_unstable, phi2);
1719 
1720     phase->register_control(region, loop, heap_stable_ctrl->in(0));
1721     phase->register_new_node(phi, region);
1722 
1723     fix_ctrl(barrier, region, fixer, uses, uses_to_ignore, last, phase);
1724     for(uint next = 0; next < uses.size(); next++ ) {
1725       Node *n = uses.at(next);
1726       assert(phase->get_ctrl(n) == init_ctrl, "bad control");
1727       assert(n != init_raw_mem, "should leave input raw mem above the barrier");
1728       phase->set_ctrl(n, region);
1729       follow_barrier_uses(n, init_ctrl, uses, phase);
1730     }
1731     fixer.fix_mem(init_ctrl, region, init_raw_mem, raw_mem_for_ctrl, phi, uses);
1732 
1733     phase->igvn().replace_node(barrier, pre_val);
1734   }
1735   assert(state->enqueue_barriers_count() == 0, "all enqueue barrier nodes should have been replaced");
1736 
1737 }
1738 
1739 void ShenandoahBarrierC2Support::move_heap_stable_test_out_of_loop(IfNode* iff, PhaseIdealLoop* phase) {
1740   IdealLoopTree *loop = phase->get_loop(iff);
1741   Node* loop_head = loop->_head;
1742   Node* entry_c = loop_head->in(LoopNode::EntryControl);
1743 
1744   Node* bol = iff->in(1);
1745   Node* cmp = bol->in(1);
1746   Node* andi = cmp->in(1);
1747   Node* load = andi->in(1);
1748 
1749   assert(is_gc_state_load(load), "broken");
1750   if (!phase->is_dominator(load->in(0), entry_c)) {
1751     Node* mem_ctrl = NULL;
1752     Node* mem = dom_mem(load->in(MemNode::Memory), loop_head, Compile::AliasIdxRaw, mem_ctrl, phase);
1753     load = load->clone();
1754     load->set_req(MemNode::Memory, mem);
1755     load->set_req(0, entry_c);
1756     phase->register_new_node(load, entry_c);
1757     andi = andi->clone();
1758     andi->set_req(1, load);
1759     phase->register_new_node(andi, entry_c);
1760     cmp = cmp->clone();
1761     cmp->set_req(1, andi);
1762     phase->register_new_node(cmp, entry_c);
1763     bol = bol->clone();
1764     bol->set_req(1, cmp);
1765     phase->register_new_node(bol, entry_c);
1766 
1767     Node* old_bol =iff->in(1);
1768     phase->igvn().replace_input_of(iff, 1, bol);
1769   }
1770 }
1771 
1772 bool ShenandoahBarrierC2Support::identical_backtoback_ifs(Node* n, PhaseIdealLoop* phase) {
1773   if (!n->is_If() || n->is_CountedLoopEnd()) {
1774     return false;
1775   }
1776   Node* region = n->in(0);
1777 
1778   if (!region->is_Region()) {
1779     return false;
1780   }
1781   Node* dom = phase->idom(region);
1782   if (!dom->is_If()) {
1783     return false;
1784   }
1785 
1786   if (!is_heap_stable_test(n) || !is_heap_stable_test(dom)) {
1787     return false;
1788   }
1789 
1790   IfNode* dom_if = dom->as_If();
1791   Node* proj_true = dom_if->proj_out(1);
1792   Node* proj_false = dom_if->proj_out(0);
1793 
1794   for (uint i = 1; i < region->req(); i++) {
1795     if (phase->is_dominator(proj_true, region->in(i))) {
1796       continue;
1797     }
1798     if (phase->is_dominator(proj_false, region->in(i))) {
1799       continue;
1800     }
1801     return false;
1802   }
1803 
1804   return true;
1805 }
1806 
1807 void ShenandoahBarrierC2Support::merge_back_to_back_tests(Node* n, PhaseIdealLoop* phase) {
1808   assert(is_heap_stable_test(n), "no other tests");
1809   if (identical_backtoback_ifs(n, phase)) {
1810     Node* n_ctrl = n->in(0);
1811     if (phase->can_split_if(n_ctrl)) {
1812       IfNode* dom_if = phase->idom(n_ctrl)->as_If();
1813       if (is_heap_stable_test(n)) {
1814         Node* gc_state_load = n->in(1)->in(1)->in(1)->in(1);
1815         assert(is_gc_state_load(gc_state_load), "broken");
1816         Node* dom_gc_state_load = dom_if->in(1)->in(1)->in(1)->in(1);
1817         assert(is_gc_state_load(dom_gc_state_load), "broken");
1818         if (gc_state_load != dom_gc_state_load) {
1819           phase->igvn().replace_node(gc_state_load, dom_gc_state_load);
1820         }
1821       }
1822       PhiNode* bolphi = PhiNode::make_blank(n_ctrl, n->in(1));
1823       Node* proj_true = dom_if->proj_out(1);
1824       Node* proj_false = dom_if->proj_out(0);
1825       Node* con_true = phase->igvn().makecon(TypeInt::ONE);
1826       Node* con_false = phase->igvn().makecon(TypeInt::ZERO);
1827 
1828       for (uint i = 1; i < n_ctrl->req(); i++) {
1829         if (phase->is_dominator(proj_true, n_ctrl->in(i))) {
1830           bolphi->init_req(i, con_true);
1831         } else {
1832           assert(phase->is_dominator(proj_false, n_ctrl->in(i)), "bad if");
1833           bolphi->init_req(i, con_false);
1834         }
1835       }
1836       phase->register_new_node(bolphi, n_ctrl);
1837       phase->igvn().replace_input_of(n, 1, bolphi);
1838       phase->do_split_if(n);
1839     }
1840   }
1841 }
1842 
1843 IfNode* ShenandoahBarrierC2Support::find_unswitching_candidate(const IdealLoopTree* loop, PhaseIdealLoop* phase) {
1844   // Find first invariant test that doesn't exit the loop
1845   LoopNode *head = loop->_head->as_Loop();
1846   IfNode* unswitch_iff = NULL;
1847   Node* n = head->in(LoopNode::LoopBackControl);
1848   int loop_has_sfpts = -1;
1849   while (n != head) {
1850     Node* n_dom = phase->idom(n);
1851     if (n->is_Region()) {
1852       if (n_dom->is_If()) {
1853         IfNode* iff = n_dom->as_If();
1854         if (iff->in(1)->is_Bool()) {
1855           BoolNode* bol = iff->in(1)->as_Bool();
1856           if (bol->in(1)->is_Cmp()) {
1857             // If condition is invariant and not a loop exit,
1858             // then found reason to unswitch.
1859             if (is_heap_stable_test(iff) &&
1860                 (loop_has_sfpts == -1 || loop_has_sfpts == 0)) {
1861               assert(!loop->is_loop_exit(iff), "both branches should be in the loop");
1862               if (loop_has_sfpts == -1) {
1863                 for(uint i = 0; i < loop->_body.size(); i++) {
1864                   Node *m = loop->_body[i];
1865                   if (m->is_SafePoint() && !m->is_CallLeaf()) {
1866                     loop_has_sfpts = 1;
1867                     break;
1868                   }
1869                 }
1870                 if (loop_has_sfpts == -1) {
1871                   loop_has_sfpts = 0;
1872                 }
1873               }
1874               if (!loop_has_sfpts) {
1875                 unswitch_iff = iff;
1876               }
1877             }
1878           }
1879         }
1880       }
1881     }
1882     n = n_dom;
1883   }
1884   return unswitch_iff;
1885 }
1886 
1887 
1888 void ShenandoahBarrierC2Support::optimize_after_expansion(VectorSet &visited, Node_Stack &stack, Node_List &old_new, PhaseIdealLoop* phase) {
1889   Node_List heap_stable_tests;
1890   Node_List gc_state_loads;
1891   stack.push(phase->C->start(), 0);
1892   do {
1893     Node* n = stack.node();
1894     uint i = stack.index();
1895 
1896     if (i < n->outcnt()) {
1897       Node* u = n->raw_out(i);
1898       stack.set_index(i+1);
1899       if (!visited.test_set(u->_idx)) {
1900         stack.push(u, 0);
1901       }
1902     } else {
1903       stack.pop();
1904       if (ShenandoahCommonGCStateLoads && is_gc_state_load(n)) {
1905         gc_state_loads.push(n);
1906       }
1907       if (n->is_If() && is_heap_stable_test(n)) {
1908         heap_stable_tests.push(n);
1909       }
1910     }
1911   } while (stack.size() > 0);
1912 
1913   bool progress;
1914   do {
1915     progress = false;
1916     for (uint i = 0; i < gc_state_loads.size(); i++) {
1917       Node* n = gc_state_loads.at(i);
1918       if (n->outcnt() != 0) {
1919         progress |= try_common_gc_state_load(n, phase);
1920       }
1921     }
1922   } while (progress);
1923 
1924   for (uint i = 0; i < heap_stable_tests.size(); i++) {
1925     Node* n = heap_stable_tests.at(i);
1926     assert(is_heap_stable_test(n), "only evacuation test");
1927     merge_back_to_back_tests(n, phase);
1928   }
1929 
1930   if (!phase->C->major_progress()) {
1931     VectorSet seen(Thread::current()->resource_area());
1932     for (uint i = 0; i < heap_stable_tests.size(); i++) {
1933       Node* n = heap_stable_tests.at(i);
1934       IdealLoopTree* loop = phase->get_loop(n);
1935       if (loop != phase->ltree_root() &&
1936           loop->_child == NULL &&
1937           !loop->_irreducible) {
1938         LoopNode* head = loop->_head->as_Loop();
1939         if ((!head->is_CountedLoop() || head->as_CountedLoop()->is_main_loop() || head->as_CountedLoop()->is_normal_loop()) &&
1940             !seen.test_set(head->_idx)) {
1941           IfNode* iff = find_unswitching_candidate(loop, phase);
1942           if (iff != NULL) {
1943             Node* bol = iff->in(1);
1944             if (head->is_strip_mined()) {
1945               head->verify_strip_mined(0);
1946             }
1947             move_heap_stable_test_out_of_loop(iff, phase);
1948 
1949             AutoNodeBudget node_budget(phase);
1950 
1951             if (loop->policy_unswitching(phase)) {
1952               if (head->is_strip_mined()) {
1953                 OuterStripMinedLoopNode* outer = head->as_CountedLoop()->outer_loop();
1954                 hide_strip_mined_loop(outer, head->as_CountedLoop(), phase);
1955               }
1956               phase->do_unswitching(loop, old_new);
1957             } else {
1958               // Not proceeding with unswitching. Move load back in
1959               // the loop.
1960               phase->igvn().replace_input_of(iff, 1, bol);
1961             }
1962           }
1963         }
1964       }
1965     }
1966   }
1967 }
1968 
1969 #ifdef ASSERT
1970 void ShenandoahBarrierC2Support::verify_raw_mem(RootNode* root) {
1971   const bool trace = false;
1972   ResourceMark rm;
1973   Unique_Node_List nodes;
1974   Unique_Node_List controls;
1975   Unique_Node_List memories;
1976 
1977   nodes.push(root);
1978   for (uint next = 0; next < nodes.size(); next++) {
1979     Node *n  = nodes.at(next);
1980     if (ShenandoahBarrierSetC2::is_shenandoah_wb_call(n)) {
1981       controls.push(n);
1982       if (trace) { tty->print("XXXXXX verifying"); n->dump(); }
1983       for (uint next2 = 0; next2 < controls.size(); next2++) {
1984         Node *m = controls.at(next2);
1985         for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) {
1986           Node* u = m->fast_out(i);
1987           if (u->is_CFG() && !u->is_Root() &&
1988               !(u->Opcode() == Op_CProj && u->in(0)->Opcode() == Op_NeverBranch && u->as_Proj()->_con == 1) &&
1989               !(u->is_Region() && u->unique_ctrl_out()->Opcode() == Op_Halt)) {
1990             if (trace) { tty->print("XXXXXX pushing control"); u->dump(); }
1991             controls.push(u);
1992           }
1993         }
1994       }
1995       memories.push(n->as_Call()->proj_out(TypeFunc::Memory));
1996       for (uint next2 = 0; next2 < memories.size(); next2++) {
1997         Node *m = memories.at(next2);
1998         assert(m->bottom_type() == Type::MEMORY, "");
1999         for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) {
2000           Node* u = m->fast_out(i);
2001           if (u->bottom_type() == Type::MEMORY && (u->is_Mem() || u->is_ClearArray())) {
2002             if (trace) { tty->print("XXXXXX pushing memory"); u->dump(); }
2003             memories.push(u);
2004           } else if (u->is_LoadStore()) {
2005             if (trace) { tty->print("XXXXXX pushing memory"); u->find_out_with(Op_SCMemProj)->dump(); }
2006             memories.push(u->find_out_with(Op_SCMemProj));
2007           } else if (u->is_MergeMem() && u->as_MergeMem()->memory_at(Compile::AliasIdxRaw) == m) {
2008             if (trace) { tty->print("XXXXXX pushing memory"); u->dump(); }
2009             memories.push(u);
2010           } else if (u->is_Phi()) {
2011             assert(u->bottom_type() == Type::MEMORY, "");
2012             if (u->adr_type() == TypeRawPtr::BOTTOM || u->adr_type() == TypePtr::BOTTOM) {
2013               assert(controls.member(u->in(0)), "");
2014               if (trace) { tty->print("XXXXXX pushing memory"); u->dump(); }
2015               memories.push(u);
2016             }
2017           } else if (u->is_SafePoint() || u->is_MemBar()) {
2018             for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
2019               Node* uu = u->fast_out(j);
2020               if (uu->bottom_type() == Type::MEMORY) {
2021                 if (trace) { tty->print("XXXXXX pushing memory"); uu->dump(); }
2022                 memories.push(uu);
2023               }
2024             }
2025           }
2026         }
2027       }
2028       for (uint next2 = 0; next2 < controls.size(); next2++) {
2029         Node *m = controls.at(next2);
2030         if (m->is_Region()) {
2031           bool all_in = true;
2032           for (uint i = 1; i < m->req(); i++) {
2033             if (!controls.member(m->in(i))) {
2034               all_in = false;
2035               break;
2036             }
2037           }
2038           if (trace) { tty->print("XXX verifying %s", all_in ? "all in" : ""); m->dump(); }
2039           bool found_phi = false;
2040           for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax && !found_phi; j++) {
2041             Node* u = m->fast_out(j);
2042             if (u->is_Phi() && memories.member(u)) {
2043               found_phi = true;
2044               for (uint i = 1; i < u->req() && found_phi; i++) {
2045                 Node* k = u->in(i);
2046                 if (memories.member(k) != controls.member(m->in(i))) {
2047                   found_phi = false;
2048                 }
2049               }
2050             }
2051           }
2052           assert(found_phi || all_in, "");
2053         }
2054       }
2055       controls.clear();
2056       memories.clear();
2057     }
2058     for( uint i = 0; i < n->len(); ++i ) {
2059       Node *m = n->in(i);
2060       if (m != NULL) {
2061         nodes.push(m);
2062       }
2063     }
2064   }
2065 }
2066 #endif
2067 
2068 ShenandoahEnqueueBarrierNode::ShenandoahEnqueueBarrierNode(Node* val) : Node(NULL, val) {
2069   ShenandoahBarrierSetC2::bsc2()->state()->add_enqueue_barrier(this);
2070 }
2071 
2072 const Type* ShenandoahEnqueueBarrierNode::bottom_type() const {
2073   if (in(1) == NULL || in(1)->is_top()) {
2074     return Type::TOP;
2075   }
2076   const Type* t = in(1)->bottom_type();
2077   if (t == TypePtr::NULL_PTR) {
2078     return t;
2079   }
2080   return t->is_oopptr()->cast_to_nonconst();
2081 }
2082 
2083 const Type* ShenandoahEnqueueBarrierNode::Value(PhaseGVN* phase) const {
2084   if (in(1) == NULL) {
2085     return Type::TOP;
2086   }
2087   const Type* t = phase->type(in(1));
2088   if (t == Type::TOP) {
2089     return Type::TOP;
2090   }
2091   if (t == TypePtr::NULL_PTR) {
2092     return t;
2093   }
2094   return t->is_oopptr()->cast_to_nonconst();
2095 }
2096 
2097 int ShenandoahEnqueueBarrierNode::needed(Node* n) {
2098   if (n == NULL ||
2099       n->is_Allocate() ||
2100       n->Opcode() == Op_ShenandoahEnqueueBarrier ||
2101       n->bottom_type() == TypePtr::NULL_PTR ||
2102       (n->bottom_type()->make_oopptr() != NULL && n->bottom_type()->make_oopptr()->const_oop() != NULL)) {
2103     return NotNeeded;
2104   }
2105   if (n->is_Phi() ||
2106       n->is_CMove()) {
2107     return MaybeNeeded;
2108   }
2109   return Needed;
2110 }
2111 
2112 Node* ShenandoahEnqueueBarrierNode::next(Node* n) {
2113   for (;;) {
2114     if (n == NULL) {
2115       return n;
2116     } else if (n->bottom_type() == TypePtr::NULL_PTR) {
2117       return n;
2118     } else if (n->bottom_type()->make_oopptr() != NULL && n->bottom_type()->make_oopptr()->const_oop() != NULL) {
2119       return n;
2120     } else if (n->is_ConstraintCast() ||
2121                n->Opcode() == Op_DecodeN ||
2122                n->Opcode() == Op_EncodeP) {
2123       n = n->in(1);
2124     } else if (n->is_Proj()) {
2125       n = n->in(0);
2126     } else {
2127       return n;
2128     }
2129   }
2130   ShouldNotReachHere();
2131   return NULL;
2132 }
2133 
2134 Node* ShenandoahEnqueueBarrierNode::Identity(PhaseGVN* phase) {
2135   PhaseIterGVN* igvn = phase->is_IterGVN();
2136 
2137   Node* n = next(in(1));
2138 
2139   int cont = needed(n);
2140 
2141   if (cont == NotNeeded) {
2142     return in(1);
2143   } else if (cont == MaybeNeeded) {
2144     if (igvn == NULL) {
2145       phase->record_for_igvn(this);
2146       return this;
2147     } else {
2148       ResourceMark rm;
2149       Unique_Node_List wq;
2150       uint wq_i = 0;
2151 
2152       for (;;) {
2153         if (n->is_Phi()) {
2154           for (uint i = 1; i < n->req(); i++) {
2155             Node* m = n->in(i);
2156             if (m != NULL) {
2157               wq.push(m);
2158             }
2159           }
2160         } else {
2161           assert(n->is_CMove(), "nothing else here");
2162           Node* m = n->in(CMoveNode::IfFalse);
2163           wq.push(m);
2164           m = n->in(CMoveNode::IfTrue);
2165           wq.push(m);
2166         }
2167         Node* orig_n = NULL;
2168         do {
2169           if (wq_i >= wq.size()) {
2170             return in(1);
2171           }
2172           n = wq.at(wq_i);
2173           wq_i++;
2174           orig_n = n;
2175           n = next(n);
2176           cont = needed(n);
2177           if (cont == Needed) {
2178             return this;
2179           }
2180         } while (cont != MaybeNeeded || (orig_n != n && wq.member(n)));
2181       }
2182     }
2183   }
2184 
2185   return this;
2186 }
2187 
2188 #ifdef ASSERT
2189 static bool has_never_branch(Node* root) {
2190   for (uint i = 1; i < root->req(); i++) {
2191     Node* in = root->in(i);
2192     if (in != NULL && in->Opcode() == Op_Halt && in->in(0)->is_Proj() && in->in(0)->in(0)->Opcode() == Op_NeverBranch) {
2193       return true;
2194     }
2195   }
2196   return false;
2197 }
2198 #endif
2199 
2200 void MemoryGraphFixer::collect_memory_nodes() {
2201   Node_Stack stack(0);
2202   VectorSet visited(Thread::current()->resource_area());
2203   Node_List regions;
2204 
2205   // Walk the raw memory graph and create a mapping from CFG node to
2206   // memory node. Exclude phis for now.
2207   stack.push(_phase->C->root(), 1);
2208   do {
2209     Node* n = stack.node();
2210     int opc = n->Opcode();
2211     uint i = stack.index();
2212     if (i < n->req()) {
2213       Node* mem = NULL;
2214       if (opc == Op_Root) {
2215         Node* in = n->in(i);
2216         int in_opc = in->Opcode();
2217         if (in_opc == Op_Return || in_opc == Op_Rethrow) {
2218           mem = in->in(TypeFunc::Memory);
2219         } else if (in_opc == Op_Halt) {
2220           if (!in->in(0)->is_Region()) {
2221             Node* proj = in->in(0);
2222             assert(proj->is_Proj(), "");
2223             Node* in = proj->in(0);
2224             assert(in->is_CallStaticJava() || in->Opcode() == Op_NeverBranch || in->Opcode() == Op_Catch || proj->is_IfProj(), "");
2225             if (in->is_CallStaticJava()) {
2226               mem = in->in(TypeFunc::Memory);
2227             } else if (in->Opcode() == Op_Catch) {
2228               Node* call = in->in(0)->in(0);
2229               assert(call->is_Call(), "");
2230               mem = call->in(TypeFunc::Memory);
2231             } else if (in->Opcode() == Op_NeverBranch) {
2232               ResourceMark rm;
2233               Unique_Node_List wq;
2234               wq.push(in);
2235               wq.push(in->as_Multi()->proj_out(0));
2236               for (uint j = 1; j < wq.size(); j++) {
2237                 Node* c = wq.at(j);
2238                 assert(!c->is_Root(), "shouldn't leave loop");
2239                 if (c->is_SafePoint()) {
2240                   assert(mem == NULL, "only one safepoint");
2241                   mem = c->in(TypeFunc::Memory);
2242                 }
2243                 for (DUIterator_Fast kmax, k = c->fast_outs(kmax); k < kmax; k++) {
2244                   Node* u = c->fast_out(k);
2245                   if (u->is_CFG()) {
2246                     wq.push(u);
2247                   }
2248                 }
2249               }
2250               assert(mem != NULL, "should have found safepoint");
2251             }
2252           }
2253         } else {
2254 #ifdef ASSERT
2255           n->dump();
2256           in->dump();
2257 #endif
2258           ShouldNotReachHere();
2259         }
2260       } else {
2261         assert(n->is_Phi() && n->bottom_type() == Type::MEMORY, "");
2262         assert(n->adr_type() == TypePtr::BOTTOM || _phase->C->get_alias_index(n->adr_type()) == _alias, "");
2263         mem = n->in(i);
2264       }
2265       i++;
2266       stack.set_index(i);
2267       if (mem == NULL) {
2268         continue;
2269       }
2270       for (;;) {
2271         if (visited.test_set(mem->_idx) || mem->is_Start()) {
2272           break;
2273         }
2274         if (mem->is_Phi()) {
2275           stack.push(mem, 2);
2276           mem = mem->in(1);
2277         } else if (mem->is_Proj()) {
2278           stack.push(mem, mem->req());
2279           mem = mem->in(0);
2280         } else if (mem->is_SafePoint() || mem->is_MemBar()) {
2281           mem = mem->in(TypeFunc::Memory);
2282         } else if (mem->is_MergeMem()) {
2283           MergeMemNode* mm = mem->as_MergeMem();
2284           mem = mm->memory_at(_alias);
2285         } else if (mem->is_Store() || mem->is_LoadStore() || mem->is_ClearArray()) {
2286           assert(_alias == Compile::AliasIdxRaw, "");
2287           stack.push(mem, mem->req());
2288           mem = mem->in(MemNode::Memory);
2289         } else {
2290 #ifdef ASSERT
2291           mem->dump();
2292 #endif
2293           ShouldNotReachHere();
2294         }
2295       }
2296     } else {
2297       if (n->is_Phi()) {
2298         // Nothing
2299       } else if (!n->is_Root()) {
2300         Node* c = get_ctrl(n);
2301         _memory_nodes.map(c->_idx, n);
2302       }
2303       stack.pop();
2304     }
2305   } while(stack.is_nonempty());
2306 
2307   // Iterate over CFG nodes in rpo and propagate memory state to
2308   // compute memory state at regions, creating new phis if needed.
2309   Node_List rpo_list;
2310   visited.Clear();
2311   _phase->rpo(_phase->C->root(), stack, visited, rpo_list);
2312   Node* root = rpo_list.pop();
2313   assert(root == _phase->C->root(), "");
2314 
2315   const bool trace = false;
2316 #ifdef ASSERT
2317   if (trace) {
2318     for (int i = rpo_list.size() - 1; i >= 0; i--) {
2319       Node* c = rpo_list.at(i);
2320       if (_memory_nodes[c->_idx] != NULL) {
2321         tty->print("X %d", c->_idx);  _memory_nodes[c->_idx]->dump();
2322       }
2323     }
2324   }
2325 #endif
2326   uint last = _phase->C->unique();
2327 
2328 #ifdef ASSERT
2329   uint8_t max_depth = 0;
2330   for (LoopTreeIterator iter(_phase->ltree_root()); !iter.done(); iter.next()) {
2331     IdealLoopTree* lpt = iter.current();
2332     max_depth = MAX2(max_depth, lpt->_nest);
2333   }
2334 #endif
2335 
2336   bool progress = true;
2337   int iteration = 0;
2338   Node_List dead_phis;
2339   while (progress) {
2340     progress = false;
2341     iteration++;
2342     assert(iteration <= 2+max_depth || _phase->C->has_irreducible_loop() || has_never_branch(_phase->C->root()), "");
2343     if (trace) { tty->print_cr("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); }
2344     IdealLoopTree* last_updated_ilt = NULL;
2345     for (int i = rpo_list.size() - 1; i >= 0; i--) {
2346       Node* c = rpo_list.at(i);
2347 
2348       Node* prev_mem = _memory_nodes[c->_idx];
2349       if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
2350         Node* prev_region = regions[c->_idx];
2351         Node* unique = NULL;
2352         for (uint j = 1; j < c->req() && unique != NodeSentinel; j++) {
2353           Node* m = _memory_nodes[c->in(j)->_idx];
2354           assert(m != NULL || (c->is_Loop() && j == LoopNode::LoopBackControl && iteration == 1) || _phase->C->has_irreducible_loop() || has_never_branch(_phase->C->root()), "expect memory state");
2355           if (m != NULL) {
2356             if (m == prev_region && ((c->is_Loop() && j == LoopNode::LoopBackControl) || (prev_region->is_Phi() && prev_region->in(0) == c))) {
2357               assert(c->is_Loop() && j == LoopNode::LoopBackControl || _phase->C->has_irreducible_loop(), "");
2358               // continue
2359             } else if (unique == NULL) {
2360               unique = m;
2361             } else if (m == unique) {
2362               // continue
2363             } else {
2364               unique = NodeSentinel;
2365             }
2366           }
2367         }
2368         assert(unique != NULL, "empty phi???");
2369         if (unique != NodeSentinel) {
2370           if (prev_region != NULL && prev_region->is_Phi() && prev_region->in(0) == c) {
2371             dead_phis.push(prev_region);
2372           }
2373           regions.map(c->_idx, unique);
2374         } else {
2375           Node* phi = NULL;
2376           if (prev_region != NULL && prev_region->is_Phi() && prev_region->in(0) == c && prev_region->_idx >= last) {
2377             phi = prev_region;
2378             for (uint k = 1; k < c->req(); k++) {
2379               Node* m = _memory_nodes[c->in(k)->_idx];
2380               assert(m != NULL, "expect memory state");
2381               phi->set_req(k, m);
2382             }
2383           } else {
2384             for (DUIterator_Fast jmax, j = c->fast_outs(jmax); j < jmax && phi == NULL; j++) {
2385               Node* u = c->fast_out(j);
2386               if (u->is_Phi() && u->bottom_type() == Type::MEMORY &&
2387                   (u->adr_type() == TypePtr::BOTTOM || _phase->C->get_alias_index(u->adr_type()) == _alias)) {
2388                 phi = u;
2389                 for (uint k = 1; k < c->req() && phi != NULL; k++) {
2390                   Node* m = _memory_nodes[c->in(k)->_idx];
2391                   assert(m != NULL, "expect memory state");
2392                   if (u->in(k) != m) {
2393                     phi = NULL;
2394                   }
2395                 }
2396               }
2397             }
2398             if (phi == NULL) {
2399               phi = new PhiNode(c, Type::MEMORY, _phase->C->get_adr_type(_alias));
2400               for (uint k = 1; k < c->req(); k++) {
2401                 Node* m = _memory_nodes[c->in(k)->_idx];
2402                 assert(m != NULL, "expect memory state");
2403                 phi->init_req(k, m);
2404               }
2405             }
2406           }
2407           assert(phi != NULL, "");
2408           regions.map(c->_idx, phi);
2409         }
2410         Node* current_region = regions[c->_idx];
2411         if (current_region != prev_region) {
2412           progress = true;
2413           if (prev_region == prev_mem) {
2414             _memory_nodes.map(c->_idx, current_region);
2415           }
2416         }
2417       } else if (prev_mem == NULL || prev_mem->is_Phi() || ctrl_or_self(prev_mem) != c) {
2418         Node* m = _memory_nodes[_phase->idom(c)->_idx];
2419         assert(m != NULL, "expect memory state");
2420         if (m != prev_mem) {
2421           _memory_nodes.map(c->_idx, m);
2422           progress = true;
2423         }
2424       }
2425 #ifdef ASSERT
2426       if (trace) { tty->print("X %d", c->_idx);  _memory_nodes[c->_idx]->dump(); }
2427 #endif
2428     }
2429   }
2430 
2431   // Replace existing phi with computed memory state for that region
2432   // if different (could be a new phi or a dominating memory node if
2433   // that phi was found to be useless).
2434   while (dead_phis.size() > 0) {
2435     Node* n = dead_phis.pop();
2436     n->replace_by(_phase->C->top());
2437     n->destruct();
2438   }
2439   for (int i = rpo_list.size() - 1; i >= 0; i--) {
2440     Node* c = rpo_list.at(i);
2441     if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
2442       Node* n = regions[c->_idx];
2443       if (n->is_Phi() && n->_idx >= last && n->in(0) == c) {
2444         _phase->register_new_node(n, c);
2445       }
2446     }
2447   }
2448   for (int i = rpo_list.size() - 1; i >= 0; i--) {
2449     Node* c = rpo_list.at(i);
2450     if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
2451       Node* n = regions[c->_idx];
2452       for (DUIterator_Fast imax, i = c->fast_outs(imax); i < imax; i++) {
2453         Node* u = c->fast_out(i);
2454         if (u->is_Phi() && u->bottom_type() == Type::MEMORY &&
2455             u != n) {
2456           if (u->adr_type() == TypePtr::BOTTOM) {
2457             fix_memory_uses(u, n, n, c);
2458           } else if (_phase->C->get_alias_index(u->adr_type()) == _alias) {
2459             _phase->lazy_replace(u, n);
2460             --i; --imax;
2461           }
2462         }
2463       }
2464     }
2465   }
2466 }
2467 
2468 Node* MemoryGraphFixer::get_ctrl(Node* n) const {
2469   Node* c = _phase->get_ctrl(n);
2470   if (n->is_Proj() && n->in(0) != NULL && n->in(0)->is_Call()) {
2471     assert(c == n->in(0), "");
2472     CallNode* call = c->as_Call();
2473     CallProjections* projs = call->extract_projections(true, false);
2474     if (projs->catchall_memproj != NULL) {
2475       if (projs->fallthrough_memproj == n) {
2476         c = projs->fallthrough_catchproj;
2477       } else {
2478         assert(projs->catchall_memproj == n, "");
2479         c = projs->catchall_catchproj;
2480       }
2481     }
2482   }
2483   return c;
2484 }
2485 
2486 Node* MemoryGraphFixer::ctrl_or_self(Node* n) const {
2487   if (_phase->has_ctrl(n))
2488     return get_ctrl(n);
2489   else {
2490     assert (n->is_CFG(), "must be a CFG node");
2491     return n;
2492   }
2493 }
2494 
2495 bool MemoryGraphFixer::mem_is_valid(Node* m, Node* c) const {
2496   return m != NULL && get_ctrl(m) == c;
2497 }
2498 
2499 Node* MemoryGraphFixer::find_mem(Node* ctrl, Node* n) const {
2500   assert(n == NULL || _phase->ctrl_or_self(n) == ctrl, "");
2501   Node* mem = _memory_nodes[ctrl->_idx];
2502   Node* c = ctrl;
2503   while (!mem_is_valid(mem, c) &&
2504          (!c->is_CatchProj() || mem == NULL || c->in(0)->in(0)->in(0) != get_ctrl(mem))) {
2505     c = _phase->idom(c);
2506     mem = _memory_nodes[c->_idx];
2507   }
2508   if (n != NULL && mem_is_valid(mem, c)) {
2509     while (!ShenandoahBarrierC2Support::is_dominator_same_ctrl(c, mem, n, _phase) && _phase->ctrl_or_self(mem) == ctrl) {
2510       mem = next_mem(mem, _alias);
2511     }
2512     if (mem->is_MergeMem()) {
2513       mem = mem->as_MergeMem()->memory_at(_alias);
2514     }
2515     if (!mem_is_valid(mem, c)) {
2516       do {
2517         c = _phase->idom(c);
2518         mem = _memory_nodes[c->_idx];
2519       } while (!mem_is_valid(mem, c) &&
2520                (!c->is_CatchProj() || mem == NULL || c->in(0)->in(0)->in(0) != get_ctrl(mem)));
2521     }
2522   }
2523   assert(mem->bottom_type() == Type::MEMORY, "");
2524   return mem;
2525 }
2526 
2527 bool MemoryGraphFixer::has_mem_phi(Node* region) const {
2528   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
2529     Node* use = region->fast_out(i);
2530     if (use->is_Phi() && use->bottom_type() == Type::MEMORY &&
2531         (_phase->C->get_alias_index(use->adr_type()) == _alias)) {
2532       return true;
2533     }
2534   }
2535   return false;
2536 }
2537 
2538 void MemoryGraphFixer::fix_mem(Node* ctrl, Node* new_ctrl, Node* mem, Node* mem_for_ctrl, Node* new_mem, Unique_Node_List& uses) {
2539   assert(_phase->ctrl_or_self(new_mem) == new_ctrl, "");
2540   const bool trace = false;
2541   DEBUG_ONLY(if (trace) { tty->print("ZZZ control is"); ctrl->dump(); });
2542   DEBUG_ONLY(if (trace) { tty->print("ZZZ mem is"); mem->dump(); });
2543   GrowableArray<Node*> phis;
2544   if (mem_for_ctrl != mem) {
2545     Node* old = mem_for_ctrl;
2546     Node* prev = NULL;
2547     while (old != mem) {
2548       prev = old;
2549       if (old->is_Store() || old->is_ClearArray() || old->is_LoadStore()) {
2550         assert(_alias == Compile::AliasIdxRaw, "");
2551         old = old->in(MemNode::Memory);
2552       } else if (old->Opcode() == Op_SCMemProj) {
2553         assert(_alias == Compile::AliasIdxRaw, "");
2554         old = old->in(0);
2555       } else {
2556         ShouldNotReachHere();
2557       }
2558     }
2559     assert(prev != NULL, "");
2560     if (new_ctrl != ctrl) {
2561       _memory_nodes.map(ctrl->_idx, mem);
2562       _memory_nodes.map(new_ctrl->_idx, mem_for_ctrl);
2563     }
2564     uint input = (uint)MemNode::Memory;
2565     _phase->igvn().replace_input_of(prev, input, new_mem);
2566   } else {
2567     uses.clear();
2568     _memory_nodes.map(new_ctrl->_idx, new_mem);
2569     uses.push(new_ctrl);
2570     for(uint next = 0; next < uses.size(); next++ ) {
2571       Node *n = uses.at(next);
2572       assert(n->is_CFG(), "");
2573       DEBUG_ONLY(if (trace) { tty->print("ZZZ ctrl"); n->dump(); });
2574       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2575         Node* u = n->fast_out(i);
2576         if (!u->is_Root() && u->is_CFG() && u != n) {
2577           Node* m = _memory_nodes[u->_idx];
2578           if (u->is_Region() && (!u->is_OuterStripMinedLoop() || _include_lsm) &&
2579               !has_mem_phi(u) &&
2580               u->unique_ctrl_out()->Opcode() != Op_Halt) {
2581             DEBUG_ONLY(if (trace) { tty->print("ZZZ region"); u->dump(); });
2582             DEBUG_ONLY(if (trace && m != NULL) { tty->print("ZZZ mem"); m->dump(); });
2583 
2584             if (!mem_is_valid(m, u) || !m->is_Phi()) {
2585               bool push = true;
2586               bool create_phi = true;
2587               if (_phase->is_dominator(new_ctrl, u)) {
2588                 create_phi = false;
2589               } else if (!_phase->C->has_irreducible_loop()) {
2590                 IdealLoopTree* loop = _phase->get_loop(ctrl);
2591                 bool do_check = true;
2592                 IdealLoopTree* l = loop;
2593                 create_phi = false;
2594                 while (l != _phase->ltree_root()) {
2595                   if (_phase->is_dominator(l->_head, u) && _phase->is_dominator(_phase->idom(u), l->_head)) {
2596                     create_phi = true;
2597                     do_check = false;
2598                     break;
2599                   }
2600                   l = l->_parent;
2601                 }
2602 
2603                 if (do_check) {
2604                   assert(!create_phi, "");
2605                   IdealLoopTree* u_loop = _phase->get_loop(u);
2606                   if (u_loop != _phase->ltree_root() && u_loop->is_member(loop)) {
2607                     Node* c = ctrl;
2608                     while (!_phase->is_dominator(c, u_loop->tail())) {
2609                       c = _phase->idom(c);
2610                     }
2611                     if (!_phase->is_dominator(c, u)) {
2612                       do_check = false;
2613                     }
2614                   }
2615                 }
2616 
2617                 if (do_check && _phase->is_dominator(_phase->idom(u), new_ctrl)) {
2618                   create_phi = true;
2619                 }
2620               }
2621               if (create_phi) {
2622                 Node* phi = new PhiNode(u, Type::MEMORY, _phase->C->get_adr_type(_alias));
2623                 _phase->register_new_node(phi, u);
2624                 phis.push(phi);
2625                 DEBUG_ONLY(if (trace) { tty->print("ZZZ new phi"); phi->dump(); });
2626                 if (!mem_is_valid(m, u)) {
2627                   DEBUG_ONLY(if (trace) { tty->print("ZZZ setting mem"); phi->dump(); });
2628                   _memory_nodes.map(u->_idx, phi);
2629                 } else {
2630                   DEBUG_ONLY(if (trace) { tty->print("ZZZ NOT setting mem"); m->dump(); });
2631                   for (;;) {
2632                     assert(m->is_Mem() || m->is_LoadStore() || m->is_Proj(), "");
2633                     Node* next = NULL;
2634                     if (m->is_Proj()) {
2635                       next = m->in(0);
2636                     } else {
2637                       assert(m->is_Mem() || m->is_LoadStore(), "");
2638                       assert(_alias == Compile::AliasIdxRaw, "");
2639                       next = m->in(MemNode::Memory);
2640                     }
2641                     if (_phase->get_ctrl(next) != u) {
2642                       break;
2643                     }
2644                     if (next->is_MergeMem()) {
2645                       assert(_phase->get_ctrl(next->as_MergeMem()->memory_at(_alias)) != u, "");
2646                       break;
2647                     }
2648                     if (next->is_Phi()) {
2649                       assert(next->adr_type() == TypePtr::BOTTOM && next->in(0) == u, "");
2650                       break;
2651                     }
2652                     m = next;
2653                   }
2654 
2655                   DEBUG_ONLY(if (trace) { tty->print("ZZZ setting to phi"); m->dump(); });
2656                   assert(m->is_Mem() || m->is_LoadStore(), "");
2657                   uint input = (uint)MemNode::Memory;
2658                   _phase->igvn().replace_input_of(m, input, phi);
2659                   push = false;
2660                 }
2661               } else {
2662                 DEBUG_ONLY(if (trace) { tty->print("ZZZ skipping region"); u->dump(); });
2663               }
2664               if (push) {
2665                 uses.push(u);
2666               }
2667             }
2668           } else if (!mem_is_valid(m, u) &&
2669                      !(u->Opcode() == Op_CProj && u->in(0)->Opcode() == Op_NeverBranch && u->as_Proj()->_con == 1)) {
2670             uses.push(u);
2671           }
2672         }
2673       }
2674     }
2675     for (int i = 0; i < phis.length(); i++) {
2676       Node* n = phis.at(i);
2677       Node* r = n->in(0);
2678       DEBUG_ONLY(if (trace) { tty->print("ZZZ fixing new phi"); n->dump(); });
2679       for (uint j = 1; j < n->req(); j++) {
2680         Node* m = find_mem(r->in(j), NULL);
2681         _phase->igvn().replace_input_of(n, j, m);
2682         DEBUG_ONLY(if (trace) { tty->print("ZZZ fixing new phi: %d", j); m->dump(); });
2683       }
2684     }
2685   }
2686   uint last = _phase->C->unique();
2687   MergeMemNode* mm = NULL;
2688   int alias = _alias;
2689   DEBUG_ONLY(if (trace) { tty->print("ZZZ raw mem is"); mem->dump(); });
2690   for (DUIterator i = mem->outs(); mem->has_out(i); i++) {
2691     Node* u = mem->out(i);
2692     if (u->_idx < last) {
2693       if (u->is_Mem()) {
2694         if (_phase->C->get_alias_index(u->adr_type()) == alias) {
2695           Node* m = find_mem(_phase->get_ctrl(u), u);
2696           if (m != mem) {
2697             DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2698             _phase->igvn().replace_input_of(u, MemNode::Memory, m);
2699             --i;
2700           }
2701         }
2702       } else if (u->is_MergeMem()) {
2703         MergeMemNode* u_mm = u->as_MergeMem();
2704         if (u_mm->memory_at(alias) == mem) {
2705           MergeMemNode* newmm = NULL;
2706           for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
2707             Node* uu = u->fast_out(j);
2708             assert(!uu->is_MergeMem(), "chain of MergeMems?");
2709             if (uu->is_Phi()) {
2710               assert(uu->adr_type() == TypePtr::BOTTOM, "");
2711               Node* region = uu->in(0);
2712               int nb = 0;
2713               for (uint k = 1; k < uu->req(); k++) {
2714                 if (uu->in(k) == u) {
2715                   Node* m = find_mem(region->in(k), NULL);
2716                   if (m != mem) {
2717                     DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of phi %d", k); uu->dump(); });
2718                     newmm = clone_merge_mem(u, mem, m, _phase->ctrl_or_self(m), i);
2719                     if (newmm != u) {
2720                       _phase->igvn().replace_input_of(uu, k, newmm);
2721                       nb++;
2722                       --jmax;
2723                     }
2724                   }
2725                 }
2726               }
2727               if (nb > 0) {
2728                 --j;
2729               }
2730             } else {
2731               Node* m = find_mem(_phase->ctrl_or_self(uu), uu);
2732               if (m != mem) {
2733                 DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); uu->dump(); });
2734                 newmm = clone_merge_mem(u, mem, m, _phase->ctrl_or_self(m), i);
2735                 if (newmm != u) {
2736                   _phase->igvn().replace_input_of(uu, uu->find_edge(u), newmm);
2737                   --j, --jmax;
2738                 }
2739               }
2740             }
2741           }
2742         }
2743       } else if (u->is_Phi()) {
2744         assert(u->bottom_type() == Type::MEMORY, "what else?");
2745         if (_phase->C->get_alias_index(u->adr_type()) == alias || u->adr_type() == TypePtr::BOTTOM) {
2746           Node* region = u->in(0);
2747           bool replaced = false;
2748           for (uint j = 1; j < u->req(); j++) {
2749             if (u->in(j) == mem) {
2750               Node* m = find_mem(region->in(j), NULL);
2751               Node* nnew = m;
2752               if (m != mem) {
2753                 if (u->adr_type() == TypePtr::BOTTOM) {
2754                   mm = allocate_merge_mem(mem, m, _phase->ctrl_or_self(m));
2755                   nnew = mm;
2756                 }
2757                 DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of phi %d", j); u->dump(); });
2758                 _phase->igvn().replace_input_of(u, j, nnew);
2759                 replaced = true;
2760               }
2761             }
2762           }
2763           if (replaced) {
2764             --i;
2765           }
2766         }
2767       } else if ((u->adr_type() == TypePtr::BOTTOM && u->Opcode() != Op_StrInflatedCopy) ||
2768                  u->adr_type() == NULL) {
2769         assert(u->adr_type() != NULL ||
2770                u->Opcode() == Op_Rethrow ||
2771                u->Opcode() == Op_Return ||
2772                u->Opcode() == Op_SafePoint ||
2773                (u->is_CallStaticJava() && u->as_CallStaticJava()->uncommon_trap_request() != 0) ||
2774                (u->is_CallStaticJava() && u->as_CallStaticJava()->_entry_point == OptoRuntime::rethrow_stub()) ||
2775                u->Opcode() == Op_CallLeaf, "");
2776         Node* m = find_mem(_phase->ctrl_or_self(u), u);
2777         if (m != mem) {
2778           mm = allocate_merge_mem(mem, m, _phase->get_ctrl(m));
2779           _phase->igvn().replace_input_of(u, u->find_edge(mem), mm);
2780           --i;
2781         }
2782       } else if (_phase->C->get_alias_index(u->adr_type()) == alias) {
2783         Node* m = find_mem(_phase->ctrl_or_self(u), u);
2784         if (m != mem) {
2785           DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2786           _phase->igvn().replace_input_of(u, u->find_edge(mem), m);
2787           --i;
2788         }
2789       } else if (u->adr_type() != TypePtr::BOTTOM &&
2790                  _memory_nodes[_phase->ctrl_or_self(u)->_idx] == u) {
2791         Node* m = find_mem(_phase->ctrl_or_self(u), u);
2792         assert(m != mem, "");
2793         // u is on the wrong slice...
2794         assert(u->is_ClearArray(), "");
2795         DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2796         _phase->igvn().replace_input_of(u, u->find_edge(mem), m);
2797         --i;
2798       }
2799     }
2800   }
2801 #ifdef ASSERT
2802   assert(new_mem->outcnt() > 0, "");
2803   for (int i = 0; i < phis.length(); i++) {
2804     Node* n = phis.at(i);
2805     assert(n->outcnt() > 0, "new phi must have uses now");
2806   }
2807 #endif
2808 }
2809 
2810 MergeMemNode* MemoryGraphFixer::allocate_merge_mem(Node* mem, Node* rep_proj, Node* rep_ctrl) const {
2811   MergeMemNode* mm = MergeMemNode::make(mem);
2812   mm->set_memory_at(_alias, rep_proj);
2813   _phase->register_new_node(mm, rep_ctrl);
2814   return mm;
2815 }
2816 
2817 MergeMemNode* MemoryGraphFixer::clone_merge_mem(Node* u, Node* mem, Node* rep_proj, Node* rep_ctrl, DUIterator& i) const {
2818   MergeMemNode* newmm = NULL;
2819   MergeMemNode* u_mm = u->as_MergeMem();
2820   Node* c = _phase->get_ctrl(u);
2821   if (_phase->is_dominator(c, rep_ctrl)) {
2822     c = rep_ctrl;
2823   } else {
2824     assert(_phase->is_dominator(rep_ctrl, c), "one must dominate the other");
2825   }
2826   if (u->outcnt() == 1) {
2827     if (u->req() > (uint)_alias && u->in(_alias) == mem) {
2828       _phase->igvn().replace_input_of(u, _alias, rep_proj);
2829       --i;
2830     } else {
2831       _phase->igvn().rehash_node_delayed(u);
2832       u_mm->set_memory_at(_alias, rep_proj);
2833     }
2834     newmm = u_mm;
2835     _phase->set_ctrl_and_loop(u, c);
2836   } else {
2837     // can't simply clone u and then change one of its input because
2838     // it adds and then removes an edge which messes with the
2839     // DUIterator
2840     newmm = MergeMemNode::make(u_mm->base_memory());
2841     for (uint j = 0; j < u->req(); j++) {
2842       if (j < newmm->req()) {
2843         if (j == (uint)_alias) {
2844           newmm->set_req(j, rep_proj);
2845         } else if (newmm->in(j) != u->in(j)) {
2846           newmm->set_req(j, u->in(j));
2847         }
2848       } else if (j == (uint)_alias) {
2849         newmm->add_req(rep_proj);
2850       } else {
2851         newmm->add_req(u->in(j));
2852       }
2853     }
2854     if ((uint)_alias >= u->req()) {
2855       newmm->set_memory_at(_alias, rep_proj);
2856     }
2857     _phase->register_new_node(newmm, c);
2858   }
2859   return newmm;
2860 }
2861 
2862 bool MemoryGraphFixer::should_process_phi(Node* phi) const {
2863   if (phi->adr_type() == TypePtr::BOTTOM) {
2864     Node* region = phi->in(0);
2865     for (DUIterator_Fast jmax, j = region->fast_outs(jmax); j < jmax; j++) {
2866       Node* uu = region->fast_out(j);
2867       if (uu->is_Phi() && uu != phi && uu->bottom_type() == Type::MEMORY && _phase->C->get_alias_index(uu->adr_type()) == _alias) {
2868         return false;
2869       }
2870     }
2871     return true;
2872   }
2873   return _phase->C->get_alias_index(phi->adr_type()) == _alias;
2874 }
2875 
2876 void MemoryGraphFixer::fix_memory_uses(Node* mem, Node* replacement, Node* rep_proj, Node* rep_ctrl) const {
2877   uint last = _phase-> C->unique();
2878   MergeMemNode* mm = NULL;
2879   assert(mem->bottom_type() == Type::MEMORY, "");
2880   for (DUIterator i = mem->outs(); mem->has_out(i); i++) {
2881     Node* u = mem->out(i);
2882     if (u != replacement && u->_idx < last) {
2883       if (u->is_MergeMem()) {
2884         MergeMemNode* u_mm = u->as_MergeMem();
2885         if (u_mm->memory_at(_alias) == mem) {
2886           MergeMemNode* newmm = NULL;
2887           for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
2888             Node* uu = u->fast_out(j);
2889             assert(!uu->is_MergeMem(), "chain of MergeMems?");
2890             if (uu->is_Phi()) {
2891               if (should_process_phi(uu)) {
2892                 Node* region = uu->in(0);
2893                 int nb = 0;
2894                 for (uint k = 1; k < uu->req(); k++) {
2895                   if (uu->in(k) == u && _phase->is_dominator(rep_ctrl, region->in(k))) {
2896                     if (newmm == NULL) {
2897                       newmm = clone_merge_mem(u, mem, rep_proj, rep_ctrl, i);
2898                     }
2899                     if (newmm != u) {
2900                       _phase->igvn().replace_input_of(uu, k, newmm);
2901                       nb++;
2902                       --jmax;
2903                     }
2904                   }
2905                 }
2906                 if (nb > 0) {
2907                   --j;
2908                 }
2909               }
2910             } else {
2911               if (rep_ctrl != uu && ShenandoahBarrierC2Support::is_dominator(rep_ctrl, _phase->ctrl_or_self(uu), replacement, uu, _phase)) {
2912                 if (newmm == NULL) {
2913                   newmm = clone_merge_mem(u, mem, rep_proj, rep_ctrl, i);
2914                 }
2915                 if (newmm != u) {
2916                   _phase->igvn().replace_input_of(uu, uu->find_edge(u), newmm);
2917                   --j, --jmax;
2918                 }
2919               }
2920             }
2921           }
2922         }
2923       } else if (u->is_Phi()) {
2924         assert(u->bottom_type() == Type::MEMORY, "what else?");
2925         Node* region = u->in(0);
2926         if (should_process_phi(u)) {
2927           bool replaced = false;
2928           for (uint j = 1; j < u->req(); j++) {
2929             if (u->in(j) == mem && _phase->is_dominator(rep_ctrl, region->in(j))) {
2930               Node* nnew = rep_proj;
2931               if (u->adr_type() == TypePtr::BOTTOM) {
2932                 if (mm == NULL) {
2933                   mm = allocate_merge_mem(mem, rep_proj, rep_ctrl);
2934                 }
2935                 nnew = mm;
2936               }
2937               _phase->igvn().replace_input_of(u, j, nnew);
2938               replaced = true;
2939             }
2940           }
2941           if (replaced) {
2942             --i;
2943           }
2944 
2945         }
2946       } else if ((u->adr_type() == TypePtr::BOTTOM && u->Opcode() != Op_StrInflatedCopy) ||
2947                  u->adr_type() == NULL) {
2948         assert(u->adr_type() != NULL ||
2949                u->Opcode() == Op_Rethrow ||
2950                u->Opcode() == Op_Return ||
2951                u->Opcode() == Op_SafePoint ||
2952                u->Opcode() == Op_StoreLConditional ||
2953                (u->is_CallStaticJava() && u->as_CallStaticJava()->uncommon_trap_request() != 0) ||
2954                (u->is_CallStaticJava() && u->as_CallStaticJava()->_entry_point == OptoRuntime::rethrow_stub()) ||
2955                u->Opcode() == Op_CallLeaf, "");
2956         if (ShenandoahBarrierC2Support::is_dominator(rep_ctrl, _phase->ctrl_or_self(u), replacement, u, _phase)) {
2957           if (mm == NULL) {
2958             mm = allocate_merge_mem(mem, rep_proj, rep_ctrl);
2959           }
2960           _phase->igvn().replace_input_of(u, u->find_edge(mem), mm);
2961           --i;
2962         }
2963       } else if (_phase->C->get_alias_index(u->adr_type()) == _alias) {
2964         if (ShenandoahBarrierC2Support::is_dominator(rep_ctrl, _phase->ctrl_or_self(u), replacement, u, _phase)) {
2965           _phase->igvn().replace_input_of(u, u->find_edge(mem), rep_proj);
2966           --i;
2967         }
2968       }
2969     }
2970   }
2971 }
2972 
2973 ShenandoahLoadReferenceBarrierNode::ShenandoahLoadReferenceBarrierNode(Node* ctrl, Node* obj)
2974 : Node(ctrl, obj) {
2975   ShenandoahBarrierSetC2::bsc2()->state()->add_load_reference_barrier(this);
2976 }
2977 
2978 const Type* ShenandoahLoadReferenceBarrierNode::bottom_type() const {
2979   if (in(ValueIn) == NULL || in(ValueIn)->is_top()) {
2980     return Type::TOP;
2981   }
2982   const Type* t = in(ValueIn)->bottom_type();
2983   if (t == TypePtr::NULL_PTR) {
2984     return t;
2985   }
2986   return t->is_oopptr();
2987 }
2988 
2989 const Type* ShenandoahLoadReferenceBarrierNode::Value(PhaseGVN* phase) const {
2990   // Either input is TOP ==> the result is TOP
2991   const Type *t2 = phase->type(in(ValueIn));
2992   if( t2 == Type::TOP ) return Type::TOP;
2993 
2994   if (t2 == TypePtr::NULL_PTR) {
2995     return t2;
2996   }
2997 
2998   const Type* type = t2->is_oopptr()/*->cast_to_nonconst()*/;
2999   return type;
3000 }
3001 
3002 Node* ShenandoahLoadReferenceBarrierNode::Identity(PhaseGVN* phase) {
3003   Node* value = in(ValueIn);
3004   if (!needs_barrier(phase, value)) {
3005     return value;
3006   }
3007   return this;
3008 }
3009 
3010 bool ShenandoahLoadReferenceBarrierNode::needs_barrier(PhaseGVN* phase, Node* n) {
3011   Unique_Node_List visited;
3012   return needs_barrier_impl(phase, n, visited);
3013 }
3014 
3015 bool ShenandoahLoadReferenceBarrierNode::needs_barrier_impl(PhaseGVN* phase, Node* n, Unique_Node_List &visited) {
3016   if (n == NULL) return false;
3017   if (visited.member(n)) {
3018     return false; // Been there.
3019   }
3020   visited.push(n);
3021 
3022   if (n->is_Allocate()) {
3023     // tty->print_cr("optimize barrier on alloc");
3024     return false;
3025   }
3026   if (n->is_Call()) {
3027     // tty->print_cr("optimize barrier on call");
3028     return false;
3029   }
3030 
3031   const Type* type = phase->type(n);
3032   if (type == Type::TOP) {
3033     return false;
3034   }
3035   if (type->make_ptr()->higher_equal(TypePtr::NULL_PTR)) {
3036     // tty->print_cr("optimize barrier on null");
3037     return false;
3038   }
3039   if (type->make_oopptr() && type->make_oopptr()->const_oop() != NULL) {
3040     // tty->print_cr("optimize barrier on constant");
3041     return false;
3042   }
3043 
3044   switch (n->Opcode()) {
3045     case Op_AddP:
3046       return true; // TODO: Can refine?
3047     case Op_LoadP:
3048     case Op_ShenandoahCompareAndExchangeN:
3049     case Op_ShenandoahCompareAndExchangeP:
3050     case Op_CompareAndExchangeN:
3051     case Op_CompareAndExchangeP:
3052     case Op_GetAndSetN:
3053     case Op_GetAndSetP:
3054       return true;
3055     case Op_Phi: {
3056       for (uint i = 1; i < n->req(); i++) {
3057         if (needs_barrier_impl(phase, n->in(i), visited)) return true;
3058       }
3059       return false;
3060     }
3061     case Op_CheckCastPP:
3062     case Op_CastPP:
3063       return needs_barrier_impl(phase, n->in(1), visited);
3064     case Op_Proj:
3065       return needs_barrier_impl(phase, n->in(0), visited);
3066     case Op_ShenandoahLoadReferenceBarrier:
3067       // tty->print_cr("optimize barrier on barrier");
3068       return false;
3069     case Op_Parm:
3070       // tty->print_cr("optimize barrier on input arg");
3071       return false;
3072     case Op_DecodeN:
3073     case Op_EncodeP:
3074       return needs_barrier_impl(phase, n->in(1), visited);
3075     case Op_LoadN:
3076       return true;
3077     case Op_CMoveP:
3078       return needs_barrier_impl(phase, n->in(2), visited) ||
3079              needs_barrier_impl(phase, n->in(3), visited);
3080     case Op_ShenandoahEnqueueBarrier:
3081       return needs_barrier_impl(phase, n->in(1), visited);
3082     default:
3083       break;
3084   }
3085 #ifdef ASSERT
3086   tty->print("need barrier on?: ");
3087   tty->print_cr("ins:");
3088   n->dump(2);
3089   tty->print_cr("outs:");
3090   n->dump(-2);
3091   ShouldNotReachHere();
3092 #endif
3093   return true;
3094 }
3095 
3096 ShenandoahLoadReferenceBarrierNode::Strength ShenandoahLoadReferenceBarrierNode::get_barrier_strength() {
3097   Unique_Node_List visited;
3098   Node_Stack stack(0);
3099   stack.push(this, 0);
3100   Strength strength = NONE;
3101   while (strength != STRONG && stack.size() > 0) {
3102     Node* n = stack.node();
3103     if (visited.member(n)) {
3104       stack.pop();
3105       continue;
3106     }
3107     visited.push(n);
3108     bool visit_users = false;
3109     switch (n->Opcode()) {
3110       case Op_StoreN:
3111       case Op_StoreP: {
3112         strength = STRONG;
3113         break;
3114       }
3115       case Op_CmpP: {
3116         if (!n->in(1)->bottom_type()->higher_equal(TypePtr::NULL_PTR) &&
3117             !n->in(2)->bottom_type()->higher_equal(TypePtr::NULL_PTR)) {
3118           strength = STRONG;
3119         }
3120         break;
3121       }
3122       case Op_CallStaticJava: {
3123         strength = STRONG;
3124         break;
3125       }
3126       case Op_CallDynamicJava:
3127       case Op_CallLeaf:
3128       case Op_CallLeafNoFP:
3129       case Op_CompareAndSwapL:
3130       case Op_CompareAndSwapI:
3131       case Op_CompareAndSwapB:
3132       case Op_CompareAndSwapS:
3133       case Op_CompareAndSwapN:
3134       case Op_CompareAndSwapP:
3135       case Op_CompareAndExchangeL:
3136       case Op_CompareAndExchangeI:
3137       case Op_CompareAndExchangeB:
3138       case Op_CompareAndExchangeS:
3139       case Op_CompareAndExchangeN:
3140       case Op_CompareAndExchangeP:
3141       case Op_WeakCompareAndSwapL:
3142       case Op_WeakCompareAndSwapI:
3143       case Op_WeakCompareAndSwapB:
3144       case Op_WeakCompareAndSwapS:
3145       case Op_WeakCompareAndSwapN:
3146       case Op_WeakCompareAndSwapP:
3147       case Op_ShenandoahCompareAndSwapN:
3148       case Op_ShenandoahCompareAndSwapP:
3149       case Op_ShenandoahWeakCompareAndSwapN:
3150       case Op_ShenandoahWeakCompareAndSwapP:
3151       case Op_ShenandoahCompareAndExchangeN:
3152       case Op_ShenandoahCompareAndExchangeP:
3153       case Op_GetAndSetL:
3154       case Op_GetAndSetI:
3155       case Op_GetAndSetB:
3156       case Op_GetAndSetS:
3157       case Op_GetAndSetP:
3158       case Op_GetAndSetN:
3159       case Op_GetAndAddL:
3160       case Op_GetAndAddI:
3161       case Op_GetAndAddB:
3162       case Op_GetAndAddS:
3163       case Op_ShenandoahEnqueueBarrier:
3164       case Op_FastLock:
3165       case Op_FastUnlock:
3166       case Op_Rethrow:
3167       case Op_Return:
3168       case Op_StoreB:
3169       case Op_StoreC:
3170       case Op_StoreD:
3171       case Op_StoreF:
3172       case Op_StoreL:
3173       case Op_StoreLConditional:
3174       case Op_StoreI:
3175       case Op_StoreVector:
3176       case Op_StrInflatedCopy:
3177       case Op_StrCompressedCopy:
3178       case Op_EncodeP:
3179       case Op_CastP2X:
3180       case Op_SafePoint:
3181       case Op_EncodeISOArray:
3182         strength = STRONG;
3183         break;
3184       case Op_LoadB:
3185       case Op_LoadUB:
3186       case Op_LoadUS:
3187       case Op_LoadD:
3188       case Op_LoadF:
3189       case Op_LoadL:
3190       case Op_LoadI:
3191       case Op_LoadS:
3192       case Op_LoadN:
3193       case Op_LoadP:
3194       case Op_LoadVector: {
3195         const TypePtr* adr_type = n->adr_type();
3196         int alias_idx = Compile::current()->get_alias_index(adr_type);
3197         Compile::AliasType* alias_type = Compile::current()->alias_type(alias_idx);
3198         ciField* field = alias_type->field();
3199         bool is_static = field != NULL && field->is_static();
3200         bool is_final = field != NULL && field->is_final();
3201         bool is_stable = field != NULL && field->is_stable();
3202         if (ShenandoahOptimizeStaticFinals && is_static && is_final) {
3203           // Leave strength as is.
3204         } else if (ShenandoahOptimizeInstanceFinals && !is_static && is_final) {
3205           // Leave strength as is.
3206         } else if (ShenandoahOptimizeStableFinals && (is_stable || (adr_type->isa_aryptr() && adr_type->isa_aryptr()->is_stable()))) {
3207           // Leave strength as is.
3208         } else {
3209           strength = WEAK;
3210         }
3211         break;
3212       }
3213       case Op_AryEq: {
3214         Node* n1 = n->in(2);
3215         Node* n2 = n->in(3);
3216         if (!ShenandoahOptimizeStableFinals ||
3217             !n1->bottom_type()->isa_aryptr() || !n1->bottom_type()->isa_aryptr()->is_stable() ||
3218             !n2->bottom_type()->isa_aryptr() || !n2->bottom_type()->isa_aryptr()->is_stable()) {
3219           strength = WEAK;
3220         }
3221         break;
3222       }
3223       case Op_StrEquals:
3224       case Op_StrComp:
3225       case Op_StrIndexOf:
3226       case Op_StrIndexOfChar:
3227         if (!ShenandoahOptimizeStableFinals) {
3228            strength = WEAK;
3229         }
3230         break;
3231       case Op_Conv2B:
3232       case Op_LoadRange:
3233       case Op_LoadKlass:
3234       case Op_LoadNKlass:
3235         // NONE, i.e. leave current strength as is
3236         break;
3237       case Op_AddP:
3238       case Op_CheckCastPP:
3239       case Op_CastPP:
3240       case Op_CMoveP:
3241       case Op_Phi:
3242       case Op_ShenandoahLoadReferenceBarrier:
3243         visit_users = true;
3244         break;
3245       default: {
3246 #ifdef ASSERT
3247         tty->print_cr("Unknown node in get_barrier_strength:");
3248         n->dump(1);
3249         ShouldNotReachHere();
3250 #else
3251         strength = STRONG;
3252 #endif
3253       }
3254     }
3255 #ifdef ASSERT
3256 /*
3257     if (strength == STRONG) {
3258       tty->print("strengthening node: ");
3259       n->dump();
3260     }
3261     */
3262 #endif
3263     stack.pop();
3264     if (visit_users) {
3265       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3266         Node* user = n->fast_out(i);
3267         if (user != NULL) {
3268           stack.push(user, 0);
3269         }
3270       }
3271     }
3272   }
3273   return strength;
3274 }
3275 
3276 CallStaticJavaNode* ShenandoahLoadReferenceBarrierNode::pin_and_expand_null_check(PhaseIterGVN& igvn) {
3277   Node* val = in(ValueIn);
3278 
3279   const Type* val_t = igvn.type(val);
3280 
3281   if (val_t->meet(TypePtr::NULL_PTR) != val_t &&
3282       val->Opcode() == Op_CastPP &&
3283       val->in(0) != NULL &&
3284       val->in(0)->Opcode() == Op_IfTrue &&
3285       val->in(0)->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none) &&
3286       val->in(0)->in(0)->is_If() &&
3287       val->in(0)->in(0)->in(1)->Opcode() == Op_Bool &&
3288       val->in(0)->in(0)->in(1)->as_Bool()->_test._test == BoolTest::ne &&
3289       val->in(0)->in(0)->in(1)->in(1)->Opcode() == Op_CmpP &&
3290       val->in(0)->in(0)->in(1)->in(1)->in(1) == val->in(1) &&
3291       val->in(0)->in(0)->in(1)->in(1)->in(2)->bottom_type() == TypePtr::NULL_PTR) {
3292     assert(val->in(0)->in(0)->in(1)->in(1)->in(1) == val->in(1), "");
3293     CallStaticJavaNode* unc = val->in(0)->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none);
3294     return unc;
3295   }
3296   return NULL;
3297 }