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