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