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