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