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