parse.hpp revision 196:d1605aabd0a1
1/*
2 * Copyright 1997-2008 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
20 * CA 95054 USA or visit www.sun.com if you need additional information or
21 * have any questions.
22 *
23 */
24
25class BytecodeParseHistogram;
26class InlineTree;
27class Parse;
28class SwitchRange;
29
30
31//------------------------------InlineTree-------------------------------------
32class InlineTree : public ResourceObj {
33  Compile*    C;                  // cache
34  JVMState*   _caller_jvms;       // state of caller
35  ciMethod*   _method;            // method being called by the caller_jvms
36  InlineTree* _caller_tree;
37  uint        _count_inline_bcs;  // Accumulated count of inlined bytecodes
38  // Call-site count / interpreter invocation count, scaled recursively.
39  // Always between 0.0 and 1.0.  Represents the percentage of the method's
40  // total execution time used at this call site.
41  const float _site_invoke_ratio;
42  float compute_callee_frequency( int caller_bci ) const;
43
44  GrowableArray<InlineTree*> _subtrees;
45  friend class Compile;
46
47protected:
48  InlineTree(Compile* C,
49             const InlineTree* caller_tree,
50             ciMethod* callee_method,
51             JVMState* caller_jvms,
52             int caller_bci,
53             float site_invoke_ratio);
54  InlineTree *build_inline_tree_for_callee(ciMethod* callee_method,
55                                           JVMState* caller_jvms,
56                                           int caller_bci);
57  const char* try_to_inline(ciMethod* callee_method, ciMethod* caller_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result);
58  const char* shouldInline(ciMethod* callee_method, ciMethod* caller_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result) const;
59  const char* shouldNotInline(ciMethod* callee_method, ciMethod* caller_method, WarmCallInfo* wci_result) const;
60  void        print_inlining(ciMethod *callee_method, int caller_bci, const char *failure_msg) const PRODUCT_RETURN;
61
62  InlineTree *caller_tree()       const { return _caller_tree;  }
63  InlineTree* callee_at(int bci, ciMethod* m) const;
64  int         inline_depth()      const { return _caller_jvms ? _caller_jvms->depth() : 0; }
65
66public:
67  static InlineTree* build_inline_tree_root();
68  static InlineTree* find_subtree_from_root(InlineTree* root, JVMState* jvms, ciMethod* callee, bool create_if_not_found = false);
69
70  // For temporary (stack-allocated, stateless) ilts:
71  InlineTree(Compile* c, ciMethod* callee_method, JVMState* caller_jvms, float site_invoke_ratio);
72
73  // InlineTree enum
74  enum InlineStyle {
75    Inline_do_not_inline             =   0, //
76    Inline_cha_is_monomorphic        =   1, //
77    Inline_type_profile_monomorphic  =   2  //
78  };
79
80  // See if it is OK to inline.
81  // The reciever is the inline tree for the caller.
82  //
83  // The result is a temperature indication.  If it is hot or cold,
84  // inlining is immediate or undesirable.  Otherwise, the info block
85  // returned is newly allocated and may be enqueued.
86  //
87  // If the method is inlinable, a new inline subtree is created on the fly,
88  // and may be accessed by find_subtree_from_root.
89  // The call_method is the dest_method for a special or static invocation.
90  // The call_method is an optimized virtual method candidate otherwise.
91  WarmCallInfo* ok_to_inline(ciMethod *call_method, JVMState* caller_jvms, ciCallProfile& profile, WarmCallInfo* wci);
92
93  // Information about inlined method
94  JVMState*   caller_jvms()       const { return _caller_jvms; }
95  ciMethod   *method()            const { return _method; }
96  int         caller_bci()        const { return _caller_jvms ? _caller_jvms->bci() : InvocationEntryBci; }
97  uint        count_inline_bcs()  const { return _count_inline_bcs; }
98  float       site_invoke_ratio() const { return _site_invoke_ratio; };
99
100#ifndef PRODUCT
101private:
102  uint        _count_inlines;     // Count of inlined methods
103public:
104  // Debug information collected during parse
105  uint        count_inlines()     const { return _count_inlines; };
106#endif
107  GrowableArray<InlineTree*> subtrees() { return _subtrees; }
108};
109
110
111//-----------------------------------------------------------------------------
112//------------------------------Parse------------------------------------------
113// Parse bytecodes, build a Graph
114class Parse : public GraphKit {
115 public:
116  // Per-block information needed by the parser:
117  class Block {
118   private:
119    ciTypeFlow::Block* _flow;
120    int                _pred_count;     // how many predecessors in CFG?
121    int                _preds_parsed;   // how many of these have been parsed?
122    uint               _count;          // how many times executed?  Currently only set by _goto's
123    bool               _is_parsed;      // has this block been parsed yet?
124    bool               _is_handler;     // is this block an exception handler?
125    SafePointNode*     _start_map;      // all values flowing into this block
126    MethodLivenessResult _live_locals;  // lazily initialized liveness bitmap
127
128    int                _num_successors; // Includes only normal control flow.
129    int                _all_successors; // Include exception paths also.
130    Block**            _successors;
131
132    // Use init_node/init_graph to initialize Blocks.
133    // Block() : _live_locals((uintptr_t*)NULL,0) { ShouldNotReachHere(); }
134    Block() : _live_locals(NULL,0) { ShouldNotReachHere(); }
135
136   public:
137
138    // Set up the block data structure itself.
139    void init_node(Parse* outer, int po);
140    // Set up the block's relations to other blocks.
141    void init_graph(Parse* outer);
142
143    ciTypeFlow::Block* flow() const        { return _flow; }
144    int pred_count() const                 { return _pred_count; }
145    int preds_parsed() const               { return _preds_parsed; }
146    bool is_parsed() const                 { return _is_parsed; }
147    bool is_handler() const                { return _is_handler; }
148    void set_count( uint x )               { _count = x; }
149    uint count() const                     { return _count; }
150
151    SafePointNode* start_map() const       { assert(is_merged(),"");   return _start_map; }
152    void set_start_map(SafePointNode* m)   { assert(!is_merged(), ""); _start_map = m; }
153
154    // True after any predecessor flows control into this block
155    bool is_merged() const                 { return _start_map != NULL; }
156
157    // True when all non-exception predecessors have been parsed.
158    bool is_ready() const                  { return preds_parsed() == pred_count(); }
159
160    int num_successors() const             { return _num_successors; }
161    int all_successors() const             { return _all_successors; }
162    Block* successor_at(int i) const {
163      assert((uint)i < (uint)all_successors(), "");
164      return _successors[i];
165    }
166    Block* successor_for_bci(int bci);
167
168    int start() const                      { return flow()->start(); }
169    int limit() const                      { return flow()->limit(); }
170    int pre_order() const                  { return flow()->pre_order(); }
171    int start_sp() const                   { return flow()->stack_size(); }
172
173    const Type* peek(int off=0) const      { return stack_type_at(start_sp() - (off+1)); }
174
175    const Type* stack_type_at(int i) const;
176    const Type* local_type_at(int i) const;
177    static const Type* get_type(ciType* t) { return Type::get_typeflow_type(t); }
178
179    bool has_trap_at(int bci) const        { return flow()->has_trap() && flow()->trap_bci() == bci; }
180
181    // Call this just before parsing a block.
182    void mark_parsed() {
183      assert(!_is_parsed, "must parse each block exactly once");
184      _is_parsed = true;
185    }
186
187    // Return the phi/region input index for the "current" pred,
188    // and bump the pred number.  For historical reasons these index
189    // numbers are handed out in descending order.  The last index is
190    // always PhiNode::Input (i.e., 1).  The value returned is known
191    // as a "path number" because it distinguishes by which path we are
192    // entering the block.
193    int next_path_num() {
194      assert(preds_parsed() < pred_count(), "too many preds?");
195      return pred_count() - _preds_parsed++;
196    }
197
198    // Add a previously unaccounted predecessor to this block.
199    // This operates by increasing the size of the block's region
200    // and all its phi nodes (if any).  The value returned is a
201    // path number ("pnum").
202    int add_new_path();
203
204    // Initialize me by recording the parser's map.  My own map must be NULL.
205    void record_state(Parse* outer);
206  };
207
208#ifndef PRODUCT
209  // BytecodeParseHistogram collects number of bytecodes parsed, nodes constructed, and transformations.
210  class BytecodeParseHistogram : public ResourceObj {
211   private:
212    enum BPHType {
213      BPH_transforms,
214      BPH_values
215    };
216    static bool _initialized;
217    static uint _bytecodes_parsed [Bytecodes::number_of_codes];
218    static uint _nodes_constructed[Bytecodes::number_of_codes];
219    static uint _nodes_transformed[Bytecodes::number_of_codes];
220    static uint _new_values       [Bytecodes::number_of_codes];
221
222    Bytecodes::Code _initial_bytecode;
223    int             _initial_node_count;
224    int             _initial_transforms;
225    int             _initial_values;
226
227    Parse     *_parser;
228    Compile   *_compiler;
229
230    // Initialization
231    static void reset();
232
233    // Return info being collected, select with global flag 'BytecodeParseInfo'
234    int current_count(BPHType info_selector);
235
236   public:
237    BytecodeParseHistogram(Parse *p, Compile *c);
238    static bool initialized();
239
240    // Record info when starting to parse one bytecode
241    void set_initial_state( Bytecodes::Code bc );
242    // Record results of parsing one bytecode
243    void record_change();
244
245    // Profile printing
246    static void print(float cutoff = 0.01F); // cutoff in percent
247  };
248
249  public:
250    // Record work done during parsing
251    BytecodeParseHistogram* _parse_histogram;
252    void set_parse_histogram(BytecodeParseHistogram *bph) { _parse_histogram = bph; }
253    BytecodeParseHistogram* parse_histogram()      { return _parse_histogram; }
254#endif
255
256 private:
257  friend class Block;
258
259  // Variables which characterize this compilation as a whole:
260
261  JVMState*     _caller;        // JVMS which carries incoming args & state.
262  float         _expected_uses; // expected number of calls to this code
263  float         _prof_factor;   // discount applied to my profile counts
264  int           _depth;         // Inline tree depth, for debug printouts
265  const TypeFunc*_tf;           // My kind of function type
266  int           _entry_bci;     // the osr bci or InvocationEntryBci
267
268  ciTypeFlow*   _flow;          // Results of previous flow pass.
269  Block*        _blocks;        // Array of basic-block structs.
270  int           _block_count;   // Number of elements in _blocks.
271
272  GraphKit      _exits;         // Record all normal returns and throws here.
273  bool          _wrote_final;   // Did we write a final field?
274  bool          _count_invocations; // update and test invocation counter
275  bool          _method_data_update; // update method data oop
276
277  // Variables which track Java semantics during bytecode parsing:
278
279  Block*            _block;     // block currently getting parsed
280  ciBytecodeStream  _iter;      // stream of this method's bytecodes
281
282  int           _blocks_merged; // Progress meter: state merges from BB preds
283  int           _blocks_parsed; // Progress meter: BBs actually parsed
284
285  const FastLockNode* _synch_lock; // FastLockNode for synchronized method
286
287#ifndef PRODUCT
288  int _max_switch_depth;        // Debugging SwitchRanges.
289  int _est_switch_depth;        // Debugging SwitchRanges.
290#endif
291
292 public:
293  // Constructor
294  Parse(JVMState* caller, ciMethod* parse_method, float expected_uses);
295
296  virtual Parse* is_Parse() const { return (Parse*)this; }
297
298 public:
299  // Accessors.
300  JVMState*     caller()        const { return _caller; }
301  float         expected_uses() const { return _expected_uses; }
302  float         prof_factor()   const { return _prof_factor; }
303  int           depth()         const { return _depth; }
304  const TypeFunc* tf()          const { return _tf; }
305  //            entry_bci()     -- see osr_bci, etc.
306
307  ciTypeFlow*   flow()          const { return _flow; }
308  //            blocks()        -- see pre_order_at, start_block, etc.
309  int           block_count()   const { return _block_count; }
310
311  GraphKit&     exits()               { return _exits; }
312  bool          wrote_final() const   { return _wrote_final; }
313  void      set_wrote_final(bool z)   { _wrote_final = z; }
314  bool          count_invocations() const  { return _count_invocations; }
315  bool          method_data_update() const { return _method_data_update; }
316
317  Block*             block()    const { return _block; }
318  ciBytecodeStream&  iter()           { return _iter; }
319  Bytecodes::Code    bc()       const { return _iter.cur_bc(); }
320
321  void set_block(Block* b)            { _block = b; }
322
323  // Derived accessors:
324  bool is_normal_parse() const  { return _entry_bci == InvocationEntryBci; }
325  bool is_osr_parse() const     { return _entry_bci != InvocationEntryBci; }
326  int osr_bci() const           { assert(is_osr_parse(),""); return _entry_bci; }
327
328  void set_parse_bci(int bci);
329
330  // Must this parse be aborted?
331  bool failing()                { return C->failing(); }
332
333  Block* pre_order_at(int po) {
334    assert(0 <= po && po < _block_count, "oob");
335    return &_blocks[po];
336  }
337  Block* start_block() {
338    return pre_order_at(flow()->start_block()->pre_order());
339  }
340  // Can return NULL if the flow pass did not complete a block.
341  Block* successor_for_bci(int bci) {
342    return block()->successor_for_bci(bci);
343  }
344
345 private:
346  // Create a JVMS & map for the initial state of this method.
347  SafePointNode* create_entry_map();
348
349  // OSR helpers
350  Node *fetch_interpreter_state(int index, BasicType bt, Node *local_addrs, Node *local_addrs_base);
351  Node* check_interpreter_type(Node* l, const Type* type, SafePointNode* &bad_type_exit);
352  void  load_interpreter_state(Node* osr_buf);
353
354  // Functions for managing basic blocks:
355  void init_blocks();
356  void load_state_from(Block* b);
357  void store_state_to(Block* b) { b->record_state(this); }
358
359  // Parse all the basic blocks.
360  void do_all_blocks();
361
362  // Helper for do_all_blocks; makes one pass in pre-order.
363  void visit_blocks();
364
365  // Parse the current basic block
366  void do_one_block();
367
368  // Raise an error if we get a bad ciTypeFlow CFG.
369  void handle_missing_successor(int bci);
370
371  // first actions (before BCI 0)
372  void do_method_entry();
373
374  // implementation of monitorenter/monitorexit
375  void do_monitor_enter();
376  void do_monitor_exit();
377
378  // Eagerly create phie throughout the state, to cope with back edges.
379  void ensure_phis_everywhere();
380
381  // Merge the current mapping into the basic block starting at bci
382  void merge(          int target_bci);
383  // Same as plain merge, except that it allocates a new path number.
384  void merge_new_path( int target_bci);
385  // Merge the current mapping into an exception handler.
386  void merge_exception(int target_bci);
387  // Helper: Merge the current mapping into the given basic block
388  void merge_common(Block* target, int pnum);
389  // Helper functions for merging individual cells.
390  PhiNode *ensure_phi(       int idx, bool nocreate = false);
391  PhiNode *ensure_memory_phi(int idx, bool nocreate = false);
392  // Helper to merge the current memory state into the given basic block
393  void merge_memory_edges(MergeMemNode* n, int pnum, bool nophi);
394
395  // Parse this bytecode, and alter the Parsers JVM->Node mapping
396  void do_one_bytecode();
397
398  // helper function to generate array store check
399  void array_store_check();
400  // Helper function to generate array load
401  void array_load(BasicType etype);
402  // Helper function to generate array store
403  void array_store(BasicType etype);
404  // Helper function to compute array addressing
405  Node* array_addressing(BasicType type, int vals, const Type* *result2=NULL);
406
407  // Pass current map to exits
408  void return_current(Node* value);
409
410  // Register finalizers on return from Object.<init>
411  void call_register_finalizer();
412
413  // Insert a compiler safepoint into the graph
414  void add_safepoint();
415
416  // Insert a compiler safepoint into the graph, if there is a back-branch.
417  void maybe_add_safepoint(int target_bci) {
418    if (UseLoopSafepoints && target_bci <= bci()) {
419      add_safepoint();
420    }
421  }
422
423  // Note:  Intrinsic generation routines may be found in library_call.cpp.
424
425  // Helper function to setup Ideal Call nodes
426  void do_call();
427
428  // Helper function to uncommon-trap or bailout for non-compilable call-sites
429  bool can_not_compile_call_site(ciMethod *dest_method, ciInstanceKlass *klass);
430
431  // Helper function to identify inlining potential at call-site
432  ciMethod* optimize_inlining(ciMethod* caller, int bci, ciInstanceKlass* klass,
433                              ciMethod *dest_method, const TypeOopPtr* receiver_type);
434
435  // Helper function to setup for type-profile based inlining
436  bool prepare_type_profile_inline(ciInstanceKlass* prof_klass, ciMethod* prof_method);
437
438  // Helper functions for type checking bytecodes:
439  void  do_checkcast();
440  void  do_instanceof();
441
442  // Helper functions for shifting & arithmetic
443  void modf();
444  void modd();
445  void l2f();
446
447  void do_irem();
448
449  // implementation of _get* and _put* bytecodes
450  void do_getstatic() { do_field_access(true,  false); }
451  void do_getfield () { do_field_access(true,  true); }
452  void do_putstatic() { do_field_access(false, false); }
453  void do_putfield () { do_field_access(false, true); }
454
455  // common code for making initial checks and forming addresses
456  void do_field_access(bool is_get, bool is_field);
457  bool static_field_ok_in_clinit(ciField *field, ciMethod *method);
458
459  // common code for actually performing the load or store
460  void do_get_xxx(const TypePtr* obj_type, Node* obj, ciField* field, bool is_field);
461  void do_put_xxx(const TypePtr* obj_type, Node* obj, ciField* field, bool is_field);
462
463  // loading from a constant field or the constant pool
464  // returns false if push failed (non-perm field constants only, not ldcs)
465  bool push_constant(ciConstant con);
466
467  // implementation of object creation bytecodes
468  void do_new();
469  void do_newarray(BasicType elemtype);
470  void do_anewarray();
471  void do_multianewarray();
472  Node* expand_multianewarray(ciArrayKlass* array_klass, Node* *lengths, int ndimensions);
473
474  // implementation of jsr/ret
475  void do_jsr();
476  void do_ret();
477
478  float   dynamic_branch_prediction(float &cnt);
479  float   branch_prediction(float &cnt, BoolTest::mask btest, int target_bci);
480  bool    seems_never_taken(float prob);
481
482  void    do_ifnull(BoolTest::mask btest);
483  void    do_if(BoolTest::mask btest, Node* c);
484  void    repush_if_args();
485  void    adjust_map_after_if(BoolTest::mask btest, Node* c, float prob,
486                              Block* path, Block* other_path);
487  IfNode* jump_if_fork_int(Node* a, Node* b, BoolTest::mask mask);
488  Node*   jump_if_join(Node* iffalse, Node* iftrue);
489  void    jump_if_true_fork(IfNode *ifNode, int dest_bci_if_true, int prof_table_index);
490  void    jump_if_false_fork(IfNode *ifNode, int dest_bci_if_false, int prof_table_index);
491  void    jump_if_always_fork(int dest_bci_if_true, int prof_table_index);
492
493  friend class SwitchRange;
494  void    do_tableswitch();
495  void    do_lookupswitch();
496  void    jump_switch_ranges(Node* a, SwitchRange* lo, SwitchRange* hi, int depth = 0);
497  bool    create_jump_tables(Node* a, SwitchRange* lo, SwitchRange* hi);
498
499  // helper functions for methodData style profiling
500  void test_counter_against_threshold(Node* cnt, int limit);
501  void increment_and_test_invocation_counter(int limit);
502  void test_for_osr_md_counter_at(ciMethodData* md, ciProfileData* data, ByteSize offset, int limit);
503  Node* method_data_addressing(ciMethodData* md, ciProfileData* data, ByteSize offset, Node* idx = NULL, uint stride = 0);
504  void increment_md_counter_at(ciMethodData* md, ciProfileData* data, ByteSize offset, Node* idx = NULL, uint stride = 0);
505  void set_md_flag_at(ciMethodData* md, ciProfileData* data, int flag_constant);
506
507  void profile_method_entry();
508  void profile_taken_branch(int target_bci, bool force_update = false);
509  void profile_not_taken_branch(bool force_update = false);
510  void profile_call(Node* receiver);
511  void profile_generic_call();
512  void profile_receiver_type(Node* receiver);
513  void profile_ret(int target_bci);
514  void profile_null_checkcast();
515  void profile_switch_case(int table_index);
516
517  // helper function for call statistics
518  void count_compiled_calls(bool at_method_entry, bool is_inline) PRODUCT_RETURN;
519
520  Node_Notes* make_node_notes(Node_Notes* caller_nn);
521
522  // Helper functions for handling normal and abnormal exits.
523  void build_exits();
524
525  // Fix up all exceptional control flow exiting a single bytecode.
526  void do_exceptions();
527
528  // Fix up all exiting control flow at the end of the parse.
529  void do_exits();
530
531  // Add Catch/CatchProjs
532  // The call is either a Java call or the VM's rethrow stub
533  void catch_call_exceptions(ciExceptionHandlerStream&);
534
535  // Handle all exceptions thrown by the inlined method.
536  // Also handles exceptions for individual bytecodes.
537  void catch_inline_exceptions(SafePointNode* ex_map);
538
539  // Bytecode classifier, helps decide to use uncommon_trap vs. rethrow_C.
540  bool can_rerun_bytecode();
541
542  // Merge the given map into correct exceptional exit state.
543  // Assumes that there is no applicable local handler.
544  void throw_to_exit(SafePointNode* ex_map);
545
546 public:
547#ifndef PRODUCT
548  // Handle PrintOpto, etc.
549  void show_parse_info();
550  void dump_map_adr_mem() const;
551  static void print_statistics(); // Print some performance counters
552  void dump();
553  void dump_bci(int bci);
554#endif
555};
556