1 /*
  2  * Copyright (c) 2001, 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 #ifndef SHARE_OPTO_GRAPHKIT_HPP
 26 #define SHARE_OPTO_GRAPHKIT_HPP
 27 
 28 #include "ci/ciEnv.hpp"
 29 #include "ci/ciMethodData.hpp"
 30 #include "gc/shared/c2/barrierSetC2.hpp"
 31 #include "opto/addnode.hpp"
 32 #include "opto/callnode.hpp"
 33 #include "opto/cfgnode.hpp"
 34 #include "opto/compile.hpp"
 35 #include "opto/divnode.hpp"
 36 #include "opto/mulnode.hpp"
 37 #include "opto/phaseX.hpp"
 38 #include "opto/subnode.hpp"
 39 #include "opto/type.hpp"
 40 #include "runtime/deoptimization.hpp"
 41 
 42 class BarrierSetC2;
 43 class FastLockNode;
 44 class FastUnlockNode;
 45 class IdealKit;
 46 class LibraryCallKit;
 47 class Parse;
 48 class RootNode;
 49 
 50 //-----------------------------------------------------------------------------
 51 //----------------------------GraphKit-----------------------------------------
 52 // Toolkit for building the common sorts of subgraphs.
 53 // Does not know about bytecode parsing or type-flow results.
 54 // It is able to create graphs implementing the semantics of most
 55 // or all bytecodes, so that it can expand intrinsics and calls.
 56 // It may depend on JVMState structure, but it must not depend
 57 // on specific bytecode streams.
 58 class GraphKit : public Phase {
 59   friend class PreserveJVMState;
 60 
 61  protected:
 62   ciEnv*            _env;       // Compilation environment
 63   PhaseGVN         &_gvn;       // Some optimizations while parsing
 64   SafePointNode*    _map;       // Parser map from JVM to Nodes
 65   SafePointNode*    _exceptions;// Parser map(s) for exception state(s)
 66   int               _bci;       // JVM Bytecode Pointer
 67   ciMethod*         _method;    // JVM Current Method
 68   BarrierSetC2*     _barrier_set;
 69 
 70  private:
 71   int               _sp;        // JVM Expression Stack Pointer; don't modify directly!
 72 
 73  private:
 74   SafePointNode*     map_not_null() const {
 75     assert(_map != nullptr, "must call stopped() to test for reset compiler map");
 76     return _map;
 77   }
 78 
 79  public:
 80   GraphKit();                   // empty constructor
 81   GraphKit(JVMState* jvms);     // the JVM state on which to operate
 82 
 83 #ifdef ASSERT
 84   ~GraphKit() {
 85     assert(failing() || !has_exceptions(),
 86            "unless compilation failed, user must call transfer_exceptions_into_jvms");
 87   }
 88 #endif
 89 
 90   virtual Parse*          is_Parse()          const { return nullptr; }
 91   virtual LibraryCallKit* is_LibraryCallKit() const { return nullptr; }
 92 
 93   ciEnv*        env()               const { return _env; }
 94   PhaseGVN&     gvn()               const { return _gvn; }
 95   void*         barrier_set_state() const { return C->barrier_set_state(); }
 96 
 97   void record_for_igvn(Node* n) const { C->record_for_igvn(n); }  // delegate to Compile
 98   void remove_for_igvn(Node* n) const { C->remove_for_igvn(n); }
 99 
100   // Handy well-known nodes:
101   Node*         null()          const { return zerocon(T_OBJECT); }
102   Node*         top()           const { return C->top(); }
103   RootNode*     root()          const { return C->root(); }
104 
105   // Create or find a constant node
106   Node* intcon(jint con)        const { return _gvn.intcon(con); }
107   Node* longcon(jlong con)      const { return _gvn.longcon(con); }
108   Node* integercon(jlong con, BasicType bt)   const {
109     if (bt == T_INT) {
110       return intcon(checked_cast<jint>(con));
111     }
112     assert(bt == T_LONG, "basic type not an int or long");
113     return longcon(con);
114   }
115   Node* makecon(const Type *t)  const { return _gvn.makecon(t); }
116   Node* zerocon(BasicType bt)   const { return _gvn.zerocon(bt); }
117   // (See also macro MakeConX in type.hpp, which uses intcon or longcon.)
118 
119   jint  find_int_con(Node* n, jint value_if_unknown) {
120     return _gvn.find_int_con(n, value_if_unknown);
121   }
122   jlong find_long_con(Node* n, jlong value_if_unknown) {
123     return _gvn.find_long_con(n, value_if_unknown);
124   }
125   // (See also macro find_intptr_t_con in type.hpp, which uses one of these.)
126 
127   // JVM State accessors:
128   // Parser mapping from JVM indices into Nodes.
129   // Low slots are accessed by the StartNode::enum.
130   // Then come the locals at StartNode::Parms to StartNode::Parms+max_locals();
131   // Then come JVM stack slots.
132   // Finally come the monitors, if any.
133   // See layout accessors in class JVMState.
134 
135   SafePointNode*     map()      const { return _map; }
136   bool               has_exceptions() const { return _exceptions != nullptr; }
137   JVMState*          jvms()     const { return map_not_null()->_jvms; }
138   int                sp()       const { return _sp; }
139   int                bci()      const { return _bci; }
140   Bytecodes::Code    java_bc()  const;
141   ciMethod*          method()   const { return _method; }
142 
143   void set_jvms(JVMState* jvms)       { set_map(jvms->map());
144                                         assert(jvms == this->jvms(), "sanity");
145                                         _sp = jvms->sp();
146                                         _bci = jvms->bci();
147                                         _method = jvms->has_method() ? jvms->method() : nullptr; }
148   void set_map(SafePointNode* m)      { _map = m; debug_only(verify_map()); }
149   void set_sp(int sp)                 { assert(sp >= 0, "sp must be non-negative: %d", sp); _sp = sp; }
150   void clean_stack(int from_sp); // clear garbage beyond from_sp to top
151 
152   void inc_sp(int i)                  { set_sp(sp() + i); }
153   void dec_sp(int i)                  { set_sp(sp() - i); }
154   void set_bci(int bci)               { _bci = bci; }
155 
156   // Make sure jvms has current bci & sp.
157   JVMState* sync_jvms() const;
158   JVMState* sync_jvms_for_reexecute();
159 
160 #ifdef ASSERT
161   // Make sure JVMS has an updated copy of bci and sp.
162   // Also sanity-check method, depth, and monitor depth.
163   bool jvms_in_sync() const;
164 
165   // Make sure the map looks OK.
166   void verify_map() const;
167 
168   // Make sure a proposed exception state looks OK.
169   static void verify_exception_state(SafePointNode* ex_map);
170 #endif
171 
172   // Clone the existing map state.  (Implements PreserveJVMState.)
173   SafePointNode* clone_map();
174 
175   // Reverses the work done by clone_map(). Should only be used when the node returned by
176   // clone_map() is ultimately not used. Calling Node::destruct directly in the previously
177   // mentioned circumstance instead of this method may result in use-after-free.
178   void destruct_map_clone(SafePointNode* sfp);
179 
180   // Set the map to a clone of the given one.
181   void set_map_clone(SafePointNode* m);
182 
183   // Tell if the compilation is failing.
184   bool failing() const { return C->failing(); }
185 
186   // Set _map to null, signalling a stop to further bytecode execution.
187   // Preserve the map intact for future use, and return it back to the caller.
188   SafePointNode* stop() { SafePointNode* m = map(); set_map(nullptr); return m; }
189 
190   // Stop, but first smash the map's inputs to null, to mark it dead.
191   void stop_and_kill_map();
192 
193   // Tell if _map is null, or control is top.
194   bool stopped();
195 
196   // Tell if this method or any caller method has exception handlers.
197   bool has_exception_handler();
198 
199   // Save an exception without blowing stack contents or other JVM state.
200   // (The extra pointer is stuck with add_req on the map, beyond the JVMS.)
201   static void set_saved_ex_oop(SafePointNode* ex_map, Node* ex_oop);
202 
203   // Recover a saved exception from its map.
204   static Node* saved_ex_oop(SafePointNode* ex_map);
205 
206   // Recover a saved exception from its map, and remove it from the map.
207   static Node* clear_saved_ex_oop(SafePointNode* ex_map);
208 
209 #ifdef ASSERT
210   // Recover a saved exception from its map, and remove it from the map.
211   static bool has_saved_ex_oop(SafePointNode* ex_map);
212 #endif
213 
214   // Push an exception in the canonical position for handlers (stack(0)).
215   void push_ex_oop(Node* ex_oop) {
216     ensure_stack(1);  // ensure room to push the exception
217     set_stack(0, ex_oop);
218     set_sp(1);
219     clean_stack(1);
220   }
221 
222   // Detach and return an exception state.
223   SafePointNode* pop_exception_state() {
224     SafePointNode* ex_map = _exceptions;
225     if (ex_map != nullptr) {
226       _exceptions = ex_map->next_exception();
227       ex_map->set_next_exception(nullptr);
228       debug_only(verify_exception_state(ex_map));
229     }
230     return ex_map;
231   }
232 
233   // Add an exception, using the given JVM state, without commoning.
234   void push_exception_state(SafePointNode* ex_map) {
235     debug_only(verify_exception_state(ex_map));
236     ex_map->set_next_exception(_exceptions);
237     _exceptions = ex_map;
238   }
239 
240   // Turn the current JVM state into an exception state, appending the ex_oop.
241   SafePointNode* make_exception_state(Node* ex_oop);
242 
243   // Add an exception, using the given JVM state.
244   // Combine all exceptions with a common exception type into a single state.
245   // (This is done via combine_exception_states.)
246   void add_exception_state(SafePointNode* ex_map);
247 
248   // Combine all exceptions of any sort whatever into a single master state.
249   SafePointNode* combine_and_pop_all_exception_states() {
250     if (_exceptions == nullptr)  return nullptr;
251     SafePointNode* phi_map = pop_exception_state();
252     SafePointNode* ex_map;
253     while ((ex_map = pop_exception_state()) != nullptr) {
254       combine_exception_states(ex_map, phi_map);
255     }
256     return phi_map;
257   }
258 
259   // Combine the two exception states, building phis as necessary.
260   // The second argument is updated to include contributions from the first.
261   void combine_exception_states(SafePointNode* ex_map, SafePointNode* phi_map);
262 
263   // Reset the map to the given state.  If there are any half-finished phis
264   // in it (created by combine_exception_states), transform them now.
265   // Returns the exception oop.  (Caller must call push_ex_oop if required.)
266   Node* use_exception_state(SafePointNode* ex_map);
267 
268   // Collect exceptions from a given JVM state into my exception list.
269   void add_exception_states_from(JVMState* jvms);
270 
271   // Collect all raised exceptions into the current JVM state.
272   // Clear the current exception list and map, returns the combined states.
273   JVMState* transfer_exceptions_into_jvms();
274 
275   // Helper to throw a built-in exception.
276   // The JVMS must allow the bytecode to be re-executed via an uncommon trap.
277   void builtin_throw(Deoptimization::DeoptReason reason);
278 
279   // Helper to check the JavaThread::_should_post_on_exceptions flag
280   // and branch to an uncommon_trap if it is true (with the specified reason and must_throw)
281   void uncommon_trap_if_should_post_on_exceptions(Deoptimization::DeoptReason reason,
282                                                   bool must_throw) ;
283 
284   // Helper Functions for adding debug information
285   void kill_dead_locals();
286 #ifdef ASSERT
287   bool dead_locals_are_killed();
288 #endif
289   // The call may deoptimize.  Supply required JVM state as debug info.
290   // If must_throw is true, the call is guaranteed not to return normally.
291   void add_safepoint_edges(SafePointNode* call,
292                            bool must_throw = false);
293 
294   // How many stack inputs does the current BC consume?
295   // And, how does the stack change after the bytecode?
296   // Returns false if unknown.
297   bool compute_stack_effects(int& inputs, int& depth);
298 
299   // Add a fixed offset to a pointer
300   Node* basic_plus_adr(Node* base, Node* ptr, intptr_t offset) {
301     return basic_plus_adr(base, ptr, MakeConX(offset));
302   }
303   Node* basic_plus_adr(Node* base, intptr_t offset) {
304     return basic_plus_adr(base, base, MakeConX(offset));
305   }
306   // Add a variable offset to a pointer
307   Node* basic_plus_adr(Node* base, Node* offset) {
308     return basic_plus_adr(base, base, offset);
309   }
310   Node* basic_plus_adr(Node* base, Node* ptr, Node* offset);
311 
312 
313   // Some convenient shortcuts for common nodes
314   Node* IfTrue(IfNode* iff)                   { return _gvn.transform(new IfTrueNode(iff));      }
315   Node* IfFalse(IfNode* iff)                  { return _gvn.transform(new IfFalseNode(iff));     }
316 
317   Node* AddI(Node* l, Node* r)                { return _gvn.transform(new AddINode(l, r));       }
318   Node* SubI(Node* l, Node* r)                { return _gvn.transform(new SubINode(l, r));       }
319   Node* MulI(Node* l, Node* r)                { return _gvn.transform(new MulINode(l, r));       }
320   Node* DivI(Node* ctl, Node* l, Node* r)     { return _gvn.transform(new DivINode(ctl, l, r));  }
321 
322   Node* AndI(Node* l, Node* r)                { return _gvn.transform(new AndINode(l, r));       }
323   Node* OrI(Node* l, Node* r)                 { return _gvn.transform(new OrINode(l, r));        }
324   Node* XorI(Node* l, Node* r)                { return _gvn.transform(new XorINode(l, r));       }
325 
326   Node* MaxI(Node* l, Node* r)                { return _gvn.transform(new MaxINode(l, r));       }
327   Node* MinI(Node* l, Node* r)                { return _gvn.transform(new MinINode(l, r));       }
328 
329   Node* LShiftI(Node* l, Node* r)             { return _gvn.transform(new LShiftINode(l, r));    }
330   Node* RShiftI(Node* l, Node* r)             { return _gvn.transform(new RShiftINode(l, r));    }
331   Node* URShiftI(Node* l, Node* r)            { return _gvn.transform(new URShiftINode(l, r));   }
332 
333   Node* CmpI(Node* l, Node* r)                { return _gvn.transform(new CmpINode(l, r));       }
334   Node* CmpL(Node* l, Node* r)                { return _gvn.transform(new CmpLNode(l, r));       }
335   Node* CmpP(Node* l, Node* r)                { return _gvn.transform(new CmpPNode(l, r));       }
336   Node* Bool(Node* cmp, BoolTest::mask relop) { return _gvn.transform(new BoolNode(cmp, relop)); }
337 
338   Node* AddP(Node* b, Node* a, Node* o)       { return _gvn.transform(new AddPNode(b, a, o));    }
339 
340   // Convert between int and long, and size_t.
341   // (See macros ConvI2X, etc., in type.hpp for ConvI2X, etc.)
342   Node* ConvI2L(Node* offset);
343   Node* ConvI2UL(Node* offset);
344   Node* ConvL2I(Node* offset);
345   // Find out the klass of an object.
346   Node* load_object_klass(Node* object);
347   // Find out the length of an array.
348   Node* load_array_length(Node* array);
349   // Cast array allocation's length as narrow as possible.
350   // If replace_length_in_map is true, replace length with CastIINode in map.
351   // This method is invoked after creating/moving ArrayAllocationNode or in load_array_length
352   Node* array_ideal_length(AllocateArrayNode* alloc,
353                            const TypeOopPtr* oop_type,
354                            bool replace_length_in_map);
355 
356 
357   // Helper function to do a null pointer check or ZERO check based on type.
358   // Throw an exception if a given value is null.
359   // Return the value cast to not-null.
360   // Be clever about equivalent dominating null checks.
361   Node* null_check_common(Node* value, BasicType type,
362                           bool assert_null = false,
363                           Node* *null_control = nullptr,
364                           bool speculative = false);
365   Node* null_check(Node* value, BasicType type = T_OBJECT) {
366     return null_check_common(value, type, false, nullptr, !_gvn.type(value)->speculative_maybe_null());
367   }
368   Node* null_check_receiver() {
369     assert(argument(0)->bottom_type()->isa_ptr(), "must be");
370     return null_check(argument(0));
371   }
372   Node* zero_check_int(Node* value) {
373     assert(value->bottom_type()->basic_type() == T_INT,
374            "wrong type: %s", type2name(value->bottom_type()->basic_type()));
375     return null_check_common(value, T_INT);
376   }
377   Node* zero_check_long(Node* value) {
378     assert(value->bottom_type()->basic_type() == T_LONG,
379            "wrong type: %s", type2name(value->bottom_type()->basic_type()));
380     return null_check_common(value, T_LONG);
381   }
382   // Throw an uncommon trap if a given value is __not__ null.
383   // Return the value cast to null, and be clever about dominating checks.
384   Node* null_assert(Node* value, BasicType type = T_OBJECT) {
385     return null_check_common(value, type, true, nullptr, _gvn.type(value)->speculative_always_null());
386   }
387 
388   // Check if value is null and abort if it is
389   Node* must_be_not_null(Node* value, bool do_replace_in_map);
390 
391   // Null check oop.  Return null-path control into (*null_control).
392   // Return a cast-not-null node which depends on the not-null control.
393   // If never_see_null, use an uncommon trap (*null_control sees a top).
394   // The cast is not valid along the null path; keep a copy of the original.
395   // If safe_for_replace, then we can replace the value with the cast
396   // in the parsing map (the cast is guaranteed to dominate the map)
397   Node* null_check_oop(Node* value, Node* *null_control,
398                        bool never_see_null = false,
399                        bool safe_for_replace = false,
400                        bool speculative = false);
401 
402   // Check the null_seen bit.
403   bool seems_never_null(Node* obj, ciProfileData* data, bool& speculating);
404 
405   void guard_klass_is_initialized(Node* klass);
406   void guard_klass_being_initialized(Node* klass);
407   void guard_init_thread(Node* klass);
408 
409   void clinit_barrier(ciInstanceKlass* ik, ciMethod* context);
410 
411   // Check for unique class for receiver at call
412   ciKlass* profile_has_unique_klass() {
413     ciCallProfile profile = method()->call_profile_at_bci(bci());
414     if (profile.count() >= 0 &&         // no cast failures here
415         profile.has_receiver(0) &&
416         profile.morphism() == 1) {
417       return profile.receiver(0);
418     }
419     return nullptr;
420   }
421 
422   // record type from profiling with the type system
423   Node* record_profile_for_speculation(Node* n, ciKlass* exact_kls, ProfilePtrKind ptr_kind);
424   void record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc);
425   void record_profiled_parameters_for_speculation();
426   void record_profiled_return_for_speculation();
427   Node* record_profiled_receiver_for_speculation(Node* n);
428 
429   // Use the type profile to narrow an object type.
430   Node* maybe_cast_profiled_receiver(Node* not_null_obj,
431                                      const TypeKlassPtr* require_klass,
432                                      ciKlass* spec,
433                                      bool safe_for_replace);
434 
435   // Cast obj to type and emit guard unless we had too many traps here already
436   Node* maybe_cast_profiled_obj(Node* obj,
437                                 ciKlass* type,
438                                 bool not_null = false);
439 
440   // Cast obj to not-null on this path
441   Node* cast_not_null(Node* obj, bool do_replace_in_map = true);
442   // Replace all occurrences of one node by another.
443   void replace_in_map(Node* old, Node* neww);
444 
445   void  push(Node* n)     { map_not_null();        _map->set_stack(_map->_jvms,   _sp++        , n); }
446   Node* pop()             { map_not_null(); return _map->stack(    _map->_jvms, --_sp             ); }
447   Node* peek(int off = 0) { map_not_null(); return _map->stack(    _map->_jvms,   _sp - off - 1   ); }
448 
449   void push_pair(Node* ldval) {
450     push(ldval);
451     push(top());  // the halfword is merely a placeholder
452   }
453   void push_pair_local(int i) {
454     // longs are stored in locals in "push" order
455     push(  local(i+0) );  // the real value
456     assert(local(i+1) == top(), "");
457     push(top());  // halfword placeholder
458   }
459   Node* pop_pair() {
460     // the second half is pushed last & popped first; it contains exactly nothing
461     Node* halfword = pop();
462     assert(halfword == top(), "");
463     // the long bits are pushed first & popped last:
464     return pop();
465   }
466   void set_pair_local(int i, Node* lval) {
467     // longs are stored in locals as a value/half pair (like doubles)
468     set_local(i+0, lval);
469     set_local(i+1, top());
470   }
471 
472   // Push the node, which may be zero, one, or two words.
473   void push_node(BasicType n_type, Node* n) {
474     int n_size = type2size[n_type];
475     if      (n_size == 1)  push(      n );  // T_INT, ...
476     else if (n_size == 2)  push_pair( n );  // T_DOUBLE, T_LONG
477     else                   { assert(n_size == 0, "must be T_VOID"); }
478   }
479 
480   Node* pop_node(BasicType n_type) {
481     int n_size = type2size[n_type];
482     if      (n_size == 1)  return pop();
483     else if (n_size == 2)  return pop_pair();
484     else                   return nullptr;
485   }
486 
487   Node* control()               const { return map_not_null()->control(); }
488   Node* i_o()                   const { return map_not_null()->i_o(); }
489   Node* returnadr()             const { return map_not_null()->returnadr(); }
490   Node* frameptr()              const { return map_not_null()->frameptr(); }
491   Node* local(uint idx)         const { map_not_null(); return _map->local(      _map->_jvms, idx); }
492   Node* stack(uint idx)         const { map_not_null(); return _map->stack(      _map->_jvms, idx); }
493   Node* argument(uint idx)      const { map_not_null(); return _map->argument(   _map->_jvms, idx); }
494   Node* monitor_box(uint idx)   const { map_not_null(); return _map->monitor_box(_map->_jvms, idx); }
495   Node* monitor_obj(uint idx)   const { map_not_null(); return _map->monitor_obj(_map->_jvms, idx); }
496 
497   void set_control  (Node* c)         { map_not_null()->set_control(c); }
498   void set_i_o      (Node* c)         { map_not_null()->set_i_o(c); }
499   void set_local(uint idx, Node* c)   { map_not_null(); _map->set_local(   _map->_jvms, idx, c); }
500   void set_stack(uint idx, Node* c)   { map_not_null(); _map->set_stack(   _map->_jvms, idx, c); }
501   void set_argument(uint idx, Node* c){ map_not_null(); _map->set_argument(_map->_jvms, idx, c); }
502   void ensure_stack(uint stk_size)    { map_not_null(); _map->ensure_stack(_map->_jvms, stk_size); }
503 
504   // Access unaliased memory
505   Node* memory(uint alias_idx);
506   Node* memory(const TypePtr *tp) { return memory(C->get_alias_index(tp)); }
507   Node* memory(Node* adr) { return memory(_gvn.type(adr)->is_ptr()); }
508 
509   // Access immutable memory
510   Node* immutable_memory() { return C->immutable_memory(); }
511 
512   // Set unaliased memory
513   void set_memory(Node* c, uint alias_idx) { merged_memory()->set_memory_at(alias_idx, c); }
514   void set_memory(Node* c, const TypePtr *tp) { set_memory(c,C->get_alias_index(tp)); }
515   void set_memory(Node* c, Node* adr) { set_memory(c,_gvn.type(adr)->is_ptr()); }
516 
517   // Get the entire memory state (probably a MergeMemNode), and reset it
518   // (The resetting prevents somebody from using the dangling Node pointer.)
519   Node* reset_memory();
520 
521   // Get the entire memory state, asserted to be a MergeMemNode.
522   MergeMemNode* merged_memory() {
523     Node* mem = map_not_null()->memory();
524     assert(mem->is_MergeMem(), "parse memory is always pre-split");
525     return mem->as_MergeMem();
526   }
527 
528   // Set the entire memory state; produce a new MergeMemNode.
529   void set_all_memory(Node* newmem);
530 
531   // Create a memory projection from the call, then set_all_memory.
532   void set_all_memory_call(Node* call, bool separate_io_proj = false);
533 
534   // Create a LoadNode, reading from the parser's memory state.
535   // (Note:  require_atomic_access is useful only with T_LONG.)
536   //
537   // We choose the unordered semantics by default because we have
538   // adapted the `do_put_xxx' and `do_get_xxx' procedures for the case
539   // of volatile fields.
540   Node* make_load(Node* ctl, Node* adr, const Type* t, BasicType bt,
541                   MemNode::MemOrd mo, LoadNode::ControlDependency control_dependency = LoadNode::DependsOnlyOnTest,
542                   bool require_atomic_access = false, bool unaligned = false,
543                   bool mismatched = false, bool unsafe = false, uint8_t barrier_data = 0) {
544     // This version computes alias_index from bottom_type
545     return make_load(ctl, adr, t, bt, adr->bottom_type()->is_ptr(),
546                      mo, control_dependency, require_atomic_access,
547                      unaligned, mismatched, unsafe, barrier_data);
548   }
549   Node* make_load(Node* ctl, Node* adr, const Type* t, BasicType bt, const TypePtr* adr_type,
550                   MemNode::MemOrd mo, LoadNode::ControlDependency control_dependency = LoadNode::DependsOnlyOnTest,
551                   bool require_atomic_access = false, bool unaligned = false,
552                   bool mismatched = false, bool unsafe = false, uint8_t barrier_data = 0) {
553     // This version computes alias_index from an address type
554     assert(adr_type != nullptr, "use other make_load factory");
555     return make_load(ctl, adr, t, bt, C->get_alias_index(adr_type),
556                      mo, control_dependency, require_atomic_access,
557                      unaligned, mismatched, unsafe, barrier_data);
558   }
559   // This is the base version which is given an alias index.
560   Node* make_load(Node* ctl, Node* adr, const Type* t, BasicType bt, int adr_idx,
561                   MemNode::MemOrd mo, LoadNode::ControlDependency control_dependency = LoadNode::DependsOnlyOnTest,
562                   bool require_atomic_access = false, bool unaligned = false,
563                   bool mismatched = false, bool unsafe = false, uint8_t barrier_data = 0);
564 
565   // Create & transform a StoreNode and store the effect into the
566   // parser's memory state.
567   //
568   // We must ensure that stores of object references will be visible
569   // only after the object's initialization. So the clients of this
570   // procedure must indicate that the store requires `release'
571   // semantics, if the stored value is an object reference that might
572   // point to a new object and may become externally visible.
573   Node* store_to_memory(Node* ctl, Node* adr, Node* val, BasicType bt,
574                         const TypePtr* adr_type,
575                         MemNode::MemOrd mo,
576                         bool require_atomic_access = false,
577                         bool unaligned = false,
578                         bool mismatched = false,
579                         bool unsafe = false,
580                         int barrier_data = 0) {
581     // This version computes alias_index from an address type
582     assert(adr_type != nullptr, "use other store_to_memory factory");
583     return store_to_memory(ctl, adr, val, bt,
584                            C->get_alias_index(adr_type),
585                            mo, require_atomic_access,
586                            unaligned, mismatched, unsafe,
587                            barrier_data);
588   }
589   // This is the base version which is given alias index
590   // Return the new StoreXNode
591   Node* store_to_memory(Node* ctl, Node* adr, Node* val, BasicType bt,
592                         int adr_idx,
593                         MemNode::MemOrd,
594                         bool require_atomic_access = false,
595                         bool unaligned = false,
596                         bool mismatched = false,
597                         bool unsafe = false,
598                         int barrier_data = 0);
599 
600   // Perform decorated accesses
601 
602   Node* access_store_at(Node* obj,   // containing obj
603                         Node* adr,   // actual address to store val at
604                         const TypePtr* adr_type,
605                         Node* val,
606                         const Type* val_type,
607                         BasicType bt,
608                         DecoratorSet decorators);
609 
610   Node* access_load_at(Node* obj,   // containing obj
611                        Node* adr,   // actual address to load val at
612                        const TypePtr* adr_type,
613                        const Type* val_type,
614                        BasicType bt,
615                        DecoratorSet decorators);
616 
617   Node* access_load(Node* adr,   // actual address to load val at
618                     const Type* val_type,
619                     BasicType bt,
620                     DecoratorSet decorators);
621 
622   Node* access_atomic_cmpxchg_val_at(Node* obj,
623                                      Node* adr,
624                                      const TypePtr* adr_type,
625                                      int alias_idx,
626                                      Node* expected_val,
627                                      Node* new_val,
628                                      const Type* value_type,
629                                      BasicType bt,
630                                      DecoratorSet decorators);
631 
632   Node* access_atomic_cmpxchg_bool_at(Node* obj,
633                                       Node* adr,
634                                       const TypePtr* adr_type,
635                                       int alias_idx,
636                                       Node* expected_val,
637                                       Node* new_val,
638                                       const Type* value_type,
639                                       BasicType bt,
640                                       DecoratorSet decorators);
641 
642   Node* access_atomic_xchg_at(Node* obj,
643                               Node* adr,
644                               const TypePtr* adr_type,
645                               int alias_idx,
646                               Node* new_val,
647                               const Type* value_type,
648                               BasicType bt,
649                               DecoratorSet decorators);
650 
651   Node* access_atomic_add_at(Node* obj,
652                              Node* adr,
653                              const TypePtr* adr_type,
654                              int alias_idx,
655                              Node* new_val,
656                              const Type* value_type,
657                              BasicType bt,
658                              DecoratorSet decorators);
659 
660   void access_clone(Node* src, Node* dst, Node* size, bool is_array);
661 
662   // Return addressing for an array element.
663   Node* array_element_address(Node* ary, Node* idx, BasicType elembt,
664                               // Optional constraint on the array size:
665                               const TypeInt* sizetype = nullptr,
666                               // Optional control dependency (for example, on range check)
667                               Node* ctrl = nullptr);
668 
669   // Return a load of array element at idx.
670   Node* load_array_element(Node* ary, Node* idx, const TypeAryPtr* arytype, bool set_ctrl);
671 
672   //---------------- Dtrace support --------------------
673   void make_dtrace_method_entry_exit(ciMethod* method, bool is_entry);
674   void make_dtrace_method_entry(ciMethod* method) {
675     make_dtrace_method_entry_exit(method, true);
676   }
677   void make_dtrace_method_exit(ciMethod* method) {
678     make_dtrace_method_entry_exit(method, false);
679   }
680 
681   //--------------- stub generation -------------------
682  public:
683   void gen_stub(address C_function,
684                 const char *name,
685                 int is_fancy_jump,
686                 bool pass_tls,
687                 bool return_pc);
688 
689   //---------- help for generating calls --------------
690 
691   // Do a null check on the receiver as it would happen before the call to
692   // callee (with all arguments still on the stack).
693   Node* null_check_receiver_before_call(ciMethod* callee) {
694     assert(!callee->is_static(), "must be a virtual method");
695     // Callsite signature can be different from actual method being called (i.e _linkTo* sites).
696     // Use callsite signature always.
697     ciMethod* declared_method = method()->get_method_at_bci(bci());
698     const int nargs = declared_method->arg_size();
699     inc_sp(nargs);
700     Node* n = null_check_receiver();
701     dec_sp(nargs);
702     return n;
703   }
704 
705   // Fill in argument edges for the call from argument(0), argument(1), ...
706   // (The next step is to call set_edges_for_java_call.)
707   void  set_arguments_for_java_call(CallJavaNode* call);
708 
709   // Fill in non-argument edges for the call.
710   // Transform the call, and update the basics: control, i_o, memory.
711   // (The next step is usually to call set_results_for_java_call.)
712   void set_edges_for_java_call(CallJavaNode* call,
713                                bool must_throw = false, bool separate_io_proj = false);
714 
715   // Finish up a java call that was started by set_edges_for_java_call.
716   // Call add_exception on any throw arising from the call.
717   // Return the call result (transformed).
718   Node* set_results_for_java_call(CallJavaNode* call, bool separate_io_proj = false, bool deoptimize = false);
719 
720   // Similar to set_edges_for_java_call, but simplified for runtime calls.
721   void  set_predefined_output_for_runtime_call(Node* call) {
722     set_predefined_output_for_runtime_call(call, nullptr, nullptr);
723   }
724   void  set_predefined_output_for_runtime_call(Node* call,
725                                                Node* keep_mem,
726                                                const TypePtr* hook_mem);
727   Node* set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem = nullptr);
728 
729   // Replace the call with the current state of the kit.  Requires
730   // that the call was generated with separate io_projs so that
731   // exceptional control flow can be handled properly.
732   void replace_call(CallNode* call, Node* result, bool do_replaced_nodes = false);
733 
734   // helper functions for statistics
735   void increment_counter(address counter_addr);   // increment a debug counter
736   void increment_counter(Node*   counter_addr);   // increment a debug counter
737 
738   // Bail out to the interpreter right now
739   // The optional klass is the one causing the trap.
740   // The optional reason is debug information written to the compile log.
741   // Optional must_throw is the same as with add_safepoint_edges.
742   Node* uncommon_trap(int trap_request,
743                      ciKlass* klass = nullptr, const char* reason_string = nullptr,
744                      bool must_throw = false, bool keep_exact_action = false);
745 
746   // Shorthand, to avoid saying "Deoptimization::" so many times.
747   Node* uncommon_trap(Deoptimization::DeoptReason reason,
748                      Deoptimization::DeoptAction action,
749                      ciKlass* klass = nullptr, const char* reason_string = nullptr,
750                      bool must_throw = false, bool keep_exact_action = false) {
751     return uncommon_trap(Deoptimization::make_trap_request(reason, action),
752                   klass, reason_string, must_throw, keep_exact_action);
753   }
754 
755   // Bail out to the interpreter and keep exact action (avoid switching to Action_none).
756   Node* uncommon_trap_exact(Deoptimization::DeoptReason reason,
757                            Deoptimization::DeoptAction action,
758                            ciKlass* klass = nullptr, const char* reason_string = nullptr,
759                            bool must_throw = false) {
760     return uncommon_trap(Deoptimization::make_trap_request(reason, action),
761                   klass, reason_string, must_throw, /*keep_exact_action=*/true);
762   }
763 
764   // SP when bytecode needs to be reexecuted.
765   virtual int reexecute_sp() { return sp(); }
766 
767   // Report if there were too many traps at the current method and bci.
768   // Report if a trap was recorded, and/or PerMethodTrapLimit was exceeded.
769   // If there is no MDO at all, report no trap unless told to assume it.
770   bool too_many_traps(Deoptimization::DeoptReason reason) {
771     return C->too_many_traps(method(), bci(), reason);
772   }
773 
774   // Report if there were too many recompiles at the current method and bci.
775   bool too_many_recompiles(Deoptimization::DeoptReason reason) {
776     return C->too_many_recompiles(method(), bci(), reason);
777   }
778 
779   bool too_many_traps_or_recompiles(Deoptimization::DeoptReason reason) {
780       return C->too_many_traps_or_recompiles(method(), bci(), reason);
781   }
782 
783   // Returns the object (if any) which was created the moment before.
784   Node* just_allocated_object(Node* current_control);
785 
786   // Sync Ideal and Graph kits.
787   void sync_kit(IdealKit& ideal);
788   void final_sync(IdealKit& ideal);
789 
790   public:
791   // Helper function to round double arguments before a call
792   void round_double_arguments(ciMethod* dest_method);
793 
794   // rounding for strict float precision conformance
795   Node* precision_rounding(Node* n);
796 
797   // rounding for strict double precision conformance
798   Node* dprecision_rounding(Node* n);
799 
800   // Helper functions for fast/slow path codes
801   Node* opt_iff(Node* region, Node* iff);
802   Node* make_runtime_call(int flags,
803                           const TypeFunc* call_type, address call_addr,
804                           const char* call_name,
805                           const TypePtr* adr_type, // null if no memory effects
806                           Node* parm0 = nullptr, Node* parm1 = nullptr,
807                           Node* parm2 = nullptr, Node* parm3 = nullptr,
808                           Node* parm4 = nullptr, Node* parm5 = nullptr,
809                           Node* parm6 = nullptr, Node* parm7 = nullptr);
810 
811   Node* sign_extend_byte(Node* in);
812   Node* sign_extend_short(Node* in);
813 
814   enum {  // flag values for make_runtime_call
815     RC_NO_FP = 1,               // CallLeafNoFPNode
816     RC_NO_IO = 2,               // do not hook IO edges
817     RC_NO_LEAF = 4,             // CallStaticJavaNode
818     RC_MUST_THROW = 8,          // flag passed to add_safepoint_edges
819     RC_NARROW_MEM = 16,         // input memory is same as output
820     RC_UNCOMMON = 32,           // freq. expected to be like uncommon trap
821     RC_VECTOR = 64,             // CallLeafVectorNode
822     RC_LEAF = 0                 // null value:  no flags set
823   };
824 
825   // merge in all memory slices from new_mem, along the given path
826   void merge_memory(Node* new_mem, Node* region, int new_path);
827   void make_slow_call_ex(Node* call, ciInstanceKlass* ex_klass, bool separate_io_proj, bool deoptimize = false);
828 
829   // Helper functions to build synchronizations
830   int next_monitor();
831   Node* insert_mem_bar(int opcode, Node* precedent = nullptr);
832   Node* insert_mem_bar_volatile(int opcode, int alias_idx, Node* precedent = nullptr);
833   // Optional 'precedent' is appended as an extra edge, to force ordering.
834   FastLockNode* shared_lock(Node* obj);
835   void shared_unlock(Node* box, Node* obj);
836 
837   // helper functions for the fast path/slow path idioms
838   Node* fast_and_slow(Node* in, const Type *result_type, Node* null_result, IfNode* fast_test, Node* fast_result, address slow_call, const TypeFunc *slow_call_type, Node* slow_arg, Klass* ex_klass, Node* slow_result);
839 
840   // Generate an instance-of idiom.  Used by both the instance-of bytecode
841   // and the reflective instance-of call.
842   Node* gen_instanceof(Node *subobj, Node* superkls, bool safe_for_replace = false);
843 
844   // Generate a check-cast idiom.  Used by both the check-cast bytecode
845   // and the array-store bytecode
846   Node* gen_checkcast( Node *subobj, Node* superkls,
847                        Node* *failure_control = nullptr );
848 
849   Node* gen_subtype_check(Node* obj, Node* superklass);
850 
851   // Exact type check used for predicted calls and casts.
852   // Rewrites (*casted_receiver) to be casted to the stronger type.
853   // (Caller is responsible for doing replace_in_map.)
854   Node* type_check_receiver(Node* receiver, ciKlass* klass, float prob,
855                             Node* *casted_receiver);
856 
857   // Inexact type check used for predicted calls.
858   Node* subtype_check_receiver(Node* receiver, ciKlass* klass,
859                                Node** casted_receiver);
860 
861   // implementation of object creation
862   Node* set_output_for_allocation(AllocateNode* alloc,
863                                   const TypeOopPtr* oop_type,
864                                   bool deoptimize_on_exception=false);
865   Node* get_layout_helper(Node* klass_node, jint& constant_value);
866   Node* new_instance(Node* klass_node,
867                      Node* slow_test = nullptr,
868                      Node* *return_size_val = nullptr,
869                      bool deoptimize_on_exception = false);
870   Node* new_array(Node* klass_node, Node* count_val, int nargs,
871                   Node* *return_size_val = nullptr,
872                   bool deoptimize_on_exception = false);
873 
874   // java.lang.String helpers
875   Node* load_String_length(Node* str, bool set_ctrl);
876   Node* load_String_value(Node* str, bool set_ctrl);
877   Node* load_String_coder(Node* str, bool set_ctrl);
878   void store_String_value(Node* str, Node* value);
879   void store_String_coder(Node* str, Node* value);
880   Node* capture_memory(const TypePtr* src_type, const TypePtr* dst_type);
881   Node* compress_string(Node* src, const TypeAryPtr* src_type, Node* dst, Node* count);
882   void inflate_string(Node* src, Node* dst, const TypeAryPtr* dst_type, Node* count);
883   void inflate_string_slow(Node* src, Node* dst, Node* start, Node* count);
884 
885   // Handy for making control flow
886   IfNode* create_and_map_if(Node* ctrl, Node* tst, float prob, float cnt) {
887     IfNode* iff = new IfNode(ctrl, tst, prob, cnt);// New IfNode's
888     _gvn.set_type(iff, iff->Value(&_gvn)); // Value may be known at parse-time
889     // Place 'if' on worklist if it will be in graph
890     if (!tst->is_Con())  record_for_igvn(iff);     // Range-check and Null-check removal is later
891     return iff;
892   }
893 
894   IfNode* create_and_xform_if(Node* ctrl, Node* tst, float prob, float cnt) {
895     IfNode* iff = new IfNode(ctrl, tst, prob, cnt);// New IfNode's
896     _gvn.transform(iff);                           // Value may be known at parse-time
897     // Place 'if' on worklist if it will be in graph
898     if (!tst->is_Con())  record_for_igvn(iff);     // Range-check and Null-check removal is later
899     return iff;
900   }
901 
902   void add_parse_predicates(int nargs = 0);
903   void add_parse_predicate(Deoptimization::DeoptReason reason, int nargs);
904 
905   Node* make_constant_from_field(ciField* field, Node* obj);
906 
907   // Vector API support (implemented in vectorIntrinsics.cpp)
908   Node* box_vector(Node* in, const TypeInstPtr* vbox_type, BasicType elem_bt, int num_elem, bool deoptimize_on_exception = false);
909   Node* unbox_vector(Node* in, const TypeInstPtr* vbox_type, BasicType elem_bt, int num_elem, bool shuffle_to_vector = false);
910   Node* vector_shift_count(Node* cnt, int shift_op, BasicType bt, int num_elem);
911 };
912 
913 // Helper class to support building of control flow branches. Upon
914 // creation the map and sp at bci are cloned and restored upon de-
915 // struction. Typical use:
916 //
917 // { PreserveJVMState pjvms(this);
918 //   // code of new branch
919 // }
920 // // here the JVM state at bci is established
921 
922 class PreserveJVMState: public StackObj {
923  protected:
924   GraphKit*      _kit;
925 #ifdef ASSERT
926   int            _block;  // PO of current block, if a Parse
927   int            _bci;
928 #endif
929   SafePointNode* _map;
930   uint           _sp;
931 
932  public:
933   PreserveJVMState(GraphKit* kit, bool clone_map = true);
934   ~PreserveJVMState();
935 };
936 
937 // Helper class to build cutouts of the form if (p) ; else {x...}.
938 // The code {x...} must not fall through.
939 // The kit's main flow of control is set to the "then" continuation of if(p).
940 class BuildCutout: public PreserveJVMState {
941  public:
942   BuildCutout(GraphKit* kit, Node* p, float prob, float cnt = COUNT_UNKNOWN);
943   ~BuildCutout();
944 };
945 
946 // Helper class to preserve the original _reexecute bit and _sp and restore
947 // them back
948 class PreserveReexecuteState: public StackObj {
949  protected:
950   GraphKit*                 _kit;
951   uint                      _sp;
952   JVMState::ReexecuteState  _reexecute;
953 
954  public:
955   PreserveReexecuteState(GraphKit* kit);
956   ~PreserveReexecuteState();
957 };
958 
959 #endif // SHARE_OPTO_GRAPHKIT_HPP