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_polymorphic, 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 full
2195   //   for (i = 0; i < receiver_count(); i++) {
2196   //     if (receiver(i) == null) goto found_null(i);
2197   //   }
2198   //   goto polymorphic
2199   //
2200   //   // Slow: try to install receiver
2201   // found_null(i):
2202   //   CAS(&receiver(i), null, recv);
2203   //   goto restart
2204   //
2205   // polymorphic:
2206   //   count++;
2207   //   return
2208   //
2209   // found_recv(i):
2210   //   *receiver_count(i)++
2211   //
2212 
2213   bind(L_restart);
2214 
2215   // Fastest: receiver is already installed
2216   mov(offset, base_receiver_offset);
2217   bind(L_loop_search_receiver);
2218     ldr(rscratch1, Address(mdp, offset));
2219     cmp(rscratch1, recv);
2220     br(Assembler::EQ, L_found_recv);
2221   add(offset, offset, receiver_step);
2222   sub(rscratch1, offset, end_receiver_offset);
2223   cbnz(rscratch1, L_loop_search_receiver);
2224 
2225   // Fast: no receiver, but profile is full
2226   mov(offset, base_receiver_offset);
2227   bind(L_loop_search_empty);
2228     ldr(rscratch1, Address(mdp, offset));
2229     cbz(rscratch1, L_found_empty);
2230   add(offset, offset, receiver_step);
2231   sub(rscratch1, offset, end_receiver_offset);
2232   cbnz(rscratch1, L_loop_search_empty);
2233   b(L_polymorphic);
2234 
2235   // Slow: try to install receiver
2236   bind(L_found_empty);
2237 
2238   // Atomically swing receiver slot: null -> recv.
2239   //
2240   // The update uses CAS, which clobbers rscratch1. Therefore, rscratch2
2241   // is used to hold the destination address. This is safe because the
2242   // offset is no longer needed after the address is computed.
2243 
2244   lea(rscratch2, Address(mdp, offset));
2245   cmpxchg(/*addr*/ rscratch2, /*expected*/ zr, /*new*/ recv, Assembler::xword,
2246           /*acquire*/ false, /*release*/ false, /*weak*/ true, noreg);
2247 
2248   // CAS success means the slot now has the receiver we want. CAS failure means
2249   // something had claimed the slot concurrently: it can be the same receiver we want,
2250   // or something else. Since this is a slow path, we can optimize for code density,
2251   // and just restart the search from the beginning.
2252   b(L_restart);
2253 
2254   // Counter updates:
2255 
2256   // Increment polymorphic counter instead of receiver slot.
2257   bind(L_polymorphic);
2258   mov(offset, poly_count_offset);
2259   b(L_count_update);
2260 
2261   // Found a receiver, convert its slot offset to corresponding count offset.
2262   bind(L_found_recv);
2263   add(offset, offset, receiver_to_count_step);
2264 
2265   bind(L_count_update);
2266   increment(Address(mdp, offset), DataLayout::counter_increment);
2267 }
2268 
2269 
2270 void MacroAssembler::call_VM_leaf_base(address entry_point,
2271                                        int number_of_arguments,
2272                                        Label *retaddr) {
2273   Label E, L;
2274 
2275   stp(rscratch1, rmethod, Address(pre(sp, -2 * wordSize)));
2276 
2277   mov(rscratch1, RuntimeAddress(entry_point));
2278   blr(rscratch1);
2279   if (retaddr)
2280     bind(*retaddr);
2281 
2282   ldp(rscratch1, rmethod, Address(post(sp, 2 * wordSize)));
2283 }
2284 
2285 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2286   call_VM_leaf_base(entry_point, number_of_arguments);
2287 }
2288 
2289 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2290   pass_arg0(this, arg_0);
2291   call_VM_leaf_base(entry_point, 1);
2292 }
2293 
2294 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2295   assert_different_registers(arg_1, c_rarg0);
2296   pass_arg0(this, arg_0);
2297   pass_arg1(this, arg_1);
2298   call_VM_leaf_base(entry_point, 2);
2299 }
2300 
2301 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0,
2302                                   Register arg_1, Register arg_2) {
2303   assert_different_registers(arg_1, c_rarg0);
2304   assert_different_registers(arg_2, c_rarg0, c_rarg1);
2305   pass_arg0(this, arg_0);
2306   pass_arg1(this, arg_1);
2307   pass_arg2(this, arg_2);
2308   call_VM_leaf_base(entry_point, 3);
2309 }
2310 
2311 void MacroAssembler::super_call_VM_leaf(address entry_point) {
2312   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2313 }
2314 
2315 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2316   pass_arg0(this, arg_0);
2317   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2318 }
2319 
2320 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2321 
2322   assert_different_registers(arg_0, c_rarg1);
2323   pass_arg1(this, arg_1);
2324   pass_arg0(this, arg_0);
2325   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2326 }
2327 
2328 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2329   assert_different_registers(arg_0, c_rarg1, c_rarg2);
2330   assert_different_registers(arg_1, c_rarg2);
2331   pass_arg2(this, arg_2);
2332   pass_arg1(this, arg_1);
2333   pass_arg0(this, arg_0);
2334   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2335 }
2336 
2337 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2338   assert_different_registers(arg_0, c_rarg1, c_rarg2, c_rarg3);
2339   assert_different_registers(arg_1, c_rarg2, c_rarg3);
2340   assert_different_registers(arg_2, c_rarg3);
2341   pass_arg3(this, arg_3);
2342   pass_arg2(this, arg_2);
2343   pass_arg1(this, arg_1);
2344   pass_arg0(this, arg_0);
2345   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2346 }
2347 
2348 void MacroAssembler::null_check(Register reg, int offset) {
2349   if (needs_explicit_null_check(offset)) {
2350     // provoke OS null exception if reg is null by
2351     // accessing M[reg] w/o changing any registers
2352     // NOTE: this is plenty to provoke a segv
2353     ldr(zr, Address(reg));
2354   } else {
2355     // nothing to do, (later) access of M[reg + offset]
2356     // will provoke OS null exception if reg is null
2357   }
2358 }
2359 
2360 void MacroAssembler::test_markword_is_inline_type(Register markword, Label& is_inline_type) {
2361   assert_different_registers(markword, rscratch2);
2362   mov(rscratch2, markWord::inline_type_pattern_mask);
2363   andr(markword, markword, rscratch2);
2364   mov(rscratch2, markWord::inline_type_pattern);
2365   cmp(markword, rscratch2);
2366   br(Assembler::EQ, is_inline_type);
2367 }
2368 
2369 void MacroAssembler::test_oop_is_not_inline_type(Register object, Register tmp, Label& not_inline_type, bool can_be_null) {
2370   assert_different_registers(tmp, rscratch1);
2371   if (can_be_null) {
2372     cbz(object, not_inline_type);
2373   }
2374   const int is_inline_type_mask = markWord::inline_type_pattern;
2375   ldr(tmp, Address(object, oopDesc::mark_offset_in_bytes()));
2376   mov(rscratch1, is_inline_type_mask);
2377   andr(tmp, tmp, rscratch1);
2378   cmp(tmp, rscratch1);
2379   br(Assembler::NE, not_inline_type);
2380 }
2381 
2382 void MacroAssembler::test_field_is_null_free_inline_type(Register flags, Register temp_reg, Label& is_null_free_inline_type) {
2383   assert(temp_reg == noreg, "not needed"); // keep signature uniform with x86
2384   tbnz(flags, ResolvedFieldEntry::is_null_free_inline_type_shift, is_null_free_inline_type);
2385 }
2386 
2387 void MacroAssembler::test_field_is_not_null_free_inline_type(Register flags, Register temp_reg, Label& not_null_free_inline_type) {
2388   assert(temp_reg == noreg, "not needed"); // keep signature uniform with x86
2389   tbz(flags, ResolvedFieldEntry::is_null_free_inline_type_shift, not_null_free_inline_type);
2390 }
2391 
2392 void MacroAssembler::test_field_is_flat(Register flags, Register temp_reg, Label& is_flat) {
2393   assert(temp_reg == noreg, "not needed"); // keep signature uniform with x86
2394   tbnz(flags, ResolvedFieldEntry::is_flat_shift, is_flat);
2395 }
2396 
2397 void MacroAssembler::test_oop_prototype_bit(Register oop, Register temp_reg, int32_t test_bit, bool jmp_set, Label& jmp_label) {
2398   Label test_mark_word;
2399   // load mark word
2400   ldr(temp_reg, Address(oop, oopDesc::mark_offset_in_bytes()));
2401   // check displaced
2402   tst(temp_reg, markWord::unlocked_value);
2403   br(Assembler::NE, test_mark_word);
2404   // slow path use klass prototype
2405   load_prototype_header(temp_reg, oop);
2406 
2407   bind(test_mark_word);
2408   andr(temp_reg, temp_reg, test_bit);
2409   if (jmp_set) {
2410     cbnz(temp_reg, jmp_label);
2411   } else {
2412     cbz(temp_reg, jmp_label);
2413   }
2414 }
2415 
2416 void MacroAssembler::test_flat_array_oop(Register oop, Register temp_reg, Label& is_flat_array) {
2417   test_oop_prototype_bit(oop, temp_reg, markWord::flat_array_bit_in_place, true, is_flat_array);
2418 }
2419 
2420 void MacroAssembler::test_non_flat_array_oop(Register oop, Register temp_reg,
2421                                                   Label&is_non_flat_array) {
2422   test_oop_prototype_bit(oop, temp_reg, markWord::flat_array_bit_in_place, false, is_non_flat_array);
2423 }
2424 
2425 void MacroAssembler::test_null_free_array_oop(Register oop, Register temp_reg, Label& is_null_free_array) {
2426   test_oop_prototype_bit(oop, temp_reg, markWord::null_free_array_bit_in_place, true, is_null_free_array);
2427 }
2428 
2429 void MacroAssembler::test_non_null_free_array_oop(Register oop, Register temp_reg, Label&is_non_null_free_array) {
2430   test_oop_prototype_bit(oop, temp_reg, markWord::null_free_array_bit_in_place, false, is_non_null_free_array);
2431 }
2432 
2433 void MacroAssembler::test_flat_array_layout(Register lh, Label& is_flat_array) {
2434   tst(lh, Klass::_lh_array_tag_flat_value_bit_inplace);
2435   br(Assembler::NE, is_flat_array);
2436 }
2437 
2438 // MacroAssembler protected routines needed to implement
2439 // public methods
2440 
2441 void MacroAssembler::mov(Register r, Address dest) {
2442   code_section()->relocate(pc(), dest.rspec());
2443   uint64_t imm64 = (uint64_t)dest.target();
2444   movptr(r, imm64);
2445 }
2446 
2447 // Move a constant pointer into r.  In AArch64 mode the virtual
2448 // address space is 48 bits in size, so we only need three
2449 // instructions to create a patchable instruction sequence that can
2450 // reach anywhere.
2451 void MacroAssembler::movptr(Register r, uintptr_t imm64) {
2452 #ifndef PRODUCT
2453   {
2454     char buffer[64];
2455     os::snprintf_checked(buffer, sizeof(buffer), "0x%" PRIX64, (uint64_t)imm64);
2456     block_comment(buffer);
2457   }
2458 #endif
2459   assert(imm64 < (1ull << 48), "48-bit overflow in address constant");
2460   movz(r, imm64 & 0xffff);
2461   imm64 >>= 16;
2462   movk(r, imm64 & 0xffff, 16);
2463   imm64 >>= 16;
2464   movk(r, imm64 & 0xffff, 32);
2465 }
2466 
2467 // Macro to mov replicated immediate to vector register.
2468 // imm64: only the lower 8/16/32 bits are considered for B/H/S type. That is,
2469 //        the upper 56/48/32 bits must be zeros for B/H/S type.
2470 // Vd will get the following values for different arrangements in T
2471 //   imm64 == hex 000000gh  T8B:  Vd = ghghghghghghghgh
2472 //   imm64 == hex 000000gh  T16B: Vd = ghghghghghghghghghghghghghghghgh
2473 //   imm64 == hex 0000efgh  T4H:  Vd = efghefghefghefgh
2474 //   imm64 == hex 0000efgh  T8H:  Vd = efghefghefghefghefghefghefghefgh
2475 //   imm64 == hex abcdefgh  T2S:  Vd = abcdefghabcdefgh
2476 //   imm64 == hex abcdefgh  T4S:  Vd = abcdefghabcdefghabcdefghabcdefgh
2477 //   imm64 == hex abcdefgh  T1D:  Vd = 00000000abcdefgh
2478 //   imm64 == hex abcdefgh  T2D:  Vd = 00000000abcdefgh00000000abcdefgh
2479 // Clobbers rscratch1
2480 void MacroAssembler::mov(FloatRegister Vd, SIMD_Arrangement T, uint64_t imm64) {
2481   assert(T != T1Q, "unsupported");
2482   if (T == T1D || T == T2D) {
2483     int imm = operand_valid_for_movi_immediate(imm64, T);
2484     if (-1 != imm) {
2485       movi(Vd, T, imm);
2486     } else {
2487       mov(rscratch1, imm64);
2488       dup(Vd, T, rscratch1);
2489     }
2490     return;
2491   }
2492 
2493 #ifdef ASSERT
2494   if (T == T8B || T == T16B) assert((imm64 & ~0xff) == 0, "extraneous bits (T8B/T16B)");
2495   if (T == T4H || T == T8H) assert((imm64  & ~0xffff) == 0, "extraneous bits (T4H/T8H)");
2496   if (T == T2S || T == T4S) assert((imm64  & ~0xffffffff) == 0, "extraneous bits (T2S/T4S)");
2497 #endif
2498   int shift = operand_valid_for_movi_immediate(imm64, T);
2499   uint32_t imm32 = imm64 & 0xffffffffULL;
2500   if (shift >= 0) {
2501     movi(Vd, T, (imm32 >> shift) & 0xff, shift);
2502   } else {
2503     movw(rscratch1, imm32);
2504     dup(Vd, T, rscratch1);
2505   }
2506 }
2507 
2508 void MacroAssembler::mov_immediate64(Register dst, uint64_t imm64)
2509 {
2510 #ifndef PRODUCT
2511   {
2512     char buffer[64];
2513     os::snprintf_checked(buffer, sizeof(buffer), "0x%" PRIX64, imm64);
2514     block_comment(buffer);
2515   }
2516 #endif
2517   if (operand_valid_for_logical_immediate(false, imm64)) {
2518     orr(dst, zr, imm64);
2519   } else {
2520     // we can use a combination of MOVZ or MOVN with
2521     // MOVK to build up the constant
2522     uint64_t imm_h[4];
2523     int zero_count = 0;
2524     int neg_count = 0;
2525     int i;
2526     for (i = 0; i < 4; i++) {
2527       imm_h[i] = ((imm64 >> (i * 16)) & 0xffffL);
2528       if (imm_h[i] == 0) {
2529         zero_count++;
2530       } else if (imm_h[i] == 0xffffL) {
2531         neg_count++;
2532       }
2533     }
2534     if (zero_count == 4) {
2535       // one MOVZ will do
2536       movz(dst, 0);
2537     } else if (neg_count == 4) {
2538       // one MOVN will do
2539       movn(dst, 0);
2540     } else if (zero_count == 3) {
2541       for (i = 0; i < 4; i++) {
2542         if (imm_h[i] != 0L) {
2543           movz(dst, (uint32_t)imm_h[i], (i << 4));
2544           break;
2545         }
2546       }
2547     } else if (neg_count == 3) {
2548       // one MOVN will do
2549       for (int i = 0; i < 4; i++) {
2550         if (imm_h[i] != 0xffffL) {
2551           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
2552           break;
2553         }
2554       }
2555     } else if (zero_count == 2) {
2556       // one MOVZ and one MOVK will do
2557       for (i = 0; i < 3; i++) {
2558         if (imm_h[i] != 0L) {
2559           movz(dst, (uint32_t)imm_h[i], (i << 4));
2560           i++;
2561           break;
2562         }
2563       }
2564       for (;i < 4; i++) {
2565         if (imm_h[i] != 0L) {
2566           movk(dst, (uint32_t)imm_h[i], (i << 4));
2567         }
2568       }
2569     } else if (neg_count == 2) {
2570       // one MOVN and one MOVK will do
2571       for (i = 0; i < 4; i++) {
2572         if (imm_h[i] != 0xffffL) {
2573           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
2574           i++;
2575           break;
2576         }
2577       }
2578       for (;i < 4; i++) {
2579         if (imm_h[i] != 0xffffL) {
2580           movk(dst, (uint32_t)imm_h[i], (i << 4));
2581         }
2582       }
2583     } else if (zero_count == 1) {
2584       // one MOVZ and two MOVKs will do
2585       for (i = 0; i < 4; i++) {
2586         if (imm_h[i] != 0L) {
2587           movz(dst, (uint32_t)imm_h[i], (i << 4));
2588           i++;
2589           break;
2590         }
2591       }
2592       for (;i < 4; i++) {
2593         if (imm_h[i] != 0x0L) {
2594           movk(dst, (uint32_t)imm_h[i], (i << 4));
2595         }
2596       }
2597     } else if (neg_count == 1) {
2598       // one MOVN and two MOVKs will do
2599       for (i = 0; i < 4; i++) {
2600         if (imm_h[i] != 0xffffL) {
2601           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
2602           i++;
2603           break;
2604         }
2605       }
2606       for (;i < 4; i++) {
2607         if (imm_h[i] != 0xffffL) {
2608           movk(dst, (uint32_t)imm_h[i], (i << 4));
2609         }
2610       }
2611     } else {
2612       // use a MOVZ and 3 MOVKs (makes it easier to debug)
2613       movz(dst, (uint32_t)imm_h[0], 0);
2614       for (i = 1; i < 4; i++) {
2615         movk(dst, (uint32_t)imm_h[i], (i << 4));
2616       }
2617     }
2618   }
2619 }
2620 
2621 void MacroAssembler::mov_immediate32(Register dst, uint32_t imm32)
2622 {
2623 #ifndef PRODUCT
2624     {
2625       char buffer[64];
2626       os::snprintf_checked(buffer, sizeof(buffer), "0x%" PRIX32, imm32);
2627       block_comment(buffer);
2628     }
2629 #endif
2630   if (operand_valid_for_logical_immediate(true, imm32)) {
2631     orrw(dst, zr, imm32);
2632   } else {
2633     // we can use MOVZ, MOVN or two calls to MOVK to build up the
2634     // constant
2635     uint32_t imm_h[2];
2636     imm_h[0] = imm32 & 0xffff;
2637     imm_h[1] = ((imm32 >> 16) & 0xffff);
2638     if (imm_h[0] == 0) {
2639       movzw(dst, imm_h[1], 16);
2640     } else if (imm_h[0] == 0xffff) {
2641       movnw(dst, imm_h[1] ^ 0xffff, 16);
2642     } else if (imm_h[1] == 0) {
2643       movzw(dst, imm_h[0], 0);
2644     } else if (imm_h[1] == 0xffff) {
2645       movnw(dst, imm_h[0] ^ 0xffff, 0);
2646     } else {
2647       // use a MOVZ and MOVK (makes it easier to debug)
2648       movzw(dst, imm_h[0], 0);
2649       movkw(dst, imm_h[1], 16);
2650     }
2651   }
2652 }
2653 
2654 // Form an address from base + offset in Rd.  Rd may or may
2655 // not actually be used: you must use the Address that is returned.
2656 // It is up to you to ensure that the shift provided matches the size
2657 // of your data.
2658 Address MacroAssembler::form_address(Register Rd, Register base, int64_t byte_offset, int shift) {
2659   if (Address::offset_ok_for_immed(byte_offset, shift))
2660     // It fits; no need for any heroics
2661     return Address(base, byte_offset);
2662 
2663   // Don't do anything clever with negative or misaligned offsets
2664   unsigned mask = (1 << shift) - 1;
2665   if (byte_offset < 0 || byte_offset & mask) {
2666     mov(Rd, byte_offset);
2667     add(Rd, base, Rd);
2668     return Address(Rd);
2669   }
2670 
2671   // See if we can do this with two 12-bit offsets
2672   {
2673     uint64_t word_offset = byte_offset >> shift;
2674     uint64_t masked_offset = word_offset & 0xfff000;
2675     if (Address::offset_ok_for_immed(word_offset - masked_offset, 0)
2676         && Assembler::operand_valid_for_add_sub_immediate(masked_offset << shift)) {
2677       add(Rd, base, masked_offset << shift);
2678       word_offset -= masked_offset;
2679       return Address(Rd, word_offset << shift);
2680     }
2681   }
2682 
2683   // Do it the hard way
2684   mov(Rd, byte_offset);
2685   add(Rd, base, Rd);
2686   return Address(Rd);
2687 }
2688 
2689 int MacroAssembler::corrected_idivl(Register result, Register ra, Register rb,
2690                                     bool want_remainder, Register scratch)
2691 {
2692   // Full implementation of Java idiv and irem.  The function
2693   // returns the (pc) offset of the div instruction - may be needed
2694   // for implicit exceptions.
2695   //
2696   // constraint : ra/rb =/= scratch
2697   //         normal case
2698   //
2699   // input : ra: dividend
2700   //         rb: divisor
2701   //
2702   // result: either
2703   //         quotient  (= ra idiv rb)
2704   //         remainder (= ra irem rb)
2705 
2706   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
2707 
2708   int idivl_offset = offset();
2709   if (! want_remainder) {
2710     sdivw(result, ra, rb);
2711   } else {
2712     sdivw(scratch, ra, rb);
2713     Assembler::msubw(result, scratch, rb, ra);
2714   }
2715 
2716   return idivl_offset;
2717 }
2718 
2719 int MacroAssembler::corrected_idivq(Register result, Register ra, Register rb,
2720                                     bool want_remainder, Register scratch)
2721 {
2722   // Full implementation of Java ldiv and lrem.  The function
2723   // returns the (pc) offset of the div instruction - may be needed
2724   // for implicit exceptions.
2725   //
2726   // constraint : ra/rb =/= scratch
2727   //         normal case
2728   //
2729   // input : ra: dividend
2730   //         rb: divisor
2731   //
2732   // result: either
2733   //         quotient  (= ra idiv rb)
2734   //         remainder (= ra irem rb)
2735 
2736   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
2737 
2738   int idivq_offset = offset();
2739   if (! want_remainder) {
2740     sdiv(result, ra, rb);
2741   } else {
2742     sdiv(scratch, ra, rb);
2743     Assembler::msub(result, scratch, rb, ra);
2744   }
2745 
2746   return idivq_offset;
2747 }
2748 
2749 void MacroAssembler::membar(Membar_mask_bits order_constraint) {
2750   address prev = pc() - NativeMembar::instruction_size;
2751   address last = code()->last_merge_candidate();
2752   if (last != nullptr && nativeInstruction_at(last)->is_Membar() && prev == last) {
2753     NativeMembar *bar = NativeMembar_at(prev);
2754     if (AlwaysMergeDMB) {
2755       bar->set_kind(bar->get_kind() | order_constraint);
2756       BLOCK_COMMENT("merged membar(always)");
2757       return;
2758     }
2759     // Don't promote DMB ST|DMB LD to DMB (a full barrier) because
2760     // doing so would introduce a StoreLoad which the caller did not
2761     // intend
2762     if (bar->get_kind() == order_constraint
2763         || bar->get_kind() == AnyAny
2764         || order_constraint == AnyAny) {
2765       // We are merging two memory barrier instructions.  On AArch64 we
2766       // can do this simply by ORing them together.
2767       bar->set_kind(bar->get_kind() | order_constraint);
2768       BLOCK_COMMENT("merged membar");
2769       return;
2770     } else {
2771       // A special case like "DMB ST;DMB LD;DMB ST", the last DMB can be skipped.
2772       // We need to check the second-to-last instruction, only if it is inside
2773       // the current code section.
2774       address prev2 = prev - NativeMembar::instruction_size;
2775       if (prev2 >= begin() && last != code()->last_label() && nativeInstruction_at(prev2)->is_Membar()) {
2776         NativeMembar *bar2 = NativeMembar_at(prev2);
2777         assert(bar2->get_kind() == order_constraint, "it should be merged before");
2778         BLOCK_COMMENT("merged membar(elided)");
2779         return;
2780       }
2781     }
2782   }
2783   code()->set_last_merge_candidate(pc());
2784   dmb(Assembler::barrier(order_constraint));
2785 }
2786 
2787 bool MacroAssembler::try_merge_ldst(Register rt, const Address &adr, size_t size_in_bytes, bool is_store) {
2788   if (ldst_can_merge(rt, adr, size_in_bytes, is_store)) {
2789     merge_ldst(rt, adr, size_in_bytes, is_store);
2790     code()->clear_last_merge_candidate();
2791     return true;
2792   } else {
2793     assert(size_in_bytes == 8 || size_in_bytes == 4, "only 8 bytes or 4 bytes load/store is supported.");
2794     const uint64_t mask = size_in_bytes - 1;
2795     if (adr.getMode() == Address::base_plus_offset &&
2796         (adr.offset() & mask) == 0) { // only supports base_plus_offset.
2797       code()->set_last_merge_candidate(pc());
2798     }
2799     return false;
2800   }
2801 }
2802 
2803 void MacroAssembler::ldr(Register Rx, const Address &adr) {
2804   // We always try to merge two adjacent loads into one ldp.
2805   if (!try_merge_ldst(Rx, adr, 8, false)) {
2806     Assembler::ldr(Rx, adr);
2807   }
2808 }
2809 
2810 void MacroAssembler::ldrw(Register Rw, const Address &adr) {
2811   // We always try to merge two adjacent loads into one ldp.
2812   if (!try_merge_ldst(Rw, adr, 4, false)) {
2813     Assembler::ldrw(Rw, adr);
2814   }
2815 }
2816 
2817 void MacroAssembler::str(Register Rx, const Address &adr) {
2818   // We always try to merge two adjacent stores into one stp.
2819   if (!try_merge_ldst(Rx, adr, 8, true)) {
2820     Assembler::str(Rx, adr);
2821   }
2822 }
2823 
2824 void MacroAssembler::strw(Register Rw, const Address &adr) {
2825   // We always try to merge two adjacent stores into one stp.
2826   if (!try_merge_ldst(Rw, adr, 4, true)) {
2827     Assembler::strw(Rw, adr);
2828   }
2829 }
2830 
2831 // MacroAssembler routines found actually to be needed
2832 
2833 void MacroAssembler::push(Register src)
2834 {
2835   str(src, Address(pre(esp, -1 * wordSize)));
2836 }
2837 
2838 void MacroAssembler::pop(Register dst)
2839 {
2840   ldr(dst, Address(post(esp, 1 * wordSize)));
2841 }
2842 
2843 // Note: load_unsigned_short used to be called load_unsigned_word.
2844 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
2845   int off = offset();
2846   ldrh(dst, src);
2847   return off;
2848 }
2849 
2850 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
2851   int off = offset();
2852   ldrb(dst, src);
2853   return off;
2854 }
2855 
2856 int MacroAssembler::load_signed_short(Register dst, Address src) {
2857   int off = offset();
2858   ldrsh(dst, src);
2859   return off;
2860 }
2861 
2862 int MacroAssembler::load_signed_byte(Register dst, Address src) {
2863   int off = offset();
2864   ldrsb(dst, src);
2865   return off;
2866 }
2867 
2868 int MacroAssembler::load_signed_short32(Register dst, Address src) {
2869   int off = offset();
2870   ldrshw(dst, src);
2871   return off;
2872 }
2873 
2874 int MacroAssembler::load_signed_byte32(Register dst, Address src) {
2875   int off = offset();
2876   ldrsbw(dst, src);
2877   return off;
2878 }
2879 
2880 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed) {
2881   switch (size_in_bytes) {
2882   case  8:  ldr(dst, src); break;
2883   case  4:  ldrw(dst, src); break;
2884   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
2885   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
2886   default:  ShouldNotReachHere();
2887   }
2888 }
2889 
2890 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes) {
2891   switch (size_in_bytes) {
2892   case  8:  str(src, dst); break;
2893   case  4:  strw(src, dst); break;
2894   case  2:  strh(src, dst); break;
2895   case  1:  strb(src, dst); break;
2896   default:  ShouldNotReachHere();
2897   }
2898 }
2899 
2900 void MacroAssembler::narrow_subword_type(Register reg, BasicType bt) {
2901   assert(is_subword_type(bt), "required");
2902   switch (bt) {
2903   case T_BOOLEAN: andw(reg, reg, 1); break;
2904   case T_BYTE:    sxtbw(reg, reg); break;
2905   case T_CHAR:    uxthw(reg, reg); break;
2906   case T_SHORT:   sxthw(reg, reg); break;
2907   default:        ShouldNotReachHere();
2908   }
2909 }
2910 
2911 void MacroAssembler::decrementw(Register reg, int value)
2912 {
2913   if (value < 0)  { incrementw(reg, -value);      return; }
2914   if (value == 0) {                               return; }
2915   if (value < (1 << 12)) { subw(reg, reg, value); return; }
2916   /* else */ {
2917     guarantee(reg != rscratch2, "invalid dst for register decrement");
2918     movw(rscratch2, (unsigned)value);
2919     subw(reg, reg, rscratch2);
2920   }
2921 }
2922 
2923 void MacroAssembler::decrement(Register reg, int value)
2924 {
2925   if (value < 0)  { increment(reg, -value);      return; }
2926   if (value == 0) {                              return; }
2927   if (value < (1 << 12)) { sub(reg, reg, value); return; }
2928   /* else */ {
2929     assert(reg != rscratch2, "invalid dst for register decrement");
2930     mov(rscratch2, (uint64_t)value);
2931     sub(reg, reg, rscratch2);
2932   }
2933 }
2934 
2935 void MacroAssembler::decrementw(Address dst, int value)
2936 {
2937   assert(!dst.uses(rscratch1), "invalid dst for address decrement");
2938   if (dst.getMode() == Address::literal) {
2939     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2940     lea(rscratch2, dst);
2941     dst = Address(rscratch2);
2942   }
2943   ldrw(rscratch1, dst);
2944   decrementw(rscratch1, value);
2945   strw(rscratch1, dst);
2946 }
2947 
2948 void MacroAssembler::decrement(Address dst, int value)
2949 {
2950   assert(!dst.uses(rscratch1), "invalid address for decrement");
2951   if (dst.getMode() == Address::literal) {
2952     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2953     lea(rscratch2, dst);
2954     dst = Address(rscratch2);
2955   }
2956   ldr(rscratch1, dst);
2957   decrement(rscratch1, value);
2958   str(rscratch1, dst);
2959 }
2960 
2961 void MacroAssembler::incrementw(Register reg, int value)
2962 {
2963   if (value < 0)  { decrementw(reg, -value);      return; }
2964   if (value == 0) {                               return; }
2965   if (value < (1 << 12)) { addw(reg, reg, value); return; }
2966   /* else */ {
2967     assert(reg != rscratch2, "invalid dst for register increment");
2968     movw(rscratch2, (unsigned)value);
2969     addw(reg, reg, rscratch2);
2970   }
2971 }
2972 
2973 void MacroAssembler::increment(Register reg, int value)
2974 {
2975   if (value < 0)  { decrement(reg, -value);      return; }
2976   if (value == 0) {                              return; }
2977   if (value < (1 << 12)) { add(reg, reg, value); return; }
2978   /* else */ {
2979     assert(reg != rscratch2, "invalid dst for register increment");
2980     movw(rscratch2, (unsigned)value);
2981     add(reg, reg, rscratch2);
2982   }
2983 }
2984 
2985 void MacroAssembler::incrementw(Address dst, int value)
2986 {
2987   assert(!dst.uses(rscratch1), "invalid dst for address increment");
2988   if (dst.getMode() == Address::literal) {
2989     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2990     lea(rscratch2, dst);
2991     dst = Address(rscratch2);
2992   }
2993   ldrw(rscratch1, dst);
2994   incrementw(rscratch1, value);
2995   strw(rscratch1, dst);
2996 }
2997 
2998 void MacroAssembler::increment(Address dst, int value)
2999 {
3000   assert(!dst.uses(rscratch1), "invalid dst for address increment");
3001   if (dst.getMode() == Address::literal) {
3002     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
3003     lea(rscratch2, dst);
3004     dst = Address(rscratch2);
3005   }
3006   ldr(rscratch1, dst);
3007   increment(rscratch1, value);
3008   str(rscratch1, dst);
3009 }
3010 
3011 // Push lots of registers in the bit set supplied.  Don't push sp.
3012 // Return the number of words pushed
3013 int MacroAssembler::push(RegSet regset, Register stack) {
3014   if (regset.bits() == 0) {
3015     return 0;
3016   }
3017   auto bitset = integer_cast<unsigned int>(regset.bits());
3018   int words_pushed = 0;
3019 
3020   // Scan bitset to accumulate register pairs
3021   unsigned char regs[32];
3022   int count = 0;
3023   for (int reg = 0; reg <= 30; reg++) {
3024     if (1 & bitset)
3025       regs[count++] = reg;
3026     bitset >>= 1;
3027   }
3028   regs[count++] = zr->raw_encoding();
3029   count &= ~1;  // Only push an even number of regs
3030 
3031   if (count) {
3032     stp(as_Register(regs[0]), as_Register(regs[1]),
3033        Address(pre(stack, -count * wordSize)));
3034     words_pushed += 2;
3035   }
3036   for (int i = 2; i < count; i += 2) {
3037     stp(as_Register(regs[i]), as_Register(regs[i+1]),
3038        Address(stack, i * wordSize));
3039     words_pushed += 2;
3040   }
3041 
3042   assert(words_pushed == count, "oops, pushed != count");
3043 
3044   return count;
3045 }
3046 
3047 int MacroAssembler::pop(RegSet regset, Register stack) {
3048   if (regset.bits() == 0) {
3049     return 0;
3050   }
3051   auto bitset = integer_cast<unsigned int>(regset.bits());
3052   int words_pushed = 0;
3053 
3054   // Scan bitset to accumulate register pairs
3055   unsigned char regs[32];
3056   int count = 0;
3057   for (int reg = 0; reg <= 30; reg++) {
3058     if (1 & bitset)
3059       regs[count++] = reg;
3060     bitset >>= 1;
3061   }
3062   regs[count++] = zr->raw_encoding();
3063   count &= ~1;
3064 
3065   for (int i = 2; i < count; i += 2) {
3066     ldp(as_Register(regs[i]), as_Register(regs[i+1]),
3067        Address(stack, i * wordSize));
3068     words_pushed += 2;
3069   }
3070   if (count) {
3071     ldp(as_Register(regs[0]), as_Register(regs[1]),
3072        Address(post(stack, count * wordSize)));
3073     words_pushed += 2;
3074   }
3075 
3076   assert(words_pushed == count, "oops, pushed != count");
3077 
3078   return count;
3079 }
3080 
3081 // Push lots of registers in the bit set supplied.  Don't push sp.
3082 // Return the number of dwords pushed
3083 int MacroAssembler::push_fp(FloatRegSet regset, Register stack, FpPushPopMode mode) {
3084   if (regset.bits() == 0) {
3085     return 0;
3086   }
3087   auto bitset = integer_cast<unsigned int>(regset.bits());
3088   int words_pushed = 0;
3089   bool use_sve = false;
3090   int sve_vector_size_in_bytes = 0;
3091 
3092 #ifdef COMPILER2
3093   use_sve = Matcher::supports_scalable_vector();
3094   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
3095 #endif
3096 
3097   // Scan bitset to accumulate register pairs
3098   unsigned char regs[32];
3099   int count = 0;
3100   for (int reg = 0; reg <= 31; reg++) {
3101     if (1 & bitset)
3102       regs[count++] = reg;
3103     bitset >>= 1;
3104   }
3105 
3106   if (count == 0) {
3107     return 0;
3108   }
3109 
3110   if (mode == PushPopFull) {
3111     if (use_sve && sve_vector_size_in_bytes > 16) {
3112       mode = PushPopSVE;
3113     } else {
3114       mode = PushPopNeon;
3115     }
3116   }
3117 
3118 #ifndef PRODUCT
3119   {
3120     char buffer[48];
3121     if (mode == PushPopSVE) {
3122       os::snprintf_checked(buffer, sizeof(buffer), "push_fp: %d SVE registers", count);
3123     } else if (mode == PushPopNeon) {
3124       os::snprintf_checked(buffer, sizeof(buffer), "push_fp: %d Neon registers", count);
3125     } else {
3126       os::snprintf_checked(buffer, sizeof(buffer), "push_fp: %d fp registers", count);
3127     }
3128     block_comment(buffer);
3129   }
3130 #endif
3131 
3132   if (mode == PushPopSVE) {
3133     sub(stack, stack, sve_vector_size_in_bytes * count);
3134     for (int i = 0; i < count; i++) {
3135       sve_str(as_FloatRegister(regs[i]), Address(stack, i));
3136     }
3137     return count * sve_vector_size_in_bytes / 8;
3138   }
3139 
3140   if (mode == PushPopNeon) {
3141     if (count == 1) {
3142       strq(as_FloatRegister(regs[0]), Address(pre(stack, -wordSize * 2)));
3143       return 2;
3144     }
3145 
3146     bool odd = (count & 1) == 1;
3147     int push_slots = count + (odd ? 1 : 0);
3148 
3149     // Always pushing full 128 bit registers.
3150     stpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(pre(stack, -push_slots * wordSize * 2)));
3151     words_pushed += 2;
3152 
3153     for (int i = 2; i + 1 < count; i += 2) {
3154       stpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
3155       words_pushed += 2;
3156     }
3157 
3158     if (odd) {
3159       strq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
3160       words_pushed++;
3161     }
3162 
3163     assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
3164     return count * 2;
3165   }
3166 
3167   if (mode == PushPopFp) {
3168     bool odd = (count & 1) == 1;
3169     int push_slots = count + (odd ? 1 : 0);
3170 
3171     if (count == 1) {
3172       // Stack pointer must be 16 bytes aligned
3173       strd(as_FloatRegister(regs[0]), Address(pre(stack, -push_slots * wordSize)));
3174       return 1;
3175     }
3176 
3177     stpd(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(pre(stack, -push_slots * wordSize)));
3178     words_pushed += 2;
3179 
3180     for (int i = 2; i + 1 < count; i += 2) {
3181       stpd(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize));
3182       words_pushed += 2;
3183     }
3184 
3185     if (odd) {
3186       // Stack pointer must be 16 bytes aligned
3187       strd(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize));
3188       words_pushed++;
3189     }
3190 
3191     assert(words_pushed == count, "oops, pushed != count");
3192 
3193     return count;
3194   }
3195 
3196   return 0;
3197 }
3198 
3199 // Return the number of dwords popped
3200 int MacroAssembler::pop_fp(FloatRegSet regset, Register stack, FpPushPopMode mode) {
3201   if (regset.bits() == 0) {
3202     return 0;
3203   }
3204   auto bitset = integer_cast<unsigned int>(regset.bits());
3205   int words_pushed = 0;
3206   bool use_sve = false;
3207   int sve_vector_size_in_bytes = 0;
3208 
3209 #ifdef COMPILER2
3210   use_sve = Matcher::supports_scalable_vector();
3211   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
3212 #endif
3213   // Scan bitset to accumulate register pairs
3214   unsigned char regs[32];
3215   int count = 0;
3216   for (int reg = 0; reg <= 31; reg++) {
3217     if (1 & bitset)
3218       regs[count++] = reg;
3219     bitset >>= 1;
3220   }
3221 
3222   if (count == 0) {
3223     return 0;
3224   }
3225 
3226   if (mode == PushPopFull) {
3227     if (use_sve && sve_vector_size_in_bytes > 16) {
3228       mode = PushPopSVE;
3229     } else {
3230       mode = PushPopNeon;
3231     }
3232   }
3233 
3234 #ifndef PRODUCT
3235   {
3236     char buffer[48];
3237     if (mode == PushPopSVE) {
3238       os::snprintf_checked(buffer, sizeof(buffer), "pop_fp: %d SVE registers", count);
3239     } else if (mode == PushPopNeon) {
3240       os::snprintf_checked(buffer, sizeof(buffer), "pop_fp: %d Neon registers", count);
3241     } else {
3242       os::snprintf_checked(buffer, sizeof(buffer), "pop_fp: %d fp registers", count);
3243     }
3244     block_comment(buffer);
3245   }
3246 #endif
3247 
3248   if (mode == PushPopSVE) {
3249     for (int i = count - 1; i >= 0; i--) {
3250       sve_ldr(as_FloatRegister(regs[i]), Address(stack, i));
3251     }
3252     add(stack, stack, sve_vector_size_in_bytes * count);
3253     return count * sve_vector_size_in_bytes / 8;
3254   }
3255 
3256   if (mode == PushPopNeon) {
3257     if (count == 1) {
3258       ldrq(as_FloatRegister(regs[0]), Address(post(stack, wordSize * 2)));
3259       return 2;
3260     }
3261 
3262     bool odd = (count & 1) == 1;
3263     int push_slots = count + (odd ? 1 : 0);
3264 
3265     if (odd) {
3266       ldrq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
3267       words_pushed++;
3268     }
3269 
3270     for (int i = 2; i + 1 < count; i += 2) {
3271       ldpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
3272       words_pushed += 2;
3273     }
3274 
3275     ldpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(post(stack, push_slots * wordSize * 2)));
3276     words_pushed += 2;
3277 
3278     assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
3279 
3280     return count * 2;
3281   }
3282 
3283   if (mode == PushPopFp) {
3284     bool odd = (count & 1) == 1;
3285     int push_slots = count + (odd ? 1 : 0);
3286 
3287     if (count == 1) {
3288       ldrd(as_FloatRegister(regs[0]), Address(post(stack, push_slots * wordSize)));
3289       return 1;
3290     }
3291 
3292     if (odd) {
3293       ldrd(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize));
3294       words_pushed++;
3295     }
3296 
3297     for (int i = 2; i + 1 < count; i += 2) {
3298       ldpd(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize));
3299       words_pushed += 2;
3300     }
3301 
3302     ldpd(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(post(stack, push_slots * wordSize)));
3303     words_pushed += 2;
3304 
3305     assert(words_pushed == count, "oops, pushed != count");
3306 
3307     return count;
3308   }
3309 
3310   return 0;
3311 }
3312 
3313 // Return the number of dwords pushed
3314 int MacroAssembler::push_p(PRegSet regset, Register stack) {
3315   if (regset.bits() == 0) {
3316     return 0;
3317   }
3318   auto bitset = integer_cast<unsigned int>(regset.bits());
3319   bool use_sve = false;
3320   int sve_predicate_size_in_slots = 0;
3321 
3322 #ifdef COMPILER2
3323   use_sve = Matcher::supports_scalable_vector();
3324   if (use_sve) {
3325     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
3326   }
3327 #endif
3328 
3329   if (!use_sve) {
3330     return 0;
3331   }
3332 
3333   unsigned char regs[PRegister::number_of_registers];
3334   int count = 0;
3335   for (int reg = 0; reg < PRegister::number_of_registers; reg++) {
3336     if (1 & bitset)
3337       regs[count++] = reg;
3338     bitset >>= 1;
3339   }
3340 
3341   if (count == 0) {
3342     return 0;
3343   }
3344 
3345   int total_push_bytes = align_up(sve_predicate_size_in_slots *
3346                                   VMRegImpl::stack_slot_size * count, 16);
3347   sub(stack, stack, total_push_bytes);
3348   for (int i = 0; i < count; i++) {
3349     sve_str(as_PRegister(regs[i]), Address(stack, i));
3350   }
3351   return total_push_bytes / 8;
3352 }
3353 
3354 // Return the number of dwords popped
3355 int MacroAssembler::pop_p(PRegSet regset, Register stack) {
3356   if (regset.bits() == 0) {
3357     return 0;
3358   }
3359   auto bitset = integer_cast<unsigned int>(regset.bits());
3360   bool use_sve = false;
3361   int sve_predicate_size_in_slots = 0;
3362 
3363 #ifdef COMPILER2
3364   use_sve = Matcher::supports_scalable_vector();
3365   if (use_sve) {
3366     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
3367   }
3368 #endif
3369 
3370   if (!use_sve) {
3371     return 0;
3372   }
3373 
3374   unsigned char regs[PRegister::number_of_registers];
3375   int count = 0;
3376   for (int reg = 0; reg < PRegister::number_of_registers; reg++) {
3377     if (1 & bitset)
3378       regs[count++] = reg;
3379     bitset >>= 1;
3380   }
3381 
3382   if (count == 0) {
3383     return 0;
3384   }
3385 
3386   int total_pop_bytes = align_up(sve_predicate_size_in_slots *
3387                                  VMRegImpl::stack_slot_size * count, 16);
3388   for (int i = count - 1; i >= 0; i--) {
3389     sve_ldr(as_PRegister(regs[i]), Address(stack, i));
3390   }
3391   add(stack, stack, total_pop_bytes);
3392   return total_pop_bytes / 8;
3393 }
3394 
3395 #ifdef ASSERT
3396 void MacroAssembler::verify_heapbase(const char* msg) {
3397 #if 0
3398   assert (Universe::heap() != nullptr, "java heap should be initialized");
3399   if (!UseCompressedOops || Universe::ptr_base() == nullptr) {
3400     // rheapbase is allocated as general register
3401     return;
3402   }
3403   if (CheckCompressedOops) {
3404     Label ok;
3405     push(1 << rscratch1->encoding(), sp); // cmpptr trashes rscratch1
3406     cmpptr(rheapbase, ExternalAddress(CompressedOops::base_addr()));
3407     br(Assembler::EQ, ok);
3408     stop(msg);
3409     bind(ok);
3410     pop(1 << rscratch1->encoding(), sp);
3411   }
3412 #endif
3413 }
3414 #endif
3415 
3416 void MacroAssembler::resolve_jobject(Register value, Register tmp1, Register tmp2) {
3417   assert_different_registers(value, tmp1, tmp2);
3418   Label done, tagged, weak_tagged;
3419 
3420   cbz(value, done);           // Use null as-is.
3421   tst(value, JNIHandles::tag_mask); // Test for tag.
3422   br(Assembler::NE, tagged);
3423 
3424   // Resolve local handle
3425   access_load_at(T_OBJECT, IN_NATIVE | AS_RAW, value, Address(value, 0), tmp1, tmp2);
3426   verify_oop(value);
3427   b(done);
3428 
3429   bind(tagged);
3430   STATIC_ASSERT(JNIHandles::TypeTag::weak_global == 0b1);
3431   tbnz(value, 0, weak_tagged);    // Test for weak tag.
3432 
3433   // Resolve global handle
3434   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, -JNIHandles::TypeTag::global), tmp1, tmp2);
3435   verify_oop(value);
3436   b(done);
3437 
3438   bind(weak_tagged);
3439   // Resolve jweak.
3440   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
3441                  value, Address(value, -JNIHandles::TypeTag::weak_global), tmp1, tmp2);
3442   verify_oop(value);
3443 
3444   bind(done);
3445 }
3446 
3447 void MacroAssembler::resolve_global_jobject(Register value, Register tmp1, Register tmp2) {
3448   assert_different_registers(value, tmp1, tmp2);
3449   Label done;
3450 
3451   cbz(value, done);           // Use null as-is.
3452 
3453 #ifdef ASSERT
3454   {
3455     STATIC_ASSERT(JNIHandles::TypeTag::global == 0b10);
3456     Label valid_global_tag;
3457     tbnz(value, 1, valid_global_tag); // Test for global tag
3458     stop("non global jobject using resolve_global_jobject");
3459     bind(valid_global_tag);
3460   }
3461 #endif
3462 
3463   // Resolve global handle
3464   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, -JNIHandles::TypeTag::global), tmp1, tmp2);
3465   verify_oop(value);
3466 
3467   bind(done);
3468 }
3469 
3470 void MacroAssembler::stop(const char* msg) {
3471   // Skip AOT caching C strings in scratch buffer.
3472   const char* str = (code_section()->scratch_emit()) ? msg : AOTCodeCache::add_C_string(msg);
3473   BLOCK_COMMENT(str);
3474   // load msg into r0 so we can access it from the signal handler
3475   // ExternalAddress enables saving and restoring via the code cache
3476   lea(c_rarg0, ExternalAddress((address) str));
3477   dcps1(0xdeae);
3478 }
3479 
3480 void MacroAssembler::unimplemented(const char* what) {
3481   const char* buf = nullptr;
3482   {
3483     ResourceMark rm;
3484     stringStream ss;
3485     ss.print("unimplemented: %s", what);
3486     buf = code_string(ss.as_string());
3487   }
3488   stop(buf);
3489 }
3490 
3491 void MacroAssembler::_assert_asm(Assembler::Condition cc, const char* msg) {
3492 #ifdef ASSERT
3493   Label OK;
3494   br(cc, OK);
3495   stop(msg);
3496   bind(OK);
3497 #endif
3498 }
3499 
3500 // If a constant does not fit in an immediate field, generate some
3501 // number of MOV instructions and then perform the operation.
3502 void MacroAssembler::wrap_add_sub_imm_insn(Register Rd, Register Rn, uint64_t imm,
3503                                            add_sub_imm_insn insn1,
3504                                            add_sub_reg_insn insn2,
3505                                            bool is32) {
3506   assert(Rd != zr, "Rd = zr and not setting flags?");
3507   bool fits = operand_valid_for_add_sub_immediate(is32 ? (int32_t)imm : imm);
3508   if (fits) {
3509     (this->*insn1)(Rd, Rn, imm);
3510   } else {
3511     if (g_uabs(imm) < (1 << 24)) {
3512        (this->*insn1)(Rd, Rn, imm & -(1 << 12));
3513        (this->*insn1)(Rd, Rd, imm & ((1 << 12)-1));
3514     } else {
3515        assert_different_registers(Rd, Rn);
3516        mov(Rd, imm);
3517        (this->*insn2)(Rd, Rn, Rd, LSL, 0);
3518     }
3519   }
3520 }
3521 
3522 // Separate vsn which sets the flags. Optimisations are more restricted
3523 // because we must set the flags correctly.
3524 void MacroAssembler::wrap_adds_subs_imm_insn(Register Rd, Register Rn, uint64_t imm,
3525                                              add_sub_imm_insn insn1,
3526                                              add_sub_reg_insn insn2,
3527                                              bool is32) {
3528   bool fits = operand_valid_for_add_sub_immediate(is32 ? (int32_t)imm : imm);
3529   if (fits) {
3530     (this->*insn1)(Rd, Rn, imm);
3531   } else {
3532     assert_different_registers(Rd, Rn);
3533     assert(Rd != zr, "overflow in immediate operand");
3534     mov(Rd, imm);
3535     (this->*insn2)(Rd, Rn, Rd, LSL, 0);
3536   }
3537 }
3538 
3539 
3540 void MacroAssembler::add(Register Rd, Register Rn, RegisterOrConstant increment) {
3541   if (increment.is_register()) {
3542     add(Rd, Rn, increment.as_register());
3543   } else {
3544     add(Rd, Rn, increment.as_constant());
3545   }
3546 }
3547 
3548 void MacroAssembler::addw(Register Rd, Register Rn, RegisterOrConstant increment) {
3549   if (increment.is_register()) {
3550     addw(Rd, Rn, increment.as_register());
3551   } else {
3552     addw(Rd, Rn, increment.as_constant());
3553   }
3554 }
3555 
3556 void MacroAssembler::sub(Register Rd, Register Rn, RegisterOrConstant decrement) {
3557   if (decrement.is_register()) {
3558     sub(Rd, Rn, decrement.as_register());
3559   } else {
3560     sub(Rd, Rn, decrement.as_constant());
3561   }
3562 }
3563 
3564 void MacroAssembler::subw(Register Rd, Register Rn, RegisterOrConstant decrement) {
3565   if (decrement.is_register()) {
3566     subw(Rd, Rn, decrement.as_register());
3567   } else {
3568     subw(Rd, Rn, decrement.as_constant());
3569   }
3570 }
3571 
3572 void MacroAssembler::reinit_heapbase()
3573 {
3574   if (UseCompressedOops) {
3575     if (Universe::is_fully_initialized() && !AOTCodeCache::is_on_for_dump()) {
3576       mov(rheapbase, CompressedOops::base());
3577     } else {
3578       lea(rheapbase, ExternalAddress(CompressedOops::base_addr()));
3579       ldr(rheapbase, Address(rheapbase));
3580     }
3581   }
3582 }
3583 
3584 // A generic CAS; success or failure is in the EQ flag.  A weak CAS
3585 // doesn't retry and may fail spuriously.  If the oldval is wanted,
3586 // Pass a register for the result, otherwise pass noreg.
3587 
3588 // Clobbers rscratch1
3589 void MacroAssembler::cmpxchg(Register addr, Register expected,
3590                              Register new_val,
3591                              enum operand_size size,
3592                              bool acquire, bool release,
3593                              bool weak,
3594                              Register result) {
3595   if (result == noreg)  result = rscratch1;
3596   BLOCK_COMMENT("cmpxchg {");
3597   if (UseLSE) {
3598     mov(result, expected);
3599     lse_cas(result, new_val, addr, size, acquire, release, /*not_pair*/ true);
3600     compare_eq(result, expected, size);
3601 #ifdef ASSERT
3602     // Poison rscratch1 which is written on !UseLSE branch
3603     mov(rscratch1, 0x1f1f1f1f1f1f1f1f);
3604 #endif
3605   } else {
3606     Label retry_load, done;
3607     prfm(Address(addr), PSTL1STRM);
3608     bind(retry_load);
3609     load_exclusive(result, addr, size, acquire);
3610     compare_eq(result, expected, size);
3611     br(Assembler::NE, done);
3612     store_exclusive(rscratch1, new_val, addr, size, release);
3613     if (weak) {
3614       cmpw(rscratch1, 0u);  // If the store fails, return NE to our caller.
3615     } else {
3616       cbnzw(rscratch1, retry_load);
3617     }
3618     bind(done);
3619   }
3620   BLOCK_COMMENT("} cmpxchg");
3621 }
3622 
3623 // A generic comparison. Only compares for equality, clobbers rscratch1.
3624 void MacroAssembler::compare_eq(Register rm, Register rn, enum operand_size size) {
3625   if (size == xword) {
3626     cmp(rm, rn);
3627   } else if (size == word) {
3628     cmpw(rm, rn);
3629   } else if (size == halfword) {
3630     eorw(rscratch1, rm, rn);
3631     ands(zr, rscratch1, 0xffff);
3632   } else if (size == byte) {
3633     eorw(rscratch1, rm, rn);
3634     ands(zr, rscratch1, 0xff);
3635   } else {
3636     ShouldNotReachHere();
3637   }
3638 }
3639 
3640 
3641 static bool different(Register a, RegisterOrConstant b, Register c) {
3642   if (b.is_constant())
3643     return a != c;
3644   else
3645     return a != b.as_register() && a != c && b.as_register() != c;
3646 }
3647 
3648 #define ATOMIC_OP(NAME, LDXR, OP, IOP, AOP, STXR, sz)                   \
3649 void MacroAssembler::atomic_##NAME(Register prev, RegisterOrConstant incr, Register addr) { \
3650   if (UseLSE) {                                                         \
3651     prev = prev->is_valid() ? prev : zr;                                \
3652     if (incr.is_register()) {                                           \
3653       AOP(sz, incr.as_register(), prev, addr);                          \
3654     } else {                                                            \
3655       mov(rscratch2, incr.as_constant());                               \
3656       AOP(sz, rscratch2, prev, addr);                                   \
3657     }                                                                   \
3658     return;                                                             \
3659   }                                                                     \
3660   Register result = rscratch2;                                          \
3661   if (prev->is_valid())                                                 \
3662     result = different(prev, incr, addr) ? prev : rscratch2;            \
3663                                                                         \
3664   Label retry_load;                                                     \
3665   prfm(Address(addr), PSTL1STRM);                                       \
3666   bind(retry_load);                                                     \
3667   LDXR(result, addr);                                                   \
3668   OP(rscratch1, result, incr);                                          \
3669   STXR(rscratch2, rscratch1, addr);                                     \
3670   cbnzw(rscratch2, retry_load);                                         \
3671   if (prev->is_valid() && prev != result) {                             \
3672     IOP(prev, rscratch1, incr);                                         \
3673   }                                                                     \
3674 }
3675 
3676 ATOMIC_OP(add, ldxr, add, sub, ldadd, stxr, Assembler::xword)
3677 ATOMIC_OP(addw, ldxrw, addw, subw, ldadd, stxrw, Assembler::word)
3678 ATOMIC_OP(addal, ldaxr, add, sub, ldaddal, stlxr, Assembler::xword)
3679 ATOMIC_OP(addalw, ldaxrw, addw, subw, ldaddal, stlxrw, Assembler::word)
3680 
3681 #undef ATOMIC_OP
3682 
3683 #define ATOMIC_XCHG(OP, AOP, LDXR, STXR, sz)                            \
3684 void MacroAssembler::atomic_##OP(Register prev, Register newv, Register addr) { \
3685   if (UseLSE) {                                                         \
3686     prev = prev->is_valid() ? prev : zr;                                \
3687     AOP(sz, newv, prev, addr);                                          \
3688     return;                                                             \
3689   }                                                                     \
3690   Register result = rscratch2;                                          \
3691   if (prev->is_valid())                                                 \
3692     result = different(prev, newv, addr) ? prev : rscratch2;            \
3693                                                                         \
3694   Label retry_load;                                                     \
3695   prfm(Address(addr), PSTL1STRM);                                       \
3696   bind(retry_load);                                                     \
3697   LDXR(result, addr);                                                   \
3698   STXR(rscratch1, newv, addr);                                          \
3699   cbnzw(rscratch1, retry_load);                                         \
3700   if (prev->is_valid() && prev != result)                               \
3701     mov(prev, result);                                                  \
3702 }
3703 
3704 ATOMIC_XCHG(xchg, swp, ldxr, stxr, Assembler::xword)
3705 ATOMIC_XCHG(xchgw, swp, ldxrw, stxrw, Assembler::word)
3706 ATOMIC_XCHG(xchgl, swpl, ldxr, stlxr, Assembler::xword)
3707 ATOMIC_XCHG(xchglw, swpl, ldxrw, stlxrw, Assembler::word)
3708 ATOMIC_XCHG(xchgal, swpal, ldaxr, stlxr, Assembler::xword)
3709 ATOMIC_XCHG(xchgalw, swpal, ldaxrw, stlxrw, Assembler::word)
3710 
3711 #undef ATOMIC_XCHG
3712 
3713 #ifndef PRODUCT
3714 extern "C" void findpc(intptr_t x);
3715 #endif
3716 
3717 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[])
3718 {
3719   // In order to get locks to work, we need to fake a in_VM state
3720   if (ShowMessageBoxOnError) {
3721     JavaThread* thread = JavaThread::current();
3722     thread->set_thread_state(_thread_in_vm);
3723 #ifndef PRODUCT
3724     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
3725       ttyLocker ttyl;
3726       BytecodeCounter::print();
3727     }
3728 #endif
3729     if (os::message_box(msg, "Execution stopped, print registers?")) {
3730       ttyLocker ttyl;
3731       tty->print_cr(" pc = 0x%016" PRIx64, pc);
3732 #ifndef PRODUCT
3733       tty->cr();
3734       findpc(pc);
3735       tty->cr();
3736 #endif
3737       tty->print_cr(" r0 = 0x%016" PRIx64, regs[0]);
3738       tty->print_cr(" r1 = 0x%016" PRIx64, regs[1]);
3739       tty->print_cr(" r2 = 0x%016" PRIx64, regs[2]);
3740       tty->print_cr(" r3 = 0x%016" PRIx64, regs[3]);
3741       tty->print_cr(" r4 = 0x%016" PRIx64, regs[4]);
3742       tty->print_cr(" r5 = 0x%016" PRIx64, regs[5]);
3743       tty->print_cr(" r6 = 0x%016" PRIx64, regs[6]);
3744       tty->print_cr(" r7 = 0x%016" PRIx64, regs[7]);
3745       tty->print_cr(" r8 = 0x%016" PRIx64, regs[8]);
3746       tty->print_cr(" r9 = 0x%016" PRIx64, regs[9]);
3747       tty->print_cr("r10 = 0x%016" PRIx64, regs[10]);
3748       tty->print_cr("r11 = 0x%016" PRIx64, regs[11]);
3749       tty->print_cr("r12 = 0x%016" PRIx64, regs[12]);
3750       tty->print_cr("r13 = 0x%016" PRIx64, regs[13]);
3751       tty->print_cr("r14 = 0x%016" PRIx64, regs[14]);
3752       tty->print_cr("r15 = 0x%016" PRIx64, regs[15]);
3753       tty->print_cr("r16 = 0x%016" PRIx64, regs[16]);
3754       tty->print_cr("r17 = 0x%016" PRIx64, regs[17]);
3755       tty->print_cr("r18 = 0x%016" PRIx64, regs[18]);
3756       tty->print_cr("r19 = 0x%016" PRIx64, regs[19]);
3757       tty->print_cr("r20 = 0x%016" PRIx64, regs[20]);
3758       tty->print_cr("r21 = 0x%016" PRIx64, regs[21]);
3759       tty->print_cr("r22 = 0x%016" PRIx64, regs[22]);
3760       tty->print_cr("r23 = 0x%016" PRIx64, regs[23]);
3761       tty->print_cr("r24 = 0x%016" PRIx64, regs[24]);
3762       tty->print_cr("r25 = 0x%016" PRIx64, regs[25]);
3763       tty->print_cr("r26 = 0x%016" PRIx64, regs[26]);
3764       tty->print_cr("r27 = 0x%016" PRIx64, regs[27]);
3765       tty->print_cr("r28 = 0x%016" PRIx64, regs[28]);
3766       tty->print_cr("r30 = 0x%016" PRIx64, regs[30]);
3767       tty->print_cr("r31 = 0x%016" PRIx64, regs[31]);
3768       BREAKPOINT;
3769     }
3770   }
3771   fatal("DEBUG MESSAGE: %s", msg);
3772 }
3773 
3774 RegSet MacroAssembler::call_clobbered_gp_registers() {
3775   RegSet regs = RegSet::range(r0, r17) - RegSet::of(rscratch1, rscratch2);
3776 #ifndef R18_RESERVED
3777   regs += r18_tls;
3778 #endif
3779   return regs;
3780 }
3781 
3782 void MacroAssembler::push_call_clobbered_registers_except(RegSet exclude) {
3783   int step = 4 * wordSize;
3784   push(call_clobbered_gp_registers() - exclude, sp);
3785   sub(sp, sp, step);
3786   mov(rscratch1, -step);
3787   // Push v0-v7, v16-v31.
3788   for (int i = 31; i>= 4; i -= 4) {
3789     if (i <= v7->encoding() || i >= v16->encoding())
3790       st1(as_FloatRegister(i-3), as_FloatRegister(i-2), as_FloatRegister(i-1),
3791           as_FloatRegister(i), T1D, Address(post(sp, rscratch1)));
3792   }
3793   st1(as_FloatRegister(0), as_FloatRegister(1), as_FloatRegister(2),
3794       as_FloatRegister(3), T1D, Address(sp));
3795 }
3796 
3797 void MacroAssembler::pop_call_clobbered_registers_except(RegSet exclude) {
3798   for (int i = 0; i < 32; i += 4) {
3799     if (i <= v7->encoding() || i >= v16->encoding())
3800       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3801           as_FloatRegister(i+3), T1D, Address(post(sp, 4 * wordSize)));
3802   }
3803 
3804   reinitialize_ptrue();
3805 
3806   pop(call_clobbered_gp_registers() - exclude, sp);
3807 }
3808 
3809 void MacroAssembler::push_CPU_state(bool save_vectors, bool use_sve,
3810                                     int sve_vector_size_in_bytes, int total_predicate_in_bytes) {
3811   push(RegSet::range(r0, r29), sp); // integer registers except lr & sp
3812   if (save_vectors && use_sve && sve_vector_size_in_bytes > 16) {
3813     sub(sp, sp, sve_vector_size_in_bytes * FloatRegister::number_of_registers);
3814     for (int i = 0; i < FloatRegister::number_of_registers; i++) {
3815       sve_str(as_FloatRegister(i), Address(sp, i));
3816     }
3817   } else {
3818     int step = (save_vectors ? 8 : 4) * wordSize;
3819     mov(rscratch1, -step);
3820     sub(sp, sp, step);
3821     for (int i = 28; i >= 4; i -= 4) {
3822       st1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3823           as_FloatRegister(i+3), save_vectors ? T2D : T1D, Address(post(sp, rscratch1)));
3824     }
3825     st1(v0, v1, v2, v3, save_vectors ? T2D : T1D, sp);
3826   }
3827   if (save_vectors && use_sve && total_predicate_in_bytes > 0) {
3828     sub(sp, sp, total_predicate_in_bytes);
3829     for (int i = 0; i < PRegister::number_of_registers; i++) {
3830       sve_str(as_PRegister(i), Address(sp, i));
3831     }
3832   }
3833 }
3834 
3835 void MacroAssembler::pop_CPU_state(bool restore_vectors, bool use_sve,
3836                                    int sve_vector_size_in_bytes, int total_predicate_in_bytes) {
3837   if (restore_vectors && use_sve && total_predicate_in_bytes > 0) {
3838     for (int i = PRegister::number_of_registers - 1; i >= 0; i--) {
3839       sve_ldr(as_PRegister(i), Address(sp, i));
3840     }
3841     add(sp, sp, total_predicate_in_bytes);
3842   }
3843   if (restore_vectors && use_sve && sve_vector_size_in_bytes > 16) {
3844     for (int i = FloatRegister::number_of_registers - 1; i >= 0; i--) {
3845       sve_ldr(as_FloatRegister(i), Address(sp, i));
3846     }
3847     add(sp, sp, sve_vector_size_in_bytes * FloatRegister::number_of_registers);
3848   } else {
3849     int step = (restore_vectors ? 8 : 4) * wordSize;
3850     for (int i = 0; i <= 28; i += 4)
3851       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3852           as_FloatRegister(i+3), restore_vectors ? T2D : T1D, Address(post(sp, step)));
3853   }
3854 
3855   // We may use predicate registers and rely on ptrue with SVE,
3856   // regardless of wide vector (> 8 bytes) used or not.
3857   if (use_sve) {
3858     reinitialize_ptrue();
3859   }
3860 
3861   // integer registers except lr & sp
3862   pop(RegSet::range(r0, r17), sp);
3863 #ifdef R18_RESERVED
3864   ldp(zr, r19, Address(post(sp, 2 * wordSize)));
3865   pop(RegSet::range(r20, r29), sp);
3866 #else
3867   pop(RegSet::range(r18_tls, r29), sp);
3868 #endif
3869 }
3870 
3871 /**
3872  * Helpers for multiply_to_len().
3873  */
3874 void MacroAssembler::add2_with_carry(Register final_dest_hi, Register dest_hi, Register dest_lo,
3875                                      Register src1, Register src2) {
3876   adds(dest_lo, dest_lo, src1);
3877   adc(dest_hi, dest_hi, zr);
3878   adds(dest_lo, dest_lo, src2);
3879   adc(final_dest_hi, dest_hi, zr);
3880 }
3881 
3882 // Generate an address from (r + r1 extend offset).  "size" is the
3883 // size of the operand.  The result may be in rscratch2.
3884 Address MacroAssembler::offsetted_address(Register r, Register r1,
3885                                           Address::extend ext, int offset, int size) {
3886   if (offset || (ext.shift() % size != 0)) {
3887     lea(rscratch2, Address(r, r1, ext));
3888     return Address(rscratch2, offset);
3889   } else {
3890     return Address(r, r1, ext);
3891   }
3892 }
3893 
3894 Address MacroAssembler::spill_address(int size, int offset, Register tmp)
3895 {
3896   assert(offset >= 0, "spill to negative address?");
3897   // Offset reachable ?
3898   //   Not aligned - 9 bits signed offset
3899   //   Aligned - 12 bits unsigned offset shifted
3900   Register base = sp;
3901   if ((offset & (size-1)) && offset >= (1<<8)) {
3902     add(tmp, base, offset & ((1<<12)-1));
3903     base = tmp;
3904     offset &= -1u<<12;
3905   }
3906 
3907   if (offset >= (1<<12) * size) {
3908     add(tmp, base, offset & (((1<<12)-1)<<12));
3909     base = tmp;
3910     offset &= ~(((1<<12)-1)<<12);
3911   }
3912 
3913   return Address(base, offset);
3914 }
3915 
3916 Address MacroAssembler::sve_spill_address(int sve_reg_size_in_bytes, int offset, Register tmp) {
3917   assert(offset >= 0, "spill to negative address?");
3918 
3919   Register base = sp;
3920 
3921   // An immediate offset in the range 0 to 255 which is multiplied
3922   // by the current vector or predicate register size in bytes.
3923   if (offset % sve_reg_size_in_bytes == 0 && offset < ((1<<8)*sve_reg_size_in_bytes)) {
3924     return Address(base, offset / sve_reg_size_in_bytes);
3925   }
3926 
3927   add(tmp, base, offset);
3928   return Address(tmp);
3929 }
3930 
3931 // Checks whether offset is aligned.
3932 // Returns true if it is, else false.
3933 bool MacroAssembler::merge_alignment_check(Register base,
3934                                            size_t size,
3935                                            int64_t cur_offset,
3936                                            int64_t prev_offset) const {
3937   if (AvoidUnalignedAccesses) {
3938     if (base == sp) {
3939       // Checks whether low offset if aligned to pair of registers.
3940       int64_t pair_mask = size * 2 - 1;
3941       int64_t offset = prev_offset > cur_offset ? cur_offset : prev_offset;
3942       return (offset & pair_mask) == 0;
3943     } else { // If base is not sp, we can't guarantee the access is aligned.
3944       return false;
3945     }
3946   } else {
3947     int64_t mask = size - 1;
3948     // Load/store pair instruction only supports element size aligned offset.
3949     return (cur_offset & mask) == 0 && (prev_offset & mask) == 0;
3950   }
3951 }
3952 
3953 // Checks whether current and previous loads/stores can be merged.
3954 // Returns true if it can be merged, else false.
3955 bool MacroAssembler::ldst_can_merge(Register rt,
3956                                     const Address &adr,
3957                                     size_t cur_size_in_bytes,
3958                                     bool is_store) const {
3959   address prev = pc() - NativeInstruction::instruction_size;
3960   address last = code()->last_merge_candidate();
3961 
3962   if (last == nullptr || !nativeInstruction_at(last)->is_Imm_LdSt()) {
3963     return false;
3964   }
3965 
3966   if (adr.getMode() != Address::base_plus_offset || prev != last) {
3967     return false;
3968   }
3969 
3970   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
3971   size_t prev_size_in_bytes = prev_ldst->size_in_bytes();
3972 
3973   assert(prev_size_in_bytes == 4 || prev_size_in_bytes == 8, "only supports 64/32bit merging.");
3974   assert(cur_size_in_bytes == 4 || cur_size_in_bytes == 8, "only supports 64/32bit merging.");
3975 
3976   if (cur_size_in_bytes != prev_size_in_bytes || is_store != prev_ldst->is_store()) {
3977     return false;
3978   }
3979 
3980   int64_t max_offset = 63 * prev_size_in_bytes;
3981   int64_t min_offset = -64 * prev_size_in_bytes;
3982 
3983   assert(prev_ldst->is_not_pre_post_index(), "pre-index or post-index is not supported to be merged.");
3984 
3985   // Only same base can be merged.
3986   if (adr.base() != prev_ldst->base()) {
3987     return false;
3988   }
3989 
3990   int64_t cur_offset = adr.offset();
3991   int64_t prev_offset = prev_ldst->offset();
3992   size_t diff = abs(cur_offset - prev_offset);
3993   if (diff != prev_size_in_bytes) {
3994     return false;
3995   }
3996 
3997   // Following cases can not be merged:
3998   // ldr x2, [x2, #8]
3999   // ldr x3, [x2, #16]
4000   // or:
4001   // ldr x2, [x3, #8]
4002   // ldr x2, [x3, #16]
4003   // If t1 and t2 is the same in "ldp t1, t2, [xn, #imm]", we'll get SIGILL.
4004   if (!is_store && (adr.base() == prev_ldst->target() || rt == prev_ldst->target())) {
4005     return false;
4006   }
4007 
4008   int64_t low_offset = prev_offset > cur_offset ? cur_offset : prev_offset;
4009   // Offset range must be in ldp/stp instruction's range.
4010   if (low_offset > max_offset || low_offset < min_offset) {
4011     return false;
4012   }
4013 
4014   if (merge_alignment_check(adr.base(), prev_size_in_bytes, cur_offset, prev_offset)) {
4015     return true;
4016   }
4017 
4018   return false;
4019 }
4020 
4021 // Merge current load/store with previous load/store into ldp/stp.
4022 void MacroAssembler::merge_ldst(Register rt,
4023                                 const Address &adr,
4024                                 size_t cur_size_in_bytes,
4025                                 bool is_store) {
4026 
4027   assert(ldst_can_merge(rt, adr, cur_size_in_bytes, is_store) == true, "cur and prev must be able to be merged.");
4028 
4029   Register rt_low, rt_high;
4030   address prev = pc() - NativeInstruction::instruction_size;
4031   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
4032 
4033   int64_t offset;
4034 
4035   if (adr.offset() < prev_ldst->offset()) {
4036     offset = adr.offset();
4037     rt_low = rt;
4038     rt_high = prev_ldst->target();
4039   } else {
4040     offset = prev_ldst->offset();
4041     rt_low = prev_ldst->target();
4042     rt_high = rt;
4043   }
4044 
4045   Address adr_p = Address(prev_ldst->base(), offset);
4046   // Overwrite previous generated binary.
4047   code_section()->set_end(prev);
4048 
4049   const size_t sz = prev_ldst->size_in_bytes();
4050   assert(sz == 8 || sz == 4, "only supports 64/32bit merging.");
4051   if (!is_store) {
4052     BLOCK_COMMENT("merged ldr pair");
4053     if (sz == 8) {
4054       ldp(rt_low, rt_high, adr_p);
4055     } else {
4056       ldpw(rt_low, rt_high, adr_p);
4057     }
4058   } else {
4059     BLOCK_COMMENT("merged str pair");
4060     if (sz == 8) {
4061       stp(rt_low, rt_high, adr_p);
4062     } else {
4063       stpw(rt_low, rt_high, adr_p);
4064     }
4065   }
4066 }
4067 
4068 /**
4069  * Multiply 64 bit by 64 bit first loop.
4070  */
4071 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
4072                                            Register y, Register y_idx, Register z,
4073                                            Register carry, Register product,
4074                                            Register idx, Register kdx) {
4075   //
4076   //  jlong carry, x[], y[], z[];
4077   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
4078   //    huge_128 product = y[idx] * x[xstart] + carry;
4079   //    z[kdx] = (jlong)product;
4080   //    carry  = (jlong)(product >>> 64);
4081   //  }
4082   //  z[xstart] = carry;
4083   //
4084 
4085   Label L_first_loop, L_first_loop_exit;
4086   Label L_one_x, L_one_y, L_multiply;
4087 
4088   subsw(xstart, xstart, 1);
4089   br(Assembler::MI, L_one_x);
4090 
4091   lea(rscratch1, Address(x, xstart, Address::lsl(LogBytesPerInt)));
4092   ldr(x_xstart, Address(rscratch1));
4093   ror(x_xstart, x_xstart, 32); // convert big-endian to little-endian
4094 
4095   bind(L_first_loop);
4096   subsw(idx, idx, 1);
4097   br(Assembler::MI, L_first_loop_exit);
4098   subsw(idx, idx, 1);
4099   br(Assembler::MI, L_one_y);
4100   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4101   ldr(y_idx, Address(rscratch1));
4102   ror(y_idx, y_idx, 32); // convert big-endian to little-endian
4103   bind(L_multiply);
4104 
4105   // AArch64 has a multiply-accumulate instruction that we can't use
4106   // here because it has no way to process carries, so we have to use
4107   // separate add and adc instructions.  Bah.
4108   umulh(rscratch1, x_xstart, y_idx); // x_xstart * y_idx -> rscratch1:product
4109   mul(product, x_xstart, y_idx);
4110   adds(product, product, carry);
4111   adc(carry, rscratch1, zr);   // x_xstart * y_idx + carry -> carry:product
4112 
4113   subw(kdx, kdx, 2);
4114   ror(product, product, 32); // back to big-endian
4115   str(product, offsetted_address(z, kdx, Address::uxtw(LogBytesPerInt), 0, BytesPerLong));
4116 
4117   b(L_first_loop);
4118 
4119   bind(L_one_y);
4120   ldrw(y_idx, Address(y,  0));
4121   b(L_multiply);
4122 
4123   bind(L_one_x);
4124   ldrw(x_xstart, Address(x,  0));
4125   b(L_first_loop);
4126 
4127   bind(L_first_loop_exit);
4128 }
4129 
4130 /**
4131  * Multiply 128 bit by 128. Unrolled inner loop.
4132  *
4133  */
4134 void MacroAssembler::multiply_128_x_128_loop(Register y, Register z,
4135                                              Register carry, Register carry2,
4136                                              Register idx, Register jdx,
4137                                              Register yz_idx1, Register yz_idx2,
4138                                              Register tmp, Register tmp3, Register tmp4,
4139                                              Register tmp6, Register product_hi) {
4140 
4141   //   jlong carry, x[], y[], z[];
4142   //   int kdx = ystart+1;
4143   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
4144   //     huge_128 tmp3 = (y[idx+1] * product_hi) + z[kdx+idx+1] + carry;
4145   //     jlong carry2  = (jlong)(tmp3 >>> 64);
4146   //     huge_128 tmp4 = (y[idx]   * product_hi) + z[kdx+idx] + carry2;
4147   //     carry  = (jlong)(tmp4 >>> 64);
4148   //     z[kdx+idx+1] = (jlong)tmp3;
4149   //     z[kdx+idx] = (jlong)tmp4;
4150   //   }
4151   //   idx += 2;
4152   //   if (idx > 0) {
4153   //     yz_idx1 = (y[idx] * product_hi) + z[kdx+idx] + carry;
4154   //     z[kdx+idx] = (jlong)yz_idx1;
4155   //     carry  = (jlong)(yz_idx1 >>> 64);
4156   //   }
4157   //
4158 
4159   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
4160 
4161   lsrw(jdx, idx, 2);
4162 
4163   bind(L_third_loop);
4164 
4165   subsw(jdx, jdx, 1);
4166   br(Assembler::MI, L_third_loop_exit);
4167   subw(idx, idx, 4);
4168 
4169   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4170 
4171   ldp(yz_idx2, yz_idx1, Address(rscratch1, 0));
4172 
4173   lea(tmp6, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4174 
4175   ror(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
4176   ror(yz_idx2, yz_idx2, 32);
4177 
4178   ldp(rscratch2, rscratch1, Address(tmp6, 0));
4179 
4180   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
4181   umulh(tmp4, product_hi, yz_idx1);
4182 
4183   ror(rscratch1, rscratch1, 32); // convert big-endian to little-endian
4184   ror(rscratch2, rscratch2, 32);
4185 
4186   mul(tmp, product_hi, yz_idx2);   //  yz_idx2 * product_hi -> carry2:tmp
4187   umulh(carry2, product_hi, yz_idx2);
4188 
4189   // propagate sum of both multiplications into carry:tmp4:tmp3
4190   adds(tmp3, tmp3, carry);
4191   adc(tmp4, tmp4, zr);
4192   adds(tmp3, tmp3, rscratch1);
4193   adcs(tmp4, tmp4, tmp);
4194   adc(carry, carry2, zr);
4195   adds(tmp4, tmp4, rscratch2);
4196   adc(carry, carry, zr);
4197 
4198   ror(tmp3, tmp3, 32); // convert little-endian to big-endian
4199   ror(tmp4, tmp4, 32);
4200   stp(tmp4, tmp3, Address(tmp6, 0));
4201 
4202   b(L_third_loop);
4203   bind (L_third_loop_exit);
4204 
4205   andw (idx, idx, 0x3);
4206   cbz(idx, L_post_third_loop_done);
4207 
4208   Label L_check_1;
4209   subsw(idx, idx, 2);
4210   br(Assembler::MI, L_check_1);
4211 
4212   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4213   ldr(yz_idx1, Address(rscratch1, 0));
4214   ror(yz_idx1, yz_idx1, 32);
4215   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
4216   umulh(tmp4, product_hi, yz_idx1);
4217   lea(rscratch1, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4218   ldr(yz_idx2, Address(rscratch1, 0));
4219   ror(yz_idx2, yz_idx2, 32);
4220 
4221   add2_with_carry(carry, tmp4, tmp3, carry, yz_idx2);
4222 
4223   ror(tmp3, tmp3, 32);
4224   str(tmp3, Address(rscratch1, 0));
4225 
4226   bind (L_check_1);
4227 
4228   andw (idx, idx, 0x1);
4229   subsw(idx, idx, 1);
4230   br(Assembler::MI, L_post_third_loop_done);
4231   ldrw(tmp4, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4232   mul(tmp3, tmp4, product_hi);  //  tmp4 * product_hi -> carry2:tmp3
4233   umulh(carry2, tmp4, product_hi);
4234   ldrw(tmp4, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4235 
4236   add2_with_carry(carry2, tmp3, tmp4, carry);
4237 
4238   strw(tmp3, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4239   extr(carry, carry2, tmp3, 32);
4240 
4241   bind(L_post_third_loop_done);
4242 }
4243 
4244 /**
4245  * Code for BigInteger::multiplyToLen() intrinsic.
4246  *
4247  * r0: x
4248  * r1: xlen
4249  * r2: y
4250  * r3: ylen
4251  * r4:  z
4252  * r5: tmp0
4253  * r10: tmp1
4254  * r11: tmp2
4255  * r12: tmp3
4256  * r13: tmp4
4257  * r14: tmp5
4258  * r15: tmp6
4259  * r16: tmp7
4260  *
4261  */
4262 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen,
4263                                      Register z, Register tmp0,
4264                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4,
4265                                      Register tmp5, Register tmp6, Register product_hi) {
4266 
4267   assert_different_registers(x, xlen, y, ylen, z, tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, product_hi);
4268 
4269   const Register idx = tmp1;
4270   const Register kdx = tmp2;
4271   const Register xstart = tmp3;
4272 
4273   const Register y_idx = tmp4;
4274   const Register carry = tmp5;
4275   const Register product  = xlen;
4276   const Register x_xstart = tmp0;
4277 
4278   // First Loop.
4279   //
4280   //  final static long LONG_MASK = 0xffffffffL;
4281   //  int xstart = xlen - 1;
4282   //  int ystart = ylen - 1;
4283   //  long carry = 0;
4284   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
4285   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
4286   //    z[kdx] = (int)product;
4287   //    carry = product >>> 32;
4288   //  }
4289   //  z[xstart] = (int)carry;
4290   //
4291 
4292   movw(idx, ylen);       // idx = ylen;
4293   addw(kdx, xlen, ylen); // kdx = xlen+ylen;
4294   mov(carry, zr);        // carry = 0;
4295 
4296   Label L_done;
4297 
4298   movw(xstart, xlen);
4299   subsw(xstart, xstart, 1);
4300   br(Assembler::MI, L_done);
4301 
4302   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
4303 
4304   Label L_second_loop;
4305   cbzw(kdx, L_second_loop);
4306 
4307   Label L_carry;
4308   subw(kdx, kdx, 1);
4309   cbzw(kdx, L_carry);
4310 
4311   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
4312   lsr(carry, carry, 32);
4313   subw(kdx, kdx, 1);
4314 
4315   bind(L_carry);
4316   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
4317 
4318   // Second and third (nested) loops.
4319   //
4320   // for (int i = xstart-1; i >= 0; i--) { // Second loop
4321   //   carry = 0;
4322   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
4323   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
4324   //                    (z[k] & LONG_MASK) + carry;
4325   //     z[k] = (int)product;
4326   //     carry = product >>> 32;
4327   //   }
4328   //   z[i] = (int)carry;
4329   // }
4330   //
4331   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = product_hi
4332 
4333   const Register jdx = tmp1;
4334 
4335   bind(L_second_loop);
4336   mov(carry, zr);                // carry = 0;
4337   movw(jdx, ylen);               // j = ystart+1
4338 
4339   subsw(xstart, xstart, 1);      // i = xstart-1;
4340   br(Assembler::MI, L_done);
4341 
4342   str(z, Address(pre(sp, -4 * wordSize)));
4343 
4344   Label L_last_x;
4345   lea(z, offsetted_address(z, xstart, Address::uxtw(LogBytesPerInt), 4, BytesPerInt)); // z = z + k - j
4346   subsw(xstart, xstart, 1);       // i = xstart-1;
4347   br(Assembler::MI, L_last_x);
4348 
4349   lea(rscratch1, Address(x, xstart, Address::uxtw(LogBytesPerInt)));
4350   ldr(product_hi, Address(rscratch1));
4351   ror(product_hi, product_hi, 32);  // convert big-endian to little-endian
4352 
4353   Label L_third_loop_prologue;
4354   bind(L_third_loop_prologue);
4355 
4356   str(ylen, Address(sp, wordSize));
4357   stp(x, xstart, Address(sp, 2 * wordSize));
4358   multiply_128_x_128_loop(y, z, carry, x, jdx, ylen, product,
4359                           tmp2, x_xstart, tmp3, tmp4, tmp6, product_hi);
4360   ldp(z, ylen, Address(post(sp, 2 * wordSize)));
4361   ldp(x, xlen, Address(post(sp, 2 * wordSize)));   // copy old xstart -> xlen
4362 
4363   addw(tmp3, xlen, 1);
4364   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
4365   subsw(tmp3, tmp3, 1);
4366   br(Assembler::MI, L_done);
4367 
4368   lsr(carry, carry, 32);
4369   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
4370   b(L_second_loop);
4371 
4372   // Next infrequent code is moved outside loops.
4373   bind(L_last_x);
4374   ldrw(product_hi, Address(x,  0));
4375   b(L_third_loop_prologue);
4376 
4377   bind(L_done);
4378 }
4379 
4380 // Code for BigInteger::mulAdd intrinsic
4381 // out     = r0
4382 // in      = r1
4383 // offset  = r2  (already out.length-offset)
4384 // len     = r3
4385 // k       = r4
4386 //
4387 // pseudo code from java implementation:
4388 // carry = 0;
4389 // offset = out.length-offset - 1;
4390 // for (int j=len-1; j >= 0; j--) {
4391 //     product = (in[j] & LONG_MASK) * kLong + (out[offset] & LONG_MASK) + carry;
4392 //     out[offset--] = (int)product;
4393 //     carry = product >>> 32;
4394 // }
4395 // return (int)carry;
4396 void MacroAssembler::mul_add(Register out, Register in, Register offset,
4397       Register len, Register k) {
4398     Label LOOP, END;
4399     // pre-loop
4400     cmp(len, zr); // cmp, not cbz/cbnz: to use condition twice => less branches
4401     csel(out, zr, out, Assembler::EQ);
4402     br(Assembler::EQ, END);
4403     add(in, in, len, LSL, 2); // in[j+1] address
4404     add(offset, out, offset, LSL, 2); // out[offset + 1] address
4405     mov(out, zr); // used to keep carry now
4406     BIND(LOOP);
4407     ldrw(rscratch1, Address(pre(in, -4)));
4408     madd(rscratch1, rscratch1, k, out);
4409     ldrw(rscratch2, Address(pre(offset, -4)));
4410     add(rscratch1, rscratch1, rscratch2);
4411     strw(rscratch1, Address(offset));
4412     lsr(out, rscratch1, 32);
4413     subs(len, len, 1);
4414     br(Assembler::NE, LOOP);
4415     BIND(END);
4416 }
4417 
4418 /**
4419  * Emits code to update CRC-32 with a byte value according to constants in table
4420  *
4421  * @param [in,out]crc   Register containing the crc.
4422  * @param [in]val       Register containing the byte to fold into the CRC.
4423  * @param [in]table     Register containing the table of crc constants.
4424  *
4425  * uint32_t crc;
4426  * val = crc_table[(val ^ crc) & 0xFF];
4427  * crc = val ^ (crc >> 8);
4428  *
4429  */
4430 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
4431   eor(val, val, crc);
4432   andr(val, val, 0xff);
4433   ldrw(val, Address(table, val, Address::lsl(2)));
4434   eor(crc, val, crc, Assembler::LSR, 8);
4435 }
4436 
4437 /**
4438  * Emits code to update CRC-32 with a 32-bit value according to tables 0 to 3
4439  *
4440  * @param [in,out]crc   Register containing the crc.
4441  * @param [in]v         Register containing the 32-bit to fold into the CRC.
4442  * @param [in]table0    Register containing table 0 of crc constants.
4443  * @param [in]table1    Register containing table 1 of crc constants.
4444  * @param [in]table2    Register containing table 2 of crc constants.
4445  * @param [in]table3    Register containing table 3 of crc constants.
4446  *
4447  * uint32_t crc;
4448  *   v = crc ^ v
4449  *   crc = table3[v&0xff]^table2[(v>>8)&0xff]^table1[(v>>16)&0xff]^table0[v>>24]
4450  *
4451  */
4452 void MacroAssembler::update_word_crc32(Register crc, Register v, Register tmp,
4453         Register table0, Register table1, Register table2, Register table3,
4454         bool upper) {
4455   eor(v, crc, v, upper ? LSR:LSL, upper ? 32:0);
4456   uxtb(tmp, v);
4457   ldrw(crc, Address(table3, tmp, Address::lsl(2)));
4458   ubfx(tmp, v, 8, 8);
4459   ldrw(tmp, Address(table2, tmp, Address::lsl(2)));
4460   eor(crc, crc, tmp);
4461   ubfx(tmp, v, 16, 8);
4462   ldrw(tmp, Address(table1, tmp, Address::lsl(2)));
4463   eor(crc, crc, tmp);
4464   ubfx(tmp, v, 24, 8);
4465   ldrw(tmp, Address(table0, tmp, Address::lsl(2)));
4466   eor(crc, crc, tmp);
4467 }
4468 
4469 void MacroAssembler::kernel_crc32_using_crypto_pmull(Register crc, Register buf,
4470         Register len, Register tmp0, Register tmp1, Register tmp2, Register tmp3) {
4471     Label CRC_by4_loop, CRC_by1_loop, CRC_less128, CRC_by128_pre, CRC_by32_loop, CRC_less32, L_exit;
4472     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2);
4473 
4474     subs(tmp0, len, 384);
4475     mvnw(crc, crc);
4476     br(Assembler::GE, CRC_by128_pre);
4477   BIND(CRC_less128);
4478     subs(len, len, 32);
4479     br(Assembler::GE, CRC_by32_loop);
4480   BIND(CRC_less32);
4481     adds(len, len, 32 - 4);
4482     br(Assembler::GE, CRC_by4_loop);
4483     adds(len, len, 4);
4484     br(Assembler::GT, CRC_by1_loop);
4485     b(L_exit);
4486 
4487   BIND(CRC_by32_loop);
4488     ldp(tmp0, tmp1, Address(buf));
4489     crc32x(crc, crc, tmp0);
4490     ldp(tmp2, tmp3, Address(buf, 16));
4491     crc32x(crc, crc, tmp1);
4492     add(buf, buf, 32);
4493     crc32x(crc, crc, tmp2);
4494     subs(len, len, 32);
4495     crc32x(crc, crc, tmp3);
4496     br(Assembler::GE, CRC_by32_loop);
4497     cmn(len, (u1)32);
4498     br(Assembler::NE, CRC_less32);
4499     b(L_exit);
4500 
4501   BIND(CRC_by4_loop);
4502     ldrw(tmp0, Address(post(buf, 4)));
4503     subs(len, len, 4);
4504     crc32w(crc, crc, tmp0);
4505     br(Assembler::GE, CRC_by4_loop);
4506     adds(len, len, 4);
4507     br(Assembler::LE, L_exit);
4508   BIND(CRC_by1_loop);
4509     ldrb(tmp0, Address(post(buf, 1)));
4510     subs(len, len, 1);
4511     crc32b(crc, crc, tmp0);
4512     br(Assembler::GT, CRC_by1_loop);
4513     b(L_exit);
4514 
4515   BIND(CRC_by128_pre);
4516     kernel_crc32_common_fold_using_crypto_pmull(crc, buf, len, tmp0, tmp1, tmp2,
4517       4*256*sizeof(juint) + 8*sizeof(juint));
4518     mov(crc, 0);
4519     crc32x(crc, crc, tmp0);
4520     crc32x(crc, crc, tmp1);
4521 
4522     cbnz(len, CRC_less128);
4523 
4524   BIND(L_exit);
4525     mvnw(crc, crc);
4526 }
4527 
4528 void MacroAssembler::kernel_crc32_using_crc32(Register crc, Register buf,
4529         Register len, Register tmp0, Register tmp1, Register tmp2,
4530         Register tmp3) {
4531     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
4532     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
4533 
4534     mvnw(crc, crc);
4535 
4536     subs(len, len, 128);
4537     br(Assembler::GE, CRC_by64_pre);
4538   BIND(CRC_less64);
4539     adds(len, len, 128-32);
4540     br(Assembler::GE, CRC_by32_loop);
4541   BIND(CRC_less32);
4542     adds(len, len, 32-4);
4543     br(Assembler::GE, CRC_by4_loop);
4544     adds(len, len, 4);
4545     br(Assembler::GT, CRC_by1_loop);
4546     b(L_exit);
4547 
4548   BIND(CRC_by32_loop);
4549     ldp(tmp0, tmp1, Address(post(buf, 16)));
4550     subs(len, len, 32);
4551     crc32x(crc, crc, tmp0);
4552     ldr(tmp2, Address(post(buf, 8)));
4553     crc32x(crc, crc, tmp1);
4554     ldr(tmp3, Address(post(buf, 8)));
4555     crc32x(crc, crc, tmp2);
4556     crc32x(crc, crc, tmp3);
4557     br(Assembler::GE, CRC_by32_loop);
4558     cmn(len, (u1)32);
4559     br(Assembler::NE, CRC_less32);
4560     b(L_exit);
4561 
4562   BIND(CRC_by4_loop);
4563     ldrw(tmp0, Address(post(buf, 4)));
4564     subs(len, len, 4);
4565     crc32w(crc, crc, tmp0);
4566     br(Assembler::GE, CRC_by4_loop);
4567     adds(len, len, 4);
4568     br(Assembler::LE, L_exit);
4569   BIND(CRC_by1_loop);
4570     ldrb(tmp0, Address(post(buf, 1)));
4571     subs(len, len, 1);
4572     crc32b(crc, crc, tmp0);
4573     br(Assembler::GT, CRC_by1_loop);
4574     b(L_exit);
4575 
4576   BIND(CRC_by64_pre);
4577     sub(buf, buf, 8);
4578     ldp(tmp0, tmp1, Address(buf, 8));
4579     crc32x(crc, crc, tmp0);
4580     ldr(tmp2, Address(buf, 24));
4581     crc32x(crc, crc, tmp1);
4582     ldr(tmp3, Address(buf, 32));
4583     crc32x(crc, crc, tmp2);
4584     ldr(tmp0, Address(buf, 40));
4585     crc32x(crc, crc, tmp3);
4586     ldr(tmp1, Address(buf, 48));
4587     crc32x(crc, crc, tmp0);
4588     ldr(tmp2, Address(buf, 56));
4589     crc32x(crc, crc, tmp1);
4590     ldr(tmp3, Address(pre(buf, 64)));
4591 
4592     b(CRC_by64_loop);
4593 
4594     align(CodeEntryAlignment);
4595   BIND(CRC_by64_loop);
4596     subs(len, len, 64);
4597     crc32x(crc, crc, tmp2);
4598     ldr(tmp0, Address(buf, 8));
4599     crc32x(crc, crc, tmp3);
4600     ldr(tmp1, Address(buf, 16));
4601     crc32x(crc, crc, tmp0);
4602     ldr(tmp2, Address(buf, 24));
4603     crc32x(crc, crc, tmp1);
4604     ldr(tmp3, Address(buf, 32));
4605     crc32x(crc, crc, tmp2);
4606     ldr(tmp0, Address(buf, 40));
4607     crc32x(crc, crc, tmp3);
4608     ldr(tmp1, Address(buf, 48));
4609     crc32x(crc, crc, tmp0);
4610     ldr(tmp2, Address(buf, 56));
4611     crc32x(crc, crc, tmp1);
4612     ldr(tmp3, Address(pre(buf, 64)));
4613     br(Assembler::GE, CRC_by64_loop);
4614 
4615     // post-loop
4616     crc32x(crc, crc, tmp2);
4617     crc32x(crc, crc, tmp3);
4618 
4619     sub(len, len, 64);
4620     add(buf, buf, 8);
4621     cmn(len, (u1)128);
4622     br(Assembler::NE, CRC_less64);
4623   BIND(L_exit);
4624     mvnw(crc, crc);
4625 }
4626 
4627 /**
4628  * @param crc   register containing existing CRC (32-bit)
4629  * @param buf   register pointing to input byte buffer (byte*)
4630  * @param len   register containing number of bytes
4631  * @param table register that will contain address of CRC table
4632  * @param tmp   scratch register
4633  */
4634 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len,
4635         Register table0, Register table1, Register table2, Register table3,
4636         Register tmp, Register tmp2, Register tmp3) {
4637   Label L_by16, L_by16_loop, L_by4, L_by4_loop, L_by1, L_by1_loop, L_exit;
4638 
4639   if (UseCryptoPmullForCRC32) {
4640       kernel_crc32_using_crypto_pmull(crc, buf, len, table0, table1, table2, table3);
4641       return;
4642   }
4643 
4644   if (UseCRC32) {
4645       kernel_crc32_using_crc32(crc, buf, len, table0, table1, table2, table3);
4646       return;
4647   }
4648 
4649     mvnw(crc, crc);
4650 
4651     {
4652       uint64_t offset;
4653       adrp(table0, ExternalAddress(StubRoutines::crc_table_addr()), offset);
4654       add(table0, table0, offset);
4655     }
4656     add(table1, table0, 1*256*sizeof(juint));
4657     add(table2, table0, 2*256*sizeof(juint));
4658     add(table3, table0, 3*256*sizeof(juint));
4659 
4660     { // Neon code start
4661       cmp(len, (u1)64);
4662       br(Assembler::LT, L_by16);
4663       eor(v16, T16B, v16, v16);
4664 
4665     Label L_fold;
4666 
4667       add(tmp, table0, 4*256*sizeof(juint)); // Point at the Neon constants
4668 
4669       ld1(v0, v1, T2D, post(buf, 32));
4670       ld1r(v4, T2D, post(tmp, 8));
4671       ld1r(v5, T2D, post(tmp, 8));
4672       ld1r(v6, T2D, post(tmp, 8));
4673       ld1r(v7, T2D, post(tmp, 8));
4674       mov(v16, S, 0, crc);
4675 
4676       eor(v0, T16B, v0, v16);
4677       sub(len, len, 64);
4678 
4679     BIND(L_fold);
4680       pmull(v22, T8H, v0, v5, T8B);
4681       pmull(v20, T8H, v0, v7, T8B);
4682       pmull(v23, T8H, v0, v4, T8B);
4683       pmull(v21, T8H, v0, v6, T8B);
4684 
4685       pmull2(v18, T8H, v0, v5, T16B);
4686       pmull2(v16, T8H, v0, v7, T16B);
4687       pmull2(v19, T8H, v0, v4, T16B);
4688       pmull2(v17, T8H, v0, v6, T16B);
4689 
4690       uzp1(v24, T8H, v20, v22);
4691       uzp2(v25, T8H, v20, v22);
4692       eor(v20, T16B, v24, v25);
4693 
4694       uzp1(v26, T8H, v16, v18);
4695       uzp2(v27, T8H, v16, v18);
4696       eor(v16, T16B, v26, v27);
4697 
4698       ushll2(v22, T4S, v20, T8H, 8);
4699       ushll(v20, T4S, v20, T4H, 8);
4700 
4701       ushll2(v18, T4S, v16, T8H, 8);
4702       ushll(v16, T4S, v16, T4H, 8);
4703 
4704       eor(v22, T16B, v23, v22);
4705       eor(v18, T16B, v19, v18);
4706       eor(v20, T16B, v21, v20);
4707       eor(v16, T16B, v17, v16);
4708 
4709       uzp1(v17, T2D, v16, v20);
4710       uzp2(v21, T2D, v16, v20);
4711       eor(v17, T16B, v17, v21);
4712 
4713       ushll2(v20, T2D, v17, T4S, 16);
4714       ushll(v16, T2D, v17, T2S, 16);
4715 
4716       eor(v20, T16B, v20, v22);
4717       eor(v16, T16B, v16, v18);
4718 
4719       uzp1(v17, T2D, v20, v16);
4720       uzp2(v21, T2D, v20, v16);
4721       eor(v28, T16B, v17, v21);
4722 
4723       pmull(v22, T8H, v1, v5, T8B);
4724       pmull(v20, T8H, v1, v7, T8B);
4725       pmull(v23, T8H, v1, v4, T8B);
4726       pmull(v21, T8H, v1, v6, T8B);
4727 
4728       pmull2(v18, T8H, v1, v5, T16B);
4729       pmull2(v16, T8H, v1, v7, T16B);
4730       pmull2(v19, T8H, v1, v4, T16B);
4731       pmull2(v17, T8H, v1, v6, T16B);
4732 
4733       ld1(v0, v1, T2D, post(buf, 32));
4734 
4735       uzp1(v24, T8H, v20, v22);
4736       uzp2(v25, T8H, v20, v22);
4737       eor(v20, T16B, v24, v25);
4738 
4739       uzp1(v26, T8H, v16, v18);
4740       uzp2(v27, T8H, v16, v18);
4741       eor(v16, T16B, v26, v27);
4742 
4743       ushll2(v22, T4S, v20, T8H, 8);
4744       ushll(v20, T4S, v20, T4H, 8);
4745 
4746       ushll2(v18, T4S, v16, T8H, 8);
4747       ushll(v16, T4S, v16, T4H, 8);
4748 
4749       eor(v22, T16B, v23, v22);
4750       eor(v18, T16B, v19, v18);
4751       eor(v20, T16B, v21, v20);
4752       eor(v16, T16B, v17, v16);
4753 
4754       uzp1(v17, T2D, v16, v20);
4755       uzp2(v21, T2D, v16, v20);
4756       eor(v16, T16B, v17, v21);
4757 
4758       ushll2(v20, T2D, v16, T4S, 16);
4759       ushll(v16, T2D, v16, T2S, 16);
4760 
4761       eor(v20, T16B, v22, v20);
4762       eor(v16, T16B, v16, v18);
4763 
4764       uzp1(v17, T2D, v20, v16);
4765       uzp2(v21, T2D, v20, v16);
4766       eor(v20, T16B, v17, v21);
4767 
4768       shl(v16, T2D, v28, 1);
4769       shl(v17, T2D, v20, 1);
4770 
4771       eor(v0, T16B, v0, v16);
4772       eor(v1, T16B, v1, v17);
4773 
4774       subs(len, len, 32);
4775       br(Assembler::GE, L_fold);
4776 
4777       mov(crc, 0);
4778       mov(tmp, v0, D, 0);
4779       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4780       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4781       mov(tmp, v0, D, 1);
4782       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4783       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4784       mov(tmp, v1, D, 0);
4785       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4786       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4787       mov(tmp, v1, D, 1);
4788       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4789       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4790 
4791       add(len, len, 32);
4792     } // Neon code end
4793 
4794   BIND(L_by16);
4795     subs(len, len, 16);
4796     br(Assembler::GE, L_by16_loop);
4797     adds(len, len, 16-4);
4798     br(Assembler::GE, L_by4_loop);
4799     adds(len, len, 4);
4800     br(Assembler::GT, L_by1_loop);
4801     b(L_exit);
4802 
4803   BIND(L_by4_loop);
4804     ldrw(tmp, Address(post(buf, 4)));
4805     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3);
4806     subs(len, len, 4);
4807     br(Assembler::GE, L_by4_loop);
4808     adds(len, len, 4);
4809     br(Assembler::LE, L_exit);
4810   BIND(L_by1_loop);
4811     subs(len, len, 1);
4812     ldrb(tmp, Address(post(buf, 1)));
4813     update_byte_crc32(crc, tmp, table0);
4814     br(Assembler::GT, L_by1_loop);
4815     b(L_exit);
4816 
4817     align(CodeEntryAlignment);
4818   BIND(L_by16_loop);
4819     subs(len, len, 16);
4820     ldp(tmp, tmp3, Address(post(buf, 16)));
4821     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4822     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4823     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, false);
4824     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, true);
4825     br(Assembler::GE, L_by16_loop);
4826     adds(len, len, 16-4);
4827     br(Assembler::GE, L_by4_loop);
4828     adds(len, len, 4);
4829     br(Assembler::GT, L_by1_loop);
4830   BIND(L_exit);
4831     mvnw(crc, crc);
4832 }
4833 
4834 void MacroAssembler::kernel_crc32c_using_crypto_pmull(Register crc, Register buf,
4835         Register len, Register tmp0, Register tmp1, Register tmp2, Register tmp3) {
4836     Label CRC_by4_loop, CRC_by1_loop, CRC_less128, CRC_by128_pre, CRC_by32_loop, CRC_less32, L_exit;
4837     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2);
4838 
4839     subs(tmp0, len, 384);
4840     br(Assembler::GE, CRC_by128_pre);
4841   BIND(CRC_less128);
4842     subs(len, len, 32);
4843     br(Assembler::GE, CRC_by32_loop);
4844   BIND(CRC_less32);
4845     adds(len, len, 32 - 4);
4846     br(Assembler::GE, CRC_by4_loop);
4847     adds(len, len, 4);
4848     br(Assembler::GT, CRC_by1_loop);
4849     b(L_exit);
4850 
4851   BIND(CRC_by32_loop);
4852     ldp(tmp0, tmp1, Address(buf));
4853     crc32cx(crc, crc, tmp0);
4854     ldr(tmp2, Address(buf, 16));
4855     crc32cx(crc, crc, tmp1);
4856     ldr(tmp3, Address(buf, 24));
4857     crc32cx(crc, crc, tmp2);
4858     add(buf, buf, 32);
4859     subs(len, len, 32);
4860     crc32cx(crc, crc, tmp3);
4861     br(Assembler::GE, CRC_by32_loop);
4862     cmn(len, (u1)32);
4863     br(Assembler::NE, CRC_less32);
4864     b(L_exit);
4865 
4866   BIND(CRC_by4_loop);
4867     ldrw(tmp0, Address(post(buf, 4)));
4868     subs(len, len, 4);
4869     crc32cw(crc, crc, tmp0);
4870     br(Assembler::GE, CRC_by4_loop);
4871     adds(len, len, 4);
4872     br(Assembler::LE, L_exit);
4873   BIND(CRC_by1_loop);
4874     ldrb(tmp0, Address(post(buf, 1)));
4875     subs(len, len, 1);
4876     crc32cb(crc, crc, tmp0);
4877     br(Assembler::GT, CRC_by1_loop);
4878     b(L_exit);
4879 
4880   BIND(CRC_by128_pre);
4881     kernel_crc32_common_fold_using_crypto_pmull(crc, buf, len, tmp0, tmp1, tmp2,
4882       4*256*sizeof(juint) + 8*sizeof(juint) + 0x50);
4883     mov(crc, 0);
4884     crc32cx(crc, crc, tmp0);
4885     crc32cx(crc, crc, tmp1);
4886 
4887     cbnz(len, CRC_less128);
4888 
4889   BIND(L_exit);
4890 }
4891 
4892 void MacroAssembler::kernel_crc32c_using_crc32c(Register crc, Register buf,
4893         Register len, Register tmp0, Register tmp1, Register tmp2,
4894         Register tmp3) {
4895     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
4896     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
4897 
4898     subs(len, len, 128);
4899     br(Assembler::GE, CRC_by64_pre);
4900   BIND(CRC_less64);
4901     adds(len, len, 128-32);
4902     br(Assembler::GE, CRC_by32_loop);
4903   BIND(CRC_less32);
4904     adds(len, len, 32-4);
4905     br(Assembler::GE, CRC_by4_loop);
4906     adds(len, len, 4);
4907     br(Assembler::GT, CRC_by1_loop);
4908     b(L_exit);
4909 
4910   BIND(CRC_by32_loop);
4911     ldp(tmp0, tmp1, Address(post(buf, 16)));
4912     subs(len, len, 32);
4913     crc32cx(crc, crc, tmp0);
4914     ldr(tmp2, Address(post(buf, 8)));
4915     crc32cx(crc, crc, tmp1);
4916     ldr(tmp3, Address(post(buf, 8)));
4917     crc32cx(crc, crc, tmp2);
4918     crc32cx(crc, crc, tmp3);
4919     br(Assembler::GE, CRC_by32_loop);
4920     cmn(len, (u1)32);
4921     br(Assembler::NE, CRC_less32);
4922     b(L_exit);
4923 
4924   BIND(CRC_by4_loop);
4925     ldrw(tmp0, Address(post(buf, 4)));
4926     subs(len, len, 4);
4927     crc32cw(crc, crc, tmp0);
4928     br(Assembler::GE, CRC_by4_loop);
4929     adds(len, len, 4);
4930     br(Assembler::LE, L_exit);
4931   BIND(CRC_by1_loop);
4932     ldrb(tmp0, Address(post(buf, 1)));
4933     subs(len, len, 1);
4934     crc32cb(crc, crc, tmp0);
4935     br(Assembler::GT, CRC_by1_loop);
4936     b(L_exit);
4937 
4938   BIND(CRC_by64_pre);
4939     sub(buf, buf, 8);
4940     ldp(tmp0, tmp1, Address(buf, 8));
4941     crc32cx(crc, crc, tmp0);
4942     ldr(tmp2, Address(buf, 24));
4943     crc32cx(crc, crc, tmp1);
4944     ldr(tmp3, Address(buf, 32));
4945     crc32cx(crc, crc, tmp2);
4946     ldr(tmp0, Address(buf, 40));
4947     crc32cx(crc, crc, tmp3);
4948     ldr(tmp1, Address(buf, 48));
4949     crc32cx(crc, crc, tmp0);
4950     ldr(tmp2, Address(buf, 56));
4951     crc32cx(crc, crc, tmp1);
4952     ldr(tmp3, Address(pre(buf, 64)));
4953 
4954     b(CRC_by64_loop);
4955 
4956     align(CodeEntryAlignment);
4957   BIND(CRC_by64_loop);
4958     subs(len, len, 64);
4959     crc32cx(crc, crc, tmp2);
4960     ldr(tmp0, Address(buf, 8));
4961     crc32cx(crc, crc, tmp3);
4962     ldr(tmp1, Address(buf, 16));
4963     crc32cx(crc, crc, tmp0);
4964     ldr(tmp2, Address(buf, 24));
4965     crc32cx(crc, crc, tmp1);
4966     ldr(tmp3, Address(buf, 32));
4967     crc32cx(crc, crc, tmp2);
4968     ldr(tmp0, Address(buf, 40));
4969     crc32cx(crc, crc, tmp3);
4970     ldr(tmp1, Address(buf, 48));
4971     crc32cx(crc, crc, tmp0);
4972     ldr(tmp2, Address(buf, 56));
4973     crc32cx(crc, crc, tmp1);
4974     ldr(tmp3, Address(pre(buf, 64)));
4975     br(Assembler::GE, CRC_by64_loop);
4976 
4977     // post-loop
4978     crc32cx(crc, crc, tmp2);
4979     crc32cx(crc, crc, tmp3);
4980 
4981     sub(len, len, 64);
4982     add(buf, buf, 8);
4983     cmn(len, (u1)128);
4984     br(Assembler::NE, CRC_less64);
4985   BIND(L_exit);
4986 }
4987 
4988 /**
4989  * @param crc   register containing existing CRC (32-bit)
4990  * @param buf   register pointing to input byte buffer (byte*)
4991  * @param len   register containing number of bytes
4992  * @param table register that will contain address of CRC table
4993  * @param tmp   scratch register
4994  */
4995 void MacroAssembler::kernel_crc32c(Register crc, Register buf, Register len,
4996         Register table0, Register table1, Register table2, Register table3,
4997         Register tmp, Register tmp2, Register tmp3) {
4998   if (UseCryptoPmullForCRC32) {
4999     kernel_crc32c_using_crypto_pmull(crc, buf, len, table0, table1, table2, table3);
5000   } else {
5001     kernel_crc32c_using_crc32c(crc, buf, len, table0, table1, table2, table3);
5002   }
5003 }
5004 
5005 void MacroAssembler::kernel_crc32_common_fold_using_crypto_pmull(Register crc, Register buf,
5006         Register len, Register tmp0, Register tmp1, Register tmp2, size_t table_offset) {
5007     Label CRC_by128_loop;
5008     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2);
5009 
5010     sub(len, len, 256);
5011     Register table = tmp0;
5012     {
5013       uint64_t offset;
5014       adrp(table, ExternalAddress(StubRoutines::crc_table_addr()), offset);
5015       add(table, table, offset);
5016     }
5017     add(table, table, table_offset);
5018 
5019     // Registers v0..v7 are used as data registers.
5020     // Registers v16..v31 are used as tmp registers.
5021     sub(buf, buf, 0x10);
5022     ldrq(v0, Address(buf, 0x10));
5023     ldrq(v1, Address(buf, 0x20));
5024     ldrq(v2, Address(buf, 0x30));
5025     ldrq(v3, Address(buf, 0x40));
5026     ldrq(v4, Address(buf, 0x50));
5027     ldrq(v5, Address(buf, 0x60));
5028     ldrq(v6, Address(buf, 0x70));
5029     ldrq(v7, Address(pre(buf, 0x80)));
5030 
5031     movi(v31, T4S, 0);
5032     mov(v31, S, 0, crc);
5033     eor(v0, T16B, v0, v31);
5034 
5035     // Register v16 contains constants from the crc table.
5036     ldrq(v16, Address(table));
5037     b(CRC_by128_loop);
5038 
5039     align(OptoLoopAlignment);
5040   BIND(CRC_by128_loop);
5041     pmull (v17,  T1Q, v0, v16, T1D);
5042     pmull2(v18, T1Q, v0, v16, T2D);
5043     ldrq(v0, Address(buf, 0x10));
5044     eor3(v0, T16B, v17,  v18, v0);
5045 
5046     pmull (v19, T1Q, v1, v16, T1D);
5047     pmull2(v20, T1Q, v1, v16, T2D);
5048     ldrq(v1, Address(buf, 0x20));
5049     eor3(v1, T16B, v19, v20, v1);
5050 
5051     pmull (v21, T1Q, v2, v16, T1D);
5052     pmull2(v22, T1Q, v2, v16, T2D);
5053     ldrq(v2, Address(buf, 0x30));
5054     eor3(v2, T16B, v21, v22, v2);
5055 
5056     pmull (v23, T1Q, v3, v16, T1D);
5057     pmull2(v24, T1Q, v3, v16, T2D);
5058     ldrq(v3, Address(buf, 0x40));
5059     eor3(v3, T16B, v23, v24, v3);
5060 
5061     pmull (v25, T1Q, v4, v16, T1D);
5062     pmull2(v26, T1Q, v4, v16, T2D);
5063     ldrq(v4, Address(buf, 0x50));
5064     eor3(v4, T16B, v25, v26, v4);
5065 
5066     pmull (v27, T1Q, v5, v16, T1D);
5067     pmull2(v28, T1Q, v5, v16, T2D);
5068     ldrq(v5, Address(buf, 0x60));
5069     eor3(v5, T16B, v27, v28, v5);
5070 
5071     pmull (v29, T1Q, v6, v16, T1D);
5072     pmull2(v30, T1Q, v6, v16, T2D);
5073     ldrq(v6, Address(buf, 0x70));
5074     eor3(v6, T16B, v29, v30, v6);
5075 
5076     // Reuse registers v23, v24.
5077     // Using them won't block the first instruction of the next iteration.
5078     pmull (v23, T1Q, v7, v16, T1D);
5079     pmull2(v24, T1Q, v7, v16, T2D);
5080     ldrq(v7, Address(pre(buf, 0x80)));
5081     eor3(v7, T16B, v23, v24, v7);
5082 
5083     subs(len, len, 0x80);
5084     br(Assembler::GE, CRC_by128_loop);
5085 
5086     // fold into 512 bits
5087     // Use v31 for constants because v16 can be still in use.
5088     ldrq(v31, Address(table, 0x10));
5089 
5090     pmull (v17,  T1Q, v0, v31, T1D);
5091     pmull2(v18, T1Q, v0, v31, T2D);
5092     eor3(v0, T16B, v17, v18, v4);
5093 
5094     pmull (v19, T1Q, v1, v31, T1D);
5095     pmull2(v20, T1Q, v1, v31, T2D);
5096     eor3(v1, T16B, v19, v20, v5);
5097 
5098     pmull (v21, T1Q, v2, v31, T1D);
5099     pmull2(v22, T1Q, v2, v31, T2D);
5100     eor3(v2, T16B, v21, v22, v6);
5101 
5102     pmull (v23, T1Q, v3, v31, T1D);
5103     pmull2(v24, T1Q, v3, v31, T2D);
5104     eor3(v3, T16B, v23, v24, v7);
5105 
5106     // fold into 128 bits
5107     // Use v17 for constants because v31 can be still in use.
5108     ldrq(v17, Address(table, 0x20));
5109     pmull (v25, T1Q, v0, v17, T1D);
5110     pmull2(v26, T1Q, v0, v17, T2D);
5111     eor3(v3, T16B, v3, v25, v26);
5112 
5113     // Use v18 for constants because v17 can be still in use.
5114     ldrq(v18, Address(table, 0x30));
5115     pmull (v27, T1Q, v1, v18, T1D);
5116     pmull2(v28, T1Q, v1, v18, T2D);
5117     eor3(v3, T16B, v3, v27, v28);
5118 
5119     // Use v19 for constants because v18 can be still in use.
5120     ldrq(v19, Address(table, 0x40));
5121     pmull (v29, T1Q, v2, v19, T1D);
5122     pmull2(v30, T1Q, v2, v19, T2D);
5123     eor3(v0, T16B, v3, v29, v30);
5124 
5125     add(len, len, 0x80);
5126     add(buf, buf, 0x10);
5127 
5128     mov(tmp0, v0, D, 0);
5129     mov(tmp1, v0, D, 1);
5130 }
5131 
5132 void MacroAssembler::addptr(const Address &dst, int32_t src) {
5133   Address adr;
5134   switch(dst.getMode()) {
5135   case Address::base_plus_offset:
5136     // This is the expected mode, although we allow all the other
5137     // forms below.
5138     adr = form_address(rscratch2, dst.base(), dst.offset(), LogBytesPerWord);
5139     break;
5140   default:
5141     lea(rscratch2, dst);
5142     adr = Address(rscratch2);
5143     break;
5144   }
5145   ldr(rscratch1, adr);
5146   add(rscratch1, rscratch1, src);
5147   str(rscratch1, adr);
5148 }
5149 
5150 void MacroAssembler::cmpptr(Register src1, Address src2) {
5151   uint64_t offset;
5152   adrp(rscratch1, src2, offset);
5153   ldr(rscratch1, Address(rscratch1, offset));
5154   cmp(src1, rscratch1);
5155 }
5156 
5157 void MacroAssembler::cmpoop(Register obj1, Register obj2) {
5158   cmp(obj1, obj2);
5159 }
5160 
5161 void MacroAssembler::load_method_holder_cld(Register rresult, Register rmethod) {
5162   load_method_holder(rresult, rmethod);
5163   ldr(rresult, Address(rresult, InstanceKlass::class_loader_data_offset()));
5164 }
5165 
5166 void MacroAssembler::load_method_holder(Register holder, Register method) {
5167   ldr(holder, Address(method, Method::const_offset()));                      // ConstMethod*
5168   ldr(holder, Address(holder, ConstMethod::constants_offset()));             // ConstantPool*
5169   ldr(holder, Address(holder, ConstantPool::pool_holder_offset()));          // InstanceKlass*
5170 }
5171 
5172 void MacroAssembler::load_metadata(Register dst, Register src) {
5173   if (UseCompactObjectHeaders) {
5174     load_narrow_klass_compact(dst, src);
5175   } else {
5176     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5177   }
5178 }
5179 
5180 // Loads the obj's Klass* into dst.
5181 // Preserves all registers (incl src, rscratch1 and rscratch2).
5182 // Input:
5183 // src - the oop we want to load the klass from.
5184 // dst - output narrow klass.
5185 void MacroAssembler::load_narrow_klass_compact(Register dst, Register src) {
5186   assert(UseCompactObjectHeaders, "expects UseCompactObjectHeaders");
5187   ldr(dst, Address(src, oopDesc::mark_offset_in_bytes()));
5188   lsr(dst, dst, markWord::klass_shift);
5189 }
5190 
5191 void MacroAssembler::load_klass(Register dst, Register src) {
5192   if (UseCompactObjectHeaders) {
5193     load_narrow_klass_compact(dst, src);
5194   } else {
5195     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5196   }
5197   decode_klass_not_null(dst);
5198 }
5199 
5200 void MacroAssembler::restore_cpu_control_state_after_jni(Register tmp1, Register tmp2) {
5201   if (RestoreMXCSROnJNICalls) {
5202     Label OK;
5203     get_fpcr(tmp1);
5204     mov(tmp2, tmp1);
5205     // Set FPCR to the state we need. We do want Round to Nearest. We
5206     // don't want non-IEEE rounding modes or floating-point traps.
5207     bfi(tmp1, zr, 22, 4); // Clear DN, FZ, and Rmode
5208     bfi(tmp1, zr, 8, 5);  // Clear exception-control bits (8-12)
5209     bfi(tmp1, zr, 0, 2);  // Clear AH:FIZ
5210     eor(tmp2, tmp1, tmp2);
5211     cbz(tmp2, OK);        // Only reset FPCR if it's wrong
5212     set_fpcr(tmp1);
5213     bind(OK);
5214   }
5215 }
5216 
5217 // ((OopHandle)result).resolve();
5218 void MacroAssembler::resolve_oop_handle(Register result, Register tmp1, Register tmp2) {
5219   // OopHandle::resolve is an indirection.
5220   access_load_at(T_OBJECT, IN_NATIVE, result, Address(result, 0), tmp1, tmp2);
5221 }
5222 
5223 // ((WeakHandle)result).resolve();
5224 void MacroAssembler::resolve_weak_handle(Register result, Register tmp1, Register tmp2) {
5225   assert_different_registers(result, tmp1, tmp2);
5226   Label resolved;
5227 
5228   // A null weak handle resolves to null.
5229   cbz(result, resolved);
5230 
5231   // Only 64 bit platforms support GCs that require a tmp register
5232   // WeakHandle::resolve is an indirection like jweak.
5233   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
5234                  result, Address(result), tmp1, tmp2);
5235   bind(resolved);
5236 }
5237 
5238 void MacroAssembler::load_mirror(Register dst, Register method, Register tmp1, Register tmp2) {
5239   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
5240   ldr(dst, Address(rmethod, Method::const_offset()));
5241   ldr(dst, Address(dst, ConstMethod::constants_offset()));
5242   ldr(dst, Address(dst, ConstantPool::pool_holder_offset()));
5243   ldr(dst, Address(dst, mirror_offset));
5244   resolve_oop_handle(dst, tmp1, tmp2);
5245 }
5246 
5247 void MacroAssembler::cmp_klass(Register obj, Register klass, Register tmp) {
5248   assert_different_registers(obj, klass, tmp);
5249   if (UseCompactObjectHeaders) {
5250     load_narrow_klass_compact(tmp, obj);
5251   } else {
5252     ldrw(tmp, Address(obj, oopDesc::klass_offset_in_bytes()));
5253   }
5254   if (CompressedKlassPointers::base() == nullptr) {
5255     cmp(klass, tmp, LSL, CompressedKlassPointers::shift());
5256     return;
5257   } else if (!AOTCodeCache::is_on_for_dump() &&
5258              ((uint64_t)CompressedKlassPointers::base() & 0xffffffff) == 0
5259              && CompressedKlassPointers::shift() == 0) {
5260     // Only the bottom 32 bits matter
5261     cmpw(klass, tmp);
5262     return;
5263   }
5264   decode_klass_not_null(tmp);
5265   cmp(klass, tmp);
5266 }
5267 
5268 void MacroAssembler::cmp_klasses_from_objects(Register obj1, Register obj2, Register tmp1, Register tmp2) {
5269   if (UseCompactObjectHeaders) {
5270     load_narrow_klass_compact(tmp1, obj1);
5271     load_narrow_klass_compact(tmp2, obj2);
5272   } else {
5273     ldrw(tmp1, Address(obj1, oopDesc::klass_offset_in_bytes()));
5274     ldrw(tmp2, Address(obj2, oopDesc::klass_offset_in_bytes()));
5275   }
5276   cmpw(tmp1, tmp2);
5277 }
5278 
5279 void MacroAssembler::load_prototype_header(Register dst, Register src) {
5280   load_klass(dst, src);
5281   ldr(dst, Address(dst, Klass::prototype_header_offset()));
5282 }
5283 
5284 void MacroAssembler::store_klass(Register dst, Register src) {
5285   // FIXME: Should this be a store release?  concurrent gcs assumes
5286   // klass length is valid if klass field is not null.
5287   assert(!UseCompactObjectHeaders, "not with compact headers");
5288   encode_klass_not_null(src);
5289   strw(src, Address(dst, oopDesc::klass_offset_in_bytes()));
5290 }
5291 
5292 void MacroAssembler::store_klass_gap(Register dst, Register src) {
5293   assert(!UseCompactObjectHeaders, "not with compact headers");
5294   // Store to klass gap in destination
5295   strw(src, Address(dst, oopDesc::klass_gap_offset_in_bytes()));
5296 }
5297 
5298 // Algorithm must match CompressedOops::encode.
5299 void MacroAssembler::encode_heap_oop(Register d, Register s) {
5300 #ifdef ASSERT
5301   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
5302 #endif
5303   verify_oop_msg(s, "broken oop in encode_heap_oop");
5304   if (CompressedOops::base() == nullptr) {
5305     if (CompressedOops::shift() != 0) {
5306       assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5307       lsr(d, s, LogMinObjAlignmentInBytes);
5308     } else {
5309       mov(d, s);
5310     }
5311   } else {
5312     subs(d, s, rheapbase);
5313     csel(d, d, zr, Assembler::HS);
5314     lsr(d, d, LogMinObjAlignmentInBytes);
5315 
5316     /*  Old algorithm: is this any worse?
5317     Label nonnull;
5318     cbnz(r, nonnull);
5319     sub(r, r, rheapbase);
5320     bind(nonnull);
5321     lsr(r, r, LogMinObjAlignmentInBytes);
5322     */
5323   }
5324 }
5325 
5326 void MacroAssembler::encode_heap_oop_not_null(Register r) {
5327 #ifdef ASSERT
5328   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
5329   if (CheckCompressedOops) {
5330     Label ok;
5331     cbnz(r, ok);
5332     stop("null oop passed to encode_heap_oop_not_null");
5333     bind(ok);
5334   }
5335 #endif
5336   verify_oop_msg(r, "broken oop in encode_heap_oop_not_null");
5337   if (CompressedOops::base() != nullptr) {
5338     sub(r, r, rheapbase);
5339   }
5340   if (CompressedOops::shift() != 0) {
5341     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5342     lsr(r, r, LogMinObjAlignmentInBytes);
5343   }
5344 }
5345 
5346 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
5347 #ifdef ASSERT
5348   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
5349   if (CheckCompressedOops) {
5350     Label ok;
5351     cbnz(src, ok);
5352     stop("null oop passed to encode_heap_oop_not_null2");
5353     bind(ok);
5354   }
5355 #endif
5356   verify_oop_msg(src, "broken oop in encode_heap_oop_not_null2");
5357 
5358   Register data = src;
5359   if (CompressedOops::base() != nullptr) {
5360     sub(dst, src, rheapbase);
5361     data = dst;
5362   }
5363   if (CompressedOops::shift() != 0) {
5364     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5365     lsr(dst, data, LogMinObjAlignmentInBytes);
5366     data = dst;
5367   }
5368   if (data == src)
5369     mov(dst, src);
5370 }
5371 
5372 void  MacroAssembler::decode_heap_oop(Register d, Register s) {
5373 #ifdef ASSERT
5374   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
5375 #endif
5376   if (CompressedOops::base() == nullptr) {
5377     if (CompressedOops::shift() != 0) {
5378       lsl(d, s, CompressedOops::shift());
5379     } else if (d != s) {
5380       mov(d, s);
5381     }
5382   } else {
5383     Label done;
5384     if (d != s)
5385       mov(d, s);
5386     cbz(s, done);
5387     add(d, rheapbase, s, Assembler::LSL, LogMinObjAlignmentInBytes);
5388     bind(done);
5389   }
5390   verify_oop_msg(d, "broken oop in decode_heap_oop");
5391 }
5392 
5393 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
5394   assert (UseCompressedOops, "should only be used for compressed headers");
5395   assert (Universe::heap() != nullptr, "java heap should be initialized");
5396   // Cannot assert, unverified entry point counts instructions (see .ad file)
5397   // vtableStubs also counts instructions in pd_code_size_limit.
5398   // Also do not verify_oop as this is called by verify_oop.
5399   if (CompressedOops::shift() != 0) {
5400     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5401     if (CompressedOops::base() != nullptr) {
5402       add(r, rheapbase, r, Assembler::LSL, LogMinObjAlignmentInBytes);
5403     } else {
5404       add(r, zr, r, Assembler::LSL, LogMinObjAlignmentInBytes);
5405     }
5406   } else {
5407     assert (CompressedOops::base() == nullptr, "sanity");
5408   }
5409 }
5410 
5411 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
5412   assert (UseCompressedOops, "should only be used for compressed headers");
5413   assert (Universe::heap() != nullptr, "java heap should be initialized");
5414   // Cannot assert, unverified entry point counts instructions (see .ad file)
5415   // vtableStubs also counts instructions in pd_code_size_limit.
5416   // Also do not verify_oop as this is called by verify_oop.
5417   if (CompressedOops::shift() != 0) {
5418     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5419     if (CompressedOops::base() != nullptr) {
5420       add(dst, rheapbase, src, Assembler::LSL, LogMinObjAlignmentInBytes);
5421     } else {
5422       add(dst, zr, src, Assembler::LSL, LogMinObjAlignmentInBytes);
5423     }
5424   } else {
5425     assert (CompressedOops::base() == nullptr, "sanity");
5426     if (dst != src) {
5427       mov(dst, src);
5428     }
5429   }
5430 }
5431 
5432 MacroAssembler::KlassDecodeMode MacroAssembler::_klass_decode_mode(KlassDecodeNone);
5433 
5434 MacroAssembler::KlassDecodeMode MacroAssembler::klass_decode_mode() {
5435   assert(Metaspace::initialized(), "metaspace not initialized yet");
5436   assert(_klass_decode_mode != KlassDecodeNone, "should be initialized");
5437   return _klass_decode_mode;
5438 }
5439 
5440 MacroAssembler::KlassDecodeMode  MacroAssembler::klass_decode_mode(address base, int shift, const size_t range) {
5441   // KlassDecodeMode shouldn't be set already.
5442   assert(_klass_decode_mode == KlassDecodeNone, "set once");
5443 
5444   if (base == nullptr) {
5445     return KlassDecodeZero;
5446   }
5447 
5448   if (operand_valid_for_logical_immediate(
5449         /*is32*/false, (uint64_t)base)) {
5450     const uint64_t range_mask = right_n_bits(log2i_ceil(range));
5451     if (((uint64_t)base & range_mask) == 0) {
5452       return KlassDecodeXor;
5453     }
5454   }
5455 
5456   const uint64_t shifted_base =
5457     (uint64_t)base >> shift;
5458   if ((shifted_base & 0xffff0000ffffffff) == 0) {
5459     return KlassDecodeMovk;
5460   }
5461 
5462   // No valid encoding.
5463   return KlassDecodeNone;
5464 }
5465 
5466 // Check if one of the above decoding modes will work for given base, shift and range.
5467 bool MacroAssembler::check_klass_decode_mode(address base, int shift, const size_t range) {
5468   return klass_decode_mode(base, shift, range) != KlassDecodeNone;
5469 }
5470 
5471 bool MacroAssembler::set_klass_decode_mode(address base, int shift, const size_t range) {
5472   _klass_decode_mode = klass_decode_mode(base, shift, range);
5473   return _klass_decode_mode != KlassDecodeNone;
5474 }
5475 
5476 static Register pick_different_tmp(Register dst, Register src) {
5477   auto tmps = RegSet::of(r0, r1, r2) - RegSet::of(src, dst);
5478   return *tmps.begin();
5479 }
5480 
5481 void MacroAssembler::encode_klass_not_null_for_aot(Register dst, Register src) {
5482   // we have to load the klass base from the AOT constants area but
5483   // not the shift because it is not allowed to change
5484   int shift = CompressedKlassPointers::shift();
5485   assert(shift >= 0 && shift <= CompressedKlassPointers::max_shift(), "unexpected compressed klass shift!");
5486   if (dst != src) {
5487     // we can load the base into dst, subtract it formthe src and shift down
5488     lea(dst, ExternalAddress(CompressedKlassPointers::base_addr()));
5489     ldr(dst, dst);
5490     sub(dst, src, dst);
5491     lsr(dst, dst, shift);
5492   } else {
5493     // we need an extra register in order to load the coop base
5494     Register tmp = pick_different_tmp(dst, src);
5495     RegSet regs = RegSet::of(tmp);
5496     push(regs, sp);
5497     lea(tmp, ExternalAddress(CompressedKlassPointers::base_addr()));
5498     ldr(tmp, tmp);
5499     sub(dst, src, tmp);
5500     lsr(dst, dst, shift);
5501     pop(regs, sp);
5502   }
5503 }
5504 
5505 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
5506   if (CompressedKlassPointers::base() != nullptr && AOTCodeCache::is_on_for_dump()) {
5507     encode_klass_not_null_for_aot(dst, src);
5508     return;
5509   }
5510 
5511   switch (klass_decode_mode()) {
5512   case KlassDecodeZero:
5513     if (CompressedKlassPointers::shift() != 0) {
5514       lsr(dst, src, CompressedKlassPointers::shift());
5515     } else {
5516       if (dst != src) mov(dst, src);
5517     }
5518     break;
5519 
5520   case KlassDecodeXor:
5521     if (CompressedKlassPointers::shift() != 0) {
5522       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
5523       lsr(dst, dst, CompressedKlassPointers::shift());
5524     } else {
5525       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
5526     }
5527     break;
5528 
5529   case KlassDecodeMovk:
5530     if (CompressedKlassPointers::shift() != 0) {
5531       ubfx(dst, src, CompressedKlassPointers::shift(), 32);
5532     } else {
5533       movw(dst, src);
5534     }
5535     break;
5536 
5537   case KlassDecodeNone:
5538     ShouldNotReachHere();
5539     break;
5540   }
5541 }
5542 
5543 void MacroAssembler::encode_klass_not_null(Register r) {
5544   encode_klass_not_null(r, r);
5545 }
5546 
5547 void MacroAssembler::decode_klass_not_null_for_aot(Register dst, Register src) {
5548   // we have to load the klass base from the AOT constants area but
5549   // not the shift because it is not allowed to change
5550   int shift = CompressedKlassPointers::shift();
5551   assert(shift >= 0 && shift <= CompressedKlassPointers::max_shift(), "unexpected compressed klass shift!");
5552   if (dst != src) {
5553     // we can load the base into dst then add the offset with a suitable shift
5554     lea(dst, ExternalAddress(CompressedKlassPointers::base_addr()));
5555     ldr(dst, dst);
5556     add(dst, dst, src, LSL,  shift);
5557   } else {
5558     // we need an extra register in order to load the coop base
5559     Register tmp = pick_different_tmp(dst, src);
5560     RegSet regs = RegSet::of(tmp);
5561     push(regs, sp);
5562     lea(tmp, ExternalAddress(CompressedKlassPointers::base_addr()));
5563     ldr(tmp, tmp);
5564     add(dst, tmp,  src, LSL,  shift);
5565     pop(regs, sp);
5566   }
5567 }
5568 
5569 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
5570   if (AOTCodeCache::is_on_for_dump()) {
5571     decode_klass_not_null_for_aot(dst, src);
5572     return;
5573   }
5574 
5575   switch (klass_decode_mode()) {
5576   case KlassDecodeZero:
5577     if (CompressedKlassPointers::shift() != 0) {
5578       lsl(dst, src, CompressedKlassPointers::shift());
5579     } else {
5580       if (dst != src) mov(dst, src);
5581     }
5582     break;
5583 
5584   case KlassDecodeXor:
5585     if (CompressedKlassPointers::shift() != 0) {
5586       lsl(dst, src, CompressedKlassPointers::shift());
5587       eor(dst, dst, (uint64_t)CompressedKlassPointers::base());
5588     } else {
5589       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
5590     }
5591     break;
5592 
5593   case KlassDecodeMovk: {
5594     const uint64_t shifted_base =
5595       (uint64_t)CompressedKlassPointers::base() >> CompressedKlassPointers::shift();
5596 
5597     if (dst != src) movw(dst, src);
5598     movk(dst, shifted_base >> 32, 32);
5599 
5600     if (CompressedKlassPointers::shift() != 0) {
5601       lsl(dst, dst, CompressedKlassPointers::shift());
5602     }
5603 
5604     break;
5605   }
5606 
5607   case KlassDecodeNone:
5608     ShouldNotReachHere();
5609     break;
5610   }
5611 }
5612 
5613 void  MacroAssembler::decode_klass_not_null(Register r) {
5614   decode_klass_not_null(r, r);
5615 }
5616 
5617 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
5618 #ifdef ASSERT
5619   {
5620     ThreadInVMfromUnknown tiv;
5621     assert (UseCompressedOops, "should only be used for compressed oops");
5622     assert (Universe::heap() != nullptr, "java heap should be initialized");
5623     assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5624     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
5625   }
5626 #endif
5627   int oop_index = oop_recorder()->find_index(obj);
5628   InstructionMark im(this);
5629   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5630   code_section()->relocate(inst_mark(), rspec);
5631   movz(dst, 0xDEAD, 16);
5632   movk(dst, 0xBEEF);
5633 }
5634 
5635 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
5636   assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5637   int index = oop_recorder()->find_index(k);
5638 
5639   InstructionMark im(this);
5640   RelocationHolder rspec = metadata_Relocation::spec(index);
5641   code_section()->relocate(inst_mark(), rspec);
5642   narrowKlass nk = CompressedKlassPointers::encode(k);
5643   movz(dst, (nk >> 16), 16);
5644   movk(dst, nk & 0xffff);
5645 }
5646 
5647 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators,
5648                                     Register dst, Address src,
5649                                     Register tmp1, Register tmp2) {
5650   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
5651   decorators = AccessInternal::decorator_fixup(decorators, type);
5652   bool as_raw = (decorators & AS_RAW) != 0;
5653   if (as_raw) {
5654     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, tmp2);
5655   } else {
5656     bs->load_at(this, decorators, type, dst, src, tmp1, tmp2);
5657   }
5658 }
5659 
5660 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators,
5661                                      Address dst, Register val,
5662                                      Register tmp1, Register tmp2, Register tmp3) {
5663   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
5664   decorators = AccessInternal::decorator_fixup(decorators, type);
5665   bool as_raw = (decorators & AS_RAW) != 0;
5666   if (as_raw) {
5667     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, val, tmp1, tmp2, tmp3);
5668   } else {
5669     bs->store_at(this, decorators, type, dst, val, tmp1, tmp2, tmp3);
5670   }
5671 }
5672 
5673 void MacroAssembler::flat_field_copy(DecoratorSet decorators, Register src, Register dst,
5674                                      Register inline_layout_info) {
5675   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5676   bs->flat_field_copy(this, decorators, src, dst, inline_layout_info);
5677 }
5678 
5679 void MacroAssembler::payload_offset(Register inline_klass, Register offset) {
5680   ldr(offset, Address(inline_klass, InlineKlass::adr_members_offset()));
5681   ldrw(offset, Address(offset, InlineKlass::payload_offset_offset()));
5682 }
5683 
5684 void MacroAssembler::payload_address(Register oop, Register data, Register inline_klass) {
5685   // ((address) (void*) o) + vk->payload_offset();
5686   Register offset = (data == oop) ? rscratch1 : data;
5687   payload_offset(inline_klass, offset);
5688   if (data == oop) {
5689     add(data, data, offset);
5690   } else {
5691     lea(data, Address(oop, offset));
5692   }
5693 }
5694 
5695 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
5696                                    Register tmp2, DecoratorSet decorators) {
5697   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2);
5698 }
5699 
5700 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
5701                                             Register tmp2, DecoratorSet decorators) {
5702   access_load_at(T_OBJECT, IN_HEAP | IS_NOT_NULL | decorators, dst, src, tmp1, tmp2);
5703 }
5704 
5705 void MacroAssembler::store_heap_oop(Address dst, Register val, Register tmp1,
5706                                     Register tmp2, Register tmp3, DecoratorSet decorators) {
5707   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, val, tmp1, tmp2, tmp3);
5708 }
5709 
5710 // Used for storing nulls.
5711 void MacroAssembler::store_heap_oop_null(Address dst) {
5712   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg, noreg);
5713 }
5714 
5715 Address MacroAssembler::allocate_metadata_address(Metadata* obj) {
5716   assert(oop_recorder() != nullptr, "this assembler needs a Recorder");
5717   int index = oop_recorder()->allocate_metadata_index(obj);
5718   RelocationHolder rspec = metadata_Relocation::spec(index);
5719   return Address((address)obj, rspec);
5720 }
5721 
5722 // Move an oop into a register.
5723 void MacroAssembler::movoop(Register dst, jobject obj) {
5724   int oop_index;
5725   if (obj == nullptr) {
5726     oop_index = oop_recorder()->allocate_oop_index(obj);
5727   } else {
5728 #ifdef ASSERT
5729     {
5730       ThreadInVMfromUnknown tiv;
5731       assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
5732     }
5733 #endif
5734     oop_index = oop_recorder()->find_index(obj);
5735   }
5736   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5737 
5738   if (BarrierSet::barrier_set()->barrier_set_assembler()->supports_instruction_patching()) {
5739     mov(dst, Address((address)obj, rspec));
5740   } else {
5741     address dummy = address(uintptr_t(pc()) & -wordSize); // A nearby aligned address
5742     ldr(dst, Address(dummy, rspec));
5743   }
5744 }
5745 
5746 // Move a metadata address into a register.
5747 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
5748   int oop_index;
5749   if (obj == nullptr) {
5750     oop_index = oop_recorder()->allocate_metadata_index(obj);
5751   } else {
5752     oop_index = oop_recorder()->find_index(obj);
5753   }
5754   RelocationHolder rspec = metadata_Relocation::spec(oop_index);
5755   mov(dst, Address((address)obj, rspec));
5756 }
5757 
5758 Address MacroAssembler::constant_oop_address(jobject obj) {
5759 #ifdef ASSERT
5760   {
5761     ThreadInVMfromUnknown tiv;
5762     assert(oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5763     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "not an oop");
5764   }
5765 #endif
5766   int oop_index = oop_recorder()->find_index(obj);
5767   return Address((address)obj, oop_Relocation::spec(oop_index));
5768 }
5769 
5770 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5771 void MacroAssembler::tlab_allocate(Register obj,
5772                                    Register var_size_in_bytes,
5773                                    int con_size_in_bytes,
5774                                    Register t1,
5775                                    Register t2,
5776                                    Label& slow_case) {
5777   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
5778   bs->tlab_allocate(this, obj, var_size_in_bytes, con_size_in_bytes, t1, t2, slow_case);
5779 }
5780 
5781 void MacroAssembler::verify_tlab() {
5782 #ifdef ASSERT
5783   if (UseTLAB && VerifyOops) {
5784     Label next, ok;
5785 
5786     stp(rscratch2, rscratch1, Address(pre(sp, -16)));
5787 
5788     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
5789     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
5790     cmp(rscratch2, rscratch1);
5791     br(Assembler::HS, next);
5792     STOP("assert(top >= start)");
5793     should_not_reach_here();
5794 
5795     bind(next);
5796     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
5797     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
5798     cmp(rscratch2, rscratch1);
5799     br(Assembler::HS, ok);
5800     STOP("assert(top <= end)");
5801     should_not_reach_here();
5802 
5803     bind(ok);
5804     ldp(rscratch2, rscratch1, Address(post(sp, 16)));
5805   }
5806 #endif
5807 }
5808 
5809 void MacroAssembler::inline_layout_info(Register holder_klass, Register index, Register layout_info) {
5810   assert_different_registers(holder_klass, index, layout_info);
5811   InlineLayoutInfo array[2];
5812   int size = (char*)&array[1] - (char*)&array[0]; // computing size of array elements
5813   if (is_power_of_2(size)) {
5814     lsl(index, index, log2i_exact(size)); // Scale index by power of 2
5815   } else {
5816     mov(layout_info, size);
5817     mul(index, index, layout_info); // Scale the index to be the entry index * array_element_size
5818   }
5819   ldr(layout_info, Address(holder_klass, InstanceKlass::inline_layout_info_array_offset()));
5820   add(layout_info, layout_info, Array<InlineLayoutInfo>::base_offset_in_bytes());
5821   lea(layout_info, Address(layout_info, index));
5822 }
5823 
5824 // Writes to stack successive pages until offset reached to check for
5825 // stack overflow + shadow pages.  This clobbers tmp.
5826 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
5827   assert_different_registers(tmp, size, rscratch1);
5828   mov(tmp, sp);
5829   // Bang stack for total size given plus shadow page size.
5830   // Bang one page at a time because large size can bang beyond yellow and
5831   // red zones.
5832   Label loop;
5833   mov(rscratch1, (int)os::vm_page_size());
5834   bind(loop);
5835   lea(tmp, Address(tmp, -(int)os::vm_page_size()));
5836   subsw(size, size, rscratch1);
5837   str(size, Address(tmp));
5838   br(Assembler::GT, loop);
5839 
5840   // Bang down shadow pages too.
5841   // At this point, (tmp-0) is the last address touched, so don't
5842   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
5843   // was post-decremented.)  Skip this address by starting at i=1, and
5844   // touch a few more pages below.  N.B.  It is important to touch all
5845   // the way down to and including i=StackShadowPages.
5846   for (int i = 0; i < (int)(StackOverflow::stack_shadow_zone_size() / (int)os::vm_page_size()) - 1; i++) {
5847     // this could be any sized move but this is can be a debugging crumb
5848     // so the bigger the better.
5849     lea(tmp, Address(tmp, -(int)os::vm_page_size()));
5850     str(size, Address(tmp));
5851   }
5852 }
5853 
5854 // Move the address of the polling page into dest.
5855 void MacroAssembler::get_polling_page(Register dest, relocInfo::relocType rtype) {
5856   ldr(dest, Address(rthread, JavaThread::polling_page_offset()));
5857 }
5858 
5859 // Read the polling page.  The address of the polling page must
5860 // already be in r.
5861 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
5862   address mark;
5863   {
5864     InstructionMark im(this);
5865     code_section()->relocate(inst_mark(), rtype);
5866     ldrw(zr, Address(r, 0));
5867     mark = inst_mark();
5868   }
5869   verify_cross_modify_fence_not_required();
5870   return mark;
5871 }
5872 
5873 void MacroAssembler::adrp(Register reg1, const Address &dest, uint64_t &byte_offset) {
5874   uint64_t low_page = (uint64_t)CodeCache::low_bound() >> 12;
5875   uint64_t high_page = (uint64_t)(CodeCache::high_bound()-1) >> 12;
5876   uint64_t dest_page = (uint64_t)dest.target() >> 12;
5877   int64_t offset_low = dest_page - low_page;
5878   int64_t offset_high = dest_page - high_page;
5879 
5880   assert(is_valid_AArch64_address(dest.target()), "bad address");
5881   assert(dest.getMode() == Address::literal, "ADRP must be applied to a literal address");
5882 
5883   InstructionMark im(this);
5884   code_section()->relocate(inst_mark(), dest.rspec());
5885   // 8143067: Ensure that the adrp can reach the dest from anywhere within
5886   // the code cache so that if it is relocated we know it will still reach
5887   if (offset_high >= -(1<<20) && offset_low < (1<<20)) {
5888     _adrp(reg1, dest.target());
5889   } else {
5890     uint64_t target = (uint64_t)dest.target();
5891     uint64_t adrp_target
5892       = (target & 0xffffffffULL) | ((uint64_t)pc() & 0xffff00000000ULL);
5893 
5894     _adrp(reg1, (address)adrp_target);
5895     movk(reg1, target >> 32, 32);
5896   }
5897   byte_offset = (uint64_t)dest.target() & 0xfff;
5898 }
5899 
5900 void MacroAssembler::load_byte_map_base(Register reg) {
5901 #if INCLUDE_CDS
5902   if (AOTCodeCache::is_on_for_dump()) {
5903     address byte_map_base_adr = AOTRuntimeConstants::card_table_base_address();
5904     lea(reg, ExternalAddress(byte_map_base_adr));
5905     ldr(reg, Address(reg));
5906     return;
5907   }
5908 #endif
5909   CardTableBarrierSet* ctbs = CardTableBarrierSet::barrier_set();
5910 
5911   // Strictly speaking the card table base isn't an address at all, and it might
5912   // even be negative. It is thus materialised as a constant.
5913   mov(reg, (uint64_t)ctbs->card_table_base_const());
5914 }
5915 
5916 void MacroAssembler::load_aotrc_address(Register reg, address a) {
5917 #if INCLUDE_CDS
5918   assert(AOTRuntimeConstants::contains(a), "address out of range for data area");
5919   if (AOTCodeCache::is_on_for_dump()) {
5920     // all aotrc field addresses should be registered in the AOTCodeCache address table
5921     lea(reg, ExternalAddress(a));
5922   } else {
5923     mov(reg, (uint64_t)a);
5924   }
5925 #else
5926   ShouldNotReachHere();
5927 #endif
5928 }
5929 
5930 #ifdef ASSERT
5931 void MacroAssembler::build_frame(int framesize) {
5932   build_frame(framesize, false);
5933 }
5934 #endif
5935 
5936 void MacroAssembler::build_frame(int framesize DEBUG_ONLY(COMMA bool zap_rfp_lr_spills)) {
5937   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
5938   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
5939   protect_return_address();
5940   if (framesize < ((1 << 9) + 2 * wordSize)) {
5941     sub(sp, sp, framesize);
5942     if (DEBUG_ONLY(zap_rfp_lr_spills ||) false) {
5943       mov_immediate64(rscratch1, ((uint64_t)badRegWordVal) << 32 | (uint64_t)badRegWordVal);
5944       stp(rscratch1, rscratch1, Address(sp, framesize - 2 * wordSize));
5945     } else {
5946       stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
5947     }
5948     if (PreserveFramePointer) add(rfp, sp, framesize - 2 * wordSize);
5949   } else {
5950     if (DEBUG_ONLY(zap_rfp_lr_spills ||) false) {
5951       mov_immediate64(rscratch1, ((uint64_t)badRegWordVal) << 32 | (uint64_t)badRegWordVal);
5952       stp(rscratch1, rscratch1, Address(pre(sp, -2 * wordSize)));
5953     } else {
5954       stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
5955     }
5956     if (PreserveFramePointer) mov(rfp, sp);
5957     if (framesize < ((1 << 12) + 2 * wordSize))
5958       sub(sp, sp, framesize - 2 * wordSize);
5959     else {
5960       mov(rscratch1, framesize - 2 * wordSize);
5961       sub(sp, sp, rscratch1);
5962     }
5963   }
5964   verify_cross_modify_fence_not_required();
5965 }
5966 
5967 void MacroAssembler::remove_frame(int framesize) {
5968   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
5969   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
5970   if (framesize < ((1 << 9) + 2 * wordSize)) {
5971     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
5972     add(sp, sp, framesize);
5973   } else {
5974     if (framesize < ((1 << 12) + 2 * wordSize))
5975       add(sp, sp, framesize - 2 * wordSize);
5976     else {
5977       mov(rscratch1, framesize - 2 * wordSize);
5978       add(sp, sp, rscratch1);
5979     }
5980     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
5981   }
5982   authenticate_return_address();
5983 }
5984 
5985 void MacroAssembler::remove_frame(int initial_framesize, bool needs_stack_repair) {
5986   if (needs_stack_repair) {
5987     // The method has a scalarized entry point (where fields of value object arguments
5988     // are passed through registers and stack), and a non-scalarized entry point (where
5989     // value object arguments are given as oops). The non-scalarized entry point will
5990     // first load each field of value object arguments and store them in registers and on
5991     // the stack in a way compatible with the scalarized entry point. To do so, some extra
5992     // stack space might be reserved (if argument registers are not enough). On leaving the
5993     // method, this space must be freed.
5994     //
5995     // In case we used the non-scalarized entry point the stack looks like this:
5996     //
5997     // | Arguments from caller     |
5998     // |---------------------------|  <-- caller's SP
5999     // | Saved LR #1               |
6000     // | Saved FP #1               |
6001     // |---------------------------|
6002     // | Extension space for       |
6003     // |   inline arg (un)packing  |
6004     // |---------------------------|  <-- start of this method's frame
6005     // | Saved LR #2               |
6006     // | Saved FP #2               |
6007     // |---------------------------|  <-- FP (with -XX:+PreserveFramePointer)
6008     // | sp_inc                    |
6009     // | method locals             |
6010     // |---------------------------|  <-- SP
6011     //
6012     // There are two copies of FP and LR on the stack. They will be identical at
6013     // first, but that can change.
6014     // If the caller has been deoptimized, LR #1 will be patched to point at the
6015     // deopt blob, and LR #2 will still point into the old method.
6016     // If the saved FP (x29) was not used as the frame pointer, but to store an
6017     // oop, the GC will be aware only of FP #1 as the spilled location of x29 and
6018     // will fix only this one. Overall, FP/LR #2 are not reliable and are simply
6019     // needed to add space between the extension space and the locals, as there
6020     // would be between the real arguments and the locals if we don't need to
6021     // do unpacking (from the scalarized entry point).
6022     //
6023     // When restoring, one must then load FP #1 into x29, and LR #1 into x30,
6024     // while keeping in mind that from the scalarized entry point, there will be
6025     // only one copy of each. Indeed, in the case we used the scalarized calling
6026     // convention, the stack looks like this:
6027     //
6028     // | Arguments from caller     |
6029     // |---------------------------|  <-- caller's SP / start of this method's frame
6030     // | Saved LR                  |
6031     // | Saved FP                  |
6032     // |---------------------------|  <-- FP (with -XX:+PreserveFramePointer)
6033     // | sp_inc                    |
6034     // | method locals             |
6035     // |---------------------------|  <-- SP
6036     //
6037     // The sp_inc stack slot holds the total size of the frame including the
6038     // extension space minus two words for the saved FP and LR. That is how to
6039     // find FP/LR #1. This size is expressed in bytes. Be careful when using it
6040     // from C++ in pointer arithmetic; you might need to divide it by wordSize.
6041     //
6042     // One can find sp_inc since the start the method's frame is SP + initial_framesize.
6043 
6044     int sp_inc_offset = initial_framesize - 3 * wordSize;  // Immediately below saved LR and FP
6045 
6046     ldr(rscratch1, Address(sp, sp_inc_offset));
6047     add(sp, sp, rscratch1);
6048     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
6049   } else {
6050     remove_frame(initial_framesize);
6051   }
6052 }
6053 
6054 void MacroAssembler::save_stack_increment(int sp_inc, int frame_size) {
6055   int real_frame_size = frame_size + sp_inc;
6056   assert(sp_inc == 0 || sp_inc > 2*wordSize, "invalid sp_inc value");
6057   assert(real_frame_size >= 2*wordSize, "frame size must include FP/LR space");
6058   assert((real_frame_size & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
6059 
6060   int sp_inc_offset = frame_size - 3 * wordSize;  // Immediately below saved LR and FP
6061 
6062   // Subtract two words for the saved FP and LR as these will be popped
6063   // separately. See remove_frame above.
6064   mov(rscratch1, real_frame_size - 2*wordSize);
6065   str(rscratch1, Address(sp, sp_inc_offset));
6066 }
6067 
6068 // This method counts leading positive bytes (highest bit not set) in provided byte array
6069 address MacroAssembler::count_positives(Register ary1, Register len, Register result) {
6070     // Simple and most common case of aligned small array which is not at the
6071     // end of memory page is placed here. All other cases are in stub.
6072     Label LOOP, END, STUB, STUB_LONG, SET_RESULT, DONE;
6073     const uint64_t UPPER_BIT_MASK=0x8080808080808080;
6074     assert_different_registers(ary1, len, result);
6075 
6076     mov(result, len);
6077     cmpw(len, 0);
6078     br(LE, DONE);
6079     cmpw(len, 4 * wordSize);
6080     br(GE, STUB_LONG); // size > 32 then go to stub
6081 
6082     int shift = 64 - exact_log2(os::vm_page_size());
6083     lsl(rscratch1, ary1, shift);
6084     mov(rscratch2, (size_t)(4 * wordSize) << shift);
6085     adds(rscratch2, rscratch1, rscratch2);  // At end of page?
6086     br(CS, STUB); // at the end of page then go to stub
6087     subs(len, len, wordSize);
6088     br(LT, END);
6089 
6090   BIND(LOOP);
6091     ldr(rscratch1, Address(post(ary1, wordSize)));
6092     tst(rscratch1, UPPER_BIT_MASK);
6093     br(NE, SET_RESULT);
6094     subs(len, len, wordSize);
6095     br(GE, LOOP);
6096     cmpw(len, -wordSize);
6097     br(EQ, DONE);
6098 
6099   BIND(END);
6100     ldr(rscratch1, Address(ary1));
6101     sub(rscratch2, zr, len, LSL, 3); // LSL 3 is to get bits from bytes
6102     lslv(rscratch1, rscratch1, rscratch2);
6103     tst(rscratch1, UPPER_BIT_MASK);
6104     br(NE, SET_RESULT);
6105     b(DONE);
6106 
6107   BIND(STUB);
6108     RuntimeAddress count_pos = RuntimeAddress(StubRoutines::aarch64::count_positives());
6109     assert(count_pos.target() != nullptr, "count_positives stub has not been generated");
6110     address tpc1 = trampoline_call(count_pos);
6111     if (tpc1 == nullptr) {
6112       DEBUG_ONLY(reset_labels(STUB_LONG, SET_RESULT, DONE));
6113       postcond(pc() == badAddress);
6114       return nullptr;
6115     }
6116     b(DONE);
6117 
6118   BIND(STUB_LONG);
6119     RuntimeAddress count_pos_long = RuntimeAddress(StubRoutines::aarch64::count_positives_long());
6120     assert(count_pos_long.target() != nullptr, "count_positives_long stub has not been generated");
6121     address tpc2 = trampoline_call(count_pos_long);
6122     if (tpc2 == nullptr) {
6123       DEBUG_ONLY(reset_labels(SET_RESULT, DONE));
6124       postcond(pc() == badAddress);
6125       return nullptr;
6126     }
6127     b(DONE);
6128 
6129   BIND(SET_RESULT);
6130 
6131     add(len, len, wordSize);
6132     sub(result, result, len);
6133 
6134   BIND(DONE);
6135   postcond(pc() != badAddress);
6136   return pc();
6137 }
6138 
6139 // Clobbers: rscratch1, rscratch2, rflags
6140 // May also clobber v0-v7 when (!UseSimpleArrayEquals && UseSIMDForArrayEquals)
6141 address MacroAssembler::arrays_equals(Register a1, Register a2, Register tmp3,
6142                                       Register tmp4, Register tmp5, Register result,
6143                                       Register cnt1, int elem_size) {
6144   Label DONE, SAME;
6145   Register tmp1 = rscratch1;
6146   Register tmp2 = rscratch2;
6147   int elem_per_word = wordSize/elem_size;
6148   int log_elem_size = exact_log2(elem_size);
6149   int klass_offset  = arrayOopDesc::klass_offset_in_bytes();
6150   int length_offset = arrayOopDesc::length_offset_in_bytes();
6151   int base_offset
6152     = arrayOopDesc::base_offset_in_bytes(elem_size == 2 ? T_CHAR : T_BYTE);
6153   // When the length offset is not aligned to 8 bytes,
6154   // then we align it down. This is valid because the new
6155   // offset will always be the klass which is the same
6156   // for type arrays.
6157   int start_offset = align_down(length_offset, BytesPerWord);
6158   int extra_length = base_offset - start_offset;
6159   assert(start_offset == length_offset || start_offset == klass_offset,
6160          "start offset must be 8-byte-aligned or be the klass offset");
6161   assert(base_offset != start_offset, "must include the length field");
6162   extra_length = extra_length / elem_size; // We count in elements, not bytes.
6163   int stubBytesThreshold = 3 * 64 + (UseSIMDForArrayEquals ? 0 : 16);
6164 
6165   assert(elem_size == 1 || elem_size == 2, "must be char or byte");
6166   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
6167 
6168 #ifndef PRODUCT
6169   {
6170     const char kind = (elem_size == 2) ? 'U' : 'L';
6171     char comment[64];
6172     os::snprintf_checked(comment, sizeof comment, "array_equals%c{", kind);
6173     BLOCK_COMMENT(comment);
6174   }
6175 #endif
6176 
6177   // if (a1 == a2)
6178   //     return true;
6179   cmpoop(a1, a2); // May have read barriers for a1 and a2.
6180   br(EQ, SAME);
6181 
6182   if (UseSimpleArrayEquals) {
6183     Label NEXT_WORD, SHORT, TAIL03, TAIL01, A_MIGHT_BE_NULL, A_IS_NOT_NULL;
6184     // if (a1 == nullptr || a2 == nullptr)
6185     //     return false;
6186     // a1 & a2 == 0 means (some-pointer is null) or
6187     // (very-rare-or-even-probably-impossible-pointer-values)
6188     // so, we can save one branch in most cases
6189     tst(a1, a2);
6190     mov(result, false);
6191     br(EQ, A_MIGHT_BE_NULL);
6192     // if (a1.length != a2.length)
6193     //      return false;
6194     bind(A_IS_NOT_NULL);
6195     ldrw(cnt1, Address(a1, length_offset));
6196     ldrw(tmp5, Address(a2, length_offset));
6197     cmp(cnt1, tmp5);
6198     br(NE, DONE); // If lengths differ, return false
6199     // Increase loop counter by diff between base- and actual start-offset.
6200     addw(cnt1, cnt1, extra_length);
6201     lea(a1, Address(a1, start_offset));
6202     lea(a2, Address(a2, start_offset));
6203     // Check for short strings, i.e. smaller than wordSize.
6204     subs(cnt1, cnt1, elem_per_word);
6205     br(Assembler::LT, SHORT);
6206     // Main 8 byte comparison loop.
6207     bind(NEXT_WORD); {
6208       ldr(tmp1, Address(post(a1, wordSize)));
6209       ldr(tmp2, Address(post(a2, wordSize)));
6210       subs(cnt1, cnt1, elem_per_word);
6211       eor(tmp5, tmp1, tmp2);
6212       cbnz(tmp5, DONE);
6213     } br(GT, NEXT_WORD);
6214     // Last longword.  In the case where length == 4 we compare the
6215     // same longword twice, but that's still faster than another
6216     // conditional branch.
6217     // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
6218     // length == 4.
6219     if (log_elem_size > 0)
6220       lsl(cnt1, cnt1, log_elem_size);
6221     ldr(tmp3, Address(a1, cnt1));
6222     ldr(tmp4, Address(a2, cnt1));
6223     eor(tmp5, tmp3, tmp4);
6224     cbnz(tmp5, DONE);
6225     b(SAME);
6226     bind(A_MIGHT_BE_NULL);
6227     // in case both a1 and a2 are not-null, proceed with loads
6228     cbz(a1, DONE);
6229     cbz(a2, DONE);
6230     b(A_IS_NOT_NULL);
6231     bind(SHORT);
6232 
6233     tbz(cnt1, 2 - log_elem_size, TAIL03); // 0-7 bytes left.
6234     {
6235       ldrw(tmp1, Address(post(a1, 4)));
6236       ldrw(tmp2, Address(post(a2, 4)));
6237       eorw(tmp5, tmp1, tmp2);
6238       cbnzw(tmp5, DONE);
6239     }
6240     bind(TAIL03);
6241     tbz(cnt1, 1 - log_elem_size, TAIL01); // 0-3 bytes left.
6242     {
6243       ldrh(tmp3, Address(post(a1, 2)));
6244       ldrh(tmp4, Address(post(a2, 2)));
6245       eorw(tmp5, tmp3, tmp4);
6246       cbnzw(tmp5, DONE);
6247     }
6248     bind(TAIL01);
6249     if (elem_size == 1) { // Only needed when comparing byte arrays.
6250       tbz(cnt1, 0, SAME); // 0-1 bytes left.
6251       {
6252         ldrb(tmp1, a1);
6253         ldrb(tmp2, a2);
6254         eorw(tmp5, tmp1, tmp2);
6255         cbnzw(tmp5, DONE);
6256       }
6257     }
6258   } else {
6259     Label NEXT_DWORD, SHORT, TAIL, TAIL2, STUB,
6260         CSET_EQ, LAST_CHECK;
6261     mov(result, false);
6262     cbz(a1, DONE);
6263     ldrw(cnt1, Address(a1, length_offset));
6264     cbz(a2, DONE);
6265     ldrw(tmp5, Address(a2, length_offset));
6266     cmp(cnt1, tmp5);
6267     br(NE, DONE); // If lengths differ, return false
6268     // Increase loop counter by diff between base- and actual start-offset.
6269     addw(cnt1, cnt1, extra_length);
6270 
6271     // on most CPUs a2 is still "locked"(surprisingly) in ldrw and it's
6272     // faster to perform another branch before comparing a1 and a2
6273     cmp(cnt1, (u1)elem_per_word);
6274     br(LE, SHORT); // short or same
6275     ldr(tmp3, Address(pre(a1, start_offset)));
6276     subs(zr, cnt1, stubBytesThreshold);
6277     br(GE, STUB);
6278     ldr(tmp4, Address(pre(a2, start_offset)));
6279     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
6280 
6281     // Main 16 byte comparison loop with 2 exits
6282     bind(NEXT_DWORD); {
6283       ldr(tmp1, Address(pre(a1, wordSize)));
6284       ldr(tmp2, Address(pre(a2, wordSize)));
6285       subs(cnt1, cnt1, 2 * elem_per_word);
6286       br(LE, TAIL);
6287       eor(tmp4, tmp3, tmp4);
6288       cbnz(tmp4, DONE);
6289       ldr(tmp3, Address(pre(a1, wordSize)));
6290       ldr(tmp4, Address(pre(a2, wordSize)));
6291       cmp(cnt1, (u1)elem_per_word);
6292       br(LE, TAIL2);
6293       cmp(tmp1, tmp2);
6294     } br(EQ, NEXT_DWORD);
6295     b(DONE);
6296 
6297     bind(TAIL);
6298     eor(tmp4, tmp3, tmp4);
6299     eor(tmp2, tmp1, tmp2);
6300     lslv(tmp2, tmp2, tmp5);
6301     orr(tmp5, tmp4, tmp2);
6302     cmp(tmp5, zr);
6303     b(CSET_EQ);
6304 
6305     bind(TAIL2);
6306     eor(tmp2, tmp1, tmp2);
6307     cbnz(tmp2, DONE);
6308     b(LAST_CHECK);
6309 
6310     bind(STUB);
6311     ldr(tmp4, Address(pre(a2, start_offset)));
6312     if (elem_size == 2) { // convert to byte counter
6313       lsl(cnt1, cnt1, 1);
6314     }
6315     eor(tmp5, tmp3, tmp4);
6316     cbnz(tmp5, DONE);
6317     RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_array_equals());
6318     assert(stub.target() != nullptr, "array_equals_long stub has not been generated");
6319     address tpc = trampoline_call(stub);
6320     if (tpc == nullptr) {
6321       DEBUG_ONLY(reset_labels(SHORT, LAST_CHECK, CSET_EQ, SAME, DONE));
6322       postcond(pc() == badAddress);
6323       return nullptr;
6324     }
6325     b(DONE);
6326 
6327     // (a1 != null && a2 == null) || (a1 != null && a2 != null && a1 == a2)
6328     // so, if a2 == null => return false(0), else return true, so we can return a2
6329     mov(result, a2);
6330     b(DONE);
6331     bind(SHORT);
6332     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
6333     ldr(tmp3, Address(a1, start_offset));
6334     ldr(tmp4, Address(a2, start_offset));
6335     bind(LAST_CHECK);
6336     eor(tmp4, tmp3, tmp4);
6337     lslv(tmp5, tmp4, tmp5);
6338     cmp(tmp5, zr);
6339     bind(CSET_EQ);
6340     cset(result, EQ);
6341     b(DONE);
6342   }
6343 
6344   bind(SAME);
6345   mov(result, true);
6346   // That's it.
6347   bind(DONE);
6348 
6349   BLOCK_COMMENT("} array_equals");
6350   postcond(pc() != badAddress);
6351   return pc();
6352 }
6353 
6354 // Compare Strings
6355 
6356 // For Strings we're passed the address of the first characters in a1
6357 // and a2 and the length in cnt1.
6358 // There are two implementations.  For arrays >= 8 bytes, all
6359 // comparisons (including the final one, which may overlap) are
6360 // performed 8 bytes at a time.  For strings < 8 bytes, we compare a
6361 // halfword, then a short, and then a byte.
6362 
6363 void MacroAssembler::string_equals(Register a1, Register a2,
6364                                    Register result, Register cnt1)
6365 {
6366   Label SAME, DONE, SHORT, NEXT_WORD;
6367   Register tmp1 = rscratch1;
6368   Register tmp2 = rscratch2;
6369 
6370   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
6371 
6372 #ifndef PRODUCT
6373   {
6374     char comment[64];
6375     os::snprintf_checked(comment, sizeof comment, "{string_equalsL");
6376     BLOCK_COMMENT(comment);
6377   }
6378 #endif
6379 
6380   mov(result, false);
6381 
6382   // Check for short strings, i.e. smaller than wordSize.
6383   subs(cnt1, cnt1, wordSize);
6384   br(Assembler::LT, SHORT);
6385   // Main 8 byte comparison loop.
6386   bind(NEXT_WORD); {
6387     ldr(tmp1, Address(post(a1, wordSize)));
6388     ldr(tmp2, Address(post(a2, wordSize)));
6389     subs(cnt1, cnt1, wordSize);
6390     eor(tmp1, tmp1, tmp2);
6391     cbnz(tmp1, DONE);
6392   } br(GT, NEXT_WORD);
6393   // Last longword.  In the case where length == 4 we compare the
6394   // same longword twice, but that's still faster than another
6395   // conditional branch.
6396   // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
6397   // length == 4.
6398   ldr(tmp1, Address(a1, cnt1));
6399   ldr(tmp2, Address(a2, cnt1));
6400   eor(tmp2, tmp1, tmp2);
6401   cbnz(tmp2, DONE);
6402   b(SAME);
6403 
6404   bind(SHORT);
6405   Label TAIL03, TAIL01;
6406 
6407   tbz(cnt1, 2, TAIL03); // 0-7 bytes left.
6408   {
6409     ldrw(tmp1, Address(post(a1, 4)));
6410     ldrw(tmp2, Address(post(a2, 4)));
6411     eorw(tmp1, tmp1, tmp2);
6412     cbnzw(tmp1, DONE);
6413   }
6414   bind(TAIL03);
6415   tbz(cnt1, 1, TAIL01); // 0-3 bytes left.
6416   {
6417     ldrh(tmp1, Address(post(a1, 2)));
6418     ldrh(tmp2, Address(post(a2, 2)));
6419     eorw(tmp1, tmp1, tmp2);
6420     cbnzw(tmp1, DONE);
6421   }
6422   bind(TAIL01);
6423   tbz(cnt1, 0, SAME); // 0-1 bytes left.
6424     {
6425     ldrb(tmp1, a1);
6426     ldrb(tmp2, a2);
6427     eorw(tmp1, tmp1, tmp2);
6428     cbnzw(tmp1, DONE);
6429   }
6430   // Arrays are equal.
6431   bind(SAME);
6432   mov(result, true);
6433 
6434   // That's it.
6435   bind(DONE);
6436   BLOCK_COMMENT("} string_equals");
6437 }
6438 
6439 
6440 // The size of the blocks erased by the zero_blocks stub.  We must
6441 // handle anything smaller than this ourselves in zero_words().
6442 const int MacroAssembler::zero_words_block_size = 8;
6443 
6444 // zero_words() is used by C2 ClearArray patterns and by
6445 // C1_MacroAssembler.  It is as small as possible, handling small word
6446 // counts locally and delegating anything larger to the zero_blocks
6447 // stub.  It is expanded many times in compiled code, so it is
6448 // important to keep it short.
6449 
6450 // ptr:   Address of a buffer to be zeroed.
6451 // cnt:   Count in HeapWords.
6452 //
6453 // ptr, cnt, rscratch1, and rscratch2 are clobbered.
6454 address MacroAssembler::zero_words(Register ptr, Register cnt)
6455 {
6456   assert(is_power_of_2(zero_words_block_size), "adjust this");
6457 
6458   BLOCK_COMMENT("zero_words {");
6459   assert(ptr == r10 && cnt == r11, "mismatch in register usage");
6460   RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
6461   assert(zero_blocks.target() != nullptr, "zero_blocks stub has not been generated");
6462 
6463   subs(rscratch1, cnt, zero_words_block_size);
6464   Label around;
6465   br(LO, around);
6466   {
6467     RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
6468     assert(zero_blocks.target() != nullptr, "zero_blocks stub has not been generated");
6469     // Make sure this is a C2 compilation. C1 allocates space only for
6470     // trampoline stubs generated by Call LIR ops, and in any case it
6471     // makes sense for a C1 compilation task to proceed as quickly as
6472     // possible.
6473     CompileTask* task;
6474     if (StubRoutines::aarch64::complete()
6475         && Thread::current()->is_Compiler_thread()
6476         && (task = ciEnv::current()->task())
6477         && is_c2_compile(task->comp_level())) {
6478       address tpc = trampoline_call(zero_blocks);
6479       if (tpc == nullptr) {
6480         DEBUG_ONLY(reset_labels(around));
6481         return nullptr;
6482       }
6483     } else {
6484       far_call(zero_blocks);
6485     }
6486   }
6487   bind(around);
6488 
6489   // We have a few words left to do. zero_blocks has adjusted r10 and r11
6490   // for us.
6491   for (int i = zero_words_block_size >> 1; i > 1; i >>= 1) {
6492     Label l;
6493     tbz(cnt, exact_log2(i), l);
6494     for (int j = 0; j < i; j += 2) {
6495       stp(zr, zr, post(ptr, 2 * BytesPerWord));
6496     }
6497     bind(l);
6498   }
6499   {
6500     Label l;
6501     tbz(cnt, 0, l);
6502     str(zr, Address(ptr));
6503     bind(l);
6504   }
6505 
6506   BLOCK_COMMENT("} zero_words");
6507   return pc();
6508 }
6509 
6510 // base:         Address of a buffer to be zeroed, 8 bytes aligned.
6511 // cnt:          Immediate count in HeapWords.
6512 //
6513 // r10, r11, rscratch1, and rscratch2 are clobbered.
6514 address MacroAssembler::zero_words(Register base, uint64_t cnt)
6515 {
6516   assert(wordSize <= BlockZeroingLowLimit,
6517             "increase BlockZeroingLowLimit");
6518   address result = nullptr;
6519   if (cnt <= (uint64_t)BlockZeroingLowLimit / BytesPerWord) {
6520 #ifndef PRODUCT
6521     {
6522       char buf[64];
6523       os::snprintf_checked(buf, sizeof buf, "zero_words (count = %" PRIu64 ") {", cnt);
6524       BLOCK_COMMENT(buf);
6525     }
6526 #endif
6527     if (cnt >= 16) {
6528       uint64_t loops = cnt/16;
6529       if (loops > 1) {
6530         mov(rscratch2, loops - 1);
6531       }
6532       {
6533         Label loop;
6534         bind(loop);
6535         for (int i = 0; i < 16; i += 2) {
6536           stp(zr, zr, Address(base, i * BytesPerWord));
6537         }
6538         add(base, base, 16 * BytesPerWord);
6539         if (loops > 1) {
6540           subs(rscratch2, rscratch2, 1);
6541           br(GE, loop);
6542         }
6543       }
6544     }
6545     cnt %= 16;
6546     int i = cnt & 1;  // store any odd word to start
6547     if (i) str(zr, Address(base));
6548     for (; i < (int)cnt; i += 2) {
6549       stp(zr, zr, Address(base, i * wordSize));
6550     }
6551     BLOCK_COMMENT("} zero_words");
6552     result = pc();
6553   } else {
6554     mov(r10, base); mov(r11, cnt);
6555     result = zero_words(r10, r11);
6556   }
6557   return result;
6558 }
6559 
6560 // Zero blocks of memory by using DC ZVA.
6561 //
6562 // Aligns the base address first sufficiently for DC ZVA, then uses
6563 // DC ZVA repeatedly for every full block.  cnt is the size to be
6564 // zeroed in HeapWords.  Returns the count of words left to be zeroed
6565 // in cnt.
6566 //
6567 // NOTE: This is intended to be used in the zero_blocks() stub.  If
6568 // you want to use it elsewhere, note that cnt must be >= 2*zva_length.
6569 void MacroAssembler::zero_dcache_blocks(Register base, Register cnt) {
6570   Register tmp = rscratch1;
6571   Register tmp2 = rscratch2;
6572   int zva_length = VM_Version::zva_length();
6573   Label initial_table_end, loop_zva;
6574   Label fini;
6575 
6576   // Base must be 16 byte aligned. If not just return and let caller handle it
6577   tst(base, 0x0f);
6578   br(Assembler::NE, fini);
6579   // Align base with ZVA length.
6580   neg(tmp, base);
6581   andr(tmp, tmp, zva_length - 1);
6582 
6583   // tmp: the number of bytes to be filled to align the base with ZVA length.
6584   add(base, base, tmp);
6585   sub(cnt, cnt, tmp, Assembler::ASR, 3);
6586   adr(tmp2, initial_table_end);
6587   sub(tmp2, tmp2, tmp, Assembler::LSR, 2);
6588   br(tmp2);
6589 
6590   for (int i = -zva_length + 16; i < 0; i += 16)
6591     stp(zr, zr, Address(base, i));
6592   bind(initial_table_end);
6593 
6594   sub(cnt, cnt, zva_length >> 3);
6595   bind(loop_zva);
6596   dc(Assembler::ZVA, base);
6597   subs(cnt, cnt, zva_length >> 3);
6598   add(base, base, zva_length);
6599   br(Assembler::GE, loop_zva);
6600   add(cnt, cnt, zva_length >> 3); // count not zeroed by DC ZVA
6601   bind(fini);
6602 }
6603 
6604 // base:   Address of a buffer to be filled, 8 bytes aligned.
6605 // cnt:    Count in 8-byte unit.
6606 // value:  Value to be filled with.
6607 // base will point to the end of the buffer after filling.
6608 void MacroAssembler::fill_words(Register base, Register cnt, Register value)
6609 {
6610 //  Algorithm:
6611 //
6612 //    if (cnt == 0) {
6613 //      return;
6614 //    }
6615 //    if ((p & 8) != 0) {
6616 //      *p++ = v;
6617 //    }
6618 //
6619 //    scratch1 = cnt & 14;
6620 //    cnt -= scratch1;
6621 //    p += scratch1;
6622 //    switch (scratch1 / 2) {
6623 //      do {
6624 //        cnt -= 16;
6625 //          p[-16] = v;
6626 //          p[-15] = v;
6627 //        case 7:
6628 //          p[-14] = v;
6629 //          p[-13] = v;
6630 //        case 6:
6631 //          p[-12] = v;
6632 //          p[-11] = v;
6633 //          // ...
6634 //        case 1:
6635 //          p[-2] = v;
6636 //          p[-1] = v;
6637 //        case 0:
6638 //          p += 16;
6639 //      } while (cnt);
6640 //    }
6641 //    if ((cnt & 1) == 1) {
6642 //      *p++ = v;
6643 //    }
6644 
6645   assert_different_registers(base, cnt, value, rscratch1, rscratch2);
6646 
6647   Label fini, skip, entry, loop;
6648   const int unroll = 8; // Number of stp instructions we'll unroll
6649 
6650   cbz(cnt, fini);
6651   tbz(base, 3, skip);
6652   str(value, Address(post(base, 8)));
6653   sub(cnt, cnt, 1);
6654   bind(skip);
6655 
6656   andr(rscratch1, cnt, (unroll-1) * 2);
6657   sub(cnt, cnt, rscratch1);
6658   add(base, base, rscratch1, Assembler::LSL, 3);
6659   adr(rscratch2, entry);
6660   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 1);
6661   br(rscratch2);
6662 
6663   bind(loop);
6664   add(base, base, unroll * 16);
6665   for (int i = -unroll; i < 0; i++)
6666     stp(value, value, Address(base, i * 16));
6667   bind(entry);
6668   subs(cnt, cnt, unroll * 2);
6669   br(Assembler::GE, loop);
6670 
6671   tbz(cnt, 0, fini);
6672   str(value, Address(post(base, 8)));
6673   bind(fini);
6674 }
6675 
6676 // Intrinsic for
6677 //
6678 // - sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6679 //   Encodes char[] to byte[] in ISO-8859-1
6680 //
6681 // - java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6682 //   Encodes byte[] (containing UTF-16) to byte[] in ISO-8859-1
6683 //
6684 // - java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6685 //   Encodes char[] to byte[] in ASCII
6686 //
6687 // This version always returns the number of characters copied, and does not
6688 // clobber the 'len' register. A successful copy will complete with the post-
6689 // condition: 'res' == 'len', while an unsuccessful copy will exit with the
6690 // post-condition: 0 <= 'res' < 'len'.
6691 //
6692 // NOTE: Attempts to use 'ld2' (and 'umaxv' in the ISO part) has proven to
6693 //       degrade performance (on Ampere Altra - Neoverse N1), to an extent
6694 //       beyond the acceptable, even though the footprint would be smaller.
6695 //       Using 'umaxv' in the ASCII-case comes with a small penalty but does
6696 //       avoid additional bloat.
6697 //
6698 // Clobbers: src, dst, res, rscratch1, rscratch2, rflags
6699 void MacroAssembler::encode_iso_array(Register src, Register dst,
6700                                       Register len, Register res, bool ascii,
6701                                       FloatRegister vtmp0, FloatRegister vtmp1,
6702                                       FloatRegister vtmp2, FloatRegister vtmp3,
6703                                       FloatRegister vtmp4, FloatRegister vtmp5)
6704 {
6705   Register cnt = res;
6706   Register max = rscratch1;
6707   Register chk = rscratch2;
6708 
6709   prfm(Address(src), PLDL1STRM);
6710   movw(cnt, len);
6711 
6712 #define ASCII(insn) do { if (ascii) { insn; } } while (0)
6713 
6714   Label LOOP_32, DONE_32, FAIL_32;
6715 
6716   BIND(LOOP_32);
6717   {
6718     cmpw(cnt, 32);
6719     br(LT, DONE_32);
6720     ld1(vtmp0, vtmp1, vtmp2, vtmp3, T8H, Address(post(src, 64)));
6721     // Extract lower bytes.
6722     FloatRegister vlo0 = vtmp4;
6723     FloatRegister vlo1 = vtmp5;
6724     uzp1(vlo0, T16B, vtmp0, vtmp1);
6725     uzp1(vlo1, T16B, vtmp2, vtmp3);
6726     // Merge bits...
6727     orr(vtmp0, T16B, vtmp0, vtmp1);
6728     orr(vtmp2, T16B, vtmp2, vtmp3);
6729     // Extract merged upper bytes.
6730     FloatRegister vhix = vtmp0;
6731     uzp2(vhix, T16B, vtmp0, vtmp2);
6732     // ISO-check on hi-parts (all zero).
6733     //                          ASCII-check on lo-parts (no sign).
6734     FloatRegister vlox = vtmp1; // Merge lower bytes.
6735                                 ASCII(orr(vlox, T16B, vlo0, vlo1));
6736     umov(chk, vhix, D, 1);      ASCII(cm(LT, vlox, T16B, vlox));
6737     fmovd(max, vhix);           ASCII(umaxv(vlox, T16B, vlox));
6738     orr(chk, chk, max);         ASCII(umov(max, vlox, B, 0));
6739                                 ASCII(orr(chk, chk, max));
6740     cbnz(chk, FAIL_32);
6741     subw(cnt, cnt, 32);
6742     st1(vlo0, vlo1, T16B, Address(post(dst, 32)));
6743     b(LOOP_32);
6744   }
6745   BIND(FAIL_32);
6746   sub(src, src, 64);
6747   BIND(DONE_32);
6748 
6749   Label LOOP_8, SKIP_8;
6750 
6751   BIND(LOOP_8);
6752   {
6753     cmpw(cnt, 8);
6754     br(LT, SKIP_8);
6755     FloatRegister vhi = vtmp0;
6756     FloatRegister vlo = vtmp1;
6757     ld1(vtmp3, T8H, src);
6758     uzp1(vlo, T16B, vtmp3, vtmp3);
6759     uzp2(vhi, T16B, vtmp3, vtmp3);
6760     // ISO-check on hi-parts (all zero).
6761     //                          ASCII-check on lo-parts (no sign).
6762                                 ASCII(cm(LT, vtmp2, T16B, vlo));
6763     fmovd(chk, vhi);            ASCII(umaxv(vtmp2, T16B, vtmp2));
6764                                 ASCII(umov(max, vtmp2, B, 0));
6765                                 ASCII(orr(chk, chk, max));
6766     cbnz(chk, SKIP_8);
6767 
6768     strd(vlo, Address(post(dst, 8)));
6769     subw(cnt, cnt, 8);
6770     add(src, src, 16);
6771     b(LOOP_8);
6772   }
6773   BIND(SKIP_8);
6774 
6775 #undef ASCII
6776 
6777   Label LOOP, DONE;
6778 
6779   cbz(cnt, DONE);
6780   BIND(LOOP);
6781   {
6782     Register chr = rscratch1;
6783     ldrh(chr, Address(post(src, 2)));
6784     tst(chr, ascii ? 0xff80 : 0xff00);
6785     br(NE, DONE);
6786     strb(chr, Address(post(dst, 1)));
6787     subs(cnt, cnt, 1);
6788     br(GT, LOOP);
6789   }
6790   BIND(DONE);
6791   // Return index where we stopped.
6792   subw(res, len, cnt);
6793 }
6794 
6795 // Inflate byte[] array to char[].
6796 // Clobbers: src, dst, len, rflags, rscratch1, v0-v6
6797 address MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
6798                                            FloatRegister vtmp1, FloatRegister vtmp2,
6799                                            FloatRegister vtmp3, Register tmp4) {
6800   Label big, done, after_init, to_stub;
6801 
6802   assert_different_registers(src, dst, len, tmp4, rscratch1);
6803 
6804   fmovd(vtmp1, 0.0);
6805   lsrw(tmp4, len, 3);
6806   bind(after_init);
6807   cbnzw(tmp4, big);
6808   // Short string: less than 8 bytes.
6809   {
6810     Label loop, tiny;
6811 
6812     cmpw(len, 4);
6813     br(LT, tiny);
6814     // Use SIMD to do 4 bytes.
6815     ldrs(vtmp2, post(src, 4));
6816     zip1(vtmp3, T8B, vtmp2, vtmp1);
6817     subw(len, len, 4);
6818     strd(vtmp3, post(dst, 8));
6819 
6820     cbzw(len, done);
6821 
6822     // Do the remaining bytes by steam.
6823     bind(loop);
6824     ldrb(tmp4, post(src, 1));
6825     strh(tmp4, post(dst, 2));
6826     subw(len, len, 1);
6827 
6828     bind(tiny);
6829     cbnz(len, loop);
6830 
6831     b(done);
6832   }
6833 
6834   if (SoftwarePrefetchHintDistance >= 0) {
6835     bind(to_stub);
6836       RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_byte_array_inflate());
6837       assert(stub.target() != nullptr, "large_byte_array_inflate stub has not been generated");
6838       address tpc = trampoline_call(stub);
6839       if (tpc == nullptr) {
6840         DEBUG_ONLY(reset_labels(big, done));
6841         postcond(pc() == badAddress);
6842         return nullptr;
6843       }
6844       b(after_init);
6845   }
6846 
6847   // Unpack the bytes 8 at a time.
6848   bind(big);
6849   {
6850     Label loop, around, loop_last, loop_start;
6851 
6852     if (SoftwarePrefetchHintDistance >= 0) {
6853       const int large_loop_threshold = (64 + 16)/8;
6854       ldrd(vtmp2, post(src, 8));
6855       andw(len, len, 7);
6856       cmp(tmp4, (u1)large_loop_threshold);
6857       br(GE, to_stub);
6858       b(loop_start);
6859 
6860       bind(loop);
6861       ldrd(vtmp2, post(src, 8));
6862       bind(loop_start);
6863       subs(tmp4, tmp4, 1);
6864       br(EQ, loop_last);
6865       zip1(vtmp2, T16B, vtmp2, vtmp1);
6866       ldrd(vtmp3, post(src, 8));
6867       st1(vtmp2, T8H, post(dst, 16));
6868       subs(tmp4, tmp4, 1);
6869       zip1(vtmp3, T16B, vtmp3, vtmp1);
6870       st1(vtmp3, T8H, post(dst, 16));
6871       br(NE, loop);
6872       b(around);
6873       bind(loop_last);
6874       zip1(vtmp2, T16B, vtmp2, vtmp1);
6875       st1(vtmp2, T8H, post(dst, 16));
6876       bind(around);
6877       cbz(len, done);
6878     } else {
6879       andw(len, len, 7);
6880       bind(loop);
6881       ldrd(vtmp2, post(src, 8));
6882       sub(tmp4, tmp4, 1);
6883       zip1(vtmp3, T16B, vtmp2, vtmp1);
6884       st1(vtmp3, T8H, post(dst, 16));
6885       cbnz(tmp4, loop);
6886     }
6887   }
6888 
6889   // Do the tail of up to 8 bytes.
6890   add(src, src, len);
6891   ldrd(vtmp3, Address(src, -8));
6892   add(dst, dst, len, ext::uxtw, 1);
6893   zip1(vtmp3, T16B, vtmp3, vtmp1);
6894   strq(vtmp3, Address(dst, -16));
6895 
6896   bind(done);
6897   postcond(pc() != badAddress);
6898   return pc();
6899 }
6900 
6901 // Compress char[] array to byte[].
6902 // Intrinsic for java.lang.StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
6903 // Return the array length if every element in array can be encoded,
6904 // otherwise, the index of first non-latin1 (> 0xff) character.
6905 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
6906                                          Register res,
6907                                          FloatRegister tmp0, FloatRegister tmp1,
6908                                          FloatRegister tmp2, FloatRegister tmp3,
6909                                          FloatRegister tmp4, FloatRegister tmp5) {
6910   encode_iso_array(src, dst, len, res, false, tmp0, tmp1, tmp2, tmp3, tmp4, tmp5);
6911 }
6912 
6913 // java.math.round(double a)
6914 // Returns the closest long to the argument, with ties rounding to
6915 // positive infinity.  This requires some fiddling for corner
6916 // cases. We take care to avoid double rounding in e.g. (jlong)(a + 0.5).
6917 void MacroAssembler::java_round_double(Register dst, FloatRegister src,
6918                                        FloatRegister ftmp) {
6919   Label DONE;
6920   BLOCK_COMMENT("java_round_double: { ");
6921   fmovd(rscratch1, src);
6922   // Use RoundToNearestTiesAway unless src small and -ve.
6923   fcvtasd(dst, src);
6924   // Test if src >= 0 || abs(src) >= 0x1.0p52
6925   eor(rscratch1, rscratch1, UCONST64(1) << 63); // flip sign bit
6926   mov(rscratch2, julong_cast(0x1.0p52));
6927   cmp(rscratch1, rscratch2);
6928   br(HS, DONE); {
6929     // src < 0 && abs(src) < 0x1.0p52
6930     // src may have a fractional part, so add 0.5
6931     fmovd(ftmp, 0.5);
6932     faddd(ftmp, src, ftmp);
6933     // Convert double to jlong, use RoundTowardsNegative
6934     fcvtmsd(dst, ftmp);
6935   }
6936   bind(DONE);
6937   BLOCK_COMMENT("} java_round_double");
6938 }
6939 
6940 void MacroAssembler::java_round_float(Register dst, FloatRegister src,
6941                                       FloatRegister ftmp) {
6942   Label DONE;
6943   BLOCK_COMMENT("java_round_float: { ");
6944   fmovs(rscratch1, src);
6945   // Use RoundToNearestTiesAway unless src small and -ve.
6946   fcvtassw(dst, src);
6947   // Test if src >= 0 || abs(src) >= 0x1.0p23
6948   eor(rscratch1, rscratch1, 0x80000000); // flip sign bit
6949   mov(rscratch2, jint_cast(0x1.0p23f));
6950   cmp(rscratch1, rscratch2);
6951   br(HS, DONE); {
6952     // src < 0 && |src| < 0x1.0p23
6953     // src may have a fractional part, so add 0.5
6954     fmovs(ftmp, 0.5f);
6955     fadds(ftmp, src, ftmp);
6956     // Convert float to jint, use RoundTowardsNegative
6957     fcvtmssw(dst, ftmp);
6958   }
6959   bind(DONE);
6960   BLOCK_COMMENT("} java_round_float");
6961 }
6962 
6963 // get_thread() can be called anywhere inside generated code so we
6964 // need to save whatever non-callee save context might get clobbered
6965 // by the call to JavaThread::aarch64_get_thread_helper() or, indeed,
6966 // the call setup code.
6967 //
6968 // On Linux and Windows, aarch64_get_thread_helper() is implemented in
6969 // assembly and clobbers only r0, r1, and flags.
6970 // On other systems, the helper is a usual C function.
6971 //
6972 void MacroAssembler::get_thread(Register dst) {
6973   RegSet saved_regs =
6974     BSD_ONLY(RegSet::range(r0, r17) + lr - dst)
6975     NOT_BSD (RegSet::range(r0, r1)  + lr - dst);
6976 
6977   protect_return_address();
6978   push(saved_regs, sp);
6979 
6980   mov(lr, ExternalAddress(CAST_FROM_FN_PTR(address, JavaThread::aarch64_get_thread_helper)));
6981   blr(lr);
6982   if (dst != c_rarg0) {
6983     mov(dst, c_rarg0);
6984   }
6985 
6986   pop(saved_regs, sp);
6987   authenticate_return_address();
6988 }
6989 
6990 #ifdef COMPILER2
6991 // C2 compiled method's prolog code
6992 // Moved here from aarch64.ad to support Valhalla code below
6993 void MacroAssembler::verified_entry(Compile* C, int sp_inc) {
6994   if (C->clinit_barrier_on_entry()) {
6995     assert(!C->method()->holder()->is_not_initialized(), "initialization should have been started");
6996 
6997     Label L_skip_barrier;
6998 
6999     mov_metadata(rscratch2, C->method()->holder()->constant_encoding());
7000     clinit_barrier(rscratch2, rscratch1, &L_skip_barrier);
7001     far_jump(RuntimeAddress(SharedRuntime::get_handle_wrong_method_stub()));
7002     bind(L_skip_barrier);
7003   }
7004 
7005   if (C->max_vector_size() > 0) {
7006     reinitialize_ptrue();
7007   }
7008 
7009   int bangsize = C->output()->bang_size_in_bytes();
7010   if (C->output()->need_stack_bang(bangsize))
7011     generate_stack_overflow_check(bangsize);
7012 
7013   // n.b. frame size includes space for return pc and rfp
7014   const long framesize = C->output()->frame_size_in_bytes();
7015   build_frame(framesize DEBUG_ONLY(COMMA sp_inc != 0));
7016 
7017   if (C->needs_stack_repair()) {
7018     save_stack_increment(sp_inc, framesize);
7019   }
7020 
7021   if (VerifyStackAtCalls) {
7022     Unimplemented();
7023   }
7024 }
7025 #endif // COMPILER2
7026 
7027 int MacroAssembler::store_inline_type_fields_to_buf(ciInlineKlass* vk, bool from_interpreter) {
7028   assert(InlineTypeReturnedAsFields, "Inline types should never be returned as fields");
7029   // An inline type might be returned. If fields are in registers we
7030   // need to allocate an inline type instance and initialize it with
7031   // the value of the fields.
7032   Label skip;
7033   // We only need a new buffered inline type if a new one is not returned
7034   tbz(r0, 0, skip);
7035   int call_offset = -1;
7036 
7037   // Be careful not to clobber r1-7 which hold returned fields
7038   // Also do not use callee-saved registers as these may be live in the interpreter
7039   Register tmp1 = r13, tmp2 = r14, klass = r15, r0_preserved = r12;
7040 
7041   // The following code is similar to the instance allocation code in TemplateTable::_new
7042   //  but has some slight differences,
7043   // e.g. object size is always not zero, sometimes it's constant; storing klass ptr after
7044   // allocating is not necessary if vk != nullptr, etc.
7045   Label slow_case;
7046   // 1. Try to allocate a new buffered inline instance either from TLAB or eden space
7047   mov(r0_preserved, r0); // save r0 for slow_case since *_allocate may corrupt it when allocation failed
7048 
7049   if (vk != nullptr) {
7050     // Called from C1, where the return type is statically known.
7051     movptr(klass, (intptr_t)vk->get_InlineKlass());
7052     jint lh = vk->layout_helper();
7053     assert(lh != Klass::_lh_neutral_value, "inline class in return type must have been resolved");
7054     if (UseTLAB && !Klass::layout_helper_needs_slow_path(lh)) {
7055       tlab_allocate(r0, noreg, lh, tmp1, tmp2, slow_case);
7056     } else {
7057       b(slow_case);
7058     }
7059   } else {
7060     // Call from interpreter. R0 contains ((the InlineKlass* of the return type) | 0x01)
7061     andr(klass, r0, -2);
7062     if (UseTLAB) {
7063       ldrw(tmp2, Address(klass, Klass::layout_helper_offset()));
7064       tst(tmp2, Klass::_lh_instance_slow_path_bit);
7065       br(Assembler::NE, slow_case);
7066       tlab_allocate(r0, tmp2, 0, tmp1, tmp2, slow_case);
7067     } else {
7068       b(slow_case);
7069     }
7070   }
7071   if (UseTLAB) {
7072     // 2. Initialize buffered inline instance header
7073     Register buffer_obj = r0;
7074     if (UseCompactObjectHeaders) {
7075       ldr(rscratch1, Address(klass, Klass::prototype_header_offset()));
7076       str(rscratch1, Address(buffer_obj, oopDesc::mark_offset_in_bytes()));
7077     } else {
7078       mov(rscratch1, (intptr_t)markWord::inline_type_prototype().value());
7079       str(rscratch1, Address(buffer_obj, oopDesc::mark_offset_in_bytes()));
7080       store_klass_gap(buffer_obj, zr);
7081       if (vk == nullptr) {
7082         // store_klass corrupts klass, so save it for later use (interpreter case only).
7083         mov(tmp1, klass);
7084       }
7085       store_klass(buffer_obj, klass);
7086       klass = tmp1;
7087     }
7088     // 3. Initialize its fields with an inline class specific handler
7089     if (vk != nullptr) {
7090       far_call(RuntimeAddress(vk->pack_handler())); // no need for call info as this will not safepoint.
7091     } else {
7092       ldr(tmp1, Address(klass, InlineKlass::adr_members_offset()));
7093       ldr(tmp1, Address(tmp1, InlineKlass::pack_handler_offset()));
7094       blr(tmp1);
7095     }
7096 
7097     membar(Assembler::StoreStore);
7098     b(skip);
7099   } else {
7100     // Must have already branched to slow_case above.
7101     DEBUG_ONLY(should_not_reach_here());
7102   }
7103   bind(slow_case);
7104   // We failed to allocate a new inline type, fall back to a runtime
7105   // call. Some oop field may be live in some registers but we can't
7106   // tell. That runtime call will take care of preserving them
7107   // across a GC if there's one.
7108   mov(r0, r0_preserved);
7109 
7110   if (from_interpreter) {
7111     super_call_VM_leaf(StubRoutines::store_inline_type_fields_to_buf());
7112   } else {
7113     far_call(RuntimeAddress(StubRoutines::store_inline_type_fields_to_buf()));
7114     call_offset = offset();
7115   }
7116   membar(Assembler::StoreStore);
7117 
7118   bind(skip);
7119   return call_offset;
7120 }
7121 
7122 // Move a value between registers/stack slots and update the reg_state
7123 bool MacroAssembler::move_helper(VMReg from, VMReg to, BasicType bt, RegState reg_state[]) {
7124   assert(from->is_valid() && to->is_valid(), "source and destination must be valid");
7125   if (reg_state[to->value()] == reg_written) {
7126     return true; // Already written
7127   }
7128 
7129   if (from != to && bt != T_VOID) {
7130     if (reg_state[to->value()] == reg_readonly) {
7131       return false; // Not yet writable
7132     }
7133     if (from->is_reg()) {
7134       if (to->is_reg()) {
7135         if (from->is_Register() && to->is_Register()) {
7136           mov(to->as_Register(), from->as_Register());
7137         } else if (from->is_FloatRegister() && to->is_FloatRegister()) {
7138           fmovd(to->as_FloatRegister(), from->as_FloatRegister());
7139         } else {
7140           ShouldNotReachHere();
7141         }
7142       } else {
7143         int st_off = to->reg2stack() * VMRegImpl::stack_slot_size;
7144         Address to_addr = Address(sp, st_off);
7145         if (from->is_FloatRegister()) {
7146           if (bt == T_DOUBLE) {
7147              strd(from->as_FloatRegister(), to_addr);
7148           } else {
7149              assert(bt == T_FLOAT, "must be float");
7150              strs(from->as_FloatRegister(), to_addr);
7151           }
7152         } else {
7153           str(from->as_Register(), to_addr);
7154         }
7155       }
7156     } else {
7157       Address from_addr = Address(sp, from->reg2stack() * VMRegImpl::stack_slot_size);
7158       if (to->is_reg()) {
7159         if (to->is_FloatRegister()) {
7160           if (bt == T_DOUBLE) {
7161             ldrd(to->as_FloatRegister(), from_addr);
7162           } else {
7163             assert(bt == T_FLOAT, "must be float");
7164             ldrs(to->as_FloatRegister(), from_addr);
7165           }
7166         } else {
7167           ldr(to->as_Register(), from_addr);
7168         }
7169       } else {
7170         int st_off = to->reg2stack() * VMRegImpl::stack_slot_size;
7171         ldr(rscratch1, from_addr);
7172         str(rscratch1, Address(sp, st_off));
7173       }
7174     }
7175   }
7176 
7177   // Update register states
7178   reg_state[from->value()] = reg_writable;
7179   reg_state[to->value()] = reg_written;
7180   return true;
7181 }
7182 
7183 // Calculate the extra stack space required for packing or unpacking inline
7184 // args and adjust the stack pointer
7185 int MacroAssembler::extend_stack_for_inline_args(int args_on_stack) {
7186   int sp_inc = args_on_stack * VMRegImpl::stack_slot_size;
7187   sp_inc = align_up(sp_inc, StackAlignmentInBytes);
7188   assert(sp_inc > 0, "sanity");
7189 
7190   // Save a copy of the FP and LR here for deoptimization patching and frame walking
7191   stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
7192 
7193   // Adjust the stack pointer. This will be repaired on return by MacroAssembler::remove_frame
7194   if (sp_inc < (1 << 9)) {
7195     sub(sp, sp, sp_inc);   // Fits in an immediate
7196   } else {
7197     mov(rscratch1, sp_inc);
7198     sub(sp, sp, rscratch1);
7199   }
7200 
7201   return sp_inc + 2 * wordSize;  // Account for the FP/LR space
7202 }
7203 
7204 // Read all fields from an inline type oop and store the values in registers/stack slots
7205 bool MacroAssembler::unpack_inline_helper(const GrowableArray<SigEntry>* sig, int& sig_index,
7206                                           VMReg from, int& from_index, VMRegPair* to, int to_count, int& to_index,
7207                                           RegState reg_state[]) {
7208   assert(sig->at(sig_index)._bt == T_VOID, "should be at end delimiter");
7209   assert(from->is_valid(), "source must be valid");
7210   bool progress = false;
7211 #ifdef ASSERT
7212   const int start_offset = offset();
7213 #endif
7214 
7215   Label L_null, L_notNull;
7216   // Don't use r14 as tmp because it's used for spilling (see MacroAssembler::spill_reg_for)
7217   Register tmp1 = r10;
7218   Register tmp2 = r11;
7219 
7220 #ifdef ASSERT
7221   RegSet clobbered_gp_regs = MacroAssembler::call_clobbered_gp_registers();
7222   assert(clobbered_gp_regs.contains(tmp1), "tmp1 must be saved explicitly if it's not a clobber");
7223   assert(clobbered_gp_regs.contains(tmp2), "tmp2 must be saved explicitly if it's not a clobber");
7224   assert(clobbered_gp_regs.contains(r14), "r14 must be saved explicitly if it's not a clobber");
7225 #endif
7226 
7227   Register fromReg = noreg;
7228   ScalarizedInlineArgsStream stream(sig, sig_index, to, to_count, to_index, true);
7229   bool done = true;
7230   bool mark_done = true;
7231   VMReg toReg;
7232   BasicType bt;
7233   // Check if argument requires a null check
7234   bool null_check = false;
7235   VMReg nullCheckReg;
7236   while (stream.next(nullCheckReg, bt)) {
7237     if (sig->at(stream.sig_index())._offset == -1) {
7238       null_check = true;
7239       break;
7240     }
7241   }
7242   stream.reset(sig_index, to_index);
7243   while (stream.next(toReg, bt)) {
7244     assert(toReg->is_valid(), "destination must be valid");
7245     int idx = (int)toReg->value();
7246     if (reg_state[idx] == reg_readonly) {
7247       if (idx != from->value()) {
7248         mark_done = false;
7249       }
7250       done = false;
7251       continue;
7252     } else if (reg_state[idx] == reg_written) {
7253       continue;
7254     }
7255     assert(reg_state[idx] == reg_writable, "must be writable");
7256     reg_state[idx] = reg_written;
7257     progress = true;
7258 
7259     if (fromReg == noreg) {
7260       if (from->is_reg()) {
7261         fromReg = from->as_Register();
7262       } else {
7263         int st_off = from->reg2stack() * VMRegImpl::stack_slot_size;
7264         ldr(tmp1, Address(sp, st_off));
7265         fromReg = tmp1;
7266       }
7267       if (null_check) {
7268         // Nullable inline type argument, emit null check
7269         cbz(fromReg, L_null);
7270       }
7271     }
7272     int off = sig->at(stream.sig_index())._offset;
7273     if (off == -1) {
7274       assert(null_check, "Missing null check at");
7275       if (toReg->is_stack()) {
7276         int st_off = toReg->reg2stack() * VMRegImpl::stack_slot_size;
7277         mov(tmp2, 1);
7278         str(tmp2, Address(sp, st_off));
7279       } else {
7280         mov(toReg->as_Register(), 1);
7281       }
7282       continue;
7283     }
7284     if (sig->at(stream.sig_index())._vt_oop) {
7285       if (toReg->is_stack()) {
7286         int st_off = toReg->reg2stack() * VMRegImpl::stack_slot_size;
7287         str(fromReg, Address(sp, st_off));
7288       } else {
7289         mov(toReg->as_Register(), fromReg);
7290       }
7291       continue;
7292     }
7293     assert(off > 0, "offset in object should be positive");
7294     Address fromAddr = Address(fromReg, off);
7295     if (!toReg->is_FloatRegister()) {
7296       Register dst = toReg->is_stack() ? tmp2 : toReg->as_Register();
7297       if (is_reference_type(bt)) {
7298         load_heap_oop(dst, fromAddr, rscratch1, rscratch2);
7299       } else {
7300         bool is_signed = (bt != T_CHAR) && (bt != T_BOOLEAN);
7301         load_sized_value(dst, fromAddr, type2aelembytes(bt), is_signed);
7302       }
7303       if (toReg->is_stack()) {
7304         int st_off = toReg->reg2stack() * VMRegImpl::stack_slot_size;
7305         str(dst, Address(sp, st_off));
7306       }
7307     } else if (bt == T_DOUBLE) {
7308       ldrd(toReg->as_FloatRegister(), fromAddr);
7309     } else {
7310       assert(bt == T_FLOAT, "must be float");
7311       ldrs(toReg->as_FloatRegister(), fromAddr);
7312     }
7313   }
7314   if (progress && null_check) {
7315     if (done) {
7316       b(L_notNull);
7317       bind(L_null);
7318       // Set null marker to zero to signal that the argument is null.
7319       // Also set all fields to zero since the runtime requires a canonical
7320       // representation of a flat null.
7321       stream.reset(sig_index, to_index);
7322       while (stream.next(toReg, bt)) {
7323         if (toReg->is_stack()) {
7324           int st_off = toReg->reg2stack() * VMRegImpl::stack_slot_size;
7325           str(zr, Address(sp, st_off));
7326         } else if (toReg->is_FloatRegister()) {
7327           mov(toReg->as_FloatRegister(), T2S, 0);
7328         } else {
7329           mov(toReg->as_Register(), zr);
7330         }
7331       }
7332       bind(L_notNull);
7333     } else {
7334       bind(L_null);
7335     }
7336   }
7337 
7338   sig_index = stream.sig_index();
7339   to_index = stream.regs_index();
7340 
7341   if (mark_done && reg_state[from->value()] != reg_written) {
7342     // This is okay because no one else will write to that slot
7343     reg_state[from->value()] = reg_writable;
7344   }
7345   from_index--;
7346   assert(progress || (start_offset == offset()), "should not emit code");
7347   return done;
7348 }
7349 
7350 // Pack fields back into an inline type oop
7351 bool MacroAssembler::pack_inline_helper(const GrowableArray<SigEntry>* sig, int& sig_index, int vtarg_index,
7352                                         VMRegPair* from, int from_count, int& from_index, VMReg to,
7353                                         RegState reg_state[], Register val_array) {
7354   assert(sig->at(sig_index)._bt == T_METADATA, "should be at delimiter");
7355   assert(to->is_valid(), "destination must be valid");
7356 
7357   if (reg_state[to->value()] == reg_written) {
7358     skip_unpacked_fields(sig, sig_index, from, from_count, from_index);
7359     return true; // Already written
7360   }
7361 
7362   // The GC barrier expanded by store_heap_oop below may call into the
7363   // runtime so use callee-saved registers for any values that need to be
7364   // preserved. The GC barrier assembler should take care of saving the
7365   // Java argument registers.
7366   // Be careful with r14 because it's used for spilling (see MacroAssembler::spill_reg_for).
7367   Register val_obj_tmp = r21;
7368   Register from_reg_tmp = r22;
7369   Register tmp1 = r14;
7370   Register tmp2 = r13;
7371   Register tmp3 = r12;
7372   Register val_obj = to->is_stack() ? val_obj_tmp : to->as_Register();
7373 
7374   assert_different_registers(val_obj_tmp, from_reg_tmp, tmp1, tmp2, tmp3, val_array);
7375 
7376   if (reg_state[to->value()] == reg_readonly) {
7377     if (!is_reg_in_unpacked_fields(sig, sig_index, to, from, from_count, from_index)) {
7378       skip_unpacked_fields(sig, sig_index, from, from_count, from_index);
7379       return false; // Not yet writable
7380     }
7381     val_obj = val_obj_tmp;
7382   }
7383 
7384   ScalarizedInlineArgsStream stream(sig, sig_index, from, from_count, from_index);
7385   VMReg fromReg;
7386   BasicType bt;
7387   Label L_null;
7388   while (stream.next(fromReg, bt)) {
7389     assert(fromReg->is_valid(), "source must be valid");
7390     reg_state[fromReg->value()] = reg_writable;
7391 
7392     int off = sig->at(stream.sig_index())._offset;
7393     if (off == -1) {
7394       // Nullable inline type argument, emit null check
7395       Label L_notNull;
7396       if (fromReg->is_stack()) {
7397         int ld_off = fromReg->reg2stack() * VMRegImpl::stack_slot_size;
7398         ldrb(tmp2, Address(sp, ld_off));
7399         cbnz(tmp2, L_notNull);
7400       } else {
7401         cbnz(fromReg->as_Register(), L_notNull);
7402       }
7403       mov(val_obj, 0);
7404       b(L_null);
7405       bind(L_notNull);
7406       continue;
7407     }
7408     if (sig->at(stream.sig_index())._vt_oop) {
7409       if (fromReg->is_stack()) {
7410         int ld_off = fromReg->reg2stack() * VMRegImpl::stack_slot_size;
7411         ldr(val_obj, Address(sp, ld_off));
7412       } else {
7413         mov(val_obj, fromReg->as_Register());
7414       }
7415       cbnz(val_obj, L_null);
7416       // get the buffer from the just allocated pool of buffers
7417       int index = arrayOopDesc::base_offset_in_bytes(T_OBJECT) + vtarg_index * type2aelembytes(T_OBJECT);
7418       load_heap_oop(val_obj, Address(val_array, index), rscratch1, rscratch2);
7419       continue;
7420     }
7421 
7422     assert(off > 0, "offset in object should be positive");
7423     size_t size_in_bytes = is_java_primitive(bt) ? type2aelembytes(bt) : wordSize;
7424 
7425     // Pack the scalarized field into the value object.
7426     Address dst(val_obj, off);
7427     if (!fromReg->is_FloatRegister()) {
7428       Register src;
7429       if (fromReg->is_stack()) {
7430         src = from_reg_tmp;
7431         int ld_off = fromReg->reg2stack() * VMRegImpl::stack_slot_size;
7432         load_sized_value(src, Address(sp, ld_off), size_in_bytes, /* is_signed */ false);
7433       } else {
7434         src = fromReg->as_Register();
7435       }
7436       assert_different_registers(dst.base(), src, tmp1, tmp2, tmp3, val_array);
7437       if (is_reference_type(bt)) {
7438         // store_heap_oop transitively calls oop_store_at which corrupts to.base(). We need to keep val_obj valid.
7439         mov(tmp3, val_obj);
7440         Address dst_with_tmp3(tmp3, off);
7441         store_heap_oop(dst_with_tmp3, src, tmp1, tmp2, tmp3, IN_HEAP | ACCESS_WRITE | IS_DEST_UNINITIALIZED);
7442       } else {
7443         store_sized_value(dst, src, size_in_bytes);
7444       }
7445     } else if (bt == T_DOUBLE) {
7446       strd(fromReg->as_FloatRegister(), dst);
7447     } else {
7448       assert(bt == T_FLOAT, "must be float");
7449       strs(fromReg->as_FloatRegister(), dst);
7450     }
7451   }
7452   bind(L_null);
7453   sig_index = stream.sig_index();
7454   from_index = stream.regs_index();
7455 
7456   assert(reg_state[to->value()] == reg_writable, "must have already been read");
7457   bool success = move_helper(val_obj->as_VMReg(), to, T_OBJECT, reg_state);
7458   assert(success, "to register must be writable");
7459   return true;
7460 }
7461 
7462 VMReg MacroAssembler::spill_reg_for(VMReg reg) {
7463   return (reg->is_FloatRegister()) ? v8->as_VMReg() : r14->as_VMReg();
7464 }
7465 
7466 void MacroAssembler::cache_wb(Address line) {
7467   assert(line.getMode() == Address::base_plus_offset, "mode should be base_plus_offset");
7468   assert(line.index() == noreg, "index should be noreg");
7469   assert(line.offset() == 0, "offset should be 0");
7470   // would like to assert this
7471   // assert(line._ext.shift == 0, "shift should be zero");
7472   if (VM_Version::supports_dcpop()) {
7473     // writeback using clear virtual address to point of persistence
7474     dc(Assembler::CVAP, line.base());
7475   } else {
7476     // no need to generate anything as Unsafe.writebackMemory should
7477     // never invoke this stub
7478   }
7479 }
7480 
7481 void MacroAssembler::cache_wbsync(bool is_pre) {
7482   // we only need a barrier post sync
7483   if (!is_pre) {
7484     membar(Assembler::AnyAny);
7485   }
7486 }
7487 
7488 void MacroAssembler::verify_sve_vector_length(Register tmp) {
7489   if (!UseSVE || VM_Version::get_max_supported_sve_vector_length() == FloatRegister::sve_vl_min) {
7490     return;
7491   }
7492   // Make sure that native code does not change SVE vector length.
7493   Label verify_ok;
7494   movw(tmp, zr);
7495   sve_inc(tmp, B);
7496   subsw(zr, tmp, VM_Version::get_initial_sve_vector_length());
7497   br(EQ, verify_ok);
7498   stop("Error: SVE vector length has changed since jvm startup");
7499   bind(verify_ok);
7500 }
7501 
7502 void MacroAssembler::verify_ptrue() {
7503   Label verify_ok;
7504   if (!UseSVE) {
7505     return;
7506   }
7507   sve_cntp(rscratch1, B, ptrue, ptrue); // get true elements count.
7508   sve_dec(rscratch1, B);
7509   cbz(rscratch1, verify_ok);
7510   stop("Error: the preserved predicate register (p7) elements are not all true");
7511   bind(verify_ok);
7512 }
7513 
7514 void MacroAssembler::safepoint_isb() {
7515   isb();
7516 #ifndef PRODUCT
7517   if (VerifyCrossModifyFence) {
7518     // Clear the thread state.
7519     strb(zr, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
7520   }
7521 #endif
7522 }
7523 
7524 #ifndef PRODUCT
7525 void MacroAssembler::verify_cross_modify_fence_not_required() {
7526   if (VerifyCrossModifyFence) {
7527     // Check if thread needs a cross modify fence.
7528     ldrb(rscratch1, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
7529     Label fence_not_required;
7530     cbz(rscratch1, fence_not_required);
7531     // If it does then fail.
7532     lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::verify_cross_modify_fence_failure)));
7533     mov(c_rarg0, rthread);
7534     blr(rscratch1);
7535     bind(fence_not_required);
7536   }
7537 }
7538 #endif
7539 
7540 void MacroAssembler::spin_wait() {
7541   block_comment("spin_wait {");
7542   for (int i = 0; i < VM_Version::spin_wait_desc().inst_count(); ++i) {
7543     switch (VM_Version::spin_wait_desc().inst()) {
7544       case SpinWait::NOP:
7545         nop();
7546         break;
7547       case SpinWait::ISB:
7548         isb();
7549         break;
7550       case SpinWait::YIELD:
7551         yield();
7552         break;
7553       case SpinWait::SB:
7554         assert(VM_Version::supports_sb(), "current CPU does not support SB instruction");
7555         sb();
7556         break;
7557       case SpinWait::WFET:
7558         spin_wait_wfet(VM_Version::spin_wait_desc().delay());
7559         break;
7560       default:
7561         ShouldNotReachHere();
7562     }
7563   }
7564   block_comment("}");
7565 }
7566 
7567 void MacroAssembler::spin_wait_wfet(int delay_ns) {
7568   // The sequence assumes CNTFRQ_EL0 is fixed to 1GHz. The assumption is valid
7569   // starting from Armv8.6, according to the "D12.1.2 The system counter" of the
7570   // Arm Architecture Reference Manual for A-profile architecture version M.a.a.
7571   // This is sufficient because FEAT_WFXT is introduced from Armv8.6.
7572   Register target = rscratch1;
7573   Register current = rscratch2;
7574   get_cntvctss_el0(current);
7575   add(target, current, delay_ns);
7576 
7577   Label L_wait_loop;
7578   bind(L_wait_loop);
7579 
7580   wfet(target);
7581   get_cntvctss_el0(current);
7582 
7583   cmp(current, target);
7584   br(LT, L_wait_loop);
7585 
7586   sb();
7587 }
7588 
7589 // Stack frame creation/removal
7590 
7591 void MacroAssembler::enter(bool strip_ret_addr) {
7592   if (strip_ret_addr) {
7593     // Addresses can only be signed once. If there are multiple nested frames being created
7594     // in the same function, then the return address needs stripping first.
7595     strip_return_address();
7596   }
7597   protect_return_address();
7598   stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
7599   mov(rfp, sp);
7600 }
7601 
7602 void MacroAssembler::leave() {
7603   mov(sp, rfp);
7604   ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
7605   authenticate_return_address();
7606 }
7607 
7608 // ROP Protection
7609 // Use the AArch64 PAC feature to add ROP protection for generated code. Use whenever creating/
7610 // destroying stack frames or whenever directly loading/storing the LR to memory.
7611 // If ROP protection is not set then these functions are no-ops.
7612 // For more details on PAC see pauth_aarch64.hpp.
7613 
7614 // Sign the LR. Use during construction of a stack frame, before storing the LR to memory.
7615 // Uses value zero as the modifier.
7616 //
7617 void MacroAssembler::protect_return_address() {
7618   if (VM_Version::use_rop_protection()) {
7619     check_return_address();
7620     paciaz();
7621   }
7622 }
7623 
7624 // Sign the return value in the given register. Use before updating the LR in the existing stack
7625 // frame for the current function.
7626 // Uses value zero as the modifier.
7627 //
7628 void MacroAssembler::protect_return_address(Register return_reg) {
7629   if (VM_Version::use_rop_protection()) {
7630     check_return_address(return_reg);
7631     paciza(return_reg);
7632   }
7633 }
7634 
7635 // Authenticate the LR. Use before function return, after restoring FP and loading LR from memory.
7636 // Uses value zero as the modifier.
7637 //
7638 void MacroAssembler::authenticate_return_address() {
7639   if (VM_Version::use_rop_protection()) {
7640     autiaz();
7641     check_return_address();
7642   }
7643 }
7644 
7645 // Authenticate the return value in the given register. Use before updating the LR in the existing
7646 // stack frame for the current function.
7647 // Uses value zero as the modifier.
7648 //
7649 void MacroAssembler::authenticate_return_address(Register return_reg) {
7650   if (VM_Version::use_rop_protection()) {
7651     autiza(return_reg);
7652     check_return_address(return_reg);
7653   }
7654 }
7655 
7656 // Strip any PAC data from LR without performing any authentication. Use with caution - only if
7657 // there is no guaranteed way of authenticating the LR.
7658 //
7659 void MacroAssembler::strip_return_address() {
7660   if (VM_Version::use_rop_protection()) {
7661     xpaclri();
7662   }
7663 }
7664 
7665 #ifndef PRODUCT
7666 // PAC failures can be difficult to debug. After an authentication failure, a segfault will only
7667 // occur when the pointer is used - ie when the program returns to the invalid LR. At this point
7668 // it is difficult to debug back to the callee function.
7669 // This function simply loads from the address in the given register.
7670 // Use directly after authentication to catch authentication failures.
7671 // Also use before signing to check that the pointer is valid and hasn't already been signed.
7672 //
7673 void MacroAssembler::check_return_address(Register return_reg) {
7674   if (VM_Version::use_rop_protection()) {
7675     ldr(zr, Address(return_reg));
7676   }
7677 }
7678 #endif
7679 
7680 // The java_calling_convention describes stack locations as ideal slots on
7681 // a frame with no abi restrictions. Since we must observe abi restrictions
7682 // (like the placement of the register window) the slots must be biased by
7683 // the following value.
7684 static int reg2offset_in(VMReg r) {
7685   // Account for saved rfp and lr
7686   // This should really be in_preserve_stack_slots
7687   return (r->reg2stack() + 4) * VMRegImpl::stack_slot_size;
7688 }
7689 
7690 static int reg2offset_out(VMReg r) {
7691   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
7692 }
7693 
7694 // On 64bit we will store integer like items to the stack as
7695 // 64bits items (AArch64 ABI) even though java would only store
7696 // 32bits for a parameter. On 32bit it will simply be 32bits
7697 // So this routine will do 32->32 on 32bit and 32->64 on 64bit
7698 void MacroAssembler::move32_64(VMRegPair src, VMRegPair dst, Register tmp) {
7699   if (src.first()->is_stack()) {
7700     if (dst.first()->is_stack()) {
7701       // stack to stack
7702       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
7703       str(tmp, Address(sp, reg2offset_out(dst.first())));
7704     } else {
7705       // stack to reg
7706       ldrsw(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
7707     }
7708   } else if (dst.first()->is_stack()) {
7709     // reg to stack
7710     str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
7711   } else {
7712     if (dst.first() != src.first()) {
7713       sxtw(dst.first()->as_Register(), src.first()->as_Register());
7714     }
7715   }
7716 }
7717 
7718 // An oop arg. Must pass a handle not the oop itself
7719 void MacroAssembler::object_move(
7720                         OopMap* map,
7721                         int oop_handle_offset,
7722                         int framesize_in_slots,
7723                         VMRegPair src,
7724                         VMRegPair dst,
7725                         bool is_receiver,
7726                         int* receiver_offset) {
7727 
7728   // must pass a handle. First figure out the location we use as a handle
7729 
7730   Register rHandle = dst.first()->is_stack() ? rscratch2 : dst.first()->as_Register();
7731 
7732   // See if oop is null if it is we need no handle
7733 
7734   if (src.first()->is_stack()) {
7735 
7736     // Oop is already on the stack as an argument
7737     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
7738     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
7739     if (is_receiver) {
7740       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
7741     }
7742 
7743     ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
7744     lea(rHandle, Address(rfp, reg2offset_in(src.first())));
7745     // conditionally move a null
7746     cmp(rscratch1, zr);
7747     csel(rHandle, zr, rHandle, Assembler::EQ);
7748   } else {
7749 
7750     // Oop is in an a register we must store it to the space we reserve
7751     // on the stack for oop_handles and pass a handle if oop is non-null
7752 
7753     const Register rOop = src.first()->as_Register();
7754     int oop_slot;
7755     if (rOop == j_rarg0)
7756       oop_slot = 0;
7757     else if (rOop == j_rarg1)
7758       oop_slot = 1;
7759     else if (rOop == j_rarg2)
7760       oop_slot = 2;
7761     else if (rOop == j_rarg3)
7762       oop_slot = 3;
7763     else if (rOop == j_rarg4)
7764       oop_slot = 4;
7765     else if (rOop == j_rarg5)
7766       oop_slot = 5;
7767     else if (rOop == j_rarg6)
7768       oop_slot = 6;
7769     else {
7770       assert(rOop == j_rarg7, "wrong register");
7771       oop_slot = 7;
7772     }
7773 
7774     oop_slot = oop_slot * VMRegImpl::slots_per_word + oop_handle_offset;
7775     int offset = oop_slot*VMRegImpl::stack_slot_size;
7776 
7777     map->set_oop(VMRegImpl::stack2reg(oop_slot));
7778     // Store oop in handle area, may be null
7779     str(rOop, Address(sp, offset));
7780     if (is_receiver) {
7781       *receiver_offset = offset;
7782     }
7783 
7784     cmp(rOop, zr);
7785     lea(rHandle, Address(sp, offset));
7786     // conditionally move a null
7787     csel(rHandle, zr, rHandle, Assembler::EQ);
7788   }
7789 
7790   // If arg is on the stack then place it otherwise it is already in correct reg.
7791   if (dst.first()->is_stack()) {
7792     str(rHandle, Address(sp, reg2offset_out(dst.first())));
7793   }
7794 }
7795 
7796 // A float arg may have to do float reg int reg conversion
7797 void MacroAssembler::float_move(VMRegPair src, VMRegPair dst, Register tmp) {
7798  if (src.first()->is_stack()) {
7799     if (dst.first()->is_stack()) {
7800       ldrw(tmp, Address(rfp, reg2offset_in(src.first())));
7801       strw(tmp, Address(sp, reg2offset_out(dst.first())));
7802     } else {
7803       ldrs(dst.first()->as_FloatRegister(), Address(rfp, reg2offset_in(src.first())));
7804     }
7805   } else if (src.first() != dst.first()) {
7806     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
7807       fmovs(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
7808     else
7809       strs(src.first()->as_FloatRegister(), Address(sp, reg2offset_out(dst.first())));
7810   }
7811 }
7812 
7813 // A long move
7814 void MacroAssembler::long_move(VMRegPair src, VMRegPair dst, Register tmp) {
7815   if (src.first()->is_stack()) {
7816     if (dst.first()->is_stack()) {
7817       // stack to stack
7818       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
7819       str(tmp, Address(sp, reg2offset_out(dst.first())));
7820     } else {
7821       // stack to reg
7822       ldr(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
7823     }
7824   } else if (dst.first()->is_stack()) {
7825     // reg to stack
7826     // Do we really have to sign extend???
7827     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
7828     str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
7829   } else {
7830     if (dst.first() != src.first()) {
7831       mov(dst.first()->as_Register(), src.first()->as_Register());
7832     }
7833   }
7834 }
7835 
7836 
7837 // A double move
7838 void MacroAssembler::double_move(VMRegPair src, VMRegPair dst, Register tmp) {
7839  if (src.first()->is_stack()) {
7840     if (dst.first()->is_stack()) {
7841       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
7842       str(tmp, Address(sp, reg2offset_out(dst.first())));
7843     } else {
7844       ldrd(dst.first()->as_FloatRegister(), Address(rfp, reg2offset_in(src.first())));
7845     }
7846   } else if (src.first() != dst.first()) {
7847     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
7848       fmovd(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
7849     else
7850       strd(src.first()->as_FloatRegister(), Address(sp, reg2offset_out(dst.first())));
7851   }
7852 }
7853 
7854 // Implements fast-locking.
7855 //
7856 //  - obj: the object to be locked
7857 //  - t1, t2, t3: temporary registers, will be destroyed
7858 //  - slow: branched to if locking fails, absolute offset may larger than 32KB (imm14 encoding).
7859 void MacroAssembler::fast_lock(Register basic_lock, Register obj, Register t1, Register t2, Register t3, Label& slow) {
7860   assert_different_registers(basic_lock, obj, t1, t2, t3, rscratch1);
7861 
7862   Label push;
7863   const Register top = t1;
7864   const Register mark = t2;
7865   const Register t = t3;
7866 
7867   // Preload the markWord. It is important that this is the first
7868   // instruction emitted as it is part of C1's null check semantics.
7869   ldr(mark, Address(obj, oopDesc::mark_offset_in_bytes()));
7870 
7871   if (UseObjectMonitorTable) {
7872     // Clear cache in case fast locking succeeds or we need to take the slow-path.
7873     str(zr, Address(basic_lock, BasicObjectLock::lock_offset() + in_ByteSize((BasicLock::object_monitor_cache_offset_in_bytes()))));
7874   }
7875 
7876   if (DiagnoseSyncOnValueBasedClasses != 0) {
7877     load_klass(t1, obj);
7878     ldrb(t1, Address(t1, Klass::misc_flags_offset()));
7879     tst(t1, KlassFlags::_misc_is_value_based_class);
7880     br(Assembler::NE, slow);
7881   }
7882 
7883   // Check if the lock-stack is full.
7884   ldrw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7885   cmpw(top, (unsigned)LockStack::end_offset());
7886   br(Assembler::GE, slow);
7887 
7888   // Check for recursion.
7889   subw(t, top, oopSize);
7890   ldr(t, Address(rthread, t));
7891   cmp(obj, t);
7892   br(Assembler::EQ, push);
7893 
7894   // Check header for monitor (0b10).
7895   tst(mark, markWord::monitor_value);
7896   br(Assembler::NE, slow);
7897 
7898   // Try to lock. Transition lock bits 0b01 => 0b00
7899   assert(oopDesc::mark_offset_in_bytes() == 0, "required to avoid lea");
7900   orr(mark, mark, markWord::unlocked_value);
7901   // Mask inline_type bit such that we go to the slow path if object is an inline type
7902   andr(mark, mark, ~((int) markWord::inline_type_bit_in_place));
7903 
7904   eor(t, mark, markWord::unlocked_value);
7905   cmpxchg(/*addr*/ obj, /*expected*/ mark, /*new*/ t, Assembler::xword,
7906           /*acquire*/ true, /*release*/ false, /*weak*/ false, noreg);
7907   br(Assembler::NE, slow);
7908 
7909   bind(push);
7910   // After successful lock, push object on lock-stack.
7911   str(obj, Address(rthread, top));
7912   addw(top, top, oopSize);
7913   strw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7914 }
7915 
7916 // Implements fast-unlocking.
7917 //
7918 // - obj: the object to be unlocked
7919 // - t1, t2, t3: temporary registers
7920 // - slow: branched to if unlocking fails, absolute offset may larger than 32KB (imm14 encoding).
7921 void MacroAssembler::fast_unlock(Register obj, Register t1, Register t2, Register t3, Label& slow) {
7922   // cmpxchg clobbers rscratch1.
7923   assert_different_registers(obj, t1, t2, t3, rscratch1);
7924 
7925 #ifdef ASSERT
7926   {
7927     // Check for lock-stack underflow.
7928     Label stack_ok;
7929     ldrw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
7930     cmpw(t1, (unsigned)LockStack::start_offset());
7931     br(Assembler::GE, stack_ok);
7932     STOP("Lock-stack underflow");
7933     bind(stack_ok);
7934   }
7935 #endif
7936 
7937   Label unlocked, push_and_slow;
7938   const Register top = t1;
7939   const Register mark = t2;
7940   const Register t = t3;
7941 
7942   // Check if obj is top of lock-stack.
7943   ldrw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7944   subw(top, top, oopSize);
7945   ldr(t, Address(rthread, top));
7946   cmp(obj, t);
7947   br(Assembler::NE, slow);
7948 
7949   // Pop lock-stack.
7950   DEBUG_ONLY(str(zr, Address(rthread, top));)
7951   strw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7952 
7953   // Check if recursive.
7954   subw(t, top, oopSize);
7955   ldr(t, Address(rthread, t));
7956   cmp(obj, t);
7957   br(Assembler::EQ, unlocked);
7958 
7959   // Not recursive. Check header for monitor (0b10).
7960   ldr(mark, Address(obj, oopDesc::mark_offset_in_bytes()));
7961   tbnz(mark, log2i_exact(markWord::monitor_value), push_and_slow);
7962 
7963 #ifdef ASSERT
7964   // Check header not unlocked (0b01).
7965   Label not_unlocked;
7966   tbz(mark, log2i_exact(markWord::unlocked_value), not_unlocked);
7967   stop("fast_unlock already unlocked");
7968   bind(not_unlocked);
7969 #endif
7970 
7971   // Try to unlock. Transition lock bits 0b00 => 0b01
7972   assert(oopDesc::mark_offset_in_bytes() == 0, "required to avoid lea");
7973   orr(t, mark, markWord::unlocked_value);
7974   cmpxchg(obj, mark, t, Assembler::xword,
7975           /*acquire*/ false, /*release*/ true, /*weak*/ false, noreg);
7976   br(Assembler::EQ, unlocked);
7977 
7978   bind(push_and_slow);
7979   // Restore lock-stack and handle the unlock in runtime.
7980   DEBUG_ONLY(str(obj, Address(rthread, top));)
7981   addw(top, top, oopSize);
7982   strw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7983   b(slow);
7984 
7985   bind(unlocked);
7986 }
7987 
7988 // Rotate using USHR and SLI instructions (or copy, if rotate count is zero)
7989 void MacroAssembler::neon_vector_rotate(FloatRegister dst, SIMD_Arrangement T,
7990                                         FloatRegister src, int shift_amount) {
7991   assert(src != dst, "did not expect src and dst to be the same register");
7992 
7993   int esize = BitsPerByte << (T / 2);
7994   int lshift = shift_amount & (esize - 1);
7995 
7996   if (lshift == 0) {
7997     // T & 1 == 0 => 64-bit arrangements, else 128-bit arrangements
7998     orr(dst, (T & 1) == 0 ? T8B : T16B, src, src);
7999   } else {
8000     ushr(dst, T, src, esize - lshift);
8001     sli(dst, T, src, lshift);
8002   }
8003 }
--- EOF ---