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