1 /*
   2  * Copyright (c) 2005, 2015, 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 "ci/ciArrayKlass.hpp"
  27 #include "ci/ciEnv.hpp"
  28 #include "ci/ciKlass.hpp"
  29 #include "ci/ciMethod.hpp"
  30 #include "classfile/javaClasses.inline.hpp"
  31 #include "code/dependencies.hpp"
  32 #include "compiler/compileLog.hpp"
  33 #include "oops/oop.inline.hpp"
  34 #include "runtime/handles.hpp"
  35 #include "runtime/handles.inline.hpp"
  36 #include "runtime/thread.inline.hpp"
  37 #include "utilities/copy.hpp"
  38 
  39 
  40 #ifdef ASSERT
  41 static bool must_be_in_vm() {
  42   Thread* thread = Thread::current();
  43   if (thread->is_Java_thread())
  44     return ((JavaThread*)thread)->thread_state() == _thread_in_vm;
  45   else
  46     return true;  //something like this: thread->is_VM_thread();
  47 }
  48 #endif //ASSERT
  49 
  50 void Dependencies::initialize(ciEnv* env) {
  51   Arena* arena = env->arena();
  52   _oop_recorder = env->oop_recorder();
  53   _log = env->log();
  54   _dep_seen = new(arena) GrowableArray<int>(arena, 500, 0, 0);
  55   DEBUG_ONLY(_deps[end_marker] = NULL);
  56   for (int i = (int)FIRST_TYPE; i < (int)TYPE_LIMIT; i++) {
  57     _deps[i] = new(arena) GrowableArray<ciBaseObject*>(arena, 10, 0, 0);
  58   }
  59   _content_bytes = NULL;
  60   _size_in_bytes = (size_t)-1;
  61 
  62   assert(TYPE_LIMIT <= (1<<LG2_TYPE_LIMIT), "sanity");
  63 }
  64 
  65 void Dependencies::assert_evol_method(ciMethod* m) {
  66   assert_common_1(evol_method, m);
  67 }
  68 
  69 void Dependencies::assert_leaf_type(ciKlass* ctxk) {
  70   if (ctxk->is_array_klass()) {
  71     // As a special case, support this assertion on an array type,
  72     // which reduces to an assertion on its element type.
  73     // Note that this cannot be done with assertions that
  74     // relate to concreteness or abstractness.
  75     ciType* elemt = ctxk->as_array_klass()->base_element_type();
  76     if (!elemt->is_instance_klass())  return;   // Ex:  int[][]
  77     ctxk = elemt->as_instance_klass();
  78     //if (ctxk->is_final())  return;            // Ex:  String[][]
  79   }
  80   check_ctxk(ctxk);
  81   assert_common_1(leaf_type, ctxk);
  82 }
  83 
  84 void Dependencies::assert_abstract_with_unique_concrete_subtype(ciKlass* ctxk, ciKlass* conck) {
  85   check_ctxk_abstract(ctxk);
  86   assert_common_2(abstract_with_unique_concrete_subtype, ctxk, conck);
  87 }
  88 
  89 void Dependencies::assert_abstract_with_no_concrete_subtype(ciKlass* ctxk) {
  90   check_ctxk_abstract(ctxk);
  91   assert_common_1(abstract_with_no_concrete_subtype, ctxk);
  92 }
  93 
  94 void Dependencies::assert_concrete_with_no_concrete_subtype(ciKlass* ctxk) {
  95   check_ctxk_concrete(ctxk);
  96   assert_common_1(concrete_with_no_concrete_subtype, ctxk);
  97 }
  98 
  99 void Dependencies::assert_unique_concrete_method(ciKlass* ctxk, ciMethod* uniqm) {
 100   check_ctxk(ctxk);
 101   assert_common_2(unique_concrete_method, ctxk, uniqm);
 102 }
 103 
 104 void Dependencies::assert_abstract_with_exclusive_concrete_subtypes(ciKlass* ctxk, ciKlass* k1, ciKlass* k2) {
 105   check_ctxk(ctxk);
 106   assert_common_3(abstract_with_exclusive_concrete_subtypes_2, ctxk, k1, k2);
 107 }
 108 
 109 void Dependencies::assert_exclusive_concrete_methods(ciKlass* ctxk, ciMethod* m1, ciMethod* m2) {
 110   check_ctxk(ctxk);
 111   assert_common_3(exclusive_concrete_methods_2, ctxk, m1, m2);
 112 }
 113 
 114 void Dependencies::assert_has_no_finalizable_subclasses(ciKlass* ctxk) {
 115   check_ctxk(ctxk);
 116   assert_common_1(no_finalizable_subclasses, ctxk);
 117 }
 118 
 119 void Dependencies::assert_call_site_target_value(ciCallSite* call_site, ciMethodHandle* method_handle) {
 120   ciKlass* ctxk = call_site->get_context();
 121   check_ctxk(ctxk);
 122   assert_common_3(call_site_target_value, ctxk, call_site, method_handle);
 123 }
 124 
 125 // Helper function.  If we are adding a new dep. under ctxk2,
 126 // try to find an old dep. under a broader* ctxk1.  If there is
 127 //
 128 bool Dependencies::maybe_merge_ctxk(GrowableArray<ciBaseObject*>* deps,
 129                                     int ctxk_i, ciKlass* ctxk2) {
 130   ciKlass* ctxk1 = deps->at(ctxk_i)->as_metadata()->as_klass();
 131   if (ctxk2->is_subtype_of(ctxk1)) {
 132     return true;  // success, and no need to change
 133   } else if (ctxk1->is_subtype_of(ctxk2)) {
 134     // new context class fully subsumes previous one
 135     deps->at_put(ctxk_i, ctxk2);
 136     return true;
 137   } else {
 138     return false;
 139   }
 140 }
 141 
 142 void Dependencies::assert_common_1(DepType dept, ciBaseObject* x) {
 143   assert(dep_args(dept) == 1, "sanity");
 144   log_dependency(dept, x);
 145   GrowableArray<ciBaseObject*>* deps = _deps[dept];
 146 
 147   // see if the same (or a similar) dep is already recorded
 148   if (note_dep_seen(dept, x)) {
 149     assert(deps->find(x) >= 0, "sanity");
 150   } else {
 151     deps->append(x);
 152   }
 153 }
 154 
 155 void Dependencies::assert_common_2(DepType dept,
 156                                    ciBaseObject* x0, ciBaseObject* x1) {
 157   assert(dep_args(dept) == 2, "sanity");
 158   log_dependency(dept, x0, x1);
 159   GrowableArray<ciBaseObject*>* deps = _deps[dept];
 160 
 161   // see if the same (or a similar) dep is already recorded
 162   bool has_ctxk = has_explicit_context_arg(dept);
 163   if (has_ctxk) {
 164     assert(dep_context_arg(dept) == 0, "sanity");
 165     if (note_dep_seen(dept, x1)) {
 166       // look in this bucket for redundant assertions
 167       const int stride = 2;
 168       for (int i = deps->length(); (i -= stride) >= 0; ) {
 169         ciBaseObject* y1 = deps->at(i+1);
 170         if (x1 == y1) {  // same subject; check the context
 171           if (maybe_merge_ctxk(deps, i+0, x0->as_metadata()->as_klass())) {
 172             return;
 173           }
 174         }
 175       }
 176     }
 177   } else {
 178     assert(dep_implicit_context_arg(dept) == 0, "sanity");
 179     if (note_dep_seen(dept, x0) && note_dep_seen(dept, x1)) {
 180       // look in this bucket for redundant assertions
 181       const int stride = 2;
 182       for (int i = deps->length(); (i -= stride) >= 0; ) {
 183         ciBaseObject* y0 = deps->at(i+0);
 184         ciBaseObject* y1 = deps->at(i+1);
 185         if (x0 == y0 && x1 == y1) {
 186           return;
 187         }
 188       }
 189     }
 190   }
 191 
 192   // append the assertion in the correct bucket:
 193   deps->append(x0);
 194   deps->append(x1);
 195 }
 196 
 197 void Dependencies::assert_common_3(DepType dept,
 198                                    ciKlass* ctxk, ciBaseObject* x, ciBaseObject* x2) {
 199   assert(dep_context_arg(dept) == 0, "sanity");
 200   assert(dep_args(dept) == 3, "sanity");
 201   log_dependency(dept, ctxk, x, x2);
 202   GrowableArray<ciBaseObject*>* deps = _deps[dept];
 203 
 204   // try to normalize an unordered pair:
 205   bool swap = false;
 206   switch (dept) {
 207   case abstract_with_exclusive_concrete_subtypes_2:
 208     swap = (x->ident() > x2->ident() && x->as_metadata()->as_klass() != ctxk);
 209     break;
 210   case exclusive_concrete_methods_2:
 211     swap = (x->ident() > x2->ident() && x->as_metadata()->as_method()->holder() != ctxk);
 212     break;
 213   }
 214   if (swap) { ciBaseObject* t = x; x = x2; x2 = t; }
 215 
 216   // see if the same (or a similar) dep is already recorded
 217   if (note_dep_seen(dept, x) && note_dep_seen(dept, x2)) {
 218     // look in this bucket for redundant assertions
 219     const int stride = 3;
 220     for (int i = deps->length(); (i -= stride) >= 0; ) {
 221       ciBaseObject* y  = deps->at(i+1);
 222       ciBaseObject* y2 = deps->at(i+2);
 223       if (x == y && x2 == y2) {  // same subjects; check the context
 224         if (maybe_merge_ctxk(deps, i+0, ctxk)) {
 225           return;
 226         }
 227       }
 228     }
 229   }
 230   // append the assertion in the correct bucket:
 231   deps->append(ctxk);
 232   deps->append(x);
 233   deps->append(x2);
 234 }
 235 
 236 /// Support for encoding dependencies into an nmethod:
 237 
 238 void Dependencies::copy_to(nmethod* nm) {
 239   address beg = nm->dependencies_begin();
 240   address end = nm->dependencies_end();
 241   guarantee(end - beg >= (ptrdiff_t) size_in_bytes(), "bad sizing");
 242   Copy::disjoint_words((HeapWord*) content_bytes(),
 243                        (HeapWord*) beg,
 244                        size_in_bytes() / sizeof(HeapWord));
 245   assert(size_in_bytes() % sizeof(HeapWord) == 0, "copy by words");
 246 }
 247 
 248 static int sort_dep(ciBaseObject** p1, ciBaseObject** p2, int narg) {
 249   for (int i = 0; i < narg; i++) {
 250     int diff = p1[i]->ident() - p2[i]->ident();
 251     if (diff != 0)  return diff;
 252   }
 253   return 0;
 254 }
 255 static int sort_dep_arg_1(ciBaseObject** p1, ciBaseObject** p2)
 256 { return sort_dep(p1, p2, 1); }
 257 static int sort_dep_arg_2(ciBaseObject** p1, ciBaseObject** p2)
 258 { return sort_dep(p1, p2, 2); }
 259 static int sort_dep_arg_3(ciBaseObject** p1, ciBaseObject** p2)
 260 { return sort_dep(p1, p2, 3); }
 261 
 262 void Dependencies::sort_all_deps() {
 263   for (int deptv = (int)FIRST_TYPE; deptv < (int)TYPE_LIMIT; deptv++) {
 264     DepType dept = (DepType)deptv;
 265     GrowableArray<ciBaseObject*>* deps = _deps[dept];
 266     if (deps->length() <= 1)  continue;
 267     switch (dep_args(dept)) {
 268     case 1: deps->sort(sort_dep_arg_1, 1); break;
 269     case 2: deps->sort(sort_dep_arg_2, 2); break;
 270     case 3: deps->sort(sort_dep_arg_3, 3); break;
 271     default: ShouldNotReachHere();
 272     }
 273   }
 274 }
 275 
 276 size_t Dependencies::estimate_size_in_bytes() {
 277   size_t est_size = 100;
 278   for (int deptv = (int)FIRST_TYPE; deptv < (int)TYPE_LIMIT; deptv++) {
 279     DepType dept = (DepType)deptv;
 280     GrowableArray<ciBaseObject*>* deps = _deps[dept];
 281     est_size += deps->length()*2;  // tags and argument(s)
 282   }
 283   return est_size;
 284 }
 285 
 286 ciKlass* Dependencies::ctxk_encoded_as_null(DepType dept, ciBaseObject* x) {
 287   switch (dept) {
 288   case abstract_with_exclusive_concrete_subtypes_2:
 289     return x->as_metadata()->as_klass();
 290   case unique_concrete_method:
 291   case exclusive_concrete_methods_2:
 292     return x->as_metadata()->as_method()->holder();
 293   }
 294   return NULL;  // let NULL be NULL
 295 }
 296 
 297 Klass* Dependencies::ctxk_encoded_as_null(DepType dept, Metadata* x) {
 298   assert(must_be_in_vm(), "raw oops here");
 299   switch (dept) {
 300   case abstract_with_exclusive_concrete_subtypes_2:
 301     assert(x->is_klass(), "sanity");
 302     return (Klass*) x;
 303   case unique_concrete_method:
 304   case exclusive_concrete_methods_2:
 305     assert(x->is_method(), "sanity");
 306     return ((Method*)x)->method_holder();
 307   }
 308   return NULL;  // let NULL be NULL
 309 }
 310 
 311 void Dependencies::encode_content_bytes() {
 312   sort_all_deps();
 313 
 314   // cast is safe, no deps can overflow INT_MAX
 315   CompressedWriteStream bytes((int)estimate_size_in_bytes());
 316 
 317   for (int deptv = (int)FIRST_TYPE; deptv < (int)TYPE_LIMIT; deptv++) {
 318     DepType dept = (DepType)deptv;
 319     GrowableArray<ciBaseObject*>* deps = _deps[dept];
 320     if (deps->length() == 0)  continue;
 321     int stride = dep_args(dept);
 322     int ctxkj  = dep_context_arg(dept);  // -1 if no context arg
 323     assert(stride > 0, "sanity");
 324     for (int i = 0; i < deps->length(); i += stride) {
 325       jbyte code_byte = (jbyte)dept;
 326       int skipj = -1;
 327       if (ctxkj >= 0 && ctxkj+1 < stride) {
 328         ciKlass*  ctxk = deps->at(i+ctxkj+0)->as_metadata()->as_klass();
 329         ciBaseObject* x     = deps->at(i+ctxkj+1);  // following argument
 330         if (ctxk == ctxk_encoded_as_null(dept, x)) {
 331           skipj = ctxkj;  // we win:  maybe one less oop to keep track of
 332           code_byte |= default_context_type_bit;
 333         }
 334       }
 335       bytes.write_byte(code_byte);
 336       for (int j = 0; j < stride; j++) {
 337         if (j == skipj)  continue;
 338         ciBaseObject* v = deps->at(i+j);
 339         int idx;
 340         if (v->is_object()) {
 341           idx = _oop_recorder->find_index(v->as_object()->constant_encoding());
 342         } else {
 343           ciMetadata* meta = v->as_metadata();
 344           idx = _oop_recorder->find_index(meta->constant_encoding());
 345         }
 346         bytes.write_int(idx);
 347       }
 348     }
 349   }
 350 
 351   // write a sentinel byte to mark the end
 352   bytes.write_byte(end_marker);
 353 
 354   // round it out to a word boundary
 355   while (bytes.position() % sizeof(HeapWord) != 0) {
 356     bytes.write_byte(end_marker);
 357   }
 358 
 359   // check whether the dept byte encoding really works
 360   assert((jbyte)default_context_type_bit != 0, "byte overflow");
 361 
 362   _content_bytes = bytes.buffer();
 363   _size_in_bytes = bytes.position();
 364 }
 365 
 366 
 367 const char* Dependencies::_dep_name[TYPE_LIMIT] = {
 368   "end_marker",
 369   "evol_method",
 370   "leaf_type",
 371   "abstract_with_unique_concrete_subtype",
 372   "abstract_with_no_concrete_subtype",
 373   "concrete_with_no_concrete_subtype",
 374   "unique_concrete_method",
 375   "abstract_with_exclusive_concrete_subtypes_2",
 376   "exclusive_concrete_methods_2",
 377   "no_finalizable_subclasses",
 378   "call_site_target_value"
 379 };
 380 
 381 int Dependencies::_dep_args[TYPE_LIMIT] = {
 382   -1,// end_marker
 383   1, // evol_method m
 384   1, // leaf_type ctxk
 385   2, // abstract_with_unique_concrete_subtype ctxk, k
 386   1, // abstract_with_no_concrete_subtype ctxk
 387   1, // concrete_with_no_concrete_subtype ctxk
 388   2, // unique_concrete_method ctxk, m
 389   3, // unique_concrete_subtypes_2 ctxk, k1, k2
 390   3, // unique_concrete_methods_2 ctxk, m1, m2
 391   1, // no_finalizable_subclasses ctxk
 392   3  // call_site_target_value ctxk, call_site, method_handle
 393 };
 394 
 395 const char* Dependencies::dep_name(Dependencies::DepType dept) {
 396   if (!dept_in_mask(dept, all_types))  return "?bad-dep?";
 397   return _dep_name[dept];
 398 }
 399 
 400 int Dependencies::dep_args(Dependencies::DepType dept) {
 401   if (!dept_in_mask(dept, all_types))  return -1;
 402   return _dep_args[dept];
 403 }
 404 
 405 void Dependencies::check_valid_dependency_type(DepType dept) {
 406   guarantee(FIRST_TYPE <= dept && dept < TYPE_LIMIT, err_msg("invalid dependency type: %d", (int) dept));
 407 }
 408 
 409 // for the sake of the compiler log, print out current dependencies:
 410 void Dependencies::log_all_dependencies() {
 411   if (log() == NULL)  return;
 412   ResourceMark rm;
 413   for (int deptv = (int)FIRST_TYPE; deptv < (int)TYPE_LIMIT; deptv++) {
 414     DepType dept = (DepType)deptv;
 415     GrowableArray<ciBaseObject*>* deps = _deps[dept];
 416     int deplen = deps->length();
 417     if (deplen == 0) {
 418       continue;
 419     }
 420     int stride = dep_args(dept);
 421     GrowableArray<ciBaseObject*>* ciargs = new GrowableArray<ciBaseObject*>(stride);
 422     for (int i = 0; i < deps->length(); i += stride) {
 423       for (int j = 0; j < stride; j++) {
 424         // flush out the identities before printing
 425         ciargs->push(deps->at(i+j));
 426       }
 427       write_dependency_to(log(), dept, ciargs);
 428       ciargs->clear();
 429     }
 430     guarantee(deplen == deps->length(), "deps array cannot grow inside nested ResoureMark scope");
 431   }
 432 }
 433 
 434 void Dependencies::write_dependency_to(CompileLog* log,
 435                                        DepType dept,
 436                                        GrowableArray<DepArgument>* args,
 437                                        Klass* witness) {
 438   if (log == NULL) {
 439     return;
 440   }
 441   ResourceMark rm;
 442   ciEnv* env = ciEnv::current();
 443   GrowableArray<ciBaseObject*>* ciargs = new GrowableArray<ciBaseObject*>(args->length());
 444   for (GrowableArrayIterator<DepArgument> it = args->begin(); it != args->end(); ++it) {
 445     DepArgument arg = *it;
 446     if (arg.is_oop()) {
 447       ciargs->push(env->get_object(arg.oop_value()));
 448     } else {
 449       ciargs->push(env->get_metadata(arg.metadata_value()));
 450     }
 451   }
 452   int argslen = ciargs->length();
 453   Dependencies::write_dependency_to(log, dept, ciargs, witness);
 454   guarantee(argslen == ciargs->length(), "ciargs array cannot grow inside nested ResoureMark scope");
 455 }
 456 
 457 void Dependencies::write_dependency_to(CompileLog* log,
 458                                        DepType dept,
 459                                        GrowableArray<ciBaseObject*>* args,
 460                                        Klass* witness) {
 461   if (log == NULL) {
 462     return;
 463   }
 464   ResourceMark rm;
 465   GrowableArray<int>* argids = new GrowableArray<int>(args->length());
 466   for (GrowableArrayIterator<ciBaseObject*> it = args->begin(); it != args->end(); ++it) {
 467     ciBaseObject* obj = *it;
 468     if (obj->is_object()) {
 469       argids->push(log->identify(obj->as_object()));
 470     } else {
 471       argids->push(log->identify(obj->as_metadata()));
 472     }
 473   }
 474   if (witness != NULL) {
 475     log->begin_elem("dependency_failed");
 476   } else {
 477     log->begin_elem("dependency");
 478   }
 479   log->print(" type='%s'", dep_name(dept));
 480   const int ctxkj = dep_context_arg(dept);  // -1 if no context arg
 481   if (ctxkj >= 0 && ctxkj < argids->length()) {
 482     log->print(" ctxk='%d'", argids->at(ctxkj));
 483   }
 484   // write remaining arguments, if any.
 485   for (int j = 0; j < argids->length(); j++) {
 486     if (j == ctxkj)  continue;  // already logged
 487     if (j == 1) {
 488       log->print(  " x='%d'",    argids->at(j));
 489     } else {
 490       log->print(" x%d='%d'", j, argids->at(j));
 491     }
 492   }
 493   if (witness != NULL) {
 494     log->object("witness", witness);
 495     log->stamp();
 496   }
 497   log->end_elem();
 498 }
 499 
 500 void Dependencies::write_dependency_to(xmlStream* xtty,
 501                                        DepType dept,
 502                                        GrowableArray<DepArgument>* args,
 503                                        Klass* witness) {
 504   if (xtty == NULL) {
 505     return;
 506   }
 507   ResourceMark rm;
 508   ttyLocker ttyl;
 509   int ctxkj = dep_context_arg(dept);  // -1 if no context arg
 510   if (witness != NULL) {
 511     xtty->begin_elem("dependency_failed");
 512   } else {
 513     xtty->begin_elem("dependency");
 514   }
 515   xtty->print(" type='%s'", dep_name(dept));
 516   if (ctxkj >= 0) {
 517     xtty->object("ctxk", args->at(ctxkj).metadata_value());
 518   }
 519   // write remaining arguments, if any.
 520   for (int j = 0; j < args->length(); j++) {
 521     if (j == ctxkj)  continue;  // already logged
 522     DepArgument arg = args->at(j);
 523     if (j == 1) {
 524       if (arg.is_oop()) {
 525         xtty->object("x", arg.oop_value());
 526       } else {
 527         xtty->object("x", arg.metadata_value());
 528       }
 529     } else {
 530       char xn[10]; sprintf(xn, "x%d", j);
 531       if (arg.is_oop()) {
 532         xtty->object(xn, arg.oop_value());
 533       } else {
 534         xtty->object(xn, arg.metadata_value());
 535       }
 536     }
 537   }
 538   if (witness != NULL) {
 539     xtty->object("witness", witness);
 540     xtty->stamp();
 541   }
 542   xtty->end_elem();
 543 }
 544 
 545 void Dependencies::print_dependency(DepType dept, GrowableArray<DepArgument>* args,
 546                                     Klass* witness) {
 547   ResourceMark rm;
 548   ttyLocker ttyl;   // keep the following output all in one block
 549   tty->print_cr("%s of type %s",
 550                 (witness == NULL)? "Dependency": "Failed dependency",
 551                 dep_name(dept));
 552   // print arguments
 553   int ctxkj = dep_context_arg(dept);  // -1 if no context arg
 554   for (int j = 0; j < args->length(); j++) {
 555     DepArgument arg = args->at(j);
 556     bool put_star = false;
 557     if (arg.is_null())  continue;
 558     const char* what;
 559     if (j == ctxkj) {
 560       assert(arg.is_metadata(), "must be");
 561       what = "context";
 562       put_star = !Dependencies::is_concrete_klass((Klass*)arg.metadata_value());
 563     } else if (arg.is_method()) {
 564       what = "method ";
 565       put_star = !Dependencies::is_concrete_method((Method*)arg.metadata_value(), NULL);
 566     } else if (arg.is_klass()) {
 567       what = "class  ";
 568     } else {
 569       what = "object ";
 570     }
 571     tty->print("  %s = %s", what, (put_star? "*": ""));
 572     if (arg.is_klass()) {
 573       tty->print("%s", ((Klass*)arg.metadata_value())->external_name());
 574     } else if (arg.is_method()) {
 575       ((Method*)arg.metadata_value())->print_value();
 576     } else if (arg.is_oop()) {
 577       arg.oop_value()->print_value_on(tty);
 578     } else {
 579       ShouldNotReachHere(); // Provide impl for this type.
 580     }
 581 
 582     tty->cr();
 583   }
 584   if (witness != NULL) {
 585     bool put_star = !Dependencies::is_concrete_klass(witness);
 586     tty->print_cr("  witness = %s%s",
 587                   (put_star? "*": ""),
 588                   witness->external_name());
 589   }
 590 }
 591 
 592 void Dependencies::DepStream::log_dependency(Klass* witness) {
 593   if (_deps == NULL && xtty == NULL)  return;  // fast cutout for runtime
 594   ResourceMark rm;
 595   const int nargs = argument_count();
 596   GrowableArray<DepArgument>* args = new GrowableArray<DepArgument>(nargs);
 597   for (int j = 0; j < nargs; j++) {
 598     if (is_oop_argument(j)) {
 599       args->push(argument_oop(j));
 600     } else {
 601       args->push(argument(j));
 602     }
 603   }
 604   int argslen = args->length();
 605   if (_deps != NULL && _deps->log() != NULL) {
 606     Dependencies::write_dependency_to(_deps->log(), type(), args, witness);
 607   } else {
 608     Dependencies::write_dependency_to(xtty, type(), args, witness);
 609   }
 610   guarantee(argslen == args->length(), "args array cannot grow inside nested ResoureMark scope");
 611 }
 612 
 613 void Dependencies::DepStream::print_dependency(Klass* witness, bool verbose) {
 614   ResourceMark rm;
 615   int nargs = argument_count();
 616   GrowableArray<DepArgument>* args = new GrowableArray<DepArgument>(nargs);
 617   for (int j = 0; j < nargs; j++) {
 618     if (is_oop_argument(j)) {
 619       args->push(argument_oop(j));
 620     } else {
 621       args->push(argument(j));
 622     }
 623   }
 624   int argslen = args->length();
 625   Dependencies::print_dependency(type(), args, witness);
 626   if (verbose) {
 627     if (_code != NULL) {
 628       tty->print("  code: ");
 629       _code->print_value_on(tty);
 630       tty->cr();
 631     }
 632   }
 633   guarantee(argslen == args->length(), "args array cannot grow inside nested ResoureMark scope");
 634 }
 635 
 636 
 637 /// Dependency stream support (decodes dependencies from an nmethod):
 638 
 639 #ifdef ASSERT
 640 void Dependencies::DepStream::initial_asserts(size_t byte_limit) {
 641   assert(must_be_in_vm(), "raw oops here");
 642   _byte_limit = byte_limit;
 643   _type       = (DepType)(end_marker-1);  // defeat "already at end" assert
 644   assert((_code!=NULL) + (_deps!=NULL) == 1, "one or t'other");
 645 }
 646 #endif //ASSERT
 647 
 648 bool Dependencies::DepStream::next() {
 649   assert(_type != end_marker, "already at end");
 650   if (_bytes.position() == 0 && _code != NULL
 651       && _code->dependencies_size() == 0) {
 652     // Method has no dependencies at all.
 653     return false;
 654   }
 655   int code_byte = (_bytes.read_byte() & 0xFF);
 656   if (code_byte == end_marker) {
 657     DEBUG_ONLY(_type = end_marker);
 658     return false;
 659   } else {
 660     int ctxk_bit = (code_byte & Dependencies::default_context_type_bit);
 661     code_byte -= ctxk_bit;
 662     DepType dept = (DepType)code_byte;
 663     _type = dept;
 664     Dependencies::check_valid_dependency_type(dept);
 665     int stride = _dep_args[dept];
 666     assert(stride == dep_args(dept), "sanity");
 667     int skipj = -1;
 668     if (ctxk_bit != 0) {
 669       skipj = 0;  // currently the only context argument is at zero
 670       assert(skipj == dep_context_arg(dept), "zero arg always ctxk");
 671     }
 672     for (int j = 0; j < stride; j++) {
 673       _xi[j] = (j == skipj)? 0: _bytes.read_int();
 674     }
 675     DEBUG_ONLY(_xi[stride] = -1);   // help detect overruns
 676     return true;
 677   }
 678 }
 679 
 680 inline Metadata* Dependencies::DepStream::recorded_metadata_at(int i) {
 681   Metadata* o = NULL;
 682   if (_code != NULL) {
 683     o = _code->metadata_at(i);
 684   } else {
 685     o = _deps->oop_recorder()->metadata_at(i);
 686   }
 687   return o;
 688 }
 689 
 690 inline oop Dependencies::DepStream::recorded_oop_at(int i) {
 691   return (_code != NULL)
 692          ? _code->oop_at(i)
 693     : JNIHandles::resolve(_deps->oop_recorder()->oop_at(i));
 694 }
 695 
 696 Metadata* Dependencies::DepStream::argument(int i) {
 697   Metadata* result = recorded_metadata_at(argument_index(i));
 698 
 699   if (result == NULL) { // Explicit context argument can be compressed
 700     int ctxkj = dep_context_arg(type());  // -1 if no explicit context arg
 701     if (ctxkj >= 0 && i == ctxkj && ctxkj+1 < argument_count()) {
 702       result = ctxk_encoded_as_null(type(), argument(ctxkj+1));
 703     }
 704   }
 705 
 706   assert(result == NULL || result->is_klass() || result->is_method(), "must be");
 707   return result;
 708 }
 709 
 710 /**
 711  * Returns a unique identifier for each dependency argument.
 712  */
 713 uintptr_t Dependencies::DepStream::get_identifier(int i) {
 714   if (is_oop_argument(i)) {
 715     return (uintptr_t)(oopDesc*)argument_oop(i);
 716   } else {
 717     return (uintptr_t)argument(i);
 718   }
 719 }
 720 
 721 oop Dependencies::DepStream::argument_oop(int i) {
 722   oop result = recorded_oop_at(argument_index(i));
 723   assert(result == NULL || result->is_oop(), "must be");
 724   return result;
 725 }
 726 
 727 Klass* Dependencies::DepStream::context_type() {
 728   assert(must_be_in_vm(), "raw oops here");
 729 
 730   // Most dependencies have an explicit context type argument.
 731   {
 732     int ctxkj = dep_context_arg(type());  // -1 if no explicit context arg
 733     if (ctxkj >= 0) {
 734       Metadata* k = argument(ctxkj);
 735       assert(k != NULL && k->is_klass(), "type check");
 736       return (Klass*)k;
 737     }
 738   }
 739 
 740   // Some dependencies are using the klass of the first object
 741   // argument as implicit context type.
 742   {
 743     int ctxkj = dep_implicit_context_arg(type());
 744     if (ctxkj >= 0) {
 745       Klass* k = argument_oop(ctxkj)->klass();
 746       assert(k != NULL && k->is_klass(), "type check");
 747       return (Klass*) k;
 748     }
 749   }
 750 
 751   // And some dependencies don't have a context type at all,
 752   // e.g. evol_method.
 753   return NULL;
 754 }
 755 
 756 // ----------------- DependencySignature --------------------------------------
 757 bool DependencySignature::equals(DependencySignature const& s1, DependencySignature const& s2) {
 758   if ((s1.type() != s2.type()) || (s1.args_count() != s2.args_count())) {
 759     return false;
 760   }
 761 
 762   for (int i = 0; i < s1.args_count(); i++) {
 763     if (s1.arg(i) != s2.arg(i)) {
 764       return false;
 765     }
 766   }
 767   return true;
 768 }
 769 
 770 /// Checking dependencies:
 771 
 772 // This hierarchy walker inspects subtypes of a given type,
 773 // trying to find a "bad" class which breaks a dependency.
 774 // Such a class is called a "witness" to the broken dependency.
 775 // While searching around, we ignore "participants", which
 776 // are already known to the dependency.
 777 class ClassHierarchyWalker {
 778  public:
 779   enum { PARTICIPANT_LIMIT = 3 };
 780 
 781  private:
 782   // optional method descriptor to check for:
 783   Symbol* _name;
 784   Symbol* _signature;
 785 
 786   // special classes which are not allowed to be witnesses:
 787   Klass*    _participants[PARTICIPANT_LIMIT+1];
 788   int       _num_participants;
 789 
 790   // cache of method lookups
 791   Method* _found_methods[PARTICIPANT_LIMIT+1];
 792 
 793   // if non-zero, tells how many witnesses to convert to participants
 794   int       _record_witnesses;
 795 
 796   void initialize(Klass* participant) {
 797     _record_witnesses = 0;
 798     _participants[0]  = participant;
 799     _found_methods[0] = NULL;
 800     _num_participants = 0;
 801     if (participant != NULL) {
 802       // Terminating NULL.
 803       _participants[1] = NULL;
 804       _found_methods[1] = NULL;
 805       _num_participants = 1;
 806     }
 807   }
 808 
 809   void initialize_from_method(Method* m) {
 810     assert(m != NULL && m->is_method(), "sanity");
 811     _name      = m->name();
 812     _signature = m->signature();
 813   }
 814 
 815  public:
 816   // The walker is initialized to recognize certain methods and/or types
 817   // as friendly participants.
 818   ClassHierarchyWalker(Klass* participant, Method* m) {
 819     initialize_from_method(m);
 820     initialize(participant);
 821   }
 822   ClassHierarchyWalker(Method* m) {
 823     initialize_from_method(m);
 824     initialize(NULL);
 825   }
 826   ClassHierarchyWalker(Klass* participant = NULL) {
 827     _name      = NULL;
 828     _signature = NULL;
 829     initialize(participant);
 830   }
 831 
 832   // This is common code for two searches:  One for concrete subtypes,
 833   // the other for concrete method implementations and overrides.
 834   bool doing_subtype_search() {
 835     return _name == NULL;
 836   }
 837 
 838   int num_participants() { return _num_participants; }
 839   Klass* participant(int n) {
 840     assert((uint)n <= (uint)_num_participants, "oob");
 841     return _participants[n];
 842   }
 843 
 844   // Note:  If n==num_participants, returns NULL.
 845   Method* found_method(int n) {
 846     assert((uint)n <= (uint)_num_participants, "oob");
 847     Method* fm = _found_methods[n];
 848     assert(n == _num_participants || fm != NULL, "proper usage");
 849     if (fm != NULL && fm->method_holder() != _participants[n]) {
 850       // Default methods from interfaces can be added to classes. In
 851       // that case the holder of the method is not the class but the
 852       // interface where it's defined.
 853       assert(fm->is_default_method(), "sanity");
 854       return NULL;
 855     }
 856     return fm;
 857   }
 858 
 859 #ifdef ASSERT
 860   // Assert that m is inherited into ctxk, without intervening overrides.
 861   // (May return true even if this is not true, in corner cases where we punt.)
 862   bool check_method_context(Klass* ctxk, Method* m) {
 863     if (m->method_holder() == ctxk)
 864       return true;  // Quick win.
 865     if (m->is_private())
 866       return false; // Quick lose.  Should not happen.
 867     if (!(m->is_public() || m->is_protected()))
 868       // The override story is complex when packages get involved.
 869       return true;  // Must punt the assertion to true.
 870     Klass* k = ctxk;
 871     Method* lm = k->lookup_method(m->name(), m->signature());
 872     if (lm == NULL && k->oop_is_instance()) {
 873       // It might be an interface method
 874         lm = ((InstanceKlass*)k)->lookup_method_in_ordered_interfaces(m->name(),
 875                                                                 m->signature());
 876     }
 877     if (lm == m)
 878       // Method m is inherited into ctxk.
 879       return true;
 880     if (lm != NULL) {
 881       if (!(lm->is_public() || lm->is_protected())) {
 882         // Method is [package-]private, so the override story is complex.
 883         return true;  // Must punt the assertion to true.
 884       }
 885       if (lm->is_static()) {
 886         // Static methods don't override non-static so punt
 887         return true;
 888       }
 889       if (   !Dependencies::is_concrete_method(lm, k)
 890           && !Dependencies::is_concrete_method(m, ctxk)
 891           && lm->method_holder()->is_subtype_of(m->method_holder()))
 892         // Method m is overridden by lm, but both are non-concrete.
 893         return true;
 894     }
 895     ResourceMark rm;
 896     tty->print_cr("Dependency method not found in the associated context:");
 897     tty->print_cr("  context = %s", ctxk->external_name());
 898     tty->print(   "  method = "); m->print_short_name(tty); tty->cr();
 899     if (lm != NULL) {
 900       tty->print( "  found = "); lm->print_short_name(tty); tty->cr();
 901     }
 902     return false;
 903   }
 904 #endif
 905 
 906   void add_participant(Klass* participant) {
 907     assert(_num_participants + _record_witnesses < PARTICIPANT_LIMIT, "oob");
 908     int np = _num_participants++;
 909     _participants[np] = participant;
 910     _participants[np+1] = NULL;
 911     _found_methods[np+1] = NULL;
 912   }
 913 
 914   void record_witnesses(int add) {
 915     if (add > PARTICIPANT_LIMIT)  add = PARTICIPANT_LIMIT;
 916     assert(_num_participants + add < PARTICIPANT_LIMIT, "oob");
 917     _record_witnesses = add;
 918   }
 919 
 920   bool is_witness(Klass* k) {
 921     if (doing_subtype_search()) {
 922       return Dependencies::is_concrete_klass(k);
 923     } else if (!k->oop_is_instance()) {
 924       return false; // no methods to find in an array type
 925     } else {
 926       // Search class hierarchy first.
 927       Method* m = InstanceKlass::cast(k)->find_instance_method(_name, _signature);
 928       if (!Dependencies::is_concrete_method(m, k)) {
 929         // Check interface defaults also, if any exist.
 930         Array<Method*>* default_methods = InstanceKlass::cast(k)->default_methods();
 931         if (default_methods == NULL)
 932             return false;
 933         m = InstanceKlass::cast(k)->find_method(default_methods, _name, _signature);
 934         if (!Dependencies::is_concrete_method(m, NULL))
 935             return false;
 936       }
 937       _found_methods[_num_participants] = m;
 938       // Note:  If add_participant(k) is called,
 939       // the method m will already be memoized for it.
 940       return true;
 941     }
 942   }
 943 
 944   bool is_participant(Klass* k) {
 945     if (k == _participants[0]) {
 946       return true;
 947     } else if (_num_participants <= 1) {
 948       return false;
 949     } else {
 950       return in_list(k, &_participants[1]);
 951     }
 952   }
 953   bool ignore_witness(Klass* witness) {
 954     if (_record_witnesses == 0) {
 955       return false;
 956     } else {
 957       --_record_witnesses;
 958       add_participant(witness);
 959       return true;
 960     }
 961   }
 962   static bool in_list(Klass* x, Klass** list) {
 963     for (int i = 0; ; i++) {
 964       Klass* y = list[i];
 965       if (y == NULL)  break;
 966       if (y == x)  return true;
 967     }
 968     return false;  // not in list
 969   }
 970 
 971  private:
 972   // the actual search method:
 973   Klass* find_witness_anywhere(Klass* context_type,
 974                                  bool participants_hide_witnesses,
 975                                  bool top_level_call = true);
 976   // the spot-checking version:
 977   Klass* find_witness_in(KlassDepChange& changes,
 978                          Klass* context_type,
 979                            bool participants_hide_witnesses);
 980  public:
 981   Klass* find_witness_subtype(Klass* context_type, KlassDepChange* changes = NULL) {
 982     assert(doing_subtype_search(), "must set up a subtype search");
 983     // When looking for unexpected concrete types,
 984     // do not look beneath expected ones.
 985     const bool participants_hide_witnesses = true;
 986     // CX > CC > C' is OK, even if C' is new.
 987     // CX > { CC,  C' } is not OK if C' is new, and C' is the witness.
 988     if (changes != NULL) {
 989       return find_witness_in(*changes, context_type, participants_hide_witnesses);
 990     } else {
 991       return find_witness_anywhere(context_type, participants_hide_witnesses);
 992     }
 993   }
 994   Klass* find_witness_definer(Klass* context_type, KlassDepChange* changes = NULL) {
 995     assert(!doing_subtype_search(), "must set up a method definer search");
 996     // When looking for unexpected concrete methods,
 997     // look beneath expected ones, to see if there are overrides.
 998     const bool participants_hide_witnesses = true;
 999     // CX.m > CC.m > C'.m is not OK, if C'.m is new, and C' is the witness.
1000     if (changes != NULL) {
1001       return find_witness_in(*changes, context_type, !participants_hide_witnesses);
1002     } else {
1003       return find_witness_anywhere(context_type, !participants_hide_witnesses);
1004     }
1005   }
1006 };
1007 
1008 #ifndef PRODUCT
1009 static int deps_find_witness_calls = 0;
1010 static int deps_find_witness_steps = 0;
1011 static int deps_find_witness_recursions = 0;
1012 static int deps_find_witness_singles = 0;
1013 static int deps_find_witness_print = 0; // set to -1 to force a final print
1014 static bool count_find_witness_calls() {
1015   if (TraceDependencies || LogCompilation) {
1016     int pcount = deps_find_witness_print + 1;
1017     bool final_stats      = (pcount == 0);
1018     bool initial_call     = (pcount == 1);
1019     bool occasional_print = ((pcount & ((1<<10) - 1)) == 0);
1020     if (pcount < 0)  pcount = 1; // crude overflow protection
1021     deps_find_witness_print = pcount;
1022     if (VerifyDependencies && initial_call) {
1023       tty->print_cr("Warning:  TraceDependencies results may be inflated by VerifyDependencies");
1024     }
1025     if (occasional_print || final_stats) {
1026       // Every now and then dump a little info about dependency searching.
1027       if (xtty != NULL) {
1028        ttyLocker ttyl;
1029        xtty->elem("deps_find_witness calls='%d' steps='%d' recursions='%d' singles='%d'",
1030                    deps_find_witness_calls,
1031                    deps_find_witness_steps,
1032                    deps_find_witness_recursions,
1033                    deps_find_witness_singles);
1034       }
1035       if (final_stats || (TraceDependencies && WizardMode)) {
1036         ttyLocker ttyl;
1037         tty->print_cr("Dependency check (find_witness) "
1038                       "calls=%d, steps=%d (avg=%.1f), recursions=%d, singles=%d",
1039                       deps_find_witness_calls,
1040                       deps_find_witness_steps,
1041                       (double)deps_find_witness_steps / deps_find_witness_calls,
1042                       deps_find_witness_recursions,
1043                       deps_find_witness_singles);
1044       }
1045     }
1046     return true;
1047   }
1048   return false;
1049 }
1050 #else
1051 #define count_find_witness_calls() (0)
1052 #endif //PRODUCT
1053 
1054 
1055 Klass* ClassHierarchyWalker::find_witness_in(KlassDepChange& changes,
1056                                                Klass* context_type,
1057                                                bool participants_hide_witnesses) {
1058   assert(changes.involves_context(context_type), "irrelevant dependency");
1059   Klass* new_type = changes.new_type();
1060 
1061   (void)count_find_witness_calls();
1062   NOT_PRODUCT(deps_find_witness_singles++);
1063 
1064   // Current thread must be in VM (not native mode, as in CI):
1065   assert(must_be_in_vm(), "raw oops here");
1066   // Must not move the class hierarchy during this check:
1067   assert_locked_or_safepoint(Compile_lock);
1068 
1069   int nof_impls = InstanceKlass::cast(context_type)->nof_implementors();
1070   if (nof_impls > 1) {
1071     // Avoid this case: *I.m > { A.m, C }; B.m > C
1072     // %%% Until this is fixed more systematically, bail out.
1073     // See corresponding comment in find_witness_anywhere.
1074     return context_type;
1075   }
1076 
1077   assert(!is_participant(new_type), "only old classes are participants");
1078   if (participants_hide_witnesses) {
1079     // If the new type is a subtype of a participant, we are done.
1080     for (int i = 0; i < num_participants(); i++) {
1081       Klass* part = participant(i);
1082       if (part == NULL)  continue;
1083       assert(changes.involves_context(part) == new_type->is_subtype_of(part),
1084              "correct marking of participants, b/c new_type is unique");
1085       if (changes.involves_context(part)) {
1086         // new guy is protected from this check by previous participant
1087         return NULL;
1088       }
1089     }
1090   }
1091 
1092   if (is_witness(new_type) &&
1093       !ignore_witness(new_type)) {
1094     return new_type;
1095   }
1096 
1097   return NULL;
1098 }
1099 
1100 
1101 // Walk hierarchy under a context type, looking for unexpected types.
1102 // Do not report participant types, and recursively walk beneath
1103 // them only if participants_hide_witnesses is false.
1104 // If top_level_call is false, skip testing the context type,
1105 // because the caller has already considered it.
1106 Klass* ClassHierarchyWalker::find_witness_anywhere(Klass* context_type,
1107                                                      bool participants_hide_witnesses,
1108                                                      bool top_level_call) {
1109   // Current thread must be in VM (not native mode, as in CI):
1110   assert(must_be_in_vm(), "raw oops here");
1111   // Must not move the class hierarchy during this check:
1112   assert_locked_or_safepoint(Compile_lock);
1113 
1114   bool do_counts = count_find_witness_calls();
1115 
1116   // Check the root of the sub-hierarchy first.
1117   if (top_level_call) {
1118     if (do_counts) {
1119       NOT_PRODUCT(deps_find_witness_calls++);
1120       NOT_PRODUCT(deps_find_witness_steps++);
1121     }
1122     if (is_participant(context_type)) {
1123       if (participants_hide_witnesses)  return NULL;
1124       // else fall through to search loop...
1125     } else if (is_witness(context_type) && !ignore_witness(context_type)) {
1126       // The context is an abstract class or interface, to start with.
1127       return context_type;
1128     }
1129   }
1130 
1131   // Now we must check each implementor and each subclass.
1132   // Use a short worklist to avoid blowing the stack.
1133   // Each worklist entry is a *chain* of subklass siblings to process.
1134   const int CHAINMAX = 100;  // >= 1 + InstanceKlass::implementors_limit
1135   Klass* chains[CHAINMAX];
1136   int    chaini = 0;  // index into worklist
1137   Klass* chain;       // scratch variable
1138 #define ADD_SUBCLASS_CHAIN(k)                     {  \
1139     assert(chaini < CHAINMAX, "oob");                \
1140     chain = k->subklass();                           \
1141     if (chain != NULL)  chains[chaini++] = chain;    }
1142 
1143   // Look for non-abstract subclasses.
1144   // (Note:  Interfaces do not have subclasses.)
1145   ADD_SUBCLASS_CHAIN(context_type);
1146 
1147   // If it is an interface, search its direct implementors.
1148   // (Their subclasses are additional indirect implementors.
1149   // See InstanceKlass::add_implementor.)
1150   // (Note:  nof_implementors is always zero for non-interfaces.)
1151   if (top_level_call) {
1152     int nof_impls = InstanceKlass::cast(context_type)->nof_implementors();
1153     if (nof_impls > 1) {
1154       // Avoid this case: *I.m > { A.m, C }; B.m > C
1155       // Here, I.m has 2 concrete implementations, but m appears unique
1156       // as A.m, because the search misses B.m when checking C.
1157       // The inherited method B.m was getting missed by the walker
1158       // when interface 'I' was the starting point.
1159       // %%% Until this is fixed more systematically, bail out.
1160       // (Old CHA had the same limitation.)
1161       return context_type;
1162     }
1163     if (nof_impls > 0) {
1164       Klass* impl = InstanceKlass::cast(context_type)->implementor();
1165       assert(impl != NULL, "just checking");
1166       // If impl is the same as the context_type, then more than one
1167       // implementor has seen. No exact info in this case.
1168       if (impl == context_type) {
1169         return context_type;  // report an inexact witness to this sad affair
1170       }
1171       if (do_counts)
1172         { NOT_PRODUCT(deps_find_witness_steps++); }
1173       if (is_participant(impl)) {
1174         if (!participants_hide_witnesses) {
1175           ADD_SUBCLASS_CHAIN(impl);
1176         }
1177       } else if (is_witness(impl) && !ignore_witness(impl)) {
1178         return impl;
1179       } else {
1180         ADD_SUBCLASS_CHAIN(impl);
1181       }
1182     }
1183   }
1184 
1185   // Recursively process each non-trivial sibling chain.
1186   while (chaini > 0) {
1187     Klass* chain = chains[--chaini];
1188     for (Klass* sub = chain; sub != NULL; sub = sub->next_sibling()) {
1189       if (do_counts) { NOT_PRODUCT(deps_find_witness_steps++); }
1190       if (is_participant(sub)) {
1191         if (participants_hide_witnesses)  continue;
1192         // else fall through to process this guy's subclasses
1193       } else if (is_witness(sub) && !ignore_witness(sub)) {
1194         return sub;
1195       }
1196       if (chaini < (VerifyDependencies? 2: CHAINMAX)) {
1197         // Fast path.  (Partially disabled if VerifyDependencies.)
1198         ADD_SUBCLASS_CHAIN(sub);
1199       } else {
1200         // Worklist overflow.  Do a recursive call.  Should be rare.
1201         // The recursive call will have its own worklist, of course.
1202         // (Note that sub has already been tested, so that there is
1203         // no need for the recursive call to re-test.  That's handy,
1204         // since the recursive call sees sub as the context_type.)
1205         if (do_counts) { NOT_PRODUCT(deps_find_witness_recursions++); }
1206         Klass* witness = find_witness_anywhere(sub,
1207                                                  participants_hide_witnesses,
1208                                                  /*top_level_call=*/ false);
1209         if (witness != NULL)  return witness;
1210       }
1211     }
1212   }
1213 
1214   // No witness found.  The dependency remains unbroken.
1215   return NULL;
1216 #undef ADD_SUBCLASS_CHAIN
1217 }
1218 
1219 
1220 bool Dependencies::is_concrete_klass(Klass* k) {
1221   if (k->is_abstract())  return false;
1222   // %%% We could treat classes which are concrete but
1223   // have not yet been instantiated as virtually abstract.
1224   // This would require a deoptimization barrier on first instantiation.
1225   //if (k->is_not_instantiated())  return false;
1226   return true;
1227 }
1228 
1229 bool Dependencies::is_concrete_method(Method* m, Klass * k) {
1230   // NULL is not a concrete method,
1231   // statics are irrelevant to virtual call sites,
1232   // abstract methods are not concrete,
1233   // overpass (error) methods are not concrete if k is abstract
1234   //
1235   // note "true" is conservative answer --
1236   //     overpass clause is false if k == NULL, implies return true if
1237   //     answer depends on overpass clause.
1238   return ! ( m == NULL || m -> is_static() || m -> is_abstract() ||
1239              m->is_overpass() && k != NULL && k -> is_abstract() );
1240 }
1241 
1242 
1243 Klass* Dependencies::find_finalizable_subclass(Klass* k) {
1244   if (k->is_interface())  return NULL;
1245   if (k->has_finalizer()) return k;
1246   k = k->subklass();
1247   while (k != NULL) {
1248     Klass* result = find_finalizable_subclass(k);
1249     if (result != NULL) return result;
1250     k = k->next_sibling();
1251   }
1252   return NULL;
1253 }
1254 
1255 
1256 bool Dependencies::is_concrete_klass(ciInstanceKlass* k) {
1257   if (k->is_abstract())  return false;
1258   // We could also return false if k does not yet appear to be
1259   // instantiated, if the VM version supports this distinction also.
1260   //if (k->is_not_instantiated())  return false;
1261   return true;
1262 }
1263 
1264 bool Dependencies::has_finalizable_subclass(ciInstanceKlass* k) {
1265   return k->has_finalizable_subclass();
1266 }
1267 
1268 
1269 // Any use of the contents (bytecodes) of a method must be
1270 // marked by an "evol_method" dependency, if those contents
1271 // can change.  (Note: A method is always dependent on itself.)
1272 Klass* Dependencies::check_evol_method(Method* m) {
1273   assert(must_be_in_vm(), "raw oops here");
1274   // Did somebody do a JVMTI RedefineClasses while our backs were turned?
1275   // Or is there a now a breakpoint?
1276   // (Assumes compiled code cannot handle bkpts; change if UseFastBreakpoints.)
1277   if (m->is_old()
1278       || m->number_of_breakpoints() > 0) {
1279     return m->method_holder();
1280   } else {
1281     return NULL;
1282   }
1283 }
1284 
1285 // This is a strong assertion:  It is that the given type
1286 // has no subtypes whatever.  It is most useful for
1287 // optimizing checks on reflected types or on array types.
1288 // (Checks on types which are derived from real instances
1289 // can be optimized more strongly than this, because we
1290 // know that the checked type comes from a concrete type,
1291 // and therefore we can disregard abstract types.)
1292 Klass* Dependencies::check_leaf_type(Klass* ctxk) {
1293   assert(must_be_in_vm(), "raw oops here");
1294   assert_locked_or_safepoint(Compile_lock);
1295   InstanceKlass* ctx = InstanceKlass::cast(ctxk);
1296   Klass* sub = ctx->subklass();
1297   if (sub != NULL) {
1298     return sub;
1299   } else if (ctx->nof_implementors() != 0) {
1300     // if it is an interface, it must be unimplemented
1301     // (if it is not an interface, nof_implementors is always zero)
1302     Klass* impl = ctx->implementor();
1303     assert(impl != NULL, "must be set");
1304     return impl;
1305   } else {
1306     return NULL;
1307   }
1308 }
1309 
1310 // Test the assertion that conck is the only concrete subtype* of ctxk.
1311 // The type conck itself is allowed to have have further concrete subtypes.
1312 // This allows the compiler to narrow occurrences of ctxk by conck,
1313 // when dealing with the types of actual instances.
1314 Klass* Dependencies::check_abstract_with_unique_concrete_subtype(Klass* ctxk,
1315                                                                    Klass* conck,
1316                                                                    KlassDepChange* changes) {
1317   ClassHierarchyWalker wf(conck);
1318   return wf.find_witness_subtype(ctxk, changes);
1319 }
1320 
1321 // If a non-concrete class has no concrete subtypes, it is not (yet)
1322 // instantiatable.  This can allow the compiler to make some paths go
1323 // dead, if they are gated by a test of the type.
1324 Klass* Dependencies::check_abstract_with_no_concrete_subtype(Klass* ctxk,
1325                                                                KlassDepChange* changes) {
1326   // Find any concrete subtype, with no participants:
1327   ClassHierarchyWalker wf;
1328   return wf.find_witness_subtype(ctxk, changes);
1329 }
1330 
1331 
1332 // If a concrete class has no concrete subtypes, it can always be
1333 // exactly typed.  This allows the use of a cheaper type test.
1334 Klass* Dependencies::check_concrete_with_no_concrete_subtype(Klass* ctxk,
1335                                                                KlassDepChange* changes) {
1336   // Find any concrete subtype, with only the ctxk as participant:
1337   ClassHierarchyWalker wf(ctxk);
1338   return wf.find_witness_subtype(ctxk, changes);
1339 }
1340 
1341 
1342 // Find the unique concrete proper subtype of ctxk, or NULL if there
1343 // is more than one concrete proper subtype.  If there are no concrete
1344 // proper subtypes, return ctxk itself, whether it is concrete or not.
1345 // The returned subtype is allowed to have have further concrete subtypes.
1346 // That is, return CC1 for CX > CC1 > CC2, but NULL for CX > { CC1, CC2 }.
1347 Klass* Dependencies::find_unique_concrete_subtype(Klass* ctxk) {
1348   ClassHierarchyWalker wf(ctxk);   // Ignore ctxk when walking.
1349   wf.record_witnesses(1);          // Record one other witness when walking.
1350   Klass* wit = wf.find_witness_subtype(ctxk);
1351   if (wit != NULL)  return NULL;   // Too many witnesses.
1352   Klass* conck = wf.participant(0);
1353   if (conck == NULL) {
1354 #ifndef PRODUCT
1355     // Make sure the dependency mechanism will pass this discovery:
1356     if (VerifyDependencies) {
1357       // Turn off dependency tracing while actually testing deps.
1358       FlagSetting fs(TraceDependencies, false);
1359       if (!Dependencies::is_concrete_klass(ctxk)) {
1360         guarantee(NULL ==
1361                   (void *)check_abstract_with_no_concrete_subtype(ctxk),
1362                   "verify dep.");
1363       } else {
1364         guarantee(NULL ==
1365                   (void *)check_concrete_with_no_concrete_subtype(ctxk),
1366                   "verify dep.");
1367       }
1368     }
1369 #endif //PRODUCT
1370     return ctxk;                   // Return ctxk as a flag for "no subtypes".
1371   } else {
1372 #ifndef PRODUCT
1373     // Make sure the dependency mechanism will pass this discovery:
1374     if (VerifyDependencies) {
1375       // Turn off dependency tracing while actually testing deps.
1376       FlagSetting fs(TraceDependencies, false);
1377       if (!Dependencies::is_concrete_klass(ctxk)) {
1378         guarantee(NULL == (void *)
1379                   check_abstract_with_unique_concrete_subtype(ctxk, conck),
1380                   "verify dep.");
1381       }
1382     }
1383 #endif //PRODUCT
1384     return conck;
1385   }
1386 }
1387 
1388 // Test the assertion that the k[12] are the only concrete subtypes of ctxk,
1389 // except possibly for further subtypes of k[12] themselves.
1390 // The context type must be abstract.  The types k1 and k2 are themselves
1391 // allowed to have further concrete subtypes.
1392 Klass* Dependencies::check_abstract_with_exclusive_concrete_subtypes(
1393                                                 Klass* ctxk,
1394                                                 Klass* k1,
1395                                                 Klass* k2,
1396                                                 KlassDepChange* changes) {
1397   ClassHierarchyWalker wf;
1398   wf.add_participant(k1);
1399   wf.add_participant(k2);
1400   return wf.find_witness_subtype(ctxk, changes);
1401 }
1402 
1403 // Search ctxk for concrete implementations.  If there are klen or fewer,
1404 // pack them into the given array and return the number.
1405 // Otherwise, return -1, meaning the given array would overflow.
1406 // (Note that a return of 0 means there are exactly no concrete subtypes.)
1407 // In this search, if ctxk is concrete, it will be reported alone.
1408 // For any type CC reported, no proper subtypes of CC will be reported.
1409 int Dependencies::find_exclusive_concrete_subtypes(Klass* ctxk,
1410                                                    int klen,
1411                                                    Klass* karray[]) {
1412   ClassHierarchyWalker wf;
1413   wf.record_witnesses(klen);
1414   Klass* wit = wf.find_witness_subtype(ctxk);
1415   if (wit != NULL)  return -1;  // Too many witnesses.
1416   int num = wf.num_participants();
1417   assert(num <= klen, "oob");
1418   // Pack the result array with the good news.
1419   for (int i = 0; i < num; i++)
1420     karray[i] = wf.participant(i);
1421 #ifndef PRODUCT
1422   // Make sure the dependency mechanism will pass this discovery:
1423   if (VerifyDependencies) {
1424     // Turn off dependency tracing while actually testing deps.
1425     FlagSetting fs(TraceDependencies, false);
1426     switch (Dependencies::is_concrete_klass(ctxk)? -1: num) {
1427     case -1: // ctxk was itself concrete
1428       guarantee(num == 1 && karray[0] == ctxk, "verify dep.");
1429       break;
1430     case 0:
1431       guarantee(NULL == (void *)check_abstract_with_no_concrete_subtype(ctxk),
1432                 "verify dep.");
1433       break;
1434     case 1:
1435       guarantee(NULL == (void *)
1436                 check_abstract_with_unique_concrete_subtype(ctxk, karray[0]),
1437                 "verify dep.");
1438       break;
1439     case 2:
1440       guarantee(NULL == (void *)
1441                 check_abstract_with_exclusive_concrete_subtypes(ctxk,
1442                                                                 karray[0],
1443                                                                 karray[1]),
1444                 "verify dep.");
1445       break;
1446     default:
1447       ShouldNotReachHere();  // klen > 2 yet supported
1448     }
1449   }
1450 #endif //PRODUCT
1451   return num;
1452 }
1453 
1454 // If a class (or interface) has a unique concrete method uniqm, return NULL.
1455 // Otherwise, return a class that contains an interfering method.
1456 Klass* Dependencies::check_unique_concrete_method(Klass* ctxk, Method* uniqm,
1457                                                     KlassDepChange* changes) {
1458   // Here is a missing optimization:  If uniqm->is_final(),
1459   // we don't really need to search beneath it for overrides.
1460   // This is probably not important, since we don't use dependencies
1461   // to track final methods.  (They can't be "definalized".)
1462   ClassHierarchyWalker wf(uniqm->method_holder(), uniqm);
1463   return wf.find_witness_definer(ctxk, changes);
1464 }
1465 
1466 // Find the set of all non-abstract methods under ctxk that match m.
1467 // (The method m must be defined or inherited in ctxk.)
1468 // Include m itself in the set, unless it is abstract.
1469 // If this set has exactly one element, return that element.
1470 Method* Dependencies::find_unique_concrete_method(Klass* ctxk, Method* m) {
1471   // Return NULL if m is marked old; must have been a redefined method.
1472   if (m->is_old()) {
1473     return NULL;
1474   }
1475   ClassHierarchyWalker wf(m);
1476   assert(wf.check_method_context(ctxk, m), "proper context");
1477   wf.record_witnesses(1);
1478   Klass* wit = wf.find_witness_definer(ctxk);
1479   if (wit != NULL)  return NULL;  // Too many witnesses.
1480   Method* fm = wf.found_method(0);  // Will be NULL if num_parts == 0.
1481   if (Dependencies::is_concrete_method(m, ctxk)) {
1482     if (fm == NULL) {
1483       // It turns out that m was always the only implementation.
1484       fm = m;
1485     } else if (fm != m) {
1486       // Two conflicting implementations after all.
1487       // (This can happen if m is inherited into ctxk and fm overrides it.)
1488       return NULL;
1489     }
1490   }
1491 #ifndef PRODUCT
1492   // Make sure the dependency mechanism will pass this discovery:
1493   if (VerifyDependencies && fm != NULL) {
1494     guarantee(NULL == (void *)check_unique_concrete_method(ctxk, fm),
1495               "verify dep.");
1496   }
1497 #endif //PRODUCT
1498   return fm;
1499 }
1500 
1501 Klass* Dependencies::check_exclusive_concrete_methods(Klass* ctxk,
1502                                                         Method* m1,
1503                                                         Method* m2,
1504                                                         KlassDepChange* changes) {
1505   ClassHierarchyWalker wf(m1);
1506   wf.add_participant(m1->method_holder());
1507   wf.add_participant(m2->method_holder());
1508   return wf.find_witness_definer(ctxk, changes);
1509 }
1510 
1511 Klass* Dependencies::check_has_no_finalizable_subclasses(Klass* ctxk, KlassDepChange* changes) {
1512   Klass* search_at = ctxk;
1513   if (changes != NULL)
1514     search_at = changes->new_type(); // just look at the new bit
1515   return find_finalizable_subclass(search_at);
1516 }
1517 
1518 Klass* Dependencies::check_call_site_target_value(Klass* recorded_ctxk, oop call_site, oop method_handle, CallSiteDepChange* changes) {
1519   assert(call_site->is_a(SystemDictionary::CallSite_klass()),     "sanity");
1520   assert(!oopDesc::is_null(method_handle), "sanity");
1521 
1522   Klass* call_site_ctxk = MethodHandles::get_call_site_context(call_site);
1523   assert(!Klass::is_null(call_site_ctxk), "call site context should be initialized already");
1524   if (recorded_ctxk != call_site_ctxk) {
1525     // Stale context
1526     return recorded_ctxk;
1527   }
1528   if (changes == NULL) {
1529     // Validate all CallSites
1530     if (java_lang_invoke_CallSite::target(call_site) != method_handle)
1531       return call_site->klass();  // assertion failed
1532   } else {
1533     // Validate the given CallSite
1534     if (call_site == changes->call_site() && java_lang_invoke_CallSite::target(call_site) != changes->method_handle()) {
1535       assert(method_handle != changes->method_handle(), "must be");
1536       return call_site->klass();  // assertion failed
1537     }
1538   }
1539   return NULL;  // assertion still valid
1540 }
1541 
1542 void Dependencies::DepStream::trace_and_log_witness(Klass* witness) {
1543   if (witness != NULL) {
1544     if (TraceDependencies) {
1545       print_dependency(witness, /*verbose=*/ true);
1546     }
1547     // The following is a no-op unless logging is enabled:
1548     log_dependency(witness);
1549   }
1550 }
1551 
1552 
1553 Klass* Dependencies::DepStream::check_klass_dependency(KlassDepChange* changes) {
1554   assert_locked_or_safepoint(Compile_lock);
1555   Dependencies::check_valid_dependency_type(type());
1556 
1557   Klass* witness = NULL;
1558   switch (type()) {
1559   case evol_method:
1560     witness = check_evol_method(method_argument(0));
1561     break;
1562   case leaf_type:
1563     witness = check_leaf_type(context_type());
1564     break;
1565   case abstract_with_unique_concrete_subtype:
1566     witness = check_abstract_with_unique_concrete_subtype(context_type(), type_argument(1), changes);
1567     break;
1568   case abstract_with_no_concrete_subtype:
1569     witness = check_abstract_with_no_concrete_subtype(context_type(), changes);
1570     break;
1571   case concrete_with_no_concrete_subtype:
1572     witness = check_concrete_with_no_concrete_subtype(context_type(), changes);
1573     break;
1574   case unique_concrete_method:
1575     witness = check_unique_concrete_method(context_type(), method_argument(1), changes);
1576     break;
1577   case abstract_with_exclusive_concrete_subtypes_2:
1578     witness = check_abstract_with_exclusive_concrete_subtypes(context_type(), type_argument(1), type_argument(2), changes);
1579     break;
1580   case exclusive_concrete_methods_2:
1581     witness = check_exclusive_concrete_methods(context_type(), method_argument(1), method_argument(2), changes);
1582     break;
1583   case no_finalizable_subclasses:
1584     witness = check_has_no_finalizable_subclasses(context_type(), changes);
1585     break;
1586   default:
1587     witness = NULL;
1588     break;
1589   }
1590   trace_and_log_witness(witness);
1591   return witness;
1592 }
1593 
1594 
1595 Klass* Dependencies::DepStream::check_call_site_dependency(CallSiteDepChange* changes) {
1596   assert_locked_or_safepoint(Compile_lock);
1597   Dependencies::check_valid_dependency_type(type());
1598 
1599   Klass* witness = NULL;
1600   switch (type()) {
1601   case call_site_target_value:
1602     witness = check_call_site_target_value(context_type(), argument_oop(1), argument_oop(2), changes);
1603     break;
1604   default:
1605     witness = NULL;
1606     break;
1607   }
1608   trace_and_log_witness(witness);
1609   return witness;
1610 }
1611 
1612 
1613 Klass* Dependencies::DepStream::spot_check_dependency_at(DepChange& changes) {
1614   // Handle klass dependency
1615   if (changes.is_klass_change() && changes.as_klass_change()->involves_context(context_type()))
1616     return check_klass_dependency(changes.as_klass_change());
1617 
1618   // Handle CallSite dependency
1619   if (changes.is_call_site_change())
1620     return check_call_site_dependency(changes.as_call_site_change());
1621 
1622   // irrelevant dependency; skip it
1623   return NULL;
1624 }
1625 
1626 
1627 void DepChange::print() {
1628   int nsup = 0, nint = 0;
1629   for (ContextStream str(*this); str.next(); ) {
1630     Klass* k = str.klass();
1631     switch (str.change_type()) {
1632     case Change_new_type:
1633       tty->print_cr("  dependee = %s", InstanceKlass::cast(k)->external_name());
1634       break;
1635     case Change_new_sub:
1636       if (!WizardMode) {
1637         ++nsup;
1638       } else {
1639         tty->print_cr("  context super = %s", InstanceKlass::cast(k)->external_name());
1640       }
1641       break;
1642     case Change_new_impl:
1643       if (!WizardMode) {
1644         ++nint;
1645       } else {
1646         tty->print_cr("  context interface = %s", InstanceKlass::cast(k)->external_name());
1647       }
1648       break;
1649     }
1650   }
1651   if (nsup + nint != 0) {
1652     tty->print_cr("  context supers = %d, interfaces = %d", nsup, nint);
1653   }
1654 }
1655 
1656 void DepChange::ContextStream::start() {
1657   Klass* new_type = _changes.is_klass_change() ? _changes.as_klass_change()->new_type() : (Klass*) NULL;
1658   _change_type = (new_type == NULL ? NO_CHANGE : Start_Klass);
1659   _klass = new_type;
1660   _ti_base = NULL;
1661   _ti_index = 0;
1662   _ti_limit = 0;
1663 }
1664 
1665 bool DepChange::ContextStream::next() {
1666   switch (_change_type) {
1667   case Start_Klass:             // initial state; _klass is the new type
1668     _ti_base = InstanceKlass::cast(_klass)->transitive_interfaces();
1669     _ti_index = 0;
1670     _change_type = Change_new_type;
1671     return true;
1672   case Change_new_type:
1673     // fall through:
1674     _change_type = Change_new_sub;
1675   case Change_new_sub:
1676     // 6598190: brackets workaround Sun Studio C++ compiler bug 6629277
1677     {
1678       _klass = InstanceKlass::cast(_klass)->super();
1679       if (_klass != NULL) {
1680         return true;
1681       }
1682     }
1683     // else set up _ti_limit and fall through:
1684     _ti_limit = (_ti_base == NULL) ? 0 : _ti_base->length();
1685     _change_type = Change_new_impl;
1686   case Change_new_impl:
1687     if (_ti_index < _ti_limit) {
1688       _klass = _ti_base->at(_ti_index++);
1689       return true;
1690     }
1691     // fall through:
1692     _change_type = NO_CHANGE;  // iterator is exhausted
1693   case NO_CHANGE:
1694     break;
1695   default:
1696     ShouldNotReachHere();
1697   }
1698   return false;
1699 }
1700 
1701 void KlassDepChange::initialize() {
1702   // entire transaction must be under this lock:
1703   assert_lock_strong(Compile_lock);
1704 
1705   // Mark all dependee and all its superclasses
1706   // Mark transitive interfaces
1707   for (ContextStream str(*this); str.next(); ) {
1708     Klass* d = str.klass();
1709     assert(!InstanceKlass::cast(d)->is_marked_dependent(), "checking");
1710     InstanceKlass::cast(d)->set_is_marked_dependent(true);
1711   }
1712 }
1713 
1714 KlassDepChange::~KlassDepChange() {
1715   // Unmark all dependee and all its superclasses
1716   // Unmark transitive interfaces
1717   for (ContextStream str(*this); str.next(); ) {
1718     Klass* d = str.klass();
1719     InstanceKlass::cast(d)->set_is_marked_dependent(false);
1720   }
1721 }
1722 
1723 bool KlassDepChange::involves_context(Klass* k) {
1724   if (k == NULL || !k->oop_is_instance()) {
1725     return false;
1726   }
1727   InstanceKlass* ik = InstanceKlass::cast(k);
1728   bool is_contained = ik->is_marked_dependent();
1729   assert(is_contained == new_type()->is_subtype_of(k),
1730          "correct marking of potential context types");
1731   return is_contained;
1732 }
1733 
1734 #ifndef PRODUCT
1735 void Dependencies::print_statistics() {
1736   if (deps_find_witness_print != 0) {
1737     // Call one final time, to flush out the data.
1738     deps_find_witness_print = -1;
1739     count_find_witness_calls();
1740   }
1741 }
1742 #endif