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