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