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