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