1 /*
   2  * Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2014, 2021, 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 <sys/types.h>
  27 
  28 #include "precompiled.hpp"
  29 #include "jvm.h"
  30 #include "asm/assembler.hpp"
  31 #include "asm/assembler.inline.hpp"
  32 #include "ci/ciEnv.hpp"
  33 #include "gc/shared/barrierSet.hpp"
  34 #include "gc/shared/barrierSetAssembler.hpp"
  35 #include "gc/shared/cardTableBarrierSet.hpp"
  36 #include "gc/shared/cardTable.hpp"
  37 #include "gc/shared/collectedHeap.hpp"
  38 #include "gc/shared/tlab_globals.hpp"
  39 #include "interpreter/bytecodeHistogram.hpp"
  40 #include "interpreter/interpreter.hpp"
  41 #include "compiler/compileTask.hpp"
  42 #include "compiler/disassembler.hpp"
  43 #include "logging/log.hpp"
  44 #include "memory/resourceArea.hpp"
  45 #include "memory/universe.hpp"
  46 #include "nativeInst_aarch64.hpp"
  47 #include "oops/accessDecorators.hpp"
  48 #include "oops/compressedKlass.inline.hpp"
  49 #include "oops/compressedOops.inline.hpp"
  50 #include "oops/klass.inline.hpp"
  51 #include "runtime/icache.hpp"
  52 #include "runtime/interfaceSupport.inline.hpp"
  53 #include "runtime/jniHandles.inline.hpp"
  54 #include "runtime/sharedRuntime.hpp"
  55 #include "runtime/stubRoutines.hpp"
  56 #include "runtime/thread.hpp"
  57 #include "utilities/powerOfTwo.hpp"
  58 #ifdef COMPILER1
  59 #include "c1/c1_LIRAssembler.hpp"
  60 #endif
  61 #ifdef COMPILER2
  62 #include "oops/oop.hpp"
  63 #include "opto/compile.hpp"
  64 #include "opto/node.hpp"
  65 #include "opto/output.hpp"
  66 #endif
  67 
  68 #ifdef PRODUCT
  69 #define BLOCK_COMMENT(str) /* nothing */
  70 #else
  71 #define BLOCK_COMMENT(str) block_comment(str)
  72 #endif
  73 #define STOP(str) stop(str);
  74 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  75 
  76 // Patch any kind of instruction; there may be several instructions.
  77 // Return the total length (in bytes) of the instructions.
  78 int MacroAssembler::pd_patch_instruction_size(address branch, address target) {
  79   int instructions = 1;
  80   assert((uint64_t)target < (1ull << 48), "48-bit overflow in address constant");
  81   intptr_t offset = (target - branch) >> 2;
  82   unsigned insn = *(unsigned*)branch;
  83   if ((Instruction_aarch64::extract(insn, 29, 24) & 0b111011) == 0b011000) {
  84     // Load register (literal)
  85     Instruction_aarch64::spatch(branch, 23, 5, offset);
  86   } else if (Instruction_aarch64::extract(insn, 30, 26) == 0b00101) {
  87     // Unconditional branch (immediate)
  88     Instruction_aarch64::spatch(branch, 25, 0, offset);
  89   } else if (Instruction_aarch64::extract(insn, 31, 25) == 0b0101010) {
  90     // Conditional branch (immediate)
  91     Instruction_aarch64::spatch(branch, 23, 5, offset);
  92   } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011010) {
  93     // Compare & branch (immediate)
  94     Instruction_aarch64::spatch(branch, 23, 5, offset);
  95   } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011011) {
  96     // Test & branch (immediate)
  97     Instruction_aarch64::spatch(branch, 18, 5, offset);
  98   } else if (Instruction_aarch64::extract(insn, 28, 24) == 0b10000) {
  99     // PC-rel. addressing
 100     offset = target-branch;
 101     int shift = Instruction_aarch64::extract(insn, 31, 31);
 102     if (shift) {
 103       uint64_t dest = (uint64_t)target;
 104       uint64_t pc_page = (uint64_t)branch >> 12;
 105       uint64_t adr_page = (uint64_t)target >> 12;
 106       unsigned offset_lo = dest & 0xfff;
 107       offset = adr_page - pc_page;
 108 
 109       // We handle 4 types of PC relative addressing
 110       //   1 - adrp    Rx, target_page
 111       //       ldr/str Ry, [Rx, #offset_in_page]
 112       //   2 - adrp    Rx, target_page
 113       //       add     Ry, Rx, #offset_in_page
 114       //   3 - adrp    Rx, target_page (page aligned reloc, offset == 0)
 115       //       movk    Rx, #imm16<<32
 116       //   4 - adrp    Rx, target_page (page aligned reloc, offset == 0)
 117       // In the first 3 cases we must check that Rx is the same in the adrp and the
 118       // subsequent ldr/str, add or movk instruction. Otherwise we could accidentally end
 119       // up treating a type 4 relocation as a type 1, 2 or 3 just because it happened
 120       // to be followed by a random unrelated ldr/str, add or movk instruction.
 121       //
 122       unsigned insn2 = ((unsigned*)branch)[1];
 123       if (Instruction_aarch64::extract(insn2, 29, 24) == 0b111001 &&
 124                 Instruction_aarch64::extract(insn, 4, 0) ==
 125                         Instruction_aarch64::extract(insn2, 9, 5)) {
 126         // Load/store register (unsigned immediate)
 127         unsigned size = Instruction_aarch64::extract(insn2, 31, 30);
 128         Instruction_aarch64::patch(branch + sizeof (unsigned),
 129                                     21, 10, offset_lo >> size);
 130         guarantee(((dest >> size) << size) == dest, "misaligned target");
 131         instructions = 2;
 132       } else if (Instruction_aarch64::extract(insn2, 31, 22) == 0b1001000100 &&
 133                 Instruction_aarch64::extract(insn, 4, 0) ==
 134                         Instruction_aarch64::extract(insn2, 4, 0)) {
 135         // add (immediate)
 136         Instruction_aarch64::patch(branch + sizeof (unsigned),
 137                                    21, 10, offset_lo);
 138         instructions = 2;
 139       } else if (Instruction_aarch64::extract(insn2, 31, 21) == 0b11110010110 &&
 140                    Instruction_aarch64::extract(insn, 4, 0) ==
 141                      Instruction_aarch64::extract(insn2, 4, 0)) {
 142         // movk #imm16<<32
 143         Instruction_aarch64::patch(branch + 4, 20, 5, (uint64_t)target >> 32);
 144         uintptr_t dest = ((uintptr_t)target & 0xffffffffULL) | ((uintptr_t)branch & 0xffff00000000ULL);
 145         uintptr_t pc_page = (uintptr_t)branch >> 12;
 146         uintptr_t adr_page = (uintptr_t)dest >> 12;
 147         offset = adr_page - pc_page;
 148         instructions = 2;
 149       }
 150     }
 151     int offset_lo = offset & 3;
 152     offset >>= 2;
 153     Instruction_aarch64::spatch(branch, 23, 5, offset);
 154     Instruction_aarch64::patch(branch, 30, 29, offset_lo);
 155   } else if (Instruction_aarch64::extract(insn, 31, 21) == 0b11010010100) {
 156     uint64_t dest = (uint64_t)target;
 157     // Move wide constant
 158     assert(nativeInstruction_at(branch+4)->is_movk(), "wrong insns in patch");
 159     assert(nativeInstruction_at(branch+8)->is_movk(), "wrong insns in patch");
 160     Instruction_aarch64::patch(branch, 20, 5, dest & 0xffff);
 161     Instruction_aarch64::patch(branch+4, 20, 5, (dest >>= 16) & 0xffff);
 162     Instruction_aarch64::patch(branch+8, 20, 5, (dest >>= 16) & 0xffff);
 163     assert(target_addr_for_insn(branch) == target, "should be");
 164     instructions = 3;
 165   } else if (NativeInstruction::is_ldrw_to_zr(address(&insn))) {
 166     // nothing to do
 167     assert(target == 0, "did not expect to relocate target for polling page load");
 168   } else {
 169     ShouldNotReachHere();
 170   }
 171   return instructions * NativeInstruction::instruction_size;
 172 }
 173 
 174 int MacroAssembler::patch_oop(address insn_addr, address o) {
 175   int instructions;
 176   unsigned insn = *(unsigned*)insn_addr;
 177   assert(nativeInstruction_at(insn_addr+4)->is_movk(), "wrong insns in patch");
 178 
 179   // OOPs are either narrow (32 bits) or wide (48 bits).  We encode
 180   // narrow OOPs by setting the upper 16 bits in the first
 181   // instruction.
 182   if (Instruction_aarch64::extract(insn, 31, 21) == 0b11010010101) {
 183     // Move narrow OOP
 184     uint32_t n = CompressedOops::narrow_oop_value(cast_to_oop(o));
 185     Instruction_aarch64::patch(insn_addr, 20, 5, n >> 16);
 186     Instruction_aarch64::patch(insn_addr+4, 20, 5, n & 0xffff);
 187     instructions = 2;
 188   } else {
 189     // Move wide OOP
 190     assert(nativeInstruction_at(insn_addr+8)->is_movk(), "wrong insns in patch");
 191     uintptr_t dest = (uintptr_t)o;
 192     Instruction_aarch64::patch(insn_addr, 20, 5, dest & 0xffff);
 193     Instruction_aarch64::patch(insn_addr+4, 20, 5, (dest >>= 16) & 0xffff);
 194     Instruction_aarch64::patch(insn_addr+8, 20, 5, (dest >>= 16) & 0xffff);
 195     instructions = 3;
 196   }
 197   return instructions * NativeInstruction::instruction_size;
 198 }
 199 
 200 int MacroAssembler::patch_narrow_klass(address insn_addr, narrowKlass n) {
 201   // Metadata pointers are either narrow (32 bits) or wide (48 bits).
 202   // We encode narrow ones by setting the upper 16 bits in the first
 203   // instruction.
 204   NativeInstruction *insn = nativeInstruction_at(insn_addr);
 205   assert(Instruction_aarch64::extract(insn->encoding(), 31, 21) == 0b11010010101 &&
 206          nativeInstruction_at(insn_addr+4)->is_movk(), "wrong insns in patch");
 207 
 208   Instruction_aarch64::patch(insn_addr, 20, 5, n >> 16);
 209   Instruction_aarch64::patch(insn_addr+4, 20, 5, n & 0xffff);
 210   return 2 * NativeInstruction::instruction_size;
 211 }
 212 
 213 address MacroAssembler::target_addr_for_insn(address insn_addr, unsigned insn) {
 214   intptr_t offset = 0;
 215   if ((Instruction_aarch64::extract(insn, 29, 24) & 0b011011) == 0b00011000) {
 216     // Load register (literal)
 217     offset = Instruction_aarch64::sextract(insn, 23, 5);
 218     return address(((uint64_t)insn_addr + (offset << 2)));
 219   } else if (Instruction_aarch64::extract(insn, 30, 26) == 0b00101) {
 220     // Unconditional branch (immediate)
 221     offset = Instruction_aarch64::sextract(insn, 25, 0);
 222   } else if (Instruction_aarch64::extract(insn, 31, 25) == 0b0101010) {
 223     // Conditional branch (immediate)
 224     offset = Instruction_aarch64::sextract(insn, 23, 5);
 225   } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011010) {
 226     // Compare & branch (immediate)
 227     offset = Instruction_aarch64::sextract(insn, 23, 5);
 228    } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011011) {
 229     // Test & branch (immediate)
 230     offset = Instruction_aarch64::sextract(insn, 18, 5);
 231   } else if (Instruction_aarch64::extract(insn, 28, 24) == 0b10000) {
 232     // PC-rel. addressing
 233     offset = Instruction_aarch64::extract(insn, 30, 29);
 234     offset |= Instruction_aarch64::sextract(insn, 23, 5) << 2;
 235     int shift = Instruction_aarch64::extract(insn, 31, 31) ? 12 : 0;
 236     if (shift) {
 237       offset <<= shift;
 238       uint64_t target_page = ((uint64_t)insn_addr) + offset;
 239       target_page &= ((uint64_t)-1) << shift;
 240       // Return the target address for the following sequences
 241       //   1 - adrp    Rx, target_page
 242       //       ldr/str Ry, [Rx, #offset_in_page]
 243       //   2 - adrp    Rx, target_page
 244       //       add     Ry, Rx, #offset_in_page
 245       //   3 - adrp    Rx, target_page (page aligned reloc, offset == 0)
 246       //       movk    Rx, #imm12<<32
 247       //   4 - adrp    Rx, target_page (page aligned reloc, offset == 0)
 248       //
 249       // In the first two cases  we check that the register is the same and
 250       // return the target_page + the offset within the page.
 251       // Otherwise we assume it is a page aligned relocation and return
 252       // the target page only.
 253       //
 254       unsigned insn2 = ((unsigned*)insn_addr)[1];
 255       if (Instruction_aarch64::extract(insn2, 29, 24) == 0b111001 &&
 256                 Instruction_aarch64::extract(insn, 4, 0) ==
 257                         Instruction_aarch64::extract(insn2, 9, 5)) {
 258         // Load/store register (unsigned immediate)
 259         unsigned int byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 260         unsigned int size = Instruction_aarch64::extract(insn2, 31, 30);
 261         return address(target_page + (byte_offset << size));
 262       } else if (Instruction_aarch64::extract(insn2, 31, 22) == 0b1001000100 &&
 263                 Instruction_aarch64::extract(insn, 4, 0) ==
 264                         Instruction_aarch64::extract(insn2, 4, 0)) {
 265         // add (immediate)
 266         unsigned int byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 267         return address(target_page + byte_offset);
 268       } else {
 269         if (Instruction_aarch64::extract(insn2, 31, 21) == 0b11110010110  &&
 270                Instruction_aarch64::extract(insn, 4, 0) ==
 271                  Instruction_aarch64::extract(insn2, 4, 0)) {
 272           target_page = (target_page & 0xffffffff) |
 273                          ((uint64_t)Instruction_aarch64::extract(insn2, 20, 5) << 32);
 274         }
 275         return (address)target_page;
 276       }
 277     } else {
 278       ShouldNotReachHere();
 279     }
 280   } else if (Instruction_aarch64::extract(insn, 31, 23) == 0b110100101) {
 281     uint32_t *insns = (uint32_t *)insn_addr;
 282     // Move wide constant: movz, movk, movk.  See movptr().
 283     assert(nativeInstruction_at(insns+1)->is_movk(), "wrong insns in patch");
 284     assert(nativeInstruction_at(insns+2)->is_movk(), "wrong insns in patch");
 285     return address(uint64_t(Instruction_aarch64::extract(insns[0], 20, 5))
 286                    + (uint64_t(Instruction_aarch64::extract(insns[1], 20, 5)) << 16)
 287                    + (uint64_t(Instruction_aarch64::extract(insns[2], 20, 5)) << 32));
 288   } else {
 289     ShouldNotReachHere();
 290   }
 291   return address(((uint64_t)insn_addr + (offset << 2)));
 292 }
 293 
 294 address MacroAssembler::target_addr_for_insn_or_null(address insn_addr, unsigned insn) {
 295   if (NativeInstruction::is_ldrw_to_zr(address(&insn))) {
 296     return 0;
 297   }
 298   return MacroAssembler::target_addr_for_insn(insn_addr, insn);
 299 }
 300 
 301 void MacroAssembler::safepoint_poll(Label& slow_path, bool at_return, bool acquire, bool in_nmethod) {
 302   if (acquire) {
 303     lea(rscratch1, Address(rthread, JavaThread::polling_word_offset()));
 304     ldar(rscratch1, rscratch1);
 305   } else {
 306     ldr(rscratch1, Address(rthread, JavaThread::polling_word_offset()));
 307   }
 308   if (at_return) {
 309     // Note that when in_nmethod is set, the stack pointer is incremented before the poll. Therefore,
 310     // we may safely use the sp instead to perform the stack watermark check.
 311     cmp(in_nmethod ? sp : rfp, rscratch1);
 312     br(Assembler::HI, slow_path);
 313   } else {
 314     tbnz(rscratch1, log2i_exact(SafepointMechanism::poll_bit()), slow_path);
 315   }
 316 }
 317 
 318 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 319   // we must set sp to zero to clear frame
 320   str(zr, Address(rthread, JavaThread::last_Java_sp_offset()));
 321 
 322   // must clear fp, so that compiled frames are not confused; it is
 323   // possible that we need it only for debugging
 324   if (clear_fp) {
 325     str(zr, Address(rthread, JavaThread::last_Java_fp_offset()));
 326   }
 327 
 328   // Always clear the pc because it could have been set by make_walkable()
 329   str(zr, Address(rthread, JavaThread::last_Java_pc_offset()));
 330 }
 331 
 332 // Calls to C land
 333 //
 334 // When entering C land, the rfp, & resp of the last Java frame have to be recorded
 335 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
 336 // has to be reset to 0. This is required to allow proper stack traversal.
 337 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 338                                          Register last_java_fp,
 339                                          Register last_java_pc,
 340                                          Register scratch) {
 341 
 342   if (last_java_pc->is_valid()) {
 343       str(last_java_pc, Address(rthread,
 344                                 JavaThread::frame_anchor_offset()
 345                                 + JavaFrameAnchor::last_Java_pc_offset()));
 346     }
 347 
 348   // determine last_java_sp register
 349   if (last_java_sp == sp) {
 350     mov(scratch, sp);
 351     last_java_sp = scratch;
 352   } else if (!last_java_sp->is_valid()) {
 353     last_java_sp = esp;
 354   }
 355 
 356   str(last_java_sp, Address(rthread, JavaThread::last_Java_sp_offset()));
 357 
 358   // last_java_fp is optional
 359   if (last_java_fp->is_valid()) {
 360     str(last_java_fp, Address(rthread, JavaThread::last_Java_fp_offset()));
 361   }
 362 }
 363 
 364 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 365                                          Register last_java_fp,
 366                                          address  last_java_pc,
 367                                          Register scratch) {
 368   assert(last_java_pc != NULL, "must provide a valid PC");
 369 
 370   adr(scratch, last_java_pc);
 371   str(scratch, Address(rthread,
 372                        JavaThread::frame_anchor_offset()
 373                        + JavaFrameAnchor::last_Java_pc_offset()));
 374 
 375   set_last_Java_frame(last_java_sp, last_java_fp, noreg, scratch);
 376 }
 377 
 378 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 379                                          Register last_java_fp,
 380                                          Label &L,
 381                                          Register scratch) {
 382   if (L.is_bound()) {
 383     set_last_Java_frame(last_java_sp, last_java_fp, target(L), scratch);
 384   } else {
 385     InstructionMark im(this);
 386     L.add_patch_at(code(), locator());
 387     set_last_Java_frame(last_java_sp, last_java_fp, pc() /* Patched later */, scratch);
 388   }
 389 }
 390 
 391 static inline bool target_needs_far_branch(address addr) {
 392   // codecache size <= 128M
 393   if (!MacroAssembler::far_branches()) {
 394     return false;
 395   }
 396   // codecache size > 240M
 397   if (MacroAssembler::codestub_branch_needs_far_jump()) {
 398     return true;
 399   }
 400   // codecache size: 128M..240M
 401   return !CodeCache::is_non_nmethod(addr);
 402 }
 403 
 404 void MacroAssembler::far_call(Address entry, CodeBuffer *cbuf, Register tmp) {
 405   assert(ReservedCodeCacheSize < 4*G, "branch out of range");
 406   assert(CodeCache::find_blob(entry.target()) != NULL,
 407          "destination of far call not found in code cache");
 408   if (target_needs_far_branch(entry.target())) {
 409     uint64_t offset;
 410     // We can use ADRP here because we know that the total size of
 411     // the code cache cannot exceed 2Gb (ADRP limit is 4GB).
 412     adrp(tmp, entry, offset);
 413     add(tmp, tmp, offset);
 414     if (cbuf) cbuf->set_insts_mark();
 415     blr(tmp);
 416   } else {
 417     if (cbuf) cbuf->set_insts_mark();
 418     bl(entry);
 419   }
 420 }
 421 
 422 int MacroAssembler::far_jump(Address entry, CodeBuffer *cbuf, Register tmp) {
 423   assert(ReservedCodeCacheSize < 4*G, "branch out of range");
 424   assert(CodeCache::find_blob(entry.target()) != NULL,
 425          "destination of far call not found in code cache");
 426   address start = pc();
 427   if (target_needs_far_branch(entry.target())) {
 428     uint64_t offset;
 429     // We can use ADRP here because we know that the total size of
 430     // the code cache cannot exceed 2Gb (ADRP limit is 4GB).
 431     adrp(tmp, entry, offset);
 432     add(tmp, tmp, offset);
 433     if (cbuf) cbuf->set_insts_mark();
 434     br(tmp);
 435   } else {
 436     if (cbuf) cbuf->set_insts_mark();
 437     b(entry);
 438   }
 439   return pc() - start;
 440 }
 441 
 442 void MacroAssembler::reserved_stack_check() {
 443     // testing if reserved zone needs to be enabled
 444     Label no_reserved_zone_enabling;
 445 
 446     ldr(rscratch1, Address(rthread, JavaThread::reserved_stack_activation_offset()));
 447     cmp(sp, rscratch1);
 448     br(Assembler::LO, no_reserved_zone_enabling);
 449 
 450     enter();   // LR and FP are live.
 451     lea(rscratch1, CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone));
 452     mov(c_rarg0, rthread);
 453     blr(rscratch1);
 454     leave();
 455 
 456     // We have already removed our own frame.
 457     // throw_delayed_StackOverflowError will think that it's been
 458     // called by our caller.
 459     lea(rscratch1, RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
 460     br(rscratch1);
 461     should_not_reach_here();
 462 
 463     bind(no_reserved_zone_enabling);
 464 }
 465 
 466 static void pass_arg0(MacroAssembler* masm, Register arg) {
 467   if (c_rarg0 != arg ) {
 468     masm->mov(c_rarg0, arg);
 469   }
 470 }
 471 
 472 static void pass_arg1(MacroAssembler* masm, Register arg) {
 473   if (c_rarg1 != arg ) {
 474     masm->mov(c_rarg1, arg);
 475   }
 476 }
 477 
 478 static void pass_arg2(MacroAssembler* masm, Register arg) {
 479   if (c_rarg2 != arg ) {
 480     masm->mov(c_rarg2, arg);
 481   }
 482 }
 483 
 484 static void pass_arg3(MacroAssembler* masm, Register arg) {
 485   if (c_rarg3 != arg ) {
 486     masm->mov(c_rarg3, arg);
 487   }
 488 }
 489 
 490 void MacroAssembler::call_VM_base(Register oop_result,
 491                                   Register java_thread,
 492                                   Register last_java_sp,
 493                                   address  entry_point,
 494                                   int      number_of_arguments,
 495                                   bool     check_exceptions) {
 496    // determine java_thread register
 497   if (!java_thread->is_valid()) {
 498     java_thread = rthread;
 499   }
 500 
 501   // determine last_java_sp register
 502   if (!last_java_sp->is_valid()) {
 503     last_java_sp = esp;
 504   }
 505 
 506   // debugging support
 507   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
 508   assert(java_thread == rthread, "unexpected register");
 509 #ifdef ASSERT
 510   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
 511   // if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");
 512 #endif // ASSERT
 513 
 514   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
 515   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
 516 
 517   // push java thread (becomes first argument of C function)
 518 
 519   mov(c_rarg0, java_thread);
 520 
 521   // set last Java frame before call
 522   assert(last_java_sp != rfp, "can't use rfp");
 523 
 524   Label l;
 525   set_last_Java_frame(last_java_sp, rfp, l, rscratch1);
 526 
 527   // do the call, remove parameters
 528   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments, &l);
 529 
 530   // lr could be poisoned with PAC signature during throw_pending_exception
 531   // if it was tail-call optimized by compiler, since lr is not callee-saved
 532   // reload it with proper value
 533   adr(lr, l);
 534 
 535   // reset last Java frame
 536   // Only interpreter should have to clear fp
 537   reset_last_Java_frame(true);
 538 
 539    // C++ interp handles this in the interpreter
 540   check_and_handle_popframe(java_thread);
 541   check_and_handle_earlyret(java_thread);
 542 
 543   if (check_exceptions) {
 544     // check for pending exceptions (java_thread is set upon return)
 545     ldr(rscratch1, Address(java_thread, in_bytes(Thread::pending_exception_offset())));
 546     Label ok;
 547     cbz(rscratch1, ok);
 548     lea(rscratch1, RuntimeAddress(StubRoutines::forward_exception_entry()));
 549     br(rscratch1);
 550     bind(ok);
 551   }
 552 
 553   // get oop result if there is one and reset the value in the thread
 554   if (oop_result->is_valid()) {
 555     get_vm_result(oop_result, java_thread);
 556   }
 557 }
 558 
 559 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
 560   call_VM_base(oop_result, noreg, noreg, entry_point, number_of_arguments, check_exceptions);
 561 }
 562 
 563 // Maybe emit a call via a trampoline.  If the code cache is small
 564 // trampolines won't be emitted.
 565 
 566 address MacroAssembler::trampoline_call(Address entry, CodeBuffer* cbuf) {
 567   assert(JavaThread::current()->is_Compiler_thread(), "just checking");
 568   assert(entry.rspec().type() == relocInfo::runtime_call_type
 569          || entry.rspec().type() == relocInfo::opt_virtual_call_type
 570          || entry.rspec().type() == relocInfo::static_call_type
 571          || entry.rspec().type() == relocInfo::virtual_call_type, "wrong reloc type");
 572 
 573   // We need a trampoline if branches are far.
 574   if (far_branches()) {
 575     bool in_scratch_emit_size = false;
 576 #ifdef COMPILER2
 577     // We don't want to emit a trampoline if C2 is generating dummy
 578     // code during its branch shortening phase.
 579     CompileTask* task = ciEnv::current()->task();
 580     in_scratch_emit_size =
 581       (task != NULL && is_c2_compile(task->comp_level()) &&
 582        Compile::current()->output()->in_scratch_emit_size());
 583 #endif
 584     if (!in_scratch_emit_size) {
 585       address stub = emit_trampoline_stub(offset(), entry.target());
 586       if (stub == NULL) {
 587         postcond(pc() == badAddress);
 588         return NULL; // CodeCache is full
 589       }
 590     }
 591   }
 592 
 593   if (cbuf) cbuf->set_insts_mark();
 594   relocate(entry.rspec());
 595   if (!far_branches()) {
 596     bl(entry.target());
 597   } else {
 598     bl(pc());
 599   }
 600   // just need to return a non-null address
 601   postcond(pc() != badAddress);
 602   return pc();
 603 }
 604 
 605 
 606 // Emit a trampoline stub for a call to a target which is too far away.
 607 //
 608 // code sequences:
 609 //
 610 // call-site:
 611 //   branch-and-link to <destination> or <trampoline stub>
 612 //
 613 // Related trampoline stub for this call site in the stub section:
 614 //   load the call target from the constant pool
 615 //   branch (LR still points to the call site above)
 616 
 617 address MacroAssembler::emit_trampoline_stub(int insts_call_instruction_offset,
 618                                              address dest) {
 619   // Max stub size: alignment nop, TrampolineStub.
 620   address stub = start_a_stub(NativeInstruction::instruction_size
 621                    + NativeCallTrampolineStub::instruction_size);
 622   if (stub == NULL) {
 623     return NULL;  // CodeBuffer::expand failed
 624   }
 625 
 626   // Create a trampoline stub relocation which relates this trampoline stub
 627   // with the call instruction at insts_call_instruction_offset in the
 628   // instructions code-section.
 629   align(wordSize);
 630   relocate(trampoline_stub_Relocation::spec(code()->insts()->start()
 631                                             + insts_call_instruction_offset));
 632   const int stub_start_offset = offset();
 633 
 634   // Now, create the trampoline stub's code:
 635   // - load the call
 636   // - call
 637   Label target;
 638   ldr(rscratch1, target);
 639   br(rscratch1);
 640   bind(target);
 641   assert(offset() - stub_start_offset == NativeCallTrampolineStub::data_offset,
 642          "should be");
 643   emit_int64((int64_t)dest);
 644 
 645   const address stub_start_addr = addr_at(stub_start_offset);
 646 
 647   assert(is_NativeCallTrampolineStub_at(stub_start_addr), "doesn't look like a trampoline");
 648 
 649   end_a_stub();
 650   return stub_start_addr;
 651 }
 652 
 653 void MacroAssembler::emit_static_call_stub() {
 654   // CompiledDirectStaticCall::set_to_interpreted knows the
 655   // exact layout of this stub.
 656 
 657   isb();
 658   mov_metadata(rmethod, (Metadata*)NULL);
 659 
 660   // Jump to the entry point of the i2c stub.
 661   movptr(rscratch1, 0);
 662   br(rscratch1);
 663 }
 664 
 665 void MacroAssembler::c2bool(Register x) {
 666   // implements x == 0 ? 0 : 1
 667   // note: must only look at least-significant byte of x
 668   //       since C-style booleans are stored in one byte
 669   //       only! (was bug)
 670   tst(x, 0xff);
 671   cset(x, Assembler::NE);
 672 }
 673 
 674 address MacroAssembler::ic_call(address entry, jint method_index) {
 675   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
 676   // address const_ptr = long_constant((jlong)Universe::non_oop_word());
 677   // uintptr_t offset;
 678   // ldr_constant(rscratch2, const_ptr);
 679   movptr(rscratch2, (uintptr_t)Universe::non_oop_word());
 680   return trampoline_call(Address(entry, rh));
 681 }
 682 
 683 // Implementation of call_VM versions
 684 
 685 void MacroAssembler::call_VM(Register oop_result,
 686                              address entry_point,
 687                              bool check_exceptions) {
 688   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
 689 }
 690 
 691 void MacroAssembler::call_VM(Register oop_result,
 692                              address entry_point,
 693                              Register arg_1,
 694                              bool check_exceptions) {
 695   pass_arg1(this, arg_1);
 696   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
 697 }
 698 
 699 void MacroAssembler::call_VM(Register oop_result,
 700                              address entry_point,
 701                              Register arg_1,
 702                              Register arg_2,
 703                              bool check_exceptions) {
 704   assert(arg_1 != c_rarg2, "smashed arg");
 705   pass_arg2(this, arg_2);
 706   pass_arg1(this, arg_1);
 707   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
 708 }
 709 
 710 void MacroAssembler::call_VM(Register oop_result,
 711                              address entry_point,
 712                              Register arg_1,
 713                              Register arg_2,
 714                              Register arg_3,
 715                              bool check_exceptions) {
 716   assert(arg_1 != c_rarg3, "smashed arg");
 717   assert(arg_2 != c_rarg3, "smashed arg");
 718   pass_arg3(this, arg_3);
 719 
 720   assert(arg_1 != c_rarg2, "smashed arg");
 721   pass_arg2(this, arg_2);
 722 
 723   pass_arg1(this, arg_1);
 724   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
 725 }
 726 
 727 void MacroAssembler::call_VM(Register oop_result,
 728                              Register last_java_sp,
 729                              address entry_point,
 730                              int number_of_arguments,
 731                              bool check_exceptions) {
 732   call_VM_base(oop_result, rthread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
 733 }
 734 
 735 void MacroAssembler::call_VM(Register oop_result,
 736                              Register last_java_sp,
 737                              address entry_point,
 738                              Register arg_1,
 739                              bool check_exceptions) {
 740   pass_arg1(this, arg_1);
 741   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
 742 }
 743 
 744 void MacroAssembler::call_VM(Register oop_result,
 745                              Register last_java_sp,
 746                              address entry_point,
 747                              Register arg_1,
 748                              Register arg_2,
 749                              bool check_exceptions) {
 750 
 751   assert(arg_1 != c_rarg2, "smashed arg");
 752   pass_arg2(this, arg_2);
 753   pass_arg1(this, arg_1);
 754   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
 755 }
 756 
 757 void MacroAssembler::call_VM(Register oop_result,
 758                              Register last_java_sp,
 759                              address entry_point,
 760                              Register arg_1,
 761                              Register arg_2,
 762                              Register arg_3,
 763                              bool check_exceptions) {
 764   assert(arg_1 != c_rarg3, "smashed arg");
 765   assert(arg_2 != c_rarg3, "smashed arg");
 766   pass_arg3(this, arg_3);
 767   assert(arg_1 != c_rarg2, "smashed arg");
 768   pass_arg2(this, arg_2);
 769   pass_arg1(this, arg_1);
 770   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
 771 }
 772 
 773 
 774 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
 775   ldr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
 776   str(zr, Address(java_thread, JavaThread::vm_result_offset()));
 777   verify_oop_msg(oop_result, "broken oop in call_VM_base");
 778 }
 779 
 780 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
 781   ldr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
 782   str(zr, Address(java_thread, JavaThread::vm_result_2_offset()));
 783 }
 784 
 785 void MacroAssembler::align(int modulus) {
 786   while (offset() % modulus != 0) nop();
 787 }
 788 
 789 // these are no-ops overridden by InterpreterMacroAssembler
 790 
 791 void MacroAssembler::check_and_handle_earlyret(Register java_thread) { }
 792 
 793 void MacroAssembler::check_and_handle_popframe(Register java_thread) { }
 794 
 795 // Look up the method for a megamorphic invokeinterface call.
 796 // The target method is determined by <intf_klass, itable_index>.
 797 // The receiver klass is in recv_klass.
 798 // On success, the result will be in method_result, and execution falls through.
 799 // On failure, execution transfers to the given label.
 800 void MacroAssembler::lookup_interface_method(Register recv_klass,
 801                                              Register intf_klass,
 802                                              RegisterOrConstant itable_index,
 803                                              Register method_result,
 804                                              Register scan_temp,
 805                                              Label& L_no_such_interface,
 806                          bool return_method) {
 807   assert_different_registers(recv_klass, intf_klass, scan_temp);
 808   assert_different_registers(method_result, intf_klass, scan_temp);
 809   assert(recv_klass != method_result || !return_method,
 810      "recv_klass can be destroyed when method isn't needed");
 811   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
 812          "caller must use same register for non-constant itable index as for method");
 813 
 814   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
 815   int vtable_base = in_bytes(Klass::vtable_start_offset());
 816   int itentry_off = itableMethodEntry::method_offset_in_bytes();
 817   int scan_step   = itableOffsetEntry::size() * wordSize;
 818   int vte_size    = vtableEntry::size_in_bytes();
 819   assert(vte_size == wordSize, "else adjust times_vte_scale");
 820 
 821   ldrw(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
 822 
 823   // %%% Could store the aligned, prescaled offset in the klassoop.
 824   // lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
 825   lea(scan_temp, Address(recv_klass, scan_temp, Address::lsl(3)));
 826   add(scan_temp, scan_temp, vtable_base);
 827 
 828   if (return_method) {
 829     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
 830     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
 831     // lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
 832     lea(recv_klass, Address(recv_klass, itable_index, Address::lsl(3)));
 833     if (itentry_off)
 834       add(recv_klass, recv_klass, itentry_off);
 835   }
 836 
 837   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
 838   //   if (scan->interface() == intf) {
 839   //     result = (klass + scan->offset() + itable_index);
 840   //   }
 841   // }
 842   Label search, found_method;
 843 
 844   ldr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
 845   cmp(intf_klass, method_result);
 846   br(Assembler::EQ, found_method);
 847   bind(search);
 848   // Check that the previous entry is non-null.  A null entry means that
 849   // the receiver class doesn't implement the interface, and wasn't the
 850   // same as when the caller was compiled.
 851   cbz(method_result, L_no_such_interface);
 852   if (itableOffsetEntry::interface_offset_in_bytes() != 0) {
 853     add(scan_temp, scan_temp, scan_step);
 854     ldr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
 855   } else {
 856     ldr(method_result, Address(pre(scan_temp, scan_step)));
 857   }
 858   cmp(intf_klass, method_result);
 859   br(Assembler::NE, search);
 860 
 861   bind(found_method);
 862 
 863   // Got a hit.
 864   if (return_method) {
 865     ldrw(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
 866     ldr(method_result, Address(recv_klass, scan_temp, Address::uxtw(0)));
 867   }
 868 }
 869 
 870 // virtual method calling
 871 void MacroAssembler::lookup_virtual_method(Register recv_klass,
 872                                            RegisterOrConstant vtable_index,
 873                                            Register method_result) {
 874   const int base = in_bytes(Klass::vtable_start_offset());
 875   assert(vtableEntry::size() * wordSize == 8,
 876          "adjust the scaling in the code below");
 877   int vtable_offset_in_bytes = base + vtableEntry::method_offset_in_bytes();
 878 
 879   if (vtable_index.is_register()) {
 880     lea(method_result, Address(recv_klass,
 881                                vtable_index.as_register(),
 882                                Address::lsl(LogBytesPerWord)));
 883     ldr(method_result, Address(method_result, vtable_offset_in_bytes));
 884   } else {
 885     vtable_offset_in_bytes += vtable_index.as_constant() * wordSize;
 886     ldr(method_result,
 887         form_address(rscratch1, recv_klass, vtable_offset_in_bytes, 0));
 888   }
 889 }
 890 
 891 void MacroAssembler::check_klass_subtype(Register sub_klass,
 892                            Register super_klass,
 893                            Register temp_reg,
 894                            Label& L_success) {
 895   Label L_failure;
 896   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
 897   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
 898   bind(L_failure);
 899 }
 900 
 901 
 902 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
 903                                                    Register super_klass,
 904                                                    Register temp_reg,
 905                                                    Label* L_success,
 906                                                    Label* L_failure,
 907                                                    Label* L_slow_path,
 908                                         RegisterOrConstant super_check_offset) {
 909   assert_different_registers(sub_klass, super_klass, temp_reg);
 910   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
 911   if (super_check_offset.is_register()) {
 912     assert_different_registers(sub_klass, super_klass,
 913                                super_check_offset.as_register());
 914   } else if (must_load_sco) {
 915     assert(temp_reg != noreg, "supply either a temp or a register offset");
 916   }
 917 
 918   Label L_fallthrough;
 919   int label_nulls = 0;
 920   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
 921   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
 922   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
 923   assert(label_nulls <= 1, "at most one NULL in the batch");
 924 
 925   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
 926   int sco_offset = in_bytes(Klass::super_check_offset_offset());
 927   Address super_check_offset_addr(super_klass, sco_offset);
 928 
 929   // Hacked jmp, which may only be used just before L_fallthrough.
 930 #define final_jmp(label)                                                \
 931   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
 932   else                            b(label)                /*omit semi*/
 933 
 934   // If the pointers are equal, we are done (e.g., String[] elements).
 935   // This self-check enables sharing of secondary supertype arrays among
 936   // non-primary types such as array-of-interface.  Otherwise, each such
 937   // type would need its own customized SSA.
 938   // We move this check to the front of the fast path because many
 939   // type checks are in fact trivially successful in this manner,
 940   // so we get a nicely predicted branch right at the start of the check.
 941   cmp(sub_klass, super_klass);
 942   br(Assembler::EQ, *L_success);
 943 
 944   // Check the supertype display:
 945   if (must_load_sco) {
 946     ldrw(temp_reg, super_check_offset_addr);
 947     super_check_offset = RegisterOrConstant(temp_reg);
 948   }
 949   Address super_check_addr(sub_klass, super_check_offset);
 950   ldr(rscratch1, super_check_addr);
 951   cmp(super_klass, rscratch1); // load displayed supertype
 952 
 953   // This check has worked decisively for primary supers.
 954   // Secondary supers are sought in the super_cache ('super_cache_addr').
 955   // (Secondary supers are interfaces and very deeply nested subtypes.)
 956   // This works in the same check above because of a tricky aliasing
 957   // between the super_cache and the primary super display elements.
 958   // (The 'super_check_addr' can address either, as the case requires.)
 959   // Note that the cache is updated below if it does not help us find
 960   // what we need immediately.
 961   // So if it was a primary super, we can just fail immediately.
 962   // Otherwise, it's the slow path for us (no success at this point).
 963 
 964   if (super_check_offset.is_register()) {
 965     br(Assembler::EQ, *L_success);
 966     subs(zr, super_check_offset.as_register(), sc_offset);
 967     if (L_failure == &L_fallthrough) {
 968       br(Assembler::EQ, *L_slow_path);
 969     } else {
 970       br(Assembler::NE, *L_failure);
 971       final_jmp(*L_slow_path);
 972     }
 973   } else if (super_check_offset.as_constant() == sc_offset) {
 974     // Need a slow path; fast failure is impossible.
 975     if (L_slow_path == &L_fallthrough) {
 976       br(Assembler::EQ, *L_success);
 977     } else {
 978       br(Assembler::NE, *L_slow_path);
 979       final_jmp(*L_success);
 980     }
 981   } else {
 982     // No slow path; it's a fast decision.
 983     if (L_failure == &L_fallthrough) {
 984       br(Assembler::EQ, *L_success);
 985     } else {
 986       br(Assembler::NE, *L_failure);
 987       final_jmp(*L_success);
 988     }
 989   }
 990 
 991   bind(L_fallthrough);
 992 
 993 #undef final_jmp
 994 }
 995 
 996 // These two are taken from x86, but they look generally useful
 997 
 998 // scans count pointer sized words at [addr] for occurrence of value,
 999 // generic
1000 void MacroAssembler::repne_scan(Register addr, Register value, Register count,
1001                                 Register scratch) {
1002   Label Lloop, Lexit;
1003   cbz(count, Lexit);
1004   bind(Lloop);
1005   ldr(scratch, post(addr, wordSize));
1006   cmp(value, scratch);
1007   br(EQ, Lexit);
1008   sub(count, count, 1);
1009   cbnz(count, Lloop);
1010   bind(Lexit);
1011 }
1012 
1013 // scans count 4 byte words at [addr] for occurrence of value,
1014 // generic
1015 void MacroAssembler::repne_scanw(Register addr, Register value, Register count,
1016                                 Register scratch) {
1017   Label Lloop, Lexit;
1018   cbz(count, Lexit);
1019   bind(Lloop);
1020   ldrw(scratch, post(addr, wordSize));
1021   cmpw(value, scratch);
1022   br(EQ, Lexit);
1023   sub(count, count, 1);
1024   cbnz(count, Lloop);
1025   bind(Lexit);
1026 }
1027 
1028 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
1029                                                    Register super_klass,
1030                                                    Register temp_reg,
1031                                                    Register temp2_reg,
1032                                                    Label* L_success,
1033                                                    Label* L_failure,
1034                                                    bool set_cond_codes) {
1035   assert_different_registers(sub_klass, super_klass, temp_reg);
1036   if (temp2_reg != noreg)
1037     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg, rscratch1);
1038 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
1039 
1040   Label L_fallthrough;
1041   int label_nulls = 0;
1042   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
1043   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
1044   assert(label_nulls <= 1, "at most one NULL in the batch");
1045 
1046   // a couple of useful fields in sub_klass:
1047   int ss_offset = in_bytes(Klass::secondary_supers_offset());
1048   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
1049   Address secondary_supers_addr(sub_klass, ss_offset);
1050   Address super_cache_addr(     sub_klass, sc_offset);
1051 
1052   BLOCK_COMMENT("check_klass_subtype_slow_path");
1053 
1054   // Do a linear scan of the secondary super-klass chain.
1055   // This code is rarely used, so simplicity is a virtue here.
1056   // The repne_scan instruction uses fixed registers, which we must spill.
1057   // Don't worry too much about pre-existing connections with the input regs.
1058 
1059   assert(sub_klass != r0, "killed reg"); // killed by mov(r0, super)
1060   assert(sub_klass != r2, "killed reg"); // killed by lea(r2, &pst_counter)
1061 
1062   RegSet pushed_registers;
1063   if (!IS_A_TEMP(r2))    pushed_registers += r2;
1064   if (!IS_A_TEMP(r5))    pushed_registers += r5;
1065 
1066   if (super_klass != r0 || UseCompressedOops) {
1067     if (!IS_A_TEMP(r0))   pushed_registers += r0;
1068   }
1069 
1070   push(pushed_registers, sp);
1071 
1072   // Get super_klass value into r0 (even if it was in r5 or r2).
1073   if (super_klass != r0) {
1074     mov(r0, super_klass);
1075   }
1076 
1077 #ifndef PRODUCT
1078   mov(rscratch2, (address)&SharedRuntime::_partial_subtype_ctr);
1079   Address pst_counter_addr(rscratch2);
1080   ldr(rscratch1, pst_counter_addr);
1081   add(rscratch1, rscratch1, 1);
1082   str(rscratch1, pst_counter_addr);
1083 #endif //PRODUCT
1084 
1085   // We will consult the secondary-super array.
1086   ldr(r5, secondary_supers_addr);
1087   // Load the array length.
1088   ldrw(r2, Address(r5, Array<Klass*>::length_offset_in_bytes()));
1089   // Skip to start of data.
1090   add(r5, r5, Array<Klass*>::base_offset_in_bytes());
1091 
1092   cmp(sp, zr); // Clear Z flag; SP is never zero
1093   // Scan R2 words at [R5] for an occurrence of R0.
1094   // Set NZ/Z based on last compare.
1095   repne_scan(r5, r0, r2, rscratch1);
1096 
1097   // Unspill the temp. registers:
1098   pop(pushed_registers, sp);
1099 
1100   br(Assembler::NE, *L_failure);
1101 
1102   // Success.  Cache the super we found and proceed in triumph.
1103   str(super_klass, super_cache_addr);
1104 
1105   if (L_success != &L_fallthrough) {
1106     b(*L_success);
1107   }
1108 
1109 #undef IS_A_TEMP
1110 
1111   bind(L_fallthrough);
1112 }
1113 
1114 void MacroAssembler::clinit_barrier(Register klass, Register scratch, Label* L_fast_path, Label* L_slow_path) {
1115   assert(L_fast_path != NULL || L_slow_path != NULL, "at least one is required");
1116   assert_different_registers(klass, rthread, scratch);
1117 
1118   Label L_fallthrough, L_tmp;
1119   if (L_fast_path == NULL) {
1120     L_fast_path = &L_fallthrough;
1121   } else if (L_slow_path == NULL) {
1122     L_slow_path = &L_fallthrough;
1123   }
1124   // Fast path check: class is fully initialized
1125   ldrb(scratch, Address(klass, InstanceKlass::init_state_offset()));
1126   subs(zr, scratch, InstanceKlass::fully_initialized);
1127   br(Assembler::EQ, *L_fast_path);
1128 
1129   // Fast path check: current thread is initializer thread
1130   ldr(scratch, Address(klass, InstanceKlass::init_thread_offset()));
1131   cmp(rthread, scratch);
1132 
1133   if (L_slow_path == &L_fallthrough) {
1134     br(Assembler::EQ, *L_fast_path);
1135     bind(*L_slow_path);
1136   } else if (L_fast_path == &L_fallthrough) {
1137     br(Assembler::NE, *L_slow_path);
1138     bind(*L_fast_path);
1139   } else {
1140     Unimplemented();
1141   }
1142 }
1143 
1144 void MacroAssembler::_verify_oop(Register reg, const char* s, const char* file, int line) {
1145   if (!VerifyOops) return;
1146 
1147   // Pass register number to verify_oop_subroutine
1148   const char* b = NULL;
1149   {
1150     ResourceMark rm;
1151     stringStream ss;
1152     ss.print("verify_oop: %s: %s (%s:%d)", reg->name(), s, file, line);
1153     b = code_string(ss.as_string());
1154   }
1155   BLOCK_COMMENT("verify_oop {");
1156 
1157   strip_return_address(); // This might happen within a stack frame.
1158   protect_return_address();
1159   stp(r0, rscratch1, Address(pre(sp, -2 * wordSize)));
1160   stp(rscratch2, lr, Address(pre(sp, -2 * wordSize)));
1161 
1162   mov(r0, reg);
1163   movptr(rscratch1, (uintptr_t)(address)b);
1164 
1165   // call indirectly to solve generation ordering problem
1166   lea(rscratch2, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
1167   ldr(rscratch2, Address(rscratch2));
1168   blr(rscratch2);
1169 
1170   ldp(rscratch2, lr, Address(post(sp, 2 * wordSize)));
1171   ldp(r0, rscratch1, Address(post(sp, 2 * wordSize)));
1172   authenticate_return_address();
1173 
1174   BLOCK_COMMENT("} verify_oop");
1175 }
1176 
1177 void MacroAssembler::_verify_oop_addr(Address addr, const char* s, const char* file, int line) {
1178   if (!VerifyOops) return;
1179 
1180   const char* b = NULL;
1181   {
1182     ResourceMark rm;
1183     stringStream ss;
1184     ss.print("verify_oop_addr: %s (%s:%d)", s, file, line);
1185     b = code_string(ss.as_string());
1186   }
1187   BLOCK_COMMENT("verify_oop_addr {");
1188 
1189   strip_return_address(); // This might happen within a stack frame.
1190   protect_return_address();
1191   stp(r0, rscratch1, Address(pre(sp, -2 * wordSize)));
1192   stp(rscratch2, lr, Address(pre(sp, -2 * wordSize)));
1193 
1194   // addr may contain sp so we will have to adjust it based on the
1195   // pushes that we just did.
1196   if (addr.uses(sp)) {
1197     lea(r0, addr);
1198     ldr(r0, Address(r0, 4 * wordSize));
1199   } else {
1200     ldr(r0, addr);
1201   }
1202   movptr(rscratch1, (uintptr_t)(address)b);
1203 
1204   // call indirectly to solve generation ordering problem
1205   lea(rscratch2, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
1206   ldr(rscratch2, Address(rscratch2));
1207   blr(rscratch2);
1208 
1209   ldp(rscratch2, lr, Address(post(sp, 2 * wordSize)));
1210   ldp(r0, rscratch1, Address(post(sp, 2 * wordSize)));
1211   authenticate_return_address();
1212 
1213   BLOCK_COMMENT("} verify_oop_addr");
1214 }
1215 
1216 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
1217                                          int extra_slot_offset) {
1218   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
1219   int stackElementSize = Interpreter::stackElementSize;
1220   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
1221 #ifdef ASSERT
1222   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
1223   assert(offset1 - offset == stackElementSize, "correct arithmetic");
1224 #endif
1225   if (arg_slot.is_constant()) {
1226     return Address(esp, arg_slot.as_constant() * stackElementSize
1227                    + offset);
1228   } else {
1229     add(rscratch1, esp, arg_slot.as_register(),
1230         ext::uxtx, exact_log2(stackElementSize));
1231     return Address(rscratch1, offset);
1232   }
1233 }
1234 
1235 void MacroAssembler::call_VM_leaf_base(address entry_point,
1236                                        int number_of_arguments,
1237                                        Label *retaddr) {
1238   Label E, L;
1239 
1240   stp(rscratch1, rmethod, Address(pre(sp, -2 * wordSize)));
1241 
1242   mov(rscratch1, entry_point);
1243   blr(rscratch1);
1244   if (retaddr)
1245     bind(*retaddr);
1246 
1247   ldp(rscratch1, rmethod, Address(post(sp, 2 * wordSize)));
1248 }
1249 
1250 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
1251   call_VM_leaf_base(entry_point, number_of_arguments);
1252 }
1253 
1254 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
1255   pass_arg0(this, arg_0);
1256   call_VM_leaf_base(entry_point, 1);
1257 }
1258 
1259 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
1260   pass_arg0(this, arg_0);
1261   pass_arg1(this, arg_1);
1262   call_VM_leaf_base(entry_point, 2);
1263 }
1264 
1265 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0,
1266                                   Register arg_1, Register arg_2) {
1267   pass_arg0(this, arg_0);
1268   pass_arg1(this, arg_1);
1269   pass_arg2(this, arg_2);
1270   call_VM_leaf_base(entry_point, 3);
1271 }
1272 
1273 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
1274   pass_arg0(this, arg_0);
1275   MacroAssembler::call_VM_leaf_base(entry_point, 1);
1276 }
1277 
1278 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
1279 
1280   assert(arg_0 != c_rarg1, "smashed arg");
1281   pass_arg1(this, arg_1);
1282   pass_arg0(this, arg_0);
1283   MacroAssembler::call_VM_leaf_base(entry_point, 2);
1284 }
1285 
1286 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
1287   assert(arg_0 != c_rarg2, "smashed arg");
1288   assert(arg_1 != c_rarg2, "smashed arg");
1289   pass_arg2(this, arg_2);
1290   assert(arg_0 != c_rarg1, "smashed arg");
1291   pass_arg1(this, arg_1);
1292   pass_arg0(this, arg_0);
1293   MacroAssembler::call_VM_leaf_base(entry_point, 3);
1294 }
1295 
1296 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
1297   assert(arg_0 != c_rarg3, "smashed arg");
1298   assert(arg_1 != c_rarg3, "smashed arg");
1299   assert(arg_2 != c_rarg3, "smashed arg");
1300   pass_arg3(this, arg_3);
1301   assert(arg_0 != c_rarg2, "smashed arg");
1302   assert(arg_1 != c_rarg2, "smashed arg");
1303   pass_arg2(this, arg_2);
1304   assert(arg_0 != c_rarg1, "smashed arg");
1305   pass_arg1(this, arg_1);
1306   pass_arg0(this, arg_0);
1307   MacroAssembler::call_VM_leaf_base(entry_point, 4);
1308 }
1309 
1310 void MacroAssembler::null_check(Register reg, int offset) {
1311   if (needs_explicit_null_check(offset)) {
1312     // provoke OS NULL exception if reg = NULL by
1313     // accessing M[reg] w/o changing any registers
1314     // NOTE: this is plenty to provoke a segv
1315     ldr(zr, Address(reg));
1316   } else {
1317     // nothing to do, (later) access of M[reg + offset]
1318     // will provoke OS NULL exception if reg = NULL
1319   }
1320 }
1321 
1322 // MacroAssembler protected routines needed to implement
1323 // public methods
1324 
1325 void MacroAssembler::mov(Register r, Address dest) {
1326   code_section()->relocate(pc(), dest.rspec());
1327   uint64_t imm64 = (uint64_t)dest.target();
1328   movptr(r, imm64);
1329 }
1330 
1331 // Move a constant pointer into r.  In AArch64 mode the virtual
1332 // address space is 48 bits in size, so we only need three
1333 // instructions to create a patchable instruction sequence that can
1334 // reach anywhere.
1335 void MacroAssembler::movptr(Register r, uintptr_t imm64) {
1336 #ifndef PRODUCT
1337   {
1338     char buffer[64];
1339     snprintf(buffer, sizeof(buffer), "0x%" PRIX64, (uint64_t)imm64);
1340     block_comment(buffer);
1341   }
1342 #endif
1343   assert(imm64 < (1ull << 48), "48-bit overflow in address constant");
1344   movz(r, imm64 & 0xffff);
1345   imm64 >>= 16;
1346   movk(r, imm64 & 0xffff, 16);
1347   imm64 >>= 16;
1348   movk(r, imm64 & 0xffff, 32);
1349 }
1350 
1351 // Macro to mov replicated immediate to vector register.
1352 // imm64: only the lower 8/16/32 bits are considered for B/H/S type. That is,
1353 //        the upper 56/48/32 bits must be zeros for B/H/S type.
1354 // Vd will get the following values for different arrangements in T
1355 //   imm64 == hex 000000gh  T8B:  Vd = ghghghghghghghgh
1356 //   imm64 == hex 000000gh  T16B: Vd = ghghghghghghghghghghghghghghghgh
1357 //   imm64 == hex 0000efgh  T4H:  Vd = efghefghefghefgh
1358 //   imm64 == hex 0000efgh  T8H:  Vd = efghefghefghefghefghefghefghefgh
1359 //   imm64 == hex abcdefgh  T2S:  Vd = abcdefghabcdefgh
1360 //   imm64 == hex abcdefgh  T4S:  Vd = abcdefghabcdefghabcdefghabcdefgh
1361 //   imm64 == hex abcdefgh  T1D:  Vd = 00000000abcdefgh
1362 //   imm64 == hex abcdefgh  T2D:  Vd = 00000000abcdefgh00000000abcdefgh
1363 // Clobbers rscratch1
1364 void MacroAssembler::mov(FloatRegister Vd, SIMD_Arrangement T, uint64_t imm64) {
1365   assert(T != T1Q, "unsupported");
1366   if (T == T1D || T == T2D) {
1367     int imm = operand_valid_for_movi_immediate(imm64, T);
1368     if (-1 != imm) {
1369       movi(Vd, T, imm);
1370     } else {
1371       mov(rscratch1, imm64);
1372       dup(Vd, T, rscratch1);
1373     }
1374     return;
1375   }
1376 
1377 #ifdef ASSERT
1378   if (T == T8B || T == T16B) assert((imm64 & ~0xff) == 0, "extraneous bits (T8B/T16B)");
1379   if (T == T4H || T == T8H) assert((imm64  & ~0xffff) == 0, "extraneous bits (T4H/T8H)");
1380   if (T == T2S || T == T4S) assert((imm64  & ~0xffffffff) == 0, "extraneous bits (T2S/T4S)");
1381 #endif
1382   int shift = operand_valid_for_movi_immediate(imm64, T);
1383   uint32_t imm32 = imm64 & 0xffffffffULL;
1384   if (shift >= 0) {
1385     movi(Vd, T, (imm32 >> shift) & 0xff, shift);
1386   } else {
1387     movw(rscratch1, imm32);
1388     dup(Vd, T, rscratch1);
1389   }
1390 }
1391 
1392 void MacroAssembler::mov_immediate64(Register dst, uint64_t imm64)
1393 {
1394 #ifndef PRODUCT
1395   {
1396     char buffer[64];
1397     snprintf(buffer, sizeof(buffer), "0x%" PRIX64, imm64);
1398     block_comment(buffer);
1399   }
1400 #endif
1401   if (operand_valid_for_logical_immediate(false, imm64)) {
1402     orr(dst, zr, imm64);
1403   } else {
1404     // we can use a combination of MOVZ or MOVN with
1405     // MOVK to build up the constant
1406     uint64_t imm_h[4];
1407     int zero_count = 0;
1408     int neg_count = 0;
1409     int i;
1410     for (i = 0; i < 4; i++) {
1411       imm_h[i] = ((imm64 >> (i * 16)) & 0xffffL);
1412       if (imm_h[i] == 0) {
1413         zero_count++;
1414       } else if (imm_h[i] == 0xffffL) {
1415         neg_count++;
1416       }
1417     }
1418     if (zero_count == 4) {
1419       // one MOVZ will do
1420       movz(dst, 0);
1421     } else if (neg_count == 4) {
1422       // one MOVN will do
1423       movn(dst, 0);
1424     } else if (zero_count == 3) {
1425       for (i = 0; i < 4; i++) {
1426         if (imm_h[i] != 0L) {
1427           movz(dst, (uint32_t)imm_h[i], (i << 4));
1428           break;
1429         }
1430       }
1431     } else if (neg_count == 3) {
1432       // one MOVN will do
1433       for (int i = 0; i < 4; i++) {
1434         if (imm_h[i] != 0xffffL) {
1435           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
1436           break;
1437         }
1438       }
1439     } else if (zero_count == 2) {
1440       // one MOVZ and one MOVK will do
1441       for (i = 0; i < 3; i++) {
1442         if (imm_h[i] != 0L) {
1443           movz(dst, (uint32_t)imm_h[i], (i << 4));
1444           i++;
1445           break;
1446         }
1447       }
1448       for (;i < 4; i++) {
1449         if (imm_h[i] != 0L) {
1450           movk(dst, (uint32_t)imm_h[i], (i << 4));
1451         }
1452       }
1453     } else if (neg_count == 2) {
1454       // one MOVN and one MOVK will do
1455       for (i = 0; i < 4; i++) {
1456         if (imm_h[i] != 0xffffL) {
1457           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
1458           i++;
1459           break;
1460         }
1461       }
1462       for (;i < 4; i++) {
1463         if (imm_h[i] != 0xffffL) {
1464           movk(dst, (uint32_t)imm_h[i], (i << 4));
1465         }
1466       }
1467     } else if (zero_count == 1) {
1468       // one MOVZ and two MOVKs will do
1469       for (i = 0; i < 4; i++) {
1470         if (imm_h[i] != 0L) {
1471           movz(dst, (uint32_t)imm_h[i], (i << 4));
1472           i++;
1473           break;
1474         }
1475       }
1476       for (;i < 4; i++) {
1477         if (imm_h[i] != 0x0L) {
1478           movk(dst, (uint32_t)imm_h[i], (i << 4));
1479         }
1480       }
1481     } else if (neg_count == 1) {
1482       // one MOVN and two MOVKs will do
1483       for (i = 0; i < 4; i++) {
1484         if (imm_h[i] != 0xffffL) {
1485           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
1486           i++;
1487           break;
1488         }
1489       }
1490       for (;i < 4; i++) {
1491         if (imm_h[i] != 0xffffL) {
1492           movk(dst, (uint32_t)imm_h[i], (i << 4));
1493         }
1494       }
1495     } else {
1496       // use a MOVZ and 3 MOVKs (makes it easier to debug)
1497       movz(dst, (uint32_t)imm_h[0], 0);
1498       for (i = 1; i < 4; i++) {
1499         movk(dst, (uint32_t)imm_h[i], (i << 4));
1500       }
1501     }
1502   }
1503 }
1504 
1505 void MacroAssembler::mov_immediate32(Register dst, uint32_t imm32)
1506 {
1507 #ifndef PRODUCT
1508     {
1509       char buffer[64];
1510       snprintf(buffer, sizeof(buffer), "0x%" PRIX32, imm32);
1511       block_comment(buffer);
1512     }
1513 #endif
1514   if (operand_valid_for_logical_immediate(true, imm32)) {
1515     orrw(dst, zr, imm32);
1516   } else {
1517     // we can use MOVZ, MOVN or two calls to MOVK to build up the
1518     // constant
1519     uint32_t imm_h[2];
1520     imm_h[0] = imm32 & 0xffff;
1521     imm_h[1] = ((imm32 >> 16) & 0xffff);
1522     if (imm_h[0] == 0) {
1523       movzw(dst, imm_h[1], 16);
1524     } else if (imm_h[0] == 0xffff) {
1525       movnw(dst, imm_h[1] ^ 0xffff, 16);
1526     } else if (imm_h[1] == 0) {
1527       movzw(dst, imm_h[0], 0);
1528     } else if (imm_h[1] == 0xffff) {
1529       movnw(dst, imm_h[0] ^ 0xffff, 0);
1530     } else {
1531       // use a MOVZ and MOVK (makes it easier to debug)
1532       movzw(dst, imm_h[0], 0);
1533       movkw(dst, imm_h[1], 16);
1534     }
1535   }
1536 }
1537 
1538 // Form an address from base + offset in Rd.  Rd may or may
1539 // not actually be used: you must use the Address that is returned.
1540 // It is up to you to ensure that the shift provided matches the size
1541 // of your data.
1542 Address MacroAssembler::form_address(Register Rd, Register base, int64_t byte_offset, int shift) {
1543   if (Address::offset_ok_for_immed(byte_offset, shift))
1544     // It fits; no need for any heroics
1545     return Address(base, byte_offset);
1546 
1547   // Don't do anything clever with negative or misaligned offsets
1548   unsigned mask = (1 << shift) - 1;
1549   if (byte_offset < 0 || byte_offset & mask) {
1550     mov(Rd, byte_offset);
1551     add(Rd, base, Rd);
1552     return Address(Rd);
1553   }
1554 
1555   // See if we can do this with two 12-bit offsets
1556   {
1557     uint64_t word_offset = byte_offset >> shift;
1558     uint64_t masked_offset = word_offset & 0xfff000;
1559     if (Address::offset_ok_for_immed(word_offset - masked_offset, 0)
1560         && Assembler::operand_valid_for_add_sub_immediate(masked_offset << shift)) {
1561       add(Rd, base, masked_offset << shift);
1562       word_offset -= masked_offset;
1563       return Address(Rd, word_offset << shift);
1564     }
1565   }
1566 
1567   // Do it the hard way
1568   mov(Rd, byte_offset);
1569   add(Rd, base, Rd);
1570   return Address(Rd);
1571 }
1572 
1573 void MacroAssembler::atomic_incw(Register counter_addr, Register tmp, Register tmp2) {
1574   if (UseLSE) {
1575     mov(tmp, 1);
1576     ldadd(Assembler::word, tmp, zr, counter_addr);
1577     return;
1578   }
1579   Label retry_load;
1580   if (VM_Version::supports_stxr_prefetch())
1581     prfm(Address(counter_addr), PSTL1STRM);
1582   bind(retry_load);
1583   // flush and load exclusive from the memory location
1584   ldxrw(tmp, counter_addr);
1585   addw(tmp, tmp, 1);
1586   // if we store+flush with no intervening write tmp will be zero
1587   stxrw(tmp2, tmp, counter_addr);
1588   cbnzw(tmp2, retry_load);
1589 }
1590 
1591 
1592 int MacroAssembler::corrected_idivl(Register result, Register ra, Register rb,
1593                                     bool want_remainder, Register scratch)
1594 {
1595   // Full implementation of Java idiv and irem.  The function
1596   // returns the (pc) offset of the div instruction - may be needed
1597   // for implicit exceptions.
1598   //
1599   // constraint : ra/rb =/= scratch
1600   //         normal case
1601   //
1602   // input : ra: dividend
1603   //         rb: divisor
1604   //
1605   // result: either
1606   //         quotient  (= ra idiv rb)
1607   //         remainder (= ra irem rb)
1608 
1609   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
1610 
1611   int idivl_offset = offset();
1612   if (! want_remainder) {
1613     sdivw(result, ra, rb);
1614   } else {
1615     sdivw(scratch, ra, rb);
1616     Assembler::msubw(result, scratch, rb, ra);
1617   }
1618 
1619   return idivl_offset;
1620 }
1621 
1622 int MacroAssembler::corrected_idivq(Register result, Register ra, Register rb,
1623                                     bool want_remainder, Register scratch)
1624 {
1625   // Full implementation of Java ldiv and lrem.  The function
1626   // returns the (pc) offset of the div instruction - may be needed
1627   // for implicit exceptions.
1628   //
1629   // constraint : ra/rb =/= scratch
1630   //         normal case
1631   //
1632   // input : ra: dividend
1633   //         rb: divisor
1634   //
1635   // result: either
1636   //         quotient  (= ra idiv rb)
1637   //         remainder (= ra irem rb)
1638 
1639   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
1640 
1641   int idivq_offset = offset();
1642   if (! want_remainder) {
1643     sdiv(result, ra, rb);
1644   } else {
1645     sdiv(scratch, ra, rb);
1646     Assembler::msub(result, scratch, rb, ra);
1647   }
1648 
1649   return idivq_offset;
1650 }
1651 
1652 void MacroAssembler::membar(Membar_mask_bits order_constraint) {
1653   address prev = pc() - NativeMembar::instruction_size;
1654   address last = code()->last_insn();
1655   if (last != NULL && nativeInstruction_at(last)->is_Membar() && prev == last) {
1656     NativeMembar *bar = NativeMembar_at(prev);
1657     // We are merging two memory barrier instructions.  On AArch64 we
1658     // can do this simply by ORing them together.
1659     bar->set_kind(bar->get_kind() | order_constraint);
1660     BLOCK_COMMENT("merged membar");
1661   } else {
1662     code()->set_last_insn(pc());
1663     dmb(Assembler::barrier(order_constraint));
1664   }
1665 }
1666 
1667 bool MacroAssembler::try_merge_ldst(Register rt, const Address &adr, size_t size_in_bytes, bool is_store) {
1668   if (ldst_can_merge(rt, adr, size_in_bytes, is_store)) {
1669     merge_ldst(rt, adr, size_in_bytes, is_store);
1670     code()->clear_last_insn();
1671     return true;
1672   } else {
1673     assert(size_in_bytes == 8 || size_in_bytes == 4, "only 8 bytes or 4 bytes load/store is supported.");
1674     const uint64_t mask = size_in_bytes - 1;
1675     if (adr.getMode() == Address::base_plus_offset &&
1676         (adr.offset() & mask) == 0) { // only supports base_plus_offset.
1677       code()->set_last_insn(pc());
1678     }
1679     return false;
1680   }
1681 }
1682 
1683 void MacroAssembler::ldr(Register Rx, const Address &adr) {
1684   // We always try to merge two adjacent loads into one ldp.
1685   if (!try_merge_ldst(Rx, adr, 8, false)) {
1686     Assembler::ldr(Rx, adr);
1687   }
1688 }
1689 
1690 void MacroAssembler::ldrw(Register Rw, const Address &adr) {
1691   // We always try to merge two adjacent loads into one ldp.
1692   if (!try_merge_ldst(Rw, adr, 4, false)) {
1693     Assembler::ldrw(Rw, adr);
1694   }
1695 }
1696 
1697 void MacroAssembler::str(Register Rx, const Address &adr) {
1698   // We always try to merge two adjacent stores into one stp.
1699   if (!try_merge_ldst(Rx, adr, 8, true)) {
1700     Assembler::str(Rx, adr);
1701   }
1702 }
1703 
1704 void MacroAssembler::strw(Register Rw, const Address &adr) {
1705   // We always try to merge two adjacent stores into one stp.
1706   if (!try_merge_ldst(Rw, adr, 4, true)) {
1707     Assembler::strw(Rw, adr);
1708   }
1709 }
1710 
1711 // MacroAssembler routines found actually to be needed
1712 
1713 void MacroAssembler::push(Register src)
1714 {
1715   str(src, Address(pre(esp, -1 * wordSize)));
1716 }
1717 
1718 void MacroAssembler::pop(Register dst)
1719 {
1720   ldr(dst, Address(post(esp, 1 * wordSize)));
1721 }
1722 
1723 // Note: load_unsigned_short used to be called load_unsigned_word.
1724 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
1725   int off = offset();
1726   ldrh(dst, src);
1727   return off;
1728 }
1729 
1730 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
1731   int off = offset();
1732   ldrb(dst, src);
1733   return off;
1734 }
1735 
1736 int MacroAssembler::load_signed_short(Register dst, Address src) {
1737   int off = offset();
1738   ldrsh(dst, src);
1739   return off;
1740 }
1741 
1742 int MacroAssembler::load_signed_byte(Register dst, Address src) {
1743   int off = offset();
1744   ldrsb(dst, src);
1745   return off;
1746 }
1747 
1748 int MacroAssembler::load_signed_short32(Register dst, Address src) {
1749   int off = offset();
1750   ldrshw(dst, src);
1751   return off;
1752 }
1753 
1754 int MacroAssembler::load_signed_byte32(Register dst, Address src) {
1755   int off = offset();
1756   ldrsbw(dst, src);
1757   return off;
1758 }
1759 
1760 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
1761   switch (size_in_bytes) {
1762   case  8:  ldr(dst, src); break;
1763   case  4:  ldrw(dst, src); break;
1764   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
1765   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
1766   default:  ShouldNotReachHere();
1767   }
1768 }
1769 
1770 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
1771   switch (size_in_bytes) {
1772   case  8:  str(src, dst); break;
1773   case  4:  strw(src, dst); break;
1774   case  2:  strh(src, dst); break;
1775   case  1:  strb(src, dst); break;
1776   default:  ShouldNotReachHere();
1777   }
1778 }
1779 
1780 void MacroAssembler::decrementw(Register reg, int value)
1781 {
1782   if (value < 0)  { incrementw(reg, -value);      return; }
1783   if (value == 0) {                               return; }
1784   if (value < (1 << 12)) { subw(reg, reg, value); return; }
1785   /* else */ {
1786     guarantee(reg != rscratch2, "invalid dst for register decrement");
1787     movw(rscratch2, (unsigned)value);
1788     subw(reg, reg, rscratch2);
1789   }
1790 }
1791 
1792 void MacroAssembler::decrement(Register reg, int value)
1793 {
1794   if (value < 0)  { increment(reg, -value);      return; }
1795   if (value == 0) {                              return; }
1796   if (value < (1 << 12)) { sub(reg, reg, value); return; }
1797   /* else */ {
1798     assert(reg != rscratch2, "invalid dst for register decrement");
1799     mov(rscratch2, (uint64_t)value);
1800     sub(reg, reg, rscratch2);
1801   }
1802 }
1803 
1804 void MacroAssembler::decrementw(Address dst, int value)
1805 {
1806   assert(!dst.uses(rscratch1), "invalid dst for address decrement");
1807   if (dst.getMode() == Address::literal) {
1808     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
1809     lea(rscratch2, dst);
1810     dst = Address(rscratch2);
1811   }
1812   ldrw(rscratch1, dst);
1813   decrementw(rscratch1, value);
1814   strw(rscratch1, dst);
1815 }
1816 
1817 void MacroAssembler::decrement(Address dst, int value)
1818 {
1819   assert(!dst.uses(rscratch1), "invalid address for decrement");
1820   if (dst.getMode() == Address::literal) {
1821     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
1822     lea(rscratch2, dst);
1823     dst = Address(rscratch2);
1824   }
1825   ldr(rscratch1, dst);
1826   decrement(rscratch1, value);
1827   str(rscratch1, dst);
1828 }
1829 
1830 void MacroAssembler::incrementw(Register reg, int value)
1831 {
1832   if (value < 0)  { decrementw(reg, -value);      return; }
1833   if (value == 0) {                               return; }
1834   if (value < (1 << 12)) { addw(reg, reg, value); return; }
1835   /* else */ {
1836     assert(reg != rscratch2, "invalid dst for register increment");
1837     movw(rscratch2, (unsigned)value);
1838     addw(reg, reg, rscratch2);
1839   }
1840 }
1841 
1842 void MacroAssembler::increment(Register reg, int value)
1843 {
1844   if (value < 0)  { decrement(reg, -value);      return; }
1845   if (value == 0) {                              return; }
1846   if (value < (1 << 12)) { add(reg, reg, value); return; }
1847   /* else */ {
1848     assert(reg != rscratch2, "invalid dst for register increment");
1849     movw(rscratch2, (unsigned)value);
1850     add(reg, reg, rscratch2);
1851   }
1852 }
1853 
1854 void MacroAssembler::incrementw(Address dst, int value)
1855 {
1856   assert(!dst.uses(rscratch1), "invalid dst for address increment");
1857   if (dst.getMode() == Address::literal) {
1858     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
1859     lea(rscratch2, dst);
1860     dst = Address(rscratch2);
1861   }
1862   ldrw(rscratch1, dst);
1863   incrementw(rscratch1, value);
1864   strw(rscratch1, dst);
1865 }
1866 
1867 void MacroAssembler::increment(Address dst, int value)
1868 {
1869   assert(!dst.uses(rscratch1), "invalid dst for address increment");
1870   if (dst.getMode() == Address::literal) {
1871     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
1872     lea(rscratch2, dst);
1873     dst = Address(rscratch2);
1874   }
1875   ldr(rscratch1, dst);
1876   increment(rscratch1, value);
1877   str(rscratch1, dst);
1878 }
1879 
1880 // Push lots of registers in the bit set supplied.  Don't push sp.
1881 // Return the number of words pushed
1882 int MacroAssembler::push(unsigned int bitset, Register stack) {
1883   int words_pushed = 0;
1884 
1885   // Scan bitset to accumulate register pairs
1886   unsigned char regs[32];
1887   int count = 0;
1888   for (int reg = 0; reg <= 30; reg++) {
1889     if (1 & bitset)
1890       regs[count++] = reg;
1891     bitset >>= 1;
1892   }
1893   regs[count++] = zr->encoding_nocheck();
1894   count &= ~1;  // Only push an even number of regs
1895 
1896   if (count) {
1897     stp(as_Register(regs[0]), as_Register(regs[1]),
1898        Address(pre(stack, -count * wordSize)));
1899     words_pushed += 2;
1900   }
1901   for (int i = 2; i < count; i += 2) {
1902     stp(as_Register(regs[i]), as_Register(regs[i+1]),
1903        Address(stack, i * wordSize));
1904     words_pushed += 2;
1905   }
1906 
1907   assert(words_pushed == count, "oops, pushed != count");
1908 
1909   return count;
1910 }
1911 
1912 int MacroAssembler::pop(unsigned int bitset, Register stack) {
1913   int words_pushed = 0;
1914 
1915   // Scan bitset to accumulate register pairs
1916   unsigned char regs[32];
1917   int count = 0;
1918   for (int reg = 0; reg <= 30; reg++) {
1919     if (1 & bitset)
1920       regs[count++] = reg;
1921     bitset >>= 1;
1922   }
1923   regs[count++] = zr->encoding_nocheck();
1924   count &= ~1;
1925 
1926   for (int i = 2; i < count; i += 2) {
1927     ldp(as_Register(regs[i]), as_Register(regs[i+1]),
1928        Address(stack, i * wordSize));
1929     words_pushed += 2;
1930   }
1931   if (count) {
1932     ldp(as_Register(regs[0]), as_Register(regs[1]),
1933        Address(post(stack, count * wordSize)));
1934     words_pushed += 2;
1935   }
1936 
1937   assert(words_pushed == count, "oops, pushed != count");
1938 
1939   return count;
1940 }
1941 
1942 // Push lots of registers in the bit set supplied.  Don't push sp.
1943 // Return the number of dwords pushed
1944 int MacroAssembler::push_fp(unsigned int bitset, Register stack) {
1945   int words_pushed = 0;
1946   bool use_sve = false;
1947   int sve_vector_size_in_bytes = 0;
1948 
1949 #ifdef COMPILER2
1950   use_sve = Matcher::supports_scalable_vector();
1951   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
1952 #endif
1953 
1954   // Scan bitset to accumulate register pairs
1955   unsigned char regs[32];
1956   int count = 0;
1957   for (int reg = 0; reg <= 31; reg++) {
1958     if (1 & bitset)
1959       regs[count++] = reg;
1960     bitset >>= 1;
1961   }
1962 
1963   if (count == 0) {
1964     return 0;
1965   }
1966 
1967   // SVE
1968   if (use_sve && sve_vector_size_in_bytes > 16) {
1969     sub(stack, stack, sve_vector_size_in_bytes * count);
1970     for (int i = 0; i < count; i++) {
1971       sve_str(as_FloatRegister(regs[i]), Address(stack, i));
1972     }
1973     return count * sve_vector_size_in_bytes / 8;
1974   }
1975 
1976   // NEON
1977   if (count == 1) {
1978     strq(as_FloatRegister(regs[0]), Address(pre(stack, -wordSize * 2)));
1979     return 2;
1980   }
1981 
1982   bool odd = (count & 1) == 1;
1983   int push_slots = count + (odd ? 1 : 0);
1984 
1985   // Always pushing full 128 bit registers.
1986   stpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(pre(stack, -push_slots * wordSize * 2)));
1987   words_pushed += 2;
1988 
1989   for (int i = 2; i + 1 < count; i += 2) {
1990     stpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
1991     words_pushed += 2;
1992   }
1993 
1994   if (odd) {
1995     strq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
1996     words_pushed++;
1997   }
1998 
1999   assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
2000   return count * 2;
2001 }
2002 
2003 // Return the number of dwords popped
2004 int MacroAssembler::pop_fp(unsigned int bitset, Register stack) {
2005   int words_pushed = 0;
2006   bool use_sve = false;
2007   int sve_vector_size_in_bytes = 0;
2008 
2009 #ifdef COMPILER2
2010   use_sve = Matcher::supports_scalable_vector();
2011   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
2012 #endif
2013   // Scan bitset to accumulate register pairs
2014   unsigned char regs[32];
2015   int count = 0;
2016   for (int reg = 0; reg <= 31; reg++) {
2017     if (1 & bitset)
2018       regs[count++] = reg;
2019     bitset >>= 1;
2020   }
2021 
2022   if (count == 0) {
2023     return 0;
2024   }
2025 
2026   // SVE
2027   if (use_sve && sve_vector_size_in_bytes > 16) {
2028     for (int i = count - 1; i >= 0; i--) {
2029       sve_ldr(as_FloatRegister(regs[i]), Address(stack, i));
2030     }
2031     add(stack, stack, sve_vector_size_in_bytes * count);
2032     return count * sve_vector_size_in_bytes / 8;
2033   }
2034 
2035   // NEON
2036   if (count == 1) {
2037     ldrq(as_FloatRegister(regs[0]), Address(post(stack, wordSize * 2)));
2038     return 2;
2039   }
2040 
2041   bool odd = (count & 1) == 1;
2042   int push_slots = count + (odd ? 1 : 0);
2043 
2044   if (odd) {
2045     ldrq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
2046     words_pushed++;
2047   }
2048 
2049   for (int i = 2; i + 1 < count; i += 2) {
2050     ldpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
2051     words_pushed += 2;
2052   }
2053 
2054   ldpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(post(stack, push_slots * wordSize * 2)));
2055   words_pushed += 2;
2056 
2057   assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
2058 
2059   return count * 2;
2060 }
2061 
2062 // Return the number of dwords pushed
2063 int MacroAssembler::push_p(unsigned int bitset, Register stack) {
2064   bool use_sve = false;
2065   int sve_predicate_size_in_slots = 0;
2066 
2067 #ifdef COMPILER2
2068   use_sve = Matcher::supports_scalable_vector();
2069   if (use_sve) {
2070     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
2071   }
2072 #endif
2073 
2074   if (!use_sve) {
2075     return 0;
2076   }
2077 
2078   unsigned char regs[PRegisterImpl::number_of_saved_registers];
2079   int count = 0;
2080   for (int reg = 0; reg < PRegisterImpl::number_of_saved_registers; reg++) {
2081     if (1 & bitset)
2082       regs[count++] = reg;
2083     bitset >>= 1;
2084   }
2085 
2086   if (count == 0) {
2087     return 0;
2088   }
2089 
2090   int total_push_bytes = align_up(sve_predicate_size_in_slots *
2091                                   VMRegImpl::stack_slot_size * count, 16);
2092   sub(stack, stack, total_push_bytes);
2093   for (int i = 0; i < count; i++) {
2094     sve_str(as_PRegister(regs[i]), Address(stack, i));
2095   }
2096   return total_push_bytes / 8;
2097 }
2098 
2099 // Return the number of dwords popped
2100 int MacroAssembler::pop_p(unsigned int bitset, Register stack) {
2101   bool use_sve = false;
2102   int sve_predicate_size_in_slots = 0;
2103 
2104 #ifdef COMPILER2
2105   use_sve = Matcher::supports_scalable_vector();
2106   if (use_sve) {
2107     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
2108   }
2109 #endif
2110 
2111   if (!use_sve) {
2112     return 0;
2113   }
2114 
2115   unsigned char regs[PRegisterImpl::number_of_saved_registers];
2116   int count = 0;
2117   for (int reg = 0; reg < PRegisterImpl::number_of_saved_registers; reg++) {
2118     if (1 & bitset)
2119       regs[count++] = reg;
2120     bitset >>= 1;
2121   }
2122 
2123   if (count == 0) {
2124     return 0;
2125   }
2126 
2127   int total_pop_bytes = align_up(sve_predicate_size_in_slots *
2128                                  VMRegImpl::stack_slot_size * count, 16);
2129   for (int i = count - 1; i >= 0; i--) {
2130     sve_ldr(as_PRegister(regs[i]), Address(stack, i));
2131   }
2132   add(stack, stack, total_pop_bytes);
2133   return total_pop_bytes / 8;
2134 }
2135 
2136 #ifdef ASSERT
2137 void MacroAssembler::verify_heapbase(const char* msg) {
2138 #if 0
2139   assert (UseCompressedOops || UseCompressedClassPointers, "should be compressed");
2140   assert (Universe::heap() != NULL, "java heap should be initialized");
2141   if (!UseCompressedOops || Universe::ptr_base() == NULL) {
2142     // rheapbase is allocated as general register
2143     return;
2144   }
2145   if (CheckCompressedOops) {
2146     Label ok;
2147     push(1 << rscratch1->encoding(), sp); // cmpptr trashes rscratch1
2148     cmpptr(rheapbase, ExternalAddress((address)CompressedOops::ptrs_base_addr()));
2149     br(Assembler::EQ, ok);
2150     stop(msg);
2151     bind(ok);
2152     pop(1 << rscratch1->encoding(), sp);
2153   }
2154 #endif
2155 }
2156 #endif
2157 
2158 void MacroAssembler::resolve_jobject(Register value, Register thread, Register tmp) {
2159   Label done, not_weak;
2160   cbz(value, done);           // Use NULL as-is.
2161 
2162   STATIC_ASSERT(JNIHandles::weak_tag_mask == 1u);
2163   tbz(r0, 0, not_weak);    // Test for jweak tag.
2164 
2165   // Resolve jweak.
2166   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF, value,
2167                  Address(value, -JNIHandles::weak_tag_value), tmp, thread);
2168   verify_oop(value);
2169   b(done);
2170 
2171   bind(not_weak);
2172   // Resolve (untagged) jobject.
2173   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, 0), tmp, thread);
2174   verify_oop(value);
2175   bind(done);
2176 }
2177 
2178 void MacroAssembler::stop(const char* msg) {
2179   BLOCK_COMMENT(msg);
2180   dcps1(0xdeae);
2181   emit_int64((uintptr_t)msg);
2182 }
2183 
2184 void MacroAssembler::unimplemented(const char* what) {
2185   const char* buf = NULL;
2186   {
2187     ResourceMark rm;
2188     stringStream ss;
2189     ss.print("unimplemented: %s", what);
2190     buf = code_string(ss.as_string());
2191   }
2192   stop(buf);
2193 }
2194 
2195 // If a constant does not fit in an immediate field, generate some
2196 // number of MOV instructions and then perform the operation.
2197 void MacroAssembler::wrap_add_sub_imm_insn(Register Rd, Register Rn, unsigned imm,
2198                                            add_sub_imm_insn insn1,
2199                                            add_sub_reg_insn insn2) {
2200   assert(Rd != zr, "Rd = zr and not setting flags?");
2201   if (operand_valid_for_add_sub_immediate((int)imm)) {
2202     (this->*insn1)(Rd, Rn, imm);
2203   } else {
2204     if (uabs(imm) < (1 << 24)) {
2205        (this->*insn1)(Rd, Rn, imm & -(1 << 12));
2206        (this->*insn1)(Rd, Rd, imm & ((1 << 12)-1));
2207     } else {
2208        assert_different_registers(Rd, Rn);
2209        mov(Rd, (uint64_t)imm);
2210        (this->*insn2)(Rd, Rn, Rd, LSL, 0);
2211     }
2212   }
2213 }
2214 
2215 // Separate vsn which sets the flags. Optimisations are more restricted
2216 // because we must set the flags correctly.
2217 void MacroAssembler::wrap_adds_subs_imm_insn(Register Rd, Register Rn, unsigned imm,
2218                                            add_sub_imm_insn insn1,
2219                                            add_sub_reg_insn insn2) {
2220   if (operand_valid_for_add_sub_immediate((int)imm)) {
2221     (this->*insn1)(Rd, Rn, imm);
2222   } else {
2223     assert_different_registers(Rd, Rn);
2224     assert(Rd != zr, "overflow in immediate operand");
2225     mov(Rd, (uint64_t)imm);
2226     (this->*insn2)(Rd, Rn, Rd, LSL, 0);
2227   }
2228 }
2229 
2230 
2231 void MacroAssembler::add(Register Rd, Register Rn, RegisterOrConstant increment) {
2232   if (increment.is_register()) {
2233     add(Rd, Rn, increment.as_register());
2234   } else {
2235     add(Rd, Rn, increment.as_constant());
2236   }
2237 }
2238 
2239 void MacroAssembler::addw(Register Rd, Register Rn, RegisterOrConstant increment) {
2240   if (increment.is_register()) {
2241     addw(Rd, Rn, increment.as_register());
2242   } else {
2243     addw(Rd, Rn, increment.as_constant());
2244   }
2245 }
2246 
2247 void MacroAssembler::sub(Register Rd, Register Rn, RegisterOrConstant decrement) {
2248   if (decrement.is_register()) {
2249     sub(Rd, Rn, decrement.as_register());
2250   } else {
2251     sub(Rd, Rn, decrement.as_constant());
2252   }
2253 }
2254 
2255 void MacroAssembler::subw(Register Rd, Register Rn, RegisterOrConstant decrement) {
2256   if (decrement.is_register()) {
2257     subw(Rd, Rn, decrement.as_register());
2258   } else {
2259     subw(Rd, Rn, decrement.as_constant());
2260   }
2261 }
2262 
2263 void MacroAssembler::reinit_heapbase()
2264 {
2265   if (UseCompressedOops) {
2266     if (Universe::is_fully_initialized()) {
2267       mov(rheapbase, CompressedOops::ptrs_base());
2268     } else {
2269       lea(rheapbase, ExternalAddress((address)CompressedOops::ptrs_base_addr()));
2270       ldr(rheapbase, Address(rheapbase));
2271     }
2272   }
2273 }
2274 
2275 // this simulates the behaviour of the x86 cmpxchg instruction using a
2276 // load linked/store conditional pair. we use the acquire/release
2277 // versions of these instructions so that we flush pending writes as
2278 // per Java semantics.
2279 
2280 // n.b the x86 version assumes the old value to be compared against is
2281 // in rax and updates rax with the value located in memory if the
2282 // cmpxchg fails. we supply a register for the old value explicitly
2283 
2284 // the aarch64 load linked/store conditional instructions do not
2285 // accept an offset. so, unlike x86, we must provide a plain register
2286 // to identify the memory word to be compared/exchanged rather than a
2287 // register+offset Address.
2288 
2289 void MacroAssembler::cmpxchgptr(Register oldv, Register newv, Register addr, Register tmp,
2290                                 Label &succeed, Label *fail) {
2291   // oldv holds comparison value
2292   // newv holds value to write in exchange
2293   // addr identifies memory word to compare against/update
2294   if (UseLSE) {
2295     mov(tmp, oldv);
2296     casal(Assembler::xword, oldv, newv, addr);
2297     cmp(tmp, oldv);
2298     br(Assembler::EQ, succeed);
2299     membar(AnyAny);
2300   } else {
2301     Label retry_load, nope;
2302     if (VM_Version::supports_stxr_prefetch())
2303       prfm(Address(addr), PSTL1STRM);
2304     bind(retry_load);
2305     // flush and load exclusive from the memory location
2306     // and fail if it is not what we expect
2307     ldaxr(tmp, addr);
2308     cmp(tmp, oldv);
2309     br(Assembler::NE, nope);
2310     // if we store+flush with no intervening write tmp will be zero
2311     stlxr(tmp, newv, addr);
2312     cbzw(tmp, succeed);
2313     // retry so we only ever return after a load fails to compare
2314     // ensures we don't return a stale value after a failed write.
2315     b(retry_load);
2316     // if the memory word differs we return it in oldv and signal a fail
2317     bind(nope);
2318     membar(AnyAny);
2319     mov(oldv, tmp);
2320   }
2321   if (fail)
2322     b(*fail);
2323 }
2324 
2325 void MacroAssembler::cmpxchg_obj_header(Register oldv, Register newv, Register obj, Register tmp,
2326                                         Label &succeed, Label *fail) {
2327   assert(oopDesc::mark_offset_in_bytes() == 0, "assumption");
2328   cmpxchgptr(oldv, newv, obj, tmp, succeed, fail);
2329 }
2330 
2331 void MacroAssembler::cmpxchgw(Register oldv, Register newv, Register addr, Register tmp,
2332                                 Label &succeed, Label *fail) {
2333   // oldv holds comparison value
2334   // newv holds value to write in exchange
2335   // addr identifies memory word to compare against/update
2336   // tmp returns 0/1 for success/failure
2337   if (UseLSE) {
2338     mov(tmp, oldv);
2339     casal(Assembler::word, oldv, newv, addr);
2340     cmp(tmp, oldv);
2341     br(Assembler::EQ, succeed);
2342     membar(AnyAny);
2343   } else {
2344     Label retry_load, nope;
2345     if (VM_Version::supports_stxr_prefetch())
2346       prfm(Address(addr), PSTL1STRM);
2347     bind(retry_load);
2348     // flush and load exclusive from the memory location
2349     // and fail if it is not what we expect
2350     ldaxrw(tmp, addr);
2351     cmp(tmp, oldv);
2352     br(Assembler::NE, nope);
2353     // if we store+flush with no intervening write tmp will be zero
2354     stlxrw(tmp, newv, addr);
2355     cbzw(tmp, succeed);
2356     // retry so we only ever return after a load fails to compare
2357     // ensures we don't return a stale value after a failed write.
2358     b(retry_load);
2359     // if the memory word differs we return it in oldv and signal a fail
2360     bind(nope);
2361     membar(AnyAny);
2362     mov(oldv, tmp);
2363   }
2364   if (fail)
2365     b(*fail);
2366 }
2367 
2368 // A generic CAS; success or failure is in the EQ flag.  A weak CAS
2369 // doesn't retry and may fail spuriously.  If the oldval is wanted,
2370 // Pass a register for the result, otherwise pass noreg.
2371 
2372 // Clobbers rscratch1
2373 void MacroAssembler::cmpxchg(Register addr, Register expected,
2374                              Register new_val,
2375                              enum operand_size size,
2376                              bool acquire, bool release,
2377                              bool weak,
2378                              Register result) {
2379   if (result == noreg)  result = rscratch1;
2380   BLOCK_COMMENT("cmpxchg {");
2381   if (UseLSE) {
2382     mov(result, expected);
2383     lse_cas(result, new_val, addr, size, acquire, release, /*not_pair*/ true);
2384     compare_eq(result, expected, size);
2385   } else {
2386     Label retry_load, done;
2387     if (VM_Version::supports_stxr_prefetch())
2388       prfm(Address(addr), PSTL1STRM);
2389     bind(retry_load);
2390     load_exclusive(result, addr, size, acquire);
2391     compare_eq(result, expected, size);
2392     br(Assembler::NE, done);
2393     store_exclusive(rscratch1, new_val, addr, size, release);
2394     if (weak) {
2395       cmpw(rscratch1, 0u);  // If the store fails, return NE to our caller.
2396     } else {
2397       cbnzw(rscratch1, retry_load);
2398     }
2399     bind(done);
2400   }
2401   BLOCK_COMMENT("} cmpxchg");
2402 }
2403 
2404 // A generic comparison. Only compares for equality, clobbers rscratch1.
2405 void MacroAssembler::compare_eq(Register rm, Register rn, enum operand_size size) {
2406   if (size == xword) {
2407     cmp(rm, rn);
2408   } else if (size == word) {
2409     cmpw(rm, rn);
2410   } else if (size == halfword) {
2411     eorw(rscratch1, rm, rn);
2412     ands(zr, rscratch1, 0xffff);
2413   } else if (size == byte) {
2414     eorw(rscratch1, rm, rn);
2415     ands(zr, rscratch1, 0xff);
2416   } else {
2417     ShouldNotReachHere();
2418   }
2419 }
2420 
2421 
2422 static bool different(Register a, RegisterOrConstant b, Register c) {
2423   if (b.is_constant())
2424     return a != c;
2425   else
2426     return a != b.as_register() && a != c && b.as_register() != c;
2427 }
2428 
2429 #define ATOMIC_OP(NAME, LDXR, OP, IOP, AOP, STXR, sz)                   \
2430 void MacroAssembler::atomic_##NAME(Register prev, RegisterOrConstant incr, Register addr) { \
2431   if (UseLSE) {                                                         \
2432     prev = prev->is_valid() ? prev : zr;                                \
2433     if (incr.is_register()) {                                           \
2434       AOP(sz, incr.as_register(), prev, addr);                          \
2435     } else {                                                            \
2436       mov(rscratch2, incr.as_constant());                               \
2437       AOP(sz, rscratch2, prev, addr);                                   \
2438     }                                                                   \
2439     return;                                                             \
2440   }                                                                     \
2441   Register result = rscratch2;                                          \
2442   if (prev->is_valid())                                                 \
2443     result = different(prev, incr, addr) ? prev : rscratch2;            \
2444                                                                         \
2445   Label retry_load;                                                     \
2446   if (VM_Version::supports_stxr_prefetch())                             \
2447     prfm(Address(addr), PSTL1STRM);                                     \
2448   bind(retry_load);                                                     \
2449   LDXR(result, addr);                                                   \
2450   OP(rscratch1, result, incr);                                          \
2451   STXR(rscratch2, rscratch1, addr);                                     \
2452   cbnzw(rscratch2, retry_load);                                         \
2453   if (prev->is_valid() && prev != result) {                             \
2454     IOP(prev, rscratch1, incr);                                         \
2455   }                                                                     \
2456 }
2457 
2458 ATOMIC_OP(add, ldxr, add, sub, ldadd, stxr, Assembler::xword)
2459 ATOMIC_OP(addw, ldxrw, addw, subw, ldadd, stxrw, Assembler::word)
2460 ATOMIC_OP(addal, ldaxr, add, sub, ldaddal, stlxr, Assembler::xword)
2461 ATOMIC_OP(addalw, ldaxrw, addw, subw, ldaddal, stlxrw, Assembler::word)
2462 
2463 #undef ATOMIC_OP
2464 
2465 #define ATOMIC_XCHG(OP, AOP, LDXR, STXR, sz)                            \
2466 void MacroAssembler::atomic_##OP(Register prev, Register newv, Register addr) { \
2467   if (UseLSE) {                                                         \
2468     prev = prev->is_valid() ? prev : zr;                                \
2469     AOP(sz, newv, prev, addr);                                          \
2470     return;                                                             \
2471   }                                                                     \
2472   Register result = rscratch2;                                          \
2473   if (prev->is_valid())                                                 \
2474     result = different(prev, newv, addr) ? prev : rscratch2;            \
2475                                                                         \
2476   Label retry_load;                                                     \
2477   if (VM_Version::supports_stxr_prefetch())                             \
2478     prfm(Address(addr), PSTL1STRM);                                     \
2479   bind(retry_load);                                                     \
2480   LDXR(result, addr);                                                   \
2481   STXR(rscratch1, newv, addr);                                          \
2482   cbnzw(rscratch1, retry_load);                                         \
2483   if (prev->is_valid() && prev != result)                               \
2484     mov(prev, result);                                                  \
2485 }
2486 
2487 ATOMIC_XCHG(xchg, swp, ldxr, stxr, Assembler::xword)
2488 ATOMIC_XCHG(xchgw, swp, ldxrw, stxrw, Assembler::word)
2489 ATOMIC_XCHG(xchgl, swpl, ldxr, stlxr, Assembler::xword)
2490 ATOMIC_XCHG(xchglw, swpl, ldxrw, stlxrw, Assembler::word)
2491 ATOMIC_XCHG(xchgal, swpal, ldaxr, stlxr, Assembler::xword)
2492 ATOMIC_XCHG(xchgalw, swpal, ldaxrw, stlxrw, Assembler::word)
2493 
2494 #undef ATOMIC_XCHG
2495 
2496 #ifndef PRODUCT
2497 extern "C" void findpc(intptr_t x);
2498 #endif
2499 
2500 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[])
2501 {
2502   // In order to get locks to work, we need to fake a in_VM state
2503   if (ShowMessageBoxOnError ) {
2504     JavaThread* thread = JavaThread::current();
2505     JavaThreadState saved_state = thread->thread_state();
2506     thread->set_thread_state(_thread_in_vm);
2507 #ifndef PRODUCT
2508     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
2509       ttyLocker ttyl;
2510       BytecodeCounter::print();
2511     }
2512 #endif
2513     if (os::message_box(msg, "Execution stopped, print registers?")) {
2514       ttyLocker ttyl;
2515       tty->print_cr(" pc = 0x%016" PRIx64, pc);
2516 #ifndef PRODUCT
2517       tty->cr();
2518       findpc(pc);
2519       tty->cr();
2520 #endif
2521       tty->print_cr(" r0 = 0x%016" PRIx64, regs[0]);
2522       tty->print_cr(" r1 = 0x%016" PRIx64, regs[1]);
2523       tty->print_cr(" r2 = 0x%016" PRIx64, regs[2]);
2524       tty->print_cr(" r3 = 0x%016" PRIx64, regs[3]);
2525       tty->print_cr(" r4 = 0x%016" PRIx64, regs[4]);
2526       tty->print_cr(" r5 = 0x%016" PRIx64, regs[5]);
2527       tty->print_cr(" r6 = 0x%016" PRIx64, regs[6]);
2528       tty->print_cr(" r7 = 0x%016" PRIx64, regs[7]);
2529       tty->print_cr(" r8 = 0x%016" PRIx64, regs[8]);
2530       tty->print_cr(" r9 = 0x%016" PRIx64, regs[9]);
2531       tty->print_cr("r10 = 0x%016" PRIx64, regs[10]);
2532       tty->print_cr("r11 = 0x%016" PRIx64, regs[11]);
2533       tty->print_cr("r12 = 0x%016" PRIx64, regs[12]);
2534       tty->print_cr("r13 = 0x%016" PRIx64, regs[13]);
2535       tty->print_cr("r14 = 0x%016" PRIx64, regs[14]);
2536       tty->print_cr("r15 = 0x%016" PRIx64, regs[15]);
2537       tty->print_cr("r16 = 0x%016" PRIx64, regs[16]);
2538       tty->print_cr("r17 = 0x%016" PRIx64, regs[17]);
2539       tty->print_cr("r18 = 0x%016" PRIx64, regs[18]);
2540       tty->print_cr("r19 = 0x%016" PRIx64, regs[19]);
2541       tty->print_cr("r20 = 0x%016" PRIx64, regs[20]);
2542       tty->print_cr("r21 = 0x%016" PRIx64, regs[21]);
2543       tty->print_cr("r22 = 0x%016" PRIx64, regs[22]);
2544       tty->print_cr("r23 = 0x%016" PRIx64, regs[23]);
2545       tty->print_cr("r24 = 0x%016" PRIx64, regs[24]);
2546       tty->print_cr("r25 = 0x%016" PRIx64, regs[25]);
2547       tty->print_cr("r26 = 0x%016" PRIx64, regs[26]);
2548       tty->print_cr("r27 = 0x%016" PRIx64, regs[27]);
2549       tty->print_cr("r28 = 0x%016" PRIx64, regs[28]);
2550       tty->print_cr("r30 = 0x%016" PRIx64, regs[30]);
2551       tty->print_cr("r31 = 0x%016" PRIx64, regs[31]);
2552       BREAKPOINT;
2553     }
2554   }
2555   fatal("DEBUG MESSAGE: %s", msg);
2556 }
2557 
2558 RegSet MacroAssembler::call_clobbered_gp_registers() {
2559   RegSet regs = RegSet::range(r0, r17) - RegSet::of(rscratch1, rscratch2);
2560 #ifndef R18_RESERVED
2561   regs += r18_tls;
2562 #endif
2563   return regs;
2564 }
2565 
2566 void MacroAssembler::push_call_clobbered_registers_except(RegSet exclude) {
2567   int step = 4 * wordSize;
2568   push(call_clobbered_gp_registers() - exclude, sp);
2569   sub(sp, sp, step);
2570   mov(rscratch1, -step);
2571   // Push v0-v7, v16-v31.
2572   for (int i = 31; i>= 4; i -= 4) {
2573     if (i <= v7->encoding() || i >= v16->encoding())
2574       st1(as_FloatRegister(i-3), as_FloatRegister(i-2), as_FloatRegister(i-1),
2575           as_FloatRegister(i), T1D, Address(post(sp, rscratch1)));
2576   }
2577   st1(as_FloatRegister(0), as_FloatRegister(1), as_FloatRegister(2),
2578       as_FloatRegister(3), T1D, Address(sp));
2579 }
2580 
2581 void MacroAssembler::pop_call_clobbered_registers_except(RegSet exclude) {
2582   for (int i = 0; i < 32; i += 4) {
2583     if (i <= v7->encoding() || i >= v16->encoding())
2584       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
2585           as_FloatRegister(i+3), T1D, Address(post(sp, 4 * wordSize)));
2586   }
2587 
2588   reinitialize_ptrue();
2589 
2590   pop(call_clobbered_gp_registers() - exclude, sp);
2591 }
2592 
2593 void MacroAssembler::push_CPU_state(bool save_vectors, bool use_sve,
2594                                     int sve_vector_size_in_bytes, int total_predicate_in_bytes) {
2595   push(RegSet::range(r0, r29), sp); // integer registers except lr & sp
2596   if (save_vectors && use_sve && sve_vector_size_in_bytes > 16) {
2597     sub(sp, sp, sve_vector_size_in_bytes * FloatRegisterImpl::number_of_registers);
2598     for (int i = 0; i < FloatRegisterImpl::number_of_registers; i++) {
2599       sve_str(as_FloatRegister(i), Address(sp, i));
2600     }
2601   } else {
2602     int step = (save_vectors ? 8 : 4) * wordSize;
2603     mov(rscratch1, -step);
2604     sub(sp, sp, step);
2605     for (int i = 28; i >= 4; i -= 4) {
2606       st1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
2607           as_FloatRegister(i+3), save_vectors ? T2D : T1D, Address(post(sp, rscratch1)));
2608     }
2609     st1(v0, v1, v2, v3, save_vectors ? T2D : T1D, sp);
2610   }
2611   if (save_vectors && use_sve && total_predicate_in_bytes > 0) {
2612     sub(sp, sp, total_predicate_in_bytes);
2613     for (int i = 0; i < PRegisterImpl::number_of_saved_registers; i++) {
2614       sve_str(as_PRegister(i), Address(sp, i));
2615     }
2616   }
2617 }
2618 
2619 void MacroAssembler::pop_CPU_state(bool restore_vectors, bool use_sve,
2620                                    int sve_vector_size_in_bytes, int total_predicate_in_bytes) {
2621   if (restore_vectors && use_sve && total_predicate_in_bytes > 0) {
2622     for (int i = PRegisterImpl::number_of_saved_registers - 1; i >= 0; i--) {
2623       sve_ldr(as_PRegister(i), Address(sp, i));
2624     }
2625     add(sp, sp, total_predicate_in_bytes);
2626   }
2627   if (restore_vectors && use_sve && sve_vector_size_in_bytes > 16) {
2628     for (int i = FloatRegisterImpl::number_of_registers - 1; i >= 0; i--) {
2629       sve_ldr(as_FloatRegister(i), Address(sp, i));
2630     }
2631     add(sp, sp, sve_vector_size_in_bytes * FloatRegisterImpl::number_of_registers);
2632   } else {
2633     int step = (restore_vectors ? 8 : 4) * wordSize;
2634     for (int i = 0; i <= 28; i += 4)
2635       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
2636           as_FloatRegister(i+3), restore_vectors ? T2D : T1D, Address(post(sp, step)));
2637   }
2638 
2639   // We may use predicate registers and rely on ptrue with SVE,
2640   // regardless of wide vector (> 8 bytes) used or not.
2641   if (use_sve) {
2642     reinitialize_ptrue();
2643   }
2644 
2645   // integer registers except lr & sp
2646   pop(RegSet::range(r0, r17), sp);
2647 #ifdef R18_RESERVED
2648   ldp(zr, r19, Address(post(sp, 2 * wordSize)));
2649   pop(RegSet::range(r20, r29), sp);
2650 #else
2651   pop(RegSet::range(r18_tls, r29), sp);
2652 #endif
2653 }
2654 
2655 /**
2656  * Helpers for multiply_to_len().
2657  */
2658 void MacroAssembler::add2_with_carry(Register final_dest_hi, Register dest_hi, Register dest_lo,
2659                                      Register src1, Register src2) {
2660   adds(dest_lo, dest_lo, src1);
2661   adc(dest_hi, dest_hi, zr);
2662   adds(dest_lo, dest_lo, src2);
2663   adc(final_dest_hi, dest_hi, zr);
2664 }
2665 
2666 // Generate an address from (r + r1 extend offset).  "size" is the
2667 // size of the operand.  The result may be in rscratch2.
2668 Address MacroAssembler::offsetted_address(Register r, Register r1,
2669                                           Address::extend ext, int offset, int size) {
2670   if (offset || (ext.shift() % size != 0)) {
2671     lea(rscratch2, Address(r, r1, ext));
2672     return Address(rscratch2, offset);
2673   } else {
2674     return Address(r, r1, ext);
2675   }
2676 }
2677 
2678 Address MacroAssembler::spill_address(int size, int offset, Register tmp)
2679 {
2680   assert(offset >= 0, "spill to negative address?");
2681   // Offset reachable ?
2682   //   Not aligned - 9 bits signed offset
2683   //   Aligned - 12 bits unsigned offset shifted
2684   Register base = sp;
2685   if ((offset & (size-1)) && offset >= (1<<8)) {
2686     add(tmp, base, offset & ((1<<12)-1));
2687     base = tmp;
2688     offset &= -1u<<12;
2689   }
2690 
2691   if (offset >= (1<<12) * size) {
2692     add(tmp, base, offset & (((1<<12)-1)<<12));
2693     base = tmp;
2694     offset &= ~(((1<<12)-1)<<12);
2695   }
2696 
2697   return Address(base, offset);
2698 }
2699 
2700 Address MacroAssembler::sve_spill_address(int sve_reg_size_in_bytes, int offset, Register tmp) {
2701   assert(offset >= 0, "spill to negative address?");
2702 
2703   Register base = sp;
2704 
2705   // An immediate offset in the range 0 to 255 which is multiplied
2706   // by the current vector or predicate register size in bytes.
2707   if (offset % sve_reg_size_in_bytes == 0 && offset < ((1<<8)*sve_reg_size_in_bytes)) {
2708     return Address(base, offset / sve_reg_size_in_bytes);
2709   }
2710 
2711   add(tmp, base, offset);
2712   return Address(tmp);
2713 }
2714 
2715 // Checks whether offset is aligned.
2716 // Returns true if it is, else false.
2717 bool MacroAssembler::merge_alignment_check(Register base,
2718                                            size_t size,
2719                                            int64_t cur_offset,
2720                                            int64_t prev_offset) const {
2721   if (AvoidUnalignedAccesses) {
2722     if (base == sp) {
2723       // Checks whether low offset if aligned to pair of registers.
2724       int64_t pair_mask = size * 2 - 1;
2725       int64_t offset = prev_offset > cur_offset ? cur_offset : prev_offset;
2726       return (offset & pair_mask) == 0;
2727     } else { // If base is not sp, we can't guarantee the access is aligned.
2728       return false;
2729     }
2730   } else {
2731     int64_t mask = size - 1;
2732     // Load/store pair instruction only supports element size aligned offset.
2733     return (cur_offset & mask) == 0 && (prev_offset & mask) == 0;
2734   }
2735 }
2736 
2737 // Checks whether current and previous loads/stores can be merged.
2738 // Returns true if it can be merged, else false.
2739 bool MacroAssembler::ldst_can_merge(Register rt,
2740                                     const Address &adr,
2741                                     size_t cur_size_in_bytes,
2742                                     bool is_store) const {
2743   address prev = pc() - NativeInstruction::instruction_size;
2744   address last = code()->last_insn();
2745 
2746   if (last == NULL || !nativeInstruction_at(last)->is_Imm_LdSt()) {
2747     return false;
2748   }
2749 
2750   if (adr.getMode() != Address::base_plus_offset || prev != last) {
2751     return false;
2752   }
2753 
2754   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
2755   size_t prev_size_in_bytes = prev_ldst->size_in_bytes();
2756 
2757   assert(prev_size_in_bytes == 4 || prev_size_in_bytes == 8, "only supports 64/32bit merging.");
2758   assert(cur_size_in_bytes == 4 || cur_size_in_bytes == 8, "only supports 64/32bit merging.");
2759 
2760   if (cur_size_in_bytes != prev_size_in_bytes || is_store != prev_ldst->is_store()) {
2761     return false;
2762   }
2763 
2764   int64_t max_offset = 63 * prev_size_in_bytes;
2765   int64_t min_offset = -64 * prev_size_in_bytes;
2766 
2767   assert(prev_ldst->is_not_pre_post_index(), "pre-index or post-index is not supported to be merged.");
2768 
2769   // Only same base can be merged.
2770   if (adr.base() != prev_ldst->base()) {
2771     return false;
2772   }
2773 
2774   int64_t cur_offset = adr.offset();
2775   int64_t prev_offset = prev_ldst->offset();
2776   size_t diff = abs(cur_offset - prev_offset);
2777   if (diff != prev_size_in_bytes) {
2778     return false;
2779   }
2780 
2781   // Following cases can not be merged:
2782   // ldr x2, [x2, #8]
2783   // ldr x3, [x2, #16]
2784   // or:
2785   // ldr x2, [x3, #8]
2786   // ldr x2, [x3, #16]
2787   // If t1 and t2 is the same in "ldp t1, t2, [xn, #imm]", we'll get SIGILL.
2788   if (!is_store && (adr.base() == prev_ldst->target() || rt == prev_ldst->target())) {
2789     return false;
2790   }
2791 
2792   int64_t low_offset = prev_offset > cur_offset ? cur_offset : prev_offset;
2793   // Offset range must be in ldp/stp instruction's range.
2794   if (low_offset > max_offset || low_offset < min_offset) {
2795     return false;
2796   }
2797 
2798   if (merge_alignment_check(adr.base(), prev_size_in_bytes, cur_offset, prev_offset)) {
2799     return true;
2800   }
2801 
2802   return false;
2803 }
2804 
2805 // Merge current load/store with previous load/store into ldp/stp.
2806 void MacroAssembler::merge_ldst(Register rt,
2807                                 const Address &adr,
2808                                 size_t cur_size_in_bytes,
2809                                 bool is_store) {
2810 
2811   assert(ldst_can_merge(rt, adr, cur_size_in_bytes, is_store) == true, "cur and prev must be able to be merged.");
2812 
2813   Register rt_low, rt_high;
2814   address prev = pc() - NativeInstruction::instruction_size;
2815   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
2816 
2817   int64_t offset;
2818 
2819   if (adr.offset() < prev_ldst->offset()) {
2820     offset = adr.offset();
2821     rt_low = rt;
2822     rt_high = prev_ldst->target();
2823   } else {
2824     offset = prev_ldst->offset();
2825     rt_low = prev_ldst->target();
2826     rt_high = rt;
2827   }
2828 
2829   Address adr_p = Address(prev_ldst->base(), offset);
2830   // Overwrite previous generated binary.
2831   code_section()->set_end(prev);
2832 
2833   const size_t sz = prev_ldst->size_in_bytes();
2834   assert(sz == 8 || sz == 4, "only supports 64/32bit merging.");
2835   if (!is_store) {
2836     BLOCK_COMMENT("merged ldr pair");
2837     if (sz == 8) {
2838       ldp(rt_low, rt_high, adr_p);
2839     } else {
2840       ldpw(rt_low, rt_high, adr_p);
2841     }
2842   } else {
2843     BLOCK_COMMENT("merged str pair");
2844     if (sz == 8) {
2845       stp(rt_low, rt_high, adr_p);
2846     } else {
2847       stpw(rt_low, rt_high, adr_p);
2848     }
2849   }
2850 }
2851 
2852 /**
2853  * Multiply 64 bit by 64 bit first loop.
2854  */
2855 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
2856                                            Register y, Register y_idx, Register z,
2857                                            Register carry, Register product,
2858                                            Register idx, Register kdx) {
2859   //
2860   //  jlong carry, x[], y[], z[];
2861   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
2862   //    huge_128 product = y[idx] * x[xstart] + carry;
2863   //    z[kdx] = (jlong)product;
2864   //    carry  = (jlong)(product >>> 64);
2865   //  }
2866   //  z[xstart] = carry;
2867   //
2868 
2869   Label L_first_loop, L_first_loop_exit;
2870   Label L_one_x, L_one_y, L_multiply;
2871 
2872   subsw(xstart, xstart, 1);
2873   br(Assembler::MI, L_one_x);
2874 
2875   lea(rscratch1, Address(x, xstart, Address::lsl(LogBytesPerInt)));
2876   ldr(x_xstart, Address(rscratch1));
2877   ror(x_xstart, x_xstart, 32); // convert big-endian to little-endian
2878 
2879   bind(L_first_loop);
2880   subsw(idx, idx, 1);
2881   br(Assembler::MI, L_first_loop_exit);
2882   subsw(idx, idx, 1);
2883   br(Assembler::MI, L_one_y);
2884   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2885   ldr(y_idx, Address(rscratch1));
2886   ror(y_idx, y_idx, 32); // convert big-endian to little-endian
2887   bind(L_multiply);
2888 
2889   // AArch64 has a multiply-accumulate instruction that we can't use
2890   // here because it has no way to process carries, so we have to use
2891   // separate add and adc instructions.  Bah.
2892   umulh(rscratch1, x_xstart, y_idx); // x_xstart * y_idx -> rscratch1:product
2893   mul(product, x_xstart, y_idx);
2894   adds(product, product, carry);
2895   adc(carry, rscratch1, zr);   // x_xstart * y_idx + carry -> carry:product
2896 
2897   subw(kdx, kdx, 2);
2898   ror(product, product, 32); // back to big-endian
2899   str(product, offsetted_address(z, kdx, Address::uxtw(LogBytesPerInt), 0, BytesPerLong));
2900 
2901   b(L_first_loop);
2902 
2903   bind(L_one_y);
2904   ldrw(y_idx, Address(y,  0));
2905   b(L_multiply);
2906 
2907   bind(L_one_x);
2908   ldrw(x_xstart, Address(x,  0));
2909   b(L_first_loop);
2910 
2911   bind(L_first_loop_exit);
2912 }
2913 
2914 /**
2915  * Multiply 128 bit by 128. Unrolled inner loop.
2916  *
2917  */
2918 void MacroAssembler::multiply_128_x_128_loop(Register y, Register z,
2919                                              Register carry, Register carry2,
2920                                              Register idx, Register jdx,
2921                                              Register yz_idx1, Register yz_idx2,
2922                                              Register tmp, Register tmp3, Register tmp4,
2923                                              Register tmp6, Register product_hi) {
2924 
2925   //   jlong carry, x[], y[], z[];
2926   //   int kdx = ystart+1;
2927   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
2928   //     huge_128 tmp3 = (y[idx+1] * product_hi) + z[kdx+idx+1] + carry;
2929   //     jlong carry2  = (jlong)(tmp3 >>> 64);
2930   //     huge_128 tmp4 = (y[idx]   * product_hi) + z[kdx+idx] + carry2;
2931   //     carry  = (jlong)(tmp4 >>> 64);
2932   //     z[kdx+idx+1] = (jlong)tmp3;
2933   //     z[kdx+idx] = (jlong)tmp4;
2934   //   }
2935   //   idx += 2;
2936   //   if (idx > 0) {
2937   //     yz_idx1 = (y[idx] * product_hi) + z[kdx+idx] + carry;
2938   //     z[kdx+idx] = (jlong)yz_idx1;
2939   //     carry  = (jlong)(yz_idx1 >>> 64);
2940   //   }
2941   //
2942 
2943   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
2944 
2945   lsrw(jdx, idx, 2);
2946 
2947   bind(L_third_loop);
2948 
2949   subsw(jdx, jdx, 1);
2950   br(Assembler::MI, L_third_loop_exit);
2951   subw(idx, idx, 4);
2952 
2953   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2954 
2955   ldp(yz_idx2, yz_idx1, Address(rscratch1, 0));
2956 
2957   lea(tmp6, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2958 
2959   ror(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
2960   ror(yz_idx2, yz_idx2, 32);
2961 
2962   ldp(rscratch2, rscratch1, Address(tmp6, 0));
2963 
2964   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
2965   umulh(tmp4, product_hi, yz_idx1);
2966 
2967   ror(rscratch1, rscratch1, 32); // convert big-endian to little-endian
2968   ror(rscratch2, rscratch2, 32);
2969 
2970   mul(tmp, product_hi, yz_idx2);   //  yz_idx2 * product_hi -> carry2:tmp
2971   umulh(carry2, product_hi, yz_idx2);
2972 
2973   // propagate sum of both multiplications into carry:tmp4:tmp3
2974   adds(tmp3, tmp3, carry);
2975   adc(tmp4, tmp4, zr);
2976   adds(tmp3, tmp3, rscratch1);
2977   adcs(tmp4, tmp4, tmp);
2978   adc(carry, carry2, zr);
2979   adds(tmp4, tmp4, rscratch2);
2980   adc(carry, carry, zr);
2981 
2982   ror(tmp3, tmp3, 32); // convert little-endian to big-endian
2983   ror(tmp4, tmp4, 32);
2984   stp(tmp4, tmp3, Address(tmp6, 0));
2985 
2986   b(L_third_loop);
2987   bind (L_third_loop_exit);
2988 
2989   andw (idx, idx, 0x3);
2990   cbz(idx, L_post_third_loop_done);
2991 
2992   Label L_check_1;
2993   subsw(idx, idx, 2);
2994   br(Assembler::MI, L_check_1);
2995 
2996   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2997   ldr(yz_idx1, Address(rscratch1, 0));
2998   ror(yz_idx1, yz_idx1, 32);
2999   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
3000   umulh(tmp4, product_hi, yz_idx1);
3001   lea(rscratch1, Address(z, idx, Address::uxtw(LogBytesPerInt)));
3002   ldr(yz_idx2, Address(rscratch1, 0));
3003   ror(yz_idx2, yz_idx2, 32);
3004 
3005   add2_with_carry(carry, tmp4, tmp3, carry, yz_idx2);
3006 
3007   ror(tmp3, tmp3, 32);
3008   str(tmp3, Address(rscratch1, 0));
3009 
3010   bind (L_check_1);
3011 
3012   andw (idx, idx, 0x1);
3013   subsw(idx, idx, 1);
3014   br(Assembler::MI, L_post_third_loop_done);
3015   ldrw(tmp4, Address(y, idx, Address::uxtw(LogBytesPerInt)));
3016   mul(tmp3, tmp4, product_hi);  //  tmp4 * product_hi -> carry2:tmp3
3017   umulh(carry2, tmp4, product_hi);
3018   ldrw(tmp4, Address(z, idx, Address::uxtw(LogBytesPerInt)));
3019 
3020   add2_with_carry(carry2, tmp3, tmp4, carry);
3021 
3022   strw(tmp3, Address(z, idx, Address::uxtw(LogBytesPerInt)));
3023   extr(carry, carry2, tmp3, 32);
3024 
3025   bind(L_post_third_loop_done);
3026 }
3027 
3028 /**
3029  * Code for BigInteger::multiplyToLen() intrinsic.
3030  *
3031  * r0: x
3032  * r1: xlen
3033  * r2: y
3034  * r3: ylen
3035  * r4:  z
3036  * r5: zlen
3037  * r10: tmp1
3038  * r11: tmp2
3039  * r12: tmp3
3040  * r13: tmp4
3041  * r14: tmp5
3042  * r15: tmp6
3043  * r16: tmp7
3044  *
3045  */
3046 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen,
3047                                      Register z, Register zlen,
3048                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4,
3049                                      Register tmp5, Register tmp6, Register product_hi) {
3050 
3051   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6);
3052 
3053   const Register idx = tmp1;
3054   const Register kdx = tmp2;
3055   const Register xstart = tmp3;
3056 
3057   const Register y_idx = tmp4;
3058   const Register carry = tmp5;
3059   const Register product  = xlen;
3060   const Register x_xstart = zlen;  // reuse register
3061 
3062   // First Loop.
3063   //
3064   //  final static long LONG_MASK = 0xffffffffL;
3065   //  int xstart = xlen - 1;
3066   //  int ystart = ylen - 1;
3067   //  long carry = 0;
3068   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
3069   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
3070   //    z[kdx] = (int)product;
3071   //    carry = product >>> 32;
3072   //  }
3073   //  z[xstart] = (int)carry;
3074   //
3075 
3076   movw(idx, ylen);      // idx = ylen;
3077   movw(kdx, zlen);      // kdx = xlen+ylen;
3078   mov(carry, zr);       // carry = 0;
3079 
3080   Label L_done;
3081 
3082   movw(xstart, xlen);
3083   subsw(xstart, xstart, 1);
3084   br(Assembler::MI, L_done);
3085 
3086   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
3087 
3088   Label L_second_loop;
3089   cbzw(kdx, L_second_loop);
3090 
3091   Label L_carry;
3092   subw(kdx, kdx, 1);
3093   cbzw(kdx, L_carry);
3094 
3095   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
3096   lsr(carry, carry, 32);
3097   subw(kdx, kdx, 1);
3098 
3099   bind(L_carry);
3100   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
3101 
3102   // Second and third (nested) loops.
3103   //
3104   // for (int i = xstart-1; i >= 0; i--) { // Second loop
3105   //   carry = 0;
3106   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
3107   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
3108   //                    (z[k] & LONG_MASK) + carry;
3109   //     z[k] = (int)product;
3110   //     carry = product >>> 32;
3111   //   }
3112   //   z[i] = (int)carry;
3113   // }
3114   //
3115   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = product_hi
3116 
3117   const Register jdx = tmp1;
3118 
3119   bind(L_second_loop);
3120   mov(carry, zr);                // carry = 0;
3121   movw(jdx, ylen);               // j = ystart+1
3122 
3123   subsw(xstart, xstart, 1);      // i = xstart-1;
3124   br(Assembler::MI, L_done);
3125 
3126   str(z, Address(pre(sp, -4 * wordSize)));
3127 
3128   Label L_last_x;
3129   lea(z, offsetted_address(z, xstart, Address::uxtw(LogBytesPerInt), 4, BytesPerInt)); // z = z + k - j
3130   subsw(xstart, xstart, 1);       // i = xstart-1;
3131   br(Assembler::MI, L_last_x);
3132 
3133   lea(rscratch1, Address(x, xstart, Address::uxtw(LogBytesPerInt)));
3134   ldr(product_hi, Address(rscratch1));
3135   ror(product_hi, product_hi, 32);  // convert big-endian to little-endian
3136 
3137   Label L_third_loop_prologue;
3138   bind(L_third_loop_prologue);
3139 
3140   str(ylen, Address(sp, wordSize));
3141   stp(x, xstart, Address(sp, 2 * wordSize));
3142   multiply_128_x_128_loop(y, z, carry, x, jdx, ylen, product,
3143                           tmp2, x_xstart, tmp3, tmp4, tmp6, product_hi);
3144   ldp(z, ylen, Address(post(sp, 2 * wordSize)));
3145   ldp(x, xlen, Address(post(sp, 2 * wordSize)));   // copy old xstart -> xlen
3146 
3147   addw(tmp3, xlen, 1);
3148   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
3149   subsw(tmp3, tmp3, 1);
3150   br(Assembler::MI, L_done);
3151 
3152   lsr(carry, carry, 32);
3153   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
3154   b(L_second_loop);
3155 
3156   // Next infrequent code is moved outside loops.
3157   bind(L_last_x);
3158   ldrw(product_hi, Address(x,  0));
3159   b(L_third_loop_prologue);
3160 
3161   bind(L_done);
3162 }
3163 
3164 // Code for BigInteger::mulAdd intrinsic
3165 // out     = r0
3166 // in      = r1
3167 // offset  = r2  (already out.length-offset)
3168 // len     = r3
3169 // k       = r4
3170 //
3171 // pseudo code from java implementation:
3172 // carry = 0;
3173 // offset = out.length-offset - 1;
3174 // for (int j=len-1; j >= 0; j--) {
3175 //     product = (in[j] & LONG_MASK) * kLong + (out[offset] & LONG_MASK) + carry;
3176 //     out[offset--] = (int)product;
3177 //     carry = product >>> 32;
3178 // }
3179 // return (int)carry;
3180 void MacroAssembler::mul_add(Register out, Register in, Register offset,
3181       Register len, Register k) {
3182     Label LOOP, END;
3183     // pre-loop
3184     cmp(len, zr); // cmp, not cbz/cbnz: to use condition twice => less branches
3185     csel(out, zr, out, Assembler::EQ);
3186     br(Assembler::EQ, END);
3187     add(in, in, len, LSL, 2); // in[j+1] address
3188     add(offset, out, offset, LSL, 2); // out[offset + 1] address
3189     mov(out, zr); // used to keep carry now
3190     BIND(LOOP);
3191     ldrw(rscratch1, Address(pre(in, -4)));
3192     madd(rscratch1, rscratch1, k, out);
3193     ldrw(rscratch2, Address(pre(offset, -4)));
3194     add(rscratch1, rscratch1, rscratch2);
3195     strw(rscratch1, Address(offset));
3196     lsr(out, rscratch1, 32);
3197     subs(len, len, 1);
3198     br(Assembler::NE, LOOP);
3199     BIND(END);
3200 }
3201 
3202 /**
3203  * Emits code to update CRC-32 with a byte value according to constants in table
3204  *
3205  * @param [in,out]crc   Register containing the crc.
3206  * @param [in]val       Register containing the byte to fold into the CRC.
3207  * @param [in]table     Register containing the table of crc constants.
3208  *
3209  * uint32_t crc;
3210  * val = crc_table[(val ^ crc) & 0xFF];
3211  * crc = val ^ (crc >> 8);
3212  *
3213  */
3214 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
3215   eor(val, val, crc);
3216   andr(val, val, 0xff);
3217   ldrw(val, Address(table, val, Address::lsl(2)));
3218   eor(crc, val, crc, Assembler::LSR, 8);
3219 }
3220 
3221 /**
3222  * Emits code to update CRC-32 with a 32-bit value according to tables 0 to 3
3223  *
3224  * @param [in,out]crc   Register containing the crc.
3225  * @param [in]v         Register containing the 32-bit to fold into the CRC.
3226  * @param [in]table0    Register containing table 0 of crc constants.
3227  * @param [in]table1    Register containing table 1 of crc constants.
3228  * @param [in]table2    Register containing table 2 of crc constants.
3229  * @param [in]table3    Register containing table 3 of crc constants.
3230  *
3231  * uint32_t crc;
3232  *   v = crc ^ v
3233  *   crc = table3[v&0xff]^table2[(v>>8)&0xff]^table1[(v>>16)&0xff]^table0[v>>24]
3234  *
3235  */
3236 void MacroAssembler::update_word_crc32(Register crc, Register v, Register tmp,
3237         Register table0, Register table1, Register table2, Register table3,
3238         bool upper) {
3239   eor(v, crc, v, upper ? LSR:LSL, upper ? 32:0);
3240   uxtb(tmp, v);
3241   ldrw(crc, Address(table3, tmp, Address::lsl(2)));
3242   ubfx(tmp, v, 8, 8);
3243   ldrw(tmp, Address(table2, tmp, Address::lsl(2)));
3244   eor(crc, crc, tmp);
3245   ubfx(tmp, v, 16, 8);
3246   ldrw(tmp, Address(table1, tmp, Address::lsl(2)));
3247   eor(crc, crc, tmp);
3248   ubfx(tmp, v, 24, 8);
3249   ldrw(tmp, Address(table0, tmp, Address::lsl(2)));
3250   eor(crc, crc, tmp);
3251 }
3252 
3253 void MacroAssembler::kernel_crc32_using_crc32(Register crc, Register buf,
3254         Register len, Register tmp0, Register tmp1, Register tmp2,
3255         Register tmp3) {
3256     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
3257     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
3258 
3259     mvnw(crc, crc);
3260 
3261     subs(len, len, 128);
3262     br(Assembler::GE, CRC_by64_pre);
3263   BIND(CRC_less64);
3264     adds(len, len, 128-32);
3265     br(Assembler::GE, CRC_by32_loop);
3266   BIND(CRC_less32);
3267     adds(len, len, 32-4);
3268     br(Assembler::GE, CRC_by4_loop);
3269     adds(len, len, 4);
3270     br(Assembler::GT, CRC_by1_loop);
3271     b(L_exit);
3272 
3273   BIND(CRC_by32_loop);
3274     ldp(tmp0, tmp1, Address(post(buf, 16)));
3275     subs(len, len, 32);
3276     crc32x(crc, crc, tmp0);
3277     ldr(tmp2, Address(post(buf, 8)));
3278     crc32x(crc, crc, tmp1);
3279     ldr(tmp3, Address(post(buf, 8)));
3280     crc32x(crc, crc, tmp2);
3281     crc32x(crc, crc, tmp3);
3282     br(Assembler::GE, CRC_by32_loop);
3283     cmn(len, 32);
3284     br(Assembler::NE, CRC_less32);
3285     b(L_exit);
3286 
3287   BIND(CRC_by4_loop);
3288     ldrw(tmp0, Address(post(buf, 4)));
3289     subs(len, len, 4);
3290     crc32w(crc, crc, tmp0);
3291     br(Assembler::GE, CRC_by4_loop);
3292     adds(len, len, 4);
3293     br(Assembler::LE, L_exit);
3294   BIND(CRC_by1_loop);
3295     ldrb(tmp0, Address(post(buf, 1)));
3296     subs(len, len, 1);
3297     crc32b(crc, crc, tmp0);
3298     br(Assembler::GT, CRC_by1_loop);
3299     b(L_exit);
3300 
3301   BIND(CRC_by64_pre);
3302     sub(buf, buf, 8);
3303     ldp(tmp0, tmp1, Address(buf, 8));
3304     crc32x(crc, crc, tmp0);
3305     ldr(tmp2, Address(buf, 24));
3306     crc32x(crc, crc, tmp1);
3307     ldr(tmp3, Address(buf, 32));
3308     crc32x(crc, crc, tmp2);
3309     ldr(tmp0, Address(buf, 40));
3310     crc32x(crc, crc, tmp3);
3311     ldr(tmp1, Address(buf, 48));
3312     crc32x(crc, crc, tmp0);
3313     ldr(tmp2, Address(buf, 56));
3314     crc32x(crc, crc, tmp1);
3315     ldr(tmp3, Address(pre(buf, 64)));
3316 
3317     b(CRC_by64_loop);
3318 
3319     align(CodeEntryAlignment);
3320   BIND(CRC_by64_loop);
3321     subs(len, len, 64);
3322     crc32x(crc, crc, tmp2);
3323     ldr(tmp0, Address(buf, 8));
3324     crc32x(crc, crc, tmp3);
3325     ldr(tmp1, Address(buf, 16));
3326     crc32x(crc, crc, tmp0);
3327     ldr(tmp2, Address(buf, 24));
3328     crc32x(crc, crc, tmp1);
3329     ldr(tmp3, Address(buf, 32));
3330     crc32x(crc, crc, tmp2);
3331     ldr(tmp0, Address(buf, 40));
3332     crc32x(crc, crc, tmp3);
3333     ldr(tmp1, Address(buf, 48));
3334     crc32x(crc, crc, tmp0);
3335     ldr(tmp2, Address(buf, 56));
3336     crc32x(crc, crc, tmp1);
3337     ldr(tmp3, Address(pre(buf, 64)));
3338     br(Assembler::GE, CRC_by64_loop);
3339 
3340     // post-loop
3341     crc32x(crc, crc, tmp2);
3342     crc32x(crc, crc, tmp3);
3343 
3344     sub(len, len, 64);
3345     add(buf, buf, 8);
3346     cmn(len, 128);
3347     br(Assembler::NE, CRC_less64);
3348   BIND(L_exit);
3349     mvnw(crc, crc);
3350 }
3351 
3352 /**
3353  * @param crc   register containing existing CRC (32-bit)
3354  * @param buf   register pointing to input byte buffer (byte*)
3355  * @param len   register containing number of bytes
3356  * @param table register that will contain address of CRC table
3357  * @param tmp   scratch register
3358  */
3359 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len,
3360         Register table0, Register table1, Register table2, Register table3,
3361         Register tmp, Register tmp2, Register tmp3) {
3362   Label L_by16, L_by16_loop, L_by4, L_by4_loop, L_by1, L_by1_loop, L_exit;
3363   uint64_t offset;
3364 
3365   if (UseCRC32) {
3366       kernel_crc32_using_crc32(crc, buf, len, table0, table1, table2, table3);
3367       return;
3368   }
3369 
3370     mvnw(crc, crc);
3371 
3372     adrp(table0, ExternalAddress(StubRoutines::crc_table_addr()), offset);
3373     if (offset) add(table0, table0, offset);
3374     add(table1, table0, 1*256*sizeof(juint));
3375     add(table2, table0, 2*256*sizeof(juint));
3376     add(table3, table0, 3*256*sizeof(juint));
3377 
3378   if (UseNeon) {
3379       cmp(len, (u1)64);
3380       br(Assembler::LT, L_by16);
3381       eor(v16, T16B, v16, v16);
3382 
3383     Label L_fold;
3384 
3385       add(tmp, table0, 4*256*sizeof(juint)); // Point at the Neon constants
3386 
3387       ld1(v0, v1, T2D, post(buf, 32));
3388       ld1r(v4, T2D, post(tmp, 8));
3389       ld1r(v5, T2D, post(tmp, 8));
3390       ld1r(v6, T2D, post(tmp, 8));
3391       ld1r(v7, T2D, post(tmp, 8));
3392       mov(v16, S, 0, crc);
3393 
3394       eor(v0, T16B, v0, v16);
3395       sub(len, len, 64);
3396 
3397     BIND(L_fold);
3398       pmull(v22, T8H, v0, v5, T8B);
3399       pmull(v20, T8H, v0, v7, T8B);
3400       pmull(v23, T8H, v0, v4, T8B);
3401       pmull(v21, T8H, v0, v6, T8B);
3402 
3403       pmull2(v18, T8H, v0, v5, T16B);
3404       pmull2(v16, T8H, v0, v7, T16B);
3405       pmull2(v19, T8H, v0, v4, T16B);
3406       pmull2(v17, T8H, v0, v6, T16B);
3407 
3408       uzp1(v24, T8H, v20, v22);
3409       uzp2(v25, T8H, v20, v22);
3410       eor(v20, T16B, v24, v25);
3411 
3412       uzp1(v26, T8H, v16, v18);
3413       uzp2(v27, T8H, v16, v18);
3414       eor(v16, T16B, v26, v27);
3415 
3416       ushll2(v22, T4S, v20, T8H, 8);
3417       ushll(v20, T4S, v20, T4H, 8);
3418 
3419       ushll2(v18, T4S, v16, T8H, 8);
3420       ushll(v16, T4S, v16, T4H, 8);
3421 
3422       eor(v22, T16B, v23, v22);
3423       eor(v18, T16B, v19, v18);
3424       eor(v20, T16B, v21, v20);
3425       eor(v16, T16B, v17, v16);
3426 
3427       uzp1(v17, T2D, v16, v20);
3428       uzp2(v21, T2D, v16, v20);
3429       eor(v17, T16B, v17, v21);
3430 
3431       ushll2(v20, T2D, v17, T4S, 16);
3432       ushll(v16, T2D, v17, T2S, 16);
3433 
3434       eor(v20, T16B, v20, v22);
3435       eor(v16, T16B, v16, v18);
3436 
3437       uzp1(v17, T2D, v20, v16);
3438       uzp2(v21, T2D, v20, v16);
3439       eor(v28, T16B, v17, v21);
3440 
3441       pmull(v22, T8H, v1, v5, T8B);
3442       pmull(v20, T8H, v1, v7, T8B);
3443       pmull(v23, T8H, v1, v4, T8B);
3444       pmull(v21, T8H, v1, v6, T8B);
3445 
3446       pmull2(v18, T8H, v1, v5, T16B);
3447       pmull2(v16, T8H, v1, v7, T16B);
3448       pmull2(v19, T8H, v1, v4, T16B);
3449       pmull2(v17, T8H, v1, v6, T16B);
3450 
3451       ld1(v0, v1, T2D, post(buf, 32));
3452 
3453       uzp1(v24, T8H, v20, v22);
3454       uzp2(v25, T8H, v20, v22);
3455       eor(v20, T16B, v24, v25);
3456 
3457       uzp1(v26, T8H, v16, v18);
3458       uzp2(v27, T8H, v16, v18);
3459       eor(v16, T16B, v26, v27);
3460 
3461       ushll2(v22, T4S, v20, T8H, 8);
3462       ushll(v20, T4S, v20, T4H, 8);
3463 
3464       ushll2(v18, T4S, v16, T8H, 8);
3465       ushll(v16, T4S, v16, T4H, 8);
3466 
3467       eor(v22, T16B, v23, v22);
3468       eor(v18, T16B, v19, v18);
3469       eor(v20, T16B, v21, v20);
3470       eor(v16, T16B, v17, v16);
3471 
3472       uzp1(v17, T2D, v16, v20);
3473       uzp2(v21, T2D, v16, v20);
3474       eor(v16, T16B, v17, v21);
3475 
3476       ushll2(v20, T2D, v16, T4S, 16);
3477       ushll(v16, T2D, v16, T2S, 16);
3478 
3479       eor(v20, T16B, v22, v20);
3480       eor(v16, T16B, v16, v18);
3481 
3482       uzp1(v17, T2D, v20, v16);
3483       uzp2(v21, T2D, v20, v16);
3484       eor(v20, T16B, v17, v21);
3485 
3486       shl(v16, T2D, v28, 1);
3487       shl(v17, T2D, v20, 1);
3488 
3489       eor(v0, T16B, v0, v16);
3490       eor(v1, T16B, v1, v17);
3491 
3492       subs(len, len, 32);
3493       br(Assembler::GE, L_fold);
3494 
3495       mov(crc, 0);
3496       mov(tmp, v0, D, 0);
3497       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3498       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3499       mov(tmp, v0, D, 1);
3500       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3501       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3502       mov(tmp, v1, D, 0);
3503       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3504       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3505       mov(tmp, v1, D, 1);
3506       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3507       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3508 
3509       add(len, len, 32);
3510   }
3511 
3512   BIND(L_by16);
3513     subs(len, len, 16);
3514     br(Assembler::GE, L_by16_loop);
3515     adds(len, len, 16-4);
3516     br(Assembler::GE, L_by4_loop);
3517     adds(len, len, 4);
3518     br(Assembler::GT, L_by1_loop);
3519     b(L_exit);
3520 
3521   BIND(L_by4_loop);
3522     ldrw(tmp, Address(post(buf, 4)));
3523     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3);
3524     subs(len, len, 4);
3525     br(Assembler::GE, L_by4_loop);
3526     adds(len, len, 4);
3527     br(Assembler::LE, L_exit);
3528   BIND(L_by1_loop);
3529     subs(len, len, 1);
3530     ldrb(tmp, Address(post(buf, 1)));
3531     update_byte_crc32(crc, tmp, table0);
3532     br(Assembler::GT, L_by1_loop);
3533     b(L_exit);
3534 
3535     align(CodeEntryAlignment);
3536   BIND(L_by16_loop);
3537     subs(len, len, 16);
3538     ldp(tmp, tmp3, Address(post(buf, 16)));
3539     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3540     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3541     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, false);
3542     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, true);
3543     br(Assembler::GE, L_by16_loop);
3544     adds(len, len, 16-4);
3545     br(Assembler::GE, L_by4_loop);
3546     adds(len, len, 4);
3547     br(Assembler::GT, L_by1_loop);
3548   BIND(L_exit);
3549     mvnw(crc, crc);
3550 }
3551 
3552 void MacroAssembler::kernel_crc32c_using_crc32c(Register crc, Register buf,
3553         Register len, Register tmp0, Register tmp1, Register tmp2,
3554         Register tmp3) {
3555     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
3556     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
3557 
3558     subs(len, len, 128);
3559     br(Assembler::GE, CRC_by64_pre);
3560   BIND(CRC_less64);
3561     adds(len, len, 128-32);
3562     br(Assembler::GE, CRC_by32_loop);
3563   BIND(CRC_less32);
3564     adds(len, len, 32-4);
3565     br(Assembler::GE, CRC_by4_loop);
3566     adds(len, len, 4);
3567     br(Assembler::GT, CRC_by1_loop);
3568     b(L_exit);
3569 
3570   BIND(CRC_by32_loop);
3571     ldp(tmp0, tmp1, Address(post(buf, 16)));
3572     subs(len, len, 32);
3573     crc32cx(crc, crc, tmp0);
3574     ldr(tmp2, Address(post(buf, 8)));
3575     crc32cx(crc, crc, tmp1);
3576     ldr(tmp3, Address(post(buf, 8)));
3577     crc32cx(crc, crc, tmp2);
3578     crc32cx(crc, crc, tmp3);
3579     br(Assembler::GE, CRC_by32_loop);
3580     cmn(len, 32);
3581     br(Assembler::NE, CRC_less32);
3582     b(L_exit);
3583 
3584   BIND(CRC_by4_loop);
3585     ldrw(tmp0, Address(post(buf, 4)));
3586     subs(len, len, 4);
3587     crc32cw(crc, crc, tmp0);
3588     br(Assembler::GE, CRC_by4_loop);
3589     adds(len, len, 4);
3590     br(Assembler::LE, L_exit);
3591   BIND(CRC_by1_loop);
3592     ldrb(tmp0, Address(post(buf, 1)));
3593     subs(len, len, 1);
3594     crc32cb(crc, crc, tmp0);
3595     br(Assembler::GT, CRC_by1_loop);
3596     b(L_exit);
3597 
3598   BIND(CRC_by64_pre);
3599     sub(buf, buf, 8);
3600     ldp(tmp0, tmp1, Address(buf, 8));
3601     crc32cx(crc, crc, tmp0);
3602     ldr(tmp2, Address(buf, 24));
3603     crc32cx(crc, crc, tmp1);
3604     ldr(tmp3, Address(buf, 32));
3605     crc32cx(crc, crc, tmp2);
3606     ldr(tmp0, Address(buf, 40));
3607     crc32cx(crc, crc, tmp3);
3608     ldr(tmp1, Address(buf, 48));
3609     crc32cx(crc, crc, tmp0);
3610     ldr(tmp2, Address(buf, 56));
3611     crc32cx(crc, crc, tmp1);
3612     ldr(tmp3, Address(pre(buf, 64)));
3613 
3614     b(CRC_by64_loop);
3615 
3616     align(CodeEntryAlignment);
3617   BIND(CRC_by64_loop);
3618     subs(len, len, 64);
3619     crc32cx(crc, crc, tmp2);
3620     ldr(tmp0, Address(buf, 8));
3621     crc32cx(crc, crc, tmp3);
3622     ldr(tmp1, Address(buf, 16));
3623     crc32cx(crc, crc, tmp0);
3624     ldr(tmp2, Address(buf, 24));
3625     crc32cx(crc, crc, tmp1);
3626     ldr(tmp3, Address(buf, 32));
3627     crc32cx(crc, crc, tmp2);
3628     ldr(tmp0, Address(buf, 40));
3629     crc32cx(crc, crc, tmp3);
3630     ldr(tmp1, Address(buf, 48));
3631     crc32cx(crc, crc, tmp0);
3632     ldr(tmp2, Address(buf, 56));
3633     crc32cx(crc, crc, tmp1);
3634     ldr(tmp3, Address(pre(buf, 64)));
3635     br(Assembler::GE, CRC_by64_loop);
3636 
3637     // post-loop
3638     crc32cx(crc, crc, tmp2);
3639     crc32cx(crc, crc, tmp3);
3640 
3641     sub(len, len, 64);
3642     add(buf, buf, 8);
3643     cmn(len, 128);
3644     br(Assembler::NE, CRC_less64);
3645   BIND(L_exit);
3646 }
3647 
3648 /**
3649  * @param crc   register containing existing CRC (32-bit)
3650  * @param buf   register pointing to input byte buffer (byte*)
3651  * @param len   register containing number of bytes
3652  * @param table register that will contain address of CRC table
3653  * @param tmp   scratch register
3654  */
3655 void MacroAssembler::kernel_crc32c(Register crc, Register buf, Register len,
3656         Register table0, Register table1, Register table2, Register table3,
3657         Register tmp, Register tmp2, Register tmp3) {
3658   kernel_crc32c_using_crc32c(crc, buf, len, table0, table1, table2, table3);
3659 }
3660 
3661 
3662 SkipIfEqual::SkipIfEqual(
3663     MacroAssembler* masm, const bool* flag_addr, bool value) {
3664   _masm = masm;
3665   uint64_t offset;
3666   _masm->adrp(rscratch1, ExternalAddress((address)flag_addr), offset);
3667   _masm->ldrb(rscratch1, Address(rscratch1, offset));
3668   _masm->cbzw(rscratch1, _label);
3669 }
3670 
3671 SkipIfEqual::~SkipIfEqual() {
3672   _masm->bind(_label);
3673 }
3674 
3675 void MacroAssembler::addptr(const Address &dst, int32_t src) {
3676   Address adr;
3677   switch(dst.getMode()) {
3678   case Address::base_plus_offset:
3679     // This is the expected mode, although we allow all the other
3680     // forms below.
3681     adr = form_address(rscratch2, dst.base(), dst.offset(), LogBytesPerWord);
3682     break;
3683   default:
3684     lea(rscratch2, dst);
3685     adr = Address(rscratch2);
3686     break;
3687   }
3688   ldr(rscratch1, adr);
3689   add(rscratch1, rscratch1, src);
3690   str(rscratch1, adr);
3691 }
3692 
3693 void MacroAssembler::cmpptr(Register src1, Address src2) {
3694   uint64_t offset;
3695   adrp(rscratch1, src2, offset);
3696   ldr(rscratch1, Address(rscratch1, offset));
3697   cmp(src1, rscratch1);
3698 }
3699 
3700 void MacroAssembler::cmpoop(Register obj1, Register obj2) {
3701   cmp(obj1, obj2);
3702 }
3703 
3704 void MacroAssembler::load_method_holder_cld(Register rresult, Register rmethod) {
3705   load_method_holder(rresult, rmethod);
3706   ldr(rresult, Address(rresult, InstanceKlass::class_loader_data_offset()));
3707 }
3708 
3709 void MacroAssembler::load_method_holder(Register holder, Register method) {
3710   ldr(holder, Address(method, Method::const_offset()));                      // ConstMethod*
3711   ldr(holder, Address(holder, ConstMethod::constants_offset()));             // ConstantPool*
3712   ldr(holder, Address(holder, ConstantPool::pool_holder_offset_in_bytes())); // InstanceKlass*
3713 }
3714 
3715 // Loads the obj's Klass* into dst.
3716 // src and dst must be distinct registers
3717 // Preserves all registers (incl src, rscratch1 and rscratch2), but clobbers condition flags
3718 void MacroAssembler::load_nklass(Register dst, Register src) {
3719   assert(UseCompressedClassPointers, "expects UseCompressedClassPointers");
3720 
3721   assert_different_registers(src, dst);
3722 
3723   Label slow, done;
3724 
3725   // Check if we can take the (common) fast path, if obj is unlocked.
3726   ldr(dst, Address(src, oopDesc::mark_offset_in_bytes()));
3727   eor(dst, dst, markWord::unlocked_value);
3728   tst(dst, markWord::lock_mask_in_place);
3729   br(Assembler::NE, slow);
3730 
3731   // Fast-path: shift and decode Klass*.
3732   lsr(dst, dst, markWord::klass_shift);
3733   b(done);
3734 
3735   bind(slow);
3736   RegSet saved_regs = RegSet::of(lr);
3737   // We need r0 as argument and return register for the call. Preserve it, if necessary.
3738   if (dst != r0) {
3739     saved_regs += RegSet::of(r0);
3740   }
3741   push(saved_regs, sp);
3742   mov(r0, src);
3743   assert(StubRoutines::load_nklass() != NULL, "Must have stub");
3744   far_call(RuntimeAddress(StubRoutines::load_nklass()));
3745   if (dst != r0) {
3746     mov(dst, r0);
3747   }
3748   pop(saved_regs, sp);
3749   bind(done);
3750 }
3751 
3752 void MacroAssembler::load_klass(Register dst, Register src) {
3753   load_nklass(dst, src);
3754   decode_klass_not_null(dst);
3755 }
3756 
3757 // ((OopHandle)result).resolve();
3758 void MacroAssembler::resolve_oop_handle(Register result, Register tmp) {
3759   // OopHandle::resolve is an indirection.
3760   access_load_at(T_OBJECT, IN_NATIVE, result, Address(result, 0), tmp, noreg);
3761 }
3762 
3763 // ((WeakHandle)result).resolve();
3764 void MacroAssembler::resolve_weak_handle(Register rresult, Register rtmp) {
3765   assert_different_registers(rresult, rtmp);
3766   Label resolved;
3767 
3768   // A null weak handle resolves to null.
3769   cbz(rresult, resolved);
3770 
3771   // Only 64 bit platforms support GCs that require a tmp register
3772   // Only IN_HEAP loads require a thread_tmp register
3773   // WeakHandle::resolve is an indirection like jweak.
3774   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
3775                  rresult, Address(rresult), rtmp, /*tmp_thread*/noreg);
3776   bind(resolved);
3777 }
3778 
3779 void MacroAssembler::load_mirror(Register dst, Register method, Register tmp) {
3780   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
3781   ldr(dst, Address(rmethod, Method::const_offset()));
3782   ldr(dst, Address(dst, ConstMethod::constants_offset()));
3783   ldr(dst, Address(dst, ConstantPool::pool_holder_offset_in_bytes()));
3784   ldr(dst, Address(dst, mirror_offset));
3785   resolve_oop_handle(dst, tmp);
3786 }
3787 
3788 void MacroAssembler::cmp_klass(Register oop, Register trial_klass, Register tmp) {
3789   assert(UseCompressedClassPointers, "Lilliput");
3790   load_nklass(tmp, oop);
3791   if (CompressedKlassPointers::base() == NULL) {
3792     cmp(trial_klass, tmp, LSL, CompressedKlassPointers::shift());
3793     return;
3794   } else if (((uint64_t)CompressedKlassPointers::base() & 0xffffffff) == 0
3795              && CompressedKlassPointers::shift() == 0) {
3796     // Only the bottom 32 bits matter
3797     cmpw(trial_klass, tmp);
3798     return;
3799   }
3800   decode_klass_not_null(tmp);
3801   cmp(trial_klass, tmp);
3802 }
3803 
3804 // Algorithm must match CompressedOops::encode.
3805 void MacroAssembler::encode_heap_oop(Register d, Register s) {
3806 #ifdef ASSERT
3807   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
3808 #endif
3809   verify_oop_msg(s, "broken oop in encode_heap_oop");
3810   if (CompressedOops::base() == NULL) {
3811     if (CompressedOops::shift() != 0) {
3812       assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
3813       lsr(d, s, LogMinObjAlignmentInBytes);
3814     } else {
3815       mov(d, s);
3816     }
3817   } else {
3818     subs(d, s, rheapbase);
3819     csel(d, d, zr, Assembler::HS);
3820     lsr(d, d, LogMinObjAlignmentInBytes);
3821 
3822     /*  Old algorithm: is this any worse?
3823     Label nonnull;
3824     cbnz(r, nonnull);
3825     sub(r, r, rheapbase);
3826     bind(nonnull);
3827     lsr(r, r, LogMinObjAlignmentInBytes);
3828     */
3829   }
3830 }
3831 
3832 void MacroAssembler::encode_heap_oop_not_null(Register r) {
3833 #ifdef ASSERT
3834   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
3835   if (CheckCompressedOops) {
3836     Label ok;
3837     cbnz(r, ok);
3838     stop("null oop passed to encode_heap_oop_not_null");
3839     bind(ok);
3840   }
3841 #endif
3842   verify_oop_msg(r, "broken oop in encode_heap_oop_not_null");
3843   if (CompressedOops::base() != NULL) {
3844     sub(r, r, rheapbase);
3845   }
3846   if (CompressedOops::shift() != 0) {
3847     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
3848     lsr(r, r, LogMinObjAlignmentInBytes);
3849   }
3850 }
3851 
3852 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
3853 #ifdef ASSERT
3854   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
3855   if (CheckCompressedOops) {
3856     Label ok;
3857     cbnz(src, ok);
3858     stop("null oop passed to encode_heap_oop_not_null2");
3859     bind(ok);
3860   }
3861 #endif
3862   verify_oop_msg(src, "broken oop in encode_heap_oop_not_null2");
3863 
3864   Register data = src;
3865   if (CompressedOops::base() != NULL) {
3866     sub(dst, src, rheapbase);
3867     data = dst;
3868   }
3869   if (CompressedOops::shift() != 0) {
3870     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
3871     lsr(dst, data, LogMinObjAlignmentInBytes);
3872     data = dst;
3873   }
3874   if (data == src)
3875     mov(dst, src);
3876 }
3877 
3878 void  MacroAssembler::decode_heap_oop(Register d, Register s) {
3879 #ifdef ASSERT
3880   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
3881 #endif
3882   if (CompressedOops::base() == NULL) {
3883     if (CompressedOops::shift() != 0 || d != s) {
3884       lsl(d, s, CompressedOops::shift());
3885     }
3886   } else {
3887     Label done;
3888     if (d != s)
3889       mov(d, s);
3890     cbz(s, done);
3891     add(d, rheapbase, s, Assembler::LSL, LogMinObjAlignmentInBytes);
3892     bind(done);
3893   }
3894   verify_oop_msg(d, "broken oop in decode_heap_oop");
3895 }
3896 
3897 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
3898   assert (UseCompressedOops, "should only be used for compressed headers");
3899   assert (Universe::heap() != NULL, "java heap should be initialized");
3900   // Cannot assert, unverified entry point counts instructions (see .ad file)
3901   // vtableStubs also counts instructions in pd_code_size_limit.
3902   // Also do not verify_oop as this is called by verify_oop.
3903   if (CompressedOops::shift() != 0) {
3904     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
3905     if (CompressedOops::base() != NULL) {
3906       add(r, rheapbase, r, Assembler::LSL, LogMinObjAlignmentInBytes);
3907     } else {
3908       add(r, zr, r, Assembler::LSL, LogMinObjAlignmentInBytes);
3909     }
3910   } else {
3911     assert (CompressedOops::base() == NULL, "sanity");
3912   }
3913 }
3914 
3915 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
3916   assert (UseCompressedOops, "should only be used for compressed headers");
3917   assert (Universe::heap() != NULL, "java heap should be initialized");
3918   // Cannot assert, unverified entry point counts instructions (see .ad file)
3919   // vtableStubs also counts instructions in pd_code_size_limit.
3920   // Also do not verify_oop as this is called by verify_oop.
3921   if (CompressedOops::shift() != 0) {
3922     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
3923     if (CompressedOops::base() != NULL) {
3924       add(dst, rheapbase, src, Assembler::LSL, LogMinObjAlignmentInBytes);
3925     } else {
3926       add(dst, zr, src, Assembler::LSL, LogMinObjAlignmentInBytes);
3927     }
3928   } else {
3929     assert (CompressedOops::base() == NULL, "sanity");
3930     if (dst != src) {
3931       mov(dst, src);
3932     }
3933   }
3934 }
3935 
3936 MacroAssembler::KlassDecodeMode MacroAssembler::_klass_decode_mode(KlassDecodeNone);
3937 
3938 // Returns a static string
3939 const char* MacroAssembler::describe_klass_decode_mode(MacroAssembler::KlassDecodeMode mode) {
3940   switch (mode) {
3941   case KlassDecodeNone: return "none";
3942   case KlassDecodeZero: return "zero";
3943   case KlassDecodeXor:  return "xor";
3944   case KlassDecodeMovk: return "movk";
3945   default:
3946     ShouldNotReachHere();
3947   }
3948   return NULL;
3949 }
3950 
3951 // Return the current narrow Klass pointer decode mode.
3952 MacroAssembler::KlassDecodeMode MacroAssembler::klass_decode_mode() {
3953   if (_klass_decode_mode == KlassDecodeNone) {
3954     // First time initialization
3955     assert(UseCompressedClassPointers, "not using compressed class pointers");
3956     assert(Metaspace::initialized(), "metaspace not initialized yet");
3957 
3958     _klass_decode_mode = klass_decode_mode_for_base(CompressedKlassPointers::base());
3959     guarantee(_klass_decode_mode != KlassDecodeNone,
3960               PTR_FORMAT " is not a valid encoding base on aarch64",
3961               p2i(CompressedKlassPointers::base()));
3962     log_info(metaspace)("klass decode mode initialized: %s", describe_klass_decode_mode(_klass_decode_mode));
3963   }
3964   return _klass_decode_mode;
3965 }
3966 
3967 // Given an arbitrary base address, return the KlassDecodeMode that would be used. Return KlassDecodeNone
3968 // if base address is not valid for encoding.
3969 MacroAssembler::KlassDecodeMode MacroAssembler::klass_decode_mode_for_base(address base) {
3970   assert(CompressedKlassPointers::shift() != 0, "not lilliput?");
3971 
3972   const uint64_t base_u64 = (uint64_t) base;
3973 
3974   if (base_u64 == 0) {
3975     return KlassDecodeZero;
3976   }
3977 
3978   if (operand_valid_for_logical_immediate(false, base_u64) &&
3979       ((base_u64 & (KlassEncodingMetaspaceMax - 1)) == 0)) {
3980     return KlassDecodeXor;
3981   }
3982 
3983   const uint64_t shifted_base = base_u64 >> CompressedKlassPointers::shift();
3984   if ((shifted_base & 0xffff0000ffffffff) == 0) {
3985     return KlassDecodeMovk;
3986   }
3987 
3988   return KlassDecodeNone;
3989 }
3990 
3991 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
3992   assert (UseCompressedClassPointers, "should only be used for compressed headers");
3993   assert(CompressedKlassPointers::shift() != 0, "not lilliput?");
3994   switch (klass_decode_mode()) {
3995   case KlassDecodeZero:
3996     lsr(dst, src, LogKlassAlignmentInBytes);
3997     break;
3998 
3999   case KlassDecodeXor:
4000     eor(dst, src, (uint64_t)CompressedKlassPointers::base());
4001     lsr(dst, dst, LogKlassAlignmentInBytes);
4002     break;
4003 
4004   case KlassDecodeMovk:
4005     ubfx(dst, src, LogKlassAlignmentInBytes, MaxNarrowKlassPointerBits);
4006     break;
4007 
4008   case KlassDecodeNone:
4009     ShouldNotReachHere();
4010     break;
4011   }
4012 }
4013 
4014 void MacroAssembler::encode_klass_not_null(Register r) {
4015   encode_klass_not_null(r, r);
4016 }
4017 
4018 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
4019   assert (UseCompressedClassPointers, "should only be used for compressed headers");
4020 
4021   assert(CompressedKlassPointers::shift() != 0, "not lilliput?");
4022 
4023   switch (klass_decode_mode()) {
4024   case KlassDecodeZero:
4025     if (dst != src) mov(dst, src);
4026     break;
4027 
4028   case KlassDecodeXor:
4029     lsl(dst, src, LogKlassAlignmentInBytes);
4030     eor(dst, dst, (uint64_t)CompressedKlassPointers::base());
4031     break;
4032 
4033   case KlassDecodeMovk: {
4034     const uint64_t shifted_base =
4035       (uint64_t)CompressedKlassPointers::base() >> CompressedKlassPointers::shift();
4036 
4037     // Invalid base should have been gracefully handled via klass_decode_mode() in VM initialization.
4038     assert((shifted_base & 0xffff0000ffffffff) == 0, "incompatible base");
4039 
4040     if (dst != src) movw(dst, src);
4041     movk(dst, shifted_base >> 32, 32);
4042     lsl(dst, dst, LogKlassAlignmentInBytes);
4043     break;
4044   }
4045 
4046   case KlassDecodeNone:
4047     ShouldNotReachHere();
4048     break;
4049   }
4050 }
4051 
4052 void  MacroAssembler::decode_klass_not_null(Register r) {
4053   decode_klass_not_null(r, r);
4054 }
4055 
4056 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
4057 #ifdef ASSERT
4058   {
4059     ThreadInVMfromUnknown tiv;
4060     assert (UseCompressedOops, "should only be used for compressed oops");
4061     assert (Universe::heap() != NULL, "java heap should be initialized");
4062     assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
4063     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
4064   }
4065 #endif
4066   int oop_index = oop_recorder()->find_index(obj);
4067   InstructionMark im(this);
4068   RelocationHolder rspec = oop_Relocation::spec(oop_index);
4069   code_section()->relocate(inst_mark(), rspec);
4070   movz(dst, 0xDEAD, 16);
4071   movk(dst, 0xBEEF);
4072 }
4073 
4074 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
4075   assert (UseCompressedClassPointers, "should only be used for compressed headers");
4076   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
4077   int index = oop_recorder()->find_index(k);
4078   assert(! Universe::heap()->is_in(k), "should not be an oop");
4079 
4080   InstructionMark im(this);
4081   RelocationHolder rspec = metadata_Relocation::spec(index);
4082   code_section()->relocate(inst_mark(), rspec);
4083   narrowKlass nk = CompressedKlassPointers::encode(k);
4084   movz(dst, (nk >> 16), 16);
4085   movk(dst, nk & 0xffff);
4086 }
4087 
4088 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators,
4089                                     Register dst, Address src,
4090                                     Register tmp1, Register thread_tmp) {
4091   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
4092   decorators = AccessInternal::decorator_fixup(decorators);
4093   bool as_raw = (decorators & AS_RAW) != 0;
4094   if (as_raw) {
4095     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
4096   } else {
4097     bs->load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
4098   }
4099 }
4100 
4101 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators,
4102                                      Address dst, Register src,
4103                                      Register tmp1, Register thread_tmp) {
4104   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
4105   decorators = AccessInternal::decorator_fixup(decorators);
4106   bool as_raw = (decorators & AS_RAW) != 0;
4107   if (as_raw) {
4108     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, src, tmp1, thread_tmp);
4109   } else {
4110     bs->store_at(this, decorators, type, dst, src, tmp1, thread_tmp);
4111   }
4112 }
4113 
4114 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
4115                                    Register thread_tmp, DecoratorSet decorators) {
4116   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, thread_tmp);
4117 }
4118 
4119 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
4120                                             Register thread_tmp, DecoratorSet decorators) {
4121   access_load_at(T_OBJECT, IN_HEAP | IS_NOT_NULL | decorators, dst, src, tmp1, thread_tmp);
4122 }
4123 
4124 void MacroAssembler::store_heap_oop(Address dst, Register src, Register tmp1,
4125                                     Register thread_tmp, DecoratorSet decorators) {
4126   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, thread_tmp);
4127 }
4128 
4129 // Used for storing NULLs.
4130 void MacroAssembler::store_heap_oop_null(Address dst) {
4131   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg);
4132 }
4133 
4134 Address MacroAssembler::allocate_metadata_address(Metadata* obj) {
4135   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
4136   int index = oop_recorder()->allocate_metadata_index(obj);
4137   RelocationHolder rspec = metadata_Relocation::spec(index);
4138   return Address((address)obj, rspec);
4139 }
4140 
4141 // Move an oop into a register.  immediate is true if we want
4142 // immediate instructions and nmethod entry barriers are not enabled.
4143 // i.e. we are not going to patch this instruction while the code is being
4144 // executed by another thread.
4145 void MacroAssembler::movoop(Register dst, jobject obj, bool immediate) {
4146   int oop_index;
4147   if (obj == NULL) {
4148     oop_index = oop_recorder()->allocate_oop_index(obj);
4149   } else {
4150 #ifdef ASSERT
4151     {
4152       ThreadInVMfromUnknown tiv;
4153       assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
4154     }
4155 #endif
4156     oop_index = oop_recorder()->find_index(obj);
4157   }
4158   RelocationHolder rspec = oop_Relocation::spec(oop_index);
4159 
4160   // nmethod entry barrier necessitate using the constant pool. They have to be
4161   // ordered with respected to oop accesses.
4162   // Using immediate literals would necessitate ISBs.
4163   if (BarrierSet::barrier_set()->barrier_set_nmethod() != NULL || !immediate) {
4164     address dummy = address(uintptr_t(pc()) & -wordSize); // A nearby aligned address
4165     ldr_constant(dst, Address(dummy, rspec));
4166   } else
4167     mov(dst, Address((address)obj, rspec));
4168 
4169 }
4170 
4171 // Move a metadata address into a register.
4172 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
4173   int oop_index;
4174   if (obj == NULL) {
4175     oop_index = oop_recorder()->allocate_metadata_index(obj);
4176   } else {
4177     oop_index = oop_recorder()->find_index(obj);
4178   }
4179   RelocationHolder rspec = metadata_Relocation::spec(oop_index);
4180   mov(dst, Address((address)obj, rspec));
4181 }
4182 
4183 Address MacroAssembler::constant_oop_address(jobject obj) {
4184 #ifdef ASSERT
4185   {
4186     ThreadInVMfromUnknown tiv;
4187     assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
4188     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "not an oop");
4189   }
4190 #endif
4191   int oop_index = oop_recorder()->find_index(obj);
4192   return Address((address)obj, oop_Relocation::spec(oop_index));
4193 }
4194 
4195 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
4196 void MacroAssembler::tlab_allocate(Register obj,
4197                                    Register var_size_in_bytes,
4198                                    int con_size_in_bytes,
4199                                    Register t1,
4200                                    Register t2,
4201                                    Label& slow_case) {
4202   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
4203   bs->tlab_allocate(this, obj, var_size_in_bytes, con_size_in_bytes, t1, t2, slow_case);
4204 }
4205 
4206 // Defines obj, preserves var_size_in_bytes
4207 void MacroAssembler::eden_allocate(Register obj,
4208                                    Register var_size_in_bytes,
4209                                    int con_size_in_bytes,
4210                                    Register t1,
4211                                    Label& slow_case) {
4212   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
4213   bs->eden_allocate(this, obj, var_size_in_bytes, con_size_in_bytes, t1, slow_case);
4214 }
4215 
4216 void MacroAssembler::verify_tlab() {
4217 #ifdef ASSERT
4218   if (UseTLAB && VerifyOops) {
4219     Label next, ok;
4220 
4221     stp(rscratch2, rscratch1, Address(pre(sp, -16)));
4222 
4223     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4224     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
4225     cmp(rscratch2, rscratch1);
4226     br(Assembler::HS, next);
4227     STOP("assert(top >= start)");
4228     should_not_reach_here();
4229 
4230     bind(next);
4231     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
4232     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4233     cmp(rscratch2, rscratch1);
4234     br(Assembler::HS, ok);
4235     STOP("assert(top <= end)");
4236     should_not_reach_here();
4237 
4238     bind(ok);
4239     ldp(rscratch2, rscratch1, Address(post(sp, 16)));
4240   }
4241 #endif
4242 }
4243 
4244 // Writes to stack successive pages until offset reached to check for
4245 // stack overflow + shadow pages.  This clobbers tmp.
4246 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
4247   assert_different_registers(tmp, size, rscratch1);
4248   mov(tmp, sp);
4249   // Bang stack for total size given plus shadow page size.
4250   // Bang one page at a time because large size can bang beyond yellow and
4251   // red zones.
4252   Label loop;
4253   mov(rscratch1, os::vm_page_size());
4254   bind(loop);
4255   lea(tmp, Address(tmp, -os::vm_page_size()));
4256   subsw(size, size, rscratch1);
4257   str(size, Address(tmp));
4258   br(Assembler::GT, loop);
4259 
4260   // Bang down shadow pages too.
4261   // At this point, (tmp-0) is the last address touched, so don't
4262   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
4263   // was post-decremented.)  Skip this address by starting at i=1, and
4264   // touch a few more pages below.  N.B.  It is important to touch all
4265   // the way down to and including i=StackShadowPages.
4266   for (int i = 0; i < (int)(StackOverflow::stack_shadow_zone_size() / os::vm_page_size()) - 1; i++) {
4267     // this could be any sized move but this is can be a debugging crumb
4268     // so the bigger the better.
4269     lea(tmp, Address(tmp, -os::vm_page_size()));
4270     str(size, Address(tmp));
4271   }
4272 }
4273 
4274 // Move the address of the polling page into dest.
4275 void MacroAssembler::get_polling_page(Register dest, relocInfo::relocType rtype) {
4276   ldr(dest, Address(rthread, JavaThread::polling_page_offset()));
4277 }
4278 
4279 // Read the polling page.  The address of the polling page must
4280 // already be in r.
4281 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
4282   address mark;
4283   {
4284     InstructionMark im(this);
4285     code_section()->relocate(inst_mark(), rtype);
4286     ldrw(zr, Address(r, 0));
4287     mark = inst_mark();
4288   }
4289   verify_cross_modify_fence_not_required();
4290   return mark;
4291 }
4292 
4293 void MacroAssembler::adrp(Register reg1, const Address &dest, uint64_t &byte_offset) {
4294   relocInfo::relocType rtype = dest.rspec().reloc()->type();
4295   uint64_t low_page = (uint64_t)CodeCache::low_bound() >> 12;
4296   uint64_t high_page = (uint64_t)(CodeCache::high_bound()-1) >> 12;
4297   uint64_t dest_page = (uint64_t)dest.target() >> 12;
4298   int64_t offset_low = dest_page - low_page;
4299   int64_t offset_high = dest_page - high_page;
4300 
4301   assert(is_valid_AArch64_address(dest.target()), "bad address");
4302   assert(dest.getMode() == Address::literal, "ADRP must be applied to a literal address");
4303 
4304   InstructionMark im(this);
4305   code_section()->relocate(inst_mark(), dest.rspec());
4306   // 8143067: Ensure that the adrp can reach the dest from anywhere within
4307   // the code cache so that if it is relocated we know it will still reach
4308   if (offset_high >= -(1<<20) && offset_low < (1<<20)) {
4309     _adrp(reg1, dest.target());
4310   } else {
4311     uint64_t target = (uint64_t)dest.target();
4312     uint64_t adrp_target
4313       = (target & 0xffffffffULL) | ((uint64_t)pc() & 0xffff00000000ULL);
4314 
4315     _adrp(reg1, (address)adrp_target);
4316     movk(reg1, target >> 32, 32);
4317   }
4318   byte_offset = (uint64_t)dest.target() & 0xfff;
4319 }
4320 
4321 void MacroAssembler::load_byte_map_base(Register reg) {
4322   CardTable::CardValue* byte_map_base =
4323     ((CardTableBarrierSet*)(BarrierSet::barrier_set()))->card_table()->byte_map_base();
4324 
4325   // Strictly speaking the byte_map_base isn't an address at all, and it might
4326   // even be negative. It is thus materialised as a constant.
4327   mov(reg, (uint64_t)byte_map_base);
4328 }
4329 
4330 void MacroAssembler::build_frame(int framesize) {
4331   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
4332   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
4333   protect_return_address();
4334   if (framesize < ((1 << 9) + 2 * wordSize)) {
4335     sub(sp, sp, framesize);
4336     stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4337     if (PreserveFramePointer) add(rfp, sp, framesize - 2 * wordSize);
4338   } else {
4339     stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
4340     if (PreserveFramePointer) mov(rfp, sp);
4341     if (framesize < ((1 << 12) + 2 * wordSize))
4342       sub(sp, sp, framesize - 2 * wordSize);
4343     else {
4344       mov(rscratch1, framesize - 2 * wordSize);
4345       sub(sp, sp, rscratch1);
4346     }
4347   }
4348   verify_cross_modify_fence_not_required();
4349 }
4350 
4351 void MacroAssembler::remove_frame(int framesize) {
4352   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
4353   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
4354   if (framesize < ((1 << 9) + 2 * wordSize)) {
4355     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4356     add(sp, sp, framesize);
4357   } else {
4358     if (framesize < ((1 << 12) + 2 * wordSize))
4359       add(sp, sp, framesize - 2 * wordSize);
4360     else {
4361       mov(rscratch1, framesize - 2 * wordSize);
4362       add(sp, sp, rscratch1);
4363     }
4364     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
4365   }
4366   authenticate_return_address();
4367 }
4368 
4369 
4370 // This method counts leading positive bytes (highest bit not set) in provided byte array
4371 address MacroAssembler::count_positives(Register ary1, Register len, Register result) {
4372     // Simple and most common case of aligned small array which is not at the
4373     // end of memory page is placed here. All other cases are in stub.
4374     Label LOOP, END, STUB, STUB_LONG, SET_RESULT, DONE;
4375     const uint64_t UPPER_BIT_MASK=0x8080808080808080;
4376     assert_different_registers(ary1, len, result);
4377 
4378     mov(result, len);
4379     cmpw(len, 0);
4380     br(LE, DONE);
4381     cmpw(len, 4 * wordSize);
4382     br(GE, STUB_LONG); // size > 32 then go to stub
4383 
4384     int shift = 64 - exact_log2(os::vm_page_size());
4385     lsl(rscratch1, ary1, shift);
4386     mov(rscratch2, (size_t)(4 * wordSize) << shift);
4387     adds(rscratch2, rscratch1, rscratch2);  // At end of page?
4388     br(CS, STUB); // at the end of page then go to stub
4389     subs(len, len, wordSize);
4390     br(LT, END);
4391 
4392   BIND(LOOP);
4393     ldr(rscratch1, Address(post(ary1, wordSize)));
4394     tst(rscratch1, UPPER_BIT_MASK);
4395     br(NE, SET_RESULT);
4396     subs(len, len, wordSize);
4397     br(GE, LOOP);
4398     cmpw(len, -wordSize);
4399     br(EQ, DONE);
4400 
4401   BIND(END);
4402     ldr(rscratch1, Address(ary1));
4403     sub(rscratch2, zr, len, LSL, 3); // LSL 3 is to get bits from bytes
4404     lslv(rscratch1, rscratch1, rscratch2);
4405     tst(rscratch1, UPPER_BIT_MASK);
4406     br(NE, SET_RESULT);
4407     b(DONE);
4408 
4409   BIND(STUB);
4410     RuntimeAddress count_pos = RuntimeAddress(StubRoutines::aarch64::count_positives());
4411     assert(count_pos.target() != NULL, "count_positives stub has not been generated");
4412     address tpc1 = trampoline_call(count_pos);
4413     if (tpc1 == NULL) {
4414       DEBUG_ONLY(reset_labels(STUB_LONG, SET_RESULT, DONE));
4415       postcond(pc() == badAddress);
4416       return NULL;
4417     }
4418     b(DONE);
4419 
4420   BIND(STUB_LONG);
4421     RuntimeAddress count_pos_long = RuntimeAddress(StubRoutines::aarch64::count_positives_long());
4422     assert(count_pos_long.target() != NULL, "count_positives_long stub has not been generated");
4423     address tpc2 = trampoline_call(count_pos_long);
4424     if (tpc2 == NULL) {
4425       DEBUG_ONLY(reset_labels(SET_RESULT, DONE));
4426       postcond(pc() == badAddress);
4427       return NULL;
4428     }
4429     b(DONE);
4430 
4431   BIND(SET_RESULT);
4432 
4433     add(len, len, wordSize);
4434     sub(result, result, len);
4435 
4436   BIND(DONE);
4437   postcond(pc() != badAddress);
4438   return pc();
4439 }
4440 
4441 address MacroAssembler::arrays_equals(Register a1, Register a2, Register tmp3,
4442                                       Register tmp4, Register tmp5, Register result,
4443                                       Register cnt1, int elem_size) {
4444   Label DONE, SAME;
4445   Register tmp1 = rscratch1;
4446   Register tmp2 = rscratch2;
4447   Register cnt2 = tmp2;  // cnt2 only used in array length compare
4448   int elem_per_word = wordSize/elem_size;
4449   int log_elem_size = exact_log2(elem_size);
4450   int length_offset = arrayOopDesc::length_offset_in_bytes();
4451   int base_offset
4452     = arrayOopDesc::base_offset_in_bytes(elem_size == 2 ? T_CHAR : T_BYTE);
4453   int stubBytesThreshold = 3 * 64 + (UseSIMDForArrayEquals ? 0 : 16);
4454 
4455   assert(elem_size == 1 || elem_size == 2, "must be char or byte");
4456   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
4457 
4458 #ifndef PRODUCT
4459   {
4460     const char kind = (elem_size == 2) ? 'U' : 'L';
4461     char comment[64];
4462     snprintf(comment, sizeof comment, "array_equals%c{", kind);
4463     BLOCK_COMMENT(comment);
4464   }
4465 #endif
4466 
4467   // if (a1 == a2)
4468   //     return true;
4469   cmpoop(a1, a2); // May have read barriers for a1 and a2.
4470   br(EQ, SAME);
4471 
4472   if (UseSimpleArrayEquals) {
4473     Label NEXT_WORD, SHORT, TAIL03, TAIL01, A_MIGHT_BE_NULL, A_IS_NOT_NULL;
4474     // if (a1 == null || a2 == null)
4475     //     return false;
4476     // a1 & a2 == 0 means (some-pointer is null) or
4477     // (very-rare-or-even-probably-impossible-pointer-values)
4478     // so, we can save one branch in most cases
4479     tst(a1, a2);
4480     mov(result, false);
4481     br(EQ, A_MIGHT_BE_NULL);
4482     // if (a1.length != a2.length)
4483     //      return false;
4484     bind(A_IS_NOT_NULL);
4485     ldrw(cnt1, Address(a1, length_offset));
4486     ldrw(cnt2, Address(a2, length_offset));
4487     eorw(tmp5, cnt1, cnt2);
4488     cbnzw(tmp5, DONE);
4489     lea(a1, Address(a1, base_offset));
4490     lea(a2, Address(a2, base_offset));
4491     // Check for short strings, i.e. smaller than wordSize.
4492     subs(cnt1, cnt1, elem_per_word);
4493     br(Assembler::LT, SHORT);
4494     // Main 8 byte comparison loop.
4495     bind(NEXT_WORD); {
4496       ldr(tmp1, Address(post(a1, wordSize)));
4497       ldr(tmp2, Address(post(a2, wordSize)));
4498       subs(cnt1, cnt1, elem_per_word);
4499       eor(tmp5, tmp1, tmp2);
4500       cbnz(tmp5, DONE);
4501     } br(GT, NEXT_WORD);
4502     // Last longword.  In the case where length == 4 we compare the
4503     // same longword twice, but that's still faster than another
4504     // conditional branch.
4505     // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
4506     // length == 4.
4507     if (log_elem_size > 0)
4508       lsl(cnt1, cnt1, log_elem_size);
4509     ldr(tmp3, Address(a1, cnt1));
4510     ldr(tmp4, Address(a2, cnt1));
4511     eor(tmp5, tmp3, tmp4);
4512     cbnz(tmp5, DONE);
4513     b(SAME);
4514     bind(A_MIGHT_BE_NULL);
4515     // in case both a1 and a2 are not-null, proceed with loads
4516     cbz(a1, DONE);
4517     cbz(a2, DONE);
4518     b(A_IS_NOT_NULL);
4519     bind(SHORT);
4520 
4521     tbz(cnt1, 2 - log_elem_size, TAIL03); // 0-7 bytes left.
4522     {
4523       ldrw(tmp1, Address(post(a1, 4)));
4524       ldrw(tmp2, Address(post(a2, 4)));
4525       eorw(tmp5, tmp1, tmp2);
4526       cbnzw(tmp5, DONE);
4527     }
4528     bind(TAIL03);
4529     tbz(cnt1, 1 - log_elem_size, TAIL01); // 0-3 bytes left.
4530     {
4531       ldrh(tmp3, Address(post(a1, 2)));
4532       ldrh(tmp4, Address(post(a2, 2)));
4533       eorw(tmp5, tmp3, tmp4);
4534       cbnzw(tmp5, DONE);
4535     }
4536     bind(TAIL01);
4537     if (elem_size == 1) { // Only needed when comparing byte arrays.
4538       tbz(cnt1, 0, SAME); // 0-1 bytes left.
4539       {
4540         ldrb(tmp1, a1);
4541         ldrb(tmp2, a2);
4542         eorw(tmp5, tmp1, tmp2);
4543         cbnzw(tmp5, DONE);
4544       }
4545     }
4546   } else {
4547     Label NEXT_DWORD, SHORT, TAIL, TAIL2, STUB,
4548         CSET_EQ, LAST_CHECK;
4549     mov(result, false);
4550     cbz(a1, DONE);
4551     ldrw(cnt1, Address(a1, length_offset));
4552     cbz(a2, DONE);
4553     ldrw(cnt2, Address(a2, length_offset));
4554     // on most CPUs a2 is still "locked"(surprisingly) in ldrw and it's
4555     // faster to perform another branch before comparing a1 and a2
4556     cmp(cnt1, (u1)elem_per_word);
4557     br(LE, SHORT); // short or same
4558     ldr(tmp3, Address(pre(a1, base_offset)));
4559     subs(zr, cnt1, stubBytesThreshold);
4560     br(GE, STUB);
4561     ldr(tmp4, Address(pre(a2, base_offset)));
4562     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
4563     cmp(cnt2, cnt1);
4564     br(NE, DONE);
4565 
4566     // Main 16 byte comparison loop with 2 exits
4567     bind(NEXT_DWORD); {
4568       ldr(tmp1, Address(pre(a1, wordSize)));
4569       ldr(tmp2, Address(pre(a2, wordSize)));
4570       subs(cnt1, cnt1, 2 * elem_per_word);
4571       br(LE, TAIL);
4572       eor(tmp4, tmp3, tmp4);
4573       cbnz(tmp4, DONE);
4574       ldr(tmp3, Address(pre(a1, wordSize)));
4575       ldr(tmp4, Address(pre(a2, wordSize)));
4576       cmp(cnt1, (u1)elem_per_word);
4577       br(LE, TAIL2);
4578       cmp(tmp1, tmp2);
4579     } br(EQ, NEXT_DWORD);
4580     b(DONE);
4581 
4582     bind(TAIL);
4583     eor(tmp4, tmp3, tmp4);
4584     eor(tmp2, tmp1, tmp2);
4585     lslv(tmp2, tmp2, tmp5);
4586     orr(tmp5, tmp4, tmp2);
4587     cmp(tmp5, zr);
4588     b(CSET_EQ);
4589 
4590     bind(TAIL2);
4591     eor(tmp2, tmp1, tmp2);
4592     cbnz(tmp2, DONE);
4593     b(LAST_CHECK);
4594 
4595     bind(STUB);
4596     ldr(tmp4, Address(pre(a2, base_offset)));
4597     cmp(cnt2, cnt1);
4598     br(NE, DONE);
4599     if (elem_size == 2) { // convert to byte counter
4600       lsl(cnt1, cnt1, 1);
4601     }
4602     eor(tmp5, tmp3, tmp4);
4603     cbnz(tmp5, DONE);
4604     RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_array_equals());
4605     assert(stub.target() != NULL, "array_equals_long stub has not been generated");
4606     address tpc = trampoline_call(stub);
4607     if (tpc == NULL) {
4608       DEBUG_ONLY(reset_labels(SHORT, LAST_CHECK, CSET_EQ, SAME, DONE));
4609       postcond(pc() == badAddress);
4610       return NULL;
4611     }
4612     b(DONE);
4613 
4614     // (a1 != null && a2 == null) || (a1 != null && a2 != null && a1 == a2)
4615     // so, if a2 == null => return false(0), else return true, so we can return a2
4616     mov(result, a2);
4617     b(DONE);
4618     bind(SHORT);
4619     cmp(cnt2, cnt1);
4620     br(NE, DONE);
4621     cbz(cnt1, SAME);
4622     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
4623     ldr(tmp3, Address(a1, base_offset));
4624     ldr(tmp4, Address(a2, base_offset));
4625     bind(LAST_CHECK);
4626     eor(tmp4, tmp3, tmp4);
4627     lslv(tmp5, tmp4, tmp5);
4628     cmp(tmp5, zr);
4629     bind(CSET_EQ);
4630     cset(result, EQ);
4631     b(DONE);
4632   }
4633 
4634   bind(SAME);
4635   mov(result, true);
4636   // That's it.
4637   bind(DONE);
4638 
4639   BLOCK_COMMENT("} array_equals");
4640   postcond(pc() != badAddress);
4641   return pc();
4642 }
4643 
4644 // Compare Strings
4645 
4646 // For Strings we're passed the address of the first characters in a1
4647 // and a2 and the length in cnt1.
4648 // elem_size is the element size in bytes: either 1 or 2.
4649 // There are two implementations.  For arrays >= 8 bytes, all
4650 // comparisons (including the final one, which may overlap) are
4651 // performed 8 bytes at a time.  For strings < 8 bytes, we compare a
4652 // halfword, then a short, and then a byte.
4653 
4654 void MacroAssembler::string_equals(Register a1, Register a2,
4655                                    Register result, Register cnt1, int elem_size)
4656 {
4657   Label SAME, DONE, SHORT, NEXT_WORD;
4658   Register tmp1 = rscratch1;
4659   Register tmp2 = rscratch2;
4660   Register cnt2 = tmp2;  // cnt2 only used in array length compare
4661 
4662   assert(elem_size == 1 || elem_size == 2, "must be 2 or 1 byte");
4663   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
4664 
4665 #ifndef PRODUCT
4666   {
4667     const char kind = (elem_size == 2) ? 'U' : 'L';
4668     char comment[64];
4669     snprintf(comment, sizeof comment, "{string_equals%c", kind);
4670     BLOCK_COMMENT(comment);
4671   }
4672 #endif
4673 
4674   mov(result, false);
4675 
4676   // Check for short strings, i.e. smaller than wordSize.
4677   subs(cnt1, cnt1, wordSize);
4678   br(Assembler::LT, SHORT);
4679   // Main 8 byte comparison loop.
4680   bind(NEXT_WORD); {
4681     ldr(tmp1, Address(post(a1, wordSize)));
4682     ldr(tmp2, Address(post(a2, wordSize)));
4683     subs(cnt1, cnt1, wordSize);
4684     eor(tmp1, tmp1, tmp2);
4685     cbnz(tmp1, DONE);
4686   } br(GT, NEXT_WORD);
4687   // Last longword.  In the case where length == 4 we compare the
4688   // same longword twice, but that's still faster than another
4689   // conditional branch.
4690   // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
4691   // length == 4.
4692   ldr(tmp1, Address(a1, cnt1));
4693   ldr(tmp2, Address(a2, cnt1));
4694   eor(tmp2, tmp1, tmp2);
4695   cbnz(tmp2, DONE);
4696   b(SAME);
4697 
4698   bind(SHORT);
4699   Label TAIL03, TAIL01;
4700 
4701   tbz(cnt1, 2, TAIL03); // 0-7 bytes left.
4702   {
4703     ldrw(tmp1, Address(post(a1, 4)));
4704     ldrw(tmp2, Address(post(a2, 4)));
4705     eorw(tmp1, tmp1, tmp2);
4706     cbnzw(tmp1, DONE);
4707   }
4708   bind(TAIL03);
4709   tbz(cnt1, 1, TAIL01); // 0-3 bytes left.
4710   {
4711     ldrh(tmp1, Address(post(a1, 2)));
4712     ldrh(tmp2, Address(post(a2, 2)));
4713     eorw(tmp1, tmp1, tmp2);
4714     cbnzw(tmp1, DONE);
4715   }
4716   bind(TAIL01);
4717   if (elem_size == 1) { // Only needed when comparing 1-byte elements
4718     tbz(cnt1, 0, SAME); // 0-1 bytes left.
4719     {
4720       ldrb(tmp1, a1);
4721       ldrb(tmp2, a2);
4722       eorw(tmp1, tmp1, tmp2);
4723       cbnzw(tmp1, DONE);
4724     }
4725   }
4726   // Arrays are equal.
4727   bind(SAME);
4728   mov(result, true);
4729 
4730   // That's it.
4731   bind(DONE);
4732   BLOCK_COMMENT("} string_equals");
4733 }
4734 
4735 
4736 // The size of the blocks erased by the zero_blocks stub.  We must
4737 // handle anything smaller than this ourselves in zero_words().
4738 const int MacroAssembler::zero_words_block_size = 8;
4739 
4740 // zero_words() is used by C2 ClearArray patterns and by
4741 // C1_MacroAssembler.  It is as small as possible, handling small word
4742 // counts locally and delegating anything larger to the zero_blocks
4743 // stub.  It is expanded many times in compiled code, so it is
4744 // important to keep it short.
4745 
4746 // ptr:   Address of a buffer to be zeroed.
4747 // cnt:   Count in HeapWords.
4748 //
4749 // ptr, cnt, rscratch1, and rscratch2 are clobbered.
4750 address MacroAssembler::zero_words(Register ptr, Register cnt)
4751 {
4752   assert(is_power_of_2(zero_words_block_size), "adjust this");
4753 
4754   BLOCK_COMMENT("zero_words {");
4755   assert(ptr == r10 && cnt == r11, "mismatch in register usage");
4756   RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
4757   assert(zero_blocks.target() != NULL, "zero_blocks stub has not been generated");
4758 
4759   subs(rscratch1, cnt, zero_words_block_size);
4760   Label around;
4761   br(LO, around);
4762   {
4763     RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
4764     assert(zero_blocks.target() != NULL, "zero_blocks stub has not been generated");
4765     // Make sure this is a C2 compilation. C1 allocates space only for
4766     // trampoline stubs generated by Call LIR ops, and in any case it
4767     // makes sense for a C1 compilation task to proceed as quickly as
4768     // possible.
4769     CompileTask* task;
4770     if (StubRoutines::aarch64::complete()
4771         && Thread::current()->is_Compiler_thread()
4772         && (task = ciEnv::current()->task())
4773         && is_c2_compile(task->comp_level())) {
4774       address tpc = trampoline_call(zero_blocks);
4775       if (tpc == NULL) {
4776         DEBUG_ONLY(reset_labels(around));
4777         assert(false, "failed to allocate space for trampoline");
4778         return NULL;
4779       }
4780     } else {
4781       far_call(zero_blocks);
4782     }
4783   }
4784   bind(around);
4785 
4786   // We have a few words left to do. zero_blocks has adjusted r10 and r11
4787   // for us.
4788   for (int i = zero_words_block_size >> 1; i > 1; i >>= 1) {
4789     Label l;
4790     tbz(cnt, exact_log2(i), l);
4791     for (int j = 0; j < i; j += 2) {
4792       stp(zr, zr, post(ptr, 2 * BytesPerWord));
4793     }
4794     bind(l);
4795   }
4796   {
4797     Label l;
4798     tbz(cnt, 0, l);
4799     str(zr, Address(ptr));
4800     bind(l);
4801   }
4802 
4803   BLOCK_COMMENT("} zero_words");
4804   return pc();
4805 }
4806 
4807 // base:         Address of a buffer to be zeroed, 8 bytes aligned.
4808 // cnt:          Immediate count in HeapWords.
4809 //
4810 // r10, r11, rscratch1, and rscratch2 are clobbered.
4811 void MacroAssembler::zero_words(Register base, uint64_t cnt)
4812 {
4813   guarantee(zero_words_block_size < BlockZeroingLowLimit,
4814             "increase BlockZeroingLowLimit");
4815   if (cnt <= (uint64_t)BlockZeroingLowLimit / BytesPerWord) {
4816 #ifndef PRODUCT
4817     {
4818       char buf[64];
4819       snprintf(buf, sizeof buf, "zero_words (count = %" PRIu64 ") {", cnt);
4820       BLOCK_COMMENT(buf);
4821     }
4822 #endif
4823     if (cnt >= 16) {
4824       uint64_t loops = cnt/16;
4825       if (loops > 1) {
4826         mov(rscratch2, loops - 1);
4827       }
4828       {
4829         Label loop;
4830         bind(loop);
4831         for (int i = 0; i < 16; i += 2) {
4832           stp(zr, zr, Address(base, i * BytesPerWord));
4833         }
4834         add(base, base, 16 * BytesPerWord);
4835         if (loops > 1) {
4836           subs(rscratch2, rscratch2, 1);
4837           br(GE, loop);
4838         }
4839       }
4840     }
4841     cnt %= 16;
4842     int i = cnt & 1;  // store any odd word to start
4843     if (i) str(zr, Address(base));
4844     for (; i < (int)cnt; i += 2) {
4845       stp(zr, zr, Address(base, i * wordSize));
4846     }
4847     BLOCK_COMMENT("} zero_words");
4848   } else {
4849     mov(r10, base); mov(r11, cnt);
4850     zero_words(r10, r11);
4851   }
4852 }
4853 
4854 // Zero blocks of memory by using DC ZVA.
4855 //
4856 // Aligns the base address first sufficiently for DC ZVA, then uses
4857 // DC ZVA repeatedly for every full block.  cnt is the size to be
4858 // zeroed in HeapWords.  Returns the count of words left to be zeroed
4859 // in cnt.
4860 //
4861 // NOTE: This is intended to be used in the zero_blocks() stub.  If
4862 // you want to use it elsewhere, note that cnt must be >= 2*zva_length.
4863 void MacroAssembler::zero_dcache_blocks(Register base, Register cnt) {
4864   Register tmp = rscratch1;
4865   Register tmp2 = rscratch2;
4866   int zva_length = VM_Version::zva_length();
4867   Label initial_table_end, loop_zva;
4868   Label fini;
4869 
4870   // Base must be 16 byte aligned. If not just return and let caller handle it
4871   tst(base, 0x0f);
4872   br(Assembler::NE, fini);
4873   // Align base with ZVA length.
4874   neg(tmp, base);
4875   andr(tmp, tmp, zva_length - 1);
4876 
4877   // tmp: the number of bytes to be filled to align the base with ZVA length.
4878   add(base, base, tmp);
4879   sub(cnt, cnt, tmp, Assembler::ASR, 3);
4880   adr(tmp2, initial_table_end);
4881   sub(tmp2, tmp2, tmp, Assembler::LSR, 2);
4882   br(tmp2);
4883 
4884   for (int i = -zva_length + 16; i < 0; i += 16)
4885     stp(zr, zr, Address(base, i));
4886   bind(initial_table_end);
4887 
4888   sub(cnt, cnt, zva_length >> 3);
4889   bind(loop_zva);
4890   dc(Assembler::ZVA, base);
4891   subs(cnt, cnt, zva_length >> 3);
4892   add(base, base, zva_length);
4893   br(Assembler::GE, loop_zva);
4894   add(cnt, cnt, zva_length >> 3); // count not zeroed by DC ZVA
4895   bind(fini);
4896 }
4897 
4898 // base:   Address of a buffer to be filled, 8 bytes aligned.
4899 // cnt:    Count in 8-byte unit.
4900 // value:  Value to be filled with.
4901 // base will point to the end of the buffer after filling.
4902 void MacroAssembler::fill_words(Register base, Register cnt, Register value)
4903 {
4904 //  Algorithm:
4905 //
4906 //    if (cnt == 0) {
4907 //      return;
4908 //    }
4909 //    if ((p & 8) != 0) {
4910 //      *p++ = v;
4911 //    }
4912 //
4913 //    scratch1 = cnt & 14;
4914 //    cnt -= scratch1;
4915 //    p += scratch1;
4916 //    switch (scratch1 / 2) {
4917 //      do {
4918 //        cnt -= 16;
4919 //          p[-16] = v;
4920 //          p[-15] = v;
4921 //        case 7:
4922 //          p[-14] = v;
4923 //          p[-13] = v;
4924 //        case 6:
4925 //          p[-12] = v;
4926 //          p[-11] = v;
4927 //          // ...
4928 //        case 1:
4929 //          p[-2] = v;
4930 //          p[-1] = v;
4931 //        case 0:
4932 //          p += 16;
4933 //      } while (cnt);
4934 //    }
4935 //    if ((cnt & 1) == 1) {
4936 //      *p++ = v;
4937 //    }
4938 
4939   assert_different_registers(base, cnt, value, rscratch1, rscratch2);
4940 
4941   Label fini, skip, entry, loop;
4942   const int unroll = 8; // Number of stp instructions we'll unroll
4943 
4944   cbz(cnt, fini);
4945   tbz(base, 3, skip);
4946   str(value, Address(post(base, 8)));
4947   sub(cnt, cnt, 1);
4948   bind(skip);
4949 
4950   andr(rscratch1, cnt, (unroll-1) * 2);
4951   sub(cnt, cnt, rscratch1);
4952   add(base, base, rscratch1, Assembler::LSL, 3);
4953   adr(rscratch2, entry);
4954   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 1);
4955   br(rscratch2);
4956 
4957   bind(loop);
4958   add(base, base, unroll * 16);
4959   for (int i = -unroll; i < 0; i++)
4960     stp(value, value, Address(base, i * 16));
4961   bind(entry);
4962   subs(cnt, cnt, unroll * 2);
4963   br(Assembler::GE, loop);
4964 
4965   tbz(cnt, 0, fini);
4966   str(value, Address(post(base, 8)));
4967   bind(fini);
4968 }
4969 
4970 // Intrinsic for
4971 //
4972 // - sun/nio/cs/ISO_8859_1$Encoder.implEncodeISOArray
4973 //     return the number of characters copied.
4974 // - java/lang/StringUTF16.compress
4975 //     return zero (0) if copy fails, otherwise 'len'.
4976 //
4977 // This version always returns the number of characters copied, and does not
4978 // clobber the 'len' register. A successful copy will complete with the post-
4979 // condition: 'res' == 'len', while an unsuccessful copy will exit with the
4980 // post-condition: 0 <= 'res' < 'len'.
4981 //
4982 // NOTE: Attempts to use 'ld2' (and 'umaxv' in the ISO part) has proven to
4983 //       degrade performance (on Ampere Altra - Neoverse N1), to an extent
4984 //       beyond the acceptable, even though the footprint would be smaller.
4985 //       Using 'umaxv' in the ASCII-case comes with a small penalty but does
4986 //       avoid additional bloat.
4987 //
4988 void MacroAssembler::encode_iso_array(Register src, Register dst,
4989                                       Register len, Register res, bool ascii,
4990                                       FloatRegister vtmp0, FloatRegister vtmp1,
4991                                       FloatRegister vtmp2, FloatRegister vtmp3)
4992 {
4993   Register cnt = res;
4994   Register max = rscratch1;
4995   Register chk = rscratch2;
4996 
4997   prfm(Address(src), PLDL1STRM);
4998   movw(cnt, len);
4999 
5000 #define ASCII(insn) do { if (ascii) { insn; } } while (0)
5001 
5002   Label LOOP_32, DONE_32, FAIL_32;
5003 
5004   BIND(LOOP_32);
5005   {
5006     cmpw(cnt, 32);
5007     br(LT, DONE_32);
5008     ld1(vtmp0, vtmp1, vtmp2, vtmp3, T8H, Address(post(src, 64)));
5009     // Extract lower bytes.
5010     FloatRegister vlo0 = v4;
5011     FloatRegister vlo1 = v5;
5012     uzp1(vlo0, T16B, vtmp0, vtmp1);
5013     uzp1(vlo1, T16B, vtmp2, vtmp3);
5014     // Merge bits...
5015     orr(vtmp0, T16B, vtmp0, vtmp1);
5016     orr(vtmp2, T16B, vtmp2, vtmp3);
5017     // Extract merged upper bytes.
5018     FloatRegister vhix = vtmp0;
5019     uzp2(vhix, T16B, vtmp0, vtmp2);
5020     // ISO-check on hi-parts (all zero).
5021     //                          ASCII-check on lo-parts (no sign).
5022     FloatRegister vlox = vtmp1; // Merge lower bytes.
5023                                 ASCII(orr(vlox, T16B, vlo0, vlo1));
5024     umov(chk, vhix, D, 1);      ASCII(cmlt(vlox, T16B, vlox));
5025     fmovd(max, vhix);           ASCII(umaxv(vlox, T16B, vlox));
5026     orr(chk, chk, max);         ASCII(umov(max, vlox, B, 0));
5027                                 ASCII(orr(chk, chk, max));
5028     cbnz(chk, FAIL_32);
5029     subw(cnt, cnt, 32);
5030     st1(vlo0, vlo1, T16B, Address(post(dst, 32)));
5031     b(LOOP_32);
5032   }
5033   BIND(FAIL_32);
5034   sub(src, src, 64);
5035   BIND(DONE_32);
5036 
5037   Label LOOP_8, SKIP_8;
5038 
5039   BIND(LOOP_8);
5040   {
5041     cmpw(cnt, 8);
5042     br(LT, SKIP_8);
5043     FloatRegister vhi = vtmp0;
5044     FloatRegister vlo = vtmp1;
5045     ld1(vtmp3, T8H, src);
5046     uzp1(vlo, T16B, vtmp3, vtmp3);
5047     uzp2(vhi, T16B, vtmp3, vtmp3);
5048     // ISO-check on hi-parts (all zero).
5049     //                          ASCII-check on lo-parts (no sign).
5050                                 ASCII(cmlt(vtmp2, T16B, vlo));
5051     fmovd(chk, vhi);            ASCII(umaxv(vtmp2, T16B, vtmp2));
5052                                 ASCII(umov(max, vtmp2, B, 0));
5053                                 ASCII(orr(chk, chk, max));
5054     cbnz(chk, SKIP_8);
5055 
5056     strd(vlo, Address(post(dst, 8)));
5057     subw(cnt, cnt, 8);
5058     add(src, src, 16);
5059     b(LOOP_8);
5060   }
5061   BIND(SKIP_8);
5062 
5063 #undef ASCII
5064 
5065   Label LOOP, DONE;
5066 
5067   cbz(cnt, DONE);
5068   BIND(LOOP);
5069   {
5070     Register chr = rscratch1;
5071     ldrh(chr, Address(post(src, 2)));
5072     tst(chr, ascii ? 0xff80 : 0xff00);
5073     br(NE, DONE);
5074     strb(chr, Address(post(dst, 1)));
5075     subs(cnt, cnt, 1);
5076     br(GT, LOOP);
5077   }
5078   BIND(DONE);
5079   // Return index where we stopped.
5080   subw(res, len, cnt);
5081 }
5082 
5083 // Inflate byte[] array to char[].
5084 address MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
5085                                            FloatRegister vtmp1, FloatRegister vtmp2,
5086                                            FloatRegister vtmp3, Register tmp4) {
5087   Label big, done, after_init, to_stub;
5088 
5089   assert_different_registers(src, dst, len, tmp4, rscratch1);
5090 
5091   fmovd(vtmp1, 0.0);
5092   lsrw(tmp4, len, 3);
5093   bind(after_init);
5094   cbnzw(tmp4, big);
5095   // Short string: less than 8 bytes.
5096   {
5097     Label loop, tiny;
5098 
5099     cmpw(len, 4);
5100     br(LT, tiny);
5101     // Use SIMD to do 4 bytes.
5102     ldrs(vtmp2, post(src, 4));
5103     zip1(vtmp3, T8B, vtmp2, vtmp1);
5104     subw(len, len, 4);
5105     strd(vtmp3, post(dst, 8));
5106 
5107     cbzw(len, done);
5108 
5109     // Do the remaining bytes by steam.
5110     bind(loop);
5111     ldrb(tmp4, post(src, 1));
5112     strh(tmp4, post(dst, 2));
5113     subw(len, len, 1);
5114 
5115     bind(tiny);
5116     cbnz(len, loop);
5117 
5118     b(done);
5119   }
5120 
5121   if (SoftwarePrefetchHintDistance >= 0) {
5122     bind(to_stub);
5123       RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_byte_array_inflate());
5124       assert(stub.target() != NULL, "large_byte_array_inflate stub has not been generated");
5125       address tpc = trampoline_call(stub);
5126       if (tpc == NULL) {
5127         DEBUG_ONLY(reset_labels(big, done));
5128         postcond(pc() == badAddress);
5129         return NULL;
5130       }
5131       b(after_init);
5132   }
5133 
5134   // Unpack the bytes 8 at a time.
5135   bind(big);
5136   {
5137     Label loop, around, loop_last, loop_start;
5138 
5139     if (SoftwarePrefetchHintDistance >= 0) {
5140       const int large_loop_threshold = (64 + 16)/8;
5141       ldrd(vtmp2, post(src, 8));
5142       andw(len, len, 7);
5143       cmp(tmp4, (u1)large_loop_threshold);
5144       br(GE, to_stub);
5145       b(loop_start);
5146 
5147       bind(loop);
5148       ldrd(vtmp2, post(src, 8));
5149       bind(loop_start);
5150       subs(tmp4, tmp4, 1);
5151       br(EQ, loop_last);
5152       zip1(vtmp2, T16B, vtmp2, vtmp1);
5153       ldrd(vtmp3, post(src, 8));
5154       st1(vtmp2, T8H, post(dst, 16));
5155       subs(tmp4, tmp4, 1);
5156       zip1(vtmp3, T16B, vtmp3, vtmp1);
5157       st1(vtmp3, T8H, post(dst, 16));
5158       br(NE, loop);
5159       b(around);
5160       bind(loop_last);
5161       zip1(vtmp2, T16B, vtmp2, vtmp1);
5162       st1(vtmp2, T8H, post(dst, 16));
5163       bind(around);
5164       cbz(len, done);
5165     } else {
5166       andw(len, len, 7);
5167       bind(loop);
5168       ldrd(vtmp2, post(src, 8));
5169       sub(tmp4, tmp4, 1);
5170       zip1(vtmp3, T16B, vtmp2, vtmp1);
5171       st1(vtmp3, T8H, post(dst, 16));
5172       cbnz(tmp4, loop);
5173     }
5174   }
5175 
5176   // Do the tail of up to 8 bytes.
5177   add(src, src, len);
5178   ldrd(vtmp3, Address(src, -8));
5179   add(dst, dst, len, ext::uxtw, 1);
5180   zip1(vtmp3, T16B, vtmp3, vtmp1);
5181   strq(vtmp3, Address(dst, -16));
5182 
5183   bind(done);
5184   postcond(pc() != badAddress);
5185   return pc();
5186 }
5187 
5188 // Compress char[] array to byte[].
5189 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
5190                                          Register res,
5191                                          FloatRegister tmp0, FloatRegister tmp1,
5192                                          FloatRegister tmp2, FloatRegister tmp3) {
5193   encode_iso_array(src, dst, len, res, false, tmp0, tmp1, tmp2, tmp3);
5194   // Adjust result: res == len ? len : 0
5195   cmp(len, res);
5196   csel(res, res, zr, EQ);
5197 }
5198 
5199 // java.math.round(double a)
5200 // Returns the closest long to the argument, with ties rounding to
5201 // positive infinity.  This requires some fiddling for corner
5202 // cases. We take care to avoid double rounding in e.g. (jlong)(a + 0.5).
5203 void MacroAssembler::java_round_double(Register dst, FloatRegister src,
5204                                        FloatRegister ftmp) {
5205   Label DONE;
5206   BLOCK_COMMENT("java_round_double: { ");
5207   fmovd(rscratch1, src);
5208   // Use RoundToNearestTiesAway unless src small and -ve.
5209   fcvtasd(dst, src);
5210   // Test if src >= 0 || abs(src) >= 0x1.0p52
5211   eor(rscratch1, rscratch1, UCONST64(1) << 63); // flip sign bit
5212   mov(rscratch2, julong_cast(0x1.0p52));
5213   cmp(rscratch1, rscratch2);
5214   br(HS, DONE); {
5215     // src < 0 && abs(src) < 0x1.0p52
5216     // src may have a fractional part, so add 0.5
5217     fmovd(ftmp, 0.5);
5218     faddd(ftmp, src, ftmp);
5219     // Convert double to jlong, use RoundTowardsNegative
5220     fcvtmsd(dst, ftmp);
5221   }
5222   bind(DONE);
5223   BLOCK_COMMENT("} java_round_double");
5224 }
5225 
5226 void MacroAssembler::java_round_float(Register dst, FloatRegister src,
5227                                       FloatRegister ftmp) {
5228   Label DONE;
5229   BLOCK_COMMENT("java_round_float: { ");
5230   fmovs(rscratch1, src);
5231   // Use RoundToNearestTiesAway unless src small and -ve.
5232   fcvtassw(dst, src);
5233   // Test if src >= 0 || abs(src) >= 0x1.0p23
5234   eor(rscratch1, rscratch1, 0x80000000); // flip sign bit
5235   mov(rscratch2, jint_cast(0x1.0p23f));
5236   cmp(rscratch1, rscratch2);
5237   br(HS, DONE); {
5238     // src < 0 && |src| < 0x1.0p23
5239     // src may have a fractional part, so add 0.5
5240     fmovs(ftmp, 0.5f);
5241     fadds(ftmp, src, ftmp);
5242     // Convert float to jint, use RoundTowardsNegative
5243     fcvtmssw(dst, ftmp);
5244   }
5245   bind(DONE);
5246   BLOCK_COMMENT("} java_round_float");
5247 }
5248 
5249 // get_thread() can be called anywhere inside generated code so we
5250 // need to save whatever non-callee save context might get clobbered
5251 // by the call to JavaThread::aarch64_get_thread_helper() or, indeed,
5252 // the call setup code.
5253 //
5254 // On Linux, aarch64_get_thread_helper() clobbers only r0, r1, and flags.
5255 // On other systems, the helper is a usual C function.
5256 //
5257 void MacroAssembler::get_thread(Register dst) {
5258   RegSet saved_regs =
5259     LINUX_ONLY(RegSet::range(r0, r1)  + lr - dst)
5260     NOT_LINUX (RegSet::range(r0, r17) + lr - dst);
5261 
5262   protect_return_address();
5263   push(saved_regs, sp);
5264 
5265   mov(lr, CAST_FROM_FN_PTR(address, JavaThread::aarch64_get_thread_helper));
5266   blr(lr);
5267   if (dst != c_rarg0) {
5268     mov(dst, c_rarg0);
5269   }
5270 
5271   pop(saved_regs, sp);
5272   authenticate_return_address();
5273 }
5274 
5275 void MacroAssembler::cache_wb(Address line) {
5276   assert(line.getMode() == Address::base_plus_offset, "mode should be base_plus_offset");
5277   assert(line.index() == noreg, "index should be noreg");
5278   assert(line.offset() == 0, "offset should be 0");
5279   // would like to assert this
5280   // assert(line._ext.shift == 0, "shift should be zero");
5281   if (VM_Version::supports_dcpop()) {
5282     // writeback using clear virtual address to point of persistence
5283     dc(Assembler::CVAP, line.base());
5284   } else {
5285     // no need to generate anything as Unsafe.writebackMemory should
5286     // never invoke this stub
5287   }
5288 }
5289 
5290 void MacroAssembler::cache_wbsync(bool is_pre) {
5291   // we only need a barrier post sync
5292   if (!is_pre) {
5293     membar(Assembler::AnyAny);
5294   }
5295 }
5296 
5297 void MacroAssembler::verify_sve_vector_length() {
5298   // Make sure that native code does not change SVE vector length.
5299   if (!UseSVE) return;
5300   Label verify_ok;
5301   movw(rscratch1, zr);
5302   sve_inc(rscratch1, B);
5303   subsw(zr, rscratch1, VM_Version::get_initial_sve_vector_length());
5304   br(EQ, verify_ok);
5305   stop("Error: SVE vector length has changed since jvm startup");
5306   bind(verify_ok);
5307 }
5308 
5309 void MacroAssembler::verify_ptrue() {
5310   Label verify_ok;
5311   if (!UseSVE) {
5312     return;
5313   }
5314   sve_cntp(rscratch1, B, ptrue, ptrue); // get true elements count.
5315   sve_dec(rscratch1, B);
5316   cbz(rscratch1, verify_ok);
5317   stop("Error: the preserved predicate register (p7) elements are not all true");
5318   bind(verify_ok);
5319 }
5320 
5321 void MacroAssembler::safepoint_isb() {
5322   isb();
5323 #ifndef PRODUCT
5324   if (VerifyCrossModifyFence) {
5325     // Clear the thread state.
5326     strb(zr, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
5327   }
5328 #endif
5329 }
5330 
5331 #ifndef PRODUCT
5332 void MacroAssembler::verify_cross_modify_fence_not_required() {
5333   if (VerifyCrossModifyFence) {
5334     // Check if thread needs a cross modify fence.
5335     ldrb(rscratch1, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
5336     Label fence_not_required;
5337     cbz(rscratch1, fence_not_required);
5338     // If it does then fail.
5339     lea(rscratch1, CAST_FROM_FN_PTR(address, JavaThread::verify_cross_modify_fence_failure));
5340     mov(c_rarg0, rthread);
5341     blr(rscratch1);
5342     bind(fence_not_required);
5343   }
5344 }
5345 #endif
5346 
5347 void MacroAssembler::spin_wait() {
5348   for (int i = 0; i < VM_Version::spin_wait_desc().inst_count(); ++i) {
5349     switch (VM_Version::spin_wait_desc().inst()) {
5350       case SpinWait::NOP:
5351         nop();
5352         break;
5353       case SpinWait::ISB:
5354         isb();
5355         break;
5356       case SpinWait::YIELD:
5357         yield();
5358         break;
5359       default:
5360         ShouldNotReachHere();
5361     }
5362   }
5363 }
5364 
5365 // Stack frame creation/removal
5366 
5367 void MacroAssembler::enter(bool strip_ret_addr) {
5368   if (strip_ret_addr) {
5369     // Addresses can only be signed once. If there are multiple nested frames being created
5370     // in the same function, then the return address needs stripping first.
5371     strip_return_address();
5372   }
5373   protect_return_address();
5374   stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
5375   mov(rfp, sp);
5376 }
5377 
5378 void MacroAssembler::leave() {
5379   mov(sp, rfp);
5380   ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
5381   authenticate_return_address();
5382 }
5383 
5384 // ROP Protection
5385 // Use the AArch64 PAC feature to add ROP protection for generated code. Use whenever creating/
5386 // destroying stack frames or whenever directly loading/storing the LR to memory.
5387 // If ROP protection is not set then these functions are no-ops.
5388 // For more details on PAC see pauth_aarch64.hpp.
5389 
5390 // Sign the LR. Use during construction of a stack frame, before storing the LR to memory.
5391 // Uses the FP as the modifier.
5392 //
5393 void MacroAssembler::protect_return_address() {
5394   if (VM_Version::use_rop_protection()) {
5395     check_return_address();
5396     // The standard convention for C code is to use paciasp, which uses SP as the modifier. This
5397     // works because in C code, FP and SP match on function entry. In the JDK, SP and FP may not
5398     // match, so instead explicitly use the FP.
5399     pacia(lr, rfp);
5400   }
5401 }
5402 
5403 // Sign the return value in the given register. Use before updating the LR in the existing stack
5404 // frame for the current function.
5405 // Uses the FP from the start of the function as the modifier - which is stored at the address of
5406 // the current FP.
5407 //
5408 void MacroAssembler::protect_return_address(Register return_reg, Register temp_reg) {
5409   if (VM_Version::use_rop_protection()) {
5410     assert(PreserveFramePointer, "PreserveFramePointer must be set for ROP protection");
5411     check_return_address(return_reg);
5412     ldr(temp_reg, Address(rfp));
5413     pacia(return_reg, temp_reg);
5414   }
5415 }
5416 
5417 // Authenticate the LR. Use before function return, after restoring FP and loading LR from memory.
5418 //
5419 void MacroAssembler::authenticate_return_address(Register return_reg) {
5420   if (VM_Version::use_rop_protection()) {
5421     autia(return_reg, rfp);
5422     check_return_address(return_reg);
5423   }
5424 }
5425 
5426 // Authenticate the return value in the given register. Use before updating the LR in the existing
5427 // stack frame for the current function.
5428 // Uses the FP from the start of the function as the modifier - which is stored at the address of
5429 // the current FP.
5430 //
5431 void MacroAssembler::authenticate_return_address(Register return_reg, Register temp_reg) {
5432   if (VM_Version::use_rop_protection()) {
5433     assert(PreserveFramePointer, "PreserveFramePointer must be set for ROP protection");
5434     ldr(temp_reg, Address(rfp));
5435     autia(return_reg, temp_reg);
5436     check_return_address(return_reg);
5437   }
5438 }
5439 
5440 // Strip any PAC data from LR without performing any authentication. Use with caution - only if
5441 // there is no guaranteed way of authenticating the LR.
5442 //
5443 void MacroAssembler::strip_return_address() {
5444   if (VM_Version::use_rop_protection()) {
5445     xpaclri();
5446   }
5447 }
5448 
5449 #ifndef PRODUCT
5450 // PAC failures can be difficult to debug. After an authentication failure, a segfault will only
5451 // occur when the pointer is used - ie when the program returns to the invalid LR. At this point
5452 // it is difficult to debug back to the callee function.
5453 // This function simply loads from the address in the given register.
5454 // Use directly after authentication to catch authentication failures.
5455 // Also use before signing to check that the pointer is valid and hasn't already been signed.
5456 //
5457 void MacroAssembler::check_return_address(Register return_reg) {
5458   if (VM_Version::use_rop_protection()) {
5459     ldr(zr, Address(return_reg));
5460   }
5461 }
5462 #endif