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