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 // Push lots of registers in the bit set supplied.  Don't push sp.
1859 // Return the number of words pushed
1860 int MacroAssembler::push(unsigned int bitset, Register stack) {
1861   int words_pushed = 0;
1862 
1863   // Scan bitset to accumulate register pairs
1864   unsigned char regs[32];
1865   int count = 0;
1866   for (int reg = 0; reg <= 30; reg++) {
1867     if (1 & bitset)
1868       regs[count++] = reg;
1869     bitset >>= 1;
1870   }
1871   regs[count++] = zr->encoding_nocheck();
1872   count &= ~1;  // Only push an even nuber of regs
1873 
1874   if (count) {
1875     stp(as_Register(regs[0]), as_Register(regs[1]),
1876        Address(pre(stack, -count * wordSize)));
1877     words_pushed += 2;
1878   }
1879   for (int i = 2; i < count; i += 2) {
1880     stp(as_Register(regs[i]), as_Register(regs[i+1]),
1881        Address(stack, i * wordSize));
1882     words_pushed += 2;
1883   }
1884 
1885   assert(words_pushed == count, "oops, pushed != count");
1886 
1887   return count;
1888 }
1889 
1890 int MacroAssembler::pop(unsigned int bitset, Register stack) {
1891   int words_pushed = 0;
1892 
1893   // Scan bitset to accumulate register pairs
1894   unsigned char regs[32];
1895   int count = 0;
1896   for (int reg = 0; reg <= 30; reg++) {
1897     if (1 & bitset)
1898       regs[count++] = reg;
1899     bitset >>= 1;
1900   }
1901   regs[count++] = zr->encoding_nocheck();
1902   count &= ~1;
1903 
1904   for (int i = 2; i < count; i += 2) {
1905     ldp(as_Register(regs[i]), as_Register(regs[i+1]),
1906        Address(stack, i * wordSize));
1907     words_pushed += 2;
1908   }
1909   if (count) {
1910     ldp(as_Register(regs[0]), as_Register(regs[1]),
1911        Address(post(stack, count * wordSize)));
1912     words_pushed += 2;
1913   }
1914 
1915   assert(words_pushed == count, "oops, pushed != count");
1916 
1917   return count;
1918 }
1919 
1920 // Push lots of registers in the bit set supplied.  Don't push sp.
1921 // Return the number of dwords pushed
1922 int MacroAssembler::push_fp(unsigned int bitset, Register stack) {
1923   int words_pushed = 0;
1924   bool use_sve = false;
1925   int sve_vector_size_in_bytes = 0;
1926 
1927 #ifdef COMPILER2
1928   use_sve = Matcher::supports_scalable_vector();
1929   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
1930 #endif
1931 
1932   // Scan bitset to accumulate register pairs
1933   unsigned char regs[32];
1934   int count = 0;
1935   for (int reg = 0; reg <= 31; reg++) {
1936     if (1 & bitset)
1937       regs[count++] = reg;
1938     bitset >>= 1;
1939   }
1940 
1941   if (count == 0) {
1942     return 0;
1943   }
1944 
1945   // SVE
1946   if (use_sve && sve_vector_size_in_bytes > 16) {
1947     sub(stack, stack, sve_vector_size_in_bytes * count);
1948     for (int i = 0; i < count; i++) {
1949       sve_str(as_FloatRegister(regs[i]), Address(stack, i));
1950     }
1951     return count * sve_vector_size_in_bytes / 8;
1952   }
1953 
1954   // NEON
1955   if (count == 1) {
1956     strq(as_FloatRegister(regs[0]), Address(pre(stack, -wordSize * 2)));
1957     return 2;
1958   }
1959 
1960   bool odd = (count & 1) == 1;
1961   int push_slots = count + (odd ? 1 : 0);
1962 
1963   // Always pushing full 128 bit registers.
1964   stpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(pre(stack, -push_slots * wordSize * 2)));
1965   words_pushed += 2;
1966 
1967   for (int i = 2; i + 1 < count; i += 2) {
1968     stpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
1969     words_pushed += 2;
1970   }
1971 
1972   if (odd) {
1973     strq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
1974     words_pushed++;
1975   }
1976 
1977   assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
1978   return count * 2;
1979 }
1980 
1981 // Return the number of dwords popped
1982 int MacroAssembler::pop_fp(unsigned int bitset, Register stack) {
1983   int words_pushed = 0;
1984   bool use_sve = false;
1985   int sve_vector_size_in_bytes = 0;
1986 
1987 #ifdef COMPILER2
1988   use_sve = Matcher::supports_scalable_vector();
1989   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
1990 #endif
1991   // Scan bitset to accumulate register pairs
1992   unsigned char regs[32];
1993   int count = 0;
1994   for (int reg = 0; reg <= 31; reg++) {
1995     if (1 & bitset)
1996       regs[count++] = reg;
1997     bitset >>= 1;
1998   }
1999 
2000   if (count == 0) {
2001     return 0;
2002   }
2003 
2004   // SVE
2005   if (use_sve && sve_vector_size_in_bytes > 16) {
2006     for (int i = count - 1; i >= 0; i--) {
2007       sve_ldr(as_FloatRegister(regs[i]), Address(stack, i));
2008     }
2009     add(stack, stack, sve_vector_size_in_bytes * count);
2010     return count * sve_vector_size_in_bytes / 8;
2011   }
2012 
2013   // NEON
2014   if (count == 1) {
2015     ldrq(as_FloatRegister(regs[0]), Address(post(stack, wordSize * 2)));
2016     return 2;
2017   }
2018 
2019   bool odd = (count & 1) == 1;
2020   int push_slots = count + (odd ? 1 : 0);
2021 
2022   if (odd) {
2023     ldrq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
2024     words_pushed++;
2025   }
2026 
2027   for (int i = 2; i + 1 < count; i += 2) {
2028     ldpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
2029     words_pushed += 2;
2030   }
2031 
2032   ldpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(post(stack, push_slots * wordSize * 2)));
2033   words_pushed += 2;
2034 
2035   assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
2036 
2037   return count * 2;
2038 }
2039 
2040 // Return the number of dwords pushed
2041 int MacroAssembler::push_p(unsigned int bitset, Register stack) {
2042   bool use_sve = false;
2043   int sve_predicate_size_in_slots = 0;
2044 
2045 #ifdef COMPILER2
2046   use_sve = Matcher::supports_scalable_vector();
2047   if (use_sve) {
2048     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
2049   }
2050 #endif
2051 
2052   if (!use_sve) {
2053     return 0;
2054   }
2055 
2056   unsigned char regs[PRegisterImpl::number_of_saved_registers];
2057   int count = 0;
2058   for (int reg = 0; reg < PRegisterImpl::number_of_saved_registers; reg++) {
2059     if (1 & bitset)
2060       regs[count++] = reg;
2061     bitset >>= 1;
2062   }
2063 
2064   if (count == 0) {
2065     return 0;
2066   }
2067 
2068   int total_push_bytes = align_up(sve_predicate_size_in_slots *
2069                                   VMRegImpl::stack_slot_size * count, 16);
2070   sub(stack, stack, total_push_bytes);
2071   for (int i = 0; i < count; i++) {
2072     sve_str(as_PRegister(regs[i]), Address(stack, i));
2073   }
2074   return total_push_bytes / 8;
2075 }
2076 
2077 // Return the number of dwords popped
2078 int MacroAssembler::pop_p(unsigned int bitset, Register stack) {
2079   bool use_sve = false;
2080   int sve_predicate_size_in_slots = 0;
2081 
2082 #ifdef COMPILER2
2083   use_sve = Matcher::supports_scalable_vector();
2084   if (use_sve) {
2085     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
2086   }
2087 #endif
2088 
2089   if (!use_sve) {
2090     return 0;
2091   }
2092 
2093   unsigned char regs[PRegisterImpl::number_of_saved_registers];
2094   int count = 0;
2095   for (int reg = 0; reg < PRegisterImpl::number_of_saved_registers; reg++) {
2096     if (1 & bitset)
2097       regs[count++] = reg;
2098     bitset >>= 1;
2099   }
2100 
2101   if (count == 0) {
2102     return 0;
2103   }
2104 
2105   int total_pop_bytes = align_up(sve_predicate_size_in_slots *
2106                                  VMRegImpl::stack_slot_size * count, 16);
2107   for (int i = count - 1; i >= 0; i--) {
2108     sve_ldr(as_PRegister(regs[i]), Address(stack, i));
2109   }
2110   add(stack, stack, total_pop_bytes);
2111   return total_pop_bytes / 8;
2112 }
2113 
2114 #ifdef ASSERT
2115 void MacroAssembler::verify_heapbase(const char* msg) {
2116 #if 0
2117   assert (UseCompressedOops || UseCompressedClassPointers, "should be compressed");
2118   assert (Universe::heap() != NULL, "java heap should be initialized");
2119   if (!UseCompressedOops || Universe::ptr_base() == NULL) {
2120     // rheapbase is allocated as general register
2121     return;
2122   }
2123   if (CheckCompressedOops) {
2124     Label ok;
2125     push(1 << rscratch1->encoding(), sp); // cmpptr trashes rscratch1
2126     cmpptr(rheapbase, ExternalAddress((address)CompressedOops::ptrs_base_addr()));
2127     br(Assembler::EQ, ok);
2128     stop(msg);
2129     bind(ok);
2130     pop(1 << rscratch1->encoding(), sp);
2131   }
2132 #endif
2133 }
2134 #endif
2135 
2136 void MacroAssembler::resolve_jobject(Register value, Register thread, Register tmp) {
2137   Label done, not_weak;
2138   cbz(value, done);           // Use NULL as-is.
2139 
2140   STATIC_ASSERT(JNIHandles::weak_tag_mask == 1u);
2141   tbz(r0, 0, not_weak);    // Test for jweak tag.
2142 
2143   // Resolve jweak.
2144   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF, value,
2145                  Address(value, -JNIHandles::weak_tag_value), tmp, thread);
2146   verify_oop(value);
2147   b(done);
2148 
2149   bind(not_weak);
2150   // Resolve (untagged) jobject.
2151   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, 0), tmp, thread);
2152   verify_oop(value);
2153   bind(done);
2154 }
2155 
2156 void MacroAssembler::stop(const char* msg) {
2157   BLOCK_COMMENT(msg);
2158   dcps1(0xdeae);
2159   emit_int64((uintptr_t)msg);
2160 }
2161 
2162 void MacroAssembler::unimplemented(const char* what) {
2163   const char* buf = NULL;
2164   {
2165     ResourceMark rm;
2166     stringStream ss;
2167     ss.print("unimplemented: %s", what);
2168     buf = code_string(ss.as_string());
2169   }
2170   stop(buf);
2171 }
2172 
2173 // If a constant does not fit in an immediate field, generate some
2174 // number of MOV instructions and then perform the operation.
2175 void MacroAssembler::wrap_add_sub_imm_insn(Register Rd, Register Rn, unsigned imm,
2176                                            add_sub_imm_insn insn1,
2177                                            add_sub_reg_insn insn2) {
2178   assert(Rd != zr, "Rd = zr and not setting flags?");
2179   if (operand_valid_for_add_sub_immediate((int)imm)) {
2180     (this->*insn1)(Rd, Rn, imm);
2181   } else {
2182     if (uabs(imm) < (1 << 24)) {
2183        (this->*insn1)(Rd, Rn, imm & -(1 << 12));
2184        (this->*insn1)(Rd, Rd, imm & ((1 << 12)-1));
2185     } else {
2186        assert_different_registers(Rd, Rn);
2187        mov(Rd, (uint64_t)imm);
2188        (this->*insn2)(Rd, Rn, Rd, LSL, 0);
2189     }
2190   }
2191 }
2192 
2193 // Seperate vsn which sets the flags. Optimisations are more restricted
2194 // because we must set the flags correctly.
2195 void MacroAssembler::wrap_adds_subs_imm_insn(Register Rd, Register Rn, unsigned imm,
2196                                            add_sub_imm_insn insn1,
2197                                            add_sub_reg_insn insn2) {
2198   if (operand_valid_for_add_sub_immediate((int)imm)) {
2199     (this->*insn1)(Rd, Rn, imm);
2200   } else {
2201     assert_different_registers(Rd, Rn);
2202     assert(Rd != zr, "overflow in immediate operand");
2203     mov(Rd, (uint64_t)imm);
2204     (this->*insn2)(Rd, Rn, Rd, LSL, 0);
2205   }
2206 }
2207 
2208 
2209 void MacroAssembler::add(Register Rd, Register Rn, RegisterOrConstant increment) {
2210   if (increment.is_register()) {
2211     add(Rd, Rn, increment.as_register());
2212   } else {
2213     add(Rd, Rn, increment.as_constant());
2214   }
2215 }
2216 
2217 void MacroAssembler::addw(Register Rd, Register Rn, RegisterOrConstant increment) {
2218   if (increment.is_register()) {
2219     addw(Rd, Rn, increment.as_register());
2220   } else {
2221     addw(Rd, Rn, increment.as_constant());
2222   }
2223 }
2224 
2225 void MacroAssembler::sub(Register Rd, Register Rn, RegisterOrConstant decrement) {
2226   if (decrement.is_register()) {
2227     sub(Rd, Rn, decrement.as_register());
2228   } else {
2229     sub(Rd, Rn, decrement.as_constant());
2230   }
2231 }
2232 
2233 void MacroAssembler::subw(Register Rd, Register Rn, RegisterOrConstant decrement) {
2234   if (decrement.is_register()) {
2235     subw(Rd, Rn, decrement.as_register());
2236   } else {
2237     subw(Rd, Rn, decrement.as_constant());
2238   }
2239 }
2240 
2241 void MacroAssembler::reinit_heapbase()
2242 {
2243   if (UseCompressedOops) {
2244     if (Universe::is_fully_initialized()) {
2245       mov(rheapbase, CompressedOops::ptrs_base());
2246     } else {
2247       lea(rheapbase, ExternalAddress((address)CompressedOops::ptrs_base_addr()));
2248       ldr(rheapbase, Address(rheapbase));
2249     }
2250   }
2251 }
2252 
2253 // this simulates the behaviour of the x86 cmpxchg instruction using a
2254 // load linked/store conditional pair. we use the acquire/release
2255 // versions of these instructions so that we flush pending writes as
2256 // per Java semantics.
2257 
2258 // n.b the x86 version assumes the old value to be compared against is
2259 // in rax and updates rax with the value located in memory if the
2260 // cmpxchg fails. we supply a register for the old value explicitly
2261 
2262 // the aarch64 load linked/store conditional instructions do not
2263 // accept an offset. so, unlike x86, we must provide a plain register
2264 // to identify the memory word to be compared/exchanged rather than a
2265 // register+offset Address.
2266 
2267 void MacroAssembler::cmpxchgptr(Register oldv, Register newv, Register addr, Register tmp,
2268                                 Label &succeed, Label *fail) {
2269   // oldv holds comparison value
2270   // newv holds value to write in exchange
2271   // addr identifies memory word to compare against/update
2272   if (UseLSE) {
2273     mov(tmp, oldv);
2274     casal(Assembler::xword, oldv, newv, addr);
2275     cmp(tmp, oldv);
2276     br(Assembler::EQ, succeed);
2277     membar(AnyAny);
2278   } else {
2279     Label retry_load, nope;
2280     if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))
2281       prfm(Address(addr), PSTL1STRM);
2282     bind(retry_load);
2283     // flush and load exclusive from the memory location
2284     // and fail if it is not what we expect
2285     ldaxr(tmp, addr);
2286     cmp(tmp, oldv);
2287     br(Assembler::NE, nope);
2288     // if we store+flush with no intervening write tmp wil be zero
2289     stlxr(tmp, newv, addr);
2290     cbzw(tmp, succeed);
2291     // retry so we only ever return after a load fails to compare
2292     // ensures we don't return a stale value after a failed write.
2293     b(retry_load);
2294     // if the memory word differs we return it in oldv and signal a fail
2295     bind(nope);
2296     membar(AnyAny);
2297     mov(oldv, tmp);
2298   }
2299   if (fail)
2300     b(*fail);
2301 }
2302 
2303 void MacroAssembler::cmpxchg_obj_header(Register oldv, Register newv, Register obj, Register tmp,
2304                                         Label &succeed, Label *fail) {
2305   assert(oopDesc::mark_offset_in_bytes() == 0, "assumption");
2306   cmpxchgptr(oldv, newv, obj, tmp, succeed, fail);
2307 }
2308 
2309 void MacroAssembler::cmpxchgw(Register oldv, Register newv, Register addr, Register tmp,
2310                                 Label &succeed, Label *fail) {
2311   // oldv holds comparison value
2312   // newv holds value to write in exchange
2313   // addr identifies memory word to compare against/update
2314   // tmp returns 0/1 for success/failure
2315   if (UseLSE) {
2316     mov(tmp, oldv);
2317     casal(Assembler::word, oldv, newv, addr);
2318     cmp(tmp, oldv);
2319     br(Assembler::EQ, succeed);
2320     membar(AnyAny);
2321   } else {
2322     Label retry_load, nope;
2323     if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))
2324       prfm(Address(addr), PSTL1STRM);
2325     bind(retry_load);
2326     // flush and load exclusive from the memory location
2327     // and fail if it is not what we expect
2328     ldaxrw(tmp, addr);
2329     cmp(tmp, oldv);
2330     br(Assembler::NE, nope);
2331     // if we store+flush with no intervening write tmp wil be zero
2332     stlxrw(tmp, newv, addr);
2333     cbzw(tmp, succeed);
2334     // retry so we only ever return after a load fails to compare
2335     // ensures we don't return a stale value after a failed write.
2336     b(retry_load);
2337     // if the memory word differs we return it in oldv and signal a fail
2338     bind(nope);
2339     membar(AnyAny);
2340     mov(oldv, tmp);
2341   }
2342   if (fail)
2343     b(*fail);
2344 }
2345 
2346 // A generic CAS; success or failure is in the EQ flag.  A weak CAS
2347 // doesn't retry and may fail spuriously.  If the oldval is wanted,
2348 // Pass a register for the result, otherwise pass noreg.
2349 
2350 // Clobbers rscratch1
2351 void MacroAssembler::cmpxchg(Register addr, Register expected,
2352                              Register new_val,
2353                              enum operand_size size,
2354                              bool acquire, bool release,
2355                              bool weak,
2356                              Register result) {
2357   if (result == noreg)  result = rscratch1;
2358   BLOCK_COMMENT("cmpxchg {");
2359   if (UseLSE) {
2360     mov(result, expected);
2361     lse_cas(result, new_val, addr, size, acquire, release, /*not_pair*/ true);
2362     compare_eq(result, expected, size);
2363   } else {
2364     Label retry_load, done;
2365     if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))
2366       prfm(Address(addr), PSTL1STRM);
2367     bind(retry_load);
2368     load_exclusive(result, addr, size, acquire);
2369     compare_eq(result, expected, size);
2370     br(Assembler::NE, done);
2371     store_exclusive(rscratch1, new_val, addr, size, release);
2372     if (weak) {
2373       cmpw(rscratch1, 0u);  // If the store fails, return NE to our caller.
2374     } else {
2375       cbnzw(rscratch1, retry_load);
2376     }
2377     bind(done);
2378   }
2379   BLOCK_COMMENT("} cmpxchg");
2380 }
2381 
2382 // A generic comparison. Only compares for equality, clobbers rscratch1.
2383 void MacroAssembler::compare_eq(Register rm, Register rn, enum operand_size size) {
2384   if (size == xword) {
2385     cmp(rm, rn);
2386   } else if (size == word) {
2387     cmpw(rm, rn);
2388   } else if (size == halfword) {
2389     eorw(rscratch1, rm, rn);
2390     ands(zr, rscratch1, 0xffff);
2391   } else if (size == byte) {
2392     eorw(rscratch1, rm, rn);
2393     ands(zr, rscratch1, 0xff);
2394   } else {
2395     ShouldNotReachHere();
2396   }
2397 }
2398 
2399 
2400 static bool different(Register a, RegisterOrConstant b, Register c) {
2401   if (b.is_constant())
2402     return a != c;
2403   else
2404     return a != b.as_register() && a != c && b.as_register() != c;
2405 }
2406 
2407 #define ATOMIC_OP(NAME, LDXR, OP, IOP, AOP, STXR, sz)                   \
2408 void MacroAssembler::atomic_##NAME(Register prev, RegisterOrConstant incr, Register addr) { \
2409   if (UseLSE) {                                                         \
2410     prev = prev->is_valid() ? prev : zr;                                \
2411     if (incr.is_register()) {                                           \
2412       AOP(sz, incr.as_register(), prev, addr);                          \
2413     } else {                                                            \
2414       mov(rscratch2, incr.as_constant());                               \
2415       AOP(sz, rscratch2, prev, addr);                                   \
2416     }                                                                   \
2417     return;                                                             \
2418   }                                                                     \
2419   Register result = rscratch2;                                          \
2420   if (prev->is_valid())                                                 \
2421     result = different(prev, incr, addr) ? prev : rscratch2;            \
2422                                                                         \
2423   Label retry_load;                                                     \
2424   if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))         \
2425     prfm(Address(addr), PSTL1STRM);                                     \
2426   bind(retry_load);                                                     \
2427   LDXR(result, addr);                                                   \
2428   OP(rscratch1, result, incr);                                          \
2429   STXR(rscratch2, rscratch1, addr);                                     \
2430   cbnzw(rscratch2, retry_load);                                         \
2431   if (prev->is_valid() && prev != result) {                             \
2432     IOP(prev, rscratch1, incr);                                         \
2433   }                                                                     \
2434 }
2435 
2436 ATOMIC_OP(add, ldxr, add, sub, ldadd, stxr, Assembler::xword)
2437 ATOMIC_OP(addw, ldxrw, addw, subw, ldadd, stxrw, Assembler::word)
2438 ATOMIC_OP(addal, ldaxr, add, sub, ldaddal, stlxr, Assembler::xword)
2439 ATOMIC_OP(addalw, ldaxrw, addw, subw, ldaddal, stlxrw, Assembler::word)
2440 
2441 #undef ATOMIC_OP
2442 
2443 #define ATOMIC_XCHG(OP, AOP, LDXR, STXR, sz)                            \
2444 void MacroAssembler::atomic_##OP(Register prev, Register newv, Register addr) { \
2445   if (UseLSE) {                                                         \
2446     prev = prev->is_valid() ? prev : zr;                                \
2447     AOP(sz, newv, prev, addr);                                          \
2448     return;                                                             \
2449   }                                                                     \
2450   Register result = rscratch2;                                          \
2451   if (prev->is_valid())                                                 \
2452     result = different(prev, newv, addr) ? prev : rscratch2;            \
2453                                                                         \
2454   Label retry_load;                                                     \
2455   if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))         \
2456     prfm(Address(addr), PSTL1STRM);                                     \
2457   bind(retry_load);                                                     \
2458   LDXR(result, addr);                                                   \
2459   STXR(rscratch1, newv, addr);                                          \
2460   cbnzw(rscratch1, retry_load);                                         \
2461   if (prev->is_valid() && prev != result)                               \
2462     mov(prev, result);                                                  \
2463 }
2464 
2465 ATOMIC_XCHG(xchg, swp, ldxr, stxr, Assembler::xword)
2466 ATOMIC_XCHG(xchgw, swp, ldxrw, stxrw, Assembler::word)
2467 ATOMIC_XCHG(xchgl, swpl, ldxr, stlxr, Assembler::xword)
2468 ATOMIC_XCHG(xchglw, swpl, ldxrw, stlxrw, Assembler::word)
2469 ATOMIC_XCHG(xchgal, swpal, ldaxr, stlxr, Assembler::xword)
2470 ATOMIC_XCHG(xchgalw, swpal, ldaxrw, stlxrw, Assembler::word)
2471 
2472 #undef ATOMIC_XCHG
2473 
2474 #ifndef PRODUCT
2475 extern "C" void findpc(intptr_t x);
2476 #endif
2477 
2478 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[])
2479 {
2480   // In order to get locks to work, we need to fake a in_VM state
2481   if (ShowMessageBoxOnError ) {
2482     JavaThread* thread = JavaThread::current();
2483     JavaThreadState saved_state = thread->thread_state();
2484     thread->set_thread_state(_thread_in_vm);
2485 #ifndef PRODUCT
2486     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
2487       ttyLocker ttyl;
2488       BytecodeCounter::print();
2489     }
2490 #endif
2491     if (os::message_box(msg, "Execution stopped, print registers?")) {
2492       ttyLocker ttyl;
2493       tty->print_cr(" pc = 0x%016" PRIx64, pc);
2494 #ifndef PRODUCT
2495       tty->cr();
2496       findpc(pc);
2497       tty->cr();
2498 #endif
2499       tty->print_cr(" r0 = 0x%016" PRIx64, regs[0]);
2500       tty->print_cr(" r1 = 0x%016" PRIx64, regs[1]);
2501       tty->print_cr(" r2 = 0x%016" PRIx64, regs[2]);
2502       tty->print_cr(" r3 = 0x%016" PRIx64, regs[3]);
2503       tty->print_cr(" r4 = 0x%016" PRIx64, regs[4]);
2504       tty->print_cr(" r5 = 0x%016" PRIx64, regs[5]);
2505       tty->print_cr(" r6 = 0x%016" PRIx64, regs[6]);
2506       tty->print_cr(" r7 = 0x%016" PRIx64, regs[7]);
2507       tty->print_cr(" r8 = 0x%016" PRIx64, regs[8]);
2508       tty->print_cr(" r9 = 0x%016" PRIx64, regs[9]);
2509       tty->print_cr("r10 = 0x%016" PRIx64, regs[10]);
2510       tty->print_cr("r11 = 0x%016" PRIx64, regs[11]);
2511       tty->print_cr("r12 = 0x%016" PRIx64, regs[12]);
2512       tty->print_cr("r13 = 0x%016" PRIx64, regs[13]);
2513       tty->print_cr("r14 = 0x%016" PRIx64, regs[14]);
2514       tty->print_cr("r15 = 0x%016" PRIx64, regs[15]);
2515       tty->print_cr("r16 = 0x%016" PRIx64, regs[16]);
2516       tty->print_cr("r17 = 0x%016" PRIx64, regs[17]);
2517       tty->print_cr("r18 = 0x%016" PRIx64, regs[18]);
2518       tty->print_cr("r19 = 0x%016" PRIx64, regs[19]);
2519       tty->print_cr("r20 = 0x%016" PRIx64, regs[20]);
2520       tty->print_cr("r21 = 0x%016" PRIx64, regs[21]);
2521       tty->print_cr("r22 = 0x%016" PRIx64, regs[22]);
2522       tty->print_cr("r23 = 0x%016" PRIx64, regs[23]);
2523       tty->print_cr("r24 = 0x%016" PRIx64, regs[24]);
2524       tty->print_cr("r25 = 0x%016" PRIx64, regs[25]);
2525       tty->print_cr("r26 = 0x%016" PRIx64, regs[26]);
2526       tty->print_cr("r27 = 0x%016" PRIx64, regs[27]);
2527       tty->print_cr("r28 = 0x%016" PRIx64, regs[28]);
2528       tty->print_cr("r30 = 0x%016" PRIx64, regs[30]);
2529       tty->print_cr("r31 = 0x%016" PRIx64, regs[31]);
2530       BREAKPOINT;
2531     }
2532   }
2533   fatal("DEBUG MESSAGE: %s", msg);
2534 }
2535 
2536 RegSet MacroAssembler::call_clobbered_registers() {
2537   RegSet regs = RegSet::range(r0, r17) - RegSet::of(rscratch1, rscratch2);
2538 #ifndef R18_RESERVED
2539   regs += r18_tls;
2540 #endif
2541   return regs;
2542 }
2543 
2544 void MacroAssembler::push_call_clobbered_registers_except(RegSet exclude) {
2545   int step = 4 * wordSize;
2546   push(call_clobbered_registers() - exclude, sp);
2547   sub(sp, sp, step);
2548   mov(rscratch1, -step);
2549   // Push v0-v7, v16-v31.
2550   for (int i = 31; i>= 4; i -= 4) {
2551     if (i <= v7->encoding() || i >= v16->encoding())
2552       st1(as_FloatRegister(i-3), as_FloatRegister(i-2), as_FloatRegister(i-1),
2553           as_FloatRegister(i), T1D, Address(post(sp, rscratch1)));
2554   }
2555   st1(as_FloatRegister(0), as_FloatRegister(1), as_FloatRegister(2),
2556       as_FloatRegister(3), T1D, Address(sp));
2557 }
2558 
2559 void MacroAssembler::pop_call_clobbered_registers_except(RegSet exclude) {
2560   for (int i = 0; i < 32; i += 4) {
2561     if (i <= v7->encoding() || i >= v16->encoding())
2562       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
2563           as_FloatRegister(i+3), T1D, Address(post(sp, 4 * wordSize)));
2564   }
2565 
2566   reinitialize_ptrue();
2567 
2568   pop(call_clobbered_registers() - exclude, sp);
2569 }
2570 
2571 void MacroAssembler::push_CPU_state(bool save_vectors, bool use_sve,
2572                                     int sve_vector_size_in_bytes, int total_predicate_in_bytes) {
2573   push(RegSet::range(r0, r29), sp); // integer registers except lr & sp
2574   if (save_vectors && use_sve && sve_vector_size_in_bytes > 16) {
2575     sub(sp, sp, sve_vector_size_in_bytes * FloatRegisterImpl::number_of_registers);
2576     for (int i = 0; i < FloatRegisterImpl::number_of_registers; i++) {
2577       sve_str(as_FloatRegister(i), Address(sp, i));
2578     }
2579   } else {
2580     int step = (save_vectors ? 8 : 4) * wordSize;
2581     mov(rscratch1, -step);
2582     sub(sp, sp, step);
2583     for (int i = 28; i >= 4; i -= 4) {
2584       st1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
2585           as_FloatRegister(i+3), save_vectors ? T2D : T1D, Address(post(sp, rscratch1)));
2586     }
2587     st1(v0, v1, v2, v3, save_vectors ? T2D : T1D, sp);
2588   }
2589   if (save_vectors && use_sve && total_predicate_in_bytes > 0) {
2590     sub(sp, sp, total_predicate_in_bytes);
2591     for (int i = 0; i < PRegisterImpl::number_of_saved_registers; i++) {
2592       sve_str(as_PRegister(i), Address(sp, i));
2593     }
2594   }
2595 }
2596 
2597 void MacroAssembler::pop_CPU_state(bool restore_vectors, bool use_sve,
2598                                    int sve_vector_size_in_bytes, int total_predicate_in_bytes) {
2599   if (restore_vectors && use_sve && total_predicate_in_bytes > 0) {
2600     for (int i = PRegisterImpl::number_of_saved_registers - 1; i >= 0; i--) {
2601       sve_ldr(as_PRegister(i), Address(sp, i));
2602     }
2603     add(sp, sp, total_predicate_in_bytes);
2604   }
2605   if (restore_vectors && use_sve && sve_vector_size_in_bytes > 16) {
2606     for (int i = FloatRegisterImpl::number_of_registers - 1; i >= 0; i--) {
2607       sve_ldr(as_FloatRegister(i), Address(sp, i));
2608     }
2609     add(sp, sp, sve_vector_size_in_bytes * FloatRegisterImpl::number_of_registers);
2610   } else {
2611     int step = (restore_vectors ? 8 : 4) * wordSize;
2612     for (int i = 0; i <= 28; i += 4)
2613       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
2614           as_FloatRegister(i+3), restore_vectors ? T2D : T1D, Address(post(sp, step)));
2615   }
2616 
2617   // We may use predicate registers and rely on ptrue with SVE,
2618   // regardless of wide vector (> 8 bytes) used or not.
2619   if (use_sve) {
2620     reinitialize_ptrue();
2621   }
2622 
2623   // integer registers except lr & sp
2624   pop(RegSet::range(r0, r17), sp);
2625 #ifdef R18_RESERVED
2626   ldp(zr, r19, Address(post(sp, 2 * wordSize)));
2627   pop(RegSet::range(r20, r29), sp);
2628 #else
2629   pop(RegSet::range(r18_tls, r29), sp);
2630 #endif
2631 }
2632 
2633 /**
2634  * Helpers for multiply_to_len().
2635  */
2636 void MacroAssembler::add2_with_carry(Register final_dest_hi, Register dest_hi, Register dest_lo,
2637                                      Register src1, Register src2) {
2638   adds(dest_lo, dest_lo, src1);
2639   adc(dest_hi, dest_hi, zr);
2640   adds(dest_lo, dest_lo, src2);
2641   adc(final_dest_hi, dest_hi, zr);
2642 }
2643 
2644 // Generate an address from (r + r1 extend offset).  "size" is the
2645 // size of the operand.  The result may be in rscratch2.
2646 Address MacroAssembler::offsetted_address(Register r, Register r1,
2647                                           Address::extend ext, int offset, int size) {
2648   if (offset || (ext.shift() % size != 0)) {
2649     lea(rscratch2, Address(r, r1, ext));
2650     return Address(rscratch2, offset);
2651   } else {
2652     return Address(r, r1, ext);
2653   }
2654 }
2655 
2656 Address MacroAssembler::spill_address(int size, int offset, Register tmp)
2657 {
2658   assert(offset >= 0, "spill to negative address?");
2659   // Offset reachable ?
2660   //   Not aligned - 9 bits signed offset
2661   //   Aligned - 12 bits unsigned offset shifted
2662   Register base = sp;
2663   if ((offset & (size-1)) && offset >= (1<<8)) {
2664     add(tmp, base, offset & ((1<<12)-1));
2665     base = tmp;
2666     offset &= -1u<<12;
2667   }
2668 
2669   if (offset >= (1<<12) * size) {
2670     add(tmp, base, offset & (((1<<12)-1)<<12));
2671     base = tmp;
2672     offset &= ~(((1<<12)-1)<<12);
2673   }
2674 
2675   return Address(base, offset);
2676 }
2677 
2678 Address MacroAssembler::sve_spill_address(int sve_reg_size_in_bytes, int offset, Register tmp) {
2679   assert(offset >= 0, "spill to negative address?");
2680 
2681   Register base = sp;
2682 
2683   // An immediate offset in the range 0 to 255 which is multiplied
2684   // by the current vector or predicate register size in bytes.
2685   if (offset % sve_reg_size_in_bytes == 0 && offset < ((1<<8)*sve_reg_size_in_bytes)) {
2686     return Address(base, offset / sve_reg_size_in_bytes);
2687   }
2688 
2689   add(tmp, base, offset);
2690   return Address(tmp);
2691 }
2692 
2693 // Checks whether offset is aligned.
2694 // Returns true if it is, else false.
2695 bool MacroAssembler::merge_alignment_check(Register base,
2696                                            size_t size,
2697                                            int64_t cur_offset,
2698                                            int64_t prev_offset) const {
2699   if (AvoidUnalignedAccesses) {
2700     if (base == sp) {
2701       // Checks whether low offset if aligned to pair of registers.
2702       int64_t pair_mask = size * 2 - 1;
2703       int64_t offset = prev_offset > cur_offset ? cur_offset : prev_offset;
2704       return (offset & pair_mask) == 0;
2705     } else { // If base is not sp, we can't guarantee the access is aligned.
2706       return false;
2707     }
2708   } else {
2709     int64_t mask = size - 1;
2710     // Load/store pair instruction only supports element size aligned offset.
2711     return (cur_offset & mask) == 0 && (prev_offset & mask) == 0;
2712   }
2713 }
2714 
2715 // Checks whether current and previous loads/stores can be merged.
2716 // Returns true if it can be merged, else false.
2717 bool MacroAssembler::ldst_can_merge(Register rt,
2718                                     const Address &adr,
2719                                     size_t cur_size_in_bytes,
2720                                     bool is_store) const {
2721   address prev = pc() - NativeInstruction::instruction_size;
2722   address last = code()->last_insn();
2723 
2724   if (last == NULL || !nativeInstruction_at(last)->is_Imm_LdSt()) {
2725     return false;
2726   }
2727 
2728   if (adr.getMode() != Address::base_plus_offset || prev != last) {
2729     return false;
2730   }
2731 
2732   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
2733   size_t prev_size_in_bytes = prev_ldst->size_in_bytes();
2734 
2735   assert(prev_size_in_bytes == 4 || prev_size_in_bytes == 8, "only supports 64/32bit merging.");
2736   assert(cur_size_in_bytes == 4 || cur_size_in_bytes == 8, "only supports 64/32bit merging.");
2737 
2738   if (cur_size_in_bytes != prev_size_in_bytes || is_store != prev_ldst->is_store()) {
2739     return false;
2740   }
2741 
2742   int64_t max_offset = 63 * prev_size_in_bytes;
2743   int64_t min_offset = -64 * prev_size_in_bytes;
2744 
2745   assert(prev_ldst->is_not_pre_post_index(), "pre-index or post-index is not supported to be merged.");
2746 
2747   // Only same base can be merged.
2748   if (adr.base() != prev_ldst->base()) {
2749     return false;
2750   }
2751 
2752   int64_t cur_offset = adr.offset();
2753   int64_t prev_offset = prev_ldst->offset();
2754   size_t diff = abs(cur_offset - prev_offset);
2755   if (diff != prev_size_in_bytes) {
2756     return false;
2757   }
2758 
2759   // Following cases can not be merged:
2760   // ldr x2, [x2, #8]
2761   // ldr x3, [x2, #16]
2762   // or:
2763   // ldr x2, [x3, #8]
2764   // ldr x2, [x3, #16]
2765   // If t1 and t2 is the same in "ldp t1, t2, [xn, #imm]", we'll get SIGILL.
2766   if (!is_store && (adr.base() == prev_ldst->target() || rt == prev_ldst->target())) {
2767     return false;
2768   }
2769 
2770   int64_t low_offset = prev_offset > cur_offset ? cur_offset : prev_offset;
2771   // Offset range must be in ldp/stp instruction's range.
2772   if (low_offset > max_offset || low_offset < min_offset) {
2773     return false;
2774   }
2775 
2776   if (merge_alignment_check(adr.base(), prev_size_in_bytes, cur_offset, prev_offset)) {
2777     return true;
2778   }
2779 
2780   return false;
2781 }
2782 
2783 // Merge current load/store with previous load/store into ldp/stp.
2784 void MacroAssembler::merge_ldst(Register rt,
2785                                 const Address &adr,
2786                                 size_t cur_size_in_bytes,
2787                                 bool is_store) {
2788 
2789   assert(ldst_can_merge(rt, adr, cur_size_in_bytes, is_store) == true, "cur and prev must be able to be merged.");
2790 
2791   Register rt_low, rt_high;
2792   address prev = pc() - NativeInstruction::instruction_size;
2793   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
2794 
2795   int64_t offset;
2796 
2797   if (adr.offset() < prev_ldst->offset()) {
2798     offset = adr.offset();
2799     rt_low = rt;
2800     rt_high = prev_ldst->target();
2801   } else {
2802     offset = prev_ldst->offset();
2803     rt_low = prev_ldst->target();
2804     rt_high = rt;
2805   }
2806 
2807   Address adr_p = Address(prev_ldst->base(), offset);
2808   // Overwrite previous generated binary.
2809   code_section()->set_end(prev);
2810 
2811   const size_t sz = prev_ldst->size_in_bytes();
2812   assert(sz == 8 || sz == 4, "only supports 64/32bit merging.");
2813   if (!is_store) {
2814     BLOCK_COMMENT("merged ldr pair");
2815     if (sz == 8) {
2816       ldp(rt_low, rt_high, adr_p);
2817     } else {
2818       ldpw(rt_low, rt_high, adr_p);
2819     }
2820   } else {
2821     BLOCK_COMMENT("merged str pair");
2822     if (sz == 8) {
2823       stp(rt_low, rt_high, adr_p);
2824     } else {
2825       stpw(rt_low, rt_high, adr_p);
2826     }
2827   }
2828 }
2829 
2830 /**
2831  * Multiply 64 bit by 64 bit first loop.
2832  */
2833 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
2834                                            Register y, Register y_idx, Register z,
2835                                            Register carry, Register product,
2836                                            Register idx, Register kdx) {
2837   //
2838   //  jlong carry, x[], y[], z[];
2839   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
2840   //    huge_128 product = y[idx] * x[xstart] + carry;
2841   //    z[kdx] = (jlong)product;
2842   //    carry  = (jlong)(product >>> 64);
2843   //  }
2844   //  z[xstart] = carry;
2845   //
2846 
2847   Label L_first_loop, L_first_loop_exit;
2848   Label L_one_x, L_one_y, L_multiply;
2849 
2850   subsw(xstart, xstart, 1);
2851   br(Assembler::MI, L_one_x);
2852 
2853   lea(rscratch1, Address(x, xstart, Address::lsl(LogBytesPerInt)));
2854   ldr(x_xstart, Address(rscratch1));
2855   ror(x_xstart, x_xstart, 32); // convert big-endian to little-endian
2856 
2857   bind(L_first_loop);
2858   subsw(idx, idx, 1);
2859   br(Assembler::MI, L_first_loop_exit);
2860   subsw(idx, idx, 1);
2861   br(Assembler::MI, L_one_y);
2862   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2863   ldr(y_idx, Address(rscratch1));
2864   ror(y_idx, y_idx, 32); // convert big-endian to little-endian
2865   bind(L_multiply);
2866 
2867   // AArch64 has a multiply-accumulate instruction that we can't use
2868   // here because it has no way to process carries, so we have to use
2869   // separate add and adc instructions.  Bah.
2870   umulh(rscratch1, x_xstart, y_idx); // x_xstart * y_idx -> rscratch1:product
2871   mul(product, x_xstart, y_idx);
2872   adds(product, product, carry);
2873   adc(carry, rscratch1, zr);   // x_xstart * y_idx + carry -> carry:product
2874 
2875   subw(kdx, kdx, 2);
2876   ror(product, product, 32); // back to big-endian
2877   str(product, offsetted_address(z, kdx, Address::uxtw(LogBytesPerInt), 0, BytesPerLong));
2878 
2879   b(L_first_loop);
2880 
2881   bind(L_one_y);
2882   ldrw(y_idx, Address(y,  0));
2883   b(L_multiply);
2884 
2885   bind(L_one_x);
2886   ldrw(x_xstart, Address(x,  0));
2887   b(L_first_loop);
2888 
2889   bind(L_first_loop_exit);
2890 }
2891 
2892 /**
2893  * Multiply 128 bit by 128. Unrolled inner loop.
2894  *
2895  */
2896 void MacroAssembler::multiply_128_x_128_loop(Register y, Register z,
2897                                              Register carry, Register carry2,
2898                                              Register idx, Register jdx,
2899                                              Register yz_idx1, Register yz_idx2,
2900                                              Register tmp, Register tmp3, Register tmp4,
2901                                              Register tmp6, Register product_hi) {
2902 
2903   //   jlong carry, x[], y[], z[];
2904   //   int kdx = ystart+1;
2905   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
2906   //     huge_128 tmp3 = (y[idx+1] * product_hi) + z[kdx+idx+1] + carry;
2907   //     jlong carry2  = (jlong)(tmp3 >>> 64);
2908   //     huge_128 tmp4 = (y[idx]   * product_hi) + z[kdx+idx] + carry2;
2909   //     carry  = (jlong)(tmp4 >>> 64);
2910   //     z[kdx+idx+1] = (jlong)tmp3;
2911   //     z[kdx+idx] = (jlong)tmp4;
2912   //   }
2913   //   idx += 2;
2914   //   if (idx > 0) {
2915   //     yz_idx1 = (y[idx] * product_hi) + z[kdx+idx] + carry;
2916   //     z[kdx+idx] = (jlong)yz_idx1;
2917   //     carry  = (jlong)(yz_idx1 >>> 64);
2918   //   }
2919   //
2920 
2921   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
2922 
2923   lsrw(jdx, idx, 2);
2924 
2925   bind(L_third_loop);
2926 
2927   subsw(jdx, jdx, 1);
2928   br(Assembler::MI, L_third_loop_exit);
2929   subw(idx, idx, 4);
2930 
2931   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2932 
2933   ldp(yz_idx2, yz_idx1, Address(rscratch1, 0));
2934 
2935   lea(tmp6, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2936 
2937   ror(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
2938   ror(yz_idx2, yz_idx2, 32);
2939 
2940   ldp(rscratch2, rscratch1, Address(tmp6, 0));
2941 
2942   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
2943   umulh(tmp4, product_hi, yz_idx1);
2944 
2945   ror(rscratch1, rscratch1, 32); // convert big-endian to little-endian
2946   ror(rscratch2, rscratch2, 32);
2947 
2948   mul(tmp, product_hi, yz_idx2);   //  yz_idx2 * product_hi -> carry2:tmp
2949   umulh(carry2, product_hi, yz_idx2);
2950 
2951   // propagate sum of both multiplications into carry:tmp4:tmp3
2952   adds(tmp3, tmp3, carry);
2953   adc(tmp4, tmp4, zr);
2954   adds(tmp3, tmp3, rscratch1);
2955   adcs(tmp4, tmp4, tmp);
2956   adc(carry, carry2, zr);
2957   adds(tmp4, tmp4, rscratch2);
2958   adc(carry, carry, zr);
2959 
2960   ror(tmp3, tmp3, 32); // convert little-endian to big-endian
2961   ror(tmp4, tmp4, 32);
2962   stp(tmp4, tmp3, Address(tmp6, 0));
2963 
2964   b(L_third_loop);
2965   bind (L_third_loop_exit);
2966 
2967   andw (idx, idx, 0x3);
2968   cbz(idx, L_post_third_loop_done);
2969 
2970   Label L_check_1;
2971   subsw(idx, idx, 2);
2972   br(Assembler::MI, L_check_1);
2973 
2974   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2975   ldr(yz_idx1, Address(rscratch1, 0));
2976   ror(yz_idx1, yz_idx1, 32);
2977   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
2978   umulh(tmp4, product_hi, yz_idx1);
2979   lea(rscratch1, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2980   ldr(yz_idx2, Address(rscratch1, 0));
2981   ror(yz_idx2, yz_idx2, 32);
2982 
2983   add2_with_carry(carry, tmp4, tmp3, carry, yz_idx2);
2984 
2985   ror(tmp3, tmp3, 32);
2986   str(tmp3, Address(rscratch1, 0));
2987 
2988   bind (L_check_1);
2989 
2990   andw (idx, idx, 0x1);
2991   subsw(idx, idx, 1);
2992   br(Assembler::MI, L_post_third_loop_done);
2993   ldrw(tmp4, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2994   mul(tmp3, tmp4, product_hi);  //  tmp4 * product_hi -> carry2:tmp3
2995   umulh(carry2, tmp4, product_hi);
2996   ldrw(tmp4, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2997 
2998   add2_with_carry(carry2, tmp3, tmp4, carry);
2999 
3000   strw(tmp3, Address(z, idx, Address::uxtw(LogBytesPerInt)));
3001   extr(carry, carry2, tmp3, 32);
3002 
3003   bind(L_post_third_loop_done);
3004 }
3005 
3006 /**
3007  * Code for BigInteger::multiplyToLen() instrinsic.
3008  *
3009  * r0: x
3010  * r1: xlen
3011  * r2: y
3012  * r3: ylen
3013  * r4:  z
3014  * r5: zlen
3015  * r10: tmp1
3016  * r11: tmp2
3017  * r12: tmp3
3018  * r13: tmp4
3019  * r14: tmp5
3020  * r15: tmp6
3021  * r16: tmp7
3022  *
3023  */
3024 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen,
3025                                      Register z, Register zlen,
3026                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4,
3027                                      Register tmp5, Register tmp6, Register product_hi) {
3028 
3029   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6);
3030 
3031   const Register idx = tmp1;
3032   const Register kdx = tmp2;
3033   const Register xstart = tmp3;
3034 
3035   const Register y_idx = tmp4;
3036   const Register carry = tmp5;
3037   const Register product  = xlen;
3038   const Register x_xstart = zlen;  // reuse register
3039 
3040   // First Loop.
3041   //
3042   //  final static long LONG_MASK = 0xffffffffL;
3043   //  int xstart = xlen - 1;
3044   //  int ystart = ylen - 1;
3045   //  long carry = 0;
3046   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
3047   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
3048   //    z[kdx] = (int)product;
3049   //    carry = product >>> 32;
3050   //  }
3051   //  z[xstart] = (int)carry;
3052   //
3053 
3054   movw(idx, ylen);      // idx = ylen;
3055   movw(kdx, zlen);      // kdx = xlen+ylen;
3056   mov(carry, zr);       // carry = 0;
3057 
3058   Label L_done;
3059 
3060   movw(xstart, xlen);
3061   subsw(xstart, xstart, 1);
3062   br(Assembler::MI, L_done);
3063 
3064   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
3065 
3066   Label L_second_loop;
3067   cbzw(kdx, L_second_loop);
3068 
3069   Label L_carry;
3070   subw(kdx, kdx, 1);
3071   cbzw(kdx, L_carry);
3072 
3073   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
3074   lsr(carry, carry, 32);
3075   subw(kdx, kdx, 1);
3076 
3077   bind(L_carry);
3078   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
3079 
3080   // Second and third (nested) loops.
3081   //
3082   // for (int i = xstart-1; i >= 0; i--) { // Second loop
3083   //   carry = 0;
3084   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
3085   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
3086   //                    (z[k] & LONG_MASK) + carry;
3087   //     z[k] = (int)product;
3088   //     carry = product >>> 32;
3089   //   }
3090   //   z[i] = (int)carry;
3091   // }
3092   //
3093   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = product_hi
3094 
3095   const Register jdx = tmp1;
3096 
3097   bind(L_second_loop);
3098   mov(carry, zr);                // carry = 0;
3099   movw(jdx, ylen);               // j = ystart+1
3100 
3101   subsw(xstart, xstart, 1);      // i = xstart-1;
3102   br(Assembler::MI, L_done);
3103 
3104   str(z, Address(pre(sp, -4 * wordSize)));
3105 
3106   Label L_last_x;
3107   lea(z, offsetted_address(z, xstart, Address::uxtw(LogBytesPerInt), 4, BytesPerInt)); // z = z + k - j
3108   subsw(xstart, xstart, 1);       // i = xstart-1;
3109   br(Assembler::MI, L_last_x);
3110 
3111   lea(rscratch1, Address(x, xstart, Address::uxtw(LogBytesPerInt)));
3112   ldr(product_hi, Address(rscratch1));
3113   ror(product_hi, product_hi, 32);  // convert big-endian to little-endian
3114 
3115   Label L_third_loop_prologue;
3116   bind(L_third_loop_prologue);
3117 
3118   str(ylen, Address(sp, wordSize));
3119   stp(x, xstart, Address(sp, 2 * wordSize));
3120   multiply_128_x_128_loop(y, z, carry, x, jdx, ylen, product,
3121                           tmp2, x_xstart, tmp3, tmp4, tmp6, product_hi);
3122   ldp(z, ylen, Address(post(sp, 2 * wordSize)));
3123   ldp(x, xlen, Address(post(sp, 2 * wordSize)));   // copy old xstart -> xlen
3124 
3125   addw(tmp3, xlen, 1);
3126   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
3127   subsw(tmp3, tmp3, 1);
3128   br(Assembler::MI, L_done);
3129 
3130   lsr(carry, carry, 32);
3131   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
3132   b(L_second_loop);
3133 
3134   // Next infrequent code is moved outside loops.
3135   bind(L_last_x);
3136   ldrw(product_hi, Address(x,  0));
3137   b(L_third_loop_prologue);
3138 
3139   bind(L_done);
3140 }
3141 
3142 // Code for BigInteger::mulAdd instrinsic
3143 // out     = r0
3144 // in      = r1
3145 // offset  = r2  (already out.length-offset)
3146 // len     = r3
3147 // k       = r4
3148 //
3149 // pseudo code from java implementation:
3150 // carry = 0;
3151 // offset = out.length-offset - 1;
3152 // for (int j=len-1; j >= 0; j--) {
3153 //     product = (in[j] & LONG_MASK) * kLong + (out[offset] & LONG_MASK) + carry;
3154 //     out[offset--] = (int)product;
3155 //     carry = product >>> 32;
3156 // }
3157 // return (int)carry;
3158 void MacroAssembler::mul_add(Register out, Register in, Register offset,
3159       Register len, Register k) {
3160     Label LOOP, END;
3161     // pre-loop
3162     cmp(len, zr); // cmp, not cbz/cbnz: to use condition twice => less branches
3163     csel(out, zr, out, Assembler::EQ);
3164     br(Assembler::EQ, END);
3165     add(in, in, len, LSL, 2); // in[j+1] address
3166     add(offset, out, offset, LSL, 2); // out[offset + 1] address
3167     mov(out, zr); // used to keep carry now
3168     BIND(LOOP);
3169     ldrw(rscratch1, Address(pre(in, -4)));
3170     madd(rscratch1, rscratch1, k, out);
3171     ldrw(rscratch2, Address(pre(offset, -4)));
3172     add(rscratch1, rscratch1, rscratch2);
3173     strw(rscratch1, Address(offset));
3174     lsr(out, rscratch1, 32);
3175     subs(len, len, 1);
3176     br(Assembler::NE, LOOP);
3177     BIND(END);
3178 }
3179 
3180 /**
3181  * Emits code to update CRC-32 with a byte value according to constants in table
3182  *
3183  * @param [in,out]crc   Register containing the crc.
3184  * @param [in]val       Register containing the byte to fold into the CRC.
3185  * @param [in]table     Register containing the table of crc constants.
3186  *
3187  * uint32_t crc;
3188  * val = crc_table[(val ^ crc) & 0xFF];
3189  * crc = val ^ (crc >> 8);
3190  *
3191  */
3192 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
3193   eor(val, val, crc);
3194   andr(val, val, 0xff);
3195   ldrw(val, Address(table, val, Address::lsl(2)));
3196   eor(crc, val, crc, Assembler::LSR, 8);
3197 }
3198 
3199 /**
3200  * Emits code to update CRC-32 with a 32-bit value according to tables 0 to 3
3201  *
3202  * @param [in,out]crc   Register containing the crc.
3203  * @param [in]v         Register containing the 32-bit to fold into the CRC.
3204  * @param [in]table0    Register containing table 0 of crc constants.
3205  * @param [in]table1    Register containing table 1 of crc constants.
3206  * @param [in]table2    Register containing table 2 of crc constants.
3207  * @param [in]table3    Register containing table 3 of crc constants.
3208  *
3209  * uint32_t crc;
3210  *   v = crc ^ v
3211  *   crc = table3[v&0xff]^table2[(v>>8)&0xff]^table1[(v>>16)&0xff]^table0[v>>24]
3212  *
3213  */
3214 void MacroAssembler::update_word_crc32(Register crc, Register v, Register tmp,
3215         Register table0, Register table1, Register table2, Register table3,
3216         bool upper) {
3217   eor(v, crc, v, upper ? LSR:LSL, upper ? 32:0);
3218   uxtb(tmp, v);
3219   ldrw(crc, Address(table3, tmp, Address::lsl(2)));
3220   ubfx(tmp, v, 8, 8);
3221   ldrw(tmp, Address(table2, tmp, Address::lsl(2)));
3222   eor(crc, crc, tmp);
3223   ubfx(tmp, v, 16, 8);
3224   ldrw(tmp, Address(table1, tmp, Address::lsl(2)));
3225   eor(crc, crc, tmp);
3226   ubfx(tmp, v, 24, 8);
3227   ldrw(tmp, Address(table0, tmp, Address::lsl(2)));
3228   eor(crc, crc, tmp);
3229 }
3230 
3231 void MacroAssembler::kernel_crc32_using_crc32(Register crc, Register buf,
3232         Register len, Register tmp0, Register tmp1, Register tmp2,
3233         Register tmp3) {
3234     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
3235     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
3236 
3237     mvnw(crc, crc);
3238 
3239     subs(len, len, 128);
3240     br(Assembler::GE, CRC_by64_pre);
3241   BIND(CRC_less64);
3242     adds(len, len, 128-32);
3243     br(Assembler::GE, CRC_by32_loop);
3244   BIND(CRC_less32);
3245     adds(len, len, 32-4);
3246     br(Assembler::GE, CRC_by4_loop);
3247     adds(len, len, 4);
3248     br(Assembler::GT, CRC_by1_loop);
3249     b(L_exit);
3250 
3251   BIND(CRC_by32_loop);
3252     ldp(tmp0, tmp1, Address(post(buf, 16)));
3253     subs(len, len, 32);
3254     crc32x(crc, crc, tmp0);
3255     ldr(tmp2, Address(post(buf, 8)));
3256     crc32x(crc, crc, tmp1);
3257     ldr(tmp3, Address(post(buf, 8)));
3258     crc32x(crc, crc, tmp2);
3259     crc32x(crc, crc, tmp3);
3260     br(Assembler::GE, CRC_by32_loop);
3261     cmn(len, 32);
3262     br(Assembler::NE, CRC_less32);
3263     b(L_exit);
3264 
3265   BIND(CRC_by4_loop);
3266     ldrw(tmp0, Address(post(buf, 4)));
3267     subs(len, len, 4);
3268     crc32w(crc, crc, tmp0);
3269     br(Assembler::GE, CRC_by4_loop);
3270     adds(len, len, 4);
3271     br(Assembler::LE, L_exit);
3272   BIND(CRC_by1_loop);
3273     ldrb(tmp0, Address(post(buf, 1)));
3274     subs(len, len, 1);
3275     crc32b(crc, crc, tmp0);
3276     br(Assembler::GT, CRC_by1_loop);
3277     b(L_exit);
3278 
3279   BIND(CRC_by64_pre);
3280     sub(buf, buf, 8);
3281     ldp(tmp0, tmp1, Address(buf, 8));
3282     crc32x(crc, crc, tmp0);
3283     ldr(tmp2, Address(buf, 24));
3284     crc32x(crc, crc, tmp1);
3285     ldr(tmp3, Address(buf, 32));
3286     crc32x(crc, crc, tmp2);
3287     ldr(tmp0, Address(buf, 40));
3288     crc32x(crc, crc, tmp3);
3289     ldr(tmp1, Address(buf, 48));
3290     crc32x(crc, crc, tmp0);
3291     ldr(tmp2, Address(buf, 56));
3292     crc32x(crc, crc, tmp1);
3293     ldr(tmp3, Address(pre(buf, 64)));
3294 
3295     b(CRC_by64_loop);
3296 
3297     align(CodeEntryAlignment);
3298   BIND(CRC_by64_loop);
3299     subs(len, len, 64);
3300     crc32x(crc, crc, tmp2);
3301     ldr(tmp0, Address(buf, 8));
3302     crc32x(crc, crc, tmp3);
3303     ldr(tmp1, Address(buf, 16));
3304     crc32x(crc, crc, tmp0);
3305     ldr(tmp2, Address(buf, 24));
3306     crc32x(crc, crc, tmp1);
3307     ldr(tmp3, Address(buf, 32));
3308     crc32x(crc, crc, tmp2);
3309     ldr(tmp0, Address(buf, 40));
3310     crc32x(crc, crc, tmp3);
3311     ldr(tmp1, Address(buf, 48));
3312     crc32x(crc, crc, tmp0);
3313     ldr(tmp2, Address(buf, 56));
3314     crc32x(crc, crc, tmp1);
3315     ldr(tmp3, Address(pre(buf, 64)));
3316     br(Assembler::GE, CRC_by64_loop);
3317 
3318     // post-loop
3319     crc32x(crc, crc, tmp2);
3320     crc32x(crc, crc, tmp3);
3321 
3322     sub(len, len, 64);
3323     add(buf, buf, 8);
3324     cmn(len, 128);
3325     br(Assembler::NE, CRC_less64);
3326   BIND(L_exit);
3327     mvnw(crc, crc);
3328 }
3329 
3330 /**
3331  * @param crc   register containing existing CRC (32-bit)
3332  * @param buf   register pointing to input byte buffer (byte*)
3333  * @param len   register containing number of bytes
3334  * @param table register that will contain address of CRC table
3335  * @param tmp   scratch register
3336  */
3337 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len,
3338         Register table0, Register table1, Register table2, Register table3,
3339         Register tmp, Register tmp2, Register tmp3) {
3340   Label L_by16, L_by16_loop, L_by4, L_by4_loop, L_by1, L_by1_loop, L_exit;
3341   uint64_t offset;
3342 
3343   if (UseCRC32) {
3344       kernel_crc32_using_crc32(crc, buf, len, table0, table1, table2, table3);
3345       return;
3346   }
3347 
3348     mvnw(crc, crc);
3349 
3350     adrp(table0, ExternalAddress(StubRoutines::crc_table_addr()), offset);
3351     if (offset) add(table0, table0, offset);
3352     add(table1, table0, 1*256*sizeof(juint));
3353     add(table2, table0, 2*256*sizeof(juint));
3354     add(table3, table0, 3*256*sizeof(juint));
3355 
3356   if (UseNeon) {
3357       cmp(len, (u1)64);
3358       br(Assembler::LT, L_by16);
3359       eor(v16, T16B, v16, v16);
3360 
3361     Label L_fold;
3362 
3363       add(tmp, table0, 4*256*sizeof(juint)); // Point at the Neon constants
3364 
3365       ld1(v0, v1, T2D, post(buf, 32));
3366       ld1r(v4, T2D, post(tmp, 8));
3367       ld1r(v5, T2D, post(tmp, 8));
3368       ld1r(v6, T2D, post(tmp, 8));
3369       ld1r(v7, T2D, post(tmp, 8));
3370       mov(v16, T4S, 0, crc);
3371 
3372       eor(v0, T16B, v0, v16);
3373       sub(len, len, 64);
3374 
3375     BIND(L_fold);
3376       pmull(v22, T8H, v0, v5, T8B);
3377       pmull(v20, T8H, v0, v7, T8B);
3378       pmull(v23, T8H, v0, v4, T8B);
3379       pmull(v21, T8H, v0, v6, T8B);
3380 
3381       pmull2(v18, T8H, v0, v5, T16B);
3382       pmull2(v16, T8H, v0, v7, T16B);
3383       pmull2(v19, T8H, v0, v4, T16B);
3384       pmull2(v17, T8H, v0, v6, T16B);
3385 
3386       uzp1(v24, T8H, v20, v22);
3387       uzp2(v25, T8H, v20, v22);
3388       eor(v20, T16B, v24, v25);
3389 
3390       uzp1(v26, T8H, v16, v18);
3391       uzp2(v27, T8H, v16, v18);
3392       eor(v16, T16B, v26, v27);
3393 
3394       ushll2(v22, T4S, v20, T8H, 8);
3395       ushll(v20, T4S, v20, T4H, 8);
3396 
3397       ushll2(v18, T4S, v16, T8H, 8);
3398       ushll(v16, T4S, v16, T4H, 8);
3399 
3400       eor(v22, T16B, v23, v22);
3401       eor(v18, T16B, v19, v18);
3402       eor(v20, T16B, v21, v20);
3403       eor(v16, T16B, v17, v16);
3404 
3405       uzp1(v17, T2D, v16, v20);
3406       uzp2(v21, T2D, v16, v20);
3407       eor(v17, T16B, v17, v21);
3408 
3409       ushll2(v20, T2D, v17, T4S, 16);
3410       ushll(v16, T2D, v17, T2S, 16);
3411 
3412       eor(v20, T16B, v20, v22);
3413       eor(v16, T16B, v16, v18);
3414 
3415       uzp1(v17, T2D, v20, v16);
3416       uzp2(v21, T2D, v20, v16);
3417       eor(v28, T16B, v17, v21);
3418 
3419       pmull(v22, T8H, v1, v5, T8B);
3420       pmull(v20, T8H, v1, v7, T8B);
3421       pmull(v23, T8H, v1, v4, T8B);
3422       pmull(v21, T8H, v1, v6, T8B);
3423 
3424       pmull2(v18, T8H, v1, v5, T16B);
3425       pmull2(v16, T8H, v1, v7, T16B);
3426       pmull2(v19, T8H, v1, v4, T16B);
3427       pmull2(v17, T8H, v1, v6, T16B);
3428 
3429       ld1(v0, v1, T2D, post(buf, 32));
3430 
3431       uzp1(v24, T8H, v20, v22);
3432       uzp2(v25, T8H, v20, v22);
3433       eor(v20, T16B, v24, v25);
3434 
3435       uzp1(v26, T8H, v16, v18);
3436       uzp2(v27, T8H, v16, v18);
3437       eor(v16, T16B, v26, v27);
3438 
3439       ushll2(v22, T4S, v20, T8H, 8);
3440       ushll(v20, T4S, v20, T4H, 8);
3441 
3442       ushll2(v18, T4S, v16, T8H, 8);
3443       ushll(v16, T4S, v16, T4H, 8);
3444 
3445       eor(v22, T16B, v23, v22);
3446       eor(v18, T16B, v19, v18);
3447       eor(v20, T16B, v21, v20);
3448       eor(v16, T16B, v17, v16);
3449 
3450       uzp1(v17, T2D, v16, v20);
3451       uzp2(v21, T2D, v16, v20);
3452       eor(v16, T16B, v17, v21);
3453 
3454       ushll2(v20, T2D, v16, T4S, 16);
3455       ushll(v16, T2D, v16, T2S, 16);
3456 
3457       eor(v20, T16B, v22, v20);
3458       eor(v16, T16B, v16, v18);
3459 
3460       uzp1(v17, T2D, v20, v16);
3461       uzp2(v21, T2D, v20, v16);
3462       eor(v20, T16B, v17, v21);
3463 
3464       shl(v16, T2D, v28, 1);
3465       shl(v17, T2D, v20, 1);
3466 
3467       eor(v0, T16B, v0, v16);
3468       eor(v1, T16B, v1, v17);
3469 
3470       subs(len, len, 32);
3471       br(Assembler::GE, L_fold);
3472 
3473       mov(crc, 0);
3474       mov(tmp, v0, T1D, 0);
3475       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3476       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3477       mov(tmp, v0, T1D, 1);
3478       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3479       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3480       mov(tmp, v1, T1D, 0);
3481       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3482       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3483       mov(tmp, v1, T1D, 1);
3484       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3485       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3486 
3487       add(len, len, 32);
3488   }
3489 
3490   BIND(L_by16);
3491     subs(len, len, 16);
3492     br(Assembler::GE, L_by16_loop);
3493     adds(len, len, 16-4);
3494     br(Assembler::GE, L_by4_loop);
3495     adds(len, len, 4);
3496     br(Assembler::GT, L_by1_loop);
3497     b(L_exit);
3498 
3499   BIND(L_by4_loop);
3500     ldrw(tmp, Address(post(buf, 4)));
3501     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3);
3502     subs(len, len, 4);
3503     br(Assembler::GE, L_by4_loop);
3504     adds(len, len, 4);
3505     br(Assembler::LE, L_exit);
3506   BIND(L_by1_loop);
3507     subs(len, len, 1);
3508     ldrb(tmp, Address(post(buf, 1)));
3509     update_byte_crc32(crc, tmp, table0);
3510     br(Assembler::GT, L_by1_loop);
3511     b(L_exit);
3512 
3513     align(CodeEntryAlignment);
3514   BIND(L_by16_loop);
3515     subs(len, len, 16);
3516     ldp(tmp, tmp3, Address(post(buf, 16)));
3517     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3518     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3519     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, false);
3520     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, true);
3521     br(Assembler::GE, L_by16_loop);
3522     adds(len, len, 16-4);
3523     br(Assembler::GE, L_by4_loop);
3524     adds(len, len, 4);
3525     br(Assembler::GT, L_by1_loop);
3526   BIND(L_exit);
3527     mvnw(crc, crc);
3528 }
3529 
3530 void MacroAssembler::kernel_crc32c_using_crc32c(Register crc, Register buf,
3531         Register len, Register tmp0, Register tmp1, Register tmp2,
3532         Register tmp3) {
3533     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
3534     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
3535 
3536     subs(len, len, 128);
3537     br(Assembler::GE, CRC_by64_pre);
3538   BIND(CRC_less64);
3539     adds(len, len, 128-32);
3540     br(Assembler::GE, CRC_by32_loop);
3541   BIND(CRC_less32);
3542     adds(len, len, 32-4);
3543     br(Assembler::GE, CRC_by4_loop);
3544     adds(len, len, 4);
3545     br(Assembler::GT, CRC_by1_loop);
3546     b(L_exit);
3547 
3548   BIND(CRC_by32_loop);
3549     ldp(tmp0, tmp1, Address(post(buf, 16)));
3550     subs(len, len, 32);
3551     crc32cx(crc, crc, tmp0);
3552     ldr(tmp2, Address(post(buf, 8)));
3553     crc32cx(crc, crc, tmp1);
3554     ldr(tmp3, Address(post(buf, 8)));
3555     crc32cx(crc, crc, tmp2);
3556     crc32cx(crc, crc, tmp3);
3557     br(Assembler::GE, CRC_by32_loop);
3558     cmn(len, 32);
3559     br(Assembler::NE, CRC_less32);
3560     b(L_exit);
3561 
3562   BIND(CRC_by4_loop);
3563     ldrw(tmp0, Address(post(buf, 4)));
3564     subs(len, len, 4);
3565     crc32cw(crc, crc, tmp0);
3566     br(Assembler::GE, CRC_by4_loop);
3567     adds(len, len, 4);
3568     br(Assembler::LE, L_exit);
3569   BIND(CRC_by1_loop);
3570     ldrb(tmp0, Address(post(buf, 1)));
3571     subs(len, len, 1);
3572     crc32cb(crc, crc, tmp0);
3573     br(Assembler::GT, CRC_by1_loop);
3574     b(L_exit);
3575 
3576   BIND(CRC_by64_pre);
3577     sub(buf, buf, 8);
3578     ldp(tmp0, tmp1, Address(buf, 8));
3579     crc32cx(crc, crc, tmp0);
3580     ldr(tmp2, Address(buf, 24));
3581     crc32cx(crc, crc, tmp1);
3582     ldr(tmp3, Address(buf, 32));
3583     crc32cx(crc, crc, tmp2);
3584     ldr(tmp0, Address(buf, 40));
3585     crc32cx(crc, crc, tmp3);
3586     ldr(tmp1, Address(buf, 48));
3587     crc32cx(crc, crc, tmp0);
3588     ldr(tmp2, Address(buf, 56));
3589     crc32cx(crc, crc, tmp1);
3590     ldr(tmp3, Address(pre(buf, 64)));
3591 
3592     b(CRC_by64_loop);
3593 
3594     align(CodeEntryAlignment);
3595   BIND(CRC_by64_loop);
3596     subs(len, len, 64);
3597     crc32cx(crc, crc, tmp2);
3598     ldr(tmp0, Address(buf, 8));
3599     crc32cx(crc, crc, tmp3);
3600     ldr(tmp1, Address(buf, 16));
3601     crc32cx(crc, crc, tmp0);
3602     ldr(tmp2, Address(buf, 24));
3603     crc32cx(crc, crc, tmp1);
3604     ldr(tmp3, Address(buf, 32));
3605     crc32cx(crc, crc, tmp2);
3606     ldr(tmp0, Address(buf, 40));
3607     crc32cx(crc, crc, tmp3);
3608     ldr(tmp1, Address(buf, 48));
3609     crc32cx(crc, crc, tmp0);
3610     ldr(tmp2, Address(buf, 56));
3611     crc32cx(crc, crc, tmp1);
3612     ldr(tmp3, Address(pre(buf, 64)));
3613     br(Assembler::GE, CRC_by64_loop);
3614 
3615     // post-loop
3616     crc32cx(crc, crc, tmp2);
3617     crc32cx(crc, crc, tmp3);
3618 
3619     sub(len, len, 64);
3620     add(buf, buf, 8);
3621     cmn(len, 128);
3622     br(Assembler::NE, CRC_less64);
3623   BIND(L_exit);
3624 }
3625 
3626 /**
3627  * @param crc   register containing existing CRC (32-bit)
3628  * @param buf   register pointing to input byte buffer (byte*)
3629  * @param len   register containing number of bytes
3630  * @param table register that will contain address of CRC table
3631  * @param tmp   scratch register
3632  */
3633 void MacroAssembler::kernel_crc32c(Register crc, Register buf, Register len,
3634         Register table0, Register table1, Register table2, Register table3,
3635         Register tmp, Register tmp2, Register tmp3) {
3636   kernel_crc32c_using_crc32c(crc, buf, len, table0, table1, table2, table3);
3637 }
3638 
3639 
3640 SkipIfEqual::SkipIfEqual(
3641     MacroAssembler* masm, const bool* flag_addr, bool value) {
3642   _masm = masm;
3643   uint64_t offset;
3644   _masm->adrp(rscratch1, ExternalAddress((address)flag_addr), offset);
3645   _masm->ldrb(rscratch1, Address(rscratch1, offset));
3646   _masm->cbzw(rscratch1, _label);
3647 }
3648 
3649 SkipIfEqual::~SkipIfEqual() {
3650   _masm->bind(_label);
3651 }
3652 
3653 void MacroAssembler::addptr(const Address &dst, int32_t src) {
3654   Address adr;
3655   switch(dst.getMode()) {
3656   case Address::base_plus_offset:
3657     // This is the expected mode, although we allow all the other
3658     // forms below.
3659     adr = form_address(rscratch2, dst.base(), dst.offset(), LogBytesPerWord);
3660     break;
3661   default:
3662     lea(rscratch2, dst);
3663     adr = Address(rscratch2);
3664     break;
3665   }
3666   ldr(rscratch1, adr);
3667   add(rscratch1, rscratch1, src);
3668   str(rscratch1, adr);
3669 }
3670 
3671 void MacroAssembler::cmpptr(Register src1, Address src2) {
3672   uint64_t offset;
3673   adrp(rscratch1, src2, offset);
3674   ldr(rscratch1, Address(rscratch1, offset));
3675   cmp(src1, rscratch1);
3676 }
3677 
3678 void MacroAssembler::cmpoop(Register obj1, Register obj2) {
3679   cmp(obj1, obj2);
3680 }
3681 
3682 void MacroAssembler::load_method_holder_cld(Register rresult, Register rmethod) {
3683   load_method_holder(rresult, rmethod);
3684   ldr(rresult, Address(rresult, InstanceKlass::class_loader_data_offset()));
3685 }
3686 
3687 void MacroAssembler::load_method_holder(Register holder, Register method) {
3688   ldr(holder, Address(method, Method::const_offset()));                      // ConstMethod*
3689   ldr(holder, Address(holder, ConstMethod::constants_offset()));             // ConstantPool*
3690   ldr(holder, Address(holder, ConstantPool::pool_holder_offset_in_bytes())); // InstanceKlass*
3691 }
3692 
3693 void MacroAssembler::load_klass(Register dst, Register src) {
3694   if (UseCompressedClassPointers) {
3695     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3696     decode_klass_not_null(dst);
3697   } else {
3698     ldr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3699   }
3700 }
3701 
3702 // ((OopHandle)result).resolve();
3703 void MacroAssembler::resolve_oop_handle(Register result, Register tmp) {
3704   // OopHandle::resolve is an indirection.
3705   access_load_at(T_OBJECT, IN_NATIVE, result, Address(result, 0), tmp, noreg);
3706 }
3707 
3708 // ((WeakHandle)result).resolve();
3709 void MacroAssembler::resolve_weak_handle(Register rresult, Register rtmp) {
3710   assert_different_registers(rresult, rtmp);
3711   Label resolved;
3712 
3713   // A null weak handle resolves to null.
3714   cbz(rresult, resolved);
3715 
3716   // Only 64 bit platforms support GCs that require a tmp register
3717   // Only IN_HEAP loads require a thread_tmp register
3718   // WeakHandle::resolve is an indirection like jweak.
3719   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
3720                  rresult, Address(rresult), rtmp, /*tmp_thread*/noreg);
3721   bind(resolved);
3722 }
3723 
3724 void MacroAssembler::load_mirror(Register dst, Register method, Register tmp) {
3725   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
3726   ldr(dst, Address(rmethod, Method::const_offset()));
3727   ldr(dst, Address(dst, ConstMethod::constants_offset()));
3728   ldr(dst, Address(dst, ConstantPool::pool_holder_offset_in_bytes()));
3729   ldr(dst, Address(dst, mirror_offset));
3730   resolve_oop_handle(dst, tmp);
3731 }
3732 
3733 void MacroAssembler::cmp_klass(Register oop, Register trial_klass, Register tmp) {
3734   if (UseCompressedClassPointers) {
3735     ldrw(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
3736     if (CompressedKlassPointers::base() == NULL) {
3737       cmp(trial_klass, tmp, LSL, CompressedKlassPointers::shift());
3738       return;
3739     } else if (((uint64_t)CompressedKlassPointers::base() & 0xffffffff) == 0
3740                && CompressedKlassPointers::shift() == 0) {
3741       // Only the bottom 32 bits matter
3742       cmpw(trial_klass, tmp);
3743       return;
3744     }
3745     decode_klass_not_null(tmp);
3746   } else {
3747     ldr(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
3748   }
3749   cmp(trial_klass, tmp);
3750 }
3751 
3752 void MacroAssembler::store_klass(Register dst, Register src) {
3753   // FIXME: Should this be a store release?  concurrent gcs assumes
3754   // klass length is valid if klass field is not null.
3755   if (UseCompressedClassPointers) {
3756     encode_klass_not_null(src);
3757     strw(src, Address(dst, oopDesc::klass_offset_in_bytes()));
3758   } else {
3759     str(src, Address(dst, oopDesc::klass_offset_in_bytes()));
3760   }
3761 }
3762 
3763 void MacroAssembler::store_klass_gap(Register dst, Register src) {
3764   if (UseCompressedClassPointers) {
3765     // Store to klass gap in destination
3766     strw(src, Address(dst, oopDesc::klass_gap_offset_in_bytes()));
3767   }
3768 }
3769 
3770 // Algorithm must match CompressedOops::encode.
3771 void MacroAssembler::encode_heap_oop(Register d, Register s) {
3772 #ifdef ASSERT
3773   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
3774 #endif
3775   verify_oop(s, "broken oop in encode_heap_oop");
3776   if (CompressedOops::base() == NULL) {
3777     if (CompressedOops::shift() != 0) {
3778       assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
3779       lsr(d, s, LogMinObjAlignmentInBytes);
3780     } else {
3781       mov(d, s);
3782     }
3783   } else {
3784     subs(d, s, rheapbase);
3785     csel(d, d, zr, Assembler::HS);
3786     lsr(d, d, LogMinObjAlignmentInBytes);
3787 
3788     /*  Old algorithm: is this any worse?
3789     Label nonnull;
3790     cbnz(r, nonnull);
3791     sub(r, r, rheapbase);
3792     bind(nonnull);
3793     lsr(r, r, LogMinObjAlignmentInBytes);
3794     */
3795   }
3796 }
3797 
3798 void MacroAssembler::encode_heap_oop_not_null(Register r) {
3799 #ifdef ASSERT
3800   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
3801   if (CheckCompressedOops) {
3802     Label ok;
3803     cbnz(r, ok);
3804     stop("null oop passed to encode_heap_oop_not_null");
3805     bind(ok);
3806   }
3807 #endif
3808   verify_oop(r, "broken oop in encode_heap_oop_not_null");
3809   if (CompressedOops::base() != NULL) {
3810     sub(r, r, rheapbase);
3811   }
3812   if (CompressedOops::shift() != 0) {
3813     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
3814     lsr(r, r, LogMinObjAlignmentInBytes);
3815   }
3816 }
3817 
3818 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
3819 #ifdef ASSERT
3820   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
3821   if (CheckCompressedOops) {
3822     Label ok;
3823     cbnz(src, ok);
3824     stop("null oop passed to encode_heap_oop_not_null2");
3825     bind(ok);
3826   }
3827 #endif
3828   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
3829 
3830   Register data = src;
3831   if (CompressedOops::base() != NULL) {
3832     sub(dst, src, rheapbase);
3833     data = dst;
3834   }
3835   if (CompressedOops::shift() != 0) {
3836     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
3837     lsr(dst, data, LogMinObjAlignmentInBytes);
3838     data = dst;
3839   }
3840   if (data == src)
3841     mov(dst, src);
3842 }
3843 
3844 void  MacroAssembler::decode_heap_oop(Register d, Register s) {
3845 #ifdef ASSERT
3846   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
3847 #endif
3848   if (CompressedOops::base() == NULL) {
3849     if (CompressedOops::shift() != 0 || d != s) {
3850       lsl(d, s, CompressedOops::shift());
3851     }
3852   } else {
3853     Label done;
3854     if (d != s)
3855       mov(d, s);
3856     cbz(s, done);
3857     add(d, rheapbase, s, Assembler::LSL, LogMinObjAlignmentInBytes);
3858     bind(done);
3859   }
3860   verify_oop(d, "broken oop in decode_heap_oop");
3861 }
3862 
3863 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
3864   assert (UseCompressedOops, "should only be used for compressed headers");
3865   assert (Universe::heap() != NULL, "java heap should be initialized");
3866   // Cannot assert, unverified entry point counts instructions (see .ad file)
3867   // vtableStubs also counts instructions in pd_code_size_limit.
3868   // Also do not verify_oop as this is called by verify_oop.
3869   if (CompressedOops::shift() != 0) {
3870     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
3871     if (CompressedOops::base() != NULL) {
3872       add(r, rheapbase, r, Assembler::LSL, LogMinObjAlignmentInBytes);
3873     } else {
3874       add(r, zr, r, Assembler::LSL, LogMinObjAlignmentInBytes);
3875     }
3876   } else {
3877     assert (CompressedOops::base() == NULL, "sanity");
3878   }
3879 }
3880 
3881 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
3882   assert (UseCompressedOops, "should only be used for compressed headers");
3883   assert (Universe::heap() != NULL, "java heap should be initialized");
3884   // Cannot assert, unverified entry point counts instructions (see .ad file)
3885   // vtableStubs also counts instructions in pd_code_size_limit.
3886   // Also do not verify_oop as this is called by verify_oop.
3887   if (CompressedOops::shift() != 0) {
3888     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
3889     if (CompressedOops::base() != NULL) {
3890       add(dst, rheapbase, src, Assembler::LSL, LogMinObjAlignmentInBytes);
3891     } else {
3892       add(dst, zr, src, Assembler::LSL, LogMinObjAlignmentInBytes);
3893     }
3894   } else {
3895     assert (CompressedOops::base() == NULL, "sanity");
3896     if (dst != src) {
3897       mov(dst, src);
3898     }
3899   }
3900 }
3901 
3902 MacroAssembler::KlassDecodeMode MacroAssembler::_klass_decode_mode(KlassDecodeNone);
3903 
3904 MacroAssembler::KlassDecodeMode MacroAssembler::klass_decode_mode() {
3905   assert(UseCompressedClassPointers, "not using compressed class pointers");
3906   assert(Metaspace::initialized(), "metaspace not initialized yet");
3907 
3908   if (_klass_decode_mode != KlassDecodeNone) {
3909     return _klass_decode_mode;
3910   }
3911 
3912   assert(LogKlassAlignmentInBytes == CompressedKlassPointers::shift()
3913          || 0 == CompressedKlassPointers::shift(), "decode alg wrong");
3914 
3915   if (CompressedKlassPointers::base() == NULL) {
3916     return (_klass_decode_mode = KlassDecodeZero);
3917   }
3918 
3919   if (operand_valid_for_logical_immediate(
3920         /*is32*/false, (uint64_t)CompressedKlassPointers::base())) {
3921     const uint64_t range_mask =
3922       (1ULL << log2i(CompressedKlassPointers::range())) - 1;
3923     if (((uint64_t)CompressedKlassPointers::base() & range_mask) == 0) {
3924       return (_klass_decode_mode = KlassDecodeXor);
3925     }
3926   }
3927 
3928   const uint64_t shifted_base =
3929     (uint64_t)CompressedKlassPointers::base() >> CompressedKlassPointers::shift();
3930   guarantee((shifted_base & 0xffff0000ffffffff) == 0,
3931             "compressed class base bad alignment");
3932 
3933   return (_klass_decode_mode = KlassDecodeMovk);
3934 }
3935 
3936 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
3937   switch (klass_decode_mode()) {
3938   case KlassDecodeZero:
3939     if (CompressedKlassPointers::shift() != 0) {
3940       lsr(dst, src, LogKlassAlignmentInBytes);
3941     } else {
3942       if (dst != src) mov(dst, src);
3943     }
3944     break;
3945 
3946   case KlassDecodeXor:
3947     if (CompressedKlassPointers::shift() != 0) {
3948       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
3949       lsr(dst, dst, LogKlassAlignmentInBytes);
3950     } else {
3951       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
3952     }
3953     break;
3954 
3955   case KlassDecodeMovk:
3956     if (CompressedKlassPointers::shift() != 0) {
3957       ubfx(dst, src, LogKlassAlignmentInBytes, 32);
3958     } else {
3959       movw(dst, src);
3960     }
3961     break;
3962 
3963   case KlassDecodeNone:
3964     ShouldNotReachHere();
3965     break;
3966   }
3967 }
3968 
3969 void MacroAssembler::encode_klass_not_null(Register r) {
3970   encode_klass_not_null(r, r);
3971 }
3972 
3973 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
3974   assert (UseCompressedClassPointers, "should only be used for compressed headers");
3975 
3976   switch (klass_decode_mode()) {
3977   case KlassDecodeZero:
3978     if (CompressedKlassPointers::shift() != 0) {
3979       lsl(dst, src, LogKlassAlignmentInBytes);
3980     } else {
3981       if (dst != src) mov(dst, src);
3982     }
3983     break;
3984 
3985   case KlassDecodeXor:
3986     if (CompressedKlassPointers::shift() != 0) {
3987       lsl(dst, src, LogKlassAlignmentInBytes);
3988       eor(dst, dst, (uint64_t)CompressedKlassPointers::base());
3989     } else {
3990       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
3991     }
3992     break;
3993 
3994   case KlassDecodeMovk: {
3995     const uint64_t shifted_base =
3996       (uint64_t)CompressedKlassPointers::base() >> CompressedKlassPointers::shift();
3997 
3998     if (dst != src) movw(dst, src);
3999     movk(dst, shifted_base >> 32, 32);
4000 
4001     if (CompressedKlassPointers::shift() != 0) {
4002       lsl(dst, dst, LogKlassAlignmentInBytes);
4003     }
4004 
4005     break;
4006   }
4007 
4008   case KlassDecodeNone:
4009     ShouldNotReachHere();
4010     break;
4011   }
4012 }
4013 
4014 void  MacroAssembler::decode_klass_not_null(Register r) {
4015   decode_klass_not_null(r, r);
4016 }
4017 
4018 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
4019 #ifdef ASSERT
4020   {
4021     ThreadInVMfromUnknown tiv;
4022     assert (UseCompressedOops, "should only be used for compressed oops");
4023     assert (Universe::heap() != NULL, "java heap should be initialized");
4024     assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
4025     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
4026   }
4027 #endif
4028   int oop_index = oop_recorder()->find_index(obj);
4029   InstructionMark im(this);
4030   RelocationHolder rspec = oop_Relocation::spec(oop_index);
4031   code_section()->relocate(inst_mark(), rspec);
4032   movz(dst, 0xDEAD, 16);
4033   movk(dst, 0xBEEF);
4034 }
4035 
4036 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
4037   assert (UseCompressedClassPointers, "should only be used for compressed headers");
4038   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
4039   int index = oop_recorder()->find_index(k);
4040   assert(! Universe::heap()->is_in(k), "should not be an oop");
4041 
4042   InstructionMark im(this);
4043   RelocationHolder rspec = metadata_Relocation::spec(index);
4044   code_section()->relocate(inst_mark(), rspec);
4045   narrowKlass nk = CompressedKlassPointers::encode(k);
4046   movz(dst, (nk >> 16), 16);
4047   movk(dst, nk & 0xffff);
4048 }
4049 
4050 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators,
4051                                     Register dst, Address src,
4052                                     Register tmp1, Register thread_tmp) {
4053   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
4054   decorators = AccessInternal::decorator_fixup(decorators);
4055   bool as_raw = (decorators & AS_RAW) != 0;
4056   if (as_raw) {
4057     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
4058   } else {
4059     bs->load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
4060   }
4061 }
4062 
4063 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators,
4064                                      Address dst, Register src,
4065                                      Register tmp1, Register thread_tmp) {
4066   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
4067   decorators = AccessInternal::decorator_fixup(decorators);
4068   bool as_raw = (decorators & AS_RAW) != 0;
4069   if (as_raw) {
4070     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, src, tmp1, thread_tmp);
4071   } else {
4072     bs->store_at(this, decorators, type, dst, src, tmp1, thread_tmp);
4073   }
4074 }
4075 
4076 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
4077                                    Register thread_tmp, DecoratorSet decorators) {
4078   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, thread_tmp);
4079 }
4080 
4081 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
4082                                             Register thread_tmp, DecoratorSet decorators) {
4083   access_load_at(T_OBJECT, IN_HEAP | IS_NOT_NULL | decorators, dst, src, tmp1, thread_tmp);
4084 }
4085 
4086 void MacroAssembler::store_heap_oop(Address dst, Register src, Register tmp1,
4087                                     Register thread_tmp, DecoratorSet decorators) {
4088   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, thread_tmp);
4089 }
4090 
4091 // Used for storing NULLs.
4092 void MacroAssembler::store_heap_oop_null(Address dst) {
4093   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg);
4094 }
4095 
4096 Address MacroAssembler::allocate_metadata_address(Metadata* obj) {
4097   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
4098   int index = oop_recorder()->allocate_metadata_index(obj);
4099   RelocationHolder rspec = metadata_Relocation::spec(index);
4100   return Address((address)obj, rspec);
4101 }
4102 
4103 // Move an oop into a register.  immediate is true if we want
4104 // immediate instructions and nmethod entry barriers are not enabled.
4105 // i.e. we are not going to patch this instruction while the code is being
4106 // executed by another thread.
4107 void MacroAssembler::movoop(Register dst, jobject obj, bool immediate) {
4108   int oop_index;
4109   if (obj == NULL) {
4110     oop_index = oop_recorder()->allocate_oop_index(obj);
4111   } else {
4112 #ifdef ASSERT
4113     {
4114       ThreadInVMfromUnknown tiv;
4115       assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
4116     }
4117 #endif
4118     oop_index = oop_recorder()->find_index(obj);
4119   }
4120   RelocationHolder rspec = oop_Relocation::spec(oop_index);
4121 
4122   // nmethod entry barrier necessitate using the constant pool. They have to be
4123   // ordered with respected to oop accesses.
4124   // Using immediate literals would necessitate ISBs.
4125   if (BarrierSet::barrier_set()->barrier_set_nmethod() != NULL || !immediate) {
4126     address dummy = address(uintptr_t(pc()) & -wordSize); // A nearby aligned address
4127     ldr_constant(dst, Address(dummy, rspec));
4128   } else
4129     mov(dst, Address((address)obj, rspec));
4130 
4131 }
4132 
4133 // Move a metadata address into a register.
4134 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
4135   int oop_index;
4136   if (obj == NULL) {
4137     oop_index = oop_recorder()->allocate_metadata_index(obj);
4138   } else {
4139     oop_index = oop_recorder()->find_index(obj);
4140   }
4141   RelocationHolder rspec = metadata_Relocation::spec(oop_index);
4142   mov(dst, Address((address)obj, rspec));
4143 }
4144 
4145 Address MacroAssembler::constant_oop_address(jobject obj) {
4146 #ifdef ASSERT
4147   {
4148     ThreadInVMfromUnknown tiv;
4149     assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
4150     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "not an oop");
4151   }
4152 #endif
4153   int oop_index = oop_recorder()->find_index(obj);
4154   return Address((address)obj, oop_Relocation::spec(oop_index));
4155 }
4156 
4157 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
4158 void MacroAssembler::tlab_allocate(Register obj,
4159                                    Register var_size_in_bytes,
4160                                    int con_size_in_bytes,
4161                                    Register t1,
4162                                    Register t2,
4163                                    Label& slow_case) {
4164   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
4165   bs->tlab_allocate(this, obj, var_size_in_bytes, con_size_in_bytes, t1, t2, slow_case);
4166 }
4167 
4168 // Defines obj, preserves var_size_in_bytes
4169 void MacroAssembler::eden_allocate(Register obj,
4170                                    Register var_size_in_bytes,
4171                                    int con_size_in_bytes,
4172                                    Register t1,
4173                                    Label& slow_case) {
4174   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
4175   bs->eden_allocate(this, obj, var_size_in_bytes, con_size_in_bytes, t1, slow_case);
4176 }
4177 
4178 void MacroAssembler::verify_tlab() {
4179 #ifdef ASSERT
4180   if (UseTLAB && VerifyOops) {
4181     Label next, ok;
4182 
4183     stp(rscratch2, rscratch1, Address(pre(sp, -16)));
4184 
4185     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4186     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
4187     cmp(rscratch2, rscratch1);
4188     br(Assembler::HS, next);
4189     STOP("assert(top >= start)");
4190     should_not_reach_here();
4191 
4192     bind(next);
4193     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
4194     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4195     cmp(rscratch2, rscratch1);
4196     br(Assembler::HS, ok);
4197     STOP("assert(top <= end)");
4198     should_not_reach_here();
4199 
4200     bind(ok);
4201     ldp(rscratch2, rscratch1, Address(post(sp, 16)));
4202   }
4203 #endif
4204 }
4205 
4206 // Writes to stack successive pages until offset reached to check for
4207 // stack overflow + shadow pages.  This clobbers tmp.
4208 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
4209   assert_different_registers(tmp, size, rscratch1);
4210   mov(tmp, sp);
4211   // Bang stack for total size given plus shadow page size.
4212   // Bang one page at a time because large size can bang beyond yellow and
4213   // red zones.
4214   Label loop;
4215   mov(rscratch1, os::vm_page_size());
4216   bind(loop);
4217   lea(tmp, Address(tmp, -os::vm_page_size()));
4218   subsw(size, size, rscratch1);
4219   str(size, Address(tmp));
4220   br(Assembler::GT, loop);
4221 
4222   // Bang down shadow pages too.
4223   // At this point, (tmp-0) is the last address touched, so don't
4224   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
4225   // was post-decremented.)  Skip this address by starting at i=1, and
4226   // touch a few more pages below.  N.B.  It is important to touch all
4227   // the way down to and including i=StackShadowPages.
4228   for (int i = 0; i < (int)(StackOverflow::stack_shadow_zone_size() / os::vm_page_size()) - 1; i++) {
4229     // this could be any sized move but this is can be a debugging crumb
4230     // so the bigger the better.
4231     lea(tmp, Address(tmp, -os::vm_page_size()));
4232     str(size, Address(tmp));
4233   }
4234 }
4235 
4236 // Move the address of the polling page into dest.
4237 void MacroAssembler::get_polling_page(Register dest, relocInfo::relocType rtype) {
4238   ldr(dest, Address(rthread, JavaThread::polling_page_offset()));
4239 }
4240 
4241 // Read the polling page.  The address of the polling page must
4242 // already be in r.
4243 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
4244   address mark;
4245   {
4246     InstructionMark im(this);
4247     code_section()->relocate(inst_mark(), rtype);
4248     ldrw(zr, Address(r, 0));
4249     mark = inst_mark();
4250   }
4251   verify_cross_modify_fence_not_required();
4252   return mark;
4253 }
4254 
4255 void MacroAssembler::adrp(Register reg1, const Address &dest, uint64_t &byte_offset) {
4256   relocInfo::relocType rtype = dest.rspec().reloc()->type();
4257   uint64_t low_page = (uint64_t)CodeCache::low_bound() >> 12;
4258   uint64_t high_page = (uint64_t)(CodeCache::high_bound()-1) >> 12;
4259   uint64_t dest_page = (uint64_t)dest.target() >> 12;
4260   int64_t offset_low = dest_page - low_page;
4261   int64_t offset_high = dest_page - high_page;
4262 
4263   assert(is_valid_AArch64_address(dest.target()), "bad address");
4264   assert(dest.getMode() == Address::literal, "ADRP must be applied to a literal address");
4265 
4266   InstructionMark im(this);
4267   code_section()->relocate(inst_mark(), dest.rspec());
4268   // 8143067: Ensure that the adrp can reach the dest from anywhere within
4269   // the code cache so that if it is relocated we know it will still reach
4270   if (offset_high >= -(1<<20) && offset_low < (1<<20)) {
4271     _adrp(reg1, dest.target());
4272   } else {
4273     uint64_t target = (uint64_t)dest.target();
4274     uint64_t adrp_target
4275       = (target & 0xffffffffULL) | ((uint64_t)pc() & 0xffff00000000ULL);
4276 
4277     _adrp(reg1, (address)adrp_target);
4278     movk(reg1, target >> 32, 32);
4279   }
4280   byte_offset = (uint64_t)dest.target() & 0xfff;
4281 }
4282 
4283 void MacroAssembler::load_byte_map_base(Register reg) {
4284   CardTable::CardValue* byte_map_base =
4285     ((CardTableBarrierSet*)(BarrierSet::barrier_set()))->card_table()->byte_map_base();
4286 
4287   // Strictly speaking the byte_map_base isn't an address at all, and it might
4288   // even be negative. It is thus materialised as a constant.
4289   mov(reg, (uint64_t)byte_map_base);
4290 }
4291 
4292 void MacroAssembler::build_frame(int framesize) {
4293   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
4294   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
4295   if (framesize < ((1 << 9) + 2 * wordSize)) {
4296     sub(sp, sp, framesize);
4297     stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4298     if (PreserveFramePointer) add(rfp, sp, framesize - 2 * wordSize);
4299   } else {
4300     stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
4301     if (PreserveFramePointer) mov(rfp, sp);
4302     if (framesize < ((1 << 12) + 2 * wordSize))
4303       sub(sp, sp, framesize - 2 * wordSize);
4304     else {
4305       mov(rscratch1, framesize - 2 * wordSize);
4306       sub(sp, sp, rscratch1);
4307     }
4308   }
4309   verify_cross_modify_fence_not_required();
4310 }
4311 
4312 void MacroAssembler::remove_frame(int framesize) {
4313   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
4314   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
4315   if (framesize < ((1 << 9) + 2 * wordSize)) {
4316     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4317     add(sp, sp, framesize);
4318   } else {
4319     if (framesize < ((1 << 12) + 2 * wordSize))
4320       add(sp, sp, framesize - 2 * wordSize);
4321     else {
4322       mov(rscratch1, framesize - 2 * wordSize);
4323       add(sp, sp, rscratch1);
4324     }
4325     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
4326   }
4327 }
4328 
4329 
4330 // This method checks if provided byte array contains byte with highest bit set.
4331 address MacroAssembler::has_negatives(Register ary1, Register len, Register result) {
4332     // Simple and most common case of aligned small array which is not at the
4333     // end of memory page is placed here. All other cases are in stub.
4334     Label LOOP, END, STUB, STUB_LONG, SET_RESULT, DONE;
4335     const uint64_t UPPER_BIT_MASK=0x8080808080808080;
4336     assert_different_registers(ary1, len, result);
4337 
4338     cmpw(len, 0);
4339     br(LE, SET_RESULT);
4340     cmpw(len, 4 * wordSize);
4341     br(GE, STUB_LONG); // size > 32 then go to stub
4342 
4343     int shift = 64 - exact_log2(os::vm_page_size());
4344     lsl(rscratch1, ary1, shift);
4345     mov(rscratch2, (size_t)(4 * wordSize) << shift);
4346     adds(rscratch2, rscratch1, rscratch2);  // At end of page?
4347     br(CS, STUB); // at the end of page then go to stub
4348     subs(len, len, wordSize);
4349     br(LT, END);
4350 
4351   BIND(LOOP);
4352     ldr(rscratch1, Address(post(ary1, wordSize)));
4353     tst(rscratch1, UPPER_BIT_MASK);
4354     br(NE, SET_RESULT);
4355     subs(len, len, wordSize);
4356     br(GE, LOOP);
4357     cmpw(len, -wordSize);
4358     br(EQ, SET_RESULT);
4359 
4360   BIND(END);
4361     ldr(result, Address(ary1));
4362     sub(len, zr, len, LSL, 3); // LSL 3 is to get bits from bytes
4363     lslv(result, result, len);
4364     tst(result, UPPER_BIT_MASK);
4365     b(SET_RESULT);
4366 
4367   BIND(STUB);
4368     RuntimeAddress has_neg = RuntimeAddress(StubRoutines::aarch64::has_negatives());
4369     assert(has_neg.target() != NULL, "has_negatives stub has not been generated");
4370     address tpc1 = trampoline_call(has_neg);
4371     if (tpc1 == NULL) {
4372       DEBUG_ONLY(reset_labels(STUB_LONG, SET_RESULT, DONE));
4373       postcond(pc() == badAddress);
4374       return NULL;
4375     }
4376     b(DONE);
4377 
4378   BIND(STUB_LONG);
4379     RuntimeAddress has_neg_long = RuntimeAddress(StubRoutines::aarch64::has_negatives_long());
4380     assert(has_neg_long.target() != NULL, "has_negatives stub has not been generated");
4381     address tpc2 = trampoline_call(has_neg_long);
4382     if (tpc2 == NULL) {
4383       DEBUG_ONLY(reset_labels(SET_RESULT, DONE));
4384       postcond(pc() == badAddress);
4385       return NULL;
4386     }
4387     b(DONE);
4388 
4389   BIND(SET_RESULT);
4390     cset(result, NE); // set true or false
4391 
4392   BIND(DONE);
4393   postcond(pc() != badAddress);
4394   return pc();
4395 }
4396 
4397 address MacroAssembler::arrays_equals(Register a1, Register a2, Register tmp3,
4398                                       Register tmp4, Register tmp5, Register result,
4399                                       Register cnt1, int elem_size) {
4400   Label DONE, SAME;
4401   Register tmp1 = rscratch1;
4402   Register tmp2 = rscratch2;
4403   Register cnt2 = tmp2;  // cnt2 only used in array length compare
4404   int elem_per_word = wordSize/elem_size;
4405   int log_elem_size = exact_log2(elem_size);
4406   int length_offset = arrayOopDesc::length_offset_in_bytes();
4407   int base_offset
4408     = arrayOopDesc::base_offset_in_bytes(elem_size == 2 ? T_CHAR : T_BYTE);
4409   int stubBytesThreshold = 3 * 64 + (UseSIMDForArrayEquals ? 0 : 16);
4410 
4411   assert(elem_size == 1 || elem_size == 2, "must be char or byte");
4412   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
4413 
4414 #ifndef PRODUCT
4415   {
4416     const char kind = (elem_size == 2) ? 'U' : 'L';
4417     char comment[64];
4418     snprintf(comment, sizeof comment, "array_equals%c{", kind);
4419     BLOCK_COMMENT(comment);
4420   }
4421 #endif
4422 
4423   // if (a1 == a2)
4424   //     return true;
4425   cmpoop(a1, a2); // May have read barriers for a1 and a2.
4426   br(EQ, SAME);
4427 
4428   if (UseSimpleArrayEquals) {
4429     Label NEXT_WORD, SHORT, TAIL03, TAIL01, A_MIGHT_BE_NULL, A_IS_NOT_NULL;
4430     // if (a1 == null || a2 == null)
4431     //     return false;
4432     // a1 & a2 == 0 means (some-pointer is null) or
4433     // (very-rare-or-even-probably-impossible-pointer-values)
4434     // so, we can save one branch in most cases
4435     tst(a1, a2);
4436     mov(result, false);
4437     br(EQ, A_MIGHT_BE_NULL);
4438     // if (a1.length != a2.length)
4439     //      return false;
4440     bind(A_IS_NOT_NULL);
4441     ldrw(cnt1, Address(a1, length_offset));
4442     ldrw(cnt2, Address(a2, length_offset));
4443     eorw(tmp5, cnt1, cnt2);
4444     cbnzw(tmp5, DONE);
4445     lea(a1, Address(a1, base_offset));
4446     lea(a2, Address(a2, base_offset));
4447     // Check for short strings, i.e. smaller than wordSize.
4448     subs(cnt1, cnt1, elem_per_word);
4449     br(Assembler::LT, SHORT);
4450     // Main 8 byte comparison loop.
4451     bind(NEXT_WORD); {
4452       ldr(tmp1, Address(post(a1, wordSize)));
4453       ldr(tmp2, Address(post(a2, wordSize)));
4454       subs(cnt1, cnt1, elem_per_word);
4455       eor(tmp5, tmp1, tmp2);
4456       cbnz(tmp5, DONE);
4457     } br(GT, NEXT_WORD);
4458     // Last longword.  In the case where length == 4 we compare the
4459     // same longword twice, but that's still faster than another
4460     // conditional branch.
4461     // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
4462     // length == 4.
4463     if (log_elem_size > 0)
4464       lsl(cnt1, cnt1, log_elem_size);
4465     ldr(tmp3, Address(a1, cnt1));
4466     ldr(tmp4, Address(a2, cnt1));
4467     eor(tmp5, tmp3, tmp4);
4468     cbnz(tmp5, DONE);
4469     b(SAME);
4470     bind(A_MIGHT_BE_NULL);
4471     // in case both a1 and a2 are not-null, proceed with loads
4472     cbz(a1, DONE);
4473     cbz(a2, DONE);
4474     b(A_IS_NOT_NULL);
4475     bind(SHORT);
4476 
4477     tbz(cnt1, 2 - log_elem_size, TAIL03); // 0-7 bytes left.
4478     {
4479       ldrw(tmp1, Address(post(a1, 4)));
4480       ldrw(tmp2, Address(post(a2, 4)));
4481       eorw(tmp5, tmp1, tmp2);
4482       cbnzw(tmp5, DONE);
4483     }
4484     bind(TAIL03);
4485     tbz(cnt1, 1 - log_elem_size, TAIL01); // 0-3 bytes left.
4486     {
4487       ldrh(tmp3, Address(post(a1, 2)));
4488       ldrh(tmp4, Address(post(a2, 2)));
4489       eorw(tmp5, tmp3, tmp4);
4490       cbnzw(tmp5, DONE);
4491     }
4492     bind(TAIL01);
4493     if (elem_size == 1) { // Only needed when comparing byte arrays.
4494       tbz(cnt1, 0, SAME); // 0-1 bytes left.
4495       {
4496         ldrb(tmp1, a1);
4497         ldrb(tmp2, a2);
4498         eorw(tmp5, tmp1, tmp2);
4499         cbnzw(tmp5, DONE);
4500       }
4501     }
4502   } else {
4503     Label NEXT_DWORD, SHORT, TAIL, TAIL2, STUB,
4504         CSET_EQ, LAST_CHECK;
4505     mov(result, false);
4506     cbz(a1, DONE);
4507     ldrw(cnt1, Address(a1, length_offset));
4508     cbz(a2, DONE);
4509     ldrw(cnt2, Address(a2, length_offset));
4510     // on most CPUs a2 is still "locked"(surprisingly) in ldrw and it's
4511     // faster to perform another branch before comparing a1 and a2
4512     cmp(cnt1, (u1)elem_per_word);
4513     br(LE, SHORT); // short or same
4514     ldr(tmp3, Address(pre(a1, base_offset)));
4515     subs(zr, cnt1, stubBytesThreshold);
4516     br(GE, STUB);
4517     ldr(tmp4, Address(pre(a2, base_offset)));
4518     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
4519     cmp(cnt2, cnt1);
4520     br(NE, DONE);
4521 
4522     // Main 16 byte comparison loop with 2 exits
4523     bind(NEXT_DWORD); {
4524       ldr(tmp1, Address(pre(a1, wordSize)));
4525       ldr(tmp2, Address(pre(a2, wordSize)));
4526       subs(cnt1, cnt1, 2 * elem_per_word);
4527       br(LE, TAIL);
4528       eor(tmp4, tmp3, tmp4);
4529       cbnz(tmp4, DONE);
4530       ldr(tmp3, Address(pre(a1, wordSize)));
4531       ldr(tmp4, Address(pre(a2, wordSize)));
4532       cmp(cnt1, (u1)elem_per_word);
4533       br(LE, TAIL2);
4534       cmp(tmp1, tmp2);
4535     } br(EQ, NEXT_DWORD);
4536     b(DONE);
4537 
4538     bind(TAIL);
4539     eor(tmp4, tmp3, tmp4);
4540     eor(tmp2, tmp1, tmp2);
4541     lslv(tmp2, tmp2, tmp5);
4542     orr(tmp5, tmp4, tmp2);
4543     cmp(tmp5, zr);
4544     b(CSET_EQ);
4545 
4546     bind(TAIL2);
4547     eor(tmp2, tmp1, tmp2);
4548     cbnz(tmp2, DONE);
4549     b(LAST_CHECK);
4550 
4551     bind(STUB);
4552     ldr(tmp4, Address(pre(a2, base_offset)));
4553     cmp(cnt2, cnt1);
4554     br(NE, DONE);
4555     if (elem_size == 2) { // convert to byte counter
4556       lsl(cnt1, cnt1, 1);
4557     }
4558     eor(tmp5, tmp3, tmp4);
4559     cbnz(tmp5, DONE);
4560     RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_array_equals());
4561     assert(stub.target() != NULL, "array_equals_long stub has not been generated");
4562     address tpc = trampoline_call(stub);
4563     if (tpc == NULL) {
4564       DEBUG_ONLY(reset_labels(SHORT, LAST_CHECK, CSET_EQ, SAME, DONE));
4565       postcond(pc() == badAddress);
4566       return NULL;
4567     }
4568     b(DONE);
4569 
4570     // (a1 != null && a2 == null) || (a1 != null && a2 != null && a1 == a2)
4571     // so, if a2 == null => return false(0), else return true, so we can return a2
4572     mov(result, a2);
4573     b(DONE);
4574     bind(SHORT);
4575     cmp(cnt2, cnt1);
4576     br(NE, DONE);
4577     cbz(cnt1, SAME);
4578     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
4579     ldr(tmp3, Address(a1, base_offset));
4580     ldr(tmp4, Address(a2, base_offset));
4581     bind(LAST_CHECK);
4582     eor(tmp4, tmp3, tmp4);
4583     lslv(tmp5, tmp4, tmp5);
4584     cmp(tmp5, zr);
4585     bind(CSET_EQ);
4586     cset(result, EQ);
4587     b(DONE);
4588   }
4589 
4590   bind(SAME);
4591   mov(result, true);
4592   // That's it.
4593   bind(DONE);
4594 
4595   BLOCK_COMMENT("} array_equals");
4596   postcond(pc() != badAddress);
4597   return pc();
4598 }
4599 
4600 // Compare Strings
4601 
4602 // For Strings we're passed the address of the first characters in a1
4603 // and a2 and the length in cnt1.
4604 // elem_size is the element size in bytes: either 1 or 2.
4605 // There are two implementations.  For arrays >= 8 bytes, all
4606 // comparisons (including the final one, which may overlap) are
4607 // performed 8 bytes at a time.  For strings < 8 bytes, we compare a
4608 // halfword, then a short, and then a byte.
4609 
4610 void MacroAssembler::string_equals(Register a1, Register a2,
4611                                    Register result, Register cnt1, int elem_size)
4612 {
4613   Label SAME, DONE, SHORT, NEXT_WORD;
4614   Register tmp1 = rscratch1;
4615   Register tmp2 = rscratch2;
4616   Register cnt2 = tmp2;  // cnt2 only used in array length compare
4617 
4618   assert(elem_size == 1 || elem_size == 2, "must be 2 or 1 byte");
4619   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
4620 
4621 #ifndef PRODUCT
4622   {
4623     const char kind = (elem_size == 2) ? 'U' : 'L';
4624     char comment[64];
4625     snprintf(comment, sizeof comment, "{string_equals%c", kind);
4626     BLOCK_COMMENT(comment);
4627   }
4628 #endif
4629 
4630   mov(result, false);
4631 
4632   // Check for short strings, i.e. smaller than wordSize.
4633   subs(cnt1, cnt1, wordSize);
4634   br(Assembler::LT, SHORT);
4635   // Main 8 byte comparison loop.
4636   bind(NEXT_WORD); {
4637     ldr(tmp1, Address(post(a1, wordSize)));
4638     ldr(tmp2, Address(post(a2, wordSize)));
4639     subs(cnt1, cnt1, wordSize);
4640     eor(tmp1, tmp1, tmp2);
4641     cbnz(tmp1, DONE);
4642   } br(GT, NEXT_WORD);
4643   // Last longword.  In the case where length == 4 we compare the
4644   // same longword twice, but that's still faster than another
4645   // conditional branch.
4646   // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
4647   // length == 4.
4648   ldr(tmp1, Address(a1, cnt1));
4649   ldr(tmp2, Address(a2, cnt1));
4650   eor(tmp2, tmp1, tmp2);
4651   cbnz(tmp2, DONE);
4652   b(SAME);
4653 
4654   bind(SHORT);
4655   Label TAIL03, TAIL01;
4656 
4657   tbz(cnt1, 2, TAIL03); // 0-7 bytes left.
4658   {
4659     ldrw(tmp1, Address(post(a1, 4)));
4660     ldrw(tmp2, Address(post(a2, 4)));
4661     eorw(tmp1, tmp1, tmp2);
4662     cbnzw(tmp1, DONE);
4663   }
4664   bind(TAIL03);
4665   tbz(cnt1, 1, TAIL01); // 0-3 bytes left.
4666   {
4667     ldrh(tmp1, Address(post(a1, 2)));
4668     ldrh(tmp2, Address(post(a2, 2)));
4669     eorw(tmp1, tmp1, tmp2);
4670     cbnzw(tmp1, DONE);
4671   }
4672   bind(TAIL01);
4673   if (elem_size == 1) { // Only needed when comparing 1-byte elements
4674     tbz(cnt1, 0, SAME); // 0-1 bytes left.
4675     {
4676       ldrb(tmp1, a1);
4677       ldrb(tmp2, a2);
4678       eorw(tmp1, tmp1, tmp2);
4679       cbnzw(tmp1, DONE);
4680     }
4681   }
4682   // Arrays are equal.
4683   bind(SAME);
4684   mov(result, true);
4685 
4686   // That's it.
4687   bind(DONE);
4688   BLOCK_COMMENT("} string_equals");
4689 }
4690 
4691 
4692 // The size of the blocks erased by the zero_blocks stub.  We must
4693 // handle anything smaller than this ourselves in zero_words().
4694 const int MacroAssembler::zero_words_block_size = 8;
4695 
4696 // zero_words() is used by C2 ClearArray patterns and by
4697 // C1_MacroAssembler.  It is as small as possible, handling small word
4698 // counts locally and delegating anything larger to the zero_blocks
4699 // stub.  It is expanded many times in compiled code, so it is
4700 // important to keep it short.
4701 
4702 // ptr:   Address of a buffer to be zeroed.
4703 // cnt:   Count in HeapWords.
4704 //
4705 // ptr, cnt, rscratch1, and rscratch2 are clobbered.
4706 address MacroAssembler::zero_words(Register ptr, Register cnt)
4707 {
4708   assert(is_power_of_2(zero_words_block_size), "adjust this");
4709 
4710   BLOCK_COMMENT("zero_words {");
4711   assert(ptr == r10 && cnt == r11, "mismatch in register usage");
4712   RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
4713   assert(zero_blocks.target() != NULL, "zero_blocks stub has not been generated");
4714 
4715   subs(rscratch1, cnt, zero_words_block_size);
4716   Label around;
4717   br(LO, around);
4718   {
4719     RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
4720     assert(zero_blocks.target() != NULL, "zero_blocks stub has not been generated");
4721     // Make sure this is a C2 compilation. C1 allocates space only for
4722     // trampoline stubs generated by Call LIR ops, and in any case it
4723     // makes sense for a C1 compilation task to proceed as quickly as
4724     // possible.
4725     CompileTask* task;
4726     if (StubRoutines::aarch64::complete()
4727         && Thread::current()->is_Compiler_thread()
4728         && (task = ciEnv::current()->task())
4729         && is_c2_compile(task->comp_level())) {
4730       address tpc = trampoline_call(zero_blocks);
4731       if (tpc == NULL) {
4732         DEBUG_ONLY(reset_labels(around));
4733         assert(false, "failed to allocate space for trampoline");
4734         return NULL;
4735       }
4736     } else {
4737       far_call(zero_blocks);
4738     }
4739   }
4740   bind(around);
4741 
4742   // We have a few words left to do. zero_blocks has adjusted r10 and r11
4743   // for us.
4744   for (int i = zero_words_block_size >> 1; i > 1; i >>= 1) {
4745     Label l;
4746     tbz(cnt, exact_log2(i), l);
4747     for (int j = 0; j < i; j += 2) {
4748       stp(zr, zr, post(ptr, 2 * BytesPerWord));
4749     }
4750     bind(l);
4751   }
4752   {
4753     Label l;
4754     tbz(cnt, 0, l);
4755     str(zr, Address(ptr));
4756     bind(l);
4757   }
4758 
4759   BLOCK_COMMENT("} zero_words");
4760   return pc();
4761 }
4762 
4763 // base:         Address of a buffer to be zeroed, 8 bytes aligned.
4764 // cnt:          Immediate count in HeapWords.
4765 //
4766 // r10, r11, rscratch1, and rscratch2 are clobbered.
4767 void MacroAssembler::zero_words(Register base, uint64_t cnt)
4768 {
4769   guarantee(zero_words_block_size < BlockZeroingLowLimit,
4770             "increase BlockZeroingLowLimit");
4771   if (cnt <= (uint64_t)BlockZeroingLowLimit / BytesPerWord) {
4772 #ifndef PRODUCT
4773     {
4774       char buf[64];
4775       snprintf(buf, sizeof buf, "zero_words (count = %" PRIu64 ") {", cnt);
4776       BLOCK_COMMENT(buf);
4777     }
4778 #endif
4779     if (cnt >= 16) {
4780       uint64_t loops = cnt/16;
4781       if (loops > 1) {
4782         mov(rscratch2, loops - 1);
4783       }
4784       {
4785         Label loop;
4786         bind(loop);
4787         for (int i = 0; i < 16; i += 2) {
4788           stp(zr, zr, Address(base, i * BytesPerWord));
4789         }
4790         add(base, base, 16 * BytesPerWord);
4791         if (loops > 1) {
4792           subs(rscratch2, rscratch2, 1);
4793           br(GE, loop);
4794         }
4795       }
4796     }
4797     cnt %= 16;
4798     int i = cnt & 1;  // store any odd word to start
4799     if (i) str(zr, Address(base));
4800     for (; i < (int)cnt; i += 2) {
4801       stp(zr, zr, Address(base, i * wordSize));
4802     }
4803     BLOCK_COMMENT("} zero_words");
4804   } else {
4805     mov(r10, base); mov(r11, cnt);
4806     zero_words(r10, r11);
4807   }
4808 }
4809 
4810 // Zero blocks of memory by using DC ZVA.
4811 //
4812 // Aligns the base address first sufficently for DC ZVA, then uses
4813 // DC ZVA repeatedly for every full block.  cnt is the size to be
4814 // zeroed in HeapWords.  Returns the count of words left to be zeroed
4815 // in cnt.
4816 //
4817 // NOTE: This is intended to be used in the zero_blocks() stub.  If
4818 // you want to use it elsewhere, note that cnt must be >= 2*zva_length.
4819 void MacroAssembler::zero_dcache_blocks(Register base, Register cnt) {
4820   Register tmp = rscratch1;
4821   Register tmp2 = rscratch2;
4822   int zva_length = VM_Version::zva_length();
4823   Label initial_table_end, loop_zva;
4824   Label fini;
4825 
4826   // Base must be 16 byte aligned. If not just return and let caller handle it
4827   tst(base, 0x0f);
4828   br(Assembler::NE, fini);
4829   // Align base with ZVA length.
4830   neg(tmp, base);
4831   andr(tmp, tmp, zva_length - 1);
4832 
4833   // tmp: the number of bytes to be filled to align the base with ZVA length.
4834   add(base, base, tmp);
4835   sub(cnt, cnt, tmp, Assembler::ASR, 3);
4836   adr(tmp2, initial_table_end);
4837   sub(tmp2, tmp2, tmp, Assembler::LSR, 2);
4838   br(tmp2);
4839 
4840   for (int i = -zva_length + 16; i < 0; i += 16)
4841     stp(zr, zr, Address(base, i));
4842   bind(initial_table_end);
4843 
4844   sub(cnt, cnt, zva_length >> 3);
4845   bind(loop_zva);
4846   dc(Assembler::ZVA, base);
4847   subs(cnt, cnt, zva_length >> 3);
4848   add(base, base, zva_length);
4849   br(Assembler::GE, loop_zva);
4850   add(cnt, cnt, zva_length >> 3); // count not zeroed by DC ZVA
4851   bind(fini);
4852 }
4853 
4854 // base:   Address of a buffer to be filled, 8 bytes aligned.
4855 // cnt:    Count in 8-byte unit.
4856 // value:  Value to be filled with.
4857 // base will point to the end of the buffer after filling.
4858 void MacroAssembler::fill_words(Register base, Register cnt, Register value)
4859 {
4860 //  Algorithm:
4861 //
4862 //    if (cnt == 0) {
4863 //      return;
4864 //    }
4865 //    if ((p & 8) != 0) {
4866 //      *p++ = v;
4867 //    }
4868 //
4869 //    scratch1 = cnt & 14;
4870 //    cnt -= scratch1;
4871 //    p += scratch1;
4872 //    switch (scratch1 / 2) {
4873 //      do {
4874 //        cnt -= 16;
4875 //          p[-16] = v;
4876 //          p[-15] = v;
4877 //        case 7:
4878 //          p[-14] = v;
4879 //          p[-13] = v;
4880 //        case 6:
4881 //          p[-12] = v;
4882 //          p[-11] = v;
4883 //          // ...
4884 //        case 1:
4885 //          p[-2] = v;
4886 //          p[-1] = v;
4887 //        case 0:
4888 //          p += 16;
4889 //      } while (cnt);
4890 //    }
4891 //    if ((cnt & 1) == 1) {
4892 //      *p++ = v;
4893 //    }
4894 
4895   assert_different_registers(base, cnt, value, rscratch1, rscratch2);
4896 
4897   Label fini, skip, entry, loop;
4898   const int unroll = 8; // Number of stp instructions we'll unroll
4899 
4900   cbz(cnt, fini);
4901   tbz(base, 3, skip);
4902   str(value, Address(post(base, 8)));
4903   sub(cnt, cnt, 1);
4904   bind(skip);
4905 
4906   andr(rscratch1, cnt, (unroll-1) * 2);
4907   sub(cnt, cnt, rscratch1);
4908   add(base, base, rscratch1, Assembler::LSL, 3);
4909   adr(rscratch2, entry);
4910   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 1);
4911   br(rscratch2);
4912 
4913   bind(loop);
4914   add(base, base, unroll * 16);
4915   for (int i = -unroll; i < 0; i++)
4916     stp(value, value, Address(base, i * 16));
4917   bind(entry);
4918   subs(cnt, cnt, unroll * 2);
4919   br(Assembler::GE, loop);
4920 
4921   tbz(cnt, 0, fini);
4922   str(value, Address(post(base, 8)));
4923   bind(fini);
4924 }
4925 
4926 // Intrinsic for sun/nio/cs/ISO_8859_1$Encoder.implEncodeISOArray and
4927 // java/lang/StringUTF16.compress.
4928 void MacroAssembler::encode_iso_array(Register src, Register dst,
4929                       Register len, Register result,
4930                       FloatRegister Vtmp1, FloatRegister Vtmp2,
4931                       FloatRegister Vtmp3, FloatRegister Vtmp4)
4932 {
4933     Label DONE, SET_RESULT, NEXT_32, NEXT_32_PRFM, LOOP_8, NEXT_8, LOOP_1, NEXT_1,
4934         NEXT_32_START, NEXT_32_PRFM_START;
4935     Register tmp1 = rscratch1, tmp2 = rscratch2;
4936 
4937       mov(result, len); // Save initial len
4938 
4939       cmp(len, (u1)8); // handle shortest strings first
4940       br(LT, LOOP_1);
4941       cmp(len, (u1)32);
4942       br(LT, NEXT_8);
4943       // The following code uses the SIMD 'uzp1' and 'uzp2' instructions
4944       // to convert chars to bytes
4945       if (SoftwarePrefetchHintDistance >= 0) {
4946         ld1(Vtmp1, Vtmp2, Vtmp3, Vtmp4, T8H, src);
4947         subs(tmp2, len, SoftwarePrefetchHintDistance/2 + 16);
4948         br(LE, NEXT_32_START);
4949         b(NEXT_32_PRFM_START);
4950         BIND(NEXT_32_PRFM);
4951           ld1(Vtmp1, Vtmp2, Vtmp3, Vtmp4, T8H, src);
4952         BIND(NEXT_32_PRFM_START);
4953           prfm(Address(src, SoftwarePrefetchHintDistance));
4954           orr(v4, T16B, Vtmp1, Vtmp2);
4955           orr(v5, T16B, Vtmp3, Vtmp4);
4956           uzp1(Vtmp1, T16B, Vtmp1, Vtmp2);
4957           uzp1(Vtmp3, T16B, Vtmp3, Vtmp4);
4958           uzp2(v5, T16B, v4, v5); // high bytes
4959           umov(tmp2, v5, D, 1);
4960           fmovd(tmp1, v5);
4961           orr(tmp1, tmp1, tmp2);
4962           cbnz(tmp1, LOOP_8);
4963           stpq(Vtmp1, Vtmp3, dst);
4964           sub(len, len, 32);
4965           add(dst, dst, 32);
4966           add(src, src, 64);
4967           subs(tmp2, len, SoftwarePrefetchHintDistance/2 + 16);
4968           br(GE, NEXT_32_PRFM);
4969           cmp(len, (u1)32);
4970           br(LT, LOOP_8);
4971         BIND(NEXT_32);
4972           ld1(Vtmp1, Vtmp2, Vtmp3, Vtmp4, T8H, src);
4973         BIND(NEXT_32_START);
4974       } else {
4975         BIND(NEXT_32);
4976           ld1(Vtmp1, Vtmp2, Vtmp3, Vtmp4, T8H, src);
4977       }
4978       prfm(Address(src, SoftwarePrefetchHintDistance));
4979       uzp1(v4, T16B, Vtmp1, Vtmp2);
4980       uzp1(v5, T16B, Vtmp3, Vtmp4);
4981       orr(Vtmp1, T16B, Vtmp1, Vtmp2);
4982       orr(Vtmp3, T16B, Vtmp3, Vtmp4);
4983       uzp2(Vtmp1, T16B, Vtmp1, Vtmp3); // high bytes
4984       umov(tmp2, Vtmp1, D, 1);
4985       fmovd(tmp1, Vtmp1);
4986       orr(tmp1, tmp1, tmp2);
4987       cbnz(tmp1, LOOP_8);
4988       stpq(v4, v5, dst);
4989       sub(len, len, 32);
4990       add(dst, dst, 32);
4991       add(src, src, 64);
4992       cmp(len, (u1)32);
4993       br(GE, NEXT_32);
4994       cbz(len, DONE);
4995 
4996     BIND(LOOP_8);
4997       cmp(len, (u1)8);
4998       br(LT, LOOP_1);
4999     BIND(NEXT_8);
5000       ld1(Vtmp1, T8H, src);
5001       uzp1(Vtmp2, T16B, Vtmp1, Vtmp1); // low bytes
5002       uzp2(Vtmp3, T16B, Vtmp1, Vtmp1); // high bytes
5003       fmovd(tmp1, Vtmp3);
5004       cbnz(tmp1, NEXT_1);
5005       strd(Vtmp2, dst);
5006 
5007       sub(len, len, 8);
5008       add(dst, dst, 8);
5009       add(src, src, 16);
5010       cmp(len, (u1)8);
5011       br(GE, NEXT_8);
5012 
5013     BIND(LOOP_1);
5014 
5015     cbz(len, DONE);
5016     BIND(NEXT_1);
5017       ldrh(tmp1, Address(post(src, 2)));
5018       tst(tmp1, 0xff00);
5019       br(NE, SET_RESULT);
5020       strb(tmp1, Address(post(dst, 1)));
5021       subs(len, len, 1);
5022       br(GT, NEXT_1);
5023 
5024     BIND(SET_RESULT);
5025       sub(result, result, len); // Return index where we stopped
5026                                 // Return len == 0 if we processed all
5027                                 // characters
5028     BIND(DONE);
5029 }
5030 
5031 
5032 // Inflate byte[] array to char[].
5033 address MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
5034                                            FloatRegister vtmp1, FloatRegister vtmp2,
5035                                            FloatRegister vtmp3, Register tmp4) {
5036   Label big, done, after_init, to_stub;
5037 
5038   assert_different_registers(src, dst, len, tmp4, rscratch1);
5039 
5040   fmovd(vtmp1, 0.0);
5041   lsrw(tmp4, len, 3);
5042   bind(after_init);
5043   cbnzw(tmp4, big);
5044   // Short string: less than 8 bytes.
5045   {
5046     Label loop, tiny;
5047 
5048     cmpw(len, 4);
5049     br(LT, tiny);
5050     // Use SIMD to do 4 bytes.
5051     ldrs(vtmp2, post(src, 4));
5052     zip1(vtmp3, T8B, vtmp2, vtmp1);
5053     subw(len, len, 4);
5054     strd(vtmp3, post(dst, 8));
5055 
5056     cbzw(len, done);
5057 
5058     // Do the remaining bytes by steam.
5059     bind(loop);
5060     ldrb(tmp4, post(src, 1));
5061     strh(tmp4, post(dst, 2));
5062     subw(len, len, 1);
5063 
5064     bind(tiny);
5065     cbnz(len, loop);
5066 
5067     b(done);
5068   }
5069 
5070   if (SoftwarePrefetchHintDistance >= 0) {
5071     bind(to_stub);
5072       RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_byte_array_inflate());
5073       assert(stub.target() != NULL, "large_byte_array_inflate stub has not been generated");
5074       address tpc = trampoline_call(stub);
5075       if (tpc == NULL) {
5076         DEBUG_ONLY(reset_labels(big, done));
5077         postcond(pc() == badAddress);
5078         return NULL;
5079       }
5080       b(after_init);
5081   }
5082 
5083   // Unpack the bytes 8 at a time.
5084   bind(big);
5085   {
5086     Label loop, around, loop_last, loop_start;
5087 
5088     if (SoftwarePrefetchHintDistance >= 0) {
5089       const int large_loop_threshold = (64 + 16)/8;
5090       ldrd(vtmp2, post(src, 8));
5091       andw(len, len, 7);
5092       cmp(tmp4, (u1)large_loop_threshold);
5093       br(GE, to_stub);
5094       b(loop_start);
5095 
5096       bind(loop);
5097       ldrd(vtmp2, post(src, 8));
5098       bind(loop_start);
5099       subs(tmp4, tmp4, 1);
5100       br(EQ, loop_last);
5101       zip1(vtmp2, T16B, vtmp2, vtmp1);
5102       ldrd(vtmp3, post(src, 8));
5103       st1(vtmp2, T8H, post(dst, 16));
5104       subs(tmp4, tmp4, 1);
5105       zip1(vtmp3, T16B, vtmp3, vtmp1);
5106       st1(vtmp3, T8H, post(dst, 16));
5107       br(NE, loop);
5108       b(around);
5109       bind(loop_last);
5110       zip1(vtmp2, T16B, vtmp2, vtmp1);
5111       st1(vtmp2, T8H, post(dst, 16));
5112       bind(around);
5113       cbz(len, done);
5114     } else {
5115       andw(len, len, 7);
5116       bind(loop);
5117       ldrd(vtmp2, post(src, 8));
5118       sub(tmp4, tmp4, 1);
5119       zip1(vtmp3, T16B, vtmp2, vtmp1);
5120       st1(vtmp3, T8H, post(dst, 16));
5121       cbnz(tmp4, loop);
5122     }
5123   }
5124 
5125   // Do the tail of up to 8 bytes.
5126   add(src, src, len);
5127   ldrd(vtmp3, Address(src, -8));
5128   add(dst, dst, len, ext::uxtw, 1);
5129   zip1(vtmp3, T16B, vtmp3, vtmp1);
5130   strq(vtmp3, Address(dst, -16));
5131 
5132   bind(done);
5133   postcond(pc() != badAddress);
5134   return pc();
5135 }
5136 
5137 // Compress char[] array to byte[].
5138 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
5139                                          FloatRegister tmp1Reg, FloatRegister tmp2Reg,
5140                                          FloatRegister tmp3Reg, FloatRegister tmp4Reg,
5141                                          Register result) {
5142   encode_iso_array(src, dst, len, result,
5143                    tmp1Reg, tmp2Reg, tmp3Reg, tmp4Reg);
5144   cmp(len, zr);
5145   csel(result, result, zr, EQ);
5146 }
5147 
5148 // get_thread() can be called anywhere inside generated code so we
5149 // need to save whatever non-callee save context might get clobbered
5150 // by the call to JavaThread::aarch64_get_thread_helper() or, indeed,
5151 // the call setup code.
5152 //
5153 // On Linux, aarch64_get_thread_helper() clobbers only r0, r1, and flags.
5154 // On other systems, the helper is a usual C function.
5155 //
5156 void MacroAssembler::get_thread(Register dst) {
5157   RegSet saved_regs =
5158     LINUX_ONLY(RegSet::range(r0, r1)  + lr - dst)
5159     NOT_LINUX (RegSet::range(r0, r17) + lr - dst);
5160 
5161   push(saved_regs, sp);
5162 
5163   mov(lr, CAST_FROM_FN_PTR(address, JavaThread::aarch64_get_thread_helper));
5164   blr(lr);
5165   if (dst != c_rarg0) {
5166     mov(dst, c_rarg0);
5167   }
5168 
5169   pop(saved_regs, sp);
5170 }
5171 
5172 void MacroAssembler::cache_wb(Address line) {
5173   assert(line.getMode() == Address::base_plus_offset, "mode should be base_plus_offset");
5174   assert(line.index() == noreg, "index should be noreg");
5175   assert(line.offset() == 0, "offset should be 0");
5176   // would like to assert this
5177   // assert(line._ext.shift == 0, "shift should be zero");
5178   if (VM_Version::features() & VM_Version::CPU_DCPOP) {
5179     // writeback using clear virtual address to point of persistence
5180     dc(Assembler::CVAP, line.base());
5181   } else {
5182     // no need to generate anything as Unsafe.writebackMemory should
5183     // never invoke this stub
5184   }
5185 }
5186 
5187 void MacroAssembler::cache_wbsync(bool is_pre) {
5188   // we only need a barrier post sync
5189   if (!is_pre) {
5190     membar(Assembler::AnyAny);
5191   }
5192 }
5193 
5194 void MacroAssembler::verify_sve_vector_length() {
5195   // Make sure that native code does not change SVE vector length.
5196   if (!UseSVE) return;
5197   Label verify_ok;
5198   movw(rscratch1, zr);
5199   sve_inc(rscratch1, B);
5200   subsw(zr, rscratch1, VM_Version::get_initial_sve_vector_length());
5201   br(EQ, verify_ok);
5202   stop("Error: SVE vector length has changed since jvm startup");
5203   bind(verify_ok);
5204 }
5205 
5206 void MacroAssembler::verify_ptrue() {
5207   Label verify_ok;
5208   if (!UseSVE) {
5209     return;
5210   }
5211   sve_cntp(rscratch1, B, ptrue, ptrue); // get true elements count.
5212   sve_dec(rscratch1, B);
5213   cbz(rscratch1, verify_ok);
5214   stop("Error: the preserved predicate register (p7) elements are not all true");
5215   bind(verify_ok);
5216 }
5217 
5218 void MacroAssembler::safepoint_isb() {
5219   isb();
5220 #ifndef PRODUCT
5221   if (VerifyCrossModifyFence) {
5222     // Clear the thread state.
5223     strb(zr, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
5224   }
5225 #endif
5226 }
5227 
5228 #ifndef PRODUCT
5229 void MacroAssembler::verify_cross_modify_fence_not_required() {
5230   if (VerifyCrossModifyFence) {
5231     // Check if thread needs a cross modify fence.
5232     ldrb(rscratch1, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
5233     Label fence_not_required;
5234     cbz(rscratch1, fence_not_required);
5235     // If it does then fail.
5236     lea(rscratch1, CAST_FROM_FN_PTR(address, JavaThread::verify_cross_modify_fence_failure));
5237     mov(c_rarg0, rthread);
5238     blr(rscratch1);
5239     bind(fence_not_required);
5240   }
5241 }
5242 #endif
5243 
5244 void MacroAssembler::spin_wait() {
5245   for (int i = 0; i < VM_Version::spin_wait_desc().inst_count(); ++i) {
5246     switch (VM_Version::spin_wait_desc().inst()) {
5247       case SpinWait::NOP:
5248         nop();
5249         break;
5250       case SpinWait::ISB:
5251         isb();
5252         break;
5253       case SpinWait::YIELD:
5254         yield();
5255         break;
5256       default:
5257         ShouldNotReachHere();
5258     }
5259   }
5260 }