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