1 /*
   2  * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2014, 2024, 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 "asm/assembler.hpp"
  27 #include "asm/assembler.inline.hpp"
  28 #include "ci/ciEnv.hpp"
  29 #include "ci/ciInlineKlass.hpp"
  30 #include "code/compiledIC.hpp"
  31 #include "compiler/compileTask.hpp"
  32 #include "compiler/disassembler.hpp"
  33 #include "compiler/oopMap.hpp"
  34 #include "gc/shared/barrierSet.hpp"
  35 #include "gc/shared/barrierSetAssembler.hpp"
  36 #include "gc/shared/cardTableBarrierSet.hpp"
  37 #include "gc/shared/cardTable.hpp"
  38 #include "gc/shared/collectedHeap.hpp"
  39 #include "gc/shared/tlab_globals.hpp"
  40 #include "interpreter/bytecodeHistogram.hpp"
  41 #include "interpreter/interpreter.hpp"
  42 #include "interpreter/interpreterRuntime.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 "oops/resolvedFieldEntry.hpp"
  52 #include "runtime/arguments.hpp"
  53 #include "runtime/continuation.hpp"
  54 #include "runtime/globals.hpp"
  55 #include "runtime/icache.hpp"
  56 #include "runtime/interfaceSupport.inline.hpp"
  57 #include "runtime/javaThread.hpp"
  58 #include "runtime/jniHandles.inline.hpp"
  59 #include "runtime/sharedRuntime.hpp"
  60 #include "runtime/signature_cc.hpp"
  61 #include "runtime/stubRoutines.hpp"
  62 #include "utilities/globalDefinitions.hpp"
  63 #include "utilities/integerCast.hpp"
  64 #include "utilities/powerOfTwo.hpp"
  65 #include "vmreg_aarch64.inline.hpp"
  66 #ifdef COMPILER1
  67 #include "c1/c1_LIRAssembler.hpp"
  68 #endif
  69 #ifdef COMPILER2
  70 #include "oops/oop.hpp"
  71 #include "opto/compile.hpp"
  72 #include "opto/node.hpp"
  73 #include "opto/output.hpp"
  74 #endif
  75 
  76 #include <sys/types.h>
  77 
  78 #ifdef PRODUCT
  79 #define BLOCK_COMMENT(str) /* nothing */
  80 #else
  81 #define BLOCK_COMMENT(str) block_comment(str)
  82 #endif
  83 #define STOP(str) stop(str);
  84 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  85 
  86 #ifdef ASSERT
  87 extern "C" void disnm(intptr_t p);
  88 #endif
  89 // Target-dependent relocation processing
  90 //
  91 // Instruction sequences whose target may need to be retrieved or
  92 // patched are distinguished by their leading instruction, sorting
  93 // them into three main instruction groups and related subgroups.
  94 //
  95 // 1) Branch, Exception and System (insn count = 1)
  96 //    1a) Unconditional branch (immediate):
  97 //      b/bl imm19
  98 //    1b) Compare & branch (immediate):
  99 //      cbz/cbnz Rt imm19
 100 //    1c) Test & branch (immediate):
 101 //      tbz/tbnz Rt imm14
 102 //    1d) Conditional branch (immediate):
 103 //      b.cond imm19
 104 //
 105 // 2) Loads and Stores (insn count = 1)
 106 //    2a) Load register literal:
 107 //      ldr Rt imm19
 108 //
 109 // 3) Data Processing Immediate (insn count = 2 or 3)
 110 //    3a) PC-rel. addressing
 111 //      adr/adrp Rx imm21; ldr/str Ry Rx  #imm12
 112 //      adr/adrp Rx imm21; add Ry Rx  #imm12
 113 //      adr/adrp Rx imm21; movk Rx #imm16<<32; ldr/str Ry, [Rx, #offset_in_page]
 114 //      adr/adrp Rx imm21
 115 //      adr/adrp Rx imm21; movk Rx #imm16<<32
 116 //      adr/adrp Rx imm21; movk Rx #imm16<<32; add Ry, Rx, #offset_in_page
 117 //      The latter form can only happen when the target is an
 118 //      ExternalAddress, and (by definition) ExternalAddresses don't
 119 //      move. Because of that property, there is never any need to
 120 //      patch the last of the three instructions. However,
 121 //      MacroAssembler::target_addr_for_insn takes all three
 122 //      instructions into account and returns the correct address.
 123 //    3b) Move wide (immediate)
 124 //      movz Rx #imm16; movk Rx #imm16 << 16; movk Rx #imm16 << 32;
 125 //
 126 // A switch on a subset of the instruction's bits provides an
 127 // efficient dispatch to these subcases.
 128 //
 129 // insn[28:26] -> main group ('x' == don't care)
 130 //   00x -> UNALLOCATED
 131 //   100 -> Data Processing Immediate
 132 //   101 -> Branch, Exception and System
 133 //   x1x -> Loads and Stores
 134 //
 135 // insn[30:25] -> subgroup ('_' == group, 'x' == don't care).
 136 // n.b. in some cases extra bits need to be checked to verify the
 137 // instruction is as expected
 138 //
 139 // 1) ... xx101x Branch, Exception and System
 140 //   1a)  00___x Unconditional branch (immediate)
 141 //   1b)  01___0 Compare & branch (immediate)
 142 //   1c)  01___1 Test & branch (immediate)
 143 //   1d)  10___0 Conditional branch (immediate)
 144 //        other  Should not happen
 145 //
 146 // 2) ... xxx1x0 Loads and Stores
 147 //   2a)  xx1__00 Load/Store register (insn[28] == 1 && insn[24] == 0)
 148 //   2aa) x01__00 Load register literal (i.e. requires insn[29] == 0)
 149 //                strictly should be 64 bit non-FP/SIMD i.e.
 150 //       0101_000 (i.e. requires insn[31:24] == 01011000)
 151 //
 152 // 3) ... xx100x Data Processing Immediate
 153 //   3a)  xx___00 PC-rel. addressing (n.b. requires insn[24] == 0)
 154 //   3b)  xx___101 Move wide (immediate) (n.b. requires insn[24:23] == 01)
 155 //                 strictly should be 64 bit movz #imm16<<0
 156 //       110___10100 (i.e. requires insn[31:21] == 11010010100)
 157 //
 158 
 159 static uint32_t insn_at(address insn_addr, int n) {
 160   return ((uint32_t*)insn_addr)[n];
 161 }
 162 
 163 template<typename T>
 164 class RelocActions : public AllStatic {
 165 
 166 public:
 167 
 168   static int ALWAYSINLINE run(address insn_addr, address &target) {
 169     int instructions = 1;
 170     uint32_t insn = insn_at(insn_addr, 0);
 171 
 172     uint32_t dispatch = Instruction_aarch64::extract(insn, 30, 25);
 173     switch(dispatch) {
 174       case 0b001010:
 175       case 0b001011: {
 176         instructions = T::unconditionalBranch(insn_addr, target);
 177         break;
 178       }
 179       case 0b101010:   // Conditional branch (immediate)
 180       case 0b011010: { // Compare & branch (immediate)
 181         instructions = T::conditionalBranch(insn_addr, target);
 182         break;
 183       }
 184       case 0b011011: {
 185         instructions = T::testAndBranch(insn_addr, target);
 186         break;
 187       }
 188       case 0b001100:
 189       case 0b001110:
 190       case 0b011100:
 191       case 0b011110:
 192       case 0b101100:
 193       case 0b101110:
 194       case 0b111100:
 195       case 0b111110: {
 196         // load/store
 197         if ((Instruction_aarch64::extract(insn, 29, 24) & 0b111011) == 0b011000) {
 198           // Load register (literal)
 199           instructions = T::loadStore(insn_addr, target);
 200           break;
 201         } else {
 202           // nothing to do
 203           assert(target == nullptr, "did not expect to relocate target for polling page load");
 204         }
 205         break;
 206       }
 207       case 0b001000:
 208       case 0b011000:
 209       case 0b101000:
 210       case 0b111000: {
 211         // adr/adrp
 212         assert(Instruction_aarch64::extract(insn, 28, 24) == 0b10000, "must be");
 213         int shift = Instruction_aarch64::extract(insn, 31, 31);
 214         if (shift) {
 215           uint32_t insn2 = insn_at(insn_addr, 1);
 216           if (Instruction_aarch64::extract(insn2, 29, 24) == 0b111001 &&
 217               Instruction_aarch64::extract(insn, 4, 0) ==
 218               Instruction_aarch64::extract(insn2, 9, 5)) {
 219             instructions = T::adrp(insn_addr, target, T::adrpMem);
 220           } else if (Instruction_aarch64::extract(insn2, 31, 22) == 0b1001000100 &&
 221                      Instruction_aarch64::extract(insn, 4, 0) ==
 222                      Instruction_aarch64::extract(insn2, 4, 0)) {
 223             instructions = T::adrp(insn_addr, target, T::adrpAdd);
 224           } else if (Instruction_aarch64::extract(insn2, 31, 21) == 0b11110010110 &&
 225                      Instruction_aarch64::extract(insn, 4, 0) ==
 226                      Instruction_aarch64::extract(insn2, 4, 0)) {
 227             instructions = T::adrp(insn_addr, target, T::adrpMovk);
 228           } else {
 229             ShouldNotReachHere();
 230           }
 231         } else {
 232           instructions = T::adr(insn_addr, target);
 233         }
 234         break;
 235       }
 236       case 0b001001:
 237       case 0b011001:
 238       case 0b101001:
 239       case 0b111001: {
 240         instructions = T::immediate(insn_addr, target);
 241         break;
 242       }
 243       default: {
 244         ShouldNotReachHere();
 245       }
 246     }
 247 
 248     T::verify(insn_addr, target);
 249     return instructions * NativeInstruction::instruction_size;
 250   }
 251 };
 252 
 253 class Patcher : public AllStatic {
 254 public:
 255   static int unconditionalBranch(address insn_addr, address &target) {
 256     intptr_t offset = (target - insn_addr) >> 2;
 257     Instruction_aarch64::spatch(insn_addr, 25, 0, offset);
 258     return 1;
 259   }
 260   static int conditionalBranch(address insn_addr, address &target) {
 261     intptr_t offset = (target - insn_addr) >> 2;
 262     Instruction_aarch64::spatch(insn_addr, 23, 5, offset);
 263     return 1;
 264   }
 265   static int testAndBranch(address insn_addr, address &target) {
 266     intptr_t offset = (target - insn_addr) >> 2;
 267     Instruction_aarch64::spatch(insn_addr, 18, 5, offset);
 268     return 1;
 269   }
 270   static int loadStore(address insn_addr, address &target) {
 271     intptr_t offset = (target - insn_addr) >> 2;
 272     Instruction_aarch64::spatch(insn_addr, 23, 5, offset);
 273     return 1;
 274   }
 275   static int adr(address insn_addr, address &target) {
 276 #ifdef ASSERT
 277     assert(Instruction_aarch64::extract(insn_at(insn_addr, 0), 28, 24) == 0b10000, "must be");
 278 #endif
 279     // PC-rel. addressing
 280     ptrdiff_t offset = target - insn_addr;
 281     int offset_lo = offset & 3;
 282     offset >>= 2;
 283     Instruction_aarch64::spatch(insn_addr, 23, 5, offset);
 284     Instruction_aarch64::patch(insn_addr, 30, 29, offset_lo);
 285     return 1;
 286   }
 287   template<typename U>
 288   static int adrp(address insn_addr, address &target, U inner) {
 289     int instructions = 1;
 290 #ifdef ASSERT
 291     assert(Instruction_aarch64::extract(insn_at(insn_addr, 0), 28, 24) == 0b10000, "must be");
 292 #endif
 293     ptrdiff_t offset = target - insn_addr;
 294     instructions = 2;
 295     precond(inner != nullptr);
 296     // Give the inner reloc a chance to modify the target.
 297     address adjusted_target = target;
 298     instructions = inner(insn_addr, adjusted_target);
 299     uintptr_t pc_page = (uintptr_t)insn_addr >> 12;
 300     uintptr_t adr_page = (uintptr_t)adjusted_target >> 12;
 301     offset = adr_page - pc_page;
 302     int offset_lo = offset & 3;
 303     offset >>= 2;
 304     Instruction_aarch64::spatch(insn_addr, 23, 5, offset);
 305     Instruction_aarch64::patch(insn_addr, 30, 29, offset_lo);
 306     return instructions;
 307   }
 308   static int adrpMem(address insn_addr, address &target) {
 309     uintptr_t dest = (uintptr_t)target;
 310     int offset_lo = dest & 0xfff;
 311     uint32_t insn2 = insn_at(insn_addr, 1);
 312     uint32_t size = Instruction_aarch64::extract(insn2, 31, 30);
 313     Instruction_aarch64::patch(insn_addr + sizeof (uint32_t), 21, 10, offset_lo >> size);
 314     guarantee(((dest >> size) << size) == dest, "misaligned target");
 315     return 2;
 316   }
 317   static int adrpAdd(address insn_addr, address &target) {
 318     uintptr_t dest = (uintptr_t)target;
 319     int offset_lo = dest & 0xfff;
 320     Instruction_aarch64::patch(insn_addr + sizeof (uint32_t), 21, 10, offset_lo);
 321     return 2;
 322   }
 323   static int adrpMovk(address insn_addr, address &target) {
 324     uintptr_t dest = uintptr_t(target);
 325     Instruction_aarch64::patch(insn_addr + sizeof (uint32_t), 20, 5, (uintptr_t)target >> 32);
 326     dest = (dest & 0xffffffffULL) | (uintptr_t(insn_addr) & 0xffff00000000ULL);
 327     target = address(dest);
 328     return 2;
 329   }
 330   static int immediate(address insn_addr, address &target) {
 331     assert(Instruction_aarch64::extract(insn_at(insn_addr, 0), 31, 21) == 0b11010010100, "must be");
 332     uint64_t dest = (uint64_t)target;
 333     // Move wide constant
 334     assert(nativeInstruction_at(insn_addr+4)->is_movk(), "wrong insns in patch");
 335     assert(nativeInstruction_at(insn_addr+8)->is_movk(), "wrong insns in patch");
 336     Instruction_aarch64::patch(insn_addr, 20, 5, dest & 0xffff);
 337     Instruction_aarch64::patch(insn_addr+4, 20, 5, (dest >>= 16) & 0xffff);
 338     Instruction_aarch64::patch(insn_addr+8, 20, 5, (dest >>= 16) & 0xffff);
 339     return 3;
 340   }
 341   static void verify(address insn_addr, address &target) {
 342 #ifdef ASSERT
 343     address address_is = MacroAssembler::target_addr_for_insn(insn_addr);
 344     if (!(address_is == target)) {
 345       tty->print_cr("%p at %p should be %p", address_is, insn_addr, target);
 346       disnm((intptr_t)insn_addr);
 347       assert(address_is == target, "should be");
 348     }
 349 #endif
 350   }
 351 };
 352 
 353 // If insn1 and insn2 use the same register to form an address, either
 354 // by an offsetted LDR or a simple ADD, return the offset. If the
 355 // second instruction is an LDR, the offset may be scaled.
 356 static bool offset_for(uint32_t insn1, uint32_t insn2, ptrdiff_t &byte_offset) {
 357   if (Instruction_aarch64::extract(insn2, 29, 24) == 0b111001 &&
 358       Instruction_aarch64::extract(insn1, 4, 0) ==
 359       Instruction_aarch64::extract(insn2, 9, 5)) {
 360     // Load/store register (unsigned immediate)
 361     byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 362     uint32_t size = Instruction_aarch64::extract(insn2, 31, 30);
 363     byte_offset <<= size;
 364     return true;
 365   } else if (Instruction_aarch64::extract(insn2, 31, 22) == 0b1001000100 &&
 366              Instruction_aarch64::extract(insn1, 4, 0) ==
 367              Instruction_aarch64::extract(insn2, 4, 0)) {
 368     // add (immediate)
 369     byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 370     return true;
 371   }
 372   return false;
 373 }
 374 
 375 class AArch64Decoder : public AllStatic {
 376 public:
 377 
 378   static int loadStore(address insn_addr, address &target) {
 379     intptr_t offset = Instruction_aarch64::sextract(insn_at(insn_addr, 0), 23, 5);
 380     target = insn_addr + (offset << 2);
 381     return 1;
 382   }
 383   static int unconditionalBranch(address insn_addr, address &target) {
 384     intptr_t offset = Instruction_aarch64::sextract(insn_at(insn_addr, 0), 25, 0);
 385     target = insn_addr + (offset << 2);
 386     return 1;
 387   }
 388   static int conditionalBranch(address insn_addr, address &target) {
 389     intptr_t offset = Instruction_aarch64::sextract(insn_at(insn_addr, 0), 23, 5);
 390     target = address(((uint64_t)insn_addr + (offset << 2)));
 391     return 1;
 392   }
 393   static int testAndBranch(address insn_addr, address &target) {
 394     intptr_t offset = Instruction_aarch64::sextract(insn_at(insn_addr, 0), 18, 5);
 395     target = address(((uint64_t)insn_addr + (offset << 2)));
 396     return 1;
 397   }
 398   static int adr(address insn_addr, address &target) {
 399     // PC-rel. addressing
 400     uint32_t insn = insn_at(insn_addr, 0);
 401     intptr_t offset = Instruction_aarch64::extract(insn, 30, 29);
 402     offset |= Instruction_aarch64::sextract(insn, 23, 5) << 2;
 403     target = address((uint64_t)insn_addr + offset);
 404     return 1;
 405   }
 406   template<typename U>
 407   static int adrp(address insn_addr, address &target, U inner) {
 408     uint32_t insn = insn_at(insn_addr, 0);
 409     assert(Instruction_aarch64::extract(insn, 28, 24) == 0b10000, "must be");
 410     intptr_t offset = Instruction_aarch64::extract(insn, 30, 29);
 411     offset |= Instruction_aarch64::sextract(insn, 23, 5) << 2;
 412     int shift = 12;
 413     offset <<= shift;
 414     uint64_t target_page = ((uint64_t)insn_addr) + offset;
 415     target_page &= ((uint64_t)-1) << shift;
 416     target = address(target_page);
 417     precond(inner != nullptr);
 418     inner(insn_addr, target);
 419     return 2;
 420   }
 421   static int adrpMem(address insn_addr, address &target) {
 422     uint32_t insn2 = insn_at(insn_addr, 1);
 423     // Load/store register (unsigned immediate)
 424     ptrdiff_t byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 425     uint32_t size = Instruction_aarch64::extract(insn2, 31, 30);
 426     byte_offset <<= size;
 427     target += byte_offset;
 428     return 2;
 429   }
 430   static int adrpAdd(address insn_addr, address &target) {
 431     uint32_t insn2 = insn_at(insn_addr, 1);
 432     // add (immediate)
 433     ptrdiff_t byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 434     target += byte_offset;
 435     return 2;
 436   }
 437   static int adrpMovk(address insn_addr, address &target) {
 438     uint32_t insn2 = insn_at(insn_addr, 1);
 439     uint64_t dest = uint64_t(target);
 440     dest = (dest & 0xffff0000ffffffff) |
 441       ((uint64_t)Instruction_aarch64::extract(insn2, 20, 5) << 32);
 442     target = address(dest);
 443 
 444     // We know the destination 4k page. Maybe we have a third
 445     // instruction.
 446     uint32_t insn = insn_at(insn_addr, 0);
 447     uint32_t insn3 = insn_at(insn_addr, 2);
 448     ptrdiff_t byte_offset;
 449     if (offset_for(insn, insn3, byte_offset)) {
 450       target += byte_offset;
 451       return 3;
 452     } else {
 453       return 2;
 454     }
 455   }
 456   static int immediate(address insn_addr, address &target) {
 457     uint32_t *insns = (uint32_t *)insn_addr;
 458     assert(Instruction_aarch64::extract(insns[0], 31, 21) == 0b11010010100, "must be");
 459     // Move wide constant: movz, movk, movk.  See movptr().
 460     assert(nativeInstruction_at(insns+1)->is_movk(), "wrong insns in patch");
 461     assert(nativeInstruction_at(insns+2)->is_movk(), "wrong insns in patch");
 462     target = address(uint64_t(Instruction_aarch64::extract(insns[0], 20, 5))
 463                   + (uint64_t(Instruction_aarch64::extract(insns[1], 20, 5)) << 16)
 464                   + (uint64_t(Instruction_aarch64::extract(insns[2], 20, 5)) << 32));
 465     assert(nativeInstruction_at(insn_addr+4)->is_movk(), "wrong insns in patch");
 466     assert(nativeInstruction_at(insn_addr+8)->is_movk(), "wrong insns in patch");
 467     return 3;
 468   }
 469   static void verify(address insn_addr, address &target) {
 470   }
 471 };
 472 
 473 address MacroAssembler::target_addr_for_insn(address insn_addr) {
 474   address target;
 475   RelocActions<AArch64Decoder>::run(insn_addr, target);
 476   return target;
 477 }
 478 
 479 // Patch any kind of instruction; there may be several instructions.
 480 // Return the total length (in bytes) of the instructions.
 481 int MacroAssembler::pd_patch_instruction_size(address insn_addr, address target) {
 482   MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
 483   return RelocActions<Patcher>::run(insn_addr, target);
 484 }
 485 
 486 int MacroAssembler::patch_oop(address insn_addr, address o) {
 487   int instructions;
 488   unsigned insn = *(unsigned*)insn_addr;
 489   assert(nativeInstruction_at(insn_addr+4)->is_movk(), "wrong insns in patch");
 490 
 491   MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
 492 
 493   // OOPs are either narrow (32 bits) or wide (48 bits).  We encode
 494   // narrow OOPs by setting the upper 16 bits in the first
 495   // instruction.
 496   if (Instruction_aarch64::extract(insn, 31, 21) == 0b11010010101) {
 497     // Move narrow OOP
 498     uint32_t n = CompressedOops::narrow_oop_value(cast_to_oop(o));
 499     Instruction_aarch64::patch(insn_addr, 20, 5, n >> 16);
 500     Instruction_aarch64::patch(insn_addr+4, 20, 5, n & 0xffff);
 501     instructions = 2;
 502   } else {
 503     // Move wide OOP
 504     assert(nativeInstruction_at(insn_addr+8)->is_movk(), "wrong insns in patch");
 505     uintptr_t dest = (uintptr_t)o;
 506     Instruction_aarch64::patch(insn_addr, 20, 5, dest & 0xffff);
 507     Instruction_aarch64::patch(insn_addr+4, 20, 5, (dest >>= 16) & 0xffff);
 508     Instruction_aarch64::patch(insn_addr+8, 20, 5, (dest >>= 16) & 0xffff);
 509     instructions = 3;
 510   }
 511   return instructions * NativeInstruction::instruction_size;
 512 }
 513 
 514 void MacroAssembler::safepoint_poll(Label& slow_path, bool at_return, bool in_nmethod, Register tmp) {
 515   ldr(tmp, Address(rthread, JavaThread::polling_word_offset()));
 516   if (at_return) {
 517     // Note that when in_nmethod is set, the stack pointer is incremented before the poll. Therefore,
 518     // we may safely use the sp instead to perform the stack watermark check.
 519     cmp(in_nmethod ? sp : rfp, tmp);
 520     br(Assembler::HI, slow_path);
 521   } else {
 522     tbnz(tmp, log2i_exact(SafepointMechanism::poll_bit()), slow_path);
 523   }
 524 }
 525 
 526 void MacroAssembler::rt_call(address dest, Register tmp) {
 527   CodeBlob *cb = CodeCache::find_blob(dest);
 528   if (cb) {
 529     far_call(RuntimeAddress(dest));
 530   } else {
 531     lea(tmp, RuntimeAddress(dest));
 532     blr(tmp);
 533   }
 534 }
 535 
 536 void MacroAssembler::push_cont_fastpath(Register java_thread) {
 537   if (!Continuations::enabled()) return;
 538   Label done;
 539   ldr(rscratch1, Address(java_thread, JavaThread::cont_fastpath_offset()));
 540   cmp(sp, rscratch1);
 541   br(Assembler::LS, done);
 542   mov(rscratch1, sp); // we can't use sp as the source in str
 543   str(rscratch1, Address(java_thread, JavaThread::cont_fastpath_offset()));
 544   bind(done);
 545 }
 546 
 547 void MacroAssembler::pop_cont_fastpath(Register java_thread) {
 548   if (!Continuations::enabled()) return;
 549   Label done;
 550   ldr(rscratch1, Address(java_thread, JavaThread::cont_fastpath_offset()));
 551   cmp(sp, rscratch1);
 552   br(Assembler::LO, done);
 553   str(zr, Address(java_thread, JavaThread::cont_fastpath_offset()));
 554   bind(done);
 555 }
 556 
 557 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 558   // we must set sp to zero to clear frame
 559   str(zr, Address(rthread, JavaThread::last_Java_sp_offset()));
 560 
 561   // must clear fp, so that compiled frames are not confused; it is
 562   // possible that we need it only for debugging
 563   if (clear_fp) {
 564     str(zr, Address(rthread, JavaThread::last_Java_fp_offset()));
 565   }
 566 
 567   // Always clear the pc because it could have been set by make_walkable()
 568   str(zr, Address(rthread, JavaThread::last_Java_pc_offset()));
 569 }
 570 
 571 // Calls to C land
 572 //
 573 // When entering C land, the rfp, & resp of the last Java frame have to be recorded
 574 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
 575 // has to be reset to 0. This is required to allow proper stack traversal.
 576 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 577                                          Register last_java_fp,
 578                                          Register last_java_pc,
 579                                          Register scratch) {
 580 
 581   if (last_java_pc->is_valid()) {
 582       str(last_java_pc, Address(rthread,
 583                                 JavaThread::frame_anchor_offset()
 584                                 + JavaFrameAnchor::last_Java_pc_offset()));
 585     }
 586 
 587   // determine last_java_sp register
 588   if (last_java_sp == sp) {
 589     mov(scratch, sp);
 590     last_java_sp = scratch;
 591   } else if (!last_java_sp->is_valid()) {
 592     last_java_sp = esp;
 593   }
 594 
 595   // last_java_fp is optional
 596   if (last_java_fp->is_valid()) {
 597     str(last_java_fp, Address(rthread, JavaThread::last_Java_fp_offset()));
 598   }
 599 
 600   // We must set sp last.
 601   str(last_java_sp, Address(rthread, JavaThread::last_Java_sp_offset()));
 602 }
 603 
 604 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 605                                          Register last_java_fp,
 606                                          address  last_java_pc,
 607                                          Register scratch) {
 608   assert(last_java_pc != nullptr, "must provide a valid PC");
 609 
 610   adr(scratch, last_java_pc);
 611   str(scratch, Address(rthread,
 612                        JavaThread::frame_anchor_offset()
 613                        + JavaFrameAnchor::last_Java_pc_offset()));
 614 
 615   set_last_Java_frame(last_java_sp, last_java_fp, noreg, scratch);
 616 }
 617 
 618 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 619                                          Register last_java_fp,
 620                                          Label &L,
 621                                          Register scratch) {
 622   if (L.is_bound()) {
 623     set_last_Java_frame(last_java_sp, last_java_fp, target(L), scratch);
 624   } else {
 625     InstructionMark im(this);
 626     L.add_patch_at(code(), locator());
 627     set_last_Java_frame(last_java_sp, last_java_fp, pc() /* Patched later */, scratch);
 628   }
 629 }
 630 
 631 static inline bool target_needs_far_branch(address addr) {
 632   if (AOTCodeCache::is_on_for_dump()) {
 633     return true;
 634   }
 635   // codecache size <= 128M
 636   if (!MacroAssembler::far_branches()) {
 637     return false;
 638   }
 639   // codecache size > 240M
 640   if (MacroAssembler::codestub_branch_needs_far_jump()) {
 641     return true;
 642   }
 643   // codecache size: 128M..240M
 644   return !CodeCache::is_non_nmethod(addr);
 645 }
 646 
 647 void MacroAssembler::far_call(Address entry, Register tmp) {
 648   assert(ReservedCodeCacheSize < 4*G, "branch out of range");
 649   assert(CodeCache::find_blob(entry.target()) != nullptr,
 650          "destination of far call not found in code cache");
 651   assert(entry.rspec().type() == relocInfo::external_word_type
 652          || entry.rspec().type() == relocInfo::runtime_call_type
 653          || entry.rspec().type() == relocInfo::none, "wrong entry relocInfo type");
 654   if (target_needs_far_branch(entry.target())) {
 655     uint64_t offset;
 656     // We can use ADRP here because we know that the total size of
 657     // the code cache cannot exceed 2Gb (ADRP limit is 4GB).
 658     adrp(tmp, entry, offset);
 659     add(tmp, tmp, offset);
 660     blr(tmp);
 661   } else {
 662     bl(entry);
 663   }
 664 }
 665 
 666 int MacroAssembler::far_jump(Address entry, Register tmp) {
 667   assert(ReservedCodeCacheSize < 4*G, "branch out of range");
 668   assert(CodeCache::find_blob(entry.target()) != nullptr,
 669          "destination of far call not found in code cache");
 670   assert(entry.rspec().type() == relocInfo::external_word_type
 671          || entry.rspec().type() == relocInfo::runtime_call_type
 672          || entry.rspec().type() == relocInfo::none, "wrong entry relocInfo type");
 673   address start = pc();
 674   if (target_needs_far_branch(entry.target())) {
 675     uint64_t offset;
 676     // We can use ADRP here because we know that the total size of
 677     // the code cache cannot exceed 2Gb (ADRP limit is 4GB).
 678     adrp(tmp, entry, offset);
 679     add(tmp, tmp, offset);
 680     br(tmp);
 681   } else {
 682     b(entry);
 683   }
 684   return pc() - start;
 685 }
 686 
 687 void MacroAssembler::reserved_stack_check() {
 688     // testing if reserved zone needs to be enabled
 689     Label no_reserved_zone_enabling;
 690 
 691     ldr(rscratch1, Address(rthread, JavaThread::reserved_stack_activation_offset()));
 692     cmp(sp, rscratch1);
 693     br(Assembler::LO, no_reserved_zone_enabling);
 694 
 695     enter();   // LR and FP are live.
 696     lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone)));
 697     mov(c_rarg0, rthread);
 698     blr(rscratch1);
 699     leave();
 700 
 701     // We have already removed our own frame.
 702     // throw_delayed_StackOverflowError will think that it's been
 703     // called by our caller.
 704     lea(rscratch1, RuntimeAddress(SharedRuntime::throw_delayed_StackOverflowError_entry()));
 705     br(rscratch1);
 706     should_not_reach_here();
 707 
 708     bind(no_reserved_zone_enabling);
 709 }
 710 
 711 static void pass_arg0(MacroAssembler* masm, Register arg) {
 712   if (c_rarg0 != arg ) {
 713     masm->mov(c_rarg0, arg);
 714   }
 715 }
 716 
 717 static void pass_arg1(MacroAssembler* masm, Register arg) {
 718   if (c_rarg1 != arg ) {
 719     masm->mov(c_rarg1, arg);
 720   }
 721 }
 722 
 723 static void pass_arg2(MacroAssembler* masm, Register arg) {
 724   if (c_rarg2 != arg ) {
 725     masm->mov(c_rarg2, arg);
 726   }
 727 }
 728 
 729 static void pass_arg3(MacroAssembler* masm, Register arg) {
 730   if (c_rarg3 != arg ) {
 731     masm->mov(c_rarg3, arg);
 732   }
 733 }
 734 
 735 void MacroAssembler::call_VM_base(Register oop_result,
 736                                   Register java_thread,
 737                                   Register last_java_sp,
 738                                   Label*   return_pc,
 739                                   address  entry_point,
 740                                   int      number_of_arguments,
 741                                   bool     check_exceptions) {
 742    // determine java_thread register
 743   if (!java_thread->is_valid()) {
 744     java_thread = rthread;
 745   }
 746 
 747   // determine last_java_sp register
 748   if (!last_java_sp->is_valid()) {
 749     last_java_sp = esp;
 750   }
 751 
 752   // debugging support
 753   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
 754   assert(java_thread == rthread, "unexpected register");
 755 #ifdef ASSERT
 756   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
 757   // if (!TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");
 758 #endif // ASSERT
 759 
 760   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
 761   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
 762 
 763   // push java thread (becomes first argument of C function)
 764 
 765   mov(c_rarg0, java_thread);
 766 
 767   // set last Java frame before call
 768   assert(last_java_sp != rfp, "can't use rfp");
 769 
 770   Label l;
 771   set_last_Java_frame(last_java_sp, rfp, return_pc != nullptr ? *return_pc : l, rscratch1);
 772 
 773   // do the call, remove parameters
 774   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments, &l);
 775 
 776   // lr could be poisoned with PAC signature during throw_pending_exception
 777   // if it was tail-call optimized by compiler, since lr is not callee-saved
 778   // reload it with proper value
 779   adr(lr, l);
 780 
 781   // reset last Java frame
 782   // Only interpreter should have to clear fp
 783   reset_last_Java_frame(true);
 784 
 785    // C++ interp handles this in the interpreter
 786   check_and_handle_popframe(java_thread);
 787   check_and_handle_earlyret(java_thread);
 788 
 789   if (check_exceptions) {
 790     // check for pending exceptions (java_thread is set upon return)
 791     ldr(rscratch1, Address(java_thread, in_bytes(Thread::pending_exception_offset())));
 792     Label ok;
 793     cbz(rscratch1, ok);
 794     lea(rscratch1, RuntimeAddress(StubRoutines::forward_exception_entry()));
 795     br(rscratch1);
 796     bind(ok);
 797   }
 798 
 799   // get oop result if there is one and reset the value in the thread
 800   if (oop_result->is_valid()) {
 801     get_vm_result_oop(oop_result, java_thread);
 802   }
 803 }
 804 
 805 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
 806   call_VM_base(oop_result, noreg, noreg, nullptr, entry_point, number_of_arguments, check_exceptions);
 807 }
 808 
 809 // Check the entry target is always reachable from any branch.
 810 static bool is_always_within_branch_range(Address entry) {
 811   if (AOTCodeCache::is_on_for_dump()) {
 812     return false;
 813   }
 814   const address target = entry.target();
 815 
 816   if (!CodeCache::contains(target)) {
 817     // We always use trampolines for callees outside CodeCache.
 818     assert(entry.rspec().type() == relocInfo::runtime_call_type, "non-runtime call of an external target");
 819     return false;
 820   }
 821 
 822   if (!MacroAssembler::far_branches()) {
 823     return true;
 824   }
 825 
 826   if (entry.rspec().type() == relocInfo::runtime_call_type) {
 827     // Runtime calls are calls of a non-compiled method (stubs, adapters).
 828     // Non-compiled methods stay forever in CodeCache.
 829     // We check whether the longest possible branch is within the branch range.
 830     assert(CodeCache::find_blob(target) != nullptr &&
 831           !CodeCache::find_blob(target)->is_nmethod(),
 832           "runtime call of compiled method");
 833     const address right_longest_branch_start = CodeCache::high_bound() - NativeInstruction::instruction_size;
 834     const address left_longest_branch_start = CodeCache::low_bound();
 835     const bool is_reachable = Assembler::reachable_from_branch_at(left_longest_branch_start, target) &&
 836                               Assembler::reachable_from_branch_at(right_longest_branch_start, target);
 837     return is_reachable;
 838   }
 839 
 840   return false;
 841 }
 842 
 843 // Maybe emit a call via a trampoline. If the code cache is small
 844 // trampolines won't be emitted.
 845 address MacroAssembler::trampoline_call(Address entry) {
 846   assert(entry.rspec().type() == relocInfo::runtime_call_type
 847          || entry.rspec().type() == relocInfo::opt_virtual_call_type
 848          || entry.rspec().type() == relocInfo::static_call_type
 849          || entry.rspec().type() == relocInfo::virtual_call_type, "wrong reloc type");
 850 
 851   address target = entry.target();
 852 
 853   if (!is_always_within_branch_range(entry)) {
 854     if (!in_scratch_emit_size()) {
 855       // We don't want to emit a trampoline if C2 is generating dummy
 856       // code during its branch shortening phase.
 857       if (entry.rspec().type() == relocInfo::runtime_call_type) {
 858         assert(CodeBuffer::supports_shared_stubs(), "must support shared stubs");
 859         code()->share_trampoline_for(entry.target(), offset());
 860       } else {
 861         address stub = emit_trampoline_stub(offset(), target);
 862         if (stub == nullptr) {
 863           postcond(pc() == badAddress);
 864           return nullptr; // CodeCache is full
 865         }
 866       }
 867     }
 868     target = pc();
 869   }
 870 
 871   address call_pc = pc();
 872   relocate(entry.rspec());
 873   bl(target);
 874 
 875   postcond(pc() != badAddress);
 876   return call_pc;
 877 }
 878 
 879 // Emit a trampoline stub for a call to a target which is too far away.
 880 //
 881 // code sequences:
 882 //
 883 // call-site:
 884 //   branch-and-link to <destination> or <trampoline stub>
 885 //
 886 // Related trampoline stub for this call site in the stub section:
 887 //   load the call target from the constant pool
 888 //   branch (LR still points to the call site above)
 889 
 890 address MacroAssembler::emit_trampoline_stub(int insts_call_instruction_offset,
 891                                              address dest) {
 892   // Max stub size: alignment nop, TrampolineStub.
 893   address stub = start_a_stub(max_trampoline_stub_size());
 894   if (stub == nullptr) {
 895     return nullptr;  // CodeBuffer::expand failed
 896   }
 897 
 898   // Create a trampoline stub relocation which relates this trampoline stub
 899   // with the call instruction at insts_call_instruction_offset in the
 900   // instructions code-section.
 901   align(wordSize);
 902   relocate(trampoline_stub_Relocation::spec(code()->insts()->start()
 903                                             + insts_call_instruction_offset));
 904   const int stub_start_offset = offset();
 905 
 906   // Now, create the trampoline stub's code:
 907   // - load the call
 908   // - call
 909   Label target;
 910   ldr(rscratch1, target);
 911   br(rscratch1);
 912   bind(target);
 913   assert(offset() - stub_start_offset == NativeCallTrampolineStub::data_offset,
 914          "should be");
 915   emit_int64((int64_t)dest);
 916 
 917   const address stub_start_addr = addr_at(stub_start_offset);
 918 
 919   assert(is_NativeCallTrampolineStub_at(stub_start_addr), "doesn't look like a trampoline");
 920 
 921   end_a_stub();
 922   return stub_start_addr;
 923 }
 924 
 925 int MacroAssembler::max_trampoline_stub_size() {
 926   // Max stub size: alignment nop, TrampolineStub.
 927   return NativeInstruction::instruction_size + NativeCallTrampolineStub::instruction_size;
 928 }
 929 
 930 void MacroAssembler::emit_static_call_stub() {
 931   // CompiledDirectCall::set_to_interpreted knows the
 932   // exact layout of this stub.
 933 
 934   isb();
 935   mov_metadata(rmethod, nullptr);
 936 
 937   // Jump to the entry point of the c2i stub.
 938   if (codestub_branch_needs_far_jump()) {
 939     movptr(rscratch1, 0);
 940     br(rscratch1);
 941   } else {
 942     b(pc());
 943   }
 944 }
 945 
 946 int MacroAssembler::static_call_stub_size() {
 947   // During AOT production run AOT and JIT compiled code
 948   // are used at the same time. We need this size
 949   // to be the same for both types of code.
 950   if (!codestub_branch_needs_far_jump() && !AOTCodeCache::is_on_for_use()) {
 951     // isb; movk; movz; movz; b
 952     return 5 * NativeInstruction::instruction_size;
 953   }
 954   // isb; movk; movz; movz; movk; movz; movz; br
 955   return 8 * NativeInstruction::instruction_size;
 956 }
 957 
 958 void MacroAssembler::c2bool(Register x) {
 959   // implements x == 0 ? 0 : 1
 960   // note: must only look at least-significant byte of x
 961   //       since C-style booleans are stored in one byte
 962   //       only! (was bug)
 963   tst(x, 0xff);
 964   cset(x, Assembler::NE);
 965 }
 966 
 967 address MacroAssembler::ic_call(address entry, jint method_index) {
 968   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
 969   movptr(rscratch2, (intptr_t)Universe::non_oop_word());
 970   return trampoline_call(Address(entry, rh));
 971 }
 972 
 973 int MacroAssembler::ic_check_size() {
 974   int extra_instructions = UseCompactObjectHeaders ? 1 : 0;
 975   if (target_needs_far_branch(CAST_FROM_FN_PTR(address, SharedRuntime::get_ic_miss_stub()))) {
 976     return NativeInstruction::instruction_size * (7 + extra_instructions);
 977   } else {
 978     return NativeInstruction::instruction_size * (5 + extra_instructions);
 979   }
 980 }
 981 
 982 int MacroAssembler::ic_check(int end_alignment) {
 983   Register receiver = j_rarg0;
 984   Register data = rscratch2;
 985   Register tmp1 = rscratch1;
 986   Register tmp2 = r10;
 987 
 988   // The UEP of a code blob ensures that the VEP is padded. However, the padding of the UEP is placed
 989   // before the inline cache check, so we don't have to execute any nop instructions when dispatching
 990   // through the UEP, yet we can ensure that the VEP is aligned appropriately. That's why we align
 991   // before the inline cache check here, and not after
 992   align(end_alignment, offset() + ic_check_size());
 993 
 994   int uep_offset = offset();
 995 
 996   if (UseCompactObjectHeaders) {
 997     load_narrow_klass_compact(tmp1, receiver);
 998     ldrw(tmp2, Address(data, CompiledICData::speculated_klass_offset()));
 999     cmpw(tmp1, tmp2);
1000   } else {
1001     ldrw(tmp1, Address(receiver, oopDesc::klass_offset_in_bytes()));
1002     ldrw(tmp2, Address(data, CompiledICData::speculated_klass_offset()));
1003     cmpw(tmp1, tmp2);
1004   }
1005 
1006   Label dont;
1007   br(Assembler::EQ, dont);
1008   far_jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
1009   bind(dont);
1010   assert((offset() % end_alignment) == 0, "Misaligned verified entry point");
1011 
1012   return uep_offset;
1013 }
1014 
1015 // Implementation of call_VM versions
1016 
1017 void MacroAssembler::call_VM(Register oop_result,
1018                              address entry_point,
1019                              bool check_exceptions) {
1020   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
1021 }
1022 
1023 void MacroAssembler::call_VM(Register oop_result,
1024                              address entry_point,
1025                              Register arg_1,
1026                              bool check_exceptions) {
1027   pass_arg1(this, arg_1);
1028   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
1029 }
1030 
1031 void MacroAssembler::call_VM(Register oop_result,
1032                              address entry_point,
1033                              Register arg_1,
1034                              Register arg_2,
1035                              bool check_exceptions) {
1036   assert_different_registers(arg_1, c_rarg2);
1037   pass_arg2(this, arg_2);
1038   pass_arg1(this, arg_1);
1039   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
1040 }
1041 
1042 void MacroAssembler::call_VM(Register oop_result,
1043                              address entry_point,
1044                              Register arg_1,
1045                              Register arg_2,
1046                              Register arg_3,
1047                              bool check_exceptions) {
1048   assert_different_registers(arg_1, c_rarg2, c_rarg3);
1049   assert_different_registers(arg_2, c_rarg3);
1050   pass_arg3(this, arg_3);
1051 
1052   pass_arg2(this, arg_2);
1053 
1054   pass_arg1(this, arg_1);
1055   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
1056 }
1057 
1058 void MacroAssembler::call_VM(Register oop_result,
1059                              Register last_java_sp,
1060                              address entry_point,
1061                              int number_of_arguments,
1062                              bool check_exceptions) {
1063   call_VM_base(oop_result, rthread, last_java_sp, nullptr, entry_point, number_of_arguments, check_exceptions);
1064 }
1065 
1066 void MacroAssembler::call_VM(Register oop_result,
1067                              Register last_java_sp,
1068                              address entry_point,
1069                              Register arg_1,
1070                              bool check_exceptions) {
1071   pass_arg1(this, arg_1);
1072   call_VM(oop_result, last_java_sp, entry_point, 1, 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                              bool check_exceptions) {
1081 
1082   assert_different_registers(arg_1, c_rarg2);
1083   pass_arg2(this, arg_2);
1084   pass_arg1(this, arg_1);
1085   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
1086 }
1087 
1088 void MacroAssembler::call_VM(Register oop_result,
1089                              Register last_java_sp,
1090                              address entry_point,
1091                              Register arg_1,
1092                              Register arg_2,
1093                              Register arg_3,
1094                              bool check_exceptions) {
1095   assert_different_registers(arg_1, c_rarg2, c_rarg3);
1096   assert_different_registers(arg_2, c_rarg3);
1097   pass_arg3(this, arg_3);
1098   pass_arg2(this, arg_2);
1099   pass_arg1(this, arg_1);
1100   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
1101 }
1102 
1103 
1104 void MacroAssembler::get_vm_result_oop(Register oop_result, Register java_thread) {
1105   ldr(oop_result, Address(java_thread, JavaThread::vm_result_oop_offset()));
1106   str(zr, Address(java_thread, JavaThread::vm_result_oop_offset()));
1107   verify_oop_msg(oop_result, "broken oop in call_VM_base");
1108 }
1109 
1110 void MacroAssembler::get_vm_result_metadata(Register metadata_result, Register java_thread) {
1111   ldr(metadata_result, Address(java_thread, JavaThread::vm_result_metadata_offset()));
1112   str(zr, Address(java_thread, JavaThread::vm_result_metadata_offset()));
1113 }
1114 
1115 void MacroAssembler::align(int modulus) {
1116   align(modulus, offset());
1117 }
1118 
1119 // Ensure that the code at target bytes offset from the current offset() is aligned
1120 // according to modulus.
1121 void MacroAssembler::align(int modulus, int target) {
1122   int delta = target - offset();
1123   while ((offset() + delta) % modulus != 0) nop();
1124 }
1125 
1126 void MacroAssembler::post_call_nop() {
1127   if (!Continuations::enabled()) {
1128     return;
1129   }
1130   InstructionMark im(this);
1131   relocate(post_call_nop_Relocation::spec());
1132   InlineSkippedInstructionsCounter skipCounter(this);
1133   nop();
1134   movk(zr, 0);
1135   movk(zr, 0);
1136 }
1137 
1138 // these are no-ops overridden by InterpreterMacroAssembler
1139 
1140 void MacroAssembler::check_and_handle_earlyret(Register java_thread) { }
1141 
1142 void MacroAssembler::check_and_handle_popframe(Register java_thread) { }
1143 
1144 // Look up the method for a megamorphic invokeinterface call.
1145 // The target method is determined by <intf_klass, itable_index>.
1146 // The receiver klass is in recv_klass.
1147 // On success, the result will be in method_result, and execution falls through.
1148 // On failure, execution transfers to the given label.
1149 void MacroAssembler::lookup_interface_method(Register recv_klass,
1150                                              Register intf_klass,
1151                                              RegisterOrConstant itable_index,
1152                                              Register method_result,
1153                                              Register scan_temp,
1154                                              Label& L_no_such_interface,
1155                          bool return_method) {
1156   assert_different_registers(recv_klass, intf_klass, scan_temp);
1157   assert_different_registers(method_result, intf_klass, scan_temp);
1158   assert(recv_klass != method_result || !return_method,
1159      "recv_klass can be destroyed when method isn't needed");
1160   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
1161          "caller must use same register for non-constant itable index as for method");
1162 
1163   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
1164   int vtable_base = in_bytes(Klass::vtable_start_offset());
1165   int itentry_off = in_bytes(itableMethodEntry::method_offset());
1166   int scan_step   = itableOffsetEntry::size() * wordSize;
1167   int vte_size    = vtableEntry::size_in_bytes();
1168   assert(vte_size == wordSize, "else adjust times_vte_scale");
1169 
1170   ldrw(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
1171 
1172   // Could store the aligned, prescaled offset in the klass.
1173   // lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
1174   lea(scan_temp, Address(recv_klass, scan_temp, Address::lsl(3)));
1175   add(scan_temp, scan_temp, vtable_base);
1176 
1177   if (return_method) {
1178     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
1179     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
1180     // lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
1181     lea(recv_klass, Address(recv_klass, itable_index, Address::lsl(3)));
1182     if (itentry_off)
1183       add(recv_klass, recv_klass, itentry_off);
1184   }
1185 
1186   // for (scan = klass->itable(); scan->interface() != nullptr; scan += scan_step) {
1187   //   if (scan->interface() == intf) {
1188   //     result = (klass + scan->offset() + itable_index);
1189   //   }
1190   // }
1191   Label search, found_method;
1192 
1193   ldr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset()));
1194   cmp(intf_klass, method_result);
1195   br(Assembler::EQ, found_method);
1196   bind(search);
1197   // Check that the previous entry is non-null.  A null entry means that
1198   // the receiver class doesn't implement the interface, and wasn't the
1199   // same as when the caller was compiled.
1200   cbz(method_result, L_no_such_interface);
1201   if (itableOffsetEntry::interface_offset() != 0) {
1202     add(scan_temp, scan_temp, scan_step);
1203     ldr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset()));
1204   } else {
1205     ldr(method_result, Address(pre(scan_temp, scan_step)));
1206   }
1207   cmp(intf_klass, method_result);
1208   br(Assembler::NE, search);
1209 
1210   bind(found_method);
1211 
1212   // Got a hit.
1213   if (return_method) {
1214     ldrw(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset()));
1215     ldr(method_result, Address(recv_klass, scan_temp, Address::uxtw(0)));
1216   }
1217 }
1218 
1219 // Look up the method for a megamorphic invokeinterface call in a single pass over itable:
1220 // - check recv_klass (actual object class) is a subtype of resolved_klass from CompiledICData
1221 // - find a holder_klass (class that implements the method) vtable offset and get the method from vtable by index
1222 // The target method is determined by <holder_klass, itable_index>.
1223 // The receiver klass is in recv_klass.
1224 // On success, the result will be in method_result, and execution falls through.
1225 // On failure, execution transfers to the given label.
1226 void MacroAssembler::lookup_interface_method_stub(Register recv_klass,
1227                                                   Register holder_klass,
1228                                                   Register resolved_klass,
1229                                                   Register method_result,
1230                                                   Register temp_itbl_klass,
1231                                                   Register scan_temp,
1232                                                   int itable_index,
1233                                                   Label& L_no_such_interface) {
1234   // 'method_result' is only used as output register at the very end of this method.
1235   // Until then we can reuse it as 'holder_offset'.
1236   Register holder_offset = method_result;
1237   assert_different_registers(resolved_klass, recv_klass, holder_klass, temp_itbl_klass, scan_temp, holder_offset);
1238 
1239   int vtable_start_offset = in_bytes(Klass::vtable_start_offset());
1240   int itable_offset_entry_size = itableOffsetEntry::size() * wordSize;
1241   int ioffset = in_bytes(itableOffsetEntry::interface_offset());
1242   int ooffset = in_bytes(itableOffsetEntry::offset_offset());
1243 
1244   Label L_loop_search_resolved_entry, L_resolved_found, L_holder_found;
1245 
1246   ldrw(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
1247   add(recv_klass, recv_klass, vtable_start_offset + ioffset);
1248   // itableOffsetEntry[] itable = recv_klass + Klass::vtable_start_offset() + sizeof(vtableEntry) * recv_klass->_vtable_len;
1249   // temp_itbl_klass = itable[0]._interface;
1250   int vtblEntrySize = vtableEntry::size_in_bytes();
1251   assert(vtblEntrySize == wordSize, "ldr lsl shift amount must be 3");
1252   ldr(temp_itbl_klass, Address(recv_klass, scan_temp, Address::lsl(exact_log2(vtblEntrySize))));
1253   mov(holder_offset, zr);
1254   // scan_temp = &(itable[0]._interface)
1255   lea(scan_temp, Address(recv_klass, scan_temp, Address::lsl(exact_log2(vtblEntrySize))));
1256 
1257   // Initial checks:
1258   //   - if (holder_klass != resolved_klass), go to "scan for resolved"
1259   //   - if (itable[0] == holder_klass), shortcut to "holder found"
1260   //   - if (itable[0] == 0), no such interface
1261   cmp(resolved_klass, holder_klass);
1262   br(Assembler::NE, L_loop_search_resolved_entry);
1263   cmp(holder_klass, temp_itbl_klass);
1264   br(Assembler::EQ, L_holder_found);
1265   cbz(temp_itbl_klass, L_no_such_interface);
1266 
1267   // Loop: Look for holder_klass record in itable
1268   //   do {
1269   //     temp_itbl_klass = *(scan_temp += itable_offset_entry_size);
1270   //     if (temp_itbl_klass == holder_klass) {
1271   //       goto L_holder_found; // Found!
1272   //     }
1273   //   } while (temp_itbl_klass != 0);
1274   //   goto L_no_such_interface // Not found.
1275   Label L_search_holder;
1276   bind(L_search_holder);
1277     ldr(temp_itbl_klass, Address(pre(scan_temp, itable_offset_entry_size)));
1278     cmp(holder_klass, temp_itbl_klass);
1279     br(Assembler::EQ, L_holder_found);
1280     cbnz(temp_itbl_klass, L_search_holder);
1281 
1282   b(L_no_such_interface);
1283 
1284   // Loop: Look for resolved_class record in itable
1285   //   while (true) {
1286   //     temp_itbl_klass = *(scan_temp += itable_offset_entry_size);
1287   //     if (temp_itbl_klass == 0) {
1288   //       goto L_no_such_interface;
1289   //     }
1290   //     if (temp_itbl_klass == resolved_klass) {
1291   //        goto L_resolved_found;  // Found!
1292   //     }
1293   //     if (temp_itbl_klass == holder_klass) {
1294   //        holder_offset = scan_temp;
1295   //     }
1296   //   }
1297   //
1298   Label L_loop_search_resolved;
1299   bind(L_loop_search_resolved);
1300     ldr(temp_itbl_klass, Address(pre(scan_temp, itable_offset_entry_size)));
1301   bind(L_loop_search_resolved_entry);
1302     cbz(temp_itbl_klass, L_no_such_interface);
1303     cmp(resolved_klass, temp_itbl_klass);
1304     br(Assembler::EQ, L_resolved_found);
1305     cmp(holder_klass, temp_itbl_klass);
1306     br(Assembler::NE, L_loop_search_resolved);
1307     mov(holder_offset, scan_temp);
1308     b(L_loop_search_resolved);
1309 
1310   // See if we already have a holder klass. If not, go and scan for it.
1311   bind(L_resolved_found);
1312   cbz(holder_offset, L_search_holder);
1313   mov(scan_temp, holder_offset);
1314 
1315   // Finally, scan_temp contains holder_klass vtable offset
1316   bind(L_holder_found);
1317   ldrw(method_result, Address(scan_temp, ooffset - ioffset));
1318   add(recv_klass, recv_klass, itable_index * wordSize + in_bytes(itableMethodEntry::method_offset())
1319     - vtable_start_offset - ioffset); // substract offsets to restore the original value of recv_klass
1320   ldr(method_result, Address(recv_klass, method_result, Address::uxtw(0)));
1321 }
1322 
1323 // virtual method calling
1324 void MacroAssembler::lookup_virtual_method(Register recv_klass,
1325                                            RegisterOrConstant vtable_index,
1326                                            Register method_result) {
1327   assert(vtableEntry::size() * wordSize == 8,
1328          "adjust the scaling in the code below");
1329   int64_t vtable_offset_in_bytes = in_bytes(Klass::vtable_start_offset() + vtableEntry::method_offset());
1330 
1331   if (vtable_index.is_register()) {
1332     lea(method_result, Address(recv_klass,
1333                                vtable_index.as_register(),
1334                                Address::lsl(LogBytesPerWord)));
1335     ldr(method_result, Address(method_result, vtable_offset_in_bytes));
1336   } else {
1337     vtable_offset_in_bytes += vtable_index.as_constant() * wordSize;
1338     ldr(method_result,
1339         form_address(rscratch1, recv_klass, vtable_offset_in_bytes, 0));
1340   }
1341 }
1342 
1343 void MacroAssembler::check_klass_subtype(Register sub_klass,
1344                            Register super_klass,
1345                            Register temp_reg,
1346                            Label& L_success) {
1347   Label L_failure;
1348   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, nullptr);
1349   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, nullptr);
1350   bind(L_failure);
1351 }
1352 
1353 
1354 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
1355                                                    Register super_klass,
1356                                                    Register temp_reg,
1357                                                    Label* L_success,
1358                                                    Label* L_failure,
1359                                                    Label* L_slow_path,
1360                                                    Register super_check_offset) {
1361   assert_different_registers(sub_klass, super_klass, temp_reg, super_check_offset);
1362   bool must_load_sco = ! super_check_offset->is_valid();
1363   if (must_load_sco) {
1364     assert(temp_reg != noreg, "supply either a temp or a register offset");
1365   }
1366 
1367   Label L_fallthrough;
1368   int label_nulls = 0;
1369   if (L_success == nullptr)   { L_success   = &L_fallthrough; label_nulls++; }
1370   if (L_failure == nullptr)   { L_failure   = &L_fallthrough; label_nulls++; }
1371   if (L_slow_path == nullptr) { L_slow_path = &L_fallthrough; label_nulls++; }
1372   assert(label_nulls <= 1, "at most one null in the batch");
1373 
1374   int sco_offset = in_bytes(Klass::super_check_offset_offset());
1375   Address super_check_offset_addr(super_klass, sco_offset);
1376 
1377   // Hacked jmp, which may only be used just before L_fallthrough.
1378 #define final_jmp(label)                                                \
1379   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
1380   else                            b(label)                /*omit semi*/
1381 
1382   // If the pointers are equal, we are done (e.g., String[] elements).
1383   // This self-check enables sharing of secondary supertype arrays among
1384   // non-primary types such as array-of-interface.  Otherwise, each such
1385   // type would need its own customized SSA.
1386   // We move this check to the front of the fast path because many
1387   // type checks are in fact trivially successful in this manner,
1388   // so we get a nicely predicted branch right at the start of the check.
1389   cmp(sub_klass, super_klass);
1390   br(Assembler::EQ, *L_success);
1391 
1392   // Check the supertype display:
1393   if (must_load_sco) {
1394     ldrw(temp_reg, super_check_offset_addr);
1395     super_check_offset = temp_reg;
1396   }
1397 
1398   Address super_check_addr(sub_klass, super_check_offset);
1399   ldr(rscratch1, super_check_addr);
1400   cmp(super_klass, rscratch1); // load displayed supertype
1401   br(Assembler::EQ, *L_success);
1402 
1403   // This check has worked decisively for primary supers.
1404   // Secondary supers are sought in the super_cache ('super_cache_addr').
1405   // (Secondary supers are interfaces and very deeply nested subtypes.)
1406   // This works in the same check above because of a tricky aliasing
1407   // between the super_cache and the primary super display elements.
1408   // (The 'super_check_addr' can address either, as the case requires.)
1409   // Note that the cache is updated below if it does not help us find
1410   // what we need immediately.
1411   // So if it was a primary super, we can just fail immediately.
1412   // Otherwise, it's the slow path for us (no success at this point).
1413 
1414   sub(rscratch1, super_check_offset, in_bytes(Klass::secondary_super_cache_offset()));
1415   if (L_failure == &L_fallthrough) {
1416     cbz(rscratch1, *L_slow_path);
1417   } else {
1418     cbnz(rscratch1, *L_failure);
1419     final_jmp(*L_slow_path);
1420   }
1421 
1422   bind(L_fallthrough);
1423 
1424 #undef final_jmp
1425 }
1426 
1427 // These two are taken from x86, but they look generally useful
1428 
1429 // scans count pointer sized words at [addr] for occurrence of value,
1430 // generic
1431 void MacroAssembler::repne_scan(Register addr, Register value, Register count,
1432                                 Register scratch) {
1433   Label Lloop, Lexit;
1434   cbz(count, Lexit);
1435   bind(Lloop);
1436   ldr(scratch, post(addr, wordSize));
1437   cmp(value, scratch);
1438   br(EQ, Lexit);
1439   sub(count, count, 1);
1440   cbnz(count, Lloop);
1441   bind(Lexit);
1442 }
1443 
1444 // scans count 4 byte words at [addr] for occurrence of value,
1445 // generic
1446 void MacroAssembler::repne_scanw(Register addr, Register value, Register count,
1447                                 Register scratch) {
1448   Label Lloop, Lexit;
1449   cbz(count, Lexit);
1450   bind(Lloop);
1451   ldrw(scratch, post(addr, wordSize));
1452   cmpw(value, scratch);
1453   br(EQ, Lexit);
1454   sub(count, count, 1);
1455   cbnz(count, Lloop);
1456   bind(Lexit);
1457 }
1458 
1459 void MacroAssembler::check_klass_subtype_slow_path_linear(Register sub_klass,
1460                                                           Register super_klass,
1461                                                           Register temp_reg,
1462                                                           Register temp2_reg,
1463                                                           Label* L_success,
1464                                                           Label* L_failure,
1465                                                           bool set_cond_codes) {
1466   // NB! Callers may assume that, when temp2_reg is a valid register,
1467   // this code sets it to a nonzero value.
1468 
1469   assert_different_registers(sub_klass, super_klass, temp_reg);
1470   if (temp2_reg != noreg)
1471     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg, rscratch1);
1472 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
1473 
1474   Label L_fallthrough;
1475   int label_nulls = 0;
1476   if (L_success == nullptr)   { L_success   = &L_fallthrough; label_nulls++; }
1477   if (L_failure == nullptr)   { L_failure   = &L_fallthrough; label_nulls++; }
1478   assert(label_nulls <= 1, "at most one null in the batch");
1479 
1480   // a couple of useful fields in sub_klass:
1481   int ss_offset = in_bytes(Klass::secondary_supers_offset());
1482   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
1483   Address secondary_supers_addr(sub_klass, ss_offset);
1484   Address super_cache_addr(     sub_klass, sc_offset);
1485 
1486   BLOCK_COMMENT("check_klass_subtype_slow_path");
1487 
1488   // Do a linear scan of the secondary super-klass chain.
1489   // This code is rarely used, so simplicity is a virtue here.
1490   // The repne_scan instruction uses fixed registers, which we must spill.
1491   // Don't worry too much about pre-existing connections with the input regs.
1492 
1493   assert(sub_klass != r0, "killed reg"); // killed by mov(r0, super)
1494   assert(sub_klass != r2, "killed reg"); // killed by lea(r2, &pst_counter)
1495 
1496   RegSet pushed_registers;
1497   if (!IS_A_TEMP(r2))    pushed_registers += r2;
1498   if (!IS_A_TEMP(r5))    pushed_registers += r5;
1499 
1500   if (super_klass != r0) {
1501     if (!IS_A_TEMP(r0))   pushed_registers += r0;
1502   }
1503 
1504   push(pushed_registers, sp);
1505 
1506   // Get super_klass value into r0 (even if it was in r5 or r2).
1507   if (super_klass != r0) {
1508     mov(r0, super_klass);
1509   }
1510 
1511 #ifndef PRODUCT
1512   incrementw(ExternalAddress((address)&SharedRuntime::_partial_subtype_ctr));
1513 #endif //PRODUCT
1514 
1515   // We will consult the secondary-super array.
1516   ldr(r5, secondary_supers_addr);
1517   // Load the array length.
1518   ldrw(r2, Address(r5, Array<Klass*>::length_offset_in_bytes()));
1519   // Skip to start of data.
1520   add(r5, r5, Array<Klass*>::base_offset_in_bytes());
1521 
1522   cmp(sp, zr); // Clear Z flag; SP is never zero
1523   // Scan R2 words at [R5] for an occurrence of R0.
1524   // Set NZ/Z based on last compare.
1525   repne_scan(r5, r0, r2, rscratch1);
1526 
1527   // Unspill the temp. registers:
1528   pop(pushed_registers, sp);
1529 
1530   br(Assembler::NE, *L_failure);
1531 
1532   // Success.  Cache the super we found and proceed in triumph.
1533 
1534   if (UseSecondarySupersCache) {
1535     str(super_klass, super_cache_addr);
1536   }
1537 
1538   if (L_success != &L_fallthrough) {
1539     b(*L_success);
1540   }
1541 
1542 #undef IS_A_TEMP
1543 
1544   bind(L_fallthrough);
1545 }
1546 
1547 // If Register r is invalid, remove a new register from
1548 // available_regs, and add new register to regs_to_push.
1549 Register MacroAssembler::allocate_if_noreg(Register r,
1550                                   RegSetIterator<Register> &available_regs,
1551                                   RegSet &regs_to_push) {
1552   if (!r->is_valid()) {
1553     r = *available_regs++;
1554     regs_to_push += r;
1555   }
1556   return r;
1557 }
1558 
1559 // check_klass_subtype_slow_path_table() looks for super_klass in the
1560 // hash table belonging to super_klass, branching to L_success or
1561 // L_failure as appropriate. This is essentially a shim which
1562 // allocates registers as necessary then calls
1563 // lookup_secondary_supers_table() to do the work. Any of the temp
1564 // regs may be noreg, in which case this logic will chooses some
1565 // registers push and pop them from the stack.
1566 void MacroAssembler::check_klass_subtype_slow_path_table(Register sub_klass,
1567                                                          Register super_klass,
1568                                                          Register temp_reg,
1569                                                          Register temp2_reg,
1570                                                          Register temp3_reg,
1571                                                          Register result_reg,
1572                                                          FloatRegister vtemp,
1573                                                          Label* L_success,
1574                                                          Label* L_failure,
1575                                                          bool set_cond_codes) {
1576   RegSet temps = RegSet::of(temp_reg, temp2_reg, temp3_reg);
1577 
1578   assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg, rscratch1);
1579 
1580   Label L_fallthrough;
1581   int label_nulls = 0;
1582   if (L_success == nullptr)   { L_success   = &L_fallthrough; label_nulls++; }
1583   if (L_failure == nullptr)   { L_failure   = &L_fallthrough; label_nulls++; }
1584   assert(label_nulls <= 1, "at most one null in the batch");
1585 
1586   BLOCK_COMMENT("check_klass_subtype_slow_path");
1587 
1588   RegSetIterator<Register> available_regs
1589     = (RegSet::range(r0, r15) - temps - sub_klass - super_klass).begin();
1590 
1591   RegSet pushed_regs;
1592 
1593   temp_reg = allocate_if_noreg(temp_reg, available_regs, pushed_regs);
1594   temp2_reg = allocate_if_noreg(temp2_reg, available_regs, pushed_regs);
1595   temp3_reg = allocate_if_noreg(temp3_reg, available_regs, pushed_regs);
1596   result_reg = allocate_if_noreg(result_reg, available_regs, pushed_regs);
1597 
1598   push(pushed_regs, sp);
1599 
1600   lookup_secondary_supers_table_var(sub_klass,
1601                                     super_klass,
1602                                     temp_reg, temp2_reg, temp3_reg, vtemp, result_reg,
1603                                     nullptr);
1604   cmp(result_reg, zr);
1605 
1606   // Unspill the temp. registers:
1607   pop(pushed_regs, sp);
1608 
1609   // NB! Callers may assume that, when set_cond_codes is true, this
1610   // code sets temp2_reg to a nonzero value.
1611   if (set_cond_codes) {
1612     mov(temp2_reg, 1);
1613   }
1614 
1615   br(Assembler::NE, *L_failure);
1616 
1617   if (L_success != &L_fallthrough) {
1618     b(*L_success);
1619   }
1620 
1621   bind(L_fallthrough);
1622 }
1623 
1624 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
1625                                                    Register super_klass,
1626                                                    Register temp_reg,
1627                                                    Register temp2_reg,
1628                                                    Label* L_success,
1629                                                    Label* L_failure,
1630                                                    bool set_cond_codes) {
1631   if (UseSecondarySupersTable) {
1632     check_klass_subtype_slow_path_table
1633       (sub_klass, super_klass, temp_reg, temp2_reg, /*temp3*/noreg, /*result*/noreg,
1634        /*vtemp*/fnoreg,
1635        L_success, L_failure, set_cond_codes);
1636   } else {
1637     check_klass_subtype_slow_path_linear
1638       (sub_klass, super_klass, temp_reg, temp2_reg, L_success, L_failure, set_cond_codes);
1639   }
1640 }
1641 
1642 
1643 // Ensure that the inline code and the stub are using the same registers.
1644 #define LOOKUP_SECONDARY_SUPERS_TABLE_REGISTERS                    \
1645 do {                                                               \
1646   assert(r_super_klass  == r0                                   && \
1647          r_array_base   == r1                                   && \
1648          r_array_length == r2                                   && \
1649          (r_array_index == r3        || r_array_index == noreg) && \
1650          (r_sub_klass   == r4        || r_sub_klass   == noreg) && \
1651          (r_bitmap      == rscratch2 || r_bitmap      == noreg) && \
1652          (result        == r5        || result        == noreg), "registers must match aarch64.ad"); \
1653 } while(0)
1654 
1655 bool MacroAssembler::lookup_secondary_supers_table_const(Register r_sub_klass,
1656                                                          Register r_super_klass,
1657                                                          Register temp1,
1658                                                          Register temp2,
1659                                                          Register temp3,
1660                                                          FloatRegister vtemp,
1661                                                          Register result,
1662                                                          u1 super_klass_slot,
1663                                                          bool stub_is_near) {
1664   assert_different_registers(r_sub_klass, temp1, temp2, temp3, result, rscratch1, rscratch2);
1665 
1666   Label L_fallthrough;
1667 
1668   BLOCK_COMMENT("lookup_secondary_supers_table {");
1669 
1670   const Register
1671     r_array_base   = temp1, // r1
1672     r_array_length = temp2, // r2
1673     r_array_index  = temp3, // r3
1674     r_bitmap       = rscratch2;
1675 
1676   LOOKUP_SECONDARY_SUPERS_TABLE_REGISTERS;
1677 
1678   u1 bit = super_klass_slot;
1679 
1680   // Make sure that result is nonzero if the TBZ below misses.
1681   mov(result, 1);
1682 
1683   // We're going to need the bitmap in a vector reg and in a core reg,
1684   // so load both now.
1685   ldr(r_bitmap, Address(r_sub_klass, Klass::secondary_supers_bitmap_offset()));
1686   if (bit != 0) {
1687     ldrd(vtemp, Address(r_sub_klass, Klass::secondary_supers_bitmap_offset()));
1688   }
1689   // First check the bitmap to see if super_klass might be present. If
1690   // the bit is zero, we are certain that super_klass is not one of
1691   // the secondary supers.
1692   tbz(r_bitmap, bit, L_fallthrough);
1693 
1694   // Get the first array index that can contain super_klass into r_array_index.
1695   if (bit != 0) {
1696     shld(vtemp, vtemp, Klass::SECONDARY_SUPERS_TABLE_MASK - bit);
1697     cnt(vtemp, T8B, vtemp);
1698     addv(vtemp, T8B, vtemp);
1699     fmovd(r_array_index, vtemp);
1700   } else {
1701     mov(r_array_index, (u1)1);
1702   }
1703   // NB! r_array_index is off by 1. It is compensated by keeping r_array_base off by 1 word.
1704 
1705   // We will consult the secondary-super array.
1706   ldr(r_array_base, Address(r_sub_klass, in_bytes(Klass::secondary_supers_offset())));
1707 
1708   // The value i in r_array_index is >= 1, so even though r_array_base
1709   // points to the length, we don't need to adjust it to point to the
1710   // data.
1711   assert(Array<Klass*>::base_offset_in_bytes() == wordSize, "Adjust this code");
1712   assert(Array<Klass*>::length_offset_in_bytes() == 0, "Adjust this code");
1713 
1714   ldr(result, Address(r_array_base, r_array_index, Address::lsl(LogBytesPerWord)));
1715   eor(result, result, r_super_klass);
1716   cbz(result, L_fallthrough); // Found a match
1717 
1718   // Is there another entry to check? Consult the bitmap.
1719   tbz(r_bitmap, (bit + 1) & Klass::SECONDARY_SUPERS_TABLE_MASK, L_fallthrough);
1720 
1721   // Linear probe.
1722   if (bit != 0) {
1723     ror(r_bitmap, r_bitmap, bit);
1724   }
1725 
1726   // The slot we just inspected is at secondary_supers[r_array_index - 1].
1727   // The next slot to be inspected, by the stub we're about to call,
1728   // is secondary_supers[r_array_index]. Bits 0 and 1 in the bitmap
1729   // have been checked.
1730   Address stub = RuntimeAddress(StubRoutines::lookup_secondary_supers_table_slow_path_stub());
1731   if (stub_is_near) {
1732     bl(stub);
1733   } else {
1734     address call = trampoline_call(stub);
1735     if (call == nullptr) {
1736       return false; // trampoline allocation failed
1737     }
1738   }
1739 
1740   BLOCK_COMMENT("} lookup_secondary_supers_table");
1741 
1742   bind(L_fallthrough);
1743 
1744   if (VerifySecondarySupers) {
1745     verify_secondary_supers_table(r_sub_klass, r_super_klass, // r4, r0
1746                                   temp1, temp2, result);      // r1, r2, r5
1747   }
1748   return true;
1749 }
1750 
1751 // At runtime, return 0 in result if r_super_klass is a superclass of
1752 // r_sub_klass, otherwise return nonzero. Use this version of
1753 // lookup_secondary_supers_table() if you don't know ahead of time
1754 // which superclass will be searched for. Used by interpreter and
1755 // runtime stubs. It is larger and has somewhat greater latency than
1756 // the version above, which takes a constant super_klass_slot.
1757 void MacroAssembler::lookup_secondary_supers_table_var(Register r_sub_klass,
1758                                                        Register r_super_klass,
1759                                                        Register temp1,
1760                                                        Register temp2,
1761                                                        Register temp3,
1762                                                        FloatRegister vtemp,
1763                                                        Register result,
1764                                                        Label *L_success) {
1765   assert_different_registers(r_sub_klass, temp1, temp2, temp3, result, rscratch1, rscratch2);
1766 
1767   Label L_fallthrough;
1768 
1769   BLOCK_COMMENT("lookup_secondary_supers_table {");
1770 
1771   const Register
1772     r_array_index = temp3,
1773     slot          = rscratch1,
1774     r_bitmap      = rscratch2;
1775 
1776   ldrb(slot, Address(r_super_klass, Klass::hash_slot_offset()));
1777 
1778   // Make sure that result is nonzero if the test below misses.
1779   mov(result, 1);
1780 
1781   ldr(r_bitmap, Address(r_sub_klass, Klass::secondary_supers_bitmap_offset()));
1782 
1783   // First check the bitmap to see if super_klass might be present. If
1784   // the bit is zero, we are certain that super_klass is not one of
1785   // the secondary supers.
1786 
1787   // This next instruction is equivalent to:
1788   // mov(tmp_reg, (u1)(Klass::SECONDARY_SUPERS_TABLE_SIZE - 1));
1789   // sub(temp2, tmp_reg, slot);
1790   eor(temp2, slot, (u1)(Klass::SECONDARY_SUPERS_TABLE_SIZE - 1));
1791   lslv(temp2, r_bitmap, temp2);
1792   tbz(temp2, Klass::SECONDARY_SUPERS_TABLE_SIZE - 1, L_fallthrough);
1793 
1794   bool must_save_v0 = (vtemp == fnoreg);
1795   if (must_save_v0) {
1796     // temp1 and result are free, so use them to preserve vtemp
1797     vtemp = v0;
1798     mov(temp1,  vtemp, D, 0);
1799     mov(result, vtemp, D, 1);
1800   }
1801 
1802   // Get the first array index that can contain super_klass into r_array_index.
1803   mov(vtemp, D, 0, temp2);
1804   cnt(vtemp, T8B, vtemp);
1805   addv(vtemp, T8B, vtemp);
1806   mov(r_array_index, vtemp, D, 0);
1807 
1808   if (must_save_v0) {
1809     mov(vtemp, D, 0, temp1 );
1810     mov(vtemp, D, 1, result);
1811   }
1812 
1813   // NB! r_array_index is off by 1. It is compensated by keeping r_array_base off by 1 word.
1814 
1815   const Register
1816     r_array_base   = temp1,
1817     r_array_length = temp2;
1818 
1819   // The value i in r_array_index is >= 1, so even though r_array_base
1820   // points to the length, we don't need to adjust it to point to the
1821   // data.
1822   assert(Array<Klass*>::base_offset_in_bytes() == wordSize, "Adjust this code");
1823   assert(Array<Klass*>::length_offset_in_bytes() == 0, "Adjust this code");
1824 
1825   // We will consult the secondary-super array.
1826   ldr(r_array_base, Address(r_sub_klass, in_bytes(Klass::secondary_supers_offset())));
1827 
1828   ldr(result, Address(r_array_base, r_array_index, Address::lsl(LogBytesPerWord)));
1829   eor(result, result, r_super_klass);
1830   cbz(result, L_success ? *L_success : L_fallthrough); // Found a match
1831 
1832   // Is there another entry to check? Consult the bitmap.
1833   rorv(r_bitmap, r_bitmap, slot);
1834   // rol(r_bitmap, r_bitmap, 1);
1835   tbz(r_bitmap, 1, L_fallthrough);
1836 
1837   // The slot we just inspected is at secondary_supers[r_array_index - 1].
1838   // The next slot to be inspected, by the logic we're about to call,
1839   // is secondary_supers[r_array_index]. Bits 0 and 1 in the bitmap
1840   // have been checked.
1841   lookup_secondary_supers_table_slow_path(r_super_klass, r_array_base, r_array_index,
1842                                           r_bitmap, r_array_length, result, /*is_stub*/false);
1843 
1844   BLOCK_COMMENT("} lookup_secondary_supers_table");
1845 
1846   bind(L_fallthrough);
1847 
1848   if (VerifySecondarySupers) {
1849     verify_secondary_supers_table(r_sub_klass, r_super_klass, // r4, r0
1850                                   temp1, temp2, result);      // r1, r2, r5
1851   }
1852 
1853   if (L_success) {
1854     cbz(result, *L_success);
1855   }
1856 }
1857 
1858 // Called by code generated by check_klass_subtype_slow_path
1859 // above. This is called when there is a collision in the hashed
1860 // lookup in the secondary supers array.
1861 void MacroAssembler::lookup_secondary_supers_table_slow_path(Register r_super_klass,
1862                                                              Register r_array_base,
1863                                                              Register r_array_index,
1864                                                              Register r_bitmap,
1865                                                              Register temp1,
1866                                                              Register result,
1867                                                              bool is_stub) {
1868   assert_different_registers(r_super_klass, r_array_base, r_array_index, r_bitmap, temp1, result, rscratch1);
1869 
1870   const Register
1871     r_array_length = temp1,
1872     r_sub_klass    = noreg; // unused
1873 
1874   if (is_stub) {
1875     LOOKUP_SECONDARY_SUPERS_TABLE_REGISTERS;
1876   }
1877 
1878   Label L_fallthrough, L_huge;
1879 
1880   // Load the array length.
1881   ldrw(r_array_length, Address(r_array_base, Array<Klass*>::length_offset_in_bytes()));
1882   // And adjust the array base to point to the data.
1883   // NB! Effectively increments current slot index by 1.
1884   assert(Array<Klass*>::base_offset_in_bytes() == wordSize, "");
1885   add(r_array_base, r_array_base, Array<Klass*>::base_offset_in_bytes());
1886 
1887   // The bitmap is full to bursting.
1888   // Implicit invariant: BITMAP_FULL implies (length > 0)
1889   assert(Klass::SECONDARY_SUPERS_BITMAP_FULL == ~uintx(0), "");
1890   cmpw(r_array_length, (u1)(Klass::SECONDARY_SUPERS_TABLE_SIZE - 2));
1891   br(GT, L_huge);
1892 
1893   // NB! Our caller has checked bits 0 and 1 in the bitmap. The
1894   // current slot (at secondary_supers[r_array_index]) has not yet
1895   // been inspected, and r_array_index may be out of bounds if we
1896   // wrapped around the end of the array.
1897 
1898   { // This is conventional linear probing, but instead of terminating
1899     // when a null entry is found in the table, we maintain a bitmap
1900     // in which a 0 indicates missing entries.
1901     // As long as the bitmap is not completely full,
1902     // array_length == popcount(bitmap). The array_length check above
1903     // guarantees there are 0s in the bitmap, so the loop eventually
1904     // terminates.
1905     Label L_loop;
1906     bind(L_loop);
1907 
1908     // Check for wraparound.
1909     cmp(r_array_index, r_array_length);
1910     csel(r_array_index, zr, r_array_index, GE);
1911 
1912     ldr(rscratch1, Address(r_array_base, r_array_index, Address::lsl(LogBytesPerWord)));
1913     eor(result, rscratch1, r_super_klass);
1914     cbz(result, L_fallthrough);
1915 
1916     tbz(r_bitmap, 2, L_fallthrough); // look-ahead check (Bit 2); result is non-zero
1917 
1918     ror(r_bitmap, r_bitmap, 1);
1919     add(r_array_index, r_array_index, 1);
1920     b(L_loop);
1921   }
1922 
1923   { // Degenerate case: more than 64 secondary supers.
1924     // FIXME: We could do something smarter here, maybe a vectorized
1925     // comparison or a binary search, but is that worth any added
1926     // complexity?
1927     bind(L_huge);
1928     cmp(sp, zr); // Clear Z flag; SP is never zero
1929     repne_scan(r_array_base, r_super_klass, r_array_length, rscratch1);
1930     cset(result, NE); // result == 0 iff we got a match.
1931   }
1932 
1933   bind(L_fallthrough);
1934 }
1935 
1936 // Make sure that the hashed lookup and a linear scan agree.
1937 void MacroAssembler::verify_secondary_supers_table(Register r_sub_klass,
1938                                                    Register r_super_klass,
1939                                                    Register temp1,
1940                                                    Register temp2,
1941                                                    Register result) {
1942   assert_different_registers(r_sub_klass, r_super_klass, temp1, temp2, result, rscratch1);
1943 
1944   const Register
1945     r_array_base   = temp1,
1946     r_array_length = temp2;
1947 
1948   BLOCK_COMMENT("verify_secondary_supers_table {");
1949 
1950   // We will consult the secondary-super array.
1951   ldr(r_array_base, Address(r_sub_klass, in_bytes(Klass::secondary_supers_offset())));
1952 
1953   // Load the array length.
1954   ldrw(r_array_length, Address(r_array_base, Array<Klass*>::length_offset_in_bytes()));
1955   // And adjust the array base to point to the data.
1956   add(r_array_base, r_array_base, Array<Klass*>::base_offset_in_bytes());
1957 
1958   cmp(sp, zr); // Clear Z flag; SP is never zero
1959   // Scan R2 words at [R5] for an occurrence of R0.
1960   // Set NZ/Z based on last compare.
1961   repne_scan(/*addr*/r_array_base, /*value*/r_super_klass, /*count*/r_array_length, rscratch2);
1962   // rscratch1 == 0 iff we got a match.
1963   cset(rscratch1, NE);
1964 
1965   Label passed;
1966   cmp(result, zr);
1967   cset(result, NE); // normalize result to 0/1 for comparison
1968 
1969   cmp(rscratch1, result);
1970   br(EQ, passed);
1971   {
1972     mov(r0, r_super_klass);         // r0 <- r0
1973     mov(r1, r_sub_klass);           // r1 <- r4
1974     mov(r2, /*expected*/rscratch1); // r2 <- r8
1975     mov(r3, result);                // r3 <- r5
1976     mov(r4, (address)("mismatch")); // r4 <- const
1977     rt_call(CAST_FROM_FN_PTR(address, Klass::on_secondary_supers_verification_failure), rscratch2);
1978     should_not_reach_here();
1979   }
1980   bind(passed);
1981 
1982   BLOCK_COMMENT("} verify_secondary_supers_table");
1983 }
1984 
1985 void MacroAssembler::clinit_barrier(Register klass, Register scratch, Label* L_fast_path, Label* L_slow_path) {
1986   assert(L_fast_path != nullptr || L_slow_path != nullptr, "at least one is required");
1987   assert_different_registers(klass, rthread, scratch);
1988 
1989   Label L_fallthrough, L_tmp;
1990   if (L_fast_path == nullptr) {
1991     L_fast_path = &L_fallthrough;
1992   } else if (L_slow_path == nullptr) {
1993     L_slow_path = &L_fallthrough;
1994   }
1995   // Fast path check: class is fully initialized
1996   lea(scratch, Address(klass, InstanceKlass::init_state_offset()));
1997   ldarb(scratch, scratch);
1998   cmp(scratch, InstanceKlass::fully_initialized);
1999   br(Assembler::EQ, *L_fast_path);
2000 
2001   // Fast path check: current thread is initializer thread
2002   ldr(scratch, Address(klass, InstanceKlass::init_thread_offset()));
2003   cmp(rthread, scratch);
2004 
2005   if (L_slow_path == &L_fallthrough) {
2006     br(Assembler::EQ, *L_fast_path);
2007     bind(*L_slow_path);
2008   } else if (L_fast_path == &L_fallthrough) {
2009     br(Assembler::NE, *L_slow_path);
2010     bind(*L_fast_path);
2011   } else {
2012     Unimplemented();
2013   }
2014 }
2015 
2016 void MacroAssembler::_verify_oop(Register reg, const char* s, const char* file, int line) {
2017   if (!VerifyOops || VerifyAdapterSharing) {
2018     // Below address of the code string confuses VerifyAdapterSharing
2019     // because it may differ between otherwise equivalent adapters.
2020     return;
2021   }
2022 
2023   // Pass register number to verify_oop_subroutine
2024   const char* b = nullptr;
2025   {
2026     ResourceMark rm;
2027     stringStream ss;
2028     ss.print("verify_oop: %s: %s (%s:%d)", reg->name(), s, file, line);
2029     b = code_string(ss.as_string());
2030   }
2031   BLOCK_COMMENT("verify_oop {");
2032 
2033   strip_return_address(); // This might happen within a stack frame.
2034   protect_return_address();
2035   stp(r0, rscratch1, Address(pre(sp, -2 * wordSize)));
2036   stp(rscratch2, lr, Address(pre(sp, -2 * wordSize)));
2037 
2038   mov(r0, reg);
2039   movptr(rscratch1, (uintptr_t)(address)b);
2040 
2041   // call indirectly to solve generation ordering problem
2042   lea(rscratch2, RuntimeAddress(StubRoutines::verify_oop_subroutine_entry_address()));
2043   ldr(rscratch2, Address(rscratch2));
2044   blr(rscratch2);
2045 
2046   ldp(rscratch2, lr, Address(post(sp, 2 * wordSize)));
2047   ldp(r0, rscratch1, Address(post(sp, 2 * wordSize)));
2048   authenticate_return_address();
2049 
2050   BLOCK_COMMENT("} verify_oop");
2051 }
2052 
2053 void MacroAssembler::_verify_oop_addr(Address addr, const char* s, const char* file, int line) {
2054   if (!VerifyOops || VerifyAdapterSharing) {
2055     // Below address of the code string confuses VerifyAdapterSharing
2056     // because it may differ between otherwise equivalent adapters.
2057     return;
2058   }
2059 
2060   const char* b = nullptr;
2061   {
2062     ResourceMark rm;
2063     stringStream ss;
2064     ss.print("verify_oop_addr: %s (%s:%d)", s, file, line);
2065     b = code_string(ss.as_string());
2066   }
2067   BLOCK_COMMENT("verify_oop_addr {");
2068 
2069   strip_return_address(); // This might happen within a stack frame.
2070   protect_return_address();
2071   stp(r0, rscratch1, Address(pre(sp, -2 * wordSize)));
2072   stp(rscratch2, lr, Address(pre(sp, -2 * wordSize)));
2073 
2074   // addr may contain sp so we will have to adjust it based on the
2075   // pushes that we just did.
2076   if (addr.uses(sp)) {
2077     lea(r0, addr);
2078     ldr(r0, Address(r0, 4 * wordSize));
2079   } else {
2080     ldr(r0, addr);
2081   }
2082   movptr(rscratch1, (uintptr_t)(address)b);
2083 
2084   // call indirectly to solve generation ordering problem
2085   lea(rscratch2, RuntimeAddress(StubRoutines::verify_oop_subroutine_entry_address()));
2086   ldr(rscratch2, Address(rscratch2));
2087   blr(rscratch2);
2088 
2089   ldp(rscratch2, lr, Address(post(sp, 2 * wordSize)));
2090   ldp(r0, rscratch1, Address(post(sp, 2 * wordSize)));
2091   authenticate_return_address();
2092 
2093   BLOCK_COMMENT("} verify_oop_addr");
2094 }
2095 
2096 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
2097                                          int extra_slot_offset) {
2098   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
2099   int stackElementSize = Interpreter::stackElementSize;
2100   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
2101 #ifdef ASSERT
2102   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
2103   assert(offset1 - offset == stackElementSize, "correct arithmetic");
2104 #endif
2105   if (arg_slot.is_constant()) {
2106     return Address(esp, arg_slot.as_constant() * stackElementSize
2107                    + offset);
2108   } else {
2109     add(rscratch1, esp, arg_slot.as_register(),
2110         ext::uxtx, exact_log2(stackElementSize));
2111     return Address(rscratch1, offset);
2112   }
2113 }
2114 
2115 // Handle the receiver type profile update given the "recv" klass.
2116 //
2117 // Normally updates the ReceiverData (RD) that starts at "mdp" + "mdp_offset".
2118 // If there are no matching or claimable receiver entries in RD, updates
2119 // the polymorphic counter.
2120 //
2121 // This code expected to run by either the interpreter or JIT-ed code, without
2122 // extra synchronization. For safety, receiver cells are claimed atomically, which
2123 // avoids grossly misrepresenting the profiles under concurrent updates. For speed,
2124 // counter updates are not atomic.
2125 //
2126 void MacroAssembler::profile_receiver_type(Register recv, Register mdp, int mdp_offset) {
2127   assert_different_registers(recv, mdp, rscratch1, rscratch2);
2128 
2129   int base_receiver_offset   = in_bytes(ReceiverTypeData::receiver_offset(0));
2130   int end_receiver_offset    = in_bytes(ReceiverTypeData::receiver_offset(ReceiverTypeData::row_limit()));
2131   int poly_count_offset      = in_bytes(CounterData::count_offset());
2132   int receiver_step          = in_bytes(ReceiverTypeData::receiver_offset(1)) - base_receiver_offset;
2133   int receiver_to_count_step = in_bytes(ReceiverTypeData::receiver_count_offset(0)) - base_receiver_offset;
2134 
2135   // Adjust for MDP offsets.
2136   base_receiver_offset += mdp_offset;
2137   end_receiver_offset  += mdp_offset;
2138   poly_count_offset    += mdp_offset;
2139 
2140 #ifdef ASSERT
2141   // We are about to walk the MDO slots without asking for offsets.
2142   // Check that our math hits all the right spots.
2143   for (uint c = 0; c < ReceiverTypeData::row_limit(); c++) {
2144     int real_recv_offset  = mdp_offset + in_bytes(ReceiverTypeData::receiver_offset(c));
2145     int real_count_offset = mdp_offset + in_bytes(ReceiverTypeData::receiver_count_offset(c));
2146     int offset = base_receiver_offset + receiver_step*c;
2147     int count_offset = offset + receiver_to_count_step;
2148     assert(offset == real_recv_offset, "receiver slot math");
2149     assert(count_offset == real_count_offset, "receiver count math");
2150   }
2151   int real_poly_count_offset = mdp_offset + in_bytes(CounterData::count_offset());
2152   assert(poly_count_offset == real_poly_count_offset, "poly counter math");
2153 #endif
2154 
2155   // Corner case: no profile table. Increment poly counter and exit.
2156   if (ReceiverTypeData::row_limit() == 0) {
2157     increment(Address(mdp, poly_count_offset), DataLayout::counter_increment);
2158     return;
2159   }
2160 
2161   Register offset = rscratch2;
2162 
2163   Label L_loop_search_receiver, L_loop_search_empty;
2164   Label L_restart, L_found_recv, L_found_empty, L_count_update;
2165 
2166   // The code here recognizes three major cases:
2167   //   A. Fastest: receiver found in the table
2168   //   B. Fast: no receiver in the table, and the table is full
2169   //   C. Slow: no receiver in the table, free slots in the table
2170   //
2171   // The case A performance is most important, as perfectly-behaved code would end up
2172   // there, especially with larger TypeProfileWidth. The case B performance is
2173   // important as well, this is where bulk of code would land for normally megamorphic
2174   // cases. The case C performance is not essential, its job is to deal with installation
2175   // races, we optimize for code density instead. Case C needs to make sure that receiver
2176   // rows are only claimed once. This makes sure we never overwrite a row for another
2177   // receiver and never duplicate the receivers in the list, making profile type-accurate.
2178   //
2179   // It is very tempting to handle these cases in a single loop, and claim the first slot
2180   // without checking the rest of the table. But, profiling code should tolerate free slots
2181   // in the table, as class unloading can clear them. After such cleanup, the receiver
2182   // we need might be _after_ the free slot. Therefore, we need to let at least full scan
2183   // to complete, before trying to install new slots. Splitting the code in several tight
2184   // loops also helpfully optimizes for cases A and B.
2185   //
2186   // This code is effectively:
2187   //
2188   // restart:
2189   //   // Fastest: receiver is already installed
2190   //   for (i = 0; i < receiver_count(); i++) {
2191   //     if (receiver(i) == recv) goto found_recv(i);
2192   //   }
2193   //
2194   //   // Fast: no receiver, but profile is not full
2195   //   for (i = 0; i < receiver_count(); i++) {
2196   //     if (receiver(i) == null) goto found_null(i);
2197   //   }
2198   //
2199   //   // Slow: profile is full, polymorphic case
2200   //   count++;
2201   //   return
2202   //
2203   //   // Slow: try to install receiver
2204   // found_null(i):
2205   //   CAS(&receiver(i), null, recv);
2206   //   goto restart
2207   //
2208   // found_recv(i):
2209   //   *receiver_count(i)++
2210   //
2211 
2212   bind(L_restart);
2213 
2214   // Fastest: receiver is already installed
2215   mov(offset, base_receiver_offset);
2216   bind(L_loop_search_receiver);
2217     ldr(rscratch1, Address(mdp, offset));
2218     cmp(rscratch1, recv);
2219     br(Assembler::EQ, L_found_recv);
2220   add(offset, offset, receiver_step);
2221   sub(rscratch1, offset, end_receiver_offset);
2222   cbnz(rscratch1, L_loop_search_receiver);
2223 
2224   // Fast: no receiver, but profile is not full
2225   mov(offset, base_receiver_offset);
2226   bind(L_loop_search_empty);
2227     ldr(rscratch1, Address(mdp, offset));
2228     cbz(rscratch1, L_found_empty);
2229   add(offset, offset, receiver_step);
2230   sub(rscratch1, offset, end_receiver_offset);
2231   cbnz(rscratch1, L_loop_search_empty);
2232 
2233   // Slow: Receiver is not found and table is full.
2234   // Increment polymorphic counter instead of receiver slot.
2235   mov(offset, poly_count_offset);
2236   b(L_count_update);
2237 
2238   // Slowest: try to install receiver
2239   bind(L_found_empty);
2240 
2241   // Atomically swing receiver slot: null -> recv.
2242   //
2243   // The update uses CAS, which clobbers rscratch1. Therefore, rscratch2
2244   // is used to hold the destination address. This is safe because the
2245   // offset is no longer needed after the address is computed.
2246 
2247   lea(rscratch2, Address(mdp, offset));
2248   cmpxchg_weak(/*addr*/ rscratch2, /*expected*/ zr, /*new*/ recv, Assembler::xword, memory_order_relaxed);
2249 
2250   // CAS success means the slot now has the receiver we want. CAS failure means
2251   // something had claimed the slot concurrently: it can be the same receiver we want,
2252   // or something else. Since this is a slow path, we can optimize for code density,
2253   // and just restart the search from the beginning.
2254   b(L_restart);
2255 
2256   // Found a receiver, convert its slot offset to corresponding count offset.
2257   bind(L_found_recv);
2258   add(offset, offset, receiver_to_count_step);
2259 
2260   // Finally, update the counter
2261   bind(L_count_update);
2262   increment(Address(mdp, offset), DataLayout::counter_increment);
2263 }
2264 
2265 
2266 void MacroAssembler::call_VM_leaf_base(address entry_point,
2267                                        int number_of_arguments,
2268                                        Label *retaddr) {
2269   Label E, L;
2270 
2271   stp(rscratch1, rmethod, Address(pre(sp, -2 * wordSize)));
2272 
2273   mov(rscratch1, RuntimeAddress(entry_point));
2274   blr(rscratch1);
2275   if (retaddr)
2276     bind(*retaddr);
2277 
2278   ldp(rscratch1, rmethod, Address(post(sp, 2 * wordSize)));
2279 }
2280 
2281 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2282   call_VM_leaf_base(entry_point, number_of_arguments);
2283 }
2284 
2285 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2286   pass_arg0(this, arg_0);
2287   call_VM_leaf_base(entry_point, 1);
2288 }
2289 
2290 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2291   assert_different_registers(arg_1, c_rarg0);
2292   pass_arg0(this, arg_0);
2293   pass_arg1(this, arg_1);
2294   call_VM_leaf_base(entry_point, 2);
2295 }
2296 
2297 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0,
2298                                   Register arg_1, Register arg_2) {
2299   assert_different_registers(arg_1, c_rarg0);
2300   assert_different_registers(arg_2, c_rarg0, c_rarg1);
2301   pass_arg0(this, arg_0);
2302   pass_arg1(this, arg_1);
2303   pass_arg2(this, arg_2);
2304   call_VM_leaf_base(entry_point, 3);
2305 }
2306 
2307 void MacroAssembler::super_call_VM_leaf(address entry_point) {
2308   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2309 }
2310 
2311 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2312   pass_arg0(this, arg_0);
2313   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2314 }
2315 
2316 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2317 
2318   assert_different_registers(arg_0, c_rarg1);
2319   pass_arg1(this, arg_1);
2320   pass_arg0(this, arg_0);
2321   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2322 }
2323 
2324 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2325   assert_different_registers(arg_0, c_rarg1, c_rarg2);
2326   assert_different_registers(arg_1, c_rarg2);
2327   pass_arg2(this, arg_2);
2328   pass_arg1(this, arg_1);
2329   pass_arg0(this, arg_0);
2330   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2331 }
2332 
2333 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2334   assert_different_registers(arg_0, c_rarg1, c_rarg2, c_rarg3);
2335   assert_different_registers(arg_1, c_rarg2, c_rarg3);
2336   assert_different_registers(arg_2, c_rarg3);
2337   pass_arg3(this, arg_3);
2338   pass_arg2(this, arg_2);
2339   pass_arg1(this, arg_1);
2340   pass_arg0(this, arg_0);
2341   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2342 }
2343 
2344 void MacroAssembler::null_check(Register reg, int offset) {
2345   if (needs_explicit_null_check(offset)) {
2346     // provoke OS null exception if reg is null by
2347     // accessing M[reg] w/o changing any registers
2348     // NOTE: this is plenty to provoke a segv
2349     ldr(zr, Address(reg));
2350   } else {
2351     // nothing to do, (later) access of M[reg + offset]
2352     // will provoke OS null exception if reg is null
2353   }
2354 }
2355 
2356 void MacroAssembler::test_markword_is_inline_type(Register markword, Label& is_inline_type) {
2357   assert_different_registers(markword, rscratch2);
2358   mov(rscratch2, markWord::inline_type_pattern_mask);
2359   andr(markword, markword, rscratch2);
2360   mov(rscratch2, markWord::inline_type_pattern);
2361   cmp(markword, rscratch2);
2362   br(Assembler::EQ, is_inline_type);
2363 }
2364 
2365 void MacroAssembler::test_oop_is_not_inline_type(Register object, Register tmp, Label& not_inline_type, bool can_be_null) {
2366   assert_different_registers(tmp, rscratch1);
2367   if (can_be_null) {
2368     cbz(object, not_inline_type);
2369   }
2370   const int is_inline_type_mask = markWord::inline_type_pattern;
2371   ldr(tmp, Address(object, oopDesc::mark_offset_in_bytes()));
2372   mov(rscratch1, is_inline_type_mask);
2373   andr(tmp, tmp, rscratch1);
2374   cmp(tmp, rscratch1);
2375   br(Assembler::NE, not_inline_type);
2376 }
2377 
2378 void MacroAssembler::test_field_is_null_free_inline_type(Register flags, Register temp_reg, Label& is_null_free_inline_type) {
2379   assert(temp_reg == noreg, "not needed"); // keep signature uniform with x86
2380   tbnz(flags, ResolvedFieldEntry::is_null_free_inline_type_shift, is_null_free_inline_type);
2381 }
2382 
2383 void MacroAssembler::test_field_is_not_null_free_inline_type(Register flags, Register temp_reg, Label& not_null_free_inline_type) {
2384   assert(temp_reg == noreg, "not needed"); // keep signature uniform with x86
2385   tbz(flags, ResolvedFieldEntry::is_null_free_inline_type_shift, not_null_free_inline_type);
2386 }
2387 
2388 void MacroAssembler::test_field_is_flat(Register flags, Register temp_reg, Label& is_flat) {
2389   assert(temp_reg == noreg, "not needed"); // keep signature uniform with x86
2390   tbnz(flags, ResolvedFieldEntry::is_flat_shift, is_flat);
2391 }
2392 
2393 void MacroAssembler::test_oop_prototype_bit(Register oop, Register temp_reg, int32_t test_bit, bool jmp_set, Label& jmp_label) {
2394   // load mark word
2395   ldr(temp_reg, Address(oop, oopDesc::mark_offset_in_bytes()));
2396   if (!UseObjectMonitorTable) {
2397     Label test_mark_word;
2398     // check displaced
2399     tst(temp_reg, markWord::unlocked_value);
2400     br(Assembler::NE, test_mark_word);
2401     // slow path use klass prototype
2402     load_prototype_header(temp_reg, oop);
2403 
2404     bind(test_mark_word);
2405   }
2406   andr(temp_reg, temp_reg, test_bit);
2407   if (jmp_set) {
2408     cbnz(temp_reg, jmp_label);
2409   } else {
2410     cbz(temp_reg, jmp_label);
2411   }
2412 }
2413 
2414 void MacroAssembler::test_flat_array_oop(Register oop, Register temp_reg, Label& is_flat_array) {
2415   test_oop_prototype_bit(oop, temp_reg, markWord::flat_array_bit_in_place, true, is_flat_array);
2416 }
2417 
2418 void MacroAssembler::test_non_flat_array_oop(Register oop, Register temp_reg,
2419                                                   Label&is_non_flat_array) {
2420   test_oop_prototype_bit(oop, temp_reg, markWord::flat_array_bit_in_place, false, is_non_flat_array);
2421 }
2422 
2423 void MacroAssembler::test_null_free_array_oop(Register oop, Register temp_reg, Label& is_null_free_array) {
2424   test_oop_prototype_bit(oop, temp_reg, markWord::null_free_array_bit_in_place, true, is_null_free_array);
2425 }
2426 
2427 void MacroAssembler::test_non_null_free_array_oop(Register oop, Register temp_reg, Label&is_non_null_free_array) {
2428   test_oop_prototype_bit(oop, temp_reg, markWord::null_free_array_bit_in_place, false, is_non_null_free_array);
2429 }
2430 
2431 void MacroAssembler::test_flat_array_layout(Register lh, Label& is_flat_array) {
2432   tst(lh, Klass::_lh_array_tag_flat_value_bit_inplace);
2433   br(Assembler::NE, is_flat_array);
2434 }
2435 
2436 // MacroAssembler protected routines needed to implement
2437 // public methods
2438 
2439 void MacroAssembler::mov(Register r, Address dest) {
2440   code_section()->relocate(pc(), dest.rspec());
2441   uint64_t imm64 = (uint64_t)dest.target();
2442   movptr(r, imm64);
2443 }
2444 
2445 // Move a constant pointer into r.  In AArch64 mode the virtual
2446 // address space is 48 bits in size, so we only need three
2447 // instructions to create a patchable instruction sequence that can
2448 // reach anywhere.
2449 void MacroAssembler::movptr(Register r, uintptr_t imm64) {
2450 #ifndef PRODUCT
2451   {
2452     char buffer[64];
2453     os::snprintf_checked(buffer, sizeof(buffer), "0x%" PRIX64, (uint64_t)imm64);
2454     block_comment(buffer);
2455   }
2456 #endif
2457   assert(imm64 < (1ull << 48), "48-bit overflow in address constant");
2458   movz(r, imm64 & 0xffff);
2459   imm64 >>= 16;
2460   movk(r, imm64 & 0xffff, 16);
2461   imm64 >>= 16;
2462   movk(r, imm64 & 0xffff, 32);
2463 }
2464 
2465 // Macro to mov replicated immediate to vector register.
2466 // imm64: only the lower 8/16/32 bits are considered for B/H/S type. That is,
2467 //        the upper 56/48/32 bits must be zeros for B/H/S type.
2468 // Vd will get the following values for different arrangements in T
2469 //   imm64 == hex 000000gh  T8B:  Vd = ghghghghghghghgh
2470 //   imm64 == hex 000000gh  T16B: Vd = ghghghghghghghghghghghghghghghgh
2471 //   imm64 == hex 0000efgh  T4H:  Vd = efghefghefghefgh
2472 //   imm64 == hex 0000efgh  T8H:  Vd = efghefghefghefghefghefghefghefgh
2473 //   imm64 == hex abcdefgh  T2S:  Vd = abcdefghabcdefgh
2474 //   imm64 == hex abcdefgh  T4S:  Vd = abcdefghabcdefghabcdefghabcdefgh
2475 //   imm64 == hex abcdefgh  T1D:  Vd = 00000000abcdefgh
2476 //   imm64 == hex abcdefgh  T2D:  Vd = 00000000abcdefgh00000000abcdefgh
2477 // Clobbers rscratch1
2478 void MacroAssembler::mov(FloatRegister Vd, SIMD_Arrangement T, uint64_t imm64) {
2479   assert(T != T1Q, "unsupported");
2480   if (T == T1D || T == T2D) {
2481     int imm = operand_valid_for_movi_immediate(imm64, T);
2482     if (-1 != imm) {
2483       movi(Vd, T, imm);
2484     } else {
2485       mov(rscratch1, imm64);
2486       dup(Vd, T, rscratch1);
2487     }
2488     return;
2489   }
2490 
2491 #ifdef ASSERT
2492   if (T == T8B || T == T16B) assert((imm64 & ~0xff) == 0, "extraneous bits (T8B/T16B)");
2493   if (T == T4H || T == T8H) assert((imm64  & ~0xffff) == 0, "extraneous bits (T4H/T8H)");
2494   if (T == T2S || T == T4S) assert((imm64  & ~0xffffffff) == 0, "extraneous bits (T2S/T4S)");
2495 #endif
2496   int shift = operand_valid_for_movi_immediate(imm64, T);
2497   uint32_t imm32 = imm64 & 0xffffffffULL;
2498   if (shift >= 0) {
2499     movi(Vd, T, (imm32 >> shift) & 0xff, shift);
2500   } else {
2501     movw(rscratch1, imm32);
2502     dup(Vd, T, rscratch1);
2503   }
2504 }
2505 
2506 void MacroAssembler::mov_immediate64(Register dst, uint64_t imm64)
2507 {
2508 #ifndef PRODUCT
2509   {
2510     char buffer[64];
2511     os::snprintf_checked(buffer, sizeof(buffer), "0x%" PRIX64, imm64);
2512     block_comment(buffer);
2513   }
2514 #endif
2515   if (operand_valid_for_logical_immediate(false, imm64)) {
2516     orr(dst, zr, imm64);
2517   } else {
2518     // we can use a combination of MOVZ or MOVN with
2519     // MOVK to build up the constant
2520     uint64_t imm_h[4];
2521     int zero_count = 0;
2522     int neg_count = 0;
2523     int i;
2524     for (i = 0; i < 4; i++) {
2525       imm_h[i] = ((imm64 >> (i * 16)) & 0xffffL);
2526       if (imm_h[i] == 0) {
2527         zero_count++;
2528       } else if (imm_h[i] == 0xffffL) {
2529         neg_count++;
2530       }
2531     }
2532     if (zero_count == 4) {
2533       // one MOVZ will do
2534       movz(dst, 0);
2535     } else if (neg_count == 4) {
2536       // one MOVN will do
2537       movn(dst, 0);
2538     } else if (zero_count == 3) {
2539       for (i = 0; i < 4; i++) {
2540         if (imm_h[i] != 0L) {
2541           movz(dst, (uint32_t)imm_h[i], (i << 4));
2542           break;
2543         }
2544       }
2545     } else if (neg_count == 3) {
2546       // one MOVN will do
2547       for (int i = 0; i < 4; i++) {
2548         if (imm_h[i] != 0xffffL) {
2549           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
2550           break;
2551         }
2552       }
2553     } else if (zero_count == 2) {
2554       // one MOVZ and one MOVK will do
2555       for (i = 0; i < 3; i++) {
2556         if (imm_h[i] != 0L) {
2557           movz(dst, (uint32_t)imm_h[i], (i << 4));
2558           i++;
2559           break;
2560         }
2561       }
2562       for (;i < 4; i++) {
2563         if (imm_h[i] != 0L) {
2564           movk(dst, (uint32_t)imm_h[i], (i << 4));
2565         }
2566       }
2567     } else if (neg_count == 2) {
2568       // one MOVN and one MOVK will do
2569       for (i = 0; i < 4; i++) {
2570         if (imm_h[i] != 0xffffL) {
2571           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
2572           i++;
2573           break;
2574         }
2575       }
2576       for (;i < 4; i++) {
2577         if (imm_h[i] != 0xffffL) {
2578           movk(dst, (uint32_t)imm_h[i], (i << 4));
2579         }
2580       }
2581     } else if (zero_count == 1) {
2582       // one MOVZ and two MOVKs will do
2583       for (i = 0; i < 4; i++) {
2584         if (imm_h[i] != 0L) {
2585           movz(dst, (uint32_t)imm_h[i], (i << 4));
2586           i++;
2587           break;
2588         }
2589       }
2590       for (;i < 4; i++) {
2591         if (imm_h[i] != 0x0L) {
2592           movk(dst, (uint32_t)imm_h[i], (i << 4));
2593         }
2594       }
2595     } else if (neg_count == 1) {
2596       // one MOVN and two MOVKs will do
2597       for (i = 0; i < 4; i++) {
2598         if (imm_h[i] != 0xffffL) {
2599           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
2600           i++;
2601           break;
2602         }
2603       }
2604       for (;i < 4; i++) {
2605         if (imm_h[i] != 0xffffL) {
2606           movk(dst, (uint32_t)imm_h[i], (i << 4));
2607         }
2608       }
2609     } else {
2610       // use a MOVZ and 3 MOVKs (makes it easier to debug)
2611       movz(dst, (uint32_t)imm_h[0], 0);
2612       for (i = 1; i < 4; i++) {
2613         movk(dst, (uint32_t)imm_h[i], (i << 4));
2614       }
2615     }
2616   }
2617 }
2618 
2619 void MacroAssembler::mov_immediate32(Register dst, uint32_t imm32)
2620 {
2621 #ifndef PRODUCT
2622     {
2623       char buffer[64];
2624       os::snprintf_checked(buffer, sizeof(buffer), "0x%" PRIX32, imm32);
2625       block_comment(buffer);
2626     }
2627 #endif
2628   if (operand_valid_for_logical_immediate(true, imm32)) {
2629     orrw(dst, zr, imm32);
2630   } else {
2631     // we can use MOVZ, MOVN or two calls to MOVK to build up the
2632     // constant
2633     uint32_t imm_h[2];
2634     imm_h[0] = imm32 & 0xffff;
2635     imm_h[1] = ((imm32 >> 16) & 0xffff);
2636     if (imm_h[0] == 0) {
2637       movzw(dst, imm_h[1], 16);
2638     } else if (imm_h[0] == 0xffff) {
2639       movnw(dst, imm_h[1] ^ 0xffff, 16);
2640     } else if (imm_h[1] == 0) {
2641       movzw(dst, imm_h[0], 0);
2642     } else if (imm_h[1] == 0xffff) {
2643       movnw(dst, imm_h[0] ^ 0xffff, 0);
2644     } else {
2645       // use a MOVZ and MOVK (makes it easier to debug)
2646       movzw(dst, imm_h[0], 0);
2647       movkw(dst, imm_h[1], 16);
2648     }
2649   }
2650 }
2651 
2652 // Form an address from base + offset in Rd.  Rd may or may
2653 // not actually be used: you must use the Address that is returned.
2654 // It is up to you to ensure that the shift provided matches the size
2655 // of your data.
2656 Address MacroAssembler::form_address(Register Rd, Register base, int64_t byte_offset, int shift) {
2657   if (Address::offset_ok_for_immed(byte_offset, shift))
2658     // It fits; no need for any heroics
2659     return Address(base, byte_offset);
2660 
2661   // Don't do anything clever with negative or misaligned offsets
2662   unsigned mask = (1 << shift) - 1;
2663   if (byte_offset < 0 || byte_offset & mask) {
2664     mov(Rd, byte_offset);
2665     add(Rd, base, Rd);
2666     return Address(Rd);
2667   }
2668 
2669   // See if we can do this with two 12-bit offsets
2670   {
2671     uint64_t word_offset = byte_offset >> shift;
2672     uint64_t masked_offset = word_offset & 0xfff000;
2673     if (Address::offset_ok_for_immed(word_offset - masked_offset, 0)
2674         && Assembler::operand_valid_for_add_sub_immediate(masked_offset << shift)) {
2675       add(Rd, base, masked_offset << shift);
2676       word_offset -= masked_offset;
2677       return Address(Rd, word_offset << shift);
2678     }
2679   }
2680 
2681   // Do it the hard way
2682   mov(Rd, byte_offset);
2683   add(Rd, base, Rd);
2684   return Address(Rd);
2685 }
2686 
2687 int MacroAssembler::corrected_idivl(Register result, Register ra, Register rb,
2688                                     bool want_remainder, Register scratch)
2689 {
2690   // Full implementation of Java idiv and irem.  The function
2691   // returns the (pc) offset of the div instruction - may be needed
2692   // for implicit exceptions.
2693   //
2694   // constraint : ra/rb =/= scratch
2695   //         normal case
2696   //
2697   // input : ra: dividend
2698   //         rb: divisor
2699   //
2700   // result: either
2701   //         quotient  (= ra idiv rb)
2702   //         remainder (= ra irem rb)
2703 
2704   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
2705 
2706   int idivl_offset = offset();
2707   if (! want_remainder) {
2708     sdivw(result, ra, rb);
2709   } else {
2710     sdivw(scratch, ra, rb);
2711     Assembler::msubw(result, scratch, rb, ra);
2712   }
2713 
2714   return idivl_offset;
2715 }
2716 
2717 int MacroAssembler::corrected_idivq(Register result, Register ra, Register rb,
2718                                     bool want_remainder, Register scratch)
2719 {
2720   // Full implementation of Java ldiv and lrem.  The function
2721   // returns the (pc) offset of the div instruction - may be needed
2722   // for implicit exceptions.
2723   //
2724   // constraint : ra/rb =/= scratch
2725   //         normal case
2726   //
2727   // input : ra: dividend
2728   //         rb: divisor
2729   //
2730   // result: either
2731   //         quotient  (= ra idiv rb)
2732   //         remainder (= ra irem rb)
2733 
2734   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
2735 
2736   int idivq_offset = offset();
2737   if (! want_remainder) {
2738     sdiv(result, ra, rb);
2739   } else {
2740     sdiv(scratch, ra, rb);
2741     Assembler::msub(result, scratch, rb, ra);
2742   }
2743 
2744   return idivq_offset;
2745 }
2746 
2747 void MacroAssembler::membar(Membar_mask_bits order_constraint) {
2748   address prev = pc() - NativeMembar::instruction_size;
2749   address last = code()->last_merge_candidate();
2750   if (last != nullptr && nativeInstruction_at(last)->is_Membar() && prev == last) {
2751     NativeMembar *bar = NativeMembar_at(prev);
2752     if (AlwaysMergeDMB) {
2753       bar->set_kind(bar->get_kind() | order_constraint);
2754       BLOCK_COMMENT("merged membar(always)");
2755       return;
2756     }
2757     // Don't promote DMB ST|DMB LD to DMB (a full barrier) because
2758     // doing so would introduce a StoreLoad which the caller did not
2759     // intend
2760     if (bar->get_kind() == order_constraint
2761         || bar->get_kind() == AnyAny
2762         || order_constraint == AnyAny) {
2763       // We are merging two memory barrier instructions.  On AArch64 we
2764       // can do this simply by ORing them together.
2765       bar->set_kind(bar->get_kind() | order_constraint);
2766       BLOCK_COMMENT("merged membar");
2767       return;
2768     } else {
2769       // A special case like "DMB ST;DMB LD;DMB ST", the last DMB can be skipped.
2770       // We need to check the second-to-last instruction, only if it is inside
2771       // the current code section.
2772       address prev2 = prev - NativeMembar::instruction_size;
2773       if (prev2 >= begin() && last != code()->last_label() && nativeInstruction_at(prev2)->is_Membar()) {
2774         NativeMembar *bar2 = NativeMembar_at(prev2);
2775         assert(bar2->get_kind() == order_constraint, "it should be merged before");
2776         BLOCK_COMMENT("merged membar(elided)");
2777         return;
2778       }
2779     }
2780   }
2781   code()->set_last_merge_candidate(pc());
2782   dmb(Assembler::barrier(order_constraint));
2783 }
2784 
2785 bool MacroAssembler::try_merge_ldst(Register rt, const Address &adr, size_t size_in_bytes, bool is_store) {
2786   if (ldst_can_merge(rt, adr, size_in_bytes, is_store)) {
2787     merge_ldst(rt, adr, size_in_bytes, is_store);
2788     code()->clear_last_merge_candidate();
2789     return true;
2790   } else {
2791     assert(size_in_bytes == 8 || size_in_bytes == 4, "only 8 bytes or 4 bytes load/store is supported.");
2792     const uint64_t mask = size_in_bytes - 1;
2793     if (adr.getMode() == Address::base_plus_offset &&
2794         (adr.offset() & mask) == 0) { // only supports base_plus_offset.
2795       code()->set_last_merge_candidate(pc());
2796     }
2797     return false;
2798   }
2799 }
2800 
2801 void MacroAssembler::ldr(Register Rx, const Address &adr) {
2802   // We always try to merge two adjacent loads into one ldp.
2803   if (!try_merge_ldst(Rx, adr, 8, false)) {
2804     Assembler::ldr(Rx, adr);
2805   }
2806 }
2807 
2808 void MacroAssembler::ldrw(Register Rw, const Address &adr) {
2809   // We always try to merge two adjacent loads into one ldp.
2810   if (!try_merge_ldst(Rw, adr, 4, false)) {
2811     Assembler::ldrw(Rw, adr);
2812   }
2813 }
2814 
2815 void MacroAssembler::str(Register Rx, const Address &adr) {
2816   // We always try to merge two adjacent stores into one stp.
2817   if (!try_merge_ldst(Rx, adr, 8, true)) {
2818     Assembler::str(Rx, adr);
2819   }
2820 }
2821 
2822 void MacroAssembler::strw(Register Rw, const Address &adr) {
2823   // We always try to merge two adjacent stores into one stp.
2824   if (!try_merge_ldst(Rw, adr, 4, true)) {
2825     Assembler::strw(Rw, adr);
2826   }
2827 }
2828 
2829 // MacroAssembler routines found actually to be needed
2830 
2831 void MacroAssembler::push(Register src)
2832 {
2833   str(src, Address(pre(esp, -1 * wordSize)));
2834 }
2835 
2836 void MacroAssembler::pop(Register dst)
2837 {
2838   ldr(dst, Address(post(esp, 1 * wordSize)));
2839 }
2840 
2841 // Note: load_unsigned_short used to be called load_unsigned_word.
2842 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
2843   int off = offset();
2844   ldrh(dst, src);
2845   return off;
2846 }
2847 
2848 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
2849   int off = offset();
2850   ldrb(dst, src);
2851   return off;
2852 }
2853 
2854 int MacroAssembler::load_signed_short(Register dst, Address src) {
2855   int off = offset();
2856   ldrsh(dst, src);
2857   return off;
2858 }
2859 
2860 int MacroAssembler::load_signed_byte(Register dst, Address src) {
2861   int off = offset();
2862   ldrsb(dst, src);
2863   return off;
2864 }
2865 
2866 int MacroAssembler::load_signed_short32(Register dst, Address src) {
2867   int off = offset();
2868   ldrshw(dst, src);
2869   return off;
2870 }
2871 
2872 int MacroAssembler::load_signed_byte32(Register dst, Address src) {
2873   int off = offset();
2874   ldrsbw(dst, src);
2875   return off;
2876 }
2877 
2878 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed) {
2879   switch (size_in_bytes) {
2880   case  8:  ldr(dst, src); break;
2881   case  4:  ldrw(dst, src); break;
2882   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
2883   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
2884   default:  ShouldNotReachHere();
2885   }
2886 }
2887 
2888 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes) {
2889   switch (size_in_bytes) {
2890   case  8:  str(src, dst); break;
2891   case  4:  strw(src, dst); break;
2892   case  2:  strh(src, dst); break;
2893   case  1:  strb(src, dst); break;
2894   default:  ShouldNotReachHere();
2895   }
2896 }
2897 
2898 void MacroAssembler::narrow_subword_type(Register reg, BasicType bt) {
2899   assert(is_subword_type(bt), "required");
2900   switch (bt) {
2901   case T_BOOLEAN: andw(reg, reg, 1); break;
2902   case T_BYTE:    sxtbw(reg, reg); break;
2903   case T_CHAR:    uxthw(reg, reg); break;
2904   case T_SHORT:   sxthw(reg, reg); break;
2905   default:        ShouldNotReachHere();
2906   }
2907 }
2908 
2909 void MacroAssembler::decrementw(Register reg, int value)
2910 {
2911   if (value < 0)  { incrementw(reg, -value);      return; }
2912   if (value == 0) {                               return; }
2913   if (value < (1 << 24)) { subw(reg, reg, value); return; }
2914   /* else */ {
2915     guarantee(reg != rscratch2, "invalid dst for register decrement");
2916     movw(rscratch2, (unsigned)value);
2917     subw(reg, reg, rscratch2);
2918   }
2919 }
2920 
2921 void MacroAssembler::decrement(Register reg, int value)
2922 {
2923   if (value < 0)  { increment(reg, -value);      return; }
2924   if (value == 0) {                              return; }
2925   if (value < (1 << 24)) { sub(reg, reg, value); return; }
2926   /* else */ {
2927     assert(reg != rscratch2, "invalid dst for register decrement");
2928     mov(rscratch2, (uint64_t)value);
2929     sub(reg, reg, rscratch2);
2930   }
2931 }
2932 
2933 void MacroAssembler::decrementw(Address dst, int value)
2934 {
2935   assert(!dst.uses(rscratch1), "invalid dst for address decrement");
2936   if (dst.getMode() == Address::literal) {
2937     assert(abs(value) < (1 << 24), "invalid value and address mode combination");
2938     lea(rscratch2, dst);
2939     dst = Address(rscratch2);
2940   }
2941   ldrw(rscratch1, dst);
2942   decrementw(rscratch1, value);
2943   strw(rscratch1, dst);
2944 }
2945 
2946 void MacroAssembler::decrement(Address dst, int value)
2947 {
2948   assert(!dst.uses(rscratch1), "invalid address for decrement");
2949   if (dst.getMode() == Address::literal) {
2950     assert(abs(value) < (1 << 24), "invalid value and address mode combination");
2951     lea(rscratch2, dst);
2952     dst = Address(rscratch2);
2953   }
2954   ldr(rscratch1, dst);
2955   decrement(rscratch1, value);
2956   str(rscratch1, dst);
2957 }
2958 
2959 void MacroAssembler::incrementw(Register reg, int value)
2960 {
2961   if (value < 0)  { decrementw(reg, -value);      return; }
2962   if (value == 0) {                               return; }
2963   if (value < (1 << 24)) { addw(reg, reg, value); return; }
2964   /* else */ {
2965     assert(reg != rscratch2, "invalid dst for register increment");
2966     movw(rscratch2, (unsigned)value);
2967     addw(reg, reg, rscratch2);
2968   }
2969 }
2970 
2971 void MacroAssembler::increment(Register reg, int value)
2972 {
2973   if (value < 0)  { decrement(reg, -value);      return; }
2974   if (value == 0) {                              return; }
2975   if (value < (1 << 24)) { add(reg, reg, value); return; }
2976   /* else */ {
2977     assert(reg != rscratch2, "invalid dst for register increment");
2978     movw(rscratch2, (unsigned)value);
2979     add(reg, reg, rscratch2);
2980   }
2981 }
2982 
2983 void MacroAssembler::incrementw(Address dst, int value, Register result)
2984 {
2985   assert(!dst.uses(result), "invalid dst for address increment");
2986   assert(result->is_valid(), "must be");
2987   assert_different_registers(result, rscratch2);
2988   if (dst.getMode() == Address::literal) {
2989     assert(abs(value) < (1 << 24), "invalid value and address mode combination");
2990     lea(rscratch2, dst);
2991     dst = Address(rscratch2);
2992   }
2993   ldrw(result, dst);
2994   incrementw(result, value);
2995   strw(result, dst);
2996 }
2997 
2998 void MacroAssembler::increment(Address dst, int value, Register result)
2999 {
3000   assert(!dst.uses(result), "invalid dst for address increment");
3001   assert(result->is_valid(), "must be");
3002   assert_different_registers(result, rscratch2);
3003   if (dst.getMode() == Address::literal) {
3004     assert(abs(value) < (1 << 24), "invalid value and address mode combination");
3005     lea(rscratch2, dst);
3006     dst = Address(rscratch2);
3007   }
3008   ldr(result, dst);
3009   increment(result, value);
3010   str(result, dst);
3011 }
3012 
3013 // Push lots of registers in the bit set supplied.  Don't push sp.
3014 // Return the number of words pushed
3015 int MacroAssembler::push(RegSet regset, Register stack) {
3016   if (regset.bits() == 0) {
3017     return 0;
3018   }
3019   auto bitset = integer_cast<unsigned int>(regset.bits());
3020   int words_pushed = 0;
3021 
3022   // Scan bitset to accumulate register pairs
3023   unsigned char regs[32];
3024   int count = 0;
3025   for (int reg = 0; reg <= 30; reg++) {
3026     if (1 & bitset)
3027       regs[count++] = reg;
3028     bitset >>= 1;
3029   }
3030   regs[count++] = zr->raw_encoding();
3031   count &= ~1;  // Only push an even number of regs
3032 
3033   if (count) {
3034     stp(as_Register(regs[0]), as_Register(regs[1]),
3035        Address(pre(stack, -count * wordSize)));
3036     words_pushed += 2;
3037   }
3038   for (int i = 2; i < count; i += 2) {
3039     stp(as_Register(regs[i]), as_Register(regs[i+1]),
3040        Address(stack, i * wordSize));
3041     words_pushed += 2;
3042   }
3043 
3044   assert(words_pushed == count, "oops, pushed != count");
3045 
3046   return count;
3047 }
3048 
3049 int MacroAssembler::pop(RegSet regset, Register stack) {
3050   if (regset.bits() == 0) {
3051     return 0;
3052   }
3053   auto bitset = integer_cast<unsigned int>(regset.bits());
3054   int words_pushed = 0;
3055 
3056   // Scan bitset to accumulate register pairs
3057   unsigned char regs[32];
3058   int count = 0;
3059   for (int reg = 0; reg <= 30; reg++) {
3060     if (1 & bitset)
3061       regs[count++] = reg;
3062     bitset >>= 1;
3063   }
3064   regs[count++] = zr->raw_encoding();
3065   count &= ~1;
3066 
3067   for (int i = 2; i < count; i += 2) {
3068     ldp(as_Register(regs[i]), as_Register(regs[i+1]),
3069        Address(stack, i * wordSize));
3070     words_pushed += 2;
3071   }
3072   if (count) {
3073     ldp(as_Register(regs[0]), as_Register(regs[1]),
3074        Address(post(stack, count * wordSize)));
3075     words_pushed += 2;
3076   }
3077 
3078   assert(words_pushed == count, "oops, pushed != count");
3079 
3080   return count;
3081 }
3082 
3083 // Push lots of registers in the bit set supplied.  Don't push sp.
3084 // Return the number of dwords pushed
3085 int MacroAssembler::push_fp(FloatRegSet regset, Register stack, FpPushPopMode mode) {
3086   if (regset.bits() == 0) {
3087     return 0;
3088   }
3089   auto bitset = integer_cast<unsigned int>(regset.bits());
3090   int words_pushed = 0;
3091   bool use_sve = false;
3092   int sve_vector_size_in_bytes = 0;
3093 
3094 #ifdef COMPILER2
3095   use_sve = Matcher::supports_scalable_vector();
3096   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
3097 #endif
3098 
3099   // Scan bitset to accumulate register pairs
3100   unsigned char regs[32];
3101   int count = 0;
3102   for (int reg = 0; reg <= 31; reg++) {
3103     if (1 & bitset)
3104       regs[count++] = reg;
3105     bitset >>= 1;
3106   }
3107 
3108   if (count == 0) {
3109     return 0;
3110   }
3111 
3112   if (mode == PushPopFull) {
3113     if (use_sve && sve_vector_size_in_bytes > 16) {
3114       mode = PushPopSVE;
3115     } else {
3116       mode = PushPopNeon;
3117     }
3118   }
3119 
3120 #ifndef PRODUCT
3121   {
3122     char buffer[48];
3123     if (mode == PushPopSVE) {
3124       os::snprintf_checked(buffer, sizeof(buffer), "push_fp: %d SVE registers", count);
3125     } else if (mode == PushPopNeon) {
3126       os::snprintf_checked(buffer, sizeof(buffer), "push_fp: %d Neon registers", count);
3127     } else {
3128       os::snprintf_checked(buffer, sizeof(buffer), "push_fp: %d fp registers", count);
3129     }
3130     block_comment(buffer);
3131   }
3132 #endif
3133 
3134   if (mode == PushPopSVE) {
3135     sub(stack, stack, sve_vector_size_in_bytes * count);
3136     for (int i = 0; i < count; i++) {
3137       sve_str(as_FloatRegister(regs[i]), Address(stack, i));
3138     }
3139     return count * sve_vector_size_in_bytes / 8;
3140   }
3141 
3142   if (mode == PushPopNeon) {
3143     if (count == 1) {
3144       strq(as_FloatRegister(regs[0]), Address(pre(stack, -wordSize * 2)));
3145       return 2;
3146     }
3147 
3148     bool odd = (count & 1) == 1;
3149     int push_slots = count + (odd ? 1 : 0);
3150 
3151     // Always pushing full 128 bit registers.
3152     stpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(pre(stack, -push_slots * wordSize * 2)));
3153     words_pushed += 2;
3154 
3155     for (int i = 2; i + 1 < count; i += 2) {
3156       stpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
3157       words_pushed += 2;
3158     }
3159 
3160     if (odd) {
3161       strq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
3162       words_pushed++;
3163     }
3164 
3165     assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
3166     return count * 2;
3167   }
3168 
3169   if (mode == PushPopFp) {
3170     bool odd = (count & 1) == 1;
3171     int push_slots = count + (odd ? 1 : 0);
3172 
3173     if (count == 1) {
3174       // Stack pointer must be 16 bytes aligned
3175       strd(as_FloatRegister(regs[0]), Address(pre(stack, -push_slots * wordSize)));
3176       return 1;
3177     }
3178 
3179     stpd(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(pre(stack, -push_slots * wordSize)));
3180     words_pushed += 2;
3181 
3182     for (int i = 2; i + 1 < count; i += 2) {
3183       stpd(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize));
3184       words_pushed += 2;
3185     }
3186 
3187     if (odd) {
3188       // Stack pointer must be 16 bytes aligned
3189       strd(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize));
3190       words_pushed++;
3191     }
3192 
3193     assert(words_pushed == count, "oops, pushed != count");
3194 
3195     return count;
3196   }
3197 
3198   return 0;
3199 }
3200 
3201 // Return the number of dwords popped
3202 int MacroAssembler::pop_fp(FloatRegSet regset, Register stack, FpPushPopMode mode) {
3203   if (regset.bits() == 0) {
3204     return 0;
3205   }
3206   auto bitset = integer_cast<unsigned int>(regset.bits());
3207   int words_pushed = 0;
3208   bool use_sve = false;
3209   int sve_vector_size_in_bytes = 0;
3210 
3211 #ifdef COMPILER2
3212   use_sve = Matcher::supports_scalable_vector();
3213   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
3214 #endif
3215   // Scan bitset to accumulate register pairs
3216   unsigned char regs[32];
3217   int count = 0;
3218   for (int reg = 0; reg <= 31; reg++) {
3219     if (1 & bitset)
3220       regs[count++] = reg;
3221     bitset >>= 1;
3222   }
3223 
3224   if (count == 0) {
3225     return 0;
3226   }
3227 
3228   if (mode == PushPopFull) {
3229     if (use_sve && sve_vector_size_in_bytes > 16) {
3230       mode = PushPopSVE;
3231     } else {
3232       mode = PushPopNeon;
3233     }
3234   }
3235 
3236 #ifndef PRODUCT
3237   {
3238     char buffer[48];
3239     if (mode == PushPopSVE) {
3240       os::snprintf_checked(buffer, sizeof(buffer), "pop_fp: %d SVE registers", count);
3241     } else if (mode == PushPopNeon) {
3242       os::snprintf_checked(buffer, sizeof(buffer), "pop_fp: %d Neon registers", count);
3243     } else {
3244       os::snprintf_checked(buffer, sizeof(buffer), "pop_fp: %d fp registers", count);
3245     }
3246     block_comment(buffer);
3247   }
3248 #endif
3249 
3250   if (mode == PushPopSVE) {
3251     for (int i = count - 1; i >= 0; i--) {
3252       sve_ldr(as_FloatRegister(regs[i]), Address(stack, i));
3253     }
3254     add(stack, stack, sve_vector_size_in_bytes * count);
3255     return count * sve_vector_size_in_bytes / 8;
3256   }
3257 
3258   if (mode == PushPopNeon) {
3259     if (count == 1) {
3260       ldrq(as_FloatRegister(regs[0]), Address(post(stack, wordSize * 2)));
3261       return 2;
3262     }
3263 
3264     bool odd = (count & 1) == 1;
3265     int push_slots = count + (odd ? 1 : 0);
3266 
3267     if (odd) {
3268       ldrq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
3269       words_pushed++;
3270     }
3271 
3272     for (int i = 2; i + 1 < count; i += 2) {
3273       ldpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
3274       words_pushed += 2;
3275     }
3276 
3277     ldpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(post(stack, push_slots * wordSize * 2)));
3278     words_pushed += 2;
3279 
3280     assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
3281 
3282     return count * 2;
3283   }
3284 
3285   if (mode == PushPopFp) {
3286     bool odd = (count & 1) == 1;
3287     int push_slots = count + (odd ? 1 : 0);
3288 
3289     if (count == 1) {
3290       ldrd(as_FloatRegister(regs[0]), Address(post(stack, push_slots * wordSize)));
3291       return 1;
3292     }
3293 
3294     if (odd) {
3295       ldrd(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize));
3296       words_pushed++;
3297     }
3298 
3299     for (int i = 2; i + 1 < count; i += 2) {
3300       ldpd(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize));
3301       words_pushed += 2;
3302     }
3303 
3304     ldpd(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(post(stack, push_slots * wordSize)));
3305     words_pushed += 2;
3306 
3307     assert(words_pushed == count, "oops, pushed != count");
3308 
3309     return count;
3310   }
3311 
3312   return 0;
3313 }
3314 
3315 // Return the number of dwords pushed
3316 int MacroAssembler::push_p(PRegSet regset, Register stack) {
3317   if (regset.bits() == 0) {
3318     return 0;
3319   }
3320   auto bitset = integer_cast<unsigned int>(regset.bits());
3321   bool use_sve = false;
3322   int sve_predicate_size_in_slots = 0;
3323 
3324 #ifdef COMPILER2
3325   use_sve = Matcher::supports_scalable_vector();
3326   if (use_sve) {
3327     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
3328   }
3329 #endif
3330 
3331   if (!use_sve) {
3332     return 0;
3333   }
3334 
3335   unsigned char regs[PRegister::number_of_registers];
3336   int count = 0;
3337   for (int reg = 0; reg < PRegister::number_of_registers; reg++) {
3338     if (1 & bitset)
3339       regs[count++] = reg;
3340     bitset >>= 1;
3341   }
3342 
3343   if (count == 0) {
3344     return 0;
3345   }
3346 
3347   int total_push_bytes = align_up(sve_predicate_size_in_slots *
3348                                   VMRegImpl::stack_slot_size * count, 16);
3349   sub(stack, stack, total_push_bytes);
3350   for (int i = 0; i < count; i++) {
3351     sve_str(as_PRegister(regs[i]), Address(stack, i));
3352   }
3353   return total_push_bytes / 8;
3354 }
3355 
3356 // Return the number of dwords popped
3357 int MacroAssembler::pop_p(PRegSet regset, Register stack) {
3358   if (regset.bits() == 0) {
3359     return 0;
3360   }
3361   auto bitset = integer_cast<unsigned int>(regset.bits());
3362   bool use_sve = false;
3363   int sve_predicate_size_in_slots = 0;
3364 
3365 #ifdef COMPILER2
3366   use_sve = Matcher::supports_scalable_vector();
3367   if (use_sve) {
3368     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
3369   }
3370 #endif
3371 
3372   if (!use_sve) {
3373     return 0;
3374   }
3375 
3376   unsigned char regs[PRegister::number_of_registers];
3377   int count = 0;
3378   for (int reg = 0; reg < PRegister::number_of_registers; reg++) {
3379     if (1 & bitset)
3380       regs[count++] = reg;
3381     bitset >>= 1;
3382   }
3383 
3384   if (count == 0) {
3385     return 0;
3386   }
3387 
3388   int total_pop_bytes = align_up(sve_predicate_size_in_slots *
3389                                  VMRegImpl::stack_slot_size * count, 16);
3390   for (int i = count - 1; i >= 0; i--) {
3391     sve_ldr(as_PRegister(regs[i]), Address(stack, i));
3392   }
3393   add(stack, stack, total_pop_bytes);
3394   return total_pop_bytes / 8;
3395 }
3396 
3397 #ifdef ASSERT
3398 void MacroAssembler::verify_heapbase(const char* msg) {
3399 #if 0
3400   assert (Universe::heap() != nullptr, "java heap should be initialized");
3401   if (!UseCompressedOops || Universe::ptr_base() == nullptr) {
3402     // rheapbase is allocated as general register
3403     return;
3404   }
3405   if (CheckCompressedOops) {
3406     Label ok;
3407     push(1 << rscratch1->encoding(), sp); // cmpptr trashes rscratch1
3408     cmpptr(rheapbase, ExternalAddress(CompressedOops::base_addr()));
3409     br(Assembler::EQ, ok);
3410     stop(msg);
3411     bind(ok);
3412     pop(1 << rscratch1->encoding(), sp);
3413   }
3414 #endif
3415 }
3416 #endif
3417 
3418 void MacroAssembler::resolve_jobject(Register value, Register tmp1, Register tmp2) {
3419   assert_different_registers(value, tmp1, tmp2);
3420   Label done, tagged, weak_tagged;
3421 
3422   cbz(value, done);           // Use null as-is.
3423   tst(value, JNIHandles::tag_mask); // Test for tag.
3424   br(Assembler::NE, tagged);
3425 
3426   // Resolve local handle
3427   access_load_at(T_OBJECT, IN_NATIVE | AS_RAW, value, Address(value, 0), tmp1, tmp2);
3428   verify_oop(value);
3429   b(done);
3430 
3431   bind(tagged);
3432   STATIC_ASSERT(JNIHandles::TypeTag::weak_global == 0b1);
3433   tbnz(value, 0, weak_tagged);    // Test for weak tag.
3434 
3435   // Resolve global handle
3436   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, -JNIHandles::TypeTag::global), tmp1, tmp2);
3437   verify_oop(value);
3438   b(done);
3439 
3440   bind(weak_tagged);
3441   // Resolve jweak.
3442   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
3443                  value, Address(value, -JNIHandles::TypeTag::weak_global), tmp1, tmp2);
3444   verify_oop(value);
3445 
3446   bind(done);
3447 }
3448 
3449 void MacroAssembler::resolve_global_jobject(Register value, Register tmp1, Register tmp2) {
3450   assert_different_registers(value, tmp1, tmp2);
3451   Label done;
3452 
3453   cbz(value, done);           // Use null as-is.
3454 
3455 #ifdef ASSERT
3456   {
3457     STATIC_ASSERT(JNIHandles::TypeTag::global == 0b10);
3458     Label valid_global_tag;
3459     tbnz(value, 1, valid_global_tag); // Test for global tag
3460     stop("non global jobject using resolve_global_jobject");
3461     bind(valid_global_tag);
3462   }
3463 #endif
3464 
3465   // Resolve global handle
3466   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, -JNIHandles::TypeTag::global), tmp1, tmp2);
3467   verify_oop(value);
3468 
3469   bind(done);
3470 }
3471 
3472 void MacroAssembler::stop(const char* msg) {
3473   // Skip AOT caching C strings in scratch buffer.
3474   const char* str = (code_section()->scratch_emit()) ? msg : AOTCodeCache::add_C_string(msg);
3475   BLOCK_COMMENT(str);
3476   // load msg into r0 so we can access it from the signal handler
3477   // ExternalAddress enables saving and restoring via the code cache
3478   lea(c_rarg0, ExternalAddress((address) str));
3479   dcps1(0xdeae);
3480 }
3481 
3482 void MacroAssembler::unimplemented(const char* what) {
3483   const char* buf = nullptr;
3484   {
3485     ResourceMark rm;
3486     stringStream ss;
3487     ss.print("unimplemented: %s", what);
3488     buf = code_string(ss.as_string());
3489   }
3490   stop(buf);
3491 }
3492 
3493 void MacroAssembler::_assert_asm(Assembler::Condition cc, const char* msg) {
3494 #ifdef ASSERT
3495   Label OK;
3496   br(cc, OK);
3497   stop(msg);
3498   bind(OK);
3499 #endif
3500 }
3501 
3502 // If a constant does not fit in an immediate field, generate some
3503 // number of MOV instructions and then perform the operation.
3504 void MacroAssembler::wrap_add_sub_imm_insn(Register Rd, Register Rn, uint64_t imm,
3505                                            add_sub_imm_insn insn1,
3506                                            add_sub_reg_insn insn2,
3507                                            bool is32) {
3508   assert(Rd != zr, "Rd = zr and not setting flags?");
3509   bool fits = operand_valid_for_add_sub_immediate(is32 ? (int32_t)imm : imm);
3510   if (fits) {
3511     (this->*insn1)(Rd, Rn, imm);
3512   } else {
3513     if (g_uabs(imm) < (1 << 24)) {
3514        (this->*insn1)(Rd, Rn, imm & -(1 << 12));
3515        (this->*insn1)(Rd, Rd, imm & ((1 << 12)-1));
3516     } else {
3517        assert_different_registers(Rd, Rn);
3518        mov(Rd, imm);
3519        (this->*insn2)(Rd, Rn, Rd, LSL, 0);
3520     }
3521   }
3522 }
3523 
3524 // Separate vsn which sets the flags. Optimisations are more restricted
3525 // because we must set the flags correctly.
3526 void MacroAssembler::wrap_adds_subs_imm_insn(Register Rd, Register Rn, uint64_t imm,
3527                                              add_sub_imm_insn insn1,
3528                                              add_sub_reg_insn insn2,
3529                                              bool is32) {
3530   bool fits = operand_valid_for_add_sub_immediate(is32 ? (int32_t)imm : imm);
3531   if (fits) {
3532     (this->*insn1)(Rd, Rn, imm);
3533   } else {
3534     assert_different_registers(Rd, Rn);
3535     assert(Rd != zr, "overflow in immediate operand");
3536     mov(Rd, imm);
3537     (this->*insn2)(Rd, Rn, Rd, LSL, 0);
3538   }
3539 }
3540 
3541 
3542 void MacroAssembler::add(Register Rd, Register Rn, RegisterOrConstant increment) {
3543   if (increment.is_register()) {
3544     add(Rd, Rn, increment.as_register());
3545   } else {
3546     add(Rd, Rn, increment.as_constant());
3547   }
3548 }
3549 
3550 void MacroAssembler::addw(Register Rd, Register Rn, RegisterOrConstant increment) {
3551   if (increment.is_register()) {
3552     addw(Rd, Rn, increment.as_register());
3553   } else {
3554     addw(Rd, Rn, increment.as_constant());
3555   }
3556 }
3557 
3558 void MacroAssembler::sub(Register Rd, Register Rn, RegisterOrConstant decrement) {
3559   if (decrement.is_register()) {
3560     sub(Rd, Rn, decrement.as_register());
3561   } else {
3562     sub(Rd, Rn, decrement.as_constant());
3563   }
3564 }
3565 
3566 void MacroAssembler::subw(Register Rd, Register Rn, RegisterOrConstant decrement) {
3567   if (decrement.is_register()) {
3568     subw(Rd, Rn, decrement.as_register());
3569   } else {
3570     subw(Rd, Rn, decrement.as_constant());
3571   }
3572 }
3573 
3574 void MacroAssembler::reinit_heapbase()
3575 {
3576   if (UseCompressedOops) {
3577     if (Universe::is_fully_initialized() && !AOTCodeCache::is_on_for_dump()) {
3578       mov(rheapbase, CompressedOops::base());
3579     } else {
3580       lea(rheapbase, ExternalAddress(CompressedOops::base_addr()));
3581       ldr(rheapbase, Address(rheapbase));
3582     }
3583   }
3584 }
3585 
3586 // A generic CAS; success or failure is in the EQ flag.  A weak CAS
3587 // doesn't retry and may fail spuriously.  If the oldval is wanted,
3588 // Pass a register for the result, otherwise pass noreg.
3589 
3590 // Clobbers rscratch1
3591 void MacroAssembler::cmpxchg(Register addr, Register expected,
3592                              Register new_val,
3593                              enum operand_size size,
3594                              enum atomic_memory_order order,
3595                              bool weak,
3596                              Register result) {
3597   bool acquire, release;
3598 
3599   switch (order) {
3600     case memory_order_relaxed:
3601       acquire = false;
3602       release = false;
3603       break;
3604     case memory_order_acquire:
3605       acquire = true;
3606       release = false;
3607       break;
3608     case memory_order_release:
3609       acquire = false;
3610       release = true;
3611       break;
3612     case memory_order_acq_rel:
3613     case memory_order_seq_cst:
3614       acquire = true;
3615       release = true;
3616       break;
3617     default:
3618       ShouldNotReachHere();
3619   }
3620 
3621   if (result == noreg)  result = rscratch1;
3622   BLOCK_COMMENT("cmpxchg {");
3623   if (UseLSE) {
3624     mov(result, expected);
3625     lse_cas(result, new_val, addr, size, acquire, release, /*not_pair*/ true);
3626     compare_eq(result, expected, size);
3627 #ifdef ASSERT
3628     // Poison rscratch1 which is written on !UseLSE branch
3629     mov(rscratch1, 0x1f1f1f1f1f1f1f1f);
3630 #endif
3631   } else {
3632     Label retry_load, done;
3633     prfm(Address(addr), PSTL1STRM);
3634     bind(retry_load);
3635     load_exclusive(result, addr, size, acquire);
3636     compare_eq(result, expected, size);
3637     br(Assembler::NE, done);
3638     store_exclusive(rscratch1, new_val, addr, size, release);
3639     if (weak) {
3640       cmpw(rscratch1, 0u);  // If the store fails, return NE to our caller.
3641     } else {
3642       cbnzw(rscratch1, retry_load);
3643     }
3644     bind(done);
3645   }
3646   BLOCK_COMMENT("} cmpxchg");
3647 }
3648 
3649 // A generic comparison. Only compares for equality, clobbers rscratch1.
3650 void MacroAssembler::compare_eq(Register rm, Register rn, enum operand_size size) {
3651   if (size == xword) {
3652     cmp(rm, rn);
3653   } else if (size == word) {
3654     cmpw(rm, rn);
3655   } else if (size == halfword) {
3656     eorw(rscratch1, rm, rn);
3657     ands(zr, rscratch1, 0xffff);
3658   } else if (size == byte) {
3659     eorw(rscratch1, rm, rn);
3660     ands(zr, rscratch1, 0xff);
3661   } else {
3662     ShouldNotReachHere();
3663   }
3664 }
3665 
3666 
3667 static bool different(Register a, RegisterOrConstant b, Register c) {
3668   if (b.is_constant())
3669     return a != c;
3670   else
3671     return a != b.as_register() && a != c && b.as_register() != c;
3672 }
3673 
3674 #define ATOMIC_OP(NAME, LDXR, OP, IOP, AOP, STXR, sz)                   \
3675 void MacroAssembler::atomic_##NAME(Register prev, RegisterOrConstant incr, Register addr) { \
3676   if (UseLSE) {                                                         \
3677     prev = prev->is_valid() ? prev : zr;                                \
3678     if (incr.is_register()) {                                           \
3679       AOP(sz, incr.as_register(), prev, addr);                          \
3680     } else {                                                            \
3681       mov(rscratch2, incr.as_constant());                               \
3682       AOP(sz, rscratch2, prev, addr);                                   \
3683     }                                                                   \
3684     return;                                                             \
3685   }                                                                     \
3686   Register result = rscratch2;                                          \
3687   if (prev->is_valid())                                                 \
3688     result = different(prev, incr, addr) ? prev : rscratch2;            \
3689                                                                         \
3690   Label retry_load;                                                     \
3691   prfm(Address(addr), PSTL1STRM);                                       \
3692   bind(retry_load);                                                     \
3693   LDXR(result, addr);                                                   \
3694   OP(rscratch1, result, incr);                                          \
3695   STXR(rscratch2, rscratch1, addr);                                     \
3696   cbnzw(rscratch2, retry_load);                                         \
3697   if (prev->is_valid() && prev != result) {                             \
3698     IOP(prev, rscratch1, incr);                                         \
3699   }                                                                     \
3700 }
3701 
3702 ATOMIC_OP(add, ldxr, add, sub, ldadd, stxr, Assembler::xword)
3703 ATOMIC_OP(addw, ldxrw, addw, subw, ldadd, stxrw, Assembler::word)
3704 ATOMIC_OP(addal, ldaxr, add, sub, ldaddal, stlxr, Assembler::xword)
3705 ATOMIC_OP(addalw, ldaxrw, addw, subw, ldaddal, stlxrw, Assembler::word)
3706 
3707 #undef ATOMIC_OP
3708 
3709 #define ATOMIC_XCHG(OP, AOP, LDXR, STXR, sz)                            \
3710 void MacroAssembler::atomic_##OP(Register prev, Register newv, Register addr) { \
3711   if (UseLSE) {                                                         \
3712     prev = prev->is_valid() ? prev : zr;                                \
3713     AOP(sz, newv, prev, addr);                                          \
3714     return;                                                             \
3715   }                                                                     \
3716   Register result = rscratch2;                                          \
3717   if (prev->is_valid())                                                 \
3718     result = different(prev, newv, addr) ? prev : rscratch2;            \
3719                                                                         \
3720   Label retry_load;                                                     \
3721   prfm(Address(addr), PSTL1STRM);                                       \
3722   bind(retry_load);                                                     \
3723   LDXR(result, addr);                                                   \
3724   STXR(rscratch1, newv, addr);                                          \
3725   cbnzw(rscratch1, retry_load);                                         \
3726   if (prev->is_valid() && prev != result)                               \
3727     mov(prev, result);                                                  \
3728 }
3729 
3730 ATOMIC_XCHG(xchg, swp, ldxr, stxr, Assembler::xword)
3731 ATOMIC_XCHG(xchgw, swp, ldxrw, stxrw, Assembler::word)
3732 ATOMIC_XCHG(xchgl, swpl, ldxr, stlxr, Assembler::xword)
3733 ATOMIC_XCHG(xchglw, swpl, ldxrw, stlxrw, Assembler::word)
3734 ATOMIC_XCHG(xchgal, swpal, ldaxr, stlxr, Assembler::xword)
3735 ATOMIC_XCHG(xchgalw, swpal, ldaxrw, stlxrw, Assembler::word)
3736 
3737 #undef ATOMIC_XCHG
3738 
3739 #ifndef PRODUCT
3740 extern "C" void findpc(intptr_t x);
3741 #endif
3742 
3743 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[])
3744 {
3745   // In order to get locks to work, we need to fake a in_VM state
3746   if (ShowMessageBoxOnError) {
3747     JavaThread* thread = JavaThread::current();
3748     thread->set_thread_state(_thread_in_vm);
3749 #ifndef PRODUCT
3750     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
3751       ttyLocker ttyl;
3752       BytecodeCounter::print();
3753     }
3754 #endif
3755     if (os::message_box(msg, "Execution stopped, print registers?")) {
3756       ttyLocker ttyl;
3757       tty->print_cr(" pc = 0x%016" PRIx64, pc);
3758 #ifndef PRODUCT
3759       tty->cr();
3760       findpc(pc);
3761       tty->cr();
3762 #endif
3763       tty->print_cr(" r0 = 0x%016" PRIx64, regs[0]);
3764       tty->print_cr(" r1 = 0x%016" PRIx64, regs[1]);
3765       tty->print_cr(" r2 = 0x%016" PRIx64, regs[2]);
3766       tty->print_cr(" r3 = 0x%016" PRIx64, regs[3]);
3767       tty->print_cr(" r4 = 0x%016" PRIx64, regs[4]);
3768       tty->print_cr(" r5 = 0x%016" PRIx64, regs[5]);
3769       tty->print_cr(" r6 = 0x%016" PRIx64, regs[6]);
3770       tty->print_cr(" r7 = 0x%016" PRIx64, regs[7]);
3771       tty->print_cr(" r8 = 0x%016" PRIx64, regs[8]);
3772       tty->print_cr(" r9 = 0x%016" PRIx64, regs[9]);
3773       tty->print_cr("r10 = 0x%016" PRIx64, regs[10]);
3774       tty->print_cr("r11 = 0x%016" PRIx64, regs[11]);
3775       tty->print_cr("r12 = 0x%016" PRIx64, regs[12]);
3776       tty->print_cr("r13 = 0x%016" PRIx64, regs[13]);
3777       tty->print_cr("r14 = 0x%016" PRIx64, regs[14]);
3778       tty->print_cr("r15 = 0x%016" PRIx64, regs[15]);
3779       tty->print_cr("r16 = 0x%016" PRIx64, regs[16]);
3780       tty->print_cr("r17 = 0x%016" PRIx64, regs[17]);
3781       tty->print_cr("r18 = 0x%016" PRIx64, regs[18]);
3782       tty->print_cr("r19 = 0x%016" PRIx64, regs[19]);
3783       tty->print_cr("r20 = 0x%016" PRIx64, regs[20]);
3784       tty->print_cr("r21 = 0x%016" PRIx64, regs[21]);
3785       tty->print_cr("r22 = 0x%016" PRIx64, regs[22]);
3786       tty->print_cr("r23 = 0x%016" PRIx64, regs[23]);
3787       tty->print_cr("r24 = 0x%016" PRIx64, regs[24]);
3788       tty->print_cr("r25 = 0x%016" PRIx64, regs[25]);
3789       tty->print_cr("r26 = 0x%016" PRIx64, regs[26]);
3790       tty->print_cr("r27 = 0x%016" PRIx64, regs[27]);
3791       tty->print_cr("r28 = 0x%016" PRIx64, regs[28]);
3792       tty->print_cr("r30 = 0x%016" PRIx64, regs[30]);
3793       tty->print_cr("r31 = 0x%016" PRIx64, regs[31]);
3794       BREAKPOINT;
3795     }
3796   }
3797   fatal("DEBUG MESSAGE: %s", msg);
3798 }
3799 
3800 RegSet MacroAssembler::call_clobbered_gp_registers() {
3801   RegSet regs = RegSet::range(r0, r17) - RegSet::of(rscratch1, rscratch2);
3802 #ifndef R18_RESERVED
3803   regs += r18_tls;
3804 #endif
3805   return regs;
3806 }
3807 
3808 void MacroAssembler::push_call_clobbered_registers_except(RegSet exclude) {
3809   int step = 4 * wordSize;
3810   push(call_clobbered_gp_registers() - exclude, sp);
3811   sub(sp, sp, step);
3812   mov(rscratch1, -step);
3813   // Push v0-v7, v16-v31.
3814   for (int i = 31; i>= 4; i -= 4) {
3815     if (i <= v7->encoding() || i >= v16->encoding())
3816       st1(as_FloatRegister(i-3), as_FloatRegister(i-2), as_FloatRegister(i-1),
3817           as_FloatRegister(i), T1D, Address(post(sp, rscratch1)));
3818   }
3819   st1(as_FloatRegister(0), as_FloatRegister(1), as_FloatRegister(2),
3820       as_FloatRegister(3), T1D, Address(sp));
3821 }
3822 
3823 void MacroAssembler::pop_call_clobbered_registers_except(RegSet exclude) {
3824   for (int i = 0; i < 32; i += 4) {
3825     if (i <= v7->encoding() || i >= v16->encoding())
3826       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3827           as_FloatRegister(i+3), T1D, Address(post(sp, 4 * wordSize)));
3828   }
3829 
3830   reinitialize_ptrue();
3831 
3832   pop(call_clobbered_gp_registers() - exclude, sp);
3833 }
3834 
3835 void MacroAssembler::push_CPU_state(bool save_vectors, bool use_sve,
3836                                     int sve_vector_size_in_bytes, int total_predicate_in_bytes) {
3837   push(RegSet::range(r0, r29), sp); // integer registers except lr & sp
3838   if (save_vectors && use_sve && sve_vector_size_in_bytes > 16) {
3839     sub(sp, sp, sve_vector_size_in_bytes * FloatRegister::number_of_registers);
3840     for (int i = 0; i < FloatRegister::number_of_registers; i++) {
3841       sve_str(as_FloatRegister(i), Address(sp, i));
3842     }
3843   } else {
3844     int step = (save_vectors ? 8 : 4) * wordSize;
3845     mov(rscratch1, -step);
3846     sub(sp, sp, step);
3847     for (int i = 28; i >= 4; i -= 4) {
3848       st1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3849           as_FloatRegister(i+3), save_vectors ? T2D : T1D, Address(post(sp, rscratch1)));
3850     }
3851     st1(v0, v1, v2, v3, save_vectors ? T2D : T1D, sp);
3852   }
3853   if (save_vectors && use_sve && total_predicate_in_bytes > 0) {
3854     sub(sp, sp, total_predicate_in_bytes);
3855     for (int i = 0; i < PRegister::number_of_registers; i++) {
3856       sve_str(as_PRegister(i), Address(sp, i));
3857     }
3858   }
3859 }
3860 
3861 void MacroAssembler::pop_CPU_state(bool restore_vectors, bool use_sve,
3862                                    int sve_vector_size_in_bytes, int total_predicate_in_bytes) {
3863   if (restore_vectors && use_sve && total_predicate_in_bytes > 0) {
3864     for (int i = PRegister::number_of_registers - 1; i >= 0; i--) {
3865       sve_ldr(as_PRegister(i), Address(sp, i));
3866     }
3867     add(sp, sp, total_predicate_in_bytes);
3868   }
3869   if (restore_vectors && use_sve && sve_vector_size_in_bytes > 16) {
3870     for (int i = FloatRegister::number_of_registers - 1; i >= 0; i--) {
3871       sve_ldr(as_FloatRegister(i), Address(sp, i));
3872     }
3873     add(sp, sp, sve_vector_size_in_bytes * FloatRegister::number_of_registers);
3874   } else {
3875     int step = (restore_vectors ? 8 : 4) * wordSize;
3876     for (int i = 0; i <= 28; i += 4)
3877       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3878           as_FloatRegister(i+3), restore_vectors ? T2D : T1D, Address(post(sp, step)));
3879   }
3880 
3881   // We may use predicate registers and rely on ptrue with SVE,
3882   // regardless of wide vector (> 8 bytes) used or not.
3883   if (use_sve) {
3884     reinitialize_ptrue();
3885   }
3886 
3887   // integer registers except lr & sp
3888   pop(RegSet::range(r0, r17), sp);
3889 #ifdef R18_RESERVED
3890   ldp(zr, r19, Address(post(sp, 2 * wordSize)));
3891   pop(RegSet::range(r20, r29), sp);
3892 #else
3893   pop(RegSet::range(r18_tls, r29), sp);
3894 #endif
3895 }
3896 
3897 /**
3898  * Helpers for multiply_to_len().
3899  */
3900 void MacroAssembler::add2_with_carry(Register final_dest_hi, Register dest_hi, Register dest_lo,
3901                                      Register src1, Register src2) {
3902   adds(dest_lo, dest_lo, src1);
3903   adc(dest_hi, dest_hi, zr);
3904   adds(dest_lo, dest_lo, src2);
3905   adc(final_dest_hi, dest_hi, zr);
3906 }
3907 
3908 // Generate an address from (r + r1 extend offset).  "size" is the
3909 // size of the operand.  The result may be in rscratch2.
3910 Address MacroAssembler::offsetted_address(Register r, Register r1,
3911                                           Address::extend ext, int offset, int size) {
3912   if (offset || (ext.shift() % size != 0)) {
3913     lea(rscratch2, Address(r, r1, ext));
3914     return Address(rscratch2, offset);
3915   } else {
3916     return Address(r, r1, ext);
3917   }
3918 }
3919 
3920 Address MacroAssembler::spill_address(int size, int offset, Register tmp)
3921 {
3922   assert(offset >= 0, "spill to negative address?");
3923   // Offset reachable ?
3924   //   Not aligned - 9 bits signed offset
3925   //   Aligned - 12 bits unsigned offset shifted
3926   Register base = sp;
3927   if ((offset & (size-1)) && offset >= (1<<8)) {
3928     add(tmp, base, offset & ((1<<12)-1));
3929     base = tmp;
3930     offset &= -1u<<12;
3931   }
3932 
3933   if (offset >= (1<<12) * size) {
3934     add(tmp, base, offset & (((1<<12)-1)<<12));
3935     base = tmp;
3936     offset &= ~(((1<<12)-1)<<12);
3937   }
3938 
3939   return Address(base, offset);
3940 }
3941 
3942 Address MacroAssembler::sve_spill_address(int sve_reg_size_in_bytes, int offset, Register tmp) {
3943   assert(offset >= 0, "spill to negative address?");
3944 
3945   Register base = sp;
3946 
3947   // An immediate offset in the range 0 to 255 which is multiplied
3948   // by the current vector or predicate register size in bytes.
3949   if (offset % sve_reg_size_in_bytes == 0 && offset < ((1<<8)*sve_reg_size_in_bytes)) {
3950     return Address(base, offset / sve_reg_size_in_bytes);
3951   }
3952 
3953   add(tmp, base, offset);
3954   return Address(tmp);
3955 }
3956 
3957 // Checks whether offset is aligned.
3958 // Returns true if it is, else false.
3959 bool MacroAssembler::merge_alignment_check(Register base,
3960                                            size_t size,
3961                                            int64_t cur_offset,
3962                                            int64_t prev_offset) const {
3963   if (AvoidUnalignedAccesses) {
3964     if (base == sp) {
3965       // Checks whether low offset if aligned to pair of registers.
3966       int64_t pair_mask = size * 2 - 1;
3967       int64_t offset = prev_offset > cur_offset ? cur_offset : prev_offset;
3968       return (offset & pair_mask) == 0;
3969     } else { // If base is not sp, we can't guarantee the access is aligned.
3970       return false;
3971     }
3972   } else {
3973     int64_t mask = size - 1;
3974     // Load/store pair instruction only supports element size aligned offset.
3975     return (cur_offset & mask) == 0 && (prev_offset & mask) == 0;
3976   }
3977 }
3978 
3979 // Checks whether current and previous loads/stores can be merged.
3980 // Returns true if it can be merged, else false.
3981 bool MacroAssembler::ldst_can_merge(Register rt,
3982                                     const Address &adr,
3983                                     size_t cur_size_in_bytes,
3984                                     bool is_store) const {
3985   address prev = pc() - NativeInstruction::instruction_size;
3986   address last = code()->last_merge_candidate();
3987 
3988   if (last == nullptr || !nativeInstruction_at(last)->is_Imm_LdSt()) {
3989     return false;
3990   }
3991 
3992   if (adr.getMode() != Address::base_plus_offset || prev != last) {
3993     return false;
3994   }
3995 
3996   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
3997   size_t prev_size_in_bytes = prev_ldst->size_in_bytes();
3998 
3999   assert(prev_size_in_bytes == 4 || prev_size_in_bytes == 8, "only supports 64/32bit merging.");
4000   assert(cur_size_in_bytes == 4 || cur_size_in_bytes == 8, "only supports 64/32bit merging.");
4001 
4002   if (cur_size_in_bytes != prev_size_in_bytes || is_store != prev_ldst->is_store()) {
4003     return false;
4004   }
4005 
4006   int64_t max_offset = 63 * prev_size_in_bytes;
4007   int64_t min_offset = -64 * prev_size_in_bytes;
4008 
4009   assert(prev_ldst->is_not_pre_post_index(), "pre-index or post-index is not supported to be merged.");
4010 
4011   // Only same base can be merged.
4012   if (adr.base() != prev_ldst->base()) {
4013     return false;
4014   }
4015 
4016   int64_t cur_offset = adr.offset();
4017   int64_t prev_offset = prev_ldst->offset();
4018   size_t diff = abs(cur_offset - prev_offset);
4019   if (diff != prev_size_in_bytes) {
4020     return false;
4021   }
4022 
4023   // Following cases can not be merged:
4024   // ldr x2, [x2, #8]
4025   // ldr x3, [x2, #16]
4026   // or:
4027   // ldr x2, [x3, #8]
4028   // ldr x2, [x3, #16]
4029   // If t1 and t2 is the same in "ldp t1, t2, [xn, #imm]", we'll get SIGILL.
4030   if (!is_store && (adr.base() == prev_ldst->target() || rt == prev_ldst->target())) {
4031     return false;
4032   }
4033 
4034   int64_t low_offset = prev_offset > cur_offset ? cur_offset : prev_offset;
4035   // Offset range must be in ldp/stp instruction's range.
4036   if (low_offset > max_offset || low_offset < min_offset) {
4037     return false;
4038   }
4039 
4040   if (merge_alignment_check(adr.base(), prev_size_in_bytes, cur_offset, prev_offset)) {
4041     return true;
4042   }
4043 
4044   return false;
4045 }
4046 
4047 // Merge current load/store with previous load/store into ldp/stp.
4048 void MacroAssembler::merge_ldst(Register rt,
4049                                 const Address &adr,
4050                                 size_t cur_size_in_bytes,
4051                                 bool is_store) {
4052 
4053   assert(ldst_can_merge(rt, adr, cur_size_in_bytes, is_store) == true, "cur and prev must be able to be merged.");
4054 
4055   Register rt_low, rt_high;
4056   address prev = pc() - NativeInstruction::instruction_size;
4057   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
4058 
4059   int64_t offset;
4060 
4061   if (adr.offset() < prev_ldst->offset()) {
4062     offset = adr.offset();
4063     rt_low = rt;
4064     rt_high = prev_ldst->target();
4065   } else {
4066     offset = prev_ldst->offset();
4067     rt_low = prev_ldst->target();
4068     rt_high = rt;
4069   }
4070 
4071   Address adr_p = Address(prev_ldst->base(), offset);
4072   // Overwrite previous generated binary.
4073   code_section()->set_end(prev);
4074 
4075   const size_t sz = prev_ldst->size_in_bytes();
4076   assert(sz == 8 || sz == 4, "only supports 64/32bit merging.");
4077   if (!is_store) {
4078     BLOCK_COMMENT("merged ldr pair");
4079     if (sz == 8) {
4080       ldp(rt_low, rt_high, adr_p);
4081     } else {
4082       ldpw(rt_low, rt_high, adr_p);
4083     }
4084   } else {
4085     BLOCK_COMMENT("merged str pair");
4086     if (sz == 8) {
4087       stp(rt_low, rt_high, adr_p);
4088     } else {
4089       stpw(rt_low, rt_high, adr_p);
4090     }
4091   }
4092 }
4093 
4094 /**
4095  * Multiply 64 bit by 64 bit first loop.
4096  */
4097 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
4098                                            Register y, Register y_idx, Register z,
4099                                            Register carry, Register product,
4100                                            Register idx, Register kdx) {
4101   //
4102   //  jlong carry, x[], y[], z[];
4103   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
4104   //    huge_128 product = y[idx] * x[xstart] + carry;
4105   //    z[kdx] = (jlong)product;
4106   //    carry  = (jlong)(product >>> 64);
4107   //  }
4108   //  z[xstart] = carry;
4109   //
4110 
4111   Label L_first_loop, L_first_loop_exit;
4112   Label L_one_x, L_one_y, L_multiply;
4113 
4114   subsw(xstart, xstart, 1);
4115   br(Assembler::MI, L_one_x);
4116 
4117   lea(rscratch1, Address(x, xstart, Address::lsl(LogBytesPerInt)));
4118   ldr(x_xstart, Address(rscratch1));
4119   ror(x_xstart, x_xstart, 32); // convert big-endian to little-endian
4120 
4121   bind(L_first_loop);
4122   subsw(idx, idx, 1);
4123   br(Assembler::MI, L_first_loop_exit);
4124   subsw(idx, idx, 1);
4125   br(Assembler::MI, L_one_y);
4126   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4127   ldr(y_idx, Address(rscratch1));
4128   ror(y_idx, y_idx, 32); // convert big-endian to little-endian
4129   bind(L_multiply);
4130 
4131   // AArch64 has a multiply-accumulate instruction that we can't use
4132   // here because it has no way to process carries, so we have to use
4133   // separate add and adc instructions.  Bah.
4134   umulh(rscratch1, x_xstart, y_idx); // x_xstart * y_idx -> rscratch1:product
4135   mul(product, x_xstart, y_idx);
4136   adds(product, product, carry);
4137   adc(carry, rscratch1, zr);   // x_xstart * y_idx + carry -> carry:product
4138 
4139   subw(kdx, kdx, 2);
4140   ror(product, product, 32); // back to big-endian
4141   str(product, offsetted_address(z, kdx, Address::uxtw(LogBytesPerInt), 0, BytesPerLong));
4142 
4143   b(L_first_loop);
4144 
4145   bind(L_one_y);
4146   ldrw(y_idx, Address(y,  0));
4147   b(L_multiply);
4148 
4149   bind(L_one_x);
4150   ldrw(x_xstart, Address(x,  0));
4151   b(L_first_loop);
4152 
4153   bind(L_first_loop_exit);
4154 }
4155 
4156 /**
4157  * Multiply 128 bit by 128. Unrolled inner loop.
4158  *
4159  */
4160 void MacroAssembler::multiply_128_x_128_loop(Register y, Register z,
4161                                              Register carry, Register carry2,
4162                                              Register idx, Register jdx,
4163                                              Register yz_idx1, Register yz_idx2,
4164                                              Register tmp, Register tmp3, Register tmp4,
4165                                              Register tmp6, Register product_hi) {
4166 
4167   //   jlong carry, x[], y[], z[];
4168   //   int kdx = ystart+1;
4169   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
4170   //     huge_128 tmp3 = (y[idx+1] * product_hi) + z[kdx+idx+1] + carry;
4171   //     jlong carry2  = (jlong)(tmp3 >>> 64);
4172   //     huge_128 tmp4 = (y[idx]   * product_hi) + z[kdx+idx] + carry2;
4173   //     carry  = (jlong)(tmp4 >>> 64);
4174   //     z[kdx+idx+1] = (jlong)tmp3;
4175   //     z[kdx+idx] = (jlong)tmp4;
4176   //   }
4177   //   idx += 2;
4178   //   if (idx > 0) {
4179   //     yz_idx1 = (y[idx] * product_hi) + z[kdx+idx] + carry;
4180   //     z[kdx+idx] = (jlong)yz_idx1;
4181   //     carry  = (jlong)(yz_idx1 >>> 64);
4182   //   }
4183   //
4184 
4185   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
4186 
4187   lsrw(jdx, idx, 2);
4188 
4189   bind(L_third_loop);
4190 
4191   subsw(jdx, jdx, 1);
4192   br(Assembler::MI, L_third_loop_exit);
4193   subw(idx, idx, 4);
4194 
4195   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4196 
4197   ldp(yz_idx2, yz_idx1, Address(rscratch1, 0));
4198 
4199   lea(tmp6, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4200 
4201   ror(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
4202   ror(yz_idx2, yz_idx2, 32);
4203 
4204   ldp(rscratch2, rscratch1, Address(tmp6, 0));
4205 
4206   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
4207   umulh(tmp4, product_hi, yz_idx1);
4208 
4209   ror(rscratch1, rscratch1, 32); // convert big-endian to little-endian
4210   ror(rscratch2, rscratch2, 32);
4211 
4212   mul(tmp, product_hi, yz_idx2);   //  yz_idx2 * product_hi -> carry2:tmp
4213   umulh(carry2, product_hi, yz_idx2);
4214 
4215   // propagate sum of both multiplications into carry:tmp4:tmp3
4216   adds(tmp3, tmp3, carry);
4217   adc(tmp4, tmp4, zr);
4218   adds(tmp3, tmp3, rscratch1);
4219   adcs(tmp4, tmp4, tmp);
4220   adc(carry, carry2, zr);
4221   adds(tmp4, tmp4, rscratch2);
4222   adc(carry, carry, zr);
4223 
4224   ror(tmp3, tmp3, 32); // convert little-endian to big-endian
4225   ror(tmp4, tmp4, 32);
4226   stp(tmp4, tmp3, Address(tmp6, 0));
4227 
4228   b(L_third_loop);
4229   bind (L_third_loop_exit);
4230 
4231   andw (idx, idx, 0x3);
4232   cbz(idx, L_post_third_loop_done);
4233 
4234   Label L_check_1;
4235   subsw(idx, idx, 2);
4236   br(Assembler::MI, L_check_1);
4237 
4238   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4239   ldr(yz_idx1, Address(rscratch1, 0));
4240   ror(yz_idx1, yz_idx1, 32);
4241   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
4242   umulh(tmp4, product_hi, yz_idx1);
4243   lea(rscratch1, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4244   ldr(yz_idx2, Address(rscratch1, 0));
4245   ror(yz_idx2, yz_idx2, 32);
4246 
4247   add2_with_carry(carry, tmp4, tmp3, carry, yz_idx2);
4248 
4249   ror(tmp3, tmp3, 32);
4250   str(tmp3, Address(rscratch1, 0));
4251 
4252   bind (L_check_1);
4253 
4254   andw (idx, idx, 0x1);
4255   subsw(idx, idx, 1);
4256   br(Assembler::MI, L_post_third_loop_done);
4257   ldrw(tmp4, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4258   mul(tmp3, tmp4, product_hi);  //  tmp4 * product_hi -> carry2:tmp3
4259   umulh(carry2, tmp4, product_hi);
4260   ldrw(tmp4, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4261 
4262   add2_with_carry(carry2, tmp3, tmp4, carry);
4263 
4264   strw(tmp3, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4265   extr(carry, carry2, tmp3, 32);
4266 
4267   bind(L_post_third_loop_done);
4268 }
4269 
4270 /**
4271  * Code for BigInteger::multiplyToLen() intrinsic.
4272  *
4273  * r0: x
4274  * r1: xlen
4275  * r2: y
4276  * r3: ylen
4277  * r4:  z
4278  * r5: tmp0
4279  * r10: tmp1
4280  * r11: tmp2
4281  * r12: tmp3
4282  * r13: tmp4
4283  * r14: tmp5
4284  * r15: tmp6
4285  * r16: tmp7
4286  *
4287  */
4288 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen,
4289                                      Register z, Register tmp0,
4290                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4,
4291                                      Register tmp5, Register tmp6, Register product_hi) {
4292 
4293   assert_different_registers(x, xlen, y, ylen, z, tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, product_hi);
4294 
4295   const Register idx = tmp1;
4296   const Register kdx = tmp2;
4297   const Register xstart = tmp3;
4298 
4299   const Register y_idx = tmp4;
4300   const Register carry = tmp5;
4301   const Register product  = xlen;
4302   const Register x_xstart = tmp0;
4303 
4304   // First Loop.
4305   //
4306   //  final static long LONG_MASK = 0xffffffffL;
4307   //  int xstart = xlen - 1;
4308   //  int ystart = ylen - 1;
4309   //  long carry = 0;
4310   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
4311   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
4312   //    z[kdx] = (int)product;
4313   //    carry = product >>> 32;
4314   //  }
4315   //  z[xstart] = (int)carry;
4316   //
4317 
4318   movw(idx, ylen);       // idx = ylen;
4319   addw(kdx, xlen, ylen); // kdx = xlen+ylen;
4320   mov(carry, zr);        // carry = 0;
4321 
4322   Label L_done;
4323 
4324   movw(xstart, xlen);
4325   subsw(xstart, xstart, 1);
4326   br(Assembler::MI, L_done);
4327 
4328   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
4329 
4330   Label L_second_loop;
4331   cbzw(kdx, L_second_loop);
4332 
4333   Label L_carry;
4334   subw(kdx, kdx, 1);
4335   cbzw(kdx, L_carry);
4336 
4337   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
4338   lsr(carry, carry, 32);
4339   subw(kdx, kdx, 1);
4340 
4341   bind(L_carry);
4342   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
4343 
4344   // Second and third (nested) loops.
4345   //
4346   // for (int i = xstart-1; i >= 0; i--) { // Second loop
4347   //   carry = 0;
4348   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
4349   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
4350   //                    (z[k] & LONG_MASK) + carry;
4351   //     z[k] = (int)product;
4352   //     carry = product >>> 32;
4353   //   }
4354   //   z[i] = (int)carry;
4355   // }
4356   //
4357   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = product_hi
4358 
4359   const Register jdx = tmp1;
4360 
4361   bind(L_second_loop);
4362   mov(carry, zr);                // carry = 0;
4363   movw(jdx, ylen);               // j = ystart+1
4364 
4365   subsw(xstart, xstart, 1);      // i = xstart-1;
4366   br(Assembler::MI, L_done);
4367 
4368   str(z, Address(pre(sp, -4 * wordSize)));
4369 
4370   Label L_last_x;
4371   lea(z, offsetted_address(z, xstart, Address::uxtw(LogBytesPerInt), 4, BytesPerInt)); // z = z + k - j
4372   subsw(xstart, xstart, 1);       // i = xstart-1;
4373   br(Assembler::MI, L_last_x);
4374 
4375   lea(rscratch1, Address(x, xstart, Address::uxtw(LogBytesPerInt)));
4376   ldr(product_hi, Address(rscratch1));
4377   ror(product_hi, product_hi, 32);  // convert big-endian to little-endian
4378 
4379   Label L_third_loop_prologue;
4380   bind(L_third_loop_prologue);
4381 
4382   str(ylen, Address(sp, wordSize));
4383   stp(x, xstart, Address(sp, 2 * wordSize));
4384   multiply_128_x_128_loop(y, z, carry, x, jdx, ylen, product,
4385                           tmp2, x_xstart, tmp3, tmp4, tmp6, product_hi);
4386   ldp(z, ylen, Address(post(sp, 2 * wordSize)));
4387   ldp(x, xlen, Address(post(sp, 2 * wordSize)));   // copy old xstart -> xlen
4388 
4389   addw(tmp3, xlen, 1);
4390   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
4391   subsw(tmp3, tmp3, 1);
4392   br(Assembler::MI, L_done);
4393 
4394   lsr(carry, carry, 32);
4395   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
4396   b(L_second_loop);
4397 
4398   // Next infrequent code is moved outside loops.
4399   bind(L_last_x);
4400   ldrw(product_hi, Address(x,  0));
4401   b(L_third_loop_prologue);
4402 
4403   bind(L_done);
4404 }
4405 
4406 // Code for BigInteger::mulAdd intrinsic
4407 // out     = r0
4408 // in      = r1
4409 // offset  = r2  (already out.length-offset)
4410 // len     = r3
4411 // k       = r4
4412 //
4413 // pseudo code from java implementation:
4414 // carry = 0;
4415 // offset = out.length-offset - 1;
4416 // for (int j=len-1; j >= 0; j--) {
4417 //     product = (in[j] & LONG_MASK) * kLong + (out[offset] & LONG_MASK) + carry;
4418 //     out[offset--] = (int)product;
4419 //     carry = product >>> 32;
4420 // }
4421 // return (int)carry;
4422 void MacroAssembler::mul_add(Register out, Register in, Register offset,
4423       Register len, Register k) {
4424     Label LOOP, END;
4425     // pre-loop
4426     cmp(len, zr); // cmp, not cbz/cbnz: to use condition twice => less branches
4427     csel(out, zr, out, Assembler::EQ);
4428     br(Assembler::EQ, END);
4429     add(in, in, len, LSL, 2); // in[j+1] address
4430     add(offset, out, offset, LSL, 2); // out[offset + 1] address
4431     mov(out, zr); // used to keep carry now
4432     BIND(LOOP);
4433     ldrw(rscratch1, Address(pre(in, -4)));
4434     madd(rscratch1, rscratch1, k, out);
4435     ldrw(rscratch2, Address(pre(offset, -4)));
4436     add(rscratch1, rscratch1, rscratch2);
4437     strw(rscratch1, Address(offset));
4438     lsr(out, rscratch1, 32);
4439     subs(len, len, 1);
4440     br(Assembler::NE, LOOP);
4441     BIND(END);
4442 }
4443 
4444 /**
4445  * Emits code to update CRC-32 with a byte value according to constants in table
4446  *
4447  * @param [in,out]crc   Register containing the crc.
4448  * @param [in]val       Register containing the byte to fold into the CRC.
4449  * @param [in]table     Register containing the table of crc constants.
4450  *
4451  * uint32_t crc;
4452  * val = crc_table[(val ^ crc) & 0xFF];
4453  * crc = val ^ (crc >> 8);
4454  *
4455  */
4456 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
4457   eor(val, val, crc);
4458   andr(val, val, 0xff);
4459   ldrw(val, Address(table, val, Address::lsl(2)));
4460   eor(crc, val, crc, Assembler::LSR, 8);
4461 }
4462 
4463 /**
4464  * Emits code to update CRC-32 with a 32-bit value according to tables 0 to 3
4465  *
4466  * @param [in,out]crc   Register containing the crc.
4467  * @param [in]v         Register containing the 32-bit to fold into the CRC.
4468  * @param [in]table0    Register containing table 0 of crc constants.
4469  * @param [in]table1    Register containing table 1 of crc constants.
4470  * @param [in]table2    Register containing table 2 of crc constants.
4471  * @param [in]table3    Register containing table 3 of crc constants.
4472  *
4473  * uint32_t crc;
4474  *   v = crc ^ v
4475  *   crc = table3[v&0xff]^table2[(v>>8)&0xff]^table1[(v>>16)&0xff]^table0[v>>24]
4476  *
4477  */
4478 void MacroAssembler::update_word_crc32(Register crc, Register v, Register tmp,
4479         Register table0, Register table1, Register table2, Register table3,
4480         bool upper) {
4481   eor(v, crc, v, upper ? LSR:LSL, upper ? 32:0);
4482   uxtb(tmp, v);
4483   ldrw(crc, Address(table3, tmp, Address::lsl(2)));
4484   ubfx(tmp, v, 8, 8);
4485   ldrw(tmp, Address(table2, tmp, Address::lsl(2)));
4486   eor(crc, crc, tmp);
4487   ubfx(tmp, v, 16, 8);
4488   ldrw(tmp, Address(table1, tmp, Address::lsl(2)));
4489   eor(crc, crc, tmp);
4490   ubfx(tmp, v, 24, 8);
4491   ldrw(tmp, Address(table0, tmp, Address::lsl(2)));
4492   eor(crc, crc, tmp);
4493 }
4494 
4495 void MacroAssembler::kernel_crc32_using_crypto_pmull(Register crc, Register buf,
4496         Register len, Register tmp0, Register tmp1, Register tmp2, Register tmp3) {
4497     Label CRC_by4_loop, CRC_by1_loop, CRC_less128, CRC_by128_pre, CRC_by32_loop, CRC_less32, L_exit;
4498     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2);
4499 
4500     subs(tmp0, len, 384);
4501     mvnw(crc, crc);
4502     br(Assembler::GE, CRC_by128_pre);
4503   BIND(CRC_less128);
4504     subs(len, len, 32);
4505     br(Assembler::GE, CRC_by32_loop);
4506   BIND(CRC_less32);
4507     adds(len, len, 32 - 4);
4508     br(Assembler::GE, CRC_by4_loop);
4509     adds(len, len, 4);
4510     br(Assembler::GT, CRC_by1_loop);
4511     b(L_exit);
4512 
4513   BIND(CRC_by32_loop);
4514     ldp(tmp0, tmp1, Address(buf));
4515     crc32x(crc, crc, tmp0);
4516     ldp(tmp2, tmp3, Address(buf, 16));
4517     crc32x(crc, crc, tmp1);
4518     add(buf, buf, 32);
4519     crc32x(crc, crc, tmp2);
4520     subs(len, len, 32);
4521     crc32x(crc, crc, tmp3);
4522     br(Assembler::GE, CRC_by32_loop);
4523     cmn(len, (u1)32);
4524     br(Assembler::NE, CRC_less32);
4525     b(L_exit);
4526 
4527   BIND(CRC_by4_loop);
4528     ldrw(tmp0, Address(post(buf, 4)));
4529     subs(len, len, 4);
4530     crc32w(crc, crc, tmp0);
4531     br(Assembler::GE, CRC_by4_loop);
4532     adds(len, len, 4);
4533     br(Assembler::LE, L_exit);
4534   BIND(CRC_by1_loop);
4535     ldrb(tmp0, Address(post(buf, 1)));
4536     subs(len, len, 1);
4537     crc32b(crc, crc, tmp0);
4538     br(Assembler::GT, CRC_by1_loop);
4539     b(L_exit);
4540 
4541   BIND(CRC_by128_pre);
4542     kernel_crc32_common_fold_using_crypto_pmull(crc, buf, len, tmp0, tmp1, tmp2,
4543       4*256*sizeof(juint) + 8*sizeof(juint));
4544     mov(crc, 0);
4545     crc32x(crc, crc, tmp0);
4546     crc32x(crc, crc, tmp1);
4547 
4548     cbnz(len, CRC_less128);
4549 
4550   BIND(L_exit);
4551     mvnw(crc, crc);
4552 }
4553 
4554 void MacroAssembler::kernel_crc32_using_crc32(Register crc, Register buf,
4555         Register len, Register tmp0, Register tmp1, Register tmp2,
4556         Register tmp3) {
4557     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
4558     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
4559 
4560     mvnw(crc, crc);
4561 
4562     subs(len, len, 128);
4563     br(Assembler::GE, CRC_by64_pre);
4564   BIND(CRC_less64);
4565     adds(len, len, 128-32);
4566     br(Assembler::GE, CRC_by32_loop);
4567   BIND(CRC_less32);
4568     adds(len, len, 32-4);
4569     br(Assembler::GE, CRC_by4_loop);
4570     adds(len, len, 4);
4571     br(Assembler::GT, CRC_by1_loop);
4572     b(L_exit);
4573 
4574   BIND(CRC_by32_loop);
4575     ldp(tmp0, tmp1, Address(post(buf, 16)));
4576     subs(len, len, 32);
4577     crc32x(crc, crc, tmp0);
4578     ldr(tmp2, Address(post(buf, 8)));
4579     crc32x(crc, crc, tmp1);
4580     ldr(tmp3, Address(post(buf, 8)));
4581     crc32x(crc, crc, tmp2);
4582     crc32x(crc, crc, tmp3);
4583     br(Assembler::GE, CRC_by32_loop);
4584     cmn(len, (u1)32);
4585     br(Assembler::NE, CRC_less32);
4586     b(L_exit);
4587 
4588   BIND(CRC_by4_loop);
4589     ldrw(tmp0, Address(post(buf, 4)));
4590     subs(len, len, 4);
4591     crc32w(crc, crc, tmp0);
4592     br(Assembler::GE, CRC_by4_loop);
4593     adds(len, len, 4);
4594     br(Assembler::LE, L_exit);
4595   BIND(CRC_by1_loop);
4596     ldrb(tmp0, Address(post(buf, 1)));
4597     subs(len, len, 1);
4598     crc32b(crc, crc, tmp0);
4599     br(Assembler::GT, CRC_by1_loop);
4600     b(L_exit);
4601 
4602   BIND(CRC_by64_pre);
4603     sub(buf, buf, 8);
4604     ldp(tmp0, tmp1, Address(buf, 8));
4605     crc32x(crc, crc, tmp0);
4606     ldr(tmp2, Address(buf, 24));
4607     crc32x(crc, crc, tmp1);
4608     ldr(tmp3, Address(buf, 32));
4609     crc32x(crc, crc, tmp2);
4610     ldr(tmp0, Address(buf, 40));
4611     crc32x(crc, crc, tmp3);
4612     ldr(tmp1, Address(buf, 48));
4613     crc32x(crc, crc, tmp0);
4614     ldr(tmp2, Address(buf, 56));
4615     crc32x(crc, crc, tmp1);
4616     ldr(tmp3, Address(pre(buf, 64)));
4617 
4618     b(CRC_by64_loop);
4619 
4620     align(CodeEntryAlignment);
4621   BIND(CRC_by64_loop);
4622     subs(len, len, 64);
4623     crc32x(crc, crc, tmp2);
4624     ldr(tmp0, Address(buf, 8));
4625     crc32x(crc, crc, tmp3);
4626     ldr(tmp1, Address(buf, 16));
4627     crc32x(crc, crc, tmp0);
4628     ldr(tmp2, Address(buf, 24));
4629     crc32x(crc, crc, tmp1);
4630     ldr(tmp3, Address(buf, 32));
4631     crc32x(crc, crc, tmp2);
4632     ldr(tmp0, Address(buf, 40));
4633     crc32x(crc, crc, tmp3);
4634     ldr(tmp1, Address(buf, 48));
4635     crc32x(crc, crc, tmp0);
4636     ldr(tmp2, Address(buf, 56));
4637     crc32x(crc, crc, tmp1);
4638     ldr(tmp3, Address(pre(buf, 64)));
4639     br(Assembler::GE, CRC_by64_loop);
4640 
4641     // post-loop
4642     crc32x(crc, crc, tmp2);
4643     crc32x(crc, crc, tmp3);
4644 
4645     sub(len, len, 64);
4646     add(buf, buf, 8);
4647     cmn(len, (u1)128);
4648     br(Assembler::NE, CRC_less64);
4649   BIND(L_exit);
4650     mvnw(crc, crc);
4651 }
4652 
4653 /**
4654  * @param crc   register containing existing CRC (32-bit)
4655  * @param buf   register pointing to input byte buffer (byte*)
4656  * @param len   register containing number of bytes
4657  * @param table register that will contain address of CRC table
4658  * @param tmp   scratch register
4659  */
4660 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len,
4661         Register table0, Register table1, Register table2, Register table3,
4662         Register tmp, Register tmp2, Register tmp3) {
4663   Label L_by16, L_by16_loop, L_by4, L_by4_loop, L_by1, L_by1_loop, L_exit;
4664 
4665   if (UseCryptoPmullForCRC32) {
4666       kernel_crc32_using_crypto_pmull(crc, buf, len, table0, table1, table2, table3);
4667       return;
4668   }
4669 
4670   if (UseCRC32) {
4671       kernel_crc32_using_crc32(crc, buf, len, table0, table1, table2, table3);
4672       return;
4673   }
4674 
4675     mvnw(crc, crc);
4676 
4677     {
4678       uint64_t offset;
4679       adrp(table0, ExternalAddress(StubRoutines::crc_table_addr()), offset);
4680       add(table0, table0, offset);
4681     }
4682     add(table1, table0, 1*256*sizeof(juint));
4683     add(table2, table0, 2*256*sizeof(juint));
4684     add(table3, table0, 3*256*sizeof(juint));
4685 
4686     { // Neon code start
4687       cmp(len, (u1)64);
4688       br(Assembler::LT, L_by16);
4689       eor(v16, T16B, v16, v16);
4690 
4691     Label L_fold;
4692 
4693       add(tmp, table0, 4*256*sizeof(juint)); // Point at the Neon constants
4694 
4695       ld1(v0, v1, T2D, post(buf, 32));
4696       ld1r(v4, T2D, post(tmp, 8));
4697       ld1r(v5, T2D, post(tmp, 8));
4698       ld1r(v6, T2D, post(tmp, 8));
4699       ld1r(v7, T2D, post(tmp, 8));
4700       mov(v16, S, 0, crc);
4701 
4702       eor(v0, T16B, v0, v16);
4703       sub(len, len, 64);
4704 
4705     BIND(L_fold);
4706       pmull(v22, T8H, v0, v5, T8B);
4707       pmull(v20, T8H, v0, v7, T8B);
4708       pmull(v23, T8H, v0, v4, T8B);
4709       pmull(v21, T8H, v0, v6, T8B);
4710 
4711       pmull2(v18, T8H, v0, v5, T16B);
4712       pmull2(v16, T8H, v0, v7, T16B);
4713       pmull2(v19, T8H, v0, v4, T16B);
4714       pmull2(v17, T8H, v0, v6, T16B);
4715 
4716       uzp1(v24, T8H, v20, v22);
4717       uzp2(v25, T8H, v20, v22);
4718       eor(v20, T16B, v24, v25);
4719 
4720       uzp1(v26, T8H, v16, v18);
4721       uzp2(v27, T8H, v16, v18);
4722       eor(v16, T16B, v26, v27);
4723 
4724       ushll2(v22, T4S, v20, T8H, 8);
4725       ushll(v20, T4S, v20, T4H, 8);
4726 
4727       ushll2(v18, T4S, v16, T8H, 8);
4728       ushll(v16, T4S, v16, T4H, 8);
4729 
4730       eor(v22, T16B, v23, v22);
4731       eor(v18, T16B, v19, v18);
4732       eor(v20, T16B, v21, v20);
4733       eor(v16, T16B, v17, v16);
4734 
4735       uzp1(v17, T2D, v16, v20);
4736       uzp2(v21, T2D, v16, v20);
4737       eor(v17, T16B, v17, v21);
4738 
4739       ushll2(v20, T2D, v17, T4S, 16);
4740       ushll(v16, T2D, v17, T2S, 16);
4741 
4742       eor(v20, T16B, v20, v22);
4743       eor(v16, T16B, v16, v18);
4744 
4745       uzp1(v17, T2D, v20, v16);
4746       uzp2(v21, T2D, v20, v16);
4747       eor(v28, T16B, v17, v21);
4748 
4749       pmull(v22, T8H, v1, v5, T8B);
4750       pmull(v20, T8H, v1, v7, T8B);
4751       pmull(v23, T8H, v1, v4, T8B);
4752       pmull(v21, T8H, v1, v6, T8B);
4753 
4754       pmull2(v18, T8H, v1, v5, T16B);
4755       pmull2(v16, T8H, v1, v7, T16B);
4756       pmull2(v19, T8H, v1, v4, T16B);
4757       pmull2(v17, T8H, v1, v6, T16B);
4758 
4759       ld1(v0, v1, T2D, post(buf, 32));
4760 
4761       uzp1(v24, T8H, v20, v22);
4762       uzp2(v25, T8H, v20, v22);
4763       eor(v20, T16B, v24, v25);
4764 
4765       uzp1(v26, T8H, v16, v18);
4766       uzp2(v27, T8H, v16, v18);
4767       eor(v16, T16B, v26, v27);
4768 
4769       ushll2(v22, T4S, v20, T8H, 8);
4770       ushll(v20, T4S, v20, T4H, 8);
4771 
4772       ushll2(v18, T4S, v16, T8H, 8);
4773       ushll(v16, T4S, v16, T4H, 8);
4774 
4775       eor(v22, T16B, v23, v22);
4776       eor(v18, T16B, v19, v18);
4777       eor(v20, T16B, v21, v20);
4778       eor(v16, T16B, v17, v16);
4779 
4780       uzp1(v17, T2D, v16, v20);
4781       uzp2(v21, T2D, v16, v20);
4782       eor(v16, T16B, v17, v21);
4783 
4784       ushll2(v20, T2D, v16, T4S, 16);
4785       ushll(v16, T2D, v16, T2S, 16);
4786 
4787       eor(v20, T16B, v22, v20);
4788       eor(v16, T16B, v16, v18);
4789 
4790       uzp1(v17, T2D, v20, v16);
4791       uzp2(v21, T2D, v20, v16);
4792       eor(v20, T16B, v17, v21);
4793 
4794       shl(v16, T2D, v28, 1);
4795       shl(v17, T2D, v20, 1);
4796 
4797       eor(v0, T16B, v0, v16);
4798       eor(v1, T16B, v1, v17);
4799 
4800       subs(len, len, 32);
4801       br(Assembler::GE, L_fold);
4802 
4803       mov(crc, 0);
4804       mov(tmp, v0, D, 0);
4805       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4806       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4807       mov(tmp, v0, D, 1);
4808       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4809       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4810       mov(tmp, v1, D, 0);
4811       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4812       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4813       mov(tmp, v1, D, 1);
4814       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4815       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4816 
4817       add(len, len, 32);
4818     } // Neon code end
4819 
4820   BIND(L_by16);
4821     subs(len, len, 16);
4822     br(Assembler::GE, L_by16_loop);
4823     adds(len, len, 16-4);
4824     br(Assembler::GE, L_by4_loop);
4825     adds(len, len, 4);
4826     br(Assembler::GT, L_by1_loop);
4827     b(L_exit);
4828 
4829   BIND(L_by4_loop);
4830     ldrw(tmp, Address(post(buf, 4)));
4831     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3);
4832     subs(len, len, 4);
4833     br(Assembler::GE, L_by4_loop);
4834     adds(len, len, 4);
4835     br(Assembler::LE, L_exit);
4836   BIND(L_by1_loop);
4837     subs(len, len, 1);
4838     ldrb(tmp, Address(post(buf, 1)));
4839     update_byte_crc32(crc, tmp, table0);
4840     br(Assembler::GT, L_by1_loop);
4841     b(L_exit);
4842 
4843     align(CodeEntryAlignment);
4844   BIND(L_by16_loop);
4845     subs(len, len, 16);
4846     ldp(tmp, tmp3, Address(post(buf, 16)));
4847     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4848     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4849     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, false);
4850     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, true);
4851     br(Assembler::GE, L_by16_loop);
4852     adds(len, len, 16-4);
4853     br(Assembler::GE, L_by4_loop);
4854     adds(len, len, 4);
4855     br(Assembler::GT, L_by1_loop);
4856   BIND(L_exit);
4857     mvnw(crc, crc);
4858 }
4859 
4860 void MacroAssembler::kernel_crc32c_using_crypto_pmull(Register crc, Register buf,
4861         Register len, Register tmp0, Register tmp1, Register tmp2, Register tmp3) {
4862     Label CRC_by4_loop, CRC_by1_loop, CRC_less128, CRC_by128_pre, CRC_by32_loop, CRC_less32, L_exit;
4863     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2);
4864 
4865     subs(tmp0, len, 384);
4866     br(Assembler::GE, CRC_by128_pre);
4867   BIND(CRC_less128);
4868     subs(len, len, 32);
4869     br(Assembler::GE, CRC_by32_loop);
4870   BIND(CRC_less32);
4871     adds(len, len, 32 - 4);
4872     br(Assembler::GE, CRC_by4_loop);
4873     adds(len, len, 4);
4874     br(Assembler::GT, CRC_by1_loop);
4875     b(L_exit);
4876 
4877   BIND(CRC_by32_loop);
4878     ldp(tmp0, tmp1, Address(buf));
4879     crc32cx(crc, crc, tmp0);
4880     ldr(tmp2, Address(buf, 16));
4881     crc32cx(crc, crc, tmp1);
4882     ldr(tmp3, Address(buf, 24));
4883     crc32cx(crc, crc, tmp2);
4884     add(buf, buf, 32);
4885     subs(len, len, 32);
4886     crc32cx(crc, crc, tmp3);
4887     br(Assembler::GE, CRC_by32_loop);
4888     cmn(len, (u1)32);
4889     br(Assembler::NE, CRC_less32);
4890     b(L_exit);
4891 
4892   BIND(CRC_by4_loop);
4893     ldrw(tmp0, Address(post(buf, 4)));
4894     subs(len, len, 4);
4895     crc32cw(crc, crc, tmp0);
4896     br(Assembler::GE, CRC_by4_loop);
4897     adds(len, len, 4);
4898     br(Assembler::LE, L_exit);
4899   BIND(CRC_by1_loop);
4900     ldrb(tmp0, Address(post(buf, 1)));
4901     subs(len, len, 1);
4902     crc32cb(crc, crc, tmp0);
4903     br(Assembler::GT, CRC_by1_loop);
4904     b(L_exit);
4905 
4906   BIND(CRC_by128_pre);
4907     kernel_crc32_common_fold_using_crypto_pmull(crc, buf, len, tmp0, tmp1, tmp2,
4908       4*256*sizeof(juint) + 8*sizeof(juint) + 0x50);
4909     mov(crc, 0);
4910     crc32cx(crc, crc, tmp0);
4911     crc32cx(crc, crc, tmp1);
4912 
4913     cbnz(len, CRC_less128);
4914 
4915   BIND(L_exit);
4916 }
4917 
4918 void MacroAssembler::kernel_crc32c_using_crc32c(Register crc, Register buf,
4919         Register len, Register tmp0, Register tmp1, Register tmp2,
4920         Register tmp3) {
4921     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
4922     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
4923 
4924     subs(len, len, 128);
4925     br(Assembler::GE, CRC_by64_pre);
4926   BIND(CRC_less64);
4927     adds(len, len, 128-32);
4928     br(Assembler::GE, CRC_by32_loop);
4929   BIND(CRC_less32);
4930     adds(len, len, 32-4);
4931     br(Assembler::GE, CRC_by4_loop);
4932     adds(len, len, 4);
4933     br(Assembler::GT, CRC_by1_loop);
4934     b(L_exit);
4935 
4936   BIND(CRC_by32_loop);
4937     ldp(tmp0, tmp1, Address(post(buf, 16)));
4938     subs(len, len, 32);
4939     crc32cx(crc, crc, tmp0);
4940     ldr(tmp2, Address(post(buf, 8)));
4941     crc32cx(crc, crc, tmp1);
4942     ldr(tmp3, Address(post(buf, 8)));
4943     crc32cx(crc, crc, tmp2);
4944     crc32cx(crc, crc, tmp3);
4945     br(Assembler::GE, CRC_by32_loop);
4946     cmn(len, (u1)32);
4947     br(Assembler::NE, CRC_less32);
4948     b(L_exit);
4949 
4950   BIND(CRC_by4_loop);
4951     ldrw(tmp0, Address(post(buf, 4)));
4952     subs(len, len, 4);
4953     crc32cw(crc, crc, tmp0);
4954     br(Assembler::GE, CRC_by4_loop);
4955     adds(len, len, 4);
4956     br(Assembler::LE, L_exit);
4957   BIND(CRC_by1_loop);
4958     ldrb(tmp0, Address(post(buf, 1)));
4959     subs(len, len, 1);
4960     crc32cb(crc, crc, tmp0);
4961     br(Assembler::GT, CRC_by1_loop);
4962     b(L_exit);
4963 
4964   BIND(CRC_by64_pre);
4965     sub(buf, buf, 8);
4966     ldp(tmp0, tmp1, Address(buf, 8));
4967     crc32cx(crc, crc, tmp0);
4968     ldr(tmp2, Address(buf, 24));
4969     crc32cx(crc, crc, tmp1);
4970     ldr(tmp3, Address(buf, 32));
4971     crc32cx(crc, crc, tmp2);
4972     ldr(tmp0, Address(buf, 40));
4973     crc32cx(crc, crc, tmp3);
4974     ldr(tmp1, Address(buf, 48));
4975     crc32cx(crc, crc, tmp0);
4976     ldr(tmp2, Address(buf, 56));
4977     crc32cx(crc, crc, tmp1);
4978     ldr(tmp3, Address(pre(buf, 64)));
4979 
4980     b(CRC_by64_loop);
4981 
4982     align(CodeEntryAlignment);
4983   BIND(CRC_by64_loop);
4984     subs(len, len, 64);
4985     crc32cx(crc, crc, tmp2);
4986     ldr(tmp0, Address(buf, 8));
4987     crc32cx(crc, crc, tmp3);
4988     ldr(tmp1, Address(buf, 16));
4989     crc32cx(crc, crc, tmp0);
4990     ldr(tmp2, Address(buf, 24));
4991     crc32cx(crc, crc, tmp1);
4992     ldr(tmp3, Address(buf, 32));
4993     crc32cx(crc, crc, tmp2);
4994     ldr(tmp0, Address(buf, 40));
4995     crc32cx(crc, crc, tmp3);
4996     ldr(tmp1, Address(buf, 48));
4997     crc32cx(crc, crc, tmp0);
4998     ldr(tmp2, Address(buf, 56));
4999     crc32cx(crc, crc, tmp1);
5000     ldr(tmp3, Address(pre(buf, 64)));
5001     br(Assembler::GE, CRC_by64_loop);
5002 
5003     // post-loop
5004     crc32cx(crc, crc, tmp2);
5005     crc32cx(crc, crc, tmp3);
5006 
5007     sub(len, len, 64);
5008     add(buf, buf, 8);
5009     cmn(len, (u1)128);
5010     br(Assembler::NE, CRC_less64);
5011   BIND(L_exit);
5012 }
5013 
5014 /**
5015  * @param crc   register containing existing CRC (32-bit)
5016  * @param buf   register pointing to input byte buffer (byte*)
5017  * @param len   register containing number of bytes
5018  * @param table register that will contain address of CRC table
5019  * @param tmp   scratch register
5020  */
5021 void MacroAssembler::kernel_crc32c(Register crc, Register buf, Register len,
5022         Register table0, Register table1, Register table2, Register table3,
5023         Register tmp, Register tmp2, Register tmp3) {
5024   if (UseCryptoPmullForCRC32) {
5025     kernel_crc32c_using_crypto_pmull(crc, buf, len, table0, table1, table2, table3);
5026   } else {
5027     kernel_crc32c_using_crc32c(crc, buf, len, table0, table1, table2, table3);
5028   }
5029 }
5030 
5031 void MacroAssembler::kernel_crc32_common_fold_using_crypto_pmull(Register crc, Register buf,
5032         Register len, Register tmp0, Register tmp1, Register tmp2, size_t table_offset) {
5033     Label CRC_by128_loop;
5034     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2);
5035 
5036     sub(len, len, 256);
5037     Register table = tmp0;
5038     {
5039       uint64_t offset;
5040       adrp(table, ExternalAddress(StubRoutines::crc_table_addr()), offset);
5041       add(table, table, offset);
5042     }
5043     add(table, table, table_offset);
5044 
5045     // Registers v0..v7 are used as data registers.
5046     // Registers v16..v31 are used as tmp registers.
5047     sub(buf, buf, 0x10);
5048     ldrq(v0, Address(buf, 0x10));
5049     ldrq(v1, Address(buf, 0x20));
5050     ldrq(v2, Address(buf, 0x30));
5051     ldrq(v3, Address(buf, 0x40));
5052     ldrq(v4, Address(buf, 0x50));
5053     ldrq(v5, Address(buf, 0x60));
5054     ldrq(v6, Address(buf, 0x70));
5055     ldrq(v7, Address(pre(buf, 0x80)));
5056 
5057     movi(v31, T4S, 0);
5058     mov(v31, S, 0, crc);
5059     eor(v0, T16B, v0, v31);
5060 
5061     // Register v16 contains constants from the crc table.
5062     ldrq(v16, Address(table));
5063     b(CRC_by128_loop);
5064 
5065     align(OptoLoopAlignment);
5066   BIND(CRC_by128_loop);
5067     pmull (v17,  T1Q, v0, v16, T1D);
5068     pmull2(v18, T1Q, v0, v16, T2D);
5069     ldrq(v0, Address(buf, 0x10));
5070     eor3(v0, T16B, v17,  v18, v0);
5071 
5072     pmull (v19, T1Q, v1, v16, T1D);
5073     pmull2(v20, T1Q, v1, v16, T2D);
5074     ldrq(v1, Address(buf, 0x20));
5075     eor3(v1, T16B, v19, v20, v1);
5076 
5077     pmull (v21, T1Q, v2, v16, T1D);
5078     pmull2(v22, T1Q, v2, v16, T2D);
5079     ldrq(v2, Address(buf, 0x30));
5080     eor3(v2, T16B, v21, v22, v2);
5081 
5082     pmull (v23, T1Q, v3, v16, T1D);
5083     pmull2(v24, T1Q, v3, v16, T2D);
5084     ldrq(v3, Address(buf, 0x40));
5085     eor3(v3, T16B, v23, v24, v3);
5086 
5087     pmull (v25, T1Q, v4, v16, T1D);
5088     pmull2(v26, T1Q, v4, v16, T2D);
5089     ldrq(v4, Address(buf, 0x50));
5090     eor3(v4, T16B, v25, v26, v4);
5091 
5092     pmull (v27, T1Q, v5, v16, T1D);
5093     pmull2(v28, T1Q, v5, v16, T2D);
5094     ldrq(v5, Address(buf, 0x60));
5095     eor3(v5, T16B, v27, v28, v5);
5096 
5097     pmull (v29, T1Q, v6, v16, T1D);
5098     pmull2(v30, T1Q, v6, v16, T2D);
5099     ldrq(v6, Address(buf, 0x70));
5100     eor3(v6, T16B, v29, v30, v6);
5101 
5102     // Reuse registers v23, v24.
5103     // Using them won't block the first instruction of the next iteration.
5104     pmull (v23, T1Q, v7, v16, T1D);
5105     pmull2(v24, T1Q, v7, v16, T2D);
5106     ldrq(v7, Address(pre(buf, 0x80)));
5107     eor3(v7, T16B, v23, v24, v7);
5108 
5109     subs(len, len, 0x80);
5110     br(Assembler::GE, CRC_by128_loop);
5111 
5112     // fold into 512 bits
5113     // Use v31 for constants because v16 can be still in use.
5114     ldrq(v31, Address(table, 0x10));
5115 
5116     pmull (v17,  T1Q, v0, v31, T1D);
5117     pmull2(v18, T1Q, v0, v31, T2D);
5118     eor3(v0, T16B, v17, v18, v4);
5119 
5120     pmull (v19, T1Q, v1, v31, T1D);
5121     pmull2(v20, T1Q, v1, v31, T2D);
5122     eor3(v1, T16B, v19, v20, v5);
5123 
5124     pmull (v21, T1Q, v2, v31, T1D);
5125     pmull2(v22, T1Q, v2, v31, T2D);
5126     eor3(v2, T16B, v21, v22, v6);
5127 
5128     pmull (v23, T1Q, v3, v31, T1D);
5129     pmull2(v24, T1Q, v3, v31, T2D);
5130     eor3(v3, T16B, v23, v24, v7);
5131 
5132     // fold into 128 bits
5133     // Use v17 for constants because v31 can be still in use.
5134     ldrq(v17, Address(table, 0x20));
5135     pmull (v25, T1Q, v0, v17, T1D);
5136     pmull2(v26, T1Q, v0, v17, T2D);
5137     eor3(v3, T16B, v3, v25, v26);
5138 
5139     // Use v18 for constants because v17 can be still in use.
5140     ldrq(v18, Address(table, 0x30));
5141     pmull (v27, T1Q, v1, v18, T1D);
5142     pmull2(v28, T1Q, v1, v18, T2D);
5143     eor3(v3, T16B, v3, v27, v28);
5144 
5145     // Use v19 for constants because v18 can be still in use.
5146     ldrq(v19, Address(table, 0x40));
5147     pmull (v29, T1Q, v2, v19, T1D);
5148     pmull2(v30, T1Q, v2, v19, T2D);
5149     eor3(v0, T16B, v3, v29, v30);
5150 
5151     add(len, len, 0x80);
5152     add(buf, buf, 0x10);
5153 
5154     mov(tmp0, v0, D, 0);
5155     mov(tmp1, v0, D, 1);
5156 }
5157 
5158 void MacroAssembler::addptr(const Address &dst, int32_t src) {
5159   Address adr;
5160   switch(dst.getMode()) {
5161   case Address::base_plus_offset:
5162     // This is the expected mode, although we allow all the other
5163     // forms below.
5164     adr = form_address(rscratch2, dst.base(), dst.offset(), LogBytesPerWord);
5165     break;
5166   default:
5167     lea(rscratch2, dst);
5168     adr = Address(rscratch2);
5169     break;
5170   }
5171   ldr(rscratch1, adr);
5172   add(rscratch1, rscratch1, src);
5173   str(rscratch1, adr);
5174 }
5175 
5176 void MacroAssembler::cmpptr(Register src1, Address src2) {
5177   uint64_t offset;
5178   adrp(rscratch1, src2, offset);
5179   ldr(rscratch1, Address(rscratch1, offset));
5180   cmp(src1, rscratch1);
5181 }
5182 
5183 void MacroAssembler::cmpoop(Register obj1, Register obj2) {
5184   cmp(obj1, obj2);
5185 }
5186 
5187 void MacroAssembler::load_method_holder_cld(Register rresult, Register rmethod) {
5188   load_method_holder(rresult, rmethod);
5189   ldr(rresult, Address(rresult, InstanceKlass::class_loader_data_offset()));
5190 }
5191 
5192 void MacroAssembler::load_method_holder(Register holder, Register method) {
5193   ldr(holder, Address(method, Method::const_offset()));                      // ConstMethod*
5194   ldr(holder, Address(holder, ConstMethod::constants_offset()));             // ConstantPool*
5195   ldr(holder, Address(holder, ConstantPool::pool_holder_offset()));          // InstanceKlass*
5196 }
5197 
5198 void MacroAssembler::load_metadata(Register dst, Register src) {
5199   if (UseCompactObjectHeaders) {
5200     load_narrow_klass_compact(dst, src);
5201   } else {
5202     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5203   }
5204 }
5205 
5206 // Loads the obj's Klass* into dst.
5207 // Preserves all registers (incl src, rscratch1 and rscratch2).
5208 // Input:
5209 // src - the oop we want to load the klass from.
5210 // dst - output narrow klass.
5211 void MacroAssembler::load_narrow_klass_compact(Register dst, Register src) {
5212   assert(UseCompactObjectHeaders, "expects UseCompactObjectHeaders");
5213   ldr(dst, Address(src, oopDesc::mark_offset_in_bytes()));
5214   lsr(dst, dst, markWord::klass_shift);
5215 }
5216 
5217 void MacroAssembler::load_klass(Register dst, Register src) {
5218   if (UseCompactObjectHeaders) {
5219     load_narrow_klass_compact(dst, src);
5220   } else {
5221     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5222   }
5223   decode_klass_not_null(dst);
5224 }
5225 
5226 void MacroAssembler::restore_cpu_control_state_after_jni(Register tmp1, Register tmp2) {
5227   if (RestoreMXCSROnJNICalls) {
5228     Label OK;
5229     get_fpcr(tmp1);
5230     mov(tmp2, tmp1);
5231     // Set FPCR to the state we need. We do want Round to Nearest. We
5232     // don't want non-IEEE rounding modes or floating-point traps.
5233     bfi(tmp1, zr, 22, 4); // Clear DN, FZ, and Rmode
5234     bfi(tmp1, zr, 8, 5);  // Clear exception-control bits (8-12)
5235     bfi(tmp1, zr, 0, 2);  // Clear AH:FIZ
5236     eor(tmp2, tmp1, tmp2);
5237     cbz(tmp2, OK);        // Only reset FPCR if it's wrong
5238     set_fpcr(tmp1);
5239     bind(OK);
5240   }
5241 }
5242 
5243 // ((OopHandle)result).resolve();
5244 void MacroAssembler::resolve_oop_handle(Register result, Register tmp1, Register tmp2) {
5245   // OopHandle::resolve is an indirection.
5246   access_load_at(T_OBJECT, IN_NATIVE, result, Address(result, 0), tmp1, tmp2);
5247 }
5248 
5249 // ((WeakHandle)result).resolve();
5250 void MacroAssembler::resolve_weak_handle(Register result, Register tmp1, Register tmp2) {
5251   assert_different_registers(result, tmp1, tmp2);
5252   Label resolved;
5253 
5254   // A null weak handle resolves to null.
5255   cbz(result, resolved);
5256 
5257   // Only 64 bit platforms support GCs that require a tmp register
5258   // WeakHandle::resolve is an indirection like jweak.
5259   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
5260                  result, Address(result), tmp1, tmp2);
5261   bind(resolved);
5262 }
5263 
5264 void MacroAssembler::load_mirror(Register dst, Register method, Register tmp1, Register tmp2) {
5265   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
5266   ldr(dst, Address(rmethod, Method::const_offset()));
5267   ldr(dst, Address(dst, ConstMethod::constants_offset()));
5268   ldr(dst, Address(dst, ConstantPool::pool_holder_offset()));
5269   ldr(dst, Address(dst, mirror_offset));
5270   resolve_oop_handle(dst, tmp1, tmp2);
5271 }
5272 
5273 void MacroAssembler::cmp_klass(Register obj, Register klass, Register tmp) {
5274   assert_different_registers(obj, klass, tmp);
5275   if (UseCompactObjectHeaders) {
5276     load_narrow_klass_compact(tmp, obj);
5277   } else {
5278     ldrw(tmp, Address(obj, oopDesc::klass_offset_in_bytes()));
5279   }
5280   if (CompressedKlassPointers::base() == nullptr) {
5281     cmp(klass, tmp, LSL, CompressedKlassPointers::shift());
5282     return;
5283   } else if (!AOTCodeCache::is_on_for_dump() &&
5284              ((uint64_t)CompressedKlassPointers::base() & 0xffffffff) == 0
5285              && CompressedKlassPointers::shift() == 0) {
5286     // Only the bottom 32 bits matter
5287     cmpw(klass, tmp);
5288     return;
5289   }
5290   decode_klass_not_null(tmp);
5291   cmp(klass, tmp);
5292 }
5293 
5294 void MacroAssembler::cmp_klasses_from_objects(Register obj1, Register obj2, Register tmp1, Register tmp2) {
5295   if (UseCompactObjectHeaders) {
5296     load_narrow_klass_compact(tmp1, obj1);
5297     load_narrow_klass_compact(tmp2, obj2);
5298   } else {
5299     ldrw(tmp1, Address(obj1, oopDesc::klass_offset_in_bytes()));
5300     ldrw(tmp2, Address(obj2, oopDesc::klass_offset_in_bytes()));
5301   }
5302   cmpw(tmp1, tmp2);
5303 }
5304 
5305 void MacroAssembler::load_prototype_header(Register dst, Register src) {
5306   load_klass(dst, src);
5307   ldr(dst, Address(dst, Klass::prototype_header_offset()));
5308 }
5309 
5310 void MacroAssembler::store_klass(Register dst, Register src) {
5311   // FIXME: Should this be a store release?  concurrent gcs assumes
5312   // klass length is valid if klass field is not null.
5313   assert(!UseCompactObjectHeaders, "not with compact headers");
5314   encode_klass_not_null(src);
5315   strw(src, Address(dst, oopDesc::klass_offset_in_bytes()));
5316 }
5317 
5318 void MacroAssembler::store_klass_gap(Register dst, Register src) {
5319   assert(!UseCompactObjectHeaders, "not with compact headers");
5320   // Store to klass gap in destination
5321   strw(src, Address(dst, oopDesc::klass_gap_offset_in_bytes()));
5322 }
5323 
5324 // Algorithm must match CompressedOops::encode.
5325 void MacroAssembler::encode_heap_oop(Register d, Register s) {
5326 #ifdef ASSERT
5327   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
5328 #endif
5329   verify_oop_msg(s, "broken oop in encode_heap_oop");
5330   if (CompressedOops::base() == nullptr) {
5331     if (CompressedOops::shift() != 0) {
5332       assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5333       lsr(d, s, LogMinObjAlignmentInBytes);
5334     } else {
5335       mov(d, s);
5336     }
5337   } else {
5338     subs(d, s, rheapbase);
5339     csel(d, d, zr, Assembler::HS);
5340     lsr(d, d, LogMinObjAlignmentInBytes);
5341 
5342     /*  Old algorithm: is this any worse?
5343     Label nonnull;
5344     cbnz(r, nonnull);
5345     sub(r, r, rheapbase);
5346     bind(nonnull);
5347     lsr(r, r, LogMinObjAlignmentInBytes);
5348     */
5349   }
5350 }
5351 
5352 void MacroAssembler::encode_heap_oop_not_null(Register r) {
5353 #ifdef ASSERT
5354   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
5355   if (CheckCompressedOops) {
5356     Label ok;
5357     cbnz(r, ok);
5358     stop("null oop passed to encode_heap_oop_not_null");
5359     bind(ok);
5360   }
5361 #endif
5362   verify_oop_msg(r, "broken oop in encode_heap_oop_not_null");
5363   if (CompressedOops::base() != nullptr) {
5364     sub(r, r, rheapbase);
5365   }
5366   if (CompressedOops::shift() != 0) {
5367     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5368     lsr(r, r, LogMinObjAlignmentInBytes);
5369   }
5370 }
5371 
5372 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
5373 #ifdef ASSERT
5374   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
5375   if (CheckCompressedOops) {
5376     Label ok;
5377     cbnz(src, ok);
5378     stop("null oop passed to encode_heap_oop_not_null2");
5379     bind(ok);
5380   }
5381 #endif
5382   verify_oop_msg(src, "broken oop in encode_heap_oop_not_null2");
5383 
5384   Register data = src;
5385   if (CompressedOops::base() != nullptr) {
5386     sub(dst, src, rheapbase);
5387     data = dst;
5388   }
5389   if (CompressedOops::shift() != 0) {
5390     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5391     lsr(dst, data, LogMinObjAlignmentInBytes);
5392     data = dst;
5393   }
5394   if (data == src)
5395     mov(dst, src);
5396 }
5397 
5398 void  MacroAssembler::decode_heap_oop(Register d, Register s) {
5399 #ifdef ASSERT
5400   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
5401 #endif
5402   if (CompressedOops::base() == nullptr) {
5403     if (CompressedOops::shift() != 0) {
5404       lsl(d, s, CompressedOops::shift());
5405     } else if (d != s) {
5406       mov(d, s);
5407     }
5408   } else {
5409     Label done;
5410     if (d != s)
5411       mov(d, s);
5412     cbz(s, done);
5413     add(d, rheapbase, s, Assembler::LSL, LogMinObjAlignmentInBytes);
5414     bind(done);
5415   }
5416   verify_oop_msg(d, "broken oop in decode_heap_oop");
5417 }
5418 
5419 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
5420   assert (UseCompressedOops, "should only be used for compressed headers");
5421   assert (Universe::heap() != nullptr, "java heap should be initialized");
5422   // Cannot assert, unverified entry point counts instructions (see .ad file)
5423   // vtableStubs also counts instructions in pd_code_size_limit.
5424   // Also do not verify_oop as this is called by verify_oop.
5425   if (CompressedOops::shift() != 0) {
5426     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5427     if (CompressedOops::base() != nullptr) {
5428       add(r, rheapbase, r, Assembler::LSL, LogMinObjAlignmentInBytes);
5429     } else {
5430       add(r, zr, r, Assembler::LSL, LogMinObjAlignmentInBytes);
5431     }
5432   } else {
5433     assert (CompressedOops::base() == nullptr, "sanity");
5434   }
5435 }
5436 
5437 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
5438   assert (UseCompressedOops, "should only be used for compressed headers");
5439   assert (Universe::heap() != nullptr, "java heap should be initialized");
5440   // Cannot assert, unverified entry point counts instructions (see .ad file)
5441   // vtableStubs also counts instructions in pd_code_size_limit.
5442   // Also do not verify_oop as this is called by verify_oop.
5443   if (CompressedOops::shift() != 0) {
5444     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5445     if (CompressedOops::base() != nullptr) {
5446       add(dst, rheapbase, src, Assembler::LSL, LogMinObjAlignmentInBytes);
5447     } else {
5448       add(dst, zr, src, Assembler::LSL, LogMinObjAlignmentInBytes);
5449     }
5450   } else {
5451     assert (CompressedOops::base() == nullptr, "sanity");
5452     if (dst != src) {
5453       mov(dst, src);
5454     }
5455   }
5456 }
5457 
5458 MacroAssembler::KlassDecodeMode MacroAssembler::_klass_decode_mode(KlassDecodeNone);
5459 
5460 MacroAssembler::KlassDecodeMode MacroAssembler::klass_decode_mode() {
5461   assert(Metaspace::initialized(), "metaspace not initialized yet");
5462   assert(_klass_decode_mode != KlassDecodeNone, "should be initialized");
5463   return _klass_decode_mode;
5464 }
5465 
5466 MacroAssembler::KlassDecodeMode  MacroAssembler::klass_decode_mode(address base, int shift, const size_t range) {
5467   // KlassDecodeMode shouldn't be set already.
5468   assert(_klass_decode_mode == KlassDecodeNone, "set once");
5469 
5470   if (base == nullptr) {
5471     return KlassDecodeZero;
5472   }
5473 
5474   if (operand_valid_for_logical_immediate(
5475         /*is32*/false, (uint64_t)base)) {
5476     const uint64_t range_mask = right_n_bits(log2i_ceil(range));
5477     if (((uint64_t)base & range_mask) == 0) {
5478       return KlassDecodeXor;
5479     }
5480   }
5481 
5482   const uint64_t shifted_base =
5483     (uint64_t)base >> shift;
5484   if ((shifted_base & 0xffff0000ffffffff) == 0) {
5485     return KlassDecodeMovk;
5486   }
5487 
5488   // No valid encoding.
5489   return KlassDecodeNone;
5490 }
5491 
5492 // Check if one of the above decoding modes will work for given base, shift and range.
5493 bool MacroAssembler::check_klass_decode_mode(address base, int shift, const size_t range) {
5494   return klass_decode_mode(base, shift, range) != KlassDecodeNone;
5495 }
5496 
5497 bool MacroAssembler::set_klass_decode_mode(address base, int shift, const size_t range) {
5498   _klass_decode_mode = klass_decode_mode(base, shift, range);
5499   return _klass_decode_mode != KlassDecodeNone;
5500 }
5501 
5502 static Register pick_different_tmp(Register dst, Register src) {
5503   auto tmps = RegSet::of(r0, r1, r2) - RegSet::of(src, dst);
5504   return *tmps.begin();
5505 }
5506 
5507 void MacroAssembler::encode_klass_not_null_for_aot(Register dst, Register src) {
5508   // we have to load the klass base from the AOT constants area but
5509   // not the shift because it is not allowed to change
5510   int shift = CompressedKlassPointers::shift();
5511   assert(shift >= 0 && shift <= CompressedKlassPointers::max_shift(), "unexpected compressed klass shift!");
5512   if (dst != src) {
5513     // we can load the base into dst, subtract it formthe src and shift down
5514     lea(dst, ExternalAddress(CompressedKlassPointers::base_addr()));
5515     ldr(dst, dst);
5516     sub(dst, src, dst);
5517     lsr(dst, dst, shift);
5518   } else {
5519     // we need an extra register in order to load the coop base
5520     Register tmp = pick_different_tmp(dst, src);
5521     RegSet regs = RegSet::of(tmp);
5522     push(regs, sp);
5523     lea(tmp, ExternalAddress(CompressedKlassPointers::base_addr()));
5524     ldr(tmp, tmp);
5525     sub(dst, src, tmp);
5526     lsr(dst, dst, shift);
5527     pop(regs, sp);
5528   }
5529 }
5530 
5531 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
5532   if (CompressedKlassPointers::base() != nullptr && AOTCodeCache::is_on_for_dump()) {
5533     encode_klass_not_null_for_aot(dst, src);
5534     return;
5535   }
5536 
5537   switch (klass_decode_mode()) {
5538   case KlassDecodeZero:
5539     if (CompressedKlassPointers::shift() != 0) {
5540       lsr(dst, src, CompressedKlassPointers::shift());
5541     } else {
5542       if (dst != src) mov(dst, src);
5543     }
5544     break;
5545 
5546   case KlassDecodeXor:
5547     if (CompressedKlassPointers::shift() != 0) {
5548       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
5549       lsr(dst, dst, CompressedKlassPointers::shift());
5550     } else {
5551       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
5552     }
5553     break;
5554 
5555   case KlassDecodeMovk:
5556     if (CompressedKlassPointers::shift() != 0) {
5557       ubfx(dst, src, CompressedKlassPointers::shift(), 32);
5558     } else {
5559       movw(dst, src);
5560     }
5561     break;
5562 
5563   case KlassDecodeNone:
5564     ShouldNotReachHere();
5565     break;
5566   }
5567 }
5568 
5569 void MacroAssembler::encode_klass_not_null(Register r) {
5570   encode_klass_not_null(r, r);
5571 }
5572 
5573 void MacroAssembler::decode_klass_not_null_for_aot(Register dst, Register src) {
5574   // we have to load the klass base from the AOT constants area but
5575   // not the shift because it is not allowed to change
5576   int shift = CompressedKlassPointers::shift();
5577   assert(shift >= 0 && shift <= CompressedKlassPointers::max_shift(), "unexpected compressed klass shift!");
5578   if (dst != src) {
5579     // we can load the base into dst then add the offset with a suitable shift
5580     lea(dst, ExternalAddress(CompressedKlassPointers::base_addr()));
5581     ldr(dst, dst);
5582     add(dst, dst, src, LSL,  shift);
5583   } else {
5584     // we need an extra register in order to load the coop base
5585     Register tmp = pick_different_tmp(dst, src);
5586     RegSet regs = RegSet::of(tmp);
5587     push(regs, sp);
5588     lea(tmp, ExternalAddress(CompressedKlassPointers::base_addr()));
5589     ldr(tmp, tmp);
5590     add(dst, tmp,  src, LSL,  shift);
5591     pop(regs, sp);
5592   }
5593 }
5594 
5595 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
5596   if (AOTCodeCache::is_on_for_dump()) {
5597     decode_klass_not_null_for_aot(dst, src);
5598     return;
5599   }
5600 
5601   switch (klass_decode_mode()) {
5602   case KlassDecodeZero:
5603     if (CompressedKlassPointers::shift() != 0) {
5604       lsl(dst, src, CompressedKlassPointers::shift());
5605     } else {
5606       if (dst != src) mov(dst, src);
5607     }
5608     break;
5609 
5610   case KlassDecodeXor:
5611     if (CompressedKlassPointers::shift() != 0) {
5612       lsl(dst, src, CompressedKlassPointers::shift());
5613       eor(dst, dst, (uint64_t)CompressedKlassPointers::base());
5614     } else {
5615       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
5616     }
5617     break;
5618 
5619   case KlassDecodeMovk: {
5620     const uint64_t shifted_base =
5621       (uint64_t)CompressedKlassPointers::base() >> CompressedKlassPointers::shift();
5622 
5623     if (dst != src) movw(dst, src);
5624     movk(dst, shifted_base >> 32, 32);
5625 
5626     if (CompressedKlassPointers::shift() != 0) {
5627       lsl(dst, dst, CompressedKlassPointers::shift());
5628     }
5629 
5630     break;
5631   }
5632 
5633   case KlassDecodeNone:
5634     ShouldNotReachHere();
5635     break;
5636   }
5637 }
5638 
5639 void  MacroAssembler::decode_klass_not_null(Register r) {
5640   decode_klass_not_null(r, r);
5641 }
5642 
5643 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
5644 #ifdef ASSERT
5645   {
5646     ThreadInVMfromUnknown tiv;
5647     assert (UseCompressedOops, "should only be used for compressed oops");
5648     assert (Universe::heap() != nullptr, "java heap should be initialized");
5649     assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5650     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
5651   }
5652 #endif
5653   int oop_index = oop_recorder()->find_index(obj);
5654   InstructionMark im(this);
5655   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5656   code_section()->relocate(inst_mark(), rspec);
5657   movz(dst, 0xDEAD, 16);
5658   movk(dst, 0xBEEF);
5659 }
5660 
5661 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
5662   assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5663   int index = oop_recorder()->find_index(k);
5664 
5665   InstructionMark im(this);
5666   RelocationHolder rspec = metadata_Relocation::spec(index);
5667   code_section()->relocate(inst_mark(), rspec);
5668   narrowKlass nk = CompressedKlassPointers::encode(k);
5669   movz(dst, (nk >> 16), 16);
5670   movk(dst, nk & 0xffff);
5671 }
5672 
5673 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators,
5674                                     Register dst, Address src,
5675                                     Register tmp1, Register tmp2) {
5676   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
5677   decorators = AccessInternal::decorator_fixup(decorators, type);
5678   bool as_raw = (decorators & AS_RAW) != 0;
5679   if (as_raw) {
5680     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, tmp2);
5681   } else {
5682     bs->load_at(this, decorators, type, dst, src, tmp1, tmp2);
5683   }
5684 }
5685 
5686 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators,
5687                                      Address dst, Register val,
5688                                      Register tmp1, Register tmp2, Register tmp3) {
5689   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
5690   decorators = AccessInternal::decorator_fixup(decorators, type);
5691   bool as_raw = (decorators & AS_RAW) != 0;
5692   if (as_raw) {
5693     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, val, tmp1, tmp2, tmp3);
5694   } else {
5695     bs->store_at(this, decorators, type, dst, val, tmp1, tmp2, tmp3);
5696   }
5697 }
5698 
5699 void MacroAssembler::flat_field_copy(DecoratorSet decorators, Register src, Register dst,
5700                                      Register inline_layout_info) {
5701   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5702   bs->flat_field_copy(this, decorators, src, dst, inline_layout_info);
5703 }
5704 
5705 void MacroAssembler::payload_offset(Register inline_klass, Register offset) {
5706   ldr(offset, Address(inline_klass, InlineKlass::adr_members_offset()));
5707   ldrw(offset, Address(offset, InlineKlass::payload_offset_offset()));
5708 }
5709 
5710 void MacroAssembler::payload_address(Register oop, Register data, Register inline_klass) {
5711   // ((address) (void*) o) + vk->payload_offset();
5712   Register offset = (data == oop) ? rscratch1 : data;
5713   payload_offset(inline_klass, offset);
5714   if (data == oop) {
5715     add(data, data, offset);
5716   } else {
5717     lea(data, Address(oop, offset));
5718   }
5719 }
5720 
5721 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
5722                                    Register tmp2, DecoratorSet decorators) {
5723   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2);
5724 }
5725 
5726 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
5727                                             Register tmp2, DecoratorSet decorators) {
5728   access_load_at(T_OBJECT, IN_HEAP | IS_NOT_NULL | decorators, dst, src, tmp1, tmp2);
5729 }
5730 
5731 void MacroAssembler::store_heap_oop(Address dst, Register val, Register tmp1,
5732                                     Register tmp2, Register tmp3, DecoratorSet decorators) {
5733   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, val, tmp1, tmp2, tmp3);
5734 }
5735 
5736 // Used for storing nulls.
5737 void MacroAssembler::store_heap_oop_null(Address dst) {
5738   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg, noreg);
5739 }
5740 
5741 Address MacroAssembler::allocate_metadata_address(Metadata* obj) {
5742   assert(oop_recorder() != nullptr, "this assembler needs a Recorder");
5743   int index = oop_recorder()->allocate_metadata_index(obj);
5744   RelocationHolder rspec = metadata_Relocation::spec(index);
5745   return Address((address)obj, rspec);
5746 }
5747 
5748 // Move an oop into a register.
5749 void MacroAssembler::movoop(Register dst, jobject obj) {
5750   int oop_index;
5751   if (obj == nullptr) {
5752     oop_index = oop_recorder()->allocate_oop_index(obj);
5753   } else {
5754 #ifdef ASSERT
5755     {
5756       ThreadInVMfromUnknown tiv;
5757       assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
5758     }
5759 #endif
5760     oop_index = oop_recorder()->find_index(obj);
5761   }
5762   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5763 
5764   if (BarrierSet::barrier_set()->barrier_set_assembler()->supports_instruction_patching()) {
5765     mov(dst, Address((address)obj, rspec));
5766   } else {
5767     address dummy = address(uintptr_t(pc()) & -wordSize); // A nearby aligned address
5768     ldr(dst, Address(dummy, rspec));
5769   }
5770 }
5771 
5772 // Move a metadata address into a register.
5773 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
5774   int oop_index;
5775   if (obj == nullptr) {
5776     oop_index = oop_recorder()->allocate_metadata_index(obj);
5777   } else {
5778     oop_index = oop_recorder()->find_index(obj);
5779   }
5780   RelocationHolder rspec = metadata_Relocation::spec(oop_index);
5781   mov(dst, Address((address)obj, rspec));
5782 }
5783 
5784 Address MacroAssembler::constant_oop_address(jobject obj) {
5785 #ifdef ASSERT
5786   {
5787     ThreadInVMfromUnknown tiv;
5788     assert(oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5789     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "not an oop");
5790   }
5791 #endif
5792   int oop_index = oop_recorder()->find_index(obj);
5793   return Address((address)obj, oop_Relocation::spec(oop_index));
5794 }
5795 
5796 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5797 void MacroAssembler::tlab_allocate(Register obj,
5798                                    Register var_size_in_bytes,
5799                                    int con_size_in_bytes,
5800                                    Register t1,
5801                                    Register t2,
5802                                    Label& slow_case) {
5803   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
5804   bs->tlab_allocate(this, obj, var_size_in_bytes, con_size_in_bytes, t1, t2, slow_case);
5805 }
5806 
5807 void MacroAssembler::verify_tlab() {
5808 #ifdef ASSERT
5809   if (UseTLAB && VerifyOops) {
5810     Label next, ok;
5811 
5812     stp(rscratch2, rscratch1, Address(pre(sp, -16)));
5813 
5814     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
5815     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
5816     cmp(rscratch2, rscratch1);
5817     br(Assembler::HS, next);
5818     STOP("assert(top >= start)");
5819     should_not_reach_here();
5820 
5821     bind(next);
5822     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
5823     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
5824     cmp(rscratch2, rscratch1);
5825     br(Assembler::HS, ok);
5826     STOP("assert(top <= end)");
5827     should_not_reach_here();
5828 
5829     bind(ok);
5830     ldp(rscratch2, rscratch1, Address(post(sp, 16)));
5831   }
5832 #endif
5833 }
5834 
5835 void MacroAssembler::inline_layout_info(Register holder_klass, Register index, Register layout_info) {
5836   assert_different_registers(holder_klass, index, layout_info);
5837   InlineLayoutInfo array[2];
5838   int size = (char*)&array[1] - (char*)&array[0]; // computing size of array elements
5839   if (is_power_of_2(size)) {
5840     lsl(index, index, log2i_exact(size)); // Scale index by power of 2
5841   } else {
5842     mov(layout_info, size);
5843     mul(index, index, layout_info); // Scale the index to be the entry index * array_element_size
5844   }
5845   ldr(layout_info, Address(holder_klass, InstanceKlass::inline_layout_info_array_offset()));
5846   add(layout_info, layout_info, Array<InlineLayoutInfo>::base_offset_in_bytes());
5847   lea(layout_info, Address(layout_info, index));
5848 }
5849 
5850 // Writes to stack successive pages until offset reached to check for
5851 // stack overflow + shadow pages.  This clobbers tmp.
5852 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
5853   assert_different_registers(tmp, size, rscratch1);
5854   mov(tmp, sp);
5855   // Bang stack for total size given plus shadow page size.
5856   // Bang one page at a time because large size can bang beyond yellow and
5857   // red zones.
5858   Label loop;
5859   mov(rscratch1, (int)os::vm_page_size());
5860   bind(loop);
5861   lea(tmp, Address(tmp, -(int)os::vm_page_size()));
5862   subsw(size, size, rscratch1);
5863   str(size, Address(tmp));
5864   br(Assembler::GT, loop);
5865 
5866   // Bang down shadow pages too.
5867   // At this point, (tmp-0) is the last address touched, so don't
5868   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
5869   // was post-decremented.)  Skip this address by starting at i=1, and
5870   // touch a few more pages below.  N.B.  It is important to touch all
5871   // the way down to and including i=StackShadowPages.
5872   for (int i = 0; i < (int)(StackOverflow::stack_shadow_zone_size() / (int)os::vm_page_size()) - 1; i++) {
5873     // this could be any sized move but this is can be a debugging crumb
5874     // so the bigger the better.
5875     lea(tmp, Address(tmp, -(int)os::vm_page_size()));
5876     str(size, Address(tmp));
5877   }
5878 }
5879 
5880 // Move the address of the polling page into dest.
5881 void MacroAssembler::get_polling_page(Register dest, relocInfo::relocType rtype) {
5882   ldr(dest, Address(rthread, JavaThread::polling_page_offset()));
5883 }
5884 
5885 // Read the polling page.  The address of the polling page must
5886 // already be in r.
5887 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
5888   address mark;
5889   {
5890     InstructionMark im(this);
5891     code_section()->relocate(inst_mark(), rtype);
5892     ldrw(zr, Address(r, 0));
5893     mark = inst_mark();
5894   }
5895   verify_cross_modify_fence_not_required();
5896   return mark;
5897 }
5898 
5899 void MacroAssembler::adrp(Register reg1, const Address &dest, uint64_t &byte_offset) {
5900   uint64_t low_page = (uint64_t)CodeCache::low_bound() >> 12;
5901   uint64_t high_page = (uint64_t)(CodeCache::high_bound()-1) >> 12;
5902   uint64_t dest_page = (uint64_t)dest.target() >> 12;
5903   int64_t offset_low = dest_page - low_page;
5904   int64_t offset_high = dest_page - high_page;
5905 
5906   assert(is_valid_AArch64_address(dest.target()), "bad address");
5907   assert(dest.getMode() == Address::literal, "ADRP must be applied to a literal address");
5908 
5909   InstructionMark im(this);
5910   code_section()->relocate(inst_mark(), dest.rspec());
5911   // 8143067: Ensure that the adrp can reach the dest from anywhere within
5912   // the code cache so that if it is relocated we know it will still reach
5913   if (offset_high >= -(1<<20) && offset_low < (1<<20)) {
5914     _adrp(reg1, dest.target());
5915   } else {
5916     uint64_t target = (uint64_t)dest.target();
5917     uint64_t adrp_target
5918       = (target & 0xffffffffULL) | ((uint64_t)pc() & 0xffff00000000ULL);
5919 
5920     _adrp(reg1, (address)adrp_target);
5921     movk(reg1, target >> 32, 32);
5922   }
5923   byte_offset = (uint64_t)dest.target() & 0xfff;
5924 }
5925 
5926 void MacroAssembler::load_byte_map_base(Register reg) {
5927 #if INCLUDE_CDS
5928   if (AOTCodeCache::is_on_for_dump()) {
5929     address byte_map_base_adr = AOTRuntimeConstants::card_table_base_address();
5930     lea(reg, ExternalAddress(byte_map_base_adr));
5931     ldr(reg, Address(reg));
5932     return;
5933   }
5934 #endif
5935   CardTableBarrierSet* ctbs = CardTableBarrierSet::barrier_set();
5936 
5937   // Strictly speaking the card table base isn't an address at all, and it might
5938   // even be negative. It is thus materialised as a constant.
5939   mov(reg, (uint64_t)ctbs->card_table_base_const());
5940 }
5941 
5942 void MacroAssembler::load_aotrc_address(Register reg, address a) {
5943 #if INCLUDE_CDS
5944   assert(AOTRuntimeConstants::contains(a), "address out of range for data area");
5945   if (AOTCodeCache::is_on_for_dump()) {
5946     // all aotrc field addresses should be registered in the AOTCodeCache address table
5947     lea(reg, ExternalAddress(a));
5948   } else {
5949     mov(reg, (uint64_t)a);
5950   }
5951 #else
5952   ShouldNotReachHere();
5953 #endif
5954 }
5955 
5956 #ifdef ASSERT
5957 void MacroAssembler::build_frame(int framesize) {
5958   build_frame(framesize, false);
5959 }
5960 #endif
5961 
5962 void MacroAssembler::build_frame(int framesize DEBUG_ONLY(COMMA bool zap_rfp_lr_spills)) {
5963   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
5964   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
5965   protect_return_address();
5966   if (framesize < ((1 << 9) + 2 * wordSize)) {
5967     sub(sp, sp, framesize);
5968     if (DEBUG_ONLY(zap_rfp_lr_spills ||) false) {
5969       mov_immediate64(rscratch1, ((uint64_t)badRegWordVal) << 32 | (uint64_t)badRegWordVal);
5970       stp(rscratch1, rscratch1, Address(sp, framesize - 2 * wordSize));
5971     } else {
5972       stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
5973     }
5974     if (PreserveFramePointer) add(rfp, sp, framesize - 2 * wordSize);
5975   } else {
5976     if (DEBUG_ONLY(zap_rfp_lr_spills ||) false) {
5977       mov_immediate64(rscratch1, ((uint64_t)badRegWordVal) << 32 | (uint64_t)badRegWordVal);
5978       stp(rscratch1, rscratch1, Address(pre(sp, -2 * wordSize)));
5979     } else {
5980       stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
5981     }
5982     if (PreserveFramePointer) mov(rfp, sp);
5983     if (framesize < ((1 << 12) + 2 * wordSize))
5984       sub(sp, sp, framesize - 2 * wordSize);
5985     else {
5986       mov(rscratch1, framesize - 2 * wordSize);
5987       sub(sp, sp, rscratch1);
5988     }
5989   }
5990   verify_cross_modify_fence_not_required();
5991 }
5992 
5993 void MacroAssembler::remove_frame(int framesize) {
5994   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
5995   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
5996   if (framesize < ((1 << 9) + 2 * wordSize)) {
5997     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
5998     add(sp, sp, framesize);
5999   } else {
6000     if (framesize < ((1 << 12) + 2 * wordSize))
6001       add(sp, sp, framesize - 2 * wordSize);
6002     else {
6003       mov(rscratch1, framesize - 2 * wordSize);
6004       add(sp, sp, rscratch1);
6005     }
6006     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
6007   }
6008   authenticate_return_address();
6009 }
6010 
6011 void MacroAssembler::remove_frame(int initial_framesize, bool needs_stack_repair) {
6012   if (needs_stack_repair) {
6013     // The method has a scalarized entry point (where fields of value object arguments
6014     // are passed through registers and stack), and a non-scalarized entry point (where
6015     // value object arguments are given as oops). The non-scalarized entry point will
6016     // first load each field of value object arguments and store them in registers and on
6017     // the stack in a way compatible with the scalarized entry point. To do so, some extra
6018     // stack space might be reserved (if argument registers are not enough). On leaving the
6019     // method, this space must be freed.
6020     //
6021     // In case we used the non-scalarized entry point the stack looks like this:
6022     //
6023     // | Arguments from caller     |
6024     // |---------------------------|  <-- caller's SP
6025     // | Saved LR #1               |
6026     // | Saved FP #1               |
6027     // |---------------------------|
6028     // | Extension space for       |
6029     // |   inline arg (un)packing  |
6030     // |---------------------------|  <-- start of this method's frame
6031     // | Saved LR #2               |
6032     // | Saved FP #2               |
6033     // |---------------------------|  <-- FP (with -XX:+PreserveFramePointer)
6034     // | sp_inc                    |
6035     // | method locals             |
6036     // |---------------------------|  <-- SP
6037     //
6038     // There are two copies of FP and LR on the stack. They will be identical at
6039     // first, but that can change.
6040     // If the caller has been deoptimized, LR #1 will be patched to point at the
6041     // deopt blob, and LR #2 will still point into the old method.
6042     // If the saved FP (x29) was not used as the frame pointer, but to store an
6043     // oop, the GC will be aware only of FP #1 as the spilled location of x29 and
6044     // will fix only this one. Overall, FP/LR #2 are not reliable and are simply
6045     // needed to add space between the extension space and the locals, as there
6046     // would be between the real arguments and the locals if we don't need to
6047     // do unpacking (from the scalarized entry point).
6048     //
6049     // When restoring, one must then load FP #1 into x29, and LR #1 into x30,
6050     // while keeping in mind that from the scalarized entry point, there will be
6051     // only one copy of each. Indeed, in the case we used the scalarized calling
6052     // convention, the stack looks like this:
6053     //
6054     // | Arguments from caller     |
6055     // |---------------------------|  <-- caller's SP / start of this method's frame
6056     // | Saved LR                  |
6057     // | Saved FP                  |
6058     // |---------------------------|  <-- FP (with -XX:+PreserveFramePointer)
6059     // | sp_inc                    |
6060     // | method locals             |
6061     // |---------------------------|  <-- SP
6062     //
6063     // The sp_inc stack slot holds the total size of the frame including the
6064     // extension space minus two words for the saved FP and LR. That is how to
6065     // find FP/LR #1. This size is expressed in bytes. Be careful when using it
6066     // from C++ in pointer arithmetic; you might need to divide it by wordSize.
6067     //
6068     // One can find sp_inc since the start the method's frame is SP + initial_framesize.
6069 
6070     int sp_inc_offset = initial_framesize - 3 * wordSize;  // Immediately below saved LR and FP
6071 
6072     ldr(rscratch1, Address(sp, sp_inc_offset));
6073     add(sp, sp, rscratch1);
6074     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
6075   } else {
6076     remove_frame(initial_framesize);
6077   }
6078 }
6079 
6080 void MacroAssembler::save_stack_increment(int sp_inc, int frame_size) {
6081   int real_frame_size = frame_size + sp_inc;
6082   assert(sp_inc == 0 || sp_inc > 2*wordSize, "invalid sp_inc value");
6083   assert(real_frame_size >= 2*wordSize, "frame size must include FP/LR space");
6084   assert((real_frame_size & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
6085 
6086   int sp_inc_offset = frame_size - 3 * wordSize;  // Immediately below saved LR and FP
6087 
6088   // Subtract two words for the saved FP and LR as these will be popped
6089   // separately. See remove_frame above.
6090   mov(rscratch1, real_frame_size - 2*wordSize);
6091   str(rscratch1, Address(sp, sp_inc_offset));
6092 }
6093 
6094 // This method counts leading positive bytes (highest bit not set) in provided byte array
6095 address MacroAssembler::count_positives(Register ary1, Register len, Register result) {
6096     // Simple and most common case of aligned small array which is not at the
6097     // end of memory page is placed here. All other cases are in stub.
6098     Label LOOP, END, STUB, STUB_LONG, SET_RESULT, DONE;
6099     const uint64_t UPPER_BIT_MASK=0x8080808080808080;
6100     assert_different_registers(ary1, len, result);
6101 
6102     mov(result, len);
6103     cmpw(len, 0);
6104     br(LE, DONE);
6105     cmpw(len, 4 * wordSize);
6106     br(GE, STUB_LONG); // size > 32 then go to stub
6107 
6108     int shift = 64 - exact_log2(os::vm_page_size());
6109     lsl(rscratch1, ary1, shift);
6110     mov(rscratch2, (size_t)(4 * wordSize) << shift);
6111     adds(rscratch2, rscratch1, rscratch2);  // At end of page?
6112     br(CS, STUB); // at the end of page then go to stub
6113     subs(len, len, wordSize);
6114     br(LT, END);
6115 
6116   BIND(LOOP);
6117     ldr(rscratch1, Address(post(ary1, wordSize)));
6118     tst(rscratch1, UPPER_BIT_MASK);
6119     br(NE, SET_RESULT);
6120     subs(len, len, wordSize);
6121     br(GE, LOOP);
6122     cmpw(len, -wordSize);
6123     br(EQ, DONE);
6124 
6125   BIND(END);
6126     ldr(rscratch1, Address(ary1));
6127     sub(rscratch2, zr, len, LSL, 3); // LSL 3 is to get bits from bytes
6128     lslv(rscratch1, rscratch1, rscratch2);
6129     tst(rscratch1, UPPER_BIT_MASK);
6130     br(NE, SET_RESULT);
6131     b(DONE);
6132 
6133   BIND(STUB);
6134     RuntimeAddress count_pos = RuntimeAddress(StubRoutines::aarch64::count_positives());
6135     assert(count_pos.target() != nullptr, "count_positives stub has not been generated");
6136     address tpc1 = trampoline_call(count_pos);
6137     if (tpc1 == nullptr) {
6138       DEBUG_ONLY(reset_labels(STUB_LONG, SET_RESULT, DONE));
6139       postcond(pc() == badAddress);
6140       return nullptr;
6141     }
6142     b(DONE);
6143 
6144   BIND(STUB_LONG);
6145     RuntimeAddress count_pos_long = RuntimeAddress(StubRoutines::aarch64::count_positives_long());
6146     assert(count_pos_long.target() != nullptr, "count_positives_long stub has not been generated");
6147     address tpc2 = trampoline_call(count_pos_long);
6148     if (tpc2 == nullptr) {
6149       DEBUG_ONLY(reset_labels(SET_RESULT, DONE));
6150       postcond(pc() == badAddress);
6151       return nullptr;
6152     }
6153     b(DONE);
6154 
6155   BIND(SET_RESULT);
6156 
6157     add(len, len, wordSize);
6158     sub(result, result, len);
6159 
6160   BIND(DONE);
6161   postcond(pc() != badAddress);
6162   return pc();
6163 }
6164 
6165 // Clobbers: rscratch1, rscratch2, rflags
6166 // May also clobber v0-v7 when (!UseSimpleArrayEquals && UseSIMDForArrayEquals)
6167 address MacroAssembler::arrays_equals(Register a1, Register a2, Register tmp3,
6168                                       Register tmp4, Register tmp5, Register result,
6169                                       Register cnt1, int elem_size) {
6170   Label DONE, SAME;
6171   Register tmp1 = rscratch1;
6172   Register tmp2 = rscratch2;
6173   int elem_per_word = wordSize/elem_size;
6174   int log_elem_size = exact_log2(elem_size);
6175   int klass_offset  = arrayOopDesc::klass_offset_in_bytes();
6176   int length_offset = arrayOopDesc::length_offset_in_bytes();
6177   int base_offset
6178     = arrayOopDesc::base_offset_in_bytes(elem_size == 2 ? T_CHAR : T_BYTE);
6179   // When the length offset is not aligned to 8 bytes,
6180   // then we align it down. This is valid because the new
6181   // offset will always be the klass which is the same
6182   // for type arrays.
6183   int start_offset = align_down(length_offset, BytesPerWord);
6184   int extra_length = base_offset - start_offset;
6185   assert(start_offset == length_offset || start_offset == klass_offset,
6186          "start offset must be 8-byte-aligned or be the klass offset");
6187   assert(base_offset != start_offset, "must include the length field");
6188   extra_length = extra_length / elem_size; // We count in elements, not bytes.
6189   int stubBytesThreshold = 3 * 64 + (UseSIMDForArrayEquals ? 0 : 16);
6190 
6191   assert(elem_size == 1 || elem_size == 2, "must be char or byte");
6192   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
6193 
6194 #ifndef PRODUCT
6195   {
6196     const char kind = (elem_size == 2) ? 'U' : 'L';
6197     char comment[64];
6198     os::snprintf_checked(comment, sizeof comment, "array_equals%c{", kind);
6199     BLOCK_COMMENT(comment);
6200   }
6201 #endif
6202 
6203   // if (a1 == a2)
6204   //     return true;
6205   cmpoop(a1, a2); // May have read barriers for a1 and a2.
6206   br(EQ, SAME);
6207 
6208   if (UseSimpleArrayEquals) {
6209     Label NEXT_WORD, SHORT, TAIL03, TAIL01, A_MIGHT_BE_NULL, A_IS_NOT_NULL;
6210     // if (a1 == nullptr || a2 == nullptr)
6211     //     return false;
6212     // a1 & a2 == 0 means (some-pointer is null) or
6213     // (very-rare-or-even-probably-impossible-pointer-values)
6214     // so, we can save one branch in most cases
6215     tst(a1, a2);
6216     mov(result, false);
6217     br(EQ, A_MIGHT_BE_NULL);
6218     // if (a1.length != a2.length)
6219     //      return false;
6220     bind(A_IS_NOT_NULL);
6221     ldrw(cnt1, Address(a1, length_offset));
6222     ldrw(tmp5, Address(a2, length_offset));
6223     cmp(cnt1, tmp5);
6224     br(NE, DONE); // If lengths differ, return false
6225     // Increase loop counter by diff between base- and actual start-offset.
6226     addw(cnt1, cnt1, extra_length);
6227     lea(a1, Address(a1, start_offset));
6228     lea(a2, Address(a2, start_offset));
6229     // Check for short strings, i.e. smaller than wordSize.
6230     subs(cnt1, cnt1, elem_per_word);
6231     br(Assembler::LT, SHORT);
6232     // Main 8 byte comparison loop.
6233     bind(NEXT_WORD); {
6234       ldr(tmp1, Address(post(a1, wordSize)));
6235       ldr(tmp2, Address(post(a2, wordSize)));
6236       subs(cnt1, cnt1, elem_per_word);
6237       eor(tmp5, tmp1, tmp2);
6238       cbnz(tmp5, DONE);
6239     } br(GT, NEXT_WORD);
6240     // Last longword.  In the case where length == 4 we compare the
6241     // same longword twice, but that's still faster than another
6242     // conditional branch.
6243     // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
6244     // length == 4.
6245     if (log_elem_size > 0)
6246       lsl(cnt1, cnt1, log_elem_size);
6247     ldr(tmp3, Address(a1, cnt1));
6248     ldr(tmp4, Address(a2, cnt1));
6249     eor(tmp5, tmp3, tmp4);
6250     cbnz(tmp5, DONE);
6251     b(SAME);
6252     bind(A_MIGHT_BE_NULL);
6253     // in case both a1 and a2 are not-null, proceed with loads
6254     cbz(a1, DONE);
6255     cbz(a2, DONE);
6256     b(A_IS_NOT_NULL);
6257     bind(SHORT);
6258 
6259     tbz(cnt1, 2 - log_elem_size, TAIL03); // 0-7 bytes left.
6260     {
6261       ldrw(tmp1, Address(post(a1, 4)));
6262       ldrw(tmp2, Address(post(a2, 4)));
6263       eorw(tmp5, tmp1, tmp2);
6264       cbnzw(tmp5, DONE);
6265     }
6266     bind(TAIL03);
6267     tbz(cnt1, 1 - log_elem_size, TAIL01); // 0-3 bytes left.
6268     {
6269       ldrh(tmp3, Address(post(a1, 2)));
6270       ldrh(tmp4, Address(post(a2, 2)));
6271       eorw(tmp5, tmp3, tmp4);
6272       cbnzw(tmp5, DONE);
6273     }
6274     bind(TAIL01);
6275     if (elem_size == 1) { // Only needed when comparing byte arrays.
6276       tbz(cnt1, 0, SAME); // 0-1 bytes left.
6277       {
6278         ldrb(tmp1, a1);
6279         ldrb(tmp2, a2);
6280         eorw(tmp5, tmp1, tmp2);
6281         cbnzw(tmp5, DONE);
6282       }
6283     }
6284   } else {
6285     Label NEXT_DWORD, SHORT, TAIL, TAIL2, STUB,
6286         CSET_EQ, LAST_CHECK;
6287     mov(result, false);
6288     cbz(a1, DONE);
6289     ldrw(cnt1, Address(a1, length_offset));
6290     cbz(a2, DONE);
6291     ldrw(tmp5, Address(a2, length_offset));
6292     cmp(cnt1, tmp5);
6293     br(NE, DONE); // If lengths differ, return false
6294     // Increase loop counter by diff between base- and actual start-offset.
6295     addw(cnt1, cnt1, extra_length);
6296 
6297     // on most CPUs a2 is still "locked"(surprisingly) in ldrw and it's
6298     // faster to perform another branch before comparing a1 and a2
6299     cmp(cnt1, (u1)elem_per_word);
6300     br(LE, SHORT); // short or same
6301     ldr(tmp3, Address(pre(a1, start_offset)));
6302     subs(zr, cnt1, stubBytesThreshold);
6303     br(GE, STUB);
6304     ldr(tmp4, Address(pre(a2, start_offset)));
6305     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
6306 
6307     // Main 16 byte comparison loop with 2 exits
6308     bind(NEXT_DWORD); {
6309       ldr(tmp1, Address(pre(a1, wordSize)));
6310       ldr(tmp2, Address(pre(a2, wordSize)));
6311       subs(cnt1, cnt1, 2 * elem_per_word);
6312       br(LE, TAIL);
6313       eor(tmp4, tmp3, tmp4);
6314       cbnz(tmp4, DONE);
6315       ldr(tmp3, Address(pre(a1, wordSize)));
6316       ldr(tmp4, Address(pre(a2, wordSize)));
6317       cmp(cnt1, (u1)elem_per_word);
6318       br(LE, TAIL2);
6319       cmp(tmp1, tmp2);
6320     } br(EQ, NEXT_DWORD);
6321     b(DONE);
6322 
6323     bind(TAIL);
6324     eor(tmp4, tmp3, tmp4);
6325     eor(tmp2, tmp1, tmp2);
6326     lslv(tmp2, tmp2, tmp5);
6327     orr(tmp5, tmp4, tmp2);
6328     cmp(tmp5, zr);
6329     b(CSET_EQ);
6330 
6331     bind(TAIL2);
6332     eor(tmp2, tmp1, tmp2);
6333     cbnz(tmp2, DONE);
6334     b(LAST_CHECK);
6335 
6336     bind(STUB);
6337     ldr(tmp4, Address(pre(a2, start_offset)));
6338     if (elem_size == 2) { // convert to byte counter
6339       lsl(cnt1, cnt1, 1);
6340     }
6341     eor(tmp5, tmp3, tmp4);
6342     cbnz(tmp5, DONE);
6343     RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_array_equals());
6344     assert(stub.target() != nullptr, "array_equals_long stub has not been generated");
6345     address tpc = trampoline_call(stub);
6346     if (tpc == nullptr) {
6347       DEBUG_ONLY(reset_labels(SHORT, LAST_CHECK, CSET_EQ, SAME, DONE));
6348       postcond(pc() == badAddress);
6349       return nullptr;
6350     }
6351     b(DONE);
6352 
6353     // (a1 != null && a2 == null) || (a1 != null && a2 != null && a1 == a2)
6354     // so, if a2 == null => return false(0), else return true, so we can return a2
6355     mov(result, a2);
6356     b(DONE);
6357     bind(SHORT);
6358     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
6359     ldr(tmp3, Address(a1, start_offset));
6360     ldr(tmp4, Address(a2, start_offset));
6361     bind(LAST_CHECK);
6362     eor(tmp4, tmp3, tmp4);
6363     lslv(tmp5, tmp4, tmp5);
6364     cmp(tmp5, zr);
6365     bind(CSET_EQ);
6366     cset(result, EQ);
6367     b(DONE);
6368   }
6369 
6370   bind(SAME);
6371   mov(result, true);
6372   // That's it.
6373   bind(DONE);
6374 
6375   BLOCK_COMMENT("} array_equals");
6376   postcond(pc() != badAddress);
6377   return pc();
6378 }
6379 
6380 // Compare Strings
6381 
6382 // For Strings we're passed the address of the first characters in a1
6383 // and a2 and the length in cnt1.
6384 // There are two implementations.  For arrays >= 8 bytes, all
6385 // comparisons (including the final one, which may overlap) are
6386 // performed 8 bytes at a time.  For strings < 8 bytes, we compare a
6387 // halfword, then a short, and then a byte.
6388 
6389 void MacroAssembler::string_equals(Register a1, Register a2,
6390                                    Register result, Register cnt1)
6391 {
6392   Label SAME, DONE, SHORT, NEXT_WORD;
6393   Register tmp1 = rscratch1;
6394   Register tmp2 = rscratch2;
6395 
6396   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
6397 
6398 #ifndef PRODUCT
6399   {
6400     char comment[64];
6401     os::snprintf_checked(comment, sizeof comment, "{string_equalsL");
6402     BLOCK_COMMENT(comment);
6403   }
6404 #endif
6405 
6406   mov(result, false);
6407 
6408   // Check for short strings, i.e. smaller than wordSize.
6409   subs(cnt1, cnt1, wordSize);
6410   br(Assembler::LT, SHORT);
6411   // Main 8 byte comparison loop.
6412   bind(NEXT_WORD); {
6413     ldr(tmp1, Address(post(a1, wordSize)));
6414     ldr(tmp2, Address(post(a2, wordSize)));
6415     subs(cnt1, cnt1, wordSize);
6416     eor(tmp1, tmp1, tmp2);
6417     cbnz(tmp1, DONE);
6418   } br(GT, NEXT_WORD);
6419   // Last longword.  In the case where length == 4 we compare the
6420   // same longword twice, but that's still faster than another
6421   // conditional branch.
6422   // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
6423   // length == 4.
6424   ldr(tmp1, Address(a1, cnt1));
6425   ldr(tmp2, Address(a2, cnt1));
6426   eor(tmp2, tmp1, tmp2);
6427   cbnz(tmp2, DONE);
6428   b(SAME);
6429 
6430   bind(SHORT);
6431   Label TAIL03, TAIL01;
6432 
6433   tbz(cnt1, 2, TAIL03); // 0-7 bytes left.
6434   {
6435     ldrw(tmp1, Address(post(a1, 4)));
6436     ldrw(tmp2, Address(post(a2, 4)));
6437     eorw(tmp1, tmp1, tmp2);
6438     cbnzw(tmp1, DONE);
6439   }
6440   bind(TAIL03);
6441   tbz(cnt1, 1, TAIL01); // 0-3 bytes left.
6442   {
6443     ldrh(tmp1, Address(post(a1, 2)));
6444     ldrh(tmp2, Address(post(a2, 2)));
6445     eorw(tmp1, tmp1, tmp2);
6446     cbnzw(tmp1, DONE);
6447   }
6448   bind(TAIL01);
6449   tbz(cnt1, 0, SAME); // 0-1 bytes left.
6450     {
6451     ldrb(tmp1, a1);
6452     ldrb(tmp2, a2);
6453     eorw(tmp1, tmp1, tmp2);
6454     cbnzw(tmp1, DONE);
6455   }
6456   // Arrays are equal.
6457   bind(SAME);
6458   mov(result, true);
6459 
6460   // That's it.
6461   bind(DONE);
6462   BLOCK_COMMENT("} string_equals");
6463 }
6464 
6465 
6466 // The size of the blocks erased by the zero_blocks stub.  We must
6467 // handle anything smaller than this ourselves in zero_words().
6468 const int MacroAssembler::zero_words_block_size = 8;
6469 
6470 // zero_words() is used by C2 ClearArray patterns and by
6471 // C1_MacroAssembler.  It is as small as possible, handling small word
6472 // counts locally and delegating anything larger to the zero_blocks
6473 // stub.  It is expanded many times in compiled code, so it is
6474 // important to keep it short.
6475 
6476 // ptr:   Address of a buffer to be zeroed.
6477 // cnt:   Count in HeapWords.
6478 //
6479 // ptr, cnt, rscratch1, and rscratch2 are clobbered.
6480 address MacroAssembler::zero_words(Register ptr, Register cnt)
6481 {
6482   assert(is_power_of_2(zero_words_block_size), "adjust this");
6483 
6484   BLOCK_COMMENT("zero_words {");
6485   assert(ptr == r10 && cnt == r11, "mismatch in register usage");
6486   RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
6487   assert(zero_blocks.target() != nullptr, "zero_blocks stub has not been generated");
6488 
6489   subs(rscratch1, cnt, zero_words_block_size);
6490   Label around;
6491   br(LO, around);
6492   {
6493     RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
6494     assert(zero_blocks.target() != nullptr, "zero_blocks stub has not been generated");
6495     // Make sure this is a C2 compilation. C1 allocates space only for
6496     // trampoline stubs generated by Call LIR ops, and in any case it
6497     // makes sense for a C1 compilation task to proceed as quickly as
6498     // possible.
6499     CompileTask* task;
6500     if (StubRoutines::aarch64::complete()
6501         && Thread::current()->is_Compiler_thread()
6502         && (task = ciEnv::current()->task())
6503         && is_c2_compile(task->comp_level())) {
6504       address tpc = trampoline_call(zero_blocks);
6505       if (tpc == nullptr) {
6506         DEBUG_ONLY(reset_labels(around));
6507         return nullptr;
6508       }
6509     } else {
6510       far_call(zero_blocks);
6511     }
6512   }
6513   bind(around);
6514 
6515   // We have a few words left to do. zero_blocks has adjusted r10 and r11
6516   // for us.
6517   for (int i = zero_words_block_size >> 1; i > 1; i >>= 1) {
6518     Label l;
6519     tbz(cnt, exact_log2(i), l);
6520     for (int j = 0; j < i; j += 2) {
6521       stp(zr, zr, post(ptr, 2 * BytesPerWord));
6522     }
6523     bind(l);
6524   }
6525   {
6526     Label l;
6527     tbz(cnt, 0, l);
6528     str(zr, Address(ptr));
6529     bind(l);
6530   }
6531 
6532   BLOCK_COMMENT("} zero_words");
6533   return pc();
6534 }
6535 
6536 // base:         Address of a buffer to be zeroed, 8 bytes aligned.
6537 // cnt:          Immediate count in HeapWords.
6538 //
6539 // r10, r11, rscratch1, and rscratch2 are clobbered.
6540 address MacroAssembler::zero_words(Register base, uint64_t cnt)
6541 {
6542   assert(wordSize <= BlockZeroingLowLimit,
6543             "increase BlockZeroingLowLimit");
6544   address result = nullptr;
6545   if (cnt <= (uint64_t)BlockZeroingLowLimit / BytesPerWord) {
6546 #ifndef PRODUCT
6547     {
6548       char buf[64];
6549       os::snprintf_checked(buf, sizeof buf, "zero_words (count = %" PRIu64 ") {", cnt);
6550       BLOCK_COMMENT(buf);
6551     }
6552 #endif
6553     if (cnt >= 16) {
6554       uint64_t loops = cnt/16;
6555       if (loops > 1) {
6556         mov(rscratch2, loops - 1);
6557       }
6558       {
6559         Label loop;
6560         bind(loop);
6561         for (int i = 0; i < 16; i += 2) {
6562           stp(zr, zr, Address(base, i * BytesPerWord));
6563         }
6564         add(base, base, 16 * BytesPerWord);
6565         if (loops > 1) {
6566           subs(rscratch2, rscratch2, 1);
6567           br(GE, loop);
6568         }
6569       }
6570     }
6571     cnt %= 16;
6572     int i = cnt & 1;  // store any odd word to start
6573     if (i) str(zr, Address(base));
6574     for (; i < (int)cnt; i += 2) {
6575       stp(zr, zr, Address(base, i * wordSize));
6576     }
6577     BLOCK_COMMENT("} zero_words");
6578     result = pc();
6579   } else {
6580     mov(r10, base); mov(r11, cnt);
6581     result = zero_words(r10, r11);
6582   }
6583   return result;
6584 }
6585 
6586 // Zero blocks of memory by using DC ZVA.
6587 //
6588 // Aligns the base address first sufficiently for DC ZVA, then uses
6589 // DC ZVA repeatedly for every full block.  cnt is the size to be
6590 // zeroed in HeapWords.  Returns the count of words left to be zeroed
6591 // in cnt.
6592 //
6593 // NOTE: This is intended to be used in the zero_blocks() stub.  If
6594 // you want to use it elsewhere, note that cnt must be >= 2*zva_length.
6595 void MacroAssembler::zero_dcache_blocks(Register base, Register cnt) {
6596   Register tmp = rscratch1;
6597   Register tmp2 = rscratch2;
6598   int zva_length = VM_Version::zva_length();
6599   Label initial_table_end, loop_zva;
6600   Label fini;
6601 
6602   // Base must be 16 byte aligned. If not just return and let caller handle it
6603   tst(base, 0x0f);
6604   br(Assembler::NE, fini);
6605   // Align base with ZVA length.
6606   neg(tmp, base);
6607   andr(tmp, tmp, zva_length - 1);
6608 
6609   // tmp: the number of bytes to be filled to align the base with ZVA length.
6610   add(base, base, tmp);
6611   sub(cnt, cnt, tmp, Assembler::ASR, 3);
6612   adr(tmp2, initial_table_end);
6613   sub(tmp2, tmp2, tmp, Assembler::LSR, 2);
6614   br(tmp2);
6615 
6616   for (int i = -zva_length + 16; i < 0; i += 16)
6617     stp(zr, zr, Address(base, i));
6618   bind(initial_table_end);
6619 
6620   sub(cnt, cnt, zva_length >> 3);
6621   bind(loop_zva);
6622   dc(Assembler::ZVA, base);
6623   subs(cnt, cnt, zva_length >> 3);
6624   add(base, base, zva_length);
6625   br(Assembler::GE, loop_zva);
6626   add(cnt, cnt, zva_length >> 3); // count not zeroed by DC ZVA
6627   bind(fini);
6628 }
6629 
6630 // base:   Address of a buffer to be filled, 8 bytes aligned.
6631 // cnt:    Count in 8-byte unit.
6632 // value:  Value to be filled with.
6633 // base will point to the end of the buffer after filling.
6634 void MacroAssembler::fill_words(Register base, Register cnt, Register value)
6635 {
6636 //  Algorithm:
6637 //
6638 //    if (cnt == 0) {
6639 //      return;
6640 //    }
6641 //    if ((p & 8) != 0) {
6642 //      *p++ = v;
6643 //    }
6644 //
6645 //    scratch1 = cnt & 14;
6646 //    cnt -= scratch1;
6647 //    p += scratch1;
6648 //    switch (scratch1 / 2) {
6649 //      do {
6650 //        cnt -= 16;
6651 //          p[-16] = v;
6652 //          p[-15] = v;
6653 //        case 7:
6654 //          p[-14] = v;
6655 //          p[-13] = v;
6656 //        case 6:
6657 //          p[-12] = v;
6658 //          p[-11] = v;
6659 //          // ...
6660 //        case 1:
6661 //          p[-2] = v;
6662 //          p[-1] = v;
6663 //        case 0:
6664 //          p += 16;
6665 //      } while (cnt);
6666 //    }
6667 //    if ((cnt & 1) == 1) {
6668 //      *p++ = v;
6669 //    }
6670 
6671   assert_different_registers(base, cnt, value, rscratch1, rscratch2);
6672 
6673   Label fini, skip, entry, loop;
6674   const int unroll = 8; // Number of stp instructions we'll unroll
6675 
6676   cbz(cnt, fini);
6677   tbz(base, 3, skip);
6678   str(value, Address(post(base, 8)));
6679   sub(cnt, cnt, 1);
6680   bind(skip);
6681 
6682   andr(rscratch1, cnt, (unroll-1) * 2);
6683   sub(cnt, cnt, rscratch1);
6684   add(base, base, rscratch1, Assembler::LSL, 3);
6685   adr(rscratch2, entry);
6686   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 1);
6687   br(rscratch2);
6688 
6689   bind(loop);
6690   add(base, base, unroll * 16);
6691   for (int i = -unroll; i < 0; i++)
6692     stp(value, value, Address(base, i * 16));
6693   bind(entry);
6694   subs(cnt, cnt, unroll * 2);
6695   br(Assembler::GE, loop);
6696 
6697   tbz(cnt, 0, fini);
6698   str(value, Address(post(base, 8)));
6699   bind(fini);
6700 }
6701 
6702 // Intrinsic for
6703 //
6704 // - sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6705 //   Encodes char[] to byte[] in ISO-8859-1
6706 //
6707 // - java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6708 //   Encodes byte[] (containing UTF-16) to byte[] in ISO-8859-1
6709 //
6710 // - java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6711 //   Encodes char[] to byte[] in ASCII
6712 //
6713 // This version always returns the number of characters copied, and does not
6714 // clobber the 'len' register. A successful copy will complete with the post-
6715 // condition: 'res' == 'len', while an unsuccessful copy will exit with the
6716 // post-condition: 0 <= 'res' < 'len'.
6717 //
6718 // NOTE: Attempts to use 'ld2' (and 'umaxv' in the ISO part) has proven to
6719 //       degrade performance (on Ampere Altra - Neoverse N1), to an extent
6720 //       beyond the acceptable, even though the footprint would be smaller.
6721 //       Using 'umaxv' in the ASCII-case comes with a small penalty but does
6722 //       avoid additional bloat.
6723 //
6724 // Clobbers: src, dst, res, rscratch1, rscratch2, rflags
6725 void MacroAssembler::encode_iso_array(Register src, Register dst,
6726                                       Register len, Register res, bool ascii,
6727                                       FloatRegister vtmp0, FloatRegister vtmp1,
6728                                       FloatRegister vtmp2, FloatRegister vtmp3,
6729                                       FloatRegister vtmp4, FloatRegister vtmp5)
6730 {
6731   Register cnt = res;
6732   Register max = rscratch1;
6733   Register chk = rscratch2;
6734 
6735   prfm(Address(src), PLDL1STRM);
6736   movw(cnt, len);
6737 
6738 #define ASCII(insn) do { if (ascii) { insn; } } while (0)
6739 
6740   Label LOOP_32, DONE_32, FAIL_32;
6741 
6742   BIND(LOOP_32);
6743   {
6744     cmpw(cnt, 32);
6745     br(LT, DONE_32);
6746     ld1(vtmp0, vtmp1, vtmp2, vtmp3, T8H, Address(post(src, 64)));
6747     // Extract lower bytes.
6748     FloatRegister vlo0 = vtmp4;
6749     FloatRegister vlo1 = vtmp5;
6750     uzp1(vlo0, T16B, vtmp0, vtmp1);
6751     uzp1(vlo1, T16B, vtmp2, vtmp3);
6752     // Merge bits...
6753     orr(vtmp0, T16B, vtmp0, vtmp1);
6754     orr(vtmp2, T16B, vtmp2, vtmp3);
6755     // Extract merged upper bytes.
6756     FloatRegister vhix = vtmp0;
6757     uzp2(vhix, T16B, vtmp0, vtmp2);
6758     // ISO-check on hi-parts (all zero).
6759     //                          ASCII-check on lo-parts (no sign).
6760     FloatRegister vlox = vtmp1; // Merge lower bytes.
6761                                 ASCII(orr(vlox, T16B, vlo0, vlo1));
6762     umov(chk, vhix, D, 1);      ASCII(cm(LT, vlox, T16B, vlox));
6763     fmovd(max, vhix);           ASCII(umaxv(vlox, T16B, vlox));
6764     orr(chk, chk, max);         ASCII(umov(max, vlox, B, 0));
6765                                 ASCII(orr(chk, chk, max));
6766     cbnz(chk, FAIL_32);
6767     subw(cnt, cnt, 32);
6768     st1(vlo0, vlo1, T16B, Address(post(dst, 32)));
6769     b(LOOP_32);
6770   }
6771   BIND(FAIL_32);
6772   sub(src, src, 64);
6773   BIND(DONE_32);
6774 
6775   Label LOOP_8, SKIP_8;
6776 
6777   BIND(LOOP_8);
6778   {
6779     cmpw(cnt, 8);
6780     br(LT, SKIP_8);
6781     FloatRegister vhi = vtmp0;
6782     FloatRegister vlo = vtmp1;
6783     ld1(vtmp3, T8H, src);
6784     uzp1(vlo, T16B, vtmp3, vtmp3);
6785     uzp2(vhi, T16B, vtmp3, vtmp3);
6786     // ISO-check on hi-parts (all zero).
6787     //                          ASCII-check on lo-parts (no sign).
6788                                 ASCII(cm(LT, vtmp2, T16B, vlo));
6789     fmovd(chk, vhi);            ASCII(umaxv(vtmp2, T16B, vtmp2));
6790                                 ASCII(umov(max, vtmp2, B, 0));
6791                                 ASCII(orr(chk, chk, max));
6792     cbnz(chk, SKIP_8);
6793 
6794     strd(vlo, Address(post(dst, 8)));
6795     subw(cnt, cnt, 8);
6796     add(src, src, 16);
6797     b(LOOP_8);
6798   }
6799   BIND(SKIP_8);
6800 
6801 #undef ASCII
6802 
6803   Label LOOP, DONE;
6804 
6805   cbz(cnt, DONE);
6806   BIND(LOOP);
6807   {
6808     Register chr = rscratch1;
6809     ldrh(chr, Address(post(src, 2)));
6810     tst(chr, ascii ? 0xff80 : 0xff00);
6811     br(NE, DONE);
6812     strb(chr, Address(post(dst, 1)));
6813     subs(cnt, cnt, 1);
6814     br(GT, LOOP);
6815   }
6816   BIND(DONE);
6817   // Return index where we stopped.
6818   subw(res, len, cnt);
6819 }
6820 
6821 // Inflate byte[] array to char[].
6822 // Clobbers: src, dst, len, rflags, rscratch1, v0-v6
6823 address MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
6824                                            FloatRegister vtmp1, FloatRegister vtmp2,
6825                                            FloatRegister vtmp3, Register tmp4) {
6826   Label big, done, after_init, to_stub;
6827 
6828   assert_different_registers(src, dst, len, tmp4, rscratch1);
6829 
6830   fmovd(vtmp1, 0.0);
6831   lsrw(tmp4, len, 3);
6832   bind(after_init);
6833   cbnzw(tmp4, big);
6834   // Short string: less than 8 bytes.
6835   {
6836     Label loop, tiny;
6837 
6838     cmpw(len, 4);
6839     br(LT, tiny);
6840     // Use SIMD to do 4 bytes.
6841     ldrs(vtmp2, post(src, 4));
6842     zip1(vtmp3, T8B, vtmp2, vtmp1);
6843     subw(len, len, 4);
6844     strd(vtmp3, post(dst, 8));
6845 
6846     cbzw(len, done);
6847 
6848     // Do the remaining bytes by steam.
6849     bind(loop);
6850     ldrb(tmp4, post(src, 1));
6851     strh(tmp4, post(dst, 2));
6852     subw(len, len, 1);
6853 
6854     bind(tiny);
6855     cbnz(len, loop);
6856 
6857     b(done);
6858   }
6859 
6860   if (SoftwarePrefetchHintDistance >= 0) {
6861     bind(to_stub);
6862       RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_byte_array_inflate());
6863       assert(stub.target() != nullptr, "large_byte_array_inflate stub has not been generated");
6864       address tpc = trampoline_call(stub);
6865       if (tpc == nullptr) {
6866         DEBUG_ONLY(reset_labels(big, done));
6867         postcond(pc() == badAddress);
6868         return nullptr;
6869       }
6870       b(after_init);
6871   }
6872 
6873   // Unpack the bytes 8 at a time.
6874   bind(big);
6875   {
6876     Label loop, around, loop_last, loop_start;
6877 
6878     if (SoftwarePrefetchHintDistance >= 0) {
6879       const int large_loop_threshold = (64 + 16)/8;
6880       ldrd(vtmp2, post(src, 8));
6881       andw(len, len, 7);
6882       cmp(tmp4, (u1)large_loop_threshold);
6883       br(GE, to_stub);
6884       b(loop_start);
6885 
6886       bind(loop);
6887       ldrd(vtmp2, post(src, 8));
6888       bind(loop_start);
6889       subs(tmp4, tmp4, 1);
6890       br(EQ, loop_last);
6891       zip1(vtmp2, T16B, vtmp2, vtmp1);
6892       ldrd(vtmp3, post(src, 8));
6893       st1(vtmp2, T8H, post(dst, 16));
6894       subs(tmp4, tmp4, 1);
6895       zip1(vtmp3, T16B, vtmp3, vtmp1);
6896       st1(vtmp3, T8H, post(dst, 16));
6897       br(NE, loop);
6898       b(around);
6899       bind(loop_last);
6900       zip1(vtmp2, T16B, vtmp2, vtmp1);
6901       st1(vtmp2, T8H, post(dst, 16));
6902       bind(around);
6903       cbz(len, done);
6904     } else {
6905       andw(len, len, 7);
6906       bind(loop);
6907       ldrd(vtmp2, post(src, 8));
6908       sub(tmp4, tmp4, 1);
6909       zip1(vtmp3, T16B, vtmp2, vtmp1);
6910       st1(vtmp3, T8H, post(dst, 16));
6911       cbnz(tmp4, loop);
6912     }
6913   }
6914 
6915   // Do the tail of up to 8 bytes.
6916   add(src, src, len);
6917   ldrd(vtmp3, Address(src, -8));
6918   add(dst, dst, len, ext::uxtw, 1);
6919   zip1(vtmp3, T16B, vtmp3, vtmp1);
6920   strq(vtmp3, Address(dst, -16));
6921 
6922   bind(done);
6923   postcond(pc() != badAddress);
6924   return pc();
6925 }
6926 
6927 // Compress char[] array to byte[].
6928 // Intrinsic for java.lang.StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
6929 // Return the array length if every element in array can be encoded,
6930 // otherwise, the index of first non-latin1 (> 0xff) character.
6931 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
6932                                          Register res,
6933                                          FloatRegister tmp0, FloatRegister tmp1,
6934                                          FloatRegister tmp2, FloatRegister tmp3,
6935                                          FloatRegister tmp4, FloatRegister tmp5) {
6936   encode_iso_array(src, dst, len, res, false, tmp0, tmp1, tmp2, tmp3, tmp4, tmp5);
6937 }
6938 
6939 // java.math.round(double a)
6940 // Returns the closest long to the argument, with ties rounding to
6941 // positive infinity.  This requires some fiddling for corner
6942 // cases. We take care to avoid double rounding in e.g. (jlong)(a + 0.5).
6943 void MacroAssembler::java_round_double(Register dst, FloatRegister src,
6944                                        FloatRegister ftmp) {
6945   Label DONE;
6946   BLOCK_COMMENT("java_round_double: { ");
6947   fmovd(rscratch1, src);
6948   // Use RoundToNearestTiesAway unless src small and -ve.
6949   fcvtasd(dst, src);
6950   // Test if src >= 0 || abs(src) >= 0x1.0p52
6951   eor(rscratch1, rscratch1, UCONST64(1) << 63); // flip sign bit
6952   mov(rscratch2, julong_cast(0x1.0p52));
6953   cmp(rscratch1, rscratch2);
6954   br(HS, DONE); {
6955     // src < 0 && abs(src) < 0x1.0p52
6956     // src may have a fractional part, so add 0.5
6957     fmovd(ftmp, 0.5);
6958     faddd(ftmp, src, ftmp);
6959     // Convert double to jlong, use RoundTowardsNegative
6960     fcvtmsd(dst, ftmp);
6961   }
6962   bind(DONE);
6963   BLOCK_COMMENT("} java_round_double");
6964 }
6965 
6966 void MacroAssembler::java_round_float(Register dst, FloatRegister src,
6967                                       FloatRegister ftmp) {
6968   Label DONE;
6969   BLOCK_COMMENT("java_round_float: { ");
6970   fmovs(rscratch1, src);
6971   // Use RoundToNearestTiesAway unless src small and -ve.
6972   fcvtassw(dst, src);
6973   // Test if src >= 0 || abs(src) >= 0x1.0p23
6974   eor(rscratch1, rscratch1, 0x80000000); // flip sign bit
6975   mov(rscratch2, jint_cast(0x1.0p23f));
6976   cmp(rscratch1, rscratch2);
6977   br(HS, DONE); {
6978     // src < 0 && |src| < 0x1.0p23
6979     // src may have a fractional part, so add 0.5
6980     fmovs(ftmp, 0.5f);
6981     fadds(ftmp, src, ftmp);
6982     // Convert float to jint, use RoundTowardsNegative
6983     fcvtmssw(dst, ftmp);
6984   }
6985   bind(DONE);
6986   BLOCK_COMMENT("} java_round_float");
6987 }
6988 
6989 // get_thread() can be called anywhere inside generated code so we
6990 // need to save whatever non-callee save context might get clobbered
6991 // by the call to JavaThread::aarch64_get_thread_helper() or, indeed,
6992 // the call setup code.
6993 //
6994 // On Linux and Windows, aarch64_get_thread_helper() is implemented in
6995 // assembly and clobbers only r0, r1, and flags.
6996 // On other systems, the helper is a usual C function.
6997 //
6998 void MacroAssembler::get_thread(Register dst) {
6999   RegSet saved_regs =
7000     BSD_ONLY(RegSet::range(r0, r17) + lr - dst)
7001     NOT_BSD (RegSet::range(r0, r1)  + lr - dst);
7002 
7003   protect_return_address();
7004   push(saved_regs, sp);
7005 
7006   mov(lr, ExternalAddress(CAST_FROM_FN_PTR(address, JavaThread::aarch64_get_thread_helper)));
7007   blr(lr);
7008   if (dst != c_rarg0) {
7009     mov(dst, c_rarg0);
7010   }
7011 
7012   pop(saved_regs, sp);
7013   authenticate_return_address();
7014 }
7015 
7016 #ifdef COMPILER2
7017 // C2 compiled method's prolog code
7018 // Moved here from aarch64.ad to support Valhalla code below
7019 void MacroAssembler::verified_entry(Compile* C, int sp_inc) {
7020   if (C->clinit_barrier_on_entry()) {
7021     assert(!C->method()->holder()->is_not_initialized(), "initialization should have been started");
7022 
7023     Label L_skip_barrier;
7024 
7025     mov_metadata(rscratch2, C->method()->holder()->constant_encoding());
7026     clinit_barrier(rscratch2, rscratch1, &L_skip_barrier);
7027     far_jump(RuntimeAddress(SharedRuntime::get_handle_wrong_method_stub()));
7028     bind(L_skip_barrier);
7029   }
7030 
7031   if (C->max_vector_size() > 0) {
7032     reinitialize_ptrue();
7033   }
7034 
7035   int bangsize = C->output()->bang_size_in_bytes();
7036   if (C->output()->need_stack_bang(bangsize))
7037     generate_stack_overflow_check(bangsize);
7038 
7039   // n.b. frame size includes space for return pc and rfp
7040   const long framesize = C->output()->frame_size_in_bytes();
7041   build_frame(framesize DEBUG_ONLY(COMMA sp_inc != 0));
7042 
7043   if (C->needs_stack_repair()) {
7044     save_stack_increment(sp_inc, framesize);
7045   }
7046 
7047   if (VerifyStackAtCalls) {
7048     Unimplemented();
7049   }
7050 }
7051 #endif // COMPILER2
7052 
7053 int MacroAssembler::store_inline_type_fields_to_buf(ciInlineKlass* vk, bool from_interpreter) {
7054   assert(InlineTypeReturnedAsFields, "Inline types should never be returned as fields");
7055   // An inline type might be returned. If fields are in registers we
7056   // need to allocate an inline type instance and initialize it with
7057   // the value of the fields.
7058   Label skip;
7059   // We only need a new buffered inline type if a new one is not returned
7060   tbz(r0, 0, skip);
7061   int call_offset = -1;
7062 
7063   // Be careful not to clobber r1-7 which hold returned fields
7064   // Also do not use callee-saved registers as these may be live in the interpreter
7065   Register tmp1 = r13, tmp2 = r14, klass = r15, r0_preserved = r12;
7066 
7067   // The following code is similar to the instance allocation code in TemplateTable::_new
7068   //  but has some slight differences,
7069   // e.g. object size is always not zero, sometimes it's constant; storing klass ptr after
7070   // allocating is not necessary if vk != nullptr, etc.
7071   Label slow_case;
7072   // 1. Try to allocate a new buffered inline instance either from TLAB or eden space
7073   mov(r0_preserved, r0); // save r0 for slow_case since *_allocate may corrupt it when allocation failed
7074 
7075   if (vk != nullptr) {
7076     // Called from C1, where the return type is statically known.
7077     movptr(klass, (intptr_t)vk->get_InlineKlass());
7078     jint lh = vk->layout_helper();
7079     assert(lh != Klass::_lh_neutral_value, "inline class in return type must have been resolved");
7080     if (UseTLAB && !Klass::layout_helper_needs_slow_path(lh)) {
7081       tlab_allocate(r0, noreg, lh, tmp1, tmp2, slow_case);
7082     } else {
7083       b(slow_case);
7084     }
7085   } else {
7086     // Call from interpreter. R0 contains ((the InlineKlass* of the return type) | 0x01)
7087     andr(klass, r0, -2);
7088     if (UseTLAB) {
7089       ldrw(tmp2, Address(klass, Klass::layout_helper_offset()));
7090       tst(tmp2, Klass::_lh_instance_slow_path_bit);
7091       br(Assembler::NE, slow_case);
7092       tlab_allocate(r0, tmp2, 0, tmp1, tmp2, slow_case);
7093     } else {
7094       b(slow_case);
7095     }
7096   }
7097   if (UseTLAB) {
7098     // 2. Initialize buffered inline instance header
7099     Register buffer_obj = r0;
7100     if (UseCompactObjectHeaders) {
7101       ldr(rscratch1, Address(klass, Klass::prototype_header_offset()));
7102       str(rscratch1, Address(buffer_obj, oopDesc::mark_offset_in_bytes()));
7103     } else {
7104       mov(rscratch1, (intptr_t)markWord::inline_type_prototype().value());
7105       str(rscratch1, Address(buffer_obj, oopDesc::mark_offset_in_bytes()));
7106       store_klass_gap(buffer_obj, zr);
7107       if (vk == nullptr) {
7108         // store_klass corrupts klass, so save it for later use (interpreter case only).
7109         mov(tmp1, klass);
7110       }
7111       store_klass(buffer_obj, klass);
7112       klass = tmp1;
7113     }
7114     // 3. Initialize its fields with an inline class specific handler
7115     if (vk != nullptr) {
7116       far_call(RuntimeAddress(vk->pack_handler())); // no need for call info as this will not safepoint.
7117     } else {
7118       ldr(tmp1, Address(klass, InlineKlass::adr_members_offset()));
7119       ldr(tmp1, Address(tmp1, InlineKlass::pack_handler_offset()));
7120       blr(tmp1);
7121     }
7122 
7123     membar(Assembler::StoreStore);
7124     b(skip);
7125   } else {
7126     // Must have already branched to slow_case above.
7127     DEBUG_ONLY(should_not_reach_here());
7128   }
7129   bind(slow_case);
7130   // We failed to allocate a new inline type, fall back to a runtime
7131   // call. Some oop field may be live in some registers but we can't
7132   // tell. That runtime call will take care of preserving them
7133   // across a GC if there's one.
7134   mov(r0, r0_preserved);
7135 
7136   if (from_interpreter) {
7137     super_call_VM_leaf(StubRoutines::store_inline_type_fields_to_buf());
7138   } else {
7139     far_call(RuntimeAddress(StubRoutines::store_inline_type_fields_to_buf()));
7140     call_offset = offset();
7141   }
7142   membar(Assembler::StoreStore);
7143 
7144   bind(skip);
7145   return call_offset;
7146 }
7147 
7148 // Move a value between registers/stack slots and update the reg_state
7149 bool MacroAssembler::move_helper(VMReg from, VMReg to, BasicType bt, RegState reg_state[]) {
7150   assert(from->is_valid() && to->is_valid(), "source and destination must be valid");
7151   if (reg_state[to->value()] == reg_written) {
7152     return true; // Already written
7153   }
7154 
7155   if (from != to && bt != T_VOID) {
7156     if (reg_state[to->value()] == reg_readonly) {
7157       return false; // Not yet writable
7158     }
7159     if (from->is_reg()) {
7160       if (to->is_reg()) {
7161         if (from->is_Register() && to->is_Register()) {
7162           mov(to->as_Register(), from->as_Register());
7163         } else if (from->is_FloatRegister() && to->is_FloatRegister()) {
7164           fmovd(to->as_FloatRegister(), from->as_FloatRegister());
7165         } else {
7166           ShouldNotReachHere();
7167         }
7168       } else {
7169         int st_off = to->reg2stack() * VMRegImpl::stack_slot_size;
7170         Address to_addr = Address(sp, st_off);
7171         if (from->is_FloatRegister()) {
7172           if (bt == T_DOUBLE) {
7173              strd(from->as_FloatRegister(), to_addr);
7174           } else {
7175              assert(bt == T_FLOAT, "must be float");
7176              strs(from->as_FloatRegister(), to_addr);
7177           }
7178         } else {
7179           str(from->as_Register(), to_addr);
7180         }
7181       }
7182     } else {
7183       Address from_addr = Address(sp, from->reg2stack() * VMRegImpl::stack_slot_size);
7184       if (to->is_reg()) {
7185         if (to->is_FloatRegister()) {
7186           if (bt == T_DOUBLE) {
7187             ldrd(to->as_FloatRegister(), from_addr);
7188           } else {
7189             assert(bt == T_FLOAT, "must be float");
7190             ldrs(to->as_FloatRegister(), from_addr);
7191           }
7192         } else {
7193           ldr(to->as_Register(), from_addr);
7194         }
7195       } else {
7196         int st_off = to->reg2stack() * VMRegImpl::stack_slot_size;
7197         ldr(rscratch1, from_addr);
7198         str(rscratch1, Address(sp, st_off));
7199       }
7200     }
7201   }
7202 
7203   // Update register states
7204   reg_state[from->value()] = reg_writable;
7205   reg_state[to->value()] = reg_written;
7206   return true;
7207 }
7208 
7209 // Calculate the extra stack space required for packing or unpacking inline
7210 // args and adjust the stack pointer
7211 int MacroAssembler::extend_stack_for_inline_args(int args_on_stack) {
7212   int sp_inc = args_on_stack * VMRegImpl::stack_slot_size;
7213   sp_inc = align_up(sp_inc, StackAlignmentInBytes);
7214   assert(sp_inc > 0, "sanity");
7215 
7216   // Save a copy of the FP and LR here for deoptimization patching and frame walking
7217   stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
7218 
7219   // Adjust the stack pointer. This will be repaired on return by MacroAssembler::remove_frame
7220   if (sp_inc < (1 << 9)) {
7221     sub(sp, sp, sp_inc);   // Fits in an immediate
7222   } else {
7223     mov(rscratch1, sp_inc);
7224     sub(sp, sp, rscratch1);
7225   }
7226 
7227   return sp_inc + 2 * wordSize;  // Account for the FP/LR space
7228 }
7229 
7230 // Read all fields from an inline type oop and store the values in registers/stack slots
7231 bool MacroAssembler::unpack_inline_helper(const GrowableArray<SigEntry>* sig, int& sig_index,
7232                                           VMReg from, int& from_index, VMRegPair* to, int to_count, int& to_index,
7233                                           RegState reg_state[]) {
7234   assert(sig->at(sig_index)._bt == T_VOID, "should be at end delimiter");
7235   assert(from->is_valid(), "source must be valid");
7236   bool progress = false;
7237 #ifdef ASSERT
7238   const int start_offset = offset();
7239 #endif
7240 
7241   Label L_null, L_notNull;
7242   // Don't use r14 as tmp because it's used for spilling (see MacroAssembler::spill_reg_for)
7243   Register tmp1 = r10;
7244   Register tmp2 = r11;
7245 
7246 #ifdef ASSERT
7247   RegSet clobbered_gp_regs = MacroAssembler::call_clobbered_gp_registers();
7248   assert(clobbered_gp_regs.contains(tmp1), "tmp1 must be saved explicitly if it's not a clobber");
7249   assert(clobbered_gp_regs.contains(tmp2), "tmp2 must be saved explicitly if it's not a clobber");
7250   assert(clobbered_gp_regs.contains(r14), "r14 must be saved explicitly if it's not a clobber");
7251 #endif
7252 
7253   Register fromReg = noreg;
7254   ScalarizedInlineArgsStream stream(sig, sig_index, to, to_count, to_index, true);
7255   bool done = true;
7256   bool mark_done = true;
7257   VMReg toReg;
7258   BasicType bt;
7259   // Check if argument requires a null check
7260   bool null_check = false;
7261   VMReg nullCheckReg;
7262   while (stream.next(nullCheckReg, bt)) {
7263     if (sig->at(stream.sig_index())._offset == -1) {
7264       null_check = true;
7265       break;
7266     }
7267   }
7268   stream.reset(sig_index, to_index);
7269   while (stream.next(toReg, bt)) {
7270     assert(toReg->is_valid(), "destination must be valid");
7271     int idx = (int)toReg->value();
7272     if (reg_state[idx] == reg_readonly) {
7273       if (idx != from->value()) {
7274         mark_done = false;
7275       }
7276       done = false;
7277       continue;
7278     } else if (reg_state[idx] == reg_written) {
7279       continue;
7280     }
7281     assert(reg_state[idx] == reg_writable, "must be writable");
7282     reg_state[idx] = reg_written;
7283     progress = true;
7284 
7285     if (fromReg == noreg) {
7286       if (from->is_reg()) {
7287         fromReg = from->as_Register();
7288       } else {
7289         int st_off = from->reg2stack() * VMRegImpl::stack_slot_size;
7290         ldr(tmp1, Address(sp, st_off));
7291         fromReg = tmp1;
7292       }
7293       if (null_check) {
7294         // Nullable inline type argument, emit null check
7295         cbz(fromReg, L_null);
7296       }
7297     }
7298     int off = sig->at(stream.sig_index())._offset;
7299     if (off == -1) {
7300       assert(null_check, "Missing null check at");
7301       if (toReg->is_stack()) {
7302         int st_off = toReg->reg2stack() * VMRegImpl::stack_slot_size;
7303         mov(tmp2, 1);
7304         str(tmp2, Address(sp, st_off));
7305       } else {
7306         mov(toReg->as_Register(), 1);
7307       }
7308       continue;
7309     }
7310     if (sig->at(stream.sig_index())._vt_oop) {
7311       if (toReg->is_stack()) {
7312         int st_off = toReg->reg2stack() * VMRegImpl::stack_slot_size;
7313         str(fromReg, Address(sp, st_off));
7314       } else {
7315         mov(toReg->as_Register(), fromReg);
7316       }
7317       continue;
7318     }
7319     assert(off > 0, "offset in object should be positive");
7320     Address fromAddr = Address(fromReg, off);
7321     if (!toReg->is_FloatRegister()) {
7322       Register dst = toReg->is_stack() ? tmp2 : toReg->as_Register();
7323       if (is_reference_type(bt)) {
7324         load_heap_oop(dst, fromAddr, rscratch1, rscratch2);
7325       } else {
7326         bool is_signed = (bt != T_CHAR) && (bt != T_BOOLEAN);
7327         load_sized_value(dst, fromAddr, type2aelembytes(bt), is_signed);
7328       }
7329       if (toReg->is_stack()) {
7330         int st_off = toReg->reg2stack() * VMRegImpl::stack_slot_size;
7331         str(dst, Address(sp, st_off));
7332       }
7333     } else if (bt == T_DOUBLE) {
7334       ldrd(toReg->as_FloatRegister(), fromAddr);
7335     } else {
7336       assert(bt == T_FLOAT, "must be float");
7337       ldrs(toReg->as_FloatRegister(), fromAddr);
7338     }
7339   }
7340   if (progress && null_check) {
7341     if (done) {
7342       b(L_notNull);
7343       bind(L_null);
7344       // Set null marker to zero to signal that the argument is null.
7345       // Also set all fields to zero since the runtime requires a canonical
7346       // representation of a flat null.
7347       stream.reset(sig_index, to_index);
7348       while (stream.next(toReg, bt)) {
7349         if (toReg->is_stack()) {
7350           int st_off = toReg->reg2stack() * VMRegImpl::stack_slot_size;
7351           str(zr, Address(sp, st_off));
7352         } else if (toReg->is_FloatRegister()) {
7353           mov(toReg->as_FloatRegister(), T2S, 0);
7354         } else {
7355           mov(toReg->as_Register(), zr);
7356         }
7357       }
7358       bind(L_notNull);
7359     } else {
7360       bind(L_null);
7361     }
7362   }
7363 
7364   sig_index = stream.sig_index();
7365   to_index = stream.regs_index();
7366 
7367   if (mark_done && reg_state[from->value()] != reg_written) {
7368     // This is okay because no one else will write to that slot
7369     reg_state[from->value()] = reg_writable;
7370   }
7371   from_index--;
7372   assert(progress || (start_offset == offset()), "should not emit code");
7373   return done;
7374 }
7375 
7376 // Pack fields back into an inline type oop
7377 bool MacroAssembler::pack_inline_helper(const GrowableArray<SigEntry>* sig, int& sig_index, int vtarg_index,
7378                                         VMRegPair* from, int from_count, int& from_index, VMReg to,
7379                                         RegState reg_state[], Register val_array) {
7380   assert(sig->at(sig_index)._bt == T_METADATA, "should be at delimiter");
7381   assert(to->is_valid(), "destination must be valid");
7382 
7383   if (reg_state[to->value()] == reg_written) {
7384     skip_unpacked_fields(sig, sig_index, from, from_count, from_index);
7385     return true; // Already written
7386   }
7387 
7388   // The GC barrier expanded by store_heap_oop below may call into the
7389   // runtime so use callee-saved registers for any values that need to be
7390   // preserved. The GC barrier assembler should take care of saving the
7391   // Java argument registers.
7392   // Be careful with r14 because it's used for spilling (see MacroAssembler::spill_reg_for).
7393   Register val_obj_tmp = r21;
7394   Register from_reg_tmp = r22;
7395   Register tmp1 = r14;
7396   Register tmp2 = r13;
7397   Register tmp3 = r12;
7398   Register val_obj = to->is_stack() ? val_obj_tmp : to->as_Register();
7399 
7400   assert_different_registers(val_obj_tmp, from_reg_tmp, tmp1, tmp2, tmp3, val_array);
7401 
7402   if (reg_state[to->value()] == reg_readonly) {
7403     if (!is_reg_in_unpacked_fields(sig, sig_index, to, from, from_count, from_index)) {
7404       skip_unpacked_fields(sig, sig_index, from, from_count, from_index);
7405       return false; // Not yet writable
7406     }
7407     val_obj = val_obj_tmp;
7408   }
7409 
7410   ScalarizedInlineArgsStream stream(sig, sig_index, from, from_count, from_index);
7411   VMReg fromReg;
7412   BasicType bt;
7413   Label L_null;
7414   while (stream.next(fromReg, bt)) {
7415     assert(fromReg->is_valid(), "source must be valid");
7416     reg_state[fromReg->value()] = reg_writable;
7417 
7418     int off = sig->at(stream.sig_index())._offset;
7419     if (off == -1) {
7420       // Nullable inline type argument, emit null check
7421       Label L_notNull;
7422       if (fromReg->is_stack()) {
7423         int ld_off = fromReg->reg2stack() * VMRegImpl::stack_slot_size;
7424         ldrb(tmp2, Address(sp, ld_off));
7425         cbnz(tmp2, L_notNull);
7426       } else {
7427         cbnz(fromReg->as_Register(), L_notNull);
7428       }
7429       mov(val_obj, 0);
7430       b(L_null);
7431       bind(L_notNull);
7432       continue;
7433     }
7434     if (sig->at(stream.sig_index())._vt_oop) {
7435       if (fromReg->is_stack()) {
7436         int ld_off = fromReg->reg2stack() * VMRegImpl::stack_slot_size;
7437         ldr(val_obj, Address(sp, ld_off));
7438       } else {
7439         mov(val_obj, fromReg->as_Register());
7440       }
7441       cbnz(val_obj, L_null);
7442       // get the buffer from the just allocated pool of buffers
7443       int index = arrayOopDesc::base_offset_in_bytes(T_OBJECT) + vtarg_index * type2aelembytes(T_OBJECT);
7444       load_heap_oop(val_obj, Address(val_array, index), rscratch1, rscratch2);
7445       continue;
7446     }
7447 
7448     assert(off > 0, "offset in object should be positive");
7449     size_t size_in_bytes = is_java_primitive(bt) ? type2aelembytes(bt) : wordSize;
7450 
7451     // Pack the scalarized field into the value object.
7452     Address dst(val_obj, off);
7453     if (!fromReg->is_FloatRegister()) {
7454       Register src;
7455       if (fromReg->is_stack()) {
7456         src = from_reg_tmp;
7457         int ld_off = fromReg->reg2stack() * VMRegImpl::stack_slot_size;
7458         load_sized_value(src, Address(sp, ld_off), size_in_bytes, /* is_signed */ false);
7459       } else {
7460         src = fromReg->as_Register();
7461       }
7462       assert_different_registers(dst.base(), src, tmp1, tmp2, tmp3, val_array);
7463       if (is_reference_type(bt)) {
7464         // store_heap_oop transitively calls oop_store_at which corrupts to.base(). We need to keep val_obj valid.
7465         mov(tmp3, val_obj);
7466         Address dst_with_tmp3(tmp3, off);
7467         store_heap_oop(dst_with_tmp3, src, tmp1, tmp2, tmp3, IN_HEAP | ACCESS_WRITE | IS_DEST_UNINITIALIZED);
7468       } else {
7469         store_sized_value(dst, src, size_in_bytes);
7470       }
7471     } else if (bt == T_DOUBLE) {
7472       strd(fromReg->as_FloatRegister(), dst);
7473     } else {
7474       assert(bt == T_FLOAT, "must be float");
7475       strs(fromReg->as_FloatRegister(), dst);
7476     }
7477   }
7478   bind(L_null);
7479   sig_index = stream.sig_index();
7480   from_index = stream.regs_index();
7481 
7482   assert(reg_state[to->value()] == reg_writable, "must have already been read");
7483   bool success = move_helper(val_obj->as_VMReg(), to, T_OBJECT, reg_state);
7484   assert(success, "to register must be writable");
7485   return true;
7486 }
7487 
7488 VMReg MacroAssembler::spill_reg_for(VMReg reg) {
7489   return (reg->is_FloatRegister()) ? v8->as_VMReg() : r14->as_VMReg();
7490 }
7491 
7492 void MacroAssembler::cache_wb(Address line) {
7493   assert(line.getMode() == Address::base_plus_offset, "mode should be base_plus_offset");
7494   assert(line.index() == noreg, "index should be noreg");
7495   assert(line.offset() == 0, "offset should be 0");
7496   // would like to assert this
7497   // assert(line._ext.shift == 0, "shift should be zero");
7498   if (VM_Version::supports_dcpop()) {
7499     // writeback using clear virtual address to point of persistence
7500     dc(Assembler::CVAP, line.base());
7501   } else {
7502     // no need to generate anything as Unsafe.writebackMemory should
7503     // never invoke this stub
7504   }
7505 }
7506 
7507 void MacroAssembler::cache_wbsync(bool is_pre) {
7508   // we only need a barrier post sync
7509   if (!is_pre) {
7510     membar(Assembler::AnyAny);
7511   }
7512 }
7513 
7514 void MacroAssembler::verify_sve_vector_length(Register tmp) {
7515   if (!UseSVE || VM_Version::get_max_supported_sve_vector_length() == FloatRegister::sve_vl_min) {
7516     return;
7517   }
7518   // Make sure that native code does not change SVE vector length.
7519   Label verify_ok;
7520   movw(tmp, zr);
7521   sve_inc(tmp, B);
7522   subsw(zr, tmp, VM_Version::get_initial_sve_vector_length());
7523   br(EQ, verify_ok);
7524   stop("Error: SVE vector length has changed since jvm startup");
7525   bind(verify_ok);
7526 }
7527 
7528 void MacroAssembler::verify_ptrue() {
7529   Label verify_ok;
7530   if (!UseSVE) {
7531     return;
7532   }
7533   sve_cntp(rscratch1, B, ptrue, ptrue); // get true elements count.
7534   sve_dec(rscratch1, B);
7535   cbz(rscratch1, verify_ok);
7536   stop("Error: the preserved predicate register (p7) elements are not all true");
7537   bind(verify_ok);
7538 }
7539 
7540 void MacroAssembler::safepoint_isb() {
7541   isb();
7542 #ifndef PRODUCT
7543   if (VerifyCrossModifyFence) {
7544     // Clear the thread state.
7545     strb(zr, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
7546   }
7547 #endif
7548 }
7549 
7550 #ifndef PRODUCT
7551 void MacroAssembler::verify_cross_modify_fence_not_required() {
7552   if (VerifyCrossModifyFence) {
7553     // Check if thread needs a cross modify fence.
7554     ldrb(rscratch1, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
7555     Label fence_not_required;
7556     cbz(rscratch1, fence_not_required);
7557     // If it does then fail.
7558     lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::verify_cross_modify_fence_failure)));
7559     mov(c_rarg0, rthread);
7560     blr(rscratch1);
7561     bind(fence_not_required);
7562   }
7563 }
7564 #endif
7565 
7566 void MacroAssembler::spin_wait() {
7567   block_comment("spin_wait {");
7568   for (int i = 0; i < VM_Version::spin_wait_desc().inst_count(); ++i) {
7569     switch (VM_Version::spin_wait_desc().inst()) {
7570       case SpinWait::NOP:
7571         nop();
7572         break;
7573       case SpinWait::ISB:
7574         isb();
7575         break;
7576       case SpinWait::YIELD:
7577         yield();
7578         break;
7579       case SpinWait::SB:
7580         assert(VM_Version::supports_sb(), "current CPU does not support SB instruction");
7581         sb();
7582         break;
7583       case SpinWait::WFET:
7584         spin_wait_wfet(VM_Version::spin_wait_desc().delay());
7585         break;
7586       default:
7587         ShouldNotReachHere();
7588     }
7589   }
7590   block_comment("}");
7591 }
7592 
7593 void MacroAssembler::spin_wait_wfet(int delay_ns) {
7594   // The sequence assumes CNTFRQ_EL0 is fixed to 1GHz. The assumption is valid
7595   // starting from Armv8.6, according to the "D12.1.2 The system counter" of the
7596   // Arm Architecture Reference Manual for A-profile architecture version M.a.a.
7597   // This is sufficient because FEAT_WFXT is introduced from Armv8.6.
7598   Register target = rscratch1;
7599   Register current = rscratch2;
7600   get_cntvctss_el0(current);
7601   add(target, current, delay_ns);
7602 
7603   Label L_wait_loop;
7604   bind(L_wait_loop);
7605 
7606   wfet(target);
7607   get_cntvctss_el0(current);
7608 
7609   cmp(current, target);
7610   br(LT, L_wait_loop);
7611 
7612   sb();
7613 }
7614 
7615 // Stack frame creation/removal
7616 
7617 void MacroAssembler::enter(bool strip_ret_addr) {
7618   if (strip_ret_addr) {
7619     // Addresses can only be signed once. If there are multiple nested frames being created
7620     // in the same function, then the return address needs stripping first.
7621     strip_return_address();
7622   }
7623   protect_return_address();
7624   stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
7625   mov(rfp, sp);
7626 }
7627 
7628 void MacroAssembler::leave() {
7629   mov(sp, rfp);
7630   ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
7631   authenticate_return_address();
7632 }
7633 
7634 // ROP Protection
7635 // Use the AArch64 PAC feature to add ROP protection for generated code. Use whenever creating/
7636 // destroying stack frames or whenever directly loading/storing the LR to memory.
7637 // If ROP protection is not set then these functions are no-ops.
7638 // For more details on PAC see pauth_aarch64.hpp.
7639 
7640 // Sign the LR. Use during construction of a stack frame, before storing the LR to memory.
7641 // Uses value zero as the modifier.
7642 //
7643 void MacroAssembler::protect_return_address() {
7644   if (VM_Version::use_rop_protection()) {
7645     check_return_address();
7646     paciaz();
7647   }
7648 }
7649 
7650 // Sign the return value in the given register. Use before updating the LR in the existing stack
7651 // frame for the current function.
7652 // Uses value zero as the modifier.
7653 //
7654 void MacroAssembler::protect_return_address(Register return_reg) {
7655   if (VM_Version::use_rop_protection()) {
7656     check_return_address(return_reg);
7657     paciza(return_reg);
7658   }
7659 }
7660 
7661 // Authenticate the LR. Use before function return, after restoring FP and loading LR from memory.
7662 // Uses value zero as the modifier.
7663 //
7664 void MacroAssembler::authenticate_return_address() {
7665   if (VM_Version::use_rop_protection()) {
7666     autiaz();
7667     check_return_address();
7668   }
7669 }
7670 
7671 // Authenticate the return value in the given register. Use before updating the LR in the existing
7672 // stack frame for the current function.
7673 // Uses value zero as the modifier.
7674 //
7675 void MacroAssembler::authenticate_return_address(Register return_reg) {
7676   if (VM_Version::use_rop_protection()) {
7677     autiza(return_reg);
7678     check_return_address(return_reg);
7679   }
7680 }
7681 
7682 // Strip any PAC data from LR without performing any authentication. Use with caution - only if
7683 // there is no guaranteed way of authenticating the LR.
7684 //
7685 void MacroAssembler::strip_return_address() {
7686   if (VM_Version::use_rop_protection()) {
7687     xpaclri();
7688   }
7689 }
7690 
7691 #ifndef PRODUCT
7692 // PAC failures can be difficult to debug. After an authentication failure, a segfault will only
7693 // occur when the pointer is used - ie when the program returns to the invalid LR. At this point
7694 // it is difficult to debug back to the callee function.
7695 // This function simply loads from the address in the given register.
7696 // Use directly after authentication to catch authentication failures.
7697 // Also use before signing to check that the pointer is valid and hasn't already been signed.
7698 //
7699 void MacroAssembler::check_return_address(Register return_reg) {
7700   if (VM_Version::use_rop_protection()) {
7701     ldr(zr, Address(return_reg));
7702   }
7703 }
7704 #endif
7705 
7706 // The java_calling_convention describes stack locations as ideal slots on
7707 // a frame with no abi restrictions. Since we must observe abi restrictions
7708 // (like the placement of the register window) the slots must be biased by
7709 // the following value.
7710 static int reg2offset_in(VMReg r) {
7711   // Account for saved rfp and lr
7712   // This should really be in_preserve_stack_slots
7713   return (r->reg2stack() + 4) * VMRegImpl::stack_slot_size;
7714 }
7715 
7716 static int reg2offset_out(VMReg r) {
7717   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
7718 }
7719 
7720 // On 64bit we will store integer like items to the stack as
7721 // 64bits items (AArch64 ABI) even though java would only store
7722 // 32bits for a parameter. On 32bit it will simply be 32bits
7723 // So this routine will do 32->32 on 32bit and 32->64 on 64bit
7724 void MacroAssembler::move32_64(VMRegPair src, VMRegPair dst, Register tmp) {
7725   if (src.first()->is_stack()) {
7726     if (dst.first()->is_stack()) {
7727       // stack to stack
7728       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
7729       str(tmp, Address(sp, reg2offset_out(dst.first())));
7730     } else {
7731       // stack to reg
7732       ldrsw(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
7733     }
7734   } else if (dst.first()->is_stack()) {
7735     // reg to stack
7736     str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
7737   } else {
7738     if (dst.first() != src.first()) {
7739       sxtw(dst.first()->as_Register(), src.first()->as_Register());
7740     }
7741   }
7742 }
7743 
7744 // An oop arg. Must pass a handle not the oop itself
7745 void MacroAssembler::object_move(
7746                         OopMap* map,
7747                         int oop_handle_offset,
7748                         int framesize_in_slots,
7749                         VMRegPair src,
7750                         VMRegPair dst,
7751                         bool is_receiver,
7752                         int* receiver_offset) {
7753 
7754   // must pass a handle. First figure out the location we use as a handle
7755 
7756   Register rHandle = dst.first()->is_stack() ? rscratch2 : dst.first()->as_Register();
7757 
7758   // See if oop is null if it is we need no handle
7759 
7760   if (src.first()->is_stack()) {
7761 
7762     // Oop is already on the stack as an argument
7763     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
7764     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
7765     if (is_receiver) {
7766       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
7767     }
7768 
7769     ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
7770     lea(rHandle, Address(rfp, reg2offset_in(src.first())));
7771     // conditionally move a null
7772     cmp(rscratch1, zr);
7773     csel(rHandle, zr, rHandle, Assembler::EQ);
7774   } else {
7775 
7776     // Oop is in an a register we must store it to the space we reserve
7777     // on the stack for oop_handles and pass a handle if oop is non-null
7778 
7779     const Register rOop = src.first()->as_Register();
7780     int oop_slot;
7781     if (rOop == j_rarg0)
7782       oop_slot = 0;
7783     else if (rOop == j_rarg1)
7784       oop_slot = 1;
7785     else if (rOop == j_rarg2)
7786       oop_slot = 2;
7787     else if (rOop == j_rarg3)
7788       oop_slot = 3;
7789     else if (rOop == j_rarg4)
7790       oop_slot = 4;
7791     else if (rOop == j_rarg5)
7792       oop_slot = 5;
7793     else if (rOop == j_rarg6)
7794       oop_slot = 6;
7795     else {
7796       assert(rOop == j_rarg7, "wrong register");
7797       oop_slot = 7;
7798     }
7799 
7800     oop_slot = oop_slot * VMRegImpl::slots_per_word + oop_handle_offset;
7801     int offset = oop_slot*VMRegImpl::stack_slot_size;
7802 
7803     map->set_oop(VMRegImpl::stack2reg(oop_slot));
7804     // Store oop in handle area, may be null
7805     str(rOop, Address(sp, offset));
7806     if (is_receiver) {
7807       *receiver_offset = offset;
7808     }
7809 
7810     cmp(rOop, zr);
7811     lea(rHandle, Address(sp, offset));
7812     // conditionally move a null
7813     csel(rHandle, zr, rHandle, Assembler::EQ);
7814   }
7815 
7816   // If arg is on the stack then place it otherwise it is already in correct reg.
7817   if (dst.first()->is_stack()) {
7818     str(rHandle, Address(sp, reg2offset_out(dst.first())));
7819   }
7820 }
7821 
7822 // A float arg may have to do float reg int reg conversion
7823 void MacroAssembler::float_move(VMRegPair src, VMRegPair dst, Register tmp) {
7824  if (src.first()->is_stack()) {
7825     if (dst.first()->is_stack()) {
7826       ldrw(tmp, Address(rfp, reg2offset_in(src.first())));
7827       strw(tmp, Address(sp, reg2offset_out(dst.first())));
7828     } else {
7829       ldrs(dst.first()->as_FloatRegister(), Address(rfp, reg2offset_in(src.first())));
7830     }
7831   } else if (src.first() != dst.first()) {
7832     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
7833       fmovs(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
7834     else
7835       strs(src.first()->as_FloatRegister(), Address(sp, reg2offset_out(dst.first())));
7836   }
7837 }
7838 
7839 // A long move
7840 void MacroAssembler::long_move(VMRegPair src, VMRegPair dst, Register tmp) {
7841   if (src.first()->is_stack()) {
7842     if (dst.first()->is_stack()) {
7843       // stack to stack
7844       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
7845       str(tmp, Address(sp, reg2offset_out(dst.first())));
7846     } else {
7847       // stack to reg
7848       ldr(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
7849     }
7850   } else if (dst.first()->is_stack()) {
7851     // reg to stack
7852     // Do we really have to sign extend???
7853     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
7854     str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
7855   } else {
7856     if (dst.first() != src.first()) {
7857       mov(dst.first()->as_Register(), src.first()->as_Register());
7858     }
7859   }
7860 }
7861 
7862 
7863 // A double move
7864 void MacroAssembler::double_move(VMRegPair src, VMRegPair dst, Register tmp) {
7865  if (src.first()->is_stack()) {
7866     if (dst.first()->is_stack()) {
7867       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
7868       str(tmp, Address(sp, reg2offset_out(dst.first())));
7869     } else {
7870       ldrd(dst.first()->as_FloatRegister(), Address(rfp, reg2offset_in(src.first())));
7871     }
7872   } else if (src.first() != dst.first()) {
7873     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
7874       fmovd(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
7875     else
7876       strd(src.first()->as_FloatRegister(), Address(sp, reg2offset_out(dst.first())));
7877   }
7878 }
7879 
7880 // Implements fast-locking.
7881 //
7882 //  - obj: the object to be locked
7883 //  - t1, t2, t3: temporary registers, will be destroyed
7884 //  - slow: branched to if locking fails, absolute offset may larger than 32KB (imm14 encoding).
7885 void MacroAssembler::fast_lock(Register basic_lock, Register obj, Register t1, Register t2, Register t3, Label& slow) {
7886   assert_different_registers(basic_lock, obj, t1, t2, t3, rscratch1);
7887 
7888   Label push;
7889   const Register top = t1;
7890   const Register mark = t2;
7891   const Register t = t3;
7892 
7893   // Preload the markWord. It is important that this is the first
7894   // instruction emitted as it is part of C1's null check semantics.
7895   ldr(mark, Address(obj, oopDesc::mark_offset_in_bytes()));
7896 
7897   if (UseObjectMonitorTable) {
7898     // Clear cache in case fast locking succeeds or we need to take the slow-path.
7899     str(zr, Address(basic_lock, BasicObjectLock::lock_offset() + in_ByteSize((BasicLock::object_monitor_cache_offset_in_bytes()))));
7900   }
7901 
7902   if (DiagnoseSyncOnValueBasedClasses != 0) {
7903     load_klass(t1, obj);
7904     ldrb(t1, Address(t1, Klass::misc_flags_offset()));
7905     tst(t1, KlassFlags::_misc_is_value_based_class);
7906     br(Assembler::NE, slow);
7907   }
7908 
7909   // Check if the lock-stack is full.
7910   ldrw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7911   cmpw(top, (unsigned)LockStack::end_offset());
7912   br(Assembler::GE, slow);
7913 
7914   // Check for recursion.
7915   subw(t, top, oopSize);
7916   ldr(t, Address(rthread, t));
7917   cmp(obj, t);
7918   br(Assembler::EQ, push);
7919 
7920   // Check header for monitor (0b10).
7921   tst(mark, markWord::monitor_value);
7922   br(Assembler::NE, slow);
7923 
7924   // Try to lock. Transition lock bits 0b01 => 0b00
7925   assert(oopDesc::mark_offset_in_bytes() == 0, "required to avoid lea");
7926   orr(mark, mark, markWord::unlocked_value);
7927   // Mask inline_type bit such that we go to the slow path if object is an inline type
7928   andr(mark, mark, ~((int) markWord::inline_type_bit_in_place));
7929 
7930   eor(t, mark, markWord::unlocked_value);
7931   cmpxchg(/*addr*/ obj, /*expected*/ mark, /*new*/ t, Assembler::xword, memory_order_acquire);
7932   br(Assembler::NE, slow);
7933 
7934   bind(push);
7935   // After successful lock, push object on lock-stack.
7936   str(obj, Address(rthread, top));
7937   addw(top, top, oopSize);
7938   strw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7939 }
7940 
7941 // Implements fast-unlocking.
7942 //
7943 // - obj: the object to be unlocked
7944 // - t1, t2, t3: temporary registers
7945 // - slow: branched to if unlocking fails, absolute offset may larger than 32KB (imm14 encoding).
7946 void MacroAssembler::fast_unlock(Register obj, Register t1, Register t2, Register t3, Label& slow) {
7947   // cmpxchg clobbers rscratch1.
7948   assert_different_registers(obj, t1, t2, t3, rscratch1);
7949 
7950 #ifdef ASSERT
7951   {
7952     // Check for lock-stack underflow.
7953     Label stack_ok;
7954     ldrw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
7955     cmpw(t1, (unsigned)LockStack::start_offset());
7956     br(Assembler::GE, stack_ok);
7957     STOP("Lock-stack underflow");
7958     bind(stack_ok);
7959   }
7960 #endif
7961 
7962   Label unlocked, push_and_slow;
7963   const Register top = t1;
7964   const Register mark = t2;
7965   const Register t = t3;
7966 
7967   // Check if obj is top of lock-stack.
7968   ldrw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7969   subw(top, top, oopSize);
7970   ldr(t, Address(rthread, top));
7971   cmp(obj, t);
7972   br(Assembler::NE, slow);
7973 
7974   // Pop lock-stack.
7975   DEBUG_ONLY(str(zr, Address(rthread, top));)
7976   strw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7977 
7978   // Check if recursive.
7979   subw(t, top, oopSize);
7980   ldr(t, Address(rthread, t));
7981   cmp(obj, t);
7982   br(Assembler::EQ, unlocked);
7983 
7984   // Not recursive. Check header for monitor (0b10).
7985   ldr(mark, Address(obj, oopDesc::mark_offset_in_bytes()));
7986   tbnz(mark, log2i_exact(markWord::monitor_value), push_and_slow);
7987 
7988 #ifdef ASSERT
7989   // Check header not unlocked (0b01).
7990   Label not_unlocked;
7991   tbz(mark, log2i_exact(markWord::unlocked_value), not_unlocked);
7992   stop("fast_unlock already unlocked");
7993   bind(not_unlocked);
7994 #endif
7995 
7996   // Try to unlock. Transition lock bits 0b00 => 0b01
7997   assert(oopDesc::mark_offset_in_bytes() == 0, "required to avoid lea");
7998   orr(t, mark, markWord::unlocked_value);
7999   cmpxchg(obj, mark, t, Assembler::xword, memory_order_release);
8000   br(Assembler::EQ, unlocked);
8001 
8002   bind(push_and_slow);
8003   // Restore lock-stack and handle the unlock in runtime.
8004   DEBUG_ONLY(str(obj, Address(rthread, top));)
8005   addw(top, top, oopSize);
8006   strw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
8007   b(slow);
8008 
8009   bind(unlocked);
8010 }
8011 
8012 // Rotate using USHR and SLI instructions (or copy, if rotate count is zero)
8013 void MacroAssembler::neon_vector_rotate(FloatRegister dst, SIMD_Arrangement T,
8014                                         FloatRegister src, int shift_amount) {
8015   assert(src != dst, "did not expect src and dst to be the same register");
8016 
8017   int esize = BitsPerByte << (T / 2);
8018   int lshift = shift_amount & (esize - 1);
8019 
8020   if (lshift == 0) {
8021     // T & 1 == 0 => 64-bit arrangements, else 128-bit arrangements
8022     orr(dst, (T & 1) == 0 ? T8B : T16B, src, src);
8023   } else {
8024     ushr(dst, T, src, esize - lshift);
8025     sli(dst, T, src, lshift);
8026   }
8027 }
8028 
8029 void MacroAssembler::try_to_replace_prev_vector_copy_with_movprfx(FloatRegister dst) {
8030   if (code_section()->is_empty()) {
8031     return;
8032   }
8033 
8034   address prev = pc() - NativeInstruction::instruction_size;
8035   uint32_t insn = nativeInstruction_at(prev)->encoding();
8036   if (!NativeInstruction::is_neon_vector_mov_alias(insn) &&
8037       !NativeInstruction::is_sve_vector_mov_alias(insn)) {
8038     return;
8039   }
8040 
8041   // The destructive instruction must reuse the mov alias destination.
8042   uint32_t rd = Instruction_aarch64::extract(insn, 4, 0);
8043   if (rd != (uint32_t)dst->encoding()) {
8044     return;
8045   }
8046 
8047   uint32_t rn = Instruction_aarch64::extract(insn, 9, 5);
8048   Instruction_aarch64::patch(prev, 31, 0,
8049                              NativeInstruction::encode_sve_movprfx(rd, rn));
8050 }
--- EOF ---