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