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