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