1 /*
  2  * Copyright (c) 2016, 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 "gc/shared/barrierSet.hpp"
 27 #include "gc/shared/c2/barrierSetC2.hpp"
 28 #include "gc/shared/c2/cardTableBarrierSetC2.hpp"
 29 #include "gc/shared/gc_globals.hpp"
 30 #include "opto/arraycopynode.hpp"
 31 #include "opto/graphKit.hpp"
 32 #include "runtime/sharedRuntime.hpp"
 33 #include "utilities/macros.hpp"
 34 #include "utilities/powerOfTwo.hpp"
 35 
 36 ArrayCopyNode::ArrayCopyNode(Compile* C, bool alloc_tightly_coupled, bool has_negative_length_guard)
 37   : CallNode(arraycopy_type(), NULL, TypePtr::BOTTOM),
 38     _kind(None),
 39     _alloc_tightly_coupled(alloc_tightly_coupled),
 40     _has_negative_length_guard(has_negative_length_guard),
 41     _arguments_validated(false),
 42     _src_type(TypeOopPtr::BOTTOM),
 43     _dest_type(TypeOopPtr::BOTTOM) {
 44   init_class_id(Class_ArrayCopy);
 45   init_flags(Flag_is_macro);
 46   C->add_macro_node(this);
 47 }
 48 
 49 uint ArrayCopyNode::size_of() const { return sizeof(*this); }
 50 
 51 ArrayCopyNode* ArrayCopyNode::make(GraphKit* kit, bool may_throw,
 52                                    Node* src, Node* src_offset,
 53                                    Node* dest, Node* dest_offset,
 54                                    Node* length,
 55                                    bool alloc_tightly_coupled,
 56                                    bool has_negative_length_guard,
 57                                    Node* src_klass, Node* dest_klass,
 58                                    Node* src_length, Node* dest_length) {
 59 
 60   ArrayCopyNode* ac = new ArrayCopyNode(kit->C, alloc_tightly_coupled, has_negative_length_guard);
 61   kit->set_predefined_input_for_runtime_call(ac);
 62 
 63   ac->init_req(ArrayCopyNode::Src, src);
 64   ac->init_req(ArrayCopyNode::SrcPos, src_offset);
 65   ac->init_req(ArrayCopyNode::Dest, dest);
 66   ac->init_req(ArrayCopyNode::DestPos, dest_offset);
 67   ac->init_req(ArrayCopyNode::Length, length);
 68   ac->init_req(ArrayCopyNode::SrcLen, src_length);
 69   ac->init_req(ArrayCopyNode::DestLen, dest_length);
 70   ac->init_req(ArrayCopyNode::SrcKlass, src_klass);
 71   ac->init_req(ArrayCopyNode::DestKlass, dest_klass);
 72 
 73   if (may_throw) {
 74     ac->set_req(TypeFunc::I_O , kit->i_o());
 75     kit->add_safepoint_edges(ac, false);
 76   }
 77 
 78   return ac;
 79 }
 80 
 81 void ArrayCopyNode::connect_outputs(GraphKit* kit, bool deoptimize_on_exception) {
 82   kit->set_all_memory_call(this, true);
 83   kit->set_control(kit->gvn().transform(new ProjNode(this,TypeFunc::Control)));
 84   kit->set_i_o(kit->gvn().transform(new ProjNode(this, TypeFunc::I_O)));
 85   kit->make_slow_call_ex(this, kit->env()->Throwable_klass(), true, deoptimize_on_exception);
 86   kit->set_all_memory_call(this);
 87 }
 88 
 89 #ifndef PRODUCT
 90 const char* ArrayCopyNode::_kind_names[] = {"arraycopy", "arraycopy, validated arguments", "clone", "oop array clone", "CopyOf", "CopyOfRange"};
 91 
 92 void ArrayCopyNode::dump_spec(outputStream *st) const {
 93   CallNode::dump_spec(st);
 94   st->print(" (%s%s)", _kind_names[_kind], _alloc_tightly_coupled ? ", tightly coupled allocation" : "");
 95 }
 96 
 97 void ArrayCopyNode::dump_compact_spec(outputStream* st) const {
 98   st->print("%s%s", _kind_names[_kind], _alloc_tightly_coupled ? ",tight" : "");
 99 }
100 #endif
101 
102 intptr_t ArrayCopyNode::get_length_if_constant(PhaseGVN *phase) const {
103   // check that length is constant
104   Node* length = in(ArrayCopyNode::Length);
105   const Type* length_type = phase->type(length);
106 
107   if (length_type == Type::TOP) {
108     return -1;
109   }
110 
111   assert(is_clonebasic() || is_arraycopy() || is_copyof() || is_copyofrange(), "unexpected array copy type");
112 
113   return is_clonebasic() ? length->find_intptr_t_con(-1) : length->find_int_con(-1);
114 }
115 
116 int ArrayCopyNode::get_count(PhaseGVN *phase) const {
117   Node* src = in(ArrayCopyNode::Src);
118   const Type* src_type = phase->type(src);
119 
120   if (is_clonebasic()) {
121     if (src_type->isa_instptr()) {
122       const TypeInstPtr* inst_src = src_type->is_instptr();
123       ciInstanceKlass* ik = inst_src->klass()->as_instance_klass();
124       // ciInstanceKlass::nof_nonstatic_fields() doesn't take injected
125       // fields into account. They are rare anyway so easier to simply
126       // skip instances with injected fields.
127       if ((!inst_src->klass_is_exact() && (ik->is_interface() || ik->has_subklass())) || ik->has_injected_fields()) {
128         return -1;
129       }
130       int nb_fields = ik->nof_nonstatic_fields();
131       return nb_fields;
132     } else {
133       const TypeAryPtr* ary_src = src_type->isa_aryptr();
134       assert (ary_src != NULL, "not an array or instance?");
135       // clone passes a length as a rounded number of longs. If we're
136       // cloning an array we'll do it element by element. If the
137       // length input to ArrayCopyNode is constant, length of input
138       // array must be too.
139 
140       assert((get_length_if_constant(phase) == -1) != ary_src->size()->is_con() ||
141              phase->is_IterGVN() || phase->C->inlining_incrementally() || StressReflectiveCode, "inconsistent");
142 
143       if (ary_src->size()->is_con()) {
144         return ary_src->size()->get_con();
145       }
146       return -1;
147     }
148   }
149 
150   return get_length_if_constant(phase);
151 }
152 
153 Node* ArrayCopyNode::load(BarrierSetC2* bs, PhaseGVN *phase, Node*& ctl, MergeMemNode* mem, Node* adr, const TypePtr* adr_type, const Type *type, BasicType bt) {
154   DecoratorSet decorators = C2_READ_ACCESS | C2_CONTROL_DEPENDENT_LOAD | IN_HEAP | C2_ARRAY_COPY;
155   C2AccessValuePtr addr(adr, adr_type);
156   C2OptAccess access(*phase, ctl, mem, decorators, bt, adr->in(AddPNode::Base), addr);
157   Node* res = bs->load_at(access, type);
158   ctl = access.ctl();
159   return res;
160 }
161 
162 void ArrayCopyNode::store(BarrierSetC2* bs, PhaseGVN *phase, Node*& ctl, MergeMemNode* mem, Node* adr, const TypePtr* adr_type, Node* val, const Type *type, BasicType bt) {
163   DecoratorSet decorators = C2_WRITE_ACCESS | IN_HEAP | C2_ARRAY_COPY;
164   if (is_alloc_tightly_coupled()) {
165     decorators |= C2_TIGHTLY_COUPLED_ALLOC;
166   }
167   C2AccessValuePtr addr(adr, adr_type);
168   C2AccessValue value(val, type);
169   C2OptAccess access(*phase, ctl, mem, decorators, bt, adr->in(AddPNode::Base), addr);
170   bs->store_at(access, value);
171   ctl = access.ctl();
172 }
173 
174 
175 Node* ArrayCopyNode::try_clone_instance(PhaseGVN *phase, bool can_reshape, int count) {
176   if (!is_clonebasic()) {
177     return NULL;
178   }
179 
180   Node* base_src = in(ArrayCopyNode::Src);
181   Node* base_dest = in(ArrayCopyNode::Dest);
182   Node* ctl = in(TypeFunc::Control);
183   Node* in_mem = in(TypeFunc::Memory);
184 
185   const Type* src_type = phase->type(base_src);
186   const TypeInstPtr* inst_src = src_type->isa_instptr();
187   if (inst_src == NULL) {
188     return NULL;
189   }
190 
191   MergeMemNode* mem = phase->transform(MergeMemNode::make(in_mem))->as_MergeMem();
192   if (can_reshape) {
193     phase->is_IterGVN()->_worklist.push(mem);
194   }
195 
196   if (!inst_src->klass_is_exact()) {
197     ciInstanceKlass* ik = inst_src->klass()->as_instance_klass();
198     assert(!ik->is_interface(), "inconsistent klass hierarchy");
199     if (ik->has_subklass()) {
200       // Concurrent class loading.
201       // Fail fast and return NodeSentinel to indicate that the transform failed.
202       return NodeSentinel;
203     } else {
204       phase->C->dependencies()->assert_leaf_type(ik);
205     }
206   }
207 
208   ciInstanceKlass* ik = inst_src->klass()->as_instance_klass();
209   assert(ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem, "too many fields");
210 
211   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
212   for (int i = 0; i < count; i++) {
213     ciField* field = ik->nonstatic_field_at(i);
214     const TypePtr* adr_type = phase->C->alias_type(field)->adr_type();
215     Node* off = phase->MakeConX(field->offset());
216     Node* next_src = phase->transform(new AddPNode(base_src,base_src,off));
217     Node* next_dest = phase->transform(new AddPNode(base_dest,base_dest,off));
218     BasicType bt = field->layout_type();
219 
220     const Type *type;
221     if (bt == T_OBJECT) {
222       if (!field->type()->is_loaded()) {
223         type = TypeInstPtr::BOTTOM;
224       } else {
225         ciType* field_klass = field->type();
226         type = TypeOopPtr::make_from_klass(field_klass->as_klass());
227       }
228     } else {
229       type = Type::get_const_basic_type(bt);
230     }
231 
232     Node* v = load(bs, phase, ctl, mem, next_src, adr_type, type, bt);
233     store(bs, phase, ctl, mem, next_dest, adr_type, v, type, bt);
234   }
235 
236   if (!finish_transform(phase, can_reshape, ctl, mem)) {
237     // Return NodeSentinel to indicate that the transform failed
238     return NodeSentinel;
239   }
240 
241   return mem;
242 }
243 
244 bool ArrayCopyNode::prepare_array_copy(PhaseGVN *phase, bool can_reshape,
245                                        Node*& adr_src,
246                                        Node*& base_src,
247                                        Node*& adr_dest,
248                                        Node*& base_dest,
249                                        BasicType& copy_type,
250                                        const Type*& value_type,
251                                        bool& disjoint_bases) {
252   base_src = in(ArrayCopyNode::Src);
253   base_dest = in(ArrayCopyNode::Dest);
254   const Type* src_type = phase->type(base_src);
255   const TypeAryPtr* ary_src = src_type->isa_aryptr();
256 
257   Node* src_offset = in(ArrayCopyNode::SrcPos);
258   Node* dest_offset = in(ArrayCopyNode::DestPos);
259 
260   if (is_arraycopy() || is_copyofrange() || is_copyof()) {
261     const Type* dest_type = phase->type(base_dest);
262     const TypeAryPtr* ary_dest = dest_type->isa_aryptr();
263 
264     // newly allocated object is guaranteed to not overlap with source object
265     disjoint_bases = is_alloc_tightly_coupled();
266 
267     if (ary_src  == NULL || ary_src->klass()  == NULL ||
268         ary_dest == NULL || ary_dest->klass() == NULL) {
269       // We don't know if arguments are arrays
270       return false;
271     }
272 
273     BasicType src_elem  = ary_src->klass()->as_array_klass()->element_type()->basic_type();
274     BasicType dest_elem = ary_dest->klass()->as_array_klass()->element_type()->basic_type();
275     if (is_reference_type(src_elem))   src_elem  = T_OBJECT;
276     if (is_reference_type(dest_elem))  dest_elem = T_OBJECT;
277 
278     if (src_elem != dest_elem || dest_elem == T_VOID) {
279       // We don't know if arguments are arrays of the same type
280       return false;
281     }
282 
283     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
284     if (bs->array_copy_requires_gc_barriers(is_alloc_tightly_coupled(), dest_elem, false, false, BarrierSetC2::Optimization)) {
285       // It's an object array copy but we can't emit the card marking
286       // that is needed
287       return false;
288     }
289 
290     value_type = ary_src->elem();
291 
292     uint shift  = exact_log2(type2aelembytes(dest_elem));
293     uint header = arrayOopDesc::base_offset_in_bytes(dest_elem);
294 
295     src_offset = Compile::conv_I2X_index(phase, src_offset, ary_src->size());
296     if (src_offset->is_top()) {
297       // Offset is out of bounds (the ArrayCopyNode will be removed)
298       return false;
299     }
300     dest_offset = Compile::conv_I2X_index(phase, dest_offset, ary_dest->size());
301     if (dest_offset->is_top()) {
302       // Offset is out of bounds (the ArrayCopyNode will be removed)
303       if (can_reshape) {
304         // record src_offset, so it can be deleted later (if it is dead)
305         phase->is_IterGVN()->_worklist.push(src_offset);
306       }
307       return false;
308     }
309 
310     Node* src_scale  = phase->transform(new LShiftXNode(src_offset, phase->intcon(shift)));
311     Node* dest_scale = phase->transform(new LShiftXNode(dest_offset, phase->intcon(shift)));
312 
313     adr_src          = phase->transform(new AddPNode(base_src, base_src, src_scale));
314     adr_dest         = phase->transform(new AddPNode(base_dest, base_dest, dest_scale));
315 
316     adr_src          = phase->transform(new AddPNode(base_src, adr_src, phase->MakeConX(header)));
317     adr_dest         = phase->transform(new AddPNode(base_dest, adr_dest, phase->MakeConX(header)));
318 
319     copy_type = dest_elem;
320   } else {
321     assert(ary_src != NULL, "should be a clone");
322     assert(is_clonebasic(), "should be");
323 
324     disjoint_bases = true;
325 
326     BasicType elem = ary_src->klass()->as_array_klass()->element_type()->basic_type();
327     if (is_reference_type(elem)) {
328       elem = T_OBJECT;
329     }
330 
331     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
332     if (bs->array_copy_requires_gc_barriers(true, elem, true, is_clone_inst(), BarrierSetC2::Optimization)) {
333       return false;
334     }
335 
336     adr_src  = phase->transform(new AddPNode(base_src, base_src, src_offset));
337     adr_dest = phase->transform(new AddPNode(base_dest, base_dest, dest_offset));
338 
339     // The address is offseted to an aligned address where a raw copy would start.
340     // If the clone copy is decomposed into load-stores - the address is adjusted to
341     // point at where the array starts.
342     const Type* toff = phase->type(src_offset);
343     int offset = toff->isa_long() ? (int) toff->is_long()->get_con() : (int) toff->is_int()->get_con();
344     int diff = arrayOopDesc::base_offset_in_bytes(elem) - offset;
345     assert(diff >= 0, "clone should not start after 1st array element");
346     if (diff > 0) {
347       adr_src = phase->transform(new AddPNode(base_src, adr_src, phase->MakeConX(diff)));
348       adr_dest = phase->transform(new AddPNode(base_dest, adr_dest, phase->MakeConX(diff)));
349     }
350     copy_type = elem;
351     value_type = ary_src->elem();
352   }
353   return true;
354 }
355 
356 const TypePtr* ArrayCopyNode::get_address_type(PhaseGVN* phase, const TypePtr* atp, Node* n) {
357   if (atp == TypeOopPtr::BOTTOM) {
358     atp = phase->type(n)->isa_ptr();
359   }
360   // adjust atp to be the correct array element address type
361   return atp->add_offset(Type::OffsetBot);
362 }
363 
364 void ArrayCopyNode::array_copy_test_overlap(PhaseGVN *phase, bool can_reshape, bool disjoint_bases, int count, Node*& forward_ctl, Node*& backward_ctl) {
365   Node* ctl = in(TypeFunc::Control);
366   if (!disjoint_bases && count > 1) {
367     Node* src_offset = in(ArrayCopyNode::SrcPos);
368     Node* dest_offset = in(ArrayCopyNode::DestPos);
369     assert(src_offset != NULL && dest_offset != NULL, "should be");
370     Node* cmp = phase->transform(new CmpINode(src_offset, dest_offset));
371     Node *bol = phase->transform(new BoolNode(cmp, BoolTest::lt));
372     IfNode *iff = new IfNode(ctl, bol, PROB_FAIR, COUNT_UNKNOWN);
373 
374     phase->transform(iff);
375 
376     forward_ctl = phase->transform(new IfFalseNode(iff));
377     backward_ctl = phase->transform(new IfTrueNode(iff));
378   } else {
379     forward_ctl = ctl;
380   }
381 }
382 
383 Node* ArrayCopyNode::array_copy_forward(PhaseGVN *phase,
384                                         bool can_reshape,
385                                         Node*& forward_ctl,
386                                         Node* mem,
387                                         const TypePtr* atp_src,
388                                         const TypePtr* atp_dest,
389                                         Node* adr_src,
390                                         Node* base_src,
391                                         Node* adr_dest,
392                                         Node* base_dest,
393                                         BasicType copy_type,
394                                         const Type* value_type,
395                                         int count) {
396   if (!forward_ctl->is_top()) {
397     // copy forward
398     MergeMemNode* mm = MergeMemNode::make(mem);
399 
400     if (count > 0) {
401       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
402       Node* v = load(bs, phase, forward_ctl, mm, adr_src, atp_src, value_type, copy_type);
403       store(bs, phase, forward_ctl, mm, adr_dest, atp_dest, v, value_type, copy_type);
404       for (int i = 1; i < count; i++) {
405         Node* off  = phase->MakeConX(type2aelembytes(copy_type) * i);
406         Node* next_src = phase->transform(new AddPNode(base_src,adr_src,off));
407         Node* next_dest = phase->transform(new AddPNode(base_dest,adr_dest,off));
408         v = load(bs, phase, forward_ctl, mm, next_src, atp_src, value_type, copy_type);
409         store(bs, phase, forward_ctl, mm, next_dest, atp_dest, v, value_type, copy_type);
410       }
411     } else if (can_reshape) {
412       PhaseIterGVN* igvn = phase->is_IterGVN();
413       igvn->_worklist.push(adr_src);
414       igvn->_worklist.push(adr_dest);
415     }
416     return mm;
417   }
418   return phase->C->top();
419 }
420 
421 Node* ArrayCopyNode::array_copy_backward(PhaseGVN *phase,
422                                          bool can_reshape,
423                                          Node*& backward_ctl,
424                                          Node* mem,
425                                          const TypePtr* atp_src,
426                                          const TypePtr* atp_dest,
427                                          Node* adr_src,
428                                          Node* base_src,
429                                          Node* adr_dest,
430                                          Node* base_dest,
431                                          BasicType copy_type,
432                                          const Type* value_type,
433                                          int count) {
434   if (!backward_ctl->is_top()) {
435     // copy backward
436     MergeMemNode* mm = MergeMemNode::make(mem);
437 
438     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
439     assert(copy_type != T_OBJECT || !bs->array_copy_requires_gc_barriers(false, T_OBJECT, false, false, BarrierSetC2::Optimization), "only tightly coupled allocations for object arrays");
440 
441     if (count > 0) {
442       for (int i = count-1; i >= 1; i--) {
443         Node* off  = phase->MakeConX(type2aelembytes(copy_type) * i);
444         Node* next_src = phase->transform(new AddPNode(base_src,adr_src,off));
445         Node* next_dest = phase->transform(new AddPNode(base_dest,adr_dest,off));
446         Node* v = load(bs, phase, backward_ctl, mm, next_src, atp_src, value_type, copy_type);
447         store(bs, phase, backward_ctl, mm, next_dest, atp_dest, v, value_type, copy_type);
448       }
449       Node* v = load(bs, phase, backward_ctl, mm, adr_src, atp_src, value_type, copy_type);
450       store(bs, phase, backward_ctl, mm, adr_dest, atp_dest, v, value_type, copy_type);
451     } else if (can_reshape) {
452       PhaseIterGVN* igvn = phase->is_IterGVN();
453       igvn->_worklist.push(adr_src);
454       igvn->_worklist.push(adr_dest);
455     }
456     return phase->transform(mm);
457   }
458   return phase->C->top();
459 }
460 
461 bool ArrayCopyNode::finish_transform(PhaseGVN *phase, bool can_reshape,
462                                      Node* ctl, Node *mem) {
463   if (can_reshape) {
464     PhaseIterGVN* igvn = phase->is_IterGVN();
465     igvn->set_delay_transform(false);
466     if (is_clonebasic()) {
467       Node* out_mem = proj_out(TypeFunc::Memory);
468 
469       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
470       if (out_mem->outcnt() != 1 || !out_mem->raw_out(0)->is_MergeMem() ||
471           out_mem->raw_out(0)->outcnt() != 1 || !out_mem->raw_out(0)->raw_out(0)->is_MemBar()) {
472         assert(bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, is_clone_inst(), BarrierSetC2::Optimization), "can only happen with card marking");
473         return false;
474       }
475 
476       igvn->replace_node(out_mem->raw_out(0), mem);
477 
478       Node* out_ctl = proj_out(TypeFunc::Control);
479       igvn->replace_node(out_ctl, ctl);
480     } else {
481       // replace fallthrough projections of the ArrayCopyNode by the
482       // new memory, control and the input IO.
483       CallProjections callprojs;
484       extract_projections(&callprojs, true, false);
485 
486       if (callprojs.fallthrough_ioproj != NULL) {
487         igvn->replace_node(callprojs.fallthrough_ioproj, in(TypeFunc::I_O));
488       }
489       if (callprojs.fallthrough_memproj != NULL) {
490         igvn->replace_node(callprojs.fallthrough_memproj, mem);
491       }
492       if (callprojs.fallthrough_catchproj != NULL) {
493         igvn->replace_node(callprojs.fallthrough_catchproj, ctl);
494       }
495 
496       // The ArrayCopyNode is not disconnected. It still has the
497       // projections for the exception case. Replace current
498       // ArrayCopyNode with a dummy new one with a top() control so
499       // that this part of the graph stays consistent but is
500       // eventually removed.
501 
502       set_req(0, phase->C->top());
503       remove_dead_region(phase, can_reshape);
504     }
505   } else {
506     if (in(TypeFunc::Control) != ctl) {
507       // we can't return new memory and control from Ideal at parse time
508       assert(!is_clonebasic() || UseShenandoahGC, "added control for clone?");
509       phase->record_for_igvn(this);
510       return false;
511     }
512   }
513   return true;
514 }
515 
516 
517 Node *ArrayCopyNode::Ideal(PhaseGVN *phase, bool can_reshape) {
518   if (remove_dead_region(phase, can_reshape))  return this;
519 
520   if (StressArrayCopyMacroNode && !can_reshape) {
521     phase->record_for_igvn(this);
522     return NULL;
523   }
524 
525   // See if it's a small array copy and we can inline it as
526   // loads/stores
527   // Here we can only do:
528   // - arraycopy if all arguments were validated before and we don't
529   // need card marking
530   // - clone for which we don't need to do card marking
531 
532   if (!is_clonebasic() && !is_arraycopy_validated() &&
533       !is_copyofrange_validated() && !is_copyof_validated()) {
534     return NULL;
535   }
536 
537   assert(in(TypeFunc::Control) != NULL &&
538          in(TypeFunc::Memory) != NULL &&
539          in(ArrayCopyNode::Src) != NULL &&
540          in(ArrayCopyNode::Dest) != NULL &&
541          in(ArrayCopyNode::Length) != NULL &&
542          in(ArrayCopyNode::SrcPos) != NULL &&
543          in(ArrayCopyNode::DestPos) != NULL, "broken inputs");
544 
545   if (in(TypeFunc::Control)->is_top() ||
546       in(TypeFunc::Memory)->is_top() ||
547       phase->type(in(ArrayCopyNode::Src)) == Type::TOP ||
548       phase->type(in(ArrayCopyNode::Dest)) == Type::TOP ||
549       (in(ArrayCopyNode::SrcPos) != NULL && in(ArrayCopyNode::SrcPos)->is_top()) ||
550       (in(ArrayCopyNode::DestPos) != NULL && in(ArrayCopyNode::DestPos)->is_top())) {
551     return NULL;
552   }
553 
554   int count = get_count(phase);
555 
556   if (count < 0 || count > ArrayCopyLoadStoreMaxElem) {
557     return NULL;
558   }
559 
560   Node* mem = try_clone_instance(phase, can_reshape, count);
561   if (mem != NULL) {
562     return (mem == NodeSentinel) ? NULL : mem;
563   }
564 
565   Node* adr_src = NULL;
566   Node* base_src = NULL;
567   Node* adr_dest = NULL;
568   Node* base_dest = NULL;
569   BasicType copy_type = T_ILLEGAL;
570   const Type* value_type = NULL;
571   bool disjoint_bases = false;
572 
573   if (!prepare_array_copy(phase, can_reshape,
574                           adr_src, base_src, adr_dest, base_dest,
575                           copy_type, value_type, disjoint_bases)) {
576     assert(adr_src == NULL, "no node can be left behind");
577     assert(adr_dest == NULL, "no node can be left behind");
578     return NULL;
579   }
580 
581   Node* src = in(ArrayCopyNode::Src);
582   Node* dest = in(ArrayCopyNode::Dest);
583   const TypePtr* atp_src = get_address_type(phase, _src_type, src);
584   const TypePtr* atp_dest = get_address_type(phase, _dest_type, dest);
585   Node* in_mem = in(TypeFunc::Memory);
586 
587   if (can_reshape) {
588     assert(!phase->is_IterGVN()->delay_transform(), "cannot delay transforms");
589     phase->is_IterGVN()->set_delay_transform(true);
590   }
591 
592   Node* backward_ctl = phase->C->top();
593   Node* forward_ctl = phase->C->top();
594   array_copy_test_overlap(phase, can_reshape, disjoint_bases, count, forward_ctl, backward_ctl);
595 
596   Node* forward_mem = array_copy_forward(phase, can_reshape, forward_ctl,
597                                          in_mem,
598                                          atp_src, atp_dest,
599                                          adr_src, base_src, adr_dest, base_dest,
600                                          copy_type, value_type, count);
601 
602   Node* backward_mem = array_copy_backward(phase, can_reshape, backward_ctl,
603                                            in_mem,
604                                            atp_src, atp_dest,
605                                            adr_src, base_src, adr_dest, base_dest,
606                                            copy_type, value_type, count);
607 
608   Node* ctl = NULL;
609   if (!forward_ctl->is_top() && !backward_ctl->is_top()) {
610     ctl = new RegionNode(3);
611     ctl->init_req(1, forward_ctl);
612     ctl->init_req(2, backward_ctl);
613     ctl = phase->transform(ctl);
614     MergeMemNode* forward_mm = forward_mem->as_MergeMem();
615     MergeMemNode* backward_mm = backward_mem->as_MergeMem();
616     for (MergeMemStream mms(forward_mm, backward_mm); mms.next_non_empty2(); ) {
617       if (mms.memory() != mms.memory2()) {
618         Node* phi = new PhiNode(ctl, Type::MEMORY, phase->C->get_adr_type(mms.alias_idx()));
619         phi->init_req(1, mms.memory());
620         phi->init_req(2, mms.memory2());
621         phi = phase->transform(phi);
622         mms.set_memory(phi);
623       }
624     }
625     mem = forward_mem;
626   } else if (!forward_ctl->is_top()) {
627     ctl = forward_ctl;
628     mem = forward_mem;
629   } else {
630     assert(!backward_ctl->is_top(), "no copy?");
631     ctl = backward_ctl;
632     mem = backward_mem;
633   }
634 
635   if (can_reshape) {
636     assert(phase->is_IterGVN()->delay_transform(), "should be delaying transforms");
637     phase->is_IterGVN()->set_delay_transform(false);
638   }
639 
640   if (!finish_transform(phase, can_reshape, ctl, mem)) {
641     if (can_reshape) {
642       // put in worklist, so that if it happens to be dead it is removed
643       phase->is_IterGVN()->_worklist.push(mem);
644     }
645     return NULL;
646   }
647 
648   return mem;
649 }
650 
651 bool ArrayCopyNode::may_modify(const TypeOopPtr *t_oop, PhaseTransform *phase) {
652   Node* dest = in(ArrayCopyNode::Dest);
653   if (dest->is_top()) {
654     return false;
655   }
656   const TypeOopPtr* dest_t = phase->type(dest)->is_oopptr();
657   assert(!dest_t->is_known_instance() || _dest_type->is_known_instance(), "result of EA not recorded");
658   assert(in(ArrayCopyNode::Src)->is_top() || !phase->type(in(ArrayCopyNode::Src))->is_oopptr()->is_known_instance() ||
659          _src_type->is_known_instance(), "result of EA not recorded");
660 
661   if (_dest_type != TypeOopPtr::BOTTOM || t_oop->is_known_instance()) {
662     assert(_dest_type == TypeOopPtr::BOTTOM || _dest_type->is_known_instance(), "result of EA is known instance");
663     return t_oop->instance_id() == _dest_type->instance_id();
664   }
665 
666   return CallNode::may_modify_arraycopy_helper(dest_t, t_oop, phase);
667 }
668 
669 bool ArrayCopyNode::may_modify_helper(const TypeOopPtr *t_oop, Node* n, PhaseTransform *phase, CallNode*& call) {
670   if (n != NULL &&
671       n->is_Call() &&
672       n->as_Call()->may_modify(t_oop, phase) &&
673       (n->as_Call()->is_ArrayCopy() || n->as_Call()->is_call_to_arraycopystub())) {
674     call = n->as_Call();
675     return true;
676   }
677   return false;
678 }
679 
680 bool ArrayCopyNode::may_modify(const TypeOopPtr *t_oop, MemBarNode* mb, PhaseTransform *phase, ArrayCopyNode*& ac) {
681 
682   Node* c = mb->in(0);
683 
684   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
685   // step over g1 gc barrier if we're at e.g. a clone with ReduceInitialCardMarks off
686   c = bs->step_over_gc_barrier(c);
687 
688   CallNode* call = NULL;
689   guarantee(c != NULL, "step_over_gc_barrier failed, there must be something to step to.");
690   if (c->is_Region()) {
691     for (uint i = 1; i < c->req(); i++) {
692       if (c->in(i) != NULL) {
693         Node* n = c->in(i)->in(0);
694         if (may_modify_helper(t_oop, n, phase, call)) {
695           ac = call->isa_ArrayCopy();
696           assert(c == mb->in(0), "only for clone");
697           return true;
698         }
699       }
700     }
701   } else if (may_modify_helper(t_oop, c->in(0), phase, call)) {
702     ac = call->isa_ArrayCopy();
703 #ifdef ASSERT
704     bool use_ReduceInitialCardMarks = BarrierSet::barrier_set()->is_a(BarrierSet::CardTableBarrierSet) &&
705       static_cast<CardTableBarrierSetC2*>(bs)->use_ReduceInitialCardMarks();
706     assert(c == mb->in(0) || (ac != NULL && ac->is_clonebasic() && !use_ReduceInitialCardMarks), "only for clone");
707 #endif
708     return true;
709   } else if (mb->trailing_partial_array_copy()) {
710     return true;
711   }
712 
713   return false;
714 }
715 
716 // Does this array copy modify offsets between offset_lo and offset_hi
717 // in the destination array
718 // if must_modify is false, return true if the copy could write
719 // between offset_lo and offset_hi
720 // if must_modify is true, return true if the copy is guaranteed to
721 // write between offset_lo and offset_hi
722 bool ArrayCopyNode::modifies(intptr_t offset_lo, intptr_t offset_hi, PhaseTransform* phase, bool must_modify) const {
723   assert(_kind == ArrayCopy || _kind == CopyOf || _kind == CopyOfRange, "only for real array copies");
724 
725   Node* dest = in(Dest);
726   Node* dest_pos = in(DestPos);
727   Node* len = in(Length);
728 
729   const TypeInt *dest_pos_t = phase->type(dest_pos)->isa_int();
730   const TypeInt *len_t = phase->type(len)->isa_int();
731   const TypeAryPtr* ary_t = phase->type(dest)->isa_aryptr();
732 
733   if (dest_pos_t == NULL || len_t == NULL || ary_t == NULL) {
734     return !must_modify;
735   }
736 
737   BasicType ary_elem = ary_t->klass()->as_array_klass()->element_type()->basic_type();
738   uint header = arrayOopDesc::base_offset_in_bytes(ary_elem);
739   uint elemsize = type2aelembytes(ary_elem);
740 
741   jlong dest_pos_plus_len_lo = (((jlong)dest_pos_t->_lo) + len_t->_lo) * elemsize + header;
742   jlong dest_pos_plus_len_hi = (((jlong)dest_pos_t->_hi) + len_t->_hi) * elemsize + header;
743   jlong dest_pos_lo = ((jlong)dest_pos_t->_lo) * elemsize + header;
744   jlong dest_pos_hi = ((jlong)dest_pos_t->_hi) * elemsize + header;
745 
746   if (must_modify) {
747     if (offset_lo >= dest_pos_hi && offset_hi < dest_pos_plus_len_lo) {
748       return true;
749     }
750   } else {
751     if (offset_hi >= dest_pos_lo && offset_lo < dest_pos_plus_len_hi) {
752       return true;
753     }
754   }
755   return false;
756 }
757 
758 // As an optimization, choose optimum vector size for copy length known at compile time.
759 int ArrayCopyNode::get_partial_inline_vector_lane_count(BasicType type, int const_len) {
760   int lane_count = ArrayOperationPartialInlineSize/type2aelembytes(type);
761   if (const_len > 0) {
762     int size_in_bytes = const_len * type2aelembytes(type);
763     if (size_in_bytes <= 16)
764       lane_count = 16/type2aelembytes(type);
765     else if (size_in_bytes > 16 && size_in_bytes <= 32)
766       lane_count = 32/type2aelembytes(type);
767   }
768   return lane_count;
769 }