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