src/share/vm/classfile/defaultMethods.cpp

Mon, 26 Aug 2013 11:35:25 -0400

author
acorn
date
Mon, 26 Aug 2013 11:35:25 -0400
changeset 5599
91b93f523ec6
parent 5377
50257d6f5aaa
child 5608
915cc4f3fb15
permissions
-rw-r--r--

8012294: remove generic handling for default methods
Reviewed-by: kamg, coleenp

     1 /*
     2  * Copyright (c) 2012, 2013, 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  */
    25 #include "precompiled.hpp"
    26 #include "classfile/bytecodeAssembler.hpp"
    27 #include "classfile/defaultMethods.hpp"
    28 #include "classfile/symbolTable.hpp"
    29 #include "memory/allocation.hpp"
    30 #include "memory/metadataFactory.hpp"
    31 #include "memory/resourceArea.hpp"
    32 #include "runtime/signature.hpp"
    33 #include "runtime/thread.hpp"
    34 #include "oops/instanceKlass.hpp"
    35 #include "oops/klass.hpp"
    36 #include "oops/method.hpp"
    37 #include "utilities/accessFlags.hpp"
    38 #include "utilities/exceptions.hpp"
    39 #include "utilities/ostream.hpp"
    40 #include "utilities/pair.hpp"
    41 #include "utilities/resourceHash.hpp"
    43 typedef enum { QUALIFIED, DISQUALIFIED } QualifiedState;
    45 // Because we use an iterative algorithm when iterating over the type
    46 // hierarchy, we can't use traditional scoped objects which automatically do
    47 // cleanup in the destructor when the scope is exited.  PseudoScope (and
    48 // PseudoScopeMark) provides a similar functionality, but for when you want a
    49 // scoped object in non-stack memory (such as in resource memory, as we do
    50 // here).  You've just got to remember to call 'destroy()' on the scope when
    51 // leaving it (and marks have to be explicitly added).
    52 class PseudoScopeMark : public ResourceObj {
    53  public:
    54   virtual void destroy() = 0;
    55 };
    57 class PseudoScope : public ResourceObj {
    58  private:
    59   GrowableArray<PseudoScopeMark*> _marks;
    60  public:
    62   static PseudoScope* cast(void* data) {
    63     return static_cast<PseudoScope*>(data);
    64   }
    66   void add_mark(PseudoScopeMark* psm) {
    67    _marks.append(psm);
    68   }
    70   void destroy() {
    71     for (int i = 0; i < _marks.length(); ++i) {
    72       _marks.at(i)->destroy();
    73     }
    74   }
    75 };
    77 #ifndef PRODUCT
    78 static void print_slot(outputStream* str, Symbol* name, Symbol* signature) {
    79   ResourceMark rm;
    80   str->print("%s%s", name->as_C_string(), signature->as_C_string());
    81 }
    83 static void print_method(outputStream* str, Method* mo, bool with_class=true) {
    84   ResourceMark rm;
    85   if (with_class) {
    86     str->print("%s.", mo->klass_name()->as_C_string());
    87   }
    88   print_slot(str, mo->name(), mo->signature());
    89 }
    90 #endif // ndef PRODUCT
    92 /**
    93  * Perform a depth-first iteration over the class hierarchy, applying
    94  * algorithmic logic as it goes.
    95  *
    96  * This class is one half of the inheritance hierarchy analysis mechanism.
    97  * It is meant to be used in conjunction with another class, the algorithm,
    98  * which is indicated by the ALGO template parameter.  This class can be
    99  * paired with any algorithm class that provides the required methods.
   100  *
   101  * This class contains all the mechanics for iterating over the class hierarchy
   102  * starting at a particular root, without recursing (thus limiting stack growth
   103  * from this point).  It visits each superclass (if present) and superinterface
   104  * in a depth-first manner, with callbacks to the ALGO class as each class is
   105  * encountered (visit()), The algorithm can cut-off further exploration of a
   106  * particular branch by returning 'false' from a visit() call.
   107  *
   108  * The ALGO class, must provide a visit() method, which each of which will be
   109  * called once for each node in the inheritance tree during the iteration.  In
   110  * addition, it can provide a memory block via new_node_data(InstanceKlass*),
   111  * which it can use for node-specific storage (and access via the
   112  * current_data() and data_at_depth(int) methods).
   113  *
   114  * Bare minimum needed to be an ALGO class:
   115  * class Algo : public HierarchyVisitor<Algo> {
   116  *   void* new_node_data(InstanceKlass* cls) { return NULL; }
   117  *   void free_node_data(void* data) { return; }
   118  *   bool visit() { return true; }
   119  * };
   120  */
   121 template <class ALGO>
   122 class HierarchyVisitor : StackObj {
   123  private:
   125   class Node : public ResourceObj {
   126    public:
   127     InstanceKlass* _class;
   128     bool _super_was_visited;
   129     int _interface_index;
   130     void* _algorithm_data;
   132     Node(InstanceKlass* cls, void* data, bool visit_super)
   133         : _class(cls), _super_was_visited(!visit_super),
   134           _interface_index(0), _algorithm_data(data) {}
   136     int number_of_interfaces() { return _class->local_interfaces()->length(); }
   137     int interface_index() { return _interface_index; }
   138     void set_super_visited() { _super_was_visited = true; }
   139     void increment_visited_interface() { ++_interface_index; }
   140     void set_all_interfaces_visited() {
   141       _interface_index = number_of_interfaces();
   142     }
   143     bool has_visited_super() { return _super_was_visited; }
   144     bool has_visited_all_interfaces() {
   145       return interface_index() >= number_of_interfaces();
   146     }
   147     InstanceKlass* interface_at(int index) {
   148       return InstanceKlass::cast(_class->local_interfaces()->at(index));
   149     }
   150     InstanceKlass* next_super() { return _class->java_super(); }
   151     InstanceKlass* next_interface() {
   152       return interface_at(interface_index());
   153     }
   154   };
   156   bool _cancelled;
   157   GrowableArray<Node*> _path;
   159   Node* current_top() const { return _path.top(); }
   160   bool has_more_nodes() const { return !_path.is_empty(); }
   161   void push(InstanceKlass* cls, void* data) {
   162     assert(cls != NULL, "Requires a valid instance class");
   163     Node* node = new Node(cls, data, has_super(cls));
   164     _path.push(node);
   165   }
   166   void pop() { _path.pop(); }
   168   void reset_iteration() {
   169     _cancelled = false;
   170     _path.clear();
   171   }
   172   bool is_cancelled() const { return _cancelled; }
   174   static bool has_super(InstanceKlass* cls) {
   175     return cls->super() != NULL && !cls->is_interface();
   176   }
   178   Node* node_at_depth(int i) const {
   179     return (i >= _path.length()) ? NULL : _path.at(_path.length() - i - 1);
   180   }
   182  protected:
   184   // Accessors available to the algorithm
   185   int current_depth() const { return _path.length() - 1; }
   187   InstanceKlass* class_at_depth(int i) {
   188     Node* n = node_at_depth(i);
   189     return n == NULL ? NULL : n->_class;
   190   }
   191   InstanceKlass* current_class() { return class_at_depth(0); }
   193   void* data_at_depth(int i) {
   194     Node* n = node_at_depth(i);
   195     return n == NULL ? NULL : n->_algorithm_data;
   196   }
   197   void* current_data() { return data_at_depth(0); }
   199   void cancel_iteration() { _cancelled = true; }
   201  public:
   203   void run(InstanceKlass* root) {
   204     ALGO* algo = static_cast<ALGO*>(this);
   206     reset_iteration();
   208     void* algo_data = algo->new_node_data(root);
   209     push(root, algo_data);
   210     bool top_needs_visit = true;
   212     do {
   213       Node* top = current_top();
   214       if (top_needs_visit) {
   215         if (algo->visit() == false) {
   216           // algorithm does not want to continue along this path.  Arrange
   217           // it so that this state is immediately popped off the stack
   218           top->set_super_visited();
   219           top->set_all_interfaces_visited();
   220         }
   221         top_needs_visit = false;
   222       }
   224       if (top->has_visited_super() && top->has_visited_all_interfaces()) {
   225         algo->free_node_data(top->_algorithm_data);
   226         pop();
   227       } else {
   228         InstanceKlass* next = NULL;
   229         if (top->has_visited_super() == false) {
   230           next = top->next_super();
   231           top->set_super_visited();
   232         } else {
   233           next = top->next_interface();
   234           top->increment_visited_interface();
   235         }
   236         assert(next != NULL, "Otherwise we shouldn't be here");
   237         algo_data = algo->new_node_data(next);
   238         push(next, algo_data);
   239         top_needs_visit = true;
   240       }
   241     } while (!is_cancelled() && has_more_nodes());
   242   }
   243 };
   245 #ifndef PRODUCT
   246 class PrintHierarchy : public HierarchyVisitor<PrintHierarchy> {
   247  public:
   249   bool visit() {
   250     InstanceKlass* cls = current_class();
   251     streamIndentor si(tty, current_depth() * 2);
   252     tty->indent().print_cr("%s", cls->name()->as_C_string());
   253     return true;
   254   }
   256   void* new_node_data(InstanceKlass* cls) { return NULL; }
   257   void free_node_data(void* data) { return; }
   258 };
   259 #endif // ndef PRODUCT
   261 // Used to register InstanceKlass objects and all related metadata structures
   262 // (Methods, ConstantPools) as "in-use" by the current thread so that they can't
   263 // be deallocated by class redefinition while we're using them.  The classes are
   264 // de-registered when this goes out of scope.
   265 //
   266 // Once a class is registered, we need not bother with methodHandles or
   267 // constantPoolHandles for it's associated metadata.
   268 class KeepAliveRegistrar : public StackObj {
   269  private:
   270   Thread* _thread;
   271   GrowableArray<ConstantPool*> _keep_alive;
   273  public:
   274   KeepAliveRegistrar(Thread* thread) : _thread(thread), _keep_alive(20) {
   275     assert(thread == Thread::current(), "Must be current thread");
   276   }
   278   ~KeepAliveRegistrar() {
   279     for (int i = _keep_alive.length() - 1; i >= 0; --i) {
   280       ConstantPool* cp = _keep_alive.at(i);
   281       int idx = _thread->metadata_handles()->find_from_end(cp);
   282       assert(idx > 0, "Must be in the list");
   283       _thread->metadata_handles()->remove_at(idx);
   284     }
   285   }
   287   // Register a class as 'in-use' by the thread.  It's fine to register a class
   288   // multiple times (though perhaps inefficient)
   289   void register_class(InstanceKlass* ik) {
   290     ConstantPool* cp = ik->constants();
   291     _keep_alive.push(cp);
   292     _thread->metadata_handles()->push(cp);
   293   }
   294 };
   296 class KeepAliveVisitor : public HierarchyVisitor<KeepAliveVisitor> {
   297  private:
   298   KeepAliveRegistrar* _registrar;
   300  public:
   301   KeepAliveVisitor(KeepAliveRegistrar* registrar) : _registrar(registrar) {}
   303   void* new_node_data(InstanceKlass* cls) { return NULL; }
   304   void free_node_data(void* data) { return; }
   306   bool visit() {
   307     _registrar->register_class(current_class());
   308     return true;
   309   }
   310 };
   313 // A method family contains a set of all methods that implement a single
   314 // erased method. As members of the set are collected while walking over the
   315 // hierarchy, they are tagged with a qualification state.  The qualification
   316 // state for an erased method is set to disqualified if there exists a path
   317 // from the root of hierarchy to the method that contains an interleaving
   318 // erased method defined in an interface.
   320 class MethodFamily : public ResourceObj {
   321  private:
   323   GrowableArray<Pair<Method*,QualifiedState> > _members;
   324   ResourceHashtable<Method*, int> _member_index;
   326   Method* _selected_target;  // Filled in later, if a unique target exists
   327   Symbol* _exception_message; // If no unique target is found
   329   bool contains_method(Method* method) {
   330     int* lookup = _member_index.get(method);
   331     return lookup != NULL;
   332   }
   334   void add_method(Method* method, QualifiedState state) {
   335     Pair<Method*,QualifiedState> entry(method, state);
   336     _member_index.put(method, _members.length());
   337     _members.append(entry);
   338   }
   340   void disqualify_method(Method* method) {
   341     int* index = _member_index.get(method);
   342     guarantee(index != NULL && *index >= 0 && *index < _members.length(), "bad index");
   343     _members.at(*index).second = DISQUALIFIED;
   344   }
   346   Symbol* generate_no_defaults_message(TRAPS) const;
   347   Symbol* generate_abstract_method_message(Method* method, TRAPS) const;
   348   Symbol* generate_conflicts_message(GrowableArray<Method*>* methods, TRAPS) const;
   350  public:
   352   MethodFamily()
   353       : _selected_target(NULL), _exception_message(NULL) {}
   355   void set_target_if_empty(Method* m) {
   356     if (_selected_target == NULL && !m->is_overpass()) {
   357       _selected_target = m;
   358     }
   359   }
   361   void record_qualified_method(Method* m) {
   362     // If the method already exists in the set as qualified, this operation is
   363     // redundant.  If it already exists as disqualified, then we leave it as
   364     // disqualfied.  Thus we only add to the set if it's not already in the
   365     // set.
   366     if (!contains_method(m)) {
   367       add_method(m, QUALIFIED);
   368     }
   369   }
   371   void record_disqualified_method(Method* m) {
   372     // If not in the set, add it as disqualified.  If it's already in the set,
   373     // then set the state to disqualified no matter what the previous state was.
   374     if (!contains_method(m)) {
   375       add_method(m, DISQUALIFIED);
   376     } else {
   377       disqualify_method(m);
   378     }
   379   }
   381   bool has_target() const { return _selected_target != NULL; }
   382   bool throws_exception() { return _exception_message != NULL; }
   384   Method* get_selected_target() { return _selected_target; }
   385   Symbol* get_exception_message() { return _exception_message; }
   387   // Either sets the target or the exception error message
   388   void determine_target(InstanceKlass* root, TRAPS) {
   389     if (has_target() || throws_exception()) {
   390       return;
   391     }
   393     GrowableArray<Method*> qualified_methods;
   394     for (int i = 0; i < _members.length(); ++i) {
   395       Pair<Method*,QualifiedState> entry = _members.at(i);
   396       if (entry.second == QUALIFIED) {
   397         qualified_methods.append(entry.first);
   398       }
   399     }
   401     if (qualified_methods.length() == 0) {
   402       _exception_message = generate_no_defaults_message(CHECK);
   403     } else if (qualified_methods.length() == 1) {
   404       Method* method = qualified_methods.at(0);
   405       if (method->is_abstract()) {
   406         _exception_message = generate_abstract_method_message(method, CHECK);
   407       } else {
   408         _selected_target = qualified_methods.at(0);
   409       }
   410     } else {
   411       _exception_message = generate_conflicts_message(&qualified_methods,CHECK);
   412     }
   414     assert((has_target() ^ throws_exception()) == 1,
   415            "One and only one must be true");
   416   }
   418   bool contains_signature(Symbol* query) {
   419     for (int i = 0; i < _members.length(); ++i) {
   420       if (query == _members.at(i).first->signature()) {
   421         return true;
   422       }
   423     }
   424     return false;
   425   }
   427 #ifndef PRODUCT
   428   void print_sig_on(outputStream* str, Symbol* signature, int indent) const {
   429     streamIndentor si(str, indent * 2);
   431     str->indent().print_cr("Logical Method %s:", signature->as_C_string());
   433     streamIndentor si2(str);
   434     for (int i = 0; i < _members.length(); ++i) {
   435       str->indent();
   436       print_method(str, _members.at(i).first);
   437       if (_members.at(i).second == DISQUALIFIED) {
   438         str->print(" (disqualified)");
   439       }
   440       str->print_cr("");
   441     }
   443     if (_selected_target != NULL) {
   444       print_selected(str, 1);
   445     }
   446   }
   448   void print_selected(outputStream* str, int indent) const {
   449     assert(has_target(), "Should be called otherwise");
   450     streamIndentor si(str, indent * 2);
   451     str->indent().print("Selected method: ");
   452     print_method(str, _selected_target);
   453     str->print_cr("");
   454   }
   456   void print_exception(outputStream* str, int indent) {
   457     assert(throws_exception(), "Should be called otherwise");
   458     streamIndentor si(str, indent * 2);
   459     str->indent().print_cr("%s", _exception_message->as_C_string());
   460   }
   461 #endif // ndef PRODUCT
   462 };
   464 Symbol* MethodFamily::generate_no_defaults_message(TRAPS) const {
   465   return SymbolTable::new_symbol("No qualifying defaults found", CHECK_NULL);
   466 }
   468 Symbol* MethodFamily::generate_abstract_method_message(Method* method, TRAPS) const {
   469   Symbol* klass = method->klass_name();
   470   Symbol* name = method->name();
   471   Symbol* sig = method->signature();
   472   stringStream ss;
   473   ss.print("Method ");
   474   ss.write((const char*)klass->bytes(), klass->utf8_length());
   475   ss.print(".");
   476   ss.write((const char*)name->bytes(), name->utf8_length());
   477   ss.write((const char*)sig->bytes(), sig->utf8_length());
   478   ss.print(" is abstract");
   479   return SymbolTable::new_symbol(ss.base(), (int)ss.size(), CHECK_NULL);
   480 }
   482 Symbol* MethodFamily::generate_conflicts_message(GrowableArray<Method*>* methods, TRAPS) const {
   483   stringStream ss;
   484   ss.print("Conflicting default methods:");
   485   for (int i = 0; i < methods->length(); ++i) {
   486     Method* method = methods->at(i);
   487     Symbol* klass = method->klass_name();
   488     Symbol* name = method->name();
   489     ss.print(" ");
   490     ss.write((const char*)klass->bytes(), klass->utf8_length());
   491     ss.print(".");
   492     ss.write((const char*)name->bytes(), name->utf8_length());
   493   }
   494   return SymbolTable::new_symbol(ss.base(), (int)ss.size(), CHECK_NULL);
   495 }
   498 class StateRestorer;
   500 // StatefulMethodFamily is a wrapper around a MethodFamily that maintains the
   501 // qualification state during hierarchy visitation, and applies that state
   502 // when adding members to the MethodFamily
   503 class StatefulMethodFamily : public ResourceObj {
   504   friend class StateRestorer;
   505  private:
   506   QualifiedState _qualification_state;
   508   void set_qualification_state(QualifiedState state) {
   509     _qualification_state = state;
   510   }
   512  protected:
   513   MethodFamily* _method_family;
   515  public:
   516   StatefulMethodFamily() {
   517    _method_family = new MethodFamily();
   518    _qualification_state = QUALIFIED;
   519   }
   521   StatefulMethodFamily(MethodFamily* mf) {
   522    _method_family = mf;
   523    _qualification_state = QUALIFIED;
   524   }
   526   void set_target_if_empty(Method* m) { _method_family->set_target_if_empty(m); }
   528   MethodFamily* get_method_family() { return _method_family; }
   530   StateRestorer* record_method_and_dq_further(Method* mo);
   531 };
   533 class StateRestorer : public PseudoScopeMark {
   534  private:
   535   StatefulMethodFamily* _method;
   536   QualifiedState _state_to_restore;
   537  public:
   538   StateRestorer(StatefulMethodFamily* dm, QualifiedState state)
   539       : _method(dm), _state_to_restore(state) {}
   540   ~StateRestorer() { destroy(); }
   541   void restore_state() { _method->set_qualification_state(_state_to_restore); }
   542   virtual void destroy() { restore_state(); }
   543 };
   545 StateRestorer* StatefulMethodFamily::record_method_and_dq_further(Method* mo) {
   546   StateRestorer* mark = new StateRestorer(this, _qualification_state);
   547   if (_qualification_state == QUALIFIED) {
   548     _method_family->record_qualified_method(mo);
   549   } else {
   550     _method_family->record_disqualified_method(mo);
   551   }
   552   // Everything found "above"??? this method in the hierarchy walk is set to
   553   // disqualified
   554   set_qualification_state(DISQUALIFIED);
   555   return mark;
   556 }
   558 // Represents a location corresponding to a vtable slot for methods that
   559 // neither the class nor any of it's ancestors provide an implementaion.
   560 // Default methods may be present to fill this slot.
   561 class EmptyVtableSlot : public ResourceObj {
   562  private:
   563   Symbol* _name;
   564   Symbol* _signature;
   565   int _size_of_parameters;
   566   MethodFamily* _binding;
   568  public:
   569   EmptyVtableSlot(Method* method)
   570       : _name(method->name()), _signature(method->signature()),
   571         _size_of_parameters(method->size_of_parameters()), _binding(NULL) {}
   573   Symbol* name() const { return _name; }
   574   Symbol* signature() const { return _signature; }
   575   int size_of_parameters() const { return _size_of_parameters; }
   577   void bind_family(MethodFamily* lm) { _binding = lm; }
   578   bool is_bound() { return _binding != NULL; }
   579   MethodFamily* get_binding() { return _binding; }
   581 #ifndef PRODUCT
   582   void print_on(outputStream* str) const {
   583     print_slot(str, name(), signature());
   584   }
   585 #endif // ndef PRODUCT
   586 };
   588 static GrowableArray<EmptyVtableSlot*>* find_empty_vtable_slots(
   589     InstanceKlass* klass, GrowableArray<Method*>* mirandas, TRAPS) {
   591   assert(klass != NULL, "Must be valid class");
   593   GrowableArray<EmptyVtableSlot*>* slots = new GrowableArray<EmptyVtableSlot*>();
   595   // All miranda methods are obvious candidates
   596   for (int i = 0; i < mirandas->length(); ++i) {
   597     EmptyVtableSlot* slot = new EmptyVtableSlot(mirandas->at(i));
   598     slots->append(slot);
   599   }
   601   // Also any overpasses in our superclasses, that we haven't implemented.
   602   // (can't use the vtable because it is not guaranteed to be initialized yet)
   603   InstanceKlass* super = klass->java_super();
   604   while (super != NULL) {
   605     for (int i = 0; i < super->methods()->length(); ++i) {
   606       Method* m = super->methods()->at(i);
   607       if (m->is_overpass()) {
   608         // m is a method that would have been a miranda if not for the
   609         // default method processing that occurred on behalf of our superclass,
   610         // so it's a method we want to re-examine in this new context.  That is,
   611         // unless we have a real implementation of it in the current class.
   612         Method* impl = klass->lookup_method(m->name(), m->signature());
   613         if (impl == NULL || impl->is_overpass()) {
   614           slots->append(new EmptyVtableSlot(m));
   615         }
   616       }
   617     }
   618     super = super->java_super();
   619   }
   621 #ifndef PRODUCT
   622   if (TraceDefaultMethods) {
   623     tty->print_cr("Slots that need filling:");
   624     streamIndentor si(tty);
   625     for (int i = 0; i < slots->length(); ++i) {
   626       tty->indent();
   627       slots->at(i)->print_on(tty);
   628       tty->print_cr("");
   629     }
   630   }
   631 #endif // ndef PRODUCT
   632   return slots;
   633 }
   635 // Iterates over the superinterface type hierarchy looking for all methods
   636 // with a specific erased signature.
   637 class FindMethodsByErasedSig : public HierarchyVisitor<FindMethodsByErasedSig> {
   638  private:
   639   // Context data
   640   Symbol* _method_name;
   641   Symbol* _method_signature;
   642   StatefulMethodFamily*  _family;
   644  public:
   645   FindMethodsByErasedSig(Symbol* name, Symbol* signature) :
   646       _method_name(name), _method_signature(signature),
   647       _family(NULL) {}
   649   void get_discovered_family(MethodFamily** family) {
   650       if (_family != NULL) {
   651         *family = _family->get_method_family();
   652       } else {
   653         *family = NULL;
   654       }
   655   }
   657   void* new_node_data(InstanceKlass* cls) { return new PseudoScope(); }
   658   void free_node_data(void* node_data) {
   659     PseudoScope::cast(node_data)->destroy();
   660   }
   662   // Find all methods on this hierarchy that match this
   663   // method's erased (name, signature)
   664   bool visit() {
   665     PseudoScope* scope = PseudoScope::cast(current_data());
   666     InstanceKlass* iklass = current_class();
   668     Method* m = iklass->find_method(_method_name, _method_signature);
   669     if (m != NULL) {
   670       if (_family == NULL) {
   671         _family = new StatefulMethodFamily();
   672       }
   674       if (iklass->is_interface()) {
   675         StateRestorer* restorer = _family->record_method_and_dq_further(m);
   676         scope->add_mark(restorer);
   677       } else {
   678         // This is the rule that methods in classes "win" (bad word) over
   679         // methods in interfaces. This works because of single inheritance
   680         _family->set_target_if_empty(m);
   681       }
   682     }
   683     return true;
   684   }
   686 };
   690 static void create_overpasses(
   691     GrowableArray<EmptyVtableSlot*>* slots, InstanceKlass* klass, TRAPS);
   693 static void generate_erased_defaults(
   694      InstanceKlass* klass, GrowableArray<EmptyVtableSlot*>* empty_slots,
   695      EmptyVtableSlot* slot, TRAPS) {
   697   // sets up a set of methods with the same exact erased signature
   698   FindMethodsByErasedSig visitor(slot->name(), slot->signature());
   699   visitor.run(klass);
   701   MethodFamily* family;
   702   visitor.get_discovered_family(&family);
   703   if (family != NULL) {
   704     family->determine_target(klass, CHECK);
   705     slot->bind_family(family);
   706   }
   707 }
   709 static void merge_in_new_methods(InstanceKlass* klass,
   710     GrowableArray<Method*>* new_methods, TRAPS);
   712 // This is the guts of the default methods implementation.  This is called just
   713 // after the classfile has been parsed if some ancestor has default methods.
   714 //
   715 // First if finds any name/signature slots that need any implementation (either
   716 // because they are miranda or a superclass's implementation is an overpass
   717 // itself).  For each slot, iterate over the hierarchy, to see if they contain a
   718 // signature that matches the slot we are looking at.
   719 //
   720 // For each slot filled, we generate an overpass method that either calls the
   721 // unique default method candidate using invokespecial, or throws an exception
   722 // (in the case of no default method candidates, or more than one valid
   723 // candidate).  These methods are then added to the class's method list.
   724 // The JVM does not create bridges nor handle generic signatures here.
   725 void DefaultMethods::generate_default_methods(
   726     InstanceKlass* klass, GrowableArray<Method*>* mirandas, TRAPS) {
   728   // This resource mark is the bound for all memory allocation that takes
   729   // place during default method processing.  After this goes out of scope,
   730   // all (Resource) objects' memory will be reclaimed.  Be careful if adding an
   731   // embedded resource mark under here as that memory can't be used outside
   732   // whatever scope it's in.
   733   ResourceMark rm(THREAD);
   735   // Keep entire hierarchy alive for the duration of the computation
   736   KeepAliveRegistrar keepAlive(THREAD);
   737   KeepAliveVisitor loadKeepAlive(&keepAlive);
   738   loadKeepAlive.run(klass);
   740 #ifndef PRODUCT
   741   if (TraceDefaultMethods) {
   742     ResourceMark rm;  // be careful with these!
   743     tty->print_cr("Class %s requires default method processing",
   744         klass->name()->as_klass_external_name());
   745     PrintHierarchy printer;
   746     printer.run(klass);
   747   }
   748 #endif // ndef PRODUCT
   750   GrowableArray<EmptyVtableSlot*>* empty_slots =
   751       find_empty_vtable_slots(klass, mirandas, CHECK);
   753   for (int i = 0; i < empty_slots->length(); ++i) {
   754     EmptyVtableSlot* slot = empty_slots->at(i);
   755 #ifndef PRODUCT
   756     if (TraceDefaultMethods) {
   757       streamIndentor si(tty, 2);
   758       tty->indent().print("Looking for default methods for slot ");
   759       slot->print_on(tty);
   760       tty->print_cr("");
   761     }
   762 #endif // ndef PRODUCT
   764     generate_erased_defaults(klass, empty_slots, slot, CHECK);
   765  }
   766 #ifndef PRODUCT
   767   if (TraceDefaultMethods) {
   768     tty->print_cr("Creating overpasses...");
   769   }
   770 #endif // ndef PRODUCT
   772   create_overpasses(empty_slots, klass, CHECK);
   774 #ifndef PRODUCT
   775   if (TraceDefaultMethods) {
   776     tty->print_cr("Default method processing complete");
   777   }
   778 #endif // ndef PRODUCT
   779 }
   781 /**
   782  * Interface inheritance rules were used to find a unique default method
   783  * candidate for the resolved class. This
   784  * method is only viable if it would also be in the set of default method
   785  * candidates if we ran a full analysis on the current class.
   786  *
   787  * The only reason that the method would not be in the set of candidates for
   788  * the current class is if that there's another matching method
   789  * which is "more specific" than the found method -- i.e., one could find a
   790  * path in the interface hierarchy in which the matching method appears
   791  * before we get to '_target'.
   792  *
   793  * In order to determine this, we examine all of the implemented
   794  * interfaces.  If we find path that leads to the '_target' interface, then
   795  * we examine that path to see if there are any methods that would shadow
   796  * the selected method along that path.
   797  */
   798 class ShadowChecker : public HierarchyVisitor<ShadowChecker> {
   799  protected:
   800   Thread* THREAD;
   802   InstanceKlass* _target;
   804   Symbol* _method_name;
   805   InstanceKlass* _method_holder;
   806   bool _found_shadow;
   809  public:
   811   ShadowChecker(Thread* thread, Symbol* name, InstanceKlass* holder,
   812                 InstanceKlass* target)
   813                 : THREAD(thread), _method_name(name), _method_holder(holder),
   814                 _target(target), _found_shadow(false) {}
   816   void* new_node_data(InstanceKlass* cls) { return NULL; }
   817   void free_node_data(void* data) { return; }
   819   bool visit() {
   820     InstanceKlass* ik = current_class();
   821     if (ik == _target && current_depth() == 1) {
   822       return false; // This was the specified super -- no need to search it
   823     }
   824     if (ik == _method_holder || ik == _target) {
   825       // We found a path that should be examined to see if it shadows _method
   826       if (path_has_shadow()) {
   827         _found_shadow = true;
   828         cancel_iteration();
   829       }
   830       return false; // no need to continue up hierarchy
   831     }
   832     return true;
   833   }
   835   virtual bool path_has_shadow() = 0;
   836   bool found_shadow() { return _found_shadow; }
   837 };
   839 // Used for Invokespecial.
   840 // Invokespecial is allowed to invoke a concrete interface method
   841 // and can be used to disambuiguate among qualified candidates,
   842 // which are methods in immediate superinterfaces,
   843 // but may not be used to invoke a candidate that would be shadowed
   844 // from the perspective of the caller.
   845 // Invokespecial is also used in the overpass generation today
   846 // We re-run the shadowchecker because we can't distinguish this case,
   847 // but it should return the same answer, since the overpass target
   848 // is now the invokespecial caller.
   849 class ErasedShadowChecker : public ShadowChecker {
   850  private:
   851   bool path_has_shadow() {
   853     for (int i = current_depth() - 1; i > 0; --i) {
   854       InstanceKlass* ik = class_at_depth(i);
   856       if (ik->is_interface()) {
   857         int end;
   858         int start = ik->find_method_by_name(_method_name, &end);
   859         if (start != -1) {
   860           return true;
   861         }
   862       }
   863     }
   864     return false;
   865   }
   866  public:
   868   ErasedShadowChecker(Thread* thread, Symbol* name, InstanceKlass* holder,
   869                 InstanceKlass* target)
   870     : ShadowChecker(thread, name, holder, target) {}
   871 };
   874 // Find the unique qualified candidate from the perspective of the super_class
   875 // which is the resolved_klass, which must be an immediate superinterface
   876 // of klass
   877 Method* find_erased_super_default(InstanceKlass* current_class, InstanceKlass* super_class, Symbol* method_name, Symbol* sig, TRAPS) {
   879   FindMethodsByErasedSig visitor(method_name, sig);
   880   visitor.run(super_class);      // find candidates from resolved_klass
   882   MethodFamily* family;
   883   visitor.get_discovered_family(&family);
   885   if (family != NULL) {
   886     family->determine_target(current_class, CHECK_NULL);  // get target from current_class
   887   }
   889   if (family->has_target()) {
   890     Method* target = family->get_selected_target();
   891     InstanceKlass* holder = InstanceKlass::cast(target->method_holder());
   893     // Verify that the identified method is valid from the context of
   894     // the current class, which is the caller class for invokespecial
   895     // link resolution, i.e. ensure there it is not shadowed.
   896     // You can use invokespecial to disambiguate interface methods, but
   897     // you can not use it to skip over an interface method that would shadow it.
   898     ErasedShadowChecker checker(THREAD, target->name(), holder, super_class);
   899     checker.run(current_class);
   901     if (checker.found_shadow()) {
   902 #ifndef PRODUCT
   903       if (TraceDefaultMethods) {
   904         tty->print_cr("    Only candidate found was shadowed.");
   905       }
   906 #endif // ndef PRODUCT
   907       THROW_MSG_(vmSymbols::java_lang_AbstractMethodError(),
   908                  "Accessible default method not found", NULL);
   909     } else {
   910 #ifndef PRODUCT
   911       if (TraceDefaultMethods) {
   912         family->print_sig_on(tty, target->signature(), 1);
   913       }
   914 #endif // ndef PRODUCT
   915       return target;
   916     }
   917   } else {
   918     assert(family->throws_exception(), "must have target or throw");
   919     THROW_MSG_(vmSymbols::java_lang_AbstractMethodError(),
   920                family->get_exception_message()->as_C_string(), NULL);
   921   }
   922 }
   924 // This is called during linktime when we find an invokespecial call that
   925 // refers to a direct superinterface.  It indicates that we should find the
   926 // default method in the hierarchy of that superinterface, and if that method
   927 // would have been a candidate from the point of view of 'this' class, then we
   928 // return that method.
   929 // This logic assumes that the super is a direct superclass of the caller
   930 Method* DefaultMethods::find_super_default(
   931     Klass* cls, Klass* super, Symbol* method_name, Symbol* sig, TRAPS) {
   933   ResourceMark rm(THREAD);
   935   assert(cls != NULL && super != NULL, "Need real classes");
   937   InstanceKlass* current_class = InstanceKlass::cast(cls);
   938   InstanceKlass* super_class = InstanceKlass::cast(super);
   940   // Keep entire hierarchy alive for the duration of the computation
   941   KeepAliveRegistrar keepAlive(THREAD);
   942   KeepAliveVisitor loadKeepAlive(&keepAlive);
   943   loadKeepAlive.run(current_class);   // get hierarchy from current class
   945 #ifndef PRODUCT
   946   if (TraceDefaultMethods) {
   947     tty->print_cr("Finding super default method %s.%s%s from %s",
   948       super_class->name()->as_C_string(),
   949       method_name->as_C_string(), sig->as_C_string(),
   950       current_class->name()->as_C_string());
   951   }
   952 #endif // ndef PRODUCT
   954   assert(super_class->is_interface(), "only call for default methods");
   956   Method* target = NULL;
   957   target = find_erased_super_default(current_class, super_class,
   958                                      method_name, sig, CHECK_NULL);
   960 #ifndef PRODUCT
   961   if (target != NULL) {
   962     if (TraceDefaultMethods) {
   963       tty->print("    Returning ");
   964       print_method(tty, target, true);
   965       tty->print_cr("");
   966     }
   967   }
   968 #endif // ndef PRODUCT
   969   return target;
   970 }
   972 #ifndef PRODUCT
   973 // Return true is broad type is a covariant return of narrow type
   974 static bool covariant_return_type(BasicType narrow, BasicType broad) {
   975   if (narrow == broad) {
   976     return true;
   977   }
   978   if (broad == T_OBJECT) {
   979     return true;
   980   }
   981   return false;
   982 }
   983 #endif // ndef PRODUCT
   985 static int assemble_redirect(
   986     BytecodeConstantPool* cp, BytecodeBuffer* buffer,
   987     Symbol* incoming, Method* target, TRAPS) {
   989   BytecodeAssembler assem(buffer, cp);
   991   SignatureStream in(incoming, true);
   992   SignatureStream out(target->signature(), true);
   993   u2 parameter_count = 0;
   995   assem.aload(parameter_count++); // load 'this'
   997   while (!in.at_return_type()) {
   998     assert(!out.at_return_type(), "Parameter counts do not match");
   999     BasicType bt = in.type();
  1000     assert(out.type() == bt, "Parameter types are not compatible");
  1001     assem.load(bt, parameter_count);
  1002     if (in.is_object() && in.as_symbol(THREAD) != out.as_symbol(THREAD)) {
  1003       assem.checkcast(out.as_symbol(THREAD));
  1004     } else if (bt == T_LONG || bt == T_DOUBLE) {
  1005       ++parameter_count; // longs and doubles use two slots
  1007     ++parameter_count;
  1008     in.next();
  1009     out.next();
  1011   assert(out.at_return_type(), "Parameter counts do not match");
  1012   assert(covariant_return_type(out.type(), in.type()), "Return types are not compatible");
  1014   if (parameter_count == 1 && (in.type() == T_LONG || in.type() == T_DOUBLE)) {
  1015     ++parameter_count; // need room for return value
  1017   if (target->method_holder()->is_interface()) {
  1018     assem.invokespecial(target);
  1019   } else {
  1020     assem.invokevirtual(target);
  1023   if (in.is_object() && in.as_symbol(THREAD) != out.as_symbol(THREAD)) {
  1024     assem.checkcast(in.as_symbol(THREAD));
  1026   assem._return(in.type());
  1027   return parameter_count;
  1030 static int assemble_abstract_method_error(
  1031     BytecodeConstantPool* cp, BytecodeBuffer* buffer, Symbol* message, TRAPS) {
  1033   Symbol* errorName = vmSymbols::java_lang_AbstractMethodError();
  1034   Symbol* init = vmSymbols::object_initializer_name();
  1035   Symbol* sig = vmSymbols::string_void_signature();
  1037   BytecodeAssembler assem(buffer, cp);
  1039   assem._new(errorName);
  1040   assem.dup();
  1041   assem.load_string(message);
  1042   assem.invokespecial(errorName, init, sig);
  1043   assem.athrow();
  1045   return 3; // max stack size: [ exception, exception, string ]
  1048 static Method* new_method(
  1049     BytecodeConstantPool* cp, BytecodeBuffer* bytecodes, Symbol* name,
  1050     Symbol* sig, AccessFlags flags, int max_stack, int params,
  1051     ConstMethod::MethodType mt, TRAPS) {
  1053   address code_start = 0;
  1054   int code_length = 0;
  1055   InlineTableSizes sizes;
  1057   if (bytecodes != NULL && bytecodes->length() > 0) {
  1058     code_start = static_cast<address>(bytecodes->adr_at(0));
  1059     code_length = bytecodes->length();
  1062   Method* m = Method::allocate(cp->pool_holder()->class_loader_data(),
  1063                                code_length, flags, &sizes,
  1064                                mt, CHECK_NULL);
  1066   m->set_constants(NULL); // This will get filled in later
  1067   m->set_name_index(cp->utf8(name));
  1068   m->set_signature_index(cp->utf8(sig));
  1069 #ifdef CC_INTERP
  1070   ResultTypeFinder rtf(sig);
  1071   m->set_result_index(rtf.type());
  1072 #endif
  1073   m->set_size_of_parameters(params);
  1074   m->set_max_stack(max_stack);
  1075   m->set_max_locals(params);
  1076   m->constMethod()->set_stackmap_data(NULL);
  1077   m->set_code(code_start);
  1078   m->set_force_inline(true);
  1080   return m;
  1083 static void switchover_constant_pool(BytecodeConstantPool* bpool,
  1084     InstanceKlass* klass, GrowableArray<Method*>* new_methods, TRAPS) {
  1086   if (new_methods->length() > 0) {
  1087     ConstantPool* cp = bpool->create_constant_pool(CHECK);
  1088     if (cp != klass->constants()) {
  1089       klass->class_loader_data()->add_to_deallocate_list(klass->constants());
  1090       klass->set_constants(cp);
  1091       cp->set_pool_holder(klass);
  1093       for (int i = 0; i < new_methods->length(); ++i) {
  1094         new_methods->at(i)->set_constants(cp);
  1096       for (int i = 0; i < klass->methods()->length(); ++i) {
  1097         Method* mo = klass->methods()->at(i);
  1098         mo->set_constants(cp);
  1104 // A "bridge" is a method created by javac to bridge the gap between
  1105 // an implementation and a generically-compatible, but different, signature.
  1106 // Bridges have actual bytecode implementation in classfiles.
  1107 // An "overpass", on the other hand, performs the same function as a bridge
  1108 // but does not occur in a classfile; the VM creates overpass itself,
  1109 // when it needs a path to get from a call site to an default method, and
  1110 // a bridge doesn't exist.
  1111 static void create_overpasses(
  1112     GrowableArray<EmptyVtableSlot*>* slots,
  1113     InstanceKlass* klass, TRAPS) {
  1115   GrowableArray<Method*> overpasses;
  1116   BytecodeConstantPool bpool(klass->constants());
  1118   for (int i = 0; i < slots->length(); ++i) {
  1119     EmptyVtableSlot* slot = slots->at(i);
  1121     if (slot->is_bound()) {
  1122       MethodFamily* method = slot->get_binding();
  1123       int max_stack = 0;
  1124       BytecodeBuffer buffer;
  1126 #ifndef PRODUCT
  1127       if (TraceDefaultMethods) {
  1128         tty->print("for slot: ");
  1129         slot->print_on(tty);
  1130         tty->print_cr("");
  1131         if (method->has_target()) {
  1132           method->print_selected(tty, 1);
  1133         } else {
  1134           method->print_exception(tty, 1);
  1137 #endif // ndef PRODUCT
  1138       if (method->has_target()) {
  1139         Method* selected = method->get_selected_target();
  1140         max_stack = assemble_redirect(
  1141             &bpool, &buffer, slot->signature(), selected, CHECK);
  1142       } else if (method->throws_exception()) {
  1143         max_stack = assemble_abstract_method_error(
  1144             &bpool, &buffer, method->get_exception_message(), CHECK);
  1146       AccessFlags flags = accessFlags_from(
  1147           JVM_ACC_PUBLIC | JVM_ACC_SYNTHETIC | JVM_ACC_BRIDGE);
  1148       Method* m = new_method(&bpool, &buffer, slot->name(), slot->signature(),
  1149           flags, max_stack, slot->size_of_parameters(),
  1150           ConstMethod::OVERPASS, CHECK);
  1151       if (m != NULL) {
  1152         overpasses.push(m);
  1157 #ifndef PRODUCT
  1158   if (TraceDefaultMethods) {
  1159     tty->print_cr("Created %d overpass methods", overpasses.length());
  1161 #endif // ndef PRODUCT
  1163   switchover_constant_pool(&bpool, klass, &overpasses, CHECK);
  1164   merge_in_new_methods(klass, &overpasses, CHECK);
  1167 static void sort_methods(GrowableArray<Method*>* methods) {
  1168   // Note that this must sort using the same key as is used for sorting
  1169   // methods in InstanceKlass.
  1170   bool sorted = true;
  1171   for (int i = methods->length() - 1; i > 0; --i) {
  1172     for (int j = 0; j < i; ++j) {
  1173       Method* m1 = methods->at(j);
  1174       Method* m2 = methods->at(j + 1);
  1175       if ((uintptr_t)m1->name() > (uintptr_t)m2->name()) {
  1176         methods->at_put(j, m2);
  1177         methods->at_put(j + 1, m1);
  1178         sorted = false;
  1181     if (sorted) break;
  1182     sorted = true;
  1184 #ifdef ASSERT
  1185   uintptr_t prev = 0;
  1186   for (int i = 0; i < methods->length(); ++i) {
  1187     Method* mh = methods->at(i);
  1188     uintptr_t nv = (uintptr_t)mh->name();
  1189     assert(nv >= prev, "Incorrect overpass method ordering");
  1190     prev = nv;
  1192 #endif
  1195 static void merge_in_new_methods(InstanceKlass* klass,
  1196     GrowableArray<Method*>* new_methods, TRAPS) {
  1198   enum { ANNOTATIONS, PARAMETERS, DEFAULTS, NUM_ARRAYS };
  1200   Array<Method*>* original_methods = klass->methods();
  1201   Array<int>* original_ordering = klass->method_ordering();
  1202   Array<int>* merged_ordering = Universe::the_empty_int_array();
  1204   int new_size = klass->methods()->length() + new_methods->length();
  1206   Array<Method*>* merged_methods = MetadataFactory::new_array<Method*>(
  1207       klass->class_loader_data(), new_size, NULL, CHECK);
  1209   if (original_ordering != NULL && original_ordering->length() > 0) {
  1210     merged_ordering = MetadataFactory::new_array<int>(
  1211         klass->class_loader_data(), new_size, CHECK);
  1213   int method_order_index = klass->methods()->length();
  1215   sort_methods(new_methods);
  1217   // Perform grand merge of existing methods and new methods
  1218   int orig_idx = 0;
  1219   int new_idx = 0;
  1221   for (int i = 0; i < new_size; ++i) {
  1222     Method* orig_method = NULL;
  1223     Method* new_method = NULL;
  1224     if (orig_idx < original_methods->length()) {
  1225       orig_method = original_methods->at(orig_idx);
  1227     if (new_idx < new_methods->length()) {
  1228       new_method = new_methods->at(new_idx);
  1231     if (orig_method != NULL &&
  1232         (new_method == NULL || orig_method->name() < new_method->name())) {
  1233       merged_methods->at_put(i, orig_method);
  1234       original_methods->at_put(orig_idx, NULL);
  1235       if (merged_ordering->length() > 0) {
  1236         merged_ordering->at_put(i, original_ordering->at(orig_idx));
  1238       ++orig_idx;
  1239     } else {
  1240       merged_methods->at_put(i, new_method);
  1241       if (merged_ordering->length() > 0) {
  1242         merged_ordering->at_put(i, method_order_index++);
  1244       ++new_idx;
  1246     // update idnum for new location
  1247     merged_methods->at(i)->set_method_idnum(i);
  1250   // Verify correct order
  1251 #ifdef ASSERT
  1252   uintptr_t prev = 0;
  1253   for (int i = 0; i < merged_methods->length(); ++i) {
  1254     Method* mo = merged_methods->at(i);
  1255     uintptr_t nv = (uintptr_t)mo->name();
  1256     assert(nv >= prev, "Incorrect method ordering");
  1257     prev = nv;
  1259 #endif
  1261   // Replace klass methods with new merged lists
  1262   klass->set_methods(merged_methods);
  1263   klass->set_initial_method_idnum(new_size);
  1265   ClassLoaderData* cld = klass->class_loader_data();
  1266   MetadataFactory::free_array(cld, original_methods);
  1267   if (original_ordering->length() > 0) {
  1268     klass->set_method_ordering(merged_ordering);
  1269     MetadataFactory::free_array(cld, original_ordering);

mercurial