1 /*
   2  * Copyright (c) 2012, 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 "oops/objArrayKlass.hpp"
  27 #include "opto/convertnode.hpp"
  28 #include "opto/graphKit.hpp"
  29 #include "opto/macro.hpp"
  30 #include "opto/runtime.hpp"
  31 
  32 
  33 void PhaseMacroExpand::insert_mem_bar(Node** ctrl, Node** mem, int opcode, Node* precedent) {
  34   MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
  35   mb->init_req(TypeFunc::Control, *ctrl);
  36   mb->init_req(TypeFunc::Memory, *mem);
  37   transform_later(mb);
  38   *ctrl = new ProjNode(mb,TypeFunc::Control);
  39   transform_later(*ctrl);
  40   Node* mem_proj = new ProjNode(mb,TypeFunc::Memory);
  41   transform_later(mem_proj);
  42   *mem = mem_proj;
  43 }
  44 
  45 Node* PhaseMacroExpand::array_element_address(Node* ary, Node* idx, BasicType elembt) {
  46   uint shift  = exact_log2(type2aelembytes(elembt));
  47   uint header = arrayOopDesc::base_offset_in_bytes(elembt);
  48   Node* base =  basic_plus_adr(ary, header);
  49 #ifdef _LP64
  50   // see comment in GraphKit::array_element_address
  51   int index_max = max_jint - 1;  // array size is max_jint, index is one less
  52   const TypeLong* lidxtype = TypeLong::make(CONST64(0), index_max, Type::WidenMax);
  53   idx = transform_later( new ConvI2LNode(idx, lidxtype) );
  54 #endif
  55   Node* scale = new LShiftXNode(idx, intcon(shift));
  56   transform_later(scale);
  57   return basic_plus_adr(ary, base, scale);
  58 }
  59 
  60 Node* PhaseMacroExpand::ConvI2L(Node* offset) {
  61   return transform_later(new ConvI2LNode(offset));
  62 }
  63 
  64 Node* PhaseMacroExpand::make_leaf_call(Node* ctrl, Node* mem,
  65                                        const TypeFunc* call_type, address call_addr,
  66                                        const char* call_name,
  67                                        const TypePtr* adr_type,
  68                                        Node* parm0, Node* parm1,
  69                                        Node* parm2, Node* parm3,
  70                                        Node* parm4, Node* parm5,
  71                                        Node* parm6, Node* parm7) {
  72   int size = call_type->domain()->cnt();
  73   Node* call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);
  74   call->init_req(TypeFunc::Control, ctrl);
  75   call->init_req(TypeFunc::I_O    , top());
  76   call->init_req(TypeFunc::Memory , mem);
  77   call->init_req(TypeFunc::ReturnAdr, top());
  78   call->init_req(TypeFunc::FramePtr, top());
  79 
  80   // Hook each parm in order.  Stop looking at the first NULL.
  81   if (parm0 != NULL) { call->init_req(TypeFunc::Parms+0, parm0);
  82   if (parm1 != NULL) { call->init_req(TypeFunc::Parms+1, parm1);
  83   if (parm2 != NULL) { call->init_req(TypeFunc::Parms+2, parm2);
  84   if (parm3 != NULL) { call->init_req(TypeFunc::Parms+3, parm3);
  85   if (parm4 != NULL) { call->init_req(TypeFunc::Parms+4, parm4);
  86   if (parm5 != NULL) { call->init_req(TypeFunc::Parms+5, parm5);
  87   if (parm6 != NULL) { call->init_req(TypeFunc::Parms+6, parm6);
  88   if (parm7 != NULL) { call->init_req(TypeFunc::Parms+7, parm7);
  89     /* close each nested if ===> */  } } } } } } } }
  90   assert(call->in(call->req()-1) != NULL, "must initialize all parms");
  91 
  92   return call;
  93 }
  94 
  95 
  96 //------------------------------generate_guard---------------------------
  97 // Helper function for generating guarded fast-slow graph structures.
  98 // The given 'test', if true, guards a slow path.  If the test fails
  99 // then a fast path can be taken.  (We generally hope it fails.)
 100 // In all cases, GraphKit::control() is updated to the fast path.
 101 // The returned value represents the control for the slow path.
 102 // The return value is never 'top'; it is either a valid control
 103 // or NULL if it is obvious that the slow path can never be taken.
 104 // Also, if region and the slow control are not NULL, the slow edge
 105 // is appended to the region.
 106 Node* PhaseMacroExpand::generate_guard(Node** ctrl, Node* test, RegionNode* region, float true_prob) {
 107   if ((*ctrl)->is_top()) {
 108     // Already short circuited.
 109     return NULL;
 110   }
 111   // Build an if node and its projections.
 112   // If test is true we take the slow path, which we assume is uncommon.
 113   if (_igvn.type(test) == TypeInt::ZERO) {
 114     // The slow branch is never taken.  No need to build this guard.
 115     return NULL;
 116   }
 117 
 118   IfNode* iff = new IfNode(*ctrl, test, true_prob, COUNT_UNKNOWN);
 119   transform_later(iff);
 120 
 121   Node* if_slow = new IfTrueNode(iff);
 122   transform_later(if_slow);
 123 
 124   if (region != NULL) {
 125     region->add_req(if_slow);
 126   }
 127 
 128   Node* if_fast = new IfFalseNode(iff);
 129   transform_later(if_fast);
 130 
 131   *ctrl = if_fast;
 132 
 133   return if_slow;
 134 }
 135 
 136 inline Node* PhaseMacroExpand::generate_slow_guard(Node** ctrl, Node* test, RegionNode* region) {
 137   return generate_guard(ctrl, test, region, PROB_UNLIKELY_MAG(3));
 138 }
 139 
 140 void PhaseMacroExpand::generate_negative_guard(Node** ctrl, Node* index, RegionNode* region) {
 141   if ((*ctrl)->is_top())
 142     return;                // already stopped
 143   if (_igvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 144     return;                // index is already adequately typed
 145   Node* cmp_lt = new CmpINode(index, intcon(0));
 146   transform_later(cmp_lt);
 147   Node* bol_lt = new BoolNode(cmp_lt, BoolTest::lt);
 148   transform_later(bol_lt);
 149   generate_guard(ctrl, bol_lt, region, PROB_MIN);
 150 }
 151 
 152 void PhaseMacroExpand::generate_limit_guard(Node** ctrl, Node* offset, Node* subseq_length, Node* array_length, RegionNode* region) {
 153   if ((*ctrl)->is_top())
 154     return;                // already stopped
 155   bool zero_offset = _igvn.type(offset) == TypeInt::ZERO;
 156   if (zero_offset && subseq_length->eqv_uncast(array_length))
 157     return;                // common case of whole-array copy
 158   Node* last = subseq_length;
 159   if (!zero_offset) {            // last += offset
 160     last = new AddINode(last, offset);
 161     transform_later(last);
 162   }
 163   Node* cmp_lt = new CmpUNode(array_length, last);
 164   transform_later(cmp_lt);
 165   Node* bol_lt = new BoolNode(cmp_lt, BoolTest::lt);
 166   transform_later(bol_lt);
 167   generate_guard(ctrl, bol_lt, region, PROB_MIN);
 168 }
 169 
 170 Node* PhaseMacroExpand::generate_nonpositive_guard(Node** ctrl, Node* index, bool never_negative) {
 171   if ((*ctrl)->is_top())  return NULL;
 172 
 173   if (_igvn.type(index)->higher_equal(TypeInt::POS1)) // [1,maxint]
 174     return NULL;                // index is already adequately typed
 175   Node* cmp_le = new CmpINode(index, intcon(0));
 176   transform_later(cmp_le);
 177   BoolTest::mask le_or_eq = (never_negative ? BoolTest::eq : BoolTest::le);
 178   Node* bol_le = new BoolNode(cmp_le, le_or_eq);
 179   transform_later(bol_le);
 180   Node* is_notp = generate_guard(ctrl, bol_le, NULL, PROB_MIN);
 181 
 182   return is_notp;
 183 }
 184 
 185 void PhaseMacroExpand::finish_arraycopy_call(Node* call, Node** ctrl, MergeMemNode** mem, const TypePtr* adr_type) {
 186   transform_later(call);
 187 
 188   *ctrl = new ProjNode(call,TypeFunc::Control);
 189   transform_later(*ctrl);
 190   Node* newmem = new ProjNode(call, TypeFunc::Memory);
 191   transform_later(newmem);
 192 
 193   uint alias_idx = C->get_alias_index(adr_type);
 194   if (alias_idx != Compile::AliasIdxBot) {
 195     *mem = MergeMemNode::make(*mem);
 196     (*mem)->set_memory_at(alias_idx, newmem);
 197   } else {
 198     *mem = MergeMemNode::make(newmem);
 199   }
 200   transform_later(*mem);
 201 }
 202 
 203 address PhaseMacroExpand::basictype2arraycopy(BasicType t,
 204                                               Node* src_offset,
 205                                               Node* dest_offset,
 206                                               bool disjoint_bases,
 207                                               const char* &name,
 208                                               bool dest_uninitialized) {
 209   const TypeInt* src_offset_inttype  = _igvn.find_int_type(src_offset);;
 210   const TypeInt* dest_offset_inttype = _igvn.find_int_type(dest_offset);;
 211 
 212   bool aligned = false;
 213   bool disjoint = disjoint_bases;
 214 
 215   // if the offsets are the same, we can treat the memory regions as
 216   // disjoint, because either the memory regions are in different arrays,
 217   // or they are identical (which we can treat as disjoint.)  We can also
 218   // treat a copy with a destination index  less that the source index
 219   // as disjoint since a low->high copy will work correctly in this case.
 220   if (src_offset_inttype != NULL && src_offset_inttype->is_con() &&
 221       dest_offset_inttype != NULL && dest_offset_inttype->is_con()) {
 222     // both indices are constants
 223     int s_offs = src_offset_inttype->get_con();
 224     int d_offs = dest_offset_inttype->get_con();
 225     int element_size = type2aelembytes(t);
 226     aligned = ((arrayOopDesc::base_offset_in_bytes(t) + s_offs * element_size) % HeapWordSize == 0) &&
 227               ((arrayOopDesc::base_offset_in_bytes(t) + d_offs * element_size) % HeapWordSize == 0);
 228     if (s_offs >= d_offs)  disjoint = true;
 229   } else if (src_offset == dest_offset && src_offset != NULL) {
 230     // This can occur if the offsets are identical non-constants.
 231     disjoint = true;
 232   }
 233 
 234   return StubRoutines::select_arraycopy_function(t, aligned, disjoint, name, dest_uninitialized);
 235 }
 236 
 237 #define COMMA ,
 238 #define XTOP LP64_ONLY(COMMA top())
 239 
 240 // Generate an optimized call to arraycopy.
 241 // Caller must guard against non-arrays.
 242 // Caller must determine a common array basic-type for both arrays.
 243 // Caller must validate offsets against array bounds.
 244 // The slow_region has already collected guard failure paths
 245 // (such as out of bounds length or non-conformable array types).
 246 // The generated code has this shape, in general:
 247 //
 248 //     if (length == 0)  return   // via zero_path
 249 //     slowval = -1
 250 //     if (types unknown) {
 251 //       slowval = call generic copy loop
 252 //       if (slowval == 0)  return  // via checked_path
 253 //     } else if (indexes in bounds) {
 254 //       if ((is object array) && !(array type check)) {
 255 //         slowval = call checked copy loop
 256 //         if (slowval == 0)  return  // via checked_path
 257 //       } else {
 258 //         call bulk copy loop
 259 //         return  // via fast_path
 260 //       }
 261 //     }
 262 //     // adjust params for remaining work:
 263 //     if (slowval != -1) {
 264 //       n = -1^slowval; src_offset += n; dest_offset += n; length -= n
 265 //     }
 266 //   slow_region:
 267 //     call slow arraycopy(src, src_offset, dest, dest_offset, length)
 268 //     return  // via slow_call_path
 269 //
 270 // This routine is used from several intrinsics:  System.arraycopy,
 271 // Object.clone (the array subcase), and Arrays.copyOf[Range].
 272 //
 273 Node* PhaseMacroExpand::generate_arraycopy(ArrayCopyNode *ac, AllocateArrayNode* alloc,
 274                                            Node** ctrl, MergeMemNode* mem, Node** io,
 275                                            const TypePtr* adr_type,
 276                                            BasicType basic_elem_type,
 277                                            Node* src,  Node* src_offset,
 278                                            Node* dest, Node* dest_offset,
 279                                            Node* copy_length,
 280                                            bool disjoint_bases,
 281                                            bool length_never_negative,
 282                                            RegionNode* slow_region) {
 283   if (slow_region == NULL) {
 284     slow_region = new RegionNode(1);
 285     transform_later(slow_region);
 286   }
 287 
 288   Node* original_dest      = dest;
 289   bool  dest_uninitialized = false;
 290 
 291   // See if this is the initialization of a newly-allocated array.
 292   // If so, we will take responsibility here for initializing it to zero.
 293   // (Note:  Because tightly_coupled_allocation performs checks on the
 294   // out-edges of the dest, we need to avoid making derived pointers
 295   // from it until we have checked its uses.)
 296   if (ReduceBulkZeroing
 297       && !ZeroTLAB              // pointless if already zeroed
 298       && basic_elem_type != T_CONFLICT // avoid corner case
 299       && !src->eqv_uncast(dest)
 300       && alloc != NULL
 301       && _igvn.find_int_con(alloc->in(AllocateNode::ALength), 1) > 0
 302       && alloc->maybe_set_complete(&_igvn)) {
 303     // "You break it, you buy it."
 304     InitializeNode* init = alloc->initialization();
 305     assert(init->is_complete(), "we just did this");
 306     init->set_complete_with_arraycopy();
 307     assert(dest->is_CheckCastPP(), "sanity");
 308     assert(dest->in(0)->in(0) == init, "dest pinned");
 309     adr_type = TypeRawPtr::BOTTOM;  // all initializations are into raw memory
 310     // From this point on, every exit path is responsible for
 311     // initializing any non-copied parts of the object to zero.
 312     // Also, if this flag is set we make sure that arraycopy interacts properly
 313     // with G1, eliding pre-barriers. See CR 6627983.
 314     dest_uninitialized = true;
 315   } else {
 316     // No zeroing elimination here.
 317     alloc             = NULL;
 318     //original_dest   = dest;
 319     //dest_uninitialized = false;
 320   }
 321 
 322   uint alias_idx = C->get_alias_index(adr_type);
 323 
 324   // Results are placed here:
 325   enum { fast_path        = 1,  // normal void-returning assembly stub
 326          checked_path     = 2,  // special assembly stub with cleanup
 327          slow_call_path   = 3,  // something went wrong; call the VM
 328          zero_path        = 4,  // bypass when length of copy is zero
 329          bcopy_path       = 5,  // copy primitive array by 64-bit blocks
 330          PATH_LIMIT       = 6
 331   };
 332   RegionNode* result_region = new RegionNode(PATH_LIMIT);
 333   PhiNode*    result_i_o    = new PhiNode(result_region, Type::ABIO);
 334   PhiNode*    result_memory = new PhiNode(result_region, Type::MEMORY, adr_type);
 335   assert(adr_type != TypePtr::BOTTOM, "must be RawMem or a T[] slice");
 336   transform_later(result_region);
 337   transform_later(result_i_o);
 338   transform_later(result_memory);
 339 
 340   // The slow_control path:
 341   Node* slow_control;
 342   Node* slow_i_o = *io;
 343   Node* slow_mem = mem->memory_at(alias_idx);
 344   DEBUG_ONLY(slow_control = (Node*) badAddress);
 345 
 346   // Checked control path:
 347   Node* checked_control = top();
 348   Node* checked_mem     = NULL;
 349   Node* checked_i_o     = NULL;
 350   Node* checked_value   = NULL;
 351 
 352   if (basic_elem_type == T_CONFLICT) {
 353     assert(!dest_uninitialized, "");
 354     Node* cv = generate_generic_arraycopy(ctrl, &mem,
 355                                           adr_type,
 356                                           src, src_offset, dest, dest_offset,
 357                                           copy_length, dest_uninitialized);
 358     if (cv == NULL)  cv = intcon(-1);  // failure (no stub available)
 359     checked_control = *ctrl;
 360     checked_i_o     = *io;
 361     checked_mem     = mem->memory_at(alias_idx);
 362     checked_value   = cv;
 363     *ctrl = top();
 364   }
 365 
 366   Node* not_pos = generate_nonpositive_guard(ctrl, copy_length, length_never_negative);
 367   if (not_pos != NULL) {
 368     Node* local_ctrl = not_pos, *local_io = *io;
 369     MergeMemNode* local_mem = MergeMemNode::make(mem);
 370     transform_later(local_mem);
 371 
 372     // (6) length must not be negative.
 373     if (!length_never_negative) {
 374       generate_negative_guard(&local_ctrl, copy_length, slow_region);
 375     }
 376 
 377     // copy_length is 0.
 378     if (dest_uninitialized) {
 379       assert(!local_ctrl->is_top(), "no ctrl?");
 380       Node* dest_length = alloc->in(AllocateNode::ALength);
 381       if (copy_length->eqv_uncast(dest_length)
 382           || _igvn.find_int_con(dest_length, 1) <= 0) {
 383         // There is no zeroing to do. No need for a secondary raw memory barrier.
 384       } else {
 385         // Clear the whole thing since there are no source elements to copy.
 386         generate_clear_array(local_ctrl, local_mem,
 387                              adr_type, dest, basic_elem_type,
 388                              intcon(0), NULL,
 389                              alloc->in(AllocateNode::AllocSize));
 390         // Use a secondary InitializeNode as raw memory barrier.
 391         // Currently it is needed only on this path since other
 392         // paths have stub or runtime calls as raw memory barriers.
 393         MemBarNode* mb = MemBarNode::make(C, Op_Initialize,
 394                                           Compile::AliasIdxRaw,
 395                                           top());
 396         transform_later(mb);
 397         mb->set_req(TypeFunc::Control,local_ctrl);
 398         mb->set_req(TypeFunc::Memory, local_mem->memory_at(Compile::AliasIdxRaw));
 399         local_ctrl = transform_later(new ProjNode(mb, TypeFunc::Control));
 400         local_mem->set_memory_at(Compile::AliasIdxRaw, transform_later(new ProjNode(mb, TypeFunc::Memory)));
 401 
 402         InitializeNode* init = mb->as_Initialize();
 403         init->set_complete(&_igvn);  // (there is no corresponding AllocateNode)
 404       }
 405     }
 406 
 407     // Present the results of the fast call.
 408     result_region->init_req(zero_path, local_ctrl);
 409     result_i_o   ->init_req(zero_path, local_io);
 410     result_memory->init_req(zero_path, local_mem->memory_at(alias_idx));
 411   }
 412 
 413   if (!(*ctrl)->is_top() && dest_uninitialized) {
 414     // We have to initialize the *uncopied* part of the array to zero.
 415     // The copy destination is the slice dest[off..off+len].  The other slices
 416     // are dest_head = dest[0..off] and dest_tail = dest[off+len..dest.length].
 417     Node* dest_size   = alloc->in(AllocateNode::AllocSize);
 418     Node* dest_length = alloc->in(AllocateNode::ALength);
 419     Node* dest_tail   = transform_later( new AddINode(dest_offset, copy_length));
 420 
 421     // If there is a head section that needs zeroing, do it now.
 422     if (_igvn.find_int_con(dest_offset, -1) != 0) {
 423       generate_clear_array(*ctrl, mem,
 424                            adr_type, dest, basic_elem_type,
 425                            intcon(0), dest_offset,
 426                            NULL);
 427     }
 428 
 429     // Next, perform a dynamic check on the tail length.
 430     // It is often zero, and we can win big if we prove this.
 431     // There are two wins:  Avoid generating the ClearArray
 432     // with its attendant messy index arithmetic, and upgrade
 433     // the copy to a more hardware-friendly word size of 64 bits.
 434     Node* tail_ctl = NULL;
 435     if (!(*ctrl)->is_top() && !dest_tail->eqv_uncast(dest_length)) {
 436       Node* cmp_lt   = transform_later( new CmpINode(dest_tail, dest_length) );
 437       Node* bol_lt   = transform_later( new BoolNode(cmp_lt, BoolTest::lt) );
 438       tail_ctl = generate_slow_guard(ctrl, bol_lt, NULL);
 439       assert(tail_ctl != NULL || !(*ctrl)->is_top(), "must be an outcome");
 440     }
 441 
 442     // At this point, let's assume there is no tail.
 443     if (!(*ctrl)->is_top() && alloc != NULL && basic_elem_type != T_OBJECT) {
 444       // There is no tail.  Try an upgrade to a 64-bit copy.
 445       bool didit = false;
 446       {
 447         Node* local_ctrl = *ctrl, *local_io = *io;
 448         MergeMemNode* local_mem = MergeMemNode::make(mem);
 449         transform_later(local_mem);
 450 
 451         didit = generate_block_arraycopy(&local_ctrl, &local_mem, local_io,
 452                                          adr_type, basic_elem_type, alloc,
 453                                          src, src_offset, dest, dest_offset,
 454                                          dest_size, dest_uninitialized);
 455         if (didit) {
 456           // Present the results of the block-copying fast call.
 457           result_region->init_req(bcopy_path, local_ctrl);
 458           result_i_o   ->init_req(bcopy_path, local_io);
 459           result_memory->init_req(bcopy_path, local_mem->memory_at(alias_idx));
 460         }
 461       }
 462       if (didit) {
 463         *ctrl = top();     // no regular fast path
 464       }
 465     }
 466 
 467     // Clear the tail, if any.
 468     if (tail_ctl != NULL) {
 469       Node* notail_ctl = (*ctrl)->is_top() ? NULL : *ctrl;
 470       *ctrl = tail_ctl;
 471       if (notail_ctl == NULL) {
 472         generate_clear_array(*ctrl, mem,
 473                              adr_type, dest, basic_elem_type,
 474                              dest_tail, NULL,
 475                              dest_size);
 476       } else {
 477         // Make a local merge.
 478         Node* done_ctl = transform_later(new RegionNode(3));
 479         Node* done_mem = transform_later(new PhiNode(done_ctl, Type::MEMORY, adr_type));
 480         done_ctl->init_req(1, notail_ctl);
 481         done_mem->init_req(1, mem->memory_at(alias_idx));
 482         generate_clear_array(*ctrl, mem,
 483                              adr_type, dest, basic_elem_type,
 484                              dest_tail, NULL,
 485                              dest_size);
 486         done_ctl->init_req(2, *ctrl);
 487         done_mem->init_req(2, mem->memory_at(alias_idx));
 488         *ctrl = done_ctl;
 489         mem->set_memory_at(alias_idx, done_mem);
 490       }
 491     }
 492   }
 493 
 494   BasicType copy_type = basic_elem_type;
 495   assert(basic_elem_type != T_ARRAY, "caller must fix this");
 496   if (!(*ctrl)->is_top() && copy_type == T_OBJECT) {
 497     // If src and dest have compatible element types, we can copy bits.
 498     // Types S[] and D[] are compatible if D is a supertype of S.
 499     //
 500     // If they are not, we will use checked_oop_disjoint_arraycopy,
 501     // which performs a fast optimistic per-oop check, and backs off
 502     // further to JVM_ArrayCopy on the first per-oop check that fails.
 503     // (Actually, we don't move raw bits only; the GC requires card marks.)
 504 
 505     // Get the klass* for both src and dest
 506     Node* src_klass  = ac->in(ArrayCopyNode::SrcKlass);
 507     Node* dest_klass = ac->in(ArrayCopyNode::DestKlass);
 508 
 509     // Generate the subtype check.
 510     // This might fold up statically, or then again it might not.
 511     //
 512     // Non-static example:  Copying List<String>.elements to a new String[].
 513     // The backing store for a List<String> is always an Object[],
 514     // but its elements are always type String, if the generic types
 515     // are correct at the source level.
 516     //
 517     // Test S[] against D[], not S against D, because (probably)
 518     // the secondary supertype cache is less busy for S[] than S.
 519     // This usually only matters when D is an interface.
 520     Node* not_subtype_ctrl = ac->is_arraycopy_notest() ? top() : Phase::gen_subtype_check(src_klass, dest_klass, ctrl, mem, &_igvn);
 521     // Plug failing path into checked_oop_disjoint_arraycopy
 522     if (not_subtype_ctrl != top()) {
 523       Node* local_ctrl = not_subtype_ctrl;
 524       MergeMemNode* local_mem = MergeMemNode::make(mem);
 525       transform_later(local_mem);
 526 
 527       // (At this point we can assume disjoint_bases, since types differ.)
 528       int ek_offset = in_bytes(ObjArrayKlass::element_klass_offset());
 529       Node* p1 = basic_plus_adr(dest_klass, ek_offset);
 530       Node* n1 = LoadKlassNode::make(_igvn, C->immutable_memory(), p1, TypeRawPtr::BOTTOM);
 531       Node* dest_elem_klass = transform_later(n1);
 532       Node* cv = generate_checkcast_arraycopy(&local_ctrl, &local_mem,
 533                                               adr_type,
 534                                               dest_elem_klass,
 535                                               src, src_offset, dest, dest_offset,
 536                                               ConvI2X(copy_length), dest_uninitialized);
 537       if (cv == NULL)  cv = intcon(-1);  // failure (no stub available)
 538       checked_control = local_ctrl;
 539       checked_i_o     = *io;
 540       checked_mem     = local_mem->memory_at(alias_idx);
 541       checked_value   = cv;
 542     }
 543     // At this point we know we do not need type checks on oop stores.
 544 
 545     // Let's see if we need card marks:
 546     if (alloc != NULL && GraphKit::use_ReduceInitialCardMarks()) {
 547       // If we do not need card marks, copy using the jint or jlong stub.
 548       copy_type = LP64_ONLY(UseCompressedOops ? T_INT : T_LONG) NOT_LP64(T_INT);
 549       assert(type2aelembytes(basic_elem_type) == type2aelembytes(copy_type),
 550              "sizes agree");
 551     }
 552   }
 553 
 554   if (!(*ctrl)->is_top()) {
 555     // Generate the fast path, if possible.
 556     Node* local_ctrl = *ctrl;
 557     MergeMemNode* local_mem = MergeMemNode::make(mem);
 558     transform_later(local_mem);
 559 
 560     generate_unchecked_arraycopy(&local_ctrl, &local_mem,
 561                                  adr_type, copy_type, disjoint_bases,
 562                                  src, src_offset, dest, dest_offset,
 563                                  ConvI2X(copy_length), dest_uninitialized);
 564 
 565     // Present the results of the fast call.
 566     result_region->init_req(fast_path, local_ctrl);
 567     result_i_o   ->init_req(fast_path, *io);
 568     result_memory->init_req(fast_path, local_mem->memory_at(alias_idx));
 569   }
 570 
 571   // Here are all the slow paths up to this point, in one bundle:
 572   assert(slow_region != NULL, "allocated on entry");
 573   slow_control = slow_region;
 574   DEBUG_ONLY(slow_region = (RegionNode*)badAddress);
 575 
 576   *ctrl = checked_control;
 577   if (!(*ctrl)->is_top()) {
 578     // Clean up after the checked call.
 579     // The returned value is either 0 or -1^K,
 580     // where K = number of partially transferred array elements.
 581     Node* cmp = new CmpINode(checked_value, intcon(0));
 582     transform_later(cmp);
 583     Node* bol = new BoolNode(cmp, BoolTest::eq);
 584     transform_later(bol);
 585     IfNode* iff = new IfNode(*ctrl, bol, PROB_MAX, COUNT_UNKNOWN);
 586     transform_later(iff);
 587 
 588     // If it is 0, we are done, so transfer to the end.
 589     Node* checks_done = new IfTrueNode(iff);
 590     transform_later(checks_done);
 591     result_region->init_req(checked_path, checks_done);
 592     result_i_o   ->init_req(checked_path, checked_i_o);
 593     result_memory->init_req(checked_path, checked_mem);
 594 
 595     // If it is not zero, merge into the slow call.
 596     *ctrl = new IfFalseNode(iff);
 597     transform_later(*ctrl);
 598     RegionNode* slow_reg2 = new RegionNode(3);
 599     PhiNode*    slow_i_o2 = new PhiNode(slow_reg2, Type::ABIO);
 600     PhiNode*    slow_mem2 = new PhiNode(slow_reg2, Type::MEMORY, adr_type);
 601     transform_later(slow_reg2);
 602     transform_later(slow_i_o2);
 603     transform_later(slow_mem2);
 604     slow_reg2  ->init_req(1, slow_control);
 605     slow_i_o2  ->init_req(1, slow_i_o);
 606     slow_mem2  ->init_req(1, slow_mem);
 607     slow_reg2  ->init_req(2, *ctrl);
 608     slow_i_o2  ->init_req(2, checked_i_o);
 609     slow_mem2  ->init_req(2, checked_mem);
 610 
 611     slow_control = slow_reg2;
 612     slow_i_o     = slow_i_o2;
 613     slow_mem     = slow_mem2;
 614 
 615     if (alloc != NULL) {
 616       // We'll restart from the very beginning, after zeroing the whole thing.
 617       // This can cause double writes, but that's OK since dest is brand new.
 618       // So we ignore the low 31 bits of the value returned from the stub.
 619     } else {
 620       // We must continue the copy exactly where it failed, or else
 621       // another thread might see the wrong number of writes to dest.
 622       Node* checked_offset = new XorINode(checked_value, intcon(-1));
 623       Node* slow_offset    = new PhiNode(slow_reg2, TypeInt::INT);
 624       transform_later(checked_offset);
 625       transform_later(slow_offset);
 626       slow_offset->init_req(1, intcon(0));
 627       slow_offset->init_req(2, checked_offset);
 628 
 629       // Adjust the arguments by the conditionally incoming offset.
 630       Node* src_off_plus  = new AddINode(src_offset,  slow_offset);
 631       transform_later(src_off_plus);
 632       Node* dest_off_plus = new AddINode(dest_offset, slow_offset);
 633       transform_later(dest_off_plus);
 634       Node* length_minus  = new SubINode(copy_length, slow_offset);
 635       transform_later(length_minus);
 636 
 637       // Tweak the node variables to adjust the code produced below:
 638       src_offset  = src_off_plus;
 639       dest_offset = dest_off_plus;
 640       copy_length = length_minus;
 641     }
 642   }
 643   *ctrl = slow_control;
 644   if (!(*ctrl)->is_top()) {
 645     Node* local_ctrl = *ctrl, *local_io = slow_i_o;
 646     MergeMemNode* local_mem = MergeMemNode::make(mem);
 647     transform_later(local_mem);
 648 
 649     // Generate the slow path, if needed.
 650     local_mem->set_memory_at(alias_idx, slow_mem);
 651 
 652     if (dest_uninitialized) {
 653       generate_clear_array(local_ctrl, local_mem,
 654                            adr_type, dest, basic_elem_type,
 655                            intcon(0), NULL,
 656                            alloc->in(AllocateNode::AllocSize));
 657     }
 658 
 659     local_mem = generate_slow_arraycopy(ac,
 660                                         &local_ctrl, local_mem, &local_io,
 661                                         adr_type,
 662                                         src, src_offset, dest, dest_offset,
 663                                         copy_length, /*dest_uninitialized*/false);
 664 
 665     result_region->init_req(slow_call_path, local_ctrl);
 666     result_i_o   ->init_req(slow_call_path, local_io);
 667     result_memory->init_req(slow_call_path, local_mem->memory_at(alias_idx));
 668   } else {
 669     ShouldNotReachHere(); // no call to generate_slow_arraycopy:
 670                           // projections were not extracted
 671   }
 672 
 673   // Remove unused edges.
 674   for (uint i = 1; i < result_region->req(); i++) {
 675     if (result_region->in(i) == NULL) {
 676       result_region->init_req(i, top());
 677     }
 678   }
 679 
 680   // Finished; return the combined state.
 681   *ctrl = result_region;
 682   *io = result_i_o;
 683   mem->set_memory_at(alias_idx, result_memory);
 684 
 685   // mem no longer guaranteed to stay a MergeMemNode
 686   Node* out_mem = mem;
 687   DEBUG_ONLY(mem = NULL);
 688 
 689   // The memory edges above are precise in order to model effects around
 690   // array copies accurately to allow value numbering of field loads around
 691   // arraycopy.  Such field loads, both before and after, are common in Java
 692   // collections and similar classes involving header/array data structures.
 693   //
 694   // But with low number of register or when some registers are used or killed
 695   // by arraycopy calls it causes registers spilling on stack. See 6544710.
 696   // The next memory barrier is added to avoid it. If the arraycopy can be
 697   // optimized away (which it can, sometimes) then we can manually remove
 698   // the membar also.
 699   //
 700   // Do not let reads from the cloned object float above the arraycopy.
 701   if (alloc != NULL && !alloc->initialization()->does_not_escape()) {
 702     // Do not let stores that initialize this object be reordered with
 703     // a subsequent store that would make this object accessible by
 704     // other threads.
 705     insert_mem_bar(ctrl, &out_mem, Op_MemBarStoreStore);
 706   } else if (InsertMemBarAfterArraycopy) {
 707     insert_mem_bar(ctrl, &out_mem, Op_MemBarCPUOrder);
 708   }
 709 
 710   _igvn.replace_node(_memproj_fallthrough, out_mem);
 711   _igvn.replace_node(_ioproj_fallthrough, *io);
 712   _igvn.replace_node(_fallthroughcatchproj, *ctrl);
 713 
 714   return out_mem;
 715 }
 716 
 717 // Helper for initialization of arrays, creating a ClearArray.
 718 // It writes zero bits in [start..end), within the body of an array object.
 719 // The memory effects are all chained onto the 'adr_type' alias category.
 720 //
 721 // Since the object is otherwise uninitialized, we are free
 722 // to put a little "slop" around the edges of the cleared area,
 723 // as long as it does not go back into the array's header,
 724 // or beyond the array end within the heap.
 725 //
 726 // The lower edge can be rounded down to the nearest jint and the
 727 // upper edge can be rounded up to the nearest MinObjAlignmentInBytes.
 728 //
 729 // Arguments:
 730 //   adr_type           memory slice where writes are generated
 731 //   dest               oop of the destination array
 732 //   basic_elem_type    element type of the destination
 733 //   slice_idx          array index of first element to store
 734 //   slice_len          number of elements to store (or NULL)
 735 //   dest_size          total size in bytes of the array object
 736 //
 737 // Exactly one of slice_len or dest_size must be non-NULL.
 738 // If dest_size is non-NULL, zeroing extends to the end of the object.
 739 // If slice_len is non-NULL, the slice_idx value must be a constant.
 740 void PhaseMacroExpand::generate_clear_array(Node* ctrl, MergeMemNode* merge_mem,
 741                                             const TypePtr* adr_type,
 742                                             Node* dest,
 743                                             BasicType basic_elem_type,
 744                                             Node* slice_idx,
 745                                             Node* slice_len,
 746                                             Node* dest_size) {
 747   // one or the other but not both of slice_len and dest_size:
 748   assert((slice_len != NULL? 1: 0) + (dest_size != NULL? 1: 0) == 1, "");
 749   if (slice_len == NULL)  slice_len = top();
 750   if (dest_size == NULL)  dest_size = top();
 751 
 752   uint alias_idx = C->get_alias_index(adr_type);
 753 
 754   // operate on this memory slice:
 755   Node* mem = merge_mem->memory_at(alias_idx); // memory slice to operate on
 756 
 757   // scaling and rounding of indexes:
 758   int scale = exact_log2(type2aelembytes(basic_elem_type));
 759   int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 760   int clear_low = (-1 << scale) & (BytesPerInt  - 1);
 761   int bump_bit  = (-1 << scale) & BytesPerInt;
 762 
 763   // determine constant starts and ends
 764   const intptr_t BIG_NEG = -128;
 765   assert(BIG_NEG + 2*abase < 0, "neg enough");
 766   intptr_t slice_idx_con = (intptr_t) _igvn.find_int_con(slice_idx, BIG_NEG);
 767   intptr_t slice_len_con = (intptr_t) _igvn.find_int_con(slice_len, BIG_NEG);
 768   if (slice_len_con == 0) {
 769     return;                     // nothing to do here
 770   }
 771   intptr_t start_con = (abase + (slice_idx_con << scale)) & ~clear_low;
 772   intptr_t end_con   = _igvn.find_intptr_t_con(dest_size, -1);
 773   if (slice_idx_con >= 0 && slice_len_con >= 0) {
 774     assert(end_con < 0, "not two cons");
 775     end_con = round_to(abase + ((slice_idx_con + slice_len_con) << scale),
 776                        BytesPerLong);
 777   }
 778 
 779   if (start_con >= 0 && end_con >= 0) {
 780     // Constant start and end.  Simple.
 781     mem = ClearArrayNode::clear_memory(ctrl, mem, dest,
 782                                        start_con, end_con, &_igvn);
 783   } else if (start_con >= 0 && dest_size != top()) {
 784     // Constant start, pre-rounded end after the tail of the array.
 785     Node* end = dest_size;
 786     mem = ClearArrayNode::clear_memory(ctrl, mem, dest,
 787                                        start_con, end, &_igvn);
 788   } else if (start_con >= 0 && slice_len != top()) {
 789     // Constant start, non-constant end.  End needs rounding up.
 790     // End offset = round_up(abase + ((slice_idx_con + slice_len) << scale), 8)
 791     intptr_t end_base  = abase + (slice_idx_con << scale);
 792     int      end_round = (-1 << scale) & (BytesPerLong  - 1);
 793     Node*    end       = ConvI2X(slice_len);
 794     if (scale != 0)
 795       end = transform_later(new LShiftXNode(end, intcon(scale) ));
 796     end_base += end_round;
 797     end = transform_later(new AddXNode(end, MakeConX(end_base)) );
 798     end = transform_later(new AndXNode(end, MakeConX(~end_round)) );
 799     mem = ClearArrayNode::clear_memory(ctrl, mem, dest,
 800                                        start_con, end, &_igvn);
 801   } else if (start_con < 0 && dest_size != top()) {
 802     // Non-constant start, pre-rounded end after the tail of the array.
 803     // This is almost certainly a "round-to-end" operation.
 804     Node* start = slice_idx;
 805     start = ConvI2X(start);
 806     if (scale != 0)
 807       start = transform_later(new LShiftXNode( start, intcon(scale) ));
 808     start = transform_later(new AddXNode(start, MakeConX(abase)) );
 809     if ((bump_bit | clear_low) != 0) {
 810       int to_clear = (bump_bit | clear_low);
 811       // Align up mod 8, then store a jint zero unconditionally
 812       // just before the mod-8 boundary.
 813       if (((abase + bump_bit) & ~to_clear) - bump_bit
 814           < arrayOopDesc::length_offset_in_bytes() + BytesPerInt) {
 815         bump_bit = 0;
 816         assert((abase & to_clear) == 0, "array base must be long-aligned");
 817       } else {
 818         // Bump 'start' up to (or past) the next jint boundary:
 819         start = transform_later( new AddXNode(start, MakeConX(bump_bit)) );
 820         assert((abase & clear_low) == 0, "array base must be int-aligned");
 821       }
 822       // Round bumped 'start' down to jlong boundary in body of array.
 823       start = transform_later(new AndXNode(start, MakeConX(~to_clear)) );
 824       if (bump_bit != 0) {
 825         // Store a zero to the immediately preceding jint:
 826         Node* x1 = transform_later(new AddXNode(start, MakeConX(-bump_bit)) );
 827         Node* p1 = basic_plus_adr(dest, x1);
 828         mem = StoreNode::make(_igvn, ctrl, mem, p1, adr_type, intcon(0), T_INT, MemNode::unordered);
 829         mem = transform_later(mem);
 830       }
 831     }
 832     Node* end = dest_size; // pre-rounded
 833     mem = ClearArrayNode::clear_memory(ctrl, mem, dest,
 834                                        start, end, &_igvn);
 835   } else {
 836     // Non-constant start, unrounded non-constant end.
 837     // (Nobody zeroes a random midsection of an array using this routine.)
 838     ShouldNotReachHere();       // fix caller
 839   }
 840 
 841   // Done.
 842   merge_mem->set_memory_at(alias_idx, mem);
 843 }
 844 
 845 bool PhaseMacroExpand::generate_block_arraycopy(Node** ctrl, MergeMemNode** mem, Node* io,
 846                                                 const TypePtr* adr_type,
 847                                                 BasicType basic_elem_type,
 848                                                 AllocateNode* alloc,
 849                                                 Node* src,  Node* src_offset,
 850                                                 Node* dest, Node* dest_offset,
 851                                                 Node* dest_size, bool dest_uninitialized) {
 852   // See if there is an advantage from block transfer.
 853   int scale = exact_log2(type2aelembytes(basic_elem_type));
 854   if (scale >= LogBytesPerLong)
 855     return false;               // it is already a block transfer
 856 
 857   // Look at the alignment of the starting offsets.
 858   int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 859 
 860   intptr_t src_off_con  = (intptr_t) _igvn.find_int_con(src_offset, -1);
 861   intptr_t dest_off_con = (intptr_t) _igvn.find_int_con(dest_offset, -1);
 862   if (src_off_con < 0 || dest_off_con < 0) {
 863     // At present, we can only understand constants.
 864     return false;
 865   }
 866 
 867   intptr_t src_off  = abase + (src_off_con  << scale);
 868   intptr_t dest_off = abase + (dest_off_con << scale);
 869 
 870   if (((src_off | dest_off) & (BytesPerLong-1)) != 0) {
 871     // Non-aligned; too bad.
 872     // One more chance:  Pick off an initial 32-bit word.
 873     // This is a common case, since abase can be odd mod 8.
 874     if (((src_off | dest_off) & (BytesPerLong-1)) == BytesPerInt &&
 875         ((src_off ^ dest_off) & (BytesPerLong-1)) == 0) {
 876       Node* sptr = basic_plus_adr(src,  src_off);
 877       Node* dptr = basic_plus_adr(dest, dest_off);
 878       uint alias_idx = C->get_alias_index(adr_type);
 879       Node* sval = transform_later(LoadNode::make(_igvn, *ctrl, (*mem)->memory_at(alias_idx), sptr, adr_type, TypeInt::INT, T_INT, MemNode::unordered));
 880       Node* st = transform_later(StoreNode::make(_igvn, *ctrl, (*mem)->memory_at(alias_idx), dptr, adr_type, sval, T_INT, MemNode::unordered));
 881       (*mem)->set_memory_at(alias_idx, st);
 882       src_off += BytesPerInt;
 883       dest_off += BytesPerInt;
 884     } else {
 885       return false;
 886     }
 887   }
 888   assert(src_off % BytesPerLong == 0, "");
 889   assert(dest_off % BytesPerLong == 0, "");
 890 
 891   // Do this copy by giant steps.
 892   Node* sptr  = basic_plus_adr(src,  src_off);
 893   Node* dptr  = basic_plus_adr(dest, dest_off);
 894   Node* countx = dest_size;
 895   countx = transform_later(new SubXNode(countx, MakeConX(dest_off)));
 896   countx = transform_later(new URShiftXNode(countx, intcon(LogBytesPerLong)));
 897 
 898   bool disjoint_bases = true;   // since alloc != NULL
 899   generate_unchecked_arraycopy(ctrl, mem,
 900                                adr_type, T_LONG, disjoint_bases,
 901                                sptr, NULL, dptr, NULL, countx, dest_uninitialized);
 902 
 903   return true;
 904 }
 905 
 906 // Helper function; generates code for the slow case.
 907 // We make a call to a runtime method which emulates the native method,
 908 // but without the native wrapper overhead.
 909 MergeMemNode* PhaseMacroExpand::generate_slow_arraycopy(ArrayCopyNode *ac,
 910                                                         Node** ctrl, Node* mem, Node** io,
 911                                                         const TypePtr* adr_type,
 912                                                         Node* src,  Node* src_offset,
 913                                                         Node* dest, Node* dest_offset,
 914                                                         Node* copy_length, bool dest_uninitialized) {
 915   assert(!dest_uninitialized, "Invariant");
 916 
 917   const TypeFunc* call_type = OptoRuntime::slow_arraycopy_Type();
 918   CallNode* call = new CallStaticJavaNode(call_type, OptoRuntime::slow_arraycopy_Java(),
 919                                           "slow_arraycopy",
 920                                           ac->jvms()->bci(), TypePtr::BOTTOM);
 921 
 922   call->init_req(TypeFunc::Control, *ctrl);
 923   call->init_req(TypeFunc::I_O    , *io);
 924   call->init_req(TypeFunc::Memory , mem);
 925   call->init_req(TypeFunc::ReturnAdr, top());
 926   call->init_req(TypeFunc::FramePtr, top());
 927   call->init_req(TypeFunc::Parms+0, src);
 928   call->init_req(TypeFunc::Parms+1, src_offset);
 929   call->init_req(TypeFunc::Parms+2, dest);
 930   call->init_req(TypeFunc::Parms+3, dest_offset);
 931   call->init_req(TypeFunc::Parms+4, copy_length);
 932   copy_call_debug_info(ac, call);
 933 
 934   call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
 935   _igvn.replace_node(ac, call);
 936   transform_later(call);
 937 
 938   extract_call_projections(call);
 939   *ctrl = _fallthroughcatchproj->clone();
 940   transform_later(*ctrl);
 941 
 942   Node* m = _memproj_fallthrough->clone();
 943   transform_later(m);
 944 
 945   uint alias_idx = C->get_alias_index(adr_type);
 946   MergeMemNode* out_mem;
 947   if (alias_idx != Compile::AliasIdxBot) {
 948     out_mem = MergeMemNode::make(mem);
 949     out_mem->set_memory_at(alias_idx, m);
 950   } else {
 951     out_mem = MergeMemNode::make(m);
 952   }
 953   transform_later(out_mem);
 954 
 955   *io = _ioproj_fallthrough->clone();
 956   transform_later(*io);
 957 
 958   return out_mem;
 959 }
 960 
 961 // Helper function; generates code for cases requiring runtime checks.
 962 Node* PhaseMacroExpand::generate_checkcast_arraycopy(Node** ctrl, MergeMemNode** mem,
 963                                                      const TypePtr* adr_type,
 964                                                      Node* dest_elem_klass,
 965                                                      Node* src,  Node* src_offset,
 966                                                      Node* dest, Node* dest_offset,
 967                                                      Node* copy_length, bool dest_uninitialized) {
 968   if ((*ctrl)->is_top())  return NULL;
 969 
 970   address copyfunc_addr = StubRoutines::checkcast_arraycopy(dest_uninitialized);
 971   if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.
 972     return NULL;
 973   }
 974 
 975   // Pick out the parameters required to perform a store-check
 976   // for the target array.  This is an optimistic check.  It will
 977   // look in each non-null element's class, at the desired klass's
 978   // super_check_offset, for the desired klass.
 979   int sco_offset = in_bytes(Klass::super_check_offset_offset());
 980   Node* p3 = basic_plus_adr(dest_elem_klass, sco_offset);
 981   Node* n3 = new LoadINode(NULL, *mem /*memory(p3)*/, p3, _igvn.type(p3)->is_ptr(), TypeInt::INT, MemNode::unordered);
 982   Node* check_offset = ConvI2X(transform_later(n3));
 983   Node* check_value  = dest_elem_klass;
 984 
 985   Node* src_start  = array_element_address(src,  src_offset,  T_OBJECT);
 986   Node* dest_start = array_element_address(dest, dest_offset, T_OBJECT);
 987 
 988   const TypeFunc* call_type = OptoRuntime::checkcast_arraycopy_Type();
 989   Node* call = make_leaf_call(*ctrl, *mem, call_type, copyfunc_addr, "checkcast_arraycopy", adr_type,
 990                               src_start, dest_start, copy_length XTOP, check_offset XTOP, check_value);
 991 
 992   finish_arraycopy_call(call, ctrl, mem, adr_type);
 993 
 994   Node* proj =  new ProjNode(call, TypeFunc::Parms);
 995   transform_later(proj);
 996 
 997   return proj;
 998 }
 999 
1000 // Helper function; generates code for cases requiring runtime checks.
1001 Node* PhaseMacroExpand::generate_generic_arraycopy(Node** ctrl, MergeMemNode** mem,
1002                                                    const TypePtr* adr_type,
1003                                                    Node* src,  Node* src_offset,
1004                                                    Node* dest, Node* dest_offset,
1005                                                    Node* copy_length, bool dest_uninitialized) {
1006   if ((*ctrl)->is_top()) return NULL;
1007   assert(!dest_uninitialized, "Invariant");
1008 
1009   address copyfunc_addr = StubRoutines::generic_arraycopy();
1010   if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.
1011     return NULL;
1012   }
1013 
1014   const TypeFunc* call_type = OptoRuntime::generic_arraycopy_Type();
1015   Node* call = make_leaf_call(*ctrl, *mem, call_type, copyfunc_addr, "generic_arraycopy", adr_type,
1016                               src, src_offset, dest, dest_offset, copy_length);
1017 
1018   finish_arraycopy_call(call, ctrl, mem, adr_type);
1019 
1020   Node* proj =  new ProjNode(call, TypeFunc::Parms);
1021   transform_later(proj);
1022 
1023   return proj;
1024 }
1025 
1026 // Helper function; generates the fast out-of-line call to an arraycopy stub.
1027 void PhaseMacroExpand::generate_unchecked_arraycopy(Node** ctrl, MergeMemNode** mem,
1028                                                     const TypePtr* adr_type,
1029                                                     BasicType basic_elem_type,
1030                                                     bool disjoint_bases,
1031                                                     Node* src,  Node* src_offset,
1032                                                     Node* dest, Node* dest_offset,
1033                                                     Node* copy_length, bool dest_uninitialized) {
1034   if ((*ctrl)->is_top()) return;
1035 
1036   Node* src_start  = src;
1037   Node* dest_start = dest;
1038   if (src_offset != NULL || dest_offset != NULL) {
1039     src_start =  array_element_address(src, src_offset, basic_elem_type);
1040     dest_start = array_element_address(dest, dest_offset, basic_elem_type);
1041   }
1042 
1043   // Figure out which arraycopy runtime method to call.
1044   const char* copyfunc_name = "arraycopy";
1045   address     copyfunc_addr =
1046       basictype2arraycopy(basic_elem_type, src_offset, dest_offset,
1047                           disjoint_bases, copyfunc_name, dest_uninitialized);
1048 
1049   const TypeFunc* call_type = OptoRuntime::fast_arraycopy_Type();
1050   Node* call = make_leaf_call(*ctrl, *mem, call_type, copyfunc_addr, copyfunc_name, adr_type,
1051                               src_start, dest_start, copy_length XTOP);
1052 
1053   finish_arraycopy_call(call, ctrl, mem, adr_type);
1054 }
1055 
1056 void PhaseMacroExpand::expand_arraycopy_node(ArrayCopyNode *ac) {
1057   Node* ctrl = ac->in(TypeFunc::Control);
1058   Node* io = ac->in(TypeFunc::I_O);
1059   Node* src = ac->in(ArrayCopyNode::Src);
1060   Node* src_offset = ac->in(ArrayCopyNode::SrcPos);
1061   Node* dest = ac->in(ArrayCopyNode::Dest);
1062   Node* dest_offset = ac->in(ArrayCopyNode::DestPos);
1063   Node* length = ac->in(ArrayCopyNode::Length);
1064   MergeMemNode* merge_mem = NULL;
1065 
1066   if (ac->is_clonebasic()) {
1067     assert (src_offset == NULL && dest_offset == NULL, "for clone offsets should be null");
1068     Node* mem = ac->in(TypeFunc::Memory);
1069     const char* copyfunc_name = "arraycopy";
1070     address     copyfunc_addr =
1071       basictype2arraycopy(T_LONG, NULL, NULL,
1072                           true, copyfunc_name, true);
1073 
1074     const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
1075     const TypeFunc* call_type = OptoRuntime::fast_arraycopy_Type();
1076 
1077     Node* call = make_leaf_call(ctrl, mem, call_type, copyfunc_addr, copyfunc_name, raw_adr_type, src, dest, length XTOP);
1078     transform_later(call);
1079 
1080     _igvn.replace_node(ac, call);
1081     return;
1082   } else if (ac->is_copyof() || ac->is_copyofrange() || ac->is_cloneoop()) {
1083     Node* mem = ac->in(TypeFunc::Memory);
1084     merge_mem = MergeMemNode::make(mem);
1085     transform_later(merge_mem);
1086 
1087     RegionNode* slow_region = new RegionNode(1);
1088     transform_later(slow_region);
1089 
1090     AllocateArrayNode* alloc = NULL;
1091     if (ac->is_alloc_tightly_coupled()) {
1092       alloc = AllocateArrayNode::Ideal_array_allocation(dest, &_igvn);
1093       assert(alloc != NULL, "expect alloc");
1094     }
1095 
1096     generate_arraycopy(ac, alloc, &ctrl, merge_mem, &io,
1097                        TypeAryPtr::OOPS, T_OBJECT,
1098                        src, src_offset, dest, dest_offset, length,
1099                        true, !ac->is_copyofrange());
1100 
1101     return;
1102   }
1103 
1104   AllocateArrayNode* alloc = NULL;
1105   if (ac->is_alloc_tightly_coupled()) {
1106     alloc = AllocateArrayNode::Ideal_array_allocation(dest, &_igvn);
1107     assert(alloc != NULL, "expect alloc");
1108   }
1109 
1110   assert(ac->is_arraycopy() || ac->is_arraycopy_notest(), "should be an arraycopy");
1111 
1112   // Compile time checks.  If any of these checks cannot be verified at compile time,
1113   // we do not make a fast path for this call.  Instead, we let the call remain as it
1114   // is.  The checks we choose to mandate at compile time are:
1115   //
1116   // (1) src and dest are arrays.
1117   const Type* src_type = src->Value(&_igvn);
1118   const Type* dest_type = dest->Value(&_igvn);
1119   const TypeAryPtr* top_src = src_type->isa_aryptr();
1120   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
1121 
1122   if (top_src  == NULL || top_src->klass()  == NULL ||
1123       top_dest == NULL || top_dest->klass() == NULL) {
1124     // Conservatively insert a memory barrier on all memory slices.
1125     // Do not let writes into the source float below the arraycopy.
1126     {
1127       Node* mem = ac->in(TypeFunc::Memory);
1128       insert_mem_bar(&ctrl, &mem, Op_MemBarCPUOrder);
1129 
1130       merge_mem = MergeMemNode::make(mem);
1131       transform_later(merge_mem);
1132     }
1133 
1134     // Call StubRoutines::generic_arraycopy stub.
1135     Node* mem = generate_arraycopy(ac, NULL, &ctrl, merge_mem, &io,
1136                                    TypeRawPtr::BOTTOM, T_CONFLICT,
1137                                    src, src_offset, dest, dest_offset, length);
1138 
1139     // Do not let reads from the destination float above the arraycopy.
1140     // Since we cannot type the arrays, we don't know which slices
1141     // might be affected.  We could restrict this barrier only to those
1142     // memory slices which pertain to array elements--but don't bother.
1143     if (!InsertMemBarAfterArraycopy) {
1144       // (If InsertMemBarAfterArraycopy, there is already one in place.)
1145       insert_mem_bar(&ctrl, &mem, Op_MemBarCPUOrder);
1146     }
1147     return;
1148   }
1149   // (2) src and dest arrays must have elements of the same BasicType
1150   // Figure out the size and type of the elements we will be copying.
1151   BasicType src_elem  =  top_src->klass()->as_array_klass()->element_type()->basic_type();
1152   BasicType dest_elem = top_dest->klass()->as_array_klass()->element_type()->basic_type();
1153   if (src_elem  == T_ARRAY)  src_elem  = T_OBJECT;
1154   if (dest_elem == T_ARRAY)  dest_elem = T_OBJECT;
1155 
1156   if (src_elem != dest_elem || dest_elem == T_VOID) {
1157     // The component types are not the same or are not recognized.  Punt.
1158     // (But, avoid the native method wrapper to JVM_ArrayCopy.)
1159     {
1160       Node* mem = ac->in(TypeFunc::Memory);
1161       merge_mem = generate_slow_arraycopy(ac, &ctrl, mem, &io, TypePtr::BOTTOM, src, src_offset, dest, dest_offset, length, false);
1162     }
1163 
1164     _igvn.replace_node(_memproj_fallthrough, merge_mem);
1165     _igvn.replace_node(_ioproj_fallthrough, io);
1166     _igvn.replace_node(_fallthroughcatchproj, ctrl);
1167     return;
1168   }
1169 
1170   //---------------------------------------------------------------------------
1171   // We will make a fast path for this call to arraycopy.
1172 
1173   // We have the following tests left to perform:
1174   //
1175   // (3) src and dest must not be null.
1176   // (4) src_offset must not be negative.
1177   // (5) dest_offset must not be negative.
1178   // (6) length must not be negative.
1179   // (7) src_offset + length must not exceed length of src.
1180   // (8) dest_offset + length must not exceed length of dest.
1181   // (9) each element of an oop array must be assignable
1182 
1183   {
1184     Node* mem = ac->in(TypeFunc::Memory);
1185     merge_mem = MergeMemNode::make(mem);
1186     transform_later(merge_mem);
1187   }
1188 
1189   RegionNode* slow_region = new RegionNode(1);
1190   transform_later(slow_region);
1191 
1192   if (!ac->is_arraycopy_notest()) {
1193     // (3) operands must not be null
1194     // We currently perform our null checks with the null_check routine.
1195     // This means that the null exceptions will be reported in the caller
1196     // rather than (correctly) reported inside of the native arraycopy call.
1197     // This should be corrected, given time.  We do our null check with the
1198     // stack pointer restored.
1199     // null checks done library_call.cpp
1200 
1201     // (4) src_offset must not be negative.
1202     generate_negative_guard(&ctrl, src_offset, slow_region);
1203 
1204     // (5) dest_offset must not be negative.
1205     generate_negative_guard(&ctrl, dest_offset, slow_region);
1206 
1207     // (6) length must not be negative (moved to generate_arraycopy()).
1208     // generate_negative_guard(length, slow_region);
1209 
1210     // (7) src_offset + length must not exceed length of src.
1211     Node* alen = ac->in(ArrayCopyNode::SrcLen);
1212     generate_limit_guard(&ctrl,
1213                          src_offset, length,
1214                          alen,
1215                          slow_region);
1216 
1217     // (8) dest_offset + length must not exceed length of dest.
1218     alen = ac->in(ArrayCopyNode::DestLen);
1219     generate_limit_guard(&ctrl,
1220                          dest_offset, length,
1221                          alen,
1222                          slow_region);
1223 
1224     // (9) each element of an oop array must be assignable
1225     // The generate_arraycopy subroutine checks this.
1226   }
1227   // This is where the memory effects are placed:
1228   const TypePtr* adr_type = TypeAryPtr::get_array_body_type(dest_elem);
1229   generate_arraycopy(ac, alloc, &ctrl, merge_mem, &io,
1230                      adr_type, dest_elem,
1231                      src, src_offset, dest, dest_offset, length,
1232                      false, false, slow_region);
1233 }