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();
 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()->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   }
 674 
 675   if (verify_no_useless_barrier) {
 676     for (int i = 0; i < barriers.length(); i++) {
 677       Node* n = barriers.at(i);
 678       if (!barriers_used.member(n)) {
 679         tty->print("XXX useless barrier"); n->dump(-2);
 680         ShouldNotReachHere();
 681       }
 682     }
 683   }
 684 }
 685 #endif
 686 
 687 bool ShenandoahBarrierC2Support::is_dominator_same_ctrl(Node* c, Node* d, Node* n, PhaseIdealLoop* phase) {
 688   // That both nodes have the same control is not sufficient to prove
 689   // domination, verify that there's no path from d to n
 690   ResourceMark rm;
 691   Unique_Node_List wq;
 692   wq.push(d);
 693   for (uint next = 0; next < wq.size(); next++) {
 694     Node *m = wq.at(next);
 695     if (m == n) {
 696       return false;
 697     }
 698     if (m->is_Phi() && m->in(0)->is_Loop()) {
 699       assert(phase->ctrl_or_self(m->in(LoopNode::EntryControl)) != c, "following loop entry should lead to new control");
 700     } else {
 701       for (uint i = 0; i < m->req(); i++) {
 702         if (m->in(i) != NULL && phase->ctrl_or_self(m->in(i)) == c) {
 703           wq.push(m->in(i));
 704         }
 705       }
 706     }
 707   }
 708   return true;
 709 }
 710 
 711 bool ShenandoahBarrierC2Support::is_dominator(Node* d_c, Node* n_c, Node* d, Node* n, PhaseIdealLoop* phase) {
 712   if (d_c != n_c) {
 713     return phase->is_dominator(d_c, n_c);
 714   }
 715   return is_dominator_same_ctrl(d_c, d, n, phase);
 716 }
 717 
 718 Node* next_mem(Node* mem, int alias) {
 719   Node* res = NULL;
 720   if (mem->is_Proj()) {
 721     res = mem->in(0);
 722   } else if (mem->is_SafePoint() || mem->is_MemBar()) {
 723     res = mem->in(TypeFunc::Memory);
 724   } else if (mem->is_Phi()) {
 725     res = mem->in(1);
 726   } else if (mem->is_MergeMem()) {
 727     res = mem->as_MergeMem()->memory_at(alias);
 728   } else if (mem->is_Store() || mem->is_LoadStore() || mem->is_ClearArray()) {
 729     assert(alias = Compile::AliasIdxRaw, "following raw memory can't lead to a barrier");
 730     res = mem->in(MemNode::Memory);
 731   } else {
 732 #ifdef ASSERT
 733     mem->dump();
 734 #endif
 735     ShouldNotReachHere();
 736   }
 737   return res;
 738 }
 739 
 740 Node* ShenandoahBarrierC2Support::no_branches(Node* c, Node* dom, bool allow_one_proj, PhaseIdealLoop* phase) {
 741   Node* iffproj = NULL;
 742   while (c != dom) {
 743     Node* next = phase->idom(c);
 744     assert(next->unique_ctrl_out() == c || c->is_Proj() || c->is_Region(), "multiple control flow out but no proj or region?");
 745     if (c->is_Region()) {
 746       ResourceMark rm;
 747       Unique_Node_List wq;
 748       wq.push(c);
 749       for (uint i = 0; i < wq.size(); i++) {
 750         Node *n = wq.at(i);
 751         if (n == next) {
 752           continue;
 753         }
 754         if (n->is_Region()) {
 755           for (uint j = 1; j < n->req(); j++) {
 756             wq.push(n->in(j));
 757           }
 758         } else {
 759           wq.push(n->in(0));
 760         }
 761       }
 762       for (uint i = 0; i < wq.size(); i++) {
 763         Node *n = wq.at(i);
 764         assert(n->is_CFG(), "");
 765         if (n->is_Multi()) {
 766           for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
 767             Node* u = n->fast_out(j);
 768             if (u->is_CFG()) {
 769               if (!wq.member(u) && !u->as_Proj()->is_uncommon_trap_proj(Deoptimization::Reason_none)) {
 770                 return NodeSentinel;
 771               }
 772             }
 773           }
 774         }
 775       }
 776     } else  if (c->is_Proj()) {
 777       if (c->is_IfProj()) {
 778         if (c->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none) != NULL) {
 779           // continue;
 780         } else {
 781           if (!allow_one_proj) {
 782             return NodeSentinel;
 783           }
 784           if (iffproj == NULL) {
 785             iffproj = c;
 786           } else {
 787             return NodeSentinel;
 788           }
 789         }
 790       } else if (c->Opcode() == Op_JumpProj) {
 791         return NodeSentinel; // unsupported
 792       } else if (c->Opcode() == Op_CatchProj) {
 793         return NodeSentinel; // unsupported
 794       } else if (c->Opcode() == Op_CProj && next->Opcode() == Op_NeverBranch) {
 795         return NodeSentinel; // unsupported
 796       } else {
 797         assert(next->unique_ctrl_out() == c, "unsupported branch pattern");
 798       }
 799     }
 800     c = next;
 801   }
 802   return iffproj;
 803 }
 804 
 805 Node* ShenandoahBarrierC2Support::dom_mem(Node* mem, Node* ctrl, int alias, Node*& mem_ctrl, PhaseIdealLoop* phase) {
 806   ResourceMark rm;
 807   VectorSet wq(Thread::current()->resource_area());
 808   wq.set(mem->_idx);
 809   mem_ctrl = phase->ctrl_or_self(mem);
 810   while (!phase->is_dominator(mem_ctrl, ctrl) || mem_ctrl == ctrl) {
 811     mem = next_mem(mem, alias);
 812     if (wq.test_set(mem->_idx)) {
 813       return NULL;
 814     }
 815     mem_ctrl = phase->ctrl_or_self(mem);
 816   }
 817   if (mem->is_MergeMem()) {
 818     mem = mem->as_MergeMem()->memory_at(alias);
 819     mem_ctrl = phase->ctrl_or_self(mem);
 820   }
 821   return mem;
 822 }
 823 
 824 Node* ShenandoahBarrierC2Support::find_bottom_mem(Node* ctrl, PhaseIdealLoop* phase) {
 825   Node* mem = NULL;
 826   Node* c = ctrl;
 827   do {
 828     if (c->is_Region()) {
 829       Node* phi_bottom = NULL;
 830       for (DUIterator_Fast imax, i = c->fast_outs(imax); i < imax && mem == NULL; i++) {
 831         Node* u = c->fast_out(i);
 832         if (u->is_Phi() && u->bottom_type() == Type::MEMORY) {
 833           if (u->adr_type() == TypePtr::BOTTOM) {
 834             mem = u;
 835           }
 836         }
 837       }
 838     } else {
 839       if (c->is_Call() && c->as_Call()->adr_type() != NULL) {
 840         CallProjections projs;
 841         c->as_Call()->extract_projections(&projs, true, false);
 842         if (projs.fallthrough_memproj != NULL) {
 843           if (projs.fallthrough_memproj->adr_type() == TypePtr::BOTTOM) {
 844             if (projs.catchall_memproj == NULL) {
 845               mem = projs.fallthrough_memproj;
 846             } else {
 847               if (phase->is_dominator(projs.fallthrough_catchproj, ctrl)) {
 848                 mem = projs.fallthrough_memproj;
 849               } else {
 850                 assert(phase->is_dominator(projs.catchall_catchproj, ctrl), "one proj must dominate barrier");
 851                 mem = projs.catchall_memproj;
 852               }
 853             }
 854           }
 855         } else {
 856           Node* proj = c->as_Call()->proj_out(TypeFunc::Memory);
 857           if (proj != NULL &&
 858               proj->adr_type() == TypePtr::BOTTOM) {
 859             mem = proj;
 860           }
 861         }
 862       } else {
 863         for (DUIterator_Fast imax, i = c->fast_outs(imax); i < imax; i++) {
 864           Node* u = c->fast_out(i);
 865           if (u->is_Proj() &&
 866               u->bottom_type() == Type::MEMORY &&
 867               u->adr_type() == TypePtr::BOTTOM) {
 868               assert(c->is_SafePoint() || c->is_MemBar() || c->is_Start(), "");
 869               assert(mem == NULL, "only one proj");
 870               mem = u;
 871           }
 872         }
 873         assert(!c->is_Call() || c->as_Call()->adr_type() != NULL || mem == NULL, "no mem projection expected");
 874       }
 875     }
 876     c = phase->idom(c);
 877   } while (mem == NULL);
 878   return mem;
 879 }
 880 
 881 void ShenandoahBarrierC2Support::follow_barrier_uses(Node* n, Node* ctrl, Unique_Node_List& uses, PhaseIdealLoop* phase) {
 882   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
 883     Node* u = n->fast_out(i);
 884     if (!u->is_CFG() && phase->get_ctrl(u) == ctrl && (!u->is_Phi() || !u->in(0)->is_Loop() || u->in(LoopNode::LoopBackControl) != n)) {
 885       uses.push(u);
 886     }
 887   }
 888 }
 889 
 890 static void hide_strip_mined_loop(OuterStripMinedLoopNode* outer, CountedLoopNode* inner, PhaseIdealLoop* phase) {
 891   OuterStripMinedLoopEndNode* le = inner->outer_loop_end();
 892   Node* new_outer = new LoopNode(outer->in(LoopNode::EntryControl), outer->in(LoopNode::LoopBackControl));
 893   phase->register_control(new_outer, phase->get_loop(outer), outer->in(LoopNode::EntryControl));
 894   Node* new_le = new IfNode(le->in(0), le->in(1), le->_prob, le->_fcnt);
 895   phase->register_control(new_le, phase->get_loop(le), le->in(0));
 896   phase->lazy_replace(outer, new_outer);
 897   phase->lazy_replace(le, new_le);
 898   inner->clear_strip_mined();
 899 }
 900 
 901 void ShenandoahBarrierC2Support::test_heap_stable(Node*& ctrl, Node* raw_mem, Node*& heap_stable_ctrl,
 902                                                   PhaseIdealLoop* phase) {
 903   IdealLoopTree* loop = phase->get_loop(ctrl);
 904   Node* thread = new ThreadLocalNode();
 905   phase->register_new_node(thread, ctrl);
 906   Node* offset = phase->igvn().MakeConX(in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 907   phase->set_ctrl(offset, phase->C->root());
 908   Node* gc_state_addr = new AddPNode(phase->C->top(), thread, offset);
 909   phase->register_new_node(gc_state_addr, ctrl);
 910   uint gc_state_idx = Compile::AliasIdxRaw;
 911   const TypePtr* gc_state_adr_type = NULL; // debug-mode-only argument
 912   debug_only(gc_state_adr_type = phase->C->get_adr_type(gc_state_idx));
 913 
 914   Node* gc_state = new LoadBNode(ctrl, raw_mem, gc_state_addr, gc_state_adr_type, TypeInt::BYTE, MemNode::unordered);
 915   phase->register_new_node(gc_state, ctrl);
 916   Node* heap_stable_and = new AndINode(gc_state, phase->igvn().intcon(ShenandoahHeap::HAS_FORWARDED));
 917   phase->register_new_node(heap_stable_and, ctrl);
 918   Node* heap_stable_cmp = new CmpINode(heap_stable_and, phase->igvn().zerocon(T_INT));
 919   phase->register_new_node(heap_stable_cmp, ctrl);
 920   Node* heap_stable_test = new BoolNode(heap_stable_cmp, BoolTest::ne);
 921   phase->register_new_node(heap_stable_test, ctrl);
 922   IfNode* heap_stable_iff = new IfNode(ctrl, heap_stable_test, PROB_UNLIKELY(0.999), COUNT_UNKNOWN);
 923   phase->register_control(heap_stable_iff, loop, ctrl);
 924 
 925   heap_stable_ctrl = new IfFalseNode(heap_stable_iff);
 926   phase->register_control(heap_stable_ctrl, loop, heap_stable_iff);
 927   ctrl = new IfTrueNode(heap_stable_iff);
 928   phase->register_control(ctrl, loop, heap_stable_iff);
 929 
 930   assert(is_heap_stable_test(heap_stable_iff), "Should match the shape");
 931 }
 932 
 933 void ShenandoahBarrierC2Support::test_null(Node*& ctrl, Node* val, Node*& null_ctrl, PhaseIdealLoop* phase) {
 934   const Type* val_t = phase->igvn().type(val);
 935   if (val_t->meet(TypePtr::NULL_PTR) == val_t) {
 936     IdealLoopTree* loop = phase->get_loop(ctrl);
 937     Node* null_cmp = new CmpPNode(val, phase->igvn().zerocon(T_OBJECT));
 938     phase->register_new_node(null_cmp, ctrl);
 939     Node* null_test = new BoolNode(null_cmp, BoolTest::ne);
 940     phase->register_new_node(null_test, ctrl);
 941     IfNode* null_iff = new IfNode(ctrl, null_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
 942     phase->register_control(null_iff, loop, ctrl);
 943     ctrl = new IfTrueNode(null_iff);
 944     phase->register_control(ctrl, loop, null_iff);
 945     null_ctrl = new IfFalseNode(null_iff);
 946     phase->register_control(null_ctrl, loop, null_iff);
 947   }
 948 }
 949 
 950 Node* ShenandoahBarrierC2Support::clone_null_check(Node*& c, Node* val, Node* unc_ctrl, PhaseIdealLoop* phase) {
 951   IdealLoopTree *loop = phase->get_loop(c);
 952   Node* iff = unc_ctrl->in(0);
 953   assert(iff->is_If(), "broken");
 954   Node* new_iff = iff->clone();
 955   new_iff->set_req(0, c);
 956   phase->register_control(new_iff, loop, c);
 957   Node* iffalse = new IfFalseNode(new_iff->as_If());
 958   phase->register_control(iffalse, loop, new_iff);
 959   Node* iftrue = new IfTrueNode(new_iff->as_If());
 960   phase->register_control(iftrue, loop, new_iff);
 961   c = iftrue;
 962   const Type *t = phase->igvn().type(val);
 963   assert(val->Opcode() == Op_CastPP, "expect cast to non null here");
 964   Node* uncasted_val = val->in(1);
 965   val = new CastPPNode(uncasted_val, t);
 966   val->init_req(0, c);
 967   phase->register_new_node(val, c);
 968   return val;
 969 }
 970 
 971 void ShenandoahBarrierC2Support::fix_null_check(Node* unc, Node* unc_ctrl, Node* new_unc_ctrl,
 972                                                 Unique_Node_List& uses, PhaseIdealLoop* phase) {
 973   IfNode* iff = unc_ctrl->in(0)->as_If();
 974   Node* proj = iff->proj_out(0);
 975   assert(proj != unc_ctrl, "bad projection");
 976   Node* use = proj->unique_ctrl_out();
 977 
 978   assert(use == unc || use->is_Region(), "what else?");
 979 
 980   uses.clear();
 981   if (use == unc) {
 982     phase->set_idom(use, new_unc_ctrl, phase->dom_depth(use));
 983     for (uint i = 1; i < unc->req(); i++) {
 984       Node* n = unc->in(i);
 985       if (phase->has_ctrl(n) && phase->get_ctrl(n) == proj) {
 986         uses.push(n);
 987       }
 988     }
 989   } else {
 990     assert(use->is_Region(), "what else?");
 991     uint idx = 1;
 992     for (; use->in(idx) != proj; idx++);
 993     for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
 994       Node* u = use->fast_out(i);
 995       if (u->is_Phi() && phase->get_ctrl(u->in(idx)) == proj) {
 996         uses.push(u->in(idx));
 997       }
 998     }
 999   }
1000   for(uint next = 0; next < uses.size(); next++ ) {
1001     Node *n = uses.at(next);
1002     assert(phase->get_ctrl(n) == proj, "bad control");
1003     phase->set_ctrl_and_loop(n, new_unc_ctrl);
1004     if (n->in(0) == proj) {
1005       phase->igvn().replace_input_of(n, 0, new_unc_ctrl);
1006     }
1007     for (uint i = 0; i < n->req(); i++) {
1008       Node* m = n->in(i);
1009       if (m != NULL && phase->has_ctrl(m) && phase->get_ctrl(m) == proj) {
1010         uses.push(m);
1011       }
1012     }
1013   }
1014 
1015   phase->igvn().rehash_node_delayed(use);
1016   int nb = use->replace_edge(proj, new_unc_ctrl);
1017   assert(nb == 1, "only use expected");
1018 }
1019 
1020 void ShenandoahBarrierC2Support::in_cset_fast_test(Node*& ctrl, Node*& not_cset_ctrl, Node* val, Node* raw_mem, PhaseIdealLoop* phase) {
1021   IdealLoopTree *loop = phase->get_loop(ctrl);
1022   Node* raw_rbtrue = new CastP2XNode(ctrl, val);
1023   phase->register_new_node(raw_rbtrue, ctrl);
1024   Node* cset_offset = new URShiftXNode(raw_rbtrue, phase->igvn().intcon(ShenandoahHeapRegion::region_size_bytes_shift_jint()));
1025   phase->register_new_node(cset_offset, ctrl);
1026   Node* in_cset_fast_test_base_addr = phase->igvn().makecon(TypeRawPtr::make(ShenandoahHeap::in_cset_fast_test_addr()));
1027   phase->set_ctrl(in_cset_fast_test_base_addr, phase->C->root());
1028   Node* in_cset_fast_test_adr = new AddPNode(phase->C->top(), in_cset_fast_test_base_addr, cset_offset);
1029   phase->register_new_node(in_cset_fast_test_adr, ctrl);
1030   uint in_cset_fast_test_idx = Compile::AliasIdxRaw;
1031   const TypePtr* in_cset_fast_test_adr_type = NULL; // debug-mode-only argument
1032   debug_only(in_cset_fast_test_adr_type = phase->C->get_adr_type(in_cset_fast_test_idx));
1033   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);
1034   phase->register_new_node(in_cset_fast_test_load, ctrl);
1035   Node* in_cset_fast_test_cmp = new CmpINode(in_cset_fast_test_load, phase->igvn().zerocon(T_INT));
1036   phase->register_new_node(in_cset_fast_test_cmp, ctrl);
1037   Node* in_cset_fast_test_test = new BoolNode(in_cset_fast_test_cmp, BoolTest::eq);
1038   phase->register_new_node(in_cset_fast_test_test, ctrl);
1039   IfNode* in_cset_fast_test_iff = new IfNode(ctrl, in_cset_fast_test_test, PROB_UNLIKELY(0.999), COUNT_UNKNOWN);
1040   phase->register_control(in_cset_fast_test_iff, loop, ctrl);
1041 
1042   not_cset_ctrl = new IfTrueNode(in_cset_fast_test_iff);
1043   phase->register_control(not_cset_ctrl, loop, in_cset_fast_test_iff);
1044 
1045   ctrl = new IfFalseNode(in_cset_fast_test_iff);
1046   phase->register_control(ctrl, loop, in_cset_fast_test_iff);
1047 }
1048 
1049 void ShenandoahBarrierC2Support::call_lrb_stub(Node*& ctrl, Node*& val, Node*& result_mem, Node* raw_mem, bool is_native, PhaseIdealLoop* phase) {
1050   IdealLoopTree*loop = phase->get_loop(ctrl);
1051   const TypePtr* obj_type = phase->igvn().type(val)->is_oopptr()->cast_to_nonconst();
1052 
1053   // The slow path stub consumes and produces raw memory in addition
1054   // to the existing memory edges
1055   Node* base = find_bottom_mem(ctrl, phase);
1056   MergeMemNode* mm = MergeMemNode::make(base);
1057   mm->set_memory_at(Compile::AliasIdxRaw, raw_mem);
1058   phase->register_new_node(mm, ctrl);
1059 
1060   address calladdr = is_native ? CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_native)
1061                                : CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier);
1062   const char* name = is_native ? "oop_load_from_native_barrier" : "load_reference_barrier";
1063   Node* call = new CallLeafNode(ShenandoahBarrierSetC2::shenandoah_load_reference_barrier_Type(), calladdr, name, TypeRawPtr::BOTTOM);
1064   call->init_req(TypeFunc::Control, ctrl);
1065   call->init_req(TypeFunc::I_O, phase->C->top());
1066   call->init_req(TypeFunc::Memory, mm);
1067   call->init_req(TypeFunc::FramePtr, phase->C->top());
1068   call->init_req(TypeFunc::ReturnAdr, phase->C->top());
1069   call->init_req(TypeFunc::Parms, val);
1070   phase->register_control(call, loop, ctrl);
1071   ctrl = new ProjNode(call, TypeFunc::Control);
1072   phase->register_control(ctrl, loop, call);
1073   result_mem = new ProjNode(call, TypeFunc::Memory);
1074   phase->register_new_node(result_mem, call);
1075   val = new ProjNode(call, TypeFunc::Parms);
1076   phase->register_new_node(val, call);
1077   val = new CheckCastPPNode(ctrl, val, obj_type);
1078   phase->register_new_node(val, ctrl);
1079 }
1080 
1081 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) {
1082   Node* ctrl = phase->get_ctrl(barrier);
1083   Node* init_raw_mem = fixer.find_mem(ctrl, barrier);
1084 
1085   // Update the control of all nodes that should be after the
1086   // barrier control flow
1087   uses.clear();
1088   // Every node that is control dependent on the barrier's input
1089   // control will be after the expanded barrier. The raw memory (if
1090   // its memory is control dependent on the barrier's input control)
1091   // must stay above the barrier.
1092   uses_to_ignore.clear();
1093   if (phase->has_ctrl(init_raw_mem) && phase->get_ctrl(init_raw_mem) == ctrl && !init_raw_mem->is_Phi()) {
1094     uses_to_ignore.push(init_raw_mem);
1095   }
1096   for (uint next = 0; next < uses_to_ignore.size(); next++) {
1097     Node *n = uses_to_ignore.at(next);
1098     for (uint i = 0; i < n->req(); i++) {
1099       Node* in = n->in(i);
1100       if (in != NULL && phase->has_ctrl(in) && phase->get_ctrl(in) == ctrl) {
1101         uses_to_ignore.push(in);
1102       }
1103     }
1104   }
1105   for (DUIterator_Fast imax, i = ctrl->fast_outs(imax); i < imax; i++) {
1106     Node* u = ctrl->fast_out(i);
1107     if (u->_idx < last &&
1108         u != barrier &&
1109         !uses_to_ignore.member(u) &&
1110         (u->in(0) != ctrl || (!u->is_Region() && !u->is_Phi())) &&
1111         (ctrl->Opcode() != Op_CatchProj || u->Opcode() != Op_CreateEx)) {
1112       Node* old_c = phase->ctrl_or_self(u);
1113       Node* c = old_c;
1114       if (c != ctrl ||
1115           is_dominator_same_ctrl(old_c, barrier, u, phase) ||
1116           ShenandoahBarrierSetC2::is_shenandoah_state_load(u)) {
1117         phase->igvn().rehash_node_delayed(u);
1118         int nb = u->replace_edge(ctrl, region);
1119         if (u->is_CFG()) {
1120           if (phase->idom(u) == ctrl) {
1121             phase->set_idom(u, region, phase->dom_depth(region));
1122           }
1123         } else if (phase->get_ctrl(u) == ctrl) {
1124           assert(u != init_raw_mem, "should leave input raw mem above the barrier");
1125           uses.push(u);
1126         }
1127         assert(nb == 1, "more than 1 ctrl input?");
1128         --i, imax -= nb;
1129       }
1130     }
1131   }
1132 }
1133 
1134 static Node* create_phis_on_call_return(Node* ctrl, Node* c, Node* n, Node* n_clone, const CallProjections& projs, PhaseIdealLoop* phase) {
1135   Node* region = NULL;
1136   while (c != ctrl) {
1137     if (c->is_Region()) {
1138       region = c;
1139     }
1140     c = phase->idom(c);
1141   }
1142   assert(region != NULL, "");
1143   Node* phi = new PhiNode(region, n->bottom_type());
1144   for (uint j = 1; j < region->req(); j++) {
1145     Node* in = region->in(j);
1146     if (phase->is_dominator(projs.fallthrough_catchproj, in)) {
1147       phi->init_req(j, n);
1148     } else if (phase->is_dominator(projs.catchall_catchproj, in)) {
1149       phi->init_req(j, n_clone);
1150     } else {
1151       phi->init_req(j, create_phis_on_call_return(ctrl, in, n, n_clone, projs, phase));
1152     }
1153   }
1154   phase->register_new_node(phi, region);
1155   return phi;
1156 }
1157 
1158 void ShenandoahBarrierC2Support::pin_and_expand(PhaseIdealLoop* phase) {
1159   ShenandoahBarrierSetC2State* state = ShenandoahBarrierSetC2::bsc2()->state();
1160 
1161   Unique_Node_List uses;
1162   for (int i = 0; i < state->enqueue_barriers_count(); i++) {
1163     Node* barrier = state->enqueue_barrier(i);
1164     Node* ctrl = phase->get_ctrl(barrier);
1165     IdealLoopTree* loop = phase->get_loop(ctrl);
1166     if (loop->_head->is_OuterStripMinedLoop()) {
1167       // Expanding a barrier here will break loop strip mining
1168       // verification. Transform the loop so the loop nest doesn't
1169       // appear as strip mined.
1170       OuterStripMinedLoopNode* outer = loop->_head->as_OuterStripMinedLoop();
1171       hide_strip_mined_loop(outer, outer->unique_ctrl_out()->as_CountedLoop(), phase);
1172     }
1173   }
1174 
1175   Node_Stack stack(0);
1176   Node_List clones;
1177   for (int i = state->load_reference_barriers_count() - 1; i >= 0; i--) {
1178     ShenandoahLoadReferenceBarrierNode* lrb = state->load_reference_barrier(i);
1179     if (lrb->get_barrier_strength() == ShenandoahLoadReferenceBarrierNode::NONE) {
1180       continue;
1181     }
1182 
1183     Node* ctrl = phase->get_ctrl(lrb);
1184     Node* val = lrb->in(ShenandoahLoadReferenceBarrierNode::ValueIn);
1185 
1186     CallStaticJavaNode* unc = NULL;
1187     Node* unc_ctrl = NULL;
1188     Node* uncasted_val = val;
1189 
1190     for (DUIterator_Fast imax, i = lrb->fast_outs(imax); i < imax; i++) {
1191       Node* u = lrb->fast_out(i);
1192       if (u->Opcode() == Op_CastPP &&
1193           u->in(0) != NULL &&
1194           phase->is_dominator(u->in(0), ctrl)) {
1195         const Type* u_t = phase->igvn().type(u);
1196 
1197         if (u_t->meet(TypePtr::NULL_PTR) != u_t &&
1198             u->in(0)->Opcode() == Op_IfTrue &&
1199             u->in(0)->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none) &&
1200             u->in(0)->in(0)->is_If() &&
1201             u->in(0)->in(0)->in(1)->Opcode() == Op_Bool &&
1202             u->in(0)->in(0)->in(1)->as_Bool()->_test._test == BoolTest::ne &&
1203             u->in(0)->in(0)->in(1)->in(1)->Opcode() == Op_CmpP &&
1204             u->in(0)->in(0)->in(1)->in(1)->in(1) == val &&
1205             u->in(0)->in(0)->in(1)->in(1)->in(2)->bottom_type() == TypePtr::NULL_PTR) {
1206           IdealLoopTree* loop = phase->get_loop(ctrl);
1207           IdealLoopTree* unc_loop = phase->get_loop(u->in(0));
1208 
1209           if (!unc_loop->is_member(loop)) {
1210             continue;
1211           }
1212 
1213           Node* branch = no_branches(ctrl, u->in(0), false, phase);
1214           assert(branch == NULL || branch == NodeSentinel, "was not looking for a branch");
1215           if (branch == NodeSentinel) {
1216             continue;
1217           }
1218 
1219           phase->igvn().replace_input_of(u, 1, val);
1220           phase->igvn().replace_input_of(lrb, ShenandoahLoadReferenceBarrierNode::ValueIn, u);
1221           phase->set_ctrl(u, u->in(0));
1222           phase->set_ctrl(lrb, u->in(0));
1223           unc = u->in(0)->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none);
1224           unc_ctrl = u->in(0);
1225           val = u;
1226 
1227           for (DUIterator_Fast jmax, j = val->fast_outs(jmax); j < jmax; j++) {
1228             Node* u = val->fast_out(j);
1229             if (u == lrb) continue;
1230             phase->igvn().rehash_node_delayed(u);
1231             int nb = u->replace_edge(val, lrb);
1232             --j; jmax -= nb;
1233           }
1234 
1235           RegionNode* r = new RegionNode(3);
1236           IfNode* iff = unc_ctrl->in(0)->as_If();
1237 
1238           Node* ctrl_use = unc_ctrl->unique_ctrl_out();
1239           Node* unc_ctrl_clone = unc_ctrl->clone();
1240           phase->register_control(unc_ctrl_clone, loop, iff);
1241           Node* c = unc_ctrl_clone;
1242           Node* new_cast = clone_null_check(c, val, unc_ctrl_clone, phase);
1243           r->init_req(1, new_cast->in(0)->in(0)->as_If()->proj_out(0));
1244 
1245           phase->igvn().replace_input_of(unc_ctrl, 0, c->in(0));
1246           phase->set_idom(unc_ctrl, c->in(0), phase->dom_depth(unc_ctrl));
1247           phase->lazy_replace(c, unc_ctrl);
1248           c = NULL;;
1249           phase->igvn().replace_input_of(val, 0, unc_ctrl_clone);
1250           phase->set_ctrl(val, unc_ctrl_clone);
1251 
1252           IfNode* new_iff = new_cast->in(0)->in(0)->as_If();
1253           fix_null_check(unc, unc_ctrl_clone, r, uses, phase);
1254           Node* iff_proj = iff->proj_out(0);
1255           r->init_req(2, iff_proj);
1256           phase->register_control(r, phase->ltree_root(), iff);
1257 
1258           Node* new_bol = new_iff->in(1)->clone();
1259           Node* new_cmp = new_bol->in(1)->clone();
1260           assert(new_cmp->Opcode() == Op_CmpP, "broken");
1261           assert(new_cmp->in(1) == val->in(1), "broken");
1262           new_bol->set_req(1, new_cmp);
1263           new_cmp->set_req(1, lrb);
1264           phase->register_new_node(new_bol, new_iff->in(0));
1265           phase->register_new_node(new_cmp, new_iff->in(0));
1266           phase->igvn().replace_input_of(new_iff, 1, new_bol);
1267           phase->igvn().replace_input_of(new_cast, 1, lrb);
1268 
1269           for (DUIterator_Fast imax, i = lrb->fast_outs(imax); i < imax; i++) {
1270             Node* u = lrb->fast_out(i);
1271             if (u == new_cast || u == new_cmp) {
1272               continue;
1273             }
1274             phase->igvn().rehash_node_delayed(u);
1275             int nb = u->replace_edge(lrb, new_cast);
1276             assert(nb > 0, "no update?");
1277             --i; imax -= nb;
1278           }
1279 
1280           for (DUIterator_Fast imax, i = val->fast_outs(imax); i < imax; i++) {
1281             Node* u = val->fast_out(i);
1282             if (u == lrb) {
1283               continue;
1284             }
1285             phase->igvn().rehash_node_delayed(u);
1286             int nb = u->replace_edge(val, new_cast);
1287             assert(nb > 0, "no update?");
1288             --i; imax -= nb;
1289           }
1290 
1291           ctrl = unc_ctrl_clone;
1292           phase->set_ctrl_and_loop(lrb, ctrl);
1293           break;
1294         }
1295       }
1296     }
1297     if ((ctrl->is_Proj() && ctrl->in(0)->is_CallJava()) || ctrl->is_CallJava()) {
1298       CallNode* call = ctrl->is_Proj() ? ctrl->in(0)->as_CallJava() : ctrl->as_CallJava();
1299       CallProjections projs;
1300       call->extract_projections(&projs, false, false);
1301 
1302       Node* lrb_clone = lrb->clone();
1303       phase->register_new_node(lrb_clone, projs.catchall_catchproj);
1304       phase->set_ctrl(lrb, projs.fallthrough_catchproj);
1305 
1306       stack.push(lrb, 0);
1307       clones.push(lrb_clone);
1308 
1309       do {
1310         assert(stack.size() == clones.size(), "");
1311         Node* n = stack.node();
1312 #ifdef ASSERT
1313         if (n->is_Load()) {
1314           Node* mem = n->in(MemNode::Memory);
1315           for (DUIterator_Fast jmax, j = mem->fast_outs(jmax); j < jmax; j++) {
1316             Node* u = mem->fast_out(j);
1317             assert(!u->is_Store() || !u->is_LoadStore() || phase->get_ctrl(u) != ctrl, "anti dependent store?");
1318           }
1319         }
1320 #endif
1321         uint idx = stack.index();
1322         Node* n_clone = clones.at(clones.size()-1);
1323         if (idx < n->outcnt()) {
1324           Node* u = n->raw_out(idx);
1325           Node* c = phase->ctrl_or_self(u);
1326           if (phase->is_dominator(call, c) && phase->is_dominator(c, projs.fallthrough_proj)) {
1327             stack.set_index(idx+1);
1328             assert(!u->is_CFG(), "");
1329             stack.push(u, 0);
1330             Node* u_clone = u->clone();
1331             int nb = u_clone->replace_edge(n, n_clone);
1332             assert(nb > 0, "should have replaced some uses");
1333             phase->register_new_node(u_clone, projs.catchall_catchproj);
1334             clones.push(u_clone);
1335             phase->set_ctrl(u, projs.fallthrough_catchproj);
1336           } else {
1337             bool replaced = false;
1338             if (u->is_Phi()) {
1339               for (uint k = 1; k < u->req(); k++) {
1340                 if (u->in(k) == n) {
1341                   if (phase->is_dominator(projs.catchall_catchproj, u->in(0)->in(k))) {
1342                     phase->igvn().replace_input_of(u, k, n_clone);
1343                     replaced = true;
1344                   } else if (!phase->is_dominator(projs.fallthrough_catchproj, u->in(0)->in(k))) {
1345                     phase->igvn().replace_input_of(u, k, create_phis_on_call_return(ctrl, u->in(0)->in(k), n, n_clone, projs, phase));
1346                     replaced = true;
1347                   }
1348                 }
1349               }
1350             } else {
1351               if (phase->is_dominator(projs.catchall_catchproj, c)) {
1352                 phase->igvn().rehash_node_delayed(u);
1353                 int nb = u->replace_edge(n, n_clone);
1354                 assert(nb > 0, "should have replaced some uses");
1355                 replaced = true;
1356               } else if (!phase->is_dominator(projs.fallthrough_catchproj, c)) {
1357                 phase->igvn().rehash_node_delayed(u);
1358                 int nb = u->replace_edge(n, create_phis_on_call_return(ctrl, c, n, n_clone, projs, phase));
1359                 assert(nb > 0, "should have replaced some uses");
1360                 replaced = true;
1361               }
1362             }
1363             if (!replaced) {
1364               stack.set_index(idx+1);
1365             }
1366           }
1367         } else {
1368           stack.pop();
1369           clones.pop();
1370         }
1371       } while (stack.size() > 0);
1372       assert(stack.size() == 0 && clones.size() == 0, "");
1373     }
1374   }
1375 
1376   for (int i = 0; i < state->load_reference_barriers_count(); i++) {
1377     ShenandoahLoadReferenceBarrierNode* lrb = state->load_reference_barrier(i);
1378     if (lrb->get_barrier_strength() == ShenandoahLoadReferenceBarrierNode::NONE) {
1379       continue;
1380     }
1381     Node* ctrl = phase->get_ctrl(lrb);
1382     IdealLoopTree* loop = phase->get_loop(ctrl);
1383     if (loop->_head->is_OuterStripMinedLoop()) {
1384       // Expanding a barrier here will break loop strip mining
1385       // verification. Transform the loop so the loop nest doesn't
1386       // appear as strip mined.
1387       OuterStripMinedLoopNode* outer = loop->_head->as_OuterStripMinedLoop();
1388       hide_strip_mined_loop(outer, outer->unique_ctrl_out()->as_CountedLoop(), phase);
1389     }
1390   }
1391 
1392   // Expand load-reference-barriers
1393   MemoryGraphFixer fixer(Compile::AliasIdxRaw, true, phase);
1394   Unique_Node_List uses_to_ignore;
1395   for (int i = state->load_reference_barriers_count() - 1; i >= 0; i--) {
1396     ShenandoahLoadReferenceBarrierNode* lrb = state->load_reference_barrier(i);
1397     if (lrb->get_barrier_strength() == ShenandoahLoadReferenceBarrierNode::NONE) {
1398       phase->igvn().replace_node(lrb, lrb->in(ShenandoahLoadReferenceBarrierNode::ValueIn));
1399       continue;
1400     }
1401     uint last = phase->C->unique();
1402     Node* ctrl = phase->get_ctrl(lrb);
1403     Node* val = lrb->in(ShenandoahLoadReferenceBarrierNode::ValueIn);
1404 
1405 
1406     Node* orig_ctrl = ctrl;
1407 
1408     Node* raw_mem = fixer.find_mem(ctrl, lrb);
1409     Node* init_raw_mem = raw_mem;
1410     Node* raw_mem_for_ctrl = fixer.find_mem(ctrl, NULL);
1411 
1412     IdealLoopTree *loop = phase->get_loop(ctrl);
1413     CallStaticJavaNode* unc = lrb->pin_and_expand_null_check(phase->igvn());
1414     Node* unc_ctrl = NULL;
1415     if (unc != NULL) {
1416       if (val->in(ShenandoahLoadReferenceBarrierNode::Control) != ctrl) {
1417         unc = NULL;
1418       } else {
1419         unc_ctrl = val->in(ShenandoahLoadReferenceBarrierNode::Control);
1420       }
1421     }
1422 
1423     Node* uncasted_val = val;
1424     if (unc != NULL) {
1425       uncasted_val = val->in(1);
1426     }
1427 
1428     Node* heap_stable_ctrl = NULL;
1429     Node* null_ctrl = NULL;
1430 
1431     assert(val->bottom_type()->make_oopptr(), "need oop");
1432     assert(val->bottom_type()->make_oopptr()->const_oop() == NULL, "expect non-constant");
1433 
1434     enum { _heap_stable = 1, _not_cset, _fwded, _evac_path, _null_path, PATH_LIMIT };
1435     Node* region = new RegionNode(PATH_LIMIT);
1436     Node* val_phi = new PhiNode(region, uncasted_val->bottom_type()->is_oopptr());
1437     Node* raw_mem_phi = PhiNode::make(region, raw_mem, Type::MEMORY, TypeRawPtr::BOTTOM);
1438 
1439     // Stable path.
1440     test_heap_stable(ctrl, raw_mem, heap_stable_ctrl, phase);
1441     IfNode* heap_stable_iff = heap_stable_ctrl->in(0)->as_If();
1442 
1443     // Heap stable case
1444     region->init_req(_heap_stable, heap_stable_ctrl);
1445     val_phi->init_req(_heap_stable, uncasted_val);
1446     raw_mem_phi->init_req(_heap_stable, raw_mem);
1447 
1448     Node* reg2_ctrl = NULL;
1449     // Null case
1450     test_null(ctrl, val, null_ctrl, phase);
1451     if (null_ctrl != NULL) {
1452       reg2_ctrl = null_ctrl->in(0);
1453       region->init_req(_null_path, null_ctrl);
1454       val_phi->init_req(_null_path, uncasted_val);
1455       raw_mem_phi->init_req(_null_path, raw_mem);
1456     } else {
1457       region->del_req(_null_path);
1458       val_phi->del_req(_null_path);
1459       raw_mem_phi->del_req(_null_path);
1460     }
1461 
1462     // Test for in-cset.
1463     // Wires !in_cset(obj) to slot 2 of region and phis
1464     Node* not_cset_ctrl = NULL;
1465     in_cset_fast_test(ctrl, not_cset_ctrl, uncasted_val, raw_mem, phase);
1466     if (not_cset_ctrl != NULL) {
1467       if (reg2_ctrl == NULL) reg2_ctrl = not_cset_ctrl->in(0);
1468       region->init_req(_not_cset, not_cset_ctrl);
1469       val_phi->init_req(_not_cset, uncasted_val);
1470       raw_mem_phi->init_req(_not_cset, raw_mem);
1471     }
1472 
1473     // Resolve object when orig-value is in cset.
1474     // Make the unconditional resolve for fwdptr.
1475     Node* new_val = uncasted_val;
1476     if (unc_ctrl != NULL) {
1477       // Clone the null check in this branch to allow implicit null check
1478       new_val = clone_null_check(ctrl, val, unc_ctrl, phase);
1479       fix_null_check(unc, unc_ctrl, ctrl->in(0)->as_If()->proj_out(0), uses, phase);
1480 
1481       IfNode* iff = unc_ctrl->in(0)->as_If();
1482       phase->igvn().replace_input_of(iff, 1, phase->igvn().intcon(1));
1483     }
1484     Node* addr = new AddPNode(new_val, uncasted_val, phase->igvn().MakeConX(oopDesc::mark_offset_in_bytes()));
1485     phase->register_new_node(addr, ctrl);
1486     assert(new_val->bottom_type()->isa_oopptr(), "what else?");
1487     Node* markword = new LoadXNode(ctrl, raw_mem, addr, TypeRawPtr::BOTTOM, TypeX_X, MemNode::unordered);
1488     phase->register_new_node(markword, ctrl);
1489 
1490     // Test if object is forwarded. This is the case if lowest two bits are set.
1491     Node* masked = new AndXNode(markword, phase->igvn().MakeConX(markOopDesc::lock_mask_in_place));
1492     phase->register_new_node(masked, ctrl);
1493     Node* cmp = new CmpXNode(masked, phase->igvn().MakeConX(markOopDesc::marked_value));
1494     phase->register_new_node(cmp, ctrl);
1495 
1496     // Only branch to LRB stub if object is not forwarded; otherwise reply with fwd ptr
1497     Node* bol = new BoolNode(cmp, BoolTest::eq); // Equals 3 means it's forwarded
1498     phase->register_new_node(bol, ctrl);
1499 
1500     IfNode* iff = new IfNode(ctrl, bol, PROB_LIKELY(0.999), COUNT_UNKNOWN);
1501     phase->register_control(iff, loop, ctrl);
1502     Node* if_fwd = new IfTrueNode(iff);
1503     phase->register_control(if_fwd, loop, iff);
1504     Node* if_not_fwd = new IfFalseNode(iff);
1505     phase->register_control(if_not_fwd, loop, iff);
1506 
1507     // Decode forward pointer: since we already have the lowest bits, we can just subtract them
1508     // from the mark word without the need for large immediate mask.
1509     Node* masked2 = new SubXNode(markword, masked);
1510     phase->register_new_node(masked2, if_fwd);
1511     Node* fwdraw = new CastX2PNode(masked2);
1512     fwdraw->init_req(0, if_fwd);
1513     phase->register_new_node(fwdraw, if_fwd);
1514     Node* fwd = new CheckCastPPNode(NULL, fwdraw, val->bottom_type());
1515     phase->register_new_node(fwd, if_fwd);
1516 
1517     // Wire up not-equal-path in slots 3.
1518     region->init_req(_fwded, if_fwd);
1519     val_phi->init_req(_fwded, fwd);
1520     raw_mem_phi->init_req(_fwded, raw_mem);
1521 
1522     // Call lrb-stub and wire up that path in slots 4
1523     Node* result_mem = NULL;
1524     ctrl = if_not_fwd;
1525     fwd = new_val;
1526     call_lrb_stub(ctrl, fwd, result_mem, raw_mem, lrb->is_native(), phase);
1527     region->init_req(_evac_path, ctrl);
1528     val_phi->init_req(_evac_path, fwd);
1529     raw_mem_phi->init_req(_evac_path, result_mem);
1530 
1531     phase->register_control(region, loop, heap_stable_iff);
1532     Node* out_val = val_phi;
1533     phase->register_new_node(val_phi, region);
1534     phase->register_new_node(raw_mem_phi, region);
1535 
1536     fix_ctrl(lrb, region, fixer, uses, uses_to_ignore, last, phase);
1537 
1538     ctrl = orig_ctrl;
1539 
1540     if (unc != NULL) {
1541       for (DUIterator_Fast imax, i = val->fast_outs(imax); i < imax; i++) {
1542         Node* u = val->fast_out(i);
1543         Node* c = phase->ctrl_or_self(u);
1544         if (u != lrb && (c != ctrl || is_dominator_same_ctrl(c, lrb, u, phase))) {
1545           phase->igvn().rehash_node_delayed(u);
1546           int nb = u->replace_edge(val, out_val);
1547           --i, imax -= nb;
1548         }
1549       }
1550       if (val->outcnt() == 0) {
1551         phase->igvn()._worklist.push(val);
1552       }
1553     }
1554     phase->igvn().replace_node(lrb, out_val);
1555 
1556     follow_barrier_uses(out_val, ctrl, uses, phase);
1557 
1558     for(uint next = 0; next < uses.size(); next++ ) {
1559       Node *n = uses.at(next);
1560       assert(phase->get_ctrl(n) == ctrl, "bad control");
1561       assert(n != init_raw_mem, "should leave input raw mem above the barrier");
1562       phase->set_ctrl(n, region);
1563       follow_barrier_uses(n, ctrl, uses, phase);
1564     }
1565 
1566     // The slow path call produces memory: hook the raw memory phi
1567     // from the expanded load reference barrier with the rest of the graph
1568     // which may require adding memory phis at every post dominated
1569     // region and at enclosing loop heads. Use the memory state
1570     // collected in memory_nodes to fix the memory graph. Update that
1571     // memory state as we go.
1572     fixer.fix_mem(ctrl, region, init_raw_mem, raw_mem_for_ctrl, raw_mem_phi, uses);
1573   }
1574   // Done expanding load-reference-barriers.
1575   assert(ShenandoahBarrierSetC2::bsc2()->state()->load_reference_barriers_count() == 0, "all load reference barrier nodes should have been replaced");
1576 
1577   for (int i = state->enqueue_barriers_count() - 1; i >= 0; i--) {
1578     Node* barrier = state->enqueue_barrier(i);
1579     Node* pre_val = barrier->in(1);
1580 
1581     if (phase->igvn().type(pre_val)->higher_equal(TypePtr::NULL_PTR)) {
1582       ShouldNotReachHere();
1583       continue;
1584     }
1585 
1586     Node* ctrl = phase->get_ctrl(barrier);
1587 
1588     if (ctrl->is_Proj() && ctrl->in(0)->is_CallJava()) {
1589       assert(is_dominator(phase->get_ctrl(pre_val), ctrl->in(0)->in(0), pre_val, ctrl->in(0), phase), "can't move");
1590       ctrl = ctrl->in(0)->in(0);
1591       phase->set_ctrl(barrier, ctrl);
1592     } else if (ctrl->is_CallRuntime()) {
1593       assert(is_dominator(phase->get_ctrl(pre_val), ctrl->in(0), pre_val, ctrl, phase), "can't move");
1594       ctrl = ctrl->in(0);
1595       phase->set_ctrl(barrier, ctrl);
1596     }
1597 
1598     Node* init_ctrl = ctrl;
1599     IdealLoopTree* loop = phase->get_loop(ctrl);
1600     Node* raw_mem = fixer.find_mem(ctrl, barrier);
1601     Node* init_raw_mem = raw_mem;
1602     Node* raw_mem_for_ctrl = fixer.find_mem(ctrl, NULL);
1603     Node* heap_stable_ctrl = NULL;
1604     Node* null_ctrl = NULL;
1605     uint last = phase->C->unique();
1606 
1607     enum { _heap_stable = 1, _heap_unstable, PATH_LIMIT };
1608     Node* region = new RegionNode(PATH_LIMIT);
1609     Node* phi = PhiNode::make(region, raw_mem, Type::MEMORY, TypeRawPtr::BOTTOM);
1610 
1611     enum { _fast_path = 1, _slow_path, _null_path, PATH_LIMIT2 };
1612     Node* region2 = new RegionNode(PATH_LIMIT2);
1613     Node* phi2 = PhiNode::make(region2, raw_mem, Type::MEMORY, TypeRawPtr::BOTTOM);
1614 
1615     // Stable path.
1616     test_heap_stable(ctrl, raw_mem, heap_stable_ctrl, phase);
1617     region->init_req(_heap_stable, heap_stable_ctrl);
1618     phi->init_req(_heap_stable, raw_mem);
1619 
1620     // Null path
1621     Node* reg2_ctrl = NULL;
1622     test_null(ctrl, pre_val, null_ctrl, phase);
1623     if (null_ctrl != NULL) {
1624       reg2_ctrl = null_ctrl->in(0);
1625       region2->init_req(_null_path, null_ctrl);
1626       phi2->init_req(_null_path, raw_mem);
1627     } else {
1628       region2->del_req(_null_path);
1629       phi2->del_req(_null_path);
1630     }
1631 
1632     const int index_offset = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset());
1633     const int buffer_offset = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset());
1634     Node* thread = new ThreadLocalNode();
1635     phase->register_new_node(thread, ctrl);
1636     Node* buffer_adr = new AddPNode(phase->C->top(), thread, phase->igvn().MakeConX(buffer_offset));
1637     phase->register_new_node(buffer_adr, ctrl);
1638     Node* index_adr = new AddPNode(phase->C->top(), thread, phase->igvn().MakeConX(index_offset));
1639     phase->register_new_node(index_adr, ctrl);
1640 
1641     BasicType index_bt = TypeX_X->basic_type();
1642     assert(sizeof(size_t) == type2aelembytes(index_bt), "Loading G1 SATBMarkQueue::_index with wrong size.");
1643     const TypePtr* adr_type = TypeRawPtr::BOTTOM;
1644     Node* index = new LoadXNode(ctrl, raw_mem, index_adr, adr_type, TypeX_X, MemNode::unordered);
1645     phase->register_new_node(index, ctrl);
1646     Node* index_cmp = new CmpXNode(index, phase->igvn().MakeConX(0));
1647     phase->register_new_node(index_cmp, ctrl);
1648     Node* index_test = new BoolNode(index_cmp, BoolTest::ne);
1649     phase->register_new_node(index_test, ctrl);
1650     IfNode* queue_full_iff = new IfNode(ctrl, index_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
1651     if (reg2_ctrl == NULL) reg2_ctrl = queue_full_iff;
1652     phase->register_control(queue_full_iff, loop, ctrl);
1653     Node* not_full = new IfTrueNode(queue_full_iff);
1654     phase->register_control(not_full, loop, queue_full_iff);
1655     Node* full = new IfFalseNode(queue_full_iff);
1656     phase->register_control(full, loop, queue_full_iff);
1657 
1658     ctrl = not_full;
1659 
1660     Node* next_index = new SubXNode(index, phase->igvn().MakeConX(sizeof(intptr_t)));
1661     phase->register_new_node(next_index, ctrl);
1662 
1663     Node* buffer  = new LoadPNode(ctrl, raw_mem, buffer_adr, adr_type, TypeRawPtr::NOTNULL, MemNode::unordered);
1664     phase->register_new_node(buffer, ctrl);
1665     Node *log_addr = new AddPNode(phase->C->top(), buffer, next_index);
1666     phase->register_new_node(log_addr, ctrl);
1667     Node* log_store = new StorePNode(ctrl, raw_mem, log_addr, adr_type, pre_val, MemNode::unordered);
1668     phase->register_new_node(log_store, ctrl);
1669     // update the index
1670     Node* index_update = new StoreXNode(ctrl, log_store, index_adr, adr_type, next_index, MemNode::unordered);
1671     phase->register_new_node(index_update, ctrl);
1672 
1673     // Fast-path case
1674     region2->init_req(_fast_path, ctrl);
1675     phi2->init_req(_fast_path, index_update);
1676 
1677     ctrl = full;
1678 
1679     Node* base = find_bottom_mem(ctrl, phase);
1680 
1681     MergeMemNode* mm = MergeMemNode::make(base);
1682     mm->set_memory_at(Compile::AliasIdxRaw, raw_mem);
1683     phase->register_new_node(mm, ctrl);
1684 
1685     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);
1686     call->init_req(TypeFunc::Control, ctrl);
1687     call->init_req(TypeFunc::I_O, phase->C->top());
1688     call->init_req(TypeFunc::Memory, mm);
1689     call->init_req(TypeFunc::FramePtr, phase->C->top());
1690     call->init_req(TypeFunc::ReturnAdr, phase->C->top());
1691     call->init_req(TypeFunc::Parms, pre_val);
1692     call->init_req(TypeFunc::Parms+1, thread);
1693     phase->register_control(call, loop, ctrl);
1694 
1695     Node* ctrl_proj = new ProjNode(call, TypeFunc::Control);
1696     phase->register_control(ctrl_proj, loop, call);
1697     Node* mem_proj = new ProjNode(call, TypeFunc::Memory);
1698     phase->register_new_node(mem_proj, call);
1699 
1700     // Slow-path case
1701     region2->init_req(_slow_path, ctrl_proj);
1702     phi2->init_req(_slow_path, mem_proj);
1703 
1704     phase->register_control(region2, loop, reg2_ctrl);
1705     phase->register_new_node(phi2, region2);
1706 
1707     region->init_req(_heap_unstable, region2);
1708     phi->init_req(_heap_unstable, phi2);
1709 
1710     phase->register_control(region, loop, heap_stable_ctrl->in(0));
1711     phase->register_new_node(phi, region);
1712 
1713     fix_ctrl(barrier, region, fixer, uses, uses_to_ignore, last, phase);
1714     for(uint next = 0; next < uses.size(); next++ ) {
1715       Node *n = uses.at(next);
1716       assert(phase->get_ctrl(n) == init_ctrl, "bad control");
1717       assert(n != init_raw_mem, "should leave input raw mem above the barrier");
1718       phase->set_ctrl(n, region);
1719       follow_barrier_uses(n, init_ctrl, uses, phase);
1720     }
1721     fixer.fix_mem(init_ctrl, region, init_raw_mem, raw_mem_for_ctrl, phi, uses);
1722 
1723     phase->igvn().replace_node(barrier, pre_val);
1724   }
1725   assert(state->enqueue_barriers_count() == 0, "all enqueue barrier nodes should have been replaced");
1726 
1727 }
1728 
1729 void ShenandoahBarrierC2Support::move_heap_stable_test_out_of_loop(IfNode* iff, PhaseIdealLoop* phase) {
1730   IdealLoopTree *loop = phase->get_loop(iff);
1731   Node* loop_head = loop->_head;
1732   Node* entry_c = loop_head->in(LoopNode::EntryControl);
1733 
1734   Node* bol = iff->in(1);
1735   Node* cmp = bol->in(1);
1736   Node* andi = cmp->in(1);
1737   Node* load = andi->in(1);
1738 
1739   assert(is_gc_state_load(load), "broken");
1740   if (!phase->is_dominator(load->in(0), entry_c)) {
1741     Node* mem_ctrl = NULL;
1742     Node* mem = dom_mem(load->in(MemNode::Memory), loop_head, Compile::AliasIdxRaw, mem_ctrl, phase);
1743     load = load->clone();
1744     load->set_req(MemNode::Memory, mem);
1745     load->set_req(0, entry_c);
1746     phase->register_new_node(load, entry_c);
1747     andi = andi->clone();
1748     andi->set_req(1, load);
1749     phase->register_new_node(andi, entry_c);
1750     cmp = cmp->clone();
1751     cmp->set_req(1, andi);
1752     phase->register_new_node(cmp, entry_c);
1753     bol = bol->clone();
1754     bol->set_req(1, cmp);
1755     phase->register_new_node(bol, entry_c);
1756 
1757     Node* old_bol =iff->in(1);
1758     phase->igvn().replace_input_of(iff, 1, bol);
1759   }
1760 }
1761 
1762 bool ShenandoahBarrierC2Support::identical_backtoback_ifs(Node* n, PhaseIdealLoop* phase) {
1763   if (!n->is_If() || n->is_CountedLoopEnd()) {
1764     return false;
1765   }
1766   Node* region = n->in(0);
1767 
1768   if (!region->is_Region()) {
1769     return false;
1770   }
1771   Node* dom = phase->idom(region);
1772   if (!dom->is_If()) {
1773     return false;
1774   }
1775 
1776   if (!is_heap_stable_test(n) || !is_heap_stable_test(dom)) {
1777     return false;
1778   }
1779 
1780   IfNode* dom_if = dom->as_If();
1781   Node* proj_true = dom_if->proj_out(1);
1782   Node* proj_false = dom_if->proj_out(0);
1783 
1784   for (uint i = 1; i < region->req(); i++) {
1785     if (phase->is_dominator(proj_true, region->in(i))) {
1786       continue;
1787     }
1788     if (phase->is_dominator(proj_false, region->in(i))) {
1789       continue;
1790     }
1791     return false;
1792   }
1793 
1794   return true;
1795 }
1796 
1797 void ShenandoahBarrierC2Support::merge_back_to_back_tests(Node* n, PhaseIdealLoop* phase) {
1798   assert(is_heap_stable_test(n), "no other tests");
1799   if (identical_backtoback_ifs(n, phase)) {
1800     Node* n_ctrl = n->in(0);
1801     if (phase->can_split_if(n_ctrl)) {
1802       IfNode* dom_if = phase->idom(n_ctrl)->as_If();
1803       if (is_heap_stable_test(n)) {
1804         Node* gc_state_load = n->in(1)->in(1)->in(1)->in(1);
1805         assert(is_gc_state_load(gc_state_load), "broken");
1806         Node* dom_gc_state_load = dom_if->in(1)->in(1)->in(1)->in(1);
1807         assert(is_gc_state_load(dom_gc_state_load), "broken");
1808         if (gc_state_load != dom_gc_state_load) {
1809           phase->igvn().replace_node(gc_state_load, dom_gc_state_load);
1810         }
1811       }
1812       PhiNode* bolphi = PhiNode::make_blank(n_ctrl, n->in(1));
1813       Node* proj_true = dom_if->proj_out(1);
1814       Node* proj_false = dom_if->proj_out(0);
1815       Node* con_true = phase->igvn().makecon(TypeInt::ONE);
1816       Node* con_false = phase->igvn().makecon(TypeInt::ZERO);
1817 
1818       for (uint i = 1; i < n_ctrl->req(); i++) {
1819         if (phase->is_dominator(proj_true, n_ctrl->in(i))) {
1820           bolphi->init_req(i, con_true);
1821         } else {
1822           assert(phase->is_dominator(proj_false, n_ctrl->in(i)), "bad if");
1823           bolphi->init_req(i, con_false);
1824         }
1825       }
1826       phase->register_new_node(bolphi, n_ctrl);
1827       phase->igvn().replace_input_of(n, 1, bolphi);
1828       phase->do_split_if(n);
1829     }
1830   }
1831 }
1832 
1833 IfNode* ShenandoahBarrierC2Support::find_unswitching_candidate(const IdealLoopTree* loop, PhaseIdealLoop* phase) {
1834   // Find first invariant test that doesn't exit the loop
1835   LoopNode *head = loop->_head->as_Loop();
1836   IfNode* unswitch_iff = NULL;
1837   Node* n = head->in(LoopNode::LoopBackControl);
1838   int loop_has_sfpts = -1;
1839   while (n != head) {
1840     Node* n_dom = phase->idom(n);
1841     if (n->is_Region()) {
1842       if (n_dom->is_If()) {
1843         IfNode* iff = n_dom->as_If();
1844         if (iff->in(1)->is_Bool()) {
1845           BoolNode* bol = iff->in(1)->as_Bool();
1846           if (bol->in(1)->is_Cmp()) {
1847             // If condition is invariant and not a loop exit,
1848             // then found reason to unswitch.
1849             if (is_heap_stable_test(iff) &&
1850                 (loop_has_sfpts == -1 || loop_has_sfpts == 0)) {
1851               assert(!loop->is_loop_exit(iff), "both branches should be in the loop");
1852               if (loop_has_sfpts == -1) {
1853                 for(uint i = 0; i < loop->_body.size(); i++) {
1854                   Node *m = loop->_body[i];
1855                   if (m->is_SafePoint() && !m->is_CallLeaf()) {
1856                     loop_has_sfpts = 1;
1857                     break;
1858                   }
1859                 }
1860                 if (loop_has_sfpts == -1) {
1861                   loop_has_sfpts = 0;
1862                 }
1863               }
1864               if (!loop_has_sfpts) {
1865                 unswitch_iff = iff;
1866               }
1867             }
1868           }
1869         }
1870       }
1871     }
1872     n = n_dom;
1873   }
1874   return unswitch_iff;
1875 }
1876 
1877 
1878 void ShenandoahBarrierC2Support::optimize_after_expansion(VectorSet &visited, Node_Stack &stack, Node_List &old_new, PhaseIdealLoop* phase) {
1879   Node_List heap_stable_tests;
1880   Node_List gc_state_loads;
1881   stack.push(phase->C->start(), 0);
1882   do {
1883     Node* n = stack.node();
1884     uint i = stack.index();
1885 
1886     if (i < n->outcnt()) {
1887       Node* u = n->raw_out(i);
1888       stack.set_index(i+1);
1889       if (!visited.test_set(u->_idx)) {
1890         stack.push(u, 0);
1891       }
1892     } else {
1893       stack.pop();
1894       if (ShenandoahCommonGCStateLoads && is_gc_state_load(n)) {
1895         gc_state_loads.push(n);
1896       }
1897       if (n->is_If() && is_heap_stable_test(n)) {
1898         heap_stable_tests.push(n);
1899       }
1900     }
1901   } while (stack.size() > 0);
1902 
1903   bool progress;
1904   do {
1905     progress = false;
1906     for (uint i = 0; i < gc_state_loads.size(); i++) {
1907       Node* n = gc_state_loads.at(i);
1908       if (n->outcnt() != 0) {
1909         progress |= try_common_gc_state_load(n, phase);
1910       }
1911     }
1912   } while (progress);
1913 
1914   for (uint i = 0; i < heap_stable_tests.size(); i++) {
1915     Node* n = heap_stable_tests.at(i);
1916     assert(is_heap_stable_test(n), "only evacuation test");
1917     merge_back_to_back_tests(n, phase);
1918   }
1919 
1920   if (!phase->C->major_progress()) {
1921     VectorSet seen(Thread::current()->resource_area());
1922     for (uint i = 0; i < heap_stable_tests.size(); i++) {
1923       Node* n = heap_stable_tests.at(i);
1924       IdealLoopTree* loop = phase->get_loop(n);
1925       if (loop != phase->ltree_root() &&
1926           loop->_child == NULL &&
1927           !loop->_irreducible) {
1928         LoopNode* head = loop->_head->as_Loop();
1929         if ((!head->is_CountedLoop() || head->as_CountedLoop()->is_main_loop() || head->as_CountedLoop()->is_normal_loop()) &&
1930             !seen.test_set(head->_idx)) {
1931           IfNode* iff = find_unswitching_candidate(loop, phase);
1932           if (iff != NULL) {
1933             Node* bol = iff->in(1);
1934             if (head->is_strip_mined()) {
1935               head->verify_strip_mined(0);
1936             }
1937             move_heap_stable_test_out_of_loop(iff, phase);
1938 
1939             AutoNodeBudget node_budget(phase);
1940 
1941             if (loop->policy_unswitching(phase)) {
1942               if (head->is_strip_mined()) {
1943                 OuterStripMinedLoopNode* outer = head->as_CountedLoop()->outer_loop();
1944                 hide_strip_mined_loop(outer, head->as_CountedLoop(), phase);
1945               }
1946               phase->do_unswitching(loop, old_new);
1947             } else {
1948               // Not proceeding with unswitching. Move load back in
1949               // the loop.
1950               phase->igvn().replace_input_of(iff, 1, bol);
1951             }
1952           }
1953         }
1954       }
1955     }
1956   }
1957 }
1958 
1959 #ifdef ASSERT
1960 void ShenandoahBarrierC2Support::verify_raw_mem(RootNode* root) {
1961   const bool trace = false;
1962   ResourceMark rm;
1963   Unique_Node_List nodes;
1964   Unique_Node_List controls;
1965   Unique_Node_List memories;
1966 
1967   nodes.push(root);
1968   for (uint next = 0; next < nodes.size(); next++) {
1969     Node *n  = nodes.at(next);
1970     if (ShenandoahBarrierSetC2::is_shenandoah_lrb_call(n)) {
1971       controls.push(n);
1972       if (trace) { tty->print("XXXXXX verifying"); n->dump(); }
1973       for (uint next2 = 0; next2 < controls.size(); next2++) {
1974         Node *m = controls.at(next2);
1975         for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) {
1976           Node* u = m->fast_out(i);
1977           if (u->is_CFG() && !u->is_Root() &&
1978               !(u->Opcode() == Op_CProj && u->in(0)->Opcode() == Op_NeverBranch && u->as_Proj()->_con == 1) &&
1979               !(u->is_Region() && u->unique_ctrl_out()->Opcode() == Op_Halt)) {
1980             if (trace) { tty->print("XXXXXX pushing control"); u->dump(); }
1981             controls.push(u);
1982           }
1983         }
1984       }
1985       memories.push(n->as_Call()->proj_out(TypeFunc::Memory));
1986       for (uint next2 = 0; next2 < memories.size(); next2++) {
1987         Node *m = memories.at(next2);
1988         assert(m->bottom_type() == Type::MEMORY, "");
1989         for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) {
1990           Node* u = m->fast_out(i);
1991           if (u->bottom_type() == Type::MEMORY && (u->is_Mem() || u->is_ClearArray())) {
1992             if (trace) { tty->print("XXXXXX pushing memory"); u->dump(); }
1993             memories.push(u);
1994           } else if (u->is_LoadStore()) {
1995             if (trace) { tty->print("XXXXXX pushing memory"); u->find_out_with(Op_SCMemProj)->dump(); }
1996             memories.push(u->find_out_with(Op_SCMemProj));
1997           } else if (u->is_MergeMem() && u->as_MergeMem()->memory_at(Compile::AliasIdxRaw) == m) {
1998             if (trace) { tty->print("XXXXXX pushing memory"); u->dump(); }
1999             memories.push(u);
2000           } else if (u->is_Phi()) {
2001             assert(u->bottom_type() == Type::MEMORY, "");
2002             if (u->adr_type() == TypeRawPtr::BOTTOM || u->adr_type() == TypePtr::BOTTOM) {
2003               assert(controls.member(u->in(0)), "");
2004               if (trace) { tty->print("XXXXXX pushing memory"); u->dump(); }
2005               memories.push(u);
2006             }
2007           } else if (u->is_SafePoint() || u->is_MemBar()) {
2008             for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
2009               Node* uu = u->fast_out(j);
2010               if (uu->bottom_type() == Type::MEMORY) {
2011                 if (trace) { tty->print("XXXXXX pushing memory"); uu->dump(); }
2012                 memories.push(uu);
2013               }
2014             }
2015           }
2016         }
2017       }
2018       for (uint next2 = 0; next2 < controls.size(); next2++) {
2019         Node *m = controls.at(next2);
2020         if (m->is_Region()) {
2021           bool all_in = true;
2022           for (uint i = 1; i < m->req(); i++) {
2023             if (!controls.member(m->in(i))) {
2024               all_in = false;
2025               break;
2026             }
2027           }
2028           if (trace) { tty->print("XXX verifying %s", all_in ? "all in" : ""); m->dump(); }
2029           bool found_phi = false;
2030           for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax && !found_phi; j++) {
2031             Node* u = m->fast_out(j);
2032             if (u->is_Phi() && memories.member(u)) {
2033               found_phi = true;
2034               for (uint i = 1; i < u->req() && found_phi; i++) {
2035                 Node* k = u->in(i);
2036                 if (memories.member(k) != controls.member(m->in(i))) {
2037                   found_phi = false;
2038                 }
2039               }
2040             }
2041           }
2042           assert(found_phi || all_in, "");
2043         }
2044       }
2045       controls.clear();
2046       memories.clear();
2047     }
2048     for( uint i = 0; i < n->len(); ++i ) {
2049       Node *m = n->in(i);
2050       if (m != NULL) {
2051         nodes.push(m);
2052       }
2053     }
2054   }
2055 }
2056 #endif
2057 
2058 ShenandoahEnqueueBarrierNode::ShenandoahEnqueueBarrierNode(Node* val) : Node(NULL, val) {
2059   ShenandoahBarrierSetC2::bsc2()->state()->add_enqueue_barrier(this);
2060 }
2061 
2062 const Type* ShenandoahEnqueueBarrierNode::bottom_type() const {
2063   if (in(1) == NULL || in(1)->is_top()) {
2064     return Type::TOP;
2065   }
2066   const Type* t = in(1)->bottom_type();
2067   if (t == TypePtr::NULL_PTR) {
2068     return t;
2069   }
2070   return t->is_oopptr()->cast_to_nonconst();
2071 }
2072 
2073 const Type* ShenandoahEnqueueBarrierNode::Value(PhaseGVN* phase) const {
2074   if (in(1) == NULL) {
2075     return Type::TOP;
2076   }
2077   const Type* t = phase->type(in(1));
2078   if (t == Type::TOP) {
2079     return Type::TOP;
2080   }
2081   if (t == TypePtr::NULL_PTR) {
2082     return t;
2083   }
2084   return t->is_oopptr()->cast_to_nonconst();
2085 }
2086 
2087 int ShenandoahEnqueueBarrierNode::needed(Node* n) {
2088   if (n == NULL ||
2089       n->is_Allocate() ||
2090       n->Opcode() == Op_ShenandoahEnqueueBarrier ||
2091       n->bottom_type() == TypePtr::NULL_PTR ||
2092       (n->bottom_type()->make_oopptr() != NULL && n->bottom_type()->make_oopptr()->const_oop() != NULL)) {
2093     return NotNeeded;
2094   }
2095   if (n->is_Phi() ||
2096       n->is_CMove()) {
2097     return MaybeNeeded;
2098   }
2099   return Needed;
2100 }
2101 
2102 Node* ShenandoahEnqueueBarrierNode::next(Node* n) {
2103   for (;;) {
2104     if (n == NULL) {
2105       return n;
2106     } else if (n->bottom_type() == TypePtr::NULL_PTR) {
2107       return n;
2108     } else if (n->bottom_type()->make_oopptr() != NULL && n->bottom_type()->make_oopptr()->const_oop() != NULL) {
2109       return n;
2110     } else if (n->is_ConstraintCast() ||
2111                n->Opcode() == Op_DecodeN ||
2112                n->Opcode() == Op_EncodeP) {
2113       n = n->in(1);
2114     } else if (n->is_Proj()) {
2115       n = n->in(0);
2116     } else {
2117       return n;
2118     }
2119   }
2120   ShouldNotReachHere();
2121   return NULL;
2122 }
2123 
2124 Node* ShenandoahEnqueueBarrierNode::Identity(PhaseGVN* phase) {
2125   PhaseIterGVN* igvn = phase->is_IterGVN();
2126 
2127   Node* n = next(in(1));
2128 
2129   int cont = needed(n);
2130 
2131   if (cont == NotNeeded) {
2132     return in(1);
2133   } else if (cont == MaybeNeeded) {
2134     if (igvn == NULL) {
2135       phase->record_for_igvn(this);
2136       return this;
2137     } else {
2138       ResourceMark rm;
2139       Unique_Node_List wq;
2140       uint wq_i = 0;
2141 
2142       for (;;) {
2143         if (n->is_Phi()) {
2144           for (uint i = 1; i < n->req(); i++) {
2145             Node* m = n->in(i);
2146             if (m != NULL) {
2147               wq.push(m);
2148             }
2149           }
2150         } else {
2151           assert(n->is_CMove(), "nothing else here");
2152           Node* m = n->in(CMoveNode::IfFalse);
2153           wq.push(m);
2154           m = n->in(CMoveNode::IfTrue);
2155           wq.push(m);
2156         }
2157         Node* orig_n = NULL;
2158         do {
2159           if (wq_i >= wq.size()) {
2160             return in(1);
2161           }
2162           n = wq.at(wq_i);
2163           wq_i++;
2164           orig_n = n;
2165           n = next(n);
2166           cont = needed(n);
2167           if (cont == Needed) {
2168             return this;
2169           }
2170         } while (cont != MaybeNeeded || (orig_n != n && wq.member(n)));
2171       }
2172     }
2173   }
2174 
2175   return this;
2176 }
2177 
2178 #ifdef ASSERT
2179 static bool has_never_branch(Node* root) {
2180   for (uint i = 1; i < root->req(); i++) {
2181     Node* in = root->in(i);
2182     if (in != NULL && in->Opcode() == Op_Halt && in->in(0)->is_Proj() && in->in(0)->in(0)->Opcode() == Op_NeverBranch) {
2183       return true;
2184     }
2185   }
2186   return false;
2187 }
2188 #endif
2189 
2190 void MemoryGraphFixer::collect_memory_nodes() {
2191   Node_Stack stack(0);
2192   VectorSet visited(Thread::current()->resource_area());
2193   Node_List regions;
2194 
2195   // Walk the raw memory graph and create a mapping from CFG node to
2196   // memory node. Exclude phis for now.
2197   stack.push(_phase->C->root(), 1);
2198   do {
2199     Node* n = stack.node();
2200     int opc = n->Opcode();
2201     uint i = stack.index();
2202     if (i < n->req()) {
2203       Node* mem = NULL;
2204       if (opc == Op_Root) {
2205         Node* in = n->in(i);
2206         int in_opc = in->Opcode();
2207         if (in_opc == Op_Return || in_opc == Op_Rethrow) {
2208           mem = in->in(TypeFunc::Memory);
2209         } else if (in_opc == Op_Halt) {
2210           if (!in->in(0)->is_Region()) {
2211             Node* proj = in->in(0);
2212             assert(proj->is_Proj(), "");
2213             Node* in = proj->in(0);
2214             assert(in->is_CallStaticJava() || in->Opcode() == Op_NeverBranch || in->Opcode() == Op_Catch || proj->is_IfProj(), "");
2215             if (in->is_CallStaticJava()) {
2216               mem = in->in(TypeFunc::Memory);
2217             } else if (in->Opcode() == Op_Catch) {
2218               Node* call = in->in(0)->in(0);
2219               assert(call->is_Call(), "");
2220               mem = call->in(TypeFunc::Memory);
2221             } else if (in->Opcode() == Op_NeverBranch) {
2222               ResourceMark rm;
2223               Unique_Node_List wq;
2224               wq.push(in);
2225               wq.push(in->as_Multi()->proj_out(0));
2226               for (uint j = 1; j < wq.size(); j++) {
2227                 Node* c = wq.at(j);
2228                 assert(!c->is_Root(), "shouldn't leave loop");
2229                 if (c->is_SafePoint()) {
2230                   assert(mem == NULL, "only one safepoint");
2231                   mem = c->in(TypeFunc::Memory);
2232                 }
2233                 for (DUIterator_Fast kmax, k = c->fast_outs(kmax); k < kmax; k++) {
2234                   Node* u = c->fast_out(k);
2235                   if (u->is_CFG()) {
2236                     wq.push(u);
2237                   }
2238                 }
2239               }
2240               assert(mem != NULL, "should have found safepoint");
2241             }
2242           }
2243         } else {
2244 #ifdef ASSERT
2245           n->dump();
2246           in->dump();
2247 #endif
2248           ShouldNotReachHere();
2249         }
2250       } else {
2251         assert(n->is_Phi() && n->bottom_type() == Type::MEMORY, "");
2252         assert(n->adr_type() == TypePtr::BOTTOM || _phase->C->get_alias_index(n->adr_type()) == _alias, "");
2253         mem = n->in(i);
2254       }
2255       i++;
2256       stack.set_index(i);
2257       if (mem == NULL) {
2258         continue;
2259       }
2260       for (;;) {
2261         if (visited.test_set(mem->_idx) || mem->is_Start()) {
2262           break;
2263         }
2264         if (mem->is_Phi()) {
2265           stack.push(mem, 2);
2266           mem = mem->in(1);
2267         } else if (mem->is_Proj()) {
2268           stack.push(mem, mem->req());
2269           mem = mem->in(0);
2270         } else if (mem->is_SafePoint() || mem->is_MemBar()) {
2271           mem = mem->in(TypeFunc::Memory);
2272         } else if (mem->is_MergeMem()) {
2273           MergeMemNode* mm = mem->as_MergeMem();
2274           mem = mm->memory_at(_alias);
2275         } else if (mem->is_Store() || mem->is_LoadStore() || mem->is_ClearArray()) {
2276           assert(_alias == Compile::AliasIdxRaw, "");
2277           stack.push(mem, mem->req());
2278           mem = mem->in(MemNode::Memory);
2279         } else {
2280 #ifdef ASSERT
2281           mem->dump();
2282 #endif
2283           ShouldNotReachHere();
2284         }
2285       }
2286     } else {
2287       if (n->is_Phi()) {
2288         // Nothing
2289       } else if (!n->is_Root()) {
2290         Node* c = get_ctrl(n);
2291         _memory_nodes.map(c->_idx, n);
2292       }
2293       stack.pop();
2294     }
2295   } while(stack.is_nonempty());
2296 
2297   // Iterate over CFG nodes in rpo and propagate memory state to
2298   // compute memory state at regions, creating new phis if needed.
2299   Node_List rpo_list;
2300   visited.Clear();
2301   _phase->rpo(_phase->C->root(), stack, visited, rpo_list);
2302   Node* root = rpo_list.pop();
2303   assert(root == _phase->C->root(), "");
2304 
2305   const bool trace = false;
2306 #ifdef ASSERT
2307   if (trace) {
2308     for (int i = rpo_list.size() - 1; i >= 0; i--) {
2309       Node* c = rpo_list.at(i);
2310       if (_memory_nodes[c->_idx] != NULL) {
2311         tty->print("X %d", c->_idx);  _memory_nodes[c->_idx]->dump();
2312       }
2313     }
2314   }
2315 #endif
2316   uint last = _phase->C->unique();
2317 
2318 #ifdef ASSERT
2319   uint8_t max_depth = 0;
2320   for (LoopTreeIterator iter(_phase->ltree_root()); !iter.done(); iter.next()) {
2321     IdealLoopTree* lpt = iter.current();
2322     max_depth = MAX2(max_depth, lpt->_nest);
2323   }
2324 #endif
2325 
2326   bool progress = true;
2327   int iteration = 0;
2328   Node_List dead_phis;
2329   while (progress) {
2330     progress = false;
2331     iteration++;
2332     assert(iteration <= 2+max_depth || _phase->C->has_irreducible_loop() || has_never_branch(_phase->C->root()), "");
2333     if (trace) { tty->print_cr("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); }
2334     IdealLoopTree* last_updated_ilt = NULL;
2335     for (int i = rpo_list.size() - 1; i >= 0; i--) {
2336       Node* c = rpo_list.at(i);
2337 
2338       Node* prev_mem = _memory_nodes[c->_idx];
2339       if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
2340         Node* prev_region = regions[c->_idx];
2341         Node* unique = NULL;
2342         for (uint j = 1; j < c->req() && unique != NodeSentinel; j++) {
2343           Node* m = _memory_nodes[c->in(j)->_idx];
2344           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");
2345           if (m != NULL) {
2346             if (m == prev_region && ((c->is_Loop() && j == LoopNode::LoopBackControl) || (prev_region->is_Phi() && prev_region->in(0) == c))) {
2347               assert(c->is_Loop() && j == LoopNode::LoopBackControl || _phase->C->has_irreducible_loop(), "");
2348               // continue
2349             } else if (unique == NULL) {
2350               unique = m;
2351             } else if (m == unique) {
2352               // continue
2353             } else {
2354               unique = NodeSentinel;
2355             }
2356           }
2357         }
2358         assert(unique != NULL, "empty phi???");
2359         if (unique != NodeSentinel) {
2360           if (prev_region != NULL && prev_region->is_Phi() && prev_region->in(0) == c) {
2361             dead_phis.push(prev_region);
2362           }
2363           regions.map(c->_idx, unique);
2364         } else {
2365           Node* phi = NULL;
2366           if (prev_region != NULL && prev_region->is_Phi() && prev_region->in(0) == c && prev_region->_idx >= last) {
2367             phi = prev_region;
2368             for (uint k = 1; k < c->req(); k++) {
2369               Node* m = _memory_nodes[c->in(k)->_idx];
2370               assert(m != NULL, "expect memory state");
2371               phi->set_req(k, m);
2372             }
2373           } else {
2374             for (DUIterator_Fast jmax, j = c->fast_outs(jmax); j < jmax && phi == NULL; j++) {
2375               Node* u = c->fast_out(j);
2376               if (u->is_Phi() && u->bottom_type() == Type::MEMORY &&
2377                   (u->adr_type() == TypePtr::BOTTOM || _phase->C->get_alias_index(u->adr_type()) == _alias)) {
2378                 phi = u;
2379                 for (uint k = 1; k < c->req() && phi != NULL; k++) {
2380                   Node* m = _memory_nodes[c->in(k)->_idx];
2381                   assert(m != NULL, "expect memory state");
2382                   if (u->in(k) != m) {
2383                     phi = NULL;
2384                   }
2385                 }
2386               }
2387             }
2388             if (phi == NULL) {
2389               phi = new PhiNode(c, Type::MEMORY, _phase->C->get_adr_type(_alias));
2390               for (uint k = 1; k < c->req(); k++) {
2391                 Node* m = _memory_nodes[c->in(k)->_idx];
2392                 assert(m != NULL, "expect memory state");
2393                 phi->init_req(k, m);
2394               }
2395             }
2396           }
2397           assert(phi != NULL, "");
2398           regions.map(c->_idx, phi);
2399         }
2400         Node* current_region = regions[c->_idx];
2401         if (current_region != prev_region) {
2402           progress = true;
2403           if (prev_region == prev_mem) {
2404             _memory_nodes.map(c->_idx, current_region);
2405           }
2406         }
2407       } else if (prev_mem == NULL || prev_mem->is_Phi() || ctrl_or_self(prev_mem) != c) {
2408         Node* m = _memory_nodes[_phase->idom(c)->_idx];
2409         assert(m != NULL, "expect memory state");
2410         if (m != prev_mem) {
2411           _memory_nodes.map(c->_idx, m);
2412           progress = true;
2413         }
2414       }
2415 #ifdef ASSERT
2416       if (trace) { tty->print("X %d", c->_idx);  _memory_nodes[c->_idx]->dump(); }
2417 #endif
2418     }
2419   }
2420 
2421   // Replace existing phi with computed memory state for that region
2422   // if different (could be a new phi or a dominating memory node if
2423   // that phi was found to be useless).
2424   while (dead_phis.size() > 0) {
2425     Node* n = dead_phis.pop();
2426     n->replace_by(_phase->C->top());
2427     n->destruct();
2428   }
2429   for (int i = rpo_list.size() - 1; i >= 0; i--) {
2430     Node* c = rpo_list.at(i);
2431     if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
2432       Node* n = regions[c->_idx];
2433       if (n->is_Phi() && n->_idx >= last && n->in(0) == c) {
2434         _phase->register_new_node(n, c);
2435       }
2436     }
2437   }
2438   for (int i = rpo_list.size() - 1; i >= 0; i--) {
2439     Node* c = rpo_list.at(i);
2440     if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
2441       Node* n = regions[c->_idx];
2442       for (DUIterator_Fast imax, i = c->fast_outs(imax); i < imax; i++) {
2443         Node* u = c->fast_out(i);
2444         if (u->is_Phi() && u->bottom_type() == Type::MEMORY &&
2445             u != n) {
2446           if (u->adr_type() == TypePtr::BOTTOM) {
2447             fix_memory_uses(u, n, n, c);
2448           } else if (_phase->C->get_alias_index(u->adr_type()) == _alias) {
2449             _phase->lazy_replace(u, n);
2450             --i; --imax;
2451           }
2452         }
2453       }
2454     }
2455   }
2456 }
2457 
2458 Node* MemoryGraphFixer::get_ctrl(Node* n) const {
2459   Node* c = _phase->get_ctrl(n);
2460   if (n->is_Proj() && n->in(0) != NULL && n->in(0)->is_Call()) {
2461     assert(c == n->in(0), "");
2462     CallNode* call = c->as_Call();
2463     CallProjections projs;
2464     call->extract_projections(&projs, true, false);
2465     if (projs.catchall_memproj != NULL) {
2466       if (projs.fallthrough_memproj == n) {
2467         c = projs.fallthrough_catchproj;
2468       } else {
2469         assert(projs.catchall_memproj == n, "");
2470         c = projs.catchall_catchproj;
2471       }
2472     }
2473   }
2474   return c;
2475 }
2476 
2477 Node* MemoryGraphFixer::ctrl_or_self(Node* n) const {
2478   if (_phase->has_ctrl(n))
2479     return get_ctrl(n);
2480   else {
2481     assert (n->is_CFG(), "must be a CFG node");
2482     return n;
2483   }
2484 }
2485 
2486 bool MemoryGraphFixer::mem_is_valid(Node* m, Node* c) const {
2487   return m != NULL && get_ctrl(m) == c;
2488 }
2489 
2490 Node* MemoryGraphFixer::find_mem(Node* ctrl, Node* n) const {
2491   assert(n == NULL || _phase->ctrl_or_self(n) == ctrl, "");
2492   Node* mem = _memory_nodes[ctrl->_idx];
2493   Node* c = ctrl;
2494   while (!mem_is_valid(mem, c) &&
2495          (!c->is_CatchProj() || mem == NULL || c->in(0)->in(0)->in(0) != get_ctrl(mem))) {
2496     c = _phase->idom(c);
2497     mem = _memory_nodes[c->_idx];
2498   }
2499   if (n != NULL && mem_is_valid(mem, c)) {
2500     while (!ShenandoahBarrierC2Support::is_dominator_same_ctrl(c, mem, n, _phase) && _phase->ctrl_or_self(mem) == ctrl) {
2501       mem = next_mem(mem, _alias);
2502     }
2503     if (mem->is_MergeMem()) {
2504       mem = mem->as_MergeMem()->memory_at(_alias);
2505     }
2506     if (!mem_is_valid(mem, c)) {
2507       do {
2508         c = _phase->idom(c);
2509         mem = _memory_nodes[c->_idx];
2510       } while (!mem_is_valid(mem, c) &&
2511                (!c->is_CatchProj() || mem == NULL || c->in(0)->in(0)->in(0) != get_ctrl(mem)));
2512     }
2513   }
2514   assert(mem->bottom_type() == Type::MEMORY, "");
2515   return mem;
2516 }
2517 
2518 bool MemoryGraphFixer::has_mem_phi(Node* region) const {
2519   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
2520     Node* use = region->fast_out(i);
2521     if (use->is_Phi() && use->bottom_type() == Type::MEMORY &&
2522         (_phase->C->get_alias_index(use->adr_type()) == _alias)) {
2523       return true;
2524     }
2525   }
2526   return false;
2527 }
2528 
2529 void MemoryGraphFixer::fix_mem(Node* ctrl, Node* new_ctrl, Node* mem, Node* mem_for_ctrl, Node* new_mem, Unique_Node_List& uses) {
2530   assert(_phase->ctrl_or_self(new_mem) == new_ctrl, "");
2531   const bool trace = false;
2532   DEBUG_ONLY(if (trace) { tty->print("ZZZ control is"); ctrl->dump(); });
2533   DEBUG_ONLY(if (trace) { tty->print("ZZZ mem is"); mem->dump(); });
2534   GrowableArray<Node*> phis;
2535   if (mem_for_ctrl != mem) {
2536     Node* old = mem_for_ctrl;
2537     Node* prev = NULL;
2538     while (old != mem) {
2539       prev = old;
2540       if (old->is_Store() || old->is_ClearArray() || old->is_LoadStore()) {
2541         assert(_alias == Compile::AliasIdxRaw, "");
2542         old = old->in(MemNode::Memory);
2543       } else if (old->Opcode() == Op_SCMemProj) {
2544         assert(_alias == Compile::AliasIdxRaw, "");
2545         old = old->in(0);
2546       } else {
2547         ShouldNotReachHere();
2548       }
2549     }
2550     assert(prev != NULL, "");
2551     if (new_ctrl != ctrl) {
2552       _memory_nodes.map(ctrl->_idx, mem);
2553       _memory_nodes.map(new_ctrl->_idx, mem_for_ctrl);
2554     }
2555     uint input = (uint)MemNode::Memory;
2556     _phase->igvn().replace_input_of(prev, input, new_mem);
2557   } else {
2558     uses.clear();
2559     _memory_nodes.map(new_ctrl->_idx, new_mem);
2560     uses.push(new_ctrl);
2561     for(uint next = 0; next < uses.size(); next++ ) {
2562       Node *n = uses.at(next);
2563       assert(n->is_CFG(), "");
2564       DEBUG_ONLY(if (trace) { tty->print("ZZZ ctrl"); n->dump(); });
2565       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2566         Node* u = n->fast_out(i);
2567         if (!u->is_Root() && u->is_CFG() && u != n) {
2568           Node* m = _memory_nodes[u->_idx];
2569           if (u->is_Region() && (!u->is_OuterStripMinedLoop() || _include_lsm) &&
2570               !has_mem_phi(u) &&
2571               u->unique_ctrl_out()->Opcode() != Op_Halt) {
2572             DEBUG_ONLY(if (trace) { tty->print("ZZZ region"); u->dump(); });
2573             DEBUG_ONLY(if (trace && m != NULL) { tty->print("ZZZ mem"); m->dump(); });
2574 
2575             if (!mem_is_valid(m, u) || !m->is_Phi()) {
2576               bool push = true;
2577               bool create_phi = true;
2578               if (_phase->is_dominator(new_ctrl, u)) {
2579                 create_phi = false;
2580               } else if (!_phase->C->has_irreducible_loop()) {
2581                 IdealLoopTree* loop = _phase->get_loop(ctrl);
2582                 bool do_check = true;
2583                 IdealLoopTree* l = loop;
2584                 create_phi = false;
2585                 while (l != _phase->ltree_root()) {
2586                   Node* head = l->_head;
2587                   if (head->in(0) == NULL) {
2588                     head = _phase->get_ctrl(head);
2589                   }
2590                   if (_phase->is_dominator(head, u) && _phase->is_dominator(_phase->idom(u), head)) {
2591                     create_phi = true;
2592                     do_check = false;
2593                     break;
2594                   }
2595                   l = l->_parent;
2596                 }
2597 
2598                 if (do_check) {
2599                   assert(!create_phi, "");
2600                   IdealLoopTree* u_loop = _phase->get_loop(u);
2601                   if (u_loop != _phase->ltree_root() && u_loop->is_member(loop)) {
2602                     Node* c = ctrl;
2603                     while (!_phase->is_dominator(c, u_loop->tail())) {
2604                       c = _phase->idom(c);
2605                     }
2606                     if (!_phase->is_dominator(c, u)) {
2607                       do_check = false;
2608                     }
2609                   }
2610                 }
2611 
2612                 if (do_check && _phase->is_dominator(_phase->idom(u), new_ctrl)) {
2613                   create_phi = true;
2614                 }
2615               }
2616               if (create_phi) {
2617                 Node* phi = new PhiNode(u, Type::MEMORY, _phase->C->get_adr_type(_alias));
2618                 _phase->register_new_node(phi, u);
2619                 phis.push(phi);
2620                 DEBUG_ONLY(if (trace) { tty->print("ZZZ new phi"); phi->dump(); });
2621                 if (!mem_is_valid(m, u)) {
2622                   DEBUG_ONLY(if (trace) { tty->print("ZZZ setting mem"); phi->dump(); });
2623                   _memory_nodes.map(u->_idx, phi);
2624                 } else {
2625                   DEBUG_ONLY(if (trace) { tty->print("ZZZ NOT setting mem"); m->dump(); });
2626                   for (;;) {
2627                     assert(m->is_Mem() || m->is_LoadStore() || m->is_Proj(), "");
2628                     Node* next = NULL;
2629                     if (m->is_Proj()) {
2630                       next = m->in(0);
2631                     } else {
2632                       assert(m->is_Mem() || m->is_LoadStore(), "");
2633                       assert(_alias == Compile::AliasIdxRaw, "");
2634                       next = m->in(MemNode::Memory);
2635                     }
2636                     if (_phase->get_ctrl(next) != u) {
2637                       break;
2638                     }
2639                     if (next->is_MergeMem()) {
2640                       assert(_phase->get_ctrl(next->as_MergeMem()->memory_at(_alias)) != u, "");
2641                       break;
2642                     }
2643                     if (next->is_Phi()) {
2644                       assert(next->adr_type() == TypePtr::BOTTOM && next->in(0) == u, "");
2645                       break;
2646                     }
2647                     m = next;
2648                   }
2649 
2650                   DEBUG_ONLY(if (trace) { tty->print("ZZZ setting to phi"); m->dump(); });
2651                   assert(m->is_Mem() || m->is_LoadStore(), "");
2652                   uint input = (uint)MemNode::Memory;
2653                   _phase->igvn().replace_input_of(m, input, phi);
2654                   push = false;
2655                 }
2656               } else {
2657                 DEBUG_ONLY(if (trace) { tty->print("ZZZ skipping region"); u->dump(); });
2658               }
2659               if (push) {
2660                 uses.push(u);
2661               }
2662             }
2663           } else if (!mem_is_valid(m, u) &&
2664                      !(u->Opcode() == Op_CProj && u->in(0)->Opcode() == Op_NeverBranch && u->as_Proj()->_con == 1)) {
2665             uses.push(u);
2666           }
2667         }
2668       }
2669     }
2670     for (int i = 0; i < phis.length(); i++) {
2671       Node* n = phis.at(i);
2672       Node* r = n->in(0);
2673       DEBUG_ONLY(if (trace) { tty->print("ZZZ fixing new phi"); n->dump(); });
2674       for (uint j = 1; j < n->req(); j++) {
2675         Node* m = find_mem(r->in(j), NULL);
2676         _phase->igvn().replace_input_of(n, j, m);
2677         DEBUG_ONLY(if (trace) { tty->print("ZZZ fixing new phi: %d", j); m->dump(); });
2678       }
2679     }
2680   }
2681   uint last = _phase->C->unique();
2682   MergeMemNode* mm = NULL;
2683   int alias = _alias;
2684   DEBUG_ONLY(if (trace) { tty->print("ZZZ raw mem is"); mem->dump(); });
2685   for (DUIterator i = mem->outs(); mem->has_out(i); i++) {
2686     Node* u = mem->out(i);
2687     if (u->_idx < last) {
2688       if (u->is_Mem()) {
2689         if (_phase->C->get_alias_index(u->adr_type()) == alias) {
2690           Node* m = find_mem(_phase->get_ctrl(u), u);
2691           if (m != mem) {
2692             DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2693             _phase->igvn().replace_input_of(u, MemNode::Memory, m);
2694             --i;
2695           }
2696         }
2697       } else if (u->is_MergeMem()) {
2698         MergeMemNode* u_mm = u->as_MergeMem();
2699         if (u_mm->memory_at(alias) == mem) {
2700           MergeMemNode* newmm = NULL;
2701           for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
2702             Node* uu = u->fast_out(j);
2703             assert(!uu->is_MergeMem(), "chain of MergeMems?");
2704             if (uu->is_Phi()) {
2705               assert(uu->adr_type() == TypePtr::BOTTOM, "");
2706               Node* region = uu->in(0);
2707               int nb = 0;
2708               for (uint k = 1; k < uu->req(); k++) {
2709                 if (uu->in(k) == u) {
2710                   Node* m = find_mem(region->in(k), NULL);
2711                   if (m != mem) {
2712                     DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of phi %d", k); uu->dump(); });
2713                     newmm = clone_merge_mem(u, mem, m, _phase->ctrl_or_self(m), i);
2714                     if (newmm != u) {
2715                       _phase->igvn().replace_input_of(uu, k, newmm);
2716                       nb++;
2717                       --jmax;
2718                     }
2719                   }
2720                 }
2721               }
2722               if (nb > 0) {
2723                 --j;
2724               }
2725             } else {
2726               Node* m = find_mem(_phase->ctrl_or_self(uu), uu);
2727               if (m != mem) {
2728                 DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); uu->dump(); });
2729                 newmm = clone_merge_mem(u, mem, m, _phase->ctrl_or_self(m), i);
2730                 if (newmm != u) {
2731                   _phase->igvn().replace_input_of(uu, uu->find_edge(u), newmm);
2732                   --j, --jmax;
2733                 }
2734               }
2735             }
2736           }
2737         }
2738       } else if (u->is_Phi()) {
2739         assert(u->bottom_type() == Type::MEMORY, "what else?");
2740         if (_phase->C->get_alias_index(u->adr_type()) == alias || u->adr_type() == TypePtr::BOTTOM) {
2741           Node* region = u->in(0);
2742           bool replaced = false;
2743           for (uint j = 1; j < u->req(); j++) {
2744             if (u->in(j) == mem) {
2745               Node* m = find_mem(region->in(j), NULL);
2746               Node* nnew = m;
2747               if (m != mem) {
2748                 if (u->adr_type() == TypePtr::BOTTOM) {
2749                   mm = allocate_merge_mem(mem, m, _phase->ctrl_or_self(m));
2750                   nnew = mm;
2751                 }
2752                 DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of phi %d", j); u->dump(); });
2753                 _phase->igvn().replace_input_of(u, j, nnew);
2754                 replaced = true;
2755               }
2756             }
2757           }
2758           if (replaced) {
2759             --i;
2760           }
2761         }
2762       } else if ((u->adr_type() == TypePtr::BOTTOM && u->Opcode() != Op_StrInflatedCopy) ||
2763                  u->adr_type() == NULL) {
2764         assert(u->adr_type() != NULL ||
2765                u->Opcode() == Op_Rethrow ||
2766                u->Opcode() == Op_Return ||
2767                u->Opcode() == Op_SafePoint ||
2768                (u->is_CallStaticJava() && u->as_CallStaticJava()->uncommon_trap_request() != 0) ||
2769                (u->is_CallStaticJava() && u->as_CallStaticJava()->_entry_point == OptoRuntime::rethrow_stub()) ||
2770                u->Opcode() == Op_CallLeaf, "");
2771         Node* m = find_mem(_phase->ctrl_or_self(u), u);
2772         if (m != mem) {
2773           mm = allocate_merge_mem(mem, m, _phase->get_ctrl(m));
2774           _phase->igvn().replace_input_of(u, u->find_edge(mem), mm);
2775           --i;
2776         }
2777       } else if (_phase->C->get_alias_index(u->adr_type()) == alias) {
2778         Node* m = find_mem(_phase->ctrl_or_self(u), u);
2779         if (m != mem) {
2780           DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2781           _phase->igvn().replace_input_of(u, u->find_edge(mem), m);
2782           --i;
2783         }
2784       } else if (u->adr_type() != TypePtr::BOTTOM &&
2785                  _memory_nodes[_phase->ctrl_or_self(u)->_idx] == u) {
2786         Node* m = find_mem(_phase->ctrl_or_self(u), u);
2787         assert(m != mem, "");
2788         // u is on the wrong slice...
2789         assert(u->is_ClearArray(), "");
2790         DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2791         _phase->igvn().replace_input_of(u, u->find_edge(mem), m);
2792         --i;
2793       }
2794     }
2795   }
2796 #ifdef ASSERT
2797   assert(new_mem->outcnt() > 0, "");
2798   for (int i = 0; i < phis.length(); i++) {
2799     Node* n = phis.at(i);
2800     assert(n->outcnt() > 0, "new phi must have uses now");
2801   }
2802 #endif
2803 }
2804 
2805 MergeMemNode* MemoryGraphFixer::allocate_merge_mem(Node* mem, Node* rep_proj, Node* rep_ctrl) const {
2806   MergeMemNode* mm = MergeMemNode::make(mem);
2807   mm->set_memory_at(_alias, rep_proj);
2808   _phase->register_new_node(mm, rep_ctrl);
2809   return mm;
2810 }
2811 
2812 MergeMemNode* MemoryGraphFixer::clone_merge_mem(Node* u, Node* mem, Node* rep_proj, Node* rep_ctrl, DUIterator& i) const {
2813   MergeMemNode* newmm = NULL;
2814   MergeMemNode* u_mm = u->as_MergeMem();
2815   Node* c = _phase->get_ctrl(u);
2816   if (_phase->is_dominator(c, rep_ctrl)) {
2817     c = rep_ctrl;
2818   } else {
2819     assert(_phase->is_dominator(rep_ctrl, c), "one must dominate the other");
2820   }
2821   if (u->outcnt() == 1) {
2822     if (u->req() > (uint)_alias && u->in(_alias) == mem) {
2823       _phase->igvn().replace_input_of(u, _alias, rep_proj);
2824       --i;
2825     } else {
2826       _phase->igvn().rehash_node_delayed(u);
2827       u_mm->set_memory_at(_alias, rep_proj);
2828     }
2829     newmm = u_mm;
2830     _phase->set_ctrl_and_loop(u, c);
2831   } else {
2832     // can't simply clone u and then change one of its input because
2833     // it adds and then removes an edge which messes with the
2834     // DUIterator
2835     newmm = MergeMemNode::make(u_mm->base_memory());
2836     for (uint j = 0; j < u->req(); j++) {
2837       if (j < newmm->req()) {
2838         if (j == (uint)_alias) {
2839           newmm->set_req(j, rep_proj);
2840         } else if (newmm->in(j) != u->in(j)) {
2841           newmm->set_req(j, u->in(j));
2842         }
2843       } else if (j == (uint)_alias) {
2844         newmm->add_req(rep_proj);
2845       } else {
2846         newmm->add_req(u->in(j));
2847       }
2848     }
2849     if ((uint)_alias >= u->req()) {
2850       newmm->set_memory_at(_alias, rep_proj);
2851     }
2852     _phase->register_new_node(newmm, c);
2853   }
2854   return newmm;
2855 }
2856 
2857 bool MemoryGraphFixer::should_process_phi(Node* phi) const {
2858   if (phi->adr_type() == TypePtr::BOTTOM) {
2859     Node* region = phi->in(0);
2860     for (DUIterator_Fast jmax, j = region->fast_outs(jmax); j < jmax; j++) {
2861       Node* uu = region->fast_out(j);
2862       if (uu->is_Phi() && uu != phi && uu->bottom_type() == Type::MEMORY && _phase->C->get_alias_index(uu->adr_type()) == _alias) {
2863         return false;
2864       }
2865     }
2866     return true;
2867   }
2868   return _phase->C->get_alias_index(phi->adr_type()) == _alias;
2869 }
2870 
2871 void MemoryGraphFixer::fix_memory_uses(Node* mem, Node* replacement, Node* rep_proj, Node* rep_ctrl) const {
2872   uint last = _phase-> C->unique();
2873   MergeMemNode* mm = NULL;
2874   assert(mem->bottom_type() == Type::MEMORY, "");
2875   for (DUIterator i = mem->outs(); mem->has_out(i); i++) {
2876     Node* u = mem->out(i);
2877     if (u != replacement && u->_idx < last) {
2878       if (u->is_MergeMem()) {
2879         MergeMemNode* u_mm = u->as_MergeMem();
2880         if (u_mm->memory_at(_alias) == mem) {
2881           MergeMemNode* newmm = NULL;
2882           for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
2883             Node* uu = u->fast_out(j);
2884             assert(!uu->is_MergeMem(), "chain of MergeMems?");
2885             if (uu->is_Phi()) {
2886               if (should_process_phi(uu)) {
2887                 Node* region = uu->in(0);
2888                 int nb = 0;
2889                 for (uint k = 1; k < uu->req(); k++) {
2890                   if (uu->in(k) == u && _phase->is_dominator(rep_ctrl, region->in(k))) {
2891                     if (newmm == NULL) {
2892                       newmm = clone_merge_mem(u, mem, rep_proj, rep_ctrl, i);
2893                     }
2894                     if (newmm != u) {
2895                       _phase->igvn().replace_input_of(uu, k, newmm);
2896                       nb++;
2897                       --jmax;
2898                     }
2899                   }
2900                 }
2901                 if (nb > 0) {
2902                   --j;
2903                 }
2904               }
2905             } else {
2906               if (rep_ctrl != uu && ShenandoahBarrierC2Support::is_dominator(rep_ctrl, _phase->ctrl_or_self(uu), replacement, uu, _phase)) {
2907                 if (newmm == NULL) {
2908                   newmm = clone_merge_mem(u, mem, rep_proj, rep_ctrl, i);
2909                 }
2910                 if (newmm != u) {
2911                   _phase->igvn().replace_input_of(uu, uu->find_edge(u), newmm);
2912                   --j, --jmax;
2913                 }
2914               }
2915             }
2916           }
2917         }
2918       } else if (u->is_Phi()) {
2919         assert(u->bottom_type() == Type::MEMORY, "what else?");
2920         Node* region = u->in(0);
2921         if (should_process_phi(u)) {
2922           bool replaced = false;
2923           for (uint j = 1; j < u->req(); j++) {
2924             if (u->in(j) == mem && _phase->is_dominator(rep_ctrl, region->in(j))) {
2925               Node* nnew = rep_proj;
2926               if (u->adr_type() == TypePtr::BOTTOM) {
2927                 if (mm == NULL) {
2928                   mm = allocate_merge_mem(mem, rep_proj, rep_ctrl);
2929                 }
2930                 nnew = mm;
2931               }
2932               _phase->igvn().replace_input_of(u, j, nnew);
2933               replaced = true;
2934             }
2935           }
2936           if (replaced) {
2937             --i;
2938           }
2939 
2940         }
2941       } else if ((u->adr_type() == TypePtr::BOTTOM && u->Opcode() != Op_StrInflatedCopy) ||
2942                  u->adr_type() == NULL) {
2943         assert(u->adr_type() != NULL ||
2944                u->Opcode() == Op_Rethrow ||
2945                u->Opcode() == Op_Return ||
2946                u->Opcode() == Op_SafePoint ||
2947                u->Opcode() == Op_StoreIConditional ||
2948                u->Opcode() == Op_StoreLConditional ||
2949                (u->is_CallStaticJava() && u->as_CallStaticJava()->uncommon_trap_request() != 0) ||
2950                (u->is_CallStaticJava() && u->as_CallStaticJava()->_entry_point == OptoRuntime::rethrow_stub()) ||
2951                u->Opcode() == Op_CallLeaf, "%s", u->Name());
2952         if (ShenandoahBarrierC2Support::is_dominator(rep_ctrl, _phase->ctrl_or_self(u), replacement, u, _phase)) {
2953           if (mm == NULL) {
2954             mm = allocate_merge_mem(mem, rep_proj, rep_ctrl);
2955           }
2956           _phase->igvn().replace_input_of(u, u->find_edge(mem), mm);
2957           --i;
2958         }
2959       } else if (_phase->C->get_alias_index(u->adr_type()) == _alias) {
2960         if (ShenandoahBarrierC2Support::is_dominator(rep_ctrl, _phase->ctrl_or_self(u), replacement, u, _phase)) {
2961           _phase->igvn().replace_input_of(u, u->find_edge(mem), rep_proj);
2962           --i;
2963         }
2964       }
2965     }
2966   }
2967 }
2968 
2969 ShenandoahLoadReferenceBarrierNode::ShenandoahLoadReferenceBarrierNode(Node* ctrl, Node* obj, bool native)
2970 : Node(ctrl, obj), _native(native) {
2971   ShenandoahBarrierSetC2::bsc2()->state()->add_load_reference_barrier(this);
2972 }
2973 
2974 bool ShenandoahLoadReferenceBarrierNode::is_native() const {
2975   return _native;
2976 }
2977 
2978 uint ShenandoahLoadReferenceBarrierNode::size_of() const {
2979   return sizeof(*this);
2980 }
2981 
2982 uint ShenandoahLoadReferenceBarrierNode::hash() const {
2983   return Node::hash() + (_native ? 1 : 0);
2984 }
2985 
2986 bool ShenandoahLoadReferenceBarrierNode::cmp( const Node &n ) const {
2987   return Node::cmp(n) && n.Opcode() == Op_ShenandoahLoadReferenceBarrier &&
2988          _native == ((const ShenandoahLoadReferenceBarrierNode&)n)._native;
2989 }
2990 
2991 const Type* ShenandoahLoadReferenceBarrierNode::bottom_type() const {
2992   if (in(ValueIn) == NULL || in(ValueIn)->is_top()) {
2993     return Type::TOP;
2994   }
2995   const Type* t = in(ValueIn)->bottom_type();
2996   if (t == TypePtr::NULL_PTR) {
2997     return t;
2998   }
2999   return t->is_oopptr();
3000 }
3001 
3002 const Type* ShenandoahLoadReferenceBarrierNode::Value(PhaseGVN* phase) const {
3003   // Either input is TOP ==> the result is TOP
3004   const Type *t2 = phase->type(in(ValueIn));
3005   if( t2 == Type::TOP ) return Type::TOP;
3006 
3007   if (t2 == TypePtr::NULL_PTR) {
3008     return t2;
3009   }
3010 
3011   const Type* type = t2->is_oopptr()/*->cast_to_nonconst()*/;
3012   return type;
3013 }
3014 
3015 Node* ShenandoahLoadReferenceBarrierNode::Identity(PhaseGVN* phase) {
3016   Node* value = in(ValueIn);
3017   if (!needs_barrier(phase, value)) {
3018     return value;
3019   }
3020   return this;
3021 }
3022 
3023 bool ShenandoahLoadReferenceBarrierNode::needs_barrier(PhaseGVN* phase, Node* n) {
3024   Unique_Node_List visited;
3025   return needs_barrier_impl(phase, n, visited);
3026 }
3027 
3028 bool ShenandoahLoadReferenceBarrierNode::needs_barrier_impl(PhaseGVN* phase, Node* n, Unique_Node_List &visited) {
3029   if (n == NULL) return false;
3030   if (visited.member(n)) {
3031     return false; // Been there.
3032   }
3033   visited.push(n);
3034 
3035   if (n->is_Allocate()) {
3036     // tty->print_cr("optimize barrier on alloc");
3037     return false;
3038   }
3039   if (n->is_Call()) {
3040     // tty->print_cr("optimize barrier on call");
3041     return false;
3042   }
3043 
3044   const Type* type = phase->type(n);
3045   if (type == Type::TOP) {
3046     return false;
3047   }
3048   if (type->make_ptr()->higher_equal(TypePtr::NULL_PTR)) {
3049     // tty->print_cr("optimize barrier on null");
3050     return false;
3051   }
3052   if (type->make_oopptr() && type->make_oopptr()->const_oop() != NULL) {
3053     // tty->print_cr("optimize barrier on constant");
3054     return false;
3055   }
3056 
3057   switch (n->Opcode()) {
3058     case Op_AddP:
3059       return true; // TODO: Can refine?
3060     case Op_LoadP:
3061     case Op_ShenandoahCompareAndExchangeN:
3062     case Op_ShenandoahCompareAndExchangeP:
3063     case Op_CompareAndExchangeN:
3064     case Op_CompareAndExchangeP:
3065     case Op_GetAndSetN:
3066     case Op_GetAndSetP:
3067       return true;
3068     case Op_Phi: {
3069       for (uint i = 1; i < n->req(); i++) {
3070         if (needs_barrier_impl(phase, n->in(i), visited)) return true;
3071       }
3072       return false;
3073     }
3074     case Op_CheckCastPP:
3075     case Op_CastPP:
3076       return needs_barrier_impl(phase, n->in(1), visited);
3077     case Op_Proj:
3078       return needs_barrier_impl(phase, n->in(0), visited);
3079     case Op_ShenandoahLoadReferenceBarrier:
3080       // tty->print_cr("optimize barrier on barrier");
3081       return false;
3082     case Op_Parm:
3083       // tty->print_cr("optimize barrier on input arg");
3084       return false;
3085     case Op_DecodeN:
3086     case Op_EncodeP:
3087       return needs_barrier_impl(phase, n->in(1), visited);
3088     case Op_LoadN:
3089       return true;
3090     case Op_CMoveN:
3091     case Op_CMoveP:
3092       return needs_barrier_impl(phase, n->in(2), visited) ||
3093              needs_barrier_impl(phase, n->in(3), visited);
3094     case Op_ShenandoahEnqueueBarrier:
3095       return needs_barrier_impl(phase, n->in(1), visited);
3096     default:
3097       break;
3098   }
3099 #ifdef ASSERT
3100   tty->print("need barrier on?: ");
3101   tty->print_cr("ins:");
3102   n->dump(2);
3103   tty->print_cr("outs:");
3104   n->dump(-2);
3105   ShouldNotReachHere();
3106 #endif
3107   return true;
3108 }
3109 
3110 ShenandoahLoadReferenceBarrierNode::Strength ShenandoahLoadReferenceBarrierNode::get_barrier_strength() {
3111   Unique_Node_List visited;
3112   Node_Stack stack(0);
3113   stack.push(this, 0);
3114   Strength strength = NONE;
3115   while (strength != STRONG && stack.size() > 0) {
3116     Node* n = stack.node();
3117     if (visited.member(n)) {
3118       stack.pop();
3119       continue;
3120     }
3121     visited.push(n);
3122     bool visit_users = false;
3123     switch (n->Opcode()) {
3124       case Op_StoreN:
3125       case Op_StoreP: {
3126         strength = STRONG;
3127         break;
3128       }
3129       case Op_CmpP: {
3130         if (!n->in(1)->bottom_type()->higher_equal(TypePtr::NULL_PTR) &&
3131             !n->in(2)->bottom_type()->higher_equal(TypePtr::NULL_PTR)) {
3132           strength = STRONG;
3133         }
3134         break;
3135       }
3136       case Op_CallStaticJava: {
3137         strength = STRONG;
3138         break;
3139       }
3140       case Op_CallDynamicJava:
3141       case Op_CallLeaf:
3142       case Op_CallLeafNoFP:
3143       case Op_CompareAndSwapL:
3144       case Op_CompareAndSwapI:
3145       case Op_CompareAndSwapB:
3146       case Op_CompareAndSwapS:
3147       case Op_CompareAndSwapN:
3148       case Op_CompareAndSwapP:
3149       case Op_CompareAndExchangeL:
3150       case Op_CompareAndExchangeI:
3151       case Op_CompareAndExchangeB:
3152       case Op_CompareAndExchangeS:
3153       case Op_CompareAndExchangeN:
3154       case Op_CompareAndExchangeP:
3155       case Op_WeakCompareAndSwapL:
3156       case Op_WeakCompareAndSwapI:
3157       case Op_WeakCompareAndSwapB:
3158       case Op_WeakCompareAndSwapS:
3159       case Op_WeakCompareAndSwapN:
3160       case Op_WeakCompareAndSwapP:
3161       case Op_ShenandoahCompareAndSwapN:
3162       case Op_ShenandoahCompareAndSwapP:
3163       case Op_ShenandoahWeakCompareAndSwapN:
3164       case Op_ShenandoahWeakCompareAndSwapP:
3165       case Op_ShenandoahCompareAndExchangeN:
3166       case Op_ShenandoahCompareAndExchangeP:
3167       case Op_GetAndSetL:
3168       case Op_GetAndSetI:
3169       case Op_GetAndSetB:
3170       case Op_GetAndSetS:
3171       case Op_GetAndSetP:
3172       case Op_GetAndSetN:
3173       case Op_GetAndAddL:
3174       case Op_GetAndAddI:
3175       case Op_GetAndAddB:
3176       case Op_GetAndAddS:
3177       case Op_ShenandoahEnqueueBarrier:
3178       case Op_FastLock:
3179       case Op_FastUnlock:
3180       case Op_Rethrow:
3181       case Op_Return:
3182       case Op_StoreB:
3183       case Op_StoreC:
3184       case Op_StoreD:
3185       case Op_StoreF:
3186       case Op_StoreL:
3187       case Op_StoreLConditional:
3188       case Op_StoreI:
3189       case Op_StoreIConditional:
3190       case Op_StoreVector:
3191       case Op_StrInflatedCopy:
3192       case Op_StrCompressedCopy:
3193       case Op_EncodeP:
3194       case Op_CastP2X:
3195       case Op_SafePoint:
3196       case Op_EncodeISOArray:
3197         strength = STRONG;
3198         break;
3199       case Op_LoadB:
3200       case Op_LoadUB:
3201       case Op_LoadUS:
3202       case Op_LoadD:
3203       case Op_LoadF:
3204       case Op_LoadL:
3205       case Op_LoadI:
3206       case Op_LoadS:
3207       case Op_LoadN:
3208       case Op_LoadP:
3209       case Op_LoadVector: {
3210         const TypePtr* adr_type = n->adr_type();
3211         int alias_idx = Compile::current()->get_alias_index(adr_type);
3212         Compile::AliasType* alias_type = Compile::current()->alias_type(alias_idx);
3213         ciField* field = alias_type->field();
3214         bool is_static = field != NULL && field->is_static();
3215         bool is_final = field != NULL && field->is_final();
3216         bool is_stable = field != NULL && field->is_stable();
3217         if (ShenandoahOptimizeStaticFinals && is_static && is_final) {
3218           // Leave strength as is.
3219         } else if (ShenandoahOptimizeInstanceFinals && !is_static && is_final) {
3220           // Leave strength as is.
3221         } else if (ShenandoahOptimizeStableFinals && (is_stable || (adr_type->isa_aryptr() && adr_type->isa_aryptr()->is_stable()))) {
3222           // Leave strength as is.
3223         } else {
3224           strength = WEAK;
3225         }
3226         break;
3227       }
3228       case Op_AryEq: {
3229         Node* n1 = n->in(2);
3230         Node* n2 = n->in(3);
3231         if (!ShenandoahOptimizeStableFinals ||
3232             !n1->bottom_type()->isa_aryptr() || !n1->bottom_type()->isa_aryptr()->is_stable() ||
3233             !n2->bottom_type()->isa_aryptr() || !n2->bottom_type()->isa_aryptr()->is_stable()) {
3234           strength = WEAK;
3235         }
3236         break;
3237       }
3238       case Op_StrEquals:
3239       case Op_StrComp:
3240       case Op_StrIndexOf:
3241       case Op_StrIndexOfChar:
3242       case Op_HasNegatives:
3243         if (!ShenandoahOptimizeStableFinals) {
3244            strength = WEAK;
3245         }
3246         break;
3247       case Op_Conv2B:
3248       case Op_LoadRange:
3249       case Op_LoadKlass:
3250       case Op_LoadNKlass:
3251         // NONE, i.e. leave current strength as is
3252         break;
3253       case Op_AddP:
3254       case Op_CheckCastPP:
3255       case Op_CastPP:
3256       case Op_CMoveP:
3257       case Op_Phi:
3258       case Op_ShenandoahLoadReferenceBarrier:
3259         visit_users = true;
3260         break;
3261       default: {
3262 #ifdef ASSERT
3263         tty->print_cr("Unknown node in get_barrier_strength:");
3264         n->dump(1);
3265         ShouldNotReachHere();
3266 #else
3267         strength = STRONG;
3268 #endif
3269       }
3270     }
3271 #ifdef ASSERT
3272 /*
3273     if (strength == STRONG) {
3274       tty->print("strengthening node: ");
3275       n->dump();
3276     }
3277     */
3278 #endif
3279     stack.pop();
3280     if (visit_users) {
3281       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3282         Node* user = n->fast_out(i);
3283         if (user != NULL) {
3284           stack.push(user, 0);
3285         }
3286       }
3287     }
3288   }
3289   return strength;
3290 }
3291 
3292 CallStaticJavaNode* ShenandoahLoadReferenceBarrierNode::pin_and_expand_null_check(PhaseIterGVN& igvn) {
3293   Node* val = in(ValueIn);
3294 
3295   const Type* val_t = igvn.type(val);
3296 
3297   if (val_t->meet(TypePtr::NULL_PTR) != val_t &&
3298       val->Opcode() == Op_CastPP &&
3299       val->in(0) != NULL &&
3300       val->in(0)->Opcode() == Op_IfTrue &&
3301       val->in(0)->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none) &&
3302       val->in(0)->in(0)->is_If() &&
3303       val->in(0)->in(0)->in(1)->Opcode() == Op_Bool &&
3304       val->in(0)->in(0)->in(1)->as_Bool()->_test._test == BoolTest::ne &&
3305       val->in(0)->in(0)->in(1)->in(1)->Opcode() == Op_CmpP &&
3306       val->in(0)->in(0)->in(1)->in(1)->in(1) == val->in(1) &&
3307       val->in(0)->in(0)->in(1)->in(1)->in(2)->bottom_type() == TypePtr::NULL_PTR) {
3308     assert(val->in(0)->in(0)->in(1)->in(1)->in(1) == val->in(1), "");
3309     CallStaticJavaNode* unc = val->in(0)->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none);
3310     return unc;
3311   }
3312   return NULL;
3313 }