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