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