dependencies.hpp revision 1123:167c2986d91b
1/*
2 * Copyright 2005-2006 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
25//** Dependencies represent assertions (approximate invariants) within
26// the class hierarchy.  An example is an assertion that a given
27// method is not overridden; another example is that a type has only
28// one concrete subtype.  Compiled code which relies on such
29// assertions must be discarded if they are overturned by changes in
30// the class hierarchy.  We can think of these assertions as
31// approximate invariants, because we expect them to be overturned
32// very infrequently.  We are willing to perform expensive recovery
33// operations when they are overturned.  The benefit, of course, is
34// performing optimistic optimizations (!) on the object code.
35//
36// Changes in the class hierarchy due to dynamic linking or
37// class evolution can violate dependencies.  There is enough
38// indexing between classes and nmethods to make dependency
39// checking reasonably efficient.
40
41class ciEnv;
42class nmethod;
43class OopRecorder;
44class xmlStream;
45class CompileLog;
46class DepChange;
47class No_Safepoint_Verifier;
48
49class Dependencies: public ResourceObj {
50 public:
51  // Note: In the comments on dependency types, most uses of the terms
52  // subtype and supertype are used in a "non-strict" or "inclusive"
53  // sense, and are starred to remind the reader of this fact.
54  // Strict uses of the terms use the word "proper".
55  //
56  // Specifically, every class is its own subtype* and supertype*.
57  // (This trick is easier than continually saying things like "Y is a
58  // subtype of X or X itself".)
59  //
60  // Sometimes we write X > Y to mean X is a proper supertype of Y.
61  // The notation X > {Y, Z} means X has proper subtypes Y, Z.
62  // The notation X.m > Y means that Y inherits m from X, while
63  // X.m > Y.m means Y overrides X.m.  A star denotes abstractness,
64  // as *I > A, meaning (abstract) interface I is a super type of A,
65  // or A.*m > B.m, meaning B.m implements abstract method A.m.
66  //
67  // In this module, the terms "subtype" and "supertype" refer to
68  // Java-level reference type conversions, as detected by
69  // "instanceof" and performed by "checkcast" operations.  The method
70  // Klass::is_subtype_of tests these relations.  Note that "subtype"
71  // is richer than "subclass" (as tested by Klass::is_subclass_of),
72  // since it takes account of relations involving interface and array
73  // types.
74  //
75  // To avoid needless complexity, dependencies involving array types
76  // are not accepted.  If you need to make an assertion about an
77  // array type, make the assertion about its corresponding element
78  // types.  Any assertion that might change about an array type can
79  // be converted to an assertion about its element type.
80  //
81  // Most dependencies are evaluated over a "context type" CX, which
82  // stands for the set Subtypes(CX) of every Java type that is a subtype*
83  // of CX.  When the system loads a new class or interface N, it is
84  // responsible for re-evaluating changed dependencies whose context
85  // type now includes N, that is, all super types of N.
86  //
87  enum DepType {
88    end_marker = 0,
89
90    // An 'evol' dependency simply notes that the contents of the
91    // method were used.  If it evolves (is replaced), the nmethod
92    // must be recompiled.  No other dependencies are implied.
93    evol_method,
94    FIRST_TYPE = evol_method,
95
96    // A context type CX is a leaf it if has no proper subtype.
97    leaf_type,
98
99    // An abstract class CX has exactly one concrete subtype CC.
100    abstract_with_unique_concrete_subtype,
101
102    // The type CX is purely abstract, with no concrete subtype* at all.
103    abstract_with_no_concrete_subtype,
104
105    // The concrete CX is free of concrete proper subtypes.
106    concrete_with_no_concrete_subtype,
107
108    // Given a method M1 and a context class CX, the set MM(CX, M1) of
109    // "concrete matching methods" in CX of M1 is the set of every
110    // concrete M2 for which it is possible to create an invokevirtual
111    // or invokeinterface call site that can reach either M1 or M2.
112    // That is, M1 and M2 share a name, signature, and vtable index.
113    // We wish to notice when the set MM(CX, M1) is just {M1}, or
114    // perhaps a set of two {M1,M2}, and issue dependencies on this.
115
116    // The set MM(CX, M1) can be computed by starting with any matching
117    // concrete M2 that is inherited into CX, and then walking the
118    // subtypes* of CX looking for concrete definitions.
119
120    // The parameters to this dependency are the method M1 and the
121    // context class CX.  M1 must be either inherited in CX or defined
122    // in a subtype* of CX.  It asserts that MM(CX, M1) is no greater
123    // than {M1}.
124    unique_concrete_method,       // one unique concrete method under CX
125
126    // An "exclusive" assertion concerns two methods or subtypes, and
127    // declares that there are at most two (or perhaps later N>2)
128    // specific items that jointly satisfy the restriction.
129    // We list all items explicitly rather than just giving their
130    // count, for robustness in the face of complex schema changes.
131
132    // A context class CX (which may be either abstract or concrete)
133    // has two exclusive concrete subtypes* C1, C2 if every concrete
134    // subtype* of CX is either C1 or C2.  Note that if neither C1 or C2
135    // are equal to CX, then CX itself must be abstract.  But it is
136    // also possible (for example) that C1 is CX (a concrete class)
137    // and C2 is a proper subtype of C1.
138    abstract_with_exclusive_concrete_subtypes_2,
139
140    // This dependency asserts that MM(CX, M1) is no greater than {M1,M2}.
141    exclusive_concrete_methods_2,
142
143    // This dependency asserts that no instances of class or it's
144    // subclasses require finalization registration.
145    no_finalizable_subclasses,
146
147    TYPE_LIMIT
148  };
149  enum {
150    LG2_TYPE_LIMIT = 4,  // assert(TYPE_LIMIT <= (1<<LG2_TYPE_LIMIT))
151
152    // handy categorizations of dependency types:
153    all_types      = ((1<<TYPE_LIMIT)-1) & ((-1)<<FIRST_TYPE),
154    non_ctxk_types = (1<<evol_method),
155    ctxk_types     = all_types & ~non_ctxk_types,
156
157    max_arg_count = 3,   // current maximum number of arguments (incl. ctxk)
158
159    // A "context type" is a class or interface that
160    // provides context for evaluating a dependency.
161    // When present, it is one of the arguments (dep_context_arg).
162    //
163    // If a dependency does not have a context type, there is a
164    // default context, depending on the type of the dependency.
165    // This bit signals that a default context has been compressed away.
166    default_context_type_bit = (1<<LG2_TYPE_LIMIT)
167  };
168
169  static const char* dep_name(DepType dept);
170  static int         dep_args(DepType dept);
171  static int  dep_context_arg(DepType dept) {
172    return dept_in_mask(dept, ctxk_types)? 0: -1;
173  }
174
175 private:
176  // State for writing a new set of dependencies:
177  GrowableArray<int>*       _dep_seen;  // (seen[h->ident] & (1<<dept))
178  GrowableArray<ciObject*>* _deps[TYPE_LIMIT];
179
180  static const char* _dep_name[TYPE_LIMIT];
181  static int         _dep_args[TYPE_LIMIT];
182
183  static bool dept_in_mask(DepType dept, int mask) {
184    return (int)dept >= 0 && dept < TYPE_LIMIT && ((1<<dept) & mask) != 0;
185  }
186
187  bool note_dep_seen(int dept, ciObject* x) {
188    assert(dept < BitsPerInt, "oob");
189    int x_id = x->ident();
190    assert(_dep_seen != NULL, "deps must be writable");
191    int seen = _dep_seen->at_grow(x_id, 0);
192    _dep_seen->at_put(x_id, seen | (1<<dept));
193    // return true if we've already seen dept/x
194    return (seen & (1<<dept)) != 0;
195  }
196
197  bool maybe_merge_ctxk(GrowableArray<ciObject*>* deps,
198                        int ctxk_i, ciKlass* ctxk);
199
200  void sort_all_deps();
201  size_t estimate_size_in_bytes();
202
203  // Initialize _deps, etc.
204  void initialize(ciEnv* env);
205
206  // State for making a new set of dependencies:
207  OopRecorder* _oop_recorder;
208
209  // Logging support
210  CompileLog* _log;
211
212  address  _content_bytes;  // everything but the oop references, encoded
213  size_t   _size_in_bytes;
214
215 public:
216  // Make a new empty dependencies set.
217  Dependencies(ciEnv* env) {
218    initialize(env);
219  }
220
221 private:
222  // Check for a valid context type.
223  // Enforce the restriction against array types.
224  static void check_ctxk(ciKlass* ctxk) {
225    assert(ctxk->is_instance_klass(), "java types only");
226  }
227  static void check_ctxk_concrete(ciKlass* ctxk) {
228    assert(is_concrete_klass(ctxk->as_instance_klass()), "must be concrete");
229  }
230  static void check_ctxk_abstract(ciKlass* ctxk) {
231    check_ctxk(ctxk);
232    assert(!is_concrete_klass(ctxk->as_instance_klass()), "must be abstract");
233  }
234
235  void assert_common_1(DepType dept, ciObject* x);
236  void assert_common_2(DepType dept, ciKlass* ctxk, ciObject* x);
237  void assert_common_3(DepType dept, ciKlass* ctxk, ciObject* x, ciObject* x2);
238
239 public:
240  // Adding assertions to a new dependency set at compile time:
241  void assert_evol_method(ciMethod* m);
242  void assert_leaf_type(ciKlass* ctxk);
243  void assert_abstract_with_unique_concrete_subtype(ciKlass* ctxk, ciKlass* conck);
244  void assert_abstract_with_no_concrete_subtype(ciKlass* ctxk);
245  void assert_concrete_with_no_concrete_subtype(ciKlass* ctxk);
246  void assert_unique_concrete_method(ciKlass* ctxk, ciMethod* uniqm);
247  void assert_abstract_with_exclusive_concrete_subtypes(ciKlass* ctxk, ciKlass* k1, ciKlass* k2);
248  void assert_exclusive_concrete_methods(ciKlass* ctxk, ciMethod* m1, ciMethod* m2);
249  void assert_has_no_finalizable_subclasses(ciKlass* ctxk);
250
251  // Define whether a given method or type is concrete.
252  // These methods define the term "concrete" as used in this module.
253  // For this module, an "abstract" class is one which is non-concrete.
254  //
255  // Future optimizations may allow some classes to remain
256  // non-concrete until their first instantiation, and allow some
257  // methods to remain non-concrete until their first invocation.
258  // In that case, there would be a middle ground between concrete
259  // and abstract (as defined by the Java language and VM).
260  static bool is_concrete_klass(klassOop k);    // k is instantiable
261  static bool is_concrete_method(methodOop m);  // m is invocable
262  static Klass* find_finalizable_subclass(Klass* k);
263
264  // These versions of the concreteness queries work through the CI.
265  // The CI versions are allowed to skew sometimes from the VM
266  // (oop-based) versions.  The cost of such a difference is a
267  // (safely) aborted compilation, or a deoptimization, or a missed
268  // optimization opportunity.
269  //
270  // In order to prevent spurious assertions, query results must
271  // remain stable within any single ciEnv instance.  (I.e., they must
272  // not go back into the VM to get their value; they must cache the
273  // bit in the CI, either eagerly or lazily.)
274  static bool is_concrete_klass(ciInstanceKlass* k); // k appears instantiable
275  static bool is_concrete_method(ciMethod* m);       // m appears invocable
276  static bool has_finalizable_subclass(ciInstanceKlass* k);
277
278  // As a general rule, it is OK to compile under the assumption that
279  // a given type or method is concrete, even if it at some future
280  // point becomes abstract.  So dependency checking is one-sided, in
281  // that it permits supposedly concrete classes or methods to turn up
282  // as really abstract.  (This shouldn't happen, except during class
283  // evolution, but that's the logic of the checking.)  However, if a
284  // supposedly abstract class or method suddenly becomes concrete, a
285  // dependency on it must fail.
286
287  // Checking old assertions at run-time (in the VM only):
288  static klassOop check_evol_method(methodOop m);
289  static klassOop check_leaf_type(klassOop ctxk);
290  static klassOop check_abstract_with_unique_concrete_subtype(klassOop ctxk, klassOop conck,
291                                                              DepChange* changes = NULL);
292  static klassOop check_abstract_with_no_concrete_subtype(klassOop ctxk,
293                                                          DepChange* changes = NULL);
294  static klassOop check_concrete_with_no_concrete_subtype(klassOop ctxk,
295                                                          DepChange* changes = NULL);
296  static klassOop check_unique_concrete_method(klassOop ctxk, methodOop uniqm,
297                                               DepChange* changes = NULL);
298  static klassOop check_abstract_with_exclusive_concrete_subtypes(klassOop ctxk, klassOop k1, klassOop k2,
299                                                                  DepChange* changes = NULL);
300  static klassOop check_exclusive_concrete_methods(klassOop ctxk, methodOop m1, methodOop m2,
301                                                   DepChange* changes = NULL);
302  static klassOop check_has_no_finalizable_subclasses(klassOop ctxk,
303                                                      DepChange* changes = NULL);
304  // A returned klassOop is NULL if the dependency assertion is still
305  // valid.  A non-NULL klassOop is a 'witness' to the assertion
306  // failure, a point in the class hierarchy where the assertion has
307  // been proven false.  For example, if check_leaf_type returns
308  // non-NULL, the value is a subtype of the supposed leaf type.  This
309  // witness value may be useful for logging the dependency failure.
310  // Note that, when a dependency fails, there may be several possible
311  // witnesses to the failure.  The value returned from the check_foo
312  // method is chosen arbitrarily.
313
314  // The 'changes' value, if non-null, requests a limited spot-check
315  // near the indicated recent changes in the class hierarchy.
316  // It is used by DepStream::spot_check_dependency_at.
317
318  // Detecting possible new assertions:
319  static klassOop  find_unique_concrete_subtype(klassOop ctxk);
320  static methodOop find_unique_concrete_method(klassOop ctxk, methodOop m);
321  static int       find_exclusive_concrete_subtypes(klassOop ctxk, int klen, klassOop k[]);
322  static int       find_exclusive_concrete_methods(klassOop ctxk, int mlen, methodOop m[]);
323
324  // Create the encoding which will be stored in an nmethod.
325  void encode_content_bytes();
326
327  address content_bytes() {
328    assert(_content_bytes != NULL, "encode it first");
329    return _content_bytes;
330  }
331  size_t size_in_bytes() {
332    assert(_content_bytes != NULL, "encode it first");
333    return _size_in_bytes;
334  }
335
336  OopRecorder* oop_recorder() { return _oop_recorder; }
337  CompileLog*  log()          { return _log; }
338
339  void copy_to(nmethod* nm);
340
341  void log_all_dependencies();
342  void log_dependency(DepType dept, int nargs, ciObject* args[]) {
343    write_dependency_to(log(), dept, nargs, args);
344  }
345  void log_dependency(DepType dept,
346                      ciObject* x0,
347                      ciObject* x1 = NULL,
348                      ciObject* x2 = NULL) {
349    if (log() == NULL)  return;
350    ciObject* args[max_arg_count];
351    args[0] = x0;
352    args[1] = x1;
353    args[2] = x2;
354    assert(2 < max_arg_count, "");
355    log_dependency(dept, dep_args(dept), args);
356  }
357
358  static void write_dependency_to(CompileLog* log,
359                                  DepType dept,
360                                  int nargs, ciObject* args[],
361                                  klassOop witness = NULL);
362  static void write_dependency_to(CompileLog* log,
363                                  DepType dept,
364                                  int nargs, oop args[],
365                                  klassOop witness = NULL);
366  static void write_dependency_to(xmlStream* xtty,
367                                  DepType dept,
368                                  int nargs, oop args[],
369                                  klassOop witness = NULL);
370  static void print_dependency(DepType dept,
371                               int nargs, oop args[],
372                               klassOop witness = NULL);
373
374 private:
375  // helper for encoding common context types as zero:
376  static ciKlass* ctxk_encoded_as_null(DepType dept, ciObject* x);
377
378  static klassOop ctxk_encoded_as_null(DepType dept, oop x);
379
380 public:
381  // Use this to iterate over an nmethod's dependency set.
382  // Works on new and old dependency sets.
383  // Usage:
384  //
385  // ;
386  // Dependencies::DepType dept;
387  // for (Dependencies::DepStream deps(nm); deps.next(); ) {
388  //   ...
389  // }
390  //
391  // The caller must be in the VM, since oops are not wrapped in handles.
392  class DepStream {
393  private:
394    nmethod*              _code;   // null if in a compiler thread
395    Dependencies*         _deps;   // null if not in a compiler thread
396    CompressedReadStream  _bytes;
397#ifdef ASSERT
398    size_t                _byte_limit;
399#endif
400
401    // iteration variables:
402    DepType               _type;
403    int                   _xi[max_arg_count+1];
404
405    void initial_asserts(size_t byte_limit) NOT_DEBUG({});
406
407    inline oop recorded_oop_at(int i);
408        // => _code? _code->oop_at(i): *_deps->_oop_recorder->handle_at(i)
409
410    klassOop check_dependency_impl(DepChange* changes);
411
412  public:
413    DepStream(Dependencies* deps)
414      : _deps(deps),
415        _code(NULL),
416        _bytes(deps->content_bytes())
417    {
418      initial_asserts(deps->size_in_bytes());
419    }
420    DepStream(nmethod* code)
421      : _deps(NULL),
422        _code(code),
423        _bytes(code->dependencies_begin())
424    {
425      initial_asserts(code->dependencies_size());
426    }
427
428    bool next();
429
430    DepType type()               { return _type; }
431    int argument_count()         { return dep_args(type()); }
432    int argument_index(int i)    { assert(0 <= i && i < argument_count(), "oob");
433                                   return _xi[i]; }
434    oop argument(int i);         // => recorded_oop_at(argument_index(i))
435    klassOop context_type();
436
437    methodOop method_argument(int i) {
438      oop x = argument(i);
439      assert(x->is_method(), "type");
440      return (methodOop) x;
441    }
442    klassOop type_argument(int i) {
443      oop x = argument(i);
444      assert(x->is_klass(), "type");
445      return (klassOop) x;
446    }
447
448    // The point of the whole exercise:  Is this dep is still OK?
449    klassOop check_dependency() {
450      return check_dependency_impl(NULL);
451    }
452    // A lighter version:  Checks only around recent changes in a class
453    // hierarchy.  (See Universe::flush_dependents_on.)
454    klassOop spot_check_dependency_at(DepChange& changes);
455
456    // Log the current dependency to xtty or compilation log.
457    void log_dependency(klassOop witness = NULL);
458
459    // Print the current dependency to tty.
460    void print_dependency(klassOop witness = NULL, bool verbose = false);
461  };
462  friend class Dependencies::DepStream;
463
464  static void print_statistics() PRODUCT_RETURN;
465};
466
467// A class hierarchy change coming through the VM (under the Compile_lock).
468// The change is structured as a single new type with any number of supers
469// and implemented interface types.  Other than the new type, any of the
470// super types can be context types for a relevant dependency, which the
471// new type could invalidate.
472class DepChange : public StackObj {
473 public:
474  enum ChangeType {
475    NO_CHANGE = 0,              // an uninvolved klass
476    Change_new_type,            // a newly loaded type
477    Change_new_sub,             // a super with a new subtype
478    Change_new_impl,            // an interface with a new implementation
479    CHANGE_LIMIT,
480    Start_Klass = CHANGE_LIMIT  // internal indicator for ContextStream
481  };
482
483 private:
484  // each change set is rooted in exactly one new type (at present):
485  KlassHandle _new_type;
486
487  void initialize();
488
489 public:
490  // notes the new type, marks it and all its super-types
491  DepChange(KlassHandle new_type)
492    : _new_type(new_type)
493  {
494    initialize();
495  }
496
497  // cleans up the marks
498  ~DepChange();
499
500  klassOop new_type()                   { return _new_type(); }
501
502  // involves_context(k) is true if k is new_type or any of the super types
503  bool involves_context(klassOop k);
504
505  // Usage:
506  // for (DepChange::ContextStream str(changes); str.next(); ) {
507  //   klassOop k = str.klass();
508  //   switch (str.change_type()) {
509  //     ...
510  //   }
511  // }
512  class ContextStream : public StackObj {
513   private:
514    DepChange&  _changes;
515    friend class DepChange;
516
517    // iteration variables:
518    ChangeType  _change_type;
519    klassOop    _klass;
520    objArrayOop _ti_base;    // i.e., transitive_interfaces
521    int         _ti_index;
522    int         _ti_limit;
523
524    // start at the beginning:
525    void start() {
526      klassOop new_type = _changes.new_type();
527      _change_type = (new_type == NULL ? NO_CHANGE: Start_Klass);
528      _klass = new_type;
529      _ti_base = NULL;
530      _ti_index = 0;
531      _ti_limit = 0;
532    }
533
534   public:
535    ContextStream(DepChange& changes)
536      : _changes(changes)
537    { start(); }
538
539    ContextStream(DepChange& changes, No_Safepoint_Verifier& nsv)
540      : _changes(changes)
541      // the nsv argument makes it safe to hold oops like _klass
542    { start(); }
543
544    bool next();
545
546    ChangeType change_type()     { return _change_type; }
547    klassOop   klass()           { return _klass; }
548  };
549  friend class DepChange::ContextStream;
550
551  void print();
552};
553