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