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