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