1 /*
   2  * Copyright (c) 2015, 2021, Red Hat, Inc. All rights reserved.
   3  * Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 
  28 #include "classfile/javaClasses.hpp"
  29 #include "gc/shenandoah/c2/shenandoahSupport.hpp"
  30 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
  31 #include "gc/shenandoah/shenandoahBarrierSetAssembler.hpp"
  32 #include "gc/shenandoah/shenandoahForwarding.hpp"
  33 #include "gc/shenandoah/shenandoahHeap.hpp"
  34 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
  35 #include "gc/shenandoah/shenandoahRuntime.hpp"
  36 #include "gc/shenandoah/shenandoahThreadLocalData.hpp"
  37 #include "opto/arraycopynode.hpp"
  38 #include "opto/block.hpp"
  39 #include "opto/callnode.hpp"
  40 #include "opto/castnode.hpp"
  41 #include "opto/movenode.hpp"
  42 #include "opto/phaseX.hpp"
  43 #include "opto/rootnode.hpp"
  44 #include "opto/runtime.hpp"
  45 #include "opto/subnode.hpp"
  46 
  47 bool ShenandoahBarrierC2Support::expand(Compile* C, PhaseIterGVN& igvn) {
  48   ShenandoahBarrierSetC2State* state = ShenandoahBarrierSetC2::bsc2()->state();
  49   if (state->load_reference_barriers_count() > 0) {
  50     assert(C->post_loop_opts_phase(), "no loop opts allowed");
  51     C->reset_post_loop_opts_phase(); // ... but we know what we are doing
  52     C->clear_major_progress();
  53     PhaseIdealLoop::optimize(igvn, LoopOptsShenandoahExpand);
  54     if (C->failing()) return false;
  55 
  56     C->set_major_progress();
  57     if (!C->optimize_loops(igvn, LoopOptsShenandoahPostExpand)) {
  58       return false;
  59     }
  60     C->clear_major_progress();
  61     C->process_for_post_loop_opts_igvn(igvn);
  62     if (C->failing()) return false;
  63 
  64     C->set_post_loop_opts_phase(); // now for real!
  65   }
  66   return true;
  67 }
  68 
  69 bool ShenandoahBarrierC2Support::is_gc_state_test(Node* iff, int mask) {
  70   if (!UseShenandoahGC) {
  71     return false;
  72   }
  73   assert(iff->is_If(), "bad input");
  74   if (iff->Opcode() != Op_If) {
  75     return false;
  76   }
  77   Node* bol = iff->in(1);
  78   if (!bol->is_Bool() || bol->as_Bool()->_test._test != BoolTest::ne) {
  79     return false;
  80   }
  81   Node* cmp = bol->in(1);
  82   if (cmp->Opcode() != Op_CmpI) {
  83     return false;
  84   }
  85   Node* in1 = cmp->in(1);
  86   Node* in2 = cmp->in(2);
  87   if (in2->find_int_con(-1) != 0) {
  88     return false;
  89   }
  90   if (in1->Opcode() != Op_AndI) {
  91     return false;
  92   }
  93   in2 = in1->in(2);
  94   if (in2->find_int_con(-1) != mask) {
  95     return false;
  96   }
  97   in1 = in1->in(1);
  98 
  99   return is_gc_state_load(in1);
 100 }
 101 
 102 bool ShenandoahBarrierC2Support::is_heap_stable_test(Node* iff) {
 103   return is_gc_state_test(iff, ShenandoahHeap::HAS_FORWARDED);
 104 }
 105 
 106 bool ShenandoahBarrierC2Support::is_gc_state_load(Node *n) {
 107   if (!UseShenandoahGC) {
 108     return false;
 109   }
 110   if (n->Opcode() != Op_LoadB && n->Opcode() != Op_LoadUB) {
 111     return false;
 112   }
 113   Node* addp = n->in(MemNode::Address);
 114   if (!addp->is_AddP()) {
 115     return false;
 116   }
 117   Node* base = addp->in(AddPNode::Address);
 118   Node* off = addp->in(AddPNode::Offset);
 119   if (base->Opcode() != Op_ThreadLocal) {
 120     return false;
 121   }
 122   if (off->find_intptr_t_con(-1) != in_bytes(ShenandoahThreadLocalData::gc_state_offset())) {
 123     return false;
 124   }
 125   return true;
 126 }
 127 
 128 bool ShenandoahBarrierC2Support::has_safepoint_between(Node* start, Node* stop, PhaseIdealLoop *phase) {
 129   assert(phase->is_dominator(stop, start), "bad inputs");
 130   ResourceMark rm;
 131   Unique_Node_List wq;
 132   wq.push(start);
 133   for (uint next = 0; next < wq.size(); next++) {
 134     Node *m = wq.at(next);
 135     if (m == stop) {
 136       continue;
 137     }
 138     if (m->is_SafePoint() && !m->is_CallLeaf()) {
 139       return true;
 140     }
 141     if (m->is_Region()) {
 142       for (uint i = 1; i < m->req(); i++) {
 143         wq.push(m->in(i));
 144       }
 145     } else {
 146       wq.push(m->in(0));
 147     }
 148   }
 149   return false;
 150 }
 151 
 152 #ifdef ASSERT
 153 bool ShenandoahBarrierC2Support::verify_helper(Node* in, Node_Stack& phis, VectorSet& visited, verify_type t, bool trace, Unique_Node_List& barriers_used) {
 154   assert(phis.size() == 0, "");
 155 
 156   while (true) {
 157     if (in->bottom_type() == TypePtr::NULL_PTR) {
 158       if (trace) {tty->print_cr("null");}
 159     } else if (!in->bottom_type()->make_ptr()->make_oopptr()) {
 160       if (trace) {tty->print_cr("Non oop");}
 161     } else {
 162       if (in->is_ConstraintCast()) {
 163         in = in->in(1);
 164         continue;
 165       } else if (in->is_AddP()) {
 166         assert(!in->in(AddPNode::Address)->is_top(), "no raw memory access");
 167         in = in->in(AddPNode::Address);
 168         continue;
 169       } else if (in->is_Con()) {
 170         if (trace) {
 171           tty->print("Found constant");
 172           in->dump();
 173         }
 174       } else if (in->Opcode() == Op_Parm) {
 175         if (trace) {
 176           tty->print("Found argument");
 177         }
 178       } else if (in->Opcode() == Op_CreateEx) {
 179         if (trace) {
 180           tty->print("Found create-exception");
 181         }
 182       } else if (in->Opcode() == Op_LoadP && in->adr_type() == TypeRawPtr::BOTTOM) {
 183         if (trace) {
 184           tty->print("Found raw LoadP (OSR argument?)");
 185         }
 186       } else if (in->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
 187         if (t == ShenandoahOopStore) {
 188           return false;
 189         }
 190         barriers_used.push(in);
 191         if (trace) {tty->print("Found barrier"); in->dump();}
 192       } else if (in->is_Proj() && in->in(0)->is_Allocate()) {
 193         if (trace) {
 194           tty->print("Found alloc");
 195           in->in(0)->dump();
 196         }
 197       } else if (in->is_Proj() && (in->in(0)->Opcode() == Op_CallStaticJava || in->in(0)->Opcode() == Op_CallDynamicJava)) {
 198         if (trace) {
 199           tty->print("Found Java call");
 200         }
 201       } else if (in->is_Phi()) {
 202         if (!visited.test_set(in->_idx)) {
 203           if (trace) {tty->print("Pushed phi:"); in->dump();}
 204           phis.push(in, 2);
 205           in = in->in(1);
 206           continue;
 207         }
 208         if (trace) {tty->print("Already seen phi:"); in->dump();}
 209       } else if (in->Opcode() == Op_CMoveP || in->Opcode() == Op_CMoveN) {
 210         if (!visited.test_set(in->_idx)) {
 211           if (trace) {tty->print("Pushed cmovep:"); in->dump();}
 212           phis.push(in, CMoveNode::IfTrue);
 213           in = in->in(CMoveNode::IfFalse);
 214           continue;
 215         }
 216         if (trace) {tty->print("Already seen cmovep:"); in->dump();}
 217       } else if (in->Opcode() == Op_EncodeP || in->Opcode() == Op_DecodeN) {
 218         in = in->in(1);
 219         continue;
 220       } else {
 221         return false;
 222       }
 223     }
 224     bool cont = false;
 225     while (phis.is_nonempty()) {
 226       uint idx = phis.index();
 227       Node* phi = phis.node();
 228       if (idx >= phi->req()) {
 229         if (trace) {tty->print("Popped phi:"); phi->dump();}
 230         phis.pop();
 231         continue;
 232       }
 233       if (trace) {tty->print("Next entry(%d) for phi:", idx); phi->dump();}
 234       in = phi->in(idx);
 235       phis.set_index(idx+1);
 236       cont = true;
 237       break;
 238     }
 239     if (!cont) {
 240       break;
 241     }
 242   }
 243   return true;
 244 }
 245 
 246 void ShenandoahBarrierC2Support::report_verify_failure(const char* msg, Node* n1, Node* n2) {
 247   if (n1 != nullptr) {
 248     n1->dump(+10);
 249   }
 250   if (n2 != nullptr) {
 251     n2->dump(+10);
 252   }
 253   fatal("%s", msg);
 254 }
 255 
 256 void ShenandoahBarrierC2Support::verify(RootNode* root) {
 257   ResourceMark rm;
 258   Unique_Node_List wq;
 259   GrowableArray<Node*> barriers;
 260   Unique_Node_List barriers_used;
 261   Node_Stack phis(0);
 262   VectorSet visited;
 263   const bool trace = false;
 264   const bool verify_no_useless_barrier = false;
 265 
 266   wq.push(root);
 267   for (uint next = 0; next < wq.size(); next++) {
 268     Node *n = wq.at(next);
 269     if (n->is_Load()) {
 270       const bool trace = false;
 271       if (trace) {tty->print("Verifying"); n->dump();}
 272       if (n->Opcode() == Op_LoadRange || n->Opcode() == Op_LoadKlass || n->Opcode() == Op_LoadNKlass) {
 273         if (trace) {tty->print_cr("Load range/klass");}
 274       } else {
 275         const TypePtr* adr_type = n->as_Load()->adr_type();
 276 
 277         if (adr_type->isa_oopptr() && adr_type->is_oopptr()->offset() == oopDesc::mark_offset_in_bytes()) {
 278           if (trace) {tty->print_cr("Mark load");}
 279         } else if (adr_type->isa_instptr() &&
 280                    adr_type->is_instptr()->instance_klass()->is_subtype_of(Compile::current()->env()->Reference_klass()) &&
 281                    adr_type->is_instptr()->offset() == java_lang_ref_Reference::referent_offset()) {
 282           if (trace) {tty->print_cr("Reference.get()");}
 283         } else if (!verify_helper(n->in(MemNode::Address), phis, visited, ShenandoahLoad, trace, barriers_used)) {
 284           report_verify_failure("Shenandoah verification: Load should have barriers", n);
 285         }
 286       }
 287     } else if (n->is_Store()) {
 288       const bool trace = false;
 289 
 290       if (trace) {tty->print("Verifying"); n->dump();}
 291       if (n->in(MemNode::ValueIn)->bottom_type()->make_oopptr()) {
 292         Node* adr = n->in(MemNode::Address);
 293         bool verify = true;
 294 
 295         if (adr->is_AddP() && adr->in(AddPNode::Base)->is_top()) {
 296           adr = adr->in(AddPNode::Address);
 297           if (adr->is_AddP()) {
 298             assert(adr->in(AddPNode::Base)->is_top(), "");
 299             adr = adr->in(AddPNode::Address);
 300             if (adr->Opcode() == Op_LoadP &&
 301                 adr->in(MemNode::Address)->in(AddPNode::Base)->is_top() &&
 302                 adr->in(MemNode::Address)->in(AddPNode::Address)->Opcode() == Op_ThreadLocal &&
 303                 adr->in(MemNode::Address)->in(AddPNode::Offset)->find_intptr_t_con(-1) == in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset())) {
 304               if (trace) {tty->print_cr("SATB prebarrier");}
 305               verify = false;
 306             }
 307           }
 308         }
 309 
 310         if (verify && !verify_helper(n->in(MemNode::ValueIn), phis, visited, ShenandoahValue, trace, barriers_used)) {
 311           report_verify_failure("Shenandoah verification: Store should have barriers", n);
 312         }
 313       }
 314       if (!verify_helper(n->in(MemNode::Address), phis, visited, ShenandoahStore, trace, barriers_used)) {
 315         report_verify_failure("Shenandoah verification: Store (address) should have barriers", n);
 316       }
 317     } else if (n->Opcode() == Op_CmpP) {
 318       const bool trace = false;
 319 
 320       Node* in1 = n->in(1);
 321       Node* in2 = n->in(2);
 322       if (in1->bottom_type()->isa_oopptr()) {
 323         if (trace) {tty->print("Verifying"); n->dump();}
 324 
 325         bool mark_inputs = false;
 326         if (in1->bottom_type() == TypePtr::NULL_PTR || in2->bottom_type() == TypePtr::NULL_PTR ||
 327             (in1->is_Con() || in2->is_Con())) {
 328           if (trace) {tty->print_cr("Comparison against a constant");}
 329           mark_inputs = true;
 330         } else if ((in1->is_CheckCastPP() && in1->in(1)->is_Proj() && in1->in(1)->in(0)->is_Allocate()) ||
 331                    (in2->is_CheckCastPP() && in2->in(1)->is_Proj() && in2->in(1)->in(0)->is_Allocate())) {
 332           if (trace) {tty->print_cr("Comparison with newly alloc'ed object");}
 333           mark_inputs = true;
 334         } else {
 335           assert(in2->bottom_type()->isa_oopptr(), "");
 336 
 337           if (!verify_helper(in1, phis, visited, ShenandoahStore, trace, barriers_used) ||
 338               !verify_helper(in2, phis, visited, ShenandoahStore, trace, barriers_used)) {
 339             report_verify_failure("Shenandoah verification: Cmp should have barriers", n);
 340           }
 341         }
 342         if (verify_no_useless_barrier &&
 343             mark_inputs &&
 344             (!verify_helper(in1, phis, visited, ShenandoahValue, trace, barriers_used) ||
 345              !verify_helper(in2, phis, visited, ShenandoahValue, trace, barriers_used))) {
 346           phis.clear();
 347           visited.reset();
 348         }
 349       }
 350     } else if (n->is_LoadStore()) {
 351       if (n->in(MemNode::ValueIn)->bottom_type()->make_ptr() &&
 352           !verify_helper(n->in(MemNode::ValueIn), phis, visited, ShenandoahValue, trace, barriers_used)) {
 353         report_verify_failure("Shenandoah verification: LoadStore (value) should have barriers", n);
 354       }
 355 
 356       if (n->in(MemNode::Address)->bottom_type()->make_oopptr() && !verify_helper(n->in(MemNode::Address), phis, visited, ShenandoahStore, trace, barriers_used)) {
 357         report_verify_failure("Shenandoah verification: LoadStore (address) should have barriers", n);
 358       }
 359     } else if (n->Opcode() == Op_CallLeafNoFP || n->Opcode() == Op_CallLeaf) {
 360       CallNode* call = n->as_Call();
 361 
 362       static struct {
 363         const char* name;
 364         struct {
 365           int pos;
 366           verify_type t;
 367         } args[6];
 368       } calls[] = {
 369         "array_partition_stub",
 370         { { TypeFunc::Parms, ShenandoahStore }, { TypeFunc::Parms+4, ShenandoahStore },   { -1, ShenandoahNone },
 371           { -1, ShenandoahNone },                { -1, ShenandoahNone },                  { -1, ShenandoahNone } },
 372         "arraysort_stub",
 373         { { TypeFunc::Parms, ShenandoahStore },  { -1, ShenandoahNone },                  { -1, ShenandoahNone },
 374           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 375         "aescrypt_encryptBlock",
 376         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 377           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 378         "aescrypt_decryptBlock",
 379         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 380           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 381         "multiplyToLen",
 382         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+2, ShenandoahLoad },   { TypeFunc::Parms+4, ShenandoahStore },
 383           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 384         "squareToLen",
 385         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+2, ShenandoahLoad },   { -1,  ShenandoahNone},
 386           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 387         "montgomery_multiply",
 388         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahLoad },   { TypeFunc::Parms+2, ShenandoahLoad },
 389           { TypeFunc::Parms+6, ShenandoahStore }, { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 390         "montgomery_square",
 391         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahLoad },   { TypeFunc::Parms+5, ShenandoahStore },
 392           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 393         "mulAdd",
 394         { { TypeFunc::Parms, ShenandoahStore },  { TypeFunc::Parms+1, ShenandoahLoad },   { -1,  ShenandoahNone},
 395           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 396         "vectorizedMismatch",
 397         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahLoad },   { -1,  ShenandoahNone},
 398           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 399         "updateBytesCRC32",
 400         { { TypeFunc::Parms+1, ShenandoahLoad }, { -1,  ShenandoahNone},                  { -1,  ShenandoahNone},
 401           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 402         "updateBytesAdler32",
 403         { { TypeFunc::Parms+1, ShenandoahLoad }, { -1,  ShenandoahNone},                  { -1,  ShenandoahNone},
 404           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 405         "updateBytesCRC32C",
 406         { { TypeFunc::Parms+1, ShenandoahLoad }, { TypeFunc::Parms+3, ShenandoahLoad},    { -1,  ShenandoahNone},
 407           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 408         "counterMode_AESCrypt",
 409         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 410           { TypeFunc::Parms+3, ShenandoahStore }, { TypeFunc::Parms+5, ShenandoahStore }, { TypeFunc::Parms+6, ShenandoahStore } },
 411         "cipherBlockChaining_encryptAESCrypt",
 412         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 413           { TypeFunc::Parms+3, ShenandoahLoad },  { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 414         "cipherBlockChaining_decryptAESCrypt",
 415         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 416           { TypeFunc::Parms+3, ShenandoahLoad },  { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 417         "shenandoah_clone",
 418         { { TypeFunc::Parms, ShenandoahLoad },   { -1,  ShenandoahNone},                  { -1,  ShenandoahNone},
 419           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 420         "ghash_processBlocks",
 421         { { TypeFunc::Parms, ShenandoahStore },  { TypeFunc::Parms+1, ShenandoahLoad },   { TypeFunc::Parms+2, ShenandoahLoad },
 422           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 423         "sha1_implCompress",
 424         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
 425           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 426         "sha256_implCompress",
 427         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
 428           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 429         "sha512_implCompress",
 430         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
 431           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 432         "sha1_implCompressMB",
 433         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
 434           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 435         "sha256_implCompressMB",
 436         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
 437           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 438         "sha512_implCompressMB",
 439         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
 440           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 441         "encodeBlock",
 442         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+3, ShenandoahStore },   { -1, ShenandoahNone },
 443           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 444         "decodeBlock",
 445         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+3, ShenandoahStore },   { -1, ShenandoahNone },
 446           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 447         "intpoly_montgomeryMult_P256",
 448         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahLoad  },   { TypeFunc::Parms+2, ShenandoahStore },
 449           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 450         "intpoly_assign",
 451         { { TypeFunc::Parms+1, ShenandoahStore }, { TypeFunc::Parms+2, ShenandoahLoad },  { -1, ShenandoahNone },
 452           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 453       };
 454 
 455       if (call->is_call_to_arraycopystub()) {
 456         Node* dest = nullptr;
 457         const TypeTuple* args = n->as_Call()->_tf->domain();
 458         for (uint i = TypeFunc::Parms, j = 0; i < args->cnt(); i++) {
 459           if (args->field_at(i)->isa_ptr()) {
 460             j++;
 461             if (j == 2) {
 462               dest = n->in(i);
 463               break;
 464             }
 465           }
 466         }
 467         if (!verify_helper(n->in(TypeFunc::Parms), phis, visited, ShenandoahLoad, trace, barriers_used) ||
 468             !verify_helper(dest, phis, visited, ShenandoahStore, trace, barriers_used)) {
 469           report_verify_failure("Shenandoah verification: ArrayCopy should have barriers", n);
 470         }
 471       } else if (strlen(call->_name) > 5 &&
 472                  !strcmp(call->_name + strlen(call->_name) - 5, "_fill")) {
 473         if (!verify_helper(n->in(TypeFunc::Parms), phis, visited, ShenandoahStore, trace, barriers_used)) {
 474           report_verify_failure("Shenandoah verification: _fill should have barriers", n);
 475         }
 476       } else if (!strcmp(call->_name, "shenandoah_wb_pre")) {
 477         // skip
 478       } else {
 479         const int calls_len = sizeof(calls) / sizeof(calls[0]);
 480         int i = 0;
 481         for (; i < calls_len; i++) {
 482           if (!strcmp(calls[i].name, call->_name)) {
 483             break;
 484           }
 485         }
 486         if (i != calls_len) {
 487           const uint args_len = sizeof(calls[0].args) / sizeof(calls[0].args[0]);
 488           for (uint j = 0; j < args_len; j++) {
 489             int pos = calls[i].args[j].pos;
 490             if (pos == -1) {
 491               break;
 492             }
 493             if (!verify_helper(call->in(pos), phis, visited, calls[i].args[j].t, trace, barriers_used)) {
 494               report_verify_failure("Shenandoah verification: intrinsic calls should have barriers", n);
 495             }
 496           }
 497           for (uint j = TypeFunc::Parms; j < call->req(); j++) {
 498             if (call->in(j)->bottom_type()->make_ptr() &&
 499                 call->in(j)->bottom_type()->make_ptr()->isa_oopptr()) {
 500               uint k = 0;
 501               for (; k < args_len && calls[i].args[k].pos != (int)j; k++);
 502               if (k == args_len) {
 503                 fatal("arg %d for call %s not covered", j, call->_name);
 504               }
 505             }
 506           }
 507         } else {
 508           for (uint j = TypeFunc::Parms; j < call->req(); j++) {
 509             if (call->in(j)->bottom_type()->make_ptr() &&
 510                 call->in(j)->bottom_type()->make_ptr()->isa_oopptr()) {
 511               fatal("%s not covered", call->_name);
 512             }
 513           }
 514         }
 515       }
 516     } else if (n->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
 517       // skip
 518     } else if (n->is_AddP()
 519                || n->is_Phi()
 520                || n->is_ConstraintCast()
 521                || n->Opcode() == Op_Return
 522                || n->Opcode() == Op_CMoveP
 523                || n->Opcode() == Op_CMoveN
 524                || n->Opcode() == Op_Rethrow
 525                || n->is_MemBar()
 526                || n->Opcode() == Op_Conv2B
 527                || n->Opcode() == Op_SafePoint
 528                || n->is_CallJava()
 529                || n->Opcode() == Op_Unlock
 530                || n->Opcode() == Op_EncodeP
 531                || n->Opcode() == Op_DecodeN) {
 532       // nothing to do
 533     } else {
 534       static struct {
 535         int opcode;
 536         struct {
 537           int pos;
 538           verify_type t;
 539         } inputs[2];
 540       } others[] = {
 541         Op_FastLock,
 542         { { 1, ShenandoahLoad },                  { -1, ShenandoahNone} },
 543         Op_Lock,
 544         { { TypeFunc::Parms, ShenandoahLoad },    { -1, ShenandoahNone} },
 545         Op_ArrayCopy,
 546         { { ArrayCopyNode::Src, ShenandoahLoad }, { ArrayCopyNode::Dest, ShenandoahStore } },
 547         Op_StrCompressedCopy,
 548         { { 2, ShenandoahLoad },                  { 3, ShenandoahStore } },
 549         Op_StrInflatedCopy,
 550         { { 2, ShenandoahLoad },                  { 3, ShenandoahStore } },
 551         Op_AryEq,
 552         { { 2, ShenandoahLoad },                  { 3, ShenandoahLoad } },
 553         Op_StrIndexOf,
 554         { { 2, ShenandoahLoad },                  { 4, ShenandoahLoad } },
 555         Op_StrComp,
 556         { { 2, ShenandoahLoad },                  { 4, ShenandoahLoad } },
 557         Op_StrEquals,
 558         { { 2, ShenandoahLoad },                  { 3, ShenandoahLoad } },
 559         Op_VectorizedHashCode,
 560         { { 2, ShenandoahLoad },                  { -1, ShenandoahNone } },
 561         Op_EncodeISOArray,
 562         { { 2, ShenandoahLoad },                  { 3, ShenandoahStore } },
 563         Op_CountPositives,
 564         { { 2, ShenandoahLoad },                  { -1, ShenandoahNone} },
 565         Op_CastP2X,
 566         { { 1, ShenandoahLoad },                  { -1, ShenandoahNone} },
 567         Op_StrIndexOfChar,
 568         { { 2, ShenandoahLoad },                  { -1, ShenandoahNone } },
 569       };
 570 
 571       const int others_len = sizeof(others) / sizeof(others[0]);
 572       int i = 0;
 573       for (; i < others_len; i++) {
 574         if (others[i].opcode == n->Opcode()) {
 575           break;
 576         }
 577       }
 578       uint stop = n->is_Call() ? n->as_Call()->tf()->domain()->cnt() : n->req();
 579       if (i != others_len) {
 580         const uint inputs_len = sizeof(others[0].inputs) / sizeof(others[0].inputs[0]);
 581         for (uint j = 0; j < inputs_len; j++) {
 582           int pos = others[i].inputs[j].pos;
 583           if (pos == -1) {
 584             break;
 585           }
 586           if (!verify_helper(n->in(pos), phis, visited, others[i].inputs[j].t, trace, barriers_used)) {
 587             report_verify_failure("Shenandoah verification: intrinsic calls should have barriers", n);
 588           }
 589         }
 590         for (uint j = 1; j < stop; j++) {
 591           if (n->in(j) != nullptr && n->in(j)->bottom_type()->make_ptr() &&
 592               n->in(j)->bottom_type()->make_ptr()->make_oopptr()) {
 593             uint k = 0;
 594             for (; k < inputs_len && others[i].inputs[k].pos != (int)j; k++);
 595             if (k == inputs_len) {
 596               fatal("arg %d for node %s not covered", j, n->Name());
 597             }
 598           }
 599         }
 600       } else {
 601         for (uint j = 1; j < stop; j++) {
 602           if (n->in(j) != nullptr && n->in(j)->bottom_type()->make_ptr() &&
 603               n->in(j)->bottom_type()->make_ptr()->make_oopptr()) {
 604             fatal("%s not covered", n->Name());
 605           }
 606         }
 607       }
 608     }
 609 
 610     if (n->is_SafePoint()) {
 611       SafePointNode* sfpt = n->as_SafePoint();
 612       if (verify_no_useless_barrier && sfpt->jvms() != nullptr) {
 613         for (uint i = sfpt->jvms()->scloff(); i < sfpt->jvms()->endoff(); i++) {
 614           if (!verify_helper(sfpt->in(i), phis, visited, ShenandoahLoad, trace, barriers_used)) {
 615             phis.clear();
 616             visited.reset();
 617           }
 618         }
 619       }
 620     }
 621   }
 622 
 623   if (verify_no_useless_barrier) {
 624     for (int i = 0; i < barriers.length(); i++) {
 625       Node* n = barriers.at(i);
 626       if (!barriers_used.member(n)) {
 627         tty->print("XXX useless barrier"); n->dump(-2);
 628         ShouldNotReachHere();
 629       }
 630     }
 631   }
 632 }
 633 #endif
 634 
 635 bool ShenandoahBarrierC2Support::is_dominator_same_ctrl(Node* c, Node* d, Node* n, PhaseIdealLoop* phase) {
 636   // That both nodes have the same control is not sufficient to prove
 637   // domination, verify that there's no path from d to n
 638   ResourceMark rm;
 639   Unique_Node_List wq;
 640   wq.push(d);
 641   for (uint next = 0; next < wq.size(); next++) {
 642     Node *m = wq.at(next);
 643     if (m == n) {
 644       return false;
 645     }
 646     if (m->is_Phi() && m->in(0)->is_Loop()) {
 647       assert(phase->ctrl_or_self(m->in(LoopNode::EntryControl)) != c, "following loop entry should lead to new control");
 648     } else {
 649       if (m->is_Store() || m->is_LoadStore()) {
 650         // Take anti-dependencies into account
 651         Node* mem = m->in(MemNode::Memory);
 652         for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
 653           Node* u = mem->fast_out(i);
 654           if (u->is_Load() && phase->C->can_alias(m->adr_type(), phase->C->get_alias_index(u->adr_type())) &&
 655               phase->ctrl_or_self(u) == c) {
 656             wq.push(u);
 657           }
 658         }
 659       }
 660       for (uint i = 0; i < m->req(); i++) {
 661         if (m->in(i) != nullptr && phase->ctrl_or_self(m->in(i)) == c) {
 662           wq.push(m->in(i));
 663         }
 664       }
 665     }
 666   }
 667   return true;
 668 }
 669 
 670 bool ShenandoahBarrierC2Support::is_dominator(Node* d_c, Node* n_c, Node* d, Node* n, PhaseIdealLoop* phase) {
 671   if (d_c != n_c) {
 672     return phase->is_dominator(d_c, n_c);
 673   }
 674   return is_dominator_same_ctrl(d_c, d, n, phase);
 675 }
 676 
 677 Node* next_mem(Node* mem, int alias) {
 678   Node* res = nullptr;
 679   if (mem->is_Proj()) {
 680     res = mem->in(0);
 681   } else if (mem->is_SafePoint() || mem->is_MemBar()) {
 682     res = mem->in(TypeFunc::Memory);
 683   } else if (mem->is_Phi()) {
 684     res = mem->in(1);
 685   } else if (mem->is_MergeMem()) {
 686     res = mem->as_MergeMem()->memory_at(alias);
 687   } else if (mem->is_Store() || mem->is_LoadStore() || mem->is_ClearArray()) {
 688     assert(alias == Compile::AliasIdxRaw, "following raw memory can't lead to a barrier");
 689     res = mem->in(MemNode::Memory);
 690   } else {
 691 #ifdef ASSERT
 692     mem->dump();
 693 #endif
 694     ShouldNotReachHere();
 695   }
 696   return res;
 697 }
 698 
 699 Node* ShenandoahBarrierC2Support::no_branches(Node* c, Node* dom, bool allow_one_proj, PhaseIdealLoop* phase) {
 700   Node* iffproj = nullptr;
 701   while (c != dom) {
 702     Node* next = phase->idom(c);
 703     assert(next->unique_ctrl_out_or_null() == c || c->is_Proj() || c->is_Region(), "multiple control flow out but no proj or region?");
 704     if (c->is_Region()) {
 705       ResourceMark rm;
 706       Unique_Node_List wq;
 707       wq.push(c);
 708       for (uint i = 0; i < wq.size(); i++) {
 709         Node *n = wq.at(i);
 710         if (n == next) {
 711           continue;
 712         }
 713         if (n->is_Region()) {
 714           for (uint j = 1; j < n->req(); j++) {
 715             wq.push(n->in(j));
 716           }
 717         } else {
 718           wq.push(n->in(0));
 719         }
 720       }
 721       for (uint i = 0; i < wq.size(); i++) {
 722         Node *n = wq.at(i);
 723         assert(n->is_CFG(), "");
 724         if (n->is_Multi()) {
 725           for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
 726             Node* u = n->fast_out(j);
 727             if (u->is_CFG()) {
 728               if (!wq.member(u) && !u->as_Proj()->is_uncommon_trap_proj()) {
 729                 return NodeSentinel;
 730               }
 731             }
 732           }
 733         }
 734       }
 735     } else  if (c->is_Proj()) {
 736       if (c->is_IfProj()) {
 737         if (c->as_Proj()->is_uncommon_trap_if_pattern() != nullptr) {
 738           // continue;
 739         } else {
 740           if (!allow_one_proj) {
 741             return NodeSentinel;
 742           }
 743           if (iffproj == nullptr) {
 744             iffproj = c;
 745           } else {
 746             return NodeSentinel;
 747           }
 748         }
 749       } else if (c->Opcode() == Op_JumpProj) {
 750         return NodeSentinel; // unsupported
 751       } else if (c->Opcode() == Op_CatchProj) {
 752         return NodeSentinel; // unsupported
 753       } else if (c->Opcode() == Op_CProj && next->is_NeverBranch()) {
 754         return NodeSentinel; // unsupported
 755       } else {
 756         assert(next->unique_ctrl_out() == c, "unsupported branch pattern");
 757       }
 758     }
 759     c = next;
 760   }
 761   return iffproj;
 762 }
 763 
 764 Node* ShenandoahBarrierC2Support::dom_mem(Node* mem, Node* ctrl, int alias, Node*& mem_ctrl, PhaseIdealLoop* phase) {
 765   ResourceMark rm;
 766   VectorSet wq;
 767   wq.set(mem->_idx);
 768   mem_ctrl = phase->ctrl_or_self(mem);
 769   while (!phase->is_dominator(mem_ctrl, ctrl) || mem_ctrl == ctrl) {
 770     mem = next_mem(mem, alias);
 771     if (wq.test_set(mem->_idx)) {
 772       return nullptr;
 773     }
 774     mem_ctrl = phase->ctrl_or_self(mem);
 775   }
 776   if (mem->is_MergeMem()) {
 777     mem = mem->as_MergeMem()->memory_at(alias);
 778     mem_ctrl = phase->ctrl_or_self(mem);
 779   }
 780   return mem;
 781 }
 782 
 783 Node* ShenandoahBarrierC2Support::find_bottom_mem(Node* ctrl, PhaseIdealLoop* phase) {
 784   Node* mem = nullptr;
 785   Node* c = ctrl;
 786   do {
 787     if (c->is_Region()) {
 788       for (DUIterator_Fast imax, i = c->fast_outs(imax); i < imax && mem == nullptr; i++) {
 789         Node* u = c->fast_out(i);
 790         if (u->is_Phi() && u->bottom_type() == Type::MEMORY) {
 791           if (u->adr_type() == TypePtr::BOTTOM) {
 792             mem = u;
 793           }
 794         }
 795       }
 796     } else {
 797       if (c->is_Call() && c->as_Call()->adr_type() != nullptr) {
 798         CallProjections projs;
 799         c->as_Call()->extract_projections(&projs, true, false);
 800         if (projs.fallthrough_memproj != nullptr) {
 801           if (projs.fallthrough_memproj->adr_type() == TypePtr::BOTTOM) {
 802             if (projs.catchall_memproj == nullptr) {
 803               mem = projs.fallthrough_memproj;
 804             } else {
 805               if (phase->is_dominator(projs.fallthrough_catchproj, ctrl)) {
 806                 mem = projs.fallthrough_memproj;
 807               } else {
 808                 assert(phase->is_dominator(projs.catchall_catchproj, ctrl), "one proj must dominate barrier");
 809                 mem = projs.catchall_memproj;
 810               }
 811             }
 812           }
 813         } else {
 814           Node* proj = c->as_Call()->proj_out(TypeFunc::Memory);
 815           if (proj != nullptr &&
 816               proj->adr_type() == TypePtr::BOTTOM) {
 817             mem = proj;
 818           }
 819         }
 820       } else {
 821         for (DUIterator_Fast imax, i = c->fast_outs(imax); i < imax; i++) {
 822           Node* u = c->fast_out(i);
 823           if (u->is_Proj() &&
 824               u->bottom_type() == Type::MEMORY &&
 825               u->adr_type() == TypePtr::BOTTOM) {
 826               assert(c->is_SafePoint() || c->is_MemBar() || c->is_Start(), "");
 827               assert(mem == nullptr, "only one proj");
 828               mem = u;
 829           }
 830         }
 831         assert(!c->is_Call() || c->as_Call()->adr_type() != nullptr || mem == nullptr, "no mem projection expected");
 832       }
 833     }
 834     c = phase->idom(c);
 835   } while (mem == nullptr);
 836   return mem;
 837 }
 838 
 839 void ShenandoahBarrierC2Support::follow_barrier_uses(Node* n, Node* ctrl, Unique_Node_List& uses, PhaseIdealLoop* phase) {
 840   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
 841     Node* u = n->fast_out(i);
 842     if (!u->is_CFG() && phase->get_ctrl(u) == ctrl && (!u->is_Phi() || !u->in(0)->is_Loop() || u->in(LoopNode::LoopBackControl) != n)) {
 843       uses.push(u);
 844     }
 845   }
 846 }
 847 
 848 static void hide_strip_mined_loop(OuterStripMinedLoopNode* outer, CountedLoopNode* inner, PhaseIdealLoop* phase) {
 849   OuterStripMinedLoopEndNode* le = inner->outer_loop_end();
 850   Node* new_outer = new LoopNode(outer->in(LoopNode::EntryControl), outer->in(LoopNode::LoopBackControl));
 851   phase->register_control(new_outer, phase->get_loop(outer), outer->in(LoopNode::EntryControl));
 852   Node* new_le = new IfNode(le->in(0), le->in(1), le->_prob, le->_fcnt);
 853   phase->register_control(new_le, phase->get_loop(le), le->in(0));
 854   phase->lazy_replace(outer, new_outer);
 855   phase->lazy_replace(le, new_le);
 856   inner->clear_strip_mined();
 857 }
 858 
 859 void ShenandoahBarrierC2Support::test_gc_state(Node*& ctrl, Node* raw_mem, Node*& test_fail_ctrl,
 860                                                PhaseIdealLoop* phase, int flags) {
 861   PhaseIterGVN& igvn = phase->igvn();
 862   Node* old_ctrl = ctrl;
 863 
 864   Node* thread          = new ThreadLocalNode();
 865   Node* gc_state_offset = igvn.MakeConX(in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 866   Node* gc_state_addr   = new AddPNode(phase->C->top(), thread, gc_state_offset);
 867   Node* gc_state        = new LoadBNode(old_ctrl, raw_mem, gc_state_addr,
 868                                         DEBUG_ONLY(phase->C->get_adr_type(Compile::AliasIdxRaw)) NOT_DEBUG(nullptr),
 869                                         TypeInt::BYTE, MemNode::unordered);
 870   Node* gc_state_and    = new AndINode(gc_state, igvn.intcon(flags));
 871   Node* gc_state_cmp    = new CmpINode(gc_state_and, igvn.zerocon(T_INT));
 872   Node* gc_state_bool   = new BoolNode(gc_state_cmp, BoolTest::ne);
 873 
 874   IfNode* gc_state_iff  = new IfNode(old_ctrl, gc_state_bool, PROB_UNLIKELY(0.999), COUNT_UNKNOWN);
 875   ctrl                  = new IfTrueNode(gc_state_iff);
 876   test_fail_ctrl        = new IfFalseNode(gc_state_iff);
 877 
 878   IdealLoopTree* loop = phase->get_loop(old_ctrl);
 879   phase->register_control(gc_state_iff,   loop, old_ctrl);
 880   phase->register_control(ctrl,           loop, gc_state_iff);
 881   phase->register_control(test_fail_ctrl, loop, gc_state_iff);
 882 
 883   phase->register_new_node(thread,        old_ctrl);
 884   phase->register_new_node(gc_state_addr, old_ctrl);
 885   phase->register_new_node(gc_state,      old_ctrl);
 886   phase->register_new_node(gc_state_and,  old_ctrl);
 887   phase->register_new_node(gc_state_cmp,  old_ctrl);
 888   phase->register_new_node(gc_state_bool, old_ctrl);
 889 
 890   phase->set_ctrl(gc_state_offset, phase->C->root());
 891 
 892   assert(is_gc_state_test(gc_state_iff, flags), "Should match the shape");
 893 }
 894 
 895 void ShenandoahBarrierC2Support::test_null(Node*& ctrl, Node* val, Node*& null_ctrl, PhaseIdealLoop* phase) {
 896   Node* old_ctrl = ctrl;
 897   PhaseIterGVN& igvn = phase->igvn();
 898 
 899   const Type* val_t = igvn.type(val);
 900   if (val_t->meet(TypePtr::NULL_PTR) == val_t) {
 901     Node* null_cmp   = new CmpPNode(val, igvn.zerocon(T_OBJECT));
 902     Node* null_test  = new BoolNode(null_cmp, BoolTest::ne);
 903 
 904     IfNode* null_iff = new IfNode(old_ctrl, null_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
 905     ctrl             = new IfTrueNode(null_iff);
 906     null_ctrl        = new IfFalseNode(null_iff);
 907 
 908     IdealLoopTree* loop = phase->get_loop(old_ctrl);
 909     phase->register_control(null_iff,  loop, old_ctrl);
 910     phase->register_control(ctrl,      loop, null_iff);
 911     phase->register_control(null_ctrl, loop, null_iff);
 912 
 913     phase->register_new_node(null_cmp,  old_ctrl);
 914     phase->register_new_node(null_test, old_ctrl);
 915   }
 916 }
 917 
 918 void ShenandoahBarrierC2Support::test_in_cset(Node*& ctrl, Node*& not_cset_ctrl, Node* val, Node* raw_mem, PhaseIdealLoop* phase) {
 919   Node* old_ctrl = ctrl;
 920   PhaseIterGVN& igvn = phase->igvn();
 921 
 922   Node* raw_val        = new CastP2XNode(old_ctrl, val);
 923   Node* cset_idx       = new URShiftXNode(raw_val, igvn.intcon(ShenandoahHeapRegion::region_size_bytes_shift_jint()));
 924 
 925   // Figure out the target cset address with raw pointer math.
 926   // This avoids matching AddP+LoadB that would emit inefficient code.
 927   // See JDK-8245465.
 928   Node* cset_addr_ptr  = igvn.makecon(TypeRawPtr::make(ShenandoahHeap::in_cset_fast_test_addr()));
 929   Node* cset_addr      = new CastP2XNode(old_ctrl, cset_addr_ptr);
 930   Node* cset_load_addr = new AddXNode(cset_addr, cset_idx);
 931   Node* cset_load_ptr  = new CastX2PNode(cset_load_addr);
 932 
 933   Node* cset_load      = new LoadBNode(old_ctrl, raw_mem, cset_load_ptr,
 934                                        DEBUG_ONLY(phase->C->get_adr_type(Compile::AliasIdxRaw)) NOT_DEBUG(nullptr),
 935                                        TypeInt::BYTE, MemNode::unordered);
 936   Node* cset_cmp       = new CmpINode(cset_load, igvn.zerocon(T_INT));
 937   Node* cset_bool      = new BoolNode(cset_cmp, BoolTest::ne);
 938 
 939   IfNode* cset_iff     = new IfNode(old_ctrl, cset_bool, PROB_UNLIKELY(0.999), COUNT_UNKNOWN);
 940   ctrl                 = new IfTrueNode(cset_iff);
 941   not_cset_ctrl        = new IfFalseNode(cset_iff);
 942 
 943   IdealLoopTree *loop = phase->get_loop(old_ctrl);
 944   phase->register_control(cset_iff,      loop, old_ctrl);
 945   phase->register_control(ctrl,          loop, cset_iff);
 946   phase->register_control(not_cset_ctrl, loop, cset_iff);
 947 
 948   phase->set_ctrl(cset_addr_ptr, phase->C->root());
 949 
 950   phase->register_new_node(raw_val,        old_ctrl);
 951   phase->register_new_node(cset_idx,       old_ctrl);
 952   phase->register_new_node(cset_addr,      old_ctrl);
 953   phase->register_new_node(cset_load_addr, old_ctrl);
 954   phase->register_new_node(cset_load_ptr,  old_ctrl);
 955   phase->register_new_node(cset_load,      old_ctrl);
 956   phase->register_new_node(cset_cmp,       old_ctrl);
 957   phase->register_new_node(cset_bool,      old_ctrl);
 958 }
 959 
 960 void ShenandoahBarrierC2Support::call_lrb_stub(Node*& ctrl, Node*& val, Node* load_addr,
 961                                                DecoratorSet decorators, PhaseIdealLoop* phase) {
 962   IdealLoopTree*loop = phase->get_loop(ctrl);
 963   const TypePtr* obj_type = phase->igvn().type(val)->is_oopptr();
 964 
 965   address calladdr = nullptr;
 966   const char* name = nullptr;
 967   bool is_strong  = ShenandoahBarrierSet::is_strong_access(decorators);
 968   bool is_weak    = ShenandoahBarrierSet::is_weak_access(decorators);
 969   bool is_phantom = ShenandoahBarrierSet::is_phantom_access(decorators);
 970   bool is_native  = ShenandoahBarrierSet::is_native_access(decorators);
 971   bool is_narrow  = UseCompressedOops && !is_native;
 972   if (is_strong) {
 973     if (is_narrow) {
 974       calladdr = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong_narrow);
 975       name = "load_reference_barrier_strong_narrow";
 976     } else {
 977       calladdr = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong);
 978       name = "load_reference_barrier_strong";
 979     }
 980   } else if (is_weak) {
 981     if (is_narrow) {
 982       calladdr = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak_narrow);
 983       name = "load_reference_barrier_weak_narrow";
 984     } else {
 985       calladdr = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak);
 986       name = "load_reference_barrier_weak";
 987     }
 988   } else {
 989     assert(is_phantom, "only remaining strength");
 990     if (is_narrow) {
 991       calladdr = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom_narrow);
 992       name = "load_reference_barrier_phantom_narrow";
 993     } else {
 994       calladdr = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom);
 995       name = "load_reference_barrier_phantom";
 996     }
 997   }
 998   Node* call = new CallLeafNode(ShenandoahBarrierSetC2::load_reference_barrier_Type(), calladdr, name, TypeRawPtr::BOTTOM);
 999 
1000   call->init_req(TypeFunc::Control, ctrl);
1001   call->init_req(TypeFunc::I_O, phase->C->top());
1002   call->init_req(TypeFunc::Memory, phase->C->top());
1003   call->init_req(TypeFunc::FramePtr, phase->C->top());
1004   call->init_req(TypeFunc::ReturnAdr, phase->C->top());
1005   call->init_req(TypeFunc::Parms, val);
1006   call->init_req(TypeFunc::Parms+1, load_addr);
1007   phase->register_control(call, loop, ctrl);
1008   ctrl = new ProjNode(call, TypeFunc::Control);
1009   phase->register_control(ctrl, loop, call);
1010   val = new ProjNode(call, TypeFunc::Parms);
1011   phase->register_new_node(val, call);
1012   val = new CheckCastPPNode(ctrl, val, obj_type);
1013   phase->register_new_node(val, ctrl);
1014 }
1015 
1016 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) {
1017   Node* ctrl = phase->get_ctrl(barrier);
1018   Node* init_raw_mem = fixer.find_mem(ctrl, barrier);
1019 
1020   // Update the control of all nodes that should be after the
1021   // barrier control flow
1022   uses.clear();
1023   // Every node that is control dependent on the barrier's input
1024   // control will be after the expanded barrier. The raw memory (if
1025   // its memory is control dependent on the barrier's input control)
1026   // must stay above the barrier.
1027   uses_to_ignore.clear();
1028   if (phase->has_ctrl(init_raw_mem) && phase->get_ctrl(init_raw_mem) == ctrl && !init_raw_mem->is_Phi()) {
1029     uses_to_ignore.push(init_raw_mem);
1030   }
1031   for (uint next = 0; next < uses_to_ignore.size(); next++) {
1032     Node *n = uses_to_ignore.at(next);
1033     for (uint i = 0; i < n->req(); i++) {
1034       Node* in = n->in(i);
1035       if (in != nullptr && phase->has_ctrl(in) && phase->get_ctrl(in) == ctrl) {
1036         uses_to_ignore.push(in);
1037       }
1038     }
1039   }
1040   for (DUIterator_Fast imax, i = ctrl->fast_outs(imax); i < imax; i++) {
1041     Node* u = ctrl->fast_out(i);
1042     if (u->_idx < last &&
1043         u != barrier &&
1044         !u->depends_only_on_test() && // preserve dependency on test
1045         !uses_to_ignore.member(u) &&
1046         (u->in(0) != ctrl || (!u->is_Region() && !u->is_Phi())) &&
1047         (ctrl->Opcode() != Op_CatchProj || u->Opcode() != Op_CreateEx)) {
1048       Node* old_c = phase->ctrl_or_self(u);
1049       Node* c = old_c;
1050       if (c != ctrl ||
1051           is_dominator_same_ctrl(old_c, barrier, u, phase) ||
1052           ShenandoahBarrierSetC2::is_shenandoah_state_load(u)) {
1053         phase->igvn().rehash_node_delayed(u);
1054         int nb = u->replace_edge(ctrl, region, &phase->igvn());
1055         if (u->is_CFG()) {
1056           if (phase->idom(u) == ctrl) {
1057             phase->set_idom(u, region, phase->dom_depth(region));
1058           }
1059         } else if (phase->get_ctrl(u) == ctrl) {
1060           assert(u != init_raw_mem, "should leave input raw mem above the barrier");
1061           uses.push(u);
1062         }
1063         assert(nb == 1, "more than 1 ctrl input?");
1064         --i, imax -= nb;
1065       }
1066     }
1067   }
1068 }
1069 
1070 static Node* create_phis_on_call_return(Node* ctrl, Node* c, Node* n, Node* n_clone, const CallProjections& projs, PhaseIdealLoop* phase) {
1071   Node* region = nullptr;
1072   while (c != ctrl) {
1073     if (c->is_Region()) {
1074       region = c;
1075     }
1076     c = phase->idom(c);
1077   }
1078   assert(region != nullptr, "");
1079   Node* phi = new PhiNode(region, n->bottom_type());
1080   for (uint j = 1; j < region->req(); j++) {
1081     Node* in = region->in(j);
1082     if (phase->is_dominator(projs.fallthrough_catchproj, in)) {
1083       phi->init_req(j, n);
1084     } else if (phase->is_dominator(projs.catchall_catchproj, in)) {
1085       phi->init_req(j, n_clone);
1086     } else {
1087       phi->init_req(j, create_phis_on_call_return(ctrl, in, n, n_clone, projs, phase));
1088     }
1089   }
1090   phase->register_new_node(phi, region);
1091   return phi;
1092 }
1093 
1094 void ShenandoahBarrierC2Support::pin_and_expand(PhaseIdealLoop* phase) {
1095   ShenandoahBarrierSetC2State* state = ShenandoahBarrierSetC2::bsc2()->state();
1096 
1097   Unique_Node_List uses;
1098   Node_Stack stack(0);
1099   Node_List clones;
1100   for (int i = state->load_reference_barriers_count() - 1; i >= 0; i--) {
1101     ShenandoahLoadReferenceBarrierNode* lrb = state->load_reference_barrier(i);
1102 
1103     Node* ctrl = phase->get_ctrl(lrb);
1104     Node* val = lrb->in(ShenandoahLoadReferenceBarrierNode::ValueIn);
1105 
1106     CallStaticJavaNode* unc = nullptr;
1107     Node* unc_ctrl = nullptr;
1108     Node* uncasted_val = val;
1109 
1110     for (DUIterator_Fast imax, i = lrb->fast_outs(imax); i < imax; i++) {
1111       Node* u = lrb->fast_out(i);
1112       if (u->Opcode() == Op_CastPP &&
1113           u->in(0) != nullptr &&
1114           phase->is_dominator(u->in(0), ctrl)) {
1115         const Type* u_t = phase->igvn().type(u);
1116 
1117         if (u_t->meet(TypePtr::NULL_PTR) != u_t &&
1118             u->in(0)->Opcode() == Op_IfTrue &&
1119             u->in(0)->as_Proj()->is_uncommon_trap_if_pattern() &&
1120             u->in(0)->in(0)->is_If() &&
1121             u->in(0)->in(0)->in(1)->Opcode() == Op_Bool &&
1122             u->in(0)->in(0)->in(1)->as_Bool()->_test._test == BoolTest::ne &&
1123             u->in(0)->in(0)->in(1)->in(1)->Opcode() == Op_CmpP &&
1124             u->in(0)->in(0)->in(1)->in(1)->in(1) == val &&
1125             u->in(0)->in(0)->in(1)->in(1)->in(2)->bottom_type() == TypePtr::NULL_PTR) {
1126           IdealLoopTree* loop = phase->get_loop(ctrl);
1127           IdealLoopTree* unc_loop = phase->get_loop(u->in(0));
1128 
1129           if (!unc_loop->is_member(loop)) {
1130             continue;
1131           }
1132 
1133           Node* branch = no_branches(ctrl, u->in(0), false, phase);
1134           assert(branch == nullptr || branch == NodeSentinel, "was not looking for a branch");
1135           if (branch == NodeSentinel) {
1136             continue;
1137           }
1138 
1139           Node* iff = u->in(0)->in(0);
1140           Node* bol = iff->in(1)->clone();
1141           Node* cmp = bol->in(1)->clone();
1142           cmp->set_req(1, lrb);
1143           bol->set_req(1, cmp);
1144           phase->igvn().replace_input_of(iff, 1, bol);
1145           phase->set_ctrl(lrb, iff->in(0));
1146           phase->register_new_node(cmp, iff->in(0));
1147           phase->register_new_node(bol, iff->in(0));
1148           break;
1149         }
1150       }
1151     }
1152     if ((ctrl->is_Proj() && ctrl->in(0)->is_CallJava()) || ctrl->is_CallJava()) {
1153       CallNode* call = ctrl->is_Proj() ? ctrl->in(0)->as_CallJava() : ctrl->as_CallJava();
1154       if (call->entry_point() == OptoRuntime::rethrow_stub()) {
1155         // The rethrow call may have too many projections to be
1156         // properly handled here. Given there's no reason for a
1157         // barrier to depend on the call, move it above the call
1158         stack.push(lrb, 0);
1159         do {
1160           Node* n = stack.node();
1161           uint idx = stack.index();
1162           if (idx < n->req()) {
1163             Node* in = n->in(idx);
1164             stack.set_index(idx+1);
1165             if (in != nullptr) {
1166               if (phase->has_ctrl(in)) {
1167                 if (phase->is_dominator(call, phase->get_ctrl(in))) {
1168 #ifdef ASSERT
1169                   for (uint i = 0; i < stack.size(); i++) {
1170                     assert(stack.node_at(i) != in, "node shouldn't have been seen yet");
1171                   }
1172 #endif
1173                   stack.push(in, 0);
1174                 }
1175               } else {
1176                 assert(phase->is_dominator(in, call->in(0)), "no dependency on the call");
1177               }
1178             }
1179           } else {
1180             phase->set_ctrl(n, call->in(0));
1181             stack.pop();
1182           }
1183         } while(stack.size() > 0);
1184         continue;
1185       }
1186       CallProjections projs;
1187       call->extract_projections(&projs, false, false);
1188 
1189 #ifdef ASSERT
1190       VectorSet cloned;
1191 #endif
1192       Node* lrb_clone = lrb->clone();
1193       phase->register_new_node(lrb_clone, projs.catchall_catchproj);
1194       phase->set_ctrl(lrb, projs.fallthrough_catchproj);
1195 
1196       stack.push(lrb, 0);
1197       clones.push(lrb_clone);
1198 
1199       do {
1200         assert(stack.size() == clones.size(), "");
1201         Node* n = stack.node();
1202 #ifdef ASSERT
1203         if (n->is_Load()) {
1204           Node* mem = n->in(MemNode::Memory);
1205           for (DUIterator_Fast jmax, j = mem->fast_outs(jmax); j < jmax; j++) {
1206             Node* u = mem->fast_out(j);
1207             assert(!u->is_Store() || !u->is_LoadStore() || phase->get_ctrl(u) != ctrl, "anti dependent store?");
1208           }
1209         }
1210 #endif
1211         uint idx = stack.index();
1212         Node* n_clone = clones.at(clones.size()-1);
1213         if (idx < n->outcnt()) {
1214           Node* u = n->raw_out(idx);
1215           Node* c = phase->ctrl_or_self(u);
1216           if (phase->is_dominator(call, c) && phase->is_dominator(c, projs.fallthrough_proj)) {
1217             stack.set_index(idx+1);
1218             assert(!u->is_CFG(), "");
1219             stack.push(u, 0);
1220             assert(!cloned.test_set(u->_idx), "only one clone");
1221             Node* u_clone = u->clone();
1222             int nb = u_clone->replace_edge(n, n_clone, &phase->igvn());
1223             assert(nb > 0, "should have replaced some uses");
1224             phase->register_new_node(u_clone, projs.catchall_catchproj);
1225             clones.push(u_clone);
1226             phase->set_ctrl(u, projs.fallthrough_catchproj);
1227           } else {
1228             bool replaced = false;
1229             if (u->is_Phi()) {
1230               for (uint k = 1; k < u->req(); k++) {
1231                 if (u->in(k) == n) {
1232                   if (phase->is_dominator(projs.catchall_catchproj, u->in(0)->in(k))) {
1233                     phase->igvn().replace_input_of(u, k, n_clone);
1234                     replaced = true;
1235                   } else if (!phase->is_dominator(projs.fallthrough_catchproj, u->in(0)->in(k))) {
1236                     phase->igvn().replace_input_of(u, k, create_phis_on_call_return(ctrl, u->in(0)->in(k), n, n_clone, projs, phase));
1237                     replaced = true;
1238                   }
1239                 }
1240               }
1241             } else {
1242               if (phase->is_dominator(projs.catchall_catchproj, c)) {
1243                 phase->igvn().rehash_node_delayed(u);
1244                 int nb = u->replace_edge(n, n_clone, &phase->igvn());
1245                 assert(nb > 0, "should have replaced some uses");
1246                 replaced = true;
1247               } else if (!phase->is_dominator(projs.fallthrough_catchproj, c)) {
1248                 if (u->is_If()) {
1249                   // Can't break If/Bool/Cmp chain
1250                   assert(n->is_Bool(), "unexpected If shape");
1251                   assert(stack.node_at(stack.size()-2)->is_Cmp(), "unexpected If shape");
1252                   assert(n_clone->is_Bool(), "unexpected clone");
1253                   assert(clones.at(clones.size()-2)->is_Cmp(), "unexpected clone");
1254                   Node* bol_clone = n->clone();
1255                   Node* cmp_clone = stack.node_at(stack.size()-2)->clone();
1256                   bol_clone->set_req(1, cmp_clone);
1257 
1258                   Node* nn = stack.node_at(stack.size()-3);
1259                   Node* nn_clone = clones.at(clones.size()-3);
1260                   assert(nn->Opcode() == nn_clone->Opcode(), "mismatch");
1261 
1262                   int nb = cmp_clone->replace_edge(nn, create_phis_on_call_return(ctrl, c, nn, nn_clone, projs, phase),
1263                                                    &phase->igvn());
1264                   assert(nb > 0, "should have replaced some uses");
1265 
1266                   phase->register_new_node(bol_clone, u->in(0));
1267                   phase->register_new_node(cmp_clone, u->in(0));
1268 
1269                   phase->igvn().replace_input_of(u, 1, bol_clone);
1270 
1271                 } else {
1272                   phase->igvn().rehash_node_delayed(u);
1273                   int nb = u->replace_edge(n, create_phis_on_call_return(ctrl, c, n, n_clone, projs, phase), &phase->igvn());
1274                   assert(nb > 0, "should have replaced some uses");
1275                 }
1276                 replaced = true;
1277               }
1278             }
1279             if (!replaced) {
1280               stack.set_index(idx+1);
1281             }
1282           }
1283         } else {
1284           stack.pop();
1285           clones.pop();
1286         }
1287       } while (stack.size() > 0);
1288       assert(stack.size() == 0 && clones.size() == 0, "");
1289     }
1290   }
1291 
1292   for (int i = 0; i < state->load_reference_barriers_count(); i++) {
1293     ShenandoahLoadReferenceBarrierNode* lrb = state->load_reference_barrier(i);
1294     Node* ctrl = phase->get_ctrl(lrb);
1295     IdealLoopTree* loop = phase->get_loop(ctrl);
1296     Node* head = loop->head();
1297     if (head->is_OuterStripMinedLoop()) {
1298       // Expanding a barrier here will break loop strip mining
1299       // verification. Transform the loop so the loop nest doesn't
1300       // appear as strip mined.
1301       OuterStripMinedLoopNode* outer = head->as_OuterStripMinedLoop();
1302       hide_strip_mined_loop(outer, outer->unique_ctrl_out()->as_CountedLoop(), phase);
1303     }
1304     if (head->is_BaseCountedLoop() && ctrl->is_IfProj() && ctrl->in(0)->is_BaseCountedLoopEnd() &&
1305         head->as_BaseCountedLoop()->loopexit() == ctrl->in(0)) {
1306       Node* entry = head->in(LoopNode::EntryControl);
1307       Node* backedge = head->in(LoopNode::LoopBackControl);
1308       Node* new_head = new LoopNode(entry, backedge);
1309       phase->register_control(new_head, phase->get_loop(entry), entry);
1310       phase->lazy_replace(head, new_head);
1311     }
1312   }
1313 
1314   // Expand load-reference-barriers
1315   MemoryGraphFixer fixer(Compile::AliasIdxRaw, true, phase);
1316   Unique_Node_List uses_to_ignore;
1317   for (int i = state->load_reference_barriers_count() - 1; i >= 0; i--) {
1318     ShenandoahLoadReferenceBarrierNode* lrb = state->load_reference_barrier(i);
1319     uint last = phase->C->unique();
1320     Node* ctrl = phase->get_ctrl(lrb);
1321     Node* val = lrb->in(ShenandoahLoadReferenceBarrierNode::ValueIn);
1322 
1323     Node* orig_ctrl = ctrl;
1324 
1325     Node* raw_mem = fixer.find_mem(ctrl, lrb);
1326     Node* raw_mem_for_ctrl = fixer.find_mem(ctrl, nullptr);
1327 
1328     IdealLoopTree *loop = phase->get_loop(ctrl);
1329 
1330     Node* heap_stable_ctrl = nullptr;
1331     Node* null_ctrl = nullptr;
1332 
1333     assert(val->bottom_type()->make_oopptr(), "need oop");
1334     assert(val->bottom_type()->make_oopptr()->const_oop() == nullptr, "expect non-constant");
1335 
1336     enum { _heap_stable = 1, _evac_path, _not_cset, PATH_LIMIT };
1337     Node* region = new RegionNode(PATH_LIMIT);
1338     Node* val_phi = new PhiNode(region, val->bottom_type()->is_oopptr());
1339 
1340     // Stable path.
1341     int flags = ShenandoahHeap::HAS_FORWARDED;
1342     if (!ShenandoahBarrierSet::is_strong_access(lrb->decorators())) {
1343       flags |= ShenandoahHeap::WEAK_ROOTS;
1344     }
1345     test_gc_state(ctrl, raw_mem, heap_stable_ctrl, phase, flags);
1346     IfNode* heap_stable_iff = heap_stable_ctrl->in(0)->as_If();
1347 
1348     // Heap stable case
1349     region->init_req(_heap_stable, heap_stable_ctrl);
1350     val_phi->init_req(_heap_stable, val);
1351 
1352     // Test for in-cset, unless it's a native-LRB. Native LRBs need to return null
1353     // even for non-cset objects to prevent resurrection of such objects.
1354     // Wires !in_cset(obj) to slot 2 of region and phis
1355     Node* not_cset_ctrl = nullptr;
1356     if (ShenandoahBarrierSet::is_strong_access(lrb->decorators())) {
1357       test_in_cset(ctrl, not_cset_ctrl, val, raw_mem, phase);
1358     }
1359     if (not_cset_ctrl != nullptr) {
1360       region->init_req(_not_cset, not_cset_ctrl);
1361       val_phi->init_req(_not_cset, val);
1362     } else {
1363       region->del_req(_not_cset);
1364       val_phi->del_req(_not_cset);
1365     }
1366 
1367     // Resolve object when orig-value is in cset.
1368     // Make the unconditional resolve for fwdptr.
1369 
1370     // Call lrb-stub and wire up that path in slots 4
1371     Node* result_mem = nullptr;
1372 
1373     Node* addr;
1374     {
1375       VectorSet visited;
1376       addr = get_load_addr(phase, visited, lrb);
1377     }
1378     if (addr->Opcode() == Op_AddP) {
1379       Node* orig_base = addr->in(AddPNode::Base);
1380       Node* base = new CheckCastPPNode(ctrl, orig_base, orig_base->bottom_type(), ConstraintCastNode::StrongDependency);
1381       phase->register_new_node(base, ctrl);
1382       if (addr->in(AddPNode::Base) == addr->in((AddPNode::Address))) {
1383         // Field access
1384         addr = addr->clone();
1385         addr->set_req(AddPNode::Base, base);
1386         addr->set_req(AddPNode::Address, base);
1387         phase->register_new_node(addr, ctrl);
1388       } else {
1389         Node* addr2 = addr->in(AddPNode::Address);
1390         if (addr2->Opcode() == Op_AddP && addr2->in(AddPNode::Base) == addr2->in(AddPNode::Address) &&
1391               addr2->in(AddPNode::Base) == orig_base) {
1392           addr2 = addr2->clone();
1393           addr2->set_req(AddPNode::Base, base);
1394           addr2->set_req(AddPNode::Address, base);
1395           phase->register_new_node(addr2, ctrl);
1396           addr = addr->clone();
1397           addr->set_req(AddPNode::Base, base);
1398           addr->set_req(AddPNode::Address, addr2);
1399           phase->register_new_node(addr, ctrl);
1400         }
1401       }
1402     }
1403     call_lrb_stub(ctrl, val, addr, lrb->decorators(), phase);
1404     region->init_req(_evac_path, ctrl);
1405     val_phi->init_req(_evac_path, val);
1406 
1407     phase->register_control(region, loop, heap_stable_iff);
1408     Node* out_val = val_phi;
1409     phase->register_new_node(val_phi, region);
1410 
1411     fix_ctrl(lrb, region, fixer, uses, uses_to_ignore, last, phase);
1412 
1413     ctrl = orig_ctrl;
1414 
1415     phase->igvn().replace_node(lrb, out_val);
1416 
1417     follow_barrier_uses(out_val, ctrl, uses, phase);
1418 
1419     for(uint next = 0; next < uses.size(); next++ ) {
1420       Node *n = uses.at(next);
1421       assert(phase->get_ctrl(n) == ctrl, "bad control");
1422       assert(n != raw_mem, "should leave input raw mem above the barrier");
1423       phase->set_ctrl(n, region);
1424       follow_barrier_uses(n, ctrl, uses, phase);
1425     }
1426     fixer.record_new_ctrl(ctrl, region, raw_mem, raw_mem_for_ctrl);
1427   }
1428   // Done expanding load-reference-barriers.
1429   assert(ShenandoahBarrierSetC2::bsc2()->state()->load_reference_barriers_count() == 0, "all load reference barrier nodes should have been replaced");
1430 }
1431 
1432 Node* ShenandoahBarrierC2Support::get_load_addr(PhaseIdealLoop* phase, VectorSet& visited, Node* in) {
1433   if (visited.test_set(in->_idx)) {
1434     return nullptr;
1435   }
1436   switch (in->Opcode()) {
1437     case Op_Proj:
1438       return get_load_addr(phase, visited, in->in(0));
1439     case Op_CastPP:
1440     case Op_CheckCastPP:
1441     case Op_DecodeN:
1442     case Op_EncodeP:
1443       return get_load_addr(phase, visited, in->in(1));
1444     case Op_LoadN:
1445     case Op_LoadP:
1446       return in->in(MemNode::Address);
1447     case Op_CompareAndExchangeN:
1448     case Op_CompareAndExchangeP:
1449     case Op_GetAndSetN:
1450     case Op_GetAndSetP:
1451     case Op_ShenandoahCompareAndExchangeP:
1452     case Op_ShenandoahCompareAndExchangeN:
1453       // Those instructions would just have stored a different
1454       // value into the field. No use to attempt to fix it at this point.
1455       return phase->igvn().zerocon(T_OBJECT);
1456     case Op_CMoveP:
1457     case Op_CMoveN: {
1458       Node* t = get_load_addr(phase, visited, in->in(CMoveNode::IfTrue));
1459       Node* f = get_load_addr(phase, visited, in->in(CMoveNode::IfFalse));
1460       // Handle unambiguous cases: single address reported on both branches.
1461       if (t != nullptr && f == nullptr) return t;
1462       if (t == nullptr && f != nullptr) return f;
1463       if (t != nullptr && t == f)    return t;
1464       // Ambiguity.
1465       return phase->igvn().zerocon(T_OBJECT);
1466     }
1467     case Op_Phi: {
1468       Node* addr = nullptr;
1469       for (uint i = 1; i < in->req(); i++) {
1470         Node* addr1 = get_load_addr(phase, visited, in->in(i));
1471         if (addr == nullptr) {
1472           addr = addr1;
1473         }
1474         if (addr != addr1) {
1475           return phase->igvn().zerocon(T_OBJECT);
1476         }
1477       }
1478       return addr;
1479     }
1480     case Op_ShenandoahLoadReferenceBarrier:
1481       return get_load_addr(phase, visited, in->in(ShenandoahLoadReferenceBarrierNode::ValueIn));
1482     case Op_CallDynamicJava:
1483     case Op_CallLeaf:
1484     case Op_CallStaticJava:
1485     case Op_ConN:
1486     case Op_ConP:
1487     case Op_Parm:
1488     case Op_CreateEx:
1489       return phase->igvn().zerocon(T_OBJECT);
1490     default:
1491 #ifdef ASSERT
1492       fatal("Unknown node in get_load_addr: %s", NodeClassNames[in->Opcode()]);
1493 #endif
1494       return phase->igvn().zerocon(T_OBJECT);
1495   }
1496 
1497 }
1498 
1499 void ShenandoahBarrierC2Support::move_gc_state_test_out_of_loop(IfNode* iff, PhaseIdealLoop* phase) {
1500   IdealLoopTree *loop = phase->get_loop(iff);
1501   Node* loop_head = loop->_head;
1502   Node* entry_c = loop_head->in(LoopNode::EntryControl);
1503 
1504   Node* bol = iff->in(1);
1505   Node* cmp = bol->in(1);
1506   Node* andi = cmp->in(1);
1507   Node* load = andi->in(1);
1508 
1509   assert(is_gc_state_load(load), "broken");
1510   if (!phase->is_dominator(load->in(0), entry_c)) {
1511     Node* mem_ctrl = nullptr;
1512     Node* mem = dom_mem(load->in(MemNode::Memory), loop_head, Compile::AliasIdxRaw, mem_ctrl, phase);
1513     load = load->clone();
1514     load->set_req(MemNode::Memory, mem);
1515     load->set_req(0, entry_c);
1516     phase->register_new_node(load, entry_c);
1517     andi = andi->clone();
1518     andi->set_req(1, load);
1519     phase->register_new_node(andi, entry_c);
1520     cmp = cmp->clone();
1521     cmp->set_req(1, andi);
1522     phase->register_new_node(cmp, entry_c);
1523     bol = bol->clone();
1524     bol->set_req(1, cmp);
1525     phase->register_new_node(bol, entry_c);
1526 
1527     phase->igvn().replace_input_of(iff, 1, bol);
1528   }
1529 }
1530 
1531 bool ShenandoahBarrierC2Support::identical_backtoback_ifs(Node* n, PhaseIdealLoop* phase) {
1532   if (!n->is_If() || n->is_CountedLoopEnd()) {
1533     return false;
1534   }
1535   Node* region = n->in(0);
1536 
1537   if (!region->is_Region()) {
1538     return false;
1539   }
1540   Node* dom = phase->idom(region);
1541   if (!dom->is_If()) {
1542     return false;
1543   }
1544 
1545   if (!is_heap_stable_test(n) || !is_heap_stable_test(dom)) {
1546     return false;
1547   }
1548 
1549   IfNode* dom_if = dom->as_If();
1550   Node* proj_true = dom_if->proj_out(1);
1551   Node* proj_false = dom_if->proj_out(0);
1552 
1553   for (uint i = 1; i < region->req(); i++) {
1554     if (phase->is_dominator(proj_true, region->in(i))) {
1555       continue;
1556     }
1557     if (phase->is_dominator(proj_false, region->in(i))) {
1558       continue;
1559     }
1560     return false;
1561   }
1562 
1563   return true;
1564 }
1565 
1566 bool ShenandoahBarrierC2Support::merge_point_safe(Node* region) {
1567   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1568     Node* n = region->fast_out(i);
1569     if (n->is_LoadStore()) {
1570       // Splitting a LoadStore node through phi, causes it to lose its SCMemProj: the split if code doesn't have support
1571       // for a LoadStore at the region the if is split through because that's not expected to happen (LoadStore nodes
1572       // should be between barrier nodes). It does however happen with Shenandoah though because barriers can get
1573       // expanded around a LoadStore node.
1574       return false;
1575     }
1576   }
1577   return true;
1578 }
1579 
1580 
1581 void ShenandoahBarrierC2Support::merge_back_to_back_tests(Node* n, PhaseIdealLoop* phase) {
1582   assert(is_heap_stable_test(n), "no other tests");
1583   if (identical_backtoback_ifs(n, phase)) {
1584     Node* n_ctrl = n->in(0);
1585     if (phase->can_split_if(n_ctrl) && merge_point_safe(n_ctrl)) {
1586       IfNode* dom_if = phase->idom(n_ctrl)->as_If();
1587       if (is_heap_stable_test(n)) {
1588         Node* gc_state_load = n->in(1)->in(1)->in(1)->in(1);
1589         assert(is_gc_state_load(gc_state_load), "broken");
1590         Node* dom_gc_state_load = dom_if->in(1)->in(1)->in(1)->in(1);
1591         assert(is_gc_state_load(dom_gc_state_load), "broken");
1592         if (gc_state_load != dom_gc_state_load) {
1593           phase->igvn().replace_node(gc_state_load, dom_gc_state_load);
1594         }
1595       }
1596       PhiNode* bolphi = PhiNode::make_blank(n_ctrl, n->in(1));
1597       Node* proj_true = dom_if->proj_out(1);
1598       Node* proj_false = dom_if->proj_out(0);
1599       Node* con_true = phase->igvn().makecon(TypeInt::ONE);
1600       Node* con_false = phase->igvn().makecon(TypeInt::ZERO);
1601 
1602       for (uint i = 1; i < n_ctrl->req(); i++) {
1603         if (phase->is_dominator(proj_true, n_ctrl->in(i))) {
1604           bolphi->init_req(i, con_true);
1605         } else {
1606           assert(phase->is_dominator(proj_false, n_ctrl->in(i)), "bad if");
1607           bolphi->init_req(i, con_false);
1608         }
1609       }
1610       phase->register_new_node(bolphi, n_ctrl);
1611       phase->igvn().replace_input_of(n, 1, bolphi);
1612       phase->do_split_if(n);
1613     }
1614   }
1615 }
1616 
1617 IfNode* ShenandoahBarrierC2Support::find_unswitching_candidate(const IdealLoopTree* loop, PhaseIdealLoop* phase) {
1618   // Find first invariant test that doesn't exit the loop
1619   LoopNode *head = loop->_head->as_Loop();
1620   IfNode* unswitch_iff = nullptr;
1621   Node* n = head->in(LoopNode::LoopBackControl);
1622   int loop_has_sfpts = -1;
1623   while (n != head) {
1624     Node* n_dom = phase->idom(n);
1625     if (n->is_Region()) {
1626       if (n_dom->is_If()) {
1627         IfNode* iff = n_dom->as_If();
1628         if (iff->in(1)->is_Bool()) {
1629           BoolNode* bol = iff->in(1)->as_Bool();
1630           if (bol->in(1)->is_Cmp()) {
1631             // If condition is invariant and not a loop exit,
1632             // then found reason to unswitch.
1633             if (is_heap_stable_test(iff) &&
1634                 (loop_has_sfpts == -1 || loop_has_sfpts == 0)) {
1635               assert(!loop->is_loop_exit(iff), "both branches should be in the loop");
1636               if (loop_has_sfpts == -1) {
1637                 for(uint i = 0; i < loop->_body.size(); i++) {
1638                   Node *m = loop->_body[i];
1639                   if (m->is_SafePoint() && !m->is_CallLeaf()) {
1640                     loop_has_sfpts = 1;
1641                     break;
1642                   }
1643                 }
1644                 if (loop_has_sfpts == -1) {
1645                   loop_has_sfpts = 0;
1646                 }
1647               }
1648               if (!loop_has_sfpts) {
1649                 unswitch_iff = iff;
1650               }
1651             }
1652           }
1653         }
1654       }
1655     }
1656     n = n_dom;
1657   }
1658   return unswitch_iff;
1659 }
1660 
1661 
1662 void ShenandoahBarrierC2Support::optimize_after_expansion(VectorSet &visited, Node_Stack &stack, Node_List &old_new, PhaseIdealLoop* phase) {
1663   Node_List heap_stable_tests;
1664   stack.push(phase->C->start(), 0);
1665   do {
1666     Node* n = stack.node();
1667     uint i = stack.index();
1668 
1669     if (i < n->outcnt()) {
1670       Node* u = n->raw_out(i);
1671       stack.set_index(i+1);
1672       if (!visited.test_set(u->_idx)) {
1673         stack.push(u, 0);
1674       }
1675     } else {
1676       stack.pop();
1677       if (n->is_If() && is_heap_stable_test(n)) {
1678         heap_stable_tests.push(n);
1679       }
1680     }
1681   } while (stack.size() > 0);
1682 
1683   for (uint i = 0; i < heap_stable_tests.size(); i++) {
1684     Node* n = heap_stable_tests.at(i);
1685     assert(is_heap_stable_test(n), "only evacuation test");
1686     merge_back_to_back_tests(n, phase);
1687   }
1688 
1689   if (!phase->C->major_progress()) {
1690     VectorSet seen;
1691     for (uint i = 0; i < heap_stable_tests.size(); i++) {
1692       Node* n = heap_stable_tests.at(i);
1693       IdealLoopTree* loop = phase->get_loop(n);
1694       if (loop != phase->ltree_root() &&
1695           loop->_child == nullptr &&
1696           !loop->_irreducible) {
1697         Node* head = loop->_head;
1698         if (head->is_Loop() &&
1699             (!head->is_CountedLoop() || head->as_CountedLoop()->is_main_loop() || head->as_CountedLoop()->is_normal_loop()) &&
1700             !seen.test_set(head->_idx)) {
1701           IfNode* iff = find_unswitching_candidate(loop, phase);
1702           if (iff != nullptr) {
1703             Node* bol = iff->in(1);
1704             if (head->as_Loop()->is_strip_mined()) {
1705               head->as_Loop()->verify_strip_mined(0);
1706             }
1707             move_gc_state_test_out_of_loop(iff, phase);
1708 
1709             AutoNodeBudget node_budget(phase);
1710 
1711             if (loop->policy_unswitching(phase)) {
1712               if (head->as_Loop()->is_strip_mined()) {
1713                 OuterStripMinedLoopNode* outer = head->as_CountedLoop()->outer_loop();
1714                 hide_strip_mined_loop(outer, head->as_CountedLoop(), phase);
1715               }
1716               phase->do_unswitching(loop, old_new);
1717             } else {
1718               // Not proceeding with unswitching. Move load back in
1719               // the loop.
1720               phase->igvn().replace_input_of(iff, 1, bol);
1721             }
1722           }
1723         }
1724       }
1725     }
1726   }
1727 }
1728 
1729 #ifdef ASSERT
1730 static bool has_never_branch(Node* root) {
1731   for (uint i = 1; i < root->req(); i++) {
1732     Node* in = root->in(i);
1733     if (in != nullptr && in->Opcode() == Op_Halt && in->in(0)->is_Proj() && in->in(0)->in(0)->is_NeverBranch()) {
1734       return true;
1735     }
1736   }
1737   return false;
1738 }
1739 #endif
1740 
1741 void MemoryGraphFixer::collect_memory_nodes() {
1742   Node_Stack stack(0);
1743   VectorSet visited;
1744   Node_List regions;
1745 
1746   // Walk the raw memory graph and create a mapping from CFG node to
1747   // memory node. Exclude phis for now.
1748   stack.push(_phase->C->root(), 1);
1749   do {
1750     Node* n = stack.node();
1751     int opc = n->Opcode();
1752     uint i = stack.index();
1753     if (i < n->req()) {
1754       Node* mem = nullptr;
1755       if (opc == Op_Root) {
1756         Node* in = n->in(i);
1757         int in_opc = in->Opcode();
1758         if (in_opc == Op_Return || in_opc == Op_Rethrow) {
1759           mem = in->in(TypeFunc::Memory);
1760         } else if (in_opc == Op_Halt) {
1761           if (in->in(0)->is_Region()) {
1762             Node* r = in->in(0);
1763             for (uint j = 1; j < r->req(); j++) {
1764               assert(!r->in(j)->is_NeverBranch(), "");
1765             }
1766           } else {
1767             Node* proj = in->in(0);
1768             assert(proj->is_Proj(), "");
1769             Node* in = proj->in(0);
1770             assert(in->is_CallStaticJava() || in->is_NeverBranch() || in->Opcode() == Op_Catch || proj->is_IfProj(), "");
1771             if (in->is_CallStaticJava()) {
1772               mem = in->in(TypeFunc::Memory);
1773             } else if (in->Opcode() == Op_Catch) {
1774               Node* call = in->in(0)->in(0);
1775               assert(call->is_Call(), "");
1776               mem = call->in(TypeFunc::Memory);
1777             } else if (in->is_NeverBranch()) {
1778               mem = collect_memory_for_infinite_loop(in);
1779             }
1780           }
1781         } else {
1782 #ifdef ASSERT
1783           n->dump();
1784           in->dump();
1785 #endif
1786           ShouldNotReachHere();
1787         }
1788       } else {
1789         assert(n->is_Phi() && n->bottom_type() == Type::MEMORY, "");
1790         assert(n->adr_type() == TypePtr::BOTTOM || _phase->C->get_alias_index(n->adr_type()) == _alias, "");
1791         mem = n->in(i);
1792       }
1793       i++;
1794       stack.set_index(i);
1795       if (mem == nullptr) {
1796         continue;
1797       }
1798       for (;;) {
1799         if (visited.test_set(mem->_idx) || mem->is_Start()) {
1800           break;
1801         }
1802         if (mem->is_Phi()) {
1803           stack.push(mem, 2);
1804           mem = mem->in(1);
1805         } else if (mem->is_Proj()) {
1806           stack.push(mem, mem->req());
1807           mem = mem->in(0);
1808         } else if (mem->is_SafePoint() || mem->is_MemBar()) {
1809           mem = mem->in(TypeFunc::Memory);
1810         } else if (mem->is_MergeMem()) {
1811           MergeMemNode* mm = mem->as_MergeMem();
1812           mem = mm->memory_at(_alias);
1813         } else if (mem->is_Store() || mem->is_LoadStore() || mem->is_ClearArray()) {
1814           assert(_alias == Compile::AliasIdxRaw, "");
1815           stack.push(mem, mem->req());
1816           mem = mem->in(MemNode::Memory);
1817         } else {
1818 #ifdef ASSERT
1819           mem->dump();
1820 #endif
1821           ShouldNotReachHere();
1822         }
1823       }
1824     } else {
1825       if (n->is_Phi()) {
1826         // Nothing
1827       } else if (!n->is_Root()) {
1828         Node* c = get_ctrl(n);
1829         _memory_nodes.map(c->_idx, n);
1830       }
1831       stack.pop();
1832     }
1833   } while(stack.is_nonempty());
1834 
1835   // Iterate over CFG nodes in rpo and propagate memory state to
1836   // compute memory state at regions, creating new phis if needed.
1837   Node_List rpo_list;
1838   visited.clear();
1839   _phase->rpo(_phase->C->root(), stack, visited, rpo_list);
1840   Node* root = rpo_list.pop();
1841   assert(root == _phase->C->root(), "");
1842 
1843   const bool trace = false;
1844 #ifdef ASSERT
1845   if (trace) {
1846     for (int i = rpo_list.size() - 1; i >= 0; i--) {
1847       Node* c = rpo_list.at(i);
1848       if (_memory_nodes[c->_idx] != nullptr) {
1849         tty->print("X %d", c->_idx);  _memory_nodes[c->_idx]->dump();
1850       }
1851     }
1852   }
1853 #endif
1854   uint last = _phase->C->unique();
1855 
1856 #ifdef ASSERT
1857   uint16_t max_depth = 0;
1858   for (LoopTreeIterator iter(_phase->ltree_root()); !iter.done(); iter.next()) {
1859     IdealLoopTree* lpt = iter.current();
1860     max_depth = MAX2(max_depth, lpt->_nest);
1861   }
1862 #endif
1863 
1864   bool progress = true;
1865   int iteration = 0;
1866   Node_List dead_phis;
1867   while (progress) {
1868     progress = false;
1869     iteration++;
1870     assert(iteration <= 2+max_depth || _phase->C->has_irreducible_loop() || has_never_branch(_phase->C->root()), "");
1871     if (trace) { tty->print_cr("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); }
1872 
1873     for (int i = rpo_list.size() - 1; i >= 0; i--) {
1874       Node* c = rpo_list.at(i);
1875 
1876       Node* prev_mem = _memory_nodes[c->_idx];
1877       if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
1878         Node* prev_region = regions[c->_idx];
1879         Node* unique = nullptr;
1880         for (uint j = 1; j < c->req() && unique != NodeSentinel; j++) {
1881           Node* m = _memory_nodes[c->in(j)->_idx];
1882           assert(m != nullptr || (c->is_Loop() && j == LoopNode::LoopBackControl && iteration == 1) || _phase->C->has_irreducible_loop() || has_never_branch(_phase->C->root()), "expect memory state");
1883           if (m != nullptr) {
1884             if (m == prev_region && ((c->is_Loop() && j == LoopNode::LoopBackControl) || (prev_region->is_Phi() && prev_region->in(0) == c))) {
1885               assert((c->is_Loop() && j == LoopNode::LoopBackControl) || _phase->C->has_irreducible_loop() || has_never_branch(_phase->C->root()), "");
1886               // continue
1887             } else if (unique == nullptr) {
1888               unique = m;
1889             } else if (m == unique) {
1890               // continue
1891             } else {
1892               unique = NodeSentinel;
1893             }
1894           }
1895         }
1896         assert(unique != nullptr, "empty phi???");
1897         if (unique != NodeSentinel) {
1898           if (prev_region != nullptr && prev_region->is_Phi() && prev_region->in(0) == c) {
1899             dead_phis.push(prev_region);
1900           }
1901           regions.map(c->_idx, unique);
1902         } else {
1903           Node* phi = nullptr;
1904           if (prev_region != nullptr && prev_region->is_Phi() && prev_region->in(0) == c && prev_region->_idx >= last) {
1905             phi = prev_region;
1906             for (uint k = 1; k < c->req(); k++) {
1907               Node* m = _memory_nodes[c->in(k)->_idx];
1908               assert(m != nullptr, "expect memory state");
1909               phi->set_req(k, m);
1910             }
1911           } else {
1912             for (DUIterator_Fast jmax, j = c->fast_outs(jmax); j < jmax && phi == nullptr; j++) {
1913               Node* u = c->fast_out(j);
1914               if (u->is_Phi() && u->bottom_type() == Type::MEMORY &&
1915                   (u->adr_type() == TypePtr::BOTTOM || _phase->C->get_alias_index(u->adr_type()) == _alias)) {
1916                 phi = u;
1917                 for (uint k = 1; k < c->req() && phi != nullptr; k++) {
1918                   Node* m = _memory_nodes[c->in(k)->_idx];
1919                   assert(m != nullptr, "expect memory state");
1920                   if (u->in(k) != m) {
1921                     phi = NodeSentinel;
1922                   }
1923                 }
1924               }
1925             }
1926             if (phi == NodeSentinel) {
1927               phi = new PhiNode(c, Type::MEMORY, _phase->C->get_adr_type(_alias));
1928               for (uint k = 1; k < c->req(); k++) {
1929                 Node* m = _memory_nodes[c->in(k)->_idx];
1930                 assert(m != nullptr, "expect memory state");
1931                 phi->init_req(k, m);
1932               }
1933             }
1934           }
1935           if (phi != nullptr) {
1936             regions.map(c->_idx, phi);
1937           } else {
1938             assert(c->unique_ctrl_out()->Opcode() == Op_Halt, "expected memory state");
1939           }
1940         }
1941         Node* current_region = regions[c->_idx];
1942         if (current_region != prev_region) {
1943           progress = true;
1944           if (prev_region == prev_mem) {
1945             _memory_nodes.map(c->_idx, current_region);
1946           }
1947         }
1948       } else if (prev_mem == nullptr || prev_mem->is_Phi() || ctrl_or_self(prev_mem) != c) {
1949         Node* m = _memory_nodes[_phase->idom(c)->_idx];
1950         assert(m != nullptr || c->Opcode() == Op_Halt, "expect memory state");
1951         if (m != prev_mem) {
1952           _memory_nodes.map(c->_idx, m);
1953           progress = true;
1954         }
1955       }
1956 #ifdef ASSERT
1957       if (trace) { tty->print("X %d", c->_idx);  _memory_nodes[c->_idx]->dump(); }
1958 #endif
1959     }
1960   }
1961 
1962   // Replace existing phi with computed memory state for that region
1963   // if different (could be a new phi or a dominating memory node if
1964   // that phi was found to be useless).
1965   while (dead_phis.size() > 0) {
1966     Node* n = dead_phis.pop();
1967     n->replace_by(_phase->C->top());
1968     n->destruct(&_phase->igvn());
1969   }
1970   for (int i = rpo_list.size() - 1; i >= 0; i--) {
1971     Node* c = rpo_list.at(i);
1972     if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
1973       Node* n = regions[c->_idx];
1974       assert(n != nullptr || c->unique_ctrl_out()->Opcode() == Op_Halt, "expected memory state");
1975       if (n != nullptr && n->is_Phi() && n->_idx >= last && n->in(0) == c) {
1976         _phase->register_new_node(n, c);
1977       }
1978     }
1979   }
1980   for (int i = rpo_list.size() - 1; i >= 0; i--) {
1981     Node* c = rpo_list.at(i);
1982     if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
1983       Node* n = regions[c->_idx];
1984       assert(n != nullptr || c->unique_ctrl_out()->Opcode() == Op_Halt, "expected memory state");
1985       for (DUIterator_Fast imax, i = c->fast_outs(imax); i < imax; i++) {
1986         Node* u = c->fast_out(i);
1987         if (u->is_Phi() && u->bottom_type() == Type::MEMORY &&
1988             u != n) {
1989           assert(c->unique_ctrl_out()->Opcode() != Op_Halt, "expected memory state");
1990           if (u->adr_type() == TypePtr::BOTTOM) {
1991             fix_memory_uses(u, n, n, c);
1992           } else if (_phase->C->get_alias_index(u->adr_type()) == _alias) {
1993             _phase->lazy_replace(u, n);
1994             --i; --imax;
1995           }
1996         }
1997       }
1998     }
1999   }
2000 }
2001 
2002 Node* MemoryGraphFixer::collect_memory_for_infinite_loop(const Node* in) {
2003   Node* mem = nullptr;
2004   Node* head = in->in(0);
2005   assert(head->is_Region(), "unexpected infinite loop graph shape");
2006 
2007   Node* phi_mem = nullptr;
2008   for (DUIterator_Fast jmax, j = head->fast_outs(jmax); j < jmax; j++) {
2009     Node* u = head->fast_out(j);
2010     if (u->is_Phi() && u->bottom_type() == Type::MEMORY) {
2011       if (_phase->C->get_alias_index(u->adr_type()) == _alias) {
2012         assert(phi_mem == nullptr || phi_mem->adr_type() == TypePtr::BOTTOM, "");
2013         phi_mem = u;
2014       } else if (u->adr_type() == TypePtr::BOTTOM) {
2015         assert(phi_mem == nullptr || _phase->C->get_alias_index(phi_mem->adr_type()) == _alias, "");
2016         if (phi_mem == nullptr) {
2017           phi_mem = u;
2018         }
2019       }
2020     }
2021   }
2022   if (phi_mem == nullptr) {
2023     ResourceMark rm;
2024     Node_Stack stack(0);
2025     stack.push(head, 1);
2026     do {
2027       Node* n = stack.node();
2028       uint i = stack.index();
2029       if (i >= n->req()) {
2030         stack.pop();
2031       } else {
2032         stack.set_index(i + 1);
2033         Node* c = n->in(i);
2034         assert(c != head, "should have found a safepoint on the way");
2035         if (stack.size() != 1 || _phase->is_dominator(head, c)) {
2036           for (;;) {
2037             if (c->is_Region()) {
2038               stack.push(c, 1);
2039               break;
2040             } else if (c->is_SafePoint() && !c->is_CallLeaf()) {
2041               Node* m = c->in(TypeFunc::Memory);
2042               if (m->is_MergeMem()) {
2043                 m = m->as_MergeMem()->memory_at(_alias);
2044               }
2045               assert(mem == nullptr || mem == m, "several memory states");
2046               mem = m;
2047               break;
2048             } else {
2049               assert(c != c->in(0), "");
2050               c = c->in(0);
2051             }
2052           }
2053         }
2054       }
2055     } while (stack.size() > 0);
2056     assert(mem != nullptr, "should have found safepoint");
2057   } else {
2058     mem = phi_mem;
2059   }
2060   return mem;
2061 }
2062 
2063 Node* MemoryGraphFixer::get_ctrl(Node* n) const {
2064   Node* c = _phase->get_ctrl(n);
2065   if (n->is_Proj() && n->in(0) != nullptr && n->in(0)->is_Call()) {
2066     assert(c == n->in(0), "");
2067     CallNode* call = c->as_Call();
2068     CallProjections projs;
2069     call->extract_projections(&projs, true, false);
2070     if (projs.catchall_memproj != nullptr) {
2071       if (projs.fallthrough_memproj == n) {
2072         c = projs.fallthrough_catchproj;
2073       } else {
2074         assert(projs.catchall_memproj == n, "");
2075         c = projs.catchall_catchproj;
2076       }
2077     }
2078   }
2079   return c;
2080 }
2081 
2082 Node* MemoryGraphFixer::ctrl_or_self(Node* n) const {
2083   if (_phase->has_ctrl(n))
2084     return get_ctrl(n);
2085   else {
2086     assert (n->is_CFG(), "must be a CFG node");
2087     return n;
2088   }
2089 }
2090 
2091 bool MemoryGraphFixer::mem_is_valid(Node* m, Node* c) const {
2092   return m != nullptr && get_ctrl(m) == c;
2093 }
2094 
2095 Node* MemoryGraphFixer::find_mem(Node* ctrl, Node* n) const {
2096   assert(n == nullptr || _phase->ctrl_or_self(n) == ctrl, "");
2097   assert(!ctrl->is_Call() || ctrl == n, "projection expected");
2098 #ifdef ASSERT
2099   if ((ctrl->is_Proj() && ctrl->in(0)->is_Call()) ||
2100       (ctrl->is_Catch() && ctrl->in(0)->in(0)->is_Call())) {
2101     CallNode* call = ctrl->is_Proj() ? ctrl->in(0)->as_Call() : ctrl->in(0)->in(0)->as_Call();
2102     int mems = 0;
2103     for (DUIterator_Fast imax, i = call->fast_outs(imax); i < imax; i++) {
2104       Node* u = call->fast_out(i);
2105       if (u->bottom_type() == Type::MEMORY) {
2106         mems++;
2107       }
2108     }
2109     assert(mems <= 1, "No node right after call if multiple mem projections");
2110   }
2111 #endif
2112   Node* mem = _memory_nodes[ctrl->_idx];
2113   Node* c = ctrl;
2114   while (!mem_is_valid(mem, c) &&
2115          (!c->is_CatchProj() || mem == nullptr || c->in(0)->in(0)->in(0) != get_ctrl(mem))) {
2116     c = _phase->idom(c);
2117     mem = _memory_nodes[c->_idx];
2118   }
2119   if (n != nullptr && mem_is_valid(mem, c)) {
2120     while (!ShenandoahBarrierC2Support::is_dominator_same_ctrl(c, mem, n, _phase) && _phase->ctrl_or_self(mem) == ctrl) {
2121       mem = next_mem(mem, _alias);
2122     }
2123     if (mem->is_MergeMem()) {
2124       mem = mem->as_MergeMem()->memory_at(_alias);
2125     }
2126     if (!mem_is_valid(mem, c)) {
2127       do {
2128         c = _phase->idom(c);
2129         mem = _memory_nodes[c->_idx];
2130       } while (!mem_is_valid(mem, c) &&
2131                (!c->is_CatchProj() || mem == nullptr || c->in(0)->in(0)->in(0) != get_ctrl(mem)));
2132     }
2133   }
2134   assert(mem->bottom_type() == Type::MEMORY, "");
2135   return mem;
2136 }
2137 
2138 bool MemoryGraphFixer::has_mem_phi(Node* region) const {
2139   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
2140     Node* use = region->fast_out(i);
2141     if (use->is_Phi() && use->bottom_type() == Type::MEMORY &&
2142         (_phase->C->get_alias_index(use->adr_type()) == _alias)) {
2143       return true;
2144     }
2145   }
2146   return false;
2147 }
2148 
2149 void MemoryGraphFixer::fix_mem(Node* ctrl, Node* new_ctrl, Node* mem, Node* mem_for_ctrl, Node* new_mem, Unique_Node_List& uses) {
2150   assert(_phase->ctrl_or_self(new_mem) == new_ctrl, "");
2151   const bool trace = false;
2152   DEBUG_ONLY(if (trace) { tty->print("ZZZ control is"); ctrl->dump(); });
2153   DEBUG_ONLY(if (trace) { tty->print("ZZZ mem is"); mem->dump(); });
2154   GrowableArray<Node*> phis;
2155   if (mem_for_ctrl != mem) {
2156     Node* old = mem_for_ctrl;
2157     Node* prev = nullptr;
2158     while (old != mem) {
2159       prev = old;
2160       if (old->is_Store() || old->is_ClearArray() || old->is_LoadStore()) {
2161         assert(_alias == Compile::AliasIdxRaw, "");
2162         old = old->in(MemNode::Memory);
2163       } else if (old->Opcode() == Op_SCMemProj) {
2164         assert(_alias == Compile::AliasIdxRaw, "");
2165         old = old->in(0);
2166       } else {
2167         ShouldNotReachHere();
2168       }
2169     }
2170     assert(prev != nullptr, "");
2171     if (new_ctrl != ctrl) {
2172       _memory_nodes.map(ctrl->_idx, mem);
2173       _memory_nodes.map(new_ctrl->_idx, mem_for_ctrl);
2174     }
2175     uint input = (uint)MemNode::Memory;
2176     _phase->igvn().replace_input_of(prev, input, new_mem);
2177   } else {
2178     uses.clear();
2179     _memory_nodes.map(new_ctrl->_idx, new_mem);
2180     uses.push(new_ctrl);
2181     for(uint next = 0; next < uses.size(); next++ ) {
2182       Node *n = uses.at(next);
2183       assert(n->is_CFG(), "");
2184       DEBUG_ONLY(if (trace) { tty->print("ZZZ ctrl"); n->dump(); });
2185       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2186         Node* u = n->fast_out(i);
2187         if (!u->is_Root() && u->is_CFG() && u != n) {
2188           Node* m = _memory_nodes[u->_idx];
2189           if (u->is_Region() && (!u->is_OuterStripMinedLoop() || _include_lsm) &&
2190               !has_mem_phi(u) &&
2191               u->unique_ctrl_out()->Opcode() != Op_Halt) {
2192             DEBUG_ONLY(if (trace) { tty->print("ZZZ region"); u->dump(); });
2193             DEBUG_ONLY(if (trace && m != nullptr) { tty->print("ZZZ mem"); m->dump(); });
2194 
2195             if (!mem_is_valid(m, u) || !m->is_Phi()) {
2196               bool push = true;
2197               bool create_phi = true;
2198               if (_phase->is_dominator(new_ctrl, u)) {
2199                 create_phi = false;
2200               }
2201               if (create_phi) {
2202                 Node* phi = new PhiNode(u, Type::MEMORY, _phase->C->get_adr_type(_alias));
2203                 _phase->register_new_node(phi, u);
2204                 phis.push(phi);
2205                 DEBUG_ONLY(if (trace) { tty->print("ZZZ new phi"); phi->dump(); });
2206                 if (!mem_is_valid(m, u)) {
2207                   DEBUG_ONLY(if (trace) { tty->print("ZZZ setting mem"); phi->dump(); });
2208                   _memory_nodes.map(u->_idx, phi);
2209                 } else {
2210                   DEBUG_ONLY(if (trace) { tty->print("ZZZ NOT setting mem"); m->dump(); });
2211                   for (;;) {
2212                     assert(m->is_Mem() || m->is_LoadStore() || m->is_Proj(), "");
2213                     Node* next = nullptr;
2214                     if (m->is_Proj()) {
2215                       next = m->in(0);
2216                     } else {
2217                       assert(m->is_Mem() || m->is_LoadStore(), "");
2218                       assert(_alias == Compile::AliasIdxRaw, "");
2219                       next = m->in(MemNode::Memory);
2220                     }
2221                     if (_phase->get_ctrl(next) != u) {
2222                       break;
2223                     }
2224                     if (next->is_MergeMem()) {
2225                       assert(_phase->get_ctrl(next->as_MergeMem()->memory_at(_alias)) != u, "");
2226                       break;
2227                     }
2228                     if (next->is_Phi()) {
2229                       assert(next->adr_type() == TypePtr::BOTTOM && next->in(0) == u, "");
2230                       break;
2231                     }
2232                     m = next;
2233                   }
2234 
2235                   DEBUG_ONLY(if (trace) { tty->print("ZZZ setting to phi"); m->dump(); });
2236                   assert(m->is_Mem() || m->is_LoadStore(), "");
2237                   uint input = (uint)MemNode::Memory;
2238                   _phase->igvn().replace_input_of(m, input, phi);
2239                   push = false;
2240                 }
2241               } else {
2242                 DEBUG_ONLY(if (trace) { tty->print("ZZZ skipping region"); u->dump(); });
2243               }
2244               if (push) {
2245                 uses.push(u);
2246               }
2247             }
2248           } else if (!mem_is_valid(m, u) &&
2249                      !(u->Opcode() == Op_CProj && u->in(0)->is_NeverBranch() && u->as_Proj()->_con == 1)) {
2250             uses.push(u);
2251           }
2252         }
2253       }
2254     }
2255     for (int i = 0; i < phis.length(); i++) {
2256       Node* n = phis.at(i);
2257       Node* r = n->in(0);
2258       DEBUG_ONLY(if (trace) { tty->print("ZZZ fixing new phi"); n->dump(); });
2259       for (uint j = 1; j < n->req(); j++) {
2260         Node* m = find_mem(r->in(j), nullptr);
2261         _phase->igvn().replace_input_of(n, j, m);
2262         DEBUG_ONLY(if (trace) { tty->print("ZZZ fixing new phi: %d", j); m->dump(); });
2263       }
2264     }
2265   }
2266   uint last = _phase->C->unique();
2267   MergeMemNode* mm = nullptr;
2268   int alias = _alias;
2269   DEBUG_ONLY(if (trace) { tty->print("ZZZ raw mem is"); mem->dump(); });
2270   // Process loads first to not miss an anti-dependency: if the memory
2271   // edge of a store is updated before a load is processed then an
2272   // anti-dependency may be missed.
2273   for (DUIterator i = mem->outs(); mem->has_out(i); i++) {
2274     Node* u = mem->out(i);
2275     if (u->_idx < last && u->is_Load() && _phase->C->get_alias_index(u->adr_type()) == alias) {
2276       Node* m = find_mem(_phase->get_ctrl(u), u);
2277       if (m != mem) {
2278         DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2279         _phase->igvn().replace_input_of(u, MemNode::Memory, m);
2280         --i;
2281       }
2282     }
2283   }
2284   for (DUIterator i = mem->outs(); mem->has_out(i); i++) {
2285     Node* u = mem->out(i);
2286     if (u->_idx < last) {
2287       if (u->is_Mem()) {
2288         if (_phase->C->get_alias_index(u->adr_type()) == alias) {
2289           Node* m = find_mem(_phase->get_ctrl(u), u);
2290           if (m != mem) {
2291             DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2292             _phase->igvn().replace_input_of(u, MemNode::Memory, m);
2293             --i;
2294           }
2295         }
2296       } else if (u->is_MergeMem()) {
2297         MergeMemNode* u_mm = u->as_MergeMem();
2298         if (u_mm->memory_at(alias) == mem) {
2299           MergeMemNode* newmm = nullptr;
2300           for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
2301             Node* uu = u->fast_out(j);
2302             assert(!uu->is_MergeMem(), "chain of MergeMems?");
2303             if (uu->is_Phi()) {
2304               assert(uu->adr_type() == TypePtr::BOTTOM, "");
2305               Node* region = uu->in(0);
2306               int nb = 0;
2307               for (uint k = 1; k < uu->req(); k++) {
2308                 if (uu->in(k) == u) {
2309                   Node* m = find_mem(region->in(k), nullptr);
2310                   if (m != mem) {
2311                     DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of phi %d", k); uu->dump(); });
2312                     newmm = clone_merge_mem(u, mem, m, _phase->ctrl_or_self(m), i);
2313                     if (newmm != u) {
2314                       _phase->igvn().replace_input_of(uu, k, newmm);
2315                       nb++;
2316                       --jmax;
2317                     }
2318                   }
2319                 }
2320               }
2321               if (nb > 0) {
2322                 --j;
2323               }
2324             } else {
2325               Node* m = find_mem(_phase->ctrl_or_self(uu), uu);
2326               if (m != mem) {
2327                 DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); uu->dump(); });
2328                 newmm = clone_merge_mem(u, mem, m, _phase->ctrl_or_self(m), i);
2329                 if (newmm != u) {
2330                   _phase->igvn().replace_input_of(uu, uu->find_edge(u), newmm);
2331                   --j, --jmax;
2332                 }
2333               }
2334             }
2335           }
2336         }
2337       } else if (u->is_Phi()) {
2338         assert(u->bottom_type() == Type::MEMORY, "what else?");
2339         if (_phase->C->get_alias_index(u->adr_type()) == alias || u->adr_type() == TypePtr::BOTTOM) {
2340           Node* region = u->in(0);
2341           bool replaced = false;
2342           for (uint j = 1; j < u->req(); j++) {
2343             if (u->in(j) == mem) {
2344               Node* m = find_mem(region->in(j), nullptr);
2345               Node* nnew = m;
2346               if (m != mem) {
2347                 if (u->adr_type() == TypePtr::BOTTOM) {
2348                   mm = allocate_merge_mem(mem, m, _phase->ctrl_or_self(m));
2349                   nnew = mm;
2350                 }
2351                 DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of phi %d", j); u->dump(); });
2352                 _phase->igvn().replace_input_of(u, j, nnew);
2353                 replaced = true;
2354               }
2355             }
2356           }
2357           if (replaced) {
2358             --i;
2359           }
2360         }
2361       } else if ((u->adr_type() == TypePtr::BOTTOM && u->Opcode() != Op_StrInflatedCopy) ||
2362                  u->adr_type() == nullptr) {
2363         assert(u->adr_type() != nullptr ||
2364                u->Opcode() == Op_Rethrow ||
2365                u->Opcode() == Op_Return ||
2366                u->Opcode() == Op_SafePoint ||
2367                (u->is_CallStaticJava() && u->as_CallStaticJava()->uncommon_trap_request() != 0) ||
2368                (u->is_CallStaticJava() && u->as_CallStaticJava()->_entry_point == OptoRuntime::rethrow_stub()) ||
2369                u->Opcode() == Op_CallLeaf, "");
2370         Node* m = find_mem(_phase->ctrl_or_self(u), u);
2371         if (m != mem) {
2372           mm = allocate_merge_mem(mem, m, _phase->get_ctrl(m));
2373           _phase->igvn().replace_input_of(u, u->find_edge(mem), mm);
2374           --i;
2375         }
2376       } else if (_phase->C->get_alias_index(u->adr_type()) == alias) {
2377         Node* m = find_mem(_phase->ctrl_or_self(u), u);
2378         if (m != mem) {
2379           DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2380           _phase->igvn().replace_input_of(u, u->find_edge(mem), m);
2381           --i;
2382         }
2383       } else if (u->adr_type() != TypePtr::BOTTOM &&
2384                  _memory_nodes[_phase->ctrl_or_self(u)->_idx] == u) {
2385         Node* m = find_mem(_phase->ctrl_or_self(u), u);
2386         assert(m != mem, "");
2387         // u is on the wrong slice...
2388         assert(u->is_ClearArray(), "");
2389         DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2390         _phase->igvn().replace_input_of(u, u->find_edge(mem), m);
2391         --i;
2392       }
2393     }
2394   }
2395 #ifdef ASSERT
2396   assert(new_mem->outcnt() > 0, "");
2397   for (int i = 0; i < phis.length(); i++) {
2398     Node* n = phis.at(i);
2399     assert(n->outcnt() > 0, "new phi must have uses now");
2400   }
2401 #endif
2402 }
2403 
2404 void MemoryGraphFixer::record_new_ctrl(Node* ctrl, Node* new_ctrl, Node* mem, Node* mem_for_ctrl) {
2405   if (mem_for_ctrl != mem && new_ctrl != ctrl) {
2406     _memory_nodes.map(ctrl->_idx, mem);
2407     _memory_nodes.map(new_ctrl->_idx, mem_for_ctrl);
2408   }
2409 }
2410 
2411 MergeMemNode* MemoryGraphFixer::allocate_merge_mem(Node* mem, Node* rep_proj, Node* rep_ctrl) const {
2412   MergeMemNode* mm = MergeMemNode::make(mem);
2413   mm->set_memory_at(_alias, rep_proj);
2414   _phase->register_new_node(mm, rep_ctrl);
2415   return mm;
2416 }
2417 
2418 MergeMemNode* MemoryGraphFixer::clone_merge_mem(Node* u, Node* mem, Node* rep_proj, Node* rep_ctrl, DUIterator& i) const {
2419   MergeMemNode* newmm = nullptr;
2420   MergeMemNode* u_mm = u->as_MergeMem();
2421   Node* c = _phase->get_ctrl(u);
2422   if (_phase->is_dominator(c, rep_ctrl)) {
2423     c = rep_ctrl;
2424   } else {
2425     assert(_phase->is_dominator(rep_ctrl, c), "one must dominate the other");
2426   }
2427   if (u->outcnt() == 1) {
2428     if (u->req() > (uint)_alias && u->in(_alias) == mem) {
2429       _phase->igvn().replace_input_of(u, _alias, rep_proj);
2430       --i;
2431     } else {
2432       _phase->igvn().rehash_node_delayed(u);
2433       u_mm->set_memory_at(_alias, rep_proj);
2434     }
2435     newmm = u_mm;
2436     _phase->set_ctrl_and_loop(u, c);
2437   } else {
2438     // can't simply clone u and then change one of its input because
2439     // it adds and then removes an edge which messes with the
2440     // DUIterator
2441     newmm = MergeMemNode::make(u_mm->base_memory());
2442     for (uint j = 0; j < u->req(); j++) {
2443       if (j < newmm->req()) {
2444         if (j == (uint)_alias) {
2445           newmm->set_req(j, rep_proj);
2446         } else if (newmm->in(j) != u->in(j)) {
2447           newmm->set_req(j, u->in(j));
2448         }
2449       } else if (j == (uint)_alias) {
2450         newmm->add_req(rep_proj);
2451       } else {
2452         newmm->add_req(u->in(j));
2453       }
2454     }
2455     if ((uint)_alias >= u->req()) {
2456       newmm->set_memory_at(_alias, rep_proj);
2457     }
2458     _phase->register_new_node(newmm, c);
2459   }
2460   return newmm;
2461 }
2462 
2463 bool MemoryGraphFixer::should_process_phi(Node* phi) const {
2464   if (phi->adr_type() == TypePtr::BOTTOM) {
2465     Node* region = phi->in(0);
2466     for (DUIterator_Fast jmax, j = region->fast_outs(jmax); j < jmax; j++) {
2467       Node* uu = region->fast_out(j);
2468       if (uu->is_Phi() && uu != phi && uu->bottom_type() == Type::MEMORY && _phase->C->get_alias_index(uu->adr_type()) == _alias) {
2469         return false;
2470       }
2471     }
2472     return true;
2473   }
2474   return _phase->C->get_alias_index(phi->adr_type()) == _alias;
2475 }
2476 
2477 void MemoryGraphFixer::fix_memory_uses(Node* mem, Node* replacement, Node* rep_proj, Node* rep_ctrl) const {
2478   uint last = _phase-> C->unique();
2479   MergeMemNode* mm = nullptr;
2480   assert(mem->bottom_type() == Type::MEMORY, "");
2481   for (DUIterator i = mem->outs(); mem->has_out(i); i++) {
2482     Node* u = mem->out(i);
2483     if (u != replacement && u->_idx < last) {
2484       if (u->is_MergeMem()) {
2485         MergeMemNode* u_mm = u->as_MergeMem();
2486         if (u_mm->memory_at(_alias) == mem) {
2487           MergeMemNode* newmm = nullptr;
2488           for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
2489             Node* uu = u->fast_out(j);
2490             assert(!uu->is_MergeMem(), "chain of MergeMems?");
2491             if (uu->is_Phi()) {
2492               if (should_process_phi(uu)) {
2493                 Node* region = uu->in(0);
2494                 int nb = 0;
2495                 for (uint k = 1; k < uu->req(); k++) {
2496                   if (uu->in(k) == u && _phase->is_dominator(rep_ctrl, region->in(k))) {
2497                     if (newmm == nullptr) {
2498                       newmm = clone_merge_mem(u, mem, rep_proj, rep_ctrl, i);
2499                     }
2500                     if (newmm != u) {
2501                       _phase->igvn().replace_input_of(uu, k, newmm);
2502                       nb++;
2503                       --jmax;
2504                     }
2505                   }
2506                 }
2507                 if (nb > 0) {
2508                   --j;
2509                 }
2510               }
2511             } else {
2512               if (rep_ctrl != uu && ShenandoahBarrierC2Support::is_dominator(rep_ctrl, _phase->ctrl_or_self(uu), replacement, uu, _phase)) {
2513                 if (newmm == nullptr) {
2514                   newmm = clone_merge_mem(u, mem, rep_proj, rep_ctrl, i);
2515                 }
2516                 if (newmm != u) {
2517                   _phase->igvn().replace_input_of(uu, uu->find_edge(u), newmm);
2518                   --j, --jmax;
2519                 }
2520               }
2521             }
2522           }
2523         }
2524       } else if (u->is_Phi()) {
2525         assert(u->bottom_type() == Type::MEMORY, "what else?");
2526         Node* region = u->in(0);
2527         if (should_process_phi(u)) {
2528           bool replaced = false;
2529           for (uint j = 1; j < u->req(); j++) {
2530             if (u->in(j) == mem && _phase->is_dominator(rep_ctrl, region->in(j))) {
2531               Node* nnew = rep_proj;
2532               if (u->adr_type() == TypePtr::BOTTOM) {
2533                 if (mm == nullptr) {
2534                   mm = allocate_merge_mem(mem, rep_proj, rep_ctrl);
2535                 }
2536                 nnew = mm;
2537               }
2538               _phase->igvn().replace_input_of(u, j, nnew);
2539               replaced = true;
2540             }
2541           }
2542           if (replaced) {
2543             --i;
2544           }
2545 
2546         }
2547       } else if ((u->adr_type() == TypePtr::BOTTOM && u->Opcode() != Op_StrInflatedCopy) ||
2548                  u->adr_type() == nullptr) {
2549         assert(u->adr_type() != nullptr ||
2550                u->Opcode() == Op_Rethrow ||
2551                u->Opcode() == Op_Return ||
2552                u->Opcode() == Op_SafePoint ||
2553                (u->is_CallStaticJava() && u->as_CallStaticJava()->uncommon_trap_request() != 0) ||
2554                (u->is_CallStaticJava() && u->as_CallStaticJava()->_entry_point == OptoRuntime::rethrow_stub()) ||
2555                u->Opcode() == Op_CallLeaf, "%s", u->Name());
2556         if (ShenandoahBarrierC2Support::is_dominator(rep_ctrl, _phase->ctrl_or_self(u), replacement, u, _phase)) {
2557           if (mm == nullptr) {
2558             mm = allocate_merge_mem(mem, rep_proj, rep_ctrl);
2559           }
2560           _phase->igvn().replace_input_of(u, u->find_edge(mem), mm);
2561           --i;
2562         }
2563       } else if (_phase->C->get_alias_index(u->adr_type()) == _alias) {
2564         if (ShenandoahBarrierC2Support::is_dominator(rep_ctrl, _phase->ctrl_or_self(u), replacement, u, _phase)) {
2565           _phase->igvn().replace_input_of(u, u->find_edge(mem), rep_proj);
2566           --i;
2567         }
2568       }
2569     }
2570   }
2571 }
2572 
2573 ShenandoahLoadReferenceBarrierNode::ShenandoahLoadReferenceBarrierNode(Node* ctrl, Node* obj, DecoratorSet decorators)
2574 : Node(ctrl, obj), _decorators(decorators) {
2575   ShenandoahBarrierSetC2::bsc2()->state()->add_load_reference_barrier(this);
2576 }
2577 
2578 DecoratorSet ShenandoahLoadReferenceBarrierNode::decorators() const {
2579   return _decorators;
2580 }
2581 
2582 uint ShenandoahLoadReferenceBarrierNode::size_of() const {
2583   return sizeof(*this);
2584 }
2585 
2586 static DecoratorSet mask_decorators(DecoratorSet decorators) {
2587   return decorators & (ON_STRONG_OOP_REF | ON_WEAK_OOP_REF | ON_PHANTOM_OOP_REF | ON_UNKNOWN_OOP_REF | IN_NATIVE);
2588 }
2589 
2590 uint ShenandoahLoadReferenceBarrierNode::hash() const {
2591   uint hash = Node::hash();
2592   hash += mask_decorators(_decorators);
2593   return hash;
2594 }
2595 
2596 bool ShenandoahLoadReferenceBarrierNode::cmp( const Node &n ) const {
2597   return Node::cmp(n) && n.Opcode() == Op_ShenandoahLoadReferenceBarrier &&
2598          mask_decorators(_decorators) == mask_decorators(((const ShenandoahLoadReferenceBarrierNode&)n)._decorators);
2599 }
2600 
2601 const Type* ShenandoahLoadReferenceBarrierNode::bottom_type() const {
2602   if (in(ValueIn) == nullptr || in(ValueIn)->is_top()) {
2603     return Type::TOP;
2604   }
2605   const Type* t = in(ValueIn)->bottom_type();
2606   if (t == TypePtr::NULL_PTR) {
2607     return t;
2608   }
2609 
2610   if (ShenandoahBarrierSet::is_strong_access(decorators())) {
2611     return t;
2612   }
2613 
2614   return t->meet(TypePtr::NULL_PTR);
2615 }
2616 
2617 const Type* ShenandoahLoadReferenceBarrierNode::Value(PhaseGVN* phase) const {
2618   // Either input is TOP ==> the result is TOP
2619   const Type *t2 = phase->type(in(ValueIn));
2620   if( t2 == Type::TOP ) return Type::TOP;
2621 
2622   if (t2 == TypePtr::NULL_PTR) {
2623     return t2;
2624   }
2625 
2626   if (ShenandoahBarrierSet::is_strong_access(decorators())) {
2627     return t2;
2628   }
2629 
2630   return t2->meet(TypePtr::NULL_PTR);
2631 }
2632 
2633 Node* ShenandoahLoadReferenceBarrierNode::Identity(PhaseGVN* phase) {
2634   Node* value = in(ValueIn);
2635   if (!needs_barrier(phase, value)) {
2636     return value;
2637   }
2638   return this;
2639 }
2640 
2641 bool ShenandoahLoadReferenceBarrierNode::needs_barrier(PhaseGVN* phase, Node* n) {
2642   Unique_Node_List visited;
2643   return needs_barrier_impl(phase, n, visited);
2644 }
2645 
2646 bool ShenandoahLoadReferenceBarrierNode::needs_barrier_impl(PhaseGVN* phase, Node* n, Unique_Node_List &visited) {
2647   if (n == nullptr) return false;
2648   if (visited.member(n)) {
2649     return false; // Been there.
2650   }
2651   visited.push(n);
2652 
2653   if (n->is_Allocate()) {
2654     // tty->print_cr("optimize barrier on alloc");
2655     return false;
2656   }
2657   if (n->is_Call()) {
2658     // tty->print_cr("optimize barrier on call");
2659     return false;
2660   }
2661 
2662   const Type* type = phase->type(n);
2663   if (type == Type::TOP) {
2664     return false;
2665   }
2666   if (type->make_ptr()->higher_equal(TypePtr::NULL_PTR)) {
2667     // tty->print_cr("optimize barrier on null");
2668     return false;
2669   }
2670   if (type->make_oopptr() && type->make_oopptr()->const_oop() != nullptr) {
2671     // tty->print_cr("optimize barrier on constant");
2672     return false;
2673   }
2674 
2675   switch (n->Opcode()) {
2676     case Op_AddP:
2677       return true; // TODO: Can refine?
2678     case Op_LoadP:
2679     case Op_ShenandoahCompareAndExchangeN:
2680     case Op_ShenandoahCompareAndExchangeP:
2681     case Op_CompareAndExchangeN:
2682     case Op_CompareAndExchangeP:
2683     case Op_GetAndSetN:
2684     case Op_GetAndSetP:
2685       return true;
2686     case Op_Phi: {
2687       for (uint i = 1; i < n->req(); i++) {
2688         if (needs_barrier_impl(phase, n->in(i), visited)) return true;
2689       }
2690       return false;
2691     }
2692     case Op_CheckCastPP:
2693     case Op_CastPP:
2694       return needs_barrier_impl(phase, n->in(1), visited);
2695     case Op_Proj:
2696       return needs_barrier_impl(phase, n->in(0), visited);
2697     case Op_ShenandoahLoadReferenceBarrier:
2698       // tty->print_cr("optimize barrier on barrier");
2699       return false;
2700     case Op_Parm:
2701       // tty->print_cr("optimize barrier on input arg");
2702       return false;
2703     case Op_DecodeN:
2704     case Op_EncodeP:
2705       return needs_barrier_impl(phase, n->in(1), visited);
2706     case Op_LoadN:
2707       return true;
2708     case Op_CMoveN:
2709     case Op_CMoveP:
2710       return needs_barrier_impl(phase, n->in(2), visited) ||
2711              needs_barrier_impl(phase, n->in(3), visited);
2712     case Op_CreateEx:
2713       return false;
2714     default:
2715       break;
2716   }
2717 #ifdef ASSERT
2718   tty->print("need barrier on?: ");
2719   tty->print_cr("ins:");
2720   n->dump(2);
2721   tty->print_cr("outs:");
2722   n->dump(-2);
2723   ShouldNotReachHere();
2724 #endif
2725   return true;
2726 }