1 /*
   2  * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2014, 2020, Red Hat Inc. All rights reserved.
   4  * Copyright (c) 2020, 2022, Huawei Technologies Co., Ltd. All rights reserved.
   5  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   6  *
   7  * This code is free software; you can redistribute it and/or modify it
   8  * under the terms of the GNU General Public License version 2 only, as
   9  * published by the Free Software Foundation.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  *
  25  */
  26 
  27 #include "precompiled.hpp"
  28 #include "asm/macroAssembler.inline.hpp"
  29 #include "gc/shared/barrierSet.hpp"
  30 #include "gc/shared/barrierSetAssembler.hpp"
  31 #include "interp_masm_riscv.hpp"
  32 #include "interpreter/interpreter.hpp"
  33 #include "interpreter/interpreterRuntime.hpp"
  34 #include "logging/log.hpp"
  35 #include "oops/arrayOop.hpp"
  36 #include "oops/markWord.hpp"
  37 #include "oops/method.hpp"
  38 #include "oops/methodData.hpp"
  39 #include "prims/jvmtiExport.hpp"
  40 #include "prims/jvmtiThreadState.hpp"
  41 #include "runtime/basicLock.hpp"
  42 #include "runtime/frame.inline.hpp"
  43 #include "runtime/javaThread.hpp"
  44 #include "runtime/safepointMechanism.hpp"
  45 #include "runtime/sharedRuntime.hpp"
  46 #include "utilities/powerOfTwo.hpp"
  47 
  48 void InterpreterMacroAssembler::narrow(Register result) {
  49   // Get method->_constMethod->_result_type
  50   ld(t0, Address(fp, frame::interpreter_frame_method_offset * wordSize));
  51   ld(t0, Address(t0, Method::const_offset()));
  52   lbu(t0, Address(t0, ConstMethod::result_type_offset()));
  53 
  54   Label done, notBool, notByte, notChar;
  55 
  56   // common case first
  57   mv(t1, T_INT);
  58   beq(t0, t1, done);
  59 
  60   // mask integer result to narrower return type.
  61   mv(t1, T_BOOLEAN);
  62   bne(t0, t1, notBool);
  63 
  64   andi(result, result, 0x1);
  65   j(done);
  66 
  67   bind(notBool);
  68   mv(t1, T_BYTE);
  69   bne(t0, t1, notByte);
  70   sign_extend(result, result, 8);
  71   j(done);
  72 
  73   bind(notByte);
  74   mv(t1, T_CHAR);
  75   bne(t0, t1, notChar);
  76   zero_extend(result, result, 16);
  77   j(done);
  78 
  79   bind(notChar);
  80   sign_extend(result, result, 16);
  81 
  82   // Nothing to do for T_INT
  83   bind(done);
  84   addw(result, result, zr);
  85 }
  86 
  87 void InterpreterMacroAssembler::jump_to_entry(address entry) {
  88   assert(entry != NULL, "Entry must have been generated by now");
  89   j(entry);
  90 }
  91 
  92 void InterpreterMacroAssembler::check_and_handle_popframe(Register java_thread) {
  93   if (JvmtiExport::can_pop_frame()) {
  94     Label L;
  95     // Initiate popframe handling only if it is not already being
  96     // processed. If the flag has the popframe_processing bit set,
  97     // it means that this code is called *during* popframe handling - we
  98     // don't want to reenter.
  99     // This method is only called just after the call into the vm in
 100     // call_VM_base, so the arg registers are available.
 101     lwu(t1, Address(xthread, JavaThread::popframe_condition_offset()));
 102     andi(t0, t1, JavaThread::popframe_pending_bit);
 103     beqz(t0, L);
 104     andi(t0, t1, JavaThread::popframe_processing_bit);
 105     bnez(t0, L);
 106     // Call Interpreter::remove_activation_preserving_args_entry() to get the
 107     // address of the same-named entrypoint in the generated interpreter code.
 108     call_VM_leaf(CAST_FROM_FN_PTR(address, Interpreter::remove_activation_preserving_args_entry));
 109     jr(x10);
 110     bind(L);
 111   }
 112 }
 113 
 114 
 115 void InterpreterMacroAssembler::load_earlyret_value(TosState state) {
 116   ld(x12, Address(xthread, JavaThread::jvmti_thread_state_offset()));
 117   const Address tos_addr(x12, JvmtiThreadState::earlyret_tos_offset());
 118   const Address oop_addr(x12, JvmtiThreadState::earlyret_oop_offset());
 119   const Address val_addr(x12, JvmtiThreadState::earlyret_value_offset());
 120   switch (state) {
 121     case atos:
 122       ld(x10, oop_addr);
 123       sd(zr, oop_addr);
 124       verify_oop(x10);
 125       break;
 126     case ltos:
 127       ld(x10, val_addr);
 128       break;
 129     case btos:  // fall through
 130     case ztos:  // fall through
 131     case ctos:  // fall through
 132     case stos:  // fall through
 133     case itos:
 134       lwu(x10, val_addr);
 135       break;
 136     case ftos:
 137       flw(f10, val_addr);
 138       break;
 139     case dtos:
 140       fld(f10, val_addr);
 141       break;
 142     case vtos:
 143       /* nothing to do */
 144       break;
 145     default:
 146       ShouldNotReachHere();
 147   }
 148   // Clean up tos value in the thread object
 149   mv(t0, (int)ilgl);
 150   sw(t0, tos_addr);
 151   sw(zr, val_addr);
 152 }
 153 
 154 
 155 void InterpreterMacroAssembler::check_and_handle_earlyret(Register java_thread) {
 156   if (JvmtiExport::can_force_early_return()) {
 157     Label L;
 158     ld(t0, Address(xthread, JavaThread::jvmti_thread_state_offset()));
 159     beqz(t0, L);  // if [thread->jvmti_thread_state() == NULL] then exit
 160 
 161     // Initiate earlyret handling only if it is not already being processed.
 162     // If the flag has the earlyret_processing bit set, it means that this code
 163     // is called *during* earlyret handling - we don't want to reenter.
 164     lwu(t0, Address(t0, JvmtiThreadState::earlyret_state_offset()));
 165     mv(t1, JvmtiThreadState::earlyret_pending);
 166     bne(t0, t1, L);
 167 
 168     // Call Interpreter::remove_activation_early_entry() to get the address of the
 169     // same-named entrypoint in the generated interpreter code.
 170     ld(t0, Address(xthread, JavaThread::jvmti_thread_state_offset()));
 171     lwu(t0, Address(t0, JvmtiThreadState::earlyret_tos_offset()));
 172     call_VM_leaf(CAST_FROM_FN_PTR(address, Interpreter::remove_activation_early_entry), t0);
 173     jr(x10);
 174     bind(L);
 175   }
 176 }
 177 
 178 void InterpreterMacroAssembler::get_unsigned_2_byte_index_at_bcp(Register reg, int bcp_offset) {
 179   assert(bcp_offset >= 0, "bcp is still pointing to start of bytecode");
 180   lhu(reg, Address(xbcp, bcp_offset));
 181   revb_h(reg, reg);
 182 }
 183 
 184 void InterpreterMacroAssembler::get_dispatch() {
 185   ExternalAddress target((address)Interpreter::dispatch_table());
 186   relocate(target.rspec(), [&] {
 187     int32_t offset;
 188     la_patchable(xdispatch, target, offset);
 189     addi(xdispatch, xdispatch, offset);
 190   });
 191 }
 192 
 193 void InterpreterMacroAssembler::get_cache_index_at_bcp(Register index,
 194                                                        int bcp_offset,
 195                                                        size_t index_size) {
 196   assert(bcp_offset > 0, "bcp is still pointing to start of bytecode");
 197   if (index_size == sizeof(u2)) {
 198     load_unsigned_short(index, Address(xbcp, bcp_offset));
 199   } else if (index_size == sizeof(u4)) {
 200     lwu(index, Address(xbcp, bcp_offset));
 201     // Check if the secondary index definition is still ~x, otherwise
 202     // we have to change the following assembler code to calculate the
 203     // plain index.
 204     assert(ConstantPool::decode_invokedynamic_index(~123) == 123, "else change next line");
 205     xori(index, index, -1);
 206     addw(index, index, zr);
 207   } else if (index_size == sizeof(u1)) {
 208     load_unsigned_byte(index, Address(xbcp, bcp_offset));
 209   } else {
 210     ShouldNotReachHere();
 211   }
 212 }
 213 
 214 // Return
 215 // Rindex: index into constant pool
 216 // Rcache: address of cache entry - ConstantPoolCache::base_offset()
 217 //
 218 // A caller must add ConstantPoolCache::base_offset() to Rcache to get
 219 // the true address of the cache entry.
 220 //
 221 void InterpreterMacroAssembler::get_cache_and_index_at_bcp(Register cache,
 222                                                            Register index,
 223                                                            int bcp_offset,
 224                                                            size_t index_size) {
 225   assert_different_registers(cache, index);
 226   assert_different_registers(cache, xcpool);
 227   get_cache_index_at_bcp(index, bcp_offset, index_size);
 228   assert(sizeof(ConstantPoolCacheEntry) == 4 * wordSize, "adjust code below");
 229   // Convert from field index to ConstantPoolCacheEntry
 230   // riscv already has the cache in xcpool so there is no need to
 231   // install it in cache. Instead we pre-add the indexed offset to
 232   // xcpool and return it in cache. All clients of this method need to
 233   // be modified accordingly.
 234   shadd(cache, index, xcpool, cache, 5);
 235 }
 236 
 237 
 238 void InterpreterMacroAssembler::get_cache_and_index_and_bytecode_at_bcp(Register cache,
 239                                                                         Register index,
 240                                                                         Register bytecode,
 241                                                                         int byte_no,
 242                                                                         int bcp_offset,
 243                                                                         size_t index_size) {
 244   get_cache_and_index_at_bcp(cache, index, bcp_offset, index_size);
 245   // We use a 32-bit load here since the layout of 64-bit words on
 246   // little-endian machines allow us that.
 247   // n.b. unlike x86 cache already includes the index offset
 248   la(bytecode, Address(cache,
 249                        ConstantPoolCache::base_offset() +
 250                        ConstantPoolCacheEntry::indices_offset()));
 251   membar(MacroAssembler::AnyAny);
 252   lwu(bytecode, bytecode);
 253   membar(MacroAssembler::LoadLoad | MacroAssembler::LoadStore);
 254   const int shift_count = (1 + byte_no) * BitsPerByte;
 255   slli(bytecode, bytecode, XLEN - (shift_count + BitsPerByte));
 256   srli(bytecode, bytecode, XLEN - BitsPerByte);
 257 }
 258 
 259 void InterpreterMacroAssembler::get_cache_entry_pointer_at_bcp(Register cache,
 260                                                                Register tmp,
 261                                                                int bcp_offset,
 262                                                                size_t index_size) {
 263   assert_different_registers(cache, tmp);
 264   get_cache_index_at_bcp(tmp, bcp_offset, index_size);
 265   assert(sizeof(ConstantPoolCacheEntry) == 4 * wordSize, "adjust code below");
 266   // Convert from field index to ConstantPoolCacheEntry index
 267   // and from word offset to byte offset
 268   assert(exact_log2(in_bytes(ConstantPoolCacheEntry::size_in_bytes())) == 2 + LogBytesPerWord,
 269          "else change next line");
 270   ld(cache, Address(fp, frame::interpreter_frame_cache_offset * wordSize));
 271   // skip past the header
 272   add(cache, cache, in_bytes(ConstantPoolCache::base_offset()));
 273   // construct pointer to cache entry
 274   shadd(cache, tmp, cache, tmp, 2 + LogBytesPerWord);
 275 }
 276 
 277 // Load object from cpool->resolved_references(index)
 278 void InterpreterMacroAssembler::load_resolved_reference_at_index(
 279                                 Register result, Register index, Register tmp) {
 280   assert_different_registers(result, index);
 281 
 282   get_constant_pool(result);
 283   // Load pointer for resolved_references[] objArray
 284   ld(result, Address(result, ConstantPool::cache_offset_in_bytes()));
 285   ld(result, Address(result, ConstantPoolCache::resolved_references_offset_in_bytes()));
 286   resolve_oop_handle(result, tmp, t1);
 287   // Add in the index
 288   addi(index, index, arrayOopDesc::base_offset_in_bytes(T_OBJECT) >> LogBytesPerHeapOop);
 289   shadd(result, index, result, index, LogBytesPerHeapOop);
 290   load_heap_oop(result, Address(result, 0), tmp, t1);
 291 }
 292 
 293 void InterpreterMacroAssembler::load_resolved_klass_at_offset(
 294                                 Register cpool, Register index, Register klass, Register temp) {
 295   shadd(temp, index, cpool, temp, LogBytesPerWord);
 296   lhu(temp, Address(temp, sizeof(ConstantPool))); // temp = resolved_klass_index
 297   ld(klass, Address(cpool, ConstantPool::resolved_klasses_offset_in_bytes())); // klass = cpool->_resolved_klasses
 298   shadd(klass, temp, klass, temp, LogBytesPerWord);
 299   ld(klass, Address(klass, Array<Klass*>::base_offset_in_bytes()));
 300 }
 301 
 302 void InterpreterMacroAssembler::load_resolved_method_at_index(int byte_no,
 303                                                               Register method,
 304                                                               Register cache) {
 305   const int method_offset = in_bytes(
 306     ConstantPoolCache::base_offset() +
 307       ((byte_no == TemplateTable::f2_byte)
 308        ? ConstantPoolCacheEntry::f2_offset()
 309        : ConstantPoolCacheEntry::f1_offset()));
 310 
 311   ld(method, Address(cache, method_offset)); // get f1 Method*
 312 }
 313 
 314 // Generate a subtype check: branch to ok_is_subtype if sub_klass is a
 315 // subtype of super_klass.
 316 //
 317 // Args:
 318 //      x10: superklass
 319 //      Rsub_klass: subklass
 320 //
 321 // Kills:
 322 //      x12, x15
 323 void InterpreterMacroAssembler::gen_subtype_check(Register Rsub_klass,
 324                                                   Label& ok_is_subtype) {
 325   assert(Rsub_klass != x10, "x10 holds superklass");
 326   assert(Rsub_klass != x12, "x12 holds 2ndary super array length");
 327   assert(Rsub_klass != x15, "x15 holds 2ndary super array scan ptr");
 328 
 329   // Profile the not-null value's klass.
 330   profile_typecheck(x12, Rsub_klass, x15); // blows x12, reloads x15
 331 
 332   // Do the check.
 333   check_klass_subtype(Rsub_klass, x10, x12, ok_is_subtype); // blows x12
 334 
 335   // Profile the failure of the check.
 336   profile_typecheck_failed(x12); // blows x12
 337 }
 338 
 339 // Java Expression Stack
 340 
 341 void InterpreterMacroAssembler::pop_ptr(Register r) {
 342   ld(r, Address(esp, 0));
 343   addi(esp, esp, wordSize);
 344 }
 345 
 346 void InterpreterMacroAssembler::pop_i(Register r) {
 347   lw(r, Address(esp, 0)); // lw do signed extended
 348   addi(esp, esp, wordSize);
 349 }
 350 
 351 void InterpreterMacroAssembler::pop_l(Register r) {
 352   ld(r, Address(esp, 0));
 353   addi(esp, esp, 2 * Interpreter::stackElementSize);
 354 }
 355 
 356 void InterpreterMacroAssembler::push_ptr(Register r) {
 357   addi(esp, esp, -wordSize);
 358   sd(r, Address(esp, 0));
 359 }
 360 
 361 void InterpreterMacroAssembler::push_i(Register r) {
 362   addi(esp, esp, -wordSize);
 363   addw(r, r, zr); // signed extended
 364   sd(r, Address(esp, 0));
 365 }
 366 
 367 void InterpreterMacroAssembler::push_l(Register r) {
 368   addi(esp, esp, -2 * wordSize);
 369   sd(zr, Address(esp, wordSize));
 370   sd(r, Address(esp));
 371 }
 372 
 373 void InterpreterMacroAssembler::pop_f(FloatRegister r) {
 374   flw(r, Address(esp, 0));
 375   addi(esp, esp, wordSize);
 376 }
 377 
 378 void InterpreterMacroAssembler::pop_d(FloatRegister r) {
 379   fld(r, Address(esp, 0));
 380   addi(esp, esp, 2 * Interpreter::stackElementSize);
 381 }
 382 
 383 void InterpreterMacroAssembler::push_f(FloatRegister r) {
 384   addi(esp, esp, -wordSize);
 385   fsw(r, Address(esp, 0));
 386 }
 387 
 388 void InterpreterMacroAssembler::push_d(FloatRegister r) {
 389   addi(esp, esp, -2 * wordSize);
 390   fsd(r, Address(esp, 0));
 391 }
 392 
 393 void InterpreterMacroAssembler::pop(TosState state) {
 394   switch (state) {
 395     case atos:
 396       pop_ptr();
 397       verify_oop(x10);
 398       break;
 399     case btos:  // fall through
 400     case ztos:  // fall through
 401     case ctos:  // fall through
 402     case stos:  // fall through
 403     case itos:
 404       pop_i();
 405       break;
 406     case ltos:
 407       pop_l();
 408       break;
 409     case ftos:
 410       pop_f();
 411       break;
 412     case dtos:
 413       pop_d();
 414       break;
 415     case vtos:
 416       /* nothing to do */
 417       break;
 418     default:
 419       ShouldNotReachHere();
 420   }
 421 }
 422 
 423 void InterpreterMacroAssembler::push(TosState state) {
 424   switch (state) {
 425     case atos:
 426       verify_oop(x10);
 427       push_ptr();
 428       break;
 429     case btos:  // fall through
 430     case ztos:  // fall through
 431     case ctos:  // fall through
 432     case stos:  // fall through
 433     case itos:
 434       push_i();
 435       break;
 436     case ltos:
 437       push_l();
 438       break;
 439     case ftos:
 440       push_f();
 441       break;
 442     case dtos:
 443       push_d();
 444       break;
 445     case vtos:
 446       /* nothing to do */
 447       break;
 448     default:
 449       ShouldNotReachHere();
 450   }
 451 }
 452 
 453 // Helpers for swap and dup
 454 void InterpreterMacroAssembler::load_ptr(int n, Register val) {
 455   ld(val, Address(esp, Interpreter::expr_offset_in_bytes(n)));
 456 }
 457 
 458 void InterpreterMacroAssembler::store_ptr(int n, Register val) {
 459   sd(val, Address(esp, Interpreter::expr_offset_in_bytes(n)));
 460 }
 461 
 462 void InterpreterMacroAssembler::load_float(Address src) {
 463   flw(f10, src);
 464 }
 465 
 466 void InterpreterMacroAssembler::load_double(Address src) {
 467   fld(f10, src);
 468 }
 469 
 470 void InterpreterMacroAssembler::prepare_to_jump_from_interpreted() {
 471   // set sender sp
 472   mv(x19_sender_sp, sp);
 473   // record last_sp
 474   sd(esp, Address(fp, frame::interpreter_frame_last_sp_offset * wordSize));
 475 }
 476 
 477 // Jump to from_interpreted entry of a call unless single stepping is possible
 478 // in this thread in which case we must call the i2i entry
 479 void InterpreterMacroAssembler::jump_from_interpreted(Register method) {
 480   prepare_to_jump_from_interpreted();
 481   if (JvmtiExport::can_post_interpreter_events()) {
 482     Label run_compiled_code;
 483     // JVMTI events, such as single-stepping, are implemented partly by avoiding running
 484     // compiled code in threads for which the event is enabled.  Check here for
 485     // interp_only_mode if these events CAN be enabled.
 486     lwu(t0, Address(xthread, JavaThread::interp_only_mode_offset()));
 487     beqz(t0, run_compiled_code);
 488     ld(t0, Address(method, Method::interpreter_entry_offset()));
 489     jr(t0);
 490     bind(run_compiled_code);
 491   }
 492 
 493   ld(t0, Address(method, Method::from_interpreted_offset()));
 494   jr(t0);
 495 }
 496 
 497 // The following two routines provide a hook so that an implementation
 498 // can schedule the dispatch in two parts.  amd64 does not do this.
 499 void InterpreterMacroAssembler::dispatch_prolog(TosState state, int step) {
 500 }
 501 
 502 void InterpreterMacroAssembler::dispatch_epilog(TosState state, int step) {
 503   dispatch_next(state, step);
 504 }
 505 
 506 void InterpreterMacroAssembler::dispatch_base(TosState state,
 507                                               address* table,
 508                                               bool verifyoop,
 509                                               bool generate_poll,
 510                                               Register Rs) {
 511   // Pay attention to the argument Rs, which is acquiesce in t0.
 512   if (VerifyActivationFrameSize) {
 513     Unimplemented();
 514   }
 515   if (verifyoop && state == atos) {
 516     verify_oop(x10);
 517   }
 518 
 519   Label safepoint;
 520   address* const safepoint_table = Interpreter::safept_table(state);
 521   bool needs_thread_local_poll = generate_poll && table != safepoint_table;
 522 
 523   if (needs_thread_local_poll) {
 524     NOT_PRODUCT(block_comment("Thread-local Safepoint poll"));
 525     ld(t1, Address(xthread, JavaThread::polling_word_offset()));
 526     andi(t1, t1, SafepointMechanism::poll_bit());
 527     bnez(t1, safepoint);
 528   }
 529   if (table == Interpreter::dispatch_table(state)) {
 530     mv(t1, Interpreter::distance_from_dispatch_table(state));
 531     add(t1, Rs, t1);
 532     shadd(t1, t1, xdispatch, t1, 3);
 533   } else {
 534     mv(t1, (address)table);
 535     shadd(t1, Rs, t1, Rs, 3);
 536   }
 537   ld(t1, Address(t1));
 538   jr(t1);
 539 
 540   if (needs_thread_local_poll) {
 541     bind(safepoint);
 542     la(t1, ExternalAddress((address)safepoint_table));
 543     shadd(t1, Rs, t1, Rs, 3);
 544     ld(t1, Address(t1));
 545     jr(t1);
 546   }
 547 }
 548 
 549 void InterpreterMacroAssembler::dispatch_only(TosState state, bool generate_poll, Register Rs) {
 550   dispatch_base(state, Interpreter::dispatch_table(state), true, generate_poll, Rs);
 551 }
 552 
 553 void InterpreterMacroAssembler::dispatch_only_normal(TosState state, Register Rs) {
 554   dispatch_base(state, Interpreter::normal_table(state), true, false, Rs);
 555 }
 556 
 557 void InterpreterMacroAssembler::dispatch_only_noverify(TosState state, Register Rs) {
 558   dispatch_base(state, Interpreter::normal_table(state), false, false, Rs);
 559 }
 560 
 561 void InterpreterMacroAssembler::dispatch_next(TosState state, int step, bool generate_poll) {
 562   // load next bytecode
 563   load_unsigned_byte(t0, Address(xbcp, step));
 564   add(xbcp, xbcp, step);
 565   dispatch_base(state, Interpreter::dispatch_table(state), true, generate_poll);
 566 }
 567 
 568 void InterpreterMacroAssembler::dispatch_via(TosState state, address* table) {
 569   // load current bytecode
 570   lbu(t0, Address(xbcp, 0));
 571   dispatch_base(state, table);
 572 }
 573 
 574 // remove activation
 575 //
 576 // Apply stack watermark barrier.
 577 // Unlock the receiver if this is a synchronized method.
 578 // Unlock any Java monitors from synchronized blocks.
 579 // Remove the activation from the stack.
 580 //
 581 // If there are locked Java monitors
 582 //    If throw_monitor_exception
 583 //       throws IllegalMonitorStateException
 584 //    Else if install_monitor_exception
 585 //       installs IllegalMonitorStateException
 586 //    Else
 587 //       no error processing
 588 void InterpreterMacroAssembler::remove_activation(
 589                                 TosState state,
 590                                 bool throw_monitor_exception,
 591                                 bool install_monitor_exception,
 592                                 bool notify_jvmdi) {
 593   // Note: Registers x13 may be in use for the
 594   // result check if synchronized method
 595   Label unlocked, unlock, no_unlock;
 596 
 597   // The below poll is for the stack watermark barrier. It allows fixing up frames lazily,
 598   // that would normally not be safe to use. Such bad returns into unsafe territory of
 599   // the stack, will call InterpreterRuntime::at_unwind.
 600   Label slow_path;
 601   Label fast_path;
 602   safepoint_poll(slow_path, true /* at_return */, false /* acquire */, false /* in_nmethod */);
 603   j(fast_path);
 604 
 605   bind(slow_path);
 606   push(state);
 607   set_last_Java_frame(esp, fp, (address)pc(), t0);
 608   super_call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::at_unwind), xthread);
 609   reset_last_Java_frame(true);
 610   pop(state);
 611 
 612   bind(fast_path);
 613 
 614   // get the value of _do_not_unlock_if_synchronized into x13
 615   const Address do_not_unlock_if_synchronized(xthread,
 616     in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
 617   lbu(x13, do_not_unlock_if_synchronized);
 618   sb(zr, do_not_unlock_if_synchronized); // reset the flag
 619 
 620   // get method access flags
 621   ld(x11, Address(fp, frame::interpreter_frame_method_offset * wordSize));
 622   ld(x12, Address(x11, Method::access_flags_offset()));
 623   andi(t0, x12, JVM_ACC_SYNCHRONIZED);
 624   beqz(t0, unlocked);
 625 
 626   // Don't unlock anything if the _do_not_unlock_if_synchronized flag
 627   // is set.
 628   bnez(x13, no_unlock);
 629 
 630   // unlock monitor
 631   push(state); // save result
 632 
 633   // BasicObjectLock will be first in list, since this is a
 634   // synchronized method. However, need to check that the object has
 635   // not been unlocked by an explicit monitorexit bytecode.
 636   const Address monitor(fp, frame::interpreter_frame_initial_sp_offset *
 637                         wordSize - (int) sizeof(BasicObjectLock));
 638   // We use c_rarg1 so that if we go slow path it will be the correct
 639   // register for unlock_object to pass to VM directly
 640   la(c_rarg1, monitor); // address of first monitor
 641 
 642   ld(x10, Address(c_rarg1, BasicObjectLock::obj_offset_in_bytes()));
 643   bnez(x10, unlock);
 644 
 645   pop(state);
 646   if (throw_monitor_exception) {
 647     // Entry already unlocked, need to throw exception
 648     call_VM(noreg, CAST_FROM_FN_PTR(address,
 649                                     InterpreterRuntime::throw_illegal_monitor_state_exception));
 650     should_not_reach_here();
 651   } else {
 652     // Monitor already unlocked during a stack unroll. If requested,
 653     // install an illegal_monitor_state_exception.  Continue with
 654     // stack unrolling.
 655     if (install_monitor_exception) {
 656       call_VM(noreg, CAST_FROM_FN_PTR(address,
 657                                       InterpreterRuntime::new_illegal_monitor_state_exception));
 658     }
 659     j(unlocked);
 660   }
 661 
 662   bind(unlock);
 663   unlock_object(c_rarg1);
 664   pop(state);
 665 
 666   // Check that for block-structured locking (i.e., that all locked
 667   // objects has been unlocked)
 668   bind(unlocked);
 669 
 670   // x10: Might contain return value
 671 
 672   // Check that all monitors are unlocked
 673   {
 674     Label loop, exception, entry, restart;
 675     const int entry_size = frame::interpreter_frame_monitor_size() * wordSize;
 676     const Address monitor_block_top(
 677       fp, frame::interpreter_frame_monitor_block_top_offset * wordSize);
 678     const Address monitor_block_bot(
 679       fp, frame::interpreter_frame_initial_sp_offset * wordSize);
 680 
 681     bind(restart);
 682     // We use c_rarg1 so that if we go slow path it will be the correct
 683     // register for unlock_object to pass to VM directly
 684     ld(c_rarg1, monitor_block_top); // points to current entry, starting
 685                                      // with top-most entry
 686     la(x9, monitor_block_bot);  // points to word before bottom of
 687                                   // monitor block
 688 
 689     j(entry);
 690 
 691     // Entry already locked, need to throw exception
 692     bind(exception);
 693 
 694     if (throw_monitor_exception) {
 695       // Throw exception
 696       MacroAssembler::call_VM(noreg,
 697                               CAST_FROM_FN_PTR(address, InterpreterRuntime::
 698                                                throw_illegal_monitor_state_exception));
 699 
 700       should_not_reach_here();
 701     } else {
 702       // Stack unrolling. Unlock object and install illegal_monitor_exception.
 703       // Unlock does not block, so don't have to worry about the frame.
 704       // We don't have to preserve c_rarg1 since we are going to throw an exception.
 705 
 706       push(state);
 707       unlock_object(c_rarg1);
 708       pop(state);
 709 
 710       if (install_monitor_exception) {
 711         call_VM(noreg, CAST_FROM_FN_PTR(address,
 712                                         InterpreterRuntime::
 713                                         new_illegal_monitor_state_exception));
 714       }
 715 
 716       j(restart);
 717     }
 718 
 719     bind(loop);
 720     // check if current entry is used
 721     add(t0, c_rarg1, BasicObjectLock::obj_offset_in_bytes());
 722     ld(t0, Address(t0, 0));
 723     bnez(t0, exception);
 724 
 725     add(c_rarg1, c_rarg1, entry_size); // otherwise advance to next entry
 726     bind(entry);
 727     bne(c_rarg1, x9, loop); // check if bottom reached if not at bottom then check this entry
 728   }
 729 
 730   bind(no_unlock);
 731 
 732   // jvmti support
 733   if (notify_jvmdi) {
 734     notify_method_exit(state, NotifyJVMTI);    // preserve TOSCA
 735 
 736   } else {
 737     notify_method_exit(state, SkipNotifyJVMTI); // preserve TOSCA
 738   }
 739 
 740   // remove activation
 741   // get sender esp
 742   ld(t1,
 743      Address(fp, frame::interpreter_frame_sender_sp_offset * wordSize));
 744   if (StackReservedPages > 0) {
 745     // testing if reserved zone needs to be re-enabled
 746     Label no_reserved_zone_enabling;
 747 
 748     ld(t0, Address(xthread, JavaThread::reserved_stack_activation_offset()));
 749     ble(t1, t0, no_reserved_zone_enabling);
 750 
 751     call_VM_leaf(
 752       CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), xthread);
 753     call_VM(noreg, CAST_FROM_FN_PTR(address,
 754                                     InterpreterRuntime::throw_delayed_StackOverflowError));
 755     should_not_reach_here();
 756 
 757     bind(no_reserved_zone_enabling);
 758   }
 759 
 760   // restore sender esp
 761   mv(esp, t1);
 762 
 763   // remove frame anchor
 764   leave();
 765   // If we're returning to interpreted code we will shortly be
 766   // adjusting SP to allow some space for ESP.  If we're returning to
 767   // compiled code the saved sender SP was saved in sender_sp, so this
 768   // restores it.
 769   andi(sp, esp, -16);
 770 }
 771 
 772 // Lock object
 773 //
 774 // Args:
 775 //      c_rarg1: BasicObjectLock to be used for locking
 776 //
 777 // Kills:
 778 //      x10
 779 //      c_rarg0, c_rarg1, c_rarg2, c_rarg3, .. (param regs)
 780 //      t0, t1 (temp regs)
 781 void InterpreterMacroAssembler::lock_object(Register lock_reg)
 782 {
 783   assert(lock_reg == c_rarg1, "The argument is only for looks. It must be c_rarg1");
 784   if (UseHeavyMonitors) {
 785     call_VM(noreg,
 786             CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter),
 787             lock_reg);
 788   } else {
 789     Label count, done;
 790 
 791     const Register swap_reg = x10;
 792     const Register tmp = c_rarg2;
 793     const Register obj_reg = c_rarg3; // Will contain the oop
 794 
 795     const int obj_offset = BasicObjectLock::obj_offset_in_bytes();
 796     const int lock_offset = BasicObjectLock::lock_offset_in_bytes ();
 797     const int mark_offset = lock_offset +
 798                             BasicLock::displaced_header_offset_in_bytes();
 799 
 800     Label slow_case;
 801 
 802     // Load object pointer into obj_reg c_rarg3
 803     ld(obj_reg, Address(lock_reg, obj_offset));
 804 
 805     if (DiagnoseSyncOnValueBasedClasses != 0) {
 806       load_klass(tmp, obj_reg);
 807       lwu(tmp, Address(tmp, Klass::access_flags_offset()));
 808       andi(tmp, tmp, JVM_ACC_IS_VALUE_BASED_CLASS);
 809       bnez(tmp, slow_case);
 810     }
 811 
 812     // Load (object->mark() | 1) into swap_reg
 813     ld(t0, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
 814     ori(swap_reg, t0, 1);
 815 
 816     // Save (object->mark() | 1) into BasicLock's displaced header
 817     sd(swap_reg, Address(lock_reg, mark_offset));
 818 
 819     assert(lock_offset == 0,
 820            "displached header must be first word in BasicObjectLock");
 821 
 822     cmpxchg_obj_header(swap_reg, lock_reg, obj_reg, t0, count, /*fallthrough*/NULL);
 823 
 824     // Test if the oopMark is an obvious stack pointer, i.e.,
 825     //  1) (mark & 7) == 0, and
 826     //  2) sp <= mark < mark + os::pagesize()
 827     //
 828     // These 3 tests can be done by evaluating the following
 829     // expression: ((mark - sp) & (7 - os::vm_page_size())),
 830     // assuming both stack pointer and pagesize have their
 831     // least significant 3 bits clear.
 832     // NOTE: the oopMark is in swap_reg x10 as the result of cmpxchg
 833     sub(swap_reg, swap_reg, sp);
 834     mv(t0, (int64_t)(7 - (int)os::vm_page_size()));
 835     andr(swap_reg, swap_reg, t0);
 836 
 837     // Save the test result, for recursive case, the result is zero
 838     sd(swap_reg, Address(lock_reg, mark_offset));
 839     beqz(swap_reg, count);
 840 
 841     bind(slow_case);
 842 
 843     // Call the runtime routine for slow case
 844     call_VM(noreg,
 845             CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter),
 846             lock_reg);
 847 
 848     j(done);
 849 
 850     bind(count);
 851     increment(Address(xthread, JavaThread::held_monitor_count_offset()));
 852 
 853     bind(done);
 854   }
 855 }
 856 
 857 
 858 // Unlocks an object. Used in monitorexit bytecode and
 859 // remove_activation.  Throws an IllegalMonitorException if object is
 860 // not locked by current thread.
 861 //
 862 // Args:
 863 //      c_rarg1: BasicObjectLock for lock
 864 //
 865 // Kills:
 866 //      x10
 867 //      c_rarg0, c_rarg1, c_rarg2, c_rarg3, ... (param regs)
 868 //      t0, t1 (temp regs)
 869 void InterpreterMacroAssembler::unlock_object(Register lock_reg)
 870 {
 871   assert(lock_reg == c_rarg1, "The argument is only for looks. It must be rarg1");
 872 
 873   if (UseHeavyMonitors) {
 874     call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit), lock_reg);
 875   } else {
 876     Label count, done;
 877 
 878     const Register swap_reg   = x10;
 879     const Register header_reg = c_rarg2;  // Will contain the old oopMark
 880     const Register obj_reg    = c_rarg3;  // Will contain the oop
 881 
 882     save_bcp(); // Save in case of exception
 883 
 884     // Convert from BasicObjectLock structure to object and BasicLock
 885     // structure Store the BasicLock address into x10
 886     la(swap_reg, Address(lock_reg, BasicObjectLock::lock_offset_in_bytes()));
 887 
 888     // Load oop into obj_reg(c_rarg3)
 889     ld(obj_reg, Address(lock_reg, BasicObjectLock::obj_offset_in_bytes()));
 890 
 891     // Free entry
 892     sd(zr, Address(lock_reg, BasicObjectLock::obj_offset_in_bytes()));
 893 
 894     // Load the old header from BasicLock structure
 895     ld(header_reg, Address(swap_reg,
 896                            BasicLock::displaced_header_offset_in_bytes()));
 897 
 898     // Test for recursion
 899     beqz(header_reg, count);
 900 
 901     // Atomic swap back the old header
 902     cmpxchg_obj_header(swap_reg, header_reg, obj_reg, t0, count, /*fallthrough*/NULL);
 903 
 904     // Call the runtime routine for slow case.
 905     sd(obj_reg, Address(lock_reg, BasicObjectLock::obj_offset_in_bytes())); // restore obj
 906     call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit), lock_reg);
 907 
 908     j(done);
 909 
 910     bind(count);
 911     decrement(Address(xthread, JavaThread::held_monitor_count_offset()));
 912 
 913     bind(done);
 914 
 915     restore_bcp();
 916   }
 917 }
 918 
 919 
 920 void InterpreterMacroAssembler::test_method_data_pointer(Register mdp,
 921                                                          Label& zero_continue) {
 922   assert(ProfileInterpreter, "must be profiling interpreter");
 923   ld(mdp, Address(fp, frame::interpreter_frame_mdp_offset * wordSize));
 924   beqz(mdp, zero_continue);
 925 }
 926 
 927 // Set the method data pointer for the current bcp.
 928 void InterpreterMacroAssembler::set_method_data_pointer_for_bcp() {
 929   assert(ProfileInterpreter, "must be profiling interpreter");
 930   Label set_mdp;
 931   push_reg(RegSet::of(x10, x11), sp); // save x10, x11
 932 
 933   // Test MDO to avoid the call if it is NULL.
 934   ld(x10, Address(xmethod, in_bytes(Method::method_data_offset())));
 935   beqz(x10, set_mdp);
 936   call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::bcp_to_di), xmethod, xbcp);
 937   // x10: mdi
 938   // mdo is guaranteed to be non-zero here, we checked for it before the call.
 939   ld(x11, Address(xmethod, in_bytes(Method::method_data_offset())));
 940   la(x11, Address(x11, in_bytes(MethodData::data_offset())));
 941   add(x10, x11, x10);
 942   sd(x10, Address(fp, frame::interpreter_frame_mdp_offset * wordSize));
 943   bind(set_mdp);
 944   pop_reg(RegSet::of(x10, x11), sp);
 945 }
 946 
 947 void InterpreterMacroAssembler::verify_method_data_pointer() {
 948   assert(ProfileInterpreter, "must be profiling interpreter");
 949 #ifdef ASSERT
 950   Label verify_continue;
 951   add(sp, sp, -4 * wordSize);
 952   sd(x10, Address(sp, 0));
 953   sd(x11, Address(sp, wordSize));
 954   sd(x12, Address(sp, 2 * wordSize));
 955   sd(x13, Address(sp, 3 * wordSize));
 956   test_method_data_pointer(x13, verify_continue); // If mdp is zero, continue
 957   get_method(x11);
 958 
 959   // If the mdp is valid, it will point to a DataLayout header which is
 960   // consistent with the bcp.  The converse is highly probable also.
 961   lh(x12, Address(x13, in_bytes(DataLayout::bci_offset())));
 962   ld(t0, Address(x11, Method::const_offset()));
 963   add(x12, x12, t0);
 964   la(x12, Address(x12, ConstMethod::codes_offset()));
 965   beq(x12, xbcp, verify_continue);
 966   // x10: method
 967   // xbcp: bcp // xbcp == 22
 968   // x13: mdp
 969   call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::verify_mdp),
 970                x11, xbcp, x13);
 971   bind(verify_continue);
 972   ld(x10, Address(sp, 0));
 973   ld(x11, Address(sp, wordSize));
 974   ld(x12, Address(sp, 2 * wordSize));
 975   ld(x13, Address(sp, 3 * wordSize));
 976   add(sp, sp, 4 * wordSize);
 977 #endif // ASSERT
 978 }
 979 
 980 
 981 void InterpreterMacroAssembler::set_mdp_data_at(Register mdp_in,
 982                                                 int constant,
 983                                                 Register value) {
 984   assert(ProfileInterpreter, "must be profiling interpreter");
 985   Address data(mdp_in, constant);
 986   sd(value, data);
 987 }
 988 
 989 
 990 void InterpreterMacroAssembler::increment_mdp_data_at(Register mdp_in,
 991                                                       int constant,
 992                                                       bool decrement) {
 993   increment_mdp_data_at(mdp_in, noreg, constant, decrement);
 994 }
 995 
 996 void InterpreterMacroAssembler::increment_mdp_data_at(Register mdp_in,
 997                                                       Register reg,
 998                                                       int constant,
 999                                                       bool decrement) {
1000   assert(ProfileInterpreter, "must be profiling interpreter");
1001   // %%% this does 64bit counters at best it is wasting space
1002   // at worst it is a rare bug when counters overflow
1003 
1004   assert_different_registers(t1, t0, mdp_in, reg);
1005 
1006   Address addr1(mdp_in, constant);
1007   Address addr2(t1, 0);
1008   Address &addr = addr1;
1009   if (reg != noreg) {
1010     la(t1, addr1);
1011     add(t1, t1, reg);
1012     addr = addr2;
1013   }
1014 
1015   if (decrement) {
1016     ld(t0, addr);
1017     addi(t0, t0, -DataLayout::counter_increment);
1018     Label L;
1019     bltz(t0, L);      // skip store if counter underflow
1020     sd(t0, addr);
1021     bind(L);
1022   } else {
1023     assert(DataLayout::counter_increment == 1,
1024            "flow-free idiom only works with 1");
1025     ld(t0, addr);
1026     addi(t0, t0, DataLayout::counter_increment);
1027     Label L;
1028     blez(t0, L);       // skip store if counter overflow
1029     sd(t0, addr);
1030     bind(L);
1031   }
1032 }
1033 
1034 void InterpreterMacroAssembler::set_mdp_flag_at(Register mdp_in,
1035                                                 int flag_byte_constant) {
1036   assert(ProfileInterpreter, "must be profiling interpreter");
1037   int flags_offset = in_bytes(DataLayout::flags_offset());
1038   // Set the flag
1039   lbu(t1, Address(mdp_in, flags_offset));
1040   ori(t1, t1, flag_byte_constant);
1041   sb(t1, Address(mdp_in, flags_offset));
1042 }
1043 
1044 
1045 void InterpreterMacroAssembler::test_mdp_data_at(Register mdp_in,
1046                                                  int offset,
1047                                                  Register value,
1048                                                  Register test_value_out,
1049                                                  Label& not_equal_continue) {
1050   assert(ProfileInterpreter, "must be profiling interpreter");
1051   if (test_value_out == noreg) {
1052     ld(t1, Address(mdp_in, offset));
1053     bne(value, t1, not_equal_continue);
1054   } else {
1055     // Put the test value into a register, so caller can use it:
1056     ld(test_value_out, Address(mdp_in, offset));
1057     bne(value, test_value_out, not_equal_continue);
1058   }
1059 }
1060 
1061 
1062 void InterpreterMacroAssembler::update_mdp_by_offset(Register mdp_in,
1063                                                      int offset_of_disp) {
1064   assert(ProfileInterpreter, "must be profiling interpreter");
1065   ld(t1, Address(mdp_in, offset_of_disp));
1066   add(mdp_in, mdp_in, t1);
1067   sd(mdp_in, Address(fp, frame::interpreter_frame_mdp_offset * wordSize));
1068 }
1069 
1070 void InterpreterMacroAssembler::update_mdp_by_offset(Register mdp_in,
1071                                                      Register reg,
1072                                                      int offset_of_disp) {
1073   assert(ProfileInterpreter, "must be profiling interpreter");
1074   add(t1, mdp_in, reg);
1075   ld(t1, Address(t1, offset_of_disp));
1076   add(mdp_in, mdp_in, t1);
1077   sd(mdp_in, Address(fp, frame::interpreter_frame_mdp_offset * wordSize));
1078 }
1079 
1080 
1081 void InterpreterMacroAssembler::update_mdp_by_constant(Register mdp_in,
1082                                                        int constant) {
1083   assert(ProfileInterpreter, "must be profiling interpreter");
1084   addi(mdp_in, mdp_in, (unsigned)constant);
1085   sd(mdp_in, Address(fp, frame::interpreter_frame_mdp_offset * wordSize));
1086 }
1087 
1088 
1089 void InterpreterMacroAssembler::update_mdp_for_ret(Register return_bci) {
1090   assert(ProfileInterpreter, "must be profiling interpreter");
1091 
1092   // save/restore across call_VM
1093   addi(sp, sp, -2 * wordSize);
1094   sd(zr, Address(sp, 0));
1095   sd(return_bci, Address(sp, wordSize));
1096   call_VM(noreg,
1097           CAST_FROM_FN_PTR(address, InterpreterRuntime::update_mdp_for_ret),
1098           return_bci);
1099   ld(zr, Address(sp, 0));
1100   ld(return_bci, Address(sp, wordSize));
1101   addi(sp, sp, 2 * wordSize);
1102 }
1103 
1104 void InterpreterMacroAssembler::profile_taken_branch(Register mdp,
1105                                                      Register bumped_count) {
1106   if (ProfileInterpreter) {
1107     Label profile_continue;
1108 
1109     // If no method data exists, go to profile_continue.
1110     // Otherwise, assign to mdp
1111     test_method_data_pointer(mdp, profile_continue);
1112 
1113     // We are taking a branch.  Increment the taken count.
1114     Address data(mdp, in_bytes(JumpData::taken_offset()));
1115     ld(bumped_count, data);
1116     assert(DataLayout::counter_increment == 1,
1117             "flow-free idiom only works with 1");
1118     addi(bumped_count, bumped_count, DataLayout::counter_increment);
1119     Label L;
1120     // eg: bumped_count=0x7fff ffff ffff ffff  + 1 < 0. so we use <= 0;
1121     blez(bumped_count, L);       // skip store if counter overflow,
1122     sd(bumped_count, data);
1123     bind(L);
1124     // The method data pointer needs to be updated to reflect the new target.
1125     update_mdp_by_offset(mdp, in_bytes(JumpData::displacement_offset()));
1126     bind(profile_continue);
1127   }
1128 }
1129 
1130 void InterpreterMacroAssembler::profile_not_taken_branch(Register mdp) {
1131   if (ProfileInterpreter) {
1132     Label profile_continue;
1133 
1134     // If no method data exists, go to profile_continue.
1135     test_method_data_pointer(mdp, profile_continue);
1136 
1137     // We are taking a branch.  Increment the not taken count.
1138     increment_mdp_data_at(mdp, in_bytes(BranchData::not_taken_offset()));
1139 
1140     // The method data pointer needs to be updated to correspond to
1141     // the next bytecode
1142     update_mdp_by_constant(mdp, in_bytes(BranchData::branch_data_size()));
1143     bind(profile_continue);
1144   }
1145 }
1146 
1147 void InterpreterMacroAssembler::profile_call(Register mdp) {
1148   if (ProfileInterpreter) {
1149     Label profile_continue;
1150 
1151     // If no method data exists, go to profile_continue.
1152     test_method_data_pointer(mdp, profile_continue);
1153 
1154     // We are making a call.  Increment the count.
1155     increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1156 
1157     // The method data pointer needs to be updated to reflect the new target.
1158     update_mdp_by_constant(mdp, in_bytes(CounterData::counter_data_size()));
1159     bind(profile_continue);
1160   }
1161 }
1162 
1163 void InterpreterMacroAssembler::profile_final_call(Register mdp) {
1164   if (ProfileInterpreter) {
1165     Label profile_continue;
1166 
1167     // If no method data exists, go to profile_continue.
1168     test_method_data_pointer(mdp, profile_continue);
1169 
1170     // We are making a call.  Increment the count.
1171     increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1172 
1173     // The method data pointer needs to be updated to reflect the new target.
1174     update_mdp_by_constant(mdp,
1175                            in_bytes(VirtualCallData::
1176                                     virtual_call_data_size()));
1177     bind(profile_continue);
1178   }
1179 }
1180 
1181 
1182 void InterpreterMacroAssembler::profile_virtual_call(Register receiver,
1183                                                      Register mdp,
1184                                                      Register reg2,
1185                                                      bool receiver_can_be_null) {
1186   if (ProfileInterpreter) {
1187     Label profile_continue;
1188 
1189     // If no method data exists, go to profile_continue.
1190     test_method_data_pointer(mdp, profile_continue);
1191 
1192     Label skip_receiver_profile;
1193     if (receiver_can_be_null) {
1194       Label not_null;
1195       // We are making a call.  Increment the count for null receiver.
1196       increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1197       j(skip_receiver_profile);
1198       bind(not_null);
1199     }
1200 
1201     // Record the receiver type.
1202     record_klass_in_profile(receiver, mdp, reg2, true);
1203     bind(skip_receiver_profile);
1204 
1205     // The method data pointer needs to be updated to reflect the new target.
1206 
1207     update_mdp_by_constant(mdp,
1208                            in_bytes(VirtualCallData::
1209                                     virtual_call_data_size()));
1210     bind(profile_continue);
1211   }
1212 }
1213 
1214 // This routine creates a state machine for updating the multi-row
1215 // type profile at a virtual call site (or other type-sensitive bytecode).
1216 // The machine visits each row (of receiver/count) until the receiver type
1217 // is found, or until it runs out of rows.  At the same time, it remembers
1218 // the location of the first empty row.  (An empty row records null for its
1219 // receiver, and can be allocated for a newly-observed receiver type.)
1220 // Because there are two degrees of freedom in the state, a simple linear
1221 // search will not work; it must be a decision tree.  Hence this helper
1222 // function is recursive, to generate the required tree structured code.
1223 // It's the interpreter, so we are trading off code space for speed.
1224 // See below for example code.
1225 void InterpreterMacroAssembler::record_klass_in_profile_helper(
1226                                 Register receiver, Register mdp,
1227                                 Register reg2,
1228                                 Label& done, bool is_virtual_call) {
1229   if (TypeProfileWidth == 0) {
1230     if (is_virtual_call) {
1231       increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1232     }
1233 
1234   } else {
1235     int non_profiled_offset = -1;
1236     if (is_virtual_call) {
1237       non_profiled_offset = in_bytes(CounterData::count_offset());
1238     }
1239 
1240     record_item_in_profile_helper(receiver, mdp, reg2, 0, done, TypeProfileWidth,
1241       &VirtualCallData::receiver_offset, &VirtualCallData::receiver_count_offset, non_profiled_offset);
1242   }
1243 }
1244 
1245 void InterpreterMacroAssembler::record_item_in_profile_helper(
1246   Register item, Register mdp, Register reg2, int start_row, Label& done, int total_rows,
1247   OffsetFunction item_offset_fn, OffsetFunction item_count_offset_fn, int non_profiled_offset) {
1248   int last_row = total_rows - 1;
1249   assert(start_row <= last_row, "must be work left to do");
1250   // Test this row for both the item and for null.
1251   // Take any of three different outcomes:
1252   //   1. found item => increment count and goto done
1253   //   2. found null => keep looking for case 1, maybe allocate this cell
1254   //   3. found something else => keep looking for cases 1 and 2
1255   // Case 3 is handled by a recursive call.
1256   for (int row = start_row; row <= last_row; row++) {
1257     Label next_test;
1258     bool test_for_null_also = (row == start_row);
1259 
1260     // See if the item is item[n].
1261     int item_offset = in_bytes(item_offset_fn(row));
1262     test_mdp_data_at(mdp, item_offset, item,
1263                      (test_for_null_also ? reg2 : noreg),
1264                      next_test);
1265     // (Reg2 now contains the item from the CallData.)
1266 
1267     // The item is item[n].  Increment count[n].
1268     int count_offset = in_bytes(item_count_offset_fn(row));
1269     increment_mdp_data_at(mdp, count_offset);
1270     j(done);
1271     bind(next_test);
1272 
1273     if (test_for_null_also) {
1274       Label found_null;
1275       // Failed the equality check on item[n]...  Test for null.
1276       if (start_row == last_row) {
1277         // The only thing left to do is handle the null case.
1278         if (non_profiled_offset >= 0) {
1279           beqz(reg2, found_null);
1280           // Item did not match any saved item and there is no empty row for it.
1281           // Increment total counter to indicate polymorphic case.
1282           increment_mdp_data_at(mdp, non_profiled_offset);
1283           j(done);
1284           bind(found_null);
1285         } else {
1286           bnez(reg2, done);
1287         }
1288         break;
1289       }
1290       // Since null is rare, make it be the branch-taken case.
1291       beqz(reg2, found_null);
1292 
1293       // Put all the "Case 3" tests here.
1294       record_item_in_profile_helper(item, mdp, reg2, start_row + 1, done, total_rows,
1295         item_offset_fn, item_count_offset_fn, non_profiled_offset);
1296 
1297       // Found a null.  Keep searching for a matching item,
1298       // but remember that this is an empty (unused) slot.
1299       bind(found_null);
1300     }
1301   }
1302 
1303   // In the fall-through case, we found no matching item, but we
1304   // observed the item[start_row] is NULL.
1305   // Fill in the item field and increment the count.
1306   int item_offset = in_bytes(item_offset_fn(start_row));
1307   set_mdp_data_at(mdp, item_offset, item);
1308   int count_offset = in_bytes(item_count_offset_fn(start_row));
1309   mv(reg2, DataLayout::counter_increment);
1310   set_mdp_data_at(mdp, count_offset, reg2);
1311   if (start_row > 0) {
1312     j(done);
1313   }
1314 }
1315 
1316 // Example state machine code for three profile rows:
1317 //   # main copy of decision tree, rooted at row[1]
1318 //   if (row[0].rec == rec) then [
1319 //     row[0].incr()
1320 //     goto done
1321 //   ]
1322 //   if (row[0].rec != NULL) then [
1323 //     # inner copy of decision tree, rooted at row[1]
1324 //     if (row[1].rec == rec) then [
1325 //       row[1].incr()
1326 //       goto done
1327 //     ]
1328 //     if (row[1].rec != NULL) then [
1329 //       # degenerate decision tree, rooted at row[2]
1330 //       if (row[2].rec == rec) then [
1331 //         row[2].incr()
1332 //         goto done
1333 //       ]
1334 //       if (row[2].rec != NULL) then [
1335 //         count.incr()
1336 //         goto done
1337 //       ] # overflow
1338 //       row[2].init(rec)
1339 //       goto done
1340 //     ] else [
1341 //       # remember row[1] is empty
1342 //       if (row[2].rec == rec) then [
1343 //         row[2].incr()
1344 //         goto done
1345 //       ]
1346 //       row[1].init(rec)
1347 //       goto done
1348 //     ]
1349 //   else [
1350 //     # remember row[0] is empty
1351 //     if (row[1].rec == rec) then [
1352 //       row[1].incr()
1353 //       goto done
1354 //     ]
1355 //     if (row[2].rec == rec) then [
1356 //       row[2].incr()
1357 //       goto done
1358 //     ]
1359 //     row[0].init(rec)
1360 //     goto done
1361 //   ]
1362 //   done:
1363 
1364 void InterpreterMacroAssembler::record_klass_in_profile(Register receiver,
1365                                                         Register mdp, Register reg2,
1366                                                         bool is_virtual_call) {
1367   assert(ProfileInterpreter, "must be profiling");
1368   Label done;
1369 
1370   record_klass_in_profile_helper(receiver, mdp, reg2, done, is_virtual_call);
1371 
1372   bind(done);
1373 }
1374 
1375 void InterpreterMacroAssembler::profile_ret(Register return_bci, Register mdp) {
1376   if (ProfileInterpreter) {
1377     Label profile_continue;
1378 
1379     // If no method data exists, go to profile_continue.
1380     test_method_data_pointer(mdp, profile_continue);
1381 
1382     // Update the total ret count.
1383     increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1384 
1385     for (uint row = 0; row < RetData::row_limit(); row++) {
1386       Label next_test;
1387 
1388       // See if return_bci is equal to bci[n]:
1389       test_mdp_data_at(mdp,
1390                        in_bytes(RetData::bci_offset(row)),
1391                        return_bci, noreg,
1392                        next_test);
1393 
1394       // return_bci is equal to bci[n].  Increment the count.
1395       increment_mdp_data_at(mdp, in_bytes(RetData::bci_count_offset(row)));
1396 
1397       // The method data pointer needs to be updated to reflect the new target.
1398       update_mdp_by_offset(mdp,
1399                            in_bytes(RetData::bci_displacement_offset(row)));
1400       j(profile_continue);
1401       bind(next_test);
1402     }
1403 
1404     update_mdp_for_ret(return_bci);
1405 
1406     bind(profile_continue);
1407   }
1408 }
1409 
1410 void InterpreterMacroAssembler::profile_null_seen(Register mdp) {
1411   if (ProfileInterpreter) {
1412     Label profile_continue;
1413 
1414     // If no method data exists, go to profile_continue.
1415     test_method_data_pointer(mdp, profile_continue);
1416 
1417     set_mdp_flag_at(mdp, BitData::null_seen_byte_constant());
1418 
1419     // The method data pointer needs to be updated.
1420     int mdp_delta = in_bytes(BitData::bit_data_size());
1421     if (TypeProfileCasts) {
1422       mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size());
1423     }
1424     update_mdp_by_constant(mdp, mdp_delta);
1425 
1426     bind(profile_continue);
1427   }
1428 }
1429 
1430 void InterpreterMacroAssembler::profile_typecheck_failed(Register mdp) {
1431     if (ProfileInterpreter && TypeProfileCasts) {
1432     Label profile_continue;
1433 
1434     // If no method data exists, go to profile_continue.
1435     test_method_data_pointer(mdp, profile_continue);
1436 
1437     int count_offset = in_bytes(CounterData::count_offset());
1438     // Back up the address, since we have already bumped the mdp.
1439     count_offset -= in_bytes(VirtualCallData::virtual_call_data_size());
1440 
1441     // *Decrement* the counter.  We expect to see zero or small negatives.
1442     increment_mdp_data_at(mdp, count_offset, true);
1443 
1444     bind (profile_continue);
1445   }
1446 }
1447 
1448 void InterpreterMacroAssembler::profile_typecheck(Register mdp, Register klass, Register reg2) {
1449   if (ProfileInterpreter) {
1450     Label profile_continue;
1451 
1452     // If no method data exists, go to profile_continue.
1453     test_method_data_pointer(mdp, profile_continue);
1454 
1455     // The method data pointer needs to be updated.
1456     int mdp_delta = in_bytes(BitData::bit_data_size());
1457     if (TypeProfileCasts) {
1458       mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size());
1459 
1460       // Record the object type.
1461       record_klass_in_profile(klass, mdp, reg2, false);
1462     }
1463     update_mdp_by_constant(mdp, mdp_delta);
1464 
1465     bind(profile_continue);
1466   }
1467 }
1468 
1469 void InterpreterMacroAssembler::profile_switch_default(Register mdp) {
1470   if (ProfileInterpreter) {
1471     Label profile_continue;
1472 
1473     // If no method data exists, go to profile_continue.
1474     test_method_data_pointer(mdp, profile_continue);
1475 
1476     // Update the default case count
1477     increment_mdp_data_at(mdp,
1478                           in_bytes(MultiBranchData::default_count_offset()));
1479 
1480     // The method data pointer needs to be updated.
1481     update_mdp_by_offset(mdp,
1482                          in_bytes(MultiBranchData::
1483                                   default_displacement_offset()));
1484 
1485     bind(profile_continue);
1486   }
1487 }
1488 
1489 void InterpreterMacroAssembler::profile_switch_case(Register index,
1490                                                     Register mdp,
1491                                                     Register reg2) {
1492   if (ProfileInterpreter) {
1493     Label profile_continue;
1494 
1495     // If no method data exists, go to profile_continue.
1496     test_method_data_pointer(mdp, profile_continue);
1497 
1498     // Build the base (index * per_case_size_in_bytes()) +
1499     // case_array_offset_in_bytes()
1500     mv(reg2, in_bytes(MultiBranchData::per_case_size()));
1501     mv(t0, in_bytes(MultiBranchData::case_array_offset()));
1502     Assembler::mul(index, index, reg2);
1503     Assembler::add(index, index, t0);
1504 
1505     // Update the case count
1506     increment_mdp_data_at(mdp,
1507                           index,
1508                           in_bytes(MultiBranchData::relative_count_offset()));
1509 
1510     // The method data pointer need to be updated.
1511     update_mdp_by_offset(mdp,
1512                          index,
1513                          in_bytes(MultiBranchData::
1514                                   relative_displacement_offset()));
1515 
1516     bind(profile_continue);
1517   }
1518 }
1519 
1520 void InterpreterMacroAssembler::verify_FPU(int stack_depth, TosState state) { ; }
1521 
1522 void InterpreterMacroAssembler::notify_method_entry() {
1523   // Whenever JVMTI is interp_only_mode, method entry/exit events are sent to
1524   // track stack depth.  If it is possible to enter interp_only_mode we add
1525   // the code to check if the event should be sent.
1526   if (JvmtiExport::can_post_interpreter_events()) {
1527     Label L;
1528     lwu(x13, Address(xthread, JavaThread::interp_only_mode_offset()));
1529     beqz(x13, L);
1530     call_VM(noreg, CAST_FROM_FN_PTR(address,
1531                                     InterpreterRuntime::post_method_entry));
1532     bind(L);
1533   }
1534 
1535   {
1536     SkipIfEqual skip(this, &DTraceMethodProbes, false);
1537     get_method(c_rarg1);
1538     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
1539                  xthread, c_rarg1);
1540   }
1541 
1542   // RedefineClasses() tracing support for obsolete method entry
1543   if (log_is_enabled(Trace, redefine, class, obsolete)) {
1544     get_method(c_rarg1);
1545     call_VM_leaf(
1546       CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
1547       xthread, c_rarg1);
1548   }
1549 }
1550 
1551 
1552 void InterpreterMacroAssembler::notify_method_exit(
1553     TosState state, NotifyMethodExitMode mode) {
1554   // Whenever JVMTI is interp_only_mode, method entry/exit events are sent to
1555   // track stack depth.  If it is possible to enter interp_only_mode we add
1556   // the code to check if the event should be sent.
1557   if (mode == NotifyJVMTI && JvmtiExport::can_post_interpreter_events()) {
1558     Label L;
1559     // Note: frame::interpreter_frame_result has a dependency on how the
1560     // method result is saved across the call to post_method_exit. If this
1561     // is changed then the interpreter_frame_result implementation will
1562     // need to be updated too.
1563 
1564     // template interpreter will leave the result on the top of the stack.
1565     push(state);
1566     lwu(x13, Address(xthread, JavaThread::interp_only_mode_offset()));
1567     beqz(x13, L);
1568     call_VM(noreg,
1569             CAST_FROM_FN_PTR(address, InterpreterRuntime::post_method_exit));
1570     bind(L);
1571     pop(state);
1572   }
1573 
1574   {
1575     SkipIfEqual skip(this, &DTraceMethodProbes, false);
1576     push(state);
1577     get_method(c_rarg1);
1578     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
1579                  xthread, c_rarg1);
1580     pop(state);
1581   }
1582 }
1583 
1584 
1585 // Jump if ((*counter_addr += increment) & mask) satisfies the condition.
1586 void InterpreterMacroAssembler::increment_mask_and_jump(Address counter_addr,
1587                                                         int increment, Address mask,
1588                                                         Register tmp1, Register tmp2,
1589                                                         bool preloaded, Label* where) {
1590   Label done;
1591   if (!preloaded) {
1592     lwu(tmp1, counter_addr);
1593   }
1594   add(tmp1, tmp1, increment);
1595   sw(tmp1, counter_addr);
1596   lwu(tmp2, mask);
1597   andr(tmp1, tmp1, tmp2);
1598   bnez(tmp1, done);
1599   j(*where); // offset is too large so we have to use j instead of beqz here
1600   bind(done);
1601 }
1602 
1603 void InterpreterMacroAssembler::call_VM_leaf_base(address entry_point,
1604                                                   int number_of_arguments) {
1605   // interpreter specific
1606   //
1607   // Note: No need to save/restore rbcp & rlocals pointer since these
1608   //       are callee saved registers and no blocking/ GC can happen
1609   //       in leaf calls.
1610 #ifdef ASSERT
1611   {
1612    Label L;
1613    ld(t0, Address(fp, frame::interpreter_frame_last_sp_offset * wordSize));
1614    beqz(t0, L);
1615    stop("InterpreterMacroAssembler::call_VM_leaf_base:"
1616         " last_sp != NULL");
1617    bind(L);
1618   }
1619 #endif /* ASSERT */
1620   // super call
1621   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
1622 }
1623 
1624 void InterpreterMacroAssembler::call_VM_base(Register oop_result,
1625                                              Register java_thread,
1626                                              Register last_java_sp,
1627                                              address  entry_point,
1628                                              int      number_of_arguments,
1629                                              bool     check_exceptions) {
1630   // interpreter specific
1631   //
1632   // Note: Could avoid restoring locals ptr (callee saved) - however doesn't
1633   //       really make a difference for these runtime calls, since they are
1634   //       slow anyway. Btw., bcp must be saved/restored since it may change
1635   //       due to GC.
1636   save_bcp();
1637 #ifdef ASSERT
1638   {
1639     Label L;
1640     ld(t0, Address(fp, frame::interpreter_frame_last_sp_offset * wordSize));
1641     beqz(t0, L);
1642     stop("InterpreterMacroAssembler::call_VM_base:"
1643          " last_sp != NULL");
1644     bind(L);
1645   }
1646 #endif /* ASSERT */
1647   // super call
1648   MacroAssembler::call_VM_base(oop_result, noreg, last_java_sp,
1649                                entry_point, number_of_arguments,
1650                                check_exceptions);
1651 // interpreter specific
1652   restore_bcp();
1653   restore_locals();
1654 }
1655 
1656 void InterpreterMacroAssembler::profile_obj_type(Register obj, const Address& mdo_addr, Register tmp) {
1657   assert_different_registers(obj, tmp, t0, mdo_addr.base());
1658   Label update, next, none;
1659 
1660   verify_oop(obj);
1661 
1662   bnez(obj, update);
1663   orptr(mdo_addr, TypeEntries::null_seen, t0, tmp);
1664   j(next);
1665 
1666   bind(update);
1667   load_klass(obj, obj);
1668 
1669   ld(t0, mdo_addr);
1670   xorr(obj, obj, t0);
1671   andi(t0, obj, TypeEntries::type_klass_mask);
1672   beqz(t0, next); // klass seen before, nothing to
1673                   // do. The unknown bit may have been
1674                   // set already but no need to check.
1675 
1676   andi(t0, obj, TypeEntries::type_unknown);
1677   bnez(t0, next);
1678   // already unknown. Nothing to do anymore.
1679 
1680   ld(t0, mdo_addr);
1681   beqz(t0, none);
1682   mv(tmp, (u1)TypeEntries::null_seen);
1683   beq(t0, tmp, none);
1684   // There is a chance that the checks above (re-reading profiling
1685   // data from memory) fail if another thread has just set the
1686   // profiling to this obj's klass
1687   ld(t0, mdo_addr);
1688   xorr(obj, obj, t0);
1689   andi(t0, obj, TypeEntries::type_klass_mask);
1690   beqz(t0, next);
1691 
1692   // different than before. Cannot keep accurate profile.
1693   orptr(mdo_addr, TypeEntries::type_unknown, t0, tmp);
1694   j(next);
1695 
1696   bind(none);
1697   // first time here. Set profile type.
1698   sd(obj, mdo_addr);
1699 
1700   bind(next);
1701 }
1702 
1703 void InterpreterMacroAssembler::profile_arguments_type(Register mdp, Register callee, Register tmp, bool is_virtual) {
1704   if (!ProfileInterpreter) {
1705     return;
1706   }
1707 
1708   if (MethodData::profile_arguments() || MethodData::profile_return()) {
1709     Label profile_continue;
1710 
1711     test_method_data_pointer(mdp, profile_continue);
1712 
1713     int off_to_start = is_virtual ? in_bytes(VirtualCallData::virtual_call_data_size()) : in_bytes(CounterData::counter_data_size());
1714 
1715     lbu(t0, Address(mdp, in_bytes(DataLayout::tag_offset()) - off_to_start));
1716     if (is_virtual) {
1717       mv(tmp, (u1)DataLayout::virtual_call_type_data_tag);
1718       bne(t0, tmp, profile_continue);
1719     } else {
1720       mv(tmp, (u1)DataLayout::call_type_data_tag);
1721       bne(t0, tmp, profile_continue);
1722     }
1723 
1724     // calculate slot step
1725     static int stack_slot_offset0 = in_bytes(TypeEntriesAtCall::stack_slot_offset(0));
1726     static int slot_step = in_bytes(TypeEntriesAtCall::stack_slot_offset(1)) - stack_slot_offset0;
1727 
1728     // calculate type step
1729     static int argument_type_offset0 = in_bytes(TypeEntriesAtCall::argument_type_offset(0));
1730     static int type_step = in_bytes(TypeEntriesAtCall::argument_type_offset(1)) - argument_type_offset0;
1731 
1732     if (MethodData::profile_arguments()) {
1733       Label done, loop, loopEnd, profileArgument, profileReturnType;
1734       RegSet pushed_registers;
1735       pushed_registers += x15;
1736       pushed_registers += x16;
1737       pushed_registers += x17;
1738       Register mdo_addr = x15;
1739       Register index = x16;
1740       Register off_to_args = x17;
1741       push_reg(pushed_registers, sp);
1742 
1743       mv(off_to_args, in_bytes(TypeEntriesAtCall::args_data_offset()));
1744       mv(t0, TypeProfileArgsLimit);
1745       beqz(t0, loopEnd);
1746 
1747       mv(index, zr); // index < TypeProfileArgsLimit
1748       bind(loop);
1749       bgtz(index, profileReturnType);
1750       mv(t0, (int)MethodData::profile_return());
1751       beqz(t0, profileArgument); // (index > 0 || MethodData::profile_return()) == false
1752       bind(profileReturnType);
1753       // If return value type is profiled we may have no argument to profile
1754       ld(tmp, Address(mdp, in_bytes(TypeEntriesAtCall::cell_count_offset())));
1755       mv(t1, - TypeStackSlotEntries::per_arg_count());
1756       mul(t1, index, t1);
1757       add(tmp, tmp, t1);
1758       mv(t1, TypeStackSlotEntries::per_arg_count());
1759       add(t0, mdp, off_to_args);
1760       blt(tmp, t1, done);
1761 
1762       bind(profileArgument);
1763 
1764       ld(tmp, Address(callee, Method::const_offset()));
1765       load_unsigned_short(tmp, Address(tmp, ConstMethod::size_of_parameters_offset()));
1766       // stack offset o (zero based) from the start of the argument
1767       // list, for n arguments translates into offset n - o - 1 from
1768       // the end of the argument list
1769       mv(t0, stack_slot_offset0);
1770       mv(t1, slot_step);
1771       mul(t1, index, t1);
1772       add(t0, t0, t1);
1773       add(t0, mdp, t0);
1774       ld(t0, Address(t0));
1775       sub(tmp, tmp, t0);
1776       addi(tmp, tmp, -1);
1777       Address arg_addr = argument_address(tmp);
1778       ld(tmp, arg_addr);
1779 
1780       mv(t0, argument_type_offset0);
1781       mv(t1, type_step);
1782       mul(t1, index, t1);
1783       add(t0, t0, t1);
1784       add(mdo_addr, mdp, t0);
1785       Address mdo_arg_addr(mdo_addr, 0);
1786       profile_obj_type(tmp, mdo_arg_addr, t1);
1787 
1788       int to_add = in_bytes(TypeStackSlotEntries::per_arg_size());
1789       addi(off_to_args, off_to_args, to_add);
1790 
1791       // increment index by 1
1792       addi(index, index, 1);
1793       mv(t1, TypeProfileArgsLimit);
1794       blt(index, t1, loop);
1795       bind(loopEnd);
1796 
1797       if (MethodData::profile_return()) {
1798         ld(tmp, Address(mdp, in_bytes(TypeEntriesAtCall::cell_count_offset())));
1799         addi(tmp, tmp, -TypeProfileArgsLimit*TypeStackSlotEntries::per_arg_count());
1800       }
1801 
1802       add(t0, mdp, off_to_args);
1803       bind(done);
1804       mv(mdp, t0);
1805 
1806       // unspill the clobbered registers
1807       pop_reg(pushed_registers, sp);
1808 
1809       if (MethodData::profile_return()) {
1810         // We're right after the type profile for the last
1811         // argument. tmp is the number of cells left in the
1812         // CallTypeData/VirtualCallTypeData to reach its end. Non null
1813         // if there's a return to profile.
1814         assert(ReturnTypeEntry::static_cell_count() < TypeStackSlotEntries::per_arg_count(), "can't move past ret type");
1815         shadd(mdp, tmp, mdp, tmp, exact_log2(DataLayout::cell_size));
1816       }
1817       sd(mdp, Address(fp, frame::interpreter_frame_mdp_offset * wordSize));
1818     } else {
1819       assert(MethodData::profile_return(), "either profile call args or call ret");
1820       update_mdp_by_constant(mdp, in_bytes(TypeEntriesAtCall::return_only_size()));
1821     }
1822 
1823     // mdp points right after the end of the
1824     // CallTypeData/VirtualCallTypeData, right after the cells for the
1825     // return value type if there's one
1826 
1827     bind(profile_continue);
1828   }
1829 }
1830 
1831 void InterpreterMacroAssembler::profile_return_type(Register mdp, Register ret, Register tmp) {
1832   assert_different_registers(mdp, ret, tmp, xbcp, t0, t1);
1833   if (ProfileInterpreter && MethodData::profile_return()) {
1834     Label profile_continue, done;
1835 
1836     test_method_data_pointer(mdp, profile_continue);
1837 
1838     if (MethodData::profile_return_jsr292_only()) {
1839       assert(Method::intrinsic_id_size_in_bytes() == 2, "assuming Method::_intrinsic_id is u2");
1840 
1841       // If we don't profile all invoke bytecodes we must make sure
1842       // it's a bytecode we indeed profile. We can't go back to the
1843       // beginning of the ProfileData we intend to update to check its
1844       // type because we're right after it and we don't known its
1845       // length
1846       Label do_profile;
1847       lbu(t0, Address(xbcp, 0));
1848       mv(tmp, (u1)Bytecodes::_invokedynamic);
1849       beq(t0, tmp, do_profile);
1850       mv(tmp, (u1)Bytecodes::_invokehandle);
1851       beq(t0, tmp, do_profile);
1852       get_method(tmp);
1853       lhu(t0, Address(tmp, Method::intrinsic_id_offset_in_bytes()));
1854       mv(t1, static_cast<int>(vmIntrinsics::_compiledLambdaForm));
1855       bne(t0, t1, profile_continue);
1856       bind(do_profile);
1857     }
1858 
1859     Address mdo_ret_addr(mdp, -in_bytes(ReturnTypeEntry::size()));
1860     mv(tmp, ret);
1861     profile_obj_type(tmp, mdo_ret_addr, t1);
1862 
1863     bind(profile_continue);
1864   }
1865 }
1866 
1867 void InterpreterMacroAssembler::profile_parameters_type(Register mdp, Register tmp1, Register tmp2, Register tmp3) {
1868   assert_different_registers(t0, t1, mdp, tmp1, tmp2, tmp3);
1869   if (ProfileInterpreter && MethodData::profile_parameters()) {
1870     Label profile_continue, done;
1871 
1872     test_method_data_pointer(mdp, profile_continue);
1873 
1874     // Load the offset of the area within the MDO used for
1875     // parameters. If it's negative we're not profiling any parameters
1876     lwu(tmp1, Address(mdp, in_bytes(MethodData::parameters_type_data_di_offset()) - in_bytes(MethodData::data_offset())));
1877     srli(tmp2, tmp1, 31);
1878     bnez(tmp2, profile_continue);  // i.e. sign bit set
1879 
1880     // Compute a pointer to the area for parameters from the offset
1881     // and move the pointer to the slot for the last
1882     // parameters. Collect profiling from last parameter down.
1883     // mdo start + parameters offset + array length - 1
1884     add(mdp, mdp, tmp1);
1885     ld(tmp1, Address(mdp, ArrayData::array_len_offset()));
1886     add(tmp1, tmp1, - TypeStackSlotEntries::per_arg_count());
1887 
1888     Label loop;
1889     bind(loop);
1890 
1891     int off_base = in_bytes(ParametersTypeData::stack_slot_offset(0));
1892     int type_base = in_bytes(ParametersTypeData::type_offset(0));
1893     int per_arg_scale = exact_log2(DataLayout::cell_size);
1894     add(t0, mdp, off_base);
1895     add(t1, mdp, type_base);
1896 
1897     shadd(tmp2, tmp1, t0, tmp2, per_arg_scale);
1898     // load offset on the stack from the slot for this parameter
1899     ld(tmp2, Address(tmp2, 0));
1900     neg(tmp2, tmp2);
1901 
1902     // read the parameter from the local area
1903     shadd(tmp2, tmp2, xlocals, tmp2, Interpreter::logStackElementSize);
1904     ld(tmp2, Address(tmp2, 0));
1905 
1906     // profile the parameter
1907     shadd(t1, tmp1, t1, t0, per_arg_scale);
1908     Address arg_type(t1, 0);
1909     profile_obj_type(tmp2, arg_type, tmp3);
1910 
1911     // go to next parameter
1912     add(tmp1, tmp1, - TypeStackSlotEntries::per_arg_count());
1913     bgez(tmp1, loop);
1914 
1915     bind(profile_continue);
1916   }
1917 }
1918 
1919 void InterpreterMacroAssembler::get_method_counters(Register method,
1920                                                     Register mcs, Label& skip) {
1921   Label has_counters;
1922   ld(mcs, Address(method, Method::method_counters_offset()));
1923   bnez(mcs, has_counters);
1924   call_VM(noreg, CAST_FROM_FN_PTR(address,
1925           InterpreterRuntime::build_method_counters), method);
1926   ld(mcs, Address(method, Method::method_counters_offset()));
1927   beqz(mcs, skip); // No MethodCounters allocated, OutOfMemory
1928   bind(has_counters);
1929 }
1930 
1931 #ifdef ASSERT
1932 void InterpreterMacroAssembler::verify_access_flags(Register access_flags, uint32_t flag_bits,
1933                                                     const char* msg, bool stop_by_hit) {
1934   Label L;
1935   andi(t0, access_flags, flag_bits);
1936   if (stop_by_hit) {
1937     beqz(t0, L);
1938   } else {
1939     bnez(t0, L);
1940   }
1941   stop(msg);
1942   bind(L);
1943 }
1944 
1945 void InterpreterMacroAssembler::verify_frame_setup() {
1946   Label L;
1947   const Address monitor_block_top(fp, frame::interpreter_frame_monitor_block_top_offset * wordSize);
1948   ld(t0, monitor_block_top);
1949   beq(esp, t0, L);
1950   stop("broken stack frame setup in interpreter");
1951   bind(L);
1952 }
1953 #endif