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