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