1 /*
   2  * Copyright (c) 2012, 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 #include "precompiled.hpp"
  26 #include "classfile/bytecodeAssembler.hpp"
  27 #include "classfile/defaultMethods.hpp"
  28 #include "classfile/genericSignatures.hpp"
  29 #include "classfile/symbolTable.hpp"
  30 #include "memory/allocation.hpp"
  31 #include "memory/metadataFactory.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "runtime/signature.hpp"
  34 #include "runtime/thread.hpp"
  35 #include "oops/instanceKlass.hpp"
  36 #include "oops/klass.hpp"
  37 #include "oops/method.hpp"
  38 #include "utilities/accessFlags.hpp"
  39 #include "utilities/exceptions.hpp"
  40 #include "utilities/ostream.hpp"
  41 #include "utilities/pair.hpp"
  42 #include "utilities/resourceHash.hpp"
  43 
  44 typedef enum { QUALIFIED, DISQUALIFIED } QualifiedState;
  45 
  46 // Because we use an iterative algorithm when iterating over the type
  47 // hierarchy, we can't use traditional scoped objects which automatically do
  48 // cleanup in the destructor when the scope is exited.  PseudoScope (and
  49 // PseudoScopeMark) provides a similar functionality, but for when you want a
  50 // scoped object in non-stack memory (such as in resource memory, as we do
  51 // here).  You've just got to remember to call 'destroy()' on the scope when
  52 // leaving it (and marks have to be explicitly added).
  53 class PseudoScopeMark : public ResourceObj {
  54  public:
  55   virtual void destroy() = 0;
  56 };
  57 
  58 class PseudoScope : public ResourceObj {
  59  private:
  60   GrowableArray<PseudoScopeMark*> _marks;
  61  public:
  62 
  63   static PseudoScope* cast(void* data) {
  64     return static_cast<PseudoScope*>(data);
  65   }
  66 
  67   void add_mark(PseudoScopeMark* psm) {
  68    _marks.append(psm);
  69   }
  70 
  71   void destroy() {
  72     for (int i = 0; i < _marks.length(); ++i) {
  73       _marks.at(i)->destroy();
  74     }
  75   }
  76 };
  77 
  78 class ContextMark : public PseudoScopeMark {
  79  private:
  80   generic::Context::Mark _mark;
  81  public:
  82   ContextMark(const generic::Context::Mark& cm) : _mark(cm) {}
  83   virtual void destroy() { _mark.destroy(); }
  84 };
  85 
  86 #ifndef PRODUCT
  87 static void print_slot(outputStream* str, Symbol* name, Symbol* signature) {
  88   ResourceMark rm;
  89   str->print("%s%s", name->as_C_string(), signature->as_C_string());
  90 }
  91 
  92 static void print_method(outputStream* str, Method* mo, bool with_class=true) {
  93   ResourceMark rm;
  94   if (with_class) {
  95     str->print("%s.", mo->klass_name()->as_C_string());
  96   }
  97   print_slot(str, mo->name(), mo->signature());
  98 }
  99 #endif // ndef PRODUCT
 100 
 101 /**
 102  * Perform a depth-first iteration over the class hierarchy, applying
 103  * algorithmic logic as it goes.
 104  *
 105  * This class is one half of the inheritance hierarchy analysis mechanism.
 106  * It is meant to be used in conjunction with another class, the algorithm,
 107  * which is indicated by the ALGO template parameter.  This class can be
 108  * paired with any algorithm class that provides the required methods.
 109  *
 110  * This class contains all the mechanics for iterating over the class hierarchy
 111  * starting at a particular root, without recursing (thus limiting stack growth
 112  * from this point).  It visits each superclass (if present) and superinterface
 113  * in a depth-first manner, with callbacks to the ALGO class as each class is
 114  * encountered (visit()), The algorithm can cut-off further exploration of a
 115  * particular branch by returning 'false' from a visit() call.
 116  *
 117  * The ALGO class, must provide a visit() method, which each of which will be
 118  * called once for each node in the inheritance tree during the iteration.  In
 119  * addition, it can provide a memory block via new_node_data(InstanceKlass*),
 120  * which it can use for node-specific storage (and access via the
 121  * current_data() and data_at_depth(int) methods).
 122  *
 123  * Bare minimum needed to be an ALGO class:
 124  * class Algo : public HierarchyVisitor<Algo> {
 125  *   void* new_node_data(InstanceKlass* cls) { return NULL; }
 126  *   void free_node_data(void* data) { return; }
 127  *   bool visit() { return true; }
 128  * };
 129  */
 130 template <class ALGO>
 131 class HierarchyVisitor : StackObj {
 132  private:
 133 
 134   class Node : public ResourceObj {
 135    public:
 136     InstanceKlass* _class;
 137     bool _super_was_visited;
 138     int _interface_index;
 139     void* _algorithm_data;
 140 
 141     Node(InstanceKlass* cls, void* data, bool visit_super)
 142         : _class(cls), _super_was_visited(!visit_super),
 143           _interface_index(0), _algorithm_data(data) {}
 144 
 145     int number_of_interfaces() { return _class->local_interfaces()->length(); }
 146     int interface_index() { return _interface_index; }
 147     void set_super_visited() { _super_was_visited = true; }
 148     void increment_visited_interface() { ++_interface_index; }
 149     void set_all_interfaces_visited() {
 150       _interface_index = number_of_interfaces();
 151     }
 152     bool has_visited_super() { return _super_was_visited; }
 153     bool has_visited_all_interfaces() {
 154       return interface_index() >= number_of_interfaces();
 155     }
 156     InstanceKlass* interface_at(int index) {
 157       return InstanceKlass::cast(_class->local_interfaces()->at(index));
 158     }
 159     InstanceKlass* next_super() { return _class->java_super(); }
 160     InstanceKlass* next_interface() {
 161       return interface_at(interface_index());
 162     }
 163   };
 164 
 165   bool _cancelled;
 166   GrowableArray<Node*> _path;
 167 
 168   Node* current_top() const { return _path.top(); }
 169   bool has_more_nodes() const { return !_path.is_empty(); }
 170   void push(InstanceKlass* cls, void* data) {
 171     assert(cls != NULL, "Requires a valid instance class");
 172     Node* node = new Node(cls, data, has_super(cls));
 173     _path.push(node);
 174   }
 175   void pop() { _path.pop(); }
 176 
 177   void reset_iteration() {
 178     _cancelled = false;
 179     _path.clear();
 180   }
 181   bool is_cancelled() const { return _cancelled; }
 182 
 183   static bool has_super(InstanceKlass* cls) {
 184     return cls->super() != NULL && !cls->is_interface();
 185   }
 186 
 187   Node* node_at_depth(int i) const {
 188     return (i >= _path.length()) ? NULL : _path.at(_path.length() - i - 1);
 189   }
 190 
 191  protected:
 192 
 193   // Accessors available to the algorithm
 194   int current_depth() const { return _path.length() - 1; }
 195 
 196   InstanceKlass* class_at_depth(int i) {
 197     Node* n = node_at_depth(i);
 198     return n == NULL ? NULL : n->_class;
 199   }
 200   InstanceKlass* current_class() { return class_at_depth(0); }
 201 
 202   void* data_at_depth(int i) {
 203     Node* n = node_at_depth(i);
 204     return n == NULL ? NULL : n->_algorithm_data;
 205   }
 206   void* current_data() { return data_at_depth(0); }
 207 
 208   void cancel_iteration() { _cancelled = true; }
 209 
 210  public:
 211 
 212   void run(InstanceKlass* root) {
 213     ALGO* algo = static_cast<ALGO*>(this);
 214 
 215     reset_iteration();
 216 
 217     void* algo_data = algo->new_node_data(root);
 218     push(root, algo_data);
 219     bool top_needs_visit = true;
 220 
 221     do {
 222       Node* top = current_top();
 223       if (top_needs_visit) {
 224         if (algo->visit() == false) {
 225           // algorithm does not want to continue along this path.  Arrange
 226           // it so that this state is immediately popped off the stack
 227           top->set_super_visited();
 228           top->set_all_interfaces_visited();
 229         }
 230         top_needs_visit = false;
 231       }
 232 
 233       if (top->has_visited_super() && top->has_visited_all_interfaces()) {
 234         algo->free_node_data(top->_algorithm_data);
 235         pop();
 236       } else {
 237         InstanceKlass* next = NULL;
 238         if (top->has_visited_super() == false) {
 239           next = top->next_super();
 240           top->set_super_visited();
 241         } else {
 242           next = top->next_interface();
 243           top->increment_visited_interface();
 244         }
 245         assert(next != NULL, "Otherwise we shouldn't be here");
 246         algo_data = algo->new_node_data(next);
 247         push(next, algo_data);
 248         top_needs_visit = true;
 249       }
 250     } while (!is_cancelled() && has_more_nodes());
 251   }
 252 };
 253 
 254 #ifndef PRODUCT
 255 class PrintHierarchy : public HierarchyVisitor<PrintHierarchy> {
 256  public:
 257 
 258   bool visit() {
 259     InstanceKlass* cls = current_class();
 260     streamIndentor si(tty, current_depth() * 2);
 261     tty->indent().print_cr("%s", cls->name()->as_C_string());
 262     return true;
 263   }
 264 
 265   void* new_node_data(InstanceKlass* cls) { return NULL; }
 266   void free_node_data(void* data) { return; }
 267 };
 268 #endif // ndef PRODUCT
 269 
 270 // Used to register InstanceKlass objects and all related metadata structures
 271 // (Methods, ConstantPools) as "in-use" by the current thread so that they can't
 272 // be deallocated by class redefinition while we're using them.  The classes are
 273 // de-registered when this goes out of scope.
 274 //
 275 // Once a class is registered, we need not bother with methodHandles or
 276 // constantPoolHandles for it's associated metadata.
 277 class KeepAliveRegistrar : public StackObj {
 278  private:
 279   Thread* _thread;
 280   GrowableArray<ConstantPool*> _keep_alive;
 281 
 282  public:
 283   KeepAliveRegistrar(Thread* thread) : _thread(thread), _keep_alive(20) {
 284     assert(thread == Thread::current(), "Must be current thread");
 285   }
 286 
 287   ~KeepAliveRegistrar() {
 288     for (int i = _keep_alive.length() - 1; i >= 0; --i) {
 289       ConstantPool* cp = _keep_alive.at(i);
 290       int idx = _thread->metadata_handles()->find_from_end(cp);
 291       assert(idx > 0, "Must be in the list");
 292       _thread->metadata_handles()->remove_at(idx);
 293     }
 294   }
 295 
 296   // Register a class as 'in-use' by the thread.  It's fine to register a class
 297   // multiple times (though perhaps inefficient)
 298   void register_class(InstanceKlass* ik) {
 299     ConstantPool* cp = ik->constants();
 300     _keep_alive.push(cp);
 301     _thread->metadata_handles()->push(cp);
 302   }
 303 };
 304 
 305 class KeepAliveVisitor : public HierarchyVisitor<KeepAliveVisitor> {
 306  private:
 307   KeepAliveRegistrar* _registrar;
 308 
 309  public:
 310   KeepAliveVisitor(KeepAliveRegistrar* registrar) : _registrar(registrar) {}
 311 
 312   void* new_node_data(InstanceKlass* cls) { return NULL; }
 313   void free_node_data(void* data) { return; }
 314 
 315   bool visit() {
 316     _registrar->register_class(current_class());
 317     return true;
 318   }
 319 };
 320 
 321 // A method family contains a set of all methods that implement a single
 322 // language-level method.  Because of erasure, these methods may have different
 323 // signatures.  As members of the set are collected while walking over the
 324 // hierarchy, they are tagged with a qualification state.  The qualification
 325 // state for an erased method is set to disqualified if there exists a path
 326 // from the root of hierarchy to the method that contains an interleaving
 327 // language-equivalent method defined in an interface.
 328 class MethodFamily : public ResourceObj {
 329  private:
 330 
 331   generic::MethodDescriptor* _descriptor; // language-level description
 332   GrowableArray<Pair<Method*,QualifiedState> > _members;
 333   ResourceHashtable<Method*, int> _member_index;
 334 
 335   Method* _selected_target;  // Filled in later, if a unique target exists
 336   Symbol* _exception_message; // If no unique target is found
 337 
 338   bool contains_method(Method* method) {
 339     int* lookup = _member_index.get(method);
 340     return lookup != NULL;
 341   }
 342 
 343   void add_method(Method* method, QualifiedState state) {
 344     Pair<Method*,QualifiedState> entry(method, state);
 345     _member_index.put(method, _members.length());
 346     _members.append(entry);
 347   }
 348 
 349   void disqualify_method(Method* method) {
 350     int* index = _member_index.get(method);
 351     assert(index != NULL && *index >= 0 && *index < _members.length(), "bad index");
 352     _members.at(*index).second = DISQUALIFIED;
 353   }
 354 
 355   Symbol* generate_no_defaults_message(TRAPS) const;
 356   Symbol* generate_abstract_method_message(Method* method, TRAPS) const;
 357   Symbol* generate_conflicts_message(GrowableArray<Method*>* methods, TRAPS) const;
 358 
 359  public:
 360 
 361   MethodFamily(generic::MethodDescriptor* canonical_desc)
 362       : _descriptor(canonical_desc), _selected_target(NULL),
 363         _exception_message(NULL) {}
 364 
 365   generic::MethodDescriptor* descriptor() const { return _descriptor; }
 366 
 367   bool descriptor_matches(generic::MethodDescriptor* md, generic::Context* ctx) {
 368     return descriptor()->covariant_match(md, ctx);
 369   }
 370 
 371   void set_target_if_empty(Method* m) {
 372     if (_selected_target == NULL && !m->is_overpass()) {
 373       _selected_target = m;
 374     }
 375   }
 376 
 377   void record_qualified_method(Method* m) {
 378     // If the method already exists in the set as qualified, this operation is
 379     // redundant.  If it already exists as disqualified, then we leave it as
 380     // disqualfied.  Thus we only add to the set if it's not already in the
 381     // set.
 382     if (!contains_method(m)) {
 383       add_method(m, QUALIFIED);
 384     }
 385   }
 386 
 387   void record_disqualified_method(Method* m) {
 388     // If not in the set, add it as disqualified.  If it's already in the set,
 389     // then set the state to disqualified no matter what the previous state was.
 390     if (!contains_method(m)) {
 391       add_method(m, DISQUALIFIED);
 392     } else {
 393       disqualify_method(m);
 394     }
 395   }
 396 
 397   bool has_target() const { return _selected_target != NULL; }
 398   bool throws_exception() { return _exception_message != NULL; }
 399 
 400   Method* get_selected_target() { return _selected_target; }
 401   Symbol* get_exception_message() { return _exception_message; }
 402 
 403   // Either sets the target or the exception error message
 404   void determine_target(InstanceKlass* root, TRAPS) {
 405     if (has_target() || throws_exception()) {
 406       return;
 407     }
 408 
 409     GrowableArray<Method*> qualified_methods;
 410     for (int i = 0; i < _members.length(); ++i) {
 411       Pair<Method*,QualifiedState> entry = _members.at(i);
 412       if (entry.second == QUALIFIED) {
 413         qualified_methods.append(entry.first);
 414       }
 415     }
 416 
 417     if (qualified_methods.length() == 0) {
 418       _exception_message = generate_no_defaults_message(CHECK);
 419     } else if (qualified_methods.length() == 1) {
 420       Method* method = qualified_methods.at(0);
 421       if (method->is_abstract()) {
 422         _exception_message = generate_abstract_method_message(method, CHECK);
 423       } else {
 424         _selected_target = qualified_methods.at(0);
 425       }
 426     } else {
 427       _exception_message = generate_conflicts_message(&qualified_methods,CHECK);
 428     }
 429 
 430     assert((has_target() ^ throws_exception()) == 1,
 431            "One and only one must be true");
 432   }
 433 
 434   bool contains_signature(Symbol* query) {
 435     for (int i = 0; i < _members.length(); ++i) {
 436       if (query == _members.at(i).first->signature()) {
 437         return true;
 438       }
 439     }
 440     return false;
 441   }
 442 
 443 #ifndef PRODUCT
 444   void print_on(outputStream* str) const {
 445     print_on(str, 0);
 446   }
 447 
 448   void print_on(outputStream* str, int indent) const {
 449     streamIndentor si(str, indent * 2);
 450 
 451     generic::Context ctx(NULL); // empty, as _descriptor already canonicalized
 452     TempNewSymbol family = descriptor()->reify_signature(&ctx, Thread::current());
 453     str->indent().print_cr("Logical Method %s:", family->as_C_string());
 454 
 455     streamIndentor si2(str);
 456     for (int i = 0; i < _members.length(); ++i) {
 457       str->indent();
 458       print_method(str, _members.at(i).first);
 459       if (_members.at(i).second == DISQUALIFIED) {
 460         str->print(" (disqualified)");
 461       }
 462       str->print_cr("");
 463     }
 464 
 465     if (_selected_target != NULL) {
 466       print_selected(str, 1);
 467     }
 468   }
 469 
 470   void print_selected(outputStream* str, int indent) const {
 471     assert(has_target(), "Should be called otherwise");
 472     streamIndentor si(str, indent * 2);
 473     str->indent().print("Selected method: ");
 474     print_method(str, _selected_target);
 475     str->print_cr("");
 476   }
 477 
 478   void print_exception(outputStream* str, int indent) {
 479     assert(throws_exception(), "Should be called otherwise");
 480     streamIndentor si(str, indent * 2);
 481     str->indent().print_cr("%s", _exception_message->as_C_string());
 482   }
 483 #endif // ndef PRODUCT
 484 };
 485 
 486 Symbol* MethodFamily::generate_no_defaults_message(TRAPS) const {
 487   return SymbolTable::new_symbol("No qualifying defaults found", CHECK_NULL);
 488 }
 489 
 490 Symbol* MethodFamily::generate_abstract_method_message(Method* method, TRAPS) const {
 491   Symbol* klass = method->klass_name();
 492   Symbol* name = method->name();
 493   Symbol* sig = method->signature();
 494   stringStream ss;
 495   ss.print("Method ");
 496   ss.write((const char*)klass->bytes(), klass->utf8_length());
 497   ss.print(".");
 498   ss.write((const char*)name->bytes(), name->utf8_length());
 499   ss.write((const char*)sig->bytes(), sig->utf8_length());
 500   ss.print(" is abstract");
 501   return SymbolTable::new_symbol(ss.base(), (int)ss.size(), CHECK_NULL);
 502 }
 503 
 504 Symbol* MethodFamily::generate_conflicts_message(GrowableArray<Method*>* methods, TRAPS) const {
 505   stringStream ss;
 506   ss.print("Conflicting default methods:");
 507   for (int i = 0; i < methods->length(); ++i) {
 508     Method* method = methods->at(i);
 509     Symbol* klass = method->klass_name();
 510     Symbol* name = method->name();
 511     ss.print(" ");
 512     ss.write((const char*)klass->bytes(), klass->utf8_length());
 513     ss.print(".");
 514     ss.write((const char*)name->bytes(), name->utf8_length());
 515   }
 516   return SymbolTable::new_symbol(ss.base(), (int)ss.size(), CHECK_NULL);
 517 }
 518 
 519 class StateRestorer;
 520 
 521 // StatefulMethodFamily is a wrapper around MethodFamily that maintains the
 522 // qualification state during hierarchy visitation, and applies that state
 523 // when adding members to the MethodFamily.
 524 class StatefulMethodFamily : public ResourceObj {
 525   friend class StateRestorer;
 526  private:
 527   MethodFamily* _method;
 528   QualifiedState _qualification_state;
 529 
 530   void set_qualification_state(QualifiedState state) {
 531     _qualification_state = state;
 532   }
 533 
 534  public:
 535   StatefulMethodFamily(generic::MethodDescriptor* md, generic::Context* ctx) {
 536     _method = new MethodFamily(md->canonicalize(ctx));
 537     _qualification_state = QUALIFIED;
 538   }
 539 
 540   void set_target_if_empty(Method* m) { _method->set_target_if_empty(m); }
 541 
 542   MethodFamily* get_method_family() { return _method; }
 543 
 544   bool descriptor_matches(generic::MethodDescriptor* md, generic::Context* ctx) {
 545     return _method->descriptor_matches(md, ctx);
 546   }
 547 
 548   StateRestorer* record_method_and_dq_further(Method* mo);
 549 };
 550 
 551 class StateRestorer : public PseudoScopeMark {
 552  private:
 553   StatefulMethodFamily* _method;
 554   QualifiedState _state_to_restore;
 555  public:
 556   StateRestorer(StatefulMethodFamily* dm, QualifiedState state)
 557       : _method(dm), _state_to_restore(state) {}
 558   ~StateRestorer() { destroy(); }
 559   void restore_state() { _method->set_qualification_state(_state_to_restore); }
 560   virtual void destroy() { restore_state(); }
 561 };
 562 
 563 StateRestorer* StatefulMethodFamily::record_method_and_dq_further(Method* mo) {
 564   StateRestorer* mark = new StateRestorer(this, _qualification_state);
 565   if (_qualification_state == QUALIFIED) {
 566     _method->record_qualified_method(mo);
 567   } else {
 568     _method->record_disqualified_method(mo);
 569   }
 570   // Everything found "above"??? this method in the hierarchy walk is set to
 571   // disqualified
 572   set_qualification_state(DISQUALIFIED);
 573   return mark;
 574 }
 575 
 576 class StatefulMethodFamilies : public ResourceObj {
 577  private:
 578   GrowableArray<StatefulMethodFamily*> _methods;
 579 
 580  public:
 581   StatefulMethodFamily* find_matching(
 582       generic::MethodDescriptor* md, generic::Context* ctx) {
 583     for (int i = 0; i < _methods.length(); ++i) {
 584       StatefulMethodFamily* existing = _methods.at(i);
 585       if (existing->descriptor_matches(md, ctx)) {
 586         return existing;
 587       }
 588     }
 589     return NULL;
 590   }
 591 
 592   StatefulMethodFamily* find_matching_or_create(
 593       generic::MethodDescriptor* md, generic::Context* ctx) {
 594     StatefulMethodFamily* method = find_matching(md, ctx);
 595     if (method == NULL) {
 596       method = new StatefulMethodFamily(md, ctx);
 597       _methods.append(method);
 598     }
 599     return method;
 600   }
 601 
 602   void extract_families_into(GrowableArray<MethodFamily*>* array) {
 603     for (int i = 0; i < _methods.length(); ++i) {
 604       array->append(_methods.at(i)->get_method_family());
 605     }
 606   }
 607 };
 608 
 609 // Represents a location corresponding to a vtable slot for methods that
 610 // neither the class nor any of it's ancestors provide an implementaion.
 611 // Default methods may be present to fill this slot.
 612 class EmptyVtableSlot : public ResourceObj {
 613  private:
 614   Symbol* _name;
 615   Symbol* _signature;
 616   int _size_of_parameters;
 617   MethodFamily* _binding;
 618 
 619  public:
 620   EmptyVtableSlot(Method* method)
 621       : _name(method->name()), _signature(method->signature()),
 622         _size_of_parameters(method->size_of_parameters()), _binding(NULL) {}
 623 
 624   Symbol* name() const { return _name; }
 625   Symbol* signature() const { return _signature; }
 626   int size_of_parameters() const { return _size_of_parameters; }
 627 
 628   void bind_family(MethodFamily* lm) { _binding = lm; }
 629   bool is_bound() { return _binding != NULL; }
 630   MethodFamily* get_binding() { return _binding; }
 631 
 632 #ifndef PRODUCT
 633   void print_on(outputStream* str) const {
 634     print_slot(str, name(), signature());
 635   }
 636 #endif // ndef PRODUCT
 637 };
 638 
 639 static GrowableArray<EmptyVtableSlot*>* find_empty_vtable_slots(
 640     InstanceKlass* klass, GrowableArray<Method*>* mirandas, TRAPS) {
 641 
 642   assert(klass != NULL, "Must be valid class");
 643 
 644   GrowableArray<EmptyVtableSlot*>* slots = new GrowableArray<EmptyVtableSlot*>();
 645 
 646   // All miranda methods are obvious candidates
 647   for (int i = 0; i < mirandas->length(); ++i) {
 648     EmptyVtableSlot* slot = new EmptyVtableSlot(mirandas->at(i));
 649     slots->append(slot);
 650   }
 651 
 652   // Also any overpasses in our superclasses, that we haven't implemented.
 653   // (can't use the vtable because it is not guaranteed to be initialized yet)
 654   InstanceKlass* super = klass->java_super();
 655   while (super != NULL) {
 656     for (int i = 0; i < super->methods()->length(); ++i) {
 657       Method* m = super->methods()->at(i);
 658       if (m->is_overpass()) {
 659         // m is a method that would have been a miranda if not for the
 660         // default method processing that occurred on behalf of our superclass,
 661         // so it's a method we want to re-examine in this new context.  That is,
 662         // unless we have a real implementation of it in the current class.
 663         Method* impl = klass->lookup_method(m->name(), m->signature());
 664         if (impl == NULL || impl->is_overpass()) {
 665           slots->append(new EmptyVtableSlot(m));
 666         }
 667       }
 668     }
 669     super = super->java_super();
 670   }
 671 
 672 #ifndef PRODUCT
 673   if (TraceDefaultMethods) {
 674     tty->print_cr("Slots that need filling:");
 675     streamIndentor si(tty);
 676     for (int i = 0; i < slots->length(); ++i) {
 677       tty->indent();
 678       slots->at(i)->print_on(tty);
 679       tty->print_cr("");
 680     }
 681   }
 682 #endif // ndef PRODUCT
 683   return slots;
 684 }
 685 
 686 // Iterates over the type hierarchy looking for all methods with a specific
 687 // method name.  The result of this is a set of method families each of
 688 // which is populated with a set of methods that implement the same
 689 // language-level signature.
 690 class FindMethodsByName : public HierarchyVisitor<FindMethodsByName> {
 691  private:
 692   // Context data
 693   Thread* THREAD;
 694   generic::DescriptorCache* _cache;
 695   Symbol* _method_name;
 696   generic::Context* _ctx;
 697   StatefulMethodFamilies _families;
 698 
 699  public:
 700 
 701   FindMethodsByName(generic::DescriptorCache* cache, Symbol* name,
 702       generic::Context* ctx, Thread* thread) :
 703     _cache(cache), _method_name(name), _ctx(ctx), THREAD(thread) {}
 704 
 705   void get_discovered_families(GrowableArray<MethodFamily*>* methods) {
 706     _families.extract_families_into(methods);
 707   }
 708 
 709   void* new_node_data(InstanceKlass* cls) { return new PseudoScope(); }
 710   void free_node_data(void* node_data) {
 711     PseudoScope::cast(node_data)->destroy();
 712   }
 713 
 714   bool visit() {
 715     PseudoScope* scope = PseudoScope::cast(current_data());
 716     InstanceKlass* klass = current_class();
 717     InstanceKlass* sub = current_depth() > 0 ? class_at_depth(1) : NULL;
 718 
 719     ContextMark* cm = new ContextMark(_ctx->mark());
 720     scope->add_mark(cm); // will restore context when scope is freed
 721 
 722     _ctx->apply_type_arguments(sub, klass, THREAD);
 723 
 724     // apply_type_arguments may result in a ClassCirculatoryError
 725     // exception while constructing a ClassDescriptor for klass. In
 726     // such a situation, it indicates that _method_name can not be
 727     // found in the hierarchy currently being traversed. Clear the
 728     // exception and return to continue.
 729     if (HAS_PENDING_EXCEPTION) {
 730       if (PENDING_EXCEPTION->klass()->name() == vmSymbols::java_lang_ClassCircularityError()) {
 731         CLEAR_PENDING_EXCEPTION;
 732         return true;
 733       }
 734     }
 735     
 736     int start, end = 0;
 737     start = klass->find_method_by_name(_method_name, &end);
 738     if (start != -1) {
 739       for (int i = start; i < end; ++i) {
 740         Method* m = klass->methods()->at(i);
 741         // This gets the method's parameter list with its generic type
 742         // parameters resolved
 743         generic::MethodDescriptor* md = _cache->descriptor_for(m, THREAD);
 744 
 745         // Attempt to get the class descriptor of the method may
 746         // result in a ClassCirculatoryError exception while
 747         // constructing a ClassDescriptor for the holder of m. In such
 748         // a situation, it indicates that m can not be found in the
 749         // hierarchy currently being traversed and md is NULL. Clear
 750         // the exception and return to continue.
 751 
 752         if (HAS_PENDING_EXCEPTION) {
 753           if (PENDING_EXCEPTION->klass()->name() == vmSymbols::java_lang_ClassCircularityError()) {
 754             CLEAR_PENDING_EXCEPTION;
 755             return true;
 756           }
 757         }
 758         // Find all methods on this hierarchy that match this method
 759         // (name, signature).   This class collects other families of this
 760         // method name.
 761         StatefulMethodFamily* family =
 762             _families.find_matching_or_create(md, _ctx);
 763 
 764         if (klass->is_interface()) {
 765           // ???
 766           StateRestorer* restorer = family->record_method_and_dq_further(m);
 767           scope->add_mark(restorer);
 768         } else {
 769           // This is the rule that methods in classes "win" (bad word) over
 770           // methods in interfaces.  This works because of single inheritance
 771           family->set_target_if_empty(m);
 772         }
 773       }
 774     }
 775     return true;
 776   }
 777 };
 778 
 779 #ifndef PRODUCT
 780 static void print_families(
 781     GrowableArray<MethodFamily*>* methods, Symbol* match) {
 782   streamIndentor si(tty, 4);
 783   if (methods->length() == 0) {
 784     tty->indent();
 785     tty->print_cr("No Logical Method found");
 786   }
 787   for (int i = 0; i < methods->length(); ++i) {
 788     tty->indent();
 789     MethodFamily* lm = methods->at(i);
 790     if (lm->contains_signature(match)) {
 791       tty->print_cr("<Matching>");
 792     } else {
 793       tty->print_cr("<Non-Matching>");
 794     }
 795     lm->print_on(tty, 1);
 796   }
 797 }
 798 #endif // ndef PRODUCT
 799 
 800 static void merge_in_new_methods(InstanceKlass* klass,
 801     GrowableArray<Method*>* new_methods, TRAPS);
 802 static void create_overpasses(
 803     GrowableArray<EmptyVtableSlot*>* slots, InstanceKlass* klass, TRAPS);
 804 
 805 // This is the guts of the default methods implementation.  This is called just
 806 // after the classfile has been parsed if some ancestor has default methods.
 807 //
 808 // First if finds any name/signature slots that need any implementation (either
 809 // because they are miranda or a superclass's implementation is an overpass
 810 // itself).  For each slot, iterate over the hierarchy, using generic signature
 811 // information to partition any methods that match the name into method families
 812 // where each family contains methods whose signatures are equivalent at the
 813 // language level (i.e., their reified parameters match and return values are
 814 // covariant). Check those sets to see if they contain a signature that matches
 815 // the slot we're looking at (if we're lucky, there might be other empty slots
 816 // that we can fill using the same analysis).
 817 //
 818 // For each slot filled, we generate an overpass method that either calls the
 819 // unique default method candidate using invokespecial, or throws an exception
 820 // (in the case of no default method candidates, or more than one valid
 821 // candidate).  These methods are then added to the class's method list.  If
 822 // the method set we're using contains methods (qualified or not) with a
 823 // different runtime signature than the method we're creating, then we have to
 824 // create bridges with those signatures too.
 825 void DefaultMethods::generate_default_methods(
 826     InstanceKlass* klass, GrowableArray<Method*>* mirandas, TRAPS) {
 827 
 828   // This resource mark is the bound for all memory allocation that takes
 829   // place during default method processing.  After this goes out of scope,
 830   // all (Resource) objects' memory will be reclaimed.  Be careful if adding an
 831   // embedded resource mark under here as that memory can't be used outside
 832   // whatever scope it's in.
 833   ResourceMark rm(THREAD);
 834 
 835   generic::DescriptorCache cache;
 836 
 837   // Keep entire hierarchy alive for the duration of the computation
 838   KeepAliveRegistrar keepAlive(THREAD);
 839   KeepAliveVisitor loadKeepAlive(&keepAlive);
 840   loadKeepAlive.run(klass);
 841 
 842 #ifndef PRODUCT
 843   if (TraceDefaultMethods) {
 844     ResourceMark rm;  // be careful with these!
 845     tty->print_cr("Class %s requires default method processing",
 846         klass->name()->as_klass_external_name());
 847     PrintHierarchy printer;
 848     printer.run(klass);
 849   }
 850 #endif // ndef PRODUCT
 851 
 852   GrowableArray<EmptyVtableSlot*>* empty_slots =
 853       find_empty_vtable_slots(klass, mirandas, CHECK);
 854 
 855   for (int i = 0; i < empty_slots->length(); ++i) {
 856     EmptyVtableSlot* slot = empty_slots->at(i);
 857 #ifndef PRODUCT
 858     if (TraceDefaultMethods) {
 859       streamIndentor si(tty, 2);
 860       tty->indent().print("Looking for default methods for slot ");
 861       slot->print_on(tty);
 862       tty->print_cr("");
 863     }
 864 #endif // ndef PRODUCT
 865     if (slot->is_bound()) {
 866 #ifndef PRODUCT
 867       if (TraceDefaultMethods) {
 868         streamIndentor si(tty, 4);
 869         tty->indent().print_cr("Already bound to logical method:");
 870         slot->get_binding()->print_on(tty, 1);
 871       }
 872 #endif // ndef PRODUCT
 873       continue; // covered by previous processing
 874     }
 875 
 876     generic::Context ctx(&cache);
 877     FindMethodsByName visitor(&cache, slot->name(), &ctx, CHECK);
 878     visitor.run(klass);
 879 
 880     GrowableArray<MethodFamily*> discovered_families;
 881     visitor.get_discovered_families(&discovered_families);
 882 
 883 #ifndef PRODUCT
 884     if (TraceDefaultMethods) {
 885       print_families(&discovered_families, slot->signature());
 886     }
 887 #endif // ndef PRODUCT
 888 
 889     // Find and populate any other slots that match the discovered families
 890     for (int j = i; j < empty_slots->length(); ++j) {
 891       EmptyVtableSlot* open_slot = empty_slots->at(j);
 892 
 893       if (slot->name() == open_slot->name()) {
 894         for (int k = 0; k < discovered_families.length(); ++k) {
 895           MethodFamily* lm = discovered_families.at(k);
 896 
 897           if (lm->contains_signature(open_slot->signature())) {
 898             lm->determine_target(klass, CHECK);
 899             open_slot->bind_family(lm);
 900           }
 901         }
 902       }
 903     }
 904   }
 905 
 906 #ifndef PRODUCT
 907   if (TraceDefaultMethods) {
 908     tty->print_cr("Creating overpasses...");
 909   }
 910 #endif // ndef PRODUCT
 911 
 912   create_overpasses(empty_slots, klass, CHECK);
 913 
 914 #ifndef PRODUCT
 915   if (TraceDefaultMethods) {
 916     tty->print_cr("Default method processing complete");
 917   }
 918 #endif // ndef PRODUCT
 919 }
 920 
 921 
 922 /**
 923  * Generic analysis was used upon interface '_target' and found a unique
 924  * default method candidate with generic signature '_method_desc'.  This
 925  * method is only viable if it would also be in the set of default method
 926  * candidates if we ran a full analysis on the current class.
 927  *
 928  * The only reason that the method would not be in the set of candidates for
 929  * the current class is if that there's another covariantly matching method
 930  * which is "more specific" than the found method -- i.e., one could find a
 931  * path in the interface hierarchy in which the matching method appears
 932  * before we get to '_target'.
 933  *
 934  * In order to determine this, we examine all of the implemented
 935  * interfaces.  If we find path that leads to the '_target' interface, then
 936  * we examine that path to see if there are any methods that would shadow
 937  * the selected method along that path.
 938  */
 939 class ShadowChecker : public HierarchyVisitor<ShadowChecker> {
 940  private:
 941   generic::DescriptorCache* _cache;
 942   Thread* THREAD;
 943 
 944   InstanceKlass* _target;
 945 
 946   Symbol* _method_name;
 947   InstanceKlass* _method_holder;
 948   generic::MethodDescriptor* _method_desc;
 949   bool _found_shadow;
 950 
 951   bool path_has_shadow() {
 952     generic::Context ctx(_cache);
 953 
 954     for (int i = current_depth() - 1; i > 0; --i) {
 955       InstanceKlass* ik = class_at_depth(i);
 956       InstanceKlass* sub = class_at_depth(i + 1);
 957       ctx.apply_type_arguments(sub, ik, THREAD);
 958 
 959       if (ik->is_interface()) {
 960         int end;
 961         int start = ik->find_method_by_name(_method_name, &end);
 962         if (start != -1) {
 963           for (int j = start; j < end; ++j) {
 964             Method* mo = ik->methods()->at(j);
 965             generic::MethodDescriptor* md = _cache->descriptor_for(mo, THREAD);
 966             if (_method_desc->covariant_match(md, &ctx)) {
 967               return true;
 968             }
 969           }
 970         }
 971       }
 972     }
 973     return false;
 974   }
 975 
 976  public:
 977 
 978   ShadowChecker(generic::DescriptorCache* cache, Thread* thread,
 979       Symbol* name, InstanceKlass* holder, generic::MethodDescriptor* desc,
 980       InstanceKlass* target)
 981     : _cache(cache), THREAD(thread), _method_name(name), _method_holder(holder),
 982       _method_desc(desc), _target(target), _found_shadow(false) {}
 983 
 984   void* new_node_data(InstanceKlass* cls) { return NULL; }
 985   void free_node_data(void* data) { return; }
 986 
 987   bool visit() {
 988     InstanceKlass* ik = current_class();
 989     if (ik == _target && current_depth() == 1) {
 990       return false; // This was the specified super -- no need to search it
 991     }
 992     if (ik == _method_holder || ik == _target) {
 993       // We found a path that should be examined to see if it shadows _method
 994       if (path_has_shadow()) {
 995         _found_shadow = true;
 996         cancel_iteration();
 997       }
 998       return false; // no need to continue up hierarchy
 999     }
1000     return true;
1001   }
1002 
1003   bool found_shadow() { return _found_shadow; }
1004 };
1005 
1006 // This is called during linktime when we find an invokespecial call that
1007 // refers to a direct superinterface.  It indicates that we should find the
1008 // default method in the hierarchy of that superinterface, and if that method
1009 // would have been a candidate from the point of view of 'this' class, then we
1010 // return that method.
1011 Method* DefaultMethods::find_super_default(
1012     Klass* cls, Klass* super, Symbol* method_name, Symbol* sig, TRAPS) {
1013 
1014   ResourceMark rm(THREAD);
1015 
1016   assert(cls != NULL && super != NULL, "Need real classes");
1017 
1018   InstanceKlass* current_class = InstanceKlass::cast(cls);
1019   InstanceKlass* direction = InstanceKlass::cast(super);
1020 
1021   // Keep entire hierarchy alive for the duration of the computation
1022   KeepAliveRegistrar keepAlive(THREAD);
1023   KeepAliveVisitor loadKeepAlive(&keepAlive);
1024   loadKeepAlive.run(current_class);
1025 
1026 #ifndef PRODUCT
1027   if (TraceDefaultMethods) {
1028     tty->print_cr("Finding super default method %s.%s%s from %s",
1029       direction->name()->as_C_string(),
1030       method_name->as_C_string(), sig->as_C_string(),
1031       current_class->name()->as_C_string());
1032   }
1033 #endif // ndef PRODUCT
1034 
1035   if (!direction->is_interface()) {
1036     // We should not be here
1037     return NULL;
1038   }
1039 
1040   generic::DescriptorCache cache;
1041   generic::Context ctx(&cache);
1042 
1043   // Prime the initial generic context for current -> direction
1044   ctx.apply_type_arguments(current_class, direction, CHECK_NULL);
1045 
1046   FindMethodsByName visitor(&cache, method_name, &ctx, CHECK_NULL);
1047   visitor.run(direction);
1048 
1049   GrowableArray<MethodFamily*> families;
1050   visitor.get_discovered_families(&families);
1051 
1052 #ifndef PRODUCT
1053   if (TraceDefaultMethods) {
1054     print_families(&families, sig);
1055   }
1056 #endif // ndef PRODUCT
1057 
1058   MethodFamily* selected_family = NULL;
1059 
1060   for (int i = 0; i < families.length(); ++i) {
1061     MethodFamily* lm = families.at(i);
1062     if (lm->contains_signature(sig)) {
1063       lm->determine_target(current_class, CHECK_NULL);
1064       selected_family = lm;
1065     }
1066   }
1067 
1068   if (selected_family->has_target()) {
1069     Method* target = selected_family->get_selected_target();
1070     InstanceKlass* holder = InstanceKlass::cast(target->method_holder());
1071 
1072     // Verify that the identified method is valid from the context of
1073     // the current class
1074     ShadowChecker checker(&cache, THREAD, target->name(),
1075         holder, selected_family->descriptor(), direction);
1076     checker.run(current_class);
1077 
1078     if (checker.found_shadow()) {
1079 #ifndef PRODUCT
1080       if (TraceDefaultMethods) {
1081         tty->print_cr("    Only candidate found was shadowed.");
1082       }
1083 #endif // ndef PRODUCT
1084       THROW_MSG_(vmSymbols::java_lang_AbstractMethodError(),
1085                  "Accessible default method not found", NULL);
1086     } else {
1087 #ifndef PRODUCT
1088       if (TraceDefaultMethods) {
1089         tty->print("    Returning ");
1090         print_method(tty, target, true);
1091         tty->print_cr("");
1092       }
1093 #endif // ndef PRODUCT
1094       return target;
1095     }
1096   } else {
1097     assert(selected_family->throws_exception(), "must have target or throw");
1098     THROW_MSG_(vmSymbols::java_lang_AbstractMethodError(),
1099                selected_family->get_exception_message()->as_C_string(), NULL);
1100   }
1101 }
1102 
1103 
1104 static int assemble_redirect(
1105     BytecodeConstantPool* cp, BytecodeBuffer* buffer,
1106     Symbol* incoming, Method* target, TRAPS) {
1107 
1108   BytecodeAssembler assem(buffer, cp);
1109 
1110   SignatureStream in(incoming, true);
1111   SignatureStream out(target->signature(), true);
1112   u2 parameter_count = 0;
1113 
1114   assem.aload(parameter_count++); // load 'this'
1115 
1116   while (!in.at_return_type()) {
1117     assert(!out.at_return_type(), "Parameter counts do not match");
1118     BasicType bt = in.type();
1119     assert(out.type() == bt, "Parameter types are not compatible");
1120     assem.load(bt, parameter_count);
1121     if (in.is_object() && in.as_symbol(THREAD) != out.as_symbol(THREAD)) {
1122       assem.checkcast(out.as_symbol(THREAD));
1123     } else if (bt == T_LONG || bt == T_DOUBLE) {
1124       ++parameter_count; // longs and doubles use two slots
1125     }
1126     ++parameter_count;
1127     in.next();
1128     out.next();
1129   }
1130   assert(out.at_return_type(), "Parameter counts do not match");
1131   assert(in.type() == out.type(), "Return types are not compatible");
1132 
1133   if (parameter_count == 1 && (in.type() == T_LONG || in.type() == T_DOUBLE)) {
1134     ++parameter_count; // need room for return value
1135   }
1136   if (target->method_holder()->is_interface()) {
1137     assem.invokespecial(target);
1138   } else {
1139     assem.invokevirtual(target);
1140   }
1141 
1142   if (in.is_object() && in.as_symbol(THREAD) != out.as_symbol(THREAD)) {
1143     assem.checkcast(in.as_symbol(THREAD));
1144   }
1145   assem._return(in.type());
1146   return parameter_count;
1147 }
1148 
1149 static int assemble_abstract_method_error(
1150     BytecodeConstantPool* cp, BytecodeBuffer* buffer, Symbol* message, TRAPS) {
1151 
1152   Symbol* errorName = vmSymbols::java_lang_AbstractMethodError();
1153   Symbol* init = vmSymbols::object_initializer_name();
1154   Symbol* sig = vmSymbols::string_void_signature();
1155 
1156   BytecodeAssembler assem(buffer, cp);
1157 
1158   assem._new(errorName);
1159   assem.dup();
1160   assem.load_string(message);
1161   assem.invokespecial(errorName, init, sig);
1162   assem.athrow();
1163 
1164   return 3; // max stack size: [ exception, exception, string ]
1165 }
1166 
1167 static Method* new_method(
1168     BytecodeConstantPool* cp, BytecodeBuffer* bytecodes, Symbol* name,
1169     Symbol* sig, AccessFlags flags, int max_stack, int params,
1170     ConstMethod::MethodType mt, TRAPS) {
1171 
1172   address code_start = static_cast<address>(bytecodes->adr_at(0));
1173   int code_length = bytecodes->length();
1174 
1175   Method* m = Method::allocate(cp->pool_holder()->class_loader_data(),
1176                                code_length, flags, 0, 0, 0, 0, 0, 0,
1177                                mt, CHECK_NULL);
1178 
1179   m->set_constants(NULL); // This will get filled in later
1180   m->set_name_index(cp->utf8(name));
1181   m->set_signature_index(cp->utf8(sig));
1182 #ifdef CC_INTERP
1183   ResultTypeFinder rtf(sig);
1184   m->set_result_index(rtf.type());
1185 #endif
1186   m->set_size_of_parameters(params);
1187   m->set_max_stack(max_stack);
1188   m->set_max_locals(params);
1189   m->constMethod()->set_stackmap_data(NULL);
1190   m->set_code(code_start);
1191   m->set_force_inline(true);
1192 
1193   return m;
1194 }
1195 
1196 static void switchover_constant_pool(BytecodeConstantPool* bpool,
1197     InstanceKlass* klass, GrowableArray<Method*>* new_methods, TRAPS) {
1198 
1199   if (new_methods->length() > 0) {
1200     ConstantPool* cp = bpool->create_constant_pool(CHECK);
1201     if (cp != klass->constants()) {
1202       klass->class_loader_data()->add_to_deallocate_list(klass->constants());
1203       klass->set_constants(cp);
1204       cp->set_pool_holder(klass);
1205 
1206       for (int i = 0; i < new_methods->length(); ++i) {
1207         new_methods->at(i)->set_constants(cp);
1208       }
1209       for (int i = 0; i < klass->methods()->length(); ++i) {
1210         Method* mo = klass->methods()->at(i);
1211         mo->set_constants(cp);
1212       }
1213     }
1214   }
1215 }
1216 
1217 // A "bridge" is a method created by javac to bridge the gap between
1218 // an implementation and a generically-compatible, but different, signature.
1219 // Bridges have actual bytecode implementation in classfiles.
1220 // An "overpass", on the other hand, performs the same function as a bridge
1221 // but does not occur in a classfile; the VM creates overpass itself,
1222 // when it needs a path to get from a call site to an default method, and
1223 // a bridge doesn't exist.
1224 static void create_overpasses(
1225     GrowableArray<EmptyVtableSlot*>* slots,
1226     InstanceKlass* klass, TRAPS) {
1227 
1228   GrowableArray<Method*> overpasses;
1229   BytecodeConstantPool bpool(klass->constants());
1230 
1231   for (int i = 0; i < slots->length(); ++i) {
1232     EmptyVtableSlot* slot = slots->at(i);
1233 
1234     if (slot->is_bound()) {
1235       MethodFamily* method = slot->get_binding();
1236       int max_stack = 0;
1237       BytecodeBuffer buffer;
1238 
1239 #ifndef PRODUCT
1240       if (TraceDefaultMethods) {
1241         tty->print("for slot: ");
1242         slot->print_on(tty);
1243         tty->print_cr("");
1244         if (method->has_target()) {
1245           method->print_selected(tty, 1);
1246         } else {
1247           method->print_exception(tty, 1);
1248         }
1249       }
1250 #endif // ndef PRODUCT
1251       if (method->has_target()) {
1252         Method* selected = method->get_selected_target();
1253         max_stack = assemble_redirect(
1254             &bpool, &buffer, slot->signature(), selected, CHECK);
1255       } else if (method->throws_exception()) {
1256         max_stack = assemble_abstract_method_error(
1257             &bpool, &buffer, method->get_exception_message(), CHECK);
1258       }
1259       AccessFlags flags = accessFlags_from(
1260           JVM_ACC_PUBLIC | JVM_ACC_SYNTHETIC | JVM_ACC_BRIDGE);
1261       Method* m = new_method(&bpool, &buffer, slot->name(), slot->signature(),
1262           flags, max_stack, slot->size_of_parameters(),
1263           ConstMethod::OVERPASS, CHECK);
1264       if (m != NULL) {
1265         overpasses.push(m);
1266       }
1267     }
1268   }
1269 
1270 #ifndef PRODUCT
1271   if (TraceDefaultMethods) {
1272     tty->print_cr("Created %d overpass methods", overpasses.length());
1273   }
1274 #endif // ndef PRODUCT
1275 
1276   switchover_constant_pool(&bpool, klass, &overpasses, CHECK);
1277   merge_in_new_methods(klass, &overpasses, CHECK);
1278 }
1279 
1280 static void sort_methods(GrowableArray<Method*>* methods) {
1281   // Note that this must sort using the same key as is used for sorting
1282   // methods in InstanceKlass.
1283   bool sorted = true;
1284   for (int i = methods->length() - 1; i > 0; --i) {
1285     for (int j = 0; j < i; ++j) {
1286       Method* m1 = methods->at(j);
1287       Method* m2 = methods->at(j + 1);
1288       if ((uintptr_t)m1->name() > (uintptr_t)m2->name()) {
1289         methods->at_put(j, m2);
1290         methods->at_put(j + 1, m1);
1291         sorted = false;
1292       }
1293     }
1294     if (sorted) break;
1295     sorted = true;
1296   }
1297 #ifdef ASSERT
1298   uintptr_t prev = 0;
1299   for (int i = 0; i < methods->length(); ++i) {
1300     Method* mh = methods->at(i);
1301     uintptr_t nv = (uintptr_t)mh->name();
1302     assert(nv >= prev, "Incorrect overpass method ordering");
1303     prev = nv;
1304   }
1305 #endif
1306 }
1307 
1308 static void merge_in_new_methods(InstanceKlass* klass,
1309     GrowableArray<Method*>* new_methods, TRAPS) {
1310 
1311   enum { ANNOTATIONS, PARAMETERS, DEFAULTS, NUM_ARRAYS };
1312 
1313   Array<AnnotationArray*>* original_annots[NUM_ARRAYS] = { NULL };
1314 
1315   Array<Method*>* original_methods = klass->methods();
1316   Annotations* annots = klass->annotations();
1317   if (annots != NULL) {
1318     original_annots[ANNOTATIONS] = annots->methods_annotations();
1319     original_annots[PARAMETERS]  = annots->methods_parameter_annotations();
1320     original_annots[DEFAULTS]    = annots->methods_default_annotations();
1321   }
1322 
1323   Array<int>* original_ordering = klass->method_ordering();
1324   Array<int>* merged_ordering = Universe::the_empty_int_array();
1325 
1326   int new_size = klass->methods()->length() + new_methods->length();
1327 
1328   Array<AnnotationArray*>* merged_annots[NUM_ARRAYS];
1329 
1330   Array<Method*>* merged_methods = MetadataFactory::new_array<Method*>(
1331       klass->class_loader_data(), new_size, NULL, CHECK);
1332   for (int i = 0; i < NUM_ARRAYS; ++i) {
1333     if (original_annots[i] != NULL) {
1334       merged_annots[i] = MetadataFactory::new_array<AnnotationArray*>(
1335           klass->class_loader_data(), new_size, CHECK);
1336     } else {
1337       merged_annots[i] = NULL;
1338     }
1339   }
1340   if (original_ordering != NULL && original_ordering->length() > 0) {
1341     merged_ordering = MetadataFactory::new_array<int>(
1342         klass->class_loader_data(), new_size, CHECK);
1343   }
1344   int method_order_index = klass->methods()->length();
1345 
1346   sort_methods(new_methods);
1347 
1348   // Perform grand merge of existing methods and new methods
1349   int orig_idx = 0;
1350   int new_idx = 0;
1351 
1352   for (int i = 0; i < new_size; ++i) {
1353     Method* orig_method = NULL;
1354     Method* new_method = NULL;
1355     if (orig_idx < original_methods->length()) {
1356       orig_method = original_methods->at(orig_idx);
1357     }
1358     if (new_idx < new_methods->length()) {
1359       new_method = new_methods->at(new_idx);
1360     }
1361 
1362     if (orig_method != NULL &&
1363         (new_method == NULL || orig_method->name() < new_method->name())) {
1364       merged_methods->at_put(i, orig_method);
1365       original_methods->at_put(orig_idx, NULL);
1366       for (int j = 0; j < NUM_ARRAYS; ++j) {
1367         if (merged_annots[j] != NULL) {
1368           merged_annots[j]->at_put(i, original_annots[j]->at(orig_idx));
1369           original_annots[j]->at_put(orig_idx, NULL);
1370         }
1371       }
1372       if (merged_ordering->length() > 0) {
1373         merged_ordering->at_put(i, original_ordering->at(orig_idx));
1374       }
1375       ++orig_idx;
1376     } else {
1377       merged_methods->at_put(i, new_method);
1378       if (merged_ordering->length() > 0) {
1379         merged_ordering->at_put(i, method_order_index++);
1380       }
1381       ++new_idx;
1382     }
1383     // update idnum for new location
1384     merged_methods->at(i)->set_method_idnum(i);
1385   }
1386 
1387   // Verify correct order
1388 #ifdef ASSERT
1389   uintptr_t prev = 0;
1390   for (int i = 0; i < merged_methods->length(); ++i) {
1391     Method* mo = merged_methods->at(i);
1392     uintptr_t nv = (uintptr_t)mo->name();
1393     assert(nv >= prev, "Incorrect method ordering");
1394     prev = nv;
1395   }
1396 #endif
1397 
1398   // Replace klass methods with new merged lists
1399   klass->set_methods(merged_methods);
1400   if (annots != NULL) {
1401     annots->set_methods_annotations(merged_annots[ANNOTATIONS]);
1402     annots->set_methods_parameter_annotations(merged_annots[PARAMETERS]);
1403     annots->set_methods_default_annotations(merged_annots[DEFAULTS]);
1404   } else {
1405     assert(merged_annots[ANNOTATIONS] == NULL, "Must be");
1406     assert(merged_annots[PARAMETERS] == NULL, "Must be");
1407     assert(merged_annots[DEFAULTS] == NULL, "Must be");
1408   }
1409 
1410   ClassLoaderData* cld = klass->class_loader_data();
1411   MetadataFactory::free_array(cld, original_methods);
1412   for (int i = 0; i < NUM_ARRAYS; ++i) {
1413     MetadataFactory::free_array(cld, original_annots[i]);
1414   }
1415   if (original_ordering->length() > 0) {
1416     klass->set_method_ordering(merged_ordering);
1417     MetadataFactory::free_array(cld, original_ordering);
1418   }
1419 }
1420