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