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