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_barrier",
 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::shenandoah_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         !uses_to_ignore.member(u) &&
1045         (u->in(0) != ctrl || (!u->is_Region() && !u->is_Phi())) &&
1046         (ctrl->Opcode() != Op_CatchProj || u->Opcode() != Op_CreateEx)) {
1047       Node* old_c = phase->ctrl_or_self(u);
1048       Node* c = old_c;
1049       if (c != ctrl ||
1050           is_dominator_same_ctrl(old_c, barrier, u, phase) ||
1051           ShenandoahBarrierSetC2::is_shenandoah_state_load(u)) {
1052         phase->igvn().rehash_node_delayed(u);
1053         int nb = u->replace_edge(ctrl, region, &phase->igvn());
1054         if (u->is_CFG()) {
1055           if (phase->idom(u) == ctrl) {
1056             phase->set_idom(u, region, phase->dom_depth(region));
1057           }
1058         } else if (phase->get_ctrl(u) == ctrl) {
1059           assert(u != init_raw_mem, "should leave input raw mem above the barrier");
1060           uses.push(u);
1061         }
1062         assert(nb == 1, "more than 1 ctrl input?");
1063         --i, imax -= nb;
1064       }
1065     }
1066   }
1067 }
1068 
1069 static Node* create_phis_on_call_return(Node* ctrl, Node* c, Node* n, Node* n_clone, const CallProjections& projs, PhaseIdealLoop* phase) {
1070   Node* region = nullptr;
1071   while (c != ctrl) {
1072     if (c->is_Region()) {
1073       region = c;
1074     }
1075     c = phase->idom(c);
1076   }
1077   assert(region != nullptr, "");
1078   Node* phi = new PhiNode(region, n->bottom_type());
1079   for (uint j = 1; j < region->req(); j++) {
1080     Node* in = region->in(j);
1081     if (phase->is_dominator(projs.fallthrough_catchproj, in)) {
1082       phi->init_req(j, n);
1083     } else if (phase->is_dominator(projs.catchall_catchproj, in)) {
1084       phi->init_req(j, n_clone);
1085     } else {
1086       phi->init_req(j, create_phis_on_call_return(ctrl, in, n, n_clone, projs, phase));
1087     }
1088   }
1089   phase->register_new_node(phi, region);
1090   return phi;
1091 }
1092 
1093 void ShenandoahBarrierC2Support::pin_and_expand(PhaseIdealLoop* phase) {
1094   ShenandoahBarrierSetC2State* state = ShenandoahBarrierSetC2::bsc2()->state();
1095 
1096   Unique_Node_List uses;
1097   Node_Stack stack(0);
1098   Node_List clones;
1099   for (int i = state->load_reference_barriers_count() - 1; i >= 0; i--) {
1100     ShenandoahLoadReferenceBarrierNode* lrb = state->load_reference_barrier(i);
1101 
1102     Node* ctrl = phase->get_ctrl(lrb);
1103     Node* val = lrb->in(ShenandoahLoadReferenceBarrierNode::ValueIn);
1104 
1105     CallStaticJavaNode* unc = nullptr;
1106     Node* unc_ctrl = nullptr;
1107     Node* uncasted_val = val;
1108 
1109     for (DUIterator_Fast imax, i = lrb->fast_outs(imax); i < imax; i++) {
1110       Node* u = lrb->fast_out(i);
1111       if (u->Opcode() == Op_CastPP &&
1112           u->in(0) != nullptr &&
1113           phase->is_dominator(u->in(0), ctrl)) {
1114         const Type* u_t = phase->igvn().type(u);
1115 
1116         if (u_t->meet(TypePtr::NULL_PTR) != u_t &&
1117             u->in(0)->Opcode() == Op_IfTrue &&
1118             u->in(0)->as_Proj()->is_uncommon_trap_if_pattern() &&
1119             u->in(0)->in(0)->is_If() &&
1120             u->in(0)->in(0)->in(1)->Opcode() == Op_Bool &&
1121             u->in(0)->in(0)->in(1)->as_Bool()->_test._test == BoolTest::ne &&
1122             u->in(0)->in(0)->in(1)->in(1)->Opcode() == Op_CmpP &&
1123             u->in(0)->in(0)->in(1)->in(1)->in(1) == val &&
1124             u->in(0)->in(0)->in(1)->in(1)->in(2)->bottom_type() == TypePtr::NULL_PTR) {
1125           IdealLoopTree* loop = phase->get_loop(ctrl);
1126           IdealLoopTree* unc_loop = phase->get_loop(u->in(0));
1127 
1128           if (!unc_loop->is_member(loop)) {
1129             continue;
1130           }
1131 
1132           Node* branch = no_branches(ctrl, u->in(0), false, phase);
1133           assert(branch == nullptr || branch == NodeSentinel, "was not looking for a branch");
1134           if (branch == NodeSentinel) {
1135             continue;
1136           }
1137 
1138           Node* iff = u->in(0)->in(0);
1139           Node* bol = iff->in(1)->clone();
1140           Node* cmp = bol->in(1)->clone();
1141           cmp->set_req(1, lrb);
1142           bol->set_req(1, cmp);
1143           phase->igvn().replace_input_of(iff, 1, bol);
1144           phase->set_ctrl(lrb, iff->in(0));
1145           phase->register_new_node(cmp, iff->in(0));
1146           phase->register_new_node(bol, iff->in(0));
1147           break;
1148         }
1149       }
1150     }
1151     if ((ctrl->is_Proj() && ctrl->in(0)->is_CallJava()) || ctrl->is_CallJava()) {
1152       CallNode* call = ctrl->is_Proj() ? ctrl->in(0)->as_CallJava() : ctrl->as_CallJava();
1153       if (call->entry_point() == OptoRuntime::rethrow_stub()) {
1154         // The rethrow call may have too many projections to be
1155         // properly handled here. Given there's no reason for a
1156         // barrier to depend on the call, move it above the call
1157         stack.push(lrb, 0);
1158         do {
1159           Node* n = stack.node();
1160           uint idx = stack.index();
1161           if (idx < n->req()) {
1162             Node* in = n->in(idx);
1163             stack.set_index(idx+1);
1164             if (in != nullptr) {
1165               if (phase->has_ctrl(in)) {
1166                 if (phase->is_dominator(call, phase->get_ctrl(in))) {
1167 #ifdef ASSERT
1168                   for (uint i = 0; i < stack.size(); i++) {
1169                     assert(stack.node_at(i) != in, "node shouldn't have been seen yet");
1170                   }
1171 #endif
1172                   stack.push(in, 0);
1173                 }
1174               } else {
1175                 assert(phase->is_dominator(in, call->in(0)), "no dependency on the call");
1176               }
1177             }
1178           } else {
1179             phase->set_ctrl(n, call->in(0));
1180             stack.pop();
1181           }
1182         } while(stack.size() > 0);
1183         continue;
1184       }
1185       CallProjections projs;
1186       call->extract_projections(&projs, false, false);
1187 
1188 #ifdef ASSERT
1189       VectorSet cloned;
1190 #endif
1191       Node* lrb_clone = lrb->clone();
1192       phase->register_new_node(lrb_clone, projs.catchall_catchproj);
1193       phase->set_ctrl(lrb, projs.fallthrough_catchproj);
1194 
1195       stack.push(lrb, 0);
1196       clones.push(lrb_clone);
1197 
1198       do {
1199         assert(stack.size() == clones.size(), "");
1200         Node* n = stack.node();
1201 #ifdef ASSERT
1202         if (n->is_Load()) {
1203           Node* mem = n->in(MemNode::Memory);
1204           for (DUIterator_Fast jmax, j = mem->fast_outs(jmax); j < jmax; j++) {
1205             Node* u = mem->fast_out(j);
1206             assert(!u->is_Store() || !u->is_LoadStore() || phase->get_ctrl(u) != ctrl, "anti dependent store?");
1207           }
1208         }
1209 #endif
1210         uint idx = stack.index();
1211         Node* n_clone = clones.at(clones.size()-1);
1212         if (idx < n->outcnt()) {
1213           Node* u = n->raw_out(idx);
1214           Node* c = phase->ctrl_or_self(u);
1215           if (phase->is_dominator(call, c) && phase->is_dominator(c, projs.fallthrough_proj)) {
1216             stack.set_index(idx+1);
1217             assert(!u->is_CFG(), "");
1218             stack.push(u, 0);
1219             assert(!cloned.test_set(u->_idx), "only one clone");
1220             Node* u_clone = u->clone();
1221             int nb = u_clone->replace_edge(n, n_clone, &phase->igvn());
1222             assert(nb > 0, "should have replaced some uses");
1223             phase->register_new_node(u_clone, projs.catchall_catchproj);
1224             clones.push(u_clone);
1225             phase->set_ctrl(u, projs.fallthrough_catchproj);
1226           } else {
1227             bool replaced = false;
1228             if (u->is_Phi()) {
1229               for (uint k = 1; k < u->req(); k++) {
1230                 if (u->in(k) == n) {
1231                   if (phase->is_dominator(projs.catchall_catchproj, u->in(0)->in(k))) {
1232                     phase->igvn().replace_input_of(u, k, n_clone);
1233                     replaced = true;
1234                   } else if (!phase->is_dominator(projs.fallthrough_catchproj, u->in(0)->in(k))) {
1235                     phase->igvn().replace_input_of(u, k, create_phis_on_call_return(ctrl, u->in(0)->in(k), n, n_clone, projs, phase));
1236                     replaced = true;
1237                   }
1238                 }
1239               }
1240             } else {
1241               if (phase->is_dominator(projs.catchall_catchproj, c)) {
1242                 phase->igvn().rehash_node_delayed(u);
1243                 int nb = u->replace_edge(n, n_clone, &phase->igvn());
1244                 assert(nb > 0, "should have replaced some uses");
1245                 replaced = true;
1246               } else if (!phase->is_dominator(projs.fallthrough_catchproj, c)) {
1247                 if (u->is_If()) {
1248                   // Can't break If/Bool/Cmp chain
1249                   assert(n->is_Bool(), "unexpected If shape");
1250                   assert(stack.node_at(stack.size()-2)->is_Cmp(), "unexpected If shape");
1251                   assert(n_clone->is_Bool(), "unexpected clone");
1252                   assert(clones.at(clones.size()-2)->is_Cmp(), "unexpected clone");
1253                   Node* bol_clone = n->clone();
1254                   Node* cmp_clone = stack.node_at(stack.size()-2)->clone();
1255                   bol_clone->set_req(1, cmp_clone);
1256 
1257                   Node* nn = stack.node_at(stack.size()-3);
1258                   Node* nn_clone = clones.at(clones.size()-3);
1259                   assert(nn->Opcode() == nn_clone->Opcode(), "mismatch");
1260 
1261                   int nb = cmp_clone->replace_edge(nn, create_phis_on_call_return(ctrl, c, nn, nn_clone, projs, phase),
1262                                                    &phase->igvn());
1263                   assert(nb > 0, "should have replaced some uses");
1264 
1265                   phase->register_new_node(bol_clone, u->in(0));
1266                   phase->register_new_node(cmp_clone, u->in(0));
1267 
1268                   phase->igvn().replace_input_of(u, 1, bol_clone);
1269 
1270                 } else {
1271                   phase->igvn().rehash_node_delayed(u);
1272                   int nb = u->replace_edge(n, create_phis_on_call_return(ctrl, c, n, n_clone, projs, phase), &phase->igvn());
1273                   assert(nb > 0, "should have replaced some uses");
1274                 }
1275                 replaced = true;
1276               }
1277             }
1278             if (!replaced) {
1279               stack.set_index(idx+1);
1280             }
1281           }
1282         } else {
1283           stack.pop();
1284           clones.pop();
1285         }
1286       } while (stack.size() > 0);
1287       assert(stack.size() == 0 && clones.size() == 0, "");
1288     }
1289   }
1290 
1291   for (int i = 0; i < state->load_reference_barriers_count(); i++) {
1292     ShenandoahLoadReferenceBarrierNode* lrb = state->load_reference_barrier(i);
1293     Node* ctrl = phase->get_ctrl(lrb);
1294     IdealLoopTree* loop = phase->get_loop(ctrl);
1295     Node* head = loop->head();
1296     if (head->is_OuterStripMinedLoop()) {
1297       // Expanding a barrier here will break loop strip mining
1298       // verification. Transform the loop so the loop nest doesn't
1299       // appear as strip mined.
1300       OuterStripMinedLoopNode* outer = head->as_OuterStripMinedLoop();
1301       hide_strip_mined_loop(outer, outer->unique_ctrl_out()->as_CountedLoop(), phase);
1302     }
1303     if (head->is_BaseCountedLoop() && ctrl->is_IfProj() && ctrl->in(0)->is_BaseCountedLoopEnd() &&
1304         head->as_BaseCountedLoop()->loopexit() == ctrl->in(0)) {
1305       Node* entry = head->in(LoopNode::EntryControl);
1306       Node* backedge = head->in(LoopNode::LoopBackControl);
1307       Node* new_head = new LoopNode(entry, backedge);
1308       phase->register_control(new_head, phase->get_loop(entry), entry);
1309       phase->lazy_replace(head, new_head);
1310     }
1311   }
1312 
1313   // Expand load-reference-barriers
1314   MemoryGraphFixer fixer(Compile::AliasIdxRaw, true, phase);
1315   Unique_Node_List uses_to_ignore;
1316   for (int i = state->load_reference_barriers_count() - 1; i >= 0; i--) {
1317     ShenandoahLoadReferenceBarrierNode* lrb = state->load_reference_barrier(i);
1318     uint last = phase->C->unique();
1319     Node* ctrl = phase->get_ctrl(lrb);
1320     Node* val = lrb->in(ShenandoahLoadReferenceBarrierNode::ValueIn);
1321 
1322     Node* orig_ctrl = ctrl;
1323 
1324     Node* raw_mem = fixer.find_mem(ctrl, lrb);
1325     Node* raw_mem_for_ctrl = fixer.find_mem(ctrl, nullptr);
1326 
1327     IdealLoopTree *loop = phase->get_loop(ctrl);
1328 
1329     Node* heap_stable_ctrl = nullptr;
1330     Node* null_ctrl = nullptr;
1331 
1332     assert(val->bottom_type()->make_oopptr(), "need oop");
1333     assert(val->bottom_type()->make_oopptr()->const_oop() == nullptr, "expect non-constant");
1334 
1335     enum { _heap_stable = 1, _evac_path, _not_cset, PATH_LIMIT };
1336     Node* region = new RegionNode(PATH_LIMIT);
1337     Node* val_phi = new PhiNode(region, val->bottom_type()->is_oopptr());
1338 
1339     // Stable path.
1340     int flags = ShenandoahHeap::HAS_FORWARDED;
1341     if (!ShenandoahBarrierSet::is_strong_access(lrb->decorators())) {
1342       flags |= ShenandoahHeap::WEAK_ROOTS;
1343     }
1344     test_gc_state(ctrl, raw_mem, heap_stable_ctrl, phase, flags);
1345     IfNode* heap_stable_iff = heap_stable_ctrl->in(0)->as_If();
1346 
1347     // Heap stable case
1348     region->init_req(_heap_stable, heap_stable_ctrl);
1349     val_phi->init_req(_heap_stable, val);
1350 
1351     // Test for in-cset, unless it's a native-LRB. Native LRBs need to return null
1352     // even for non-cset objects to prevent resurrection of such objects.
1353     // Wires !in_cset(obj) to slot 2 of region and phis
1354     Node* not_cset_ctrl = nullptr;
1355     if (ShenandoahBarrierSet::is_strong_access(lrb->decorators())) {
1356       test_in_cset(ctrl, not_cset_ctrl, val, raw_mem, phase);
1357     }
1358     if (not_cset_ctrl != nullptr) {
1359       region->init_req(_not_cset, not_cset_ctrl);
1360       val_phi->init_req(_not_cset, val);
1361     } else {
1362       region->del_req(_not_cset);
1363       val_phi->del_req(_not_cset);
1364     }
1365 
1366     // Resolve object when orig-value is in cset.
1367     // Make the unconditional resolve for fwdptr.
1368 
1369     // Call lrb-stub and wire up that path in slots 4
1370     Node* result_mem = nullptr;
1371 
1372     Node* addr;
1373     {
1374       VectorSet visited;
1375       addr = get_load_addr(phase, visited, lrb);
1376     }
1377     if (addr->Opcode() == Op_AddP) {
1378       Node* orig_base = addr->in(AddPNode::Base);
1379       Node* base = new CheckCastPPNode(ctrl, orig_base, orig_base->bottom_type(), ConstraintCastNode::StrongDependency);
1380       phase->register_new_node(base, ctrl);
1381       if (addr->in(AddPNode::Base) == addr->in((AddPNode::Address))) {
1382         // Field access
1383         addr = addr->clone();
1384         addr->set_req(AddPNode::Base, base);
1385         addr->set_req(AddPNode::Address, base);
1386         phase->register_new_node(addr, ctrl);
1387       } else {
1388         Node* addr2 = addr->in(AddPNode::Address);
1389         if (addr2->Opcode() == Op_AddP && addr2->in(AddPNode::Base) == addr2->in(AddPNode::Address) &&
1390               addr2->in(AddPNode::Base) == orig_base) {
1391           addr2 = addr2->clone();
1392           addr2->set_req(AddPNode::Base, base);
1393           addr2->set_req(AddPNode::Address, base);
1394           phase->register_new_node(addr2, ctrl);
1395           addr = addr->clone();
1396           addr->set_req(AddPNode::Base, base);
1397           addr->set_req(AddPNode::Address, addr2);
1398           phase->register_new_node(addr, ctrl);
1399         }
1400       }
1401     }
1402     call_lrb_stub(ctrl, val, addr, lrb->decorators(), phase);
1403     region->init_req(_evac_path, ctrl);
1404     val_phi->init_req(_evac_path, val);
1405 
1406     phase->register_control(region, loop, heap_stable_iff);
1407     Node* out_val = val_phi;
1408     phase->register_new_node(val_phi, region);
1409 
1410     fix_ctrl(lrb, region, fixer, uses, uses_to_ignore, last, phase);
1411 
1412     ctrl = orig_ctrl;
1413 
1414     phase->igvn().replace_node(lrb, out_val);
1415 
1416     follow_barrier_uses(out_val, ctrl, uses, phase);
1417 
1418     for(uint next = 0; next < uses.size(); next++ ) {
1419       Node *n = uses.at(next);
1420       assert(phase->get_ctrl(n) == ctrl, "bad control");
1421       assert(n != raw_mem, "should leave input raw mem above the barrier");
1422       phase->set_ctrl(n, region);
1423       follow_barrier_uses(n, ctrl, uses, phase);
1424     }
1425     fixer.record_new_ctrl(ctrl, region, raw_mem, raw_mem_for_ctrl);
1426   }
1427   // Done expanding load-reference-barriers.
1428   assert(ShenandoahBarrierSetC2::bsc2()->state()->load_reference_barriers_count() == 0, "all load reference barrier nodes should have been replaced");
1429 }
1430 
1431 Node* ShenandoahBarrierC2Support::get_load_addr(PhaseIdealLoop* phase, VectorSet& visited, Node* in) {
1432   if (visited.test_set(in->_idx)) {
1433     return nullptr;
1434   }
1435   switch (in->Opcode()) {
1436     case Op_Proj:
1437       return get_load_addr(phase, visited, in->in(0));
1438     case Op_CastPP:
1439     case Op_CheckCastPP:
1440     case Op_DecodeN:
1441     case Op_EncodeP:
1442       return get_load_addr(phase, visited, in->in(1));
1443     case Op_LoadN:
1444     case Op_LoadP:
1445       return in->in(MemNode::Address);
1446     case Op_CompareAndExchangeN:
1447     case Op_CompareAndExchangeP:
1448     case Op_GetAndSetN:
1449     case Op_GetAndSetP:
1450     case Op_ShenandoahCompareAndExchangeP:
1451     case Op_ShenandoahCompareAndExchangeN:
1452       // Those instructions would just have stored a different
1453       // value into the field. No use to attempt to fix it at this point.
1454       return phase->igvn().zerocon(T_OBJECT);
1455     case Op_CMoveP:
1456     case Op_CMoveN: {
1457       Node* t = get_load_addr(phase, visited, in->in(CMoveNode::IfTrue));
1458       Node* f = get_load_addr(phase, visited, in->in(CMoveNode::IfFalse));
1459       // Handle unambiguous cases: single address reported on both branches.
1460       if (t != nullptr && f == nullptr) return t;
1461       if (t == nullptr && f != nullptr) return f;
1462       if (t != nullptr && t == f)    return t;
1463       // Ambiguity.
1464       return phase->igvn().zerocon(T_OBJECT);
1465     }
1466     case Op_Phi: {
1467       Node* addr = nullptr;
1468       for (uint i = 1; i < in->req(); i++) {
1469         Node* addr1 = get_load_addr(phase, visited, in->in(i));
1470         if (addr == nullptr) {
1471           addr = addr1;
1472         }
1473         if (addr != addr1) {
1474           return phase->igvn().zerocon(T_OBJECT);
1475         }
1476       }
1477       return addr;
1478     }
1479     case Op_ShenandoahLoadReferenceBarrier:
1480       return get_load_addr(phase, visited, in->in(ShenandoahLoadReferenceBarrierNode::ValueIn));
1481     case Op_CallDynamicJava:
1482     case Op_CallLeaf:
1483     case Op_CallStaticJava:
1484     case Op_ConN:
1485     case Op_ConP:
1486     case Op_Parm:
1487     case Op_CreateEx:
1488       return phase->igvn().zerocon(T_OBJECT);
1489     default:
1490 #ifdef ASSERT
1491       fatal("Unknown node in get_load_addr: %s", NodeClassNames[in->Opcode()]);
1492 #endif
1493       return phase->igvn().zerocon(T_OBJECT);
1494   }
1495 
1496 }
1497 
1498 void ShenandoahBarrierC2Support::move_gc_state_test_out_of_loop(IfNode* iff, PhaseIdealLoop* phase) {
1499   IdealLoopTree *loop = phase->get_loop(iff);
1500   Node* loop_head = loop->_head;
1501   Node* entry_c = loop_head->in(LoopNode::EntryControl);
1502 
1503   Node* bol = iff->in(1);
1504   Node* cmp = bol->in(1);
1505   Node* andi = cmp->in(1);
1506   Node* load = andi->in(1);
1507 
1508   assert(is_gc_state_load(load), "broken");
1509   if (!phase->is_dominator(load->in(0), entry_c)) {
1510     Node* mem_ctrl = nullptr;
1511     Node* mem = dom_mem(load->in(MemNode::Memory), loop_head, Compile::AliasIdxRaw, mem_ctrl, phase);
1512     load = load->clone();
1513     load->set_req(MemNode::Memory, mem);
1514     load->set_req(0, entry_c);
1515     phase->register_new_node(load, entry_c);
1516     andi = andi->clone();
1517     andi->set_req(1, load);
1518     phase->register_new_node(andi, entry_c);
1519     cmp = cmp->clone();
1520     cmp->set_req(1, andi);
1521     phase->register_new_node(cmp, entry_c);
1522     bol = bol->clone();
1523     bol->set_req(1, cmp);
1524     phase->register_new_node(bol, entry_c);
1525 
1526     phase->igvn().replace_input_of(iff, 1, bol);
1527   }
1528 }
1529 
1530 bool ShenandoahBarrierC2Support::identical_backtoback_ifs(Node* n, PhaseIdealLoop* phase) {
1531   if (!n->is_If() || n->is_CountedLoopEnd()) {
1532     return false;
1533   }
1534   Node* region = n->in(0);
1535 
1536   if (!region->is_Region()) {
1537     return false;
1538   }
1539   Node* dom = phase->idom(region);
1540   if (!dom->is_If()) {
1541     return false;
1542   }
1543 
1544   if (!is_heap_stable_test(n) || !is_heap_stable_test(dom)) {
1545     return false;
1546   }
1547 
1548   IfNode* dom_if = dom->as_If();
1549   Node* proj_true = dom_if->proj_out(1);
1550   Node* proj_false = dom_if->proj_out(0);
1551 
1552   for (uint i = 1; i < region->req(); i++) {
1553     if (phase->is_dominator(proj_true, region->in(i))) {
1554       continue;
1555     }
1556     if (phase->is_dominator(proj_false, region->in(i))) {
1557       continue;
1558     }
1559     return false;
1560   }
1561 
1562   return true;
1563 }
1564 
1565 bool ShenandoahBarrierC2Support::merge_point_safe(Node* region) {
1566   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1567     Node* n = region->fast_out(i);
1568     if (n->is_LoadStore()) {
1569       // Splitting a LoadStore node through phi, causes it to lose its SCMemProj: the split if code doesn't have support
1570       // for a LoadStore at the region the if is split through because that's not expected to happen (LoadStore nodes
1571       // should be between barrier nodes). It does however happen with Shenandoah though because barriers can get
1572       // expanded around a LoadStore node.
1573       return false;
1574     }
1575   }
1576   return true;
1577 }
1578 
1579 
1580 void ShenandoahBarrierC2Support::merge_back_to_back_tests(Node* n, PhaseIdealLoop* phase) {
1581   assert(is_heap_stable_test(n), "no other tests");
1582   if (identical_backtoback_ifs(n, phase)) {
1583     Node* n_ctrl = n->in(0);
1584     if (phase->can_split_if(n_ctrl) && merge_point_safe(n_ctrl)) {
1585       IfNode* dom_if = phase->idom(n_ctrl)->as_If();
1586       if (is_heap_stable_test(n)) {
1587         Node* gc_state_load = n->in(1)->in(1)->in(1)->in(1);
1588         assert(is_gc_state_load(gc_state_load), "broken");
1589         Node* dom_gc_state_load = dom_if->in(1)->in(1)->in(1)->in(1);
1590         assert(is_gc_state_load(dom_gc_state_load), "broken");
1591         if (gc_state_load != dom_gc_state_load) {
1592           phase->igvn().replace_node(gc_state_load, dom_gc_state_load);
1593         }
1594       }
1595       PhiNode* bolphi = PhiNode::make_blank(n_ctrl, n->in(1));
1596       Node* proj_true = dom_if->proj_out(1);
1597       Node* proj_false = dom_if->proj_out(0);
1598       Node* con_true = phase->igvn().makecon(TypeInt::ONE);
1599       Node* con_false = phase->igvn().makecon(TypeInt::ZERO);
1600 
1601       for (uint i = 1; i < n_ctrl->req(); i++) {
1602         if (phase->is_dominator(proj_true, n_ctrl->in(i))) {
1603           bolphi->init_req(i, con_true);
1604         } else {
1605           assert(phase->is_dominator(proj_false, n_ctrl->in(i)), "bad if");
1606           bolphi->init_req(i, con_false);
1607         }
1608       }
1609       phase->register_new_node(bolphi, n_ctrl);
1610       phase->igvn().replace_input_of(n, 1, bolphi);
1611       phase->do_split_if(n);
1612     }
1613   }
1614 }
1615 
1616 IfNode* ShenandoahBarrierC2Support::find_unswitching_candidate(const IdealLoopTree* loop, PhaseIdealLoop* phase) {
1617   // Find first invariant test that doesn't exit the loop
1618   LoopNode *head = loop->_head->as_Loop();
1619   IfNode* unswitch_iff = nullptr;
1620   Node* n = head->in(LoopNode::LoopBackControl);
1621   int loop_has_sfpts = -1;
1622   while (n != head) {
1623     Node* n_dom = phase->idom(n);
1624     if (n->is_Region()) {
1625       if (n_dom->is_If()) {
1626         IfNode* iff = n_dom->as_If();
1627         if (iff->in(1)->is_Bool()) {
1628           BoolNode* bol = iff->in(1)->as_Bool();
1629           if (bol->in(1)->is_Cmp()) {
1630             // If condition is invariant and not a loop exit,
1631             // then found reason to unswitch.
1632             if (is_heap_stable_test(iff) &&
1633                 (loop_has_sfpts == -1 || loop_has_sfpts == 0)) {
1634               assert(!loop->is_loop_exit(iff), "both branches should be in the loop");
1635               if (loop_has_sfpts == -1) {
1636                 for(uint i = 0; i < loop->_body.size(); i++) {
1637                   Node *m = loop->_body[i];
1638                   if (m->is_SafePoint() && !m->is_CallLeaf()) {
1639                     loop_has_sfpts = 1;
1640                     break;
1641                   }
1642                 }
1643                 if (loop_has_sfpts == -1) {
1644                   loop_has_sfpts = 0;
1645                 }
1646               }
1647               if (!loop_has_sfpts) {
1648                 unswitch_iff = iff;
1649               }
1650             }
1651           }
1652         }
1653       }
1654     }
1655     n = n_dom;
1656   }
1657   return unswitch_iff;
1658 }
1659 
1660 
1661 void ShenandoahBarrierC2Support::optimize_after_expansion(VectorSet &visited, Node_Stack &stack, Node_List &old_new, PhaseIdealLoop* phase) {
1662   Node_List heap_stable_tests;
1663   stack.push(phase->C->start(), 0);
1664   do {
1665     Node* n = stack.node();
1666     uint i = stack.index();
1667 
1668     if (i < n->outcnt()) {
1669       Node* u = n->raw_out(i);
1670       stack.set_index(i+1);
1671       if (!visited.test_set(u->_idx)) {
1672         stack.push(u, 0);
1673       }
1674     } else {
1675       stack.pop();
1676       if (n->is_If() && is_heap_stable_test(n)) {
1677         heap_stable_tests.push(n);
1678       }
1679     }
1680   } while (stack.size() > 0);
1681 
1682   for (uint i = 0; i < heap_stable_tests.size(); i++) {
1683     Node* n = heap_stable_tests.at(i);
1684     assert(is_heap_stable_test(n), "only evacuation test");
1685     merge_back_to_back_tests(n, phase);
1686   }
1687 
1688   if (!phase->C->major_progress()) {
1689     VectorSet seen;
1690     for (uint i = 0; i < heap_stable_tests.size(); i++) {
1691       Node* n = heap_stable_tests.at(i);
1692       IdealLoopTree* loop = phase->get_loop(n);
1693       if (loop != phase->ltree_root() &&
1694           loop->_child == nullptr &&
1695           !loop->_irreducible) {
1696         Node* head = loop->_head;
1697         if (head->is_Loop() &&
1698             (!head->is_CountedLoop() || head->as_CountedLoop()->is_main_loop() || head->as_CountedLoop()->is_normal_loop()) &&
1699             !seen.test_set(head->_idx)) {
1700           IfNode* iff = find_unswitching_candidate(loop, phase);
1701           if (iff != nullptr) {
1702             Node* bol = iff->in(1);
1703             if (head->as_Loop()->is_strip_mined()) {
1704               head->as_Loop()->verify_strip_mined(0);
1705             }
1706             move_gc_state_test_out_of_loop(iff, phase);
1707 
1708             AutoNodeBudget node_budget(phase);
1709 
1710             if (loop->policy_unswitching(phase)) {
1711               if (head->as_Loop()->is_strip_mined()) {
1712                 OuterStripMinedLoopNode* outer = head->as_CountedLoop()->outer_loop();
1713                 hide_strip_mined_loop(outer, head->as_CountedLoop(), phase);
1714               }
1715               phase->do_unswitching(loop, old_new);
1716             } else {
1717               // Not proceeding with unswitching. Move load back in
1718               // the loop.
1719               phase->igvn().replace_input_of(iff, 1, bol);
1720             }
1721           }
1722         }
1723       }
1724     }
1725   }
1726 }
1727 
1728 #ifdef ASSERT
1729 static bool has_never_branch(Node* root) {
1730   for (uint i = 1; i < root->req(); i++) {
1731     Node* in = root->in(i);
1732     if (in != nullptr && in->Opcode() == Op_Halt && in->in(0)->is_Proj() && in->in(0)->in(0)->is_NeverBranch()) {
1733       return true;
1734     }
1735   }
1736   return false;
1737 }
1738 #endif
1739 
1740 void MemoryGraphFixer::collect_memory_nodes() {
1741   Node_Stack stack(0);
1742   VectorSet visited;
1743   Node_List regions;
1744 
1745   // Walk the raw memory graph and create a mapping from CFG node to
1746   // memory node. Exclude phis for now.
1747   stack.push(_phase->C->root(), 1);
1748   do {
1749     Node* n = stack.node();
1750     int opc = n->Opcode();
1751     uint i = stack.index();
1752     if (i < n->req()) {
1753       Node* mem = nullptr;
1754       if (opc == Op_Root) {
1755         Node* in = n->in(i);
1756         int in_opc = in->Opcode();
1757         if (in_opc == Op_Return || in_opc == Op_Rethrow) {
1758           mem = in->in(TypeFunc::Memory);
1759         } else if (in_opc == Op_Halt) {
1760           if (in->in(0)->is_Region()) {
1761             Node* r = in->in(0);
1762             for (uint j = 1; j < r->req(); j++) {
1763               assert(!r->in(j)->is_NeverBranch(), "");
1764             }
1765           } else {
1766             Node* proj = in->in(0);
1767             assert(proj->is_Proj(), "");
1768             Node* in = proj->in(0);
1769             assert(in->is_CallStaticJava() || in->is_NeverBranch() || in->Opcode() == Op_Catch || proj->is_IfProj(), "");
1770             if (in->is_CallStaticJava()) {
1771               mem = in->in(TypeFunc::Memory);
1772             } else if (in->Opcode() == Op_Catch) {
1773               Node* call = in->in(0)->in(0);
1774               assert(call->is_Call(), "");
1775               mem = call->in(TypeFunc::Memory);
1776             } else if (in->is_NeverBranch()) {
1777               mem = collect_memory_for_infinite_loop(in);
1778             }
1779           }
1780         } else {
1781 #ifdef ASSERT
1782           n->dump();
1783           in->dump();
1784 #endif
1785           ShouldNotReachHere();
1786         }
1787       } else {
1788         assert(n->is_Phi() && n->bottom_type() == Type::MEMORY, "");
1789         assert(n->adr_type() == TypePtr::BOTTOM || _phase->C->get_alias_index(n->adr_type()) == _alias, "");
1790         mem = n->in(i);
1791       }
1792       i++;
1793       stack.set_index(i);
1794       if (mem == nullptr) {
1795         continue;
1796       }
1797       for (;;) {
1798         if (visited.test_set(mem->_idx) || mem->is_Start()) {
1799           break;
1800         }
1801         if (mem->is_Phi()) {
1802           stack.push(mem, 2);
1803           mem = mem->in(1);
1804         } else if (mem->is_Proj()) {
1805           stack.push(mem, mem->req());
1806           mem = mem->in(0);
1807         } else if (mem->is_SafePoint() || mem->is_MemBar()) {
1808           mem = mem->in(TypeFunc::Memory);
1809         } else if (mem->is_MergeMem()) {
1810           MergeMemNode* mm = mem->as_MergeMem();
1811           mem = mm->memory_at(_alias);
1812         } else if (mem->is_Store() || mem->is_LoadStore() || mem->is_ClearArray()) {
1813           assert(_alias == Compile::AliasIdxRaw, "");
1814           stack.push(mem, mem->req());
1815           mem = mem->in(MemNode::Memory);
1816         } else {
1817 #ifdef ASSERT
1818           mem->dump();
1819 #endif
1820           ShouldNotReachHere();
1821         }
1822       }
1823     } else {
1824       if (n->is_Phi()) {
1825         // Nothing
1826       } else if (!n->is_Root()) {
1827         Node* c = get_ctrl(n);
1828         _memory_nodes.map(c->_idx, n);
1829       }
1830       stack.pop();
1831     }
1832   } while(stack.is_nonempty());
1833 
1834   // Iterate over CFG nodes in rpo and propagate memory state to
1835   // compute memory state at regions, creating new phis if needed.
1836   Node_List rpo_list;
1837   visited.clear();
1838   _phase->rpo(_phase->C->root(), stack, visited, rpo_list);
1839   Node* root = rpo_list.pop();
1840   assert(root == _phase->C->root(), "");
1841 
1842   const bool trace = false;
1843 #ifdef ASSERT
1844   if (trace) {
1845     for (int i = rpo_list.size() - 1; i >= 0; i--) {
1846       Node* c = rpo_list.at(i);
1847       if (_memory_nodes[c->_idx] != nullptr) {
1848         tty->print("X %d", c->_idx);  _memory_nodes[c->_idx]->dump();
1849       }
1850     }
1851   }
1852 #endif
1853   uint last = _phase->C->unique();
1854 
1855 #ifdef ASSERT
1856   uint16_t max_depth = 0;
1857   for (LoopTreeIterator iter(_phase->ltree_root()); !iter.done(); iter.next()) {
1858     IdealLoopTree* lpt = iter.current();
1859     max_depth = MAX2(max_depth, lpt->_nest);
1860   }
1861 #endif
1862 
1863   bool progress = true;
1864   int iteration = 0;
1865   Node_List dead_phis;
1866   while (progress) {
1867     progress = false;
1868     iteration++;
1869     assert(iteration <= 2+max_depth || _phase->C->has_irreducible_loop() || has_never_branch(_phase->C->root()), "");
1870     if (trace) { tty->print_cr("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); }
1871 
1872     for (int i = rpo_list.size() - 1; i >= 0; i--) {
1873       Node* c = rpo_list.at(i);
1874 
1875       Node* prev_mem = _memory_nodes[c->_idx];
1876       if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
1877         Node* prev_region = regions[c->_idx];
1878         Node* unique = nullptr;
1879         for (uint j = 1; j < c->req() && unique != NodeSentinel; j++) {
1880           Node* m = _memory_nodes[c->in(j)->_idx];
1881           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");
1882           if (m != nullptr) {
1883             if (m == prev_region && ((c->is_Loop() && j == LoopNode::LoopBackControl) || (prev_region->is_Phi() && prev_region->in(0) == c))) {
1884               assert((c->is_Loop() && j == LoopNode::LoopBackControl) || _phase->C->has_irreducible_loop() || has_never_branch(_phase->C->root()), "");
1885               // continue
1886             } else if (unique == nullptr) {
1887               unique = m;
1888             } else if (m == unique) {
1889               // continue
1890             } else {
1891               unique = NodeSentinel;
1892             }
1893           }
1894         }
1895         assert(unique != nullptr, "empty phi???");
1896         if (unique != NodeSentinel) {
1897           if (prev_region != nullptr && prev_region->is_Phi() && prev_region->in(0) == c) {
1898             dead_phis.push(prev_region);
1899           }
1900           regions.map(c->_idx, unique);
1901         } else {
1902           Node* phi = nullptr;
1903           if (prev_region != nullptr && prev_region->is_Phi() && prev_region->in(0) == c && prev_region->_idx >= last) {
1904             phi = prev_region;
1905             for (uint k = 1; k < c->req(); k++) {
1906               Node* m = _memory_nodes[c->in(k)->_idx];
1907               assert(m != nullptr, "expect memory state");
1908               phi->set_req(k, m);
1909             }
1910           } else {
1911             for (DUIterator_Fast jmax, j = c->fast_outs(jmax); j < jmax && phi == nullptr; j++) {
1912               Node* u = c->fast_out(j);
1913               if (u->is_Phi() && u->bottom_type() == Type::MEMORY &&
1914                   (u->adr_type() == TypePtr::BOTTOM || _phase->C->get_alias_index(u->adr_type()) == _alias)) {
1915                 phi = u;
1916                 for (uint k = 1; k < c->req() && phi != nullptr; k++) {
1917                   Node* m = _memory_nodes[c->in(k)->_idx];
1918                   assert(m != nullptr, "expect memory state");
1919                   if (u->in(k) != m) {
1920                     phi = NodeSentinel;
1921                   }
1922                 }
1923               }
1924             }
1925             if (phi == NodeSentinel) {
1926               phi = new PhiNode(c, Type::MEMORY, _phase->C->get_adr_type(_alias));
1927               for (uint k = 1; k < c->req(); k++) {
1928                 Node* m = _memory_nodes[c->in(k)->_idx];
1929                 assert(m != nullptr, "expect memory state");
1930                 phi->init_req(k, m);
1931               }
1932             }
1933           }
1934           if (phi != nullptr) {
1935             regions.map(c->_idx, phi);
1936           } else {
1937             assert(c->unique_ctrl_out()->Opcode() == Op_Halt, "expected memory state");
1938           }
1939         }
1940         Node* current_region = regions[c->_idx];
1941         if (current_region != prev_region) {
1942           progress = true;
1943           if (prev_region == prev_mem) {
1944             _memory_nodes.map(c->_idx, current_region);
1945           }
1946         }
1947       } else if (prev_mem == nullptr || prev_mem->is_Phi() || ctrl_or_self(prev_mem) != c) {
1948         Node* m = _memory_nodes[_phase->idom(c)->_idx];
1949         assert(m != nullptr || c->Opcode() == Op_Halt, "expect memory state");
1950         if (m != prev_mem) {
1951           _memory_nodes.map(c->_idx, m);
1952           progress = true;
1953         }
1954       }
1955 #ifdef ASSERT
1956       if (trace) { tty->print("X %d", c->_idx);  _memory_nodes[c->_idx]->dump(); }
1957 #endif
1958     }
1959   }
1960 
1961   // Replace existing phi with computed memory state for that region
1962   // if different (could be a new phi or a dominating memory node if
1963   // that phi was found to be useless).
1964   while (dead_phis.size() > 0) {
1965     Node* n = dead_phis.pop();
1966     n->replace_by(_phase->C->top());
1967     n->destruct(&_phase->igvn());
1968   }
1969   for (int i = rpo_list.size() - 1; i >= 0; i--) {
1970     Node* c = rpo_list.at(i);
1971     if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
1972       Node* n = regions[c->_idx];
1973       assert(n != nullptr || c->unique_ctrl_out()->Opcode() == Op_Halt, "expected memory state");
1974       if (n != nullptr && n->is_Phi() && n->_idx >= last && n->in(0) == c) {
1975         _phase->register_new_node(n, c);
1976       }
1977     }
1978   }
1979   for (int i = rpo_list.size() - 1; i >= 0; i--) {
1980     Node* c = rpo_list.at(i);
1981     if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
1982       Node* n = regions[c->_idx];
1983       assert(n != nullptr || c->unique_ctrl_out()->Opcode() == Op_Halt, "expected memory state");
1984       for (DUIterator_Fast imax, i = c->fast_outs(imax); i < imax; i++) {
1985         Node* u = c->fast_out(i);
1986         if (u->is_Phi() && u->bottom_type() == Type::MEMORY &&
1987             u != n) {
1988           assert(c->unique_ctrl_out()->Opcode() != Op_Halt, "expected memory state");
1989           if (u->adr_type() == TypePtr::BOTTOM) {
1990             fix_memory_uses(u, n, n, c);
1991           } else if (_phase->C->get_alias_index(u->adr_type()) == _alias) {
1992             _phase->lazy_replace(u, n);
1993             --i; --imax;
1994           }
1995         }
1996       }
1997     }
1998   }
1999 }
2000 
2001 Node* MemoryGraphFixer::collect_memory_for_infinite_loop(const Node* in) {
2002   Node* mem = nullptr;
2003   Node* head = in->in(0);
2004   assert(head->is_Region(), "unexpected infinite loop graph shape");
2005 
2006   Node* phi_mem = nullptr;
2007   for (DUIterator_Fast jmax, j = head->fast_outs(jmax); j < jmax; j++) {
2008     Node* u = head->fast_out(j);
2009     if (u->is_Phi() && u->bottom_type() == Type::MEMORY) {
2010       if (_phase->C->get_alias_index(u->adr_type()) == _alias) {
2011         assert(phi_mem == nullptr || phi_mem->adr_type() == TypePtr::BOTTOM, "");
2012         phi_mem = u;
2013       } else if (u->adr_type() == TypePtr::BOTTOM) {
2014         assert(phi_mem == nullptr || _phase->C->get_alias_index(phi_mem->adr_type()) == _alias, "");
2015         if (phi_mem == nullptr) {
2016           phi_mem = u;
2017         }
2018       }
2019     }
2020   }
2021   if (phi_mem == nullptr) {
2022     ResourceMark rm;
2023     Node_Stack stack(0);
2024     stack.push(head, 1);
2025     do {
2026       Node* n = stack.node();
2027       uint i = stack.index();
2028       if (i >= n->req()) {
2029         stack.pop();
2030       } else {
2031         stack.set_index(i + 1);
2032         Node* c = n->in(i);
2033         assert(c != head, "should have found a safepoint on the way");
2034         if (stack.size() != 1 || _phase->is_dominator(head, c)) {
2035           for (;;) {
2036             if (c->is_Region()) {
2037               stack.push(c, 1);
2038               break;
2039             } else if (c->is_SafePoint() && !c->is_CallLeaf()) {
2040               Node* m = c->in(TypeFunc::Memory);
2041               if (m->is_MergeMem()) {
2042                 m = m->as_MergeMem()->memory_at(_alias);
2043               }
2044               assert(mem == nullptr || mem == m, "several memory states");
2045               mem = m;
2046               break;
2047             } else {
2048               assert(c != c->in(0), "");
2049               c = c->in(0);
2050             }
2051           }
2052         }
2053       }
2054     } while (stack.size() > 0);
2055     assert(mem != nullptr, "should have found safepoint");
2056   } else {
2057     mem = phi_mem;
2058   }
2059   return mem;
2060 }
2061 
2062 Node* MemoryGraphFixer::get_ctrl(Node* n) const {
2063   Node* c = _phase->get_ctrl(n);
2064   if (n->is_Proj() && n->in(0) != nullptr && n->in(0)->is_Call()) {
2065     assert(c == n->in(0), "");
2066     CallNode* call = c->as_Call();
2067     CallProjections projs;
2068     call->extract_projections(&projs, true, false);
2069     if (projs.catchall_memproj != nullptr) {
2070       if (projs.fallthrough_memproj == n) {
2071         c = projs.fallthrough_catchproj;
2072       } else {
2073         assert(projs.catchall_memproj == n, "");
2074         c = projs.catchall_catchproj;
2075       }
2076     }
2077   }
2078   return c;
2079 }
2080 
2081 Node* MemoryGraphFixer::ctrl_or_self(Node* n) const {
2082   if (_phase->has_ctrl(n))
2083     return get_ctrl(n);
2084   else {
2085     assert (n->is_CFG(), "must be a CFG node");
2086     return n;
2087   }
2088 }
2089 
2090 bool MemoryGraphFixer::mem_is_valid(Node* m, Node* c) const {
2091   return m != nullptr && get_ctrl(m) == c;
2092 }
2093 
2094 Node* MemoryGraphFixer::find_mem(Node* ctrl, Node* n) const {
2095   assert(n == nullptr || _phase->ctrl_or_self(n) == ctrl, "");
2096   assert(!ctrl->is_Call() || ctrl == n, "projection expected");
2097 #ifdef ASSERT
2098   if ((ctrl->is_Proj() && ctrl->in(0)->is_Call()) ||
2099       (ctrl->is_Catch() && ctrl->in(0)->in(0)->is_Call())) {
2100     CallNode* call = ctrl->is_Proj() ? ctrl->in(0)->as_Call() : ctrl->in(0)->in(0)->as_Call();
2101     int mems = 0;
2102     for (DUIterator_Fast imax, i = call->fast_outs(imax); i < imax; i++) {
2103       Node* u = call->fast_out(i);
2104       if (u->bottom_type() == Type::MEMORY) {
2105         mems++;
2106       }
2107     }
2108     assert(mems <= 1, "No node right after call if multiple mem projections");
2109   }
2110 #endif
2111   Node* mem = _memory_nodes[ctrl->_idx];
2112   Node* c = ctrl;
2113   while (!mem_is_valid(mem, c) &&
2114          (!c->is_CatchProj() || mem == nullptr || c->in(0)->in(0)->in(0) != get_ctrl(mem))) {
2115     c = _phase->idom(c);
2116     mem = _memory_nodes[c->_idx];
2117   }
2118   if (n != nullptr && mem_is_valid(mem, c)) {
2119     while (!ShenandoahBarrierC2Support::is_dominator_same_ctrl(c, mem, n, _phase) && _phase->ctrl_or_self(mem) == ctrl) {
2120       mem = next_mem(mem, _alias);
2121     }
2122     if (mem->is_MergeMem()) {
2123       mem = mem->as_MergeMem()->memory_at(_alias);
2124     }
2125     if (!mem_is_valid(mem, c)) {
2126       do {
2127         c = _phase->idom(c);
2128         mem = _memory_nodes[c->_idx];
2129       } while (!mem_is_valid(mem, c) &&
2130                (!c->is_CatchProj() || mem == nullptr || c->in(0)->in(0)->in(0) != get_ctrl(mem)));
2131     }
2132   }
2133   assert(mem->bottom_type() == Type::MEMORY, "");
2134   return mem;
2135 }
2136 
2137 bool MemoryGraphFixer::has_mem_phi(Node* region) const {
2138   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
2139     Node* use = region->fast_out(i);
2140     if (use->is_Phi() && use->bottom_type() == Type::MEMORY &&
2141         (_phase->C->get_alias_index(use->adr_type()) == _alias)) {
2142       return true;
2143     }
2144   }
2145   return false;
2146 }
2147 
2148 void MemoryGraphFixer::fix_mem(Node* ctrl, Node* new_ctrl, Node* mem, Node* mem_for_ctrl, Node* new_mem, Unique_Node_List& uses) {
2149   assert(_phase->ctrl_or_self(new_mem) == new_ctrl, "");
2150   const bool trace = false;
2151   DEBUG_ONLY(if (trace) { tty->print("ZZZ control is"); ctrl->dump(); });
2152   DEBUG_ONLY(if (trace) { tty->print("ZZZ mem is"); mem->dump(); });
2153   GrowableArray<Node*> phis;
2154   if (mem_for_ctrl != mem) {
2155     Node* old = mem_for_ctrl;
2156     Node* prev = nullptr;
2157     while (old != mem) {
2158       prev = old;
2159       if (old->is_Store() || old->is_ClearArray() || old->is_LoadStore()) {
2160         assert(_alias == Compile::AliasIdxRaw, "");
2161         old = old->in(MemNode::Memory);
2162       } else if (old->Opcode() == Op_SCMemProj) {
2163         assert(_alias == Compile::AliasIdxRaw, "");
2164         old = old->in(0);
2165       } else {
2166         ShouldNotReachHere();
2167       }
2168     }
2169     assert(prev != nullptr, "");
2170     if (new_ctrl != ctrl) {
2171       _memory_nodes.map(ctrl->_idx, mem);
2172       _memory_nodes.map(new_ctrl->_idx, mem_for_ctrl);
2173     }
2174     uint input = (uint)MemNode::Memory;
2175     _phase->igvn().replace_input_of(prev, input, new_mem);
2176   } else {
2177     uses.clear();
2178     _memory_nodes.map(new_ctrl->_idx, new_mem);
2179     uses.push(new_ctrl);
2180     for(uint next = 0; next < uses.size(); next++ ) {
2181       Node *n = uses.at(next);
2182       assert(n->is_CFG(), "");
2183       DEBUG_ONLY(if (trace) { tty->print("ZZZ ctrl"); n->dump(); });
2184       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2185         Node* u = n->fast_out(i);
2186         if (!u->is_Root() && u->is_CFG() && u != n) {
2187           Node* m = _memory_nodes[u->_idx];
2188           if (u->is_Region() && (!u->is_OuterStripMinedLoop() || _include_lsm) &&
2189               !has_mem_phi(u) &&
2190               u->unique_ctrl_out()->Opcode() != Op_Halt) {
2191             DEBUG_ONLY(if (trace) { tty->print("ZZZ region"); u->dump(); });
2192             DEBUG_ONLY(if (trace && m != nullptr) { tty->print("ZZZ mem"); m->dump(); });
2193 
2194             if (!mem_is_valid(m, u) || !m->is_Phi()) {
2195               bool push = true;
2196               bool create_phi = true;
2197               if (_phase->is_dominator(new_ctrl, u)) {
2198                 create_phi = false;
2199               }
2200               if (create_phi) {
2201                 Node* phi = new PhiNode(u, Type::MEMORY, _phase->C->get_adr_type(_alias));
2202                 _phase->register_new_node(phi, u);
2203                 phis.push(phi);
2204                 DEBUG_ONLY(if (trace) { tty->print("ZZZ new phi"); phi->dump(); });
2205                 if (!mem_is_valid(m, u)) {
2206                   DEBUG_ONLY(if (trace) { tty->print("ZZZ setting mem"); phi->dump(); });
2207                   _memory_nodes.map(u->_idx, phi);
2208                 } else {
2209                   DEBUG_ONLY(if (trace) { tty->print("ZZZ NOT setting mem"); m->dump(); });
2210                   for (;;) {
2211                     assert(m->is_Mem() || m->is_LoadStore() || m->is_Proj(), "");
2212                     Node* next = nullptr;
2213                     if (m->is_Proj()) {
2214                       next = m->in(0);
2215                     } else {
2216                       assert(m->is_Mem() || m->is_LoadStore(), "");
2217                       assert(_alias == Compile::AliasIdxRaw, "");
2218                       next = m->in(MemNode::Memory);
2219                     }
2220                     if (_phase->get_ctrl(next) != u) {
2221                       break;
2222                     }
2223                     if (next->is_MergeMem()) {
2224                       assert(_phase->get_ctrl(next->as_MergeMem()->memory_at(_alias)) != u, "");
2225                       break;
2226                     }
2227                     if (next->is_Phi()) {
2228                       assert(next->adr_type() == TypePtr::BOTTOM && next->in(0) == u, "");
2229                       break;
2230                     }
2231                     m = next;
2232                   }
2233 
2234                   DEBUG_ONLY(if (trace) { tty->print("ZZZ setting to phi"); m->dump(); });
2235                   assert(m->is_Mem() || m->is_LoadStore(), "");
2236                   uint input = (uint)MemNode::Memory;
2237                   _phase->igvn().replace_input_of(m, input, phi);
2238                   push = false;
2239                 }
2240               } else {
2241                 DEBUG_ONLY(if (trace) { tty->print("ZZZ skipping region"); u->dump(); });
2242               }
2243               if (push) {
2244                 uses.push(u);
2245               }
2246             }
2247           } else if (!mem_is_valid(m, u) &&
2248                      !(u->Opcode() == Op_CProj && u->in(0)->is_NeverBranch() && u->as_Proj()->_con == 1)) {
2249             uses.push(u);
2250           }
2251         }
2252       }
2253     }
2254     for (int i = 0; i < phis.length(); i++) {
2255       Node* n = phis.at(i);
2256       Node* r = n->in(0);
2257       DEBUG_ONLY(if (trace) { tty->print("ZZZ fixing new phi"); n->dump(); });
2258       for (uint j = 1; j < n->req(); j++) {
2259         Node* m = find_mem(r->in(j), nullptr);
2260         _phase->igvn().replace_input_of(n, j, m);
2261         DEBUG_ONLY(if (trace) { tty->print("ZZZ fixing new phi: %d", j); m->dump(); });
2262       }
2263     }
2264   }
2265   uint last = _phase->C->unique();
2266   MergeMemNode* mm = nullptr;
2267   int alias = _alias;
2268   DEBUG_ONLY(if (trace) { tty->print("ZZZ raw mem is"); mem->dump(); });
2269   // Process loads first to not miss an anti-dependency: if the memory
2270   // edge of a store is updated before a load is processed then an
2271   // anti-dependency may be missed.
2272   for (DUIterator i = mem->outs(); mem->has_out(i); i++) {
2273     Node* u = mem->out(i);
2274     if (u->_idx < last && u->is_Load() && _phase->C->get_alias_index(u->adr_type()) == alias) {
2275       Node* m = find_mem(_phase->get_ctrl(u), u);
2276       if (m != mem) {
2277         DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2278         _phase->igvn().replace_input_of(u, MemNode::Memory, m);
2279         --i;
2280       }
2281     }
2282   }
2283   for (DUIterator i = mem->outs(); mem->has_out(i); i++) {
2284     Node* u = mem->out(i);
2285     if (u->_idx < last) {
2286       if (u->is_Mem()) {
2287         if (_phase->C->get_alias_index(u->adr_type()) == alias) {
2288           Node* m = find_mem(_phase->get_ctrl(u), u);
2289           if (m != mem) {
2290             DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2291             _phase->igvn().replace_input_of(u, MemNode::Memory, m);
2292             --i;
2293           }
2294         }
2295       } else if (u->is_MergeMem()) {
2296         MergeMemNode* u_mm = u->as_MergeMem();
2297         if (u_mm->memory_at(alias) == mem) {
2298           MergeMemNode* newmm = nullptr;
2299           for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
2300             Node* uu = u->fast_out(j);
2301             assert(!uu->is_MergeMem(), "chain of MergeMems?");
2302             if (uu->is_Phi()) {
2303               assert(uu->adr_type() == TypePtr::BOTTOM, "");
2304               Node* region = uu->in(0);
2305               int nb = 0;
2306               for (uint k = 1; k < uu->req(); k++) {
2307                 if (uu->in(k) == u) {
2308                   Node* m = find_mem(region->in(k), nullptr);
2309                   if (m != mem) {
2310                     DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of phi %d", k); uu->dump(); });
2311                     newmm = clone_merge_mem(u, mem, m, _phase->ctrl_or_self(m), i);
2312                     if (newmm != u) {
2313                       _phase->igvn().replace_input_of(uu, k, newmm);
2314                       nb++;
2315                       --jmax;
2316                     }
2317                   }
2318                 }
2319               }
2320               if (nb > 0) {
2321                 --j;
2322               }
2323             } else {
2324               Node* m = find_mem(_phase->ctrl_or_self(uu), uu);
2325               if (m != mem) {
2326                 DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); uu->dump(); });
2327                 newmm = clone_merge_mem(u, mem, m, _phase->ctrl_or_self(m), i);
2328                 if (newmm != u) {
2329                   _phase->igvn().replace_input_of(uu, uu->find_edge(u), newmm);
2330                   --j, --jmax;
2331                 }
2332               }
2333             }
2334           }
2335         }
2336       } else if (u->is_Phi()) {
2337         assert(u->bottom_type() == Type::MEMORY, "what else?");
2338         if (_phase->C->get_alias_index(u->adr_type()) == alias || u->adr_type() == TypePtr::BOTTOM) {
2339           Node* region = u->in(0);
2340           bool replaced = false;
2341           for (uint j = 1; j < u->req(); j++) {
2342             if (u->in(j) == mem) {
2343               Node* m = find_mem(region->in(j), nullptr);
2344               Node* nnew = m;
2345               if (m != mem) {
2346                 if (u->adr_type() == TypePtr::BOTTOM) {
2347                   mm = allocate_merge_mem(mem, m, _phase->ctrl_or_self(m));
2348                   nnew = mm;
2349                 }
2350                 DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of phi %d", j); u->dump(); });
2351                 _phase->igvn().replace_input_of(u, j, nnew);
2352                 replaced = true;
2353               }
2354             }
2355           }
2356           if (replaced) {
2357             --i;
2358           }
2359         }
2360       } else if ((u->adr_type() == TypePtr::BOTTOM && u->Opcode() != Op_StrInflatedCopy) ||
2361                  u->adr_type() == nullptr) {
2362         assert(u->adr_type() != nullptr ||
2363                u->Opcode() == Op_Rethrow ||
2364                u->Opcode() == Op_Return ||
2365                u->Opcode() == Op_SafePoint ||
2366                (u->is_CallStaticJava() && u->as_CallStaticJava()->uncommon_trap_request() != 0) ||
2367                (u->is_CallStaticJava() && u->as_CallStaticJava()->_entry_point == OptoRuntime::rethrow_stub()) ||
2368                u->Opcode() == Op_CallLeaf, "");
2369         Node* m = find_mem(_phase->ctrl_or_self(u), u);
2370         if (m != mem) {
2371           mm = allocate_merge_mem(mem, m, _phase->get_ctrl(m));
2372           _phase->igvn().replace_input_of(u, u->find_edge(mem), mm);
2373           --i;
2374         }
2375       } else if (_phase->C->get_alias_index(u->adr_type()) == alias) {
2376         Node* m = find_mem(_phase->ctrl_or_self(u), u);
2377         if (m != mem) {
2378           DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2379           _phase->igvn().replace_input_of(u, u->find_edge(mem), m);
2380           --i;
2381         }
2382       } else if (u->adr_type() != TypePtr::BOTTOM &&
2383                  _memory_nodes[_phase->ctrl_or_self(u)->_idx] == u) {
2384         Node* m = find_mem(_phase->ctrl_or_self(u), u);
2385         assert(m != mem, "");
2386         // u is on the wrong slice...
2387         assert(u->is_ClearArray(), "");
2388         DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2389         _phase->igvn().replace_input_of(u, u->find_edge(mem), m);
2390         --i;
2391       }
2392     }
2393   }
2394 #ifdef ASSERT
2395   assert(new_mem->outcnt() > 0, "");
2396   for (int i = 0; i < phis.length(); i++) {
2397     Node* n = phis.at(i);
2398     assert(n->outcnt() > 0, "new phi must have uses now");
2399   }
2400 #endif
2401 }
2402 
2403 void MemoryGraphFixer::record_new_ctrl(Node* ctrl, Node* new_ctrl, Node* mem, Node* mem_for_ctrl) {
2404   if (mem_for_ctrl != mem && new_ctrl != ctrl) {
2405     _memory_nodes.map(ctrl->_idx, mem);
2406     _memory_nodes.map(new_ctrl->_idx, mem_for_ctrl);
2407   }
2408 }
2409 
2410 MergeMemNode* MemoryGraphFixer::allocate_merge_mem(Node* mem, Node* rep_proj, Node* rep_ctrl) const {
2411   MergeMemNode* mm = MergeMemNode::make(mem);
2412   mm->set_memory_at(_alias, rep_proj);
2413   _phase->register_new_node(mm, rep_ctrl);
2414   return mm;
2415 }
2416 
2417 MergeMemNode* MemoryGraphFixer::clone_merge_mem(Node* u, Node* mem, Node* rep_proj, Node* rep_ctrl, DUIterator& i) const {
2418   MergeMemNode* newmm = nullptr;
2419   MergeMemNode* u_mm = u->as_MergeMem();
2420   Node* c = _phase->get_ctrl(u);
2421   if (_phase->is_dominator(c, rep_ctrl)) {
2422     c = rep_ctrl;
2423   } else {
2424     assert(_phase->is_dominator(rep_ctrl, c), "one must dominate the other");
2425   }
2426   if (u->outcnt() == 1) {
2427     if (u->req() > (uint)_alias && u->in(_alias) == mem) {
2428       _phase->igvn().replace_input_of(u, _alias, rep_proj);
2429       --i;
2430     } else {
2431       _phase->igvn().rehash_node_delayed(u);
2432       u_mm->set_memory_at(_alias, rep_proj);
2433     }
2434     newmm = u_mm;
2435     _phase->set_ctrl_and_loop(u, c);
2436   } else {
2437     // can't simply clone u and then change one of its input because
2438     // it adds and then removes an edge which messes with the
2439     // DUIterator
2440     newmm = MergeMemNode::make(u_mm->base_memory());
2441     for (uint j = 0; j < u->req(); j++) {
2442       if (j < newmm->req()) {
2443         if (j == (uint)_alias) {
2444           newmm->set_req(j, rep_proj);
2445         } else if (newmm->in(j) != u->in(j)) {
2446           newmm->set_req(j, u->in(j));
2447         }
2448       } else if (j == (uint)_alias) {
2449         newmm->add_req(rep_proj);
2450       } else {
2451         newmm->add_req(u->in(j));
2452       }
2453     }
2454     if ((uint)_alias >= u->req()) {
2455       newmm->set_memory_at(_alias, rep_proj);
2456     }
2457     _phase->register_new_node(newmm, c);
2458   }
2459   return newmm;
2460 }
2461 
2462 bool MemoryGraphFixer::should_process_phi(Node* phi) const {
2463   if (phi->adr_type() == TypePtr::BOTTOM) {
2464     Node* region = phi->in(0);
2465     for (DUIterator_Fast jmax, j = region->fast_outs(jmax); j < jmax; j++) {
2466       Node* uu = region->fast_out(j);
2467       if (uu->is_Phi() && uu != phi && uu->bottom_type() == Type::MEMORY && _phase->C->get_alias_index(uu->adr_type()) == _alias) {
2468         return false;
2469       }
2470     }
2471     return true;
2472   }
2473   return _phase->C->get_alias_index(phi->adr_type()) == _alias;
2474 }
2475 
2476 void MemoryGraphFixer::fix_memory_uses(Node* mem, Node* replacement, Node* rep_proj, Node* rep_ctrl) const {
2477   uint last = _phase-> C->unique();
2478   MergeMemNode* mm = nullptr;
2479   assert(mem->bottom_type() == Type::MEMORY, "");
2480   for (DUIterator i = mem->outs(); mem->has_out(i); i++) {
2481     Node* u = mem->out(i);
2482     if (u != replacement && u->_idx < last) {
2483       if (u->is_MergeMem()) {
2484         MergeMemNode* u_mm = u->as_MergeMem();
2485         if (u_mm->memory_at(_alias) == mem) {
2486           MergeMemNode* newmm = nullptr;
2487           for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
2488             Node* uu = u->fast_out(j);
2489             assert(!uu->is_MergeMem(), "chain of MergeMems?");
2490             if (uu->is_Phi()) {
2491               if (should_process_phi(uu)) {
2492                 Node* region = uu->in(0);
2493                 int nb = 0;
2494                 for (uint k = 1; k < uu->req(); k++) {
2495                   if (uu->in(k) == u && _phase->is_dominator(rep_ctrl, region->in(k))) {
2496                     if (newmm == nullptr) {
2497                       newmm = clone_merge_mem(u, mem, rep_proj, rep_ctrl, i);
2498                     }
2499                     if (newmm != u) {
2500                       _phase->igvn().replace_input_of(uu, k, newmm);
2501                       nb++;
2502                       --jmax;
2503                     }
2504                   }
2505                 }
2506                 if (nb > 0) {
2507                   --j;
2508                 }
2509               }
2510             } else {
2511               if (rep_ctrl != uu && ShenandoahBarrierC2Support::is_dominator(rep_ctrl, _phase->ctrl_or_self(uu), replacement, uu, _phase)) {
2512                 if (newmm == nullptr) {
2513                   newmm = clone_merge_mem(u, mem, rep_proj, rep_ctrl, i);
2514                 }
2515                 if (newmm != u) {
2516                   _phase->igvn().replace_input_of(uu, uu->find_edge(u), newmm);
2517                   --j, --jmax;
2518                 }
2519               }
2520             }
2521           }
2522         }
2523       } else if (u->is_Phi()) {
2524         assert(u->bottom_type() == Type::MEMORY, "what else?");
2525         Node* region = u->in(0);
2526         if (should_process_phi(u)) {
2527           bool replaced = false;
2528           for (uint j = 1; j < u->req(); j++) {
2529             if (u->in(j) == mem && _phase->is_dominator(rep_ctrl, region->in(j))) {
2530               Node* nnew = rep_proj;
2531               if (u->adr_type() == TypePtr::BOTTOM) {
2532                 if (mm == nullptr) {
2533                   mm = allocate_merge_mem(mem, rep_proj, rep_ctrl);
2534                 }
2535                 nnew = mm;
2536               }
2537               _phase->igvn().replace_input_of(u, j, nnew);
2538               replaced = true;
2539             }
2540           }
2541           if (replaced) {
2542             --i;
2543           }
2544 
2545         }
2546       } else if ((u->adr_type() == TypePtr::BOTTOM && u->Opcode() != Op_StrInflatedCopy) ||
2547                  u->adr_type() == nullptr) {
2548         assert(u->adr_type() != nullptr ||
2549                u->Opcode() == Op_Rethrow ||
2550                u->Opcode() == Op_Return ||
2551                u->Opcode() == Op_SafePoint ||
2552                (u->is_CallStaticJava() && u->as_CallStaticJava()->uncommon_trap_request() != 0) ||
2553                (u->is_CallStaticJava() && u->as_CallStaticJava()->_entry_point == OptoRuntime::rethrow_stub()) ||
2554                u->Opcode() == Op_CallLeaf, "%s", u->Name());
2555         if (ShenandoahBarrierC2Support::is_dominator(rep_ctrl, _phase->ctrl_or_self(u), replacement, u, _phase)) {
2556           if (mm == nullptr) {
2557             mm = allocate_merge_mem(mem, rep_proj, rep_ctrl);
2558           }
2559           _phase->igvn().replace_input_of(u, u->find_edge(mem), mm);
2560           --i;
2561         }
2562       } else if (_phase->C->get_alias_index(u->adr_type()) == _alias) {
2563         if (ShenandoahBarrierC2Support::is_dominator(rep_ctrl, _phase->ctrl_or_self(u), replacement, u, _phase)) {
2564           _phase->igvn().replace_input_of(u, u->find_edge(mem), rep_proj);
2565           --i;
2566         }
2567       }
2568     }
2569   }
2570 }
2571 
2572 ShenandoahLoadReferenceBarrierNode::ShenandoahLoadReferenceBarrierNode(Node* ctrl, Node* obj, DecoratorSet decorators)
2573 : Node(ctrl, obj), _decorators(decorators) {
2574   ShenandoahBarrierSetC2::bsc2()->state()->add_load_reference_barrier(this);
2575 }
2576 
2577 DecoratorSet ShenandoahLoadReferenceBarrierNode::decorators() const {
2578   return _decorators;
2579 }
2580 
2581 uint ShenandoahLoadReferenceBarrierNode::size_of() const {
2582   return sizeof(*this);
2583 }
2584 
2585 static DecoratorSet mask_decorators(DecoratorSet decorators) {
2586   return decorators & (ON_STRONG_OOP_REF | ON_WEAK_OOP_REF | ON_PHANTOM_OOP_REF | ON_UNKNOWN_OOP_REF | IN_NATIVE);
2587 }
2588 
2589 uint ShenandoahLoadReferenceBarrierNode::hash() const {
2590   uint hash = Node::hash();
2591   hash += mask_decorators(_decorators);
2592   return hash;
2593 }
2594 
2595 bool ShenandoahLoadReferenceBarrierNode::cmp( const Node &n ) const {
2596   return Node::cmp(n) && n.Opcode() == Op_ShenandoahLoadReferenceBarrier &&
2597          mask_decorators(_decorators) == mask_decorators(((const ShenandoahLoadReferenceBarrierNode&)n)._decorators);
2598 }
2599 
2600 const Type* ShenandoahLoadReferenceBarrierNode::bottom_type() const {
2601   if (in(ValueIn) == nullptr || in(ValueIn)->is_top()) {
2602     return Type::TOP;
2603   }
2604   const Type* t = in(ValueIn)->bottom_type();
2605   if (t == TypePtr::NULL_PTR) {
2606     return t;
2607   }
2608 
2609   if (ShenandoahBarrierSet::is_strong_access(decorators())) {
2610     return t;
2611   }
2612 
2613   return t->meet(TypePtr::NULL_PTR);
2614 }
2615 
2616 const Type* ShenandoahLoadReferenceBarrierNode::Value(PhaseGVN* phase) const {
2617   // Either input is TOP ==> the result is TOP
2618   const Type *t2 = phase->type(in(ValueIn));
2619   if( t2 == Type::TOP ) return Type::TOP;
2620 
2621   if (t2 == TypePtr::NULL_PTR) {
2622     return t2;
2623   }
2624 
2625   if (ShenandoahBarrierSet::is_strong_access(decorators())) {
2626     return t2;
2627   }
2628 
2629   return t2->meet(TypePtr::NULL_PTR);
2630 }
2631 
2632 Node* ShenandoahLoadReferenceBarrierNode::Identity(PhaseGVN* phase) {
2633   Node* value = in(ValueIn);
2634   if (!needs_barrier(phase, value)) {
2635     return value;
2636   }
2637   return this;
2638 }
2639 
2640 bool ShenandoahLoadReferenceBarrierNode::needs_barrier(PhaseGVN* phase, Node* n) {
2641   Unique_Node_List visited;
2642   return needs_barrier_impl(phase, n, visited);
2643 }
2644 
2645 bool ShenandoahLoadReferenceBarrierNode::needs_barrier_impl(PhaseGVN* phase, Node* n, Unique_Node_List &visited) {
2646   if (n == nullptr) return false;
2647   if (visited.member(n)) {
2648     return false; // Been there.
2649   }
2650   visited.push(n);
2651 
2652   if (n->is_Allocate()) {
2653     // tty->print_cr("optimize barrier on alloc");
2654     return false;
2655   }
2656   if (n->is_Call()) {
2657     // tty->print_cr("optimize barrier on call");
2658     return false;
2659   }
2660 
2661   const Type* type = phase->type(n);
2662   if (type == Type::TOP) {
2663     return false;
2664   }
2665   if (type->make_ptr()->higher_equal(TypePtr::NULL_PTR)) {
2666     // tty->print_cr("optimize barrier on null");
2667     return false;
2668   }
2669   if (type->make_oopptr() && type->make_oopptr()->const_oop() != nullptr) {
2670     // tty->print_cr("optimize barrier on constant");
2671     return false;
2672   }
2673 
2674   switch (n->Opcode()) {
2675     case Op_AddP:
2676       return true; // TODO: Can refine?
2677     case Op_LoadP:
2678     case Op_ShenandoahCompareAndExchangeN:
2679     case Op_ShenandoahCompareAndExchangeP:
2680     case Op_CompareAndExchangeN:
2681     case Op_CompareAndExchangeP:
2682     case Op_GetAndSetN:
2683     case Op_GetAndSetP:
2684       return true;
2685     case Op_Phi: {
2686       for (uint i = 1; i < n->req(); i++) {
2687         if (needs_barrier_impl(phase, n->in(i), visited)) return true;
2688       }
2689       return false;
2690     }
2691     case Op_CheckCastPP:
2692     case Op_CastPP:
2693       return needs_barrier_impl(phase, n->in(1), visited);
2694     case Op_Proj:
2695       return needs_barrier_impl(phase, n->in(0), visited);
2696     case Op_ShenandoahLoadReferenceBarrier:
2697       // tty->print_cr("optimize barrier on barrier");
2698       return false;
2699     case Op_Parm:
2700       // tty->print_cr("optimize barrier on input arg");
2701       return false;
2702     case Op_DecodeN:
2703     case Op_EncodeP:
2704       return needs_barrier_impl(phase, n->in(1), visited);
2705     case Op_LoadN:
2706       return true;
2707     case Op_CMoveN:
2708     case Op_CMoveP:
2709       return needs_barrier_impl(phase, n->in(2), visited) ||
2710              needs_barrier_impl(phase, n->in(3), visited);
2711     case Op_CreateEx:
2712       return false;
2713     default:
2714       break;
2715   }
2716 #ifdef ASSERT
2717   tty->print("need barrier on?: ");
2718   tty->print_cr("ins:");
2719   n->dump(2);
2720   tty->print_cr("outs:");
2721   n->dump(-2);
2722   ShouldNotReachHere();
2723 #endif
2724   return true;
2725 }