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