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