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