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