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