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