1 /*
  2  * Copyright (c) 2014, 2023, 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 "opto/addnode.hpp"
 27 #include "opto/callnode.hpp"
 28 #include "opto/castnode.hpp"
 29 #include "opto/connode.hpp"
 30 #include "opto/graphKit.hpp"
 31 #include "opto/inlinetypenode.hpp"
 32 #include "opto/matcher.hpp"
 33 #include "opto/phaseX.hpp"
 34 #include "opto/rootnode.hpp"
 35 #include "opto/subnode.hpp"
 36 #include "opto/type.hpp"
 37 #include "castnode.hpp"
 38 #include "utilities/checkedCast.hpp"
 39 
 40 //=============================================================================
 41 // If input is already higher or equal to cast type, then this is an identity.
 42 Node* ConstraintCastNode::Identity(PhaseGVN* phase) {
 43   if (_dependency == UnconditionalDependency) {
 44     return this;
 45   }
 46   Node* dom = dominating_cast(phase, phase);
 47   if (dom != nullptr) {
 48     return dom;
 49   }
 50   return higher_equal_types(phase, in(1)) ? in(1) : this;
 51 }
 52 
 53 //------------------------------Value------------------------------------------
 54 // Take 'join' of input and cast-up type
 55 const Type* ConstraintCastNode::Value(PhaseGVN* phase) const {
 56   if (in(0) && phase->type(in(0)) == Type::TOP) return Type::TOP;
 57 
 58   const Type* in_type = phase->type(in(1));
 59   const Type* ft = in_type->filter_speculative(_type);
 60 
 61   // Check if both _type and in_type had a speculative type, but for the just
 62   // computed ft the speculative type was dropped.
 63   if (ft->speculative() == nullptr &&
 64       _type->speculative() != nullptr &&
 65       in_type->speculative() != nullptr) {
 66     // Speculative type may have disagreed between cast and input, and was
 67     // dropped in filtering. Recompute so that ft can take speculative type
 68     // of in_type. If we did not do it now, a subsequent ::Value call would
 69     // do it, and violate idempotence of ::Value.
 70     ft = in_type->filter_speculative(ft);
 71   }
 72 
 73 #ifdef ASSERT
 74   // Previous versions of this function had some special case logic,
 75   // which is no longer necessary.  Make sure of the required effects.
 76   switch (Opcode()) {
 77     case Op_CastII:
 78     {
 79       if (in_type == Type::TOP) {
 80         assert(ft == Type::TOP, "special case #1");
 81       }
 82       const Type* rt = in_type->join_speculative(_type);
 83       if (rt->empty()) {
 84         assert(ft == Type::TOP, "special case #2");
 85       }
 86       break;
 87     }
 88     case Op_CastPP:
 89     if (in_type == TypePtr::NULL_PTR &&
 90         _type->isa_ptr() && _type->is_ptr()->_ptr == TypePtr::NotNull) {
 91       assert(ft == Type::TOP, "special case #3");
 92       break;
 93     }
 94   }
 95 #endif //ASSERT
 96 
 97   return ft;
 98 }
 99 
100 //------------------------------Ideal------------------------------------------
101 // Return a node which is more "ideal" than the current node.  Strip out
102 // control copies
103 Node *ConstraintCastNode::Ideal(PhaseGVN *phase, bool can_reshape) {
104   if (in(0) && remove_dead_region(phase, can_reshape)) {
105     return this;
106   }
107 
108   // Push cast through InlineTypeNode
109   InlineTypeNode* vt = in(1)->isa_InlineType();
110   if (vt != nullptr && phase->type(vt)->filter_speculative(_type) != Type::TOP) {
111     // TODO 8325106 Can we avoid cloning?
112     Node* cast = clone();
113     cast->set_req(1, vt->get_oop());
114     vt = vt->clone()->as_InlineType();
115     if (!_type->maybe_null()) {
116       vt->as_InlineType()->set_is_init(*phase);
117     }
118     vt->set_oop(*phase, phase->transform(cast));
119     return vt;
120   }
121 
122   return nullptr;
123 }
124 
125 uint ConstraintCastNode::hash() const {
126   return TypeNode::hash() + (int)_dependency + (_extra_types != nullptr ? _extra_types->hash() : 0);
127 }
128 
129 bool ConstraintCastNode::cmp(const Node &n) const {
130   if (!TypeNode::cmp(n)) {
131     return false;
132   }
133   ConstraintCastNode& cast = (ConstraintCastNode&) n;
134   if (cast._dependency != _dependency) {
135     return false;
136   }
137   if (_extra_types == nullptr || cast._extra_types == nullptr) {
138     return _extra_types == cast._extra_types;
139   }
140   return _extra_types->eq(cast._extra_types);
141 }
142 
143 uint ConstraintCastNode::size_of() const {
144   return sizeof(*this);
145 }
146 
147 Node* ConstraintCastNode::make_cast_for_basic_type(Node* c, Node* n, const Type* t, DependencyType dependency, BasicType bt) {
148   switch(bt) {
149   case T_INT:
150     return new CastIINode(c, n, t, dependency);
151   case T_LONG:
152     return new CastLLNode(c, n, t, dependency);
153   default:
154     fatal("Bad basic type %s", type2name(bt));
155   }
156   return nullptr;
157 }
158 
159 TypeNode* ConstraintCastNode::dominating_cast(PhaseGVN* gvn, PhaseTransform* pt) const {
160   if (_dependency == UnconditionalDependency) {
161     return nullptr;
162   }
163   Node* val = in(1);
164   Node* ctl = in(0);
165   int opc = Opcode();
166   if (ctl == nullptr) {
167     return nullptr;
168   }
169   // Range check CastIIs may all end up under a single range check and
170   // in that case only the narrower CastII would be kept by the code
171   // below which would be incorrect.
172   if (is_CastII() && as_CastII()->has_range_check()) {
173     return nullptr;
174   }
175   if (type()->isa_rawptr() && (gvn->type_or_null(val) == nullptr || gvn->type(val)->isa_oopptr())) {
176     return nullptr;
177   }
178   for (DUIterator_Fast imax, i = val->fast_outs(imax); i < imax; i++) {
179     Node* u = val->fast_out(i);
180     if (u != this &&
181         u->outcnt() > 0 &&
182         u->Opcode() == opc &&
183         u->in(0) != nullptr &&
184         higher_equal_types(gvn, u)) {
185       if (pt->is_dominator(u->in(0), ctl)) {
186         return u->as_Type();
187       }
188       if (is_CheckCastPP() && u->in(1)->is_Proj() && u->in(1)->in(0)->is_Allocate() &&
189           u->in(0)->is_Proj() && u->in(0)->in(0)->is_Initialize() &&
190           u->in(1)->in(0)->as_Allocate()->initialization() == u->in(0)->in(0)) {
191         // CheckCastPP following an allocation always dominates all
192         // use of the allocation result
193         return u->as_Type();
194       }
195     }
196   }
197   return nullptr;
198 }
199 
200 bool ConstraintCastNode::higher_equal_types(PhaseGVN* phase, const Node* other) const {
201   const Type* t = phase->type(other);
202   if (!t->higher_equal_speculative(type())) {
203     return false;
204   }
205   if (_extra_types != nullptr) {
206     for (uint i = 0; i < _extra_types->cnt(); ++i) {
207       if (!t->higher_equal_speculative(_extra_types->field_at(i))) {
208         return false;
209       }
210     }
211   }
212   return true;
213 }
214 
215 #ifndef PRODUCT
216 void ConstraintCastNode::dump_spec(outputStream *st) const {
217   TypeNode::dump_spec(st);
218   if (_extra_types != nullptr) {
219     st->print(" extra types: ");
220     _extra_types->dump_on(st);
221   }
222   if (_dependency != RegularDependency) {
223     st->print(" %s dependency", _dependency == StrongDependency ? "strong" : "unconditional");
224   }
225 }
226 #endif
227 
228 const Type* CastIINode::Value(PhaseGVN* phase) const {
229   const Type *res = ConstraintCastNode::Value(phase);
230   if (res == Type::TOP) {
231     return Type::TOP;
232   }
233   assert(res->isa_int(), "res must be int");
234 
235   // Similar to ConvI2LNode::Value() for the same reasons
236   // see if we can remove type assertion after loop opts
237   // But here we have to pay extra attention:
238   // Do not narrow the type of range check dependent CastIINodes to
239   // avoid corruption of the graph if a CastII is replaced by TOP but
240   // the corresponding range check is not removed.
241   if (!_range_check_dependency) {
242     res = widen_type(phase, res, T_INT);
243   }
244 
245   return res;
246 }
247 
248 static Node* find_or_make_integer_cast(PhaseIterGVN* igvn, Node* parent, Node* control, const TypeInteger* type, ConstraintCastNode::DependencyType dependency, BasicType bt) {
249   Node* n = ConstraintCastNode::make_cast_for_basic_type(control, parent, type, dependency, bt);
250   Node* existing = igvn->hash_find_insert(n);
251   if (existing != nullptr) {
252     n->destruct(igvn);
253     return existing;
254   }
255   return igvn->register_new_node_with_optimizer(n);
256 }
257 
258 Node *CastIINode::Ideal(PhaseGVN *phase, bool can_reshape) {
259   Node* progress = ConstraintCastNode::Ideal(phase, can_reshape);
260   if (progress != nullptr) {
261     return progress;
262   }
263   if (can_reshape && !_range_check_dependency && !phase->C->post_loop_opts_phase()) {
264     // makes sure we run ::Value to potentially remove type assertion after loop opts
265     phase->C->record_for_post_loop_opts_igvn(this);
266   }
267   if (!_range_check_dependency) {
268     return optimize_integer_cast(phase, T_INT);
269   }
270   return nullptr;
271 }
272 
273 Node* CastIINode::Identity(PhaseGVN* phase) {
274   Node* progress = ConstraintCastNode::Identity(phase);
275   if (progress != this) {
276     return progress;
277   }
278   if (_range_check_dependency) {
279     if (phase->C->post_loop_opts_phase()) {
280       return this->in(1);
281     } else {
282       phase->C->record_for_post_loop_opts_igvn(this);
283     }
284   }
285   return this;
286 }
287 
288 bool CastIINode::cmp(const Node &n) const {
289   return ConstraintCastNode::cmp(n) && ((CastIINode&)n)._range_check_dependency == _range_check_dependency;
290 }
291 
292 uint CastIINode::size_of() const {
293   return sizeof(*this);
294 }
295 
296 #ifndef PRODUCT
297 void CastIINode::dump_spec(outputStream* st) const {
298   ConstraintCastNode::dump_spec(st);
299   if (_range_check_dependency) {
300     st->print(" range check dependency");
301   }
302 }
303 #endif
304 
305 CastIINode* CastIINode::pin_array_access_node() const {
306   assert(_dependency == RegularDependency, "already pinned");
307   if (has_range_check()) {
308     return new CastIINode(in(0), in(1), bottom_type(), StrongDependency, has_range_check());
309   }
310   return nullptr;
311 }
312 
313 
314 const Type* CastLLNode::Value(PhaseGVN* phase) const {
315   const Type* res = ConstraintCastNode::Value(phase);
316   if (res == Type::TOP) {
317     return Type::TOP;
318   }
319   assert(res->isa_long(), "res must be long");
320 
321   return widen_type(phase, res, T_LONG);
322 }
323 
324 Node* CastLLNode::Ideal(PhaseGVN* phase, bool can_reshape) {
325   Node* progress = ConstraintCastNode::Ideal(phase, can_reshape);
326   if (progress != nullptr) {
327     return progress;
328   }
329   if (!phase->C->post_loop_opts_phase()) {
330     // makes sure we run ::Value to potentially remove type assertion after loop opts
331     phase->C->record_for_post_loop_opts_igvn(this);
332   }
333   // transform (CastLL (ConvI2L ..)) into (ConvI2L (CastII ..)) if the type of the CastLL is narrower than the type of
334   // the ConvI2L.
335   Node* in1 = in(1);
336   if (in1 != nullptr && in1->Opcode() == Op_ConvI2L) {
337     const Type* t = Value(phase);
338     const Type* t_in = phase->type(in1);
339     if (t != Type::TOP && t_in != Type::TOP) {
340       const TypeLong* tl = t->is_long();
341       const TypeLong* t_in_l = t_in->is_long();
342       assert(tl->_lo >= t_in_l->_lo && tl->_hi <= t_in_l->_hi, "CastLL type should be narrower than or equal to the type of its input");
343       assert((tl != t_in_l) == (tl->_lo > t_in_l->_lo || tl->_hi < t_in_l->_hi), "if type differs then this nodes's type must be narrower");
344       if (tl != t_in_l) {
345         const TypeInt* ti = TypeInt::make(checked_cast<jint>(tl->_lo), checked_cast<jint>(tl->_hi), tl->_widen);
346         Node* castii = phase->transform(new CastIINode(in(0), in1->in(1), ti));
347         Node* convi2l = in1->clone();
348         convi2l->set_req(1, castii);
349         return convi2l;
350       }
351     }
352   }
353   return optimize_integer_cast(phase, T_LONG);
354 }
355 
356 //=============================================================================
357 //------------------------------Identity---------------------------------------
358 // If input is already higher or equal to cast type, then this is an identity.
359 Node* CheckCastPPNode::Identity(PhaseGVN* phase) {
360   if (in(1)->is_InlineType() && _type->isa_instptr() && phase->type(in(1))->inline_klass()->is_subtype_of(_type->is_instptr()->instance_klass())) {
361     return in(1);
362   }
363   return ConstraintCastNode::Identity(phase);
364 }
365 
366 //------------------------------Value------------------------------------------
367 // Take 'join' of input and cast-up type, unless working with an Interface
368 const Type* CheckCastPPNode::Value(PhaseGVN* phase) const {
369   if( in(0) && phase->type(in(0)) == Type::TOP ) return Type::TOP;
370 
371   const Type *inn = phase->type(in(1));
372   if( inn == Type::TOP ) return Type::TOP;  // No information yet
373 
374   if (inn->isa_oopptr() && _type->isa_oopptr()) {
375     return ConstraintCastNode::Value(phase);
376   }
377 
378   const TypePtr *in_type = inn->isa_ptr();
379   const TypePtr *my_type = _type->isa_ptr();
380   const Type *result = _type;
381   if (in_type != nullptr && my_type != nullptr) {
382     // TODO 8302672
383     if (!StressReflectiveCode && my_type->isa_aryptr() && in_type->isa_aryptr()) {
384       // Propagate array properties (not flat/null-free)
385       // Don't do this when StressReflectiveCode is enabled because it might lead to
386       // a dying data path while the corresponding flat/null-free check is not folded.
387       my_type = my_type->is_aryptr()->update_properties(in_type->is_aryptr());
388       if (my_type == nullptr) {
389         return Type::TOP; // Inconsistent properties
390       }
391     }
392     TypePtr::PTR in_ptr = in_type->ptr();
393     if (in_ptr == TypePtr::Null) {
394       result = in_type;
395     } else if (in_ptr != TypePtr::Constant) {
396       result = my_type->cast_to_ptr_type(my_type->join_ptr(in_ptr));
397     }
398   }
399 
400   return result;
401 }
402 
403 //=============================================================================
404 //------------------------------Value------------------------------------------
405 const Type* CastX2PNode::Value(PhaseGVN* phase) const {
406   const Type* t = phase->type(in(1));
407   if (t == Type::TOP) return Type::TOP;
408   if (t->base() == Type_X && t->singleton()) {
409     uintptr_t bits = (uintptr_t) t->is_intptr_t()->get_con();
410     if (bits == 0)   return TypePtr::NULL_PTR;
411     return TypeRawPtr::make((address) bits);
412   }
413   return CastX2PNode::bottom_type();
414 }
415 
416 //------------------------------Idealize---------------------------------------
417 static inline bool fits_in_int(const Type* t, bool but_not_min_int = false) {
418   if (t == Type::TOP)  return false;
419   const TypeX* tl = t->is_intptr_t();
420   jint lo = min_jint;
421   jint hi = max_jint;
422   if (but_not_min_int)  ++lo;  // caller wants to negate the value w/o overflow
423   return (tl->_lo >= lo) && (tl->_hi <= hi);
424 }
425 
426 static inline Node* addP_of_X2P(PhaseGVN *phase,
427                                 Node* base,
428                                 Node* dispX,
429                                 bool negate = false) {
430   if (negate) {
431     dispX = phase->transform(new SubXNode(phase->MakeConX(0), dispX));
432   }
433   return new AddPNode(phase->C->top(),
434                       phase->transform(new CastX2PNode(base)),
435                       dispX);
436 }
437 
438 Node *CastX2PNode::Ideal(PhaseGVN *phase, bool can_reshape) {
439   // convert CastX2P(AddX(x, y)) to AddP(CastX2P(x), y) if y fits in an int
440   int op = in(1)->Opcode();
441   Node* x;
442   Node* y;
443   switch (op) {
444     case Op_SubX:
445     x = in(1)->in(1);
446     // Avoid ideal transformations ping-pong between this and AddP for raw pointers.
447     if (phase->find_intptr_t_con(x, -1) == 0)
448     break;
449     y = in(1)->in(2);
450     if (fits_in_int(phase->type(y), true)) {
451       return addP_of_X2P(phase, x, y, true);
452     }
453     break;
454     case Op_AddX:
455     x = in(1)->in(1);
456     y = in(1)->in(2);
457     if (fits_in_int(phase->type(y))) {
458       return addP_of_X2P(phase, x, y);
459     }
460     if (fits_in_int(phase->type(x))) {
461       return addP_of_X2P(phase, y, x);
462     }
463     break;
464   }
465   return nullptr;
466 }
467 
468 //------------------------------Identity---------------------------------------
469 Node* CastX2PNode::Identity(PhaseGVN* phase) {
470   if (in(1)->Opcode() == Op_CastP2X)  return in(1)->in(1);
471   return this;
472 }
473 
474 //=============================================================================
475 //------------------------------Value------------------------------------------
476 const Type* CastP2XNode::Value(PhaseGVN* phase) const {
477   const Type* t = phase->type(in(1));
478   if (t == Type::TOP) return Type::TOP;
479   if (t->base() == Type::RawPtr && t->singleton()) {
480     uintptr_t bits = (uintptr_t) t->is_rawptr()->get_con();
481     return TypeX::make(bits);
482   }
483 
484   if (t->is_zero_type() || !t->maybe_null()) {
485     for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
486       Node* u = fast_out(i);
487       if (u->Opcode() == Op_OrL) {
488         for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
489           Node* cmp = u->fast_out(j);
490           if (cmp->Opcode() == Op_CmpL) {
491             // Give CmpL a chance to get optimized
492             phase->record_for_igvn(cmp);
493           }
494         }
495       }
496     }
497   }
498 
499   return CastP2XNode::bottom_type();
500 }
501 
502 Node *CastP2XNode::Ideal(PhaseGVN *phase, bool can_reshape) {
503   return (in(0) && remove_dead_region(phase, can_reshape)) ? this : nullptr;
504 }
505 
506 //------------------------------Identity---------------------------------------
507 Node* CastP2XNode::Identity(PhaseGVN* phase) {
508   if (in(1)->Opcode() == Op_CastX2P)  return in(1)->in(1);
509   return this;
510 }
511 
512 Node* ConstraintCastNode::make_cast_for_type(Node* c, Node* in, const Type* type, DependencyType dependency,
513                                              const TypeTuple* types) {
514   if (type->isa_int()) {
515     return new CastIINode(c, in, type, dependency, false, types);
516   } else if (type->isa_long()) {
517     return new CastLLNode(c, in, type, dependency, types);
518   } else if (type->isa_float()) {
519     return new CastFFNode(c, in, type, dependency, types);
520   } else if (type->isa_double()) {
521     return new CastDDNode(c, in, type, dependency, types);
522   } else if (type->isa_vect()) {
523     return new CastVVNode(c, in, type, dependency, types);
524   } else if (type->isa_ptr()) {
525     return new CastPPNode(c, in, type, dependency, types);
526   }
527   fatal("unreachable. Invalid cast type.");
528   return nullptr;
529 }
530 
531 Node* ConstraintCastNode::optimize_integer_cast(PhaseGVN* phase, BasicType bt) {
532   PhaseIterGVN *igvn = phase->is_IterGVN();
533   const TypeInteger* this_type = this->type()->is_integer(bt);
534   Node* z = in(1);
535   const TypeInteger* rx = nullptr;
536   const TypeInteger* ry = nullptr;
537   // Similar to ConvI2LNode::Ideal() for the same reasons
538   if (Compile::push_thru_add(phase, z, this_type, rx, ry, bt, bt)) {
539     if (igvn == nullptr) {
540       // Postpone this optimization to iterative GVN, where we can handle deep
541       // AddI chains without an exponential number of recursive Ideal() calls.
542       phase->record_for_igvn(this);
543       return nullptr;
544     }
545     int op = z->Opcode();
546     Node* x = z->in(1);
547     Node* y = z->in(2);
548 
549     Node* cx = find_or_make_integer_cast(igvn, x, in(0), rx, _dependency, bt);
550     Node* cy = find_or_make_integer_cast(igvn, y, in(0), ry, _dependency, bt);
551     if (op == Op_Add(bt)) {
552       return AddNode::make(cx, cy, bt);
553     } else {
554       assert(op == Op_Sub(bt), "");
555       return SubNode::make(cx, cy, bt);
556     }
557     return nullptr;
558   }
559   return nullptr;
560 }
561 
562 const Type* ConstraintCastNode::widen_type(const PhaseGVN* phase, const Type* res, BasicType bt) const {
563   if (!phase->C->post_loop_opts_phase()) {
564     return res;
565   }
566   const TypeInteger* this_type = res->is_integer(bt);
567   const TypeInteger* in_type = phase->type(in(1))->isa_integer(bt);
568   if (in_type != nullptr &&
569       (in_type->lo_as_long() != this_type->lo_as_long() ||
570        in_type->hi_as_long() != this_type->hi_as_long())) {
571     jlong lo1 = this_type->lo_as_long();
572     jlong hi1 = this_type->hi_as_long();
573     int w1 = this_type->_widen;
574     if (lo1 >= 0) {
575       // Keep a range assertion of >=0.
576       lo1 = 0;        hi1 = max_signed_integer(bt);
577     } else if (hi1 < 0) {
578       // Keep a range assertion of <0.
579       lo1 = min_signed_integer(bt); hi1 = -1;
580     } else {
581       lo1 = min_signed_integer(bt); hi1 = max_signed_integer(bt);
582     }
583     return TypeInteger::make(MAX2(in_type->lo_as_long(), lo1),
584                              MIN2(in_type->hi_as_long(), hi1),
585                              MAX2((int)in_type->_widen, w1), bt);
586   }
587   return res;
588 }