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