1 /*
   2  * Copyright (c) 2005, 2019, 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_CODE_DEPENDENCIES_HPP
  26 #define SHARE_CODE_DEPENDENCIES_HPP
  27 
  28 #include "ci/ciCallSite.hpp"
  29 #include "ci/ciKlass.hpp"
  30 #include "ci/ciMethod.hpp"
  31 #include "ci/ciMethodHandle.hpp"
  32 #include "classfile/systemDictionary.hpp"
  33 #include "code/compressedStream.hpp"
  34 #include "code/nmethod.hpp"
  35 #include "memory/resourceArea.hpp"
  36 #include "runtime/safepointVerifiers.hpp"
  37 #include "utilities/growableArray.hpp"
  38 #include "utilities/hashtable.hpp"
  39 
  40 //** Dependencies represent assertions (approximate invariants) within
  41 // the runtime system, e.g. class hierarchy changes.  An example is an
  42 // assertion that a given method is not overridden; another example is
  43 // that a type has only one concrete subtype.  Compiled code which
  44 // relies on such assertions must be discarded if they are overturned
  45 // by changes in the runtime system.  We can think of these assertions
  46 // as approximate invariants, because we expect them to be overturned
  47 // very infrequently.  We are willing to perform expensive recovery
  48 // operations when they are overturned.  The benefit, of course, is
  49 // performing optimistic optimizations (!) on the object code.
  50 //
  51 // Changes in the class hierarchy due to dynamic linking or
  52 // class evolution can violate dependencies.  There is enough
  53 // indexing between classes and nmethods to make dependency
  54 // checking reasonably efficient.
  55 
  56 class ciEnv;
  57 class nmethod;
  58 class OopRecorder;
  59 class xmlStream;
  60 class CompileLog;
  61 class DepChange;
  62 class   KlassDepChange;
  63 class   CallSiteDepChange;
  64 class NoSafepointVerifier;
  65 
  66 class Dependencies: public ResourceObj {
  67  public:
  68   // Note: In the comments on dependency types, most uses of the terms
  69   // subtype and supertype are used in a "non-strict" or "inclusive"
  70   // sense, and are starred to remind the reader of this fact.
  71   // Strict uses of the terms use the word "proper".
  72   //
  73   // Specifically, every class is its own subtype* and supertype*.
  74   // (This trick is easier than continually saying things like "Y is a
  75   // subtype of X or X itself".)
  76   //
  77   // Sometimes we write X > Y to mean X is a proper supertype of Y.
  78   // The notation X > {Y, Z} means X has proper subtypes Y, Z.
  79   // The notation X.m > Y means that Y inherits m from X, while
  80   // X.m > Y.m means Y overrides X.m.  A star denotes abstractness,
  81   // as *I > A, meaning (abstract) interface I is a super type of A,
  82   // or A.*m > B.m, meaning B.m implements abstract method A.m.
  83   //
  84   // In this module, the terms "subtype" and "supertype" refer to
  85   // Java-level reference type conversions, as detected by
  86   // "instanceof" and performed by "checkcast" operations.  The method
  87   // Klass::is_subtype_of tests these relations.  Note that "subtype"
  88   // is richer than "subclass" (as tested by Klass::is_subclass_of),
  89   // since it takes account of relations involving interface and array
  90   // types.
  91   //
  92   // To avoid needless complexity, dependencies involving array types
  93   // are not accepted.  If you need to make an assertion about an
  94   // array type, make the assertion about its corresponding element
  95   // types.  Any assertion that might change about an array type can
  96   // be converted to an assertion about its element type.
  97   //
  98   // Most dependencies are evaluated over a "context type" CX, which
  99   // stands for the set Subtypes(CX) of every Java type that is a subtype*
 100   // of CX.  When the system loads a new class or interface N, it is
 101   // responsible for re-evaluating changed dependencies whose context
 102   // type now includes N, that is, all super types of N.
 103   //
 104   enum DepType {
 105     end_marker = 0,
 106 
 107     // An 'evol' dependency simply notes that the contents of the
 108     // method were used.  If it evolves (is replaced), the nmethod
 109     // must be recompiled.  No other dependencies are implied.
 110     evol_method,
 111     FIRST_TYPE = evol_method,
 112 
 113     // A context type CX is a leaf it if has no proper subtype.
 114     leaf_type,
 115 
 116     // An abstract class CX has exactly one concrete subtype CC.
 117     abstract_with_unique_concrete_subtype,
 118 
 119     // The type CX is purely abstract, with no concrete subtype* at all.
 120     abstract_with_no_concrete_subtype,
 121 
 122     // The concrete CX is free of concrete proper subtypes.
 123     concrete_with_no_concrete_subtype,
 124 
 125     // Given a method M1 and a context class CX, the set MM(CX, M1) of
 126     // "concrete matching methods" in CX of M1 is the set of every
 127     // concrete M2 for which it is possible to create an invokevirtual
 128     // or invokeinterface call site that can reach either M1 or M2.
 129     // That is, M1 and M2 share a name, signature, and vtable index.
 130     // We wish to notice when the set MM(CX, M1) is just {M1}, or
 131     // perhaps a set of two {M1,M2}, and issue dependencies on this.
 132 
 133     // The set MM(CX, M1) can be computed by starting with any matching
 134     // concrete M2 that is inherited into CX, and then walking the
 135     // subtypes* of CX looking for concrete definitions.
 136 
 137     // The parameters to this dependency are the method M1 and the
 138     // context class CX.  M1 must be either inherited in CX or defined
 139     // in a subtype* of CX.  It asserts that MM(CX, M1) is no greater
 140     // than {M1}.
 141     unique_concrete_method,       // one unique concrete method under CX
 142 
 143     // An "exclusive" assertion concerns two methods or subtypes, and
 144     // declares that there are at most two (or perhaps later N>2)
 145     // specific items that jointly satisfy the restriction.
 146     // We list all items explicitly rather than just giving their
 147     // count, for robustness in the face of complex schema changes.
 148 
 149     // A context class CX (which may be either abstract or concrete)
 150     // has two exclusive concrete subtypes* C1, C2 if every concrete
 151     // subtype* of CX is either C1 or C2.  Note that if neither C1 or C2
 152     // are equal to CX, then CX itself must be abstract.  But it is
 153     // also possible (for example) that C1 is CX (a concrete class)
 154     // and C2 is a proper subtype of C1.
 155     abstract_with_exclusive_concrete_subtypes_2,
 156 
 157     // This dependency asserts that MM(CX, M1) is no greater than {M1,M2}.
 158     exclusive_concrete_methods_2,
 159 
 160     // This dependency asserts that no instances of class or it's
 161     // subclasses require finalization registration.
 162     no_finalizable_subclasses,
 163 
 164     // This dependency asserts when the CallSite.target value changed.
 165     call_site_target_value,
 166 
 167     TYPE_LIMIT
 168   };
 169   enum {
 170     LG2_TYPE_LIMIT = 4,  // assert(TYPE_LIMIT <= (1<<LG2_TYPE_LIMIT))
 171 
 172     // handy categorizations of dependency types:
 173     all_types           = ((1 << TYPE_LIMIT) - 1) & ((~0u) << FIRST_TYPE),
 174 
 175     non_klass_types     = (1 << call_site_target_value),
 176     klass_types         = all_types & ~non_klass_types,
 177 
 178     non_ctxk_types      = (1 << evol_method) | (1 << call_site_target_value),
 179     implicit_ctxk_types = 0,
 180     explicit_ctxk_types = all_types & ~(non_ctxk_types | implicit_ctxk_types),
 181 
 182     max_arg_count = 3,   // current maximum number of arguments (incl. ctxk)
 183 
 184     // A "context type" is a class or interface that
 185     // provides context for evaluating a dependency.
 186     // When present, it is one of the arguments (dep_context_arg).
 187     //
 188     // If a dependency does not have a context type, there is a
 189     // default context, depending on the type of the dependency.
 190     // This bit signals that a default context has been compressed away.
 191     default_context_type_bit = (1<<LG2_TYPE_LIMIT)
 192   };
 193 
 194   static const char* dep_name(DepType dept);
 195   static int         dep_args(DepType dept);
 196 
 197   static bool is_klass_type(           DepType dept) { return dept_in_mask(dept, klass_types        ); }
 198 
 199   static bool has_explicit_context_arg(DepType dept) { return dept_in_mask(dept, explicit_ctxk_types); }
 200   static bool has_implicit_context_arg(DepType dept) { return dept_in_mask(dept, implicit_ctxk_types); }
 201 
 202   static int           dep_context_arg(DepType dept) { return has_explicit_context_arg(dept) ? 0 : -1; }
 203   static int  dep_implicit_context_arg(DepType dept) { return has_implicit_context_arg(dept) ? 0 : -1; }
 204 
 205   static void check_valid_dependency_type(DepType dept);
 206 
 207 #if INCLUDE_JVMCI
 208   // A Metadata* or object value recorded in an OopRecorder
 209   class DepValue {
 210    private:
 211     // Unique identifier of the value within the associated OopRecorder that
 212     // encodes both the category of the value (0: invalid, positive: metadata, negative: object)
 213     // and the index within a category specific array (metadata: index + 1, object: -(index + 1))
 214     int _id;
 215 
 216    public:
 217     DepValue() : _id(0) {}
 218     DepValue(OopRecorder* rec, Metadata* metadata, DepValue* candidate = NULL) {
 219       assert(candidate == NULL || candidate->is_metadata(), "oops");
 220       if (candidate != NULL && candidate->as_metadata(rec) == metadata) {
 221         _id = candidate->_id;
 222       } else {
 223         _id = rec->find_index(metadata) + 1;
 224       }
 225     }
 226     DepValue(OopRecorder* rec, jobject obj, DepValue* candidate = NULL) {
 227       assert(candidate == NULL || candidate->is_object(), "oops");
 228       if (candidate != NULL && candidate->as_object(rec) == obj) {
 229         _id = candidate->_id;
 230       } else {
 231         _id = -(rec->find_index(obj) + 1);
 232       }
 233     }
 234 
 235     // Used to sort values in ascending order of index() with metadata values preceding object values
 236     int sort_key() const { return -_id; }
 237 
 238     bool operator == (const DepValue& other) const   { return other._id == _id; }
 239 
 240     bool is_valid() const             { return _id != 0; }
 241     int  index() const                { assert(is_valid(), "oops"); return _id < 0 ? -(_id + 1) : _id - 1; }
 242     bool is_metadata() const          { assert(is_valid(), "oops"); return _id > 0; }
 243     bool is_object() const            { assert(is_valid(), "oops"); return _id < 0; }
 244 
 245     Metadata*  as_metadata(OopRecorder* rec) const    { assert(is_metadata(), "oops"); return rec->metadata_at(index()); }
 246     Klass*     as_klass(OopRecorder* rec) const {
 247       Metadata* m = as_metadata(rec);
 248       assert(m != NULL, "as_metadata returned NULL");
 249       assert(m->is_klass(), "oops");
 250       return (Klass*) m;
 251     }
 252     Method*    as_method(OopRecorder* rec) const {
 253       Metadata* m = as_metadata(rec);
 254       assert(m != NULL, "as_metadata returned NULL");
 255       assert(m->is_method(), "oops");
 256       return (Method*) m;
 257     }
 258     jobject    as_object(OopRecorder* rec) const      { assert(is_object(), "oops"); return rec->oop_at(index()); }
 259   };
 260 #endif // INCLUDE_JVMCI
 261 
 262  private:
 263   // State for writing a new set of dependencies:
 264   GrowableArray<int>*       _dep_seen;  // (seen[h->ident] & (1<<dept))
 265   GrowableArray<ciBaseObject*>*  _deps[TYPE_LIMIT];
 266 #if INCLUDE_JVMCI
 267   bool _using_dep_values;
 268   GrowableArray<DepValue>*  _dep_values[TYPE_LIMIT];
 269 #endif
 270 
 271   static const char* _dep_name[TYPE_LIMIT];
 272   static int         _dep_args[TYPE_LIMIT];
 273 
 274   static bool dept_in_mask(DepType dept, int mask) {
 275     return (int)dept >= 0 && dept < TYPE_LIMIT && ((1<<dept) & mask) != 0;
 276   }
 277 
 278   bool note_dep_seen(int dept, ciBaseObject* x) {
 279     assert(dept < BitsPerInt, "oob");
 280     int x_id = x->ident();
 281     assert(_dep_seen != NULL, "deps must be writable");
 282     int seen = _dep_seen->at_grow(x_id, 0);
 283     _dep_seen->at_put(x_id, seen | (1<<dept));
 284     // return true if we've already seen dept/x
 285     return (seen & (1<<dept)) != 0;
 286   }
 287 
 288 #if INCLUDE_JVMCI
 289   bool note_dep_seen(int dept, DepValue x) {
 290     assert(dept < BitsPerInt, "oops");
 291     // place metadata deps at even indexes, object deps at odd indexes
 292     int x_id = x.is_metadata() ? x.index() * 2 : (x.index() * 2) + 1;
 293     assert(_dep_seen != NULL, "deps must be writable");
 294     int seen = _dep_seen->at_grow(x_id, 0);
 295     _dep_seen->at_put(x_id, seen | (1<<dept));
 296     // return true if we've already seen dept/x
 297     return (seen & (1<<dept)) != 0;
 298   }
 299 #endif
 300 
 301   bool maybe_merge_ctxk(GrowableArray<ciBaseObject*>* deps,
 302                         int ctxk_i, ciKlass* ctxk);
 303 #if INCLUDE_JVMCI
 304   bool maybe_merge_ctxk(GrowableArray<DepValue>* deps,
 305                         int ctxk_i, DepValue ctxk);
 306 #endif
 307 
 308   void sort_all_deps();
 309   size_t estimate_size_in_bytes();
 310 
 311   // Initialize _deps, etc.
 312   void initialize(ciEnv* env);
 313 
 314   // State for making a new set of dependencies:
 315   OopRecorder* _oop_recorder;
 316 
 317   // Logging support
 318   CompileLog* _log;
 319 
 320   address  _content_bytes;  // everything but the oop references, encoded
 321   size_t   _size_in_bytes;
 322 
 323  public:
 324   // Make a new empty dependencies set.
 325   Dependencies(ciEnv* env) {
 326     initialize(env);
 327   }
 328 #if INCLUDE_JVMCI
 329   Dependencies(Arena* arena, OopRecorder* oop_recorder, CompileLog* log);
 330 #endif
 331 
 332  private:
 333   // Check for a valid context type.
 334   // Enforce the restriction against array types.
 335   static void check_ctxk(ciKlass* ctxk) {
 336     assert(ctxk->is_instance_klass(), "java types only");
 337   }
 338   static void check_ctxk_concrete(ciKlass* ctxk) {
 339     assert(is_concrete_klass(ctxk->as_instance_klass()), "must be concrete");
 340   }
 341   static void check_ctxk_abstract(ciKlass* ctxk) {
 342     check_ctxk(ctxk);
 343     assert(!is_concrete_klass(ctxk->as_instance_klass()), "must be abstract");
 344   }
 345   static void check_unique_method(ciKlass* ctxk, ciMethod* m) {
 346     assert(!m->can_be_statically_bound(ctxk->as_instance_klass()), "redundant");
 347   }
 348 
 349   void assert_common_1(DepType dept, ciBaseObject* x);
 350   void assert_common_2(DepType dept, ciBaseObject* x0, ciBaseObject* x1);
 351   void assert_common_3(DepType dept, ciKlass* ctxk, ciBaseObject* x1, ciBaseObject* x2);
 352 
 353  public:
 354   // Adding assertions to a new dependency set at compile time:
 355   void assert_evol_method(ciMethod* m);
 356   void assert_leaf_type(ciKlass* ctxk);
 357   void assert_abstract_with_unique_concrete_subtype(ciKlass* ctxk, ciKlass* conck);
 358   void assert_abstract_with_no_concrete_subtype(ciKlass* ctxk);
 359   void assert_concrete_with_no_concrete_subtype(ciKlass* ctxk);
 360   void assert_unique_concrete_method(ciKlass* ctxk, ciMethod* uniqm);
 361   void assert_abstract_with_exclusive_concrete_subtypes(ciKlass* ctxk, ciKlass* k1, ciKlass* k2);
 362   void assert_exclusive_concrete_methods(ciKlass* ctxk, ciMethod* m1, ciMethod* m2);
 363   void assert_has_no_finalizable_subclasses(ciKlass* ctxk);
 364   void assert_call_site_target_value(ciCallSite* call_site, ciMethodHandle* method_handle);
 365 
 366 #if INCLUDE_JVMCI
 367  private:
 368   static void check_ctxk(Klass* ctxk) {
 369     assert(ctxk->is_instance_klass(), "java types only");
 370   }
 371   static void check_ctxk_abstract(Klass* ctxk) {
 372     check_ctxk(ctxk);
 373     assert(ctxk->is_abstract(), "must be abstract");
 374   }
 375   static void check_unique_method(Klass* ctxk, Method* m) {
 376     // Graal can register redundant dependencies
 377     assert(UseJVMCICompiler || !m->can_be_statically_bound(InstanceKlass::cast(ctxk)), "redundant");
 378   }
 379 
 380   void assert_common_1(DepType dept, DepValue x);
 381   void assert_common_2(DepType dept, DepValue x0, DepValue x1);
 382 
 383  public:
 384   void assert_evol_method(Method* m);
 385   void assert_has_no_finalizable_subclasses(Klass* ctxk);
 386   void assert_leaf_type(Klass* ctxk);
 387   void assert_unique_concrete_method(Klass* ctxk, Method* uniqm);
 388   void assert_abstract_with_unique_concrete_subtype(Klass* ctxk, Klass* conck);
 389   void assert_call_site_target_value(oop callSite, oop methodHandle);
 390 #endif // INCLUDE_JVMCI
 391 
 392   // Define whether a given method or type is concrete.
 393   // These methods define the term "concrete" as used in this module.
 394   // For this module, an "abstract" class is one which is non-concrete.
 395   //
 396   // Future optimizations may allow some classes to remain
 397   // non-concrete until their first instantiation, and allow some
 398   // methods to remain non-concrete until their first invocation.
 399   // In that case, there would be a middle ground between concrete
 400   // and abstract (as defined by the Java language and VM).
 401   static bool is_concrete_klass(Klass* k);    // k is instantiable
 402   static bool is_concrete_method(Method* m, Klass* k);  // m is invocable
 403   static Klass* find_finalizable_subclass(Klass* k);
 404 
 405   // These versions of the concreteness queries work through the CI.
 406   // The CI versions are allowed to skew sometimes from the VM
 407   // (oop-based) versions.  The cost of such a difference is a
 408   // (safely) aborted compilation, or a deoptimization, or a missed
 409   // optimization opportunity.
 410   //
 411   // In order to prevent spurious assertions, query results must
 412   // remain stable within any single ciEnv instance.  (I.e., they must
 413   // not go back into the VM to get their value; they must cache the
 414   // bit in the CI, either eagerly or lazily.)
 415   static bool is_concrete_klass(ciInstanceKlass* k); // k appears instantiable
 416   static bool has_finalizable_subclass(ciInstanceKlass* k);
 417 
 418   // As a general rule, it is OK to compile under the assumption that
 419   // a given type or method is concrete, even if it at some future
 420   // point becomes abstract.  So dependency checking is one-sided, in
 421   // that it permits supposedly concrete classes or methods to turn up
 422   // as really abstract.  (This shouldn't happen, except during class
 423   // evolution, but that's the logic of the checking.)  However, if a
 424   // supposedly abstract class or method suddenly becomes concrete, a
 425   // dependency on it must fail.
 426 
 427   // Checking old assertions at run-time (in the VM only):
 428   static Klass* check_evol_method(Method* m);
 429   static Klass* check_leaf_type(Klass* ctxk);
 430   static Klass* check_abstract_with_unique_concrete_subtype(Klass* ctxk, Klass* conck,
 431                                                               KlassDepChange* changes = NULL);
 432   static Klass* check_abstract_with_no_concrete_subtype(Klass* ctxk,
 433                                                           KlassDepChange* changes = NULL);
 434   static Klass* check_concrete_with_no_concrete_subtype(Klass* ctxk,
 435                                                           KlassDepChange* changes = NULL);
 436   static Klass* check_unique_concrete_method(Klass* ctxk, Method* uniqm,
 437                                                KlassDepChange* changes = NULL);
 438   static Klass* check_abstract_with_exclusive_concrete_subtypes(Klass* ctxk, Klass* k1, Klass* k2,
 439                                                                   KlassDepChange* changes = NULL);
 440   static Klass* check_exclusive_concrete_methods(Klass* ctxk, Method* m1, Method* m2,
 441                                                    KlassDepChange* changes = NULL);
 442   static Klass* check_has_no_finalizable_subclasses(Klass* ctxk, KlassDepChange* changes = NULL);
 443   static Klass* check_call_site_target_value(oop call_site, oop method_handle, CallSiteDepChange* changes = NULL);
 444   // A returned Klass* is NULL if the dependency assertion is still
 445   // valid.  A non-NULL Klass* is a 'witness' to the assertion
 446   // failure, a point in the class hierarchy where the assertion has
 447   // been proven false.  For example, if check_leaf_type returns
 448   // non-NULL, the value is a subtype of the supposed leaf type.  This
 449   // witness value may be useful for logging the dependency failure.
 450   // Note that, when a dependency fails, there may be several possible
 451   // witnesses to the failure.  The value returned from the check_foo
 452   // method is chosen arbitrarily.
 453 
 454   // The 'changes' value, if non-null, requests a limited spot-check
 455   // near the indicated recent changes in the class hierarchy.
 456   // It is used by DepStream::spot_check_dependency_at.
 457 
 458   // Detecting possible new assertions:
 459   static Klass*    find_unique_concrete_subtype(Klass* ctxk);
 460   static Method*   find_unique_concrete_method(Klass* ctxk, Method* m);
 461   static int       find_exclusive_concrete_subtypes(Klass* ctxk, int klen, Klass* k[]);
 462 
 463   // Create the encoding which will be stored in an nmethod.
 464   void encode_content_bytes();
 465 
 466   address content_bytes() {
 467     assert(_content_bytes != NULL, "encode it first");
 468     return _content_bytes;
 469   }
 470   size_t size_in_bytes() {
 471     assert(_content_bytes != NULL, "encode it first");
 472     return _size_in_bytes;
 473   }
 474 
 475   OopRecorder* oop_recorder() { return _oop_recorder; }
 476   CompileLog*  log()          { return _log; }
 477 
 478   void copy_to(nmethod* nm);
 479 
 480   DepType validate_dependencies(CompileTask* task, bool counter_changed, char** failure_detail = NULL);
 481 
 482   void log_all_dependencies();
 483 
 484   void log_dependency(DepType dept, GrowableArray<ciBaseObject*>* args) {
 485     ResourceMark rm;
 486     int argslen = args->length();
 487     write_dependency_to(log(), dept, args);
 488     guarantee(argslen == args->length(),
 489               "args array cannot grow inside nested ResoureMark scope");
 490   }
 491 
 492   void log_dependency(DepType dept,
 493                       ciBaseObject* x0,
 494                       ciBaseObject* x1 = NULL,
 495                       ciBaseObject* x2 = NULL) {
 496     if (log() == NULL) {
 497       return;
 498     }
 499     ResourceMark rm;
 500     GrowableArray<ciBaseObject*>* ciargs =
 501                 new GrowableArray<ciBaseObject*>(dep_args(dept));
 502     assert (x0 != NULL, "no log x0");
 503     ciargs->push(x0);
 504 
 505     if (x1 != NULL) {
 506       ciargs->push(x1);
 507     }
 508     if (x2 != NULL) {
 509       ciargs->push(x2);
 510     }
 511     assert(ciargs->length() == dep_args(dept), "");
 512     log_dependency(dept, ciargs);
 513   }
 514 
 515   class DepArgument : public ResourceObj {
 516    private:
 517     bool  _is_oop;
 518     bool  _valid;
 519     void* _value;
 520    public:
 521     DepArgument() : _is_oop(false), _valid(false), _value(NULL) {}
 522     DepArgument(oop v): _is_oop(true), _valid(true), _value(v) {}
 523     DepArgument(Metadata* v): _is_oop(false), _valid(true), _value(v) {}
 524 
 525     bool is_null() const               { return _value == NULL; }
 526     bool is_oop() const                { return _is_oop; }
 527     bool is_metadata() const           { return !_is_oop; }
 528     bool is_klass() const              { return is_metadata() && metadata_value()->is_klass(); }
 529     bool is_method() const              { return is_metadata() && metadata_value()->is_method(); }
 530 
 531     oop oop_value() const              { assert(_is_oop && _valid, "must be"); return (oop) _value; }
 532     Metadata* metadata_value() const { assert(!_is_oop && _valid, "must be"); return (Metadata*) _value; }
 533   };
 534 
 535   static void print_dependency(DepType dept,
 536                                GrowableArray<DepArgument>* args,
 537                                Klass* witness = NULL, outputStream* st = tty);
 538 
 539  private:
 540   // helper for encoding common context types as zero:
 541   static ciKlass* ctxk_encoded_as_null(DepType dept, ciBaseObject* x);
 542 
 543   static Klass* ctxk_encoded_as_null(DepType dept, Metadata* x);
 544 
 545   static void write_dependency_to(CompileLog* log,
 546                                   DepType dept,
 547                                   GrowableArray<ciBaseObject*>* args,
 548                                   Klass* witness = NULL);
 549   static void write_dependency_to(CompileLog* log,
 550                                   DepType dept,
 551                                   GrowableArray<DepArgument>* args,
 552                                   Klass* witness = NULL);
 553   static void write_dependency_to(xmlStream* xtty,
 554                                   DepType dept,
 555                                   GrowableArray<DepArgument>* args,
 556                                   Klass* witness = NULL);
 557  public:
 558   // Use this to iterate over an nmethod's dependency set.
 559   // Works on new and old dependency sets.
 560   // Usage:
 561   //
 562   // ;
 563   // Dependencies::DepType dept;
 564   // for (Dependencies::DepStream deps(nm); deps.next(); ) {
 565   //   ...
 566   // }
 567   //
 568   // The caller must be in the VM, since oops are not wrapped in handles.
 569   class DepStream {
 570   private:
 571     nmethod*              _code;   // null if in a compiler thread
 572     Dependencies*         _deps;   // null if not in a compiler thread
 573     CompressedReadStream  _bytes;
 574 #ifdef ASSERT
 575     size_t                _byte_limit;
 576 #endif
 577 
 578     // iteration variables:
 579     DepType               _type;
 580     int                   _xi[max_arg_count+1];
 581 
 582     void initial_asserts(size_t byte_limit) NOT_DEBUG({});
 583 
 584     inline Metadata* recorded_metadata_at(int i);
 585     inline oop recorded_oop_at(int i);
 586 
 587     Klass* check_klass_dependency(KlassDepChange* changes);
 588     Klass* check_call_site_dependency(CallSiteDepChange* changes);
 589 
 590     void trace_and_log_witness(Klass* witness);
 591 
 592   public:
 593     DepStream(Dependencies* deps)
 594       : _code(NULL),
 595         _deps(deps),
 596         _bytes(deps->content_bytes())
 597     {
 598       initial_asserts(deps->size_in_bytes());
 599     }
 600     DepStream(nmethod* code)
 601       : _code(code),
 602         _deps(NULL),
 603         _bytes(code->dependencies_begin())
 604     {
 605       initial_asserts(code->dependencies_size());
 606     }
 607 
 608     bool next();
 609 
 610     DepType type()               { return _type; }
 611     bool is_oop_argument(int i)  { return type() == call_site_target_value; }
 612     uintptr_t get_identifier(int i);
 613 
 614     int argument_count()         { return dep_args(type()); }
 615     int argument_index(int i)    { assert(0 <= i && i < argument_count(), "oob");
 616                                    return _xi[i]; }
 617     Metadata* argument(int i);     // => recorded_oop_at(argument_index(i))
 618     oop argument_oop(int i);         // => recorded_oop_at(argument_index(i))
 619     Klass* context_type();
 620 
 621     bool is_klass_type()         { return Dependencies::is_klass_type(type()); }
 622 
 623     Method* method_argument(int i) {
 624       Metadata* x = argument(i);
 625       assert(x->is_method(), "type");
 626       return (Method*) x;
 627     }
 628     Klass* type_argument(int i) {
 629       Metadata* x = argument(i);
 630       assert(x->is_klass(), "type");
 631       return (Klass*) x;
 632     }
 633 
 634     // The point of the whole exercise:  Is this dep still OK?
 635     Klass* check_dependency() {
 636       Klass* result = check_klass_dependency(NULL);
 637       if (result != NULL)  return result;
 638       return check_call_site_dependency(NULL);
 639     }
 640 
 641     // A lighter version:  Checks only around recent changes in a class
 642     // hierarchy.  (See Universe::flush_dependents_on.)
 643     Klass* spot_check_dependency_at(DepChange& changes);
 644 
 645     // Log the current dependency to xtty or compilation log.
 646     void log_dependency(Klass* witness = NULL);
 647 
 648     // Print the current dependency to tty.
 649     void print_dependency(Klass* witness = NULL, bool verbose = false, outputStream* st = tty);
 650   };
 651   friend class Dependencies::DepStream;
 652 
 653   static void print_statistics() PRODUCT_RETURN;
 654 };
 655 
 656 
 657 class DependencySignature : public ResourceObj {
 658  private:
 659   int                   _args_count;
 660   uintptr_t             _argument_hash[Dependencies::max_arg_count];
 661   Dependencies::DepType _type;
 662 
 663  public:
 664   DependencySignature(Dependencies::DepStream& dep) {
 665     _args_count = dep.argument_count();
 666     _type = dep.type();
 667     for (int i = 0; i < _args_count; i++) {
 668       _argument_hash[i] = dep.get_identifier(i);
 669     }
 670   }
 671 
 672   static bool     equals(DependencySignature const& s1, DependencySignature const& s2);
 673   static unsigned hash  (DependencySignature const& s1) { return s1.arg(0) >> 2; }
 674 
 675   int args_count()             const { return _args_count; }
 676   uintptr_t arg(int idx)       const { return _argument_hash[idx]; }
 677   Dependencies::DepType type() const { return _type; }
 678 
 679 };
 680 
 681 
 682 // Every particular DepChange is a sub-class of this class.
 683 class DepChange : public StackObj {
 684  public:
 685   // What kind of DepChange is this?
 686   virtual bool is_klass_change()     const { return false; }
 687   virtual bool is_call_site_change() const { return false; }
 688 
 689   virtual void mark_for_deoptimization(nmethod* nm) = 0;
 690 
 691   // Subclass casting with assertions.
 692   KlassDepChange*    as_klass_change() {
 693     assert(is_klass_change(), "bad cast");
 694     return (KlassDepChange*) this;
 695   }
 696   CallSiteDepChange* as_call_site_change() {
 697     assert(is_call_site_change(), "bad cast");
 698     return (CallSiteDepChange*) this;
 699   }
 700 
 701   void print();
 702 
 703  public:
 704   enum ChangeType {
 705     NO_CHANGE = 0,              // an uninvolved klass
 706     Change_new_type,            // a newly loaded type
 707     Change_new_sub,             // a super with a new subtype
 708     Change_new_impl,            // an interface with a new implementation
 709     CHANGE_LIMIT,
 710     Start_Klass = CHANGE_LIMIT  // internal indicator for ContextStream
 711   };
 712 
 713   // Usage:
 714   // for (DepChange::ContextStream str(changes); str.next(); ) {
 715   //   Klass* k = str.klass();
 716   //   switch (str.change_type()) {
 717   //     ...
 718   //   }
 719   // }
 720   class ContextStream : public StackObj {
 721    private:
 722     DepChange&  _changes;
 723     friend class DepChange;
 724 
 725     // iteration variables:
 726     ChangeType  _change_type;
 727     Klass*      _klass;
 728     Array<InstanceKlass*>* _ti_base;    // i.e., transitive_interfaces
 729     int         _ti_index;
 730     int         _ti_limit;
 731 
 732     // start at the beginning:
 733     void start();
 734 
 735    public:
 736     ContextStream(DepChange& changes)
 737       : _changes(changes)
 738     { start(); }
 739 
 740     ContextStream(DepChange& changes, NoSafepointVerifier& nsv)
 741       : _changes(changes)
 742       // the nsv argument makes it safe to hold oops like _klass
 743     { start(); }
 744 
 745     bool next();
 746 
 747     ChangeType change_type()     { return _change_type; }
 748     Klass*     klass()           { return _klass; }
 749   };
 750   friend class DepChange::ContextStream;
 751 };
 752 
 753 
 754 // A class hierarchy change coming through the VM (under the Compile_lock).
 755 // The change is structured as a single new type with any number of supers
 756 // and implemented interface types.  Other than the new type, any of the
 757 // super types can be context types for a relevant dependency, which the
 758 // new type could invalidate.
 759 class KlassDepChange : public DepChange {
 760  private:
 761   // each change set is rooted in exactly one new type (at present):
 762   Klass* _new_type;
 763 
 764   void initialize();
 765 
 766  public:
 767   // notes the new type, marks it and all its super-types
 768   KlassDepChange(Klass* new_type)
 769     : _new_type(new_type)
 770   {
 771     initialize();
 772   }
 773 
 774   // cleans up the marks
 775   ~KlassDepChange();
 776 
 777   // What kind of DepChange is this?
 778   virtual bool is_klass_change() const { return true; }
 779 
 780   virtual void mark_for_deoptimization(nmethod* nm) {
 781     nm->mark_for_deoptimization(/*inc_recompile_counts=*/true);
 782   }
 783 
 784   Klass* new_type() { return _new_type; }
 785 
 786   // involves_context(k) is true if k is new_type or any of the super types
 787   bool involves_context(Klass* k);
 788 };
 789 
 790 
 791 // A CallSite has changed its target.
 792 class CallSiteDepChange : public DepChange {
 793  private:
 794   Handle _call_site;
 795   Handle _method_handle;
 796 
 797  public:
 798   CallSiteDepChange(Handle call_site, Handle method_handle);
 799 
 800   // What kind of DepChange is this?
 801   virtual bool is_call_site_change() const { return true; }
 802 
 803   virtual void mark_for_deoptimization(nmethod* nm) {
 804     nm->mark_for_deoptimization(/*inc_recompile_counts=*/false);
 805   }
 806 
 807   oop call_site()     const { return _call_site();     }
 808   oop method_handle() const { return _method_handle(); }
 809 };
 810 
 811 #endif // SHARE_CODE_DEPENDENCIES_HPP