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