1 /*
   2  * Copyright (c) 1999, 2025, 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 "cds/aotLinkedClassBulkLoader.hpp"
  26 #include "ci/ciCallProfile.hpp"
  27 #include "ci/ciExceptionHandler.hpp"
  28 #include "ci/ciInstanceKlass.hpp"
  29 #include "ci/ciMethod.hpp"
  30 #include "ci/ciMethodBlocks.hpp"
  31 #include "ci/ciMethodData.hpp"
  32 #include "ci/ciStreams.hpp"
  33 #include "ci/ciSymbol.hpp"
  34 #include "ci/ciReplay.hpp"
  35 #include "ci/ciSymbols.hpp"
  36 #include "ci/ciUtilities.inline.hpp"
  37 #include "compiler/compileTask.hpp"
  38 #include "compiler/abstractCompiler.hpp"
  39 #include "compiler/compilerDefinitions.inline.hpp"
  40 #include "compiler/compilerOracle.hpp"
  41 #include "compiler/methodLiveness.hpp"
  42 #include "interpreter/interpreter.hpp"
  43 #include "interpreter/linkResolver.hpp"
  44 #include "interpreter/oopMapCache.hpp"
  45 #include "logging/log.hpp"
  46 #include "logging/logStream.hpp"
  47 #include "memory/allocation.inline.hpp"
  48 #include "memory/resourceArea.hpp"
  49 #include "oops/generateOopMap.hpp"
  50 #include "oops/method.inline.hpp"
  51 #include "oops/oop.inline.hpp"
  52 #include "oops/trainingData.hpp"
  53 #include "prims/methodHandles.hpp"
  54 #include "runtime/deoptimization.hpp"
  55 #include "runtime/handles.inline.hpp"
  56 #include "utilities/bitMap.inline.hpp"
  57 #include "utilities/xmlstream.hpp"
  58 #ifdef COMPILER2
  59 #include "ci/bcEscapeAnalyzer.hpp"
  60 #include "ci/ciTypeFlow.hpp"
  61 #include "oops/method.hpp"
  62 #endif
  63 
  64 // ciMethod
  65 //
  66 // This class represents a Method* in the HotSpot virtual
  67 // machine.
  68 
  69 
  70 // ------------------------------------------------------------------
  71 // ciMethod::ciMethod
  72 //
  73 // Loaded method.
  74 ciMethod::ciMethod(const methodHandle& h_m, ciInstanceKlass* holder) :
  75   ciMetadata(h_m()),
  76   _holder(holder)
  77 {
  78   assert(h_m() != nullptr, "no null method");
  79   assert(_holder->get_instanceKlass() == h_m->method_holder(), "");
  80 
  81   // These fields are always filled in in loaded methods.
  82   _flags = ciFlags(h_m->access_flags());
  83 
  84   // Easy to compute, so fill them in now.
  85   _max_stack          = h_m->max_stack();
  86   _max_locals         = h_m->max_locals();
  87   _code_size          = h_m->code_size();
  88   _handler_count      = h_m->exception_table_length();
  89   _size_of_parameters = h_m->size_of_parameters();
  90   _uses_monitors      = h_m->has_monitor_bytecodes();
  91   _balanced_monitors  = !_uses_monitors || h_m->guaranteed_monitor_matching();
  92   _is_c1_compilable   = !h_m->is_not_c1_compilable();
  93   _is_c2_compilable   = !h_m->is_not_c2_compilable();
  94   _can_be_parsed      = true;
  95   _has_reserved_stack_access = h_m->has_reserved_stack_access();
  96   _is_overpass        = h_m->is_overpass();
  97   // Lazy fields, filled in on demand.  Require allocation.
  98   _code               = nullptr;
  99   _exception_handlers = nullptr;
 100   _liveness           = nullptr;
 101   _method_blocks = nullptr;
 102 #if defined(COMPILER2)
 103   _flow               = nullptr;
 104   _bcea               = nullptr;
 105 #endif // COMPILER2
 106 
 107   // Check for blackhole intrinsic and then populate the intrinsic ID.
 108   CompilerOracle::tag_blackhole_if_possible(h_m);
 109   _intrinsic_id       = h_m->intrinsic_id();
 110 
 111   ciEnv *env = CURRENT_ENV;
 112   if (env->jvmti_can_hotswap_or_post_breakpoint()) {
 113     // 6328518 check hotswap conditions under the right lock.
 114     bool should_take_Compile_lock = !Compile_lock->owned_by_self();
 115     ConditionalMutexLocker locker(Compile_lock, should_take_Compile_lock, Mutex::_safepoint_check_flag);
 116     if (Dependencies::check_evol_method(h_m()) != nullptr) {
 117       _is_c1_compilable = false;
 118       _is_c2_compilable = false;
 119       _can_be_parsed = false;
 120     }
 121   } else {
 122     DEBUG_ONLY(CompilerThread::current()->check_possible_safepoint());
 123   }
 124 
 125   if (h_m->method_holder()->is_linked()) {
 126     _can_be_statically_bound = h_m->can_be_statically_bound();
 127     _can_omit_stack_trace = h_m->can_omit_stack_trace();
 128   } else {
 129     // Have to use a conservative value in this case.
 130     _can_be_statically_bound = false;
 131     _can_omit_stack_trace = true;
 132   }
 133 
 134   // Adjust the definition of this condition to be more useful:
 135   // %%% take these conditions into account in vtable generation
 136   if (!_can_be_statically_bound && h_m->is_private())
 137     _can_be_statically_bound = true;
 138   if (_can_be_statically_bound && h_m->is_abstract())
 139     _can_be_statically_bound = false;
 140 
 141   // generating _signature may allow GC and therefore move m.
 142   // These fields are always filled in.
 143   _name = env->get_symbol(h_m->name());
 144   ciSymbol* sig_symbol = env->get_symbol(h_m->signature());
 145   constantPoolHandle cpool(Thread::current(), h_m->constants());
 146   _signature = new (env->arena()) ciSignature(_holder, cpool, sig_symbol);
 147   _method_data = nullptr;
 148   _method_data_recorded = nullptr;
 149   // Take a snapshot of these values, so they will be commensurate with the MDO.
 150   if (ProfileInterpreter || CompilerConfig::is_c1_profiling()) {
 151     int invcnt = h_m->interpreter_invocation_count();
 152     // if the value overflowed report it as max int
 153     _interpreter_invocation_count = invcnt < 0 ? max_jint : invcnt ;
 154     _interpreter_throwout_count   = h_m->interpreter_throwout_count();
 155   } else {
 156     _interpreter_invocation_count = 0;
 157     _interpreter_throwout_count = 0;
 158   }
 159   if (_interpreter_invocation_count == 0)
 160     _interpreter_invocation_count = 1;
 161   _inline_instructions_size = -1;
 162   if (ReplayCompiles) {
 163     ciReplay::initialize(this);
 164   }
 165   DirectiveSet* directives = DirectivesStack::getMatchingDirective(h_m, CURRENT_ENV->task()->compiler());
 166   ccstrlist bci_list = directives->TooManyTrapsAtBCIOption;
 167   int len = (int)strlen(bci_list);
 168   Arena* arena = CURRENT_ENV->arena();
 169   _has_trap_at_bci = new (arena) GrowableArray<int>(arena, 2, 0, 0);
 170   for (int i = 0; i < len; i++) {
 171     int v = -1;
 172     int read;
 173     if (sscanf(bci_list + i, "%i%n", &v, &read) != 1) {
 174       warning("wrong format for TooManyTrapsAtBCI option: \"%s\"", bci_list);
 175       break;
 176     }
 177     assert(v >= 0 && v < (1<<16), "%i", v);
 178     _has_trap_at_bci->append_if_missing(v);
 179     i += read;
 180   }
 181 }
 182 
 183 
 184 // ------------------------------------------------------------------
 185 // ciMethod::ciMethod
 186 //
 187 // Unloaded method.
 188 ciMethod::ciMethod(ciInstanceKlass* holder,
 189                    ciSymbol*        name,
 190                    ciSymbol*        signature,
 191                    ciInstanceKlass* accessor) :
 192   ciMetadata((Metadata*)nullptr),
 193   _name(                   name),
 194   _holder(                 holder),
 195   _method_data(            nullptr),
 196   _method_data_recorded(   nullptr),
 197   _method_blocks(          nullptr),
 198   _intrinsic_id(           vmIntrinsics::_none),
 199   _inline_instructions_size(-1),
 200   _can_be_statically_bound(false),
 201   _can_omit_stack_trace(true),
 202   _has_trap_at_bci(        nullptr),
 203   _liveness(               nullptr)
 204 #if defined(COMPILER2)
 205   ,
 206   _flow(                   nullptr),
 207   _bcea(                   nullptr)
 208 #endif // COMPILER2
 209 {
 210   // Usually holder and accessor are the same type but in some cases
 211   // the holder has the wrong class loader (e.g. invokedynamic call
 212   // sites) so we pass the accessor.
 213   _signature = new (CURRENT_ENV->arena()) ciSignature(accessor, constantPoolHandle(), signature);
 214 }
 215 
 216 
 217 // ------------------------------------------------------------------
 218 // ciMethod::load_code
 219 //
 220 // Load the bytecodes and exception handler table for this method.
 221 void ciMethod::load_code() {
 222   VM_ENTRY_MARK;
 223   assert(is_loaded(), "only loaded methods have code");
 224 
 225   Method* me = get_Method();
 226   Arena* arena = CURRENT_THREAD_ENV->arena();
 227 
 228   // Load the bytecodes.
 229   _code = (address)arena->Amalloc(code_size());
 230   memcpy(_code, me->code_base(), code_size());
 231 
 232 #if INCLUDE_JVMTI
 233   // Revert any breakpoint bytecodes in ci's copy
 234   if (me->number_of_breakpoints() > 0) {
 235     BreakpointInfo* bp = me->method_holder()->breakpoints();
 236     for (; bp != nullptr; bp = bp->next()) {
 237       if (bp->match(me)) {
 238         code_at_put(bp->bci(), bp->orig_bytecode());
 239       }
 240     }
 241   }
 242 #endif
 243 
 244   // And load the exception table.
 245   ExceptionTable exc_table(me);
 246 
 247   // Allocate one extra spot in our list of exceptions.  This
 248   // last entry will be used to represent the possibility that
 249   // an exception escapes the method.  See ciExceptionHandlerStream
 250   // for details.
 251   _exception_handlers =
 252     (ciExceptionHandler**)arena->Amalloc(sizeof(ciExceptionHandler*)
 253                                          * (_handler_count + 1));
 254   if (_handler_count > 0) {
 255     for (int i=0; i<_handler_count; i++) {
 256       _exception_handlers[i] = new (arena) ciExceptionHandler(
 257                                 holder(),
 258             /* start    */      exc_table.start_pc(i),
 259             /* limit    */      exc_table.end_pc(i),
 260             /* goto pc  */      exc_table.handler_pc(i),
 261             /* cp index */      exc_table.catch_type_index(i));
 262     }
 263   }
 264 
 265   // Put an entry at the end of our list to represent the possibility
 266   // of exceptional exit.
 267   _exception_handlers[_handler_count] =
 268     new (arena) ciExceptionHandler(holder(), 0, code_size(), -1, 0);
 269 
 270   if (CIPrintMethodCodes) {
 271     print_codes();
 272   }
 273 }
 274 
 275 
 276 // ------------------------------------------------------------------
 277 // ciMethod::has_linenumber_table
 278 //
 279 // length unknown until decompression
 280 bool    ciMethod::has_linenumber_table() const {
 281   check_is_loaded();
 282   VM_ENTRY_MARK;
 283   return get_Method()->has_linenumber_table();
 284 }
 285 
 286 
 287 // ------------------------------------------------------------------
 288 // ciMethod::line_number_from_bci
 289 int ciMethod::line_number_from_bci(int bci) const {
 290   check_is_loaded();
 291   VM_ENTRY_MARK;
 292   return get_Method()->line_number_from_bci(bci);
 293 }
 294 
 295 
 296 // ------------------------------------------------------------------
 297 // ciMethod::vtable_index
 298 //
 299 // Get the position of this method's entry in the vtable, if any.
 300 int ciMethod::vtable_index() {
 301   check_is_loaded();
 302   assert(holder()->is_linked(), "must be linked");
 303   VM_ENTRY_MARK;
 304   return get_Method()->vtable_index();
 305 }
 306 
 307 // ------------------------------------------------------------------
 308 // ciMethod::uses_balanced_monitors
 309 //
 310 // Does this method use monitors in a strict stack-disciplined manner?
 311 bool ciMethod::has_balanced_monitors() {
 312   check_is_loaded();
 313   if (_balanced_monitors) return true;
 314 
 315   // Analyze the method to see if monitors are used properly.
 316   VM_ENTRY_MARK;
 317   methodHandle method(THREAD, get_Method());
 318   assert(method->has_monitor_bytecodes(), "should have checked this");
 319 
 320   // Check to see if a previous compilation computed the
 321   // monitor-matching analysis.
 322   if (method->guaranteed_monitor_matching()) {
 323     _balanced_monitors = true;
 324     return true;
 325   }
 326 
 327   {
 328     ExceptionMark em(THREAD);
 329     ResourceMark rm(THREAD);
 330     GeneratePairingInfo gpi(method);
 331     if (!gpi.compute_map(THREAD)) {
 332       fatal("Unrecoverable verification or out-of-memory error");
 333     }
 334     if (!gpi.monitor_safe()) {
 335       return false;
 336     }
 337     method->set_guaranteed_monitor_matching();
 338     _balanced_monitors = true;
 339   }
 340   return true;
 341 }
 342 
 343 
 344 // ------------------------------------------------------------------
 345 // ciMethod::get_flow_analysis
 346 ciTypeFlow* ciMethod::get_flow_analysis() {
 347 #if defined(COMPILER2)
 348   if (_flow == nullptr) {
 349     ciEnv* env = CURRENT_ENV;
 350     _flow = new (env->arena()) ciTypeFlow(env, this);
 351     _flow->do_flow();
 352   }
 353   return _flow;
 354 #else // COMPILER2
 355   ShouldNotReachHere();
 356   return nullptr;
 357 #endif // COMPILER2
 358 }
 359 
 360 
 361 // ------------------------------------------------------------------
 362 // ciMethod::get_osr_flow_analysis
 363 ciTypeFlow* ciMethod::get_osr_flow_analysis(int osr_bci) {
 364 #if defined(COMPILER2)
 365   // OSR entry points are always place after a call bytecode of some sort
 366   assert(osr_bci >= 0, "must supply valid OSR entry point");
 367   ciEnv* env = CURRENT_ENV;
 368   ciTypeFlow* flow = new (env->arena()) ciTypeFlow(env, this, osr_bci);
 369   flow->do_flow();
 370   return flow;
 371 #else // COMPILER2
 372   ShouldNotReachHere();
 373   return nullptr;
 374 #endif // COMPILER2
 375 }
 376 
 377 // ------------------------------------------------------------------
 378 // ciMethod::raw_liveness_at_bci
 379 //
 380 // Which local variables are live at a specific bci?
 381 MethodLivenessResult ciMethod::raw_liveness_at_bci(int bci) {
 382   check_is_loaded();
 383   if (_liveness == nullptr) {
 384     // Create the liveness analyzer.
 385     Arena* arena = CURRENT_ENV->arena();
 386     _liveness = new (arena) MethodLiveness(arena, this);
 387     _liveness->compute_liveness();
 388   }
 389   return _liveness->get_liveness_at(bci);
 390 }
 391 
 392 // ------------------------------------------------------------------
 393 // ciMethod::liveness_at_bci
 394 //
 395 // Which local variables are live at a specific bci?  When debugging
 396 // will return true for all locals in some cases to improve debug
 397 // information.
 398 MethodLivenessResult ciMethod::liveness_at_bci(int bci) {
 399   if (CURRENT_ENV->should_retain_local_variables() || DeoptimizeALot) {
 400     // Keep all locals live for the user's edification and amusement.
 401     MethodLivenessResult result(_max_locals);
 402     result.set_range(0, _max_locals);
 403     result.set_is_valid();
 404     return result;
 405   }
 406   return raw_liveness_at_bci(bci);
 407 }
 408 
 409 // ciMethod::live_local_oops_at_bci
 410 //
 411 // find all the live oops in the locals array for a particular bci
 412 // Compute what the interpreter believes by using the interpreter
 413 // oopmap generator. This is used as a double check during osr to
 414 // guard against conservative result from MethodLiveness making us
 415 // think a dead oop is live.  MethodLiveness is conservative in the
 416 // sense that it may consider locals to be live which cannot be live,
 417 // like in the case where a local could contain an oop or  a primitive
 418 // along different paths.  In that case the local must be dead when
 419 // those paths merge. Since the interpreter's viewpoint is used when
 420 // gc'ing an interpreter frame we need to use its viewpoint  during
 421 // OSR when loading the locals.
 422 
 423 ResourceBitMap ciMethod::live_local_oops_at_bci(int bci) {
 424   VM_ENTRY_MARK;
 425   InterpreterOopMap mask;
 426   OopMapCache::compute_one_oop_map(methodHandle(THREAD, get_Method()), bci, &mask);
 427   int mask_size = max_locals();
 428   ResourceBitMap result(mask_size);
 429   int i;
 430   for (i = 0; i < mask_size ; i++ ) {
 431     if (mask.is_oop(i)) result.set_bit(i);
 432   }
 433   return result;
 434 }
 435 
 436 
 437 #ifdef COMPILER1
 438 // ------------------------------------------------------------------
 439 // ciMethod::bci_block_start
 440 //
 441 // Marks all bcis where a new basic block starts
 442 const BitMap& ciMethod::bci_block_start() {
 443   check_is_loaded();
 444   if (_liveness == nullptr) {
 445     // Create the liveness analyzer.
 446     Arena* arena = CURRENT_ENV->arena();
 447     _liveness = new (arena) MethodLiveness(arena, this);
 448     _liveness->compute_liveness();
 449   }
 450 
 451   return _liveness->get_bci_block_start();
 452 }
 453 #endif // COMPILER1
 454 
 455 
 456 // ------------------------------------------------------------------
 457 // ciMethod::check_overflow
 458 //
 459 // Check whether the profile counter is overflowed and adjust if true.
 460 // For invoke* it will turn negative values into max_jint,
 461 // and for checkcast/aastore/instanceof turn positive values into min_jint.
 462 int ciMethod::check_overflow(int c, Bytecodes::Code code) {
 463   switch (code) {
 464     case Bytecodes::_aastore:    // fall-through
 465     case Bytecodes::_checkcast:  // fall-through
 466     case Bytecodes::_instanceof: {
 467       if (VM_Version::profile_all_receivers_at_type_check()) {
 468         return (c < 0 ? max_jint : c); // always non-negative
 469       }
 470       return (c > 0 ? min_jint : c); // always non-positive
 471     }
 472     default: {
 473       assert(Bytecodes::is_invoke(code), "%s", Bytecodes::name(code));
 474       return (c < 0 ? max_jint : c); // always non-negative
 475     }
 476   }
 477 }
 478 
 479 
 480 // ------------------------------------------------------------------
 481 // ciMethod::call_profile_at_bci
 482 //
 483 // Get the ciCallProfile for the invocation of this method.
 484 // Also reports receiver types for non-call type checks (if TypeProfileCasts).
 485 ciCallProfile ciMethod::call_profile_at_bci(int bci) {
 486   ResourceMark rm;
 487   ciCallProfile result;
 488   if (method_data() != nullptr && method_data()->is_mature()) {
 489     ciProfileData* data = method_data()->bci_to_data(bci);
 490     if (data != nullptr && data->is_CounterData()) {
 491       // Every profiled call site has a counter.
 492       int count = check_overflow(data->as_CounterData()->count(), java_code_at_bci(bci));
 493 
 494       if (!data->is_ReceiverTypeData()) {
 495         result._receiver_count[0] = 0;  // that's a definite zero
 496       } else { // ReceiverTypeData is a subclass of CounterData
 497         ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();
 498         // In addition, virtual call sites have receiver type information
 499         int receivers_count_total = 0;
 500         int morphism = 0;
 501         // Precompute morphism for the possible fixup
 502         for (uint i = 0; i < call->row_limit(); i++) {
 503           ciKlass* receiver = call->receiver(i);
 504           if (receiver == nullptr)  continue;
 505           morphism++;
 506         }
 507         int epsilon = 0;
 508         // For a call, it is assumed that either the type of the receiver(s)
 509         // is recorded or an associated counter is incremented, but not both. With
 510         // tiered compilation, however, both can happen due to the interpreter and
 511         // C1 profiling invocations differently. Address that inconsistency here.
 512         if (morphism == 1 && count > 0) {
 513           epsilon = count;
 514           count = 0;
 515         }
 516         for (uint i = 0; i < call->row_limit(); i++) {
 517           ciKlass* receiver = call->receiver(i);
 518           if (receiver == nullptr)  continue;
 519           int rcount = saturated_add(call->receiver_count(i), epsilon);
 520           if (rcount == 0) rcount = 1; // Should be valid value
 521           receivers_count_total = saturated_add(receivers_count_total, rcount);
 522           // Add the receiver to result data.
 523           result.add_receiver(receiver, rcount);
 524           // If we extend profiling to record methods,
 525           // we will set result._method also.
 526         }
 527         // Determine call site's morphism.
 528         // The call site count is 0 with known morphism (only 1 or 2 receivers)
 529         // or < 0 in the case of a type check failure for checkcast, aastore, instanceof.
 530         // The call site count is > 0 in the case of a polymorphic virtual call.
 531         if (morphism > 0 && morphism == result._limit) {
 532            // The morphism <= MorphismLimit.
 533            if ((morphism <  ciCallProfile::MorphismLimit) ||
 534                (morphism == ciCallProfile::MorphismLimit && count == 0)) {
 535 #ifdef ASSERT
 536              if (count > 0) {
 537                this->print_short_name(tty);
 538                tty->print_cr(" @ bci:%d", bci);
 539                this->print_codes();
 540                assert(false, "this call site should not be polymorphic");
 541              }
 542 #endif
 543              result._morphism = morphism;
 544            }
 545         }
 546         // Make the count consistent if this is a call profile. If count is
 547         // zero or less, presume that this is a typecheck profile and
 548         // do nothing.  Otherwise, increase count to be the sum of all
 549         // receiver's counts.
 550         if (count >= 0) {
 551           count = saturated_add(count, receivers_count_total);
 552         }
 553       }
 554       result._count = count;
 555     }
 556   }
 557   return result;
 558 }
 559 
 560 // ------------------------------------------------------------------
 561 // Add new receiver and sort data by receiver's profile count.
 562 void ciCallProfile::add_receiver(ciKlass* receiver, int receiver_count) {
 563   // Add new receiver and sort data by receiver's counts when we have space
 564   // for it otherwise replace the less called receiver (less called receiver
 565   // is placed to the last array element which is not used).
 566   // First array's element contains most called receiver.
 567   int i = _limit;
 568   for (; i > 0 && receiver_count > _receiver_count[i-1]; i--) {
 569     _receiver[i] = _receiver[i-1];
 570     _receiver_count[i] = _receiver_count[i-1];
 571   }
 572   _receiver[i] = receiver;
 573   _receiver_count[i] = receiver_count;
 574   if (_limit < MorphismLimit) _limit++;
 575 }
 576 
 577 
 578 void ciMethod::assert_virtual_call_type_ok(int bci) {
 579   assert(java_code_at_bci(bci) == Bytecodes::_invokevirtual ||
 580          java_code_at_bci(bci) == Bytecodes::_invokeinterface, "unexpected bytecode %s", Bytecodes::name(java_code_at_bci(bci)));
 581 }
 582 
 583 void ciMethod::assert_call_type_ok(int bci) {
 584   assert(java_code_at_bci(bci) == Bytecodes::_invokestatic ||
 585          java_code_at_bci(bci) == Bytecodes::_invokespecial ||
 586          java_code_at_bci(bci) == Bytecodes::_invokedynamic, "unexpected bytecode %s", Bytecodes::name(java_code_at_bci(bci)));
 587 }
 588 
 589 /**
 590  * Check whether profiling provides a type for the argument i to the
 591  * call at bci bci
 592  *
 593  * @param [in]bci         bci of the call
 594  * @param [in]i           argument number
 595  * @param [out]type       profiled type of argument, null if none
 596  * @param [out]ptr_kind   whether always null, never null or maybe null
 597  * @return                true if profiling exists
 598  *
 599  */
 600 bool ciMethod::argument_profiled_type(int bci, int i, ciKlass*& type, ProfilePtrKind& ptr_kind) {
 601   if (MethodData::profile_parameters() && method_data() != nullptr && method_data()->is_mature()) {
 602     ciProfileData* data = method_data()->bci_to_data(bci);
 603     if (data != nullptr) {
 604       if (data->is_VirtualCallTypeData()) {
 605         assert_virtual_call_type_ok(bci);
 606         ciVirtualCallTypeData* call = (ciVirtualCallTypeData*)data->as_VirtualCallTypeData();
 607         if (i >= call->number_of_arguments()) {
 608           return false;
 609         }
 610         type = call->valid_argument_type(i);
 611         ptr_kind = call->argument_ptr_kind(i);
 612         return true;
 613       } else if (data->is_CallTypeData()) {
 614         assert_call_type_ok(bci);
 615         ciCallTypeData* call = (ciCallTypeData*)data->as_CallTypeData();
 616         if (i >= call->number_of_arguments()) {
 617           return false;
 618         }
 619         type = call->valid_argument_type(i);
 620         ptr_kind = call->argument_ptr_kind(i);
 621         return true;
 622       }
 623     }
 624   }
 625   return false;
 626 }
 627 
 628 /**
 629  * Check whether profiling provides a type for the return value from
 630  * the call at bci bci
 631  *
 632  * @param [in]bci         bci of the call
 633  * @param [out]type       profiled type of argument, null if none
 634  * @param [out]ptr_kind   whether always null, never null or maybe null
 635  * @return                true if profiling exists
 636  *
 637  */
 638 bool ciMethod::return_profiled_type(int bci, ciKlass*& type, ProfilePtrKind& ptr_kind) {
 639   if (MethodData::profile_return() && method_data() != nullptr && method_data()->is_mature()) {
 640     ciProfileData* data = method_data()->bci_to_data(bci);
 641     if (data != nullptr) {
 642       if (data->is_VirtualCallTypeData()) {
 643         assert_virtual_call_type_ok(bci);
 644         ciVirtualCallTypeData* call = (ciVirtualCallTypeData*)data->as_VirtualCallTypeData();
 645         if (call->has_return()) {
 646           type = call->valid_return_type();
 647           ptr_kind = call->return_ptr_kind();
 648           return true;
 649         }
 650       } else if (data->is_CallTypeData()) {
 651         assert_call_type_ok(bci);
 652         ciCallTypeData* call = (ciCallTypeData*)data->as_CallTypeData();
 653         if (call->has_return()) {
 654           type = call->valid_return_type();
 655           ptr_kind = call->return_ptr_kind();
 656         }
 657         return true;
 658       }
 659     }
 660   }
 661   return false;
 662 }
 663 
 664 /**
 665  * Check whether profiling provides a type for the parameter i
 666  *
 667  * @param [in]i           parameter number
 668  * @param [out]type       profiled type of parameter, null if none
 669  * @param [out]ptr_kind   whether always null, never null or maybe null
 670  * @return                true if profiling exists
 671  *
 672  */
 673 bool ciMethod::parameter_profiled_type(int i, ciKlass*& type, ProfilePtrKind& ptr_kind) {
 674   if (MethodData::profile_parameters() && method_data() != nullptr && method_data()->is_mature()) {
 675     ciParametersTypeData* parameters = method_data()->parameters_type_data();
 676     if (parameters != nullptr && i < parameters->number_of_parameters()) {
 677       type = parameters->valid_parameter_type(i);
 678       ptr_kind = parameters->parameter_ptr_kind(i);
 679       return true;
 680     }
 681   }
 682   return false;
 683 }
 684 
 685 
 686 // ------------------------------------------------------------------
 687 // ciMethod::find_monomorphic_target
 688 //
 689 // Given a certain calling environment, find the monomorphic target
 690 // for the call.  Return null if the call is not monomorphic in
 691 // its calling environment, or if there are only abstract methods.
 692 // The returned method is never abstract.
 693 // Note: If caller uses a non-null result, it must inform dependencies
 694 // via assert_unique_concrete_method or assert_leaf_type.
 695 ciMethod* ciMethod::find_monomorphic_target(ciInstanceKlass* caller,
 696                                             ciInstanceKlass* callee_holder,
 697                                             ciInstanceKlass* actual_recv,
 698                                             bool check_access) {
 699   check_is_loaded();
 700 
 701   if (actual_recv->is_interface()) {
 702     // %%% We cannot trust interface types, yet.  See bug 6312651.
 703     return nullptr;
 704   }
 705 
 706   ciMethod* root_m = resolve_invoke(caller, actual_recv, check_access, true /* allow_abstract */);
 707   if (root_m == nullptr) {
 708     // Something went wrong looking up the actual receiver method.
 709     return nullptr;
 710   }
 711 
 712   // Make certain quick checks even if UseCHA is false.
 713 
 714   // Is it private or final?
 715   if (root_m->can_be_statically_bound()) {
 716     assert(!root_m->is_abstract(), "sanity");
 717     return root_m;
 718   }
 719 
 720   if (actual_recv->is_leaf_type() && actual_recv == root_m->holder()) {
 721     // Easy case.  There is no other place to put a method, so don't bother
 722     // to go through the VM_ENTRY_MARK and all the rest.
 723     if (root_m->is_abstract()) {
 724       return nullptr;
 725     }
 726     return root_m;
 727   }
 728 
 729   // Array methods (clone, hashCode, etc.) are always statically bound.
 730   // If we were to see an array type here, we'd return root_m.
 731   // However, this method processes only ciInstanceKlasses.  (See 4962591.)
 732   // The inline_native_clone intrinsic narrows Object to T[] properly,
 733   // so there is no need to do the same job here.
 734 
 735   if (!UseCHA)  return nullptr;
 736 
 737   VM_ENTRY_MARK;
 738 
 739   methodHandle target;
 740   {
 741     MutexLocker locker(Compile_lock);
 742     InstanceKlass* context = actual_recv->get_instanceKlass();
 743     target = methodHandle(THREAD, Dependencies::find_unique_concrete_method(context,
 744                                                                             root_m->get_Method(),
 745                                                                             callee_holder->get_Klass(),
 746                                                                             this->get_Method()));
 747     assert(target() == nullptr || !target()->is_abstract(), "not allowed");
 748     // %%% Should upgrade this ciMethod API to look for 1 or 2 concrete methods.
 749   }
 750 
 751 #ifndef PRODUCT
 752   LogTarget(Debug, dependencies) lt;
 753   if (lt.is_enabled() && target() != nullptr && target() != root_m->get_Method()) {
 754     LogStream ls(&lt);
 755     ls.print("found a non-root unique target method");
 756     ls.print_cr("  context = %s", actual_recv->get_Klass()->external_name());
 757     ls.print("  method  = ");
 758     target->print_short_name(&ls);
 759     ls.cr();
 760   }
 761 #endif //PRODUCT
 762 
 763   if (target() == nullptr) {
 764     return nullptr;
 765   }
 766 
 767   // Redefinition support.
 768   if (this->is_old() || root_m->is_old() || target->is_old()) {
 769     guarantee(CURRENT_THREAD_ENV->jvmti_state_changed(), "old method not detected");
 770     return nullptr;
 771   }
 772 
 773   if (target() == root_m->get_Method()) {
 774     return root_m;
 775   }
 776   if (!root_m->is_public() &&
 777       !root_m->is_protected()) {
 778     // If we are going to reason about inheritance, it's easiest
 779     // if the method in question is public, protected, or private.
 780     // If the answer is not root_m, it is conservatively correct
 781     // to return null, even if the CHA encountered irrelevant
 782     // methods in other packages.
 783     // %%% TO DO: Work out logic for package-private methods
 784     // with the same name but different vtable indexes.
 785     return nullptr;
 786   }
 787   return CURRENT_THREAD_ENV->get_method(target());
 788 }
 789 
 790 // ------------------------------------------------------------------
 791 // ciMethod::can_be_statically_bound
 792 //
 793 // Tries to determine whether a method can be statically bound in some context.
 794 bool ciMethod::can_be_statically_bound(ciInstanceKlass* context) const {
 795   return (holder() == context) && can_be_statically_bound();
 796 }
 797 
 798 // ------------------------------------------------------------------
 799 // ciMethod::can_omit_stack_trace
 800 //
 801 // Tries to determine whether a method can omit stack trace in throw in compiled code.
 802 bool ciMethod::can_omit_stack_trace() const {
 803   if (!StackTraceInThrowable) {
 804     return true; // stack trace is switched off.
 805   }
 806   if (!OmitStackTraceInFastThrow) {
 807     return false; // Have to provide stack trace.
 808   }
 809   return _can_omit_stack_trace;
 810 }
 811 
 812 // ------------------------------------------------------------------
 813 // ciMethod::resolve_invoke
 814 //
 815 // Given a known receiver klass, find the target for the call.
 816 // Return null if the call has no target or the target is abstract.
 817 ciMethod* ciMethod::resolve_invoke(ciKlass* caller, ciKlass* exact_receiver, bool check_access, bool allow_abstract) {
 818   check_is_loaded();
 819   VM_ENTRY_MARK;
 820 
 821   Klass* caller_klass = caller->get_Klass();
 822   Klass* recv         = exact_receiver->get_Klass();
 823   Klass* resolved     = holder()->get_Klass();
 824   Symbol* h_name      = name()->get_symbol();
 825   Symbol* h_signature = signature()->get_symbol();
 826 
 827   LinkInfo link_info(resolved, h_name, h_signature, caller_klass,
 828                      check_access ? LinkInfo::AccessCheck::required : LinkInfo::AccessCheck::skip,
 829                      check_access ? LinkInfo::LoaderConstraintCheck::required : LinkInfo::LoaderConstraintCheck::skip);
 830   Method* m = nullptr;
 831   // Only do exact lookup if receiver klass has been linked.  Otherwise,
 832   // the vtable has not been setup, and the LinkResolver will fail.
 833   if (recv->is_array_klass()
 834        ||
 835       (InstanceKlass::cast(recv)->is_linked() && !exact_receiver->is_interface())) {
 836     if (holder()->is_interface()) {
 837       m = LinkResolver::resolve_interface_call_or_null(recv, link_info);
 838     } else {
 839       m = LinkResolver::resolve_virtual_call_or_null(recv, link_info);
 840     }
 841   }
 842 
 843   if (m == nullptr) {
 844     // Return null only if there was a problem with lookup (uninitialized class, etc.)
 845     return nullptr;
 846   }
 847 
 848   ciMethod* result = this;
 849   if (m != get_Method()) {
 850     // Redefinition support.
 851     if (this->is_old() || m->is_old()) {
 852       guarantee(CURRENT_THREAD_ENV->jvmti_state_changed(), "old method not detected");
 853       return nullptr;
 854     }
 855 
 856     result = CURRENT_THREAD_ENV->get_method(m);
 857   }
 858 
 859   if (result->is_abstract() && !allow_abstract) {
 860     // Don't return abstract methods because they aren't optimizable or interesting.
 861     return nullptr;
 862   }
 863   return result;
 864 }
 865 
 866 // ------------------------------------------------------------------
 867 // ciMethod::resolve_vtable_index
 868 //
 869 // Given a known receiver klass, find the vtable index for the call.
 870 // Return Method::invalid_vtable_index if the vtable_index is unknown.
 871 int ciMethod::resolve_vtable_index(ciKlass* caller, ciKlass* receiver) {
 872    check_is_loaded();
 873 
 874    int vtable_index = Method::invalid_vtable_index;
 875    // Only do lookup if receiver klass has been linked.  Otherwise,
 876    // the vtable has not been setup, and the LinkResolver will fail.
 877    if (!receiver->is_interface()
 878        && (!receiver->is_instance_klass() ||
 879            receiver->as_instance_klass()->is_linked())) {
 880      VM_ENTRY_MARK;
 881 
 882      Klass* caller_klass = caller->get_Klass();
 883      Klass* recv         = receiver->get_Klass();
 884      Symbol* h_name = name()->get_symbol();
 885      Symbol* h_signature = signature()->get_symbol();
 886 
 887      LinkInfo link_info(recv, h_name, h_signature, caller_klass);
 888      vtable_index = LinkResolver::resolve_virtual_vtable_index(recv, link_info);
 889      if (vtable_index == Method::nonvirtual_vtable_index) {
 890        // A statically bound method.  Return "no such index".
 891        vtable_index = Method::invalid_vtable_index;
 892      }
 893    }
 894 
 895    return vtable_index;
 896 }
 897 
 898 // ------------------------------------------------------------------
 899 // ciMethod::get_field_at_bci
 900 ciField* ciMethod::get_field_at_bci(int bci, bool &will_link) {
 901   ciBytecodeStream iter(this);
 902   iter.reset_to_bci(bci);
 903   iter.next();
 904   return iter.get_field(will_link);
 905 }
 906 
 907 // ------------------------------------------------------------------
 908 // ciMethod::get_method_at_bci
 909 ciMethod* ciMethod::get_method_at_bci(int bci, bool &will_link, ciSignature* *declared_signature) {
 910   ciBytecodeStream iter(this);
 911   iter.reset_to_bci(bci);
 912   iter.next();
 913   return iter.get_method(will_link, declared_signature);
 914 }
 915 
 916 // ------------------------------------------------------------------
 917 ciKlass* ciMethod::get_declared_method_holder_at_bci(int bci) {
 918   ciBytecodeStream iter(this);
 919   iter.reset_to_bci(bci);
 920   iter.next();
 921   return iter.get_declared_method_holder();
 922 }
 923 
 924 // ------------------------------------------------------------------
 925 // Adjust a CounterData count to be commensurate with
 926 // interpreter_invocation_count.  If the MDO exists for
 927 // only 25% of the time the method exists, then the
 928 // counts in the MDO should be scaled by 4X, so that
 929 // they can be usefully and stably compared against the
 930 // invocation counts in methods.
 931 int ciMethod::scale_count(int count, float prof_factor) {
 932   if (count > 0 && method_data() != nullptr) {
 933     int counter_life = method_data()->invocation_count();
 934     int method_life = interpreter_invocation_count();
 935     if (method_life < counter_life) { // may happen because of the snapshot timing
 936       method_life = counter_life;
 937     }
 938     if (counter_life > 0) {
 939       count = (int)((double)count * prof_factor * method_life / counter_life + 0.5);
 940       count = (count > 0) ? count : 1;
 941     } else {
 942       count = 1;
 943     }
 944   }
 945   return count;
 946 }
 947 
 948 
 949 // ------------------------------------------------------------------
 950 // ciMethod::is_special_get_caller_class_method
 951 //
 952 bool ciMethod::is_ignored_by_security_stack_walk() const {
 953   check_is_loaded();
 954   VM_ENTRY_MARK;
 955   return get_Method()->is_ignored_by_security_stack_walk();
 956 }
 957 
 958 // ------------------------------------------------------------------
 959 // ciMethod::needs_clinit_barrier
 960 //
 961 bool ciMethod::needs_clinit_barrier() const {
 962   check_is_loaded();
 963   return is_static() && !holder()->is_initialized();
 964 }
 965 
 966 // ------------------------------------------------------------------
 967 // invokedynamic support
 968 
 969 // ------------------------------------------------------------------
 970 // ciMethod::is_method_handle_intrinsic
 971 //
 972 // Return true if the method is an instance of the JVM-generated
 973 // signature-polymorphic MethodHandle methods, _invokeBasic, _linkToVirtual, etc.
 974 bool ciMethod::is_method_handle_intrinsic() const {
 975   vmIntrinsics::ID iid = _intrinsic_id;  // do not check if loaded
 976   return (MethodHandles::is_signature_polymorphic(iid) &&
 977           MethodHandles::is_signature_polymorphic_intrinsic(iid));
 978 }
 979 
 980 // ------------------------------------------------------------------
 981 // ciMethod::is_compiled_lambda_form
 982 //
 983 // Return true if the method is a generated MethodHandle adapter.
 984 // These are built by Java code.
 985 bool ciMethod::is_compiled_lambda_form() const {
 986   vmIntrinsics::ID iid = _intrinsic_id;  // do not check if loaded
 987   return iid == vmIntrinsics::_compiledLambdaForm;
 988 }
 989 
 990 // ------------------------------------------------------------------
 991 // ciMethod::is_object_initializer
 992 //
 993 bool ciMethod::is_object_initializer() const {
 994    return name() == ciSymbols::object_initializer_name();
 995 }
 996 
 997 // ------------------------------------------------------------------
 998 // ciMethod::is_scoped
 999 //
1000 // Return true for methods annotated with @Scoped
1001 bool ciMethod::is_scoped() const {
1002    return get_Method()->is_scoped();
1003 }
1004 
1005 // ------------------------------------------------------------------
1006 // ciMethod::has_member_arg
1007 //
1008 // Return true if the method is a linker intrinsic like _linkToVirtual.
1009 // These are built by the JVM.
1010 bool ciMethod::has_member_arg() const {
1011   vmIntrinsics::ID iid = _intrinsic_id;  // do not check if loaded
1012   return (MethodHandles::is_signature_polymorphic(iid) &&
1013           MethodHandles::has_member_arg(iid));
1014 }
1015 
1016 // ------------------------------------------------------------------
1017 // ciMethod::ensure_method_data
1018 //
1019 // Generate new MethodData* objects at compile time.
1020 // Return true if allocation was successful or no MDO is required.
1021 bool ciMethod::ensure_method_data(const methodHandle& h_m, bool training_data_only) {
1022   EXCEPTION_CONTEXT;
1023   if (is_native() || is_abstract() || h_m()->is_accessor()) {
1024     return true;
1025   }
1026   if (h_m()->method_data() == nullptr) {
1027     if (training_data_only) {
1028       Method::install_training_method_data(h_m);
1029     } else {
1030       Method::build_profiling_method_data(h_m, THREAD);
1031       if (HAS_PENDING_EXCEPTION) {
1032         CLEAR_PENDING_EXCEPTION;
1033       }
1034     }
1035   }
1036   if (h_m()->method_data() != nullptr) {
1037     _method_data = CURRENT_ENV->get_method_data(h_m()->method_data());
1038     return _method_data->load_data();
1039   } else {
1040     _method_data = CURRENT_ENV->get_empty_methodData();
1041     return false;
1042   }
1043 }
1044 
1045 // public, retroactive version
1046 bool ciMethod::ensure_method_data(bool training_data_only) {
1047   bool result = true;
1048   if (_method_data == nullptr || _method_data->is_empty()) {
1049     GUARDED_VM_ENTRY({
1050       methodHandle mh(Thread::current(), get_Method());
1051       result = ensure_method_data(mh, training_data_only);
1052     });
1053   }
1054   return result;
1055 }
1056 
1057 
1058 // ------------------------------------------------------------------
1059 // ciMethod::method_data
1060 //
1061 ciMethodData* ciMethod::method_data() {
1062   if (CURRENT_ENV->task()->is_precompiled() && CURRENT_ENV->task()->comp_level() == CompLevel_full_optimization) {
1063     if (_method_data_recorded == nullptr) {
1064       VM_ENTRY_MARK;
1065       methodHandle h_m(thread, get_Method());
1066       MethodTrainingData* mtd = MethodTrainingData::find(h_m);
1067       MethodData* mdo = (mtd != nullptr ? mtd->final_profile() : nullptr);
1068       DirectiveSet* directives = DirectivesStack::getMatchingDirective(h_m, CURRENT_ENV->task()->compiler());
1069       if (mdo == nullptr || directives->IgnoreRecordedProfileOption) {
1070         if (directives->IgnoreRecordedProfileOption) {
1071           ResourceMark rm;
1072           log_debug(precompile)("Ignore recorded profile for %s", h_m->name_and_sig_as_C_string());
1073         } else {
1074           ResourceMark rm;
1075           log_debug(precompile)("No profile for %s", h_m->name_and_sig_as_C_string());
1076         }
1077         _method_data_recorded = CURRENT_ENV->get_empty_methodData();
1078       } else {
1079 #if INCLUDE_CDS
1080         if (mdo->extra_data_lock() == nullptr) {
1081           assert(!HAS_PENDING_EXCEPTION, "");
1082           mdo->restore_unshareable_info(thread);
1083           assert(!HAS_PENDING_EXCEPTION, "");
1084         }
1085 #endif
1086         _method_data_recorded = CURRENT_ENV->get_method_data(mdo);
1087         _method_data_recorded->load_data();
1088         {
1089           ResourceMark rm;
1090           log_debug(precompile)("Recorded profile " PTR_FORMAT " for %s", p2i(mdo), h_m->name_and_sig_as_C_string());
1091         }
1092       }
1093     }
1094     assert(_method_data_recorded != nullptr, "");
1095     return _method_data_recorded;
1096   } else {
1097     if (_method_data != nullptr) {
1098       return _method_data;
1099     }
1100     VM_ENTRY_MARK;
1101     methodHandle h_m(thread, get_Method());
1102     MethodData* mdo = h_m()->method_data();
1103     if (mdo != nullptr) {
1104       _method_data = CURRENT_ENV->get_method_data(mdo);
1105       _method_data->load_data();
1106     } else {
1107       _method_data = CURRENT_ENV->get_empty_methodData();
1108     }
1109     return _method_data;
1110   }
1111 }
1112 
1113 // ------------------------------------------------------------------
1114 // ciMethod::method_data_or_null
1115 // Returns a pointer to ciMethodData if MDO exists on the VM side,
1116 // null otherwise.
1117 ciMethodData* ciMethod::method_data_or_null() {
1118   ciMethodData *md = method_data();
1119   if (md->is_empty()) {
1120     return nullptr;
1121   }
1122   return md;
1123 }
1124 
1125 // ------------------------------------------------------------------
1126 // ciMethod::ensure_method_counters
1127 //
1128 MethodCounters* ciMethod::ensure_method_counters() {
1129   check_is_loaded();
1130   VM_ENTRY_MARK;
1131   methodHandle mh(THREAD, get_Method());
1132   MethodCounters* method_counters = mh->get_method_counters(CHECK_NULL);
1133   return method_counters;
1134 }
1135 
1136 // ------------------------------------------------------------------
1137 // ciMethod::has_option
1138 //
1139 bool ciMethod::has_option(CompileCommandEnum option) {
1140   check_is_loaded();
1141   VM_ENTRY_MARK;
1142   methodHandle mh(THREAD, get_Method());
1143   return CompilerOracle::has_option(mh, option);
1144 }
1145 
1146 // ------------------------------------------------------------------
1147 // ciMethod::has_option_value
1148 //
1149 bool ciMethod::has_option_value(CompileCommandEnum option, double& value) {
1150   check_is_loaded();
1151   VM_ENTRY_MARK;
1152   methodHandle mh(THREAD, get_Method());
1153   return CompilerOracle::has_option_value(mh, option, value);
1154 }
1155 // ------------------------------------------------------------------
1156 // ciMethod::can_be_compiled
1157 //
1158 // Have previous compilations of this method succeeded?
1159 bool ciMethod::can_be_compiled() {
1160   check_is_loaded();
1161   ciEnv* env = CURRENT_ENV;
1162   if (is_c1_compile(env->comp_level())) {
1163     return _is_c1_compilable;
1164   }
1165 
1166 #if INCLUDE_JVMCI
1167   if (EnableJVMCI && UseJVMCICompiler &&
1168       env->comp_level() == CompLevel_full_optimization && !AOTLinkedClassBulkLoader::class_preloading_finished()) {
1169     return false;
1170   }
1171 #endif
1172   return _is_c2_compilable;
1173 }
1174 
1175 // ------------------------------------------------------------------
1176 // ciMethod::has_compiled_code
1177 bool ciMethod::has_compiled_code() {
1178   return inline_instructions_size() > 0;
1179 }
1180 
1181 int ciMethod::highest_osr_comp_level() {
1182   check_is_loaded();
1183   VM_ENTRY_MARK;
1184   return get_Method()->highest_osr_comp_level();
1185 }
1186 
1187 // ------------------------------------------------------------------
1188 // ciMethod::code_size_for_inlining
1189 //
1190 // Code size for inlining decisions.  This method returns a code
1191 // size of 1 for methods which has the ForceInline annotation.
1192 int ciMethod::code_size_for_inlining() {
1193   check_is_loaded();
1194   if (get_Method()->force_inline()) {
1195     return 1;
1196   }
1197   return code_size();
1198 }
1199 
1200 // ------------------------------------------------------------------
1201 // ciMethod::inline_instructions_size
1202 //
1203 // This is a rough metric for "fat" methods, compared before inlining
1204 // with InlineSmallCode.  The CodeBlob::code_size accessor includes
1205 // junk like exception handler, stubs, and constant table, which are
1206 // not highly relevant to an inlined method.  So we use the more
1207 // specific accessor nmethod::insts_size.
1208 // Also some instructions inside the code are excluded from inline
1209 // heuristic (e.g. post call nop instructions; see InlineSkippedInstructionsCounter)
1210 int ciMethod::inline_instructions_size() {
1211   if (_inline_instructions_size == -1) {
1212     if (TrainingData::have_data()) {
1213       GUARDED_VM_ENTRY(
1214         CompLevel level = static_cast<CompLevel>(CURRENT_ENV->comp_level());
1215         methodHandle top_level_mh(Thread::current(), CURRENT_ENV->task()->method());
1216         MethodTrainingData* mtd = MethodTrainingData::find(top_level_mh);
1217         if (mtd != nullptr) {
1218           CompileTrainingData* ctd = mtd->last_toplevel_compile(level);
1219           if (ctd != nullptr) {
1220             methodHandle mh(Thread::current(), get_Method());
1221             MethodTrainingData* this_mtd = MethodTrainingData::find(mh);
1222             if (this_mtd != nullptr) {
1223               auto r = ctd->ci_records().ciMethod__inline_instructions_size.find(this_mtd);
1224               if (r.is_valid()) {
1225                 _inline_instructions_size = r.result();
1226               }
1227             }
1228           }
1229         }
1230       );
1231     }
1232   }
1233   if (_inline_instructions_size == -1) {
1234     GUARDED_VM_ENTRY(
1235       nmethod* code = get_Method()->code();
1236       if (code != nullptr && !code->is_scc() && (code->comp_level() == CompLevel_full_optimization)) {
1237         int isize = code->insts_end() - code->verified_entry_point() - code->skipped_instructions_size();
1238         _inline_instructions_size = isize > 0 ? isize : 0;
1239       } else {
1240         _inline_instructions_size = 0;
1241       }
1242       if (TrainingData::need_data()) {
1243         CompileTrainingData* ctd = CURRENT_ENV->task()->training_data();
1244         if (ctd != nullptr) {
1245           methodHandle mh(Thread::current(), get_Method());
1246           MethodTrainingData* this_mtd = MethodTrainingData::make(mh);
1247           ctd->ci_records().ciMethod__inline_instructions_size.append_if_missing(_inline_instructions_size, this_mtd);
1248         }
1249       }
1250     );
1251   }
1252   return _inline_instructions_size;
1253 }
1254 
1255 // ------------------------------------------------------------------
1256 // ciMethod::log_nmethod_identity
1257 void ciMethod::log_nmethod_identity(xmlStream* log) {
1258   GUARDED_VM_ENTRY(
1259     nmethod* code = get_Method()->code();
1260     if (code != nullptr) {
1261       code->log_identity(log);
1262     }
1263   )
1264 }
1265 
1266 // ------------------------------------------------------------------
1267 // ciMethod::is_not_reached
1268 bool ciMethod::is_not_reached(int bci) {
1269   check_is_loaded();
1270   VM_ENTRY_MARK;
1271   return Interpreter::is_not_reached(
1272                methodHandle(THREAD, get_Method()), bci);
1273 }
1274 
1275 // ------------------------------------------------------------------
1276 // ciMethod::was_never_executed
1277 bool ciMethod::was_executed_more_than(int times) {
1278   // Invocation counter is reset when the Method* is compiled.
1279   // If the method has compiled code we therefore assume it has
1280   // be executed more than n times.
1281   if (is_accessor() || is_empty() || has_compiled_code()) {
1282     // interpreter doesn't bump invocation counter of trivial methods
1283     // compiler does not bump invocation counter of compiled methods
1284     return true;
1285   }
1286   if (!method_data()->is_empty()) {
1287     return (method_data()->invocation_count() > times);
1288   }
1289   VM_ENTRY_MARK;
1290   return get_Method()->was_executed_more_than(times);
1291 }
1292 
1293 // ------------------------------------------------------------------
1294 // ciMethod::has_unloaded_classes_in_signature
1295 bool ciMethod::has_unloaded_classes_in_signature() {
1296   // ciSignature is resolved against some accessing class and
1297   // signature classes aren't required to be local. As a benefit,
1298   // it makes signature classes visible through loader constraints.
1299   // So, encountering an unloaded class signals it is absent both in
1300   // the callee (local) and caller contexts.
1301   return signature()->has_unloaded_classes();
1302 }
1303 
1304 // ------------------------------------------------------------------
1305 // ciMethod::is_klass_loaded
1306 bool ciMethod::is_klass_loaded(int refinfo_index, Bytecodes::Code bc, bool must_be_resolved) const {
1307   VM_ENTRY_MARK;
1308   return get_Method()->is_klass_loaded(refinfo_index, bc, must_be_resolved);
1309 }
1310 
1311 // ------------------------------------------------------------------
1312 // ciMethod::check_call
1313 bool ciMethod::check_call(int refinfo_index, bool is_static) const {
1314   // This method is used only in C2 from InlineTree::ok_to_inline,
1315   // and is only used under -Xcomp.
1316   // It appears to fail when applied to an invokeinterface call site.
1317   // FIXME: Remove this method and resolve_method_statically; refactor to use the other LinkResolver entry points.
1318   VM_ENTRY_MARK;
1319   {
1320     ExceptionMark em(THREAD);
1321     HandleMark hm(THREAD);
1322     constantPoolHandle pool (THREAD, get_Method()->constants());
1323     Bytecodes::Code code = (is_static ? Bytecodes::_invokestatic : Bytecodes::_invokevirtual);
1324     Method* spec_method = LinkResolver::resolve_method_statically(code, pool, refinfo_index, THREAD);
1325     if (HAS_PENDING_EXCEPTION) {
1326       CLEAR_PENDING_EXCEPTION;
1327       return false;
1328     } else {
1329       return (spec_method->is_static() == is_static);
1330     }
1331   }
1332   return false;
1333 }
1334 // ------------------------------------------------------------------
1335 // ciMethod::print_codes
1336 //
1337 // Print the bytecodes for this method.
1338 void ciMethod::print_codes_on(outputStream* st) {
1339   check_is_loaded();
1340   GUARDED_VM_ENTRY(get_Method()->print_codes_on(st);)
1341 }
1342 
1343 
1344 #define FETCH_FLAG_FROM_VM(flag_accessor) { \
1345   check_is_loaded(); \
1346   VM_ENTRY_MARK; \
1347   return get_Method()->flag_accessor(); \
1348 }
1349 
1350 bool ciMethod::has_loops      () const {         FETCH_FLAG_FROM_VM(has_loops); }
1351 bool ciMethod::has_jsrs       () const {         FETCH_FLAG_FROM_VM(has_jsrs);  }
1352 bool ciMethod::is_getter      () const {         FETCH_FLAG_FROM_VM(is_getter); }
1353 bool ciMethod::is_setter      () const {         FETCH_FLAG_FROM_VM(is_setter); }
1354 bool ciMethod::is_accessor    () const {         FETCH_FLAG_FROM_VM(is_accessor); }
1355 bool ciMethod::is_empty       () const {         FETCH_FLAG_FROM_VM(is_empty_method); }
1356 
1357 bool ciMethod::is_boxing_method() const {
1358   if (intrinsic_id() != vmIntrinsics::_none && holder()->is_box_klass()) {
1359     switch (intrinsic_id()) {
1360       case vmIntrinsics::_Boolean_valueOf:
1361       case vmIntrinsics::_Byte_valueOf:
1362       case vmIntrinsics::_Character_valueOf:
1363       case vmIntrinsics::_Short_valueOf:
1364       case vmIntrinsics::_Integer_valueOf:
1365       case vmIntrinsics::_Long_valueOf:
1366       case vmIntrinsics::_Float_valueOf:
1367       case vmIntrinsics::_Double_valueOf:
1368         return true;
1369       default:
1370         return false;
1371     }
1372   }
1373   return false;
1374 }
1375 
1376 bool ciMethod::is_unboxing_method() const {
1377   if (intrinsic_id() != vmIntrinsics::_none && holder()->is_box_klass()) {
1378     switch (intrinsic_id()) {
1379       case vmIntrinsics::_booleanValue:
1380       case vmIntrinsics::_byteValue:
1381       case vmIntrinsics::_charValue:
1382       case vmIntrinsics::_shortValue:
1383       case vmIntrinsics::_intValue:
1384       case vmIntrinsics::_longValue:
1385       case vmIntrinsics::_floatValue:
1386       case vmIntrinsics::_doubleValue:
1387         return true;
1388       default:
1389         return false;
1390     }
1391   }
1392   return false;
1393 }
1394 
1395 bool ciMethod::is_vector_method() const {
1396   return (holder() == ciEnv::current()->vector_VectorSupport_klass()) &&
1397          (intrinsic_id() != vmIntrinsics::_none);
1398 }
1399 
1400 BCEscapeAnalyzer  *ciMethod::get_bcea() {
1401 #ifdef COMPILER2
1402   if (_bcea == nullptr) {
1403     _bcea = new (CURRENT_ENV->arena()) BCEscapeAnalyzer(this, nullptr);
1404   }
1405   return _bcea;
1406 #else // COMPILER2
1407   ShouldNotReachHere();
1408   return nullptr;
1409 #endif // COMPILER2
1410 }
1411 
1412 ciMethodBlocks  *ciMethod::get_method_blocks() {
1413   if (_method_blocks == nullptr) {
1414     Arena *arena = CURRENT_ENV->arena();
1415     _method_blocks = new (arena) ciMethodBlocks(arena, this);
1416   }
1417   return _method_blocks;
1418 }
1419 
1420 #undef FETCH_FLAG_FROM_VM
1421 
1422 void ciMethod::dump_name_as_ascii(outputStream* st, Method* method) {
1423   st->print("%s %s %s",
1424             CURRENT_ENV->replay_name(method->method_holder()),
1425             method->name()->as_quoted_ascii(),
1426             method->signature()->as_quoted_ascii());
1427 }
1428 
1429 void ciMethod::dump_name_as_ascii(outputStream* st) {
1430   Method* method = get_Method();
1431   dump_name_as_ascii(st, method);
1432 }
1433 
1434 void ciMethod::dump_replay_data(outputStream* st) {
1435   ResourceMark rm;
1436   Method* method = get_Method();
1437   if (MethodHandles::is_signature_polymorphic_method(method)) {
1438     // ignore for now
1439     return;
1440   }
1441   MethodCounters* mcs = method->method_counters();
1442   st->print("ciMethod ");
1443   dump_name_as_ascii(st);
1444   st->print_cr(" %d %d %d %d %d",
1445                mcs == nullptr ? 0 : mcs->invocation_counter()->raw_counter(),
1446                mcs == nullptr ? 0 : mcs->backedge_counter()->raw_counter(),
1447                interpreter_invocation_count(),
1448                interpreter_throwout_count(),
1449                _inline_instructions_size);
1450 }
1451 
1452 // ------------------------------------------------------------------
1453 // ciMethod::print_codes
1454 //
1455 // Print a range of the bytecodes for this method.
1456 void ciMethod::print_codes_on(int from, int to, outputStream* st) {
1457   check_is_loaded();
1458   GUARDED_VM_ENTRY(get_Method()->print_codes_on(from, to, st);)
1459 }
1460 
1461 // ------------------------------------------------------------------
1462 // ciMethod::print_name
1463 //
1464 // Print the name of this method, including signature and some flags.
1465 void ciMethod::print_name(outputStream* st) {
1466   check_is_loaded();
1467   GUARDED_VM_ENTRY(get_Method()->print_name(st);)
1468 }
1469 
1470 // ------------------------------------------------------------------
1471 // ciMethod::print_short_name
1472 //
1473 // Print the name of this method, without signature.
1474 void ciMethod::print_short_name(outputStream* st) {
1475   if (is_loaded()) {
1476     GUARDED_VM_ENTRY(get_Method()->print_short_name(st););
1477   } else {
1478     // Fall back if method is not loaded.
1479     holder()->print_name_on(st);
1480     st->print("::");
1481     name()->print_symbol_on(st);
1482     if (WizardMode)
1483       signature()->as_symbol()->print_symbol_on(st);
1484   }
1485 }
1486 
1487 // ------------------------------------------------------------------
1488 // ciMethod::print_impl
1489 //
1490 // Implementation of the print method.
1491 void ciMethod::print_impl(outputStream* st) {
1492   ciMetadata::print_impl(st);
1493   st->print(" name=");
1494   name()->print_symbol_on(st);
1495   st->print(" holder=");
1496   holder()->print_name_on(st);
1497   st->print(" signature=");
1498   signature()->as_symbol()->print_symbol_on(st);
1499   if (is_loaded()) {
1500     st->print(" loaded=true");
1501     st->print(" arg_size=%d", arg_size());
1502     st->print(" flags=");
1503     flags().print_member_flags(st);
1504   } else {
1505     st->print(" loaded=false");
1506   }
1507 }
1508 
1509 // ------------------------------------------------------------------
1510 
1511 static BasicType erase_to_word_type(BasicType bt) {
1512   if (is_subword_type(bt))   return T_INT;
1513   if (is_reference_type(bt)) return T_OBJECT;
1514   return bt;
1515 }
1516 
1517 static bool basic_types_match(ciType* t1, ciType* t2) {
1518   if (t1 == t2)  return true;
1519   return erase_to_word_type(t1->basic_type()) == erase_to_word_type(t2->basic_type());
1520 }
1521 
1522 bool ciMethod::is_consistent_info(ciMethod* declared_method, ciMethod* resolved_method) {
1523   bool invoke_through_mh_intrinsic = declared_method->is_method_handle_intrinsic() &&
1524                                   !resolved_method->is_method_handle_intrinsic();
1525 
1526   if (!invoke_through_mh_intrinsic) {
1527     // Method name & descriptor should stay the same.
1528     // Signatures may reference unloaded types and thus they may be not strictly equal.
1529     ciSymbol* declared_signature = declared_method->signature()->as_symbol();
1530     ciSymbol* resolved_signature = resolved_method->signature()->as_symbol();
1531 
1532     return (declared_method->name()->equals(resolved_method->name())) &&
1533            (declared_signature->equals(resolved_signature));
1534   }
1535 
1536   ciMethod* linker = declared_method;
1537   ciMethod* target = resolved_method;
1538   // Linkers have appendix argument which is not passed to callee.
1539   int has_appendix = MethodHandles::has_member_arg(linker->intrinsic_id()) ? 1 : 0;
1540   if (linker->arg_size() != (target->arg_size() + has_appendix)) {
1541     return false; // argument slot count mismatch
1542   }
1543 
1544   ciSignature* linker_sig = linker->signature();
1545   ciSignature* target_sig = target->signature();
1546 
1547   if (linker_sig->count() + (linker->is_static() ? 0 : 1) !=
1548       target_sig->count() + (target->is_static() ? 0 : 1) + has_appendix) {
1549     return false; // argument count mismatch
1550   }
1551 
1552   int sbase = 0, rbase = 0;
1553   switch (linker->intrinsic_id()) {
1554     case vmIntrinsics::_linkToVirtual:
1555     case vmIntrinsics::_linkToInterface:
1556     case vmIntrinsics::_linkToSpecial: {
1557       if (target->is_static()) {
1558         return false;
1559       }
1560       if (linker_sig->type_at(0)->is_primitive_type()) {
1561         return false;  // receiver should be an oop
1562       }
1563       sbase = 1; // skip receiver
1564       break;
1565     }
1566     case vmIntrinsics::_linkToStatic: {
1567       if (!target->is_static()) {
1568         return false;
1569       }
1570       break;
1571     }
1572     case vmIntrinsics::_invokeBasic: {
1573       if (target->is_static()) {
1574         if (target_sig->type_at(0)->is_primitive_type()) {
1575           return false; // receiver should be an oop
1576         }
1577         rbase = 1; // skip receiver
1578       }
1579       break;
1580     }
1581     default:
1582       break;
1583   }
1584   assert(target_sig->count() - rbase == linker_sig->count() - sbase - has_appendix, "argument count mismatch");
1585   int arg_count = target_sig->count() - rbase;
1586   for (int i = 0; i < arg_count; i++) {
1587     if (!basic_types_match(linker_sig->type_at(sbase + i), target_sig->type_at(rbase + i))) {
1588       return false;
1589     }
1590   }
1591   // Only check the return type if the symbolic info has non-void return type.
1592   // I.e. the return value of the resolved method can be dropped.
1593   if (!linker->return_type()->is_void() &&
1594       !basic_types_match(linker->return_type(), target->return_type())) {
1595     return false;
1596   }
1597   return true; // no mismatch found
1598 }
1599 
1600 // ------------------------------------------------------------------
1601 // ciMethod::is_old
1602 //
1603 // Return true for redefined methods
1604 bool ciMethod::is_old() const {
1605   ASSERT_IN_VM;
1606   return get_Method()->is_old();
1607 }