1 /*
   2  * Copyright (c) 2012, 2021, 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/ciFlatArrayKlass.hpp"
  27 #include "gc/shared/barrierSet.hpp"
  28 #include "gc/shared/tlab_globals.hpp"
  29 #include "opto/arraycopynode.hpp"
  30 #include "oops/objArrayKlass.hpp"
  31 #include "opto/convertnode.hpp"
  32 #include "opto/vectornode.hpp"
  33 #include "opto/graphKit.hpp"
  34 #include "opto/macro.hpp"
  35 #include "opto/runtime.hpp"
  36 #include "opto/castnode.hpp"
  37 #include "runtime/stubRoutines.hpp"
  38 #include "utilities/align.hpp"
  39 #include "utilities/powerOfTwo.hpp"
  40 
  41 void PhaseMacroExpand::insert_mem_bar(Node** ctrl, Node** mem, int opcode, Node* precedent) {
  42   MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
  43   mb->init_req(TypeFunc::Control, *ctrl);
  44   mb->init_req(TypeFunc::Memory, *mem);
  45   transform_later(mb);
  46   *ctrl = new ProjNode(mb,TypeFunc::Control);
  47   transform_later(*ctrl);
  48   Node* mem_proj = new ProjNode(mb,TypeFunc::Memory);
  49   transform_later(mem_proj);
  50   *mem = mem_proj;
  51 }
  52 
  53 Node* PhaseMacroExpand::array_element_address(Node* ary, Node* idx, BasicType elembt) {
  54   uint shift  = exact_log2(type2aelembytes(elembt));
  55   uint header = arrayOopDesc::base_offset_in_bytes(elembt);
  56   Node* base =  basic_plus_adr(ary, header);
  57 #ifdef _LP64
  58   // see comment in GraphKit::array_element_address
  59   int index_max = max_jint - 1;  // array size is max_jint, index is one less
  60   const TypeLong* lidxtype = TypeLong::make(CONST64(0), index_max, Type::WidenMax);
  61   idx = transform_later( new ConvI2LNode(idx, lidxtype) );
  62 #endif
  63   Node* scale = new LShiftXNode(idx, intcon(shift));
  64   transform_later(scale);
  65   return basic_plus_adr(ary, base, scale);
  66 }
  67 
  68 Node* PhaseMacroExpand::ConvI2L(Node* offset) {
  69   return transform_later(new ConvI2LNode(offset));
  70 }
  71 
  72 Node* PhaseMacroExpand::make_leaf_call(Node* ctrl, Node* mem,
  73                                        const TypeFunc* call_type, address call_addr,
  74                                        const char* call_name,
  75                                        const TypePtr* adr_type,
  76                                        Node* parm0, Node* parm1,
  77                                        Node* parm2, Node* parm3,
  78                                        Node* parm4, Node* parm5,
  79                                        Node* parm6, Node* parm7) {
  80   Node* call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);
  81   call->init_req(TypeFunc::Control, ctrl);
  82   call->init_req(TypeFunc::I_O    , top());
  83   call->init_req(TypeFunc::Memory , mem);
  84   call->init_req(TypeFunc::ReturnAdr, top());
  85   call->init_req(TypeFunc::FramePtr, top());
  86 
  87   // Hook each parm in order.  Stop looking at the first NULL.
  88   if (parm0 != NULL) { call->init_req(TypeFunc::Parms+0, parm0);
  89   if (parm1 != NULL) { call->init_req(TypeFunc::Parms+1, parm1);
  90   if (parm2 != NULL) { call->init_req(TypeFunc::Parms+2, parm2);
  91   if (parm3 != NULL) { call->init_req(TypeFunc::Parms+3, parm3);
  92   if (parm4 != NULL) { call->init_req(TypeFunc::Parms+4, parm4);
  93   if (parm5 != NULL) { call->init_req(TypeFunc::Parms+5, parm5);
  94   if (parm6 != NULL) { call->init_req(TypeFunc::Parms+6, parm6);
  95   if (parm7 != NULL) { call->init_req(TypeFunc::Parms+7, parm7);
  96     /* close each nested if ===> */  } } } } } } } }
  97   assert(call->in(call->req()-1) != NULL, "must initialize all parms");
  98 
  99   return call;
 100 }
 101 
 102 
 103 //------------------------------generate_guard---------------------------
 104 // Helper function for generating guarded fast-slow graph structures.
 105 // The given 'test', if true, guards a slow path.  If the test fails
 106 // then a fast path can be taken.  (We generally hope it fails.)
 107 // In all cases, GraphKit::control() is updated to the fast path.
 108 // The returned value represents the control for the slow path.
 109 // The return value is never 'top'; it is either a valid control
 110 // or NULL if it is obvious that the slow path can never be taken.
 111 // Also, if region and the slow control are not NULL, the slow edge
 112 // is appended to the region.
 113 Node* PhaseMacroExpand::generate_guard(Node** ctrl, Node* test, RegionNode* region, float true_prob) {
 114   if ((*ctrl)->is_top()) {
 115     // Already short circuited.
 116     return NULL;
 117   }
 118   // Build an if node and its projections.
 119   // If test is true we take the slow path, which we assume is uncommon.
 120   if (_igvn.type(test) == TypeInt::ZERO) {
 121     // The slow branch is never taken.  No need to build this guard.
 122     return NULL;
 123   }
 124 
 125   IfNode* iff = new IfNode(*ctrl, test, true_prob, COUNT_UNKNOWN);
 126   transform_later(iff);
 127 
 128   Node* if_slow = new IfTrueNode(iff);
 129   transform_later(if_slow);
 130 
 131   if (region != NULL) {
 132     region->add_req(if_slow);
 133   }
 134 
 135   Node* if_fast = new IfFalseNode(iff);
 136   transform_later(if_fast);
 137 
 138   *ctrl = if_fast;
 139 
 140   return if_slow;
 141 }
 142 
 143 Node* PhaseMacroExpand::generate_slow_guard(Node** ctrl, Node* test, RegionNode* region) {
 144   return generate_guard(ctrl, test, region, PROB_UNLIKELY_MAG(3));
 145 }
 146 
 147 inline Node* PhaseMacroExpand::generate_fair_guard(Node** ctrl, Node* test, RegionNode* region) {
 148   return generate_guard(ctrl, test, region, PROB_FAIR);
 149 }
 150 
 151 void PhaseMacroExpand::generate_negative_guard(Node** ctrl, Node* index, RegionNode* region) {
 152   if ((*ctrl)->is_top())
 153     return;                // already stopped
 154   if (_igvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 155     return;                // index is already adequately typed
 156   Node* cmp_lt = new CmpINode(index, intcon(0));
 157   transform_later(cmp_lt);
 158   Node* bol_lt = new BoolNode(cmp_lt, BoolTest::lt);
 159   transform_later(bol_lt);
 160   generate_guard(ctrl, bol_lt, region, PROB_MIN);
 161 }
 162 
 163 void PhaseMacroExpand::generate_limit_guard(Node** ctrl, Node* offset, Node* subseq_length, Node* array_length, RegionNode* region) {
 164   if ((*ctrl)->is_top())
 165     return;                // already stopped
 166   bool zero_offset = _igvn.type(offset) == TypeInt::ZERO;
 167   if (zero_offset && subseq_length->eqv_uncast(array_length))
 168     return;                // common case of whole-array copy
 169   Node* last = subseq_length;
 170   if (!zero_offset) {            // last += offset
 171     last = new AddINode(last, offset);
 172     transform_later(last);
 173   }
 174   Node* cmp_lt = new CmpUNode(array_length, last);
 175   transform_later(cmp_lt);
 176   Node* bol_lt = new BoolNode(cmp_lt, BoolTest::lt);
 177   transform_later(bol_lt);
 178   generate_guard(ctrl, bol_lt, region, PROB_MIN);
 179 }
 180 
 181 //
 182 // Partial in-lining handling for smaller conjoint/disjoint array copies having
 183 // length(in bytes) less than ArrayOperationPartialInlineSize.
 184 //  if (length <= ArrayOperationPartialInlineSize) {
 185 //    partial_inlining_block:
 186 //      mask = Mask_Gen
 187 //      vload = LoadVectorMasked src , mask
 188 //      StoreVectorMasked dst, mask, vload
 189 //  } else {
 190 //    stub_block:
 191 //      callstub array_copy
 192 //  }
 193 //  exit_block:
 194 //    Phi = label partial_inlining_block:mem , label stub_block:mem (filled by caller)
 195 //    mem = MergeMem (Phi)
 196 //    control = stub_block
 197 //
 198 //  Exit_block and associated phi(memory) are partially initialized for partial_in-lining_block
 199 //  edges. Remaining edges for exit_block coming from stub_block are connected by the caller
 200 //  post stub nodes creation.
 201 //
 202 
 203 void PhaseMacroExpand::generate_partial_inlining_block(Node** ctrl, MergeMemNode** mem, const TypePtr* adr_type,
 204                                                        RegionNode** exit_block, Node** result_memory, Node* length,
 205                                                        Node* src_start, Node* dst_start, BasicType type) {
 206   const TypePtr *src_adr_type = _igvn.type(src_start)->isa_ptr();
 207   Node* inline_block = NULL;
 208   Node* stub_block = NULL;
 209 
 210   int const_len = -1;
 211   const TypeInt* lty = NULL;
 212   uint shift  = exact_log2(type2aelembytes(type));
 213   if (length->Opcode() == Op_ConvI2L) {
 214     lty = _igvn.type(length->in(1))->isa_int();
 215   } else  {
 216     lty = _igvn.type(length)->isa_int();
 217   }
 218   if (lty && lty->is_con()) {
 219     const_len = lty->get_con() << shift;
 220   }
 221 
 222   // Return if copy length is greater than partial inline size limit or
 223   // target does not supports masked load/stores.
 224   int lane_count = ArrayCopyNode::get_partial_inline_vector_lane_count(type, const_len);
 225   if ( const_len > ArrayOperationPartialInlineSize ||
 226       !Matcher::match_rule_supported_vector(Op_LoadVectorMasked, lane_count, type)  ||
 227       !Matcher::match_rule_supported_vector(Op_StoreVectorMasked, lane_count, type) ||
 228       !Matcher::match_rule_supported_vector(Op_VectorMaskGen, lane_count, type)) {
 229     return;
 230   }
 231 
 232   int inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(type);
 233   Node* casted_length = new CastLLNode(*ctrl, length, TypeLong::make(0, inline_limit, Type::WidenMin));
 234   transform_later(casted_length);
 235   Node* copy_bytes = new LShiftXNode(length, intcon(shift));
 236   transform_later(copy_bytes);
 237 
 238   Node* cmp_le = new CmpULNode(copy_bytes, longcon(ArrayOperationPartialInlineSize));
 239   transform_later(cmp_le);
 240   Node* bol_le = new BoolNode(cmp_le, BoolTest::le);
 241   transform_later(bol_le);
 242   inline_block  = generate_guard(ctrl, bol_le, NULL, PROB_FAIR);
 243   stub_block = *ctrl;
 244 
 245   Node* mask_gen =  new VectorMaskGenNode(casted_length, TypeVect::VECTMASK, type);
 246   transform_later(mask_gen);
 247 
 248   unsigned vec_size = lane_count *  type2aelembytes(type);
 249   if (C->max_vector_size() < vec_size) {
 250     C->set_max_vector_size(vec_size);
 251   }
 252 
 253   const TypeVect * vt = TypeVect::make(type, lane_count);
 254   Node* mm = (*mem)->memory_at(C->get_alias_index(src_adr_type));
 255   Node* masked_load = new LoadVectorMaskedNode(inline_block, mm, src_start,
 256                                                src_adr_type, vt, mask_gen);
 257   transform_later(masked_load);
 258 
 259   mm = (*mem)->memory_at(C->get_alias_index(adr_type));
 260   Node* masked_store = new StoreVectorMaskedNode(inline_block, mm, dst_start,
 261                                                  masked_load, adr_type, mask_gen);
 262   transform_later(masked_store);
 263 
 264   // Convergence region for inline_block and stub_block.
 265   *exit_block = new RegionNode(3);
 266   transform_later(*exit_block);
 267   (*exit_block)->init_req(1, inline_block);
 268   *result_memory = new PhiNode(*exit_block, Type::MEMORY, adr_type);
 269   transform_later(*result_memory);
 270   (*result_memory)->init_req(1, masked_store);
 271 
 272   *ctrl = stub_block;
 273 }
 274 
 275 
 276 Node* PhaseMacroExpand::generate_nonpositive_guard(Node** ctrl, Node* index, bool never_negative) {
 277   if ((*ctrl)->is_top())  return NULL;
 278 
 279   if (_igvn.type(index)->higher_equal(TypeInt::POS1)) // [1,maxint]
 280     return NULL;                // index is already adequately typed
 281   Node* cmp_le = new CmpINode(index, intcon(0));
 282   transform_later(cmp_le);
 283   BoolTest::mask le_or_eq = (never_negative ? BoolTest::eq : BoolTest::le);
 284   Node* bol_le = new BoolNode(cmp_le, le_or_eq);
 285   transform_later(bol_le);
 286   Node* is_notp = generate_guard(ctrl, bol_le, NULL, PROB_MIN);
 287 
 288   return is_notp;
 289 }
 290 
 291 Node* PhaseMacroExpand::array_lh_test(Node* array, jint mask) {
 292   Node* klass_adr = basic_plus_adr(array, oopDesc::klass_offset_in_bytes());
 293   Node* klass = transform_later(LoadKlassNode::make(_igvn, NULL, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
 294   Node* lh_addr = basic_plus_adr(klass, in_bytes(Klass::layout_helper_offset()));
 295   Node* lh_val = _igvn.transform(LoadNode::make(_igvn, NULL, C->immutable_memory(), lh_addr, lh_addr->bottom_type()->is_ptr(), TypeInt::INT, T_INT, MemNode::unordered));
 296   Node* masked = transform_later(new AndINode(lh_val, intcon(mask)));
 297   Node* cmp = transform_later(new CmpINode(masked, intcon(0)));
 298   return transform_later(new BoolNode(cmp, BoolTest::ne));
 299 }
 300 
 301 Node* PhaseMacroExpand::generate_flat_array_guard(Node** ctrl, Node* array, RegionNode* region) {
 302   assert(UseFlatArray, "can never be flattened");
 303   return generate_fair_guard(ctrl, array_lh_test(array, Klass::_lh_array_tag_vt_value_bit_inplace), region);
 304 }
 305 
 306 Node* PhaseMacroExpand::generate_null_free_array_guard(Node** ctrl, Node* array, RegionNode* region) {
 307   assert(EnableValhalla, "can never be null free");
 308   return generate_fair_guard(ctrl, array_lh_test(array, Klass::_lh_null_free_bit_inplace), region);
 309 }
 310 
 311 void PhaseMacroExpand::finish_arraycopy_call(Node* call, Node** ctrl, MergeMemNode** mem, const TypePtr* adr_type) {
 312   transform_later(call);
 313 
 314   *ctrl = new ProjNode(call,TypeFunc::Control);
 315   transform_later(*ctrl);
 316   Node* newmem = new ProjNode(call, TypeFunc::Memory);
 317   transform_later(newmem);
 318 
 319   uint alias_idx = C->get_alias_index(adr_type);
 320   if (alias_idx != Compile::AliasIdxBot) {
 321     *mem = MergeMemNode::make(*mem);
 322     (*mem)->set_memory_at(alias_idx, newmem);
 323   } else {
 324     *mem = MergeMemNode::make(newmem);
 325   }
 326   transform_later(*mem);
 327 }
 328 
 329 address PhaseMacroExpand::basictype2arraycopy(BasicType t,
 330                                               Node* src_offset,
 331                                               Node* dest_offset,
 332                                               bool disjoint_bases,
 333                                               const char* &name,
 334                                               bool dest_uninitialized) {
 335   const TypeInt* src_offset_inttype  = _igvn.find_int_type(src_offset);
 336   const TypeInt* dest_offset_inttype = _igvn.find_int_type(dest_offset);
 337 
 338   bool aligned = false;
 339   bool disjoint = disjoint_bases;
 340 
 341   // if the offsets are the same, we can treat the memory regions as
 342   // disjoint, because either the memory regions are in different arrays,
 343   // or they are identical (which we can treat as disjoint.)  We can also
 344   // treat a copy with a destination index  less that the source index
 345   // as disjoint since a low->high copy will work correctly in this case.
 346   if (src_offset_inttype != NULL && src_offset_inttype->is_con() &&
 347       dest_offset_inttype != NULL && dest_offset_inttype->is_con()) {
 348     // both indices are constants
 349     int s_offs = src_offset_inttype->get_con();
 350     int d_offs = dest_offset_inttype->get_con();
 351     int element_size = type2aelembytes(t);
 352     aligned = ((arrayOopDesc::base_offset_in_bytes(t) + s_offs * element_size) % HeapWordSize == 0) &&
 353               ((arrayOopDesc::base_offset_in_bytes(t) + d_offs * element_size) % HeapWordSize == 0);
 354     if (s_offs >= d_offs)  disjoint = true;
 355   } else if (src_offset == dest_offset && src_offset != NULL) {
 356     // This can occur if the offsets are identical non-constants.
 357     disjoint = true;
 358   }
 359 
 360   return StubRoutines::select_arraycopy_function(t, aligned, disjoint, name, dest_uninitialized);
 361 }
 362 
 363 bool PhaseMacroExpand::can_try_zeroing_elimination(AllocateArrayNode* alloc,
 364                                                    Node* src,
 365                                                    Node* dest) const {
 366   const TypeAryPtr* top_dest = _igvn.type(dest)->isa_aryptr();
 367 
 368   if (top_dest != NULL) {
 369     if (top_dest->klass() == NULL) {
 370       return false;
 371     }
 372   }
 373 
 374   return ReduceBulkZeroing
 375     && !(UseTLAB && ZeroTLAB) // pointless if already zeroed
 376     && !src->eqv_uncast(dest)
 377     && alloc != NULL
 378     && _igvn.find_int_con(alloc->in(AllocateNode::ALength), 1) > 0
 379     && alloc->maybe_set_complete(&_igvn);
 380 }
 381 
 382 #define XTOP LP64_ONLY(COMMA top())
 383 
 384 // Generate an optimized call to arraycopy.
 385 // Caller must guard against non-arrays.
 386 // Caller must determine a common array basic-type for both arrays.
 387 // Caller must validate offsets against array bounds.
 388 // The slow_region has already collected guard failure paths
 389 // (such as out of bounds length or non-conformable array types).
 390 // The generated code has this shape, in general:
 391 //
 392 //     if (length == 0)  return   // via zero_path
 393 //     slowval = -1
 394 //     if (types unknown) {
 395 //       slowval = call generic copy loop
 396 //       if (slowval == 0)  return  // via checked_path
 397 //     } else if (indexes in bounds) {
 398 //       if ((is object array) && !(array type check)) {
 399 //         slowval = call checked copy loop
 400 //         if (slowval == 0)  return  // via checked_path
 401 //       } else {
 402 //         call bulk copy loop
 403 //         return  // via fast_path
 404 //       }
 405 //     }
 406 //     // adjust params for remaining work:
 407 //     if (slowval != -1) {
 408 //       n = -1^slowval; src_offset += n; dest_offset += n; length -= n
 409 //     }
 410 //   slow_region:
 411 //     call slow arraycopy(src, src_offset, dest, dest_offset, length)
 412 //     return  // via slow_call_path
 413 //
 414 // This routine is used from several intrinsics:  System.arraycopy,
 415 // Object.clone (the array subcase), and Arrays.copyOf[Range].
 416 //
 417 Node* PhaseMacroExpand::generate_arraycopy(ArrayCopyNode *ac, AllocateArrayNode* alloc,
 418                                            Node** ctrl, MergeMemNode* mem, Node** io,
 419                                            const TypePtr* adr_type,
 420                                            BasicType basic_elem_type,
 421                                            Node* src,  Node* src_offset,
 422                                            Node* dest, Node* dest_offset,
 423                                            Node* copy_length,
 424                                            Node* dest_length,
 425                                            bool disjoint_bases,
 426                                            bool length_never_negative,
 427                                            RegionNode* slow_region) {
 428   if (slow_region == NULL) {
 429     slow_region = new RegionNode(1);
 430     transform_later(slow_region);
 431   }
 432 
 433   Node* original_dest = dest;
 434   bool  dest_needs_zeroing   = false;
 435   bool  acopy_to_uninitialized = false;
 436   Node* default_value = NULL;
 437   Node* raw_default_value = NULL;
 438 
 439   // See if this is the initialization of a newly-allocated array.
 440   // If so, we will take responsibility here for initializing it to zero.
 441   // (Note:  Because tightly_coupled_allocation performs checks on the
 442   // out-edges of the dest, we need to avoid making derived pointers
 443   // from it until we have checked its uses.)
 444   if (ReduceBulkZeroing
 445       && !(UseTLAB && ZeroTLAB) // pointless if already zeroed
 446       && basic_elem_type != T_CONFLICT // avoid corner case
 447       && !src->eqv_uncast(dest)
 448       && alloc != NULL
 449       && _igvn.find_int_con(alloc->in(AllocateNode::ALength), 1) > 0) {
 450     assert(ac->is_alloc_tightly_coupled(), "sanity");
 451     // acopy to uninitialized tightly coupled allocations
 452     // needs zeroing outside the copy range
 453     // and the acopy itself will be to uninitialized memory
 454     acopy_to_uninitialized = true;
 455     if (alloc->maybe_set_complete(&_igvn)) {
 456       // "You break it, you buy it."
 457       InitializeNode* init = alloc->initialization();
 458       assert(init->is_complete(), "we just did this");
 459       init->set_complete_with_arraycopy();
 460       assert(dest->is_CheckCastPP(), "sanity");
 461       assert(dest->in(0)->in(0) == init, "dest pinned");
 462       adr_type = TypeRawPtr::BOTTOM;  // all initializations are into raw memory
 463       // From this point on, every exit path is responsible for
 464       // initializing any non-copied parts of the object to zero.
 465       // Also, if this flag is set we make sure that arraycopy interacts properly
 466       // with G1, eliding pre-barriers. See CR 6627983.
 467       dest_needs_zeroing = true;
 468       default_value = alloc->in(AllocateNode::DefaultValue);
 469       raw_default_value = alloc->in(AllocateNode::RawDefaultValue);
 470     } else {
 471       // dest_need_zeroing = false;
 472     }
 473   } else {
 474     // No zeroing elimination needed here.
 475     alloc                  = NULL;
 476     acopy_to_uninitialized = false;
 477     //original_dest        = dest;
 478     //dest_needs_zeroing   = false;
 479   }
 480 
 481   uint alias_idx = C->get_alias_index(adr_type);
 482 
 483   // Results are placed here:
 484   enum { fast_path        = 1,  // normal void-returning assembly stub
 485          checked_path     = 2,  // special assembly stub with cleanup
 486          slow_call_path   = 3,  // something went wrong; call the VM
 487          zero_path        = 4,  // bypass when length of copy is zero
 488          bcopy_path       = 5,  // copy primitive array by 64-bit blocks
 489          PATH_LIMIT       = 6
 490   };
 491   RegionNode* result_region = new RegionNode(PATH_LIMIT);
 492   PhiNode*    result_i_o    = new PhiNode(result_region, Type::ABIO);
 493   PhiNode*    result_memory = new PhiNode(result_region, Type::MEMORY, adr_type);
 494   assert(adr_type != TypePtr::BOTTOM, "must be RawMem or a T[] slice");
 495   transform_later(result_region);
 496   transform_later(result_i_o);
 497   transform_later(result_memory);
 498 
 499   // The slow_control path:
 500   Node* slow_control;
 501   Node* slow_i_o = *io;
 502   Node* slow_mem = mem->memory_at(alias_idx);
 503   DEBUG_ONLY(slow_control = (Node*) badAddress);
 504 
 505   // Checked control path:
 506   Node* checked_control = top();
 507   Node* checked_mem     = NULL;
 508   Node* checked_i_o     = NULL;
 509   Node* checked_value   = NULL;
 510 
 511   if (basic_elem_type == T_CONFLICT) {
 512     assert(!dest_needs_zeroing, "");
 513     Node* cv = generate_generic_arraycopy(ctrl, &mem,
 514                                           adr_type,
 515                                           src, src_offset, dest, dest_offset,
 516                                           copy_length, acopy_to_uninitialized);
 517     if (cv == NULL)  cv = intcon(-1);  // failure (no stub available)
 518     checked_control = *ctrl;
 519     checked_i_o     = *io;
 520     checked_mem     = mem->memory_at(alias_idx);
 521     checked_value   = cv;
 522     *ctrl = top();
 523   }
 524 
 525   Node* not_pos = generate_nonpositive_guard(ctrl, copy_length, length_never_negative);
 526   if (not_pos != NULL) {
 527     Node* local_ctrl = not_pos, *local_io = *io;
 528     MergeMemNode* local_mem = MergeMemNode::make(mem);
 529     transform_later(local_mem);
 530 
 531     // (6) length must not be negative.
 532     if (!length_never_negative) {
 533       generate_negative_guard(&local_ctrl, copy_length, slow_region);
 534     }
 535 
 536     // copy_length is 0.
 537     if (dest_needs_zeroing) {
 538       assert(!local_ctrl->is_top(), "no ctrl?");
 539       if (copy_length->eqv_uncast(dest_length)
 540           || _igvn.find_int_con(dest_length, 1) <= 0) {
 541         // There is no zeroing to do. No need for a secondary raw memory barrier.
 542       } else {
 543         // Clear the whole thing since there are no source elements to copy.
 544         generate_clear_array(local_ctrl, local_mem,
 545                              adr_type, dest,
 546                              default_value, raw_default_value,
 547                              basic_elem_type,
 548                              intcon(0), NULL,
 549                              alloc->in(AllocateNode::AllocSize));
 550         // Use a secondary InitializeNode as raw memory barrier.
 551         // Currently it is needed only on this path since other
 552         // paths have stub or runtime calls as raw memory barriers.
 553         MemBarNode* mb = MemBarNode::make(C, Op_Initialize,
 554                                           Compile::AliasIdxRaw,
 555                                           top());
 556         transform_later(mb);
 557         mb->set_req(TypeFunc::Control,local_ctrl);
 558         mb->set_req(TypeFunc::Memory, local_mem->memory_at(Compile::AliasIdxRaw));
 559         local_ctrl = transform_later(new ProjNode(mb, TypeFunc::Control));
 560         local_mem->set_memory_at(Compile::AliasIdxRaw, transform_later(new ProjNode(mb, TypeFunc::Memory)));
 561 
 562         InitializeNode* init = mb->as_Initialize();
 563         init->set_complete(&_igvn);  // (there is no corresponding AllocateNode)
 564       }
 565     }
 566 
 567     // Present the results of the fast call.
 568     result_region->init_req(zero_path, local_ctrl);
 569     result_i_o   ->init_req(zero_path, local_io);
 570     result_memory->init_req(zero_path, local_mem->memory_at(alias_idx));
 571   }
 572 
 573   if (!(*ctrl)->is_top() && dest_needs_zeroing) {
 574     // We have to initialize the *uncopied* part of the array to zero.
 575     // The copy destination is the slice dest[off..off+len].  The other slices
 576     // are dest_head = dest[0..off] and dest_tail = dest[off+len..dest.length].
 577     Node* dest_size   = alloc->in(AllocateNode::AllocSize);
 578     Node* dest_tail   = transform_later( new AddINode(dest_offset, copy_length));
 579 
 580     // If there is a head section that needs zeroing, do it now.
 581     if (_igvn.find_int_con(dest_offset, -1) != 0) {
 582       generate_clear_array(*ctrl, mem,
 583                            adr_type, dest,
 584                            default_value, raw_default_value,
 585                            basic_elem_type,
 586                            intcon(0), dest_offset,
 587                            NULL);
 588     }
 589 
 590     // Next, perform a dynamic check on the tail length.
 591     // It is often zero, and we can win big if we prove this.
 592     // There are two wins:  Avoid generating the ClearArray
 593     // with its attendant messy index arithmetic, and upgrade
 594     // the copy to a more hardware-friendly word size of 64 bits.
 595     Node* tail_ctl = NULL;
 596     if (!(*ctrl)->is_top() && !dest_tail->eqv_uncast(dest_length)) {
 597       Node* cmp_lt   = transform_later( new CmpINode(dest_tail, dest_length) );
 598       Node* bol_lt   = transform_later( new BoolNode(cmp_lt, BoolTest::lt) );
 599       tail_ctl = generate_slow_guard(ctrl, bol_lt, NULL);
 600       assert(tail_ctl != NULL || !(*ctrl)->is_top(), "must be an outcome");
 601     }
 602 
 603     // At this point, let's assume there is no tail.
 604     if (!(*ctrl)->is_top() && alloc != NULL && basic_elem_type != T_OBJECT) {
 605       // There is no tail.  Try an upgrade to a 64-bit copy.
 606       bool didit = false;
 607       {
 608         Node* local_ctrl = *ctrl, *local_io = *io;
 609         MergeMemNode* local_mem = MergeMemNode::make(mem);
 610         transform_later(local_mem);
 611 
 612         didit = generate_block_arraycopy(&local_ctrl, &local_mem, local_io,
 613                                          adr_type, basic_elem_type, alloc,
 614                                          src, src_offset, dest, dest_offset,
 615                                          dest_size, acopy_to_uninitialized);
 616         if (didit) {
 617           // Present the results of the block-copying fast call.
 618           result_region->init_req(bcopy_path, local_ctrl);
 619           result_i_o   ->init_req(bcopy_path, local_io);
 620           result_memory->init_req(bcopy_path, local_mem->memory_at(alias_idx));
 621         }
 622       }
 623       if (didit) {
 624         *ctrl = top();     // no regular fast path
 625       }
 626     }
 627 
 628     // Clear the tail, if any.
 629     if (tail_ctl != NULL) {
 630       Node* notail_ctl = (*ctrl)->is_top() ? NULL : *ctrl;
 631       *ctrl = tail_ctl;
 632       if (notail_ctl == NULL) {
 633         generate_clear_array(*ctrl, mem,
 634                              adr_type, dest,
 635                              default_value, raw_default_value,
 636                              basic_elem_type,
 637                              dest_tail, NULL,
 638                              dest_size);
 639       } else {
 640         // Make a local merge.
 641         Node* done_ctl = transform_later(new RegionNode(3));
 642         Node* done_mem = transform_later(new PhiNode(done_ctl, Type::MEMORY, adr_type));
 643         done_ctl->init_req(1, notail_ctl);
 644         done_mem->init_req(1, mem->memory_at(alias_idx));
 645         generate_clear_array(*ctrl, mem,
 646                              adr_type, dest,
 647                              default_value, raw_default_value,
 648                              basic_elem_type,
 649                              dest_tail, NULL,
 650                              dest_size);
 651         done_ctl->init_req(2, *ctrl);
 652         done_mem->init_req(2, mem->memory_at(alias_idx));
 653         *ctrl = done_ctl;
 654         mem->set_memory_at(alias_idx, done_mem);
 655       }
 656     }
 657   }
 658 
 659   BasicType copy_type = basic_elem_type;
 660   assert(basic_elem_type != T_ARRAY, "caller must fix this");
 661   if (!(*ctrl)->is_top() && copy_type == T_OBJECT) {
 662     // If src and dest have compatible element types, we can copy bits.
 663     // Types S[] and D[] are compatible if D is a supertype of S.
 664     //
 665     // If they are not, we will use checked_oop_disjoint_arraycopy,
 666     // which performs a fast optimistic per-oop check, and backs off
 667     // further to JVM_ArrayCopy on the first per-oop check that fails.
 668     // (Actually, we don't move raw bits only; the GC requires card marks.)
 669 
 670     // We don't need a subtype check for validated copies and Object[].clone()
 671     bool skip_subtype_check = ac->is_arraycopy_validated() || ac->is_copyof_validated() ||
 672                               ac->is_copyofrange_validated() || ac->is_clone_oop_array();
 673     if (!skip_subtype_check) {
 674       // Get the klass* for both src and dest
 675       Node* src_klass  = ac->in(ArrayCopyNode::SrcKlass);
 676       Node* dest_klass = ac->in(ArrayCopyNode::DestKlass);
 677 
 678       assert(src_klass != NULL && dest_klass != NULL, "should have klasses");
 679 
 680       // Generate the subtype check.
 681       // This might fold up statically, or then again it might not.
 682       //
 683       // Non-static example:  Copying List<String>.elements to a new String[].
 684       // The backing store for a List<String> is always an Object[],
 685       // but its elements are always type String, if the generic types
 686       // are correct at the source level.
 687       //
 688       // Test S[] against D[], not S against D, because (probably)
 689       // the secondary supertype cache is less busy for S[] than S.
 690       // This usually only matters when D is an interface.
 691       Node* not_subtype_ctrl = Phase::gen_subtype_check(src_klass, dest_klass, ctrl, mem, _igvn);
 692       // Plug failing path into checked_oop_disjoint_arraycopy
 693       if (not_subtype_ctrl != top()) {
 694         Node* local_ctrl = not_subtype_ctrl;
 695         MergeMemNode* local_mem = MergeMemNode::make(mem);
 696         transform_later(local_mem);
 697 
 698         // (At this point we can assume disjoint_bases, since types differ.)
 699         int ek_offset = in_bytes(ObjArrayKlass::element_klass_offset());
 700         Node* p1 = basic_plus_adr(dest_klass, ek_offset);
 701         Node* n1 = LoadKlassNode::make(_igvn, NULL, C->immutable_memory(), p1, TypeRawPtr::BOTTOM);
 702         Node* dest_elem_klass = transform_later(n1);
 703         Node* cv = generate_checkcast_arraycopy(&local_ctrl, &local_mem,
 704                                                 adr_type,
 705                                                 dest_elem_klass,
 706                                                 src, src_offset, dest, dest_offset,
 707                                                 ConvI2X(copy_length), acopy_to_uninitialized);
 708         if (cv == NULL)  cv = intcon(-1);  // failure (no stub available)
 709         checked_control = local_ctrl;
 710         checked_i_o     = *io;
 711         checked_mem     = local_mem->memory_at(alias_idx);
 712         checked_value   = cv;
 713       }
 714     }
 715     // At this point we know we do not need type checks on oop stores.
 716 
 717     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 718     if (!bs->array_copy_requires_gc_barriers(alloc != NULL, copy_type, false, false, BarrierSetC2::Expansion)) {
 719       // If we do not need gc barriers, copy using the jint or jlong stub.
 720       copy_type = LP64_ONLY(UseCompressedOops ? T_INT : T_LONG) NOT_LP64(T_INT);
 721       assert(type2aelembytes(basic_elem_type) == type2aelembytes(copy_type),
 722              "sizes agree");
 723     }
 724   }
 725 
 726   bool is_partial_array_copy = false;
 727   if (!(*ctrl)->is_top()) {
 728     // Generate the fast path, if possible.
 729     Node* local_ctrl = *ctrl;
 730     MergeMemNode* local_mem = MergeMemNode::make(mem);
 731     transform_later(local_mem);
 732     is_partial_array_copy = generate_unchecked_arraycopy(&local_ctrl, &local_mem,
 733                                                          adr_type, copy_type, disjoint_bases,
 734                                                          src, src_offset, dest, dest_offset,
 735                                                          ConvI2X(copy_length), acopy_to_uninitialized);
 736 
 737     // Present the results of the fast call.
 738     result_region->init_req(fast_path, local_ctrl);
 739     result_i_o   ->init_req(fast_path, *io);
 740     result_memory->init_req(fast_path, local_mem->memory_at(alias_idx));
 741   }
 742 
 743   // Here are all the slow paths up to this point, in one bundle:
 744   assert(slow_region != NULL, "allocated on entry");
 745   slow_control = slow_region;
 746   DEBUG_ONLY(slow_region = (RegionNode*)badAddress);
 747 
 748   *ctrl = checked_control;
 749   if (!(*ctrl)->is_top()) {
 750     // Clean up after the checked call.
 751     // The returned value is either 0 or -1^K,
 752     // where K = number of partially transferred array elements.
 753     Node* cmp = new CmpINode(checked_value, intcon(0));
 754     transform_later(cmp);
 755     Node* bol = new BoolNode(cmp, BoolTest::eq);
 756     transform_later(bol);
 757     IfNode* iff = new IfNode(*ctrl, bol, PROB_MAX, COUNT_UNKNOWN);
 758     transform_later(iff);
 759 
 760     // If it is 0, we are done, so transfer to the end.
 761     Node* checks_done = new IfTrueNode(iff);
 762     transform_later(checks_done);
 763     result_region->init_req(checked_path, checks_done);
 764     result_i_o   ->init_req(checked_path, checked_i_o);
 765     result_memory->init_req(checked_path, checked_mem);
 766 
 767     // If it is not zero, merge into the slow call.
 768     *ctrl = new IfFalseNode(iff);
 769     transform_later(*ctrl);
 770     RegionNode* slow_reg2 = new RegionNode(3);
 771     PhiNode*    slow_i_o2 = new PhiNode(slow_reg2, Type::ABIO);
 772     PhiNode*    slow_mem2 = new PhiNode(slow_reg2, Type::MEMORY, adr_type);
 773     transform_later(slow_reg2);
 774     transform_later(slow_i_o2);
 775     transform_later(slow_mem2);
 776     slow_reg2  ->init_req(1, slow_control);
 777     slow_i_o2  ->init_req(1, slow_i_o);
 778     slow_mem2  ->init_req(1, slow_mem);
 779     slow_reg2  ->init_req(2, *ctrl);
 780     slow_i_o2  ->init_req(2, checked_i_o);
 781     slow_mem2  ->init_req(2, checked_mem);
 782 
 783     slow_control = slow_reg2;
 784     slow_i_o     = slow_i_o2;
 785     slow_mem     = slow_mem2;
 786 
 787     if (alloc != NULL) {
 788       // We'll restart from the very beginning, after zeroing the whole thing.
 789       // This can cause double writes, but that's OK since dest is brand new.
 790       // So we ignore the low 31 bits of the value returned from the stub.
 791     } else {
 792       // We must continue the copy exactly where it failed, or else
 793       // another thread might see the wrong number of writes to dest.
 794       Node* checked_offset = new XorINode(checked_value, intcon(-1));
 795       Node* slow_offset    = new PhiNode(slow_reg2, TypeInt::INT);
 796       transform_later(checked_offset);
 797       transform_later(slow_offset);
 798       slow_offset->init_req(1, intcon(0));
 799       slow_offset->init_req(2, checked_offset);
 800 
 801       // Adjust the arguments by the conditionally incoming offset.
 802       Node* src_off_plus  = new AddINode(src_offset,  slow_offset);
 803       transform_later(src_off_plus);
 804       Node* dest_off_plus = new AddINode(dest_offset, slow_offset);
 805       transform_later(dest_off_plus);
 806       Node* length_minus  = new SubINode(copy_length, slow_offset);
 807       transform_later(length_minus);
 808 
 809       // Tweak the node variables to adjust the code produced below:
 810       src_offset  = src_off_plus;
 811       dest_offset = dest_off_plus;
 812       copy_length = length_minus;
 813     }
 814   }
 815   *ctrl = slow_control;
 816   if (!(*ctrl)->is_top()) {
 817     Node* local_ctrl = *ctrl, *local_io = slow_i_o;
 818     MergeMemNode* local_mem = MergeMemNode::make(mem);
 819     transform_later(local_mem);
 820 
 821     // Generate the slow path, if needed.
 822     local_mem->set_memory_at(alias_idx, slow_mem);
 823 
 824     if (dest_needs_zeroing) {
 825       generate_clear_array(local_ctrl, local_mem,
 826                            adr_type, dest,
 827                            default_value, raw_default_value,
 828                            basic_elem_type,
 829                            intcon(0), NULL,
 830                            alloc->in(AllocateNode::AllocSize));
 831     }
 832 
 833     local_mem = generate_slow_arraycopy(ac,
 834                                         &local_ctrl, local_mem, &local_io,
 835                                         adr_type,
 836                                         src, src_offset, dest, dest_offset,
 837                                         copy_length, /*dest_uninitialized*/false);
 838 
 839     result_region->init_req(slow_call_path, local_ctrl);
 840     result_i_o   ->init_req(slow_call_path, local_io);
 841     result_memory->init_req(slow_call_path, local_mem->memory_at(alias_idx));
 842   } else {
 843     ShouldNotReachHere(); // no call to generate_slow_arraycopy:
 844                           // projections were not extracted
 845   }
 846 
 847   // Remove unused edges.
 848   for (uint i = 1; i < result_region->req(); i++) {
 849     if (result_region->in(i) == NULL) {
 850       result_region->init_req(i, top());
 851     }
 852   }
 853 
 854   // Finished; return the combined state.
 855   *ctrl = result_region;
 856   *io = result_i_o;
 857   mem->set_memory_at(alias_idx, result_memory);
 858 
 859   // mem no longer guaranteed to stay a MergeMemNode
 860   Node* out_mem = mem;
 861   DEBUG_ONLY(mem = NULL);
 862 
 863   // The memory edges above are precise in order to model effects around
 864   // array copies accurately to allow value numbering of field loads around
 865   // arraycopy.  Such field loads, both before and after, are common in Java
 866   // collections and similar classes involving header/array data structures.
 867   //
 868   // But with low number of register or when some registers are used or killed
 869   // by arraycopy calls it causes registers spilling on stack. See 6544710.
 870   // The next memory barrier is added to avoid it. If the arraycopy can be
 871   // optimized away (which it can, sometimes) then we can manually remove
 872   // the membar also.
 873   //
 874   // Do not let reads from the cloned object float above the arraycopy.
 875   if (alloc != NULL && !alloc->initialization()->does_not_escape()) {
 876     // Do not let stores that initialize this object be reordered with
 877     // a subsequent store that would make this object accessible by
 878     // other threads.
 879     insert_mem_bar(ctrl, &out_mem, Op_MemBarStoreStore);
 880   } else {
 881     // Do not let reads from the destination float above the arraycopy.
 882     // Since we cannot type the arrays, we don't know which slices
 883     // might be affected.  We could restrict this barrier only to those
 884     // memory slices which pertain to array elements--but don't bother.
 885     insert_mem_bar(ctrl, &out_mem, Op_MemBarCPUOrder);
 886   }
 887 
 888   if (is_partial_array_copy) {
 889     assert((*ctrl)->is_Proj(), "MemBar control projection");
 890     assert((*ctrl)->in(0)->isa_MemBar(), "MemBar node");
 891     (*ctrl)->in(0)->isa_MemBar()->set_trailing_partial_array_copy();
 892   }
 893 
 894   _igvn.replace_node(_callprojs->fallthrough_memproj, out_mem);
 895   if (_callprojs->fallthrough_ioproj != NULL) {
 896     _igvn.replace_node(_callprojs->fallthrough_ioproj, *io);
 897   }
 898   _igvn.replace_node(_callprojs->fallthrough_catchproj, *ctrl);
 899 
 900 #ifdef ASSERT
 901   const TypeOopPtr* dest_t = _igvn.type(dest)->is_oopptr();
 902   if (dest_t->is_known_instance() && !is_partial_array_copy) {
 903     ArrayCopyNode* ac = NULL;
 904     assert(ArrayCopyNode::may_modify(dest_t, (*ctrl)->in(0)->as_MemBar(), &_igvn, ac), "dependency on arraycopy lost");
 905     assert(ac == NULL, "no arraycopy anymore");
 906   }
 907 #endif
 908 
 909   return out_mem;
 910 }
 911 
 912 // Helper for initialization of arrays, creating a ClearArray.
 913 // It writes zero bits in [start..end), within the body of an array object.
 914 // The memory effects are all chained onto the 'adr_type' alias category.
 915 //
 916 // Since the object is otherwise uninitialized, we are free
 917 // to put a little "slop" around the edges of the cleared area,
 918 // as long as it does not go back into the array's header,
 919 // or beyond the array end within the heap.
 920 //
 921 // The lower edge can be rounded down to the nearest jint and the
 922 // upper edge can be rounded up to the nearest MinObjAlignmentInBytes.
 923 //
 924 // Arguments:
 925 //   adr_type           memory slice where writes are generated
 926 //   dest               oop of the destination array
 927 //   basic_elem_type    element type of the destination
 928 //   slice_idx          array index of first element to store
 929 //   slice_len          number of elements to store (or NULL)
 930 //   dest_size          total size in bytes of the array object
 931 //
 932 // Exactly one of slice_len or dest_size must be non-NULL.
 933 // If dest_size is non-NULL, zeroing extends to the end of the object.
 934 // If slice_len is non-NULL, the slice_idx value must be a constant.
 935 void PhaseMacroExpand::generate_clear_array(Node* ctrl, MergeMemNode* merge_mem,
 936                                             const TypePtr* adr_type,
 937                                             Node* dest,
 938                                             Node* val,
 939                                             Node* raw_val,
 940                                             BasicType basic_elem_type,
 941                                             Node* slice_idx,
 942                                             Node* slice_len,
 943                                             Node* dest_size) {
 944   // one or the other but not both of slice_len and dest_size:
 945   assert((slice_len != NULL? 1: 0) + (dest_size != NULL? 1: 0) == 1, "");
 946   if (slice_len == NULL)  slice_len = top();
 947   if (dest_size == NULL)  dest_size = top();
 948 
 949   uint alias_idx = C->get_alias_index(adr_type);
 950 
 951   // operate on this memory slice:
 952   Node* mem = merge_mem->memory_at(alias_idx); // memory slice to operate on
 953 
 954   // scaling and rounding of indexes:
 955   assert(basic_elem_type != T_INLINE_TYPE, "should have been converted to a basic type copy");
 956   int scale = exact_log2(type2aelembytes(basic_elem_type));
 957   int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 958   int clear_low = (-1 << scale) & (BytesPerInt  - 1);
 959   int bump_bit  = (-1 << scale) & BytesPerInt;
 960 
 961   // determine constant starts and ends
 962   const intptr_t BIG_NEG = -128;
 963   assert(BIG_NEG + 2*abase < 0, "neg enough");
 964   intptr_t slice_idx_con = (intptr_t) _igvn.find_int_con(slice_idx, BIG_NEG);
 965   intptr_t slice_len_con = (intptr_t) _igvn.find_int_con(slice_len, BIG_NEG);
 966   if (slice_len_con == 0) {
 967     return;                     // nothing to do here
 968   }
 969   intptr_t start_con = (abase + (slice_idx_con << scale)) & ~clear_low;
 970   intptr_t end_con   = _igvn.find_intptr_t_con(dest_size, -1);
 971   if (slice_idx_con >= 0 && slice_len_con >= 0) {
 972     assert(end_con < 0, "not two cons");
 973     end_con = align_up(abase + ((slice_idx_con + slice_len_con) << scale),
 974                        BytesPerLong);
 975   }
 976 
 977   if (start_con >= 0 && end_con >= 0) {
 978     // Constant start and end.  Simple.
 979     mem = ClearArrayNode::clear_memory(ctrl, mem, dest, val, raw_val,
 980                                        start_con, end_con, &_igvn);
 981   } else if (start_con >= 0 && dest_size != top()) {
 982     // Constant start, pre-rounded end after the tail of the array.
 983     Node* end = dest_size;
 984     mem = ClearArrayNode::clear_memory(ctrl, mem, dest, val, raw_val,
 985                                        start_con, end, &_igvn);
 986   } else if (start_con >= 0 && slice_len != top()) {
 987     // Constant start, non-constant end.  End needs rounding up.
 988     // End offset = round_up(abase + ((slice_idx_con + slice_len) << scale), 8)
 989     intptr_t end_base  = abase + (slice_idx_con << scale);
 990     int      end_round = (-1 << scale) & (BytesPerLong  - 1);
 991     Node*    end       = ConvI2X(slice_len);
 992     if (scale != 0)
 993       end = transform_later(new LShiftXNode(end, intcon(scale) ));
 994     end_base += end_round;
 995     end = transform_later(new AddXNode(end, MakeConX(end_base)) );
 996     end = transform_later(new AndXNode(end, MakeConX(~end_round)) );
 997     mem = ClearArrayNode::clear_memory(ctrl, mem, dest, val, raw_val,
 998                                        start_con, end, &_igvn);
 999   } else if (start_con < 0 && dest_size != top()) {
1000     // Non-constant start, pre-rounded end after the tail of the array.
1001     // This is almost certainly a "round-to-end" operation.
1002     Node* start = slice_idx;
1003     start = ConvI2X(start);
1004     if (scale != 0)
1005       start = transform_later(new LShiftXNode( start, intcon(scale) ));
1006     start = transform_later(new AddXNode(start, MakeConX(abase)) );
1007     if ((bump_bit | clear_low) != 0) {
1008       int to_clear = (bump_bit | clear_low);
1009       // Align up mod 8, then store a jint zero unconditionally
1010       // just before the mod-8 boundary.
1011       if (((abase + bump_bit) & ~to_clear) - bump_bit
1012           < arrayOopDesc::length_offset_in_bytes() + BytesPerInt) {
1013         bump_bit = 0;
1014         assert((abase & to_clear) == 0, "array base must be long-aligned");
1015       } else {
1016         // Bump 'start' up to (or past) the next jint boundary:
1017         start = transform_later( new AddXNode(start, MakeConX(bump_bit)) );
1018         assert((abase & clear_low) == 0, "array base must be int-aligned");
1019       }
1020       // Round bumped 'start' down to jlong boundary in body of array.
1021       start = transform_later(new AndXNode(start, MakeConX(~to_clear)) );
1022       if (bump_bit != 0) {
1023         // Store a zero to the immediately preceding jint:
1024         Node* x1 = transform_later(new AddXNode(start, MakeConX(-bump_bit)) );
1025         Node* p1 = basic_plus_adr(dest, x1);
1026         if (val == NULL) {
1027           assert(raw_val == NULL, "val may not be null");
1028           mem = StoreNode::make(_igvn, ctrl, mem, p1, adr_type, intcon(0), T_INT, MemNode::unordered);
1029         } else {
1030           assert(_igvn.type(val)->isa_narrowoop(), "should be narrow oop");
1031           mem = new StoreNNode(ctrl, mem, p1, adr_type, val, MemNode::unordered);
1032         }
1033         mem = transform_later(mem);
1034       }
1035     }
1036     Node* end = dest_size; // pre-rounded
1037     mem = ClearArrayNode::clear_memory(ctrl, mem, dest, raw_val,
1038                                        start, end, &_igvn);
1039   } else {
1040     // Non-constant start, unrounded non-constant end.
1041     // (Nobody zeroes a random midsection of an array using this routine.)
1042     ShouldNotReachHere();       // fix caller
1043   }
1044 
1045   // Done.
1046   merge_mem->set_memory_at(alias_idx, mem);
1047 }
1048 
1049 bool PhaseMacroExpand::generate_block_arraycopy(Node** ctrl, MergeMemNode** mem, Node* io,
1050                                                 const TypePtr* adr_type,
1051                                                 BasicType basic_elem_type,
1052                                                 AllocateNode* alloc,
1053                                                 Node* src,  Node* src_offset,
1054                                                 Node* dest, Node* dest_offset,
1055                                                 Node* dest_size, bool dest_uninitialized) {
1056   // See if there is an advantage from block transfer.
1057   int scale = exact_log2(type2aelembytes(basic_elem_type));
1058   if (scale >= LogBytesPerLong)
1059     return false;               // it is already a block transfer
1060 
1061   // Look at the alignment of the starting offsets.
1062   int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
1063 
1064   intptr_t src_off_con  = (intptr_t) _igvn.find_int_con(src_offset, -1);
1065   intptr_t dest_off_con = (intptr_t) _igvn.find_int_con(dest_offset, -1);
1066   if (src_off_con < 0 || dest_off_con < 0) {
1067     // At present, we can only understand constants.
1068     return false;
1069   }
1070 
1071   intptr_t src_off  = abase + (src_off_con  << scale);
1072   intptr_t dest_off = abase + (dest_off_con << scale);
1073 
1074   if (((src_off | dest_off) & (BytesPerLong-1)) != 0) {
1075     // Non-aligned; too bad.
1076     // One more chance:  Pick off an initial 32-bit word.
1077     // This is a common case, since abase can be odd mod 8.
1078     if (((src_off | dest_off) & (BytesPerLong-1)) == BytesPerInt &&
1079         ((src_off ^ dest_off) & (BytesPerLong-1)) == 0) {
1080       Node* sptr = basic_plus_adr(src,  src_off);
1081       Node* dptr = basic_plus_adr(dest, dest_off);
1082       const TypePtr* s_adr_type = _igvn.type(sptr)->is_ptr();
1083       assert(s_adr_type->isa_aryptr(), "impossible slice");
1084       uint s_alias_idx = C->get_alias_index(s_adr_type);
1085       uint d_alias_idx = C->get_alias_index(adr_type);
1086       bool is_mismatched = (basic_elem_type != T_INT);
1087       Node* sval = transform_later(
1088           LoadNode::make(_igvn, *ctrl, (*mem)->memory_at(s_alias_idx), sptr, s_adr_type,
1089                          TypeInt::INT, T_INT, MemNode::unordered, LoadNode::DependsOnlyOnTest,
1090                          false /*unaligned*/, is_mismatched));
1091       Node* st = transform_later(
1092           StoreNode::make(_igvn, *ctrl, (*mem)->memory_at(d_alias_idx), dptr, adr_type,
1093                           sval, T_INT, MemNode::unordered));
1094       if (is_mismatched) {
1095         st->as_Store()->set_mismatched_access();
1096       }
1097       (*mem)->set_memory_at(d_alias_idx, st);
1098       src_off += BytesPerInt;
1099       dest_off += BytesPerInt;
1100     } else {
1101       return false;
1102     }
1103   }
1104   assert(src_off % BytesPerLong == 0, "");
1105   assert(dest_off % BytesPerLong == 0, "");
1106 
1107   // Do this copy by giant steps.
1108   Node* sptr  = basic_plus_adr(src,  src_off);
1109   Node* dptr  = basic_plus_adr(dest, dest_off);
1110   Node* countx = dest_size;
1111   countx = transform_later(new SubXNode(countx, MakeConX(dest_off)));
1112   countx = transform_later(new URShiftXNode(countx, intcon(LogBytesPerLong)));
1113 
1114   bool disjoint_bases = true;   // since alloc != NULL
1115   generate_unchecked_arraycopy(ctrl, mem,
1116                                adr_type, T_LONG, disjoint_bases,
1117                                sptr, NULL, dptr, NULL, countx, dest_uninitialized);
1118 
1119   return true;
1120 }
1121 
1122 // Helper function; generates code for the slow case.
1123 // We make a call to a runtime method which emulates the native method,
1124 // but without the native wrapper overhead.
1125 MergeMemNode* PhaseMacroExpand::generate_slow_arraycopy(ArrayCopyNode *ac,
1126                                                         Node** ctrl, Node* mem, Node** io,
1127                                                         const TypePtr* adr_type,
1128                                                         Node* src,  Node* src_offset,
1129                                                         Node* dest, Node* dest_offset,
1130                                                         Node* copy_length, bool dest_uninitialized) {
1131   assert(!dest_uninitialized, "Invariant");
1132 
1133   const TypeFunc* call_type = OptoRuntime::slow_arraycopy_Type();
1134   CallNode* call = new CallStaticJavaNode(call_type, OptoRuntime::slow_arraycopy_Java(),
1135                                           "slow_arraycopy", TypePtr::BOTTOM);
1136 
1137   call->init_req(TypeFunc::Control, *ctrl);
1138   call->init_req(TypeFunc::I_O    , *io);
1139   call->init_req(TypeFunc::Memory , mem);
1140   call->init_req(TypeFunc::ReturnAdr, top());
1141   call->init_req(TypeFunc::FramePtr, top());
1142   call->init_req(TypeFunc::Parms+0, src);
1143   call->init_req(TypeFunc::Parms+1, src_offset);
1144   call->init_req(TypeFunc::Parms+2, dest);
1145   call->init_req(TypeFunc::Parms+3, dest_offset);
1146   call->init_req(TypeFunc::Parms+4, copy_length);
1147   call->copy_call_debug_info(&_igvn, ac);
1148 
1149   call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
1150   _igvn.replace_node(ac, call);
1151   transform_later(call);
1152 
1153   _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1154   *ctrl = _callprojs->fallthrough_catchproj->clone();
1155   transform_later(*ctrl);
1156 
1157   Node* m = _callprojs->fallthrough_memproj->clone();
1158   transform_later(m);
1159 
1160   uint alias_idx = C->get_alias_index(adr_type);
1161   MergeMemNode* out_mem;
1162   if (alias_idx != Compile::AliasIdxBot) {
1163     out_mem = MergeMemNode::make(mem);
1164     out_mem->set_memory_at(alias_idx, m);
1165   } else {
1166     out_mem = MergeMemNode::make(m);
1167   }
1168   transform_later(out_mem);
1169 
1170   // When src is negative and arraycopy is before an infinite loop,_callprojs.fallthrough_ioproj
1171   // could be NULL. Skip clone and update NULL fallthrough_ioproj.
1172   if (_callprojs->fallthrough_ioproj != NULL) {
1173     *io = _callprojs->fallthrough_ioproj->clone();
1174     transform_later(*io);
1175   } else {
1176     *io = NULL;
1177   }
1178 
1179   return out_mem;
1180 }
1181 
1182 // Helper function; generates code for cases requiring runtime checks.
1183 Node* PhaseMacroExpand::generate_checkcast_arraycopy(Node** ctrl, MergeMemNode** mem,
1184                                                      const TypePtr* adr_type,
1185                                                      Node* dest_elem_klass,
1186                                                      Node* src,  Node* src_offset,
1187                                                      Node* dest, Node* dest_offset,
1188                                                      Node* copy_length, bool dest_uninitialized) {
1189   if ((*ctrl)->is_top())  return NULL;
1190 
1191   address copyfunc_addr = StubRoutines::checkcast_arraycopy(dest_uninitialized);
1192   if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.
1193     return NULL;
1194   }
1195 
1196   // Pick out the parameters required to perform a store-check
1197   // for the target array.  This is an optimistic check.  It will
1198   // look in each non-null element's class, at the desired klass's
1199   // super_check_offset, for the desired klass.
1200   int sco_offset = in_bytes(Klass::super_check_offset_offset());
1201   Node* p3 = basic_plus_adr(dest_elem_klass, sco_offset);
1202   Node* n3 = new LoadINode(NULL, *mem /*memory(p3)*/, p3, _igvn.type(p3)->is_ptr(), TypeInt::INT, MemNode::unordered);
1203   Node* check_offset = ConvI2X(transform_later(n3));
1204   Node* check_value  = dest_elem_klass;
1205 
1206   Node* src_start  = array_element_address(src,  src_offset,  T_OBJECT);
1207   Node* dest_start = array_element_address(dest, dest_offset, T_OBJECT);
1208 
1209   const TypeFunc* call_type = OptoRuntime::checkcast_arraycopy_Type();
1210   Node* call = make_leaf_call(*ctrl, *mem, call_type, copyfunc_addr, "checkcast_arraycopy", adr_type,
1211                               src_start, dest_start, copy_length XTOP, check_offset XTOP, check_value);
1212 
1213   finish_arraycopy_call(call, ctrl, mem, adr_type);
1214 
1215   Node* proj =  new ProjNode(call, TypeFunc::Parms);
1216   transform_later(proj);
1217 
1218   return proj;
1219 }
1220 
1221 // Helper function; generates code for cases requiring runtime checks.
1222 Node* PhaseMacroExpand::generate_generic_arraycopy(Node** ctrl, MergeMemNode** mem,
1223                                                    const TypePtr* adr_type,
1224                                                    Node* src,  Node* src_offset,
1225                                                    Node* dest, Node* dest_offset,
1226                                                    Node* copy_length, bool dest_uninitialized) {
1227   if ((*ctrl)->is_top()) return NULL;
1228   assert(!dest_uninitialized, "Invariant");
1229 
1230   address copyfunc_addr = StubRoutines::generic_arraycopy();
1231   if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.
1232     return NULL;
1233   }
1234 
1235   const TypeFunc* call_type = OptoRuntime::generic_arraycopy_Type();
1236   Node* call = make_leaf_call(*ctrl, *mem, call_type, copyfunc_addr, "generic_arraycopy", adr_type,
1237                               src, src_offset, dest, dest_offset, copy_length);
1238 
1239   finish_arraycopy_call(call, ctrl, mem, adr_type);
1240 
1241   Node* proj =  new ProjNode(call, TypeFunc::Parms);
1242   transform_later(proj);
1243 
1244   return proj;
1245 }
1246 
1247 // Helper function; generates the fast out-of-line call to an arraycopy stub.
1248 bool PhaseMacroExpand::generate_unchecked_arraycopy(Node** ctrl, MergeMemNode** mem,
1249                                                     const TypePtr* adr_type,
1250                                                     BasicType basic_elem_type,
1251                                                     bool disjoint_bases,
1252                                                     Node* src,  Node* src_offset,
1253                                                     Node* dest, Node* dest_offset,
1254                                                     Node* copy_length, bool dest_uninitialized) {
1255   if ((*ctrl)->is_top()) return false;
1256 
1257   Node* src_start  = src;
1258   Node* dest_start = dest;
1259   if (src_offset != NULL || dest_offset != NULL) {
1260     src_start =  array_element_address(src, src_offset, basic_elem_type);
1261     dest_start = array_element_address(dest, dest_offset, basic_elem_type);
1262   }
1263 
1264   // Figure out which arraycopy runtime method to call.
1265   const char* copyfunc_name = "arraycopy";
1266   address     copyfunc_addr =
1267       basictype2arraycopy(basic_elem_type, src_offset, dest_offset,
1268                           disjoint_bases, copyfunc_name, dest_uninitialized);
1269 
1270   Node* result_memory = NULL;
1271   RegionNode* exit_block = NULL;
1272   if (ArrayOperationPartialInlineSize > 0 && is_subword_type(basic_elem_type) &&
1273     Matcher::vector_width_in_bytes(basic_elem_type) >= 16) {
1274     generate_partial_inlining_block(ctrl, mem, adr_type, &exit_block, &result_memory,
1275                                     copy_length, src_start, dest_start, basic_elem_type);
1276   }
1277 
1278   const TypeFunc* call_type = OptoRuntime::fast_arraycopy_Type();
1279   Node* call = make_leaf_call(*ctrl, *mem, call_type, copyfunc_addr, copyfunc_name, adr_type,
1280                               src_start, dest_start, copy_length XTOP);
1281 
1282   finish_arraycopy_call(call, ctrl, mem, adr_type);
1283 
1284   // Connecting remaining edges for exit_block coming from stub_block.
1285   if (exit_block) {
1286     exit_block->init_req(2, *ctrl);
1287 
1288     // Memory edge corresponding to stub_region.
1289     result_memory->init_req(2, *mem);
1290 
1291     uint alias_idx = C->get_alias_index(adr_type);
1292     if (alias_idx != Compile::AliasIdxBot) {
1293       *mem = MergeMemNode::make(*mem);
1294       (*mem)->set_memory_at(alias_idx, result_memory);
1295     } else {
1296       *mem = MergeMemNode::make(result_memory);
1297     }
1298     transform_later(*mem);
1299     *ctrl = exit_block;
1300     return true;
1301   }
1302   return false;
1303 }
1304 
1305 const TypePtr* PhaseMacroExpand::adjust_for_flat_array(const TypeAryPtr* top_dest, Node*& src_offset,
1306                                                        Node*& dest_offset, Node*& length, BasicType& dest_elem,
1307                                                        Node*& dest_length) {
1308 #ifdef ASSERT
1309   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1310   bool needs_barriers = top_dest->elem()->inline_klass()->contains_oops() &&
1311     bs->array_copy_requires_gc_barriers(dest_length != NULL, T_OBJECT, false, false, BarrierSetC2::Optimization);
1312   assert(!needs_barriers || StressReflectiveCode, "Flat arracopy would require GC barriers");
1313 #endif
1314   int elem_size = top_dest->klass()->as_flat_array_klass()->element_byte_size();
1315   if (elem_size >= 8) {
1316     if (elem_size > 8) {
1317       // treat as array of long but scale length, src offset and dest offset
1318       assert((elem_size % 8) == 0, "not a power of 2?");
1319       int factor = elem_size / 8;
1320       length = transform_later(new MulINode(length, intcon(factor)));
1321       src_offset = transform_later(new MulINode(src_offset, intcon(factor)));
1322       dest_offset = transform_later(new MulINode(dest_offset, intcon(factor)));
1323       if (dest_length != NULL) {
1324         dest_length = transform_later(new MulINode(dest_length, intcon(factor)));
1325       }
1326       elem_size = 8;
1327     }
1328     dest_elem = T_LONG;
1329   } else if (elem_size == 4) {
1330     dest_elem = T_INT;
1331   } else if (elem_size == 2) {
1332     dest_elem = T_CHAR;
1333   } else if (elem_size == 1) {
1334     dest_elem = T_BYTE;
1335   } else {
1336     ShouldNotReachHere();
1337   }
1338   return TypeRawPtr::BOTTOM;
1339 }
1340 
1341 #undef XTOP
1342 
1343 void PhaseMacroExpand::expand_arraycopy_node(ArrayCopyNode *ac) {
1344   Node* ctrl = ac->in(TypeFunc::Control);
1345   Node* io = ac->in(TypeFunc::I_O);
1346   Node* src = ac->in(ArrayCopyNode::Src);
1347   Node* src_offset = ac->in(ArrayCopyNode::SrcPos);
1348   Node* dest = ac->in(ArrayCopyNode::Dest);
1349   Node* dest_offset = ac->in(ArrayCopyNode::DestPos);
1350   Node* length = ac->in(ArrayCopyNode::Length);
1351   MergeMemNode* merge_mem = NULL;
1352 
1353   if (ac->is_clonebasic()) {
1354     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1355     bs->clone_at_expansion(this, ac);
1356     return;
1357   } else if (ac->is_copyof() || ac->is_copyofrange() || ac->is_clone_oop_array()) {
1358     const Type* src_type = _igvn.type(src);
1359     const Type* dest_type = _igvn.type(dest);
1360     const TypeAryPtr* top_src = src_type->isa_aryptr();
1361     const TypeAryPtr* top_dest = dest_type->isa_aryptr();
1362     BasicType dest_elem = T_OBJECT;
1363     if (top_dest != NULL && top_dest->klass() != NULL) {
1364       dest_elem = top_dest->klass()->as_array_klass()->element_type()->basic_type();
1365     }
1366     if (dest_elem == T_ARRAY || (dest_elem == T_INLINE_TYPE && top_dest->klass()->is_obj_array_klass())) {
1367       dest_elem = T_OBJECT;
1368     }
1369     if (top_src != NULL && top_src->is_flat()) {
1370       // If src is flat, dest is guaranteed to be flat as well
1371       dest_elem = T_INLINE_TYPE;
1372       top_dest = top_src;
1373     }
1374 
1375     Node* mem = ac->in(TypeFunc::Memory);
1376     merge_mem = MergeMemNode::make(mem);
1377     transform_later(merge_mem);
1378 
1379     AllocateArrayNode* alloc = NULL;
1380     Node* dest_length = NULL;
1381     if (ac->is_alloc_tightly_coupled()) {
1382       alloc = AllocateArrayNode::Ideal_array_allocation(dest, &_igvn);
1383       assert(alloc != NULL, "expect alloc");
1384       dest_length = alloc->in(AllocateNode::ALength);
1385     }
1386 
1387     const TypePtr* adr_type = NULL;
1388     if (dest_elem == T_INLINE_TYPE) {
1389       assert(dest_length != NULL || StressReflectiveCode, "must be tightly coupled");
1390       // Copy to a flat array modifies multiple memory slices. Conservatively insert a barrier
1391       // on all slices to prevent writes into the source from floating below the arraycopy.
1392       insert_mem_bar(&ctrl, &mem, Op_MemBarCPUOrder);
1393       adr_type = adjust_for_flat_array(top_dest, src_offset, dest_offset, length, dest_elem, dest_length);
1394     } else {
1395       adr_type = dest_type->is_oopptr()->add_offset(Type::OffsetBot);
1396       if (ac->_dest_type != TypeOopPtr::BOTTOM) {
1397         adr_type = ac->_dest_type->add_offset(Type::OffsetBot)->is_ptr();
1398       }
1399       if (ac->_src_type != ac->_dest_type) {
1400         adr_type = TypeRawPtr::BOTTOM;
1401       }
1402     }
1403     generate_arraycopy(ac, alloc, &ctrl, merge_mem, &io,
1404                        adr_type, dest_elem,
1405                        src, src_offset, dest, dest_offset, length,
1406                        dest_length,
1407                        true, !ac->is_copyofrange());
1408     return;
1409   }
1410 
1411   AllocateArrayNode* alloc = NULL;
1412   if (ac->is_alloc_tightly_coupled()) {
1413     alloc = AllocateArrayNode::Ideal_array_allocation(dest, &_igvn);
1414     assert(alloc != NULL, "expect alloc");
1415   }
1416 
1417   assert(ac->is_arraycopy() || ac->is_arraycopy_validated(), "should be an arraycopy");
1418 
1419   // Compile time checks.  If any of these checks cannot be verified at compile time,
1420   // we do not make a fast path for this call.  Instead, we let the call remain as it
1421   // is.  The checks we choose to mandate at compile time are:
1422   //
1423   // (1) src and dest are arrays.
1424   const Type* src_type = src->Value(&_igvn);
1425   const Type* dest_type = dest->Value(&_igvn);
1426   const TypeAryPtr* top_src = src_type->isa_aryptr();
1427   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
1428 
1429   BasicType src_elem = T_CONFLICT;
1430   BasicType dest_elem = T_CONFLICT;
1431 
1432   if (top_dest != NULL && top_dest->klass() != NULL) {
1433     dest_elem = top_dest->klass()->as_array_klass()->element_type()->basic_type();
1434   }
1435   if (top_src != NULL && top_src->klass() != NULL) {
1436     src_elem = top_src->klass()->as_array_klass()->element_type()->basic_type();
1437   }
1438   if (src_elem == T_ARRAY || (src_elem == T_INLINE_TYPE && top_src->klass()->is_obj_array_klass())) {
1439     src_elem = T_OBJECT;
1440   }
1441   if (dest_elem == T_ARRAY || (dest_elem == T_INLINE_TYPE && top_dest->klass()->is_obj_array_klass())) {
1442     dest_elem = T_OBJECT;
1443   }
1444 
1445   if (ac->is_arraycopy_validated() && dest_elem != T_CONFLICT && src_elem == T_CONFLICT) {
1446     src_elem = dest_elem;
1447   }
1448 
1449   if (src_elem == T_CONFLICT || dest_elem == T_CONFLICT) {
1450     // Conservatively insert a memory barrier on all memory slices.
1451     // Do not let writes into the source float below the arraycopy.
1452     {
1453       Node* mem = ac->in(TypeFunc::Memory);
1454       insert_mem_bar(&ctrl, &mem, Op_MemBarCPUOrder);
1455 
1456       merge_mem = MergeMemNode::make(mem);
1457       transform_later(merge_mem);
1458     }
1459 
1460     // Call StubRoutines::generic_arraycopy stub.
1461     Node* mem = generate_arraycopy(ac, NULL, &ctrl, merge_mem, &io,
1462                                    TypeRawPtr::BOTTOM, T_CONFLICT,
1463                                    src, src_offset, dest, dest_offset, length,
1464                                    NULL,
1465                                    // If a  negative length guard was generated for the ArrayCopyNode,
1466                                    // the length of the array can never be negative.
1467                                    false, ac->has_negative_length_guard());
1468     return;
1469   }
1470 
1471   assert(!ac->is_arraycopy_validated() || (src_elem == dest_elem && dest_elem != T_VOID) ||
1472          (src_elem == T_INLINE_TYPE && StressReflectiveCode), "validated but different basic types");
1473 
1474   // (2) src and dest arrays must have elements of the same BasicType
1475   // Figure out the size and type of the elements we will be copying.
1476   //
1477   // We have no stub to copy flattened inline type arrays with oop
1478   // fields if we need to emit write barriers.
1479   //
1480   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1481   if (src_elem != dest_elem || dest_elem == T_VOID ||
1482       (dest_elem == T_INLINE_TYPE && top_dest->elem()->inline_klass()->contains_oops() &&
1483        bs->array_copy_requires_gc_barriers(alloc != NULL, T_OBJECT, false, false, BarrierSetC2::Optimization))) {
1484     // The component types are not the same or are not recognized.  Punt.
1485     // (But, avoid the native method wrapper to JVM_ArrayCopy.)
1486     {
1487       Node* mem = ac->in(TypeFunc::Memory);
1488       merge_mem = generate_slow_arraycopy(ac, &ctrl, mem, &io, TypePtr::BOTTOM, src, src_offset, dest, dest_offset, length, false);
1489     }
1490 
1491     _igvn.replace_node(_callprojs->fallthrough_memproj, merge_mem);
1492     if (_callprojs->fallthrough_ioproj != NULL) {
1493       _igvn.replace_node(_callprojs->fallthrough_ioproj, io);
1494     }
1495     _igvn.replace_node(_callprojs->fallthrough_catchproj, ctrl);
1496     return;
1497   }
1498 
1499   //---------------------------------------------------------------------------
1500   // We will make a fast path for this call to arraycopy.
1501 
1502   // We have the following tests left to perform:
1503   //
1504   // (3) src and dest must not be null.
1505   // (4) src_offset must not be negative.
1506   // (5) dest_offset must not be negative.
1507   // (6) length must not be negative.
1508   // (7) src_offset + length must not exceed length of src.
1509   // (8) dest_offset + length must not exceed length of dest.
1510   // (9) each element of an oop array must be assignable
1511 
1512   Node* mem = ac->in(TypeFunc::Memory);
1513   merge_mem = MergeMemNode::make(mem);
1514   transform_later(merge_mem);
1515 
1516   RegionNode* slow_region = new RegionNode(1);
1517   transform_later(slow_region);
1518 
1519   if (!ac->is_arraycopy_validated()) {
1520     // (3) operands must not be null
1521     // We currently perform our null checks with the null_check routine.
1522     // This means that the null exceptions will be reported in the caller
1523     // rather than (correctly) reported inside of the native arraycopy call.
1524     // This should be corrected, given time.  We do our null check with the
1525     // stack pointer restored.
1526     // null checks done library_call.cpp
1527 
1528     // (4) src_offset must not be negative.
1529     generate_negative_guard(&ctrl, src_offset, slow_region);
1530 
1531     // (5) dest_offset must not be negative.
1532     generate_negative_guard(&ctrl, dest_offset, slow_region);
1533 
1534     // (6) length must not be negative (moved to generate_arraycopy()).
1535     // generate_negative_guard(length, slow_region);
1536 
1537     // (7) src_offset + length must not exceed length of src.
1538     Node* alen = ac->in(ArrayCopyNode::SrcLen);
1539     assert(alen != NULL, "need src len");
1540     generate_limit_guard(&ctrl,
1541                          src_offset, length,
1542                          alen,
1543                          slow_region);
1544 
1545     // (8) dest_offset + length must not exceed length of dest.
1546     alen = ac->in(ArrayCopyNode::DestLen);
1547     assert(alen != NULL, "need dest len");
1548     generate_limit_guard(&ctrl,
1549                          dest_offset, length,
1550                          alen,
1551                          slow_region);
1552 
1553     // (9) each element of an oop array must be assignable
1554     // The generate_arraycopy subroutine checks this.
1555 
1556     // Handle inline type arrays
1557     if (!top_src->is_flat()) {
1558       if (UseFlatArray && !top_src->is_not_flat()) {
1559         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
1560         generate_flat_array_guard(&ctrl, src, slow_region);
1561       }
1562       if (EnableValhalla) {
1563         // No validation. The subtype check emitted at macro expansion time will not go to the slow
1564         // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
1565         generate_null_free_array_guard(&ctrl, dest, slow_region);
1566       }
1567     } else {
1568       assert(top_dest->is_flat(), "dest array must be flat");
1569     }
1570   }
1571 
1572   // This is where the memory effects are placed:
1573   const TypePtr* adr_type = NULL;
1574   Node* dest_length = (alloc != NULL) ? alloc->in(AllocateNode::ALength) : NULL;
1575 
1576   if (dest_elem == T_INLINE_TYPE) {
1577     // Copy to a flat array modifies multiple memory slices. Conservatively insert a barrier
1578     // on all slices to prevent writes into the source from floating below the arraycopy.
1579     insert_mem_bar(&ctrl, &mem, Op_MemBarCPUOrder);
1580     adr_type = adjust_for_flat_array(top_dest, src_offset, dest_offset, length, dest_elem, dest_length);
1581   } else if (ac->_dest_type != TypeOopPtr::BOTTOM) {
1582     adr_type = ac->_dest_type->add_offset(Type::OffsetBot)->is_ptr();
1583   } else {
1584     adr_type = TypeAryPtr::get_array_body_type(dest_elem);
1585   }
1586 
1587   generate_arraycopy(ac, alloc, &ctrl, merge_mem, &io,
1588                      adr_type, dest_elem,
1589                      src, src_offset, dest, dest_offset, length,
1590                      dest_length,
1591                      // If a  negative length guard was generated for the ArrayCopyNode,
1592                      // the length of the array can never be negative.
1593                      false, ac->has_negative_length_guard(),
1594                      slow_region);
1595 }