1 /*
2  * Copyright (c) 1997, 2020, 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_MATCHER_HPP
26 #define SHARE_OPTO_MATCHER_HPP
27 
28 #include "libadt/vectset.hpp"
29 #include "memory/resourceArea.hpp"
30 #include "opto/node.hpp"
31 #include "opto/phaseX.hpp"
32 #include "opto/regmask.hpp"
33 
34 class Compile;
35 class Node;
36 class MachNode;
37 class MachTypeNode;
38 class MachOper;
39 
40 //---------------------------Matcher-------------------------------------------
41 class Matcher : public PhaseTransform {
42   friend class VMStructs;
43 
44 public:
45 
46   // State and MStack class used in xform() and find_shared() iterative methods.
47   enum Node_State { Pre_Visit,  // node has to be pre-visited
48                     Visit,  // visit node
49                     Post_Visit,  // post-visit node
50                     Alt_Post_Visit   // alternative post-visit path
51   };
52 
53   class MStack: public Node_Stack {
54   public:
MStack(int size)55     MStack(int size) : Node_Stack(size) { }
56 
push(Node * n,Node_State ns)57     void push(Node *n, Node_State ns) {
58       Node_Stack::push(n, (uint)ns);
59     }
push(Node * n,Node_State ns,Node * parent,int indx)60     void push(Node *n, Node_State ns, Node *parent, int indx) {
61       ++_inode_top;
62       if ((_inode_top + 1) >= _inode_max) grow();
63       _inode_top->node = parent;
64       _inode_top->indx = (uint)indx;
65       ++_inode_top;
66       _inode_top->node = n;
67       _inode_top->indx = (uint)ns;
68     }
parent()69     Node *parent() {
70       pop();
71       return node();
72     }
state() const73     Node_State state() const {
74       return (Node_State)index();
75     }
set_state(Node_State ns)76     void set_state(Node_State ns) {
77       set_index((uint)ns);
78     }
79   };
80 
81 private:
82   // Private arena of State objects
83   ResourceArea _states_arena;
84 
85   VectorSet   _visited;         // Visit bits
86 
87   // Used to control the Label pass
88   VectorSet   _shared;          // Shared Ideal Node
89   VectorSet   _dontcare;        // Nothing the matcher cares about
90 
91   // Private methods which perform the actual matching and reduction
92   // Walks the label tree, generating machine nodes
93   MachNode *ReduceInst( State *s, int rule, Node *&mem);
94   void ReduceInst_Chain_Rule( State *s, int rule, Node *&mem, MachNode *mach);
95   uint ReduceInst_Interior(State *s, int rule, Node *&mem, MachNode *mach, uint num_opnds);
96   void ReduceOper( State *s, int newrule, Node *&mem, MachNode *mach );
97 
98   // If this node already matched using "rule", return the MachNode for it.
99   MachNode* find_shared_node(Node* n, uint rule);
100 
101   // Convert a dense opcode number to an expanded rule number
102   const int *_reduceOp;
103   const int *_leftOp;
104   const int *_rightOp;
105 
106   // Map dense opcode number to info on when rule is swallowed constant.
107   const bool *_swallowed;
108 
109   // Map dense rule number to determine if this is an instruction chain rule
110   const uint _begin_inst_chain_rule;
111   const uint _end_inst_chain_rule;
112 
113   // We want to clone constants and possible CmpI-variants.
114   // If we do not clone CmpI, then we can have many instances of
115   // condition codes alive at once.  This is OK on some chips and
116   // bad on others.  Hence the machine-dependent table lookup.
117   const char *_must_clone;
118 
119   // Find shared Nodes, or Nodes that otherwise are Matcher roots
120   void find_shared( Node *n );
121   bool find_shared_visit(MStack& mstack, Node* n, uint opcode, bool& mem_op, int& mem_addr_idx);
122   void find_shared_post_visit(Node* n, uint opcode);
123 
124   bool is_vshift_con_pattern(Node *n, Node *m);
125 
126   // Debug and profile information for nodes in old space:
127   GrowableArray<Node_Notes*>* _old_node_note_array;
128 
129   // Node labeling iterator for instruction selection
130   Node* Label_Root(const Node* n, State* svec, Node* control, Node*& mem);
131 
132   Node *transform( Node *dummy );
133 
134   Node_List _projection_list;        // For Machine nodes killing many values
135 
136   Node_Array _shared_nodes;
137 
138   debug_only(Node_Array _old2new_map;)   // Map roots of ideal-trees to machine-roots
debug_only(Node_Array _new2old_map;)139   debug_only(Node_Array _new2old_map;)   // Maps machine nodes back to ideal
140 
141   // Accessors for the inherited field PhaseTransform::_nodes:
142   void   grow_new_node_array(uint idx_limit) {
143     _nodes.map(idx_limit-1, NULL);
144   }
has_new_node(const Node * n) const145   bool    has_new_node(const Node* n) const {
146     return _nodes.at(n->_idx) != NULL;
147   }
new_node(const Node * n) const148   Node*       new_node(const Node* n) const {
149     assert(has_new_node(n), "set before get");
150     return _nodes.at(n->_idx);
151   }
set_new_node(const Node * n,Node * nn)152   void    set_new_node(const Node* n, Node *nn) {
153     assert(!has_new_node(n), "set only once");
154     _nodes.map(n->_idx, nn);
155   }
156 
157 #ifdef ASSERT
158   // Make sure only new nodes are reachable from this node
159   void verify_new_nodes_only(Node* root);
160 
161   Node* _mem_node;   // Ideal memory node consumed by mach node
162 #endif
163 
164   // Mach node for ConP #NULL
165   MachNode* _mach_null;
166 
167   void handle_precedence_edges(Node* n, MachNode *mach);
168 
169 public:
170   int LabelRootDepth;
171   // Convert ideal machine register to a register mask for spill-loads
172   static const RegMask *idealreg2regmask[];
173   RegMask *idealreg2spillmask  [_last_machine_leaf];
174   RegMask *idealreg2debugmask  [_last_machine_leaf];
175   RegMask *idealreg2mhdebugmask[_last_machine_leaf];
176   void init_spill_mask( Node *ret );
177   // Convert machine register number to register mask
178   static uint mreg2regmask_max;
179   static RegMask mreg2regmask[];
180   static RegMask STACK_ONLY_mask;
181   static RegMask caller_save_regmask;
182   static RegMask caller_save_regmask_exclude_soe;
183   static RegMask mh_caller_save_regmask;
184   static RegMask mh_caller_save_regmask_exclude_soe;
185 
mach_null() const186   MachNode* mach_null() const { return _mach_null; }
187 
is_shared(Node * n)188   bool    is_shared( Node *n ) { return _shared.test(n->_idx) != 0; }
set_shared(Node * n)189   void   set_shared( Node *n ) {  _shared.set(n->_idx); }
is_visited(Node * n)190   bool   is_visited( Node *n ) { return _visited.test(n->_idx) != 0; }
set_visited(Node * n)191   void  set_visited( Node *n ) { _visited.set(n->_idx); }
is_dontcare(Node * n)192   bool  is_dontcare( Node *n ) { return _dontcare.test(n->_idx) != 0; }
set_dontcare(Node * n)193   void set_dontcare( Node *n ) {  _dontcare.set(n->_idx); }
194 
195   // Mode bit to tell DFA and expand rules whether we are running after
196   // (or during) register selection.  Usually, the matcher runs before,
197   // but it will also get called to generate post-allocation spill code.
198   // In this situation, it is a deadly error to attempt to allocate more
199   // temporary registers.
200   bool _allocation_started;
201 
202   // Machine register names
203   static const char *regName[];
204   // Machine register encodings
205   static const unsigned char _regEncode[];
206   // Machine Node names
207   const char **_ruleName;
208   // Rules that are cheaper to rematerialize than to spill
209   static const uint _begin_rematerialize;
210   static const uint _end_rematerialize;
211 
212   // An array of chars, from 0 to _last_Mach_Reg.
213   // No Save       = 'N' (for register windows)
214   // Save on Entry = 'E'
215   // Save on Call  = 'C'
216   // Always Save   = 'A' (same as SOE + SOC)
217   const char *_register_save_policy;
218   const char *_c_reg_save_policy;
219   // Convert a machine register to a machine register type, so-as to
220   // properly match spill code.
221   const int *_register_save_type;
222   // Maps from machine register to boolean; true if machine register can
223   // be holding a call argument in some signature.
224   static bool can_be_java_arg( int reg );
225   // Maps from machine register to boolean; true if machine register holds
226   // a spillable argument.
227   static bool is_spillable_arg( int reg );
228 
229   // List of IfFalse or IfTrue Nodes that indicate a taken null test.
230   // List is valid in the post-matching space.
231   Node_List _null_check_tests;
232   void collect_null_checks( Node *proj, Node *orig_proj );
233   void validate_null_checks( );
234 
235   Matcher();
236 
237   // Get a projection node at position pos
get_projection(uint pos)238   Node* get_projection(uint pos) {
239     return _projection_list[pos];
240   }
241 
242   // Push a projection node onto the projection list
push_projection(Node * node)243   void push_projection(Node* node) {
244     _projection_list.push(node);
245   }
246 
pop_projection()247   Node* pop_projection() {
248     return _projection_list.pop();
249   }
250 
251   // Number of nodes in the projection list
number_of_projections() const252   uint number_of_projections() const {
253     return _projection_list.size();
254   }
255 
256   // Select instructions for entire method
257   void match();
258 
259   // Helper for match
260   OptoReg::Name warp_incoming_stk_arg( VMReg reg );
261 
262   // Transform, then walk.  Does implicit DCE while walking.
263   // Name changed from "transform" to avoid it being virtual.
264   Node *xform( Node *old_space_node, int Nodes );
265 
266   // Match a single Ideal Node - turn it into a 1-Node tree; Label & Reduce.
267   MachNode *match_tree( const Node *n );
268   MachNode *match_sfpt( SafePointNode *sfpt );
269   // Helper for match_sfpt
270   OptoReg::Name warp_outgoing_stk_arg( VMReg reg, OptoReg::Name begin_out_arg_area, OptoReg::Name &out_arg_limit_per_call );
271 
272   // Initialize first stack mask and related masks.
273   void init_first_stack_mask();
274 
275   // If we should save-on-entry this register
276   bool is_save_on_entry( int reg );
277 
278   // Fixup the save-on-entry registers
279   void Fixup_Save_On_Entry( );
280 
281   // --- Frame handling ---
282 
283   // Register number of the stack slot corresponding to the incoming SP.
284   // Per the Big Picture in the AD file, it is:
285   //   SharedInfo::stack0 + locks + in_preserve_stack_slots + pad2.
286   OptoReg::Name _old_SP;
287 
288   // Register number of the stack slot corresponding to the highest incoming
289   // argument on the stack.  Per the Big Picture in the AD file, it is:
290   //   _old_SP + out_preserve_stack_slots + incoming argument size.
291   OptoReg::Name _in_arg_limit;
292 
293   // Register number of the stack slot corresponding to the new SP.
294   // Per the Big Picture in the AD file, it is:
295   //   _in_arg_limit + pad0
296   OptoReg::Name _new_SP;
297 
298   // Register number of the stack slot corresponding to the highest outgoing
299   // argument on the stack.  Per the Big Picture in the AD file, it is:
300   //   _new_SP + max outgoing arguments of all calls
301   OptoReg::Name _out_arg_limit;
302 
303   OptoRegPair *_parm_regs;        // Array of machine registers per argument
304   RegMask *_calling_convention_mask; // Array of RegMasks per argument
305 
306   // Does matcher have a match rule for this ideal node?
307   static const bool has_match_rule(int opcode);
308   static const bool _hasMatchRule[_last_opcode];
309 
310   // Does matcher have a match rule for this ideal node and is the
311   // predicate (if there is one) true?
312   // NOTE: If this function is used more commonly in the future, ADLC
313   // should generate this one.
314   static const bool match_rule_supported(int opcode);
315 
316   // identify extra cases that we might want to provide match rules for
317   // e.g. Op_ vector nodes and other intrinsics while guarding with vlen
318   static const bool match_rule_supported_vector(int opcode, int vlen, BasicType bt);
319 
320   // Some microarchitectures have mask registers used on vectors
321   static const bool has_predicated_vectors(void);
322 
323   // Some uarchs have different sized float register resources
324   static const int float_pressure(int default_pressure_threshold);
325 
326   // Used to determine if we have fast l2f conversion
327   // USII has it, USIII doesn't
328   static const bool convL2FSupported(void);
329 
330   // Vector width in bytes
331   static const int vector_width_in_bytes(BasicType bt);
332 
333   // Limits on vector size (number of elements).
334   static const int max_vector_size(const BasicType bt);
335   static const int min_vector_size(const BasicType bt);
vector_size_supported(const BasicType bt,int size)336   static const bool vector_size_supported(const BasicType bt, int size) {
337     return (Matcher::max_vector_size(bt) >= size &&
338             Matcher::min_vector_size(bt) <= size);
339   }
340 
341   static const bool supports_scalable_vector();
342   // Actual max scalable vector register length.
343   static const int scalable_vector_reg_size(const BasicType bt);
344 
345   // Vector ideal reg
346   static const uint vector_ideal_reg(int len);
347 
348   // Does the CPU supports vector variable shift instructions?
349   static bool supports_vector_variable_shifts(void);
350 
351   // Does the CPU supports vector vairable rotate instructions?
352   static bool supports_vector_variable_rotates(void);
353 
354   // CPU supports misaligned vectors store/load.
355   static const bool misaligned_vectors_ok();
356 
357   // Used to determine a "low complexity" 64-bit constant.  (Zero is simple.)
358   // The standard of comparison is one (StoreL ConL) vs. two (StoreI ConI).
359   // Depends on the details of 64-bit constant generation on the CPU.
360   static const bool isSimpleConstant64(jlong con);
361 
362   // These calls are all generated by the ADLC
363 
364   // Java-Java calling convention
365   // (what you use when Java calls Java)
366 
367   // Alignment of stack in bytes, standard Intel word alignment is 4.
368   // Sparc probably wants at least double-word (8).
369   static uint stack_alignment_in_bytes();
370   // Alignment of stack, measured in stack slots.
371   // The size of stack slots is defined by VMRegImpl::stack_slot_size.
stack_alignment_in_slots()372   static uint stack_alignment_in_slots() {
373     return stack_alignment_in_bytes() / (VMRegImpl::stack_slot_size);
374   }
375 
376   // Convert a sig into a calling convention register layout
377   // and find interesting things about it.
378   static OptoReg::Name  find_receiver();
379   // Return address register.  On Intel it is a stack-slot.  On PowerPC
380   // it is the Link register.  On Sparc it is r31?
381   virtual OptoReg::Name return_addr() const;
382   RegMask              _return_addr_mask;
383   // Return value register.  On Intel it is EAX.
384   static OptoRegPair   return_value(uint ideal_reg);
385   static OptoRegPair c_return_value(uint ideal_reg);
386   RegMask                     _return_value_mask;
387   // Inline Cache Register
388   static OptoReg::Name  inline_cache_reg();
389   static int            inline_cache_reg_encode();
390 
391   // Register for DIVI projection of divmodI
392   static RegMask divI_proj_mask();
393   // Register for MODI projection of divmodI
394   static RegMask modI_proj_mask();
395 
396   // Register for DIVL projection of divmodL
397   static RegMask divL_proj_mask();
398   // Register for MODL projection of divmodL
399   static RegMask modL_proj_mask();
400 
401   // Use hardware DIV instruction when it is faster than
402   // a code which use multiply for division by constant.
403   static bool use_asm_for_ldiv_by_con( jlong divisor );
404 
405   static const RegMask method_handle_invoke_SP_save_mask();
406 
407   // Java-Interpreter calling convention
408   // (what you use when calling between compiled-Java and Interpreted-Java
409 
410   // Number of callee-save + always-save registers
411   // Ignores frame pointer and "special" registers
412   static int  number_of_saved_registers();
413 
414   // The Method-klass-holder may be passed in the inline_cache_reg
415   // and then expanded into the inline_cache_reg and a method_ptr register
416 
417   // Interpreter's Frame Pointer Register
418   static OptoReg::Name  interpreter_frame_pointer_reg();
419 
420   // Java-Native calling convention
421   // (what you use when intercalling between Java and C++ code)
422 
423   // Frame pointer. The frame pointer is kept at the base of the stack
424   // and so is probably the stack pointer for most machines.  On Intel
425   // it is ESP.  On the PowerPC it is R1.  On Sparc it is SP.
426   OptoReg::Name  c_frame_pointer() const;
427   static RegMask c_frame_ptr_mask;
428 
429   // Is this branch offset small enough to be addressed by a short branch?
430   bool is_short_branch_offset(int rule, int br_size, int offset);
431 
432   // Optional scaling for the parameter to the ClearArray/CopyArray node.
433   static const bool init_array_count_is_in_bytes;
434 
435   // Some hardware needs 2 CMOV's for longs.
436   static const int long_cmove_cost();
437 
438   // Some hardware have expensive CMOV for float and double.
439   static const int float_cmove_cost();
440 
441   // Should the input 'm' of node 'n' be cloned during matching?
442   // Reports back whether the node was cloned or not.
443   bool    clone_node(Node* n, Node* m, Matcher::MStack& mstack);
444   bool pd_clone_node(Node* n, Node* m, Matcher::MStack& mstack);
445 
446   // Should the Matcher clone shifts on addressing modes, expecting them to
447   // be subsumed into complex addressing expressions or compute them into
448   // registers?  True for Intel but false for most RISCs
449   bool pd_clone_address_expressions(AddPNode* m, MStack& mstack, VectorSet& address_visited);
450   // Clone base + offset address expression
451   bool clone_base_plus_offset_address(AddPNode* m, MStack& mstack, VectorSet& address_visited);
452 
453   static bool narrow_oop_use_complex_address();
454   static bool narrow_klass_use_complex_address();
455 
456   static bool const_oop_prefer_decode();
457   static bool const_klass_prefer_decode();
458 
459   // Generate implicit null check for narrow oops if it can fold
460   // into address expression (x64).
461   //
462   // [R12 + narrow_oop_reg<<3 + offset] // fold into address expression
463   // NullCheck narrow_oop_reg
464   //
465   // When narrow oops can't fold into address expression (Sparc) and
466   // base is not null use decode_not_null and normal implicit null check.
467   // Note, decode_not_null node can be used here since it is referenced
468   // only on non null path but it requires special handling, see
469   // collect_null_checks():
470   //
471   // decode_not_null narrow_oop_reg, oop_reg // 'shift' and 'add base'
472   // [oop_reg + offset]
473   // NullCheck oop_reg
474   //
475   // With Zero base and when narrow oops can not fold into address
476   // expression use normal implicit null check since only shift
477   // is needed to decode narrow oop.
478   //
479   // decode narrow_oop_reg, oop_reg // only 'shift'
480   // [oop_reg + offset]
481   // NullCheck oop_reg
482   //
483   static bool gen_narrow_oop_implicit_null_checks();
484 
485   // Is it better to copy float constants, or load them directly from memory?
486   // Intel can load a float constant from a direct address, requiring no
487   // extra registers.  Most RISCs will have to materialize an address into a
488   // register first, so they may as well materialize the constant immediately.
489   static const bool rematerialize_float_constants;
490 
491   // If CPU can load and store mis-aligned doubles directly then no fixup is
492   // needed.  Else we split the double into 2 integer pieces and move it
493   // piece-by-piece.  Only happens when passing doubles into C code or when
494   // calling i2c adapters as the Java calling convention forces doubles to be
495   // aligned.
496   static const bool misaligned_doubles_ok;
497 
498   // Does the CPU require postalloc expand (see block.cpp for description of
499   // postalloc expand)?
500   static const bool require_postalloc_expand;
501 
502   // Does the platform support generic vector operands?
503   // Requires cleanup after selection phase.
504   static const bool supports_generic_vector_operands;
505 
506  private:
507   void do_postselect_cleanup();
508 
509   void specialize_generic_vector_operands();
510   void specialize_mach_node(MachNode* m);
511   void specialize_temp_node(MachTempNode* tmp, MachNode* use, uint idx);
512   MachOper* specialize_vector_operand(MachNode* m, uint opnd_idx);
513 
514   static MachOper* pd_specialize_generic_vector_operand(MachOper* generic_opnd, uint ideal_reg, bool is_temp);
515   static bool is_generic_reg2reg_move(MachNode* m);
516   static bool is_generic_vector(MachOper* opnd);
517 
518   const RegMask* regmask_for_ideal_register(uint ideal_reg, Node* ret);
519 
520   // Graph verification code
521   DEBUG_ONLY( bool verify_after_postselect_cleanup(); )
522 
523  public:
524   // Advertise here if the CPU requires explicit rounding operations to implement strictfp mode.
525   static const bool strict_fp_requires_explicit_rounding;
526 
527   // Are floats conerted to double when stored to stack during deoptimization?
528   static bool float_in_double();
529   // Do ints take an entire long register or just half?
530   static const bool int_in_long;
531 
532   // Do the processor's shift instructions only use the low 5/6 bits
533   // of the count for 32/64 bit ints? If not we need to do the masking
534   // ourselves.
535   static const bool need_masked_shift_count;
536 
537   // Whether code generation need accurate ConvI2L types.
538   static const bool convi2l_type_required;
539 
540   // This routine is run whenever a graph fails to match.
541   // If it returns, the compiler should bailout to interpreter without error.
542   // In non-product mode, SoftMatchFailure is false to detect non-canonical
543   // graphs.  Print a message and exit.
soft_match_failure()544   static void soft_match_failure() {
545     if( SoftMatchFailure ) return;
546     else { fatal("SoftMatchFailure is not allowed except in product"); }
547   }
548 
549   // Check for a following volatile memory barrier without an
550   // intervening load and thus we don't need a barrier here.  We
551   // retain the Node to act as a compiler ordering barrier.
552   static bool post_store_load_barrier(const Node* mb);
553 
554   // Does n lead to an uncommon trap that can cause deoptimization?
555   static bool branches_to_uncommon_trap(const Node *n);
556 
557 #ifdef ASSERT
558   void dump_old2new_map();      // machine-independent to machine-dependent
559 
find_old_node(Node * new_node)560   Node* find_old_node(Node* new_node) {
561     return _new2old_map[new_node->_idx];
562   }
563 #endif
564 };
565 
566 #endif // SHARE_OPTO_MATCHER_HPP
567