1 /*
   2  * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2012, 2025 SAP SE. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 
  27 #include "asm/macroAssembler.inline.hpp"
  28 #include "gc/shared/barrierSet.hpp"
  29 #include "gc/shared/barrierSetAssembler.hpp"
  30 #include "interp_masm_ppc.hpp"
  31 #include "interpreter/interpreterRuntime.hpp"
  32 #include "oops/methodCounters.hpp"
  33 #include "oops/methodData.hpp"
  34 #include "oops/resolvedFieldEntry.hpp"
  35 #include "oops/resolvedIndyEntry.hpp"
  36 #include "oops/resolvedMethodEntry.hpp"
  37 #include "prims/jvmtiExport.hpp"
  38 #include "prims/jvmtiThreadState.hpp"
  39 #include "runtime/frame.inline.hpp"
  40 #include "runtime/safepointMechanism.hpp"
  41 #include "runtime/sharedRuntime.hpp"
  42 #include "runtime/vm_version.hpp"
  43 #include "utilities/macros.hpp"
  44 #include "utilities/powerOfTwo.hpp"
  45 
  46 // Implementation of InterpreterMacroAssembler.
  47 
  48 // This file specializes the assembler with interpreter-specific macros.
  49 
  50 #ifdef PRODUCT
  51 #define BLOCK_COMMENT(str) // nothing
  52 #else
  53 #define BLOCK_COMMENT(str) block_comment(str)
  54 #endif
  55 
  56 void InterpreterMacroAssembler::null_check_throw(Register a, int offset, Register temp_reg) {
  57   address exception_entry = Interpreter::throw_NullPointerException_entry();
  58   MacroAssembler::null_check_throw(a, offset, temp_reg, exception_entry);
  59 }
  60 
  61 void InterpreterMacroAssembler::load_klass_check_null_throw(Register dst, Register src, Register temp_reg) {
  62   null_check_throw(src, oopDesc::klass_offset_in_bytes(), temp_reg);
  63   load_klass(dst, src);
  64 }
  65 
  66 void InterpreterMacroAssembler::jump_to_entry(address entry, Register Rscratch) {
  67   assert(entry, "Entry must have been generated by now");
  68   if (is_within_range_of_b(entry, pc())) {
  69     b(entry);
  70   } else {
  71     load_const_optimized(Rscratch, entry, R0);
  72     mtctr(Rscratch);
  73     bctr();
  74   }
  75 }
  76 
  77 void InterpreterMacroAssembler::dispatch_next(TosState state, int bcp_incr, bool generate_poll) {
  78   Register bytecode = R12_scratch2;
  79   if (bcp_incr != 0) {
  80     lbzu(bytecode, bcp_incr, R14_bcp);
  81   } else {
  82     lbz(bytecode, 0, R14_bcp);
  83   }
  84 
  85   dispatch_Lbyte_code(state, bytecode, Interpreter::dispatch_table(state), generate_poll);
  86 }
  87 
  88 void InterpreterMacroAssembler::dispatch_via(TosState state, address* table) {
  89   // Load current bytecode.
  90   Register bytecode = R12_scratch2;
  91   lbz(bytecode, 0, R14_bcp);
  92   dispatch_Lbyte_code(state, bytecode, table);
  93 }
  94 
  95 // Dispatch code executed in the prolog of a bytecode which does not do it's
  96 // own dispatch. The dispatch address is computed and placed in R24_dispatch_addr.
  97 void InterpreterMacroAssembler::dispatch_prolog(TosState state, int bcp_incr) {
  98   Register bytecode = R12_scratch2;
  99   lbz(bytecode, bcp_incr, R14_bcp);
 100 
 101   load_dispatch_table(R24_dispatch_addr, Interpreter::dispatch_table(state));
 102 
 103   sldi(bytecode, bytecode, LogBytesPerWord);
 104   ldx(R24_dispatch_addr, R24_dispatch_addr, bytecode);
 105 }
 106 
 107 // Dispatch code executed in the epilog of a bytecode which does not do it's
 108 // own dispatch. The dispatch address in R24_dispatch_addr is used for the
 109 // dispatch.
 110 void InterpreterMacroAssembler::dispatch_epilog(TosState state, int bcp_incr) {
 111   if (bcp_incr) { addi(R14_bcp, R14_bcp, bcp_incr); }
 112   mtctr(R24_dispatch_addr);
 113   bcctr(bcondAlways, 0, bhintbhBCCTRisNotPredictable);
 114 }
 115 
 116 void InterpreterMacroAssembler::check_and_handle_popframe(Register scratch_reg) {
 117   assert(scratch_reg != R0, "can't use R0 as scratch_reg here");
 118   if (JvmtiExport::can_pop_frame()) {
 119     Label L;
 120 
 121     // Check the "pending popframe condition" flag in the current thread.
 122     lwz(scratch_reg, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
 123 
 124     // Initiate popframe handling only if it is not already being
 125     // processed. If the flag has the popframe_processing bit set, it
 126     // means that this code is called *during* popframe handling - we
 127     // don't want to reenter.
 128     andi_(R0, scratch_reg, JavaThread::popframe_pending_bit);
 129     beq(CR0, L);
 130 
 131     andi_(R0, scratch_reg, JavaThread::popframe_processing_bit);
 132     bne(CR0, L);
 133 
 134     // Call the Interpreter::remove_activation_preserving_args_entry()
 135     // func to get the address of the same-named entrypoint in the
 136     // generated interpreter code.
 137     call_c(CAST_FROM_FN_PTR(address, Interpreter::remove_activation_preserving_args_entry));
 138 
 139     // Jump to Interpreter::_remove_activation_preserving_args_entry.
 140     mtctr(R3_RET);
 141     bctr();
 142 
 143     align(32, 12);
 144     bind(L);
 145   }
 146 }
 147 
 148 void InterpreterMacroAssembler::check_and_handle_earlyret(Register scratch_reg) {
 149   const Register Rthr_state_addr = scratch_reg;
 150   if (JvmtiExport::can_force_early_return()) {
 151     Label Lno_early_ret;
 152     ld(Rthr_state_addr, in_bytes(JavaThread::jvmti_thread_state_offset()), R16_thread);
 153     cmpdi(CR0, Rthr_state_addr, 0);
 154     beq(CR0, Lno_early_ret);
 155 
 156     lwz(R0, in_bytes(JvmtiThreadState::earlyret_state_offset()), Rthr_state_addr);
 157     cmpwi(CR0, R0, JvmtiThreadState::earlyret_pending);
 158     bne(CR0, Lno_early_ret);
 159 
 160     // Jump to Interpreter::_earlyret_entry.
 161     lwz(R3_ARG1, in_bytes(JvmtiThreadState::earlyret_tos_offset()), Rthr_state_addr);
 162     call_VM_leaf(CAST_FROM_FN_PTR(address, Interpreter::remove_activation_early_entry));
 163     mtlr(R3_RET);
 164     blr();
 165 
 166     align(32, 12);
 167     bind(Lno_early_ret);
 168   }
 169 }
 170 
 171 void InterpreterMacroAssembler::load_earlyret_value(TosState state, Register Rscratch1) {
 172   const Register RjvmtiState = Rscratch1;
 173   const Register Rscratch2   = R0;
 174 
 175   ld(RjvmtiState, in_bytes(JavaThread::jvmti_thread_state_offset()), R16_thread);
 176   li(Rscratch2, 0);
 177 
 178   switch (state) {
 179     case atos: ld(R17_tos, in_bytes(JvmtiThreadState::earlyret_oop_offset()), RjvmtiState);
 180                std(Rscratch2, in_bytes(JvmtiThreadState::earlyret_oop_offset()), RjvmtiState);
 181                break;
 182     case ltos: ld(R17_tos, in_bytes(JvmtiThreadState::earlyret_value_offset()), RjvmtiState);
 183                break;
 184     case btos: // fall through
 185     case ztos: // fall through
 186     case ctos: // fall through
 187     case stos: // fall through
 188     case itos: lwz(R17_tos, in_bytes(JvmtiThreadState::earlyret_value_offset()), RjvmtiState);
 189                break;
 190     case ftos: lfs(F15_ftos, in_bytes(JvmtiThreadState::earlyret_value_offset()), RjvmtiState);
 191                break;
 192     case dtos: lfd(F15_ftos, in_bytes(JvmtiThreadState::earlyret_value_offset()), RjvmtiState);
 193                break;
 194     case vtos: break;
 195     default  : ShouldNotReachHere();
 196   }
 197 
 198   // Clean up tos value in the jvmti thread state.
 199   std(Rscratch2, in_bytes(JvmtiThreadState::earlyret_value_offset()), RjvmtiState);
 200   // Set tos state field to illegal value.
 201   li(Rscratch2, ilgl);
 202   stw(Rscratch2, in_bytes(JvmtiThreadState::earlyret_tos_offset()), RjvmtiState);
 203 }
 204 
 205 // Common code to dispatch and dispatch_only.
 206 // Dispatch value in Lbyte_code and increment Lbcp.
 207 
 208 void InterpreterMacroAssembler::load_dispatch_table(Register dst, address* table) {
 209   address table_base = (address)Interpreter::dispatch_table((TosState)0);
 210   intptr_t table_offs = (intptr_t)table - (intptr_t)table_base;
 211   if (is_simm16(table_offs)) {
 212     addi(dst, R25_templateTableBase, (int)table_offs);
 213   } else {
 214     load_const_optimized(dst, table, R0);
 215   }
 216 }
 217 
 218 void InterpreterMacroAssembler::dispatch_Lbyte_code(TosState state, Register bytecode,
 219                                                     address* table, bool generate_poll) {
 220   assert_different_registers(bytecode, R11_scratch1);
 221 
 222   // Calc dispatch table address.
 223   load_dispatch_table(R11_scratch1, table);
 224 
 225   if (generate_poll) {
 226     address *sfpt_tbl = Interpreter::safept_table(state);
 227     if (table != sfpt_tbl) {
 228       Label dispatch;
 229       ld(R0, in_bytes(JavaThread::polling_word_offset()), R16_thread);
 230       // Armed page has poll_bit set, if poll bit is cleared just continue.
 231       andi_(R0, R0, SafepointMechanism::poll_bit());
 232       beq(CR0, dispatch);
 233       load_dispatch_table(R11_scratch1, sfpt_tbl);
 234       align(32, 16);
 235       bind(dispatch);
 236     }
 237   }
 238 
 239   sldi(R12_scratch2, bytecode, LogBytesPerWord);
 240   ldx(R11_scratch1, R11_scratch1, R12_scratch2);
 241 
 242   // Jump off!
 243   mtctr(R11_scratch1);
 244   bcctr(bcondAlways, 0, bhintbhBCCTRisNotPredictable);
 245 }
 246 
 247 void InterpreterMacroAssembler::load_receiver(Register Rparam_count, Register Rrecv_dst) {
 248   sldi(Rrecv_dst, Rparam_count, Interpreter::logStackElementSize);
 249   ldx(Rrecv_dst, Rrecv_dst, R15_esp);
 250 }
 251 
 252 // helpers for expression stack
 253 
 254 void InterpreterMacroAssembler::pop_i(Register r) {
 255   lwzu(r, Interpreter::stackElementSize, R15_esp);
 256 }
 257 
 258 void InterpreterMacroAssembler::pop_ptr(Register r) {
 259   ldu(r, Interpreter::stackElementSize, R15_esp);
 260 }
 261 
 262 void InterpreterMacroAssembler::pop_l(Register r) {
 263   ld(r, Interpreter::stackElementSize, R15_esp);
 264   addi(R15_esp, R15_esp, 2 * Interpreter::stackElementSize);
 265 }
 266 
 267 void InterpreterMacroAssembler::pop_f(FloatRegister f) {
 268   lfsu(f, Interpreter::stackElementSize, R15_esp);
 269 }
 270 
 271 void InterpreterMacroAssembler::pop_d(FloatRegister f) {
 272   lfd(f, Interpreter::stackElementSize, R15_esp);
 273   addi(R15_esp, R15_esp, 2 * Interpreter::stackElementSize);
 274 }
 275 
 276 void InterpreterMacroAssembler::push_i(Register r) {
 277   stw(r, 0, R15_esp);
 278   addi(R15_esp, R15_esp, - Interpreter::stackElementSize );
 279 }
 280 
 281 void InterpreterMacroAssembler::push_ptr(Register r) {
 282   std(r, 0, R15_esp);
 283   addi(R15_esp, R15_esp, - Interpreter::stackElementSize );
 284 }
 285 
 286 void InterpreterMacroAssembler::push_l(Register r) {
 287   // Clear unused slot.
 288   load_const_optimized(R0, 0L);
 289   std(R0, 0, R15_esp);
 290   std(r, - Interpreter::stackElementSize, R15_esp);
 291   addi(R15_esp, R15_esp, - 2 * Interpreter::stackElementSize );
 292 }
 293 
 294 void InterpreterMacroAssembler::push_f(FloatRegister f) {
 295   stfs(f, 0, R15_esp);
 296   addi(R15_esp, R15_esp, - Interpreter::stackElementSize );
 297 }
 298 
 299 void InterpreterMacroAssembler::push_d(FloatRegister f)   {
 300   stfd(f, - Interpreter::stackElementSize, R15_esp);
 301   addi(R15_esp, R15_esp, - 2 * Interpreter::stackElementSize );
 302 }
 303 
 304 void InterpreterMacroAssembler::push_2ptrs(Register first, Register second) {
 305   std(first, 0, R15_esp);
 306   std(second, -Interpreter::stackElementSize, R15_esp);
 307   addi(R15_esp, R15_esp, - 2 * Interpreter::stackElementSize );
 308 }
 309 
 310 void InterpreterMacroAssembler::move_l_to_d(Register l, FloatRegister d) {
 311   mtfprd(d, l);
 312 }
 313 
 314 void InterpreterMacroAssembler::move_d_to_l(FloatRegister d, Register l) {
 315   mffprd(l, d);
 316 }
 317 
 318 void InterpreterMacroAssembler::push(TosState state) {
 319   switch (state) {
 320     case atos: push_ptr();                break;
 321     case btos:
 322     case ztos:
 323     case ctos:
 324     case stos:
 325     case itos: push_i();                  break;
 326     case ltos: push_l();                  break;
 327     case ftos: push_f();                  break;
 328     case dtos: push_d();                  break;
 329     case vtos: /* nothing to do */        break;
 330     default  : ShouldNotReachHere();
 331   }
 332 }
 333 
 334 void InterpreterMacroAssembler::pop(TosState state) {
 335   switch (state) {
 336     case atos: pop_ptr();            break;
 337     case btos:
 338     case ztos:
 339     case ctos:
 340     case stos:
 341     case itos: pop_i();              break;
 342     case ltos: pop_l();              break;
 343     case ftos: pop_f();              break;
 344     case dtos: pop_d();              break;
 345     case vtos: /* nothing to do */   break;
 346     default  : ShouldNotReachHere();
 347   }
 348   verify_oop(R17_tos, state);
 349 }
 350 
 351 void InterpreterMacroAssembler::empty_expression_stack() {
 352   addi(R15_esp, R26_monitor, - Interpreter::stackElementSize);
 353 }
 354 
 355 void InterpreterMacroAssembler::get_2_byte_integer_at_bcp(int         bcp_offset,
 356                                                           Register    Rdst,
 357                                                           signedOrNot is_signed) {
 358 #if defined(VM_LITTLE_ENDIAN)
 359   if (bcp_offset) {
 360     load_const_optimized(Rdst, bcp_offset);
 361     lhbrx(Rdst, R14_bcp, Rdst);
 362   } else {
 363     lhbrx(Rdst, R14_bcp);
 364   }
 365   if (is_signed == Signed) {
 366     extsh(Rdst, Rdst);
 367   }
 368 #else
 369   // Read Java big endian format.
 370   if (is_signed == Signed) {
 371     lha(Rdst, bcp_offset, R14_bcp);
 372   } else {
 373     lhz(Rdst, bcp_offset, R14_bcp);
 374   }
 375 #endif
 376 }
 377 
 378 void InterpreterMacroAssembler::get_4_byte_integer_at_bcp(int         bcp_offset,
 379                                                           Register    Rdst,
 380                                                           signedOrNot is_signed) {
 381 #if defined(VM_LITTLE_ENDIAN)
 382   if (bcp_offset) {
 383     load_const_optimized(Rdst, bcp_offset);
 384     lwbrx(Rdst, R14_bcp, Rdst);
 385   } else {
 386     lwbrx(Rdst, R14_bcp);
 387   }
 388   if (is_signed == Signed) {
 389     extsw(Rdst, Rdst);
 390   }
 391 #else
 392   // Read Java big endian format.
 393   if (bcp_offset & 3) { // Offset unaligned?
 394     load_const_optimized(Rdst, bcp_offset);
 395     if (is_signed == Signed) {
 396       lwax(Rdst, R14_bcp, Rdst);
 397     } else {
 398       lwzx(Rdst, R14_bcp, Rdst);
 399     }
 400   } else {
 401     if (is_signed == Signed) {
 402       lwa(Rdst, bcp_offset, R14_bcp);
 403     } else {
 404       lwz(Rdst, bcp_offset, R14_bcp);
 405     }
 406   }
 407 #endif
 408 }
 409 
 410 
 411 // Load the constant pool cache index from the bytecode stream.
 412 //
 413 // Kills / writes:
 414 //   - Rdst, Rscratch
 415 void InterpreterMacroAssembler::get_cache_index_at_bcp(Register Rdst, int bcp_offset,
 416                                                        size_t index_size) {
 417   assert(bcp_offset > 0, "bcp is still pointing to start of bytecode");
 418   // Cache index is always in the native format, courtesy of Rewriter.
 419   if (index_size == sizeof(u2)) {
 420     lhz(Rdst, bcp_offset, R14_bcp);
 421   } else if (index_size == sizeof(u4)) {
 422     if (bcp_offset & 3) {
 423       load_const_optimized(Rdst, bcp_offset);
 424       lwax(Rdst, R14_bcp, Rdst);
 425     } else {
 426       lwa(Rdst, bcp_offset, R14_bcp);
 427     }
 428   } else if (index_size == sizeof(u1)) {
 429     lbz(Rdst, bcp_offset, R14_bcp);
 430   } else {
 431     ShouldNotReachHere();
 432   }
 433   // Rdst now contains cp cache index.
 434 }
 435 
 436 // Load 4-byte signed or unsigned integer in Java format (that is, big-endian format)
 437 // from (Rsrc)+offset.
 438 void InterpreterMacroAssembler::get_u4(Register Rdst, Register Rsrc, int offset,
 439                                        signedOrNot is_signed) {
 440 #if defined(VM_LITTLE_ENDIAN)
 441   if (offset) {
 442     load_const_optimized(Rdst, offset);
 443     lwbrx(Rdst, Rdst, Rsrc);
 444   } else {
 445     lwbrx(Rdst, Rsrc);
 446   }
 447   if (is_signed == Signed) {
 448     extsw(Rdst, Rdst);
 449   }
 450 #else
 451   if (is_signed == Signed) {
 452     lwa(Rdst, offset, Rsrc);
 453   } else {
 454     lwz(Rdst, offset, Rsrc);
 455   }
 456 #endif
 457 }
 458 
 459 void InterpreterMacroAssembler::load_resolved_indy_entry(Register cache, Register index) {
 460   // Get index out of bytecode pointer
 461   get_cache_index_at_bcp(index, 1, sizeof(u4));
 462 
 463   // Get address of invokedynamic array
 464   ld_ptr(cache, in_bytes(ConstantPoolCache::invokedynamic_entries_offset()), R27_constPoolCache);
 465   // Scale the index to be the entry index * sizeof(ResolvedIndyEntry)
 466   sldi(index, index, log2i_exact(sizeof(ResolvedIndyEntry)));
 467   addi(cache, cache, Array<ResolvedIndyEntry>::base_offset_in_bytes());
 468   add(cache, cache, index);
 469 }
 470 
 471 void InterpreterMacroAssembler::load_field_entry(Register cache, Register index, int bcp_offset) {
 472   // Get index out of bytecode pointer
 473   get_cache_index_at_bcp(index, bcp_offset, sizeof(u2));
 474   // Take shortcut if the size is a power of 2
 475   if (is_power_of_2(sizeof(ResolvedFieldEntry))) {
 476     // Scale index by power of 2
 477     sldi(index, index, log2i_exact(sizeof(ResolvedFieldEntry)));
 478   } else {
 479     // Scale the index to be the entry index * sizeof(ResolvedFieldEntry)
 480     mulli(index, index, sizeof(ResolvedFieldEntry));
 481   }
 482   // Get address of field entries array
 483   ld_ptr(cache, in_bytes(ConstantPoolCache::field_entries_offset()), R27_constPoolCache);
 484   addi(cache, cache, Array<ResolvedFieldEntry>::base_offset_in_bytes());
 485   add(cache, cache, index);
 486 }
 487 
 488 void InterpreterMacroAssembler::load_method_entry(Register cache, Register index, int bcp_offset) {
 489   // Get index out of bytecode pointer
 490   get_cache_index_at_bcp(index, bcp_offset, sizeof(u2));
 491   // Scale the index to be the entry index * sizeof(ResolvedMethodEntry)
 492   mulli(index, index, sizeof(ResolvedMethodEntry));
 493 
 494   // Get address of field entries array
 495   ld_ptr(cache, ConstantPoolCache::method_entries_offset(), R27_constPoolCache);
 496   addi(cache, cache, Array<ResolvedMethodEntry>::base_offset_in_bytes());
 497   add(cache, cache, index); // method_entries + base_offset + scaled index
 498 }
 499 
 500 // Load object from cpool->resolved_references(index).
 501 // Kills:
 502 //   - index
 503 void InterpreterMacroAssembler::load_resolved_reference_at_index(Register result, Register index,
 504                                                                  Register tmp1, Register tmp2,
 505                                                                  Label *L_handle_null) {
 506   assert_different_registers(result, index, tmp1, tmp2);
 507   assert(index->is_nonvolatile(), "needs to survive C-call in resolve_oop_handle");
 508   get_constant_pool(result);
 509 
 510   // Convert from field index to resolved_references() index and from
 511   // word index to byte offset. Since this is a java object, it can be compressed.
 512   sldi(index, index, LogBytesPerHeapOop);
 513   // Load pointer for resolved_references[] objArray.
 514   ld(result, ConstantPool::cache_offset(), result);
 515   ld(result, ConstantPoolCache::resolved_references_offset(), result);
 516   resolve_oop_handle(result, tmp1, tmp2, MacroAssembler::PRESERVATION_NONE);
 517 #ifdef ASSERT
 518   Label index_ok;
 519   lwa(R0, arrayOopDesc::length_offset_in_bytes(), result);
 520   sldi(R0, R0, LogBytesPerHeapOop);
 521   cmpd(CR0, index, R0);
 522   blt(CR0, index_ok);
 523   stop("resolved reference index out of bounds");
 524   bind(index_ok);
 525 #endif
 526   // Add in the index.
 527   add(result, index, result);
 528   load_heap_oop(result, arrayOopDesc::base_offset_in_bytes(T_OBJECT), result,
 529                 tmp1, tmp2,
 530                 MacroAssembler::PRESERVATION_NONE,
 531                 0, L_handle_null);
 532 }
 533 
 534 // load cpool->resolved_klass_at(index)
 535 void InterpreterMacroAssembler::load_resolved_klass_at_offset(Register Rcpool, Register Roffset, Register Rklass) {
 536   // int value = *(Rcpool->int_at_addr(which));
 537   // int resolved_klass_index = extract_low_short_from_int(value);
 538   add(Roffset, Rcpool, Roffset);
 539 #if defined(VM_LITTLE_ENDIAN)
 540   lhz(Roffset, sizeof(ConstantPool), Roffset);     // Roffset = resolved_klass_index
 541 #else
 542   lhz(Roffset, sizeof(ConstantPool) + 2, Roffset); // Roffset = resolved_klass_index
 543 #endif
 544 
 545   ld(Rklass, ConstantPool::resolved_klasses_offset(), Rcpool); // Rklass = Rcpool->_resolved_klasses
 546 
 547   sldi(Roffset, Roffset, LogBytesPerWord);
 548   addi(Roffset, Roffset, Array<Klass*>::base_offset_in_bytes());
 549   isync(); // Order load of instance Klass wrt. tags.
 550   ldx(Rklass, Rklass, Roffset);
 551 }
 552 
 553 // Generate a subtype check: branch to ok_is_subtype if sub_klass is
 554 // a subtype of super_klass. Blows registers Rsub_klass, tmp1, tmp2.
 555 void InterpreterMacroAssembler::gen_subtype_check(Register Rsub_klass, Register Rsuper_klass, Register Rtmp1,
 556                                                   Register Rtmp2, Register Rtmp3, Label &ok_is_subtype) {
 557   // Profile the not-null value's klass.
 558   profile_typecheck(Rsub_klass, Rtmp1, Rtmp2);
 559   check_klass_subtype(Rsub_klass, Rsuper_klass, Rtmp1, Rtmp2, ok_is_subtype);
 560 }
 561 
 562 // Separate these two to allow for delay slot in middle.
 563 // These are used to do a test and full jump to exception-throwing code.
 564 
 565 // Check that index is in range for array, then shift index by index_shift,
 566 // and put arrayOop + shifted_index into res.
 567 // Note: res is still shy of address by array offset into object.
 568 
 569 void InterpreterMacroAssembler::index_check_without_pop(Register Rarray, Register Rindex,
 570                                                         int index_shift, Register Rtmp, Register Rres) {
 571   // Check that index is in range for array, then shift index by index_shift,
 572   // and put arrayOop + shifted_index into res.
 573   // Note: res is still shy of address by array offset into object.
 574   // Kills:
 575   //   - Rindex
 576   // Writes:
 577   //   - Rres: Address that corresponds to the array index if check was successful.
 578   verify_oop(Rarray);
 579   const Register Rlength   = R0;
 580   const Register RsxtIndex = Rtmp;
 581   Label LisNull, LnotOOR;
 582 
 583   // Array nullcheck
 584   if (!ImplicitNullChecks) {
 585     cmpdi(CR0, Rarray, 0);
 586     beq(CR0, LisNull);
 587   } else {
 588     null_check_throw(Rarray, arrayOopDesc::length_offset_in_bytes(), /*temp*/RsxtIndex);
 589   }
 590 
 591   // Rindex might contain garbage in upper bits (remember that we don't sign extend
 592   // during integer arithmetic operations). So kill them and put value into same register
 593   // where ArrayIndexOutOfBounds would expect the index in.
 594   rldicl(RsxtIndex, Rindex, 0, 32); // zero extend 32 bit -> 64 bit
 595 
 596   // Index check
 597   lwz(Rlength, arrayOopDesc::length_offset_in_bytes(), Rarray);
 598   cmplw(CR0, Rindex, Rlength);
 599   sldi(RsxtIndex, RsxtIndex, index_shift);
 600   blt(CR0, LnotOOR);
 601   // Index should be in R17_tos, array should be in R4_ARG2.
 602   mr_if_needed(R17_tos, Rindex);
 603   mr_if_needed(R4_ARG2, Rarray);
 604   load_dispatch_table(Rtmp, (address*)Interpreter::_throw_ArrayIndexOutOfBoundsException_entry);
 605   mtctr(Rtmp);
 606   bctr();
 607 
 608   if (!ImplicitNullChecks) {
 609     bind(LisNull);
 610     load_dispatch_table(Rtmp, (address*)Interpreter::_throw_NullPointerException_entry);
 611     mtctr(Rtmp);
 612     bctr();
 613   }
 614 
 615   align(32, 16);
 616   bind(LnotOOR);
 617 
 618   // Calc address
 619   add(Rres, RsxtIndex, Rarray);
 620 }
 621 
 622 void InterpreterMacroAssembler::index_check(Register array, Register index,
 623                                             int index_shift, Register tmp, Register res) {
 624   // pop array
 625   pop_ptr(array);
 626 
 627   // check array
 628   index_check_without_pop(array, index, index_shift, tmp, res);
 629 }
 630 
 631 void InterpreterMacroAssembler::get_const(Register Rdst) {
 632   ld(Rdst, in_bytes(Method::const_offset()), R19_method);
 633 }
 634 
 635 void InterpreterMacroAssembler::get_constant_pool(Register Rdst) {
 636   get_const(Rdst);
 637   ld(Rdst, in_bytes(ConstMethod::constants_offset()), Rdst);
 638 }
 639 
 640 void InterpreterMacroAssembler::get_constant_pool_cache(Register Rdst) {
 641   get_constant_pool(Rdst);
 642   ld(Rdst, ConstantPool::cache_offset(), Rdst);
 643 }
 644 
 645 void InterpreterMacroAssembler::get_cpool_and_tags(Register Rcpool, Register Rtags) {
 646   get_constant_pool(Rcpool);
 647   ld(Rtags, ConstantPool::tags_offset(), Rcpool);
 648 }
 649 
 650 // Unlock if synchronized method.
 651 //
 652 // Unlock the receiver if this is a synchronized method.
 653 // Unlock any Java monitors from synchronized blocks.
 654 //
 655 // If there are locked Java monitors
 656 //   If throw_monitor_exception
 657 //     throws IllegalMonitorStateException
 658 //   Else if install_monitor_exception
 659 //     installs IllegalMonitorStateException
 660 //   Else
 661 //     no error processing
 662 void InterpreterMacroAssembler::unlock_if_synchronized_method(TosState state,
 663                                                               bool throw_monitor_exception,
 664                                                               bool install_monitor_exception) {
 665   Label Lunlocked, Lno_unlock;
 666   {
 667     Register Rdo_not_unlock_flag = R11_scratch1;
 668     Register Raccess_flags       = R12_scratch2;
 669 
 670     // Check if synchronized method or unlocking prevented by
 671     // JavaThread::do_not_unlock_if_synchronized flag.
 672     lbz(Rdo_not_unlock_flag, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
 673     lhz(Raccess_flags, in_bytes(Method::access_flags_offset()), R19_method);
 674     li(R0, 0);
 675     stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread); // reset flag
 676 
 677     push(state);
 678 
 679     // Skip if we don't have to unlock.
 680     testbitdi(CR0, R0, Raccess_flags, JVM_ACC_SYNCHRONIZED_BIT);
 681     beq(CR0, Lunlocked);
 682 
 683     cmpwi(CR0, Rdo_not_unlock_flag, 0);
 684     bne(CR0, Lno_unlock);
 685   }
 686 
 687   // Unlock
 688   {
 689     Register Rmonitor_base = R11_scratch1;
 690 
 691     Label Lunlock;
 692     // If it's still locked, everything is ok, unlock it.
 693     ld(Rmonitor_base, 0, R1_SP);
 694     addi(Rmonitor_base, Rmonitor_base,
 695          -(frame::ijava_state_size + frame::interpreter_frame_monitor_size_in_bytes())); // Monitor base
 696 
 697     ld(R0, BasicObjectLock::obj_offset(), Rmonitor_base);
 698     cmpdi(CR0, R0, 0);
 699     bne(CR0, Lunlock);
 700 
 701     // If it's already unlocked, throw exception.
 702     if (throw_monitor_exception) {
 703       call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_illegal_monitor_state_exception));
 704       should_not_reach_here();
 705     } else {
 706       if (install_monitor_exception) {
 707         call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::new_illegal_monitor_state_exception));
 708         b(Lunlocked);
 709       }
 710     }
 711 
 712     bind(Lunlock);
 713     unlock_object(Rmonitor_base);
 714   }
 715 
 716   // Check that all other monitors are unlocked. Throw IllegelMonitorState exception if not.
 717   bind(Lunlocked);
 718   {
 719     Label Lexception, Lrestart;
 720     Register Rcurrent_obj_addr = R11_scratch1;
 721     const int delta = frame::interpreter_frame_monitor_size_in_bytes();
 722     assert((delta & LongAlignmentMask) == 0, "sizeof BasicObjectLock must be even number of doublewords");
 723 
 724     bind(Lrestart);
 725     // Set up search loop: Calc num of iterations.
 726     {
 727       Register Riterations = R12_scratch2;
 728       Register Rmonitor_base = Rcurrent_obj_addr;
 729       ld(Rmonitor_base, 0, R1_SP);
 730       addi(Rmonitor_base, Rmonitor_base, - frame::ijava_state_size);  // Monitor base
 731 
 732       subf_(Riterations, R26_monitor, Rmonitor_base);
 733       ble(CR0, Lno_unlock);
 734 
 735       addi(Rcurrent_obj_addr, Rmonitor_base,
 736            in_bytes(BasicObjectLock::obj_offset()) - frame::interpreter_frame_monitor_size_in_bytes());
 737       // Check if any monitor is on stack, bail out if not
 738       srdi(Riterations, Riterations, exact_log2(delta));
 739       mtctr(Riterations);
 740     }
 741 
 742     // The search loop: Look for locked monitors.
 743     {
 744       const Register Rcurrent_obj = R0;
 745       Label Lloop;
 746 
 747       ld(Rcurrent_obj, 0, Rcurrent_obj_addr);
 748       addi(Rcurrent_obj_addr, Rcurrent_obj_addr, -delta);
 749       bind(Lloop);
 750 
 751       // Check if current entry is used.
 752       cmpdi(CR0, Rcurrent_obj, 0);
 753       bne(CR0, Lexception);
 754       // Preload next iteration's compare value.
 755       ld(Rcurrent_obj, 0, Rcurrent_obj_addr);
 756       addi(Rcurrent_obj_addr, Rcurrent_obj_addr, -delta);
 757       bdnz(Lloop);
 758     }
 759     // Fell through: Everything's unlocked => finish.
 760     b(Lno_unlock);
 761 
 762     // An object is still locked => need to throw exception.
 763     bind(Lexception);
 764     if (throw_monitor_exception) {
 765       call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_illegal_monitor_state_exception));
 766       should_not_reach_here();
 767     } else {
 768       // Stack unrolling. Unlock object and if requested, install illegal_monitor_exception.
 769       // Unlock does not block, so don't have to worry about the frame.
 770       Register Rmonitor_addr = R11_scratch1;
 771       addi(Rmonitor_addr, Rcurrent_obj_addr, -in_bytes(BasicObjectLock::obj_offset()) + delta);
 772       unlock_object(Rmonitor_addr);
 773       if (install_monitor_exception) {
 774         call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::new_illegal_monitor_state_exception));
 775       }
 776       b(Lrestart);
 777     }
 778   }
 779 
 780   align(32, 12);
 781   bind(Lno_unlock);
 782   pop(state);
 783 }
 784 
 785 // Support function for remove_activation & Co.
 786 void InterpreterMacroAssembler::load_fp(Register fp) {
 787   ld(fp, _abi0(callers_sp), R1_SP); // *SP
 788 }
 789 
 790 void InterpreterMacroAssembler::remove_top_frame_given_fp(Register fp, Register sender_sp, Register sender_fp,
 791                                                           Register return_pc, Register temp) {
 792   assert_different_registers(sender_sp, sender_fp, return_pc, temp);
 793   ld(sender_sp, _ijava_state_neg(sender_sp), fp);
 794   ld(sender_fp, _abi0(callers_sp), fp); // **SP
 795   if (return_pc != noreg) {
 796     ld(return_pc, _abi0(lr), fp); // last usage of fp, register can be reused
 797   }
 798   subf(temp, R1_SP, sender_sp);   // sender_sp - SP
 799   stdux(sender_fp, R1_SP, temp);  // atomically set *(SP = sender_sp) = sender_fp
 800 }
 801 
 802 void InterpreterMacroAssembler::merge_frames(Register sender_sp, Register return_pc,
 803                                              Register temp1, Register temp2) {
 804   Register fp = temp1, sender_fp = temp2;
 805   load_fp(fp);
 806   remove_top_frame_given_fp(fp, sender_sp, sender_fp, return_pc, /* temp */ fp);
 807 }
 808 
 809 void InterpreterMacroAssembler::narrow(Register result) {
 810   Register ret_type = R11_scratch1;
 811   ld(R11_scratch1, in_bytes(Method::const_offset()), R19_method);
 812   lbz(ret_type, in_bytes(ConstMethod::result_type_offset()), R11_scratch1);
 813 
 814   Label notBool, notByte, notChar, done;
 815 
 816   // common case first
 817   cmpwi(CR0, ret_type, T_INT);
 818   beq(CR0, done);
 819 
 820   cmpwi(CR0, ret_type, T_BOOLEAN);
 821   bne(CR0, notBool);
 822   andi(result, result, 0x1);
 823   b(done);
 824 
 825   bind(notBool);
 826   cmpwi(CR0, ret_type, T_BYTE);
 827   bne(CR0, notByte);
 828   extsb(result, result);
 829   b(done);
 830 
 831   bind(notByte);
 832   cmpwi(CR0, ret_type, T_CHAR);
 833   bne(CR0, notChar);
 834   andi(result, result, 0xffff);
 835   b(done);
 836 
 837   bind(notChar);
 838   // cmpwi(CR0, ret_type, T_SHORT);  // all that's left
 839   // bne(CR0, done);
 840   extsh(result, result);
 841 
 842   // Nothing to do for T_INT
 843   bind(done);
 844 }
 845 
 846 // Remove activation.
 847 //
 848 // Apply stack watermark barrier.
 849 // Unlock the receiver if this is a synchronized method.
 850 // Unlock any Java monitors from synchronized blocks.
 851 // Remove the activation from the stack.
 852 //
 853 // If there are locked Java monitors
 854 //    If throw_monitor_exception
 855 //       throws IllegalMonitorStateException
 856 //    Else if install_monitor_exception
 857 //       installs IllegalMonitorStateException
 858 //    Else
 859 //       no error processing
 860 void InterpreterMacroAssembler::remove_activation(TosState state,
 861                                                   bool throw_monitor_exception,
 862                                                   bool install_monitor_exception) {
 863   BLOCK_COMMENT("remove_activation {");
 864 
 865   unlock_if_synchronized_method(state, throw_monitor_exception, install_monitor_exception);
 866 
 867   // The below poll is for the stack watermark barrier. It allows fixing up frames lazily,
 868   // that would normally not be safe to use. Such bad returns into unsafe territory of
 869   // the stack, will call InterpreterRuntime::at_unwind.
 870   Label slow_path, fast_path;
 871   Register fp = R22_tmp2;
 872   load_fp(fp);
 873 
 874   JFR_ONLY(enter_jfr_critical_section();)
 875   safepoint_poll(slow_path, R11_scratch1, true /* at_return */, false /* in_nmethod */);
 876   b(fast_path);
 877   bind(slow_path);
 878   push(state);
 879   set_last_Java_frame(R1_SP, noreg);
 880   call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::at_unwind), R16_thread);
 881   reset_last_Java_frame();
 882   pop(state);
 883   align(32);
 884   bind(fast_path);
 885 
 886   // Save result (push state before jvmti call and pop it afterwards) and notify jvmti.
 887   notify_method_exit(false, state, NotifyJVMTI, true);
 888 
 889   BLOCK_COMMENT("reserved_stack_check:");
 890   if (StackReservedPages > 0) {
 891     // Test if reserved zone needs to be enabled.
 892     Label no_reserved_zone_enabling;
 893 
 894     // check if already enabled - if so no re-enabling needed
 895     assert(sizeof(StackOverflow::StackGuardState) == 4, "unexpected size");
 896     lwz(R0, in_bytes(JavaThread::stack_guard_state_offset()), R16_thread);
 897     cmpwi(CR0, R0, StackOverflow::stack_guard_enabled);
 898     beq_predict_taken(CR0, no_reserved_zone_enabling);
 899 
 900     // Compare frame pointers. There is no good stack pointer, as with stack
 901     // frame compression we can get different SPs when we do calls. A subsequent
 902     // call could have a smaller SP, so that this compare succeeds for an
 903     // inner call of the method annotated with ReservedStack.
 904     ld_ptr(R0, JavaThread::reserved_stack_activation_offset(), R16_thread);
 905     cmpld(CR0, fp, R0);
 906     blt_predict_taken(CR0, no_reserved_zone_enabling);
 907 
 908     JFR_ONLY(leave_jfr_critical_section();)
 909 
 910     // Enable reserved zone again, throw stack overflow exception.
 911     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), R16_thread);
 912     call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_delayed_StackOverflowError));
 913 
 914     should_not_reach_here();
 915 
 916     bind(no_reserved_zone_enabling);
 917   }
 918 
 919   verify_oop(R17_tos, state);
 920 
 921   remove_top_frame_given_fp(fp, R21_sender_SP, R23_tmp3, /*return_pc*/ R0, R11_scratch1);
 922   mtlr(R0);
 923   pop_cont_fastpath();
 924   JFR_ONLY(leave_jfr_critical_section();)
 925 
 926   BLOCK_COMMENT("} remove_activation");
 927 }
 928 
 929 #if INCLUDE_JFR
 930 void InterpreterMacroAssembler::enter_jfr_critical_section() {
 931   li(R0, 1);
 932   stb(R0, in_bytes(SAMPLING_CRITICAL_SECTION_OFFSET_JFR), R16_thread);
 933 }
 934 
 935 void InterpreterMacroAssembler::leave_jfr_critical_section() {
 936   li(R0, 0);
 937   stb(R0, in_bytes(SAMPLING_CRITICAL_SECTION_OFFSET_JFR), R16_thread);
 938 }
 939 #endif // INCLUDE_JFR
 940 
 941 // Lock object
 942 //
 943 // Registers alive
 944 //   monitor - Address of the BasicObjectLock to be used for locking,
 945 //             which must be initialized with the object to lock.
 946 //   object  - Address of the object to be locked.
 947 //
 948 void InterpreterMacroAssembler::lock_object(Register monitor, Register object) {
 949   if (LockingMode == LM_MONITOR) {
 950     call_VM_preemptable(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter), monitor);
 951   } else {
 952     // template code (for LM_LEGACY):
 953     //
 954     // markWord displaced_header = obj->mark().set_unlocked();
 955     // monitor->lock()->set_displaced_header(displaced_header);
 956     // if (Atomic::cmpxchg(/*addr*/obj->mark_addr(), /*cmp*/displaced_header, /*ex=*/monitor) == displaced_header) {
 957     //   // We stored the monitor address into the object's mark word.
 958     // } else if (THREAD->is_lock_owned((address)displaced_header))
 959     //   // Simple recursive case.
 960     //   monitor->lock()->set_displaced_header(nullptr);
 961     // } else {
 962     //   // Slow path.
 963     //   InterpreterRuntime::monitorenter(THREAD, monitor);
 964     // }
 965 
 966     const Register header           = R7_ARG5;
 967     const Register object_mark_addr = R8_ARG6;
 968     const Register current_header   = R9_ARG7;
 969     const Register tmp              = R10_ARG8;
 970 
 971     Label count_locking, done, slow_case, cas_failed;
 972 
 973     assert_different_registers(header, object_mark_addr, current_header, tmp);
 974 
 975     // markWord displaced_header = obj->mark().set_unlocked();
 976 
 977     if (LockingMode == LM_LIGHTWEIGHT) {
 978       lightweight_lock(monitor, object, header, tmp, slow_case);
 979       b(done);
 980     } else if (LockingMode == LM_LEGACY) {
 981 
 982       if (DiagnoseSyncOnValueBasedClasses != 0) {
 983         load_klass(tmp, object);
 984         lbz(tmp, in_bytes(Klass::misc_flags_offset()), tmp);
 985         testbitdi(CR0, R0, tmp, exact_log2(KlassFlags::_misc_is_value_based_class));
 986         bne(CR0, slow_case);
 987       }
 988 
 989       // Load markWord from object into header.
 990       ld(header, oopDesc::mark_offset_in_bytes(), object);
 991 
 992       // Set displaced_header to be (markWord of object | UNLOCK_VALUE).
 993       ori(header, header, markWord::unlocked_value);
 994 
 995       // monitor->lock()->set_displaced_header(displaced_header);
 996       const int lock_offset = in_bytes(BasicObjectLock::lock_offset());
 997       const int mark_offset = lock_offset +
 998                               BasicLock::displaced_header_offset_in_bytes();
 999 
1000       // Initialize the box (Must happen before we update the object mark!).
1001       std(header, mark_offset, monitor);
1002 
1003       // if (Atomic::cmpxchg(/*addr*/obj->mark_addr(), /*cmp*/displaced_header, /*ex=*/monitor) == displaced_header) {
1004 
1005       // Store stack address of the BasicObjectLock (this is monitor) into object.
1006       addi(object_mark_addr, object, oopDesc::mark_offset_in_bytes());
1007 
1008       // Must fence, otherwise, preceding store(s) may float below cmpxchg.
1009       // CmpxchgX sets CR0 to cmpX(current, displaced).
1010       cmpxchgd(/*flag=*/CR0,
1011                /*current_value=*/current_header,
1012                /*compare_value=*/header, /*exchange_value=*/monitor,
1013                /*where=*/object_mark_addr,
1014                MacroAssembler::MemBarRel | MacroAssembler::MemBarAcq,
1015                MacroAssembler::cmpxchgx_hint_acquire_lock(),
1016                noreg,
1017                &cas_failed,
1018                /*check without membar and ldarx first*/true);
1019 
1020       // If the compare-and-exchange succeeded, then we found an unlocked
1021       // object and we have now locked it.
1022       b(count_locking);
1023       bind(cas_failed);
1024 
1025       // } else if (THREAD->is_lock_owned((address)displaced_header))
1026       //   // Simple recursive case.
1027       //   monitor->lock()->set_displaced_header(nullptr);
1028 
1029       // We did not see an unlocked object so try the fast recursive case.
1030 
1031       // Check if owner is self by comparing the value in the markWord of object
1032       // (current_header) with the stack pointer.
1033       sub(current_header, current_header, R1_SP);
1034 
1035       assert(os::vm_page_size() > 0xfff, "page size too small - change the constant");
1036       load_const_optimized(tmp, ~(os::vm_page_size()-1) | markWord::lock_mask_in_place);
1037 
1038       and_(R0/*==0?*/, current_header, tmp);
1039       // If condition is true we are done and hence we can store 0 in the displaced
1040       // header indicating it is a recursive lock.
1041       bne(CR0, slow_case);
1042       std(R0/*==0!*/, mark_offset, monitor);
1043       b(count_locking);
1044     }
1045 
1046     // } else {
1047     //   // Slow path.
1048     //   InterpreterRuntime::monitorenter(THREAD, monitor);
1049 
1050     // None of the above fast optimizations worked so we have to get into the
1051     // slow case of monitor enter.
1052     bind(slow_case);
1053     call_VM_preemptable(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter), monitor);
1054     // }
1055 
1056     if (LockingMode == LM_LEGACY) {
1057       b(done);
1058       align(32, 12);
1059       bind(count_locking);
1060       inc_held_monitor_count(current_header /*tmp*/);
1061     }
1062     bind(done);
1063   }
1064 }
1065 
1066 // Unlocks an object. Used in monitorexit bytecode and remove_activation.
1067 //
1068 // Registers alive
1069 //   monitor - Address of the BasicObjectLock to be used for locking,
1070 //             which must be initialized with the object to lock.
1071 //
1072 // Throw IllegalMonitorException if object is not locked by current thread.
1073 void InterpreterMacroAssembler::unlock_object(Register monitor) {
1074   if (LockingMode == LM_MONITOR) {
1075     call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit), monitor);
1076   } else {
1077 
1078     // template code (for LM_LEGACY):
1079     //
1080     // if ((displaced_header = monitor->displaced_header()) == nullptr) {
1081     //   // Recursive unlock. Mark the monitor unlocked by setting the object field to null.
1082     //   monitor->set_obj(nullptr);
1083     // } else if (Atomic::cmpxchg(obj->mark_addr(), monitor, displaced_header) == monitor) {
1084     //   // We swapped the unlocked mark in displaced_header into the object's mark word.
1085     //   monitor->set_obj(nullptr);
1086     // } else {
1087     //   // Slow path.
1088     //   InterpreterRuntime::monitorexit(monitor);
1089     // }
1090 
1091     const Register object           = R7_ARG5;
1092     const Register header           = R8_ARG6;
1093     const Register object_mark_addr = R9_ARG7;
1094     const Register current_header   = R10_ARG8;
1095 
1096     Label free_slot;
1097     Label slow_case;
1098 
1099     assert_different_registers(object, header, object_mark_addr, current_header);
1100 
1101     if (LockingMode != LM_LIGHTWEIGHT) {
1102       // Test first if we are in the fast recursive case.
1103       ld(header, in_bytes(BasicObjectLock::lock_offset()) +
1104                  BasicLock::displaced_header_offset_in_bytes(), monitor);
1105 
1106       // If the displaced header is zero, we have a recursive unlock.
1107       cmpdi(CR0, header, 0);
1108       beq(CR0, free_slot); // recursive unlock
1109     }
1110 
1111     // } else if (Atomic::cmpxchg(obj->mark_addr(), monitor, displaced_header) == monitor) {
1112     //   // We swapped the unlocked mark in displaced_header into the object's mark word.
1113     //   monitor->set_obj(nullptr);
1114 
1115     // If we still have a lightweight lock, unlock the object and be done.
1116 
1117     // The object address from the monitor is in object.
1118     ld(object, in_bytes(BasicObjectLock::obj_offset()), monitor);
1119 
1120     if (LockingMode == LM_LIGHTWEIGHT) {
1121       lightweight_unlock(object, header, slow_case);
1122     } else {
1123       addi(object_mark_addr, object, oopDesc::mark_offset_in_bytes());
1124 
1125       // We have the displaced header in displaced_header. If the lock is still
1126       // lightweight, it will contain the monitor address and we'll store the
1127       // displaced header back into the object's mark word.
1128       // CmpxchgX sets CR0 to cmpX(current, monitor).
1129       cmpxchgd(/*flag=*/CR0,
1130                /*current_value=*/current_header,
1131                /*compare_value=*/monitor, /*exchange_value=*/header,
1132                /*where=*/object_mark_addr,
1133                MacroAssembler::MemBarRel,
1134                MacroAssembler::cmpxchgx_hint_release_lock(),
1135                noreg,
1136                &slow_case);
1137     }
1138     b(free_slot);
1139 
1140     // } else {
1141     //   // Slow path.
1142     //   InterpreterRuntime::monitorexit(monitor);
1143 
1144     // The lock has been converted into a heavy lock and hence
1145     // we need to get into the slow case.
1146     bind(slow_case);
1147     call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit), monitor);
1148     // }
1149 
1150     Label done;
1151     b(done); // Monitor register may be overwritten! Runtime has already freed the slot.
1152 
1153     // Exchange worked, do monitor->set_obj(nullptr);
1154     align(32, 12);
1155     bind(free_slot);
1156     li(R0, 0);
1157     std(R0, in_bytes(BasicObjectLock::obj_offset()), monitor);
1158     if (LockingMode == LM_LEGACY) {
1159       dec_held_monitor_count(current_header /*tmp*/);
1160     }
1161     bind(done);
1162   }
1163 }
1164 
1165 // Load compiled (i2c) or interpreter entry when calling from interpreted and
1166 // do the call. Centralized so that all interpreter calls will do the same actions.
1167 // If jvmti single stepping is on for a thread we must not call compiled code.
1168 //
1169 // Input:
1170 //   - Rtarget_method: method to call
1171 //   - Rret_addr:      return address
1172 //   - 2 scratch regs
1173 //
1174 void InterpreterMacroAssembler::call_from_interpreter(Register Rtarget_method, Register Rret_addr,
1175                                                       Register Rscratch1, Register Rscratch2) {
1176   assert_different_registers(Rscratch1, Rscratch2, Rtarget_method, Rret_addr);
1177   // Assume we want to go compiled if available.
1178   const Register Rtarget_addr = Rscratch1;
1179   const Register Rinterp_only = Rscratch2;
1180 
1181   ld(Rtarget_addr, in_bytes(Method::from_interpreted_offset()), Rtarget_method);
1182 
1183   if (JvmtiExport::can_post_interpreter_events()) {
1184     lwz(Rinterp_only, in_bytes(JavaThread::interp_only_mode_offset()), R16_thread);
1185 
1186     // JVMTI events, such as single-stepping, are implemented partly by avoiding running
1187     // compiled code in threads for which the event is enabled. Check here for
1188     // interp_only_mode if these events CAN be enabled.
1189     Label done;
1190     cmpwi(CR0, Rinterp_only, 0);
1191     beq(CR0, done);
1192     ld(Rtarget_addr, in_bytes(Method::interpreter_entry_offset()), Rtarget_method);
1193     align(32, 12);
1194     bind(done);
1195   }
1196 
1197 #ifdef ASSERT
1198   {
1199     Label Lok;
1200     cmpdi(CR0, Rtarget_addr, 0);
1201     bne(CR0, Lok);
1202     stop("null entry point");
1203     bind(Lok);
1204   }
1205 #endif // ASSERT
1206 
1207   mr(R21_sender_SP, R1_SP);
1208 
1209   // Calc a precise SP for the call. The SP value we calculated in
1210   // generate_fixed_frame() is based on the max_stack() value, so we would waste stack space
1211   // if esp is not max. Also, the i2c adapter extends the stack space without restoring
1212   // our pre-calced value, so repeating calls via i2c would result in stack overflow.
1213   // Since esp already points to an empty slot, we just have to sub 1 additional slot
1214   // to meet the abi scratch requirements.
1215   // The max_stack pointer will get restored by means of the GR_Lmax_stack local in
1216   // the return entry of the interpreter.
1217   addi(Rscratch2, R15_esp, Interpreter::stackElementSize - frame::top_ijava_frame_abi_size);
1218   clrrdi(Rscratch2, Rscratch2, exact_log2(frame::alignment_in_bytes)); // round towards smaller address
1219   resize_frame_absolute(Rscratch2, Rscratch2, R0);
1220 
1221   mr_if_needed(R19_method, Rtarget_method);
1222   mtctr(Rtarget_addr);
1223   mtlr(Rret_addr);
1224 
1225   save_interpreter_state(Rscratch2);
1226 #ifdef ASSERT
1227   ld(Rscratch1, _ijava_state_neg(top_frame_sp), Rscratch2); // Rscratch2 contains fp
1228   sldi(Rscratch1, Rscratch1, Interpreter::logStackElementSize);
1229   add(Rscratch1, Rscratch1, Rscratch2); // Rscratch2 contains fp
1230   // Compare sender_sp with the derelativized top_frame_sp
1231   cmpd(CR0, R21_sender_SP, Rscratch1);
1232   asm_assert_eq("top_frame_sp incorrect");
1233 #endif
1234 
1235   bctr();
1236 }
1237 
1238 // Set the method data pointer for the current bcp.
1239 void InterpreterMacroAssembler::set_method_data_pointer_for_bcp() {
1240   assert(ProfileInterpreter, "must be profiling interpreter");
1241   Label get_continue;
1242   ld(R28_mdx, in_bytes(Method::method_data_offset()), R19_method);
1243   test_method_data_pointer(get_continue);
1244   call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::bcp_to_di), R19_method, R14_bcp);
1245 
1246   addi(R28_mdx, R28_mdx, in_bytes(MethodData::data_offset()));
1247   add(R28_mdx, R28_mdx, R3_RET);
1248   bind(get_continue);
1249 }
1250 
1251 // Test ImethodDataPtr. If it is null, continue at the specified label.
1252 void InterpreterMacroAssembler::test_method_data_pointer(Label& zero_continue) {
1253   assert(ProfileInterpreter, "must be profiling interpreter");
1254   cmpdi(CR0, R28_mdx, 0);
1255   beq(CR0, zero_continue);
1256 }
1257 
1258 void InterpreterMacroAssembler::verify_method_data_pointer() {
1259   assert(ProfileInterpreter, "must be profiling interpreter");
1260 #ifdef ASSERT
1261   Label verify_continue;
1262   test_method_data_pointer(verify_continue);
1263 
1264   // If the mdp is valid, it will point to a DataLayout header which is
1265   // consistent with the bcp. The converse is highly probable also.
1266   lhz(R11_scratch1, in_bytes(DataLayout::bci_offset()), R28_mdx);
1267   ld(R12_scratch2, in_bytes(Method::const_offset()), R19_method);
1268   addi(R11_scratch1, R11_scratch1, in_bytes(ConstMethod::codes_offset()));
1269   add(R11_scratch1, R12_scratch2, R12_scratch2);
1270   cmpd(CR0, R11_scratch1, R14_bcp);
1271   beq(CR0, verify_continue);
1272 
1273   call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::verify_mdp ), R19_method, R14_bcp, R28_mdx);
1274 
1275   bind(verify_continue);
1276 #endif
1277 }
1278 
1279 // Store a value at some constant offset from the method data pointer.
1280 void InterpreterMacroAssembler::set_mdp_data_at(int constant, Register value) {
1281   assert(ProfileInterpreter, "must be profiling interpreter");
1282 
1283   std(value, constant, R28_mdx);
1284 }
1285 
1286 // Increment the value at some constant offset from the method data pointer.
1287 void InterpreterMacroAssembler::increment_mdp_data_at(int constant,
1288                                                       Register counter_addr,
1289                                                       Register Rbumped_count,
1290                                                       bool decrement) {
1291   // Locate the counter at a fixed offset from the mdp:
1292   addi(counter_addr, R28_mdx, constant);
1293   increment_mdp_data_at(counter_addr, Rbumped_count, decrement);
1294 }
1295 
1296 // Increment the value at some non-fixed (reg + constant) offset from
1297 // the method data pointer.
1298 void InterpreterMacroAssembler::increment_mdp_data_at(Register reg,
1299                                                       int constant,
1300                                                       Register scratch,
1301                                                       Register Rbumped_count,
1302                                                       bool decrement) {
1303   // Add the constant to reg to get the offset.
1304   add(scratch, R28_mdx, reg);
1305   // Then calculate the counter address.
1306   addi(scratch, scratch, constant);
1307   increment_mdp_data_at(scratch, Rbumped_count, decrement);
1308 }
1309 
1310 void InterpreterMacroAssembler::increment_mdp_data_at(Register counter_addr,
1311                                                       Register Rbumped_count,
1312                                                       bool decrement) {
1313   assert(ProfileInterpreter, "must be profiling interpreter");
1314 
1315   // Load the counter.
1316   ld(Rbumped_count, 0, counter_addr);
1317 
1318   if (decrement) {
1319     // Decrement the register. Set condition codes.
1320     addi(Rbumped_count, Rbumped_count, - DataLayout::counter_increment);
1321     // Store the decremented counter, if it is still negative.
1322     std(Rbumped_count, 0, counter_addr);
1323     // Note: add/sub overflow check are not ported, since 64 bit
1324     // calculation should never overflow.
1325   } else {
1326     // Increment the register. Set carry flag.
1327     addi(Rbumped_count, Rbumped_count, DataLayout::counter_increment);
1328     // Store the incremented counter.
1329     std(Rbumped_count, 0, counter_addr);
1330   }
1331 }
1332 
1333 // Set a flag value at the current method data pointer position.
1334 void InterpreterMacroAssembler::set_mdp_flag_at(int flag_constant,
1335                                                 Register scratch) {
1336   assert(ProfileInterpreter, "must be profiling interpreter");
1337   // Load the data header.
1338   lbz(scratch, in_bytes(DataLayout::flags_offset()), R28_mdx);
1339   // Set the flag.
1340   ori(scratch, scratch, flag_constant);
1341   // Store the modified header.
1342   stb(scratch, in_bytes(DataLayout::flags_offset()), R28_mdx);
1343 }
1344 
1345 // Test the location at some offset from the method data pointer.
1346 // If it is not equal to value, branch to the not_equal_continue Label.
1347 void InterpreterMacroAssembler::test_mdp_data_at(int offset,
1348                                                  Register value,
1349                                                  Label& not_equal_continue,
1350                                                  Register test_out) {
1351   assert(ProfileInterpreter, "must be profiling interpreter");
1352 
1353   ld(test_out, offset, R28_mdx);
1354   cmpd(CR0,  value, test_out);
1355   bne(CR0, not_equal_continue);
1356 }
1357 
1358 // Update the method data pointer by the displacement located at some fixed
1359 // offset from the method data pointer.
1360 void InterpreterMacroAssembler::update_mdp_by_offset(int offset_of_disp,
1361                                                      Register scratch) {
1362   assert(ProfileInterpreter, "must be profiling interpreter");
1363 
1364   ld(scratch, offset_of_disp, R28_mdx);
1365   add(R28_mdx, scratch, R28_mdx);
1366 }
1367 
1368 // Update the method data pointer by the displacement located at the
1369 // offset (reg + offset_of_disp).
1370 void InterpreterMacroAssembler::update_mdp_by_offset(Register reg,
1371                                                      int offset_of_disp,
1372                                                      Register scratch) {
1373   assert(ProfileInterpreter, "must be profiling interpreter");
1374 
1375   add(scratch, reg, R28_mdx);
1376   ld(scratch, offset_of_disp, scratch);
1377   add(R28_mdx, scratch, R28_mdx);
1378 }
1379 
1380 // Update the method data pointer by a simple constant displacement.
1381 void InterpreterMacroAssembler::update_mdp_by_constant(int constant) {
1382   assert(ProfileInterpreter, "must be profiling interpreter");
1383   addi(R28_mdx, R28_mdx, constant);
1384 }
1385 
1386 // Update the method data pointer for a _ret bytecode whose target
1387 // was not among our cached targets.
1388 void InterpreterMacroAssembler::update_mdp_for_ret(TosState state,
1389                                                    Register return_bci) {
1390   assert(ProfileInterpreter, "must be profiling interpreter");
1391 
1392   push(state);
1393   assert(return_bci->is_nonvolatile(), "need to protect return_bci");
1394   call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::update_mdp_for_ret), return_bci);
1395   pop(state);
1396 }
1397 
1398 // Increments the backedge counter.
1399 // Returns backedge counter + invocation counter in Rdst.
1400 void InterpreterMacroAssembler::increment_backedge_counter(const Register Rcounters, const Register Rdst,
1401                                                            const Register Rtmp1, Register Rscratch) {
1402   assert(UseCompiler, "incrementing must be useful");
1403   assert_different_registers(Rdst, Rtmp1);
1404   const Register invocation_counter = Rtmp1;
1405   const Register counter = Rdst;
1406   // TODO: PPC port: assert(4 == InvocationCounter::sz_counter(), "unexpected field size.");
1407 
1408   // Load backedge counter.
1409   lwz(counter, in_bytes(MethodCounters::backedge_counter_offset()) +
1410                in_bytes(InvocationCounter::counter_offset()), Rcounters);
1411   // Load invocation counter.
1412   lwz(invocation_counter, in_bytes(MethodCounters::invocation_counter_offset()) +
1413                           in_bytes(InvocationCounter::counter_offset()), Rcounters);
1414 
1415   // Add the delta to the backedge counter.
1416   addi(counter, counter, InvocationCounter::count_increment);
1417 
1418   // Mask the invocation counter.
1419   andi(invocation_counter, invocation_counter, InvocationCounter::count_mask_value);
1420 
1421   // Store new counter value.
1422   stw(counter, in_bytes(MethodCounters::backedge_counter_offset()) +
1423                in_bytes(InvocationCounter::counter_offset()), Rcounters);
1424   // Return invocation counter + backedge counter.
1425   add(counter, counter, invocation_counter);
1426 }
1427 
1428 // Count a taken branch in the bytecodes.
1429 void InterpreterMacroAssembler::profile_taken_branch(Register scratch, Register bumped_count) {
1430   if (ProfileInterpreter) {
1431     Label profile_continue;
1432 
1433     // If no method data exists, go to profile_continue.
1434     test_method_data_pointer(profile_continue);
1435 
1436     // We are taking a branch. Increment the taken count.
1437     increment_mdp_data_at(in_bytes(JumpData::taken_offset()), scratch, bumped_count);
1438 
1439     // The method data pointer needs to be updated to reflect the new target.
1440     update_mdp_by_offset(in_bytes(JumpData::displacement_offset()), scratch);
1441     bind (profile_continue);
1442   }
1443 }
1444 
1445 // Count a not-taken branch in the bytecodes.
1446 void InterpreterMacroAssembler::profile_not_taken_branch(Register scratch1, Register scratch2) {
1447   if (ProfileInterpreter) {
1448     Label profile_continue;
1449 
1450     // If no method data exists, go to profile_continue.
1451     test_method_data_pointer(profile_continue);
1452 
1453     // We are taking a branch. Increment the not taken count.
1454     increment_mdp_data_at(in_bytes(BranchData::not_taken_offset()), scratch1, scratch2);
1455 
1456     // The method data pointer needs to be updated to correspond to the
1457     // next bytecode.
1458     update_mdp_by_constant(in_bytes(BranchData::branch_data_size()));
1459     bind (profile_continue);
1460   }
1461 }
1462 
1463 // Count a non-virtual call in the bytecodes.
1464 void InterpreterMacroAssembler::profile_call(Register scratch1, Register scratch2) {
1465   if (ProfileInterpreter) {
1466     Label profile_continue;
1467 
1468     // If no method data exists, go to profile_continue.
1469     test_method_data_pointer(profile_continue);
1470 
1471     // We are making a call. Increment the count.
1472     increment_mdp_data_at(in_bytes(CounterData::count_offset()), scratch1, scratch2);
1473 
1474     // The method data pointer needs to be updated to reflect the new target.
1475     update_mdp_by_constant(in_bytes(CounterData::counter_data_size()));
1476     bind (profile_continue);
1477   }
1478 }
1479 
1480 // Count a final call in the bytecodes.
1481 void InterpreterMacroAssembler::profile_final_call(Register scratch1, Register scratch2) {
1482   if (ProfileInterpreter) {
1483     Label profile_continue;
1484 
1485     // If no method data exists, go to profile_continue.
1486     test_method_data_pointer(profile_continue);
1487 
1488     // We are making a call. Increment the count.
1489     increment_mdp_data_at(in_bytes(CounterData::count_offset()), scratch1, scratch2);
1490 
1491     // The method data pointer needs to be updated to reflect the new target.
1492     update_mdp_by_constant(in_bytes(VirtualCallData::virtual_call_data_size()));
1493     bind (profile_continue);
1494   }
1495 }
1496 
1497 // Count a virtual call in the bytecodes.
1498 void InterpreterMacroAssembler::profile_virtual_call(Register Rreceiver,
1499                                                      Register Rscratch1,
1500                                                      Register Rscratch2,
1501                                                      bool receiver_can_be_null) {
1502   if (!ProfileInterpreter) { return; }
1503   Label profile_continue;
1504 
1505   // If no method data exists, go to profile_continue.
1506   test_method_data_pointer(profile_continue);
1507 
1508   Label skip_receiver_profile;
1509   if (receiver_can_be_null) {
1510     Label not_null;
1511     cmpdi(CR0, Rreceiver, 0);
1512     bne(CR0, not_null);
1513     // We are making a call. Increment the count for null receiver.
1514     increment_mdp_data_at(in_bytes(CounterData::count_offset()), Rscratch1, Rscratch2);
1515     b(skip_receiver_profile);
1516     bind(not_null);
1517   }
1518 
1519   // Record the receiver type.
1520   record_klass_in_profile(Rreceiver, Rscratch1, Rscratch2);
1521   bind(skip_receiver_profile);
1522 
1523   // The method data pointer needs to be updated to reflect the new target.
1524   update_mdp_by_constant(in_bytes(VirtualCallData::virtual_call_data_size()));
1525   bind (profile_continue);
1526 }
1527 
1528 void InterpreterMacroAssembler::profile_typecheck(Register Rklass, Register Rscratch1, Register Rscratch2) {
1529   if (ProfileInterpreter) {
1530     Label profile_continue;
1531 
1532     // If no method data exists, go to profile_continue.
1533     test_method_data_pointer(profile_continue);
1534 
1535     int mdp_delta = in_bytes(BitData::bit_data_size());
1536     if (TypeProfileCasts) {
1537       mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size());
1538 
1539       // Record the object type.
1540       record_klass_in_profile(Rklass, Rscratch1, Rscratch2);
1541     }
1542 
1543     // The method data pointer needs to be updated.
1544     update_mdp_by_constant(mdp_delta);
1545 
1546     bind (profile_continue);
1547   }
1548 }
1549 
1550 // Count a ret in the bytecodes.
1551 void InterpreterMacroAssembler::profile_ret(TosState state, Register return_bci,
1552                                             Register scratch1, Register scratch2) {
1553   if (ProfileInterpreter) {
1554     Label profile_continue;
1555     uint row;
1556 
1557     // If no method data exists, go to profile_continue.
1558     test_method_data_pointer(profile_continue);
1559 
1560     // Update the total ret count.
1561     increment_mdp_data_at(in_bytes(CounterData::count_offset()), scratch1, scratch2 );
1562 
1563     for (row = 0; row < RetData::row_limit(); row++) {
1564       Label next_test;
1565 
1566       // See if return_bci is equal to bci[n]:
1567       test_mdp_data_at(in_bytes(RetData::bci_offset(row)), return_bci, next_test, scratch1);
1568 
1569       // return_bci is equal to bci[n]. Increment the count.
1570       increment_mdp_data_at(in_bytes(RetData::bci_count_offset(row)), scratch1, scratch2);
1571 
1572       // The method data pointer needs to be updated to reflect the new target.
1573       update_mdp_by_offset(in_bytes(RetData::bci_displacement_offset(row)), scratch1);
1574       b(profile_continue);
1575       bind(next_test);
1576     }
1577 
1578     update_mdp_for_ret(state, return_bci);
1579 
1580     bind (profile_continue);
1581   }
1582 }
1583 
1584 // Count the default case of a switch construct.
1585 void InterpreterMacroAssembler::profile_switch_default(Register scratch1,  Register scratch2) {
1586   if (ProfileInterpreter) {
1587     Label profile_continue;
1588 
1589     // If no method data exists, go to profile_continue.
1590     test_method_data_pointer(profile_continue);
1591 
1592     // Update the default case count
1593     increment_mdp_data_at(in_bytes(MultiBranchData::default_count_offset()),
1594                           scratch1, scratch2);
1595 
1596     // The method data pointer needs to be updated.
1597     update_mdp_by_offset(in_bytes(MultiBranchData::default_displacement_offset()),
1598                          scratch1);
1599 
1600     bind (profile_continue);
1601   }
1602 }
1603 
1604 // Count the index'th case of a switch construct.
1605 void InterpreterMacroAssembler::profile_switch_case(Register index,
1606                                                     Register scratch1,
1607                                                     Register scratch2,
1608                                                     Register scratch3) {
1609   if (ProfileInterpreter) {
1610     assert_different_registers(index, scratch1, scratch2, scratch3);
1611     Label profile_continue;
1612 
1613     // If no method data exists, go to profile_continue.
1614     test_method_data_pointer(profile_continue);
1615 
1616     // Build the base (index * per_case_size_in_bytes()) + case_array_offset_in_bytes().
1617     li(scratch3, in_bytes(MultiBranchData::case_array_offset()));
1618 
1619     assert (in_bytes(MultiBranchData::per_case_size()) == 16, "so that shladd works");
1620     sldi(scratch1, index, exact_log2(in_bytes(MultiBranchData::per_case_size())));
1621     add(scratch1, scratch1, scratch3);
1622 
1623     // Update the case count.
1624     increment_mdp_data_at(scratch1, in_bytes(MultiBranchData::relative_count_offset()), scratch2, scratch3);
1625 
1626     // The method data pointer needs to be updated.
1627     update_mdp_by_offset(scratch1, in_bytes(MultiBranchData::relative_displacement_offset()), scratch2);
1628 
1629     bind (profile_continue);
1630   }
1631 }
1632 
1633 void InterpreterMacroAssembler::profile_null_seen(Register Rscratch1, Register Rscratch2) {
1634   if (ProfileInterpreter) {
1635     assert_different_registers(Rscratch1, Rscratch2);
1636     Label profile_continue;
1637 
1638     // If no method data exists, go to profile_continue.
1639     test_method_data_pointer(profile_continue);
1640 
1641     set_mdp_flag_at(BitData::null_seen_byte_constant(), Rscratch1);
1642 
1643     // The method data pointer needs to be updated.
1644     int mdp_delta = in_bytes(BitData::bit_data_size());
1645     if (TypeProfileCasts) {
1646       mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size());
1647     }
1648     update_mdp_by_constant(mdp_delta);
1649 
1650     bind (profile_continue);
1651   }
1652 }
1653 
1654 void InterpreterMacroAssembler::record_klass_in_profile(Register Rreceiver,
1655                                                         Register Rscratch1, Register Rscratch2) {
1656   assert(ProfileInterpreter, "must be profiling");
1657   assert_different_registers(Rreceiver, Rscratch1, Rscratch2);
1658 
1659   Label done;
1660   record_klass_in_profile_helper(Rreceiver, Rscratch1, Rscratch2, 0, done);
1661   bind (done);
1662 }
1663 
1664 void InterpreterMacroAssembler::record_klass_in_profile_helper(
1665                                         Register receiver, Register scratch1, Register scratch2,
1666                                         int start_row, Label& done) {
1667   if (TypeProfileWidth == 0) {
1668     increment_mdp_data_at(in_bytes(CounterData::count_offset()), scratch1, scratch2);
1669     return;
1670   }
1671 
1672   int last_row = VirtualCallData::row_limit() - 1;
1673   assert(start_row <= last_row, "must be work left to do");
1674   // Test this row for both the receiver and for null.
1675   // Take any of three different outcomes:
1676   //   1. found receiver => increment count and goto done
1677   //   2. found null => keep looking for case 1, maybe allocate this cell
1678   //   3. found something else => keep looking for cases 1 and 2
1679   // Case 3 is handled by a recursive call.
1680   for (int row = start_row; row <= last_row; row++) {
1681     Label next_test;
1682     bool test_for_null_also = (row == start_row);
1683 
1684     // See if the receiver is receiver[n].
1685     int recvr_offset = in_bytes(VirtualCallData::receiver_offset(row));
1686     test_mdp_data_at(recvr_offset, receiver, next_test, scratch1);
1687     // delayed()->tst(scratch);
1688 
1689     // The receiver is receiver[n]. Increment count[n].
1690     int count_offset = in_bytes(VirtualCallData::receiver_count_offset(row));
1691     increment_mdp_data_at(count_offset, scratch1, scratch2);
1692     b(done);
1693     bind(next_test);
1694 
1695     if (test_for_null_also) {
1696       Label found_null;
1697       // Failed the equality check on receiver[n]... Test for null.
1698       if (start_row == last_row) {
1699         // The only thing left to do is handle the null case.
1700         // Scratch1 contains test_out from test_mdp_data_at.
1701         cmpdi(CR0, scratch1, 0);
1702         beq(CR0, found_null);
1703         // Receiver did not match any saved receiver and there is no empty row for it.
1704         // Increment total counter to indicate polymorphic case.
1705         increment_mdp_data_at(in_bytes(CounterData::count_offset()), scratch1, scratch2);
1706         b(done);
1707         bind(found_null);
1708         break;
1709       }
1710       // Since null is rare, make it be the branch-taken case.
1711       cmpdi(CR0, scratch1, 0);
1712       beq(CR0, found_null);
1713 
1714       // Put all the "Case 3" tests here.
1715       record_klass_in_profile_helper(receiver, scratch1, scratch2, start_row + 1, done);
1716 
1717       // Found a null. Keep searching for a matching receiver,
1718       // but remember that this is an empty (unused) slot.
1719       bind(found_null);
1720     }
1721   }
1722 
1723   // In the fall-through case, we found no matching receiver, but we
1724   // observed the receiver[start_row] is null.
1725 
1726   // Fill in the receiver field and increment the count.
1727   int recvr_offset = in_bytes(VirtualCallData::receiver_offset(start_row));
1728   set_mdp_data_at(recvr_offset, receiver);
1729   int count_offset = in_bytes(VirtualCallData::receiver_count_offset(start_row));
1730   li(scratch1, DataLayout::counter_increment);
1731   set_mdp_data_at(count_offset, scratch1);
1732   if (start_row > 0) {
1733     b(done);
1734   }
1735 }
1736 
1737 // Argument and return type profilig.
1738 // kills: tmp, tmp2, R0, CR0, CR1
1739 void InterpreterMacroAssembler::profile_obj_type(Register obj, Register mdo_addr_base,
1740                                                  RegisterOrConstant mdo_addr_offs,
1741                                                  Register tmp, Register tmp2) {
1742   Label do_nothing, do_update;
1743 
1744   // tmp2 = obj is allowed
1745   assert_different_registers(obj, mdo_addr_base, tmp, R0);
1746   assert_different_registers(tmp2, mdo_addr_base, tmp, R0);
1747   const Register klass = tmp2;
1748 
1749   verify_oop(obj);
1750 
1751   ld(tmp, mdo_addr_offs, mdo_addr_base);
1752 
1753   // Set null_seen if obj is 0.
1754   cmpdi(CR0, obj, 0);
1755   ori(R0, tmp, TypeEntries::null_seen);
1756   beq(CR0, do_update);
1757 
1758   load_klass(klass, obj);
1759 
1760   clrrdi(R0, tmp, exact_log2(-TypeEntries::type_klass_mask));
1761   // Basically same as andi(R0, tmp, TypeEntries::type_klass_mask);
1762   cmpd(CR1, R0, klass);
1763   // Klass seen before, nothing to do (regardless of unknown bit).
1764   //beq(CR1, do_nothing);
1765 
1766   andi_(R0, tmp, TypeEntries::type_unknown);
1767   // Already unknown. Nothing to do anymore.
1768   //bne(CR0, do_nothing);
1769   crorc(CR0, Assembler::equal, CR1, Assembler::equal); // cr0 eq = cr1 eq or cr0 ne
1770   beq(CR0, do_nothing);
1771 
1772   clrrdi_(R0, tmp, exact_log2(-TypeEntries::type_mask));
1773   orr(R0, klass, tmp); // Combine klass and null_seen bit (only used if (tmp & type_mask)==0).
1774   beq(CR0, do_update); // First time here. Set profile type.
1775 
1776   // Different than before. Cannot keep accurate profile.
1777   ori(R0, tmp, TypeEntries::type_unknown);
1778 
1779   bind(do_update);
1780   // update profile
1781   std(R0, mdo_addr_offs, mdo_addr_base);
1782 
1783   align(32, 12);
1784   bind(do_nothing);
1785 }
1786 
1787 void InterpreterMacroAssembler::profile_arguments_type(Register callee,
1788                                                        Register tmp1, Register tmp2,
1789                                                        bool is_virtual) {
1790   if (!ProfileInterpreter) {
1791     return;
1792   }
1793 
1794   assert_different_registers(callee, tmp1, tmp2, R28_mdx);
1795 
1796   if (MethodData::profile_arguments() || MethodData::profile_return()) {
1797     Label profile_continue;
1798 
1799     test_method_data_pointer(profile_continue);
1800 
1801     int off_to_start = is_virtual ?
1802       in_bytes(VirtualCallData::virtual_call_data_size()) : in_bytes(CounterData::counter_data_size());
1803 
1804     lbz(tmp1, in_bytes(DataLayout::tag_offset()) - off_to_start, R28_mdx);
1805     cmpwi(CR0, tmp1, is_virtual ? DataLayout::virtual_call_type_data_tag : DataLayout::call_type_data_tag);
1806     bne(CR0, profile_continue);
1807 
1808     if (MethodData::profile_arguments()) {
1809       Label done;
1810       int off_to_args = in_bytes(TypeEntriesAtCall::args_data_offset());
1811       addi(R28_mdx, R28_mdx, off_to_args);
1812 
1813       for (int i = 0; i < TypeProfileArgsLimit; i++) {
1814         if (i > 0 || MethodData::profile_return()) {
1815           // If return value type is profiled we may have no argument to profile.
1816           ld(tmp1, in_bytes(TypeEntriesAtCall::cell_count_offset())-off_to_args, R28_mdx);
1817           cmpdi(CR0, tmp1, (i+1)*TypeStackSlotEntries::per_arg_count());
1818           addi(tmp1, tmp1, -i*TypeStackSlotEntries::per_arg_count());
1819           blt(CR0, done);
1820         }
1821         ld(tmp1, in_bytes(Method::const_offset()), callee);
1822         lhz(tmp1, in_bytes(ConstMethod::size_of_parameters_offset()), tmp1);
1823         // Stack offset o (zero based) from the start of the argument
1824         // list, for n arguments translates into offset n - o - 1 from
1825         // the end of the argument list. But there's an extra slot at
1826         // the top of the stack. So the offset is n - o from Lesp.
1827         ld(tmp2, in_bytes(TypeEntriesAtCall::stack_slot_offset(i))-off_to_args, R28_mdx);
1828         subf(tmp1, tmp2, tmp1);
1829 
1830         sldi(tmp1, tmp1, Interpreter::logStackElementSize);
1831         ldx(tmp1, tmp1, R15_esp);
1832 
1833         profile_obj_type(tmp1, R28_mdx, in_bytes(TypeEntriesAtCall::argument_type_offset(i))-off_to_args, tmp2, tmp1);
1834 
1835         int to_add = in_bytes(TypeStackSlotEntries::per_arg_size());
1836         addi(R28_mdx, R28_mdx, to_add);
1837         off_to_args += to_add;
1838       }
1839 
1840       if (MethodData::profile_return()) {
1841         ld(tmp1, in_bytes(TypeEntriesAtCall::cell_count_offset())-off_to_args, R28_mdx);
1842         addi(tmp1, tmp1, -TypeProfileArgsLimit*TypeStackSlotEntries::per_arg_count());
1843       }
1844 
1845       bind(done);
1846 
1847       if (MethodData::profile_return()) {
1848         // We're right after the type profile for the last
1849         // argument. tmp1 is the number of cells left in the
1850         // CallTypeData/VirtualCallTypeData to reach its end. Non null
1851         // if there's a return to profile.
1852         assert(SingleTypeEntry::static_cell_count() < TypeStackSlotEntries::per_arg_count(),
1853                "can't move past ret type");
1854         sldi(tmp1, tmp1, exact_log2(DataLayout::cell_size));
1855         add(R28_mdx, tmp1, R28_mdx);
1856       }
1857     } else {
1858       assert(MethodData::profile_return(), "either profile call args or call ret");
1859       update_mdp_by_constant(in_bytes(TypeEntriesAtCall::return_only_size()));
1860     }
1861 
1862     // Mdp points right after the end of the
1863     // CallTypeData/VirtualCallTypeData, right after the cells for the
1864     // return value type if there's one.
1865     align(32, 12);
1866     bind(profile_continue);
1867   }
1868 }
1869 
1870 void InterpreterMacroAssembler::profile_return_type(Register ret, Register tmp1, Register tmp2) {
1871   assert_different_registers(ret, tmp1, tmp2);
1872   if (ProfileInterpreter && MethodData::profile_return()) {
1873     Label profile_continue;
1874 
1875     test_method_data_pointer(profile_continue);
1876 
1877     if (MethodData::profile_return_jsr292_only()) {
1878       // If we don't profile all invoke bytecodes we must make sure
1879       // it's a bytecode we indeed profile. We can't go back to the
1880       // beginning of the ProfileData we intend to update to check its
1881       // type because we're right after it and we don't known its
1882       // length.
1883       lbz(tmp1, 0, R14_bcp);
1884       lbz(tmp2, in_bytes(Method::intrinsic_id_offset()), R19_method);
1885       cmpwi(CR0, tmp1, Bytecodes::_invokedynamic);
1886       cmpwi(CR1, tmp1, Bytecodes::_invokehandle);
1887       cror(CR0, Assembler::equal, CR1, Assembler::equal);
1888       cmpwi(CR1, tmp2, static_cast<int>(vmIntrinsics::_compiledLambdaForm));
1889       cror(CR0, Assembler::equal, CR1, Assembler::equal);
1890       bne(CR0, profile_continue);
1891     }
1892 
1893     profile_obj_type(ret, R28_mdx, -in_bytes(SingleTypeEntry::size()), tmp1, tmp2);
1894 
1895     align(32, 12);
1896     bind(profile_continue);
1897   }
1898 }
1899 
1900 void InterpreterMacroAssembler::profile_parameters_type(Register tmp1, Register tmp2,
1901                                                         Register tmp3, Register tmp4) {
1902   if (ProfileInterpreter && MethodData::profile_parameters()) {
1903     Label profile_continue, done;
1904 
1905     test_method_data_pointer(profile_continue);
1906 
1907     // Load the offset of the area within the MDO used for
1908     // parameters. If it's negative we're not profiling any parameters.
1909     lwz(tmp1, in_bytes(MethodData::parameters_type_data_di_offset()) - in_bytes(MethodData::data_offset()), R28_mdx);
1910     cmpwi(CR0, tmp1, 0);
1911     blt(CR0, profile_continue);
1912 
1913     // Compute a pointer to the area for parameters from the offset
1914     // and move the pointer to the slot for the last
1915     // parameters. Collect profiling from last parameter down.
1916     // mdo start + parameters offset + array length - 1
1917 
1918     // Pointer to the parameter area in the MDO.
1919     const Register mdp = tmp1;
1920     add(mdp, tmp1, R28_mdx);
1921 
1922     // Offset of the current profile entry to update.
1923     const Register entry_offset = tmp2;
1924     // entry_offset = array len in number of cells
1925     ld(entry_offset, in_bytes(ArrayData::array_len_offset()), mdp);
1926 
1927     int off_base = in_bytes(ParametersTypeData::stack_slot_offset(0));
1928     assert(off_base % DataLayout::cell_size == 0, "should be a number of cells");
1929 
1930     // entry_offset (number of cells)  = array len - size of 1 entry + offset of the stack slot field
1931     addi(entry_offset, entry_offset, -TypeStackSlotEntries::per_arg_count() + (off_base / DataLayout::cell_size));
1932     // entry_offset in bytes
1933     sldi(entry_offset, entry_offset, exact_log2(DataLayout::cell_size));
1934 
1935     Label loop;
1936     align(32, 12);
1937     bind(loop);
1938 
1939     // Load offset on the stack from the slot for this parameter.
1940     ld(tmp3, entry_offset, mdp);
1941     sldi(tmp3, tmp3, Interpreter::logStackElementSize);
1942     neg(tmp3, tmp3);
1943     // Read the parameter from the local area.
1944     ldx(tmp3, tmp3, R18_locals);
1945 
1946     // Make entry_offset now point to the type field for this parameter.
1947     int type_base = in_bytes(ParametersTypeData::type_offset(0));
1948     assert(type_base > off_base, "unexpected");
1949     addi(entry_offset, entry_offset, type_base - off_base);
1950 
1951     // Profile the parameter.
1952     profile_obj_type(tmp3, mdp, entry_offset, tmp4, tmp3);
1953 
1954     // Go to next parameter.
1955     int delta = TypeStackSlotEntries::per_arg_count() * DataLayout::cell_size + (type_base - off_base);
1956     cmpdi(CR0, entry_offset, off_base + delta);
1957     addi(entry_offset, entry_offset, -delta);
1958     bge(CR0, loop);
1959 
1960     align(32, 12);
1961     bind(profile_continue);
1962   }
1963 }
1964 
1965 // Add a monitor (see frame_ppc.hpp).
1966 void InterpreterMacroAssembler::add_monitor_to_stack(bool stack_is_empty, Register Rtemp1, Register Rtemp2) {
1967 
1968   // Very-local scratch registers.
1969   const Register esp  = Rtemp1;
1970   const Register slot = Rtemp2;
1971 
1972   // Extracted monitor_size.
1973   int monitor_size = frame::interpreter_frame_monitor_size_in_bytes();
1974   assert(Assembler::is_aligned((unsigned int)monitor_size,
1975                                (unsigned int)frame::alignment_in_bytes),
1976          "size of a monitor must respect alignment of SP");
1977 
1978   resize_frame(-monitor_size, /*temp*/esp); // Allocate space for new monitor
1979   subf(Rtemp2, esp, R1_SP); // esp contains fp
1980   sradi(Rtemp2, Rtemp2, Interpreter::logStackElementSize);
1981   // Store relativized top_frame_sp
1982   std(Rtemp2, _ijava_state_neg(top_frame_sp), esp); // esp contains fp
1983 
1984   // Shuffle expression stack down. Recall that stack_base points
1985   // just above the new expression stack bottom. Old_tos and new_tos
1986   // are used to scan thru the old and new expression stacks.
1987   if (!stack_is_empty) {
1988     Label copy_slot, copy_slot_finished;
1989     const Register n_slots = slot;
1990 
1991     addi(esp, R15_esp, Interpreter::stackElementSize); // Point to first element (pre-pushed stack).
1992     subf(n_slots, esp, R26_monitor);
1993     srdi_(n_slots, n_slots, LogBytesPerWord);          // Compute number of slots to copy.
1994     assert(LogBytesPerWord == 3, "conflicts assembler instructions");
1995     beq(CR0, copy_slot_finished);                     // Nothing to copy.
1996 
1997     mtctr(n_slots);
1998 
1999     // loop
2000     bind(copy_slot);
2001     ld(slot, 0, esp);              // Move expression stack down.
2002     std(slot, -monitor_size, esp); // distance = monitor_size
2003     addi(esp, esp, BytesPerWord);
2004     bdnz(copy_slot);
2005 
2006     bind(copy_slot_finished);
2007   }
2008 
2009   addi(R15_esp, R15_esp, -monitor_size);
2010   addi(R26_monitor, R26_monitor, -monitor_size);
2011 
2012   // Restart interpreter
2013 }
2014 
2015 // ============================================================================
2016 // Java locals access
2017 
2018 // Load a local variable at index in Rindex into register Rdst_value.
2019 // Also puts address of local into Rdst_address as a service.
2020 // Kills:
2021 //   - Rdst_value
2022 //   - Rdst_address
2023 void InterpreterMacroAssembler::load_local_int(Register Rdst_value, Register Rdst_address, Register Rindex) {
2024   sldi(Rdst_address, Rindex, Interpreter::logStackElementSize);
2025   subf(Rdst_address, Rdst_address, R18_locals);
2026   lwz(Rdst_value, 0, Rdst_address);
2027 }
2028 
2029 // Load a local variable at index in Rindex into register Rdst_value.
2030 // Also puts address of local into Rdst_address as a service.
2031 // Kills:
2032 //   - Rdst_value
2033 //   - Rdst_address
2034 void InterpreterMacroAssembler::load_local_long(Register Rdst_value, Register Rdst_address, Register Rindex) {
2035   sldi(Rdst_address, Rindex, Interpreter::logStackElementSize);
2036   subf(Rdst_address, Rdst_address, R18_locals);
2037   ld(Rdst_value, -8, Rdst_address);
2038 }
2039 
2040 // Load a local variable at index in Rindex into register Rdst_value.
2041 // Also puts address of local into Rdst_address as a service.
2042 // Input:
2043 //   - Rindex:      slot nr of local variable
2044 // Kills:
2045 //   - Rdst_value
2046 //   - Rdst_address
2047 void InterpreterMacroAssembler::load_local_ptr(Register Rdst_value,
2048                                                Register Rdst_address,
2049                                                Register Rindex) {
2050   sldi(Rdst_address, Rindex, Interpreter::logStackElementSize);
2051   subf(Rdst_address, Rdst_address, R18_locals);
2052   ld(Rdst_value, 0, Rdst_address);
2053 }
2054 
2055 // Load a local variable at index in Rindex into register Rdst_value.
2056 // Also puts address of local into Rdst_address as a service.
2057 // Kills:
2058 //   - Rdst_value
2059 //   - Rdst_address
2060 void InterpreterMacroAssembler::load_local_float(FloatRegister Rdst_value,
2061                                                  Register Rdst_address,
2062                                                  Register Rindex) {
2063   sldi(Rdst_address, Rindex, Interpreter::logStackElementSize);
2064   subf(Rdst_address, Rdst_address, R18_locals);
2065   lfs(Rdst_value, 0, Rdst_address);
2066 }
2067 
2068 // Load a local variable at index in Rindex into register Rdst_value.
2069 // Also puts address of local into Rdst_address as a service.
2070 // Kills:
2071 //   - Rdst_value
2072 //   - Rdst_address
2073 void InterpreterMacroAssembler::load_local_double(FloatRegister Rdst_value,
2074                                                   Register Rdst_address,
2075                                                   Register Rindex) {
2076   sldi(Rdst_address, Rindex, Interpreter::logStackElementSize);
2077   subf(Rdst_address, Rdst_address, R18_locals);
2078   lfd(Rdst_value, -8, Rdst_address);
2079 }
2080 
2081 // Store an int value at local variable slot Rindex.
2082 // Kills:
2083 //   - Rindex
2084 void InterpreterMacroAssembler::store_local_int(Register Rvalue, Register Rindex) {
2085   sldi(Rindex, Rindex, Interpreter::logStackElementSize);
2086   subf(Rindex, Rindex, R18_locals);
2087   stw(Rvalue, 0, Rindex);
2088 }
2089 
2090 // Store a long value at local variable slot Rindex.
2091 // Kills:
2092 //   - Rindex
2093 void InterpreterMacroAssembler::store_local_long(Register Rvalue, Register Rindex) {
2094   sldi(Rindex, Rindex, Interpreter::logStackElementSize);
2095   subf(Rindex, Rindex, R18_locals);
2096   std(Rvalue, -8, Rindex);
2097 }
2098 
2099 // Store an oop value at local variable slot Rindex.
2100 // Kills:
2101 //   - Rindex
2102 void InterpreterMacroAssembler::store_local_ptr(Register Rvalue, Register Rindex) {
2103   sldi(Rindex, Rindex, Interpreter::logStackElementSize);
2104   subf(Rindex, Rindex, R18_locals);
2105   std(Rvalue, 0, Rindex);
2106 }
2107 
2108 // Store an int value at local variable slot Rindex.
2109 // Kills:
2110 //   - Rindex
2111 void InterpreterMacroAssembler::store_local_float(FloatRegister Rvalue, Register Rindex) {
2112   sldi(Rindex, Rindex, Interpreter::logStackElementSize);
2113   subf(Rindex, Rindex, R18_locals);
2114   stfs(Rvalue, 0, Rindex);
2115 }
2116 
2117 // Store an int value at local variable slot Rindex.
2118 // Kills:
2119 //   - Rindex
2120 void InterpreterMacroAssembler::store_local_double(FloatRegister Rvalue, Register Rindex) {
2121   sldi(Rindex, Rindex, Interpreter::logStackElementSize);
2122   subf(Rindex, Rindex, R18_locals);
2123   stfd(Rvalue, -8, Rindex);
2124 }
2125 
2126 // Read pending exception from thread and jump to interpreter.
2127 // Throw exception entry if one if pending. Fall through otherwise.
2128 void InterpreterMacroAssembler::check_and_forward_exception(Register Rscratch1, Register Rscratch2) {
2129   assert_different_registers(Rscratch1, Rscratch2, R3);
2130   Register Rexception = Rscratch1;
2131   Register Rtmp       = Rscratch2;
2132   Label Ldone;
2133   // Get pending exception oop.
2134   ld(Rexception, thread_(pending_exception));
2135   cmpdi(CR0, Rexception, 0);
2136   beq(CR0, Ldone);
2137   li(Rtmp, 0);
2138   mr_if_needed(R3, Rexception);
2139   std(Rtmp, thread_(pending_exception)); // Clear exception in thread
2140   if (Interpreter::rethrow_exception_entry() != nullptr) {
2141     // Already got entry address.
2142     load_dispatch_table(Rtmp, (address*)Interpreter::rethrow_exception_entry());
2143   } else {
2144     // Dynamically load entry address.
2145     int simm16_rest = load_const_optimized(Rtmp, &Interpreter::_rethrow_exception_entry, R0, true);
2146     ld(Rtmp, simm16_rest, Rtmp);
2147   }
2148   mtctr(Rtmp);
2149   save_interpreter_state(Rtmp);
2150   bctr();
2151 
2152   align(32, 12);
2153   bind(Ldone);
2154 }
2155 
2156 void InterpreterMacroAssembler::call_VM(Register oop_result, address entry_point, bool check_exceptions, Label* last_java_pc) {
2157   save_interpreter_state(R11_scratch1);
2158 
2159   MacroAssembler::call_VM(oop_result, entry_point, false /*check_exceptions*/, last_java_pc);
2160 
2161   restore_interpreter_state(R11_scratch1, /*bcp_and_mdx_only*/ true);
2162 
2163   check_and_handle_popframe(R11_scratch1);
2164   check_and_handle_earlyret(R11_scratch1);
2165   // Now check exceptions manually.
2166   if (check_exceptions) {
2167     check_and_forward_exception(R11_scratch1, R12_scratch2);
2168   }
2169 }
2170 
2171 void InterpreterMacroAssembler::call_VM(Register oop_result, address entry_point,
2172                                         Register arg_1, bool check_exceptions) {
2173   // ARG1 is reserved for the thread.
2174   mr_if_needed(R4_ARG2, arg_1);
2175   call_VM(oop_result, entry_point, check_exceptions);
2176 }
2177 
2178 void InterpreterMacroAssembler::call_VM_preemptable(Register oop_result, address entry_point,
2179                                         Register arg_1, bool check_exceptions) {
2180   if (!Continuations::enabled()) {
2181     call_VM(oop_result, entry_point, arg_1, check_exceptions);
2182     return;
2183   }
2184 
2185   Label resume_pc, not_preempted;
2186 
2187   DEBUG_ONLY(ld(R0, in_bytes(JavaThread::preempt_alternate_return_offset()), R16_thread));
2188   DEBUG_ONLY(cmpdi(CR0, R0, 0));
2189   asm_assert_eq("Should not have alternate return address set");
2190 
2191   // Preserve 2 registers
2192   assert(nonvolatile_accross_vthread_preemtion(R31) && nonvolatile_accross_vthread_preemtion(R22), "");
2193   ld(R3_ARG1, _abi0(callers_sp), R1_SP); // load FP
2194   std(R31, _ijava_state_neg(lresult), R3_ARG1);
2195   std(R22, _ijava_state_neg(fresult), R3_ARG1);
2196 
2197   // We set resume_pc as last java pc. It will be saved if the vthread gets preempted.
2198   // Later execution will continue right there.
2199   mr_if_needed(R4_ARG2, arg_1);
2200   push_cont_fastpath();
2201   call_VM(oop_result, entry_point, false /*check_exceptions*/, &resume_pc /* last_java_pc */);
2202   pop_cont_fastpath();
2203 
2204   // Jump to handler if the call was preempted
2205   ld(R0, in_bytes(JavaThread::preempt_alternate_return_offset()), R16_thread);
2206   cmpdi(CR0, R0, 0);
2207   beq(CR0, not_preempted);
2208   mtlr(R0);
2209   li(R0, 0);
2210   std(R0, in_bytes(JavaThread::preempt_alternate_return_offset()), R16_thread);
2211   blr();
2212 
2213   bind(resume_pc); // Location to resume execution
2214   restore_after_resume(noreg /* fp */);
2215   bind(not_preempted);
2216 }
2217 
2218 void InterpreterMacroAssembler::restore_after_resume(Register fp) {
2219   if (!Continuations::enabled()) return;
2220 
2221   const address resume_adapter = TemplateInterpreter::cont_resume_interpreter_adapter();
2222   add_const_optimized(R31, R29_TOC, MacroAssembler::offset_to_global_toc(resume_adapter));
2223   mtctr(R31);
2224   bctrl();
2225   // Restore registers that are preserved across vthread preemption
2226   assert(nonvolatile_accross_vthread_preemtion(R31) && nonvolatile_accross_vthread_preemtion(R22), "");
2227   ld(R3_ARG1, _abi0(callers_sp), R1_SP); // load FP
2228   ld(R31, _ijava_state_neg(lresult), R3_ARG1);
2229   ld(R22, _ijava_state_neg(fresult), R3_ARG1);
2230 #ifdef ASSERT
2231   // Assert FP is in R11_scratch1 (see generate_cont_resume_interpreter_adapter())
2232   {
2233     Label ok;
2234     ld(R12_scratch2, 0, R1_SP);  // load fp
2235     cmpd(CR0, R12_scratch2, R11_scratch1);
2236     beq(CR0, ok);
2237     stop(FILE_AND_LINE ": FP is expected in R11_scratch1");
2238     bind(ok);
2239   }
2240 #endif
2241   if (fp != noreg && fp != R11_scratch1) {
2242     mr(fp, R11_scratch1);
2243   }
2244 }
2245 
2246 void InterpreterMacroAssembler::call_VM(Register oop_result, address entry_point,
2247                                         Register arg_1, Register arg_2,
2248                                         bool check_exceptions) {
2249   // ARG1 is reserved for the thread.
2250   mr_if_needed(R4_ARG2, arg_1);
2251   assert(arg_2 != R4_ARG2, "smashed argument");
2252   mr_if_needed(R5_ARG3, arg_2);
2253   call_VM(oop_result, entry_point, check_exceptions);
2254 }
2255 
2256 void InterpreterMacroAssembler::call_VM(Register oop_result, address entry_point,
2257                                         Register arg_1, Register arg_2, Register arg_3,
2258                                         bool check_exceptions) {
2259   // ARG1 is reserved for the thread.
2260   mr_if_needed(R4_ARG2, arg_1);
2261   assert(arg_2 != R4_ARG2, "smashed argument");
2262   mr_if_needed(R5_ARG3, arg_2);
2263   assert(arg_3 != R4_ARG2 && arg_3 != R5_ARG3, "smashed argument");
2264   mr_if_needed(R6_ARG4, arg_3);
2265   call_VM(oop_result, entry_point, check_exceptions);
2266 }
2267 
2268 void InterpreterMacroAssembler::save_interpreter_state(Register scratch) {
2269   ld(scratch, 0, R1_SP);
2270   subf(R0, scratch, R15_esp);
2271   sradi(R0, R0, Interpreter::logStackElementSize);
2272   std(R0, _ijava_state_neg(esp), scratch);
2273   std(R14_bcp, _ijava_state_neg(bcp), scratch);
2274   subf(R0, scratch, R26_monitor);
2275   sradi(R0, R0, Interpreter::logStackElementSize);
2276   std(R0, _ijava_state_neg(monitors), scratch);
2277   if (ProfileInterpreter) { std(R28_mdx, _ijava_state_neg(mdx), scratch); }
2278   // Other entries should be unchanged.
2279 }
2280 
2281 void InterpreterMacroAssembler::restore_interpreter_state(Register scratch, bool bcp_and_mdx_only, bool restore_top_frame_sp) {
2282   ld_ptr(scratch, _abi0(callers_sp), R1_SP);   // Load frame pointer.
2283   if (restore_top_frame_sp) {
2284     // After thawing the top frame of a continuation we reach here with frame::java_abi.
2285     // therefore we have to restore top_frame_sp before the assertion below.
2286     assert(!bcp_and_mdx_only, "chose other registers");
2287     Register tfsp = R18_locals;
2288     Register scratch2 = R26_monitor;
2289     ld(tfsp, _ijava_state_neg(top_frame_sp), scratch);
2290     // Derelativize top_frame_sp
2291     sldi(tfsp, tfsp, Interpreter::logStackElementSize);
2292     add(tfsp, tfsp, scratch);
2293     resize_frame_absolute(tfsp, scratch2, R0);
2294   }
2295   ld(R14_bcp, _ijava_state_neg(bcp), scratch); // Changed by VM code (exception).
2296   if (ProfileInterpreter) { ld(R28_mdx, _ijava_state_neg(mdx), scratch); } // Changed by VM code.
2297   if (!bcp_and_mdx_only) {
2298     // Following ones are Metadata.
2299     ld(R19_method, _ijava_state_neg(method), scratch);
2300     ld(R27_constPoolCache, _ijava_state_neg(cpoolCache), scratch);
2301     // Following ones are stack addresses and don't require reload.
2302     // Derelativize esp
2303     ld(R15_esp, _ijava_state_neg(esp), scratch);
2304     sldi(R15_esp, R15_esp, Interpreter::logStackElementSize);
2305     add(R15_esp, R15_esp, scratch);
2306     ld(R18_locals, _ijava_state_neg(locals), scratch);
2307     sldi(R18_locals, R18_locals, Interpreter::logStackElementSize);
2308     add(R18_locals, R18_locals, scratch);
2309     ld(R26_monitor, _ijava_state_neg(monitors), scratch);
2310     // Derelativize monitors
2311     sldi(R26_monitor, R26_monitor, Interpreter::logStackElementSize);
2312     add(R26_monitor, R26_monitor, scratch);
2313   }
2314 #ifdef ASSERT
2315   {
2316     Label Lok;
2317     subf(R0, R1_SP, scratch);
2318     cmpdi(CR0, R0, frame::top_ijava_frame_abi_size + frame::ijava_state_size);
2319     bge(CR0, Lok);
2320     stop("frame too small (restore istate)");
2321     bind(Lok);
2322   }
2323 #endif
2324 }
2325 
2326 void InterpreterMacroAssembler::get_method_counters(Register method,
2327                                                     Register Rcounters,
2328                                                     Label& skip) {
2329   BLOCK_COMMENT("Load and ev. allocate counter object {");
2330   Label has_counters;
2331   ld(Rcounters, in_bytes(Method::method_counters_offset()), method);
2332   cmpdi(CR0, Rcounters, 0);
2333   bne(CR0, has_counters);
2334   call_VM(noreg, CAST_FROM_FN_PTR(address,
2335                                   InterpreterRuntime::build_method_counters), method);
2336   ld(Rcounters, in_bytes(Method::method_counters_offset()), method);
2337   cmpdi(CR0, Rcounters, 0);
2338   beq(CR0, skip); // No MethodCounters, OutOfMemory.
2339   BLOCK_COMMENT("} Load and ev. allocate counter object");
2340 
2341   bind(has_counters);
2342 }
2343 
2344 void InterpreterMacroAssembler::increment_invocation_counter(Register Rcounters,
2345                                                              Register iv_be_count,
2346                                                              Register Rtmp_r0) {
2347   assert(UseCompiler, "incrementing must be useful");
2348   Register invocation_count = iv_be_count;
2349   Register backedge_count   = Rtmp_r0;
2350   int delta = InvocationCounter::count_increment;
2351 
2352   // Load each counter in a register.
2353   //  ld(inv_counter, Rtmp);
2354   //  ld(be_counter, Rtmp2);
2355   int inv_counter_offset = in_bytes(MethodCounters::invocation_counter_offset() +
2356                                     InvocationCounter::counter_offset());
2357   int be_counter_offset  = in_bytes(MethodCounters::backedge_counter_offset() +
2358                                     InvocationCounter::counter_offset());
2359 
2360   BLOCK_COMMENT("Increment profiling counters {");
2361 
2362   // Load the backedge counter.
2363   lwz(backedge_count, be_counter_offset, Rcounters); // is unsigned int
2364   // Mask the backedge counter.
2365   andi(backedge_count, backedge_count, InvocationCounter::count_mask_value);
2366 
2367   // Load the invocation counter.
2368   lwz(invocation_count, inv_counter_offset, Rcounters); // is unsigned int
2369   // Add the delta to the invocation counter and store the result.
2370   addi(invocation_count, invocation_count, delta);
2371   // Store value.
2372   stw(invocation_count, inv_counter_offset, Rcounters);
2373 
2374   // Add invocation counter + backedge counter.
2375   add(iv_be_count, backedge_count, invocation_count);
2376 
2377   // Note that this macro must leave the backedge_count + invocation_count in
2378   // register iv_be_count!
2379   BLOCK_COMMENT("} Increment profiling counters");
2380 }
2381 
2382 void InterpreterMacroAssembler::verify_oop(Register reg, TosState state) {
2383   if (state == atos) { MacroAssembler::verify_oop(reg, FILE_AND_LINE); }
2384 }
2385 
2386 // Local helper function for the verify_oop_or_return_address macro.
2387 static bool verify_return_address(Method* m, int bci) {
2388 #ifndef PRODUCT
2389   address pc = (address)(m->constMethod()) + in_bytes(ConstMethod::codes_offset()) + bci;
2390   // Assume it is a valid return address if it is inside m and is preceded by a jsr.
2391   if (!m->contains(pc))                                            return false;
2392   address jsr_pc;
2393   jsr_pc = pc - Bytecodes::length_for(Bytecodes::_jsr);
2394   if (*jsr_pc == Bytecodes::_jsr   && jsr_pc >= m->code_base())    return true;
2395   jsr_pc = pc - Bytecodes::length_for(Bytecodes::_jsr_w);
2396   if (*jsr_pc == Bytecodes::_jsr_w && jsr_pc >= m->code_base())    return true;
2397 #endif // PRODUCT
2398   return false;
2399 }
2400 
2401 void InterpreterMacroAssembler::verify_oop_or_return_address(Register reg, Register Rtmp) {
2402   if (!VerifyOops) return;
2403 
2404   // The VM documentation for the astore[_wide] bytecode allows
2405   // the TOS to be not only an oop but also a return address.
2406   Label test;
2407   Label skip;
2408   // See if it is an address (in the current method):
2409 
2410   const int log2_bytecode_size_limit = 16;
2411   srdi_(Rtmp, reg, log2_bytecode_size_limit);
2412   bne(CR0, test);
2413 
2414   address fd = CAST_FROM_FN_PTR(address, verify_return_address);
2415   const int nbytes_save = MacroAssembler::num_volatile_regs * 8;
2416   save_volatile_gprs(R1_SP, -nbytes_save); // except R0
2417   save_LR_CR(Rtmp); // Save in old frame.
2418   push_frame_reg_args(nbytes_save, Rtmp);
2419 
2420   load_const_optimized(Rtmp, fd, R0);
2421   mr_if_needed(R4_ARG2, reg);
2422   mr(R3_ARG1, R19_method);
2423   call_c(Rtmp); // call C
2424 
2425   pop_frame();
2426   restore_LR_CR(Rtmp);
2427   restore_volatile_gprs(R1_SP, -nbytes_save); // except R0
2428   b(skip);
2429 
2430   // Perform a more elaborate out-of-line call.
2431   // Not an address; verify it:
2432   bind(test);
2433   verify_oop(reg);
2434   bind(skip);
2435 }
2436 
2437 // Inline assembly for:
2438 //
2439 // if (thread is in interp_only_mode) {
2440 //   InterpreterRuntime::post_method_entry();
2441 // }
2442 // if (*jvmpi::event_flags_array_at_addr(JVMPI_EVENT_METHOD_ENTRY ) ||
2443 //     *jvmpi::event_flags_array_at_addr(JVMPI_EVENT_METHOD_ENTRY2)   ) {
2444 //   SharedRuntime::jvmpi_method_entry(method, receiver);
2445 // }
2446 void InterpreterMacroAssembler::notify_method_entry() {
2447   // JVMTI
2448   // Whenever JVMTI puts a thread in interp_only_mode, method
2449   // entry/exit events are sent for that thread to track stack
2450   // depth. If it is possible to enter interp_only_mode we add
2451   // the code to check if the event should be sent.
2452   if (JvmtiExport::can_post_interpreter_events()) {
2453     Label jvmti_post_done;
2454 
2455     lwz(R0, in_bytes(JavaThread::interp_only_mode_offset()), R16_thread);
2456     cmpwi(CR0, R0, 0);
2457     beq(CR0, jvmti_post_done);
2458     call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::post_method_entry));
2459 
2460     bind(jvmti_post_done);
2461   }
2462 }
2463 
2464 // Inline assembly for:
2465 //
2466 // if (thread is in interp_only_mode) {
2467 //   // save result
2468 //   InterpreterRuntime::post_method_exit();
2469 //   // restore result
2470 // }
2471 // if (*jvmpi::event_flags_array_at_addr(JVMPI_EVENT_METHOD_EXIT)) {
2472 //   // save result
2473 //   SharedRuntime::jvmpi_method_exit();
2474 //   // restore result
2475 // }
2476 //
2477 // Native methods have their result stored in d_tmp and l_tmp.
2478 // Java methods have their result stored in the expression stack.
2479 void InterpreterMacroAssembler::notify_method_exit(bool is_native_method, TosState state,
2480                                                    NotifyMethodExitMode mode, bool check_exceptions) {
2481   // JVMTI
2482   // Whenever JVMTI puts a thread in interp_only_mode, method
2483   // entry/exit events are sent for that thread to track stack
2484   // depth. If it is possible to enter interp_only_mode we add
2485   // the code to check if the event should be sent.
2486   if (mode == NotifyJVMTI && JvmtiExport::can_post_interpreter_events()) {
2487     Label jvmti_post_done;
2488 
2489     lwz(R0, in_bytes(JavaThread::interp_only_mode_offset()), R16_thread);
2490     cmpwi(CR0, R0, 0);
2491     beq(CR0, jvmti_post_done);
2492     if (!is_native_method) { push(state); } // Expose tos to GC.
2493     call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::post_method_exit), check_exceptions);
2494     if (!is_native_method) { pop(state); }
2495 
2496     align(32, 12);
2497     bind(jvmti_post_done);
2498   }
2499 
2500   // Dtrace support not implemented.
2501 }