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/ciEnv.hpp"
  33 #include "gc/shared/barrierSet.hpp"
  34 #include "gc/shared/barrierSetAssembler.hpp"
  35 #include "gc/shared/cardTableBarrierSet.hpp"
  36 #include "gc/shared/cardTable.hpp"
  37 #include "gc/shared/collectedHeap.hpp"
  38 #include "gc/shared/tlab_globals.hpp"
  39 #include "interpreter/bytecodeHistogram.hpp"
  40 #include "interpreter/interpreter.hpp"
  41 #include "compiler/compileTask.hpp"
  42 #include "compiler/disassembler.hpp"
  43 #include "memory/resourceArea.hpp"
  44 #include "memory/universe.hpp"
  45 #include "nativeInst_aarch64.hpp"
  46 #include "oops/accessDecorators.hpp"
  47 #include "oops/compressedOops.inline.hpp"
  48 #include "oops/klass.inline.hpp"
  49 #include "runtime/biasedLocking.hpp"
  50 #include "runtime/icache.hpp"
  51 #include "runtime/interfaceSupport.inline.hpp"
  52 #include "runtime/jniHandles.inline.hpp"
  53 #include "runtime/objectMonitor.hpp"
  54 #include "runtime/sharedRuntime.hpp"
  55 #include "runtime/stubRoutines.hpp"
  56 #include "runtime/thread.hpp"
  57 #include "utilities/powerOfTwo.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 static inline bool target_needs_far_branch(address addr) {
 389   // codecache size <= 128M
 390   if (!MacroAssembler::far_branches()) {
 391     return false;
 392   }
 393   // codecache size > 240M
 394   if (MacroAssembler::codestub_branch_needs_far_jump()) {
 395     return true;
 396   }
 397   // codecache size: 128M..240M
 398   return !CodeCache::is_non_nmethod(addr);
 399 }
 400 
 401 void MacroAssembler::far_call(Address entry, CodeBuffer *cbuf, Register tmp) {
 402   assert(ReservedCodeCacheSize < 4*G, "branch out of range");
 403   assert(CodeCache::find_blob(entry.target()) != NULL,
 404          "destination of far call not found in code cache");
 405   if (target_needs_far_branch(entry.target())) {
 406     uint64_t offset;
 407     // We can use ADRP here because we know that the total size of
 408     // the code cache cannot exceed 2Gb (ADRP limit is 4GB).
 409     adrp(tmp, entry, offset);
 410     add(tmp, tmp, offset);
 411     if (cbuf) cbuf->set_insts_mark();
 412     blr(tmp);
 413   } else {
 414     if (cbuf) cbuf->set_insts_mark();
 415     bl(entry);
 416   }
 417 }
 418 
 419 int MacroAssembler::far_jump(Address entry, CodeBuffer *cbuf, Register tmp) {
 420   assert(ReservedCodeCacheSize < 4*G, "branch out of range");
 421   assert(CodeCache::find_blob(entry.target()) != NULL,
 422          "destination of far call not found in code cache");
 423   address start = pc();
 424   if (target_needs_far_branch(entry.target())) {
 425     uint64_t offset;
 426     // We can use ADRP here because we know that the total size of
 427     // the code cache cannot exceed 2Gb (ADRP limit is 4GB).
 428     adrp(tmp, entry, offset);
 429     add(tmp, tmp, offset);
 430     if (cbuf) cbuf->set_insts_mark();
 431     br(tmp);
 432   } else {
 433     if (cbuf) cbuf->set_insts_mark();
 434     b(entry);
 435   }
 436   return pc() - start;
 437 }
 438 
 439 void MacroAssembler::reserved_stack_check() {
 440     // testing if reserved zone needs to be enabled
 441     Label no_reserved_zone_enabling;
 442 
 443     ldr(rscratch1, Address(rthread, JavaThread::reserved_stack_activation_offset()));
 444     cmp(sp, rscratch1);
 445     br(Assembler::LO, no_reserved_zone_enabling);
 446 
 447     enter();   // LR and FP are live.
 448     lea(rscratch1, CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone));
 449     mov(c_rarg0, rthread);
 450     blr(rscratch1);
 451     leave();
 452 
 453     // We have already removed our own frame.
 454     // throw_delayed_StackOverflowError will think that it's been
 455     // called by our caller.
 456     lea(rscratch1, RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
 457     br(rscratch1);
 458     should_not_reach_here();
 459 
 460     bind(no_reserved_zone_enabling);
 461 }
 462 
 463 void MacroAssembler::biased_locking_enter(Register lock_reg,
 464                                           Register obj_reg,
 465                                           Register swap_reg,
 466                                           Register tmp_reg,
 467                                           bool swap_reg_contains_mark,
 468                                           Label& done,
 469                                           Label* slow_case,
 470                                           BiasedLockingCounters* counters) {
 471   assert(UseBiasedLocking, "why call this otherwise?");
 472   assert_different_registers(lock_reg, obj_reg, swap_reg);
 473 
 474   if (PrintBiasedLockingStatistics && counters == NULL)
 475     counters = BiasedLocking::counters();
 476 
 477   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg, rscratch1, rscratch2, noreg);
 478   assert(markWord::age_shift == markWord::lock_bits + markWord::biased_lock_bits, "biased locking makes assumptions about bit layout");
 479   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
 480   Address klass_addr     (obj_reg, oopDesc::klass_offset_in_bytes());
 481   Address saved_mark_addr(lock_reg, 0);
 482 
 483   // Biased locking
 484   // See whether the lock is currently biased toward our thread and
 485   // whether the epoch is still valid
 486   // Note that the runtime guarantees sufficient alignment of JavaThread
 487   // pointers to allow age to be placed into low bits
 488   // First check to see whether biasing is even enabled for this object
 489   Label cas_label;
 490   if (!swap_reg_contains_mark) {
 491     ldr(swap_reg, mark_addr);
 492   }
 493   andr(tmp_reg, swap_reg, markWord::biased_lock_mask_in_place);
 494   cmp(tmp_reg, (u1)markWord::biased_lock_pattern);
 495   br(Assembler::NE, cas_label);
 496   // The bias pattern is present in the object's header. Need to check
 497   // whether the bias owner and the epoch are both still current.
 498   load_prototype_header(tmp_reg, obj_reg);
 499   orr(tmp_reg, tmp_reg, rthread);
 500   eor(tmp_reg, swap_reg, tmp_reg);
 501   andr(tmp_reg, tmp_reg, ~((int) markWord::age_mask_in_place));
 502   if (counters != NULL) {
 503     Label around;
 504     cbnz(tmp_reg, around);
 505     atomic_incw(Address((address)counters->biased_lock_entry_count_addr()), tmp_reg, rscratch1, rscratch2);
 506     b(done);
 507     bind(around);
 508   } else {
 509     cbz(tmp_reg, done);
 510   }
 511 
 512   Label try_revoke_bias;
 513   Label try_rebias;
 514 
 515   // At this point we know that the header has the bias pattern and
 516   // that we are not the bias owner in the current epoch. We need to
 517   // figure out more details about the state of the header in order to
 518   // know what operations can be legally performed on the object's
 519   // header.
 520 
 521   // If the low three bits in the xor result aren't clear, that means
 522   // the prototype header is no longer biased and we have to revoke
 523   // the bias on this object.
 524   andr(rscratch1, tmp_reg, markWord::biased_lock_mask_in_place);
 525   cbnz(rscratch1, try_revoke_bias);
 526 
 527   // Biasing is still enabled for this data type. See whether the
 528   // epoch of the current bias is still valid, meaning that the epoch
 529   // bits of the mark word are equal to the epoch bits of the
 530   // prototype header. (Note that the prototype header's epoch bits
 531   // only change at a safepoint.) If not, attempt to rebias the object
 532   // toward the current thread. Note that we must be absolutely sure
 533   // that the current epoch is invalid in order to do this because
 534   // otherwise the manipulations it performs on the mark word are
 535   // illegal.
 536   andr(rscratch1, tmp_reg, markWord::epoch_mask_in_place);
 537   cbnz(rscratch1, try_rebias);
 538 
 539   // The epoch of the current bias is still valid but we know nothing
 540   // about the owner; it might be set or it might be clear. Try to
 541   // acquire the bias of the object using an atomic operation. If this
 542   // fails we will go in to the runtime to revoke the object's bias.
 543   // Note that we first construct the presumed unbiased header so we
 544   // don't accidentally blow away another thread's valid bias.
 545   {
 546     Label here;
 547     mov(rscratch1, markWord::biased_lock_mask_in_place | markWord::age_mask_in_place | markWord::epoch_mask_in_place);
 548     andr(swap_reg, swap_reg, rscratch1);
 549     orr(tmp_reg, swap_reg, rthread);
 550     cmpxchg_obj_header(swap_reg, tmp_reg, obj_reg, rscratch1, here, slow_case);
 551     // If the biasing toward our thread failed, this means that
 552     // another thread succeeded in biasing it toward itself and we
 553     // need to revoke that bias. The revocation will occur in the
 554     // interpreter runtime in the slow case.
 555     bind(here);
 556     if (counters != NULL) {
 557       atomic_incw(Address((address)counters->anonymously_biased_lock_entry_count_addr()),
 558                   tmp_reg, rscratch1, rscratch2);
 559     }
 560   }
 561   b(done);
 562 
 563   bind(try_rebias);
 564   // At this point we know the epoch has expired, meaning that the
 565   // current "bias owner", if any, is actually invalid. Under these
 566   // circumstances _only_, we are allowed to use the current header's
 567   // value as the comparison value when doing the cas to acquire the
 568   // bias in the current epoch. In other words, we allow transfer of
 569   // the bias from one thread to another directly in this situation.
 570   //
 571   // FIXME: due to a lack of registers we currently blow away the age
 572   // bits in this situation. Should attempt to preserve them.
 573   {
 574     Label here;
 575     load_prototype_header(tmp_reg, obj_reg);
 576     orr(tmp_reg, rthread, tmp_reg);
 577     cmpxchg_obj_header(swap_reg, tmp_reg, obj_reg, rscratch1, here, slow_case);
 578     // If the biasing toward our thread failed, then another thread
 579     // succeeded in biasing it toward itself and we need to revoke that
 580     // bias. The revocation will occur in the runtime in the slow case.
 581     bind(here);
 582     if (counters != NULL) {
 583       atomic_incw(Address((address)counters->rebiased_lock_entry_count_addr()),
 584                   tmp_reg, rscratch1, rscratch2);
 585     }
 586   }
 587   b(done);
 588 
 589   bind(try_revoke_bias);
 590   // The prototype mark in the klass doesn't have the bias bit set any
 591   // more, indicating that objects of this data type are not supposed
 592   // to be biased any more. We are going to try to reset the mark of
 593   // this object to the prototype value and fall through to the
 594   // CAS-based locking scheme. Note that if our CAS fails, it means
 595   // that another thread raced us for the privilege of revoking the
 596   // bias of this particular object, so it's okay to continue in the
 597   // normal locking code.
 598   //
 599   // FIXME: due to a lack of registers we currently blow away the age
 600   // bits in this situation. Should attempt to preserve them.
 601   {
 602     Label here, nope;
 603     load_prototype_header(tmp_reg, obj_reg);
 604     cmpxchg_obj_header(swap_reg, tmp_reg, obj_reg, rscratch1, here, &nope);
 605     bind(here);
 606 
 607     // Fall through to the normal CAS-based lock, because no matter what
 608     // the result of the above CAS, some thread must have succeeded in
 609     // removing the bias bit from the object's header.
 610     if (counters != NULL) {
 611       atomic_incw(Address((address)counters->revoked_lock_entry_count_addr()), tmp_reg,
 612                   rscratch1, rscratch2);
 613     }
 614     bind(nope);
 615   }
 616 
 617   bind(cas_label);
 618 }
 619 
 620 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
 621   assert(UseBiasedLocking, "why call this otherwise?");
 622 
 623   // Check for biased locking unlock case, which is a no-op
 624   // Note: we do not have to check the thread ID for two reasons.
 625   // First, the interpreter checks for IllegalMonitorStateException at
 626   // a higher level. Second, if the bias was revoked while we held the
 627   // lock, the object could not be rebiased toward another thread, so
 628   // the bias bit would be clear.
 629   ldr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
 630   andr(temp_reg, temp_reg, markWord::biased_lock_mask_in_place);
 631   cmp(temp_reg, (u1)markWord::biased_lock_pattern);
 632   br(Assembler::EQ, done);
 633 }
 634 
 635 static void pass_arg0(MacroAssembler* masm, Register arg) {
 636   if (c_rarg0 != arg ) {
 637     masm->mov(c_rarg0, arg);
 638   }
 639 }
 640 
 641 static void pass_arg1(MacroAssembler* masm, Register arg) {
 642   if (c_rarg1 != arg ) {
 643     masm->mov(c_rarg1, arg);
 644   }
 645 }
 646 
 647 static void pass_arg2(MacroAssembler* masm, Register arg) {
 648   if (c_rarg2 != arg ) {
 649     masm->mov(c_rarg2, arg);
 650   }
 651 }
 652 
 653 static void pass_arg3(MacroAssembler* masm, Register arg) {
 654   if (c_rarg3 != arg ) {
 655     masm->mov(c_rarg3, arg);
 656   }
 657 }
 658 
 659 void MacroAssembler::call_VM_base(Register oop_result,
 660                                   Register java_thread,
 661                                   Register last_java_sp,
 662                                   address  entry_point,
 663                                   int      number_of_arguments,
 664                                   bool     check_exceptions) {
 665    // determine java_thread register
 666   if (!java_thread->is_valid()) {
 667     java_thread = rthread;
 668   }
 669 
 670   // determine last_java_sp register
 671   if (!last_java_sp->is_valid()) {
 672     last_java_sp = esp;
 673   }
 674 
 675   // debugging support
 676   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
 677   assert(java_thread == rthread, "unexpected register");
 678 #ifdef ASSERT
 679   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
 680   // if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");
 681 #endif // ASSERT
 682 
 683   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
 684   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
 685 
 686   // push java thread (becomes first argument of C function)
 687 
 688   mov(c_rarg0, java_thread);
 689 
 690   // set last Java frame before call
 691   assert(last_java_sp != rfp, "can't use rfp");
 692 
 693   Label l;
 694   set_last_Java_frame(last_java_sp, rfp, l, rscratch1);
 695 
 696   // do the call, remove parameters
 697   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments, &l);
 698 
 699   // lr could be poisoned with PAC signature during throw_pending_exception
 700   // if it was tail-call optimized by compiler, since lr is not callee-saved
 701   // reload it with proper value
 702   adr(lr, l);
 703 
 704   // reset last Java frame
 705   // Only interpreter should have to clear fp
 706   reset_last_Java_frame(true);
 707 
 708    // C++ interp handles this in the interpreter
 709   check_and_handle_popframe(java_thread);
 710   check_and_handle_earlyret(java_thread);
 711 
 712   if (check_exceptions) {
 713     // check for pending exceptions (java_thread is set upon return)
 714     ldr(rscratch1, Address(java_thread, in_bytes(Thread::pending_exception_offset())));
 715     Label ok;
 716     cbz(rscratch1, ok);
 717     lea(rscratch1, RuntimeAddress(StubRoutines::forward_exception_entry()));
 718     br(rscratch1);
 719     bind(ok);
 720   }
 721 
 722   // get oop result if there is one and reset the value in the thread
 723   if (oop_result->is_valid()) {
 724     get_vm_result(oop_result, java_thread);
 725   }
 726 }
 727 
 728 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
 729   call_VM_base(oop_result, noreg, noreg, entry_point, number_of_arguments, check_exceptions);
 730 }
 731 
 732 // Maybe emit a call via a trampoline.  If the code cache is small
 733 // trampolines won't be emitted.
 734 
 735 address MacroAssembler::trampoline_call(Address entry, CodeBuffer* cbuf) {
 736   assert(JavaThread::current()->is_Compiler_thread(), "just checking");
 737   assert(entry.rspec().type() == relocInfo::runtime_call_type
 738          || entry.rspec().type() == relocInfo::opt_virtual_call_type
 739          || entry.rspec().type() == relocInfo::static_call_type
 740          || entry.rspec().type() == relocInfo::virtual_call_type, "wrong reloc type");
 741 
 742   bool need_trampoline = far_branches();
 743   if (!need_trampoline && entry.rspec().type() == relocInfo::runtime_call_type && !CodeCache::contains(entry.target())) {
 744     // If it is a runtime call of an address outside small CodeCache,
 745     // we need to check whether it is in range.
 746     address target = entry.target();
 747     assert(target < CodeCache::low_bound() || target >= CodeCache::high_bound(), "target is inside CodeCache");
 748     // Case 1: -------T-------L====CodeCache====H-------
 749     //                ^-------longest branch---|
 750     // Case 2: -------L====CodeCache====H-------T-------
 751     //                |-------longest branch ---^
 752     address longest_branch_start = (target < CodeCache::low_bound()) ? CodeCache::high_bound() - NativeInstruction::instruction_size
 753                                                                      : CodeCache::low_bound();
 754     need_trampoline = !reachable_from_branch_at(longest_branch_start, target);
 755   }
 756 
 757   // We need a trampoline if branches are far.
 758   if (need_trampoline) {
 759     bool in_scratch_emit_size = false;
 760 #ifdef COMPILER2
 761     // We don't want to emit a trampoline if C2 is generating dummy
 762     // code during its branch shortening phase.
 763     CompileTask* task = ciEnv::current()->task();
 764     in_scratch_emit_size =
 765       (task != NULL && is_c2_compile(task->comp_level()) &&
 766        Compile::current()->output()->in_scratch_emit_size());
 767 #endif
 768     if (!in_scratch_emit_size) {
 769       address stub = emit_trampoline_stub(offset(), entry.target());
 770       if (stub == NULL) {
 771         postcond(pc() == badAddress);
 772         return NULL; // CodeCache is full
 773       }
 774     }
 775   }
 776 
 777   if (cbuf) cbuf->set_insts_mark();
 778   relocate(entry.rspec());
 779   if (!need_trampoline) {
 780     bl(entry.target());
 781   } else {
 782     bl(pc());
 783   }
 784   // just need to return a non-null address
 785   postcond(pc() != badAddress);
 786   return pc();
 787 }
 788 
 789 
 790 // Emit a trampoline stub for a call to a target which is too far away.
 791 //
 792 // code sequences:
 793 //
 794 // call-site:
 795 //   branch-and-link to <destination> or <trampoline stub>
 796 //
 797 // Related trampoline stub for this call site in the stub section:
 798 //   load the call target from the constant pool
 799 //   branch (LR still points to the call site above)
 800 
 801 address MacroAssembler::emit_trampoline_stub(int insts_call_instruction_offset,
 802                                              address dest) {
 803   // Max stub size: alignment nop, TrampolineStub.
 804   address stub = start_a_stub(NativeInstruction::instruction_size
 805                    + NativeCallTrampolineStub::instruction_size);
 806   if (stub == NULL) {
 807     return NULL;  // CodeBuffer::expand failed
 808   }
 809 
 810   // Create a trampoline stub relocation which relates this trampoline stub
 811   // with the call instruction at insts_call_instruction_offset in the
 812   // instructions code-section.
 813   align(wordSize);
 814   relocate(trampoline_stub_Relocation::spec(code()->insts()->start()
 815                                             + insts_call_instruction_offset));
 816   const int stub_start_offset = offset();
 817 
 818   // Now, create the trampoline stub's code:
 819   // - load the call
 820   // - call
 821   Label target;
 822   ldr(rscratch1, target);
 823   br(rscratch1);
 824   bind(target);
 825   assert(offset() - stub_start_offset == NativeCallTrampolineStub::data_offset,
 826          "should be");
 827   emit_int64((int64_t)dest);
 828 
 829   const address stub_start_addr = addr_at(stub_start_offset);
 830 
 831   assert(is_NativeCallTrampolineStub_at(stub_start_addr), "doesn't look like a trampoline");
 832 
 833   end_a_stub();
 834   return stub_start_addr;
 835 }
 836 
 837 void MacroAssembler::emit_static_call_stub() {
 838   // CompiledDirectStaticCall::set_to_interpreted knows the
 839   // exact layout of this stub.
 840 
 841   isb();
 842   mov_metadata(rmethod, (Metadata*)NULL);
 843 
 844   // Jump to the entry point of the i2c stub.
 845   movptr(rscratch1, 0);
 846   br(rscratch1);
 847 }
 848 
 849 void MacroAssembler::c2bool(Register x) {
 850   // implements x == 0 ? 0 : 1
 851   // note: must only look at least-significant byte of x
 852   //       since C-style booleans are stored in one byte
 853   //       only! (was bug)
 854   tst(x, 0xff);
 855   cset(x, Assembler::NE);
 856 }
 857 
 858 address MacroAssembler::ic_call(address entry, jint method_index) {
 859   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
 860   // address const_ptr = long_constant((jlong)Universe::non_oop_word());
 861   // uintptr_t offset;
 862   // ldr_constant(rscratch2, const_ptr);
 863   movptr(rscratch2, (uintptr_t)Universe::non_oop_word());
 864   return trampoline_call(Address(entry, rh));
 865 }
 866 
 867 // Implementation of call_VM versions
 868 
 869 void MacroAssembler::call_VM(Register oop_result,
 870                              address entry_point,
 871                              bool check_exceptions) {
 872   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
 873 }
 874 
 875 void MacroAssembler::call_VM(Register oop_result,
 876                              address entry_point,
 877                              Register arg_1,
 878                              bool check_exceptions) {
 879   pass_arg1(this, arg_1);
 880   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
 881 }
 882 
 883 void MacroAssembler::call_VM(Register oop_result,
 884                              address entry_point,
 885                              Register arg_1,
 886                              Register arg_2,
 887                              bool check_exceptions) {
 888   assert(arg_1 != c_rarg2, "smashed arg");
 889   pass_arg2(this, arg_2);
 890   pass_arg1(this, arg_1);
 891   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
 892 }
 893 
 894 void MacroAssembler::call_VM(Register oop_result,
 895                              address entry_point,
 896                              Register arg_1,
 897                              Register arg_2,
 898                              Register arg_3,
 899                              bool check_exceptions) {
 900   assert(arg_1 != c_rarg3, "smashed arg");
 901   assert(arg_2 != c_rarg3, "smashed arg");
 902   pass_arg3(this, arg_3);
 903 
 904   assert(arg_1 != c_rarg2, "smashed arg");
 905   pass_arg2(this, arg_2);
 906 
 907   pass_arg1(this, arg_1);
 908   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
 909 }
 910 
 911 void MacroAssembler::call_VM(Register oop_result,
 912                              Register last_java_sp,
 913                              address entry_point,
 914                              int number_of_arguments,
 915                              bool check_exceptions) {
 916   call_VM_base(oop_result, rthread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
 917 }
 918 
 919 void MacroAssembler::call_VM(Register oop_result,
 920                              Register last_java_sp,
 921                              address entry_point,
 922                              Register arg_1,
 923                              bool check_exceptions) {
 924   pass_arg1(this, arg_1);
 925   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
 926 }
 927 
 928 void MacroAssembler::call_VM(Register oop_result,
 929                              Register last_java_sp,
 930                              address entry_point,
 931                              Register arg_1,
 932                              Register arg_2,
 933                              bool check_exceptions) {
 934 
 935   assert(arg_1 != c_rarg2, "smashed arg");
 936   pass_arg2(this, arg_2);
 937   pass_arg1(this, arg_1);
 938   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
 939 }
 940 
 941 void MacroAssembler::call_VM(Register oop_result,
 942                              Register last_java_sp,
 943                              address entry_point,
 944                              Register arg_1,
 945                              Register arg_2,
 946                              Register arg_3,
 947                              bool check_exceptions) {
 948   assert(arg_1 != c_rarg3, "smashed arg");
 949   assert(arg_2 != c_rarg3, "smashed arg");
 950   pass_arg3(this, arg_3);
 951   assert(arg_1 != c_rarg2, "smashed arg");
 952   pass_arg2(this, arg_2);
 953   pass_arg1(this, arg_1);
 954   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
 955 }
 956 
 957 
 958 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
 959   ldr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
 960   str(zr, Address(java_thread, JavaThread::vm_result_offset()));
 961   verify_oop(oop_result, "broken oop in call_VM_base");
 962 }
 963 
 964 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
 965   ldr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
 966   str(zr, Address(java_thread, JavaThread::vm_result_2_offset()));
 967 }
 968 
 969 void MacroAssembler::align(int modulus) {
 970   while (offset() % modulus != 0) nop();
 971 }
 972 
 973 // these are no-ops overridden by InterpreterMacroAssembler
 974 
 975 void MacroAssembler::check_and_handle_earlyret(Register java_thread) { }
 976 
 977 void MacroAssembler::check_and_handle_popframe(Register java_thread) { }
 978 
 979 // Look up the method for a megamorphic invokeinterface call.
 980 // The target method is determined by <intf_klass, itable_index>.
 981 // The receiver klass is in recv_klass.
 982 // On success, the result will be in method_result, and execution falls through.
 983 // On failure, execution transfers to the given label.
 984 void MacroAssembler::lookup_interface_method(Register recv_klass,
 985                                              Register intf_klass,
 986                                              RegisterOrConstant itable_index,
 987                                              Register method_result,
 988                                              Register scan_temp,
 989                                              Label& L_no_such_interface,
 990                          bool return_method) {
 991   assert_different_registers(recv_klass, intf_klass, scan_temp);
 992   assert_different_registers(method_result, intf_klass, scan_temp);
 993   assert(recv_klass != method_result || !return_method,
 994      "recv_klass can be destroyed when method isn't needed");
 995   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
 996          "caller must use same register for non-constant itable index as for method");
 997 
 998   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
 999   int vtable_base = in_bytes(Klass::vtable_start_offset());
1000   int itentry_off = itableMethodEntry::method_offset_in_bytes();
1001   int scan_step   = itableOffsetEntry::size() * wordSize;
1002   int vte_size    = vtableEntry::size_in_bytes();
1003   assert(vte_size == wordSize, "else adjust times_vte_scale");
1004 
1005   ldrw(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
1006 
1007   // %%% Could store the aligned, prescaled offset in the klassoop.
1008   // lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
1009   lea(scan_temp, Address(recv_klass, scan_temp, Address::lsl(3)));
1010   add(scan_temp, scan_temp, vtable_base);
1011 
1012   if (return_method) {
1013     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
1014     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
1015     // lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
1016     lea(recv_klass, Address(recv_klass, itable_index, Address::lsl(3)));
1017     if (itentry_off)
1018       add(recv_klass, recv_klass, itentry_off);
1019   }
1020 
1021   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
1022   //   if (scan->interface() == intf) {
1023   //     result = (klass + scan->offset() + itable_index);
1024   //   }
1025   // }
1026   Label search, found_method;
1027 
1028   ldr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
1029   cmp(intf_klass, method_result);
1030   br(Assembler::EQ, found_method);
1031   bind(search);
1032   // Check that the previous entry is non-null.  A null entry means that
1033   // the receiver class doesn't implement the interface, and wasn't the
1034   // same as when the caller was compiled.
1035   cbz(method_result, L_no_such_interface);
1036   if (itableOffsetEntry::interface_offset_in_bytes() != 0) {
1037     add(scan_temp, scan_temp, scan_step);
1038     ldr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
1039   } else {
1040     ldr(method_result, Address(pre(scan_temp, scan_step)));
1041   }
1042   cmp(intf_klass, method_result);
1043   br(Assembler::NE, search);
1044 
1045   bind(found_method);
1046 
1047   // Got a hit.
1048   if (return_method) {
1049     ldrw(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
1050     ldr(method_result, Address(recv_klass, scan_temp, Address::uxtw(0)));
1051   }
1052 }
1053 
1054 // virtual method calling
1055 void MacroAssembler::lookup_virtual_method(Register recv_klass,
1056                                            RegisterOrConstant vtable_index,
1057                                            Register method_result) {
1058   const int base = in_bytes(Klass::vtable_start_offset());
1059   assert(vtableEntry::size() * wordSize == 8,
1060          "adjust the scaling in the code below");
1061   int vtable_offset_in_bytes = base + vtableEntry::method_offset_in_bytes();
1062 
1063   if (vtable_index.is_register()) {
1064     lea(method_result, Address(recv_klass,
1065                                vtable_index.as_register(),
1066                                Address::lsl(LogBytesPerWord)));
1067     ldr(method_result, Address(method_result, vtable_offset_in_bytes));
1068   } else {
1069     vtable_offset_in_bytes += vtable_index.as_constant() * wordSize;
1070     ldr(method_result,
1071         form_address(rscratch1, recv_klass, vtable_offset_in_bytes, 0));
1072   }
1073 }
1074 
1075 void MacroAssembler::check_klass_subtype(Register sub_klass,
1076                            Register super_klass,
1077                            Register temp_reg,
1078                            Label& L_success) {
1079   Label L_failure;
1080   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
1081   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
1082   bind(L_failure);
1083 }
1084 
1085 
1086 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
1087                                                    Register super_klass,
1088                                                    Register temp_reg,
1089                                                    Label* L_success,
1090                                                    Label* L_failure,
1091                                                    Label* L_slow_path,
1092                                         RegisterOrConstant super_check_offset) {
1093   assert_different_registers(sub_klass, super_klass, temp_reg);
1094   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
1095   if (super_check_offset.is_register()) {
1096     assert_different_registers(sub_klass, super_klass,
1097                                super_check_offset.as_register());
1098   } else if (must_load_sco) {
1099     assert(temp_reg != noreg, "supply either a temp or a register offset");
1100   }
1101 
1102   Label L_fallthrough;
1103   int label_nulls = 0;
1104   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
1105   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
1106   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
1107   assert(label_nulls <= 1, "at most one NULL in the batch");
1108 
1109   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
1110   int sco_offset = in_bytes(Klass::super_check_offset_offset());
1111   Address super_check_offset_addr(super_klass, sco_offset);
1112 
1113   // Hacked jmp, which may only be used just before L_fallthrough.
1114 #define final_jmp(label)                                                \
1115   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
1116   else                            b(label)                /*omit semi*/
1117 
1118   // If the pointers are equal, we are done (e.g., String[] elements).
1119   // This self-check enables sharing of secondary supertype arrays among
1120   // non-primary types such as array-of-interface.  Otherwise, each such
1121   // type would need its own customized SSA.
1122   // We move this check to the front of the fast path because many
1123   // type checks are in fact trivially successful in this manner,
1124   // so we get a nicely predicted branch right at the start of the check.
1125   cmp(sub_klass, super_klass);
1126   br(Assembler::EQ, *L_success);
1127 
1128   // Check the supertype display:
1129   if (must_load_sco) {
1130     ldrw(temp_reg, super_check_offset_addr);
1131     super_check_offset = RegisterOrConstant(temp_reg);
1132   }
1133   Address super_check_addr(sub_klass, super_check_offset);
1134   ldr(rscratch1, super_check_addr);
1135   cmp(super_klass, rscratch1); // load displayed supertype
1136 
1137   // This check has worked decisively for primary supers.
1138   // Secondary supers are sought in the super_cache ('super_cache_addr').
1139   // (Secondary supers are interfaces and very deeply nested subtypes.)
1140   // This works in the same check above because of a tricky aliasing
1141   // between the super_cache and the primary super display elements.
1142   // (The 'super_check_addr' can address either, as the case requires.)
1143   // Note that the cache is updated below if it does not help us find
1144   // what we need immediately.
1145   // So if it was a primary super, we can just fail immediately.
1146   // Otherwise, it's the slow path for us (no success at this point).
1147 
1148   if (super_check_offset.is_register()) {
1149     br(Assembler::EQ, *L_success);
1150     subs(zr, super_check_offset.as_register(), sc_offset);
1151     if (L_failure == &L_fallthrough) {
1152       br(Assembler::EQ, *L_slow_path);
1153     } else {
1154       br(Assembler::NE, *L_failure);
1155       final_jmp(*L_slow_path);
1156     }
1157   } else if (super_check_offset.as_constant() == sc_offset) {
1158     // Need a slow path; fast failure is impossible.
1159     if (L_slow_path == &L_fallthrough) {
1160       br(Assembler::EQ, *L_success);
1161     } else {
1162       br(Assembler::NE, *L_slow_path);
1163       final_jmp(*L_success);
1164     }
1165   } else {
1166     // No slow path; it's a fast decision.
1167     if (L_failure == &L_fallthrough) {
1168       br(Assembler::EQ, *L_success);
1169     } else {
1170       br(Assembler::NE, *L_failure);
1171       final_jmp(*L_success);
1172     }
1173   }
1174 
1175   bind(L_fallthrough);
1176 
1177 #undef final_jmp
1178 }
1179 
1180 // These two are taken from x86, but they look generally useful
1181 
1182 // scans count pointer sized words at [addr] for occurence of value,
1183 // generic
1184 void MacroAssembler::repne_scan(Register addr, Register value, Register count,
1185                                 Register scratch) {
1186   Label Lloop, Lexit;
1187   cbz(count, Lexit);
1188   bind(Lloop);
1189   ldr(scratch, post(addr, wordSize));
1190   cmp(value, scratch);
1191   br(EQ, Lexit);
1192   sub(count, count, 1);
1193   cbnz(count, Lloop);
1194   bind(Lexit);
1195 }
1196 
1197 // scans count 4 byte words at [addr] for occurence of value,
1198 // generic
1199 void MacroAssembler::repne_scanw(Register addr, Register value, Register count,
1200                                 Register scratch) {
1201   Label Lloop, Lexit;
1202   cbz(count, Lexit);
1203   bind(Lloop);
1204   ldrw(scratch, post(addr, wordSize));
1205   cmpw(value, scratch);
1206   br(EQ, Lexit);
1207   sub(count, count, 1);
1208   cbnz(count, Lloop);
1209   bind(Lexit);
1210 }
1211 
1212 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
1213                                                    Register super_klass,
1214                                                    Register temp_reg,
1215                                                    Register temp2_reg,
1216                                                    Label* L_success,
1217                                                    Label* L_failure,
1218                                                    bool set_cond_codes) {
1219   assert_different_registers(sub_klass, super_klass, temp_reg);
1220   if (temp2_reg != noreg)
1221     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg, rscratch1);
1222 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
1223 
1224   Label L_fallthrough;
1225   int label_nulls = 0;
1226   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
1227   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
1228   assert(label_nulls <= 1, "at most one NULL in the batch");
1229 
1230   // a couple of useful fields in sub_klass:
1231   int ss_offset = in_bytes(Klass::secondary_supers_offset());
1232   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
1233   Address secondary_supers_addr(sub_klass, ss_offset);
1234   Address super_cache_addr(     sub_klass, sc_offset);
1235 
1236   BLOCK_COMMENT("check_klass_subtype_slow_path");
1237 
1238   // Do a linear scan of the secondary super-klass chain.
1239   // This code is rarely used, so simplicity is a virtue here.
1240   // The repne_scan instruction uses fixed registers, which we must spill.
1241   // Don't worry too much about pre-existing connections with the input regs.
1242 
1243   assert(sub_klass != r0, "killed reg"); // killed by mov(r0, super)
1244   assert(sub_klass != r2, "killed reg"); // killed by lea(r2, &pst_counter)
1245 
1246   RegSet pushed_registers;
1247   if (!IS_A_TEMP(r2))    pushed_registers += r2;
1248   if (!IS_A_TEMP(r5))    pushed_registers += r5;
1249 
1250   if (super_klass != r0) {
1251     if (!IS_A_TEMP(r0))   pushed_registers += r0;
1252   }
1253 
1254   push(pushed_registers, sp);
1255 
1256   // Get super_klass value into r0 (even if it was in r5 or r2).
1257   if (super_klass != r0) {
1258     mov(r0, super_klass);
1259   }
1260 
1261 #ifndef PRODUCT
1262   mov(rscratch2, (address)&SharedRuntime::_partial_subtype_ctr);
1263   Address pst_counter_addr(rscratch2);
1264   ldr(rscratch1, pst_counter_addr);
1265   add(rscratch1, rscratch1, 1);
1266   str(rscratch1, pst_counter_addr);
1267 #endif //PRODUCT
1268 
1269   // We will consult the secondary-super array.
1270   ldr(r5, secondary_supers_addr);
1271   // Load the array length.
1272   ldrw(r2, Address(r5, Array<Klass*>::length_offset_in_bytes()));
1273   // Skip to start of data.
1274   add(r5, r5, Array<Klass*>::base_offset_in_bytes());
1275 
1276   cmp(sp, zr); // Clear Z flag; SP is never zero
1277   // Scan R2 words at [R5] for an occurrence of R0.
1278   // Set NZ/Z based on last compare.
1279   repne_scan(r5, r0, r2, rscratch1);
1280 
1281   // Unspill the temp. registers:
1282   pop(pushed_registers, sp);
1283 
1284   br(Assembler::NE, *L_failure);
1285 
1286   // Success.  Cache the super we found and proceed in triumph.
1287   str(super_klass, super_cache_addr);
1288 
1289   if (L_success != &L_fallthrough) {
1290     b(*L_success);
1291   }
1292 
1293 #undef IS_A_TEMP
1294 
1295   bind(L_fallthrough);
1296 }
1297 
1298 void MacroAssembler::clinit_barrier(Register klass, Register scratch, Label* L_fast_path, Label* L_slow_path) {
1299   assert(L_fast_path != NULL || L_slow_path != NULL, "at least one is required");
1300   assert_different_registers(klass, rthread, scratch);
1301 
1302   Label L_fallthrough, L_tmp;
1303   if (L_fast_path == NULL) {
1304     L_fast_path = &L_fallthrough;
1305   } else if (L_slow_path == NULL) {
1306     L_slow_path = &L_fallthrough;
1307   }
1308   // Fast path check: class is fully initialized
1309   ldrb(scratch, Address(klass, InstanceKlass::init_state_offset()));
1310   subs(zr, scratch, InstanceKlass::fully_initialized);
1311   br(Assembler::EQ, *L_fast_path);
1312 
1313   // Fast path check: current thread is initializer thread
1314   ldr(scratch, Address(klass, InstanceKlass::init_thread_offset()));
1315   cmp(rthread, scratch);
1316 
1317   if (L_slow_path == &L_fallthrough) {
1318     br(Assembler::EQ, *L_fast_path);
1319     bind(*L_slow_path);
1320   } else if (L_fast_path == &L_fallthrough) {
1321     br(Assembler::NE, *L_slow_path);
1322     bind(*L_fast_path);
1323   } else {
1324     Unimplemented();
1325   }
1326 }
1327 
1328 void MacroAssembler::verify_oop(Register reg, const char* s) {
1329   if (!VerifyOops) return;
1330 
1331   // Pass register number to verify_oop_subroutine
1332   const char* b = NULL;
1333   {
1334     ResourceMark rm;
1335     stringStream ss;
1336     ss.print("verify_oop: %s: %s", reg->name(), s);
1337     b = code_string(ss.as_string());
1338   }
1339   BLOCK_COMMENT("verify_oop {");
1340 
1341   stp(r0, rscratch1, Address(pre(sp, -2 * wordSize)));
1342   stp(rscratch2, lr, Address(pre(sp, -2 * wordSize)));
1343 
1344   mov(r0, reg);
1345   movptr(rscratch1, (uintptr_t)(address)b);
1346 
1347   // call indirectly to solve generation ordering problem
1348   lea(rscratch2, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
1349   ldr(rscratch2, Address(rscratch2));
1350   blr(rscratch2);
1351 
1352   ldp(rscratch2, lr, Address(post(sp, 2 * wordSize)));
1353   ldp(r0, rscratch1, Address(post(sp, 2 * wordSize)));
1354 
1355   BLOCK_COMMENT("} verify_oop");
1356 }
1357 
1358 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
1359   if (!VerifyOops) return;
1360 
1361   const char* b = NULL;
1362   {
1363     ResourceMark rm;
1364     stringStream ss;
1365     ss.print("verify_oop_addr: %s", s);
1366     b = code_string(ss.as_string());
1367   }
1368   BLOCK_COMMENT("verify_oop_addr {");
1369 
1370   stp(r0, rscratch1, Address(pre(sp, -2 * wordSize)));
1371   stp(rscratch2, lr, Address(pre(sp, -2 * wordSize)));
1372 
1373   // addr may contain sp so we will have to adjust it based on the
1374   // pushes that we just did.
1375   if (addr.uses(sp)) {
1376     lea(r0, addr);
1377     ldr(r0, Address(r0, 4 * wordSize));
1378   } else {
1379     ldr(r0, addr);
1380   }
1381   movptr(rscratch1, (uintptr_t)(address)b);
1382 
1383   // call indirectly to solve generation ordering problem
1384   lea(rscratch2, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
1385   ldr(rscratch2, Address(rscratch2));
1386   blr(rscratch2);
1387 
1388   ldp(rscratch2, lr, Address(post(sp, 2 * wordSize)));
1389   ldp(r0, rscratch1, Address(post(sp, 2 * wordSize)));
1390 
1391   BLOCK_COMMENT("} verify_oop_addr");
1392 }
1393 
1394 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
1395                                          int extra_slot_offset) {
1396   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
1397   int stackElementSize = Interpreter::stackElementSize;
1398   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
1399 #ifdef ASSERT
1400   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
1401   assert(offset1 - offset == stackElementSize, "correct arithmetic");
1402 #endif
1403   if (arg_slot.is_constant()) {
1404     return Address(esp, arg_slot.as_constant() * stackElementSize
1405                    + offset);
1406   } else {
1407     add(rscratch1, esp, arg_slot.as_register(),
1408         ext::uxtx, exact_log2(stackElementSize));
1409     return Address(rscratch1, offset);
1410   }
1411 }
1412 
1413 void MacroAssembler::call_VM_leaf_base(address entry_point,
1414                                        int number_of_arguments,
1415                                        Label *retaddr) {
1416   Label E, L;
1417 
1418   stp(rscratch1, rmethod, Address(pre(sp, -2 * wordSize)));
1419 
1420   mov(rscratch1, entry_point);
1421   blr(rscratch1);
1422   if (retaddr)
1423     bind(*retaddr);
1424 
1425   ldp(rscratch1, rmethod, Address(post(sp, 2 * wordSize)));
1426 }
1427 
1428 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
1429   call_VM_leaf_base(entry_point, number_of_arguments);
1430 }
1431 
1432 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
1433   pass_arg0(this, arg_0);
1434   call_VM_leaf_base(entry_point, 1);
1435 }
1436 
1437 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
1438   pass_arg0(this, arg_0);
1439   pass_arg1(this, arg_1);
1440   call_VM_leaf_base(entry_point, 2);
1441 }
1442 
1443 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0,
1444                                   Register arg_1, Register arg_2) {
1445   pass_arg0(this, arg_0);
1446   pass_arg1(this, arg_1);
1447   pass_arg2(this, arg_2);
1448   call_VM_leaf_base(entry_point, 3);
1449 }
1450 
1451 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
1452   pass_arg0(this, arg_0);
1453   MacroAssembler::call_VM_leaf_base(entry_point, 1);
1454 }
1455 
1456 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
1457 
1458   assert(arg_0 != c_rarg1, "smashed arg");
1459   pass_arg1(this, arg_1);
1460   pass_arg0(this, arg_0);
1461   MacroAssembler::call_VM_leaf_base(entry_point, 2);
1462 }
1463 
1464 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
1465   assert(arg_0 != c_rarg2, "smashed arg");
1466   assert(arg_1 != c_rarg2, "smashed arg");
1467   pass_arg2(this, arg_2);
1468   assert(arg_0 != c_rarg1, "smashed arg");
1469   pass_arg1(this, arg_1);
1470   pass_arg0(this, arg_0);
1471   MacroAssembler::call_VM_leaf_base(entry_point, 3);
1472 }
1473 
1474 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
1475   assert(arg_0 != c_rarg3, "smashed arg");
1476   assert(arg_1 != c_rarg3, "smashed arg");
1477   assert(arg_2 != c_rarg3, "smashed arg");
1478   pass_arg3(this, arg_3);
1479   assert(arg_0 != c_rarg2, "smashed arg");
1480   assert(arg_1 != c_rarg2, "smashed arg");
1481   pass_arg2(this, arg_2);
1482   assert(arg_0 != c_rarg1, "smashed arg");
1483   pass_arg1(this, arg_1);
1484   pass_arg0(this, arg_0);
1485   MacroAssembler::call_VM_leaf_base(entry_point, 4);
1486 }
1487 
1488 void MacroAssembler::null_check(Register reg, int offset) {
1489   if (needs_explicit_null_check(offset)) {
1490     // provoke OS NULL exception if reg = NULL by
1491     // accessing M[reg] w/o changing any registers
1492     // NOTE: this is plenty to provoke a segv
1493     ldr(zr, Address(reg));
1494   } else {
1495     // nothing to do, (later) access of M[reg + offset]
1496     // will provoke OS NULL exception if reg = NULL
1497   }
1498 }
1499 
1500 // MacroAssembler protected routines needed to implement
1501 // public methods
1502 
1503 void MacroAssembler::mov(Register r, Address dest) {
1504   code_section()->relocate(pc(), dest.rspec());
1505   uint64_t imm64 = (uint64_t)dest.target();
1506   movptr(r, imm64);
1507 }
1508 
1509 // Move a constant pointer into r.  In AArch64 mode the virtual
1510 // address space is 48 bits in size, so we only need three
1511 // instructions to create a patchable instruction sequence that can
1512 // reach anywhere.
1513 void MacroAssembler::movptr(Register r, uintptr_t imm64) {
1514 #ifndef PRODUCT
1515   {
1516     char buffer[64];
1517     snprintf(buffer, sizeof(buffer), "0x%" PRIX64, (uint64_t)imm64);
1518     block_comment(buffer);
1519   }
1520 #endif
1521   assert(imm64 < (1ull << 48), "48-bit overflow in address constant");
1522   movz(r, imm64 & 0xffff);
1523   imm64 >>= 16;
1524   movk(r, imm64 & 0xffff, 16);
1525   imm64 >>= 16;
1526   movk(r, imm64 & 0xffff, 32);
1527 }
1528 
1529 // Macro to mov replicated immediate to vector register.
1530 // imm64: only the lower 8/16/32 bits are considered for B/H/S type. That is,
1531 //        the upper 56/48/32 bits must be zeros for B/H/S type.
1532 // Vd will get the following values for different arrangements in T
1533 //   imm64 == hex 000000gh  T8B:  Vd = ghghghghghghghgh
1534 //   imm64 == hex 000000gh  T16B: Vd = ghghghghghghghghghghghghghghghgh
1535 //   imm64 == hex 0000efgh  T4H:  Vd = efghefghefghefgh
1536 //   imm64 == hex 0000efgh  T8H:  Vd = efghefghefghefghefghefghefghefgh
1537 //   imm64 == hex abcdefgh  T2S:  Vd = abcdefghabcdefgh
1538 //   imm64 == hex abcdefgh  T4S:  Vd = abcdefghabcdefghabcdefghabcdefgh
1539 //   imm64 == hex abcdefgh  T1D:  Vd = 00000000abcdefgh
1540 //   imm64 == hex abcdefgh  T2D:  Vd = 00000000abcdefgh00000000abcdefgh
1541 // Clobbers rscratch1
1542 void MacroAssembler::mov(FloatRegister Vd, SIMD_Arrangement T, uint64_t imm64) {
1543   assert(T != T1Q, "unsupported");
1544   if (T == T1D || T == T2D) {
1545     int imm = operand_valid_for_movi_immediate(imm64, T);
1546     if (-1 != imm) {
1547       movi(Vd, T, imm);
1548     } else {
1549       mov(rscratch1, imm64);
1550       dup(Vd, T, rscratch1);
1551     }
1552     return;
1553   }
1554 
1555 #ifdef ASSERT
1556   if (T == T8B || T == T16B) assert((imm64 & ~0xff) == 0, "extraneous bits (T8B/T16B)");
1557   if (T == T4H || T == T8H) assert((imm64  & ~0xffff) == 0, "extraneous bits (T4H/T8H)");
1558   if (T == T2S || T == T4S) assert((imm64  & ~0xffffffff) == 0, "extraneous bits (T2S/T4S)");
1559 #endif
1560   int shift = operand_valid_for_movi_immediate(imm64, T);
1561   uint32_t imm32 = imm64 & 0xffffffffULL;
1562   if (shift >= 0) {
1563     movi(Vd, T, (imm32 >> shift) & 0xff, shift);
1564   } else {
1565     movw(rscratch1, imm32);
1566     dup(Vd, T, rscratch1);
1567   }
1568 }
1569 
1570 void MacroAssembler::mov_immediate64(Register dst, uint64_t imm64)
1571 {
1572 #ifndef PRODUCT
1573   {
1574     char buffer[64];
1575     snprintf(buffer, sizeof(buffer), "0x%" PRIX64, imm64);
1576     block_comment(buffer);
1577   }
1578 #endif
1579   if (operand_valid_for_logical_immediate(false, imm64)) {
1580     orr(dst, zr, imm64);
1581   } else {
1582     // we can use a combination of MOVZ or MOVN with
1583     // MOVK to build up the constant
1584     uint64_t imm_h[4];
1585     int zero_count = 0;
1586     int neg_count = 0;
1587     int i;
1588     for (i = 0; i < 4; i++) {
1589       imm_h[i] = ((imm64 >> (i * 16)) & 0xffffL);
1590       if (imm_h[i] == 0) {
1591         zero_count++;
1592       } else if (imm_h[i] == 0xffffL) {
1593         neg_count++;
1594       }
1595     }
1596     if (zero_count == 4) {
1597       // one MOVZ will do
1598       movz(dst, 0);
1599     } else if (neg_count == 4) {
1600       // one MOVN will do
1601       movn(dst, 0);
1602     } else if (zero_count == 3) {
1603       for (i = 0; i < 4; i++) {
1604         if (imm_h[i] != 0L) {
1605           movz(dst, (uint32_t)imm_h[i], (i << 4));
1606           break;
1607         }
1608       }
1609     } else if (neg_count == 3) {
1610       // one MOVN will do
1611       for (int i = 0; i < 4; i++) {
1612         if (imm_h[i] != 0xffffL) {
1613           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
1614           break;
1615         }
1616       }
1617     } else if (zero_count == 2) {
1618       // one MOVZ and one MOVK will do
1619       for (i = 0; i < 3; i++) {
1620         if (imm_h[i] != 0L) {
1621           movz(dst, (uint32_t)imm_h[i], (i << 4));
1622           i++;
1623           break;
1624         }
1625       }
1626       for (;i < 4; i++) {
1627         if (imm_h[i] != 0L) {
1628           movk(dst, (uint32_t)imm_h[i], (i << 4));
1629         }
1630       }
1631     } else if (neg_count == 2) {
1632       // one MOVN and one MOVK will do
1633       for (i = 0; i < 4; i++) {
1634         if (imm_h[i] != 0xffffL) {
1635           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
1636           i++;
1637           break;
1638         }
1639       }
1640       for (;i < 4; i++) {
1641         if (imm_h[i] != 0xffffL) {
1642           movk(dst, (uint32_t)imm_h[i], (i << 4));
1643         }
1644       }
1645     } else if (zero_count == 1) {
1646       // one MOVZ and two MOVKs will do
1647       for (i = 0; i < 4; i++) {
1648         if (imm_h[i] != 0L) {
1649           movz(dst, (uint32_t)imm_h[i], (i << 4));
1650           i++;
1651           break;
1652         }
1653       }
1654       for (;i < 4; i++) {
1655         if (imm_h[i] != 0x0L) {
1656           movk(dst, (uint32_t)imm_h[i], (i << 4));
1657         }
1658       }
1659     } else if (neg_count == 1) {
1660       // one MOVN and two MOVKs will do
1661       for (i = 0; i < 4; i++) {
1662         if (imm_h[i] != 0xffffL) {
1663           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
1664           i++;
1665           break;
1666         }
1667       }
1668       for (;i < 4; i++) {
1669         if (imm_h[i] != 0xffffL) {
1670           movk(dst, (uint32_t)imm_h[i], (i << 4));
1671         }
1672       }
1673     } else {
1674       // use a MOVZ and 3 MOVKs (makes it easier to debug)
1675       movz(dst, (uint32_t)imm_h[0], 0);
1676       for (i = 1; i < 4; i++) {
1677         movk(dst, (uint32_t)imm_h[i], (i << 4));
1678       }
1679     }
1680   }
1681 }
1682 
1683 void MacroAssembler::mov_immediate32(Register dst, uint32_t imm32)
1684 {
1685 #ifndef PRODUCT
1686     {
1687       char buffer[64];
1688       snprintf(buffer, sizeof(buffer), "0x%" PRIX32, imm32);
1689       block_comment(buffer);
1690     }
1691 #endif
1692   if (operand_valid_for_logical_immediate(true, imm32)) {
1693     orrw(dst, zr, imm32);
1694   } else {
1695     // we can use MOVZ, MOVN or two calls to MOVK to build up the
1696     // constant
1697     uint32_t imm_h[2];
1698     imm_h[0] = imm32 & 0xffff;
1699     imm_h[1] = ((imm32 >> 16) & 0xffff);
1700     if (imm_h[0] == 0) {
1701       movzw(dst, imm_h[1], 16);
1702     } else if (imm_h[0] == 0xffff) {
1703       movnw(dst, imm_h[1] ^ 0xffff, 16);
1704     } else if (imm_h[1] == 0) {
1705       movzw(dst, imm_h[0], 0);
1706     } else if (imm_h[1] == 0xffff) {
1707       movnw(dst, imm_h[0] ^ 0xffff, 0);
1708     } else {
1709       // use a MOVZ and MOVK (makes it easier to debug)
1710       movzw(dst, imm_h[0], 0);
1711       movkw(dst, imm_h[1], 16);
1712     }
1713   }
1714 }
1715 
1716 // Form an address from base + offset in Rd.  Rd may or may
1717 // not actually be used: you must use the Address that is returned.
1718 // It is up to you to ensure that the shift provided matches the size
1719 // of your data.
1720 Address MacroAssembler::form_address(Register Rd, Register base, int64_t byte_offset, int shift) {
1721   if (Address::offset_ok_for_immed(byte_offset, shift))
1722     // It fits; no need for any heroics
1723     return Address(base, byte_offset);
1724 
1725   // Don't do anything clever with negative or misaligned offsets
1726   unsigned mask = (1 << shift) - 1;
1727   if (byte_offset < 0 || byte_offset & mask) {
1728     mov(Rd, byte_offset);
1729     add(Rd, base, Rd);
1730     return Address(Rd);
1731   }
1732 
1733   // See if we can do this with two 12-bit offsets
1734   {
1735     uint64_t word_offset = byte_offset >> shift;
1736     uint64_t masked_offset = word_offset & 0xfff000;
1737     if (Address::offset_ok_for_immed(word_offset - masked_offset, 0)
1738         && Assembler::operand_valid_for_add_sub_immediate(masked_offset << shift)) {
1739       add(Rd, base, masked_offset << shift);
1740       word_offset -= masked_offset;
1741       return Address(Rd, word_offset << shift);
1742     }
1743   }
1744 
1745   // Do it the hard way
1746   mov(Rd, byte_offset);
1747   add(Rd, base, Rd);
1748   return Address(Rd);
1749 }
1750 
1751 void MacroAssembler::atomic_incw(Register counter_addr, Register tmp, Register tmp2) {
1752   if (UseLSE) {
1753     mov(tmp, 1);
1754     ldadd(Assembler::word, tmp, zr, counter_addr);
1755     return;
1756   }
1757   Label retry_load;
1758   if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))
1759     prfm(Address(counter_addr), PSTL1STRM);
1760   bind(retry_load);
1761   // flush and load exclusive from the memory location
1762   ldxrw(tmp, counter_addr);
1763   addw(tmp, tmp, 1);
1764   // if we store+flush with no intervening write tmp wil be zero
1765   stxrw(tmp2, tmp, counter_addr);
1766   cbnzw(tmp2, retry_load);
1767 }
1768 
1769 
1770 int MacroAssembler::corrected_idivl(Register result, Register ra, Register rb,
1771                                     bool want_remainder, Register scratch)
1772 {
1773   // Full implementation of Java idiv and irem.  The function
1774   // returns the (pc) offset of the div instruction - may be needed
1775   // for implicit exceptions.
1776   //
1777   // constraint : ra/rb =/= scratch
1778   //         normal case
1779   //
1780   // input : ra: dividend
1781   //         rb: divisor
1782   //
1783   // result: either
1784   //         quotient  (= ra idiv rb)
1785   //         remainder (= ra irem rb)
1786 
1787   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
1788 
1789   int idivl_offset = offset();
1790   if (! want_remainder) {
1791     sdivw(result, ra, rb);
1792   } else {
1793     sdivw(scratch, ra, rb);
1794     Assembler::msubw(result, scratch, rb, ra);
1795   }
1796 
1797   return idivl_offset;
1798 }
1799 
1800 int MacroAssembler::corrected_idivq(Register result, Register ra, Register rb,
1801                                     bool want_remainder, Register scratch)
1802 {
1803   // Full implementation of Java ldiv and lrem.  The function
1804   // returns the (pc) offset of the div instruction - may be needed
1805   // for implicit exceptions.
1806   //
1807   // constraint : ra/rb =/= scratch
1808   //         normal case
1809   //
1810   // input : ra: dividend
1811   //         rb: divisor
1812   //
1813   // result: either
1814   //         quotient  (= ra idiv rb)
1815   //         remainder (= ra irem rb)
1816 
1817   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
1818 
1819   int idivq_offset = offset();
1820   if (! want_remainder) {
1821     sdiv(result, ra, rb);
1822   } else {
1823     sdiv(scratch, ra, rb);
1824     Assembler::msub(result, scratch, rb, ra);
1825   }
1826 
1827   return idivq_offset;
1828 }
1829 
1830 void MacroAssembler::membar(Membar_mask_bits order_constraint) {
1831   address prev = pc() - NativeMembar::instruction_size;
1832   address last = code()->last_insn();
1833   if (last != NULL && nativeInstruction_at(last)->is_Membar() && prev == last) {
1834     NativeMembar *bar = NativeMembar_at(prev);
1835     // We are merging two memory barrier instructions.  On AArch64 we
1836     // can do this simply by ORing them together.
1837     bar->set_kind(bar->get_kind() | order_constraint);
1838     BLOCK_COMMENT("merged membar");
1839   } else {
1840     code()->set_last_insn(pc());
1841     dmb(Assembler::barrier(order_constraint));
1842   }
1843 }
1844 
1845 bool MacroAssembler::try_merge_ldst(Register rt, const Address &adr, size_t size_in_bytes, bool is_store) {
1846   if (ldst_can_merge(rt, adr, size_in_bytes, is_store)) {
1847     merge_ldst(rt, adr, size_in_bytes, is_store);
1848     code()->clear_last_insn();
1849     return true;
1850   } else {
1851     assert(size_in_bytes == 8 || size_in_bytes == 4, "only 8 bytes or 4 bytes load/store is supported.");
1852     const uint64_t mask = size_in_bytes - 1;
1853     if (adr.getMode() == Address::base_plus_offset &&
1854         (adr.offset() & mask) == 0) { // only supports base_plus_offset.
1855       code()->set_last_insn(pc());
1856     }
1857     return false;
1858   }
1859 }
1860 
1861 void MacroAssembler::ldr(Register Rx, const Address &adr) {
1862   // We always try to merge two adjacent loads into one ldp.
1863   if (!try_merge_ldst(Rx, adr, 8, false)) {
1864     Assembler::ldr(Rx, adr);
1865   }
1866 }
1867 
1868 void MacroAssembler::ldrw(Register Rw, const Address &adr) {
1869   // We always try to merge two adjacent loads into one ldp.
1870   if (!try_merge_ldst(Rw, adr, 4, false)) {
1871     Assembler::ldrw(Rw, adr);
1872   }
1873 }
1874 
1875 void MacroAssembler::str(Register Rx, const Address &adr) {
1876   // We always try to merge two adjacent stores into one stp.
1877   if (!try_merge_ldst(Rx, adr, 8, true)) {
1878     Assembler::str(Rx, adr);
1879   }
1880 }
1881 
1882 void MacroAssembler::strw(Register Rw, const Address &adr) {
1883   // We always try to merge two adjacent stores into one stp.
1884   if (!try_merge_ldst(Rw, adr, 4, true)) {
1885     Assembler::strw(Rw, adr);
1886   }
1887 }
1888 
1889 // MacroAssembler routines found actually to be needed
1890 
1891 void MacroAssembler::push(Register src)
1892 {
1893   str(src, Address(pre(esp, -1 * wordSize)));
1894 }
1895 
1896 void MacroAssembler::pop(Register dst)
1897 {
1898   ldr(dst, Address(post(esp, 1 * wordSize)));
1899 }
1900 
1901 // Note: load_unsigned_short used to be called load_unsigned_word.
1902 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
1903   int off = offset();
1904   ldrh(dst, src);
1905   return off;
1906 }
1907 
1908 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
1909   int off = offset();
1910   ldrb(dst, src);
1911   return off;
1912 }
1913 
1914 int MacroAssembler::load_signed_short(Register dst, Address src) {
1915   int off = offset();
1916   ldrsh(dst, src);
1917   return off;
1918 }
1919 
1920 int MacroAssembler::load_signed_byte(Register dst, Address src) {
1921   int off = offset();
1922   ldrsb(dst, src);
1923   return off;
1924 }
1925 
1926 int MacroAssembler::load_signed_short32(Register dst, Address src) {
1927   int off = offset();
1928   ldrshw(dst, src);
1929   return off;
1930 }
1931 
1932 int MacroAssembler::load_signed_byte32(Register dst, Address src) {
1933   int off = offset();
1934   ldrsbw(dst, src);
1935   return off;
1936 }
1937 
1938 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
1939   switch (size_in_bytes) {
1940   case  8:  ldr(dst, src); break;
1941   case  4:  ldrw(dst, src); break;
1942   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
1943   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
1944   default:  ShouldNotReachHere();
1945   }
1946 }
1947 
1948 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
1949   switch (size_in_bytes) {
1950   case  8:  str(src, dst); break;
1951   case  4:  strw(src, dst); break;
1952   case  2:  strh(src, dst); break;
1953   case  1:  strb(src, dst); break;
1954   default:  ShouldNotReachHere();
1955   }
1956 }
1957 
1958 void MacroAssembler::decrementw(Register reg, int value)
1959 {
1960   if (value < 0)  { incrementw(reg, -value);      return; }
1961   if (value == 0) {                               return; }
1962   if (value < (1 << 12)) { subw(reg, reg, value); return; }
1963   /* else */ {
1964     guarantee(reg != rscratch2, "invalid dst for register decrement");
1965     movw(rscratch2, (unsigned)value);
1966     subw(reg, reg, rscratch2);
1967   }
1968 }
1969 
1970 void MacroAssembler::decrement(Register reg, int value)
1971 {
1972   if (value < 0)  { increment(reg, -value);      return; }
1973   if (value == 0) {                              return; }
1974   if (value < (1 << 12)) { sub(reg, reg, value); return; }
1975   /* else */ {
1976     assert(reg != rscratch2, "invalid dst for register decrement");
1977     mov(rscratch2, (uint64_t)value);
1978     sub(reg, reg, rscratch2);
1979   }
1980 }
1981 
1982 void MacroAssembler::decrementw(Address dst, int value)
1983 {
1984   assert(!dst.uses(rscratch1), "invalid dst for address decrement");
1985   if (dst.getMode() == Address::literal) {
1986     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
1987     lea(rscratch2, dst);
1988     dst = Address(rscratch2);
1989   }
1990   ldrw(rscratch1, dst);
1991   decrementw(rscratch1, value);
1992   strw(rscratch1, dst);
1993 }
1994 
1995 void MacroAssembler::decrement(Address dst, int value)
1996 {
1997   assert(!dst.uses(rscratch1), "invalid address for decrement");
1998   if (dst.getMode() == Address::literal) {
1999     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2000     lea(rscratch2, dst);
2001     dst = Address(rscratch2);
2002   }
2003   ldr(rscratch1, dst);
2004   decrement(rscratch1, value);
2005   str(rscratch1, dst);
2006 }
2007 
2008 void MacroAssembler::incrementw(Register reg, int value)
2009 {
2010   if (value < 0)  { decrementw(reg, -value);      return; }
2011   if (value == 0) {                               return; }
2012   if (value < (1 << 12)) { addw(reg, reg, value); return; }
2013   /* else */ {
2014     assert(reg != rscratch2, "invalid dst for register increment");
2015     movw(rscratch2, (unsigned)value);
2016     addw(reg, reg, rscratch2);
2017   }
2018 }
2019 
2020 void MacroAssembler::increment(Register reg, int value)
2021 {
2022   if (value < 0)  { decrement(reg, -value);      return; }
2023   if (value == 0) {                              return; }
2024   if (value < (1 << 12)) { add(reg, reg, value); return; }
2025   /* else */ {
2026     assert(reg != rscratch2, "invalid dst for register increment");
2027     movw(rscratch2, (unsigned)value);
2028     add(reg, reg, rscratch2);
2029   }
2030 }
2031 
2032 void MacroAssembler::incrementw(Address dst, int value)
2033 {
2034   assert(!dst.uses(rscratch1), "invalid dst for address increment");
2035   if (dst.getMode() == Address::literal) {
2036     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2037     lea(rscratch2, dst);
2038     dst = Address(rscratch2);
2039   }
2040   ldrw(rscratch1, dst);
2041   incrementw(rscratch1, value);
2042   strw(rscratch1, dst);
2043 }
2044 
2045 void MacroAssembler::increment(Address dst, int value)
2046 {
2047   assert(!dst.uses(rscratch1), "invalid dst for address increment");
2048   if (dst.getMode() == Address::literal) {
2049     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2050     lea(rscratch2, dst);
2051     dst = Address(rscratch2);
2052   }
2053   ldr(rscratch1, dst);
2054   increment(rscratch1, value);
2055   str(rscratch1, dst);
2056 }
2057 
2058 // Push lots of registers in the bit set supplied.  Don't push sp.
2059 // Return the number of words pushed
2060 int MacroAssembler::push(unsigned int bitset, Register stack) {
2061   int words_pushed = 0;
2062 
2063   // Scan bitset to accumulate register pairs
2064   unsigned char regs[32];
2065   int count = 0;
2066   for (int reg = 0; reg <= 30; reg++) {
2067     if (1 & bitset)
2068       regs[count++] = reg;
2069     bitset >>= 1;
2070   }
2071   regs[count++] = zr->encoding_nocheck();
2072   count &= ~1;  // Only push an even nuber of regs
2073 
2074   if (count) {
2075     stp(as_Register(regs[0]), as_Register(regs[1]),
2076        Address(pre(stack, -count * wordSize)));
2077     words_pushed += 2;
2078   }
2079   for (int i = 2; i < count; i += 2) {
2080     stp(as_Register(regs[i]), as_Register(regs[i+1]),
2081        Address(stack, i * wordSize));
2082     words_pushed += 2;
2083   }
2084 
2085   assert(words_pushed == count, "oops, pushed != count");
2086 
2087   return count;
2088 }
2089 
2090 int MacroAssembler::pop(unsigned int bitset, Register stack) {
2091   int words_pushed = 0;
2092 
2093   // Scan bitset to accumulate register pairs
2094   unsigned char regs[32];
2095   int count = 0;
2096   for (int reg = 0; reg <= 30; reg++) {
2097     if (1 & bitset)
2098       regs[count++] = reg;
2099     bitset >>= 1;
2100   }
2101   regs[count++] = zr->encoding_nocheck();
2102   count &= ~1;
2103 
2104   for (int i = 2; i < count; i += 2) {
2105     ldp(as_Register(regs[i]), as_Register(regs[i+1]),
2106        Address(stack, i * wordSize));
2107     words_pushed += 2;
2108   }
2109   if (count) {
2110     ldp(as_Register(regs[0]), as_Register(regs[1]),
2111        Address(post(stack, count * wordSize)));
2112     words_pushed += 2;
2113   }
2114 
2115   assert(words_pushed == count, "oops, pushed != count");
2116 
2117   return count;
2118 }
2119 
2120 // Push lots of registers in the bit set supplied.  Don't push sp.
2121 // Return the number of dwords pushed
2122 int MacroAssembler::push_fp(unsigned int bitset, Register stack) {
2123   int words_pushed = 0;
2124   bool use_sve = false;
2125   int sve_vector_size_in_bytes = 0;
2126 
2127 #ifdef COMPILER2
2128   use_sve = Matcher::supports_scalable_vector();
2129   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
2130 #endif
2131 
2132   // Scan bitset to accumulate register pairs
2133   unsigned char regs[32];
2134   int count = 0;
2135   for (int reg = 0; reg <= 31; reg++) {
2136     if (1 & bitset)
2137       regs[count++] = reg;
2138     bitset >>= 1;
2139   }
2140 
2141   if (count == 0) {
2142     return 0;
2143   }
2144 
2145   // SVE
2146   if (use_sve && sve_vector_size_in_bytes > 16) {
2147     sub(stack, stack, sve_vector_size_in_bytes * count);
2148     for (int i = 0; i < count; i++) {
2149       sve_str(as_FloatRegister(regs[i]), Address(stack, i));
2150     }
2151     return count * sve_vector_size_in_bytes / 8;
2152   }
2153 
2154   // NEON
2155   if (count == 1) {
2156     strq(as_FloatRegister(regs[0]), Address(pre(stack, -wordSize * 2)));
2157     return 2;
2158   }
2159 
2160   bool odd = (count & 1) == 1;
2161   int push_slots = count + (odd ? 1 : 0);
2162 
2163   // Always pushing full 128 bit registers.
2164   stpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(pre(stack, -push_slots * wordSize * 2)));
2165   words_pushed += 2;
2166 
2167   for (int i = 2; i + 1 < count; i += 2) {
2168     stpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
2169     words_pushed += 2;
2170   }
2171 
2172   if (odd) {
2173     strq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
2174     words_pushed++;
2175   }
2176 
2177   assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
2178   return count * 2;
2179 }
2180 
2181 // Return the number of dwords poped
2182 int MacroAssembler::pop_fp(unsigned int bitset, Register stack) {
2183   int words_pushed = 0;
2184   bool use_sve = false;
2185   int sve_vector_size_in_bytes = 0;
2186 
2187 #ifdef COMPILER2
2188   use_sve = Matcher::supports_scalable_vector();
2189   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
2190 #endif
2191   // Scan bitset to accumulate register pairs
2192   unsigned char regs[32];
2193   int count = 0;
2194   for (int reg = 0; reg <= 31; reg++) {
2195     if (1 & bitset)
2196       regs[count++] = reg;
2197     bitset >>= 1;
2198   }
2199 
2200   if (count == 0) {
2201     return 0;
2202   }
2203 
2204   // SVE
2205   if (use_sve && sve_vector_size_in_bytes > 16) {
2206     for (int i = count - 1; i >= 0; i--) {
2207       sve_ldr(as_FloatRegister(regs[i]), Address(stack, i));
2208     }
2209     add(stack, stack, sve_vector_size_in_bytes * count);
2210     return count * sve_vector_size_in_bytes / 8;
2211   }
2212 
2213   // NEON
2214   if (count == 1) {
2215     ldrq(as_FloatRegister(regs[0]), Address(post(stack, wordSize * 2)));
2216     return 2;
2217   }
2218 
2219   bool odd = (count & 1) == 1;
2220   int push_slots = count + (odd ? 1 : 0);
2221 
2222   if (odd) {
2223     ldrq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
2224     words_pushed++;
2225   }
2226 
2227   for (int i = 2; i + 1 < count; i += 2) {
2228     ldpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
2229     words_pushed += 2;
2230   }
2231 
2232   ldpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(post(stack, push_slots * wordSize * 2)));
2233   words_pushed += 2;
2234 
2235   assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
2236 
2237   return count * 2;
2238 }
2239 
2240 #ifdef ASSERT
2241 void MacroAssembler::verify_heapbase(const char* msg) {
2242 #if 0
2243   assert (UseCompressedOops || UseCompressedClassPointers, "should be compressed");
2244   assert (Universe::heap() != NULL, "java heap should be initialized");
2245   if (!UseCompressedOops || Universe::ptr_base() == NULL) {
2246     // rheapbase is allocated as general register
2247     return;
2248   }
2249   if (CheckCompressedOops) {
2250     Label ok;
2251     push(1 << rscratch1->encoding(), sp); // cmpptr trashes rscratch1
2252     cmpptr(rheapbase, ExternalAddress((address)CompressedOops::ptrs_base_addr()));
2253     br(Assembler::EQ, ok);
2254     stop(msg);
2255     bind(ok);
2256     pop(1 << rscratch1->encoding(), sp);
2257   }
2258 #endif
2259 }
2260 #endif
2261 
2262 void MacroAssembler::resolve_jobject(Register value, Register thread, Register tmp) {
2263   Label done, not_weak;
2264   cbz(value, done);           // Use NULL as-is.
2265 
2266   STATIC_ASSERT(JNIHandles::weak_tag_mask == 1u);
2267   tbz(r0, 0, not_weak);    // Test for jweak tag.
2268 
2269   // Resolve jweak.
2270   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF, value,
2271                  Address(value, -JNIHandles::weak_tag_value), tmp, thread);
2272   verify_oop(value);
2273   b(done);
2274 
2275   bind(not_weak);
2276   // Resolve (untagged) jobject.
2277   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, 0), tmp, thread);
2278   verify_oop(value);
2279   bind(done);
2280 }
2281 
2282 void MacroAssembler::stop(const char* msg) {
2283   BLOCK_COMMENT(msg);
2284   dcps1(0xdeae);
2285   emit_int64((uintptr_t)msg);
2286 }
2287 
2288 void MacroAssembler::unimplemented(const char* what) {
2289   const char* buf = NULL;
2290   {
2291     ResourceMark rm;
2292     stringStream ss;
2293     ss.print("unimplemented: %s", what);
2294     buf = code_string(ss.as_string());
2295   }
2296   stop(buf);
2297 }
2298 
2299 // If a constant does not fit in an immediate field, generate some
2300 // number of MOV instructions and then perform the operation.
2301 void MacroAssembler::wrap_add_sub_imm_insn(Register Rd, Register Rn, uint64_t imm,
2302                                            add_sub_imm_insn insn1,
2303                                            add_sub_reg_insn insn2,
2304                                            bool is32) {
2305   assert(Rd != zr, "Rd = zr and not setting flags?");
2306   bool fits = operand_valid_for_add_sub_immediate(is32 ? (int32_t)imm : imm);
2307   if (fits) {
2308     (this->*insn1)(Rd, Rn, imm);
2309   } else {
2310     if (uabs(imm) < (1 << 24)) {
2311        (this->*insn1)(Rd, Rn, imm & -(1 << 12));
2312        (this->*insn1)(Rd, Rd, imm & ((1 << 12)-1));
2313     } else {
2314        assert_different_registers(Rd, Rn);
2315        mov(Rd, imm);
2316        (this->*insn2)(Rd, Rn, Rd, LSL, 0);
2317     }
2318   }
2319 }
2320 
2321 // Seperate vsn which sets the flags. Optimisations are more restricted
2322 // because we must set the flags correctly.
2323 void MacroAssembler::wrap_adds_subs_imm_insn(Register Rd, Register Rn, uint64_t imm,
2324                                              add_sub_imm_insn insn1,
2325                                              add_sub_reg_insn insn2,
2326                                              bool is32) {
2327   bool fits = operand_valid_for_add_sub_immediate(is32 ? (int32_t)imm : imm);
2328   if (fits) {
2329     (this->*insn1)(Rd, Rn, imm);
2330   } else {
2331     assert_different_registers(Rd, Rn);
2332     assert(Rd != zr, "overflow in immediate operand");
2333     mov(Rd, imm);
2334     (this->*insn2)(Rd, Rn, Rd, LSL, 0);
2335   }
2336 }
2337 
2338 
2339 void MacroAssembler::add(Register Rd, Register Rn, RegisterOrConstant increment) {
2340   if (increment.is_register()) {
2341     add(Rd, Rn, increment.as_register());
2342   } else {
2343     add(Rd, Rn, increment.as_constant());
2344   }
2345 }
2346 
2347 void MacroAssembler::addw(Register Rd, Register Rn, RegisterOrConstant increment) {
2348   if (increment.is_register()) {
2349     addw(Rd, Rn, increment.as_register());
2350   } else {
2351     addw(Rd, Rn, increment.as_constant());
2352   }
2353 }
2354 
2355 void MacroAssembler::sub(Register Rd, Register Rn, RegisterOrConstant decrement) {
2356   if (decrement.is_register()) {
2357     sub(Rd, Rn, decrement.as_register());
2358   } else {
2359     sub(Rd, Rn, decrement.as_constant());
2360   }
2361 }
2362 
2363 void MacroAssembler::subw(Register Rd, Register Rn, RegisterOrConstant decrement) {
2364   if (decrement.is_register()) {
2365     subw(Rd, Rn, decrement.as_register());
2366   } else {
2367     subw(Rd, Rn, decrement.as_constant());
2368   }
2369 }
2370 
2371 void MacroAssembler::reinit_heapbase()
2372 {
2373   if (UseCompressedOops) {
2374     if (Universe::is_fully_initialized()) {
2375       mov(rheapbase, CompressedOops::ptrs_base());
2376     } else {
2377       lea(rheapbase, ExternalAddress((address)CompressedOops::ptrs_base_addr()));
2378       ldr(rheapbase, Address(rheapbase));
2379     }
2380   }
2381 }
2382 
2383 // this simulates the behaviour of the x86 cmpxchg instruction using a
2384 // load linked/store conditional pair. we use the acquire/release
2385 // versions of these instructions so that we flush pending writes as
2386 // per Java semantics.
2387 
2388 // n.b the x86 version assumes the old value to be compared against is
2389 // in rax and updates rax with the value located in memory if the
2390 // cmpxchg fails. we supply a register for the old value explicitly
2391 
2392 // the aarch64 load linked/store conditional instructions do not
2393 // accept an offset. so, unlike x86, we must provide a plain register
2394 // to identify the memory word to be compared/exchanged rather than a
2395 // register+offset Address.
2396 
2397 void MacroAssembler::cmpxchgptr(Register oldv, Register newv, Register addr, Register tmp,
2398                                 Label &succeed, Label *fail) {
2399   // oldv holds comparison value
2400   // newv holds value to write in exchange
2401   // addr identifies memory word to compare against/update
2402   if (UseLSE) {
2403     mov(tmp, oldv);
2404     casal(Assembler::xword, oldv, newv, addr);
2405     cmp(tmp, oldv);
2406     br(Assembler::EQ, succeed);
2407     membar(AnyAny);
2408   } else {
2409     Label retry_load, nope;
2410     if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))
2411       prfm(Address(addr), PSTL1STRM);
2412     bind(retry_load);
2413     // flush and load exclusive from the memory location
2414     // and fail if it is not what we expect
2415     ldaxr(tmp, addr);
2416     cmp(tmp, oldv);
2417     br(Assembler::NE, nope);
2418     // if we store+flush with no intervening write tmp wil be zero
2419     stlxr(tmp, newv, addr);
2420     cbzw(tmp, succeed);
2421     // retry so we only ever return after a load fails to compare
2422     // ensures we don't return a stale value after a failed write.
2423     b(retry_load);
2424     // if the memory word differs we return it in oldv and signal a fail
2425     bind(nope);
2426     membar(AnyAny);
2427     mov(oldv, tmp);
2428   }
2429   if (fail)
2430     b(*fail);
2431 }
2432 
2433 void MacroAssembler::cmpxchg_obj_header(Register oldv, Register newv, Register obj, Register tmp,
2434                                         Label &succeed, Label *fail) {
2435   assert(oopDesc::mark_offset_in_bytes() == 0, "assumption");
2436   cmpxchgptr(oldv, newv, obj, tmp, succeed, fail);
2437 }
2438 
2439 void MacroAssembler::cmpxchgw(Register oldv, Register newv, Register addr, Register tmp,
2440                                 Label &succeed, Label *fail) {
2441   // oldv holds comparison value
2442   // newv holds value to write in exchange
2443   // addr identifies memory word to compare against/update
2444   // tmp returns 0/1 for success/failure
2445   if (UseLSE) {
2446     mov(tmp, oldv);
2447     casal(Assembler::word, oldv, newv, addr);
2448     cmp(tmp, oldv);
2449     br(Assembler::EQ, succeed);
2450     membar(AnyAny);
2451   } else {
2452     Label retry_load, nope;
2453     if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))
2454       prfm(Address(addr), PSTL1STRM);
2455     bind(retry_load);
2456     // flush and load exclusive from the memory location
2457     // and fail if it is not what we expect
2458     ldaxrw(tmp, addr);
2459     cmp(tmp, oldv);
2460     br(Assembler::NE, nope);
2461     // if we store+flush with no intervening write tmp wil be zero
2462     stlxrw(tmp, newv, addr);
2463     cbzw(tmp, succeed);
2464     // retry so we only ever return after a load fails to compare
2465     // ensures we don't return a stale value after a failed write.
2466     b(retry_load);
2467     // if the memory word differs we return it in oldv and signal a fail
2468     bind(nope);
2469     membar(AnyAny);
2470     mov(oldv, tmp);
2471   }
2472   if (fail)
2473     b(*fail);
2474 }
2475 
2476 // A generic CAS; success or failure is in the EQ flag.  A weak CAS
2477 // doesn't retry and may fail spuriously.  If the oldval is wanted,
2478 // Pass a register for the result, otherwise pass noreg.
2479 
2480 // Clobbers rscratch1
2481 void MacroAssembler::cmpxchg(Register addr, Register expected,
2482                              Register new_val,
2483                              enum operand_size size,
2484                              bool acquire, bool release,
2485                              bool weak,
2486                              Register result) {
2487   if (result == noreg)  result = rscratch1;
2488   BLOCK_COMMENT("cmpxchg {");
2489   if (UseLSE) {
2490     mov(result, expected);
2491     lse_cas(result, new_val, addr, size, acquire, release, /*not_pair*/ true);
2492     compare_eq(result, expected, size);
2493   } else {
2494     Label retry_load, done;
2495     if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))
2496       prfm(Address(addr), PSTL1STRM);
2497     bind(retry_load);
2498     load_exclusive(result, addr, size, acquire);
2499     compare_eq(result, expected, size);
2500     br(Assembler::NE, done);
2501     store_exclusive(rscratch1, new_val, addr, size, release);
2502     if (weak) {
2503       cmpw(rscratch1, 0u);  // If the store fails, return NE to our caller.
2504     } else {
2505       cbnzw(rscratch1, retry_load);
2506     }
2507     bind(done);
2508   }
2509   BLOCK_COMMENT("} cmpxchg");
2510 }
2511 
2512 // A generic comparison. Only compares for equality, clobbers rscratch1.
2513 void MacroAssembler::compare_eq(Register rm, Register rn, enum operand_size size) {
2514   if (size == xword) {
2515     cmp(rm, rn);
2516   } else if (size == word) {
2517     cmpw(rm, rn);
2518   } else if (size == halfword) {
2519     eorw(rscratch1, rm, rn);
2520     ands(zr, rscratch1, 0xffff);
2521   } else if (size == byte) {
2522     eorw(rscratch1, rm, rn);
2523     ands(zr, rscratch1, 0xff);
2524   } else {
2525     ShouldNotReachHere();
2526   }
2527 }
2528 
2529 
2530 static bool different(Register a, RegisterOrConstant b, Register c) {
2531   if (b.is_constant())
2532     return a != c;
2533   else
2534     return a != b.as_register() && a != c && b.as_register() != c;
2535 }
2536 
2537 #define ATOMIC_OP(NAME, LDXR, OP, IOP, AOP, STXR, sz)                   \
2538 void MacroAssembler::atomic_##NAME(Register prev, RegisterOrConstant incr, Register addr) { \
2539   if (UseLSE) {                                                         \
2540     prev = prev->is_valid() ? prev : zr;                                \
2541     if (incr.is_register()) {                                           \
2542       AOP(sz, incr.as_register(), prev, addr);                          \
2543     } else {                                                            \
2544       mov(rscratch2, incr.as_constant());                               \
2545       AOP(sz, rscratch2, prev, addr);                                   \
2546     }                                                                   \
2547     return;                                                             \
2548   }                                                                     \
2549   Register result = rscratch2;                                          \
2550   if (prev->is_valid())                                                 \
2551     result = different(prev, incr, addr) ? prev : rscratch2;            \
2552                                                                         \
2553   Label retry_load;                                                     \
2554   if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))         \
2555     prfm(Address(addr), PSTL1STRM);                                     \
2556   bind(retry_load);                                                     \
2557   LDXR(result, addr);                                                   \
2558   OP(rscratch1, result, incr);                                          \
2559   STXR(rscratch2, rscratch1, addr);                                     \
2560   cbnzw(rscratch2, retry_load);                                         \
2561   if (prev->is_valid() && prev != result) {                             \
2562     IOP(prev, rscratch1, incr);                                         \
2563   }                                                                     \
2564 }
2565 
2566 ATOMIC_OP(add, ldxr, add, sub, ldadd, stxr, Assembler::xword)
2567 ATOMIC_OP(addw, ldxrw, addw, subw, ldadd, stxrw, Assembler::word)
2568 ATOMIC_OP(addal, ldaxr, add, sub, ldaddal, stlxr, Assembler::xword)
2569 ATOMIC_OP(addalw, ldaxrw, addw, subw, ldaddal, stlxrw, Assembler::word)
2570 
2571 #undef ATOMIC_OP
2572 
2573 #define ATOMIC_XCHG(OP, AOP, LDXR, STXR, sz)                            \
2574 void MacroAssembler::atomic_##OP(Register prev, Register newv, Register addr) { \
2575   if (UseLSE) {                                                         \
2576     prev = prev->is_valid() ? prev : zr;                                \
2577     AOP(sz, newv, prev, addr);                                          \
2578     return;                                                             \
2579   }                                                                     \
2580   Register result = rscratch2;                                          \
2581   if (prev->is_valid())                                                 \
2582     result = different(prev, newv, addr) ? prev : rscratch2;            \
2583                                                                         \
2584   Label retry_load;                                                     \
2585   if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))         \
2586     prfm(Address(addr), PSTL1STRM);                                     \
2587   bind(retry_load);                                                     \
2588   LDXR(result, addr);                                                   \
2589   STXR(rscratch1, newv, addr);                                          \
2590   cbnzw(rscratch1, retry_load);                                         \
2591   if (prev->is_valid() && prev != result)                               \
2592     mov(prev, result);                                                  \
2593 }
2594 
2595 ATOMIC_XCHG(xchg, swp, ldxr, stxr, Assembler::xword)
2596 ATOMIC_XCHG(xchgw, swp, ldxrw, stxrw, Assembler::word)
2597 ATOMIC_XCHG(xchgl, swpl, ldxr, stlxr, Assembler::xword)
2598 ATOMIC_XCHG(xchglw, swpl, ldxrw, stlxrw, Assembler::word)
2599 ATOMIC_XCHG(xchgal, swpal, ldaxr, stlxr, Assembler::xword)
2600 ATOMIC_XCHG(xchgalw, swpal, ldaxrw, stlxrw, Assembler::word)
2601 
2602 #undef ATOMIC_XCHG
2603 
2604 #ifndef PRODUCT
2605 extern "C" void findpc(intptr_t x);
2606 #endif
2607 
2608 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[])
2609 {
2610   // In order to get locks to work, we need to fake a in_VM state
2611   if (ShowMessageBoxOnError ) {
2612     JavaThread* thread = JavaThread::current();
2613     JavaThreadState saved_state = thread->thread_state();
2614     thread->set_thread_state(_thread_in_vm);
2615 #ifndef PRODUCT
2616     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
2617       ttyLocker ttyl;
2618       BytecodeCounter::print();
2619     }
2620 #endif
2621     if (os::message_box(msg, "Execution stopped, print registers?")) {
2622       ttyLocker ttyl;
2623       tty->print_cr(" pc = 0x%016" PRIx64, pc);
2624 #ifndef PRODUCT
2625       tty->cr();
2626       findpc(pc);
2627       tty->cr();
2628 #endif
2629       tty->print_cr(" r0 = 0x%016" PRIx64, regs[0]);
2630       tty->print_cr(" r1 = 0x%016" PRIx64, regs[1]);
2631       tty->print_cr(" r2 = 0x%016" PRIx64, regs[2]);
2632       tty->print_cr(" r3 = 0x%016" PRIx64, regs[3]);
2633       tty->print_cr(" r4 = 0x%016" PRIx64, regs[4]);
2634       tty->print_cr(" r5 = 0x%016" PRIx64, regs[5]);
2635       tty->print_cr(" r6 = 0x%016" PRIx64, regs[6]);
2636       tty->print_cr(" r7 = 0x%016" PRIx64, regs[7]);
2637       tty->print_cr(" r8 = 0x%016" PRIx64, regs[8]);
2638       tty->print_cr(" r9 = 0x%016" PRIx64, regs[9]);
2639       tty->print_cr("r10 = 0x%016" PRIx64, regs[10]);
2640       tty->print_cr("r11 = 0x%016" PRIx64, regs[11]);
2641       tty->print_cr("r12 = 0x%016" PRIx64, regs[12]);
2642       tty->print_cr("r13 = 0x%016" PRIx64, regs[13]);
2643       tty->print_cr("r14 = 0x%016" PRIx64, regs[14]);
2644       tty->print_cr("r15 = 0x%016" PRIx64, regs[15]);
2645       tty->print_cr("r16 = 0x%016" PRIx64, regs[16]);
2646       tty->print_cr("r17 = 0x%016" PRIx64, regs[17]);
2647       tty->print_cr("r18 = 0x%016" PRIx64, regs[18]);
2648       tty->print_cr("r19 = 0x%016" PRIx64, regs[19]);
2649       tty->print_cr("r20 = 0x%016" PRIx64, regs[20]);
2650       tty->print_cr("r21 = 0x%016" PRIx64, regs[21]);
2651       tty->print_cr("r22 = 0x%016" PRIx64, regs[22]);
2652       tty->print_cr("r23 = 0x%016" PRIx64, regs[23]);
2653       tty->print_cr("r24 = 0x%016" PRIx64, regs[24]);
2654       tty->print_cr("r25 = 0x%016" PRIx64, regs[25]);
2655       tty->print_cr("r26 = 0x%016" PRIx64, regs[26]);
2656       tty->print_cr("r27 = 0x%016" PRIx64, regs[27]);
2657       tty->print_cr("r28 = 0x%016" PRIx64, regs[28]);
2658       tty->print_cr("r30 = 0x%016" PRIx64, regs[30]);
2659       tty->print_cr("r31 = 0x%016" PRIx64, regs[31]);
2660       BREAKPOINT;
2661     }
2662   }
2663   fatal("DEBUG MESSAGE: %s", msg);
2664 }
2665 
2666 RegSet MacroAssembler::call_clobbered_registers() {
2667   RegSet regs = RegSet::range(r0, r17) - RegSet::of(rscratch1, rscratch2);
2668 #ifndef R18_RESERVED
2669   regs += r18_tls;
2670 #endif
2671   return regs;
2672 }
2673 
2674 void MacroAssembler::push_call_clobbered_registers_except(RegSet exclude) {
2675   int step = 4 * wordSize;
2676   push(call_clobbered_registers() - exclude, sp);
2677   sub(sp, sp, step);
2678   mov(rscratch1, -step);
2679   // Push v0-v7, v16-v31.
2680   for (int i = 31; i>= 4; i -= 4) {
2681     if (i <= v7->encoding() || i >= v16->encoding())
2682       st1(as_FloatRegister(i-3), as_FloatRegister(i-2), as_FloatRegister(i-1),
2683           as_FloatRegister(i), T1D, Address(post(sp, rscratch1)));
2684   }
2685   st1(as_FloatRegister(0), as_FloatRegister(1), as_FloatRegister(2),
2686       as_FloatRegister(3), T1D, Address(sp));
2687 }
2688 
2689 void MacroAssembler::pop_call_clobbered_registers_except(RegSet exclude) {
2690   for (int i = 0; i < 32; i += 4) {
2691     if (i <= v7->encoding() || i >= v16->encoding())
2692       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
2693           as_FloatRegister(i+3), T1D, Address(post(sp, 4 * wordSize)));
2694   }
2695 
2696   reinitialize_ptrue();
2697 
2698   pop(call_clobbered_registers() - exclude, sp);
2699 }
2700 
2701 void MacroAssembler::push_CPU_state(bool save_vectors, bool use_sve,
2702                                     int sve_vector_size_in_bytes) {
2703   push(RegSet::range(r0, r29), sp); // integer registers except lr & sp
2704   if (save_vectors && use_sve && sve_vector_size_in_bytes > 16) {
2705     sub(sp, sp, sve_vector_size_in_bytes * FloatRegisterImpl::number_of_registers);
2706     for (int i = 0; i < FloatRegisterImpl::number_of_registers; i++) {
2707       sve_str(as_FloatRegister(i), Address(sp, i));
2708     }
2709   } else {
2710     int step = (save_vectors ? 8 : 4) * wordSize;
2711     mov(rscratch1, -step);
2712     sub(sp, sp, step);
2713     for (int i = 28; i >= 4; i -= 4) {
2714       st1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
2715           as_FloatRegister(i+3), save_vectors ? T2D : T1D, Address(post(sp, rscratch1)));
2716     }
2717     st1(v0, v1, v2, v3, save_vectors ? T2D : T1D, sp);
2718   }
2719 }
2720 
2721 void MacroAssembler::pop_CPU_state(bool restore_vectors, bool use_sve,
2722                                    int sve_vector_size_in_bytes) {
2723   if (restore_vectors && use_sve && sve_vector_size_in_bytes > 16) {
2724     for (int i = FloatRegisterImpl::number_of_registers - 1; i >= 0; i--) {
2725       sve_ldr(as_FloatRegister(i), Address(sp, i));
2726     }
2727     add(sp, sp, sve_vector_size_in_bytes * FloatRegisterImpl::number_of_registers);
2728   } else {
2729     int step = (restore_vectors ? 8 : 4) * wordSize;
2730     for (int i = 0; i <= 28; i += 4)
2731       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
2732           as_FloatRegister(i+3), restore_vectors ? T2D : T1D, Address(post(sp, step)));
2733   }
2734 
2735   if (restore_vectors) {
2736     reinitialize_ptrue();
2737   }
2738 
2739   // integer registers except lr & sp
2740   pop(RegSet::range(r0, r17), sp);
2741 #ifdef R18_RESERVED
2742   ldp(zr, r19, Address(post(sp, 2 * wordSize)));
2743   pop(RegSet::range(r20, r29), sp);
2744 #else
2745   pop(RegSet::range(r18_tls, r29), sp);
2746 #endif
2747 }
2748 
2749 /**
2750  * Helpers for multiply_to_len().
2751  */
2752 void MacroAssembler::add2_with_carry(Register final_dest_hi, Register dest_hi, Register dest_lo,
2753                                      Register src1, Register src2) {
2754   adds(dest_lo, dest_lo, src1);
2755   adc(dest_hi, dest_hi, zr);
2756   adds(dest_lo, dest_lo, src2);
2757   adc(final_dest_hi, dest_hi, zr);
2758 }
2759 
2760 // Generate an address from (r + r1 extend offset).  "size" is the
2761 // size of the operand.  The result may be in rscratch2.
2762 Address MacroAssembler::offsetted_address(Register r, Register r1,
2763                                           Address::extend ext, int offset, int size) {
2764   if (offset || (ext.shift() % size != 0)) {
2765     lea(rscratch2, Address(r, r1, ext));
2766     return Address(rscratch2, offset);
2767   } else {
2768     return Address(r, r1, ext);
2769   }
2770 }
2771 
2772 Address MacroAssembler::spill_address(int size, int offset, Register tmp)
2773 {
2774   assert(offset >= 0, "spill to negative address?");
2775   // Offset reachable ?
2776   //   Not aligned - 9 bits signed offset
2777   //   Aligned - 12 bits unsigned offset shifted
2778   Register base = sp;
2779   if ((offset & (size-1)) && offset >= (1<<8)) {
2780     add(tmp, base, offset & ((1<<12)-1));
2781     base = tmp;
2782     offset &= -1u<<12;
2783   }
2784 
2785   if (offset >= (1<<12) * size) {
2786     add(tmp, base, offset & (((1<<12)-1)<<12));
2787     base = tmp;
2788     offset &= ~(((1<<12)-1)<<12);
2789   }
2790 
2791   return Address(base, offset);
2792 }
2793 
2794 Address MacroAssembler::sve_spill_address(int sve_reg_size_in_bytes, int offset, Register tmp) {
2795   assert(offset >= 0, "spill to negative address?");
2796 
2797   Register base = sp;
2798 
2799   // An immediate offset in the range 0 to 255 which is multiplied
2800   // by the current vector or predicate register size in bytes.
2801   if (offset % sve_reg_size_in_bytes == 0 && offset < ((1<<8)*sve_reg_size_in_bytes)) {
2802     return Address(base, offset / sve_reg_size_in_bytes);
2803   }
2804 
2805   add(tmp, base, offset);
2806   return Address(tmp);
2807 }
2808 
2809 // Checks whether offset is aligned.
2810 // Returns true if it is, else false.
2811 bool MacroAssembler::merge_alignment_check(Register base,
2812                                            size_t size,
2813                                            int64_t cur_offset,
2814                                            int64_t prev_offset) const {
2815   if (AvoidUnalignedAccesses) {
2816     if (base == sp) {
2817       // Checks whether low offset if aligned to pair of registers.
2818       int64_t pair_mask = size * 2 - 1;
2819       int64_t offset = prev_offset > cur_offset ? cur_offset : prev_offset;
2820       return (offset & pair_mask) == 0;
2821     } else { // If base is not sp, we can't guarantee the access is aligned.
2822       return false;
2823     }
2824   } else {
2825     int64_t mask = size - 1;
2826     // Load/store pair instruction only supports element size aligned offset.
2827     return (cur_offset & mask) == 0 && (prev_offset & mask) == 0;
2828   }
2829 }
2830 
2831 // Checks whether current and previous loads/stores can be merged.
2832 // Returns true if it can be merged, else false.
2833 bool MacroAssembler::ldst_can_merge(Register rt,
2834                                     const Address &adr,
2835                                     size_t cur_size_in_bytes,
2836                                     bool is_store) const {
2837   address prev = pc() - NativeInstruction::instruction_size;
2838   address last = code()->last_insn();
2839 
2840   if (last == NULL || !nativeInstruction_at(last)->is_Imm_LdSt()) {
2841     return false;
2842   }
2843 
2844   if (adr.getMode() != Address::base_plus_offset || prev != last) {
2845     return false;
2846   }
2847 
2848   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
2849   size_t prev_size_in_bytes = prev_ldst->size_in_bytes();
2850 
2851   assert(prev_size_in_bytes == 4 || prev_size_in_bytes == 8, "only supports 64/32bit merging.");
2852   assert(cur_size_in_bytes == 4 || cur_size_in_bytes == 8, "only supports 64/32bit merging.");
2853 
2854   if (cur_size_in_bytes != prev_size_in_bytes || is_store != prev_ldst->is_store()) {
2855     return false;
2856   }
2857 
2858   int64_t max_offset = 63 * prev_size_in_bytes;
2859   int64_t min_offset = -64 * prev_size_in_bytes;
2860 
2861   assert(prev_ldst->is_not_pre_post_index(), "pre-index or post-index is not supported to be merged.");
2862 
2863   // Only same base can be merged.
2864   if (adr.base() != prev_ldst->base()) {
2865     return false;
2866   }
2867 
2868   int64_t cur_offset = adr.offset();
2869   int64_t prev_offset = prev_ldst->offset();
2870   size_t diff = abs(cur_offset - prev_offset);
2871   if (diff != prev_size_in_bytes) {
2872     return false;
2873   }
2874 
2875   // Following cases can not be merged:
2876   // ldr x2, [x2, #8]
2877   // ldr x3, [x2, #16]
2878   // or:
2879   // ldr x2, [x3, #8]
2880   // ldr x2, [x3, #16]
2881   // If t1 and t2 is the same in "ldp t1, t2, [xn, #imm]", we'll get SIGILL.
2882   if (!is_store && (adr.base() == prev_ldst->target() || rt == prev_ldst->target())) {
2883     return false;
2884   }
2885 
2886   int64_t low_offset = prev_offset > cur_offset ? cur_offset : prev_offset;
2887   // Offset range must be in ldp/stp instruction's range.
2888   if (low_offset > max_offset || low_offset < min_offset) {
2889     return false;
2890   }
2891 
2892   if (merge_alignment_check(adr.base(), prev_size_in_bytes, cur_offset, prev_offset)) {
2893     return true;
2894   }
2895 
2896   return false;
2897 }
2898 
2899 // Merge current load/store with previous load/store into ldp/stp.
2900 void MacroAssembler::merge_ldst(Register rt,
2901                                 const Address &adr,
2902                                 size_t cur_size_in_bytes,
2903                                 bool is_store) {
2904 
2905   assert(ldst_can_merge(rt, adr, cur_size_in_bytes, is_store) == true, "cur and prev must be able to be merged.");
2906 
2907   Register rt_low, rt_high;
2908   address prev = pc() - NativeInstruction::instruction_size;
2909   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
2910 
2911   int64_t offset;
2912 
2913   if (adr.offset() < prev_ldst->offset()) {
2914     offset = adr.offset();
2915     rt_low = rt;
2916     rt_high = prev_ldst->target();
2917   } else {
2918     offset = prev_ldst->offset();
2919     rt_low = prev_ldst->target();
2920     rt_high = rt;
2921   }
2922 
2923   Address adr_p = Address(prev_ldst->base(), offset);
2924   // Overwrite previous generated binary.
2925   code_section()->set_end(prev);
2926 
2927   const size_t sz = prev_ldst->size_in_bytes();
2928   assert(sz == 8 || sz == 4, "only supports 64/32bit merging.");
2929   if (!is_store) {
2930     BLOCK_COMMENT("merged ldr pair");
2931     if (sz == 8) {
2932       ldp(rt_low, rt_high, adr_p);
2933     } else {
2934       ldpw(rt_low, rt_high, adr_p);
2935     }
2936   } else {
2937     BLOCK_COMMENT("merged str pair");
2938     if (sz == 8) {
2939       stp(rt_low, rt_high, adr_p);
2940     } else {
2941       stpw(rt_low, rt_high, adr_p);
2942     }
2943   }
2944 }
2945 
2946 /**
2947  * Multiply 64 bit by 64 bit first loop.
2948  */
2949 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
2950                                            Register y, Register y_idx, Register z,
2951                                            Register carry, Register product,
2952                                            Register idx, Register kdx) {
2953   //
2954   //  jlong carry, x[], y[], z[];
2955   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
2956   //    huge_128 product = y[idx] * x[xstart] + carry;
2957   //    z[kdx] = (jlong)product;
2958   //    carry  = (jlong)(product >>> 64);
2959   //  }
2960   //  z[xstart] = carry;
2961   //
2962 
2963   Label L_first_loop, L_first_loop_exit;
2964   Label L_one_x, L_one_y, L_multiply;
2965 
2966   subsw(xstart, xstart, 1);
2967   br(Assembler::MI, L_one_x);
2968 
2969   lea(rscratch1, Address(x, xstart, Address::lsl(LogBytesPerInt)));
2970   ldr(x_xstart, Address(rscratch1));
2971   ror(x_xstart, x_xstart, 32); // convert big-endian to little-endian
2972 
2973   bind(L_first_loop);
2974   subsw(idx, idx, 1);
2975   br(Assembler::MI, L_first_loop_exit);
2976   subsw(idx, idx, 1);
2977   br(Assembler::MI, L_one_y);
2978   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2979   ldr(y_idx, Address(rscratch1));
2980   ror(y_idx, y_idx, 32); // convert big-endian to little-endian
2981   bind(L_multiply);
2982 
2983   // AArch64 has a multiply-accumulate instruction that we can't use
2984   // here because it has no way to process carries, so we have to use
2985   // separate add and adc instructions.  Bah.
2986   umulh(rscratch1, x_xstart, y_idx); // x_xstart * y_idx -> rscratch1:product
2987   mul(product, x_xstart, y_idx);
2988   adds(product, product, carry);
2989   adc(carry, rscratch1, zr);   // x_xstart * y_idx + carry -> carry:product
2990 
2991   subw(kdx, kdx, 2);
2992   ror(product, product, 32); // back to big-endian
2993   str(product, offsetted_address(z, kdx, Address::uxtw(LogBytesPerInt), 0, BytesPerLong));
2994 
2995   b(L_first_loop);
2996 
2997   bind(L_one_y);
2998   ldrw(y_idx, Address(y,  0));
2999   b(L_multiply);
3000 
3001   bind(L_one_x);
3002   ldrw(x_xstart, Address(x,  0));
3003   b(L_first_loop);
3004 
3005   bind(L_first_loop_exit);
3006 }
3007 
3008 /**
3009  * Multiply 128 bit by 128. Unrolled inner loop.
3010  *
3011  */
3012 void MacroAssembler::multiply_128_x_128_loop(Register y, Register z,
3013                                              Register carry, Register carry2,
3014                                              Register idx, Register jdx,
3015                                              Register yz_idx1, Register yz_idx2,
3016                                              Register tmp, Register tmp3, Register tmp4,
3017                                              Register tmp6, Register product_hi) {
3018 
3019   //   jlong carry, x[], y[], z[];
3020   //   int kdx = ystart+1;
3021   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
3022   //     huge_128 tmp3 = (y[idx+1] * product_hi) + z[kdx+idx+1] + carry;
3023   //     jlong carry2  = (jlong)(tmp3 >>> 64);
3024   //     huge_128 tmp4 = (y[idx]   * product_hi) + z[kdx+idx] + carry2;
3025   //     carry  = (jlong)(tmp4 >>> 64);
3026   //     z[kdx+idx+1] = (jlong)tmp3;
3027   //     z[kdx+idx] = (jlong)tmp4;
3028   //   }
3029   //   idx += 2;
3030   //   if (idx > 0) {
3031   //     yz_idx1 = (y[idx] * product_hi) + z[kdx+idx] + carry;
3032   //     z[kdx+idx] = (jlong)yz_idx1;
3033   //     carry  = (jlong)(yz_idx1 >>> 64);
3034   //   }
3035   //
3036 
3037   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
3038 
3039   lsrw(jdx, idx, 2);
3040 
3041   bind(L_third_loop);
3042 
3043   subsw(jdx, jdx, 1);
3044   br(Assembler::MI, L_third_loop_exit);
3045   subw(idx, idx, 4);
3046 
3047   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
3048 
3049   ldp(yz_idx2, yz_idx1, Address(rscratch1, 0));
3050 
3051   lea(tmp6, Address(z, idx, Address::uxtw(LogBytesPerInt)));
3052 
3053   ror(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
3054   ror(yz_idx2, yz_idx2, 32);
3055 
3056   ldp(rscratch2, rscratch1, Address(tmp6, 0));
3057 
3058   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
3059   umulh(tmp4, product_hi, yz_idx1);
3060 
3061   ror(rscratch1, rscratch1, 32); // convert big-endian to little-endian
3062   ror(rscratch2, rscratch2, 32);
3063 
3064   mul(tmp, product_hi, yz_idx2);   //  yz_idx2 * product_hi -> carry2:tmp
3065   umulh(carry2, product_hi, yz_idx2);
3066 
3067   // propagate sum of both multiplications into carry:tmp4:tmp3
3068   adds(tmp3, tmp3, carry);
3069   adc(tmp4, tmp4, zr);
3070   adds(tmp3, tmp3, rscratch1);
3071   adcs(tmp4, tmp4, tmp);
3072   adc(carry, carry2, zr);
3073   adds(tmp4, tmp4, rscratch2);
3074   adc(carry, carry, zr);
3075 
3076   ror(tmp3, tmp3, 32); // convert little-endian to big-endian
3077   ror(tmp4, tmp4, 32);
3078   stp(tmp4, tmp3, Address(tmp6, 0));
3079 
3080   b(L_third_loop);
3081   bind (L_third_loop_exit);
3082 
3083   andw (idx, idx, 0x3);
3084   cbz(idx, L_post_third_loop_done);
3085 
3086   Label L_check_1;
3087   subsw(idx, idx, 2);
3088   br(Assembler::MI, L_check_1);
3089 
3090   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
3091   ldr(yz_idx1, Address(rscratch1, 0));
3092   ror(yz_idx1, yz_idx1, 32);
3093   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
3094   umulh(tmp4, product_hi, yz_idx1);
3095   lea(rscratch1, Address(z, idx, Address::uxtw(LogBytesPerInt)));
3096   ldr(yz_idx2, Address(rscratch1, 0));
3097   ror(yz_idx2, yz_idx2, 32);
3098 
3099   add2_with_carry(carry, tmp4, tmp3, carry, yz_idx2);
3100 
3101   ror(tmp3, tmp3, 32);
3102   str(tmp3, Address(rscratch1, 0));
3103 
3104   bind (L_check_1);
3105 
3106   andw (idx, idx, 0x1);
3107   subsw(idx, idx, 1);
3108   br(Assembler::MI, L_post_third_loop_done);
3109   ldrw(tmp4, Address(y, idx, Address::uxtw(LogBytesPerInt)));
3110   mul(tmp3, tmp4, product_hi);  //  tmp4 * product_hi -> carry2:tmp3
3111   umulh(carry2, tmp4, product_hi);
3112   ldrw(tmp4, Address(z, idx, Address::uxtw(LogBytesPerInt)));
3113 
3114   add2_with_carry(carry2, tmp3, tmp4, carry);
3115 
3116   strw(tmp3, Address(z, idx, Address::uxtw(LogBytesPerInt)));
3117   extr(carry, carry2, tmp3, 32);
3118 
3119   bind(L_post_third_loop_done);
3120 }
3121 
3122 /**
3123  * Code for BigInteger::multiplyToLen() instrinsic.
3124  *
3125  * r0: x
3126  * r1: xlen
3127  * r2: y
3128  * r3: ylen
3129  * r4:  z
3130  * r5: zlen
3131  * r10: tmp1
3132  * r11: tmp2
3133  * r12: tmp3
3134  * r13: tmp4
3135  * r14: tmp5
3136  * r15: tmp6
3137  * r16: tmp7
3138  *
3139  */
3140 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen,
3141                                      Register z, Register zlen,
3142                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4,
3143                                      Register tmp5, Register tmp6, Register product_hi) {
3144 
3145   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6);
3146 
3147   const Register idx = tmp1;
3148   const Register kdx = tmp2;
3149   const Register xstart = tmp3;
3150 
3151   const Register y_idx = tmp4;
3152   const Register carry = tmp5;
3153   const Register product  = xlen;
3154   const Register x_xstart = zlen;  // reuse register
3155 
3156   // First Loop.
3157   //
3158   //  final static long LONG_MASK = 0xffffffffL;
3159   //  int xstart = xlen - 1;
3160   //  int ystart = ylen - 1;
3161   //  long carry = 0;
3162   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
3163   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
3164   //    z[kdx] = (int)product;
3165   //    carry = product >>> 32;
3166   //  }
3167   //  z[xstart] = (int)carry;
3168   //
3169 
3170   movw(idx, ylen);      // idx = ylen;
3171   movw(kdx, zlen);      // kdx = xlen+ylen;
3172   mov(carry, zr);       // carry = 0;
3173 
3174   Label L_done;
3175 
3176   movw(xstart, xlen);
3177   subsw(xstart, xstart, 1);
3178   br(Assembler::MI, L_done);
3179 
3180   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
3181 
3182   Label L_second_loop;
3183   cbzw(kdx, L_second_loop);
3184 
3185   Label L_carry;
3186   subw(kdx, kdx, 1);
3187   cbzw(kdx, L_carry);
3188 
3189   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
3190   lsr(carry, carry, 32);
3191   subw(kdx, kdx, 1);
3192 
3193   bind(L_carry);
3194   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
3195 
3196   // Second and third (nested) loops.
3197   //
3198   // for (int i = xstart-1; i >= 0; i--) { // Second loop
3199   //   carry = 0;
3200   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
3201   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
3202   //                    (z[k] & LONG_MASK) + carry;
3203   //     z[k] = (int)product;
3204   //     carry = product >>> 32;
3205   //   }
3206   //   z[i] = (int)carry;
3207   // }
3208   //
3209   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = product_hi
3210 
3211   const Register jdx = tmp1;
3212 
3213   bind(L_second_loop);
3214   mov(carry, zr);                // carry = 0;
3215   movw(jdx, ylen);               // j = ystart+1
3216 
3217   subsw(xstart, xstart, 1);      // i = xstart-1;
3218   br(Assembler::MI, L_done);
3219 
3220   str(z, Address(pre(sp, -4 * wordSize)));
3221 
3222   Label L_last_x;
3223   lea(z, offsetted_address(z, xstart, Address::uxtw(LogBytesPerInt), 4, BytesPerInt)); // z = z + k - j
3224   subsw(xstart, xstart, 1);       // i = xstart-1;
3225   br(Assembler::MI, L_last_x);
3226 
3227   lea(rscratch1, Address(x, xstart, Address::uxtw(LogBytesPerInt)));
3228   ldr(product_hi, Address(rscratch1));
3229   ror(product_hi, product_hi, 32);  // convert big-endian to little-endian
3230 
3231   Label L_third_loop_prologue;
3232   bind(L_third_loop_prologue);
3233 
3234   str(ylen, Address(sp, wordSize));
3235   stp(x, xstart, Address(sp, 2 * wordSize));
3236   multiply_128_x_128_loop(y, z, carry, x, jdx, ylen, product,
3237                           tmp2, x_xstart, tmp3, tmp4, tmp6, product_hi);
3238   ldp(z, ylen, Address(post(sp, 2 * wordSize)));
3239   ldp(x, xlen, Address(post(sp, 2 * wordSize)));   // copy old xstart -> xlen
3240 
3241   addw(tmp3, xlen, 1);
3242   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
3243   subsw(tmp3, tmp3, 1);
3244   br(Assembler::MI, L_done);
3245 
3246   lsr(carry, carry, 32);
3247   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
3248   b(L_second_loop);
3249 
3250   // Next infrequent code is moved outside loops.
3251   bind(L_last_x);
3252   ldrw(product_hi, Address(x,  0));
3253   b(L_third_loop_prologue);
3254 
3255   bind(L_done);
3256 }
3257 
3258 // Code for BigInteger::mulAdd instrinsic
3259 // out     = r0
3260 // in      = r1
3261 // offset  = r2  (already out.length-offset)
3262 // len     = r3
3263 // k       = r4
3264 //
3265 // pseudo code from java implementation:
3266 // carry = 0;
3267 // offset = out.length-offset - 1;
3268 // for (int j=len-1; j >= 0; j--) {
3269 //     product = (in[j] & LONG_MASK) * kLong + (out[offset] & LONG_MASK) + carry;
3270 //     out[offset--] = (int)product;
3271 //     carry = product >>> 32;
3272 // }
3273 // return (int)carry;
3274 void MacroAssembler::mul_add(Register out, Register in, Register offset,
3275       Register len, Register k) {
3276     Label LOOP, END;
3277     // pre-loop
3278     cmp(len, zr); // cmp, not cbz/cbnz: to use condition twice => less branches
3279     csel(out, zr, out, Assembler::EQ);
3280     br(Assembler::EQ, END);
3281     add(in, in, len, LSL, 2); // in[j+1] address
3282     add(offset, out, offset, LSL, 2); // out[offset + 1] address
3283     mov(out, zr); // used to keep carry now
3284     BIND(LOOP);
3285     ldrw(rscratch1, Address(pre(in, -4)));
3286     madd(rscratch1, rscratch1, k, out);
3287     ldrw(rscratch2, Address(pre(offset, -4)));
3288     add(rscratch1, rscratch1, rscratch2);
3289     strw(rscratch1, Address(offset));
3290     lsr(out, rscratch1, 32);
3291     subs(len, len, 1);
3292     br(Assembler::NE, LOOP);
3293     BIND(END);
3294 }
3295 
3296 /**
3297  * Emits code to update CRC-32 with a byte value according to constants in table
3298  *
3299  * @param [in,out]crc   Register containing the crc.
3300  * @param [in]val       Register containing the byte to fold into the CRC.
3301  * @param [in]table     Register containing the table of crc constants.
3302  *
3303  * uint32_t crc;
3304  * val = crc_table[(val ^ crc) & 0xFF];
3305  * crc = val ^ (crc >> 8);
3306  *
3307  */
3308 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
3309   eor(val, val, crc);
3310   andr(val, val, 0xff);
3311   ldrw(val, Address(table, val, Address::lsl(2)));
3312   eor(crc, val, crc, Assembler::LSR, 8);
3313 }
3314 
3315 /**
3316  * Emits code to update CRC-32 with a 32-bit value according to tables 0 to 3
3317  *
3318  * @param [in,out]crc   Register containing the crc.
3319  * @param [in]v         Register containing the 32-bit to fold into the CRC.
3320  * @param [in]table0    Register containing table 0 of crc constants.
3321  * @param [in]table1    Register containing table 1 of crc constants.
3322  * @param [in]table2    Register containing table 2 of crc constants.
3323  * @param [in]table3    Register containing table 3 of crc constants.
3324  *
3325  * uint32_t crc;
3326  *   v = crc ^ v
3327  *   crc = table3[v&0xff]^table2[(v>>8)&0xff]^table1[(v>>16)&0xff]^table0[v>>24]
3328  *
3329  */
3330 void MacroAssembler::update_word_crc32(Register crc, Register v, Register tmp,
3331         Register table0, Register table1, Register table2, Register table3,
3332         bool upper) {
3333   eor(v, crc, v, upper ? LSR:LSL, upper ? 32:0);
3334   uxtb(tmp, v);
3335   ldrw(crc, Address(table3, tmp, Address::lsl(2)));
3336   ubfx(tmp, v, 8, 8);
3337   ldrw(tmp, Address(table2, tmp, Address::lsl(2)));
3338   eor(crc, crc, tmp);
3339   ubfx(tmp, v, 16, 8);
3340   ldrw(tmp, Address(table1, tmp, Address::lsl(2)));
3341   eor(crc, crc, tmp);
3342   ubfx(tmp, v, 24, 8);
3343   ldrw(tmp, Address(table0, tmp, Address::lsl(2)));
3344   eor(crc, crc, tmp);
3345 }
3346 
3347 void MacroAssembler::kernel_crc32_using_crc32(Register crc, Register buf,
3348         Register len, Register tmp0, Register tmp1, Register tmp2,
3349         Register tmp3) {
3350     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
3351     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
3352 
3353     mvnw(crc, crc);
3354 
3355     subs(len, len, 128);
3356     br(Assembler::GE, CRC_by64_pre);
3357   BIND(CRC_less64);
3358     adds(len, len, 128-32);
3359     br(Assembler::GE, CRC_by32_loop);
3360   BIND(CRC_less32);
3361     adds(len, len, 32-4);
3362     br(Assembler::GE, CRC_by4_loop);
3363     adds(len, len, 4);
3364     br(Assembler::GT, CRC_by1_loop);
3365     b(L_exit);
3366 
3367   BIND(CRC_by32_loop);
3368     ldp(tmp0, tmp1, Address(post(buf, 16)));
3369     subs(len, len, 32);
3370     crc32x(crc, crc, tmp0);
3371     ldr(tmp2, Address(post(buf, 8)));
3372     crc32x(crc, crc, tmp1);
3373     ldr(tmp3, Address(post(buf, 8)));
3374     crc32x(crc, crc, tmp2);
3375     crc32x(crc, crc, tmp3);
3376     br(Assembler::GE, CRC_by32_loop);
3377     cmn(len, (u1)32);
3378     br(Assembler::NE, CRC_less32);
3379     b(L_exit);
3380 
3381   BIND(CRC_by4_loop);
3382     ldrw(tmp0, Address(post(buf, 4)));
3383     subs(len, len, 4);
3384     crc32w(crc, crc, tmp0);
3385     br(Assembler::GE, CRC_by4_loop);
3386     adds(len, len, 4);
3387     br(Assembler::LE, L_exit);
3388   BIND(CRC_by1_loop);
3389     ldrb(tmp0, Address(post(buf, 1)));
3390     subs(len, len, 1);
3391     crc32b(crc, crc, tmp0);
3392     br(Assembler::GT, CRC_by1_loop);
3393     b(L_exit);
3394 
3395   BIND(CRC_by64_pre);
3396     sub(buf, buf, 8);
3397     ldp(tmp0, tmp1, Address(buf, 8));
3398     crc32x(crc, crc, tmp0);
3399     ldr(tmp2, Address(buf, 24));
3400     crc32x(crc, crc, tmp1);
3401     ldr(tmp3, Address(buf, 32));
3402     crc32x(crc, crc, tmp2);
3403     ldr(tmp0, Address(buf, 40));
3404     crc32x(crc, crc, tmp3);
3405     ldr(tmp1, Address(buf, 48));
3406     crc32x(crc, crc, tmp0);
3407     ldr(tmp2, Address(buf, 56));
3408     crc32x(crc, crc, tmp1);
3409     ldr(tmp3, Address(pre(buf, 64)));
3410 
3411     b(CRC_by64_loop);
3412 
3413     align(CodeEntryAlignment);
3414   BIND(CRC_by64_loop);
3415     subs(len, len, 64);
3416     crc32x(crc, crc, tmp2);
3417     ldr(tmp0, Address(buf, 8));
3418     crc32x(crc, crc, tmp3);
3419     ldr(tmp1, Address(buf, 16));
3420     crc32x(crc, crc, tmp0);
3421     ldr(tmp2, Address(buf, 24));
3422     crc32x(crc, crc, tmp1);
3423     ldr(tmp3, Address(buf, 32));
3424     crc32x(crc, crc, tmp2);
3425     ldr(tmp0, Address(buf, 40));
3426     crc32x(crc, crc, tmp3);
3427     ldr(tmp1, Address(buf, 48));
3428     crc32x(crc, crc, tmp0);
3429     ldr(tmp2, Address(buf, 56));
3430     crc32x(crc, crc, tmp1);
3431     ldr(tmp3, Address(pre(buf, 64)));
3432     br(Assembler::GE, CRC_by64_loop);
3433 
3434     // post-loop
3435     crc32x(crc, crc, tmp2);
3436     crc32x(crc, crc, tmp3);
3437 
3438     sub(len, len, 64);
3439     add(buf, buf, 8);
3440     cmn(len, (u1)128);
3441     br(Assembler::NE, CRC_less64);
3442   BIND(L_exit);
3443     mvnw(crc, crc);
3444 }
3445 
3446 /**
3447  * @param crc   register containing existing CRC (32-bit)
3448  * @param buf   register pointing to input byte buffer (byte*)
3449  * @param len   register containing number of bytes
3450  * @param table register that will contain address of CRC table
3451  * @param tmp   scratch register
3452  */
3453 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len,
3454         Register table0, Register table1, Register table2, Register table3,
3455         Register tmp, Register tmp2, Register tmp3) {
3456   Label L_by16, L_by16_loop, L_by4, L_by4_loop, L_by1, L_by1_loop, L_exit;
3457   uint64_t offset;
3458 
3459   if (UseCRC32) {
3460       kernel_crc32_using_crc32(crc, buf, len, table0, table1, table2, table3);
3461       return;
3462   }
3463 
3464     mvnw(crc, crc);
3465 
3466     adrp(table0, ExternalAddress(StubRoutines::crc_table_addr()), offset);
3467     if (offset) add(table0, table0, offset);
3468     add(table1, table0, 1*256*sizeof(juint));
3469     add(table2, table0, 2*256*sizeof(juint));
3470     add(table3, table0, 3*256*sizeof(juint));
3471 
3472   if (UseNeon) {
3473       cmp(len, (u1)64);
3474       br(Assembler::LT, L_by16);
3475       eor(v16, T16B, v16, v16);
3476 
3477     Label L_fold;
3478 
3479       add(tmp, table0, 4*256*sizeof(juint)); // Point at the Neon constants
3480 
3481       ld1(v0, v1, T2D, post(buf, 32));
3482       ld1r(v4, T2D, post(tmp, 8));
3483       ld1r(v5, T2D, post(tmp, 8));
3484       ld1r(v6, T2D, post(tmp, 8));
3485       ld1r(v7, T2D, post(tmp, 8));
3486       mov(v16, T4S, 0, crc);
3487 
3488       eor(v0, T16B, v0, v16);
3489       sub(len, len, 64);
3490 
3491     BIND(L_fold);
3492       pmull(v22, T8H, v0, v5, T8B);
3493       pmull(v20, T8H, v0, v7, T8B);
3494       pmull(v23, T8H, v0, v4, T8B);
3495       pmull(v21, T8H, v0, v6, T8B);
3496 
3497       pmull2(v18, T8H, v0, v5, T16B);
3498       pmull2(v16, T8H, v0, v7, T16B);
3499       pmull2(v19, T8H, v0, v4, T16B);
3500       pmull2(v17, T8H, v0, v6, T16B);
3501 
3502       uzp1(v24, T8H, v20, v22);
3503       uzp2(v25, T8H, v20, v22);
3504       eor(v20, T16B, v24, v25);
3505 
3506       uzp1(v26, T8H, v16, v18);
3507       uzp2(v27, T8H, v16, v18);
3508       eor(v16, T16B, v26, v27);
3509 
3510       ushll2(v22, T4S, v20, T8H, 8);
3511       ushll(v20, T4S, v20, T4H, 8);
3512 
3513       ushll2(v18, T4S, v16, T8H, 8);
3514       ushll(v16, T4S, v16, T4H, 8);
3515 
3516       eor(v22, T16B, v23, v22);
3517       eor(v18, T16B, v19, v18);
3518       eor(v20, T16B, v21, v20);
3519       eor(v16, T16B, v17, v16);
3520 
3521       uzp1(v17, T2D, v16, v20);
3522       uzp2(v21, T2D, v16, v20);
3523       eor(v17, T16B, v17, v21);
3524 
3525       ushll2(v20, T2D, v17, T4S, 16);
3526       ushll(v16, T2D, v17, T2S, 16);
3527 
3528       eor(v20, T16B, v20, v22);
3529       eor(v16, T16B, v16, v18);
3530 
3531       uzp1(v17, T2D, v20, v16);
3532       uzp2(v21, T2D, v20, v16);
3533       eor(v28, T16B, v17, v21);
3534 
3535       pmull(v22, T8H, v1, v5, T8B);
3536       pmull(v20, T8H, v1, v7, T8B);
3537       pmull(v23, T8H, v1, v4, T8B);
3538       pmull(v21, T8H, v1, v6, T8B);
3539 
3540       pmull2(v18, T8H, v1, v5, T16B);
3541       pmull2(v16, T8H, v1, v7, T16B);
3542       pmull2(v19, T8H, v1, v4, T16B);
3543       pmull2(v17, T8H, v1, v6, T16B);
3544 
3545       ld1(v0, v1, T2D, post(buf, 32));
3546 
3547       uzp1(v24, T8H, v20, v22);
3548       uzp2(v25, T8H, v20, v22);
3549       eor(v20, T16B, v24, v25);
3550 
3551       uzp1(v26, T8H, v16, v18);
3552       uzp2(v27, T8H, v16, v18);
3553       eor(v16, T16B, v26, v27);
3554 
3555       ushll2(v22, T4S, v20, T8H, 8);
3556       ushll(v20, T4S, v20, T4H, 8);
3557 
3558       ushll2(v18, T4S, v16, T8H, 8);
3559       ushll(v16, T4S, v16, T4H, 8);
3560 
3561       eor(v22, T16B, v23, v22);
3562       eor(v18, T16B, v19, v18);
3563       eor(v20, T16B, v21, v20);
3564       eor(v16, T16B, v17, v16);
3565 
3566       uzp1(v17, T2D, v16, v20);
3567       uzp2(v21, T2D, v16, v20);
3568       eor(v16, T16B, v17, v21);
3569 
3570       ushll2(v20, T2D, v16, T4S, 16);
3571       ushll(v16, T2D, v16, T2S, 16);
3572 
3573       eor(v20, T16B, v22, v20);
3574       eor(v16, T16B, v16, v18);
3575 
3576       uzp1(v17, T2D, v20, v16);
3577       uzp2(v21, T2D, v20, v16);
3578       eor(v20, T16B, v17, v21);
3579 
3580       shl(v16, T2D, v28, 1);
3581       shl(v17, T2D, v20, 1);
3582 
3583       eor(v0, T16B, v0, v16);
3584       eor(v1, T16B, v1, v17);
3585 
3586       subs(len, len, 32);
3587       br(Assembler::GE, L_fold);
3588 
3589       mov(crc, 0);
3590       mov(tmp, v0, T1D, 0);
3591       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3592       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3593       mov(tmp, v0, T1D, 1);
3594       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3595       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3596       mov(tmp, v1, T1D, 0);
3597       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3598       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3599       mov(tmp, v1, T1D, 1);
3600       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3601       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3602 
3603       add(len, len, 32);
3604   }
3605 
3606   BIND(L_by16);
3607     subs(len, len, 16);
3608     br(Assembler::GE, L_by16_loop);
3609     adds(len, len, 16-4);
3610     br(Assembler::GE, L_by4_loop);
3611     adds(len, len, 4);
3612     br(Assembler::GT, L_by1_loop);
3613     b(L_exit);
3614 
3615   BIND(L_by4_loop);
3616     ldrw(tmp, Address(post(buf, 4)));
3617     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3);
3618     subs(len, len, 4);
3619     br(Assembler::GE, L_by4_loop);
3620     adds(len, len, 4);
3621     br(Assembler::LE, L_exit);
3622   BIND(L_by1_loop);
3623     subs(len, len, 1);
3624     ldrb(tmp, Address(post(buf, 1)));
3625     update_byte_crc32(crc, tmp, table0);
3626     br(Assembler::GT, L_by1_loop);
3627     b(L_exit);
3628 
3629     align(CodeEntryAlignment);
3630   BIND(L_by16_loop);
3631     subs(len, len, 16);
3632     ldp(tmp, tmp3, Address(post(buf, 16)));
3633     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3634     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3635     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, false);
3636     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, true);
3637     br(Assembler::GE, L_by16_loop);
3638     adds(len, len, 16-4);
3639     br(Assembler::GE, L_by4_loop);
3640     adds(len, len, 4);
3641     br(Assembler::GT, L_by1_loop);
3642   BIND(L_exit);
3643     mvnw(crc, crc);
3644 }
3645 
3646 void MacroAssembler::kernel_crc32c_using_crc32c(Register crc, Register buf,
3647         Register len, Register tmp0, Register tmp1, Register tmp2,
3648         Register tmp3) {
3649     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
3650     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
3651 
3652     subs(len, len, 128);
3653     br(Assembler::GE, CRC_by64_pre);
3654   BIND(CRC_less64);
3655     adds(len, len, 128-32);
3656     br(Assembler::GE, CRC_by32_loop);
3657   BIND(CRC_less32);
3658     adds(len, len, 32-4);
3659     br(Assembler::GE, CRC_by4_loop);
3660     adds(len, len, 4);
3661     br(Assembler::GT, CRC_by1_loop);
3662     b(L_exit);
3663 
3664   BIND(CRC_by32_loop);
3665     ldp(tmp0, tmp1, Address(post(buf, 16)));
3666     subs(len, len, 32);
3667     crc32cx(crc, crc, tmp0);
3668     ldr(tmp2, Address(post(buf, 8)));
3669     crc32cx(crc, crc, tmp1);
3670     ldr(tmp3, Address(post(buf, 8)));
3671     crc32cx(crc, crc, tmp2);
3672     crc32cx(crc, crc, tmp3);
3673     br(Assembler::GE, CRC_by32_loop);
3674     cmn(len, (u1)32);
3675     br(Assembler::NE, CRC_less32);
3676     b(L_exit);
3677 
3678   BIND(CRC_by4_loop);
3679     ldrw(tmp0, Address(post(buf, 4)));
3680     subs(len, len, 4);
3681     crc32cw(crc, crc, tmp0);
3682     br(Assembler::GE, CRC_by4_loop);
3683     adds(len, len, 4);
3684     br(Assembler::LE, L_exit);
3685   BIND(CRC_by1_loop);
3686     ldrb(tmp0, Address(post(buf, 1)));
3687     subs(len, len, 1);
3688     crc32cb(crc, crc, tmp0);
3689     br(Assembler::GT, CRC_by1_loop);
3690     b(L_exit);
3691 
3692   BIND(CRC_by64_pre);
3693     sub(buf, buf, 8);
3694     ldp(tmp0, tmp1, Address(buf, 8));
3695     crc32cx(crc, crc, tmp0);
3696     ldr(tmp2, Address(buf, 24));
3697     crc32cx(crc, crc, tmp1);
3698     ldr(tmp3, Address(buf, 32));
3699     crc32cx(crc, crc, tmp2);
3700     ldr(tmp0, Address(buf, 40));
3701     crc32cx(crc, crc, tmp3);
3702     ldr(tmp1, Address(buf, 48));
3703     crc32cx(crc, crc, tmp0);
3704     ldr(tmp2, Address(buf, 56));
3705     crc32cx(crc, crc, tmp1);
3706     ldr(tmp3, Address(pre(buf, 64)));
3707 
3708     b(CRC_by64_loop);
3709 
3710     align(CodeEntryAlignment);
3711   BIND(CRC_by64_loop);
3712     subs(len, len, 64);
3713     crc32cx(crc, crc, tmp2);
3714     ldr(tmp0, Address(buf, 8));
3715     crc32cx(crc, crc, tmp3);
3716     ldr(tmp1, Address(buf, 16));
3717     crc32cx(crc, crc, tmp0);
3718     ldr(tmp2, Address(buf, 24));
3719     crc32cx(crc, crc, tmp1);
3720     ldr(tmp3, Address(buf, 32));
3721     crc32cx(crc, crc, tmp2);
3722     ldr(tmp0, Address(buf, 40));
3723     crc32cx(crc, crc, tmp3);
3724     ldr(tmp1, Address(buf, 48));
3725     crc32cx(crc, crc, tmp0);
3726     ldr(tmp2, Address(buf, 56));
3727     crc32cx(crc, crc, tmp1);
3728     ldr(tmp3, Address(pre(buf, 64)));
3729     br(Assembler::GE, CRC_by64_loop);
3730 
3731     // post-loop
3732     crc32cx(crc, crc, tmp2);
3733     crc32cx(crc, crc, tmp3);
3734 
3735     sub(len, len, 64);
3736     add(buf, buf, 8);
3737     cmn(len, (u1)128);
3738     br(Assembler::NE, CRC_less64);
3739   BIND(L_exit);
3740 }
3741 
3742 /**
3743  * @param crc   register containing existing CRC (32-bit)
3744  * @param buf   register pointing to input byte buffer (byte*)
3745  * @param len   register containing number of bytes
3746  * @param table register that will contain address of CRC table
3747  * @param tmp   scratch register
3748  */
3749 void MacroAssembler::kernel_crc32c(Register crc, Register buf, Register len,
3750         Register table0, Register table1, Register table2, Register table3,
3751         Register tmp, Register tmp2, Register tmp3) {
3752   kernel_crc32c_using_crc32c(crc, buf, len, table0, table1, table2, table3);
3753 }
3754 
3755 
3756 SkipIfEqual::SkipIfEqual(
3757     MacroAssembler* masm, const bool* flag_addr, bool value) {
3758   _masm = masm;
3759   uint64_t offset;
3760   _masm->adrp(rscratch1, ExternalAddress((address)flag_addr), offset);
3761   _masm->ldrb(rscratch1, Address(rscratch1, offset));
3762   _masm->cbzw(rscratch1, _label);
3763 }
3764 
3765 SkipIfEqual::~SkipIfEqual() {
3766   _masm->bind(_label);
3767 }
3768 
3769 void MacroAssembler::addptr(const Address &dst, int32_t src) {
3770   Address adr;
3771   switch(dst.getMode()) {
3772   case Address::base_plus_offset:
3773     // This is the expected mode, although we allow all the other
3774     // forms below.
3775     adr = form_address(rscratch2, dst.base(), dst.offset(), LogBytesPerWord);
3776     break;
3777   default:
3778     lea(rscratch2, dst);
3779     adr = Address(rscratch2);
3780     break;
3781   }
3782   ldr(rscratch1, adr);
3783   add(rscratch1, rscratch1, src);
3784   str(rscratch1, adr);
3785 }
3786 
3787 void MacroAssembler::cmpptr(Register src1, Address src2) {
3788   uint64_t offset;
3789   adrp(rscratch1, src2, offset);
3790   ldr(rscratch1, Address(rscratch1, offset));
3791   cmp(src1, rscratch1);
3792 }
3793 
3794 void MacroAssembler::cmpoop(Register obj1, Register obj2) {
3795   cmp(obj1, obj2);
3796 }
3797 
3798 void MacroAssembler::load_method_holder_cld(Register rresult, Register rmethod) {
3799   load_method_holder(rresult, rmethod);
3800   ldr(rresult, Address(rresult, InstanceKlass::class_loader_data_offset()));
3801 }
3802 
3803 void MacroAssembler::load_method_holder(Register holder, Register method) {
3804   ldr(holder, Address(method, Method::const_offset()));                      // ConstMethod*
3805   ldr(holder, Address(holder, ConstMethod::constants_offset()));             // ConstantPool*
3806   ldr(holder, Address(holder, ConstantPool::pool_holder_offset_in_bytes())); // InstanceKlass*
3807 }
3808 
3809 // Loads the obj's Klass* into dst.
3810 // src and dst must be distinct registers
3811 // Preserves all registers (incl src, rscratch1 and rscratch2), but clobbers condition flags
3812 void MacroAssembler::load_nklass(Register dst, Register src) {
3813   assert(UseCompressedClassPointers, "expects UseCompressedClassPointers");
3814 
3815   if (!UseCompactObjectHeaders) {
3816     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3817     return;
3818   }
3819 
3820   Label fast;
3821 
3822   // Check if we can take the (common) fast path, if obj is unlocked.
3823   ldr(dst, Address(src, oopDesc::mark_offset_in_bytes()));
3824   tbz(dst, exact_log2(markWord::monitor_value), fast);
3825 
3826   // Fetch displaced header
3827   ldr(dst, Address(dst, OM_OFFSET_NO_MONITOR_VALUE_TAG(header)));
3828 
3829   // Fast-path: shift and decode Klass*.
3830   bind(fast);
3831   lsr(dst, dst, markWord::klass_shift);
3832 }
3833 
3834 void MacroAssembler::load_klass(Register dst, Register src, bool null_check_src) {
3835   if (null_check_src) {
3836     if (UseCompactObjectHeaders) {
3837       null_check(src, oopDesc::mark_offset_in_bytes());
3838     } else {
3839       null_check(src, oopDesc::klass_offset_in_bytes());
3840     }
3841   }
3842 
3843   if (UseCompressedClassPointers) {
3844     if (UseCompactObjectHeaders) {
3845       load_nklass(dst, src);
3846     } else {
3847       ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3848     }
3849     decode_klass_not_null(dst);
3850   } else {
3851     ldr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3852   }
3853 }
3854 
3855 // ((OopHandle)result).resolve();
3856 void MacroAssembler::resolve_oop_handle(Register result, Register tmp) {
3857   // OopHandle::resolve is an indirection.
3858   access_load_at(T_OBJECT, IN_NATIVE, result, Address(result, 0), tmp, noreg);
3859 }
3860 
3861 // ((WeakHandle)result).resolve();
3862 void MacroAssembler::resolve_weak_handle(Register rresult, Register rtmp) {
3863   assert_different_registers(rresult, rtmp);
3864   Label resolved;
3865 
3866   // A null weak handle resolves to null.
3867   cbz(rresult, resolved);
3868 
3869   // Only 64 bit platforms support GCs that require a tmp register
3870   // Only IN_HEAP loads require a thread_tmp register
3871   // WeakHandle::resolve is an indirection like jweak.
3872   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
3873                  rresult, Address(rresult), rtmp, /*tmp_thread*/noreg);
3874   bind(resolved);
3875 }
3876 
3877 void MacroAssembler::load_mirror(Register dst, Register method, Register tmp) {
3878   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
3879   ldr(dst, Address(rmethod, Method::const_offset()));
3880   ldr(dst, Address(dst, ConstMethod::constants_offset()));
3881   ldr(dst, Address(dst, ConstantPool::pool_holder_offset_in_bytes()));
3882   ldr(dst, Address(dst, mirror_offset));
3883   resolve_oop_handle(dst, tmp);
3884 }
3885 
3886 void MacroAssembler::cmp_klass(Register oop, Register trial_klass, Register tmp) {
3887   assert_different_registers(oop, trial_klass, tmp);
3888   if (UseCompressedClassPointers) {
3889     if (UseCompactObjectHeaders) {
3890       load_nklass(tmp, oop);
3891     } else {
3892       ldrw(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
3893     }
3894     if (CompressedKlassPointers::base() == NULL) {
3895       cmp(trial_klass, tmp, LSL, CompressedKlassPointers::shift());
3896       return;
3897     } else if (((uint64_t)CompressedKlassPointers::base() & 0xffffffff) == 0
3898                && CompressedKlassPointers::shift() == 0) {
3899       // Only the bottom 32 bits matter
3900       cmpw(trial_klass, tmp);
3901       return;
3902     }
3903     decode_klass_not_null(tmp);
3904   } else {
3905     ldr(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
3906   }
3907   cmp(trial_klass, tmp);
3908 }
3909 





3910 void MacroAssembler::store_klass(Register dst, Register src) {
3911   // FIXME: Should this be a store release?  concurrent gcs assumes
3912   // klass length is valid if klass field is not null.
3913   if (UseCompressedClassPointers) {
3914     encode_klass_not_null(src);
3915     strw(src, Address(dst, oopDesc::klass_offset_in_bytes()));
3916   } else {
3917     str(src, Address(dst, oopDesc::klass_offset_in_bytes()));
3918   }
3919 }
3920 
3921 void MacroAssembler::store_klass_gap(Register dst, Register src) {
3922   if (UseCompressedClassPointers) {
3923     // Store to klass gap in destination
3924     strw(src, Address(dst, oopDesc::klass_gap_offset_in_bytes()));
3925   }
3926 }
3927 
3928 void MacroAssembler::load_prototype_header(Register dst, Register src) {
3929   load_klass(dst, src);
3930   ldr(dst, Address(dst, Klass::prototype_header_offset()));
3931 }
3932 
3933 // Algorithm must match CompressedOops::encode.
3934 void MacroAssembler::encode_heap_oop(Register d, Register s) {
3935 #ifdef ASSERT
3936   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
3937 #endif
3938   verify_oop(s, "broken oop in encode_heap_oop");
3939   if (CompressedOops::base() == NULL) {
3940     if (CompressedOops::shift() != 0) {
3941       assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
3942       lsr(d, s, LogMinObjAlignmentInBytes);
3943     } else {
3944       mov(d, s);
3945     }
3946   } else {
3947     subs(d, s, rheapbase);
3948     csel(d, d, zr, Assembler::HS);
3949     lsr(d, d, LogMinObjAlignmentInBytes);
3950 
3951     /*  Old algorithm: is this any worse?
3952     Label nonnull;
3953     cbnz(r, nonnull);
3954     sub(r, r, rheapbase);
3955     bind(nonnull);
3956     lsr(r, r, LogMinObjAlignmentInBytes);
3957     */
3958   }
3959 }
3960 
3961 void MacroAssembler::encode_heap_oop_not_null(Register r) {
3962 #ifdef ASSERT
3963   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
3964   if (CheckCompressedOops) {
3965     Label ok;
3966     cbnz(r, ok);
3967     stop("null oop passed to encode_heap_oop_not_null");
3968     bind(ok);
3969   }
3970 #endif
3971   verify_oop(r, "broken oop in encode_heap_oop_not_null");
3972   if (CompressedOops::base() != NULL) {
3973     sub(r, r, rheapbase);
3974   }
3975   if (CompressedOops::shift() != 0) {
3976     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
3977     lsr(r, r, LogMinObjAlignmentInBytes);
3978   }
3979 }
3980 
3981 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
3982 #ifdef ASSERT
3983   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
3984   if (CheckCompressedOops) {
3985     Label ok;
3986     cbnz(src, ok);
3987     stop("null oop passed to encode_heap_oop_not_null2");
3988     bind(ok);
3989   }
3990 #endif
3991   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
3992 
3993   Register data = src;
3994   if (CompressedOops::base() != NULL) {
3995     sub(dst, src, rheapbase);
3996     data = dst;
3997   }
3998   if (CompressedOops::shift() != 0) {
3999     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4000     lsr(dst, data, LogMinObjAlignmentInBytes);
4001     data = dst;
4002   }
4003   if (data == src)
4004     mov(dst, src);
4005 }
4006 
4007 void  MacroAssembler::decode_heap_oop(Register d, Register s) {
4008 #ifdef ASSERT
4009   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
4010 #endif
4011   if (CompressedOops::base() == NULL) {
4012     if (CompressedOops::shift() != 0 || d != s) {
4013       lsl(d, s, CompressedOops::shift());
4014     }
4015   } else {
4016     Label done;
4017     if (d != s)
4018       mov(d, s);
4019     cbz(s, done);
4020     add(d, rheapbase, s, Assembler::LSL, LogMinObjAlignmentInBytes);
4021     bind(done);
4022   }
4023   verify_oop(d, "broken oop in decode_heap_oop");
4024 }
4025 
4026 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
4027   assert (UseCompressedOops, "should only be used for compressed headers");
4028   assert (Universe::heap() != NULL, "java heap should be initialized");
4029   // Cannot assert, unverified entry point counts instructions (see .ad file)
4030   // vtableStubs also counts instructions in pd_code_size_limit.
4031   // Also do not verify_oop as this is called by verify_oop.
4032   if (CompressedOops::shift() != 0) {
4033     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4034     if (CompressedOops::base() != NULL) {
4035       add(r, rheapbase, r, Assembler::LSL, LogMinObjAlignmentInBytes);
4036     } else {
4037       add(r, zr, r, Assembler::LSL, LogMinObjAlignmentInBytes);
4038     }
4039   } else {
4040     assert (CompressedOops::base() == NULL, "sanity");
4041   }
4042 }
4043 
4044 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
4045   assert (UseCompressedOops, "should only be used for compressed headers");
4046   assert (Universe::heap() != NULL, "java heap should be initialized");
4047   // Cannot assert, unverified entry point counts instructions (see .ad file)
4048   // vtableStubs also counts instructions in pd_code_size_limit.
4049   // Also do not verify_oop as this is called by verify_oop.
4050   if (CompressedOops::shift() != 0) {
4051     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4052     if (CompressedOops::base() != NULL) {
4053       add(dst, rheapbase, src, Assembler::LSL, LogMinObjAlignmentInBytes);
4054     } else {
4055       add(dst, zr, src, Assembler::LSL, LogMinObjAlignmentInBytes);
4056     }
4057   } else {
4058     assert (CompressedOops::base() == NULL, "sanity");
4059     if (dst != src) {
4060       mov(dst, src);
4061     }
4062   }
4063 }
4064 
4065 MacroAssembler::KlassDecodeMode MacroAssembler::_klass_decode_mode(KlassDecodeNone);
4066 
4067 MacroAssembler::KlassDecodeMode MacroAssembler::klass_decode_mode() {
4068   assert(UseCompressedClassPointers, "not using compressed class pointers");
4069   assert(Metaspace::initialized(), "metaspace not initialized yet");
4070 
4071   if (_klass_decode_mode != KlassDecodeNone) {
4072     return _klass_decode_mode;
4073   }
4074 
4075   assert(LogKlassAlignmentInBytes == CompressedKlassPointers::shift()
4076          || 0 == CompressedKlassPointers::shift(), "decode alg wrong");
4077 
4078   if (CompressedKlassPointers::base() == NULL) {
4079     return (_klass_decode_mode = KlassDecodeZero);
4080   }
4081 
4082   if (operand_valid_for_logical_immediate(
4083         /*is32*/false, (uint64_t)CompressedKlassPointers::base())) {
4084     const uint64_t range_mask =
4085       (1ULL << log2i(CompressedKlassPointers::range())) - 1;
4086     if (((uint64_t)CompressedKlassPointers::base() & range_mask) == 0) {
4087       return (_klass_decode_mode = KlassDecodeXor);
4088     }
4089   }
4090 
4091   const uint64_t shifted_base =
4092     (uint64_t)CompressedKlassPointers::base() >> CompressedKlassPointers::shift();
4093   guarantee((shifted_base & 0xffff0000ffffffff) == 0,
4094             "compressed class base bad alignment");
4095 
4096   return (_klass_decode_mode = KlassDecodeMovk);
4097 }
4098 
4099 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
4100   switch (klass_decode_mode()) {
4101   case KlassDecodeZero:
4102     if (CompressedKlassPointers::shift() != 0) {
4103       lsr(dst, src, LogKlassAlignmentInBytes);
4104     } else {
4105       if (dst != src) mov(dst, src);
4106     }
4107     break;
4108 
4109   case KlassDecodeXor:
4110     if (CompressedKlassPointers::shift() != 0) {
4111       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
4112       lsr(dst, dst, LogKlassAlignmentInBytes);
4113     } else {
4114       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
4115     }
4116     break;
4117 
4118   case KlassDecodeMovk:
4119     if (CompressedKlassPointers::shift() != 0) {
4120       ubfx(dst, src, LogKlassAlignmentInBytes, 32);
4121     } else {
4122       movw(dst, src);
4123     }
4124     break;
4125 
4126   case KlassDecodeNone:
4127     ShouldNotReachHere();
4128     break;
4129   }
4130 }
4131 
4132 void MacroAssembler::encode_klass_not_null(Register r) {
4133   encode_klass_not_null(r, r);
4134 }
4135 
4136 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
4137   assert (UseCompressedClassPointers, "should only be used for compressed headers");
4138 
4139   switch (klass_decode_mode()) {
4140   case KlassDecodeZero:
4141     if (CompressedKlassPointers::shift() != 0) {
4142       lsl(dst, src, LogKlassAlignmentInBytes);
4143     } else {
4144       if (dst != src) mov(dst, src);
4145     }
4146     break;
4147 
4148   case KlassDecodeXor:
4149     if (CompressedKlassPointers::shift() != 0) {
4150       lsl(dst, src, LogKlassAlignmentInBytes);
4151       eor(dst, dst, (uint64_t)CompressedKlassPointers::base());
4152     } else {
4153       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
4154     }
4155     break;
4156 
4157   case KlassDecodeMovk: {
4158     const uint64_t shifted_base =
4159       (uint64_t)CompressedKlassPointers::base() >> CompressedKlassPointers::shift();
4160 
4161     if (dst != src) movw(dst, src);
4162     movk(dst, shifted_base >> 32, 32);
4163 
4164     if (CompressedKlassPointers::shift() != 0) {
4165       lsl(dst, dst, LogKlassAlignmentInBytes);
4166     }
4167 
4168     break;
4169   }
4170 
4171   case KlassDecodeNone:
4172     ShouldNotReachHere();
4173     break;
4174   }
4175 }
4176 
4177 void  MacroAssembler::decode_klass_not_null(Register r) {
4178   decode_klass_not_null(r, r);
4179 }
4180 
4181 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
4182 #ifdef ASSERT
4183   {
4184     ThreadInVMfromUnknown tiv;
4185     assert (UseCompressedOops, "should only be used for compressed oops");
4186     assert (Universe::heap() != NULL, "java heap should be initialized");
4187     assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
4188     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
4189   }
4190 #endif
4191   int oop_index = oop_recorder()->find_index(obj);
4192   InstructionMark im(this);
4193   RelocationHolder rspec = oop_Relocation::spec(oop_index);
4194   code_section()->relocate(inst_mark(), rspec);
4195   movz(dst, 0xDEAD, 16);
4196   movk(dst, 0xBEEF);
4197 }
4198 
4199 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
4200   assert (UseCompressedClassPointers, "should only be used for compressed headers");
4201   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
4202   int index = oop_recorder()->find_index(k);
4203   assert(! Universe::heap()->is_in(k), "should not be an oop");
4204 
4205   InstructionMark im(this);
4206   RelocationHolder rspec = metadata_Relocation::spec(index);
4207   code_section()->relocate(inst_mark(), rspec);
4208   narrowKlass nk = CompressedKlassPointers::encode(k);
4209   movz(dst, (nk >> 16), 16);
4210   movk(dst, nk & 0xffff);
4211 }
4212 
4213 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators,
4214                                     Register dst, Address src,
4215                                     Register tmp1, Register thread_tmp) {
4216   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
4217   decorators = AccessInternal::decorator_fixup(decorators);
4218   bool as_raw = (decorators & AS_RAW) != 0;
4219   if (as_raw) {
4220     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
4221   } else {
4222     bs->load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
4223   }
4224 }
4225 
4226 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators,
4227                                      Address dst, Register src,
4228                                      Register tmp1, Register thread_tmp) {
4229   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
4230   decorators = AccessInternal::decorator_fixup(decorators);
4231   bool as_raw = (decorators & AS_RAW) != 0;
4232   if (as_raw) {
4233     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, src, tmp1, thread_tmp);
4234   } else {
4235     bs->store_at(this, decorators, type, dst, src, tmp1, thread_tmp);
4236   }
4237 }
4238 
4239 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
4240                                    Register thread_tmp, DecoratorSet decorators) {
4241   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, thread_tmp);
4242 }
4243 
4244 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
4245                                             Register thread_tmp, DecoratorSet decorators) {
4246   access_load_at(T_OBJECT, IN_HEAP | IS_NOT_NULL | decorators, dst, src, tmp1, thread_tmp);
4247 }
4248 
4249 void MacroAssembler::store_heap_oop(Address dst, Register src, Register tmp1,
4250                                     Register thread_tmp, DecoratorSet decorators) {
4251   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, thread_tmp);
4252 }
4253 
4254 // Used for storing NULLs.
4255 void MacroAssembler::store_heap_oop_null(Address dst) {
4256   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg);
4257 }
4258 
4259 Address MacroAssembler::allocate_metadata_address(Metadata* obj) {
4260   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
4261   int index = oop_recorder()->allocate_metadata_index(obj);
4262   RelocationHolder rspec = metadata_Relocation::spec(index);
4263   return Address((address)obj, rspec);
4264 }
4265 
4266 // Move an oop into a register.  immediate is true if we want
4267 // immediate instructions and nmethod entry barriers are not enabled.
4268 // i.e. we are not going to patch this instruction while the code is being
4269 // executed by another thread.
4270 void MacroAssembler::movoop(Register dst, jobject obj, bool immediate) {
4271   int oop_index;
4272   if (obj == NULL) {
4273     oop_index = oop_recorder()->allocate_oop_index(obj);
4274   } else {
4275 #ifdef ASSERT
4276     {
4277       ThreadInVMfromUnknown tiv;
4278       assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
4279     }
4280 #endif
4281     oop_index = oop_recorder()->find_index(obj);
4282   }
4283   RelocationHolder rspec = oop_Relocation::spec(oop_index);
4284 
4285   // nmethod entry barrier necessitate using the constant pool. They have to be
4286   // ordered with respected to oop accesses.
4287   // Using immediate literals would necessitate ISBs.
4288   if (BarrierSet::barrier_set()->barrier_set_nmethod() != NULL || !immediate) {
4289     address dummy = address(uintptr_t(pc()) & -wordSize); // A nearby aligned address
4290     ldr_constant(dst, Address(dummy, rspec));
4291   } else
4292     mov(dst, Address((address)obj, rspec));
4293 
4294 }
4295 
4296 // Move a metadata address into a register.
4297 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
4298   int oop_index;
4299   if (obj == NULL) {
4300     oop_index = oop_recorder()->allocate_metadata_index(obj);
4301   } else {
4302     oop_index = oop_recorder()->find_index(obj);
4303   }
4304   RelocationHolder rspec = metadata_Relocation::spec(oop_index);
4305   mov(dst, Address((address)obj, rspec));
4306 }
4307 
4308 Address MacroAssembler::constant_oop_address(jobject obj) {
4309 #ifdef ASSERT
4310   {
4311     ThreadInVMfromUnknown tiv;
4312     assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
4313     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "not an oop");
4314   }
4315 #endif
4316   int oop_index = oop_recorder()->find_index(obj);
4317   return Address((address)obj, oop_Relocation::spec(oop_index));
4318 }
4319 
4320 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
4321 void MacroAssembler::tlab_allocate(Register obj,
4322                                    Register var_size_in_bytes,
4323                                    int con_size_in_bytes,
4324                                    Register t1,
4325                                    Register t2,
4326                                    Label& slow_case) {
4327   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
4328   bs->tlab_allocate(this, obj, var_size_in_bytes, con_size_in_bytes, t1, t2, slow_case);
4329 }
4330 
4331 // Defines obj, preserves var_size_in_bytes
4332 void MacroAssembler::eden_allocate(Register obj,
4333                                    Register var_size_in_bytes,
4334                                    int con_size_in_bytes,
4335                                    Register t1,
4336                                    Label& slow_case) {
4337   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
4338   bs->eden_allocate(this, obj, var_size_in_bytes, con_size_in_bytes, t1, slow_case);
4339 }
4340 
4341 void MacroAssembler::verify_tlab() {
4342 #ifdef ASSERT
4343   if (UseTLAB && VerifyOops) {
4344     Label next, ok;
4345 
4346     stp(rscratch2, rscratch1, Address(pre(sp, -16)));
4347 
4348     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4349     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
4350     cmp(rscratch2, rscratch1);
4351     br(Assembler::HS, next);
4352     STOP("assert(top >= start)");
4353     should_not_reach_here();
4354 
4355     bind(next);
4356     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
4357     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4358     cmp(rscratch2, rscratch1);
4359     br(Assembler::HS, ok);
4360     STOP("assert(top <= end)");
4361     should_not_reach_here();
4362 
4363     bind(ok);
4364     ldp(rscratch2, rscratch1, Address(post(sp, 16)));
4365   }
4366 #endif
4367 }
4368 
4369 // Writes to stack successive pages until offset reached to check for
4370 // stack overflow + shadow pages.  This clobbers tmp.
4371 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
4372   assert_different_registers(tmp, size, rscratch1);
4373   mov(tmp, sp);
4374   // Bang stack for total size given plus shadow page size.
4375   // Bang one page at a time because large size can bang beyond yellow and
4376   // red zones.
4377   Label loop;
4378   mov(rscratch1, os::vm_page_size());
4379   bind(loop);
4380   lea(tmp, Address(tmp, -os::vm_page_size()));
4381   subsw(size, size, rscratch1);
4382   str(size, Address(tmp));
4383   br(Assembler::GT, loop);
4384 
4385   // Bang down shadow pages too.
4386   // At this point, (tmp-0) is the last address touched, so don't
4387   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
4388   // was post-decremented.)  Skip this address by starting at i=1, and
4389   // touch a few more pages below.  N.B.  It is important to touch all
4390   // the way down to and including i=StackShadowPages.
4391   for (int i = 0; i < (int)(StackOverflow::stack_shadow_zone_size() / os::vm_page_size()) - 1; i++) {
4392     // this could be any sized move but this is can be a debugging crumb
4393     // so the bigger the better.
4394     lea(tmp, Address(tmp, -os::vm_page_size()));
4395     str(size, Address(tmp));
4396   }
4397 }
4398 
4399 // Move the address of the polling page into dest.
4400 void MacroAssembler::get_polling_page(Register dest, relocInfo::relocType rtype) {
4401   ldr(dest, Address(rthread, JavaThread::polling_page_offset()));
4402 }
4403 
4404 // Read the polling page.  The address of the polling page must
4405 // already be in r.
4406 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
4407   address mark;
4408   {
4409     InstructionMark im(this);
4410     code_section()->relocate(inst_mark(), rtype);
4411     ldrw(zr, Address(r, 0));
4412     mark = inst_mark();
4413   }
4414   verify_cross_modify_fence_not_required();
4415   return mark;
4416 }
4417 
4418 void MacroAssembler::adrp(Register reg1, const Address &dest, uint64_t &byte_offset) {
4419   relocInfo::relocType rtype = dest.rspec().reloc()->type();
4420   uint64_t low_page = (uint64_t)CodeCache::low_bound() >> 12;
4421   uint64_t high_page = (uint64_t)(CodeCache::high_bound()-1) >> 12;
4422   uint64_t dest_page = (uint64_t)dest.target() >> 12;
4423   int64_t offset_low = dest_page - low_page;
4424   int64_t offset_high = dest_page - high_page;
4425 
4426   assert(is_valid_AArch64_address(dest.target()), "bad address");
4427   assert(dest.getMode() == Address::literal, "ADRP must be applied to a literal address");
4428 
4429   InstructionMark im(this);
4430   code_section()->relocate(inst_mark(), dest.rspec());
4431   // 8143067: Ensure that the adrp can reach the dest from anywhere within
4432   // the code cache so that if it is relocated we know it will still reach
4433   if (offset_high >= -(1<<20) && offset_low < (1<<20)) {
4434     _adrp(reg1, dest.target());
4435   } else {
4436     uint64_t target = (uint64_t)dest.target();
4437     uint64_t adrp_target
4438       = (target & 0xffffffffULL) | ((uint64_t)pc() & 0xffff00000000ULL);
4439 
4440     _adrp(reg1, (address)adrp_target);
4441     movk(reg1, target >> 32, 32);
4442   }
4443   byte_offset = (uint64_t)dest.target() & 0xfff;
4444 }
4445 
4446 void MacroAssembler::load_byte_map_base(Register reg) {
4447   CardTable::CardValue* byte_map_base =
4448     ((CardTableBarrierSet*)(BarrierSet::barrier_set()))->card_table()->byte_map_base();
4449 
4450   // Strictly speaking the byte_map_base isn't an address at all, and it might
4451   // even be negative. It is thus materialised as a constant.
4452   mov(reg, (uint64_t)byte_map_base);
4453 }
4454 
4455 void MacroAssembler::build_frame(int framesize) {
4456   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
4457   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
4458   if (framesize < ((1 << 9) + 2 * wordSize)) {
4459     sub(sp, sp, framesize);
4460     stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4461     if (PreserveFramePointer) add(rfp, sp, framesize - 2 * wordSize);
4462   } else {
4463     stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
4464     if (PreserveFramePointer) mov(rfp, sp);
4465     if (framesize < ((1 << 12) + 2 * wordSize))
4466       sub(sp, sp, framesize - 2 * wordSize);
4467     else {
4468       mov(rscratch1, framesize - 2 * wordSize);
4469       sub(sp, sp, rscratch1);
4470     }
4471   }
4472   verify_cross_modify_fence_not_required();
4473 }
4474 
4475 void MacroAssembler::remove_frame(int framesize) {
4476   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
4477   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
4478   if (framesize < ((1 << 9) + 2 * wordSize)) {
4479     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4480     add(sp, sp, framesize);
4481   } else {
4482     if (framesize < ((1 << 12) + 2 * wordSize))
4483       add(sp, sp, framesize - 2 * wordSize);
4484     else {
4485       mov(rscratch1, framesize - 2 * wordSize);
4486       add(sp, sp, rscratch1);
4487     }
4488     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
4489   }
4490 }
4491 
4492 
4493 // This method checks if provided byte array contains byte with highest bit set.
4494 address MacroAssembler::has_negatives(Register ary1, Register len, Register result) {
4495     // Simple and most common case of aligned small array which is not at the
4496     // end of memory page is placed here. All other cases are in stub.
4497     Label LOOP, END, STUB, STUB_LONG, SET_RESULT, DONE;
4498     const uint64_t UPPER_BIT_MASK=0x8080808080808080;
4499     assert_different_registers(ary1, len, result);
4500 
4501     cmpw(len, 0);
4502     br(LE, SET_RESULT);
4503     cmpw(len, 4 * wordSize);
4504     br(GE, STUB_LONG); // size > 32 then go to stub
4505 
4506     int shift = 64 - exact_log2(os::vm_page_size());
4507     lsl(rscratch1, ary1, shift);
4508     mov(rscratch2, (size_t)(4 * wordSize) << shift);
4509     adds(rscratch2, rscratch1, rscratch2);  // At end of page?
4510     br(CS, STUB); // at the end of page then go to stub
4511     subs(len, len, wordSize);
4512     br(LT, END);
4513 
4514   BIND(LOOP);
4515     ldr(rscratch1, Address(post(ary1, wordSize)));
4516     tst(rscratch1, UPPER_BIT_MASK);
4517     br(NE, SET_RESULT);
4518     subs(len, len, wordSize);
4519     br(GE, LOOP);
4520     cmpw(len, -wordSize);
4521     br(EQ, SET_RESULT);
4522 
4523   BIND(END);
4524     ldr(result, Address(ary1));
4525     sub(len, zr, len, LSL, 3); // LSL 3 is to get bits from bytes
4526     lslv(result, result, len);
4527     tst(result, UPPER_BIT_MASK);
4528     b(SET_RESULT);
4529 
4530   BIND(STUB);
4531     RuntimeAddress has_neg = RuntimeAddress(StubRoutines::aarch64::has_negatives());
4532     assert(has_neg.target() != NULL, "has_negatives stub has not been generated");
4533     address tpc1 = trampoline_call(has_neg);
4534     if (tpc1 == NULL) {
4535       DEBUG_ONLY(reset_labels(STUB_LONG, SET_RESULT, DONE));
4536       postcond(pc() == badAddress);
4537       return NULL;
4538     }
4539     b(DONE);
4540 
4541   BIND(STUB_LONG);
4542     RuntimeAddress has_neg_long = RuntimeAddress(StubRoutines::aarch64::has_negatives_long());
4543     assert(has_neg_long.target() != NULL, "has_negatives stub has not been generated");
4544     address tpc2 = trampoline_call(has_neg_long);
4545     if (tpc2 == NULL) {
4546       DEBUG_ONLY(reset_labels(SET_RESULT, DONE));
4547       postcond(pc() == badAddress);
4548       return NULL;
4549     }
4550     b(DONE);
4551 
4552   BIND(SET_RESULT);
4553     cset(result, NE); // set true or false
4554 
4555   BIND(DONE);
4556   postcond(pc() != badAddress);
4557   return pc();
4558 }
4559 
4560 address MacroAssembler::arrays_equals(Register a1, Register a2, Register tmp3,
4561                                       Register tmp4, Register tmp5, Register result,
4562                                       Register cnt1, int elem_size) {
4563   Label DONE, SAME;
4564   Register tmp1 = rscratch1;
4565   Register tmp2 = rscratch2;
4566   Register cnt2 = tmp2;  // cnt2 only used in array length compare
4567   int elem_per_word = wordSize/elem_size;
4568   int log_elem_size = exact_log2(elem_size);
4569   int length_offset = arrayOopDesc::length_offset_in_bytes();
4570   int base_offset
4571     = arrayOopDesc::base_offset_in_bytes(elem_size == 2 ? T_CHAR : T_BYTE);
4572   int stubBytesThreshold = 3 * 64 + (UseSIMDForArrayEquals ? 0 : 16);
4573 
4574   assert(elem_size == 1 || elem_size == 2, "must be char or byte");
4575   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
4576 
4577 #ifndef PRODUCT
4578   {
4579     const char kind = (elem_size == 2) ? 'U' : 'L';
4580     char comment[64];
4581     snprintf(comment, sizeof comment, "array_equals%c{", kind);
4582     BLOCK_COMMENT(comment);
4583   }
4584 #endif
4585 
4586   // if (a1 == a2)
4587   //     return true;
4588   cmpoop(a1, a2); // May have read barriers for a1 and a2.
4589   br(EQ, SAME);
4590 
4591   if (UseSimpleArrayEquals) {
4592     Label NEXT_WORD, SHORT, TAIL03, TAIL01, A_MIGHT_BE_NULL, A_IS_NOT_NULL;
4593     // if (a1 == null || a2 == null)
4594     //     return false;
4595     // a1 & a2 == 0 means (some-pointer is null) or
4596     // (very-rare-or-even-probably-impossible-pointer-values)
4597     // so, we can save one branch in most cases
4598     tst(a1, a2);
4599     mov(result, false);
4600     br(EQ, A_MIGHT_BE_NULL);
4601     // if (a1.length != a2.length)
4602     //      return false;
4603     bind(A_IS_NOT_NULL);
4604     ldrw(cnt1, Address(a1, length_offset));
4605     ldrw(cnt2, Address(a2, length_offset));
4606     eorw(tmp5, cnt1, cnt2);
4607     cbnzw(tmp5, DONE);
4608     lea(a1, Address(a1, base_offset));
4609     lea(a2, Address(a2, base_offset));
4610     // Check for short strings, i.e. smaller than wordSize.
4611     subs(cnt1, cnt1, elem_per_word);
4612     br(Assembler::LT, SHORT);
4613     // Main 8 byte comparison loop.
4614     bind(NEXT_WORD); {
4615       ldr(tmp1, Address(post(a1, wordSize)));
4616       ldr(tmp2, Address(post(a2, wordSize)));
4617       subs(cnt1, cnt1, elem_per_word);
4618       eor(tmp5, tmp1, tmp2);
4619       cbnz(tmp5, DONE);
4620     } br(GT, NEXT_WORD);
4621     // Last longword.  In the case where length == 4 we compare the
4622     // same longword twice, but that's still faster than another
4623     // conditional branch.
4624     // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
4625     // length == 4.
4626     if (log_elem_size > 0)
4627       lsl(cnt1, cnt1, log_elem_size);
4628     ldr(tmp3, Address(a1, cnt1));
4629     ldr(tmp4, Address(a2, cnt1));
4630     eor(tmp5, tmp3, tmp4);
4631     cbnz(tmp5, DONE);
4632     b(SAME);
4633     bind(A_MIGHT_BE_NULL);
4634     // in case both a1 and a2 are not-null, proceed with loads
4635     cbz(a1, DONE);
4636     cbz(a2, DONE);
4637     b(A_IS_NOT_NULL);
4638     bind(SHORT);
4639 
4640     tbz(cnt1, 2 - log_elem_size, TAIL03); // 0-7 bytes left.
4641     {
4642       ldrw(tmp1, Address(post(a1, 4)));
4643       ldrw(tmp2, Address(post(a2, 4)));
4644       eorw(tmp5, tmp1, tmp2);
4645       cbnzw(tmp5, DONE);
4646     }
4647     bind(TAIL03);
4648     tbz(cnt1, 1 - log_elem_size, TAIL01); // 0-3 bytes left.
4649     {
4650       ldrh(tmp3, Address(post(a1, 2)));
4651       ldrh(tmp4, Address(post(a2, 2)));
4652       eorw(tmp5, tmp3, tmp4);
4653       cbnzw(tmp5, DONE);
4654     }
4655     bind(TAIL01);
4656     if (elem_size == 1) { // Only needed when comparing byte arrays.
4657       tbz(cnt1, 0, SAME); // 0-1 bytes left.
4658       {
4659         ldrb(tmp1, a1);
4660         ldrb(tmp2, a2);
4661         eorw(tmp5, tmp1, tmp2);
4662         cbnzw(tmp5, DONE);
4663       }
4664     }
4665   } else {
4666     Label NEXT_DWORD, SHORT, TAIL, TAIL2, STUB,
4667         CSET_EQ, LAST_CHECK;
4668     mov(result, false);
4669     cbz(a1, DONE);
4670     ldrw(cnt1, Address(a1, length_offset));
4671     cbz(a2, DONE);
4672     ldrw(cnt2, Address(a2, length_offset));
4673     // on most CPUs a2 is still "locked"(surprisingly) in ldrw and it's
4674     // faster to perform another branch before comparing a1 and a2
4675     cmp(cnt1, (u1)elem_per_word);
4676     br(LE, SHORT); // short or same
4677     ldr(tmp3, Address(pre(a1, base_offset)));
4678     subs(zr, cnt1, stubBytesThreshold);
4679     br(GE, STUB);
4680     ldr(tmp4, Address(pre(a2, base_offset)));
4681     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
4682     cmp(cnt2, cnt1);
4683     br(NE, DONE);
4684 
4685     // Main 16 byte comparison loop with 2 exits
4686     bind(NEXT_DWORD); {
4687       ldr(tmp1, Address(pre(a1, wordSize)));
4688       ldr(tmp2, Address(pre(a2, wordSize)));
4689       subs(cnt1, cnt1, 2 * elem_per_word);
4690       br(LE, TAIL);
4691       eor(tmp4, tmp3, tmp4);
4692       cbnz(tmp4, DONE);
4693       ldr(tmp3, Address(pre(a1, wordSize)));
4694       ldr(tmp4, Address(pre(a2, wordSize)));
4695       cmp(cnt1, (u1)elem_per_word);
4696       br(LE, TAIL2);
4697       cmp(tmp1, tmp2);
4698     } br(EQ, NEXT_DWORD);
4699     b(DONE);
4700 
4701     bind(TAIL);
4702     eor(tmp4, tmp3, tmp4);
4703     eor(tmp2, tmp1, tmp2);
4704     lslv(tmp2, tmp2, tmp5);
4705     orr(tmp5, tmp4, tmp2);
4706     cmp(tmp5, zr);
4707     b(CSET_EQ);
4708 
4709     bind(TAIL2);
4710     eor(tmp2, tmp1, tmp2);
4711     cbnz(tmp2, DONE);
4712     b(LAST_CHECK);
4713 
4714     bind(STUB);
4715     ldr(tmp4, Address(pre(a2, base_offset)));
4716     cmp(cnt2, cnt1);
4717     br(NE, DONE);
4718     if (elem_size == 2) { // convert to byte counter
4719       lsl(cnt1, cnt1, 1);
4720     }
4721     eor(tmp5, tmp3, tmp4);
4722     cbnz(tmp5, DONE);
4723     RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_array_equals());
4724     assert(stub.target() != NULL, "array_equals_long stub has not been generated");
4725     address tpc = trampoline_call(stub);
4726     if (tpc == NULL) {
4727       DEBUG_ONLY(reset_labels(SHORT, LAST_CHECK, CSET_EQ, SAME, DONE));
4728       postcond(pc() == badAddress);
4729       return NULL;
4730     }
4731     b(DONE);
4732 
4733     // (a1 != null && a2 == null) || (a1 != null && a2 != null && a1 == a2)
4734     // so, if a2 == null => return false(0), else return true, so we can return a2
4735     mov(result, a2);
4736     b(DONE);
4737     bind(SHORT);
4738     cmp(cnt2, cnt1);
4739     br(NE, DONE);
4740     cbz(cnt1, SAME);
4741     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
4742     ldr(tmp3, Address(a1, base_offset));
4743     ldr(tmp4, Address(a2, base_offset));
4744     bind(LAST_CHECK);
4745     eor(tmp4, tmp3, tmp4);
4746     lslv(tmp5, tmp4, tmp5);
4747     cmp(tmp5, zr);
4748     bind(CSET_EQ);
4749     cset(result, EQ);
4750     b(DONE);
4751   }
4752 
4753   bind(SAME);
4754   mov(result, true);
4755   // That's it.
4756   bind(DONE);
4757 
4758   BLOCK_COMMENT("} array_equals");
4759   postcond(pc() != badAddress);
4760   return pc();
4761 }
4762 
4763 // Compare Strings
4764 
4765 // For Strings we're passed the address of the first characters in a1
4766 // and a2 and the length in cnt1.
4767 // elem_size is the element size in bytes: either 1 or 2.
4768 // There are two implementations.  For arrays >= 8 bytes, all
4769 // comparisons (including the final one, which may overlap) are
4770 // performed 8 bytes at a time.  For strings < 8 bytes, we compare a
4771 // halfword, then a short, and then a byte.
4772 
4773 void MacroAssembler::string_equals(Register a1, Register a2,
4774                                    Register result, Register cnt1, int elem_size)
4775 {
4776   Label SAME, DONE, SHORT, NEXT_WORD;
4777   Register tmp1 = rscratch1;
4778   Register tmp2 = rscratch2;
4779   Register cnt2 = tmp2;  // cnt2 only used in array length compare
4780 
4781   assert(elem_size == 1 || elem_size == 2, "must be 2 or 1 byte");
4782   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
4783 
4784 #ifndef PRODUCT
4785   {
4786     const char kind = (elem_size == 2) ? 'U' : 'L';
4787     char comment[64];
4788     snprintf(comment, sizeof comment, "{string_equals%c", kind);
4789     BLOCK_COMMENT(comment);
4790   }
4791 #endif
4792 
4793   mov(result, false);
4794 
4795   // Check for short strings, i.e. smaller than wordSize.
4796   subs(cnt1, cnt1, wordSize);
4797   br(Assembler::LT, SHORT);
4798   // Main 8 byte comparison loop.
4799   bind(NEXT_WORD); {
4800     ldr(tmp1, Address(post(a1, wordSize)));
4801     ldr(tmp2, Address(post(a2, wordSize)));
4802     subs(cnt1, cnt1, wordSize);
4803     eor(tmp1, tmp1, tmp2);
4804     cbnz(tmp1, DONE);
4805   } br(GT, NEXT_WORD);
4806   // Last longword.  In the case where length == 4 we compare the
4807   // same longword twice, but that's still faster than another
4808   // conditional branch.
4809   // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
4810   // length == 4.
4811   ldr(tmp1, Address(a1, cnt1));
4812   ldr(tmp2, Address(a2, cnt1));
4813   eor(tmp2, tmp1, tmp2);
4814   cbnz(tmp2, DONE);
4815   b(SAME);
4816 
4817   bind(SHORT);
4818   Label TAIL03, TAIL01;
4819 
4820   tbz(cnt1, 2, TAIL03); // 0-7 bytes left.
4821   {
4822     ldrw(tmp1, Address(post(a1, 4)));
4823     ldrw(tmp2, Address(post(a2, 4)));
4824     eorw(tmp1, tmp1, tmp2);
4825     cbnzw(tmp1, DONE);
4826   }
4827   bind(TAIL03);
4828   tbz(cnt1, 1, TAIL01); // 0-3 bytes left.
4829   {
4830     ldrh(tmp1, Address(post(a1, 2)));
4831     ldrh(tmp2, Address(post(a2, 2)));
4832     eorw(tmp1, tmp1, tmp2);
4833     cbnzw(tmp1, DONE);
4834   }
4835   bind(TAIL01);
4836   if (elem_size == 1) { // Only needed when comparing 1-byte elements
4837     tbz(cnt1, 0, SAME); // 0-1 bytes left.
4838     {
4839       ldrb(tmp1, a1);
4840       ldrb(tmp2, a2);
4841       eorw(tmp1, tmp1, tmp2);
4842       cbnzw(tmp1, DONE);
4843     }
4844   }
4845   // Arrays are equal.
4846   bind(SAME);
4847   mov(result, true);
4848 
4849   // That's it.
4850   bind(DONE);
4851   BLOCK_COMMENT("} string_equals");
4852 }
4853 
4854 
4855 // The size of the blocks erased by the zero_blocks stub.  We must
4856 // handle anything smaller than this ourselves in zero_words().
4857 const int MacroAssembler::zero_words_block_size = 8;
4858 
4859 // zero_words() is used by C2 ClearArray patterns and by
4860 // C1_MacroAssembler.  It is as small as possible, handling small word
4861 // counts locally and delegating anything larger to the zero_blocks
4862 // stub.  It is expanded many times in compiled code, so it is
4863 // important to keep it short.
4864 
4865 // ptr:   Address of a buffer to be zeroed.
4866 // cnt:   Count in HeapWords.
4867 //
4868 // ptr, cnt, rscratch1, and rscratch2 are clobbered.
4869 address MacroAssembler::zero_words(Register ptr, Register cnt)
4870 {
4871   assert(is_power_of_2(zero_words_block_size), "adjust this");
4872 
4873   BLOCK_COMMENT("zero_words {");
4874   assert(ptr == r10 && cnt == r11, "mismatch in register usage");
4875   RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
4876   assert(zero_blocks.target() != NULL, "zero_blocks stub has not been generated");
4877 
4878   subs(rscratch1, cnt, zero_words_block_size);
4879   Label around;
4880   br(LO, around);
4881   {
4882     RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
4883     assert(zero_blocks.target() != NULL, "zero_blocks stub has not been generated");
4884     // Make sure this is a C2 compilation. C1 allocates space only for
4885     // trampoline stubs generated by Call LIR ops, and in any case it
4886     // makes sense for a C1 compilation task to proceed as quickly as
4887     // possible.
4888     CompileTask* task;
4889     if (StubRoutines::aarch64::complete()
4890         && Thread::current()->is_Compiler_thread()
4891         && (task = ciEnv::current()->task())
4892         && is_c2_compile(task->comp_level())) {
4893       address tpc = trampoline_call(zero_blocks);
4894       if (tpc == NULL) {
4895         DEBUG_ONLY(reset_labels(around));
4896         return NULL;
4897       }
4898     } else {
4899       far_call(zero_blocks);
4900     }
4901   }
4902   bind(around);
4903 
4904   // We have a few words left to do. zero_blocks has adjusted r10 and r11
4905   // for us.
4906   for (int i = zero_words_block_size >> 1; i > 1; i >>= 1) {
4907     Label l;
4908     tbz(cnt, exact_log2(i), l);
4909     for (int j = 0; j < i; j += 2) {
4910       stp(zr, zr, post(ptr, 2 * BytesPerWord));
4911     }
4912     bind(l);
4913   }
4914   {
4915     Label l;
4916     tbz(cnt, 0, l);
4917     str(zr, Address(ptr));
4918     bind(l);
4919   }
4920 
4921   BLOCK_COMMENT("} zero_words");
4922   return pc();
4923 }
4924 
4925 // base:         Address of a buffer to be zeroed, 8 bytes aligned.
4926 // cnt:          Immediate count in HeapWords.
4927 //
4928 // r10, r11, rscratch1, and rscratch2 are clobbered.
4929 address MacroAssembler::zero_words(Register base, uint64_t cnt)
4930 {
4931   assert(wordSize <= BlockZeroingLowLimit,
4932             "increase BlockZeroingLowLimit");
4933   address result = nullptr;
4934   if (cnt <= (uint64_t)BlockZeroingLowLimit / BytesPerWord) {
4935 #ifndef PRODUCT
4936     {
4937       char buf[64];
4938       snprintf(buf, sizeof buf, "zero_words (count = %" PRIu64 ") {", cnt);
4939       BLOCK_COMMENT(buf);
4940     }
4941 #endif
4942     if (cnt >= 16) {
4943       uint64_t loops = cnt/16;
4944       if (loops > 1) {
4945         mov(rscratch2, loops - 1);
4946       }
4947       {
4948         Label loop;
4949         bind(loop);
4950         for (int i = 0; i < 16; i += 2) {
4951           stp(zr, zr, Address(base, i * BytesPerWord));
4952         }
4953         add(base, base, 16 * BytesPerWord);
4954         if (loops > 1) {
4955           subs(rscratch2, rscratch2, 1);
4956           br(GE, loop);
4957         }
4958       }
4959     }
4960     cnt %= 16;
4961     int i = cnt & 1;  // store any odd word to start
4962     if (i) str(zr, Address(base));
4963     for (; i < (int)cnt; i += 2) {
4964       stp(zr, zr, Address(base, i * wordSize));
4965     }
4966     BLOCK_COMMENT("} zero_words");
4967     result = pc();
4968   } else {
4969     mov(r10, base); mov(r11, cnt);
4970     result = zero_words(r10, r11);
4971   }
4972   return result;
4973 }
4974 
4975 // Zero blocks of memory by using DC ZVA.
4976 //
4977 // Aligns the base address first sufficently for DC ZVA, then uses
4978 // DC ZVA repeatedly for every full block.  cnt is the size to be
4979 // zeroed in HeapWords.  Returns the count of words left to be zeroed
4980 // in cnt.
4981 //
4982 // NOTE: This is intended to be used in the zero_blocks() stub.  If
4983 // you want to use it elsewhere, note that cnt must be >= 2*zva_length.
4984 void MacroAssembler::zero_dcache_blocks(Register base, Register cnt) {
4985   Register tmp = rscratch1;
4986   Register tmp2 = rscratch2;
4987   int zva_length = VM_Version::zva_length();
4988   Label initial_table_end, loop_zva;
4989   Label fini;
4990 
4991   // Base must be 16 byte aligned. If not just return and let caller handle it
4992   tst(base, 0x0f);
4993   br(Assembler::NE, fini);
4994   // Align base with ZVA length.
4995   neg(tmp, base);
4996   andr(tmp, tmp, zva_length - 1);
4997 
4998   // tmp: the number of bytes to be filled to align the base with ZVA length.
4999   add(base, base, tmp);
5000   sub(cnt, cnt, tmp, Assembler::ASR, 3);
5001   adr(tmp2, initial_table_end);
5002   sub(tmp2, tmp2, tmp, Assembler::LSR, 2);
5003   br(tmp2);
5004 
5005   for (int i = -zva_length + 16; i < 0; i += 16)
5006     stp(zr, zr, Address(base, i));
5007   bind(initial_table_end);
5008 
5009   sub(cnt, cnt, zva_length >> 3);
5010   bind(loop_zva);
5011   dc(Assembler::ZVA, base);
5012   subs(cnt, cnt, zva_length >> 3);
5013   add(base, base, zva_length);
5014   br(Assembler::GE, loop_zva);
5015   add(cnt, cnt, zva_length >> 3); // count not zeroed by DC ZVA
5016   bind(fini);
5017 }
5018 
5019 // base:   Address of a buffer to be filled, 8 bytes aligned.
5020 // cnt:    Count in 8-byte unit.
5021 // value:  Value to be filled with.
5022 // base will point to the end of the buffer after filling.
5023 void MacroAssembler::fill_words(Register base, Register cnt, Register value)
5024 {
5025 //  Algorithm:
5026 //
5027 //    scratch1 = cnt & 7;
5028 //    cnt -= scratch1;
5029 //    p += scratch1;
5030 //    switch (scratch1) {
5031 //      do {
5032 //        cnt -= 8;
5033 //          p[-8] = v;
5034 //        case 7:
5035 //          p[-7] = v;
5036 //        case 6:
5037 //          p[-6] = v;
5038 //          // ...
5039 //        case 1:
5040 //          p[-1] = v;
5041 //        case 0:
5042 //          p += 8;
5043 //      } while (cnt);
5044 //    }
5045 
5046   assert_different_registers(base, cnt, value, rscratch1, rscratch2);
5047 
5048   Label fini, skip, entry, loop;
5049   const int unroll = 8; // Number of stp instructions we'll unroll
5050 
5051   cbz(cnt, fini);
5052   tbz(base, 3, skip);
5053   str(value, Address(post(base, 8)));
5054   sub(cnt, cnt, 1);
5055   bind(skip);
5056 
5057   andr(rscratch1, cnt, (unroll-1) * 2);
5058   sub(cnt, cnt, rscratch1);
5059   add(base, base, rscratch1, Assembler::LSL, 3);
5060   adr(rscratch2, entry);
5061   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 1);
5062   br(rscratch2);
5063 
5064   bind(loop);
5065   add(base, base, unroll * 16);
5066   for (int i = -unroll; i < 0; i++)
5067     stp(value, value, Address(base, i * 16));
5068   bind(entry);
5069   subs(cnt, cnt, unroll * 2);
5070   br(Assembler::GE, loop);
5071 
5072   tbz(cnt, 0, fini);
5073   str(value, Address(post(base, 8)));
5074   bind(fini);
5075 }
5076 
5077 // Intrinsic for sun/nio/cs/ISO_8859_1$Encoder.implEncodeISOArray and
5078 // java/lang/StringUTF16.compress.
5079 void MacroAssembler::encode_iso_array(Register src, Register dst,
5080                       Register len, Register result,
5081                       FloatRegister Vtmp1, FloatRegister Vtmp2,
5082                       FloatRegister Vtmp3, FloatRegister Vtmp4)
5083 {
5084     Label DONE, SET_RESULT, NEXT_32, NEXT_32_PRFM, LOOP_8, NEXT_8, LOOP_1, NEXT_1,
5085         NEXT_32_START, NEXT_32_PRFM_START;
5086     Register tmp1 = rscratch1, tmp2 = rscratch2;
5087 
5088       mov(result, len); // Save initial len
5089 
5090       cmp(len, (u1)8); // handle shortest strings first
5091       br(LT, LOOP_1);
5092       cmp(len, (u1)32);
5093       br(LT, NEXT_8);
5094       // The following code uses the SIMD 'uzp1' and 'uzp2' instructions
5095       // to convert chars to bytes
5096       if (SoftwarePrefetchHintDistance >= 0) {
5097         ld1(Vtmp1, Vtmp2, Vtmp3, Vtmp4, T8H, src);
5098         subs(tmp2, len, SoftwarePrefetchHintDistance/2 + 16);
5099         br(LE, NEXT_32_START);
5100         b(NEXT_32_PRFM_START);
5101         BIND(NEXT_32_PRFM);
5102           ld1(Vtmp1, Vtmp2, Vtmp3, Vtmp4, T8H, src);
5103         BIND(NEXT_32_PRFM_START);
5104           prfm(Address(src, SoftwarePrefetchHintDistance));
5105           orr(v4, T16B, Vtmp1, Vtmp2);
5106           orr(v5, T16B, Vtmp3, Vtmp4);
5107           uzp1(Vtmp1, T16B, Vtmp1, Vtmp2);
5108           uzp1(Vtmp3, T16B, Vtmp3, Vtmp4);
5109           uzp2(v5, T16B, v4, v5); // high bytes
5110           umov(tmp2, v5, D, 1);
5111           fmovd(tmp1, v5);
5112           orr(tmp1, tmp1, tmp2);
5113           cbnz(tmp1, LOOP_8);
5114           stpq(Vtmp1, Vtmp3, dst);
5115           sub(len, len, 32);
5116           add(dst, dst, 32);
5117           add(src, src, 64);
5118           subs(tmp2, len, SoftwarePrefetchHintDistance/2 + 16);
5119           br(GE, NEXT_32_PRFM);
5120           cmp(len, (u1)32);
5121           br(LT, LOOP_8);
5122         BIND(NEXT_32);
5123           ld1(Vtmp1, Vtmp2, Vtmp3, Vtmp4, T8H, src);
5124         BIND(NEXT_32_START);
5125       } else {
5126         BIND(NEXT_32);
5127           ld1(Vtmp1, Vtmp2, Vtmp3, Vtmp4, T8H, src);
5128       }
5129       prfm(Address(src, SoftwarePrefetchHintDistance));
5130       uzp1(v4, T16B, Vtmp1, Vtmp2);
5131       uzp1(v5, T16B, Vtmp3, Vtmp4);
5132       orr(Vtmp1, T16B, Vtmp1, Vtmp2);
5133       orr(Vtmp3, T16B, Vtmp3, Vtmp4);
5134       uzp2(Vtmp1, T16B, Vtmp1, Vtmp3); // high bytes
5135       umov(tmp2, Vtmp1, D, 1);
5136       fmovd(tmp1, Vtmp1);
5137       orr(tmp1, tmp1, tmp2);
5138       cbnz(tmp1, LOOP_8);
5139       stpq(v4, v5, dst);
5140       sub(len, len, 32);
5141       add(dst, dst, 32);
5142       add(src, src, 64);
5143       cmp(len, (u1)32);
5144       br(GE, NEXT_32);
5145       cbz(len, DONE);
5146 
5147     BIND(LOOP_8);
5148       cmp(len, (u1)8);
5149       br(LT, LOOP_1);
5150     BIND(NEXT_8);
5151       ld1(Vtmp1, T8H, src);
5152       uzp1(Vtmp2, T16B, Vtmp1, Vtmp1); // low bytes
5153       uzp2(Vtmp3, T16B, Vtmp1, Vtmp1); // high bytes
5154       fmovd(tmp1, Vtmp3);
5155       cbnz(tmp1, NEXT_1);
5156       strd(Vtmp2, dst);
5157 
5158       sub(len, len, 8);
5159       add(dst, dst, 8);
5160       add(src, src, 16);
5161       cmp(len, (u1)8);
5162       br(GE, NEXT_8);
5163 
5164     BIND(LOOP_1);
5165 
5166     cbz(len, DONE);
5167     BIND(NEXT_1);
5168       ldrh(tmp1, Address(post(src, 2)));
5169       tst(tmp1, 0xff00);
5170       br(NE, SET_RESULT);
5171       strb(tmp1, Address(post(dst, 1)));
5172       subs(len, len, 1);
5173       br(GT, NEXT_1);
5174 
5175     BIND(SET_RESULT);
5176       sub(result, result, len); // Return index where we stopped
5177                                 // Return len == 0 if we processed all
5178                                 // characters
5179     BIND(DONE);
5180 }
5181 
5182 
5183 // Inflate byte[] array to char[].
5184 address MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
5185                                            FloatRegister vtmp1, FloatRegister vtmp2,
5186                                            FloatRegister vtmp3, Register tmp4) {
5187   Label big, done, after_init, to_stub;
5188 
5189   assert_different_registers(src, dst, len, tmp4, rscratch1);
5190 
5191   fmovd(vtmp1, 0.0);
5192   lsrw(tmp4, len, 3);
5193   bind(after_init);
5194   cbnzw(tmp4, big);
5195   // Short string: less than 8 bytes.
5196   {
5197     Label loop, tiny;
5198 
5199     cmpw(len, 4);
5200     br(LT, tiny);
5201     // Use SIMD to do 4 bytes.
5202     ldrs(vtmp2, post(src, 4));
5203     zip1(vtmp3, T8B, vtmp2, vtmp1);
5204     subw(len, len, 4);
5205     strd(vtmp3, post(dst, 8));
5206 
5207     cbzw(len, done);
5208 
5209     // Do the remaining bytes by steam.
5210     bind(loop);
5211     ldrb(tmp4, post(src, 1));
5212     strh(tmp4, post(dst, 2));
5213     subw(len, len, 1);
5214 
5215     bind(tiny);
5216     cbnz(len, loop);
5217 
5218     b(done);
5219   }
5220 
5221   if (SoftwarePrefetchHintDistance >= 0) {
5222     bind(to_stub);
5223       RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_byte_array_inflate());
5224       assert(stub.target() != NULL, "large_byte_array_inflate stub has not been generated");
5225       address tpc = trampoline_call(stub);
5226       if (tpc == NULL) {
5227         DEBUG_ONLY(reset_labels(big, done));
5228         postcond(pc() == badAddress);
5229         return NULL;
5230       }
5231       b(after_init);
5232   }
5233 
5234   // Unpack the bytes 8 at a time.
5235   bind(big);
5236   {
5237     Label loop, around, loop_last, loop_start;
5238 
5239     if (SoftwarePrefetchHintDistance >= 0) {
5240       const int large_loop_threshold = (64 + 16)/8;
5241       ldrd(vtmp2, post(src, 8));
5242       andw(len, len, 7);
5243       cmp(tmp4, (u1)large_loop_threshold);
5244       br(GE, to_stub);
5245       b(loop_start);
5246 
5247       bind(loop);
5248       ldrd(vtmp2, post(src, 8));
5249       bind(loop_start);
5250       subs(tmp4, tmp4, 1);
5251       br(EQ, loop_last);
5252       zip1(vtmp2, T16B, vtmp2, vtmp1);
5253       ldrd(vtmp3, post(src, 8));
5254       st1(vtmp2, T8H, post(dst, 16));
5255       subs(tmp4, tmp4, 1);
5256       zip1(vtmp3, T16B, vtmp3, vtmp1);
5257       st1(vtmp3, T8H, post(dst, 16));
5258       br(NE, loop);
5259       b(around);
5260       bind(loop_last);
5261       zip1(vtmp2, T16B, vtmp2, vtmp1);
5262       st1(vtmp2, T8H, post(dst, 16));
5263       bind(around);
5264       cbz(len, done);
5265     } else {
5266       andw(len, len, 7);
5267       bind(loop);
5268       ldrd(vtmp2, post(src, 8));
5269       sub(tmp4, tmp4, 1);
5270       zip1(vtmp3, T16B, vtmp2, vtmp1);
5271       st1(vtmp3, T8H, post(dst, 16));
5272       cbnz(tmp4, loop);
5273     }
5274   }
5275 
5276   // Do the tail of up to 8 bytes.
5277   add(src, src, len);
5278   ldrd(vtmp3, Address(src, -8));
5279   add(dst, dst, len, ext::uxtw, 1);
5280   zip1(vtmp3, T16B, vtmp3, vtmp1);
5281   strq(vtmp3, Address(dst, -16));
5282 
5283   bind(done);
5284   postcond(pc() != badAddress);
5285   return pc();
5286 }
5287 
5288 // Compress char[] array to byte[].
5289 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
5290                                          FloatRegister tmp1Reg, FloatRegister tmp2Reg,
5291                                          FloatRegister tmp3Reg, FloatRegister tmp4Reg,
5292                                          Register result) {
5293   encode_iso_array(src, dst, len, result,
5294                    tmp1Reg, tmp2Reg, tmp3Reg, tmp4Reg);
5295   cmp(len, zr);
5296   csel(result, result, zr, EQ);
5297 }
5298 
5299 // get_thread() can be called anywhere inside generated code so we
5300 // need to save whatever non-callee save context might get clobbered
5301 // by the call to JavaThread::aarch64_get_thread_helper() or, indeed,
5302 // the call setup code.
5303 //
5304 // On Linux, aarch64_get_thread_helper() clobbers only r0, r1, and flags.
5305 // On other systems, the helper is a usual C function.
5306 //
5307 void MacroAssembler::get_thread(Register dst) {
5308   RegSet saved_regs =
5309     LINUX_ONLY(RegSet::range(r0, r1)  + lr - dst)
5310     NOT_LINUX (RegSet::range(r0, r17) + lr - dst);
5311 
5312   push(saved_regs, sp);
5313 
5314   mov(lr, CAST_FROM_FN_PTR(address, JavaThread::aarch64_get_thread_helper));
5315   blr(lr);
5316   if (dst != c_rarg0) {
5317     mov(dst, c_rarg0);
5318   }
5319 
5320   pop(saved_regs, sp);
5321 }
5322 
5323 void MacroAssembler::cache_wb(Address line) {
5324   assert(line.getMode() == Address::base_plus_offset, "mode should be base_plus_offset");
5325   assert(line.index() == noreg, "index should be noreg");
5326   assert(line.offset() == 0, "offset should be 0");
5327   // would like to assert this
5328   // assert(line._ext.shift == 0, "shift should be zero");
5329   if (VM_Version::features() & VM_Version::CPU_DCPOP) {
5330     // writeback using clear virtual address to point of persistence
5331     dc(Assembler::CVAP, line.base());
5332   } else {
5333     // no need to generate anything as Unsafe.writebackMemory should
5334     // never invoke this stub
5335   }
5336 }
5337 
5338 void MacroAssembler::cache_wbsync(bool is_pre) {
5339   // we only need a barrier post sync
5340   if (!is_pre) {
5341     membar(Assembler::AnyAny);
5342   }
5343 }
5344 
5345 void MacroAssembler::verify_sve_vector_length() {
5346   // Make sure that native code does not change SVE vector length.
5347   if (!UseSVE) return;
5348   Label verify_ok;
5349   movw(rscratch1, zr);
5350   sve_inc(rscratch1, B);
5351   subsw(zr, rscratch1, VM_Version::get_initial_sve_vector_length());
5352   br(EQ, verify_ok);
5353   stop("Error: SVE vector length has changed since jvm startup");
5354   bind(verify_ok);
5355 }
5356 
5357 void MacroAssembler::verify_ptrue() {
5358   Label verify_ok;
5359   if (!UseSVE) {
5360     return;
5361   }
5362   sve_cntp(rscratch1, B, ptrue, ptrue); // get true elements count.
5363   sve_dec(rscratch1, B);
5364   cbz(rscratch1, verify_ok);
5365   stop("Error: the preserved predicate register (p7) elements are not all true");
5366   bind(verify_ok);
5367 }
5368 
5369 void MacroAssembler::safepoint_isb() {
5370   isb();
5371 #ifndef PRODUCT
5372   if (VerifyCrossModifyFence) {
5373     // Clear the thread state.
5374     strb(zr, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
5375   }
5376 #endif
5377 }
5378 
5379 #ifndef PRODUCT
5380 void MacroAssembler::verify_cross_modify_fence_not_required() {
5381   if (VerifyCrossModifyFence) {
5382     // Check if thread needs a cross modify fence.
5383     ldrb(rscratch1, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
5384     Label fence_not_required;
5385     cbz(rscratch1, fence_not_required);
5386     // If it does then fail.
5387     lea(rscratch1, CAST_FROM_FN_PTR(address, JavaThread::verify_cross_modify_fence_failure));
5388     mov(c_rarg0, rthread);
5389     blr(rscratch1);
5390     bind(fence_not_required);
5391   }
5392 }
5393 #endif
5394 
5395 void MacroAssembler::spin_wait() {
5396   for (int i = 0; i < VM_Version::spin_wait_desc().inst_count(); ++i) {
5397     switch (VM_Version::spin_wait_desc().inst()) {
5398       case SpinWait::NOP:
5399         nop();
5400         break;
5401       case SpinWait::ISB:
5402         isb();
5403         break;
5404       case SpinWait::YIELD:
5405         yield();
5406         break;
5407       default:
5408         ShouldNotReachHere();
5409     }
5410   }
5411 }
5412 
5413 // Implements fast-locking.
5414 // Branches to slow upon failure to lock the object, with ZF cleared.
5415 // Falls through upon success with ZF set.
5416 //
5417 //  - obj: the object to be locked
5418 //  - hdr: the header, already loaded from obj, will be destroyed
5419 //  - t1, t2: temporary registers, will be destroyed
5420 void MacroAssembler::fast_lock(Register obj, Register hdr, Register t1, Register t2, Label& slow) {
5421   assert(LockingMode == LM_LIGHTWEIGHT, "only used with new lightweight locking");
5422   assert_different_registers(obj, hdr, t1, t2);
5423 
5424   // Check if we would have space on lock-stack for the object.
5425   ldrw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
5426   cmpw(t1, (unsigned)LockStack::end_offset() - 1);
5427   br(Assembler::GT, slow);
5428 
5429   // Load (object->mark() | 1) into hdr
5430   orr(hdr, hdr, markWord::unlocked_value);
5431   // Clear lock-bits, into t2
5432   eor(t2, hdr, markWord::unlocked_value);
5433   // Try to swing header from unlocked to locked
5434   cmpxchg(/*addr*/ obj, /*expected*/ hdr, /*new*/ t2, Assembler::xword,
5435           /*acquire*/ true, /*release*/ true, /*weak*/ false, t1);
5436   br(Assembler::NE, slow);
5437 
5438   // After successful lock, push object on lock-stack
5439   ldrw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
5440   str(obj, Address(rthread, t1));
5441   addw(t1, t1, oopSize);
5442   strw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
5443 }
5444 
5445 // Implements fast-unlocking.
5446 // Branches to slow upon failure, with ZF cleared.
5447 // Falls through upon success, with ZF set.
5448 //
5449 // - obj: the object to be unlocked
5450 // - hdr: the (pre-loaded) header of the object
5451 // - t1, t2: temporary registers
5452 void MacroAssembler::fast_unlock(Register obj, Register hdr, Register t1, Register t2, Label& slow) {
5453   assert(LockingMode == LM_LIGHTWEIGHT, "only used with new lightweight locking");
5454   assert_different_registers(obj, hdr, t1, t2);
5455 
5456 #ifdef ASSERT
5457   {
5458     // The following checks rely on the fact that LockStack is only ever modified by
5459     // its owning thread, even if the lock got inflated concurrently; removal of LockStack
5460     // entries after inflation will happen delayed in that case.
5461 
5462     // Check for lock-stack underflow.
5463     Label stack_ok;
5464     ldrw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
5465     cmpw(t1, (unsigned)LockStack::start_offset());
5466     br(Assembler::GT, stack_ok);
5467     STOP("Lock-stack underflow");
5468     bind(stack_ok);
5469   }
5470   {
5471     // Check if the top of the lock-stack matches the unlocked object.
5472     Label tos_ok;
5473     subw(t1, t1, oopSize);
5474     ldr(t1, Address(rthread, t1));
5475     cmpoop(t1, obj);
5476     br(Assembler::EQ, tos_ok);
5477     STOP("Top of lock-stack does not match the unlocked object");
5478     bind(tos_ok);
5479   }
5480   {
5481     // Check that hdr is fast-locked.
5482     Label hdr_ok;
5483     tst(hdr, markWord::lock_mask_in_place);
5484     br(Assembler::EQ, hdr_ok);
5485     STOP("Header is not fast-locked");
5486     bind(hdr_ok);
5487   }
5488 #endif
5489 
5490   // Load the new header (unlocked) into t1
5491   orr(t1, hdr, markWord::unlocked_value);
5492 
5493   // Try to swing header from locked to unlocked
5494   cmpxchg(obj, hdr, t1, Assembler::xword,
5495           /*acquire*/ true, /*release*/ true, /*weak*/ false, t2);
5496   br(Assembler::NE, slow);
5497 
5498   // After successful unlock, pop object from lock-stack
5499   ldrw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
5500   subw(t1, t1, oopSize);
5501 #ifdef ASSERT
5502   str(zr, Address(rthread, t1));
5503 #endif
5504   strw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
5505 }
--- EOF ---