1 /*
  2  * Copyright (c) 1998, 2025, 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 "ci/ciSymbols.hpp"
 26 #include "compiler/compileLog.hpp"
 27 #include "oops/objArrayKlass.hpp"
 28 #include "opto/addnode.hpp"
 29 #include "opto/memnode.hpp"
 30 #include "opto/mulnode.hpp"
 31 #include "opto/parse.hpp"
 32 #include "opto/rootnode.hpp"
 33 #include "opto/runtime.hpp"
 34 #include "runtime/sharedRuntime.hpp"
 35 
 36 //------------------------------make_dtrace_method_entry_exit ----------------
 37 // Dtrace -- record entry or exit of a method if compiled with dtrace support
 38 void GraphKit::make_dtrace_method_entry_exit(ciMethod* method, bool is_entry) {
 39   const TypeFunc *call_type    = OptoRuntime::dtrace_method_entry_exit_Type();
 40   address         call_address = is_entry ? CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry) :
 41                                             CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit);
 42   const char     *call_name    = is_entry ? "dtrace_method_entry" : "dtrace_method_exit";
 43 
 44   // Get base of thread-local storage area
 45   Node* thread = _gvn.transform( new ThreadLocalNode() );
 46 
 47   // Get method
 48   const TypePtr* method_type = TypeMetadataPtr::make(method);
 49   Node *method_node = _gvn.transform(ConNode::make(method_type));
 50 
 51   kill_dead_locals();
 52 
 53   // For some reason, this call reads only raw memory.
 54   const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
 55   make_runtime_call(RC_LEAF | RC_NARROW_MEM,
 56                     call_type, call_address,
 57                     call_name, raw_adr_type,
 58                     thread, method_node);
 59 }
 60 
 61 
 62 //=============================================================================
 63 //------------------------------do_checkcast-----------------------------------
 64 void Parse::do_checkcast() {
 65   bool will_link;
 66   ciKlass* klass = iter().get_klass(will_link);
 67 
 68   Node *obj = peek();
 69 
 70   // Throw uncommon trap if class is not loaded or the value we are casting
 71   // _from_ is not loaded, and value is not null.  If the value _is_ null,
 72   // then the checkcast does nothing.
 73   const TypeOopPtr *tp = _gvn.type(obj)->isa_oopptr();
 74   if (!will_link || (tp && !tp->is_loaded())) {
 75     if (C->log() != nullptr) {
 76       if (!will_link) {
 77         C->log()->elem("assert_null reason='checkcast' klass='%d'",
 78                        C->log()->identify(klass));
 79       }
 80       if (tp && !tp->is_loaded()) {
 81         // %%% Cannot happen?
 82         ciKlass* klass = tp->unloaded_klass();
 83         C->log()->elem("assert_null reason='checkcast source' klass='%d'",
 84                        C->log()->identify(klass));
 85       }
 86     }
 87     null_assert(obj);
 88     assert( stopped() || _gvn.type(peek())->higher_equal(TypePtr::NULL_PTR), "what's left behind is null" );
 89     return;
 90   }
 91 
 92   Node* res = gen_checkcast(obj, makecon(TypeKlassPtr::make(klass, Type::trust_interfaces)));
 93   if (stopped()) {
 94     return;
 95   }
 96 
 97   // Pop from stack AFTER gen_checkcast because it can uncommon trap and
 98   // the debug info has to be correct.
 99   pop();
100   push(res);
101 }
102 
103 
104 //------------------------------do_instanceof----------------------------------
105 void Parse::do_instanceof() {
106   if (stopped())  return;
107   // We would like to return false if class is not loaded, emitting a
108   // dependency, but Java requires instanceof to load its operand.
109 
110   // Throw uncommon trap if class is not loaded
111   bool will_link;
112   ciKlass* klass = iter().get_klass(will_link);
113 
114   if (!will_link) {
115     if (C->log() != nullptr) {
116       C->log()->elem("assert_null reason='instanceof' klass='%d'",
117                      C->log()->identify(klass));
118     }
119     null_assert(peek());
120     assert( stopped() || _gvn.type(peek())->higher_equal(TypePtr::NULL_PTR), "what's left behind is null" );
121     if (!stopped()) {
122       // The object is now known to be null.
123       // Shortcut the effect of gen_instanceof and return "false" directly.
124       pop();                   // pop the null
125       push(_gvn.intcon(0));    // push false answer
126     }
127     return;
128   }
129 
130   // Push the bool result back on stack
131   Node* res = gen_instanceof(peek(), makecon(TypeKlassPtr::make(klass, Type::trust_interfaces)), true);
132 
133   // Pop from stack AFTER gen_instanceof because it can uncommon trap.
134   pop();
135   push(res);
136 }
137 
138 //------------------------------array_store_check------------------------------
139 // pull array from stack and check that the store is valid
140 void Parse::array_store_check() {
141 
142   // Shorthand access to array store elements without popping them.
143   Node *obj = peek(0);
144   Node *idx = peek(1);
145   Node *ary = peek(2);
146 
147   if (_gvn.type(obj) == TypePtr::NULL_PTR) {
148     // There's never a type check on null values.
149     // This cutout lets us avoid the uncommon_trap(Reason_array_check)
150     // below, which turns into a performance liability if the
151     // gen_checkcast folds up completely.
152     return;
153   }
154 
155   // Extract the array klass type
156   int klass_offset = oopDesc::klass_offset_in_bytes();
157   Node* p = basic_plus_adr( ary, ary, klass_offset );
158   // p's type is array-of-OOPS plus klass_offset
159   Node* array_klass = _gvn.transform(LoadKlassNode::make(_gvn, nullptr, immutable_memory(), p, TypeInstPtr::KLASS));
160   // Get the array klass
161   const TypeKlassPtr *tak = _gvn.type(array_klass)->is_klassptr();
162 
163   // The type of array_klass is usually INexact array-of-oop.  Heroically
164   // cast array_klass to EXACT array and uncommon-trap if the cast fails.
165   // Make constant out of the inexact array klass, but use it only if the cast
166   // succeeds.
167   bool always_see_exact_class = false;
168   if (MonomorphicArrayCheck
169       && !too_many_traps(Deoptimization::Reason_array_check)
170       && !tak->klass_is_exact()
171       && tak != TypeInstKlassPtr::OBJECT) {
172       // Regarding the fourth condition in the if-statement from above:
173       //
174       // If the compiler has determined that the type of array 'ary' (represented
175       // by 'array_klass') is java/lang/Object, the compiler must not assume that
176       // the array 'ary' is monomorphic.
177       //
178       // If 'ary' were of type java/lang/Object, this arraystore would have to fail,
179       // because it is not possible to perform a arraystore into an object that is not
180       // a "proper" array.
181       //
182       // Therefore, let's obtain at runtime the type of 'ary' and check if we can still
183       // successfully perform the store.
184       //
185       // The implementation reasons for the condition are the following:
186       //
187       // java/lang/Object is the superclass of all arrays, but it is represented by the VM
188       // as an InstanceKlass. The checks generated by gen_checkcast() (see below) expect
189       // 'array_klass' to be ObjArrayKlass, which can result in invalid memory accesses.
190       //
191       // See issue JDK-8057622 for details.
192 
193     always_see_exact_class = true;
194     // (If no MDO at all, hope for the best, until a trap actually occurs.)
195 
196     // Make a constant out of the inexact array klass
197     const TypeKlassPtr *extak = tak->cast_to_exactness(true);
198 
199     if (extak->exact_klass(true) != nullptr) {
200       Node* con = makecon(extak);
201       Node* cmp = _gvn.transform(new CmpPNode( array_klass, con ));
202       Node* bol = _gvn.transform(new BoolNode( cmp, BoolTest::eq ));
203       Node* ctrl= control();
204       { BuildCutout unless(this, bol, PROB_MAX);
205         uncommon_trap(Deoptimization::Reason_array_check,
206                       Deoptimization::Action_maybe_recompile,
207                       extak->exact_klass());
208       }
209       if (stopped()) {          // MUST uncommon-trap?
210         set_control(ctrl);      // Then Don't Do It, just fall into the normal checking
211       } else {                  // Cast array klass to exactness:
212         // Use the exact constant value we know it is.
213         replace_in_map(array_klass,con);
214         CompileLog* log = C->log();
215         if (log != nullptr) {
216           log->elem("cast_up reason='monomorphic_array' from='%d' to='(exact)'",
217                     log->identify(extak->exact_klass()));
218         }
219         array_klass = con;      // Use cast value moving forward
220       }
221     }
222   }
223 
224   // Come here for polymorphic array klasses
225 
226   // Extract the array element class
227   int element_klass_offset = in_bytes(ObjArrayKlass::element_klass_offset());
228   Node *p2 = basic_plus_adr(array_klass, array_klass, element_klass_offset);
229   // We are allowed to use the constant type only if cast succeeded. If always_see_exact_class is true,
230   // we must set a control edge from the IfTrue node created by the uncommon_trap above to the
231   // LoadKlassNode.
232   Node* a_e_klass = _gvn.transform(LoadKlassNode::make(_gvn, always_see_exact_class ? control() : nullptr,
233                                                        immutable_memory(), p2, tak));
234 
235   // Check (the hard way) and throw if not a subklass.
236   // Result is ignored, we just need the CFG effects.
237   gen_checkcast(obj, a_e_klass);
238 }
239 
240 
241 //------------------------------do_new-----------------------------------------
242 void Parse::do_new() {
243   kill_dead_locals();
244 
245   bool will_link;
246   ciInstanceKlass* klass = iter().get_klass(will_link)->as_instance_klass();
247   assert(will_link, "_new: typeflow responsibility");
248 
249   // Should throw an InstantiationError?
250   if (klass->is_abstract() || klass->is_interface() ||
251       klass->name() == ciSymbols::java_lang_Class() ||
252       iter().is_unresolved_klass()) {
253     uncommon_trap(Deoptimization::Reason_unhandled,
254                   Deoptimization::Action_none,
255                   klass);
256     return;
257   }
258 
259   if (C->needs_clinit_barrier(klass, method())) {
260     clinit_barrier(klass, method());
261     if (stopped())  return;
262   }
263 
264   Node* kls = makecon(TypeKlassPtr::make(klass));
265   Node* obj = new_instance(kls);
266 
267   // Push resultant oop onto stack
268   push(obj);
269 
270   // Keep track of whether opportunities exist for StringBuilder
271   // optimizations.
272   if (OptimizeStringConcat &&
273       (klass == C->env()->StringBuilder_klass() ||
274        klass == C->env()->StringBuffer_klass())) {
275     C->set_has_stringbuilder(true);
276   }
277 
278   // Keep track of boxed values for EliminateAutoBox optimizations.
279   if (C->eliminate_boxing() && klass->is_box_klass()) {
280     C->set_has_boxed_value(true);
281   }
282 }
283 
284 #ifndef PRODUCT
285 //------------------------------dump_map_adr_mem-------------------------------
286 // Debug dump of the mapping from address types to MergeMemNode indices.
287 void Parse::dump_map_adr_mem() const {
288   tty->print_cr("--- Mapping from address types to memory Nodes ---");
289   MergeMemNode *mem = map() == nullptr ? nullptr : (map()->memory()->is_MergeMem() ?
290                                       map()->memory()->as_MergeMem() : nullptr);
291   for (uint i = 0; i < (uint)C->num_alias_types(); i++) {
292     C->alias_type(i)->print_on(tty);
293     tty->print("\t");
294     // Node mapping, if any
295     if (mem && i < mem->req() && mem->in(i) && mem->in(i) != mem->empty_memory()) {
296       mem->in(i)->dump();
297     } else {
298       tty->cr();
299     }
300   }
301 }
302 
303 #endif