1 /*
   2  * Copyright (c) 2001, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "asm/register.hpp"
  26 #include "ci/ciFlatArrayKlass.hpp"
  27 #include "ci/ciInlineKlass.hpp"
  28 #include "ci/ciMethod.hpp"
  29 #include "ci/ciObjArray.hpp"
  30 #include "ci/ciUtilities.hpp"
  31 #include "classfile/javaClasses.hpp"
  32 #include "compiler/compileLog.hpp"
  33 #include "gc/shared/barrierSet.hpp"
  34 #include "gc/shared/c2/barrierSetC2.hpp"
  35 #include "interpreter/interpreter.hpp"
  36 #include "memory/resourceArea.hpp"
  37 #include "oops/flatArrayKlass.hpp"
  38 #include "opto/addnode.hpp"
  39 #include "opto/callnode.hpp"
  40 #include "opto/castnode.hpp"
  41 #include "opto/convertnode.hpp"
  42 #include "opto/graphKit.hpp"
  43 #include "opto/idealKit.hpp"
  44 #include "opto/inlinetypenode.hpp"
  45 #include "opto/intrinsicnode.hpp"
  46 #include "opto/locknode.hpp"
  47 #include "opto/machnode.hpp"
  48 #include "opto/memnode.hpp"
  49 #include "opto/multnode.hpp"
  50 #include "opto/narrowptrnode.hpp"
  51 #include "opto/opaquenode.hpp"
  52 #include "opto/parse.hpp"
  53 #include "opto/rootnode.hpp"
  54 #include "opto/runtime.hpp"
  55 #include "opto/subtypenode.hpp"
  56 #include "runtime/arguments.hpp"
  57 #include "runtime/deoptimization.hpp"
  58 #include "runtime/sharedRuntime.hpp"
  59 #include "runtime/stubRoutines.hpp"
  60 #include "utilities/bitMap.inline.hpp"
  61 #include "utilities/growableArray.hpp"
  62 #include "utilities/powerOfTwo.hpp"
  63 
  64 //----------------------------GraphKit-----------------------------------------
  65 // Main utility constructor.
  66 GraphKit::GraphKit(JVMState* jvms, PhaseGVN* gvn)
  67   : Phase(Phase::Parser),
  68     _env(C->env()),
  69     _gvn((gvn != nullptr) ? *gvn : *C->initial_gvn()),
  70     _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
  71 {
  72   assert(gvn == nullptr || !gvn->is_IterGVN() || gvn->is_IterGVN()->delay_transform(), "delay transform should be enabled");
  73   _exceptions = jvms->map()->next_exception();
  74   if (_exceptions != nullptr)  jvms->map()->set_next_exception(nullptr);
  75   set_jvms(jvms);
  76 #ifdef ASSERT
  77   if (_gvn.is_IterGVN() != nullptr) {
  78     assert(_gvn.is_IterGVN()->delay_transform(), "Transformation must be delayed if IterGVN is used");
  79     // Save the initial size of _for_igvn worklist for verification (see ~GraphKit)
  80     _worklist_size = _gvn.C->igvn_worklist()->size();
  81   }
  82 #endif
  83 }
  84 
  85 // Private constructor for parser.
  86 GraphKit::GraphKit()
  87   : Phase(Phase::Parser),
  88     _env(C->env()),
  89     _gvn(*C->initial_gvn()),
  90     _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
  91 {
  92   _exceptions = nullptr;
  93   set_map(nullptr);
  94   DEBUG_ONLY(_sp = -99);
  95   DEBUG_ONLY(set_bci(-99));
  96 }
  97 
  98 GraphKit::GraphKit(const SafePointNode* sft, PhaseIterGVN& igvn)
  99   : Phase(Phase::Parser),
 100     _env(C->env()),
 101     _gvn(igvn),
 102     _exceptions(nullptr),
 103     _barrier_set(BarrierSet::barrier_set()->barrier_set_c2()) {
 104   assert(igvn.delay_transform(), "must delay transformation during macro expansion");
 105   assert(sft->next_exception() == nullptr, "must not have a pending exception");
 106   JVMState* cloned_jvms = sft->jvms()->clone_deep(C);
 107   SafePointNode* cloned_map = new SafePointNode(sft->req(), cloned_jvms);
 108   for (uint i = 0; i < sft->req(); i++) {
 109     cloned_map->init_req(i, sft->in(i));
 110   }
 111   igvn.record_for_igvn(cloned_map);
 112   for (JVMState* current = cloned_jvms; current != nullptr; current = current->caller()) {
 113     current->set_map(cloned_map);
 114   }
 115   set_jvms(cloned_jvms);
 116   set_all_memory(reset_memory());
 117 }
 118 
 119 //---------------------------clean_stack---------------------------------------
 120 // Clear away rubbish from the stack area of the JVM state.
 121 // This destroys any arguments that may be waiting on the stack.
 122 void GraphKit::clean_stack(int from_sp) {
 123   SafePointNode* map      = this->map();
 124   JVMState*      jvms     = this->jvms();
 125   int            stk_size = jvms->stk_size();
 126   int            stkoff   = jvms->stkoff();
 127   Node*          top      = this->top();
 128   for (int i = from_sp; i < stk_size; i++) {
 129     if (map->in(stkoff + i) != top) {
 130       map->set_req(stkoff + i, top);
 131     }
 132   }
 133 }
 134 
 135 
 136 //--------------------------------sync_jvms-----------------------------------
 137 // Make sure our current jvms agrees with our parse state.
 138 JVMState* GraphKit::sync_jvms() const {
 139   JVMState* jvms = this->jvms();
 140   jvms->set_bci(bci());       // Record the new bci in the JVMState
 141   jvms->set_sp(sp());         // Record the new sp in the JVMState
 142   assert(jvms_in_sync(), "jvms is now in sync");
 143   return jvms;
 144 }
 145 
 146 //--------------------------------sync_jvms_for_reexecute---------------------
 147 // Make sure our current jvms agrees with our parse state.  This version
 148 // uses the reexecute_sp for reexecuting bytecodes.
 149 JVMState* GraphKit::sync_jvms_for_reexecute() {
 150   JVMState* jvms = this->jvms();
 151   jvms->set_bci(bci());          // Record the new bci in the JVMState
 152   jvms->set_sp(reexecute_sp());  // Record the new sp in the JVMState
 153   return jvms;
 154 }
 155 
 156 #ifdef ASSERT
 157 bool GraphKit::jvms_in_sync() const {
 158   Parse* parse = is_Parse();
 159   if (parse == nullptr) {
 160     if (bci() !=      jvms()->bci())          return false;
 161     if (sp()  != (int)jvms()->sp())           return false;
 162     return true;
 163   }
 164   if (jvms()->method() != parse->method())    return false;
 165   if (jvms()->bci()    != parse->bci())       return false;
 166   int jvms_sp = jvms()->sp();
 167   if (jvms_sp          != parse->sp())        return false;
 168   int jvms_depth = jvms()->depth();
 169   if (jvms_depth       != parse->depth())     return false;
 170   return true;
 171 }
 172 
 173 // Local helper checks for special internal merge points
 174 // used to accumulate and merge exception states.
 175 // They are marked by the region's in(0) edge being the map itself.
 176 // Such merge points must never "escape" into the parser at large,
 177 // until they have been handed to gvn.transform.
 178 static bool is_hidden_merge(Node* reg) {
 179   if (reg == nullptr)  return false;
 180   if (reg->is_Phi()) {
 181     reg = reg->in(0);
 182     if (reg == nullptr)  return false;
 183   }
 184   return reg->is_Region() && reg->in(0) != nullptr && reg->in(0)->is_Root();
 185 }
 186 
 187 void GraphKit::verify_map() const {
 188   if (map() == nullptr)  return;  // null map is OK
 189   assert(map()->req() <= jvms()->endoff(), "no extra garbage on map");
 190   assert(!map()->has_exceptions(),    "call add_exception_states_from 1st");
 191   assert(!is_hidden_merge(control()), "call use_exception_state, not set_map");
 192 }
 193 
 194 void GraphKit::verify_exception_state(SafePointNode* ex_map) {
 195   assert(ex_map->next_exception() == nullptr, "not already part of a chain");
 196   assert(has_saved_ex_oop(ex_map), "every exception state has an ex_oop");
 197 }
 198 #endif
 199 
 200 //---------------------------stop_and_kill_map---------------------------------
 201 // Set _map to null, signalling a stop to further bytecode execution.
 202 // First smash the current map's control to a constant, to mark it dead.
 203 void GraphKit::stop_and_kill_map() {
 204   SafePointNode* dead_map = stop();
 205   if (dead_map != nullptr) {
 206     dead_map->disconnect_inputs(C); // Mark the map as killed.
 207     assert(dead_map->is_killed(), "must be so marked");
 208   }
 209 }
 210 
 211 
 212 //--------------------------------stopped--------------------------------------
 213 // Tell if _map is null, or control is top.
 214 bool GraphKit::stopped() {
 215   if (map() == nullptr)        return true;
 216   else if (control() == top()) return true;
 217   else                         return false;
 218 }
 219 
 220 
 221 //-----------------------------has_exception_handler----------------------------------
 222 // Tell if this method or any caller method has exception handlers.
 223 bool GraphKit::has_exception_handler() {
 224   for (JVMState* jvmsp = jvms(); jvmsp != nullptr; jvmsp = jvmsp->caller()) {
 225     if (jvmsp->has_method() && jvmsp->method()->has_exception_handlers()) {
 226       return true;
 227     }
 228   }
 229   return false;
 230 }
 231 
 232 //------------------------------save_ex_oop------------------------------------
 233 // Save an exception without blowing stack contents or other JVM state.
 234 void GraphKit::set_saved_ex_oop(SafePointNode* ex_map, Node* ex_oop) {
 235   assert(!has_saved_ex_oop(ex_map), "clear ex-oop before setting again");
 236   ex_map->add_req(ex_oop);
 237   DEBUG_ONLY(verify_exception_state(ex_map));
 238 }
 239 
 240 inline static Node* common_saved_ex_oop(SafePointNode* ex_map, bool clear_it) {
 241   assert(GraphKit::has_saved_ex_oop(ex_map), "ex_oop must be there");
 242   Node* ex_oop = ex_map->in(ex_map->req()-1);
 243   if (clear_it)  ex_map->del_req(ex_map->req()-1);
 244   return ex_oop;
 245 }
 246 
 247 //-----------------------------saved_ex_oop------------------------------------
 248 // Recover a saved exception from its map.
 249 Node* GraphKit::saved_ex_oop(SafePointNode* ex_map) {
 250   return common_saved_ex_oop(ex_map, false);
 251 }
 252 
 253 //--------------------------clear_saved_ex_oop---------------------------------
 254 // Erase a previously saved exception from its map.
 255 Node* GraphKit::clear_saved_ex_oop(SafePointNode* ex_map) {
 256   return common_saved_ex_oop(ex_map, true);
 257 }
 258 
 259 #ifdef ASSERT
 260 //---------------------------has_saved_ex_oop----------------------------------
 261 // Erase a previously saved exception from its map.
 262 bool GraphKit::has_saved_ex_oop(SafePointNode* ex_map) {
 263   return ex_map->req() == ex_map->jvms()->endoff()+1;
 264 }
 265 #endif
 266 
 267 //-------------------------make_exception_state--------------------------------
 268 // Turn the current JVM state into an exception state, appending the ex_oop.
 269 SafePointNode* GraphKit::make_exception_state(Node* ex_oop) {
 270   sync_jvms();
 271   SafePointNode* ex_map = stop();  // do not manipulate this map any more
 272   set_saved_ex_oop(ex_map, ex_oop);
 273   return ex_map;
 274 }
 275 
 276 
 277 //--------------------------add_exception_state--------------------------------
 278 // Add an exception to my list of exceptions.
 279 void GraphKit::add_exception_state(SafePointNode* ex_map) {
 280   if (ex_map == nullptr || ex_map->control() == top()) {
 281     return;
 282   }
 283 #ifdef ASSERT
 284   verify_exception_state(ex_map);
 285   if (has_exceptions()) {
 286     assert(ex_map->jvms()->same_calls_as(_exceptions->jvms()), "all collected exceptions must come from the same place");
 287   }
 288 #endif
 289 
 290   // If there is already an exception of exactly this type, merge with it.
 291   // In particular, null-checks and other low-level exceptions common up here.
 292   Node*       ex_oop  = saved_ex_oop(ex_map);
 293   const Type* ex_type = _gvn.type(ex_oop);
 294   if (ex_oop == top()) {
 295     // No action needed.
 296     return;
 297   }
 298   assert(ex_type->isa_instptr(), "exception must be an instance");
 299   for (SafePointNode* e2 = _exceptions; e2 != nullptr; e2 = e2->next_exception()) {
 300     const Type* ex_type2 = _gvn.type(saved_ex_oop(e2));
 301     // We check sp also because call bytecodes can generate exceptions
 302     // both before and after arguments are popped!
 303     if (ex_type2 == ex_type
 304         && e2->_jvms->sp() == ex_map->_jvms->sp()) {
 305       combine_exception_states(ex_map, e2);
 306       return;
 307     }
 308   }
 309 
 310   // No pre-existing exception of the same type.  Chain it on the list.
 311   push_exception_state(ex_map);
 312 }
 313 
 314 //-----------------------add_exception_states_from-----------------------------
 315 void GraphKit::add_exception_states_from(JVMState* jvms) {
 316   SafePointNode* ex_map = jvms->map()->next_exception();
 317   if (ex_map != nullptr) {
 318     jvms->map()->set_next_exception(nullptr);
 319     for (SafePointNode* next_map; ex_map != nullptr; ex_map = next_map) {
 320       next_map = ex_map->next_exception();
 321       ex_map->set_next_exception(nullptr);
 322       add_exception_state(ex_map);
 323     }
 324   }
 325 }
 326 
 327 //-----------------------transfer_exceptions_into_jvms-------------------------
 328 JVMState* GraphKit::transfer_exceptions_into_jvms() {
 329   if (map() == nullptr) {
 330     // We need a JVMS to carry the exceptions, but the map has gone away.
 331     // Create a scratch JVMS, cloned from any of the exception states...
 332     if (has_exceptions()) {
 333       _map = _exceptions;
 334       _map = clone_map();
 335       _map->set_next_exception(nullptr);
 336       clear_saved_ex_oop(_map);
 337       DEBUG_ONLY(verify_map());
 338     } else {
 339       // ...or created from scratch
 340       JVMState* jvms = new (C) JVMState(_method, nullptr);
 341       jvms->set_bci(_bci);
 342       jvms->set_sp(_sp);
 343       jvms->set_map(new SafePointNode(TypeFunc::Parms, jvms));
 344       set_jvms(jvms);
 345       for (uint i = 0; i < map()->req(); i++)  map()->init_req(i, top());
 346       set_all_memory(top());
 347       while (map()->req() < jvms->endoff())  map()->add_req(top());
 348     }
 349     // (This is a kludge, in case you didn't notice.)
 350     set_control(top());
 351   }
 352   JVMState* jvms = sync_jvms();
 353   assert(!jvms->map()->has_exceptions(), "no exceptions on this map yet");
 354   jvms->map()->set_next_exception(_exceptions);
 355   _exceptions = nullptr;   // done with this set of exceptions
 356   return jvms;
 357 }
 358 
 359 static inline void add_n_reqs(Node* dstphi, Node* srcphi) {
 360   assert(is_hidden_merge(dstphi), "must be a special merge node");
 361   assert(is_hidden_merge(srcphi), "must be a special merge node");
 362   uint limit = srcphi->req();
 363   for (uint i = PhiNode::Input; i < limit; i++) {
 364     dstphi->add_req(srcphi->in(i));
 365   }
 366 }
 367 static inline void add_one_req(Node* dstphi, Node* src) {
 368   assert(is_hidden_merge(dstphi), "must be a special merge node");
 369   assert(!is_hidden_merge(src), "must not be a special merge node");
 370   dstphi->add_req(src);
 371 }
 372 
 373 //-----------------------combine_exception_states------------------------------
 374 // This helper function combines exception states by building phis on a
 375 // specially marked state-merging region.  These regions and phis are
 376 // untransformed, and can build up gradually.  The region is marked by
 377 // having a control input of its exception map, rather than null.  Such
 378 // regions do not appear except in this function, and in use_exception_state.
 379 void GraphKit::combine_exception_states(SafePointNode* ex_map, SafePointNode* phi_map) {
 380   if (failing_internal()) {
 381     return;  // dying anyway...
 382   }
 383   JVMState* ex_jvms = ex_map->_jvms;
 384   assert(ex_jvms->same_calls_as(phi_map->_jvms), "consistent call chains");
 385   assert(ex_jvms->stkoff() == phi_map->_jvms->stkoff(), "matching locals");
 386   // TODO 8325632 Re-enable
 387   // assert(ex_jvms->sp() == phi_map->_jvms->sp(), "matching stack sizes");
 388   assert(ex_jvms->monoff() == phi_map->_jvms->monoff(), "matching JVMS");
 389   assert(ex_jvms->scloff() == phi_map->_jvms->scloff(), "matching scalar replaced objects");
 390   assert(ex_map->req() == phi_map->req(), "matching maps");
 391   uint tos = ex_jvms->stkoff() + ex_jvms->sp();
 392   Node*         hidden_merge_mark = root();
 393   Node*         region  = phi_map->control();
 394   MergeMemNode* phi_mem = phi_map->merged_memory();
 395   MergeMemNode* ex_mem  = ex_map->merged_memory();
 396   if (region->in(0) != hidden_merge_mark) {
 397     // The control input is not (yet) a specially-marked region in phi_map.
 398     // Make it so, and build some phis.
 399     region = new RegionNode(2);
 400     _gvn.set_type(region, Type::CONTROL);
 401     region->set_req(0, hidden_merge_mark);  // marks an internal ex-state
 402     region->init_req(1, phi_map->control());
 403     phi_map->set_control(region);
 404     Node* io_phi = PhiNode::make(region, phi_map->i_o(), Type::ABIO);
 405     record_for_igvn(io_phi);
 406     _gvn.set_type(io_phi, Type::ABIO);
 407     phi_map->set_i_o(io_phi);
 408     for (MergeMemStream mms(phi_mem); mms.next_non_empty(); ) {
 409       Node* m = mms.memory();
 410       Node* m_phi = PhiNode::make(region, m, Type::MEMORY, mms.adr_type(C));
 411       record_for_igvn(m_phi);
 412       _gvn.set_type(m_phi, Type::MEMORY);
 413       mms.set_memory(m_phi);
 414     }
 415   }
 416 
 417   // Either or both of phi_map and ex_map might already be converted into phis.
 418   Node* ex_control = ex_map->control();
 419   // if there is special marking on ex_map also, we add multiple edges from src
 420   bool add_multiple = (ex_control->in(0) == hidden_merge_mark);
 421   // how wide was the destination phi_map, originally?
 422   uint orig_width = region->req();
 423 
 424   if (add_multiple) {
 425     add_n_reqs(region, ex_control);
 426     add_n_reqs(phi_map->i_o(), ex_map->i_o());
 427   } else {
 428     // ex_map has no merges, so we just add single edges everywhere
 429     add_one_req(region, ex_control);
 430     add_one_req(phi_map->i_o(), ex_map->i_o());
 431   }
 432   for (MergeMemStream mms(phi_mem, ex_mem); mms.next_non_empty2(); ) {
 433     if (mms.is_empty()) {
 434       // get a copy of the base memory, and patch some inputs into it
 435       const TypePtr* adr_type = mms.adr_type(C);
 436       Node* phi = mms.force_memory()->as_Phi()->slice_memory(adr_type);
 437       assert(phi->as_Phi()->region() == mms.base_memory()->in(0), "");
 438       mms.set_memory(phi);
 439       // Prepare to append interesting stuff onto the newly sliced phi:
 440       while (phi->req() > orig_width)  phi->del_req(phi->req()-1);
 441     }
 442     // Append stuff from ex_map:
 443     if (add_multiple) {
 444       add_n_reqs(mms.memory(), mms.memory2());
 445     } else {
 446       add_one_req(mms.memory(), mms.memory2());
 447     }
 448   }
 449   uint limit = ex_map->req();
 450   for (uint i = TypeFunc::Parms; i < limit; i++) {
 451     // Skip everything in the JVMS after tos.  (The ex_oop follows.)
 452     if (i == tos)  i = ex_jvms->monoff();
 453     Node* src = ex_map->in(i);
 454     Node* dst = phi_map->in(i);
 455     if (src != dst) {
 456       PhiNode* phi;
 457       if (dst->in(0) != region) {
 458         dst = phi = PhiNode::make(region, dst, _gvn.type(dst));
 459         record_for_igvn(phi);
 460         _gvn.set_type(phi, phi->type());
 461         phi_map->set_req(i, dst);
 462         // Prepare to append interesting stuff onto the new phi:
 463         while (dst->req() > orig_width)  dst->del_req(dst->req()-1);
 464       } else {
 465         assert(dst->is_Phi(), "nobody else uses a hidden region");
 466         phi = dst->as_Phi();
 467       }
 468       if (add_multiple && src->in(0) == ex_control) {
 469         // Both are phis.
 470         add_n_reqs(dst, src);
 471       } else {
 472         while (dst->req() < region->req())  add_one_req(dst, src);
 473       }
 474       const Type* srctype = _gvn.type(src);
 475       if (phi->type() != srctype) {
 476         const Type* dsttype = phi->type()->meet_speculative(srctype);
 477         if (phi->type() != dsttype) {
 478           phi->set_type(dsttype);
 479           _gvn.set_type(phi, dsttype);
 480         }
 481       }
 482     }
 483   }
 484   phi_map->merge_replaced_nodes_with(ex_map);
 485 }
 486 
 487 //--------------------------use_exception_state--------------------------------
 488 Node* GraphKit::use_exception_state(SafePointNode* phi_map) {
 489   if (failing_internal()) { stop(); return top(); }
 490   Node* region = phi_map->control();
 491   Node* hidden_merge_mark = root();
 492   assert(phi_map->jvms()->map() == phi_map, "sanity: 1-1 relation");
 493   Node* ex_oop = clear_saved_ex_oop(phi_map);
 494   if (region->in(0) == hidden_merge_mark) {
 495     // Special marking for internal ex-states.  Process the phis now.
 496     region->set_req(0, region);  // now it's an ordinary region
 497     set_jvms(phi_map->jvms());   // ...so now we can use it as a map
 498     // Note: Setting the jvms also sets the bci and sp.
 499     set_control(_gvn.transform(region));
 500     uint tos = jvms()->stkoff() + sp();
 501     for (uint i = 1; i < tos; i++) {
 502       Node* x = phi_map->in(i);
 503       if (x->in(0) == region) {
 504         assert(x->is_Phi(), "expected a special phi");
 505         phi_map->set_req(i, _gvn.transform(x));
 506       }
 507     }
 508     for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
 509       Node* x = mms.memory();
 510       if (x->in(0) == region) {
 511         assert(x->is_Phi(), "nobody else uses a hidden region");
 512         mms.set_memory(_gvn.transform(x));
 513       }
 514     }
 515     if (ex_oop->in(0) == region) {
 516       assert(ex_oop->is_Phi(), "expected a special phi");
 517       ex_oop = _gvn.transform(ex_oop);
 518     }
 519   } else {
 520     set_jvms(phi_map->jvms());
 521   }
 522 
 523   assert(!is_hidden_merge(phi_map->control()), "hidden ex. states cleared");
 524   assert(!is_hidden_merge(phi_map->i_o()), "hidden ex. states cleared");
 525   return ex_oop;
 526 }
 527 
 528 //---------------------------------java_bc-------------------------------------
 529 Bytecodes::Code GraphKit::java_bc() const {
 530   ciMethod* method = this->method();
 531   int       bci    = this->bci();
 532   if (method != nullptr && bci != InvocationEntryBci)
 533     return method->java_code_at_bci(bci);
 534   else
 535     return Bytecodes::_illegal;
 536 }
 537 
 538 void GraphKit::uncommon_trap_if_should_post_on_exceptions(Deoptimization::DeoptReason reason,
 539                                                           bool must_throw) {
 540     // if the exception capability is set, then we will generate code
 541     // to check the JavaThread.should_post_on_exceptions flag to see
 542     // if we actually need to report exception events (for this
 543     // thread).  If we don't need to report exception events, we will
 544     // take the normal fast path provided by add_exception_events.  If
 545     // exception event reporting is enabled for this thread, we will
 546     // take the uncommon_trap in the BuildCutout below.
 547 
 548     // first must access the should_post_on_exceptions_flag in this thread's JavaThread
 549     Node* jthread = _gvn.transform(new ThreadLocalNode());
 550     Node* adr = basic_plus_adr(top(), jthread, in_bytes(JavaThread::should_post_on_exceptions_flag_offset()));
 551     Node* should_post_flag = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
 552 
 553     // Test the should_post_on_exceptions_flag vs. 0
 554     Node* chk = _gvn.transform( new CmpINode(should_post_flag, intcon(0)) );
 555     Node* tst = _gvn.transform( new BoolNode(chk, BoolTest::eq) );
 556 
 557     // Branch to slow_path if should_post_on_exceptions_flag was true
 558     { BuildCutout unless(this, tst, PROB_MAX);
 559       // Do not try anything fancy if we're notifying the VM on every throw.
 560       // Cf. case Bytecodes::_athrow in parse2.cpp.
 561       uncommon_trap(reason, Deoptimization::Action_none,
 562                     (ciKlass*)nullptr, (char*)nullptr, must_throw);
 563     }
 564 
 565 }
 566 
 567 //------------------------------builtin_throw----------------------------------
 568 void GraphKit::builtin_throw(Deoptimization::DeoptReason reason) {
 569   builtin_throw(reason, builtin_throw_exception(reason), /*allow_too_many_traps*/ true);
 570 }
 571 
 572 void GraphKit::builtin_throw(Deoptimization::DeoptReason reason,
 573                              ciInstance* ex_obj,
 574                              bool allow_too_many_traps) {
 575   // If this throw happens frequently, an uncommon trap might cause
 576   // a performance pothole.  If there is a local exception handler,
 577   // and if this particular bytecode appears to be deoptimizing often,
 578   // let us handle the throw inline, with a preconstructed instance.
 579   // Note:   If the deopt count has blown up, the uncommon trap
 580   // runtime is going to flush this nmethod, not matter what.
 581   if (is_builtin_throw_hot(reason)) {
 582     if (method()->can_omit_stack_trace() && ex_obj != nullptr) {
 583       // If the throw is local, we use a pre-existing instance and
 584       // punt on the backtrace.  This would lead to a missing backtrace
 585       // (a repeat of 4292742) if the backtrace object is ever asked
 586       // for its backtrace.
 587       // Fixing this remaining case of 4292742 requires some flavor of
 588       // escape analysis.  Leave that for the future.
 589       if (env()->jvmti_can_post_on_exceptions()) {
 590         // check if we must post exception events, take uncommon trap if so
 591         uncommon_trap_if_should_post_on_exceptions(reason, true /*must_throw*/);
 592         // here if should_post_on_exceptions is false
 593         // continue on with the normal codegen
 594       }
 595 
 596       // Cheat with a preallocated exception object.
 597       if (C->log() != nullptr)
 598         C->log()->elem("hot_throw preallocated='1' reason='%s'",
 599                        Deoptimization::trap_reason_name(reason));
 600       const TypeInstPtr* ex_con  = TypeInstPtr::make(ex_obj);
 601       Node*              ex_node = _gvn.transform(ConNode::make(ex_con));
 602 
 603       // Clear the detail message of the preallocated exception object.
 604       // Weblogic sometimes mutates the detail message of exceptions
 605       // using reflection.
 606       int offset = java_lang_Throwable::get_detailMessage_offset();
 607       const TypePtr* adr_typ = ex_con->add_offset(offset);
 608 
 609       Node *adr = basic_plus_adr(ex_node, ex_node, offset);
 610       const TypeOopPtr* val_type = TypeOopPtr::make_from_klass(env()->String_klass());
 611       Node *store = access_store_at(ex_node, adr, adr_typ, null(), val_type, T_OBJECT, IN_HEAP);
 612 
 613       if (!method()->has_exception_handlers()) {
 614         // We don't need to preserve the stack if there's no handler as the entire frame is going to be popped anyway.
 615         // This prevents issues with exception handling and late inlining.
 616         set_sp(0);
 617         clean_stack(0);
 618       }
 619 
 620       add_exception_state(make_exception_state(ex_node));
 621       return;
 622     } else if (builtin_throw_too_many_traps(reason, ex_obj)) {
 623       // We cannot afford to take too many traps here. Suffer in the interpreter instead.
 624       assert(allow_too_many_traps, "not allowed");
 625       if (C->log() != nullptr) {
 626         C->log()->elem("hot_throw preallocated='0' reason='%s' mcount='%d'",
 627                        Deoptimization::trap_reason_name(reason),
 628                        C->trap_count(reason));
 629       }
 630       uncommon_trap(reason, Deoptimization::Action_none,
 631                     (ciKlass*) nullptr, (char*) nullptr,
 632                     true /*must_throw*/);
 633       return;
 634     }
 635   }
 636 
 637   // %%% Maybe add entry to OptoRuntime which directly throws the exc.?
 638   // It won't be much cheaper than bailing to the interp., since we'll
 639   // have to pass up all the debug-info, and the runtime will have to
 640   // create the stack trace.
 641 
 642   // Usual case:  Bail to interpreter.
 643   // Reserve the right to recompile if we haven't seen anything yet.
 644 
 645   // "must_throw" prunes the JVM state to include only the stack, if there
 646   // are no local exception handlers.  This should cut down on register
 647   // allocation time and code size, by drastically reducing the number
 648   // of in-edges on the call to the uncommon trap.
 649   uncommon_trap(reason, Deoptimization::Action_maybe_recompile,
 650                 (ciKlass*) nullptr, (char*) nullptr,
 651                 true /*must_throw*/);
 652 }
 653 
 654 bool GraphKit::is_builtin_throw_hot(Deoptimization::DeoptReason reason) {
 655   // If this particular condition has not yet happened at this
 656   // bytecode, then use the uncommon trap mechanism, and allow for
 657   // a future recompilation if several traps occur here.
 658   // If the throw is hot, try to use a more complicated inline mechanism
 659   // which keeps execution inside the compiled code.
 660   if (ProfileTraps) {
 661     if (too_many_traps(reason)) {
 662       return true;
 663     }
 664     // (If there is no MDO at all, assume it is early in
 665     // execution, and that any deopts are part of the
 666     // startup transient, and don't need to be remembered.)
 667 
 668     // Also, if there is a local exception handler, treat all throws
 669     // as hot if there has been at least one in this method.
 670     if (C->trap_count(reason) != 0 &&
 671         method()->method_data()->trap_count(reason) != 0 &&
 672         has_exception_handler()) {
 673       return true;
 674     }
 675   }
 676   return false;
 677 }
 678 
 679 bool GraphKit::builtin_throw_too_many_traps(Deoptimization::DeoptReason reason,
 680                                             ciInstance* ex_obj) {
 681   if (is_builtin_throw_hot(reason)) {
 682     if (method()->can_omit_stack_trace() && ex_obj != nullptr) {
 683       return false; // no traps; throws preallocated exception instead
 684     }
 685     ciMethod* m = Deoptimization::reason_is_speculate(reason) ? C->method() : nullptr;
 686     if (method()->method_data()->trap_recompiled_at(bci(), m) ||
 687         C->too_many_traps(reason)) {
 688       return true;
 689     }
 690   }
 691   return false;
 692 }
 693 
 694 ciInstance* GraphKit::builtin_throw_exception(Deoptimization::DeoptReason reason) const {
 695   // Preallocated exception objects to use when we don't need the backtrace.
 696   switch (reason) {
 697   case Deoptimization::Reason_null_check:
 698     return env()->NullPointerException_instance();
 699   case Deoptimization::Reason_div0_check:
 700     return env()->ArithmeticException_instance();
 701   case Deoptimization::Reason_range_check:
 702     return env()->ArrayIndexOutOfBoundsException_instance();
 703   case Deoptimization::Reason_class_check:
 704     return env()->ClassCastException_instance();
 705   case Deoptimization::Reason_array_check:
 706     return env()->ArrayStoreException_instance();
 707   default:
 708     return nullptr;
 709   }
 710 }
 711 
 712 //----------------------------PreserveJVMState---------------------------------
 713 PreserveJVMState::PreserveJVMState(GraphKit* kit, bool clone_map) {
 714   DEBUG_ONLY(kit->verify_map());
 715   _kit    = kit;
 716   _map    = kit->map();   // preserve the map
 717   _sp     = kit->sp();
 718   kit->set_map(clone_map ? kit->clone_map() : nullptr);
 719 #ifdef ASSERT
 720   _bci    = kit->bci();
 721   Parse* parser = kit->is_Parse();
 722   int block = (parser == nullptr || parser->block() == nullptr) ? -1 : parser->block()->rpo();
 723   _block  = block;
 724 #endif
 725 }
 726 PreserveJVMState::~PreserveJVMState() {
 727   GraphKit* kit = _kit;
 728 #ifdef ASSERT
 729   assert(kit->bci() == _bci, "bci must not shift");
 730   Parse* parser = kit->is_Parse();
 731   int block = (parser == nullptr || parser->block() == nullptr) ? -1 : parser->block()->rpo();
 732   assert(block == _block,    "block must not shift");
 733 #endif
 734   kit->set_map(_map);
 735   kit->set_sp(_sp);
 736 }
 737 
 738 
 739 //-----------------------------BuildCutout-------------------------------------
 740 BuildCutout::BuildCutout(GraphKit* kit, Node* p, float prob, float cnt)
 741   : PreserveJVMState(kit)
 742 {
 743   assert(p->is_Con() || p->is_Bool(), "test must be a bool");
 744   SafePointNode* outer_map = _map;   // preserved map is caller's
 745   SafePointNode* inner_map = kit->map();
 746   IfNode* iff = kit->create_and_map_if(outer_map->control(), p, prob, cnt);
 747   outer_map->set_control(kit->gvn().transform( new IfTrueNode(iff) ));
 748   inner_map->set_control(kit->gvn().transform( new IfFalseNode(iff) ));
 749 }
 750 BuildCutout::~BuildCutout() {
 751   GraphKit* kit = _kit;
 752   assert(kit->stopped(), "cutout code must stop, throw, return, etc.");
 753 }
 754 
 755 //---------------------------PreserveReexecuteState----------------------------
 756 PreserveReexecuteState::PreserveReexecuteState(GraphKit* kit) {
 757   assert(!kit->stopped(), "must call stopped() before");
 758   _kit    =    kit;
 759   _sp     =    kit->sp();
 760   _reexecute = kit->jvms()->_reexecute;
 761 }
 762 PreserveReexecuteState::~PreserveReexecuteState() {
 763   if (_kit->stopped()) return;
 764   _kit->jvms()->_reexecute = _reexecute;
 765   _kit->set_sp(_sp);
 766 }
 767 
 768 //------------------------------clone_map--------------------------------------
 769 // Implementation of PreserveJVMState
 770 //
 771 // Only clone_map(...) here. If this function is only used in the
 772 // PreserveJVMState class we may want to get rid of this extra
 773 // function eventually and do it all there.
 774 
 775 SafePointNode* GraphKit::clone_map() {
 776   if (map() == nullptr)  return nullptr;
 777 
 778   // Clone the memory edge first
 779   Node* mem = MergeMemNode::make(map()->memory());
 780   gvn().set_type_bottom(mem);
 781 
 782   SafePointNode *clonemap = (SafePointNode*)map()->clone();
 783   JVMState* jvms = this->jvms();
 784   JVMState* clonejvms = jvms->clone_shallow(C);
 785   clonemap->set_memory(mem);
 786   clonemap->set_jvms(clonejvms);
 787   clonejvms->set_map(clonemap);
 788   record_for_igvn(clonemap);
 789   gvn().set_type_bottom(clonemap);
 790   return clonemap;
 791 }
 792 
 793 //-----------------------------destruct_map_clone------------------------------
 794 //
 795 // Order of destruct is important to increase the likelyhood that memory can be re-used. We need
 796 // to destruct/free/delete in the exact opposite order as clone_map().
 797 void GraphKit::destruct_map_clone(SafePointNode* sfp) {
 798   if (sfp == nullptr) return;
 799 
 800   Node* mem = sfp->memory();
 801   JVMState* jvms = sfp->jvms();
 802 
 803   if (jvms != nullptr) {
 804     delete jvms;
 805   }
 806 
 807   remove_for_igvn(sfp);
 808   gvn().clear_type(sfp);
 809   sfp->destruct(&_gvn);
 810 
 811   if (mem != nullptr) {
 812     gvn().clear_type(mem);
 813     mem->destruct(&_gvn);
 814   }
 815 }
 816 
 817 //-----------------------------set_map_clone-----------------------------------
 818 void GraphKit::set_map_clone(SafePointNode* m) {
 819   _map = m;
 820   _map = clone_map();
 821   _map->set_next_exception(nullptr);
 822   DEBUG_ONLY(verify_map());
 823 }
 824 
 825 
 826 //----------------------------kill_dead_locals---------------------------------
 827 // Detect any locals which are known to be dead, and force them to top.
 828 void GraphKit::kill_dead_locals() {
 829   // Consult the liveness information for the locals.  If any
 830   // of them are unused, then they can be replaced by top().  This
 831   // should help register allocation time and cut down on the size
 832   // of the deoptimization information.
 833 
 834   // This call is made from many of the bytecode handling
 835   // subroutines called from the Big Switch in do_one_bytecode.
 836   // Every bytecode which might include a slow path is responsible
 837   // for killing its dead locals.  The more consistent we
 838   // are about killing deads, the fewer useless phis will be
 839   // constructed for them at various merge points.
 840 
 841   // bci can be -1 (InvocationEntryBci).  We return the entry
 842   // liveness for the method.
 843 
 844   if (method() == nullptr || method()->code_size() == 0) {
 845     // We are building a graph for a call to a native method.
 846     // All locals are live.
 847     return;
 848   }
 849 
 850   ResourceMark rm;
 851 
 852   // Consult the liveness information for the locals.  If any
 853   // of them are unused, then they can be replaced by top().  This
 854   // should help register allocation time and cut down on the size
 855   // of the deoptimization information.
 856   MethodLivenessResult live_locals = method()->liveness_at_bci(bci());
 857 
 858   int len = (int)live_locals.size();
 859   assert(len <= jvms()->loc_size(), "too many live locals");
 860   for (int local = 0; local < len; local++) {
 861     if (!live_locals.at(local)) {
 862       set_local(local, top());
 863     }
 864   }
 865 }
 866 
 867 #ifdef ASSERT
 868 //-------------------------dead_locals_are_killed------------------------------
 869 // Return true if all dead locals are set to top in the map.
 870 // Used to assert "clean" debug info at various points.
 871 bool GraphKit::dead_locals_are_killed() {
 872   if (method() == nullptr || method()->code_size() == 0) {
 873     // No locals need to be dead, so all is as it should be.
 874     return true;
 875   }
 876 
 877   // Make sure somebody called kill_dead_locals upstream.
 878   ResourceMark rm;
 879   for (JVMState* jvms = this->jvms(); jvms != nullptr; jvms = jvms->caller()) {
 880     if (jvms->loc_size() == 0)  continue;  // no locals to consult
 881     SafePointNode* map = jvms->map();
 882     ciMethod* method = jvms->method();
 883     int       bci    = jvms->bci();
 884     if (jvms == this->jvms()) {
 885       bci = this->bci();  // it might not yet be synched
 886     }
 887     MethodLivenessResult live_locals = method->liveness_at_bci(bci);
 888     int len = (int)live_locals.size();
 889     if (!live_locals.is_valid() || len == 0)
 890       // This method is trivial, or is poisoned by a breakpoint.
 891       return true;
 892     assert(len == jvms->loc_size(), "live map consistent with locals map");
 893     for (int local = 0; local < len; local++) {
 894       if (!live_locals.at(local) && map->local(jvms, local) != top()) {
 895         if (PrintMiscellaneous && (Verbose || WizardMode)) {
 896           tty->print_cr("Zombie local %d: ", local);
 897           jvms->dump();
 898         }
 899         return false;
 900       }
 901     }
 902   }
 903   return true;
 904 }
 905 
 906 #endif //ASSERT
 907 
 908 // Helper function for enforcing certain bytecodes to reexecute if deoptimization happens.
 909 static bool should_reexecute_implied_by_bytecode(JVMState *jvms, bool is_anewarray) {
 910   ciMethod* cur_method = jvms->method();
 911   int       cur_bci   = jvms->bci();
 912   if (cur_method != nullptr && cur_bci != InvocationEntryBci) {
 913     Bytecodes::Code code = cur_method->java_code_at_bci(cur_bci);
 914     return Interpreter::bytecode_should_reexecute(code) ||
 915            (is_anewarray && (code == Bytecodes::_multianewarray));
 916     // Reexecute _multianewarray bytecode which was replaced with
 917     // sequence of [a]newarray. See Parse::do_multianewarray().
 918     //
 919     // Note: interpreter should not have it set since this optimization
 920     // is limited by dimensions and guarded by flag so in some cases
 921     // multianewarray() runtime calls will be generated and
 922     // the bytecode should not be reexecutes (stack will not be reset).
 923   } else {
 924     return false;
 925   }
 926 }
 927 
 928 // Helper function for adding JVMState and debug information to node
 929 void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) {
 930   // Add the safepoint edges to the call (or other safepoint).
 931 
 932   // Make sure dead locals are set to top.  This
 933   // should help register allocation time and cut down on the size
 934   // of the deoptimization information.
 935   assert(dead_locals_are_killed(), "garbage in debug info before safepoint");
 936 
 937   // Walk the inline list to fill in the correct set of JVMState's
 938   // Also fill in the associated edges for each JVMState.
 939 
 940   // If the bytecode needs to be reexecuted we need to put
 941   // the arguments back on the stack.
 942   const bool should_reexecute = jvms()->should_reexecute();
 943   JVMState* youngest_jvms = should_reexecute ? sync_jvms_for_reexecute() : sync_jvms();
 944 
 945   // NOTE: set_bci (called from sync_jvms) might reset the reexecute bit to
 946   // undefined if the bci is different.  This is normal for Parse but it
 947   // should not happen for LibraryCallKit because only one bci is processed.
 948   assert(!is_LibraryCallKit() || (jvms()->should_reexecute() == should_reexecute),
 949          "in LibraryCallKit the reexecute bit should not change");
 950 
 951   // If we are guaranteed to throw, we can prune everything but the
 952   // input to the current bytecode.
 953   bool can_prune_locals = false;
 954   uint stack_slots_not_pruned = 0;
 955   int inputs = 0, depth = 0;
 956   if (must_throw) {
 957     assert(method() == youngest_jvms->method(), "sanity");
 958     if (compute_stack_effects(inputs, depth)) {
 959       can_prune_locals = true;
 960       stack_slots_not_pruned = inputs;
 961     }
 962   }
 963 
 964   if (env()->should_retain_local_variables()) {
 965     // At any safepoint, this method can get breakpointed, which would
 966     // then require an immediate deoptimization.
 967     can_prune_locals = false;  // do not prune locals
 968     stack_slots_not_pruned = 0;
 969   }
 970 
 971   // do not scribble on the input jvms
 972   JVMState* out_jvms = youngest_jvms->clone_deep(C);
 973   call->set_jvms(out_jvms); // Start jvms list for call node
 974 
 975   // For a known set of bytecodes, the interpreter should reexecute them if
 976   // deoptimization happens. We set the reexecute state for them here
 977   if (out_jvms->is_reexecute_undefined() && //don't change if already specified
 978       should_reexecute_implied_by_bytecode(out_jvms, call->is_AllocateArray())) {
 979 #ifdef ASSERT
 980     int inputs = 0, not_used; // initialized by GraphKit::compute_stack_effects()
 981     assert(method() == youngest_jvms->method(), "sanity");
 982     assert(compute_stack_effects(inputs, not_used), "unknown bytecode: %s", Bytecodes::name(java_bc()));
 983     // TODO 8371125
 984     // assert(out_jvms->sp() >= (uint)inputs, "not enough operands for reexecution");
 985 #endif // ASSERT
 986     out_jvms->set_should_reexecute(true); //NOTE: youngest_jvms not changed
 987   }
 988 
 989   // Presize the call:
 990   DEBUG_ONLY(uint non_debug_edges = call->req());
 991   call->add_req_batch(top(), youngest_jvms->debug_depth());
 992   assert(call->req() == non_debug_edges + youngest_jvms->debug_depth(), "");
 993 
 994   // Set up edges so that the call looks like this:
 995   //  Call [state:] ctl io mem fptr retadr
 996   //       [parms:] parm0 ... parmN
 997   //       [root:]  loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN
 998   //    [...mid:]   loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN [...]
 999   //       [young:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN
1000   // Note that caller debug info precedes callee debug info.
1001 
1002   // Fill pointer walks backwards from "young:" to "root:" in the diagram above:
1003   uint debug_ptr = call->req();
1004 
1005   // Loop over the map input edges associated with jvms, add them
1006   // to the call node, & reset all offsets to match call node array.
1007 
1008   JVMState* callee_jvms = nullptr;
1009   for (JVMState* in_jvms = youngest_jvms; in_jvms != nullptr; ) {
1010     uint debug_end   = debug_ptr;
1011     uint debug_start = debug_ptr - in_jvms->debug_size();
1012     debug_ptr = debug_start;  // back up the ptr
1013 
1014     uint p = debug_start;  // walks forward in [debug_start, debug_end)
1015     uint j, k, l;
1016     SafePointNode* in_map = in_jvms->map();
1017     out_jvms->set_map(call);
1018 
1019     if (can_prune_locals) {
1020       assert(in_jvms->method() == out_jvms->method(), "sanity");
1021       // If the current throw can reach an exception handler in this JVMS,
1022       // then we must keep everything live that can reach that handler.
1023       // As a quick and dirty approximation, we look for any handlers at all.
1024       if (in_jvms->method()->has_exception_handlers()) {
1025         can_prune_locals = false;
1026       }
1027     }
1028 
1029     // Add the Locals
1030     k = in_jvms->locoff();
1031     l = in_jvms->loc_size();
1032     out_jvms->set_locoff(p);
1033     if (!can_prune_locals) {
1034       for (j = 0; j < l; j++) {
1035         call->set_req(p++, in_map->in(k + j));
1036       }
1037     } else {
1038       p += l;  // already set to top above by add_req_batch
1039     }
1040 
1041     // Add the Expression Stack
1042     k = in_jvms->stkoff();
1043     l = in_jvms->sp();
1044     out_jvms->set_stkoff(p);
1045     if (!can_prune_locals) {
1046       for (j = 0; j < l; j++) {
1047         call->set_req(p++, in_map->in(k + j));
1048       }
1049     } else if (can_prune_locals && stack_slots_not_pruned != 0) {
1050       // Divide stack into {S0,...,S1}, where S0 is set to top.
1051       uint s1 = stack_slots_not_pruned;
1052       stack_slots_not_pruned = 0;  // for next iteration
1053       if (s1 > l)  s1 = l;
1054       uint s0 = l - s1;
1055       p += s0;  // skip the tops preinstalled by add_req_batch
1056       for (j = s0; j < l; j++)
1057         call->set_req(p++, in_map->in(k+j));
1058     } else {
1059       p += l;  // already set to top above by add_req_batch
1060     }
1061 
1062     // Add the Monitors
1063     k = in_jvms->monoff();
1064     l = in_jvms->mon_size();
1065     out_jvms->set_monoff(p);
1066     for (j = 0; j < l; j++)
1067       call->set_req(p++, in_map->in(k+j));
1068 
1069     // Copy any scalar object fields.
1070     k = in_jvms->scloff();
1071     l = in_jvms->scl_size();
1072     out_jvms->set_scloff(p);
1073     for (j = 0; j < l; j++)
1074       call->set_req(p++, in_map->in(k+j));
1075 
1076     // Finish the new jvms.
1077     out_jvms->set_endoff(p);
1078 
1079     assert(out_jvms->endoff()     == debug_end,             "fill ptr must match");
1080     assert(out_jvms->depth()      == in_jvms->depth(),      "depth must match");
1081     assert(out_jvms->loc_size()   == in_jvms->loc_size(),   "size must match");
1082     assert(out_jvms->mon_size()   == in_jvms->mon_size(),   "size must match");
1083     assert(out_jvms->scl_size()   == in_jvms->scl_size(),   "size must match");
1084     assert(out_jvms->debug_size() == in_jvms->debug_size(), "size must match");
1085 
1086     // Update the two tail pointers in parallel.
1087     callee_jvms = out_jvms;
1088     out_jvms = out_jvms->caller();
1089     in_jvms  = in_jvms->caller();
1090   }
1091 
1092   assert(debug_ptr == non_debug_edges, "debug info must fit exactly");
1093 
1094   // Test the correctness of JVMState::debug_xxx accessors:
1095   assert(call->jvms()->debug_start() == non_debug_edges, "");
1096   assert(call->jvms()->debug_end()   == call->req(), "");
1097   assert(call->jvms()->debug_depth() == call->req() - non_debug_edges, "");
1098 }
1099 
1100 bool GraphKit::compute_stack_effects(int& inputs, int& depth) {
1101   Bytecodes::Code code = java_bc();
1102   if (code == Bytecodes::_wide) {
1103     code = method()->java_code_at_bci(bci() + 1);
1104   }
1105 
1106   if (code != Bytecodes::_illegal) {
1107     depth = Bytecodes::depth(code); // checkcast=0, athrow=-1
1108   }
1109 
1110   auto rsize = [&]() {
1111     assert(code != Bytecodes::_illegal, "code is illegal!");
1112     BasicType rtype = Bytecodes::result_type(code); // checkcast=P, athrow=V
1113     return (rtype < T_CONFLICT) ? type2size[rtype] : 0;
1114   };
1115 
1116   switch (code) {
1117   case Bytecodes::_illegal:
1118     return false;
1119 
1120   case Bytecodes::_ldc:
1121   case Bytecodes::_ldc_w:
1122   case Bytecodes::_ldc2_w:
1123     inputs = 0;
1124     break;
1125 
1126   case Bytecodes::_dup:         inputs = 1;  break;
1127   case Bytecodes::_dup_x1:      inputs = 2;  break;
1128   case Bytecodes::_dup_x2:      inputs = 3;  break;
1129   case Bytecodes::_dup2:        inputs = 2;  break;
1130   case Bytecodes::_dup2_x1:     inputs = 3;  break;
1131   case Bytecodes::_dup2_x2:     inputs = 4;  break;
1132   case Bytecodes::_swap:        inputs = 2;  break;
1133   case Bytecodes::_arraylength: inputs = 1;  break;
1134 
1135   case Bytecodes::_getstatic:
1136   case Bytecodes::_putstatic:
1137   case Bytecodes::_getfield:
1138   case Bytecodes::_putfield:
1139     {
1140       bool ignored_will_link;
1141       ciField* field = method()->get_field_at_bci(bci(), ignored_will_link);
1142       int      size  = field->type()->size();
1143       bool is_get = (depth >= 0), is_static = (depth & 1);
1144       inputs = (is_static ? 0 : 1);
1145       if (is_get) {
1146         depth = size - inputs;
1147       } else {
1148         inputs += size;        // putxxx pops the value from the stack
1149         depth = - inputs;
1150       }
1151     }
1152     break;
1153 
1154   case Bytecodes::_invokevirtual:
1155   case Bytecodes::_invokespecial:
1156   case Bytecodes::_invokestatic:
1157   case Bytecodes::_invokedynamic:
1158   case Bytecodes::_invokeinterface:
1159     {
1160       bool ignored_will_link;
1161       ciSignature* declared_signature = nullptr;
1162       ciMethod* ignored_callee = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
1163       assert(declared_signature != nullptr, "cannot be null");
1164       inputs   = declared_signature->arg_size_for_bc(code);
1165       int size = declared_signature->return_type()->size();
1166       depth = size - inputs;
1167     }
1168     break;
1169 
1170   case Bytecodes::_multianewarray:
1171     {
1172       ciBytecodeStream iter(method());
1173       iter.reset_to_bci(bci());
1174       iter.next();
1175       inputs = iter.get_dimensions();
1176       assert(rsize() == 1, "");
1177       depth = 1 - inputs;
1178     }
1179     break;
1180 
1181   case Bytecodes::_ireturn:
1182   case Bytecodes::_lreturn:
1183   case Bytecodes::_freturn:
1184   case Bytecodes::_dreturn:
1185   case Bytecodes::_areturn:
1186     assert(rsize() == -depth, "");
1187     inputs = -depth;
1188     break;
1189 
1190   case Bytecodes::_jsr:
1191   case Bytecodes::_jsr_w:
1192     inputs = 0;
1193     depth  = 1;                  // S.B. depth=1, not zero
1194     break;
1195 
1196   default:
1197     // bytecode produces a typed result
1198     inputs = rsize() - depth;
1199     assert(inputs >= 0, "");
1200     break;
1201   }
1202 
1203 #ifdef ASSERT
1204   // spot check
1205   int outputs = depth + inputs;
1206   assert(outputs >= 0, "sanity");
1207   switch (code) {
1208   case Bytecodes::_checkcast: assert(inputs == 1 && outputs == 1, ""); break;
1209   case Bytecodes::_athrow:    assert(inputs == 1 && outputs == 0, ""); break;
1210   case Bytecodes::_aload_0:   assert(inputs == 0 && outputs == 1, ""); break;
1211   case Bytecodes::_return:    assert(inputs == 0 && outputs == 0, ""); break;
1212   case Bytecodes::_drem:      assert(inputs == 4 && outputs == 2, ""); break;
1213   default:                    break;
1214   }
1215 #endif //ASSERT
1216 
1217   return true;
1218 }
1219 
1220 
1221 
1222 //------------------------------basic_plus_adr---------------------------------
1223 Node* GraphKit::basic_plus_adr(Node* base, Node* ptr, Node* offset) {
1224   // short-circuit a common case
1225   if (offset == MakeConX(0)) {
1226     return ptr;
1227   }
1228 #ifdef ASSERT
1229   // Both 32-bit and 64-bit zeros should have been handled by the previous `if`
1230   // statement, so if we see either 32-bit or 64-bit zeros here, then we have a
1231   // problem.
1232   if (offset->is_Con()) {
1233     const Type* t = offset->bottom_type();
1234     bool is_zero_int = t->isa_int() && t->is_int()->get_con() == 0;
1235     bool is_zero_long = t->isa_long() && t->is_long()->get_con() == 0;
1236     assert(!is_zero_int && !is_zero_long,
1237            "Unexpected zero offset - should have matched MakeConX(0)");
1238   }
1239 #endif
1240   return _gvn.transform( new AddPNode(base, ptr, offset) );
1241 }
1242 
1243 Node* GraphKit::ConvI2L(Node* offset) {
1244   // short-circuit a common case
1245   jint offset_con = find_int_con(offset, Type::OffsetBot);
1246   if (offset_con != Type::OffsetBot) {
1247     return longcon((jlong) offset_con);
1248   }
1249   return _gvn.transform( new ConvI2LNode(offset));
1250 }
1251 
1252 Node* GraphKit::ConvI2UL(Node* offset) {
1253   juint offset_con = (juint) find_int_con(offset, Type::OffsetBot);
1254   if (offset_con != (juint) Type::OffsetBot) {
1255     return longcon((julong) offset_con);
1256   }
1257   Node* conv = _gvn.transform( new ConvI2LNode(offset));
1258   Node* mask = _gvn.transform(ConLNode::make((julong) max_juint));
1259   return _gvn.transform( new AndLNode(conv, mask) );
1260 }
1261 
1262 Node* GraphKit::ConvL2I(Node* offset) {
1263   // short-circuit a common case
1264   jlong offset_con = find_long_con(offset, (jlong)Type::OffsetBot);
1265   if (offset_con != (jlong)Type::OffsetBot) {
1266     return intcon((int) offset_con);
1267   }
1268   return _gvn.transform( new ConvL2INode(offset));
1269 }
1270 
1271 //-------------------------load_object_klass-----------------------------------
1272 Node* GraphKit::load_object_klass(Node* obj) {
1273   // Special-case a fresh allocation to avoid building nodes:
1274   Node* akls = AllocateNode::Ideal_klass(obj, &_gvn);
1275   if (akls != nullptr)  return akls;
1276   Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
1277   return _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), k_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
1278 }
1279 
1280 //-------------------------load_array_length-----------------------------------
1281 Node* GraphKit::load_array_length(Node* array) {
1282   // Special-case a fresh allocation to avoid building nodes:
1283   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(array);
1284   Node *alen;
1285   if (alloc == nullptr) {
1286     Node *r_adr = basic_plus_adr(array, arrayOopDesc::length_offset_in_bytes());
1287     alen = _gvn.transform( new LoadRangeNode(nullptr, immutable_memory(), r_adr, TypeInt::POS));
1288   } else {
1289     alen = array_ideal_length(alloc, _gvn.type(array)->is_oopptr(), false);
1290   }
1291   return alen;
1292 }
1293 
1294 Node* GraphKit::array_ideal_length(AllocateArrayNode* alloc,
1295                                    const TypeOopPtr* oop_type,
1296                                    bool replace_length_in_map) {
1297   Node* length = alloc->Ideal_length();
1298   if (replace_length_in_map == false || map()->find_edge(length) >= 0) {
1299     Node* ccast = alloc->make_ideal_length(oop_type, &_gvn);
1300     if (ccast != length) {
1301       // do not transform ccast here, it might convert to top node for
1302       // negative array length and break assumptions in parsing stage.
1303       _gvn.set_type_bottom(ccast);
1304       record_for_igvn(ccast);
1305       if (replace_length_in_map) {
1306         replace_in_map(length, ccast);
1307       }
1308       return ccast;
1309     }
1310   }
1311   return length;
1312 }
1313 
1314 //------------------------------do_null_check----------------------------------
1315 // Helper function to do a null pointer check.  Returned value is
1316 // the incoming address with null casted away.  You are allowed to use the
1317 // not-null value only if you are control dependent on the test.
1318 #ifndef PRODUCT
1319 extern uint explicit_null_checks_inserted,
1320             explicit_null_checks_elided;
1321 #endif
1322 Node* GraphKit::null_check_common(Node* value, BasicType type,
1323                                   // optional arguments for variations:
1324                                   bool assert_null,
1325                                   Node* *null_control,
1326                                   bool speculative,
1327                                   bool null_marker_check) {
1328   assert(!assert_null || null_control == nullptr, "not both at once");
1329   if (stopped())  return top();
1330   NOT_PRODUCT(explicit_null_checks_inserted++);
1331 
1332   if (value->is_InlineType()) {
1333     // Null checking a scalarized but nullable inline type. Check the null marker
1334     // input instead of the oop input to avoid keeping buffer allocations alive.
1335     InlineTypeNode* vtptr = value->as_InlineType();
1336     while (vtptr->get_oop()->is_InlineType()) {
1337       vtptr = vtptr->get_oop()->as_InlineType();
1338     }
1339     null_check_common(vtptr->get_null_marker(), T_INT, assert_null, null_control, speculative, true);
1340     if (stopped()) {
1341       return top();
1342     }
1343     if (assert_null) {
1344       // TODO 8284443 Scalarize here (this currently leads to compilation bailouts)
1345       // vtptr = InlineTypeNode::make_null(_gvn, vtptr->type()->inline_klass());
1346       // replace_in_map(value, vtptr);
1347       // return vtptr;
1348       replace_in_map(value, null());
1349       return null();
1350     }
1351     bool do_replace_in_map = (null_control == nullptr || (*null_control) == top());
1352     return cast_not_null(value, do_replace_in_map);
1353   }
1354 
1355   // Construct null check
1356   Node *chk = nullptr;
1357   switch(type) {
1358     case T_LONG   : chk = new CmpLNode(value, _gvn.zerocon(T_LONG)); break;
1359     case T_INT    : chk = new CmpINode(value, _gvn.intcon(0)); break;
1360     case T_ARRAY  : // fall through
1361       type = T_OBJECT;  // simplify further tests
1362     case T_OBJECT : {
1363       const Type *t = _gvn.type( value );
1364 
1365       const TypeOopPtr* tp = t->isa_oopptr();
1366       if (tp != nullptr && !tp->is_loaded()
1367           // Only for do_null_check, not any of its siblings:
1368           && !assert_null && null_control == nullptr) {
1369         // Usually, any field access or invocation on an unloaded oop type
1370         // will simply fail to link, since the statically linked class is
1371         // likely also to be unloaded.  However, in -Xcomp mode, sometimes
1372         // the static class is loaded but the sharper oop type is not.
1373         // Rather than checking for this obscure case in lots of places,
1374         // we simply observe that a null check on an unloaded class
1375         // will always be followed by a nonsense operation, so we
1376         // can just issue the uncommon trap here.
1377         // Our access to the unloaded class will only be correct
1378         // after it has been loaded and initialized, which requires
1379         // a trip through the interpreter.
1380         ciKlass* klass = tp->unloaded_klass();
1381 #ifndef PRODUCT
1382         if (WizardMode) { tty->print("Null check of unloaded "); klass->print(); tty->cr(); }
1383 #endif
1384         uncommon_trap(Deoptimization::Reason_unloaded,
1385                       Deoptimization::Action_reinterpret,
1386                       klass, "!loaded");
1387         return top();
1388       }
1389 
1390       if (assert_null) {
1391         // See if the type is contained in NULL_PTR.
1392         // If so, then the value is already null.
1393         if (t->higher_equal(TypePtr::NULL_PTR)) {
1394           NOT_PRODUCT(explicit_null_checks_elided++);
1395           return value;           // Elided null assert quickly!
1396         }
1397       } else {
1398         // See if mixing in the null pointer changes type.
1399         // If so, then the null pointer was not allowed in the original
1400         // type.  In other words, "value" was not-null.
1401         if (t->meet(TypePtr::NULL_PTR) != t->remove_speculative()) {
1402           // same as: if (!TypePtr::NULL_PTR->higher_equal(t)) ...
1403           NOT_PRODUCT(explicit_null_checks_elided++);
1404           return value;           // Elided null check quickly!
1405         }
1406       }
1407       chk = new CmpPNode( value, null() );
1408       break;
1409     }
1410 
1411     default:
1412       fatal("unexpected type: %s", type2name(type));
1413   }
1414   assert(chk != nullptr, "sanity check");
1415   chk = _gvn.transform(chk);
1416 
1417   BoolTest::mask btest = assert_null ? BoolTest::eq : BoolTest::ne;
1418   BoolNode *btst = new BoolNode( chk, btest);
1419   Node   *tst = _gvn.transform( btst );
1420 
1421   //-----------
1422   // if peephole optimizations occurred, a prior test existed.
1423   // If a prior test existed, maybe it dominates as we can avoid this test.
1424   if (tst != btst && type == T_OBJECT) {
1425     // At this point we want to scan up the CFG to see if we can
1426     // find an identical test (and so avoid this test altogether).
1427     Node *cfg = control();
1428     int depth = 0;
1429     while( depth < 16 ) {       // Limit search depth for speed
1430       if( cfg->Opcode() == Op_IfTrue &&
1431           cfg->in(0)->in(1) == tst ) {
1432         // Found prior test.  Use "cast_not_null" to construct an identical
1433         // CastPP (and hence hash to) as already exists for the prior test.
1434         // Return that casted value.
1435         if (assert_null) {
1436           replace_in_map(value, null());
1437           return null();  // do not issue the redundant test
1438         }
1439         Node *oldcontrol = control();
1440         set_control(cfg);
1441         Node *res = cast_not_null(value);
1442         set_control(oldcontrol);
1443         NOT_PRODUCT(explicit_null_checks_elided++);
1444         return res;
1445       }
1446       cfg = IfNode::up_one_dom(cfg, /*linear_only=*/ true);
1447       if (cfg == nullptr)  break;  // Quit at region nodes
1448       depth++;
1449     }
1450   }
1451 
1452   //-----------
1453   // Branch to failure if null
1454   float ok_prob = PROB_MAX;  // a priori estimate:  nulls never happen
1455   Deoptimization::DeoptReason reason;
1456   if (assert_null) {
1457     reason = Deoptimization::reason_null_assert(speculative);
1458   } else if (type == T_OBJECT || null_marker_check) {
1459     reason = Deoptimization::reason_null_check(speculative);
1460   } else {
1461     reason = Deoptimization::Reason_div0_check;
1462   }
1463   // %%% Since Reason_unhandled is not recorded on a per-bytecode basis,
1464   // ciMethodData::has_trap_at will return a conservative -1 if any
1465   // must-be-null assertion has failed.  This could cause performance
1466   // problems for a method after its first do_null_assert failure.
1467   // Consider using 'Reason_class_check' instead?
1468 
1469   // To cause an implicit null check, we set the not-null probability
1470   // to the maximum (PROB_MAX).  For an explicit check the probability
1471   // is set to a smaller value.
1472   if (null_control != nullptr || too_many_traps(reason)) {
1473     // probability is less likely
1474     ok_prob =  PROB_LIKELY_MAG(3);
1475   } else if (!assert_null &&
1476              (ImplicitNullCheckThreshold > 0) &&
1477              method() != nullptr &&
1478              (method()->method_data()->trap_count(reason)
1479               >= (uint)ImplicitNullCheckThreshold)) {
1480     ok_prob =  PROB_LIKELY_MAG(3);
1481   }
1482 
1483   if (null_control != nullptr) {
1484     IfNode* iff = create_and_map_if(control(), tst, ok_prob, COUNT_UNKNOWN);
1485     Node* null_true = _gvn.transform( new IfFalseNode(iff));
1486     set_control(      _gvn.transform( new IfTrueNode(iff)));
1487 #ifndef PRODUCT
1488     if (null_true == top()) {
1489       explicit_null_checks_elided++;
1490     }
1491 #endif
1492     (*null_control) = null_true;
1493   } else {
1494     BuildCutout unless(this, tst, ok_prob);
1495     // Check for optimizer eliding test at parse time
1496     if (stopped()) {
1497       // Failure not possible; do not bother making uncommon trap.
1498       NOT_PRODUCT(explicit_null_checks_elided++);
1499     } else if (assert_null) {
1500       uncommon_trap(reason,
1501                     Deoptimization::Action_make_not_entrant,
1502                     nullptr, "assert_null");
1503     } else {
1504       replace_in_map(value, zerocon(type));
1505       builtin_throw(reason);
1506     }
1507   }
1508 
1509   // Must throw exception, fall-thru not possible?
1510   if (stopped()) {
1511     return top();               // No result
1512   }
1513 
1514   if (assert_null) {
1515     // Cast obj to null on this path.
1516     replace_in_map(value, zerocon(type));
1517     return zerocon(type);
1518   }
1519 
1520   // Cast obj to not-null on this path, if there is no null_control.
1521   // (If there is a null_control, a non-null value may come back to haunt us.)
1522   if (type == T_OBJECT) {
1523     Node* cast = cast_not_null(value, false);
1524     if (null_control == nullptr || (*null_control) == top())
1525       replace_in_map(value, cast);
1526     value = cast;
1527   }
1528 
1529   return value;
1530 }
1531 
1532 //------------------------------cast_not_null----------------------------------
1533 // Cast obj to not-null on this path
1534 Node* GraphKit::cast_not_null(Node* obj, bool do_replace_in_map) {
1535   if (obj->is_InlineType()) {
1536     Node* vt = obj->isa_InlineType()->clone_if_required(&gvn(), map(), do_replace_in_map);
1537     vt->as_InlineType()->set_null_marker(_gvn);
1538     vt = _gvn.transform(vt);
1539     if (do_replace_in_map) {
1540       replace_in_map(obj, vt);
1541     }
1542     return vt;
1543   }
1544   const Type *t = _gvn.type(obj);
1545   const Type *t_not_null = t->join_speculative(TypePtr::NOTNULL);
1546   // Object is already not-null?
1547   if( t == t_not_null ) return obj;
1548 
1549   Node* cast = new CastPPNode(control(), obj,t_not_null);
1550   cast = _gvn.transform( cast );
1551 
1552   // Scan for instances of 'obj' in the current JVM mapping.
1553   // These instances are known to be not-null after the test.
1554   if (do_replace_in_map)
1555     replace_in_map(obj, cast);
1556 
1557   return cast;                  // Return casted value
1558 }
1559 
1560 // Sometimes in intrinsics, we implicitly know an object is not null
1561 // (there's no actual null check) so we can cast it to not null. In
1562 // the course of optimizations, the input to the cast can become null.
1563 // In that case that data path will die and we need the control path
1564 // to become dead as well to keep the graph consistent. So we have to
1565 // add a check for null for which one branch can't be taken. It uses
1566 // an OpaqueConstantBool node that will cause the check to be removed after loop
1567 // opts so the test goes away and the compiled code doesn't execute a
1568 // useless check.
1569 Node* GraphKit::must_be_not_null(Node* value, bool do_replace_in_map) {
1570   if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(value))) {
1571     return value;
1572   }
1573   Node* chk = _gvn.transform(new CmpPNode(value, null()));
1574   Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
1575   Node* opaq = _gvn.transform(new OpaqueConstantBoolNode(C, tst, true));
1576   IfNode* iff = new IfNode(control(), opaq, PROB_MAX, COUNT_UNKNOWN);
1577   _gvn.set_type(iff, iff->Value(&_gvn));
1578   if (!tst->is_Con()) {
1579     record_for_igvn(iff);
1580   }
1581   Node *if_f = _gvn.transform(new IfFalseNode(iff));
1582   Node *frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
1583   halt(if_f, frame, "unexpected null in intrinsic");
1584   Node *if_t = _gvn.transform(new IfTrueNode(iff));
1585   set_control(if_t);
1586   return cast_not_null(value, do_replace_in_map);
1587 }
1588 
1589 
1590 //--------------------------replace_in_map-------------------------------------
1591 void GraphKit::replace_in_map(Node* old, Node* neww) {
1592   if (old == neww) {
1593     return;
1594   }
1595 
1596   map()->replace_edge(old, neww);
1597 
1598   // Note: This operation potentially replaces any edge
1599   // on the map.  This includes locals, stack, and monitors
1600   // of the current (innermost) JVM state.
1601 
1602   // don't let inconsistent types from profiling escape this
1603   // method
1604 
1605   const Type* told = _gvn.type(old);
1606   const Type* tnew = _gvn.type(neww);
1607 
1608   if (!tnew->higher_equal(told)) {
1609     return;
1610   }
1611 
1612   map()->record_replaced_node(old, neww);
1613 }
1614 
1615 
1616 //=============================================================================
1617 //--------------------------------memory---------------------------------------
1618 Node* GraphKit::memory(uint alias_idx) {
1619   MergeMemNode* mem = merged_memory();
1620   Node* p = mem->memory_at(alias_idx);
1621   assert(p != mem->empty_memory(), "empty");
1622   _gvn.set_type(p, Type::MEMORY);  // must be mapped
1623   return p;
1624 }
1625 
1626 //-----------------------------reset_memory------------------------------------
1627 Node* GraphKit::reset_memory() {
1628   Node* mem = map()->memory();
1629   // do not use this node for any more parsing!
1630   DEBUG_ONLY( map()->set_memory((Node*)nullptr) );
1631   return _gvn.transform( mem );
1632 }
1633 
1634 //------------------------------set_all_memory---------------------------------
1635 void GraphKit::set_all_memory(Node* newmem) {
1636   Node* mergemem = MergeMemNode::make(newmem);
1637   gvn().set_type_bottom(mergemem);
1638   if (_gvn.is_IterGVN() != nullptr) {
1639     record_for_igvn(mergemem);
1640   }
1641   map()->set_memory(mergemem);
1642 }
1643 
1644 //------------------------------set_all_memory_call----------------------------
1645 void GraphKit::set_all_memory_call(Node* call, bool separate_io_proj) {
1646   Node* newmem = _gvn.transform( new ProjNode(call, TypeFunc::Memory, separate_io_proj) );
1647   set_all_memory(newmem);
1648 }
1649 
1650 //=============================================================================
1651 //
1652 // parser factory methods for MemNodes
1653 //
1654 // These are layered on top of the factory methods in LoadNode and StoreNode,
1655 // and integrate with the parser's memory state and _gvn engine.
1656 //
1657 
1658 // factory methods in "int adr_idx"
1659 Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt,
1660                           MemNode::MemOrd mo,
1661                           LoadNode::ControlDependency control_dependency,
1662                           bool require_atomic_access,
1663                           bool unaligned,
1664                           bool mismatched,
1665                           bool unsafe,
1666                           uint8_t barrier_data) {
1667   int adr_idx = C->get_alias_index(_gvn.type(adr)->isa_ptr());
1668   assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" );
1669   const TypePtr* adr_type = nullptr; // debug-mode-only argument
1670   DEBUG_ONLY(adr_type = C->get_adr_type(adr_idx));
1671   Node* mem = memory(adr_idx);
1672   Node* ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency, require_atomic_access, unaligned, mismatched, unsafe, barrier_data);
1673   ld = _gvn.transform(ld);
1674 
1675   if (((bt == T_OBJECT) && C->do_escape_analysis()) || C->eliminate_boxing()) {
1676     // Improve graph before escape analysis and boxing elimination.
1677     record_for_igvn(ld);
1678     if (ld->is_DecodeN()) {
1679       // Also record the actual load (LoadN) in case ld is DecodeN. In some
1680       // rare corner cases, ld->in(1) can be something other than LoadN (e.g.,
1681       // a Phi). Recording such cases is still perfectly sound, but may be
1682       // unnecessary and result in some minor IGVN overhead.
1683       record_for_igvn(ld->in(1));
1684     }
1685   }
1686   return ld;
1687 }
1688 
1689 Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt,
1690                                 MemNode::MemOrd mo,
1691                                 bool require_atomic_access,
1692                                 bool unaligned,
1693                                 bool mismatched,
1694                                 bool unsafe,
1695                                 int barrier_data) {
1696   int adr_idx = C->get_alias_index(_gvn.type(adr)->isa_ptr());
1697   assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
1698   const TypePtr* adr_type = nullptr;
1699   DEBUG_ONLY(adr_type = C->get_adr_type(adr_idx));
1700   Node *mem = memory(adr_idx);
1701   Node* st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo, require_atomic_access);
1702   if (unaligned) {
1703     st->as_Store()->set_unaligned_access();
1704   }
1705   if (mismatched) {
1706     st->as_Store()->set_mismatched_access();
1707   }
1708   if (unsafe) {
1709     st->as_Store()->set_unsafe_access();
1710   }
1711   st->as_Store()->set_barrier_data(barrier_data);
1712   st = _gvn.transform(st);
1713   set_memory(st, adr_idx);
1714   // Back-to-back stores can only remove intermediate store with DU info
1715   // so push on worklist for optimizer.
1716   if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address))
1717     record_for_igvn(st);
1718 
1719   return st;
1720 }
1721 
1722 Node* GraphKit::access_store_at(Node* obj,
1723                                 Node* adr,
1724                                 const TypePtr* adr_type,
1725                                 Node* val,
1726                                 const Type* val_type,
1727                                 BasicType bt,
1728                                 DecoratorSet decorators,
1729                                 bool safe_for_replace,
1730                                 const InlineTypeNode* vt) {
1731   // Transformation of a value which could be null pointer (CastPP #null)
1732   // could be delayed during Parse (for example, in adjust_map_after_if()).
1733   // Execute transformation here to avoid barrier generation in such case.
1734   if (_gvn.type(val) == TypePtr::NULL_PTR) {
1735     val = _gvn.makecon(TypePtr::NULL_PTR);
1736   }
1737 
1738   if (stopped()) {
1739     return top(); // Dead path ?
1740   }
1741 
1742   assert(val != nullptr, "not dead path");
1743   if (val->is_InlineType()) {
1744     // Store to non-flat field. Buffer the inline type and make sure
1745     // the store is re-executed if the allocation triggers deoptimization.
1746     PreserveReexecuteState preexecs(this);
1747     jvms()->set_should_reexecute(true);
1748     val = val->as_InlineType()->buffer(this, safe_for_replace);
1749   }
1750 
1751   C2AccessValuePtr addr(adr, adr_type);
1752   C2AccessValue value(val, val_type);
1753   C2ParseAccess access(this, decorators | C2_WRITE_ACCESS, bt, obj, addr, nullptr, vt);
1754   if (access.is_raw()) {
1755     return _barrier_set->BarrierSetC2::store_at(access, value);
1756   } else {
1757     return _barrier_set->store_at(access, value);
1758   }
1759 }
1760 
1761 Node* GraphKit::access_load_at(Node* obj,   // containing obj
1762                                Node* adr,   // actual address to store val at
1763                                const TypePtr* adr_type,
1764                                const Type* val_type,
1765                                BasicType bt,
1766                                DecoratorSet decorators,
1767                                Node* ctl) {
1768   if (stopped()) {
1769     return top(); // Dead path ?
1770   }
1771 
1772   C2AccessValuePtr addr(adr, adr_type);
1773   C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, obj, addr, ctl);
1774   if (access.is_raw()) {
1775     return _barrier_set->BarrierSetC2::load_at(access, val_type);
1776   } else {
1777     return _barrier_set->load_at(access, val_type);
1778   }
1779 }
1780 
1781 Node* GraphKit::access_load(Node* adr,   // actual address to load val at
1782                             const Type* val_type,
1783                             BasicType bt,
1784                             DecoratorSet decorators) {
1785   if (stopped()) {
1786     return top(); // Dead path ?
1787   }
1788 
1789   C2AccessValuePtr addr(adr, adr->bottom_type()->is_ptr());
1790   C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, nullptr, addr);
1791   if (access.is_raw()) {
1792     return _barrier_set->BarrierSetC2::load_at(access, val_type);
1793   } else {
1794     return _barrier_set->load_at(access, val_type);
1795   }
1796 }
1797 
1798 Node* GraphKit::access_atomic_cmpxchg_val_at(Node* obj,
1799                                              Node* adr,
1800                                              const TypePtr* adr_type,
1801                                              int alias_idx,
1802                                              Node* expected_val,
1803                                              Node* new_val,
1804                                              const Type* value_type,
1805                                              BasicType bt,
1806                                              DecoratorSet decorators) {
1807   C2AccessValuePtr addr(adr, adr_type);
1808   C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS,
1809                         bt, obj, addr, alias_idx);
1810   if (access.is_raw()) {
1811     return _barrier_set->BarrierSetC2::atomic_cmpxchg_val_at(access, expected_val, new_val, value_type);
1812   } else {
1813     return _barrier_set->atomic_cmpxchg_val_at(access, expected_val, new_val, value_type);
1814   }
1815 }
1816 
1817 Node* GraphKit::access_atomic_cmpxchg_bool_at(Node* obj,
1818                                               Node* adr,
1819                                               const TypePtr* adr_type,
1820                                               int alias_idx,
1821                                               Node* expected_val,
1822                                               Node* new_val,
1823                                               const Type* value_type,
1824                                               BasicType bt,
1825                                               DecoratorSet decorators) {
1826   C2AccessValuePtr addr(adr, adr_type);
1827   C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS,
1828                         bt, obj, addr, alias_idx);
1829   if (access.is_raw()) {
1830     return _barrier_set->BarrierSetC2::atomic_cmpxchg_bool_at(access, expected_val, new_val, value_type);
1831   } else {
1832     return _barrier_set->atomic_cmpxchg_bool_at(access, expected_val, new_val, value_type);
1833   }
1834 }
1835 
1836 Node* GraphKit::access_atomic_xchg_at(Node* obj,
1837                                       Node* adr,
1838                                       const TypePtr* adr_type,
1839                                       int alias_idx,
1840                                       Node* new_val,
1841                                       const Type* value_type,
1842                                       BasicType bt,
1843                                       DecoratorSet decorators) {
1844   C2AccessValuePtr addr(adr, adr_type);
1845   C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS,
1846                         bt, obj, addr, alias_idx);
1847   if (access.is_raw()) {
1848     return _barrier_set->BarrierSetC2::atomic_xchg_at(access, new_val, value_type);
1849   } else {
1850     return _barrier_set->atomic_xchg_at(access, new_val, value_type);
1851   }
1852 }
1853 
1854 Node* GraphKit::access_atomic_add_at(Node* obj,
1855                                      Node* adr,
1856                                      const TypePtr* adr_type,
1857                                      int alias_idx,
1858                                      Node* new_val,
1859                                      const Type* value_type,
1860                                      BasicType bt,
1861                                      DecoratorSet decorators) {
1862   C2AccessValuePtr addr(adr, adr_type);
1863   C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, bt, obj, addr, alias_idx);
1864   if (access.is_raw()) {
1865     return _barrier_set->BarrierSetC2::atomic_add_at(access, new_val, value_type);
1866   } else {
1867     return _barrier_set->atomic_add_at(access, new_val, value_type);
1868   }
1869 }
1870 
1871 void GraphKit::access_clone(Node* src, Node* dst, Node* size, bool is_array) {
1872   return _barrier_set->clone(this, src, dst, size, is_array);
1873 }
1874 
1875 //-------------------------array_element_address-------------------------
1876 Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt,
1877                                       const TypeInt* sizetype, Node* ctrl) {
1878   const TypeAryPtr* arytype = _gvn.type(ary)->is_aryptr();
1879   uint shift;
1880   uint header;
1881   if (arytype->is_flat() && arytype->klass_is_exact()) {
1882     // We can only determine the flat array layout statically if the klass is exact. Otherwise, we could have different
1883     // value classes at runtime with a potentially different layout. The caller needs to fall back to call
1884     // load/store_unknown_inline_Type() at runtime. We could return a sentinel node for the non-exact case but that
1885     // might mess with other GVN transformations in between. Thus, we just continue in the else branch normally, even
1886     // though we don't need the address node in this case and throw it away again.
1887     shift = arytype->flat_log_elem_size();
1888     header = arrayOopDesc::base_offset_in_bytes(T_FLAT_ELEMENT);
1889   } else {
1890     shift = exact_log2(type2aelembytes(elembt));
1891     header = arrayOopDesc::base_offset_in_bytes(elembt);
1892   }
1893 
1894   // short-circuit a common case (saves lots of confusing waste motion)
1895   jint idx_con = find_int_con(idx, -1);
1896   if (idx_con >= 0) {
1897     intptr_t offset = header + ((intptr_t)idx_con << shift);
1898     return basic_plus_adr(ary, offset);
1899   }
1900 
1901   // must be correct type for alignment purposes
1902   Node* base  = basic_plus_adr(ary, header);
1903   idx = Compile::conv_I2X_index(&_gvn, idx, sizetype, ctrl);
1904   Node* scale = _gvn.transform( new LShiftXNode(idx, intcon(shift)) );
1905   return basic_plus_adr(ary, base, scale);
1906 }
1907 
1908 Node* GraphKit::cast_to_flat_array(Node* array, ciInlineKlass* elem_vk) {
1909   assert(elem_vk->maybe_flat_in_array(), "no flat array for %s", elem_vk->name()->as_utf8());
1910   if (!elem_vk->has_null_free_atomic_layout() && !elem_vk->has_nullable_atomic_layout()) {
1911     return cast_to_flat_array_exact(array, elem_vk, true, false);
1912   } else if (!elem_vk->has_nullable_atomic_layout() && !elem_vk->has_null_free_non_atomic_layout()) {
1913     return cast_to_flat_array_exact(array, elem_vk, true, true);
1914   } else if (!elem_vk->has_null_free_atomic_layout() && !elem_vk->has_null_free_non_atomic_layout()) {
1915     return cast_to_flat_array_exact(array, elem_vk, false, true);
1916   }
1917 
1918   bool is_null_free = false;
1919   if (!elem_vk->has_nullable_atomic_layout()) {
1920     // Element does not have a nullable flat layout, cannot be nullable
1921     is_null_free = true;
1922   }
1923 
1924   ciArrayKlass* array_klass = ciObjArrayKlass::make(elem_vk, false);
1925   const TypeAryPtr* arytype = TypeOopPtr::make_from_klass(array_klass)->isa_aryptr();
1926   arytype = arytype->cast_to_flat(true)->cast_to_null_free(is_null_free);
1927   return _gvn.transform(new CheckCastPPNode(control(), array, arytype, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
1928 }
1929 
1930 Node* GraphKit::cast_to_flat_array_exact(Node* array, ciInlineKlass* elem_vk, bool is_null_free, bool is_atomic) {
1931   assert(is_null_free || is_atomic, "nullable arrays must be atomic");
1932   ciArrayKlass* array_klass = ciObjArrayKlass::make(elem_vk, true, is_null_free, is_atomic);
1933   const TypeAryPtr* arytype = TypeOopPtr::make_from_klass(array_klass)->isa_aryptr();
1934   assert(arytype->klass_is_exact(), "inconsistency");
1935   assert(arytype->is_flat(), "inconsistency");
1936   assert(arytype->is_null_free() == is_null_free, "inconsistency");
1937   assert(arytype->is_not_null_free() == !is_null_free, "inconsistency");
1938   return _gvn.transform(new CheckCastPPNode(control(), array, arytype, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
1939 }
1940 
1941 //-------------------------load_array_element-------------------------
1942 Node* GraphKit::load_array_element(Node* ary, Node* idx, const TypeAryPtr* arytype, bool set_ctrl) {
1943   const Type* elemtype = arytype->elem();
1944   BasicType elembt = elemtype->array_element_basic_type();
1945   Node* adr = array_element_address(ary, idx, elembt, arytype->size());
1946   if (elembt == T_NARROWOOP) {
1947     elembt = T_OBJECT; // To satisfy switch in LoadNode::make()
1948   }
1949   Node* ld = access_load_at(ary, adr, arytype, elemtype, elembt,
1950                             IN_HEAP | IS_ARRAY | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0));
1951   return ld;
1952 }
1953 
1954 //-------------------------set_arguments_for_java_call-------------------------
1955 // Arguments (pre-popped from the stack) are taken from the JVMS.
1956 void GraphKit::set_arguments_for_java_call(CallJavaNode* call, bool is_late_inline) {
1957   PreserveReexecuteState preexecs(this);
1958   if (Arguments::is_valhalla_enabled()) {
1959     // Make sure the call is "re-executed", if buffering of inline type arguments triggers deoptimization.
1960     // At this point, the call hasn't been executed yet, so we will only ever execute the call once.
1961     jvms()->set_should_reexecute(true);
1962     int arg_size = method()->get_declared_signature_at_bci(bci())->arg_size_for_bc(java_bc());
1963     inc_sp(arg_size);
1964   }
1965   // Add the call arguments
1966   const TypeTuple* domain = call->tf()->domain_sig();
1967   uint nargs = domain->cnt();
1968   int arg_num = 0;
1969   for (uint i = TypeFunc::Parms, idx = TypeFunc::Parms; i < nargs; i++) {
1970     uint arg_idx = i - TypeFunc::Parms;
1971     Node* arg = argument(arg_idx);
1972     const Type* t = domain->field_at(i);
1973     // TODO 8284443 A static call to a mismatched method should still be scalarized
1974     if (t->is_inlinetypeptr() && !call->method()->mismatch() && call->method()->is_scalarized_arg(arg_num)) {
1975       // We don't pass inline type arguments by reference but instead pass each field of the inline type
1976       if (!arg->is_InlineType()) {
1977         // There are 2 cases in which the argument has not been scalarized
1978         if (_gvn.type(arg)->is_zero_type()) {
1979           arg = InlineTypeNode::make_null(_gvn, t->inline_klass());
1980         } else {
1981           // During parsing, a method is called with an abstract (or j.l.Object) receiver, the
1982           // receiver is a non-scalarized oop. Later on, IGVN reveals that the receiver must be a
1983           // value object. The method is devirtualized, and replaced with a direct call with a
1984           // scalarized receiver instead.
1985           assert(arg_idx == 0 && !call->method()->is_static(), "must be the receiver");
1986           assert(C->inlining_incrementally() || C->strength_reduction(), "must be during devirtualization of calls");
1987           assert(!is_Parse(), "must be during devirtualization of calls");
1988           arg = InlineTypeNode::make_from_oop(this, arg, t->inline_klass());
1989         }
1990       }
1991       InlineTypeNode* vt = arg->as_InlineType();
1992       vt->pass_fields(this, call, idx, true, !t->maybe_null());
1993       // If an inline type argument is passed as fields, attach the Method* to the call site
1994       // to be able to access the extended signature later via attached_method_before_pc().
1995       // For example, see CompiledMethod::preserve_callee_argument_oops().
1996       call->set_override_symbolic_info(true);
1997       // Register an calling convention dependency on the callee method to make sure that this method is deoptimized and
1998       // re-compiled with a non-scalarized calling convention if the callee method is later marked as mismatched.
1999       C->dependencies()->assert_mismatch_calling_convention(call->method());
2000       arg_num++;
2001       continue;
2002     } else if (arg->is_InlineType()) {
2003       // Pass inline type argument via oop to callee
2004       arg = arg->as_InlineType()->buffer(this, true);
2005     }
2006     if (t != Type::HALF) {
2007       arg_num++;
2008     }
2009     call->init_req(idx++, arg);
2010   }
2011 }
2012 
2013 //---------------------------set_edges_for_java_call---------------------------
2014 // Connect a newly created call into the current JVMS.
2015 // A return value node (if any) is returned from set_edges_for_java_call.
2016 void GraphKit::set_edges_for_java_call(CallJavaNode* call, bool must_throw, bool separate_io_proj) {
2017 
2018   // Add the predefined inputs:
2019   call->init_req( TypeFunc::Control, control() );
2020   call->init_req( TypeFunc::I_O    , i_o() );
2021   call->init_req( TypeFunc::Memory , reset_memory() );
2022   call->init_req( TypeFunc::FramePtr, frameptr() );
2023   call->init_req( TypeFunc::ReturnAdr, top() );
2024 
2025   add_safepoint_edges(call, must_throw);
2026 
2027   Node* xcall = _gvn.transform(call);
2028 
2029   if (xcall == top()) {
2030     set_control(top());
2031     return;
2032   }
2033   assert(xcall == call, "call identity is stable");
2034 
2035   // Re-use the current map to produce the result.
2036 
2037   set_control(_gvn.transform(new ProjNode(call, TypeFunc::Control)));
2038   set_i_o(    _gvn.transform(new ProjNode(call, TypeFunc::I_O    , separate_io_proj)));
2039   set_all_memory_call(xcall, separate_io_proj);
2040 
2041   //return xcall;   // no need, caller already has it
2042 }
2043 
2044 Node* GraphKit::set_results_for_java_call(CallJavaNode* call, bool separate_io_proj, bool deoptimize) {
2045   if (stopped())  return top();  // maybe the call folded up?
2046 
2047   // Note:  Since any out-of-line call can produce an exception,
2048   // we always insert an I_O projection from the call into the result.
2049 
2050   make_slow_call_ex(call, env()->Throwable_klass(), separate_io_proj, deoptimize);
2051 
2052   if (separate_io_proj) {
2053     // The caller requested separate projections be used by the fall
2054     // through and exceptional paths, so replace the projections for
2055     // the fall through path.
2056     set_i_o(_gvn.transform( new ProjNode(call, TypeFunc::I_O) ));
2057     set_all_memory(_gvn.transform( new ProjNode(call, TypeFunc::Memory) ));
2058   }
2059 
2060   // Capture the return value, if any.
2061   Node* ret;
2062   if (call->method() == nullptr || call->method()->return_type()->basic_type() == T_VOID) {
2063     ret = top();
2064   } else if (call->tf()->returns_inline_type_as_fields()) {
2065     // Return of multiple values (inline type fields): we create a
2066     // InlineType node, each field is a projection from the call.
2067     ciInlineKlass* vk = call->method()->return_type()->as_inline_klass();
2068     uint base_input = TypeFunc::Parms;
2069     ret = InlineTypeNode::make_from_multi(this, call, vk, base_input, false, false);
2070   } else {
2071     ret = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
2072     ciType* t = call->method()->return_type();
2073     if (!t->is_loaded() && InlineTypeReturnedAsFields) {
2074       // The return type is unloaded but the callee might later be C2 compiled and then return
2075       // in scalarized form when the return type is loaded. Handle this similar to what we do in
2076       // PhaseMacroExpand::expand_mh_intrinsic_return by calling into the runtime to buffer.
2077       // It's a bit unfortunate because we will deopt anyway but the interpreter needs an oop.
2078       IdealKit ideal(this);
2079       IdealVariable res(ideal);
2080       ideal.declarations_done();
2081       // Change return type of call to scalarized return
2082       const TypeFunc* tf = call->_tf;
2083       const TypeTuple* domain = OptoRuntime::store_inline_type_fields_Type()->domain_cc();
2084       const TypeFunc* new_tf = TypeFunc::make(tf->domain_sig(), tf->domain_cc(), tf->range_sig(), domain);
2085       call->_tf = new_tf;
2086       _gvn.set_type(call, call->Value(&_gvn));
2087       _gvn.set_type(ret, ret->Value(&_gvn));
2088       // Don't add store to buffer call if we are strength reducing
2089       if (!C->strength_reduction()) {
2090         ideal.if_then(ret, BoolTest::eq, ideal.makecon(TypePtr::NULL_PTR)); {
2091           // Return value is null
2092           ideal.set(res, makecon(TypePtr::NULL_PTR));
2093         } ideal.else_(); {
2094           // Return value is non-null
2095           sync_kit(ideal);
2096 
2097           Node* store_to_buf_call = make_runtime_call(RC_NO_LEAF | RC_NO_IO,
2098                                                       OptoRuntime::store_inline_type_fields_Type(),
2099                                                       StubRoutines::store_inline_type_fields_to_buf(),
2100                                                       nullptr, TypePtr::BOTTOM, ret);
2101 
2102           // We don't know how many values are returned. This assumes the
2103           // worst case, that all available registers are used.
2104           for (uint i = TypeFunc::Parms+1; i < domain->cnt(); i++) {
2105             if (domain->field_at(i) == Type::HALF) {
2106               store_to_buf_call->init_req(i, top());
2107               continue;
2108             }
2109             Node* proj =_gvn.transform(new ProjNode(call, i));
2110             store_to_buf_call->init_req(i, proj);
2111           }
2112           make_slow_call_ex(store_to_buf_call, env()->Throwable_klass(), false);
2113 
2114           Node* buf = _gvn.transform(new ProjNode(store_to_buf_call, TypeFunc::Parms));
2115           const Type* buf_type = TypeOopPtr::make_from_klass(t->as_klass())->join_speculative(TypePtr::NOTNULL);
2116           buf = _gvn.transform(new CheckCastPPNode(control(), buf, buf_type));
2117 
2118           ideal.set(res, buf);
2119           ideal.sync_kit(this);
2120         } ideal.end_if();
2121       } else {
2122         for (uint i = TypeFunc::Parms+1; i < domain->cnt(); i++) {
2123           Node* proj =_gvn.transform(new ProjNode(call, i));
2124         }
2125         ideal.set(res, ret);
2126       }
2127       sync_kit(ideal);
2128       ret = _gvn.transform(ideal.value(res));
2129     }
2130   }
2131 
2132   return ret;
2133 }
2134 
2135 //--------------------set_predefined_input_for_runtime_call--------------------
2136 // Reading and setting the memory state is way conservative here.
2137 // The real problem is that I am not doing real Type analysis on memory,
2138 // so I cannot distinguish card mark stores from other stores.  Across a GC
2139 // point the Store Barrier and the card mark memory has to agree.  I cannot
2140 // have a card mark store and its barrier split across the GC point from
2141 // either above or below.  Here I get that to happen by reading ALL of memory.
2142 // A better answer would be to separate out card marks from other memory.
2143 // For now, return the input memory state, so that it can be reused
2144 // after the call, if this call has restricted memory effects.
2145 Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem) {
2146   // Set fixed predefined input arguments
2147   call->init_req(TypeFunc::Control, control());
2148   call->init_req(TypeFunc::I_O, top()); // does no i/o
2149   call->init_req(TypeFunc::ReturnAdr, top());
2150   if (call->is_CallLeafPure()) {
2151     call->init_req(TypeFunc::Memory, top());
2152     call->init_req(TypeFunc::FramePtr, top());
2153     return nullptr;
2154   } else {
2155     Node* memory = reset_memory();
2156     Node* m = narrow_mem == nullptr ? memory : narrow_mem;
2157     call->init_req(TypeFunc::Memory, m); // may gc ptrs
2158     call->init_req(TypeFunc::FramePtr, frameptr());
2159     return memory;
2160   }
2161 }
2162 
2163 //-------------------set_predefined_output_for_runtime_call--------------------
2164 // Set control and memory (not i_o) from the call.
2165 // If keep_mem is not null, use it for the output state,
2166 // except for the RawPtr output of the call, if hook_mem is TypeRawPtr::BOTTOM.
2167 // If hook_mem is null, this call produces no memory effects at all.
2168 // If hook_mem is a Java-visible memory slice (such as arraycopy operands),
2169 // then only that memory slice is taken from the call.
2170 // In the last case, we must put an appropriate memory barrier before
2171 // the call, so as to create the correct anti-dependencies on loads
2172 // preceding the call.
2173 void GraphKit::set_predefined_output_for_runtime_call(Node* call,
2174                                                       Node* keep_mem,
2175                                                       const TypePtr* hook_mem) {
2176   // no i/o
2177   set_control(_gvn.transform( new ProjNode(call,TypeFunc::Control) ));
2178   if (call->is_CallLeafPure()) {
2179     // Pure function have only control (for now) and data output, in particular
2180     // they don't touch the memory, so we don't want a memory proj that is set after.
2181     return;
2182   }
2183   if (keep_mem) {
2184     // First clone the existing memory state
2185     set_all_memory(keep_mem);
2186     if (hook_mem != nullptr) {
2187       // Make memory for the call
2188       Node* mem = _gvn.transform( new ProjNode(call, TypeFunc::Memory) );
2189       // Set the RawPtr memory state only.  This covers all the heap top/GC stuff
2190       // We also use hook_mem to extract specific effects from arraycopy stubs.
2191       set_memory(mem, hook_mem);
2192     }
2193     // ...else the call has NO memory effects.
2194 
2195     // Make sure the call advertises its memory effects precisely.
2196     // This lets us build accurate anti-dependences in gcm.cpp.
2197     assert(C->alias_type(call->adr_type()) == C->alias_type(hook_mem),
2198            "call node must be constructed correctly");
2199   } else {
2200     assert(hook_mem == nullptr, "");
2201     // This is not a "slow path" call; all memory comes from the call.
2202     set_all_memory_call(call);
2203   }
2204 }
2205 
2206 // Keep track of MergeMems feeding into other MergeMems
2207 static void add_mergemem_users_to_worklist(Unique_Node_List& wl, Node* mem) {
2208   if (!mem->is_MergeMem()) {
2209     return;
2210   }
2211   for (SimpleDUIterator i(mem); i.has_next(); i.next()) {
2212     Node* use = i.get();
2213     if (use->is_MergeMem()) {
2214       wl.push(use);
2215     }
2216   }
2217 }
2218 
2219 // Replace the call with the current state of the kit.
2220 void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes, bool do_asserts) {
2221   JVMState* ejvms = nullptr;
2222   if (has_exceptions()) {
2223     ejvms = transfer_exceptions_into_jvms();
2224   }
2225 
2226   ReplacedNodes replaced_nodes = map()->replaced_nodes();
2227   ReplacedNodes replaced_nodes_exception;
2228   Node* ex_ctl = top();
2229 
2230   SafePointNode* final_state = stop();
2231 
2232   // Find all the needed outputs of this call
2233   CallProjections* callprojs = call->extract_projections(true, do_asserts);
2234 
2235   Unique_Node_List wl;
2236   Node* init_mem = call->in(TypeFunc::Memory);
2237   Node* final_mem = final_state->in(TypeFunc::Memory);
2238   Node* final_ctl = final_state->in(TypeFunc::Control);
2239   Node* final_io = final_state->in(TypeFunc::I_O);
2240 
2241   // Replace all the old call edges with the edges from the inlining result
2242   if (callprojs->fallthrough_catchproj != nullptr) {
2243     C->gvn_replace_by(callprojs->fallthrough_catchproj, final_ctl);
2244   }
2245   if (callprojs->fallthrough_memproj != nullptr) {
2246     if (final_mem->is_MergeMem()) {
2247       // Parser's exits MergeMem was not transformed but may be optimized
2248       final_mem = _gvn.transform(final_mem);
2249     }
2250     C->gvn_replace_by(callprojs->fallthrough_memproj,   final_mem);
2251     add_mergemem_users_to_worklist(wl, final_mem);
2252   }
2253   if (callprojs->fallthrough_ioproj != nullptr) {
2254     C->gvn_replace_by(callprojs->fallthrough_ioproj,    final_io);
2255   }
2256 
2257   // Replace the result with the new result if it exists and is used
2258   if (callprojs->resproj[0] != nullptr && result != nullptr) {
2259     // If the inlined code is dead, the result projections for an inline type returned as
2260     // fields have not been replaced. They will go away once the call is replaced by TOP below.
2261     assert(callprojs->nb_resproj == 1 || (call->tf()->returns_inline_type_as_fields() && stopped()) ||
2262            (C->strength_reduction() && InlineTypeReturnedAsFields && !call->as_CallJava()->method()->return_type()->is_loaded()),
2263            "unexpected number of results");
2264     // If we are doing strength reduction and the return type is not loaded we
2265     // need to rewire all projections since store_inline_type_fields_to_buf is already present
2266     if (C->strength_reduction() && InlineTypeReturnedAsFields && !call->as_CallJava()->method()->return_type()->is_loaded()) {
2267       const TypeTuple* domain = OptoRuntime::store_inline_type_fields_Type()->domain_cc();
2268       for (uint i = TypeFunc::Parms; i < domain->cnt(); i++) {
2269         C->gvn_replace_by(callprojs->resproj[0], final_state->in(i));
2270       }
2271     } else {
2272       C->gvn_replace_by(callprojs->resproj[0], result);
2273     }
2274   }
2275 
2276   if (ejvms == nullptr) {
2277     // No exception edges to simply kill off those paths
2278     if (callprojs->catchall_catchproj != nullptr) {
2279       C->gvn_replace_by(callprojs->catchall_catchproj, C->top());
2280     }
2281     if (callprojs->catchall_memproj != nullptr) {
2282       C->gvn_replace_by(callprojs->catchall_memproj,   C->top());
2283     }
2284     if (callprojs->catchall_ioproj != nullptr) {
2285       C->gvn_replace_by(callprojs->catchall_ioproj,    C->top());
2286     }
2287     // Replace the old exception object with top
2288     if (callprojs->exobj != nullptr) {
2289       C->gvn_replace_by(callprojs->exobj, C->top());
2290     }
2291   } else {
2292     GraphKit ekit(ejvms);
2293 
2294     // Load my combined exception state into the kit, with all phis transformed:
2295     SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states();
2296     replaced_nodes_exception = ex_map->replaced_nodes();
2297 
2298     Node* ex_oop = ekit.use_exception_state(ex_map);
2299 
2300     if (callprojs->catchall_catchproj != nullptr) {
2301       C->gvn_replace_by(callprojs->catchall_catchproj, ekit.control());
2302       ex_ctl = ekit.control();
2303     }
2304     if (callprojs->catchall_memproj != nullptr) {
2305       Node* ex_mem = ekit.reset_memory();
2306       C->gvn_replace_by(callprojs->catchall_memproj,   ex_mem);
2307       add_mergemem_users_to_worklist(wl, ex_mem);
2308     }
2309     if (callprojs->catchall_ioproj != nullptr) {
2310       C->gvn_replace_by(callprojs->catchall_ioproj,    ekit.i_o());
2311     }
2312 
2313     // Replace the old exception object with the newly created one
2314     if (callprojs->exobj != nullptr) {
2315       C->gvn_replace_by(callprojs->exobj, ex_oop);
2316     }
2317   }
2318 
2319   // Disconnect the call from the graph
2320   call->disconnect_inputs(C);
2321   C->gvn_replace_by(call, C->top());
2322 
2323   // Clean up any MergeMems that feed other MergeMems since the
2324   // optimizer doesn't like that.
2325   while (wl.size() > 0) {
2326     _gvn.transform(wl.pop());
2327   }
2328 
2329   if (callprojs->fallthrough_catchproj != nullptr && !final_ctl->is_top() && do_replaced_nodes) {
2330     replaced_nodes.apply(C, final_ctl);
2331   }
2332   if (!ex_ctl->is_top() && do_replaced_nodes) {
2333     replaced_nodes_exception.apply(C, ex_ctl);
2334   }
2335 }
2336 
2337 
2338 //------------------------------increment_counter------------------------------
2339 // for statistics: increment a VM counter by 1
2340 
2341 void GraphKit::increment_counter(address counter_addr) {
2342   Node* adr1 = makecon(TypeRawPtr::make(counter_addr));
2343   increment_counter(adr1);
2344 }
2345 
2346 void GraphKit::increment_counter(Node* counter_addr) {
2347   Node* ctrl = control();
2348   Node* cnt  = make_load(ctrl, counter_addr, TypeLong::LONG, T_LONG, MemNode::unordered);
2349   Node* incr = _gvn.transform(new AddLNode(cnt, _gvn.longcon(1)));
2350   store_to_memory(ctrl, counter_addr, incr, T_LONG, MemNode::unordered);
2351 }
2352 
2353 void GraphKit::halt(Node* ctrl, Node* frameptr, const char* reason, bool generate_code_in_product) {
2354   Node* halt = new HaltNode(ctrl, frameptr, reason
2355                             PRODUCT_ONLY(COMMA generate_code_in_product));
2356   halt = _gvn.transform(halt);
2357   root()->add_req(halt);
2358   if (_gvn.is_IterGVN() != nullptr) {
2359     record_for_igvn(root());
2360   }
2361 }
2362 
2363 //------------------------------uncommon_trap----------------------------------
2364 // Bail out to the interpreter in mid-method.  Implemented by calling the
2365 // uncommon_trap blob.  This helper function inserts a runtime call with the
2366 // right debug info.
2367 Node* GraphKit::uncommon_trap(int trap_request,
2368                              ciKlass* klass, const char* comment,
2369                              bool must_throw,
2370                              bool keep_exact_action) {
2371   if (failing_internal()) {
2372     stop();
2373   }
2374   if (stopped())  return nullptr; // trap reachable?
2375 
2376   // Note:  If ProfileTraps is true, and if a deopt. actually
2377   // occurs here, the runtime will make sure an MDO exists.  There is
2378   // no need to call method()->ensure_method_data() at this point.
2379 
2380   // Set the stack pointer to the right value for reexecution:
2381   set_sp(reexecute_sp());
2382 
2383 #ifdef ASSERT
2384   if (!must_throw) {
2385     // Make sure the stack has at least enough depth to execute
2386     // the current bytecode.
2387     int inputs, ignored_depth;
2388     if (compute_stack_effects(inputs, ignored_depth)) {
2389       assert(sp() >= inputs, "must have enough JVMS stack to execute %s: sp=%d, inputs=%d",
2390              Bytecodes::name(java_bc()), sp(), inputs);
2391     }
2392   }
2393 #endif
2394 
2395   Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);
2396   Deoptimization::DeoptAction action = Deoptimization::trap_request_action(trap_request);
2397 
2398   switch (action) {
2399   case Deoptimization::Action_maybe_recompile:
2400   case Deoptimization::Action_reinterpret:
2401     // Temporary fix for 6529811 to allow virtual calls to be sure they
2402     // get the chance to go from mono->bi->mega
2403     if (!keep_exact_action &&
2404         Deoptimization::trap_request_index(trap_request) < 0 &&
2405         too_many_recompiles(reason)) {
2406       // This BCI is causing too many recompilations.
2407       if (C->log() != nullptr) {
2408         C->log()->elem("observe that='trap_action_change' reason='%s' from='%s' to='none'",
2409                 Deoptimization::trap_reason_name(reason),
2410                 Deoptimization::trap_action_name(action));
2411       }
2412       action = Deoptimization::Action_none;
2413       trap_request = Deoptimization::make_trap_request(reason, action);
2414     } else {
2415       C->set_trap_can_recompile(true);
2416     }
2417     break;
2418   case Deoptimization::Action_make_not_entrant:
2419     C->set_trap_can_recompile(true);
2420     break;
2421   case Deoptimization::Action_none:
2422   case Deoptimization::Action_make_not_compilable:
2423     break;
2424   default:
2425 #ifdef ASSERT
2426     fatal("unknown action %d: %s", action, Deoptimization::trap_action_name(action));
2427 #endif
2428     break;
2429   }
2430 
2431   if (TraceOptoParse) {
2432     char buf[100];
2433     tty->print_cr("Uncommon trap %s at bci:%d",
2434                   Deoptimization::format_trap_request(buf, sizeof(buf),
2435                                                       trap_request), bci());
2436   }
2437 
2438   CompileLog* log = C->log();
2439   if (log != nullptr) {
2440     int kid = (klass == nullptr)? -1: log->identify(klass);
2441     log->begin_elem("uncommon_trap bci='%d'", bci());
2442     char buf[100];
2443     log->print(" %s", Deoptimization::format_trap_request(buf, sizeof(buf),
2444                                                           trap_request));
2445     if (kid >= 0)         log->print(" klass='%d'", kid);
2446     if (comment != nullptr)  log->print(" comment='%s'", comment);
2447     log->end_elem();
2448   }
2449 
2450   // Make sure any guarding test views this path as very unlikely
2451   Node *i0 = control()->in(0);
2452   if (i0 != nullptr && i0->is_If()) {        // Found a guarding if test?
2453     IfNode *iff = i0->as_If();
2454     float f = iff->_prob;   // Get prob
2455     if (control()->Opcode() == Op_IfTrue) {
2456       if (f > PROB_UNLIKELY_MAG(4))
2457         iff->_prob = PROB_MIN;
2458     } else {
2459       if (f < PROB_LIKELY_MAG(4))
2460         iff->_prob = PROB_MAX;
2461     }
2462   }
2463 
2464   // Clear out dead values from the debug info.
2465   kill_dead_locals();
2466 
2467   // Now insert the uncommon trap subroutine call
2468   address call_addr = OptoRuntime::uncommon_trap_blob()->entry_point();
2469   const TypePtr* no_memory_effects = nullptr;
2470   // Pass the index of the class to be loaded
2471   Node* call = make_runtime_call(RC_NO_LEAF | RC_UNCOMMON |
2472                                  (must_throw ? RC_MUST_THROW : 0),
2473                                  OptoRuntime::uncommon_trap_Type(),
2474                                  call_addr, "uncommon_trap", no_memory_effects,
2475                                  intcon(trap_request));
2476   assert(call->as_CallStaticJava()->uncommon_trap_request() == trap_request,
2477          "must extract request correctly from the graph");
2478   assert(trap_request != 0, "zero value reserved by uncommon_trap_request");
2479 
2480   call->set_req(TypeFunc::ReturnAdr, returnadr());
2481   // The debug info is the only real input to this call.
2482 
2483   // Halt-and-catch fire here.  The above call should never return!
2484   // We only emit code for the HaltNode in debug, which is enough for
2485   // verifying correctness. In product, we don't want to emit it so
2486   // that we can save on code space. HaltNode often get folded because
2487   // the compiler can prove that the unreachable path is dead. But we
2488   // cannot generally expect that for uncommon traps, which are often
2489   // reachable and occasionally taken.
2490   halt(control(), frameptr(),
2491        "uncommon trap returned which should never happen",
2492        false /* don't emit code in product */);
2493   stop_and_kill_map();
2494   return call;
2495 }
2496 
2497 
2498 //--------------------------just_allocated_object------------------------------
2499 // Report the object that was just allocated.
2500 // It must be the case that there are no intervening safepoints.
2501 // We use this to determine if an object is so "fresh" that
2502 // it does not require card marks.
2503 Node* GraphKit::just_allocated_object(Node* current_control) {
2504   Node* ctrl = current_control;
2505   // Object::<init> is invoked after allocation, most of invoke nodes
2506   // will be reduced, but a region node is kept in parse time, we check
2507   // the pattern and skip the region node if it degraded to a copy.
2508   if (ctrl != nullptr && ctrl->is_Region() && ctrl->req() == 2 &&
2509       ctrl->as_Region()->is_copy()) {
2510     ctrl = ctrl->as_Region()->is_copy();
2511   }
2512   if (C->recent_alloc_ctl() == ctrl) {
2513    return C->recent_alloc_obj();
2514   }
2515   return nullptr;
2516 }
2517 
2518 
2519 /**
2520  * Record profiling data exact_kls for Node n with the type system so
2521  * that it can propagate it (speculation)
2522  *
2523  * @param n          node that the type applies to
2524  * @param exact_kls  type from profiling
2525  * @param maybe_null did profiling see null?
2526  *
2527  * @return           node with improved type
2528  */
2529 Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls, ProfilePtrKind ptr_kind) {
2530   const Type* current_type = _gvn.type(n);
2531   assert(UseTypeSpeculation, "type speculation must be on");
2532 
2533   const TypePtr* speculative = current_type->speculative();
2534 
2535   // Should the klass from the profile be recorded in the speculative type?
2536   if (current_type->would_improve_type(exact_kls, jvms()->depth())) {
2537     const TypeKlassPtr* tklass = TypeKlassPtr::make(exact_kls, Type::trust_interfaces);
2538     const TypeOopPtr* xtype = tklass->as_instance_type();
2539     assert(xtype->klass_is_exact(), "Should be exact");
2540     // Any reason to believe n is not null (from this profiling or a previous one)?
2541     assert(ptr_kind != ProfileAlwaysNull, "impossible here");
2542     const TypePtr* ptr = (ptr_kind != ProfileNeverNull && current_type->speculative_maybe_null()) ? TypePtr::BOTTOM : TypePtr::NOTNULL;
2543     // record the new speculative type's depth
2544     speculative = xtype->cast_to_ptr_type(ptr->ptr())->is_ptr();
2545     speculative = speculative->with_inline_depth(jvms()->depth());
2546   } else if (current_type->would_improve_ptr(ptr_kind)) {
2547     // Profiling report that null was never seen so we can change the
2548     // speculative type to non null ptr.
2549     if (ptr_kind == ProfileAlwaysNull) {
2550       speculative = TypePtr::NULL_PTR;
2551     } else {
2552       assert(ptr_kind == ProfileNeverNull, "nothing else is an improvement");
2553       const TypePtr* ptr = TypePtr::NOTNULL;
2554       if (speculative != nullptr) {
2555         speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr();
2556       } else {
2557         speculative = ptr;
2558       }
2559     }
2560   }
2561 
2562   if (speculative != current_type->speculative()) {
2563     // Build a type with a speculative type (what we think we know
2564     // about the type but will need a guard when we use it)
2565     const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::Offset::bottom, TypeOopPtr::InstanceBot, speculative);
2566     // We're changing the type, we need a new CheckCast node to carry
2567     // the new type. The new type depends on the control: what
2568     // profiling tells us is only valid from here as far as we can
2569     // tell.
2570     Node* cast = new CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type));
2571     cast = _gvn.transform(cast);
2572     replace_in_map(n, cast);
2573     n = cast;
2574   }
2575 
2576   return n;
2577 }
2578 
2579 /**
2580  * Record profiling data from receiver profiling at an invoke with the
2581  * type system so that it can propagate it (speculation)
2582  *
2583  * @param n  receiver node
2584  *
2585  * @return   node with improved type
2586  */
2587 Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) {
2588   if (!UseTypeSpeculation) {
2589     return n;
2590   }
2591   ciKlass* exact_kls = profile_has_unique_klass();
2592   ProfilePtrKind ptr_kind = ProfileMaybeNull;
2593   if ((java_bc() == Bytecodes::_checkcast ||
2594        java_bc() == Bytecodes::_instanceof ||
2595        java_bc() == Bytecodes::_aastore) &&
2596       method()->method_data()->is_mature()) {
2597     ciProfileData* data = method()->method_data()->bci_to_data(bci());
2598     if (data != nullptr) {
2599       if (java_bc() == Bytecodes::_aastore) {
2600         ciKlass* array_type = nullptr;
2601         ciKlass* element_type = nullptr;
2602         ProfilePtrKind element_ptr = ProfileMaybeNull;
2603         bool flat_array = true;
2604         bool null_free_array = true;
2605         method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array);
2606         exact_kls = element_type;
2607         ptr_kind = element_ptr;
2608       } else {
2609         if (!data->as_BitData()->null_seen()) {
2610           ptr_kind = ProfileNeverNull;
2611         } else {
2612           if (TypeProfileCasts) {
2613             assert(data->is_ReceiverTypeData(), "bad profile data type");
2614             ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();
2615             uint i = 0;
2616             for (; i < call->row_limit(); i++) {
2617               ciKlass* receiver = call->receiver(i);
2618               if (receiver != nullptr) {
2619                 break;
2620               }
2621             }
2622             ptr_kind = (i == call->row_limit()) ? ProfileAlwaysNull : ProfileMaybeNull;
2623           }
2624         }
2625       }
2626     }
2627   }
2628   return record_profile_for_speculation(n, exact_kls, ptr_kind);
2629 }
2630 
2631 /**
2632  * Record profiling data from argument profiling at an invoke with the
2633  * type system so that it can propagate it (speculation)
2634  *
2635  * @param dest_method  target method for the call
2636  * @param bc           what invoke bytecode is this?
2637  */
2638 void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) {
2639   if (!UseTypeSpeculation) {
2640     return;
2641   }
2642   const TypeFunc* tf    = TypeFunc::make(dest_method);
2643   int             nargs = tf->domain_sig()->cnt() - TypeFunc::Parms;
2644   int skip = Bytecodes::has_receiver(bc) ? 1 : 0;
2645   for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) {
2646     const Type *targ = tf->domain_sig()->field_at(j + TypeFunc::Parms);
2647     if (is_reference_type(targ->basic_type())) {
2648       ProfilePtrKind ptr_kind = ProfileMaybeNull;
2649       ciKlass* better_type = nullptr;
2650       if (method()->argument_profiled_type(bci(), i, better_type, ptr_kind)) {
2651         record_profile_for_speculation(argument(j), better_type, ptr_kind);
2652       }
2653       i++;
2654     }
2655   }
2656 }
2657 
2658 /**
2659  * Record profiling data from parameter profiling at an invoke with
2660  * the type system so that it can propagate it (speculation)
2661  */
2662 void GraphKit::record_profiled_parameters_for_speculation() {
2663   if (!UseTypeSpeculation) {
2664     return;
2665   }
2666   for (int i = 0, j = 0; i < method()->arg_size() ; i++) {
2667     if (_gvn.type(local(i))->isa_oopptr()) {
2668       ProfilePtrKind ptr_kind = ProfileMaybeNull;
2669       ciKlass* better_type = nullptr;
2670       if (method()->parameter_profiled_type(j, better_type, ptr_kind)) {
2671         record_profile_for_speculation(local(i), better_type, ptr_kind);
2672       }
2673       j++;
2674     }
2675   }
2676 }
2677 
2678 /**
2679  * Record profiling data from return value profiling at an invoke with
2680  * the type system so that it can propagate it (speculation)
2681  */
2682 void GraphKit::record_profiled_return_for_speculation() {
2683   if (!UseTypeSpeculation) {
2684     return;
2685   }
2686   ProfilePtrKind ptr_kind = ProfileMaybeNull;
2687   ciKlass* better_type = nullptr;
2688   if (method()->return_profiled_type(bci(), better_type, ptr_kind)) {
2689     // If profiling reports a single type for the return value,
2690     // feed it to the type system so it can propagate it as a
2691     // speculative type
2692     record_profile_for_speculation(stack(sp()-1), better_type, ptr_kind);
2693   }
2694 }
2695 
2696 
2697 //=============================================================================
2698 // Generate a fast path/slow path idiom.  Graph looks like:
2699 // [foo] indicates that 'foo' is a parameter
2700 //
2701 //              [in]     null
2702 //                 \    /
2703 //                  CmpP
2704 //                  Bool ne
2705 //                   If
2706 //                  /  \
2707 //              True    False-<2>
2708 //              / |
2709 //             /  cast_not_null
2710 //           Load  |    |   ^
2711 //        [fast_test]   |   |
2712 // gvn to   opt_test    |   |
2713 //          /    \      |  <1>
2714 //      True     False  |
2715 //        |         \\  |
2716 //   [slow_call]     \[fast_result]
2717 //    Ctl   Val       \      \
2718 //     |               \      \
2719 //    Catch       <1>   \      \
2720 //   /    \        ^     \      \
2721 //  Ex    No_Ex    |      \      \
2722 //  |       \   \  |       \ <2>  \
2723 //  ...      \  [slow_res] |  |    \   [null_result]
2724 //            \         \--+--+---  |  |
2725 //             \           | /    \ | /
2726 //              --------Region     Phi
2727 //
2728 //=============================================================================
2729 // Code is structured as a series of driver functions all called 'do_XXX' that
2730 // call a set of helper functions.  Helper functions first, then drivers.
2731 
2732 //------------------------------null_check_oop---------------------------------
2733 // Null check oop.  Set null-path control into Region in slot 3.
2734 // Make a cast-not-nullness use the other not-null control.  Return cast.
2735 Node* GraphKit::null_check_oop(Node* value, Node* *null_control,
2736                                bool never_see_null,
2737                                bool safe_for_replace,
2738                                bool speculative) {
2739   // Initial null check taken path
2740   (*null_control) = top();
2741   Node* cast = null_check_common(value, T_OBJECT, false, null_control, speculative);
2742 
2743   // Generate uncommon_trap:
2744   if (never_see_null && (*null_control) != top()) {
2745     // If we see an unexpected null at a check-cast we record it and force a
2746     // recompile; the offending check-cast will be compiled to handle nulls.
2747     // If we see more than one offending BCI, then all checkcasts in the
2748     // method will be compiled to handle nulls.
2749     PreserveJVMState pjvms(this);
2750     set_control(*null_control);
2751     replace_in_map(value, null());
2752     Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculative);
2753     uncommon_trap(reason,
2754                   Deoptimization::Action_make_not_entrant);
2755     (*null_control) = top();    // null path is dead
2756   }
2757   if ((*null_control) == top() && safe_for_replace) {
2758     replace_in_map(value, cast);
2759   }
2760 
2761   // Cast away null-ness on the result
2762   return cast;
2763 }
2764 
2765 //------------------------------opt_iff----------------------------------------
2766 // Optimize the fast-check IfNode.  Set the fast-path region slot 2.
2767 // Return slow-path control.
2768 Node* GraphKit::opt_iff(Node* region, Node* iff) {
2769   IfNode *opt_iff = _gvn.transform(iff)->as_If();
2770 
2771   // Fast path taken; set region slot 2
2772   Node *fast_taken = _gvn.transform( new IfFalseNode(opt_iff) );
2773   region->init_req(2,fast_taken); // Capture fast-control
2774 
2775   // Fast path not-taken, i.e. slow path
2776   Node *slow_taken = _gvn.transform( new IfTrueNode(opt_iff) );
2777   return slow_taken;
2778 }
2779 
2780 //-----------------------------make_runtime_call-------------------------------
2781 Node* GraphKit::make_runtime_call(int flags,
2782                                   const TypeFunc* call_type, address call_addr,
2783                                   const char* call_name,
2784                                   const TypePtr* adr_type,
2785                                   // The following parms are all optional.
2786                                   // The first null ends the list.
2787                                   Node* parm0, Node* parm1,
2788                                   Node* parm2, Node* parm3,
2789                                   Node* parm4, Node* parm5,
2790                                   Node* parm6, Node* parm7) {
2791   assert(call_addr != nullptr, "must not call null targets");
2792 
2793   // Slow-path call
2794   bool is_leaf = !(flags & RC_NO_LEAF);
2795   bool has_io  = (!is_leaf && !(flags & RC_NO_IO));
2796   if (call_name == nullptr) {
2797     assert(!is_leaf, "must supply name for leaf");
2798     call_name = OptoRuntime::stub_name(call_addr);
2799   }
2800   CallNode* call;
2801   if (!is_leaf) {
2802     call = new CallStaticJavaNode(call_type, call_addr, call_name, adr_type);
2803   } else if (flags & RC_NO_FP) {
2804     call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);
2805   } else  if (flags & RC_VECTOR){
2806     uint num_bits = call_type->range_sig()->field_at(TypeFunc::Parms)->is_vect()->length_in_bytes() * BitsPerByte;
2807     call = new CallLeafVectorNode(call_type, call_addr, call_name, adr_type, num_bits);
2808   } else if (flags & RC_PURE) {
2809     assert(adr_type == nullptr, "pure call does not touch memory");
2810     call = new CallLeafPureNode(call_type, call_addr, call_name);
2811   } else {
2812     call = new CallLeafNode(call_type, call_addr, call_name, adr_type);
2813   }
2814 
2815   // The following is similar to set_edges_for_java_call,
2816   // except that the memory effects of the call are restricted to AliasIdxRaw.
2817 
2818   // Slow path call has no side-effects, uses few values
2819   bool wide_in  = !(flags & RC_NARROW_MEM);
2820   bool wide_out = (C->get_alias_index(adr_type) == Compile::AliasIdxBot);
2821 
2822   Node* prev_mem = nullptr;
2823   if (wide_in) {
2824     prev_mem = set_predefined_input_for_runtime_call(call);
2825   } else {
2826     assert(!wide_out, "narrow in => narrow out");
2827     Node* narrow_mem = memory(adr_type);
2828     prev_mem = set_predefined_input_for_runtime_call(call, narrow_mem);
2829   }
2830 
2831   // Hook each parm in order.  Stop looking at the first null.
2832   if (parm0 != nullptr) { call->init_req(TypeFunc::Parms+0, parm0);
2833   if (parm1 != nullptr) { call->init_req(TypeFunc::Parms+1, parm1);
2834   if (parm2 != nullptr) { call->init_req(TypeFunc::Parms+2, parm2);
2835   if (parm3 != nullptr) { call->init_req(TypeFunc::Parms+3, parm3);
2836   if (parm4 != nullptr) { call->init_req(TypeFunc::Parms+4, parm4);
2837   if (parm5 != nullptr) { call->init_req(TypeFunc::Parms+5, parm5);
2838   if (parm6 != nullptr) { call->init_req(TypeFunc::Parms+6, parm6);
2839   if (parm7 != nullptr) { call->init_req(TypeFunc::Parms+7, parm7);
2840   /* close each nested if ===> */  } } } } } } } }
2841   assert(call->in(call->req()-1) != nullptr || (call->req()-1) > (TypeFunc::Parms+7), "must initialize all parms");
2842 
2843   if (!is_leaf) {
2844     // Non-leaves can block and take safepoints:
2845     add_safepoint_edges(call, ((flags & RC_MUST_THROW) != 0));
2846   }
2847   // Non-leaves can throw exceptions:
2848   if (has_io) {
2849     call->set_req(TypeFunc::I_O, i_o());
2850   }
2851 
2852   if (flags & RC_UNCOMMON) {
2853     // Set the count to a tiny probability.  Cf. Estimate_Block_Frequency.
2854     // (An "if" probability corresponds roughly to an unconditional count.
2855     // Sort of.)
2856     call->set_cnt(PROB_UNLIKELY_MAG(4));
2857   }
2858 
2859   Node* c = _gvn.transform(call);
2860   assert(c == call, "cannot disappear");
2861 
2862   if (wide_out) {
2863     // Slow path call has full side-effects.
2864     set_predefined_output_for_runtime_call(call);
2865   } else {
2866     // Slow path call has few side-effects, and/or sets few values.
2867     set_predefined_output_for_runtime_call(call, prev_mem, adr_type);
2868   }
2869 
2870   if (has_io) {
2871     set_i_o(_gvn.transform(new ProjNode(call, TypeFunc::I_O)));
2872   }
2873   return call;
2874 
2875 }
2876 
2877 // i2b
2878 Node* GraphKit::sign_extend_byte(Node* in) {
2879   Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(24)));
2880   return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(24)));
2881 }
2882 
2883 // i2s
2884 Node* GraphKit::sign_extend_short(Node* in) {
2885   Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(16)));
2886   return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(16)));
2887 }
2888 
2889 
2890 //------------------------------merge_memory-----------------------------------
2891 // Merge memory from one path into the current memory state.
2892 void GraphKit::merge_memory(Node* new_mem, Node* region, int new_path) {
2893   for (MergeMemStream mms(merged_memory(), new_mem->as_MergeMem()); mms.next_non_empty2(); ) {
2894     Node* old_slice = mms.force_memory();
2895     Node* new_slice = mms.memory2();
2896     if (old_slice != new_slice) {
2897       PhiNode* phi;
2898       if (old_slice->is_Phi() && old_slice->as_Phi()->region() == region) {
2899         if (mms.is_empty()) {
2900           // clone base memory Phi's inputs for this memory slice
2901           assert(old_slice == mms.base_memory(), "sanity");
2902           phi = PhiNode::make(region, nullptr, Type::MEMORY, mms.adr_type(C));
2903           _gvn.set_type(phi, Type::MEMORY);
2904           for (uint i = 1; i < phi->req(); i++) {
2905             phi->init_req(i, old_slice->in(i));
2906           }
2907         } else {
2908           phi = old_slice->as_Phi(); // Phi was generated already
2909         }
2910       } else {
2911         phi = PhiNode::make(region, old_slice, Type::MEMORY, mms.adr_type(C));
2912         _gvn.set_type(phi, Type::MEMORY);
2913       }
2914       phi->set_req(new_path, new_slice);
2915       mms.set_memory(phi);
2916     }
2917   }
2918 }
2919 
2920 //------------------------------make_slow_call_ex------------------------------
2921 // Make the exception handler hookups for the slow call
2922 void GraphKit::make_slow_call_ex(Node* call, ciInstanceKlass* ex_klass, bool separate_io_proj, bool deoptimize) {
2923   if (stopped())  return;
2924 
2925   // Make a catch node with just two handlers:  fall-through and catch-all
2926   Node* i_o  = _gvn.transform( new ProjNode(call, TypeFunc::I_O, separate_io_proj) );
2927   Node* catc = _gvn.transform( new CatchNode(control(), i_o, 2) );
2928   Node* norm = new CatchProjNode(catc, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci);
2929   _gvn.set_type_bottom(norm);
2930   C->record_for_igvn(norm);
2931   Node* excp = _gvn.transform( new CatchProjNode(catc, CatchProjNode::catch_all_index,    CatchProjNode::no_handler_bci) );
2932 
2933   { PreserveJVMState pjvms(this);
2934     set_control(excp);
2935     set_i_o(i_o);
2936 
2937     if (excp != top()) {
2938       if (deoptimize) {
2939         // Deoptimize if an exception is caught. Don't construct exception state in this case.
2940         uncommon_trap(Deoptimization::Reason_unhandled,
2941                       Deoptimization::Action_none);
2942       } else {
2943         // Create an exception state also.
2944         // Use an exact type if the caller has a specific exception.
2945         const Type* ex_type = TypeOopPtr::make_from_klass_unique(ex_klass)->cast_to_ptr_type(TypePtr::NotNull);
2946         Node*       ex_oop  = new CreateExNode(ex_type, control(), i_o);
2947         add_exception_state(make_exception_state(_gvn.transform(ex_oop)));
2948       }
2949     }
2950   }
2951 
2952   // Get the no-exception control from the CatchNode.
2953   set_control(norm);
2954 }
2955 
2956 static IfNode* gen_subtype_check_compare(Node* ctrl, Node* in1, Node* in2, BoolTest::mask test, float p, PhaseGVN& gvn, BasicType bt) {
2957   Node* cmp = nullptr;
2958   switch(bt) {
2959   case T_INT: cmp = new CmpINode(in1, in2); break;
2960   case T_ADDRESS: cmp = new CmpPNode(in1, in2); break;
2961   default: fatal("unexpected comparison type %s", type2name(bt));
2962   }
2963   cmp = gvn.transform(cmp);
2964   Node* bol = gvn.transform(new BoolNode(cmp, test));
2965   IfNode* iff = new IfNode(ctrl, bol, p, COUNT_UNKNOWN);
2966   gvn.transform(iff);
2967   if (!bol->is_Con()) gvn.record_for_igvn(iff);
2968   return iff;
2969 }
2970 
2971 //-------------------------------gen_subtype_check-----------------------------
2972 // Generate a subtyping check.  Takes as input the subtype and supertype.
2973 // Returns 2 values: sets the default control() to the true path and returns
2974 // the false path.  Only reads invariant memory; sets no (visible) memory.
2975 // The PartialSubtypeCheckNode sets the hidden 1-word cache in the encoding
2976 // but that's not exposed to the optimizer.  This call also doesn't take in an
2977 // Object; if you wish to check an Object you need to load the Object's class
2978 // prior to coming here.
2979 Node* Phase::gen_subtype_check(Node* subklass, Node* superklass, Node** ctrl, Node* mem, PhaseGVN& gvn,
2980                                ciMethod* method, int bci) {
2981   Compile* C = gvn.C;
2982   if ((*ctrl)->is_top()) {
2983     return C->top();
2984   }
2985 
2986   const TypeKlassPtr* klass_ptr_type = gvn.type(superklass)->is_klassptr();
2987   // For a direct pointer comparison, we need the refined array klass pointer
2988   Node* vm_superklass = superklass;
2989   if (klass_ptr_type->isa_aryklassptr() && klass_ptr_type->klass_is_exact()) {
2990     assert(!klass_ptr_type->is_aryklassptr()->is_refined_type(), "Unexpected refined array klass pointer");
2991     vm_superklass = gvn.makecon(klass_ptr_type->is_aryklassptr()->cast_to_refined_array_klass_ptr());
2992   }
2993 
2994   // Fast check for identical types, perhaps identical constants.
2995   // The types can even be identical non-constants, in cases
2996   // involving Array.newInstance, Object.clone, etc.
2997   if (subklass == superklass)
2998     return C->top();             // false path is dead; no test needed.
2999 
3000   if (gvn.type(superklass)->singleton()) {
3001     const TypeKlassPtr* superk = gvn.type(superklass)->is_klassptr();
3002     const TypeKlassPtr* subk   = gvn.type(subklass)->is_klassptr();
3003 
3004     // In the common case of an exact superklass, try to fold up the
3005     // test before generating code.  You may ask, why not just generate
3006     // the code and then let it fold up?  The answer is that the generated
3007     // code will necessarily include null checks, which do not always
3008     // completely fold away.  If they are also needless, then they turn
3009     // into a performance loss.  Example:
3010     //    Foo[] fa = blah(); Foo x = fa[0]; fa[1] = x;
3011     // Here, the type of 'fa' is often exact, so the store check
3012     // of fa[1]=x will fold up, without testing the nullness of x.
3013     //
3014     // At macro expansion, we would have already folded the SubTypeCheckNode
3015     // being expanded here because we always perform the static sub type
3016     // check in SubTypeCheckNode::sub() regardless of whether
3017     // StressReflectiveCode is set or not. We can therefore skip this
3018     // static check when StressReflectiveCode is on.
3019     switch (C->static_subtype_check(superk, subk)) {
3020     case Compile::SSC_always_false:
3021       {
3022         Node* always_fail = *ctrl;
3023         *ctrl = gvn.C->top();
3024         return always_fail;
3025       }
3026     case Compile::SSC_always_true:
3027       return C->top();
3028     case Compile::SSC_easy_test:
3029       {
3030         // Just do a direct pointer compare and be done.
3031         IfNode* iff = gen_subtype_check_compare(*ctrl, subklass, vm_superklass, BoolTest::eq, PROB_STATIC_FREQUENT, gvn, T_ADDRESS);
3032         *ctrl = gvn.transform(new IfTrueNode(iff));
3033         return gvn.transform(new IfFalseNode(iff));
3034       }
3035     case Compile::SSC_full_test:
3036       break;
3037     default:
3038       ShouldNotReachHere();
3039     }
3040   }
3041 
3042   // %%% Possible further optimization:  Even if the superklass is not exact,
3043   // if the subklass is the unique subtype of the superklass, the check
3044   // will always succeed.  We could leave a dependency behind to ensure this.
3045 
3046   // First load the super-klass's check-offset
3047   Node *p1 = gvn.transform(new AddPNode(C->top(), superklass, gvn.MakeConX(in_bytes(Klass::super_check_offset_offset()))));
3048   Node* m = C->immutable_memory();
3049   Node *chk_off = gvn.transform(new LoadINode(nullptr, m, p1, gvn.type(p1)->is_ptr(), TypeInt::INT, MemNode::unordered));
3050   int cacheoff_con = in_bytes(Klass::secondary_super_cache_offset());
3051   const TypeInt* chk_off_t = chk_off->Value(&gvn)->isa_int();
3052   int chk_off_con = (chk_off_t != nullptr && chk_off_t->is_con()) ? chk_off_t->get_con() : cacheoff_con;
3053   bool might_be_cache = (chk_off_con == cacheoff_con);
3054 
3055   // Load from the sub-klass's super-class display list, or a 1-word cache of
3056   // the secondary superclass list, or a failing value with a sentinel offset
3057   // if the super-klass is an interface or exceptionally deep in the Java
3058   // hierarchy and we have to scan the secondary superclass list the hard way.
3059   // Worst-case type is a little odd: null is allowed as a result (usually
3060   // klass loads can never produce a null).
3061   Node *chk_off_X = chk_off;
3062 #ifdef _LP64
3063   chk_off_X = gvn.transform(new ConvI2LNode(chk_off_X));
3064 #endif
3065   Node* p2 = gvn.transform(new AddPNode(C->top(), subklass, chk_off_X));
3066   // For some types like interfaces the following loadKlass is from a 1-word
3067   // cache which is mutable so can't use immutable memory.  Other
3068   // types load from the super-class display table which is immutable.
3069   Node *kmem = C->immutable_memory();
3070   // secondary_super_cache is not immutable but can be treated as such because:
3071   // - no ideal node writes to it in a way that could cause an
3072   //   incorrect/missed optimization of the following Load.
3073   // - it's a cache so, worse case, not reading the latest value
3074   //   wouldn't cause incorrect execution
3075   if (might_be_cache && mem != nullptr) {
3076     kmem = mem->is_MergeMem() ? mem->as_MergeMem()->memory_at(C->get_alias_index(gvn.type(p2)->is_ptr())) : mem;
3077   }
3078   Node* nkls = gvn.transform(LoadKlassNode::make(gvn, kmem, p2, gvn.type(p2)->is_ptr(), TypeInstKlassPtr::OBJECT_OR_NULL));
3079 
3080   // Compile speed common case: ARE a subtype and we canNOT fail
3081   if (superklass == nkls) {
3082     return C->top();             // false path is dead; no test needed.
3083   }
3084 
3085   // Gather the various success & failures here
3086   RegionNode* r_not_subtype = new RegionNode(3);
3087   gvn.record_for_igvn(r_not_subtype);
3088   RegionNode* r_ok_subtype = new RegionNode(4);
3089   gvn.record_for_igvn(r_ok_subtype);
3090 
3091   // If we might perform an expensive check, first try to take advantage of profile data that was attached to the
3092   // SubTypeCheck node
3093   if (might_be_cache && method != nullptr && VM_Version::profile_all_receivers_at_type_check()) {
3094     ciCallProfile profile = method->call_profile_at_bci(bci);
3095     float total_prob = 0;
3096     for (int i = 0; profile.has_receiver(i); ++i) {
3097       float prob = profile.receiver_prob(i);
3098       total_prob += prob;
3099     }
3100     if (total_prob * 100. >= TypeProfileSubTypeCheckCommonThreshold) {
3101       const TypeKlassPtr* superk = gvn.type(superklass)->is_klassptr();
3102       for (int i = 0; profile.has_receiver(i); ++i) {
3103         ciKlass* klass = profile.receiver(i);
3104         const TypeKlassPtr* klass_t = TypeKlassPtr::make(klass);
3105         Compile::SubTypeCheckResult result = C->static_subtype_check(superk, klass_t);
3106         if (result != Compile::SSC_always_true && result != Compile::SSC_always_false) {
3107           continue;
3108         }
3109         if (klass_t->isa_aryklassptr()) {
3110           // For a direct pointer comparison, we need the refined array klass pointer
3111           klass_t = klass_t->is_aryklassptr()->cast_to_refined_array_klass_ptr();
3112         }
3113         float prob = profile.receiver_prob(i);
3114         ConNode* klass_node = gvn.makecon(klass_t);
3115         IfNode* iff = gen_subtype_check_compare(*ctrl, subklass, klass_node, BoolTest::eq, prob, gvn, T_ADDRESS);
3116         Node* iftrue = gvn.transform(new IfTrueNode(iff));
3117 
3118         if (result == Compile::SSC_always_true) {
3119           r_ok_subtype->add_req(iftrue);
3120         } else {
3121           assert(result == Compile::SSC_always_false, "");
3122           r_not_subtype->add_req(iftrue);
3123         }
3124         *ctrl = gvn.transform(new IfFalseNode(iff));
3125       }
3126     }
3127   }
3128 
3129   // See if we get an immediate positive hit.  Happens roughly 83% of the
3130   // time.  Test to see if the value loaded just previously from the subklass
3131   // is exactly the superklass.
3132   IfNode *iff1 = gen_subtype_check_compare(*ctrl, superklass, nkls, BoolTest::eq, PROB_LIKELY(0.83f), gvn, T_ADDRESS);
3133   Node *iftrue1 = gvn.transform( new IfTrueNode (iff1));
3134   *ctrl = gvn.transform(new IfFalseNode(iff1));
3135 
3136   // Compile speed common case: Check for being deterministic right now.  If
3137   // chk_off is a constant and not equal to cacheoff then we are NOT a
3138   // subklass.  In this case we need exactly the 1 test above and we can
3139   // return those results immediately.
3140   if (!might_be_cache) {
3141     Node* not_subtype_ctrl = *ctrl;
3142     *ctrl = iftrue1; // We need exactly the 1 test above
3143     PhaseIterGVN* igvn = gvn.is_IterGVN();
3144     if (igvn != nullptr) {
3145       igvn->remove_globally_dead_node(r_ok_subtype);
3146       igvn->remove_globally_dead_node(r_not_subtype);
3147     }
3148     return not_subtype_ctrl;
3149   }
3150 
3151   r_ok_subtype->init_req(1, iftrue1);
3152 
3153   // Check for immediate negative hit.  Happens roughly 11% of the time (which
3154   // is roughly 63% of the remaining cases).  Test to see if the loaded
3155   // check-offset points into the subklass display list or the 1-element
3156   // cache.  If it points to the display (and NOT the cache) and the display
3157   // missed then it's not a subtype.
3158   Node *cacheoff = gvn.intcon(cacheoff_con);
3159   IfNode *iff2 = gen_subtype_check_compare(*ctrl, chk_off, cacheoff, BoolTest::ne, PROB_LIKELY(0.63f), gvn, T_INT);
3160   r_not_subtype->init_req(1, gvn.transform(new IfTrueNode (iff2)));
3161   *ctrl = gvn.transform(new IfFalseNode(iff2));
3162 
3163   // Check for self.  Very rare to get here, but it is taken 1/3 the time.
3164   // No performance impact (too rare) but allows sharing of secondary arrays
3165   // which has some footprint reduction.
3166   IfNode *iff3 = gen_subtype_check_compare(*ctrl, subklass, vm_superklass, BoolTest::eq, PROB_LIKELY(0.36f), gvn, T_ADDRESS);
3167   r_ok_subtype->init_req(2, gvn.transform(new IfTrueNode(iff3)));
3168   *ctrl = gvn.transform(new IfFalseNode(iff3));
3169 
3170   // -- Roads not taken here: --
3171   // We could also have chosen to perform the self-check at the beginning
3172   // of this code sequence, as the assembler does.  This would not pay off
3173   // the same way, since the optimizer, unlike the assembler, can perform
3174   // static type analysis to fold away many successful self-checks.
3175   // Non-foldable self checks work better here in second position, because
3176   // the initial primary superclass check subsumes a self-check for most
3177   // types.  An exception would be a secondary type like array-of-interface,
3178   // which does not appear in its own primary supertype display.
3179   // Finally, we could have chosen to move the self-check into the
3180   // PartialSubtypeCheckNode, and from there out-of-line in a platform
3181   // dependent manner.  But it is worthwhile to have the check here,
3182   // where it can be perhaps be optimized.  The cost in code space is
3183   // small (register compare, branch).
3184 
3185   // Now do a linear scan of the secondary super-klass array.  Again, no real
3186   // performance impact (too rare) but it's gotta be done.
3187   // Since the code is rarely used, there is no penalty for moving it
3188   // out of line, and it can only improve I-cache density.
3189   // The decision to inline or out-of-line this final check is platform
3190   // dependent, and is found in the AD file definition of PartialSubtypeCheck.
3191   Node* psc = gvn.transform(
3192     new PartialSubtypeCheckNode(*ctrl, subklass, superklass));
3193 
3194   IfNode *iff4 = gen_subtype_check_compare(*ctrl, psc, gvn.zerocon(T_OBJECT), BoolTest::ne, PROB_FAIR, gvn, T_ADDRESS);
3195   r_not_subtype->init_req(2, gvn.transform(new IfTrueNode (iff4)));
3196   r_ok_subtype ->init_req(3, gvn.transform(new IfFalseNode(iff4)));
3197 
3198   // Return false path; set default control to true path.
3199   *ctrl = gvn.transform(r_ok_subtype);
3200   return gvn.transform(r_not_subtype);
3201 }
3202 
3203 Node* GraphKit::gen_subtype_check(Node* obj_or_subklass, Node* superklass) {
3204   const Type* sub_t = _gvn.type(obj_or_subklass);
3205   if (sub_t->make_oopptr() != nullptr && sub_t->make_oopptr()->is_inlinetypeptr()) {
3206     sub_t = TypeKlassPtr::make(sub_t->inline_klass());
3207     obj_or_subklass = makecon(sub_t);
3208   }
3209   bool expand_subtype_check = C->post_loop_opts_phase(); // macro node expansion is over
3210   if (expand_subtype_check) {
3211     MergeMemNode* mem = merged_memory();
3212     Node* ctrl = control();
3213     Node* subklass = obj_or_subklass;
3214     if (!sub_t->isa_klassptr()) {
3215       subklass = load_object_klass(obj_or_subklass);
3216     }
3217 
3218     Node* n = Phase::gen_subtype_check(subklass, superklass, &ctrl, mem, _gvn, method(), bci());
3219     set_control(ctrl);
3220     return n;
3221   }
3222 
3223   Node* check = _gvn.transform(new SubTypeCheckNode(C, obj_or_subklass, superklass, method(), bci()));
3224   Node* bol = _gvn.transform(new BoolNode(check, BoolTest::eq));
3225   IfNode* iff = create_and_xform_if(control(), bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
3226   set_control(_gvn.transform(new IfTrueNode(iff)));
3227   return _gvn.transform(new IfFalseNode(iff));
3228 }
3229 
3230 // Profile-driven exact type check:
3231 Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass,
3232                                     float prob, Node* *casted_receiver) {
3233   assert(!klass->is_interface(), "no exact type check on interfaces");
3234   Node* fail = top();
3235   const Type* rec_t = _gvn.type(receiver);
3236   if (rec_t->is_inlinetypeptr()) {
3237     if (klass->equals(rec_t->inline_klass())) {
3238       (*casted_receiver) = receiver; // Always passes
3239     } else {
3240       (*casted_receiver) = top();    // Always fails
3241       fail = control();
3242       set_control(top());
3243     }
3244     return fail;
3245   }
3246   const TypeKlassPtr* tklass = TypeKlassPtr::make(klass, Type::trust_interfaces);
3247   if (tklass->isa_aryklassptr()) {
3248     // For a direct pointer comparison, we need the refined array klass pointer
3249     tklass = tklass->is_aryklassptr()->cast_to_refined_array_klass_ptr();
3250   }
3251   Node* recv_klass = load_object_klass(receiver);
3252   fail = type_check(recv_klass, tklass, prob);
3253 
3254   if (!stopped()) {
3255     const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
3256     const TypeOopPtr* recv_xtype = tklass->as_instance_type();
3257     assert(recv_xtype->klass_is_exact(), "");
3258 
3259     if (!receiver_type->higher_equal(recv_xtype)) { // ignore redundant casts
3260       // Subsume downstream occurrences of receiver with a cast to
3261       // recv_xtype, since now we know what the type will be.
3262       Node* cast = new CheckCastPPNode(control(), receiver, recv_xtype);
3263       Node* res = _gvn.transform(cast);
3264       if (recv_xtype->is_inlinetypeptr()) {
3265         assert(!gvn().type(res)->maybe_null(), "receiver should never be null");
3266         res = InlineTypeNode::make_from_oop(this, res, recv_xtype->inline_klass());
3267       }
3268       (*casted_receiver) = res;
3269       assert(!(*casted_receiver)->is_top(), "that path should be unreachable");
3270       // (User must make the replace_in_map call.)
3271     }
3272   }
3273 
3274   return fail;
3275 }
3276 
3277 Node* GraphKit::type_check(Node* recv_klass, const TypeKlassPtr* tklass,
3278                            float prob) {
3279   Node* want_klass = makecon(tklass);
3280   Node* cmp = _gvn.transform(new CmpPNode(recv_klass, want_klass));
3281   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
3282   IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN);
3283   set_control(_gvn.transform(new IfTrueNode (iff)));
3284   Node* fail = _gvn.transform(new IfFalseNode(iff));
3285   return fail;
3286 }
3287 
3288 //------------------------------subtype_check_receiver-------------------------
3289 Node* GraphKit::subtype_check_receiver(Node* receiver, ciKlass* klass,
3290                                        Node** casted_receiver) {
3291   const TypeKlassPtr* tklass = TypeKlassPtr::make(klass, Type::trust_interfaces)->try_improve();
3292   Node* want_klass = makecon(tklass);
3293 
3294   Node* slow_ctl = gen_subtype_check(receiver, want_klass);
3295 
3296   // Ignore interface type information until interface types are properly tracked.
3297   if (!stopped() && !klass->is_interface()) {
3298     const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
3299     const TypeOopPtr* recv_type = tklass->cast_to_exactness(false)->is_klassptr()->as_instance_type();
3300     if (receiver_type != nullptr && !receiver_type->higher_equal(recv_type)) { // ignore redundant casts
3301       Node* cast = _gvn.transform(new CheckCastPPNode(control(), receiver, recv_type));
3302       if (recv_type->is_inlinetypeptr()) {
3303         cast = InlineTypeNode::make_from_oop(this, cast, recv_type->inline_klass());
3304       }
3305       (*casted_receiver) = cast;
3306     }
3307   }
3308 
3309   return slow_ctl;
3310 }
3311 
3312 //------------------------------seems_never_null-------------------------------
3313 // Use null_seen information if it is available from the profile.
3314 // If we see an unexpected null at a type check we record it and force a
3315 // recompile; the offending check will be recompiled to handle nulls.
3316 // If we see several offending BCIs, then all checks in the
3317 // method will be recompiled.
3318 bool GraphKit::seems_never_null(Node* obj, ciProfileData* data, bool& speculating) {
3319   speculating = !_gvn.type(obj)->speculative_maybe_null();
3320   Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculating);
3321   if (UncommonNullCast               // Cutout for this technique
3322       && obj != null()               // And not the -Xcomp stupid case?
3323       && !too_many_traps(reason)
3324       ) {
3325     if (speculating) {
3326       return true;
3327     }
3328     if (data == nullptr)
3329       // Edge case:  no mature data.  Be optimistic here.
3330       return true;
3331     // If the profile has not seen a null, assume it won't happen.
3332     assert(java_bc() == Bytecodes::_checkcast ||
3333            java_bc() == Bytecodes::_instanceof ||
3334            java_bc() == Bytecodes::_aastore, "MDO must collect null_seen bit here");
3335     return !data->as_BitData()->null_seen();
3336   }
3337   speculating = false;
3338   return false;
3339 }
3340 
3341 void GraphKit::guard_klass_being_initialized(Node* klass) {
3342   int init_state_off = in_bytes(InstanceKlass::init_state_offset());
3343   Node* adr = basic_plus_adr(top(), klass, init_state_off);
3344   Node* init_state = LoadNode::make(_gvn, nullptr, immutable_memory(), adr,
3345                                     adr->bottom_type()->is_ptr(), TypeInt::BYTE,
3346                                     T_BYTE, MemNode::acquire);
3347   init_state = _gvn.transform(init_state);
3348 
3349   Node* being_initialized_state = makecon(TypeInt::make(InstanceKlass::being_initialized));
3350 
3351   Node* chk = _gvn.transform(new CmpINode(being_initialized_state, init_state));
3352   Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3353 
3354   { BuildCutout unless(this, tst, PROB_MAX);
3355     uncommon_trap(Deoptimization::Reason_initialized, Deoptimization::Action_reinterpret);
3356   }
3357 }
3358 
3359 void GraphKit::guard_init_thread(Node* klass) {
3360   int init_thread_off = in_bytes(InstanceKlass::init_thread_offset());
3361   Node* adr = basic_plus_adr(top(), klass, init_thread_off);
3362 
3363   Node* init_thread = LoadNode::make(_gvn, nullptr, immutable_memory(), adr,
3364                                      adr->bottom_type()->is_ptr(), TypePtr::NOTNULL,
3365                                      T_ADDRESS, MemNode::unordered);
3366   init_thread = _gvn.transform(init_thread);
3367 
3368   Node* cur_thread = _gvn.transform(new ThreadLocalNode());
3369 
3370   Node* chk = _gvn.transform(new CmpPNode(cur_thread, init_thread));
3371   Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3372 
3373   { BuildCutout unless(this, tst, PROB_MAX);
3374     uncommon_trap(Deoptimization::Reason_uninitialized, Deoptimization::Action_none);
3375   }
3376 }
3377 
3378 void GraphKit::clinit_barrier(ciInstanceKlass* ik, ciMethod* context) {
3379   if (ik->is_being_initialized()) {
3380     if (C->needs_clinit_barrier(ik, context)) {
3381       Node* klass = makecon(TypeKlassPtr::make(ik));
3382       guard_klass_being_initialized(klass);
3383       guard_init_thread(klass);
3384       insert_mem_bar(Op_MemBarCPUOrder);
3385     }
3386   } else if (ik->is_initialized()) {
3387     return; // no barrier needed
3388   } else {
3389     uncommon_trap(Deoptimization::Reason_uninitialized,
3390                   Deoptimization::Action_reinterpret,
3391                   nullptr);
3392   }
3393 }
3394 
3395 //------------------------maybe_cast_profiled_receiver-------------------------
3396 // If the profile has seen exactly one type, narrow to exactly that type.
3397 // Subsequent type checks will always fold up.
3398 Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj,
3399                                              const TypeKlassPtr* require_klass,
3400                                              ciKlass* spec_klass,
3401                                              bool safe_for_replace) {
3402   if (!UseTypeProfile || !TypeProfileCasts) return nullptr;
3403 
3404   Deoptimization::DeoptReason reason = Deoptimization::reason_class_check(spec_klass != nullptr);
3405 
3406   // Make sure we haven't already deoptimized from this tactic.
3407   if (too_many_traps_or_recompiles(reason))
3408     return nullptr;
3409 
3410   // (No, this isn't a call, but it's enough like a virtual call
3411   // to use the same ciMethod accessor to get the profile info...)
3412   // If we have a speculative type use it instead of profiling (which
3413   // may not help us)
3414   ciKlass* exact_kls = spec_klass;
3415   if (exact_kls == nullptr) {
3416     if (java_bc() == Bytecodes::_aastore) {
3417       ciKlass* array_type = nullptr;
3418       ciKlass* element_type = nullptr;
3419       ProfilePtrKind element_ptr = ProfileMaybeNull;
3420       bool flat_array = true;
3421       bool null_free_array = true;
3422       method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array);
3423       exact_kls = element_type;
3424     } else {
3425       exact_kls = profile_has_unique_klass();
3426     }
3427   }
3428   if (exact_kls != nullptr) {// no cast failures here
3429     if (require_klass == nullptr ||
3430         C->static_subtype_check(require_klass, TypeKlassPtr::make(exact_kls, Type::trust_interfaces)) == Compile::SSC_always_true) {
3431       // If we narrow the type to match what the type profile sees or
3432       // the speculative type, we can then remove the rest of the
3433       // cast.
3434       // This is a win, even if the exact_kls is very specific,
3435       // because downstream operations, such as method calls,
3436       // will often benefit from the sharper type.
3437       Node* exact_obj = not_null_obj; // will get updated in place...
3438       Node* slow_ctl  = type_check_receiver(exact_obj, exact_kls, 1.0,
3439                                             &exact_obj);
3440       { PreserveJVMState pjvms(this);
3441         set_control(slow_ctl);
3442         uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
3443       }
3444       if (safe_for_replace) {
3445         replace_in_map(not_null_obj, exact_obj);
3446       }
3447       return exact_obj;
3448     }
3449     // assert(ssc == Compile::SSC_always_true)... except maybe the profile lied to us.
3450   }
3451 
3452   return nullptr;
3453 }
3454 
3455 /**
3456  * Cast obj to type and emit guard unless we had too many traps here
3457  * already
3458  *
3459  * @param obj       node being casted
3460  * @param type      type to cast the node to
3461  * @param not_null  true if we know node cannot be null
3462  */
3463 Node* GraphKit::maybe_cast_profiled_obj(Node* obj,
3464                                         ciKlass* type,
3465                                         bool not_null) {
3466   if (stopped()) {
3467     return obj;
3468   }
3469 
3470   // type is null if profiling tells us this object is always null
3471   if (type != nullptr) {
3472     Deoptimization::DeoptReason class_reason = Deoptimization::Reason_speculate_class_check;
3473     Deoptimization::DeoptReason null_reason = Deoptimization::Reason_speculate_null_check;
3474 
3475     if (!too_many_traps_or_recompiles(null_reason) &&
3476         !too_many_traps_or_recompiles(class_reason)) {
3477       Node* not_null_obj = nullptr;
3478       // not_null is true if we know the object is not null and
3479       // there's no need for a null check
3480       if (!not_null) {
3481         Node* null_ctl = top();
3482         not_null_obj = null_check_oop(obj, &null_ctl, true, true, true);
3483         assert(null_ctl->is_top(), "no null control here");
3484       } else {
3485         not_null_obj = obj;
3486       }
3487 
3488       Node* exact_obj = not_null_obj;
3489       ciKlass* exact_kls = type;
3490       Node* slow_ctl  = type_check_receiver(exact_obj, exact_kls, 1.0,
3491                                             &exact_obj);
3492       {
3493         PreserveJVMState pjvms(this);
3494         set_control(slow_ctl);
3495         uncommon_trap_exact(class_reason, Deoptimization::Action_maybe_recompile);
3496       }
3497       replace_in_map(not_null_obj, exact_obj);
3498       obj = exact_obj;
3499     }
3500   } else {
3501     if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {
3502       Node* exact_obj = null_assert(obj);
3503       replace_in_map(obj, exact_obj);
3504       obj = exact_obj;
3505     }
3506   }
3507   return obj;
3508 }
3509 
3510 //-------------------------------gen_instanceof--------------------------------
3511 // Generate an instance-of idiom.  Used by both the instance-of bytecode
3512 // and the reflective instance-of call.
3513 Node* GraphKit::gen_instanceof(Node* obj, Node* superklass, bool safe_for_replace) {
3514   kill_dead_locals();           // Benefit all the uncommon traps
3515   assert( !stopped(), "dead parse path should be checked in callers" );
3516   assert(!TypePtr::NULL_PTR->higher_equal(_gvn.type(superklass)->is_klassptr()),
3517          "must check for not-null not-dead klass in callers");
3518 
3519   // Make the merge point
3520   enum { _obj_path = 1, _fail_path, _null_path, PATH_LIMIT };
3521   RegionNode* region = new RegionNode(PATH_LIMIT);
3522   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
3523   C->set_has_split_ifs(true); // Has chance for split-if optimization
3524 
3525   ciProfileData* data = nullptr;
3526   if (java_bc() == Bytecodes::_instanceof) {  // Only for the bytecode
3527     data = method()->method_data()->bci_to_data(bci());
3528   }
3529   bool speculative_not_null = false;
3530   bool never_see_null = (ProfileDynamicTypes  // aggressive use of profile
3531                          && seems_never_null(obj, data, speculative_not_null));
3532 
3533   // Null check; get casted pointer; set region slot 3
3534   Node* null_ctl = top();
3535   Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3536 
3537   // If not_null_obj is dead, only null-path is taken
3538   if (stopped()) {              // Doing instance-of on a null?
3539     set_control(null_ctl);
3540     return intcon(0);
3541   }
3542   region->init_req(_null_path, null_ctl);
3543   phi   ->init_req(_null_path, intcon(0)); // Set null path value
3544   if (null_ctl == top()) {
3545     // Do this eagerly, so that pattern matches like is_diamond_phi
3546     // will work even during parsing.
3547     assert(_null_path == PATH_LIMIT-1, "delete last");
3548     region->del_req(_null_path);
3549     phi   ->del_req(_null_path);
3550   }
3551 
3552   // Do we know the type check always succeed?
3553   bool known_statically = false;
3554   if (_gvn.type(superklass)->singleton()) {
3555     const TypeKlassPtr* superk = _gvn.type(superklass)->is_klassptr();
3556     const TypeKlassPtr* subk = _gvn.type(obj)->is_oopptr()->as_klass_type();
3557     if (subk != nullptr && subk->is_loaded()) {
3558       int static_res = C->static_subtype_check(superk, subk);
3559       known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false);
3560     }
3561   }
3562 
3563   if (!known_statically) {
3564     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3565     // We may not have profiling here or it may not help us. If we
3566     // have a speculative type use it to perform an exact cast.
3567     ciKlass* spec_obj_type = obj_type->speculative_type();
3568     if (spec_obj_type != nullptr || (ProfileDynamicTypes && data != nullptr)) {
3569       Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, nullptr, spec_obj_type, safe_for_replace);
3570       if (stopped()) {            // Profile disagrees with this path.
3571         set_control(null_ctl);    // Null is the only remaining possibility.
3572         return intcon(0);
3573       }
3574       if (cast_obj != nullptr) {
3575         not_null_obj = cast_obj;
3576       }
3577     }
3578   }
3579 
3580   // Generate the subtype check
3581   Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass);
3582 
3583   // Plug in the success path to the general merge in slot 1.
3584   region->init_req(_obj_path, control());
3585   phi   ->init_req(_obj_path, intcon(1));
3586 
3587   // Plug in the failing path to the general merge in slot 2.
3588   region->init_req(_fail_path, not_subtype_ctrl);
3589   phi   ->init_req(_fail_path, intcon(0));
3590 
3591   // Return final merged results
3592   set_control( _gvn.transform(region) );
3593   record_for_igvn(region);
3594 
3595   // If we know the type check always succeeds then we don't use the
3596   // profiling data at this bytecode. Don't lose it, feed it to the
3597   // type system as a speculative type.
3598   if (safe_for_replace) {
3599     Node* casted_obj = record_profiled_receiver_for_speculation(obj);
3600     replace_in_map(obj, casted_obj);
3601   }
3602 
3603   return _gvn.transform(phi);
3604 }
3605 
3606 //-------------------------------gen_checkcast---------------------------------
3607 // Generate a checkcast idiom.  Used by both the checkcast bytecode and the
3608 // array store bytecode.  Stack must be as-if BEFORE doing the bytecode so the
3609 // uncommon-trap paths work.  Adjust stack after this call.
3610 // If failure_control is supplied and not null, it is filled in with
3611 // the control edge for the cast failure.  Otherwise, an appropriate
3612 // uncommon trap or exception is thrown.
3613 Node* GraphKit::gen_checkcast(Node* obj, Node* superklass, Node* *failure_control, bool null_free, bool maybe_larval) {
3614   kill_dead_locals();           // Benefit all the uncommon traps
3615   const TypeKlassPtr* klass_ptr_type = _gvn.type(superklass)->is_klassptr();
3616   const Type* obj_type = _gvn.type(obj);
3617 
3618   const TypeKlassPtr* improved_klass_ptr_type = klass_ptr_type->try_improve();
3619   const TypeOopPtr* toop = improved_klass_ptr_type->cast_to_exactness(false)->as_instance_type();
3620   bool safe_for_replace = (failure_control == nullptr);
3621   assert(!null_free || toop->can_be_inline_type(), "must be an inline type pointer");
3622 
3623   // Fast cutout:  Check the case that the cast is vacuously true.
3624   // This detects the common cases where the test will short-circuit
3625   // away completely.  We do this before we perform the null check,
3626   // because if the test is going to turn into zero code, we don't
3627   // want a residual null check left around.  (Causes a slowdown,
3628   // for example, in some objArray manipulations, such as a[i]=a[j].)
3629   if (improved_klass_ptr_type->singleton()) {
3630     const TypeKlassPtr* kptr = nullptr;
3631     if (obj_type->isa_oop_ptr()) {
3632       kptr = obj_type->is_oopptr()->as_klass_type();
3633     } else if (obj->is_InlineType()) {
3634       ciInlineKlass* vk = obj_type->inline_klass();
3635       kptr = TypeInstKlassPtr::make(TypePtr::NotNull, vk, Type::Offset(0));
3636     }
3637 
3638     if (kptr != nullptr) {
3639       switch (C->static_subtype_check(improved_klass_ptr_type, kptr)) {
3640       case Compile::SSC_always_true:
3641         // If we know the type check always succeed then we don't use
3642         // the profiling data at this bytecode. Don't lose it, feed it
3643         // to the type system as a speculative type.
3644         obj = record_profiled_receiver_for_speculation(obj);
3645         if (null_free) {
3646           assert(safe_for_replace, "must be");
3647           obj = null_check(obj);
3648         }
3649         assert(stopped() || !toop->is_inlinetypeptr() || obj->is_InlineType(), "should have been scalarized");
3650         return obj;
3651       case Compile::SSC_always_false:
3652         if (null_free) {
3653           assert(safe_for_replace, "must be");
3654           obj = null_check(obj);
3655         }
3656         // It needs a null check because a null will *pass* the cast check.
3657         if (obj_type->isa_oopptr() != nullptr && !obj_type->is_oopptr()->maybe_null()) {
3658           bool is_aastore = (java_bc() == Bytecodes::_aastore);
3659           Deoptimization::DeoptReason reason = is_aastore ?
3660             Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3661           builtin_throw(reason);
3662           return top();
3663         } else if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {
3664           return null_assert(obj);
3665         }
3666         break; // Fall through to full check
3667       default:
3668         break;
3669       }
3670     }
3671   }
3672 
3673   ciProfileData* data = nullptr;
3674   if (failure_control == nullptr) {        // use MDO in regular case only
3675     assert(java_bc() == Bytecodes::_aastore ||
3676            java_bc() == Bytecodes::_checkcast,
3677            "interpreter profiles type checks only for these BCs");
3678     if (method()->method_data()->is_mature()) {
3679       data = method()->method_data()->bci_to_data(bci());
3680     }
3681   }
3682 
3683   // Make the merge point
3684   enum { _obj_path = 1, _null_path, PATH_LIMIT };
3685   RegionNode* region = new RegionNode(PATH_LIMIT);
3686   Node*       phi    = new PhiNode(region, toop);
3687   _gvn.set_type(region, Type::CONTROL);
3688   _gvn.set_type(phi, toop);
3689 
3690   C->set_has_split_ifs(true); // Has chance for split-if optimization
3691 
3692   // Use null-cast information if it is available
3693   bool speculative_not_null = false;
3694   bool never_see_null = ((failure_control == nullptr)  // regular case only
3695                          && seems_never_null(obj, data, speculative_not_null));
3696 
3697   if (obj->is_InlineType()) {
3698     // Re-execute if buffering during triggers deoptimization
3699     PreserveReexecuteState preexecs(this);
3700     jvms()->set_should_reexecute(true);
3701     obj = obj->as_InlineType()->buffer(this, safe_for_replace);
3702   }
3703 
3704   // Null check; get casted pointer; set region slot 3
3705   Node* null_ctl = top();
3706   Node* not_null_obj = nullptr;
3707   if (null_free) {
3708     assert(safe_for_replace, "must be");
3709     not_null_obj = null_check(obj);
3710   } else {
3711     not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3712   }
3713 
3714   // If not_null_obj is dead, only null-path is taken
3715   if (stopped()) {              // Doing instance-of on a null?
3716     set_control(null_ctl);
3717     if (toop->is_inlinetypeptr()) {
3718       return InlineTypeNode::make_null(_gvn, toop->inline_klass());
3719     }
3720     return null();
3721   }
3722   region->init_req(_null_path, null_ctl);
3723   phi   ->init_req(_null_path, null());  // Set null path value
3724   if (null_ctl == top()) {
3725     // Do this eagerly, so that pattern matches like is_diamond_phi
3726     // will work even during parsing.
3727     assert(_null_path == PATH_LIMIT-1, "delete last");
3728     region->del_req(_null_path);
3729     phi   ->del_req(_null_path);
3730   }
3731 
3732   Node* cast_obj = nullptr;
3733   if (improved_klass_ptr_type->klass_is_exact()) {
3734     // The following optimization tries to statically cast the speculative type of the object
3735     // (for example obtained during profiling) to the type of the superklass and then do a
3736     // dynamic check that the type of the object is what we expect. To work correctly
3737     // for checkcast and aastore the type of superklass should be exact.
3738     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3739     // We may not have profiling here or it may not help us. If we have
3740     // a speculative type use it to perform an exact cast.
3741     ciKlass* spec_obj_type = obj_type->speculative_type();
3742     if (spec_obj_type != nullptr || data != nullptr) {
3743       cast_obj = maybe_cast_profiled_receiver(not_null_obj, improved_klass_ptr_type, spec_obj_type, safe_for_replace);
3744       if (cast_obj != nullptr) {
3745         if (failure_control != nullptr) // failure is now impossible
3746           (*failure_control) = top();
3747         // adjust the type of the phi to the exact klass:
3748         phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));
3749       }
3750     }
3751   }
3752 
3753   if (cast_obj == nullptr) {
3754     // Generate the subtype check
3755     Node* improved_superklass = superklass;
3756     if (improved_klass_ptr_type != klass_ptr_type && improved_klass_ptr_type->singleton()) {
3757       // Only improve the super class for constants which allows subsequent sub type checks to possibly be commoned up.
3758       // The other non-constant cases cannot be improved with a cast node here since they could be folded to top.
3759       // Additionally, the benefit would only be minor in non-constant cases.
3760       improved_superklass = makecon(improved_klass_ptr_type);
3761     }
3762     Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, improved_superklass);
3763     // Plug in success path into the merge
3764     cast_obj = _gvn.transform(new CheckCastPPNode(control(), not_null_obj, toop));
3765     // Failure path ends in uncommon trap (or may be dead - failure impossible)
3766     if (failure_control == nullptr) {
3767       if (not_subtype_ctrl != top()) { // If failure is possible
3768         PreserveJVMState pjvms(this);
3769         set_control(not_subtype_ctrl);
3770         bool is_aastore = (java_bc() == Bytecodes::_aastore);
3771         Deoptimization::DeoptReason reason = is_aastore ?
3772           Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3773         builtin_throw(reason);
3774       }
3775     } else {
3776       (*failure_control) = not_subtype_ctrl;
3777     }
3778   }
3779 
3780   region->init_req(_obj_path, control());
3781   phi   ->init_req(_obj_path, cast_obj);
3782 
3783   // A merge of null or Casted-NotNull obj
3784   Node* res = _gvn.transform(phi);
3785 
3786   // Note I do NOT always 'replace_in_map(obj,result)' here.
3787   //  if( tk->klass()->can_be_primary_super()  )
3788     // This means that if I successfully store an Object into an array-of-String
3789     // I 'forget' that the Object is really now known to be a String.  I have to
3790     // do this because we don't have true union types for interfaces - if I store
3791     // a Baz into an array-of-Interface and then tell the optimizer it's an
3792     // Interface, I forget that it's also a Baz and cannot do Baz-like field
3793     // references to it.  FIX THIS WHEN UNION TYPES APPEAR!
3794   //  replace_in_map( obj, res );
3795 
3796   // Return final merged results
3797   set_control( _gvn.transform(region) );
3798   record_for_igvn(region);
3799 
3800   bool not_inline = !toop->can_be_inline_type();
3801   bool not_flat_in_array = !UseArrayFlattening || not_inline || (toop->is_inlinetypeptr() && !toop->inline_klass()->maybe_flat_in_array());
3802   if (Arguments::is_valhalla_enabled() && (not_inline || not_flat_in_array)) {
3803     // Check if obj has been loaded from an array
3804     obj = obj->isa_DecodeN() ? obj->in(1) : obj;
3805     Node* array = nullptr;
3806     if (obj->isa_Load()) {
3807       Node* address = obj->in(MemNode::Address);
3808       if (address->isa_AddP()) {
3809         array = address->as_AddP()->in(AddPNode::Base);
3810       }
3811     } else if (obj->is_Phi()) {
3812       Node* region = obj->in(0);
3813       // TODO make this more robust (see JDK-8231346)
3814       if (region->req() == 3 && region->in(2) != nullptr && region->in(2)->in(0) != nullptr) {
3815         IfNode* iff = region->in(2)->in(0)->isa_If();
3816         if (iff != nullptr) {
3817           iff->is_flat_array_check(&_gvn, &array);
3818         }
3819       }
3820     }
3821     if (array != nullptr) {
3822       const TypeAryPtr* ary_t = _gvn.type(array)->isa_aryptr();
3823       if (ary_t != nullptr) {
3824         if (!ary_t->is_not_null_free() && !ary_t->is_null_free() && not_inline) {
3825           // Casting array element to a non-inline-type, mark array as not null-free.
3826           Node* cast = _gvn.transform(new CheckCastPPNode(control(), array, ary_t->cast_to_not_null_free()));
3827           replace_in_map(array, cast);
3828           array = cast;
3829         }
3830         if (!ary_t->is_not_flat() && !ary_t->is_flat() && not_flat_in_array) {
3831           // Casting array element to a non-flat-in-array type, mark array as not flat.
3832           Node* cast = _gvn.transform(new CheckCastPPNode(control(), array, ary_t->cast_to_not_flat()));
3833           replace_in_map(array, cast);
3834           array = cast;
3835         }
3836       }
3837     }
3838   }
3839 
3840   if (!stopped() && !res->is_InlineType()) {
3841     res = record_profiled_receiver_for_speculation(res);
3842     if (toop->is_inlinetypeptr() && !maybe_larval) {
3843       Node* vt = InlineTypeNode::make_from_oop(this, res, toop->inline_klass());
3844       res = vt;
3845       if (safe_for_replace) {
3846         replace_in_map(obj, vt);
3847         replace_in_map(not_null_obj, vt);
3848         replace_in_map(res, vt);
3849       }
3850     }
3851   }
3852   return res;
3853 }
3854 
3855 Node* GraphKit::mark_word_test(Node* obj, uintptr_t mask_val, bool eq, bool check_lock) {
3856   // Load markword
3857   Node* mark_adr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
3858   Node* mark = make_load(nullptr, mark_adr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
3859   if (check_lock && !UseCompactObjectHeaders) {
3860     // COH: Locking does not override the markword with a tagged pointer. We can directly read from the markword.
3861     // Check if obj is locked
3862     Node* locked_bit = MakeConX(markWord::unlocked_value);
3863     locked_bit = _gvn.transform(new AndXNode(locked_bit, mark));
3864     Node* cmp = _gvn.transform(new CmpXNode(locked_bit, MakeConX(0)));
3865     Node* is_unlocked = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
3866     IfNode* iff = new IfNode(control(), is_unlocked, PROB_MAX, COUNT_UNKNOWN);
3867     _gvn.transform(iff);
3868     Node* locked_region = new RegionNode(3);
3869     Node* mark_phi = new PhiNode(locked_region, TypeX_X);
3870 
3871     // Unlocked: Use bits from mark word
3872     locked_region->init_req(1, _gvn.transform(new IfTrueNode(iff)));
3873     mark_phi->init_req(1, mark);
3874 
3875     // Locked: Load prototype header from klass
3876     set_control(_gvn.transform(new IfFalseNode(iff)));
3877     // Make loads control dependent to make sure they are only executed if array is locked
3878     Node* klass_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
3879     Node* klass = _gvn.transform(LoadKlassNode::make(_gvn, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
3880     Node* proto_adr = basic_plus_adr(top(), klass, in_bytes(Klass::prototype_header_offset()));
3881     Node* proto = _gvn.transform(LoadNode::make(_gvn, control(), C->immutable_memory(), proto_adr, proto_adr->bottom_type()->is_ptr(), TypeX_X, TypeX_X->basic_type(), MemNode::unordered));
3882 
3883     locked_region->init_req(2, control());
3884     mark_phi->init_req(2, proto);
3885     set_control(_gvn.transform(locked_region));
3886     record_for_igvn(locked_region);
3887 
3888     mark = mark_phi;
3889   }
3890 
3891   // Now check if mark word bits are set
3892   Node* mask = MakeConX(mask_val);
3893   Node* masked = _gvn.transform(new AndXNode(_gvn.transform(mark), mask));
3894   record_for_igvn(masked); // Give it a chance to be optimized out by IGVN
3895   Node* cmp = _gvn.transform(new CmpXNode(masked, mask));
3896   return _gvn.transform(new BoolNode(cmp, eq ? BoolTest::eq : BoolTest::ne));
3897 }
3898 
3899 Node* GraphKit::inline_type_test(Node* obj, bool is_inline) {
3900   return mark_word_test(obj, markWord::inline_type_pattern, is_inline, /* check_lock = */ false);
3901 }
3902 
3903 Node* GraphKit::flat_array_test(Node* array_or_klass, bool flat) {
3904   // We can't use immutable memory here because the mark word is mutable.
3905   // PhaseIdealLoop::move_flat_array_check_out_of_loop will make sure the
3906   // check is moved out of loops (mainly to enable loop unswitching).
3907   Node* cmp = _gvn.transform(new FlatArrayCheckNode(C, memory(Compile::AliasIdxRaw), array_or_klass));
3908   record_for_igvn(cmp); // Give it a chance to be optimized out by IGVN
3909   return _gvn.transform(new BoolNode(cmp, flat ? BoolTest::eq : BoolTest::ne));
3910 }
3911 
3912 Node* GraphKit::null_free_array_test(Node* array, bool null_free) {
3913   return mark_word_test(array, markWord::null_free_array_bit_in_place, null_free);
3914 }
3915 
3916 Node* GraphKit::null_free_atomic_array_test(Node* array, ciInlineKlass* vk) {
3917   assert(vk->has_null_free_atomic_layout() || vk->has_null_free_non_atomic_layout(), "Can't be null-free and flat");
3918 
3919   // TODO 8350865 Add a stress flag to always access atomic if layout exists?
3920   if (!vk->has_null_free_non_atomic_layout()) {
3921     return intcon(1); // Always atomic
3922   } else if (!vk->has_null_free_atomic_layout()) {
3923     return intcon(0); // Never atomic
3924   }
3925 
3926   Node* array_klass = load_object_klass(array);
3927   int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3928   Node* layout_kind_addr = basic_plus_adr(top(), array_klass, layout_kind_offset);
3929   Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::INT, T_INT, MemNode::unordered);
3930   Node* cmp = _gvn.transform(new CmpINode(layout_kind, intcon((int)LayoutKind::NULL_FREE_ATOMIC_FLAT)));
3931   return _gvn.transform(new BoolNode(cmp, BoolTest::eq));
3932 }
3933 
3934 // Deoptimize if 'ary' is a null-free inline type array and 'val' is null
3935 Node* GraphKit::inline_array_null_guard(Node* ary, Node* val, int nargs, bool safe_for_replace) {
3936   RegionNode* region = new RegionNode(3);
3937   Node* null_ctl = top();
3938   null_check_oop(val, &null_ctl);
3939   if (null_ctl != top()) {
3940     PreserveJVMState pjvms(this);
3941     set_control(null_ctl);
3942     {
3943       // Deoptimize if null-free array
3944       BuildCutout unless(this, null_free_array_test(ary, /* null_free = */ false), PROB_MAX);
3945       inc_sp(nargs);
3946       uncommon_trap(Deoptimization::Reason_null_check,
3947                     Deoptimization::Action_none);
3948     }
3949     region->init_req(1, control());
3950   }
3951   region->init_req(2, control());
3952   set_control(_gvn.transform(region));
3953   record_for_igvn(region);
3954   if (_gvn.type(val) == TypePtr::NULL_PTR) {
3955     // Since we were just successfully storing null, the array can't be null free.
3956     const TypeAryPtr* ary_t = _gvn.type(ary)->is_aryptr();
3957     ary_t = ary_t->cast_to_not_null_free();
3958     Node* cast = _gvn.transform(new CheckCastPPNode(control(), ary, ary_t));
3959     if (safe_for_replace) {
3960       replace_in_map(ary, cast);
3961     }
3962     ary = cast;
3963   }
3964   return ary;
3965 }
3966 
3967 //------------------------------next_monitor-----------------------------------
3968 // What number should be given to the next monitor?
3969 int GraphKit::next_monitor() {
3970   int current = jvms()->monitor_depth()* C->sync_stack_slots();
3971   int next = current + C->sync_stack_slots();
3972   // Keep the toplevel high water mark current:
3973   if (C->fixed_slots() < next)  C->set_fixed_slots(next);
3974   return current;
3975 }
3976 
3977 //------------------------------insert_mem_bar---------------------------------
3978 // Memory barrier to avoid floating things around
3979 // The membar serves as a pinch point between both control and all memory slices.
3980 Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) {
3981   MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
3982   mb->init_req(TypeFunc::Control, control());
3983   mb->init_req(TypeFunc::Memory,  reset_memory());
3984   Node* membar = _gvn.transform(mb);
3985   record_for_igvn(membar);
3986   set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3987   set_all_memory_call(membar);
3988   return membar;
3989 }
3990 
3991 //-------------------------insert_mem_bar_volatile----------------------------
3992 // Memory barrier to avoid floating things around
3993 // The membar serves as a pinch point between both control and memory(alias_idx).
3994 // If you want to make a pinch point on all memory slices, do not use this
3995 // function (even with AliasIdxBot); use insert_mem_bar() instead.
3996 Node* GraphKit::insert_mem_bar_volatile(int opcode, int alias_idx, Node* precedent) {
3997   // When Parse::do_put_xxx updates a volatile field, it appends a series
3998   // of MemBarVolatile nodes, one for *each* volatile field alias category.
3999   // The first membar is on the same memory slice as the field store opcode.
4000   // This forces the membar to follow the store.  (Bug 6500685 broke this.)
4001   // All the other membars (for other volatile slices, including AliasIdxBot,
4002   // which stands for all unknown volatile slices) are control-dependent
4003   // on the first membar.  This prevents later volatile loads or stores
4004   // from sliding up past the just-emitted store.
4005 
4006   MemBarNode* mb = MemBarNode::make(C, opcode, alias_idx, precedent);
4007   mb->set_req(TypeFunc::Control,control());
4008   if (alias_idx == Compile::AliasIdxBot) {
4009     mb->set_req(TypeFunc::Memory, merged_memory()->base_memory());
4010   } else {
4011     assert(!(opcode == Op_Initialize && alias_idx != Compile::AliasIdxRaw), "fix caller");
4012     mb->set_req(TypeFunc::Memory, memory(alias_idx));
4013   }
4014   Node* membar = _gvn.transform(mb);
4015   record_for_igvn(membar);
4016   set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
4017   if (alias_idx == Compile::AliasIdxBot) {
4018     merged_memory()->set_base_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)));
4019   } else {
4020     set_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)),alias_idx);
4021   }
4022   return membar;
4023 }
4024 
4025 //------------------------------shared_lock------------------------------------
4026 // Emit locking code.
4027 FastLockNode* GraphKit::shared_lock(Node* obj) {
4028   // bci is either a monitorenter bc or InvocationEntryBci
4029   // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
4030   assert(SynchronizationEntryBCI == InvocationEntryBci, "");
4031 
4032   if (stopped())                // Dead monitor?
4033     return nullptr;
4034 
4035   assert(dead_locals_are_killed(), "should kill locals before sync. point");
4036 
4037   // Box the stack location
4038   Node* box = new BoxLockNode(next_monitor());
4039   // Check for bailout after new BoxLockNode
4040   if (failing()) { return nullptr; }
4041   box = _gvn.transform(box);
4042   Node* mem = reset_memory();
4043 
4044   FastLockNode * flock = _gvn.transform(new FastLockNode(nullptr, obj, box) )->as_FastLock();
4045 
4046   // Add monitor to debug info for the slow path.  If we block inside the
4047   // slow path and de-opt, we need the monitor hanging around
4048   map()->push_monitor( flock );
4049 
4050   const TypeFunc *tf = LockNode::lock_type();
4051   LockNode *lock = new LockNode(C, tf);
4052 
4053   lock->init_req( TypeFunc::Control, control() );
4054   lock->init_req( TypeFunc::Memory , mem );
4055   lock->init_req( TypeFunc::I_O    , top() )     ;   // does no i/o
4056   lock->init_req( TypeFunc::FramePtr, frameptr() );
4057   lock->init_req( TypeFunc::ReturnAdr, top() );
4058 
4059   lock->init_req(TypeFunc::Parms + 0, obj);
4060   lock->init_req(TypeFunc::Parms + 1, box);
4061   lock->init_req(TypeFunc::Parms + 2, flock);
4062   add_safepoint_edges(lock);
4063 
4064   lock = _gvn.transform( lock )->as_Lock();
4065 
4066   // lock has no side-effects, sets few values
4067   set_predefined_output_for_runtime_call(lock, mem, TypeRawPtr::BOTTOM);
4068 
4069   insert_mem_bar(Op_MemBarAcquireLock);
4070 
4071   // Add this to the worklist so that the lock can be eliminated
4072   record_for_igvn(lock);
4073 
4074 #ifndef PRODUCT
4075   if (PrintLockStatistics) {
4076     // Update the counter for this lock.  Don't bother using an atomic
4077     // operation since we don't require absolute accuracy.
4078     lock->create_lock_counter(map()->jvms());
4079     increment_counter(lock->counter()->addr());
4080   }
4081 #endif
4082 
4083   return flock;
4084 }
4085 
4086 
4087 //------------------------------shared_unlock----------------------------------
4088 // Emit unlocking code.
4089 void GraphKit::shared_unlock(Node* box, Node* obj) {
4090   // bci is either a monitorenter bc or InvocationEntryBci
4091   // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
4092   assert(SynchronizationEntryBCI == InvocationEntryBci, "");
4093 
4094   if (stopped()) {               // Dead monitor?
4095     map()->pop_monitor();        // Kill monitor from debug info
4096     return;
4097   }
4098   assert(!obj->is_InlineType(), "should not unlock on inline type");
4099 
4100   // Memory barrier to avoid floating things down past the locked region
4101   insert_mem_bar(Op_MemBarReleaseLock);
4102 
4103   const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type();
4104   UnlockNode *unlock = new UnlockNode(C, tf);
4105 #ifdef ASSERT
4106   unlock->set_dbg_jvms(sync_jvms());
4107 #endif
4108   uint raw_idx = Compile::AliasIdxRaw;
4109   unlock->init_req( TypeFunc::Control, control() );
4110   unlock->init_req( TypeFunc::Memory , memory(raw_idx) );
4111   unlock->init_req( TypeFunc::I_O    , top() )     ;   // does no i/o
4112   unlock->init_req( TypeFunc::FramePtr, frameptr() );
4113   unlock->init_req( TypeFunc::ReturnAdr, top() );
4114 
4115   unlock->init_req(TypeFunc::Parms + 0, obj);
4116   unlock->init_req(TypeFunc::Parms + 1, box);
4117   unlock = _gvn.transform(unlock)->as_Unlock();
4118 
4119   Node* mem = reset_memory();
4120 
4121   // unlock has no side-effects, sets few values
4122   set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM);
4123 
4124   // Kill monitor from debug info
4125   map()->pop_monitor( );
4126 }
4127 
4128 //-------------------------------get_layout_helper-----------------------------
4129 // If the given klass is a constant or known to be an array,
4130 // fetch the constant layout helper value into constant_value
4131 // and return null.  Otherwise, load the non-constant
4132 // layout helper value, and return the node which represents it.
4133 // This two-faced routine is useful because allocation sites
4134 // almost always feature constant types.
4135 Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) {
4136   const TypeKlassPtr* klass_t = _gvn.type(klass_node)->isa_klassptr();
4137   if (!StressReflectiveCode && klass_t != nullptr) {
4138     bool xklass = klass_t->klass_is_exact();
4139     bool can_be_flat = false;
4140     const TypeAryPtr* ary_type = klass_t->as_instance_type()->isa_aryptr();
4141     if (UseArrayFlattening && !xklass && ary_type != nullptr && !ary_type->is_null_free()) {
4142       // Don't constant fold if the runtime type might be a flat array but the static type is not.
4143       const TypeOopPtr* elem = ary_type->elem()->make_oopptr();
4144       can_be_flat = ary_type->can_be_inline_array() && (!elem->is_inlinetypeptr() || elem->inline_klass()->maybe_flat_in_array());
4145     }
4146     if (!can_be_flat && (xklass || (klass_t->isa_aryklassptr() && klass_t->is_aryklassptr()->elem() != Type::BOTTOM))) {
4147       jint lhelper;
4148       if (klass_t->is_flat()) {
4149         lhelper = ary_type->flat_layout_helper();
4150       } else if (klass_t->isa_aryklassptr()) {
4151         BasicType elem = ary_type->elem()->array_element_basic_type();
4152         if (is_reference_type(elem, true)) {
4153           elem = T_OBJECT;
4154         }
4155         lhelper = Klass::array_layout_helper(elem);
4156       } else {
4157         lhelper = klass_t->is_instklassptr()->exact_klass()->layout_helper();
4158       }
4159       if (lhelper != Klass::_lh_neutral_value) {
4160         constant_value = lhelper;
4161         return (Node*) nullptr;
4162       }
4163     }
4164   }
4165   constant_value = Klass::_lh_neutral_value;  // put in a known value
4166   Node* lhp = basic_plus_adr(top(), klass_node, in_bytes(Klass::layout_helper_offset()));
4167   return make_load(nullptr, lhp, TypeInt::INT, T_INT, MemNode::unordered);
4168 }
4169 
4170 // We just put in an allocate/initialize with a big raw-memory effect.
4171 // Hook selected additional alias categories on the initialization.
4172 static void hook_memory_on_init(GraphKit& kit, int alias_idx,
4173                                 MergeMemNode* init_in_merge,
4174                                 Node* init_out_raw) {
4175   DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory());
4176   assert(init_in_merge->memory_at(alias_idx) == init_in_raw, "");
4177 
4178   Node* prevmem = kit.memory(alias_idx);
4179   init_in_merge->set_memory_at(alias_idx, prevmem);
4180   if (init_out_raw != nullptr) {
4181     kit.set_memory(init_out_raw, alias_idx);
4182   }
4183 }
4184 
4185 //---------------------------set_output_for_allocation-------------------------
4186 Node* GraphKit::set_output_for_allocation(AllocateNode* alloc,
4187                                           const TypeOopPtr* oop_type,
4188                                           bool deoptimize_on_exception) {
4189   int rawidx = Compile::AliasIdxRaw;
4190   alloc->set_req( TypeFunc::FramePtr, frameptr() );
4191   add_safepoint_edges(alloc);
4192   Node* allocx = _gvn.transform(alloc);
4193   set_control( _gvn.transform(new ProjNode(allocx, TypeFunc::Control) ) );
4194   // create memory projection for i_o
4195   set_memory ( _gvn.transform( new ProjNode(allocx, TypeFunc::Memory, true) ), rawidx );
4196   make_slow_call_ex(allocx, env()->Throwable_klass(), true, deoptimize_on_exception);
4197 
4198   // create a memory projection as for the normal control path
4199   Node* malloc = _gvn.transform(new ProjNode(allocx, TypeFunc::Memory));
4200   set_memory(malloc, rawidx);
4201 
4202   // a normal slow-call doesn't change i_o, but an allocation does
4203   // we create a separate i_o projection for the normal control path
4204   set_i_o(_gvn.transform( new ProjNode(allocx, TypeFunc::I_O, false) ) );
4205   Node* rawoop = _gvn.transform( new ProjNode(allocx, TypeFunc::Parms) );
4206 
4207   // put in an initialization barrier
4208   InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx,
4209                                                  rawoop)->as_Initialize();
4210   assert(alloc->initialization() == init,  "2-way macro link must work");
4211   assert(init ->allocation()     == alloc, "2-way macro link must work");
4212   {
4213     // Extract memory strands which may participate in the new object's
4214     // initialization, and source them from the new InitializeNode.
4215     // This will allow us to observe initializations when they occur,
4216     // and link them properly (as a group) to the InitializeNode.
4217     assert(init->in(InitializeNode::Memory) == malloc, "");
4218     MergeMemNode* minit_in = MergeMemNode::make(malloc);
4219     init->set_req(InitializeNode::Memory, minit_in);
4220     record_for_igvn(minit_in); // fold it up later, if possible
4221     _gvn.set_type(minit_in, Type::MEMORY);
4222     Node* minit_out = memory(rawidx);
4223     assert(minit_out->is_Proj() && minit_out->in(0) == init, "");
4224     int mark_idx = C->get_alias_index(oop_type->add_offset(oopDesc::mark_offset_in_bytes()));
4225     // Add an edge in the MergeMem for the header fields so an access to one of those has correct memory state.
4226     // Use one NarrowMemProjNode per slice to properly record the adr type of each slice. The Initialize node will have
4227     // multiple projections as a result.
4228     set_memory(_gvn.transform(new NarrowMemProjNode(init, C->get_adr_type(mark_idx))), mark_idx);
4229     int klass_idx = C->get_alias_index(oop_type->add_offset(oopDesc::klass_offset_in_bytes()));
4230     set_memory(_gvn.transform(new NarrowMemProjNode(init, C->get_adr_type(klass_idx))), klass_idx);
4231     if (oop_type->isa_aryptr()) {
4232       // Initially all flat array accesses share a single slice
4233       // but that changes after parsing. Prepare the memory graph so
4234       // it can optimize flat array accesses properly once they
4235       // don't share a single slice.
4236       assert(C->flat_accesses_share_alias(), "should be set at parse time");
4237       const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot);
4238       int            elemidx  = C->get_alias_index(telemref);
4239       const TypePtr* alias_adr_type = C->get_adr_type(elemidx);
4240       if (alias_adr_type->is_flat()) {
4241         C->set_flat_accesses();
4242       }
4243       hook_memory_on_init(*this, elemidx, minit_in, _gvn.transform(new NarrowMemProjNode(init, alias_adr_type)));
4244     } else if (oop_type->isa_instptr()) {
4245       ciInstanceKlass* ik = oop_type->is_instptr()->instance_klass();
4246       for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) {
4247         ciField* field = ik->nonstatic_field_at(i);
4248         if (field->offset_in_bytes() >= TrackedInitializationLimit * HeapWordSize)
4249           continue;  // do not bother to track really large numbers of fields
4250         // Find (or create) the alias category for this field:
4251         int fieldidx = C->alias_type(field)->index();
4252         hook_memory_on_init(*this, fieldidx, minit_in, _gvn.transform(new NarrowMemProjNode(init, C->get_adr_type(fieldidx))));
4253       }
4254     }
4255   }
4256 
4257   // Cast raw oop to the real thing...
4258   Node* javaoop = new CheckCastPPNode(control(), rawoop, oop_type);
4259   javaoop = _gvn.transform(javaoop);
4260   C->set_recent_alloc(control(), javaoop);
4261   assert(just_allocated_object(control()) == javaoop, "just allocated");
4262 
4263 #ifdef ASSERT
4264   { // Verify that the AllocateNode::Ideal_allocation recognizers work:
4265     assert(AllocateNode::Ideal_allocation(rawoop) == alloc,
4266            "Ideal_allocation works");
4267     assert(AllocateNode::Ideal_allocation(javaoop) == alloc,
4268            "Ideal_allocation works");
4269     if (alloc->is_AllocateArray()) {
4270       assert(AllocateArrayNode::Ideal_array_allocation(rawoop) == alloc->as_AllocateArray(),
4271              "Ideal_allocation works");
4272       assert(AllocateArrayNode::Ideal_array_allocation(javaoop) == alloc->as_AllocateArray(),
4273              "Ideal_allocation works");
4274     } else {
4275       assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please");
4276     }
4277   }
4278 #endif //ASSERT
4279 
4280   return javaoop;
4281 }
4282 
4283 //---------------------------new_instance--------------------------------------
4284 // This routine takes a klass_node which may be constant (for a static type)
4285 // or may be non-constant (for reflective code).  It will work equally well
4286 // for either, and the graph will fold nicely if the optimizer later reduces
4287 // the type to a constant.
4288 // The optional arguments are for specialized use by intrinsics:
4289 //  - If 'extra_slow_test' if not null is an extra condition for the slow-path.
4290 //  - If 'return_size_val', report the total object size to the caller.
4291 //  - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
4292 Node* GraphKit::new_instance(Node* klass_node,
4293                              Node* extra_slow_test,
4294                              Node* *return_size_val,
4295                              bool deoptimize_on_exception,
4296                              InlineTypeNode* inline_type_node) {
4297   // Compute size in doublewords
4298   // The size is always an integral number of doublewords, represented
4299   // as a positive bytewise size stored in the klass's layout_helper.
4300   // The layout_helper also encodes (in a low bit) the need for a slow path.
4301   jint  layout_con = Klass::_lh_neutral_value;
4302   Node* layout_val = get_layout_helper(klass_node, layout_con);
4303   bool  layout_is_con = (layout_val == nullptr);
4304 
4305   if (extra_slow_test == nullptr)  extra_slow_test = intcon(0);
4306   // Generate the initial go-slow test.  It's either ALWAYS (return a
4307   // Node for 1) or NEVER (return a null) or perhaps (in the reflective
4308   // case) a computed value derived from the layout_helper.
4309   Node* initial_slow_test = nullptr;
4310   if (layout_is_con) {
4311     assert(!StressReflectiveCode, "stress mode does not use these paths");
4312     bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con);
4313     initial_slow_test = must_go_slow ? intcon(1) : extra_slow_test;
4314   } else {   // reflective case
4315     // This reflective path is used by Unsafe.allocateInstance.
4316     // (It may be stress-tested by specifying StressReflectiveCode.)
4317     // Basically, we want to get into the VM is there's an illegal argument.
4318     Node* bit = intcon(Klass::_lh_instance_slow_path_bit);
4319     initial_slow_test = _gvn.transform( new AndINode(layout_val, bit) );
4320     if (extra_slow_test != intcon(0)) {
4321       initial_slow_test = _gvn.transform( new OrINode(initial_slow_test, extra_slow_test) );
4322     }
4323     // (Macro-expander will further convert this to a Bool, if necessary.)
4324   }
4325 
4326   // Find the size in bytes.  This is easy; it's the layout_helper.
4327   // The size value must be valid even if the slow path is taken.
4328   Node* size = nullptr;
4329   if (layout_is_con) {
4330     size = MakeConX(Klass::layout_helper_size_in_bytes(layout_con));
4331   } else {   // reflective case
4332     // This reflective path is used by clone and Unsafe.allocateInstance.
4333     size = ConvI2X(layout_val);
4334 
4335     // Clear the low bits to extract layout_helper_size_in_bytes:
4336     assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
4337     Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong));
4338     size = _gvn.transform( new AndXNode(size, mask) );
4339   }
4340   if (return_size_val != nullptr) {
4341     (*return_size_val) = size;
4342   }
4343 
4344   // This is a precise notnull oop of the klass.
4345   // (Actually, it need not be precise if this is a reflective allocation.)
4346   // It's what we cast the result to.
4347   const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr();
4348   if (!tklass)  tklass = TypeInstKlassPtr::OBJECT;
4349   const TypeOopPtr* oop_type = tklass->as_instance_type();
4350 
4351   // Now generate allocation code
4352 
4353   // The entire memory state is needed for slow path of the allocation
4354   // since GC and deoptimization can happen.
4355   Node *mem = reset_memory();
4356   set_all_memory(mem); // Create new memory state
4357 
4358   AllocateNode* alloc = new AllocateNode(C, AllocateNode::alloc_type(Type::TOP),
4359                                          control(), mem, i_o(),
4360                                          size, klass_node,
4361                                          initial_slow_test, inline_type_node);
4362 
4363   return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception);
4364 }
4365 
4366 //-------------------------------new_array-------------------------------------
4367 // helper for newarray and anewarray
4368 // The 'length' parameter is (obviously) the length of the array.
4369 // The optional arguments are for specialized use by intrinsics:
4370 //  - If 'return_size_val', report the non-padded array size (sum of header size
4371 //    and array body) to the caller.
4372 //  - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
4373 Node* GraphKit::new_array(Node* klass_node,     // array klass (maybe variable)
4374                           Node* length,         // number of array elements
4375                           int   nargs,          // number of arguments to push back for uncommon trap
4376                           Node* *return_size_val,
4377                           bool deoptimize_on_exception,
4378                           Node* init_val) {
4379   jint  layout_con = Klass::_lh_neutral_value;
4380   Node* layout_val = get_layout_helper(klass_node, layout_con);
4381   bool  layout_is_con = (layout_val == nullptr);
4382 
4383   if (!layout_is_con && !StressReflectiveCode &&
4384       !too_many_traps(Deoptimization::Reason_class_check)) {
4385     // This is a reflective array creation site.
4386     // Optimistically assume that it is a subtype of Object[],
4387     // so that we can fold up all the address arithmetic.
4388     layout_con = Klass::array_layout_helper(T_OBJECT);
4389     Node* cmp_lh = _gvn.transform( new CmpINode(layout_val, intcon(layout_con)) );
4390     Node* bol_lh = _gvn.transform( new BoolNode(cmp_lh, BoolTest::eq) );
4391     { BuildCutout unless(this, bol_lh, PROB_MAX);
4392       inc_sp(nargs);
4393       uncommon_trap(Deoptimization::Reason_class_check,
4394                     Deoptimization::Action_maybe_recompile);
4395     }
4396     layout_val = nullptr;
4397     layout_is_con = true;
4398   }
4399 
4400   // Generate the initial go-slow test.  Make sure we do not overflow
4401   // if length is huge (near 2Gig) or negative!  We do not need
4402   // exact double-words here, just a close approximation of needed
4403   // double-words.  We can't add any offset or rounding bits, lest we
4404   // take a size -1 of bytes and make it positive.  Use an unsigned
4405   // compare, so negative sizes look hugely positive.
4406   int fast_size_limit = FastAllocateSizeLimit;
4407   if (layout_is_con) {
4408     assert(!StressReflectiveCode, "stress mode does not use these paths");
4409     // Increase the size limit if we have exact knowledge of array type.
4410     int log2_esize = Klass::layout_helper_log2_element_size(layout_con);
4411     fast_size_limit <<= MAX2(LogBytesPerLong - log2_esize, 0);
4412   }
4413 
4414   Node* initial_slow_cmp  = _gvn.transform( new CmpUNode( length, intcon( fast_size_limit ) ) );
4415   Node* initial_slow_test = _gvn.transform( new BoolNode( initial_slow_cmp, BoolTest::gt ) );
4416 
4417   // --- Size Computation ---
4418   // array_size = round_to_heap(array_header + (length << elem_shift));
4419   // where round_to_heap(x) == align_to(x, MinObjAlignmentInBytes)
4420   // and align_to(x, y) == ((x + y-1) & ~(y-1))
4421   // The rounding mask is strength-reduced, if possible.
4422   int round_mask = MinObjAlignmentInBytes - 1;
4423   Node* header_size = nullptr;
4424   // (T_BYTE has the weakest alignment and size restrictions...)
4425   if (layout_is_con) {
4426     int       hsize  = Klass::layout_helper_header_size(layout_con);
4427     int       eshift = Klass::layout_helper_log2_element_size(layout_con);
4428     bool is_flat_array = Klass::layout_helper_is_flatArray(layout_con);
4429     if ((round_mask & ~right_n_bits(eshift)) == 0)
4430       round_mask = 0;  // strength-reduce it if it goes away completely
4431     assert(is_flat_array || (hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
4432     int header_size_min = arrayOopDesc::base_offset_in_bytes(T_BYTE);
4433     assert(header_size_min <= hsize, "generic minimum is smallest");
4434     header_size = intcon(hsize);
4435   } else {
4436     Node* hss   = intcon(Klass::_lh_header_size_shift);
4437     Node* hsm   = intcon(Klass::_lh_header_size_mask);
4438     header_size = _gvn.transform(new URShiftINode(layout_val, hss));
4439     header_size = _gvn.transform(new AndINode(header_size, hsm));
4440   }
4441 
4442   Node* elem_shift = nullptr;
4443   if (layout_is_con) {
4444     int eshift = Klass::layout_helper_log2_element_size(layout_con);
4445     if (eshift != 0)
4446       elem_shift = intcon(eshift);
4447   } else {
4448     // There is no need to mask or shift this value.
4449     // The semantics of LShiftINode include an implicit mask to 0x1F.
4450     assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
4451     elem_shift = layout_val;
4452   }
4453 
4454   // Transition to native address size for all offset calculations:
4455   Node* lengthx = ConvI2X(length);
4456   Node* headerx = ConvI2X(header_size);
4457 #ifdef _LP64
4458   { const TypeInt* tilen = _gvn.find_int_type(length);
4459     if (tilen != nullptr && tilen->_lo < 0) {
4460       // Add a manual constraint to a positive range.  Cf. array_element_address.
4461       jint size_max = fast_size_limit;
4462       if (size_max > tilen->_hi && tilen->_hi >= 0) {
4463         size_max = tilen->_hi;
4464       }
4465       const TypeInt* tlcon = TypeInt::make(0, size_max, Type::WidenMin);
4466 
4467       // Only do a narrow I2L conversion if the range check passed.
4468       IfNode* iff = new IfNode(control(), initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
4469       _gvn.transform(iff);
4470       RegionNode* region = new RegionNode(3);
4471       _gvn.set_type(region, Type::CONTROL);
4472       lengthx = new PhiNode(region, TypeLong::LONG);
4473       _gvn.set_type(lengthx, TypeLong::LONG);
4474 
4475       // Range check passed. Use ConvI2L node with narrow type.
4476       Node* passed = IfFalse(iff);
4477       region->init_req(1, passed);
4478       // Make I2L conversion control dependent to prevent it from
4479       // floating above the range check during loop optimizations.
4480       lengthx->init_req(1, C->constrained_convI2L(&_gvn, length, tlcon, passed));
4481 
4482       // Range check failed. Use ConvI2L with wide type because length may be invalid.
4483       region->init_req(2, IfTrue(iff));
4484       lengthx->init_req(2, ConvI2X(length));
4485 
4486       set_control(region);
4487       record_for_igvn(region);
4488       record_for_igvn(lengthx);
4489     }
4490   }
4491 #endif
4492 
4493   // Combine header size and body size for the array copy part, then align (if
4494   // necessary) for the allocation part. This computation cannot overflow,
4495   // because it is used only in two places, one where the length is sharply
4496   // limited, and the other after a successful allocation.
4497   Node* abody = lengthx;
4498   if (elem_shift != nullptr) {
4499     abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
4500   }
4501   Node* non_rounded_size = _gvn.transform(new AddXNode(headerx, abody));
4502 
4503   if (return_size_val != nullptr) {
4504     // This is the size
4505     (*return_size_val) = non_rounded_size;
4506   }
4507 
4508   Node* size = non_rounded_size;
4509   if (round_mask != 0) {
4510     Node* mask1 = MakeConX(round_mask);
4511     size = _gvn.transform(new AddXNode(size, mask1));
4512     Node* mask2 = MakeConX(~round_mask);
4513     size = _gvn.transform(new AndXNode(size, mask2));
4514   }
4515   // else if round_mask == 0, the size computation is self-rounding
4516 
4517   // Now generate allocation code
4518 
4519   // The entire memory state is needed for slow path of the allocation
4520   // since GC and deoptimization can happen.
4521   Node *mem = reset_memory();
4522   set_all_memory(mem); // Create new memory state
4523 
4524   if (initial_slow_test->is_Bool()) {
4525     // Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick.
4526     initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn);
4527   }
4528 
4529   const TypeKlassPtr* ary_klass = _gvn.type(klass_node)->isa_klassptr();
4530   const TypeOopPtr* ary_type = ary_klass->as_instance_type();
4531 
4532   Node* raw_init_value = nullptr;
4533   if (init_val != nullptr) {
4534     // TODO 8350865 Fast non-zero init not implemented yet for flat, null-free arrays
4535     if (ary_type->is_flat()) {
4536       initial_slow_test = intcon(1);
4537     }
4538 
4539     if (UseCompressedOops) {
4540       // With compressed oops, the 64-bit init value is built from two 32-bit compressed oops
4541       init_val = _gvn.transform(new EncodePNode(init_val, init_val->bottom_type()->make_narrowoop()));
4542       Node* lower = _gvn.transform(new CastP2XNode(control(), init_val));
4543       Node* upper = _gvn.transform(new LShiftLNode(lower, intcon(32)));
4544       raw_init_value = _gvn.transform(new OrLNode(lower, upper));
4545     } else {
4546       raw_init_value = _gvn.transform(new CastP2XNode(control(), init_val));
4547     }
4548   }
4549 
4550   Node* valid_length_test = _gvn.intcon(1);
4551   if (ary_type->isa_aryptr()) {
4552     BasicType bt = ary_type->isa_aryptr()->elem()->array_element_basic_type();
4553     jint max = TypeAryPtr::max_array_length(bt);
4554     Node* valid_length_cmp  = _gvn.transform(new CmpUNode(length, intcon(max)));
4555     valid_length_test = _gvn.transform(new BoolNode(valid_length_cmp, BoolTest::le));
4556   }
4557 
4558   // Create the AllocateArrayNode and its result projections
4559   AllocateArrayNode* alloc
4560     = new AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT),
4561                             control(), mem, i_o(),
4562                             size, klass_node,
4563                             initial_slow_test,
4564                             length, valid_length_test,
4565                             init_val, raw_init_value);
4566   // Cast to correct type.  Note that the klass_node may be constant or not,
4567   // and in the latter case the actual array type will be inexact also.
4568   // (This happens via a non-constant argument to inline_native_newArray.)
4569   // In any case, the value of klass_node provides the desired array type.
4570   const TypeInt* length_type = _gvn.find_int_type(length);
4571   if (ary_type->isa_aryptr() && length_type != nullptr) {
4572     // Try to get a better type than POS for the size
4573     ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
4574   }
4575 
4576   Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception);
4577 
4578   array_ideal_length(alloc, ary_type, true);
4579   return javaoop;
4580 }
4581 
4582 // The following "Ideal_foo" functions are placed here because they recognize
4583 // the graph shapes created by the functions immediately above.
4584 
4585 //---------------------------Ideal_allocation----------------------------------
4586 // Given an oop pointer or raw pointer, see if it feeds from an AllocateNode.
4587 AllocateNode* AllocateNode::Ideal_allocation(Node* ptr) {
4588   if (ptr == nullptr) {     // reduce dumb test in callers
4589     return nullptr;
4590   }
4591 
4592   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
4593   ptr = bs->step_over_gc_barrier(ptr);
4594 
4595   if (ptr->is_CheckCastPP()) { // strip only one raw-to-oop cast
4596     ptr = ptr->in(1);
4597     if (ptr == nullptr) return nullptr;
4598   }
4599   // Return null for allocations with several casts:
4600   //   j.l.reflect.Array.newInstance(jobject, jint)
4601   //   Object.clone()
4602   // to keep more precise type from last cast.
4603   if (ptr->is_Proj()) {
4604     Node* allo = ptr->in(0);
4605     if (allo != nullptr && allo->is_Allocate()) {
4606       return allo->as_Allocate();
4607     }
4608   }
4609   // Report failure to match.
4610   return nullptr;
4611 }
4612 
4613 // Fancy version which also strips off an offset (and reports it to caller).
4614 AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseValues* phase,
4615                                              intptr_t& offset) {
4616   Node* base = AddPNode::Ideal_base_and_offset(ptr, phase, offset);
4617   if (base == nullptr)  return nullptr;
4618   return Ideal_allocation(base);
4619 }
4620 
4621 // Trace Initialize <- Proj[Parm] <- Allocate
4622 AllocateNode* InitializeNode::allocation() {
4623   Node* rawoop = in(InitializeNode::RawAddress);
4624   if (rawoop->is_Proj()) {
4625     Node* alloc = rawoop->in(0);
4626     if (alloc->is_Allocate()) {
4627       return alloc->as_Allocate();
4628     }
4629   }
4630   return nullptr;
4631 }
4632 
4633 // Trace Allocate -> Proj[Parm] -> Initialize
4634 InitializeNode* AllocateNode::initialization() {
4635   ProjNode* rawoop = proj_out_or_null(AllocateNode::RawAddress);
4636   if (rawoop == nullptr)  return nullptr;
4637   for (DUIterator_Fast imax, i = rawoop->fast_outs(imax); i < imax; i++) {
4638     Node* init = rawoop->fast_out(i);
4639     if (init->is_Initialize()) {
4640       assert(init->as_Initialize()->allocation() == this, "2-way link");
4641       return init->as_Initialize();
4642     }
4643   }
4644   return nullptr;
4645 }
4646 
4647 // Add a Parse Predicate with an uncommon trap on the failing/false path. Normal control will continue on the true path.
4648 void GraphKit::add_parse_predicate(Deoptimization::DeoptReason reason, const int nargs) {
4649   // Too many traps seen?
4650   if (too_many_traps(reason)) {
4651 #ifdef ASSERT
4652     if (TraceLoopPredicate) {
4653       int tc = C->trap_count(reason);
4654       tty->print("too many traps=%s tcount=%d in ",
4655                     Deoptimization::trap_reason_name(reason), tc);
4656       method()->print(); // which method has too many predicate traps
4657       tty->cr();
4658     }
4659 #endif
4660     // We cannot afford to take more traps here,
4661     // do not generate Parse Predicate.
4662     return;
4663   }
4664 
4665   ParsePredicateNode* parse_predicate = new ParsePredicateNode(control(), reason, &_gvn);
4666   _gvn.set_type(parse_predicate, parse_predicate->Value(&_gvn));
4667   Node* if_false = _gvn.transform(new IfFalseNode(parse_predicate));
4668   {
4669     PreserveJVMState pjvms(this);
4670     set_control(if_false);
4671     inc_sp(nargs);
4672     uncommon_trap(reason, Deoptimization::Action_maybe_recompile);
4673   }
4674   Node* if_true = _gvn.transform(new IfTrueNode(parse_predicate));
4675   set_control(if_true);
4676 }
4677 
4678 // Add Parse Predicates which serve as placeholders to create new Runtime Predicates above them. All
4679 // Runtime Predicates inside a Runtime Predicate block share the same uncommon trap as the Parse Predicate.
4680 void GraphKit::add_parse_predicates(int nargs) {
4681   if (ShortRunningLongLoop) {
4682     // Will narrow the limit down with a cast node. Predicates added later may depend on the cast so should be last when
4683     // walking up from the loop.
4684     add_parse_predicate(Deoptimization::Reason_short_running_long_loop, nargs);
4685   }
4686   if (UseLoopPredicate) {
4687     add_parse_predicate(Deoptimization::Reason_predicate, nargs);
4688     if (UseProfiledLoopPredicate) {
4689       add_parse_predicate(Deoptimization::Reason_profile_predicate, nargs);
4690     }
4691   }
4692   if (UseAutoVectorizationPredicate) {
4693     add_parse_predicate(Deoptimization::Reason_auto_vectorization_check, nargs);
4694   }
4695   // Loop Limit Check Predicate should be near the loop.
4696   add_parse_predicate(Deoptimization::Reason_loop_limit_check, nargs);
4697 }
4698 
4699 void GraphKit::sync_kit(IdealKit& ideal) {
4700   reset_memory();
4701   set_all_memory(ideal.merged_memory());
4702   set_i_o(ideal.i_o());
4703   set_control(ideal.ctrl());
4704 }
4705 
4706 void GraphKit::final_sync(IdealKit& ideal) {
4707   // Final sync IdealKit and graphKit.
4708   sync_kit(ideal);
4709 }
4710 
4711 Node* GraphKit::load_String_length(Node* str, bool set_ctrl) {
4712   Node* len = load_array_length(load_String_value(str, set_ctrl));
4713   Node* coder = load_String_coder(str, set_ctrl);
4714   // Divide length by 2 if coder is UTF16
4715   return _gvn.transform(new RShiftINode(len, coder));
4716 }
4717 
4718 Node* GraphKit::load_String_value(Node* str, bool set_ctrl) {
4719   int value_offset = java_lang_String::value_offset();
4720   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4721                                                      false, nullptr, Type::Offset(0));
4722   const TypePtr* value_field_type = string_type->add_offset(value_offset);
4723   const TypeAryPtr* value_type = TypeAryPtr::make(TypePtr::NotNull,
4724                                                   TypeAry::make(TypeInt::BYTE, TypeInt::POS, false, false, true, true, true),
4725                                                   ciTypeArrayKlass::make(T_BYTE), true, Type::Offset(0));
4726   Node* p = basic_plus_adr(str, str, value_offset);
4727   Node* load = access_load_at(str, p, value_field_type, value_type, T_OBJECT,
4728                               IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4729   return load;
4730 }
4731 
4732 Node* GraphKit::load_String_coder(Node* str, bool set_ctrl) {
4733   if (!CompactStrings) {
4734     return intcon(java_lang_String::CODER_UTF16);
4735   }
4736   int coder_offset = java_lang_String::coder_offset();
4737   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4738                                                      false, nullptr, Type::Offset(0));
4739   const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4740 
4741   Node* p = basic_plus_adr(str, str, coder_offset);
4742   Node* load = access_load_at(str, p, coder_field_type, TypeInt::BYTE, T_BYTE,
4743                               IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4744   return load;
4745 }
4746 
4747 void GraphKit::store_String_value(Node* str, Node* value) {
4748   int value_offset = java_lang_String::value_offset();
4749   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4750                                                      false, nullptr, Type::Offset(0));
4751   const TypePtr* value_field_type = string_type->add_offset(value_offset);
4752 
4753   access_store_at(str,  basic_plus_adr(str, value_offset), value_field_type,
4754                   value, TypeAryPtr::BYTES, T_OBJECT, IN_HEAP | MO_UNORDERED);
4755 }
4756 
4757 void GraphKit::store_String_coder(Node* str, Node* value) {
4758   int coder_offset = java_lang_String::coder_offset();
4759   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4760                                                      false, nullptr, Type::Offset(0));
4761   const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4762 
4763   access_store_at(str, basic_plus_adr(str, coder_offset), coder_field_type,
4764                   value, TypeInt::BYTE, T_BYTE, IN_HEAP | MO_UNORDERED);
4765 }
4766 
4767 // Capture src and dst memory state with a MergeMemNode
4768 Node* GraphKit::capture_memory(const TypePtr* src_type, const TypePtr* dst_type) {
4769   if (src_type == dst_type) {
4770     // Types are equal, we don't need a MergeMemNode
4771     return memory(src_type);
4772   }
4773   MergeMemNode* merge = MergeMemNode::make(map()->memory());
4774   record_for_igvn(merge); // fold it up later, if possible
4775   int src_idx = C->get_alias_index(src_type);
4776   int dst_idx = C->get_alias_index(dst_type);
4777   merge->set_memory_at(src_idx, memory(src_idx));
4778   merge->set_memory_at(dst_idx, memory(dst_idx));
4779   return merge;
4780 }
4781 
4782 Node* GraphKit::compress_string(Node* src, const TypeAryPtr* src_type, Node* dst, Node* count) {
4783   assert(Matcher::match_rule_supported(Op_StrCompressedCopy), "Intrinsic not supported");
4784   assert(src_type == TypeAryPtr::BYTES || src_type == TypeAryPtr::CHARS, "invalid source type");
4785   // If input and output memory types differ, capture both states to preserve
4786   // the dependency between preceding and subsequent loads/stores.
4787   // For example, the following program:
4788   //  StoreB
4789   //  compress_string
4790   //  LoadB
4791   // has this memory graph (use->def):
4792   //  LoadB -> compress_string -> CharMem
4793   //             ... -> StoreB -> ByteMem
4794   // The intrinsic hides the dependency between LoadB and StoreB, causing
4795   // the load to read from memory not containing the result of the StoreB.
4796   // The correct memory graph should look like this:
4797   //  LoadB -> compress_string -> MergeMem(CharMem, StoreB(ByteMem))
4798   Node* mem = capture_memory(src_type, TypeAryPtr::BYTES);
4799   StrCompressedCopyNode* str = new StrCompressedCopyNode(control(), mem, src, dst, count);
4800   Node* res_mem = _gvn.transform(new SCMemProjNode(_gvn.transform(str)));
4801   set_memory(res_mem, TypeAryPtr::BYTES);
4802   return str;
4803 }
4804 
4805 void GraphKit::inflate_string(Node* src, Node* dst, const TypeAryPtr* dst_type, Node* count) {
4806   assert(Matcher::match_rule_supported(Op_StrInflatedCopy), "Intrinsic not supported");
4807   assert(dst_type == TypeAryPtr::BYTES || dst_type == TypeAryPtr::CHARS, "invalid dest type");
4808   // Capture src and dst memory (see comment in 'compress_string').
4809   Node* mem = capture_memory(TypeAryPtr::BYTES, dst_type);
4810   StrInflatedCopyNode* str = new StrInflatedCopyNode(control(), mem, src, dst, count);
4811   set_memory(_gvn.transform(str), dst_type);
4812 }
4813 
4814 void GraphKit::inflate_string_slow(Node* src, Node* dst, Node* start, Node* count) {
4815   /**
4816    * int i_char = start;
4817    * for (int i_byte = 0; i_byte < count; i_byte++) {
4818    *   dst[i_char++] = (char)(src[i_byte] & 0xff);
4819    * }
4820    */
4821   add_parse_predicates();
4822   C->set_has_loops(true);
4823 
4824   RegionNode* head = new RegionNode(3);
4825   head->init_req(1, control());
4826   gvn().set_type(head, Type::CONTROL);
4827   record_for_igvn(head);
4828 
4829   Node* i_byte = new PhiNode(head, TypeInt::INT);
4830   i_byte->init_req(1, intcon(0));
4831   gvn().set_type(i_byte, TypeInt::INT);
4832   record_for_igvn(i_byte);
4833 
4834   Node* i_char = new PhiNode(head, TypeInt::INT);
4835   i_char->init_req(1, start);
4836   gvn().set_type(i_char, TypeInt::INT);
4837   record_for_igvn(i_char);
4838 
4839   Node* mem = PhiNode::make(head, memory(TypeAryPtr::BYTES), Type::MEMORY, TypeAryPtr::BYTES);
4840   gvn().set_type(mem, Type::MEMORY);
4841   record_for_igvn(mem);
4842   set_control(head);
4843   set_memory(mem, TypeAryPtr::BYTES);
4844   Node* ch = load_array_element(src, i_byte, TypeAryPtr::BYTES, /* set_ctrl */ true);
4845   Node* st = store_to_memory(control(), array_element_address(dst, i_char, T_BYTE),
4846                              AndI(ch, intcon(0xff)), T_CHAR, MemNode::unordered, false,
4847                              false, true /* mismatched */);
4848 
4849   IfNode* iff = create_and_map_if(head, Bool(CmpI(i_byte, count), BoolTest::lt), PROB_FAIR, COUNT_UNKNOWN);
4850   head->init_req(2, IfTrue(iff));
4851   mem->init_req(2, st);
4852   i_byte->init_req(2, AddI(i_byte, intcon(1)));
4853   i_char->init_req(2, AddI(i_char, intcon(2)));
4854 
4855   set_control(IfFalse(iff));
4856   set_memory(st, TypeAryPtr::BYTES);
4857 }
4858 
4859 Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) {
4860   if (!field->is_constant()) {
4861     return nullptr; // Field not marked as constant.
4862   }
4863   ciInstance* holder = nullptr;
4864   if (!field->is_static()) {
4865     ciObject* const_oop = obj->bottom_type()->is_oopptr()->const_oop();
4866     if (const_oop != nullptr && const_oop->is_instance()) {
4867       holder = const_oop->as_instance();
4868     }
4869   }
4870   const Type* con_type = Type::make_constant_from_field(field, holder, field->layout_type(),
4871                                                         /*is_unsigned_load=*/false);
4872   if (con_type != nullptr) {
4873     Node* con = makecon(con_type);
4874     if (field->type()->is_inlinetype()) {
4875       con = InlineTypeNode::make_from_oop(this, con, field->type()->as_inline_klass());
4876     } else if (con_type->is_inlinetypeptr()) {
4877       con = InlineTypeNode::make_from_oop(this, con, con_type->inline_klass());
4878     }
4879     return con;
4880   }
4881   return nullptr;
4882 }
4883 
4884 Node* GraphKit::maybe_narrow_object_type(Node* obj, ciKlass* type, bool maybe_larval) {
4885   const Type* obj_type = obj->bottom_type();
4886   const TypeOopPtr* sig_type = TypeOopPtr::make_from_klass(type);
4887   if (obj_type->isa_oopptr() && sig_type->is_loaded() && !obj_type->higher_equal(sig_type)) {
4888     const Type* narrow_obj_type = obj_type->filter_speculative(sig_type); // keep speculative part
4889     Node* casted_obj = gvn().transform(new CheckCastPPNode(control(), obj, narrow_obj_type));
4890     obj = casted_obj;
4891   }
4892   if (!maybe_larval && sig_type->is_inlinetypeptr()) {
4893     obj = InlineTypeNode::make_from_oop(this, obj, sig_type->inline_klass());
4894   }
4895   return obj;
4896 }