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