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_IDENTITY);
1815   cbz(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   lea(inline_klass, Address(inline_klass, Array<InlineKlass*>::base_offset_in_bytes()));
5240   ldr(inline_klass, Address(inline_klass, index, Address::lsl(3)));
5241 }
5242 
5243 // Writes to stack successive pages until offset reached to check for
5244 // stack overflow + shadow pages.  This clobbers tmp.
5245 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
5246   assert_different_registers(tmp, size, rscratch1);
5247   mov(tmp, sp);
5248   // Bang stack for total size given plus shadow page size.
5249   // Bang one page at a time because large size can bang beyond yellow and
5250   // red zones.
5251   Label loop;
5252   mov(rscratch1, (int)os::vm_page_size());
5253   bind(loop);
5254   lea(tmp, Address(tmp, -(int)os::vm_page_size()));
5255   subsw(size, size, rscratch1);
5256   str(size, Address(tmp));
5257   br(Assembler::GT, loop);
5258 
5259   // Bang down shadow pages too.
5260   // At this point, (tmp-0) is the last address touched, so don't
5261   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
5262   // was post-decremented.)  Skip this address by starting at i=1, and
5263   // touch a few more pages below.  N.B.  It is important to touch all
5264   // the way down to and including i=StackShadowPages.
5265   for (int i = 0; i < (int)(StackOverflow::stack_shadow_zone_size() / (int)os::vm_page_size()) - 1; i++) {
5266     // this could be any sized move but this is can be a debugging crumb
5267     // so the bigger the better.
5268     lea(tmp, Address(tmp, -(int)os::vm_page_size()));
5269     str(size, Address(tmp));
5270   }
5271 }
5272 
5273 // Move the address of the polling page into dest.
5274 void MacroAssembler::get_polling_page(Register dest, relocInfo::relocType rtype) {
5275   ldr(dest, Address(rthread, JavaThread::polling_page_offset()));
5276 }
5277 
5278 // Read the polling page.  The address of the polling page must
5279 // already be in r.
5280 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
5281   address mark;
5282   {
5283     InstructionMark im(this);
5284     code_section()->relocate(inst_mark(), rtype);
5285     ldrw(zr, Address(r, 0));
5286     mark = inst_mark();
5287   }
5288   verify_cross_modify_fence_not_required();
5289   return mark;
5290 }
5291 
5292 void MacroAssembler::adrp(Register reg1, const Address &dest, uint64_t &byte_offset) {
5293   relocInfo::relocType rtype = dest.rspec().reloc()->type();
5294   uint64_t low_page = (uint64_t)CodeCache::low_bound() >> 12;
5295   uint64_t high_page = (uint64_t)(CodeCache::high_bound()-1) >> 12;
5296   uint64_t dest_page = (uint64_t)dest.target() >> 12;
5297   int64_t offset_low = dest_page - low_page;
5298   int64_t offset_high = dest_page - high_page;
5299 
5300   assert(is_valid_AArch64_address(dest.target()), "bad address");
5301   assert(dest.getMode() == Address::literal, "ADRP must be applied to a literal address");
5302 
5303   InstructionMark im(this);
5304   code_section()->relocate(inst_mark(), dest.rspec());
5305   // 8143067: Ensure that the adrp can reach the dest from anywhere within
5306   // the code cache so that if it is relocated we know it will still reach
5307   if (offset_high >= -(1<<20) && offset_low < (1<<20)) {
5308     _adrp(reg1, dest.target());
5309   } else {
5310     uint64_t target = (uint64_t)dest.target();
5311     uint64_t adrp_target
5312       = (target & 0xffffffffULL) | ((uint64_t)pc() & 0xffff00000000ULL);
5313 
5314     _adrp(reg1, (address)adrp_target);
5315     movk(reg1, target >> 32, 32);
5316   }
5317   byte_offset = (uint64_t)dest.target() & 0xfff;
5318 }
5319 
5320 void MacroAssembler::load_byte_map_base(Register reg) {
5321   CardTable::CardValue* byte_map_base =
5322     ((CardTableBarrierSet*)(BarrierSet::barrier_set()))->card_table()->byte_map_base();
5323 
5324   // Strictly speaking the byte_map_base isn't an address at all, and it might
5325   // even be negative. It is thus materialised as a constant.
5326   mov(reg, (uint64_t)byte_map_base);
5327 }
5328 
5329 void MacroAssembler::build_frame(int framesize) {
5330   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
5331   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
5332   protect_return_address();
5333   if (framesize < ((1 << 9) + 2 * wordSize)) {
5334     sub(sp, sp, framesize);
5335     stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
5336     if (PreserveFramePointer) add(rfp, sp, framesize - 2 * wordSize);
5337   } else {
5338     stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
5339     if (PreserveFramePointer) mov(rfp, sp);
5340     if (framesize < ((1 << 12) + 2 * wordSize))
5341       sub(sp, sp, framesize - 2 * wordSize);
5342     else {
5343       mov(rscratch1, framesize - 2 * wordSize);
5344       sub(sp, sp, rscratch1);
5345     }
5346   }
5347   verify_cross_modify_fence_not_required();
5348 }
5349 
5350 void MacroAssembler::remove_frame(int framesize) {
5351   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
5352   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
5353   if (framesize < ((1 << 9) + 2 * wordSize)) {
5354     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
5355     add(sp, sp, framesize);
5356   } else {
5357     if (framesize < ((1 << 12) + 2 * wordSize))
5358       add(sp, sp, framesize - 2 * wordSize);
5359     else {
5360       mov(rscratch1, framesize - 2 * wordSize);
5361       add(sp, sp, rscratch1);
5362     }
5363     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
5364   }
5365   authenticate_return_address();
5366 }
5367 
5368 void MacroAssembler::remove_frame(int initial_framesize, bool needs_stack_repair) {
5369   if (needs_stack_repair) {
5370     // Remove the extension of the caller's frame used for inline type unpacking
5371     //
5372     // Right now the stack looks like this:
5373     //
5374     // | Arguments from caller     |
5375     // |---------------------------|  <-- caller's SP
5376     // | Saved LR #1               |
5377     // | Saved FP #1               |
5378     // |---------------------------|
5379     // | Extension space for       |
5380     // |   inline arg (un)packing  |
5381     // |---------------------------|  <-- start of this method's frame
5382     // | Saved LR #2               |
5383     // | Saved FP #2               |
5384     // |---------------------------|  <-- FP
5385     // | sp_inc                    |
5386     // | method locals             |
5387     // |---------------------------|  <-- SP
5388     //
5389     // There are two copies of FP and LR on the stack. They will be identical
5390     // unless the caller has been deoptimized, in which case LR #1 will be patched
5391     // to point at the deopt blob, and LR #2 will still point into the old method.
5392     //
5393     // The sp_inc stack slot holds the total size of the frame including the
5394     // extension space minus two words for the saved FP and LR.
5395 
5396     int sp_inc_offset = initial_framesize - 3 * wordSize;  // Immediately below saved LR and FP
5397 
5398     ldr(rscratch1, Address(sp, sp_inc_offset));
5399     add(sp, sp, rscratch1);
5400     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
5401   } else {
5402     remove_frame(initial_framesize);
5403   }
5404 }
5405 
5406 void MacroAssembler::save_stack_increment(int sp_inc, int frame_size) {
5407   int real_frame_size = frame_size + sp_inc;
5408   assert(sp_inc == 0 || sp_inc > 2*wordSize, "invalid sp_inc value");
5409   assert(real_frame_size >= 2*wordSize, "frame size must include FP/LR space");
5410   assert((real_frame_size & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
5411 
5412   int sp_inc_offset = frame_size - 3 * wordSize;  // Immediately below saved LR and FP
5413 
5414   // Subtract two words for the saved FP and LR as these will be popped
5415   // separately. See remove_frame above.
5416   mov(rscratch1, real_frame_size - 2*wordSize);
5417   str(rscratch1, Address(sp, sp_inc_offset));
5418 }
5419 
5420 // This method counts leading positive bytes (highest bit not set) in provided byte array
5421 address MacroAssembler::count_positives(Register ary1, Register len, Register result) {
5422     // Simple and most common case of aligned small array which is not at the
5423     // end of memory page is placed here. All other cases are in stub.
5424     Label LOOP, END, STUB, STUB_LONG, SET_RESULT, DONE;
5425     const uint64_t UPPER_BIT_MASK=0x8080808080808080;
5426     assert_different_registers(ary1, len, result);
5427 
5428     mov(result, len);
5429     cmpw(len, 0);
5430     br(LE, DONE);
5431     cmpw(len, 4 * wordSize);
5432     br(GE, STUB_LONG); // size > 32 then go to stub
5433 
5434     int shift = 64 - exact_log2(os::vm_page_size());
5435     lsl(rscratch1, ary1, shift);
5436     mov(rscratch2, (size_t)(4 * wordSize) << shift);
5437     adds(rscratch2, rscratch1, rscratch2);  // At end of page?
5438     br(CS, STUB); // at the end of page then go to stub
5439     subs(len, len, wordSize);
5440     br(LT, END);
5441 
5442   BIND(LOOP);
5443     ldr(rscratch1, Address(post(ary1, wordSize)));
5444     tst(rscratch1, UPPER_BIT_MASK);
5445     br(NE, SET_RESULT);
5446     subs(len, len, wordSize);
5447     br(GE, LOOP);
5448     cmpw(len, -wordSize);
5449     br(EQ, DONE);
5450 
5451   BIND(END);
5452     ldr(rscratch1, Address(ary1));
5453     sub(rscratch2, zr, len, LSL, 3); // LSL 3 is to get bits from bytes
5454     lslv(rscratch1, rscratch1, rscratch2);
5455     tst(rscratch1, UPPER_BIT_MASK);
5456     br(NE, SET_RESULT);
5457     b(DONE);
5458 
5459   BIND(STUB);
5460     RuntimeAddress count_pos = RuntimeAddress(StubRoutines::aarch64::count_positives());
5461     assert(count_pos.target() != nullptr, "count_positives stub has not been generated");
5462     address tpc1 = trampoline_call(count_pos);
5463     if (tpc1 == nullptr) {
5464       DEBUG_ONLY(reset_labels(STUB_LONG, SET_RESULT, DONE));
5465       postcond(pc() == badAddress);
5466       return nullptr;
5467     }
5468     b(DONE);
5469 
5470   BIND(STUB_LONG);
5471     RuntimeAddress count_pos_long = RuntimeAddress(StubRoutines::aarch64::count_positives_long());
5472     assert(count_pos_long.target() != nullptr, "count_positives_long stub has not been generated");
5473     address tpc2 = trampoline_call(count_pos_long);
5474     if (tpc2 == nullptr) {
5475       DEBUG_ONLY(reset_labels(SET_RESULT, DONE));
5476       postcond(pc() == badAddress);
5477       return nullptr;
5478     }
5479     b(DONE);
5480 
5481   BIND(SET_RESULT);
5482 
5483     add(len, len, wordSize);
5484     sub(result, result, len);
5485 
5486   BIND(DONE);
5487   postcond(pc() != badAddress);
5488   return pc();
5489 }
5490 
5491 // Clobbers: rscratch1, rscratch2, rflags
5492 // May also clobber v0-v7 when (!UseSimpleArrayEquals && UseSIMDForArrayEquals)
5493 address MacroAssembler::arrays_equals(Register a1, Register a2, Register tmp3,
5494                                       Register tmp4, Register tmp5, Register result,
5495                                       Register cnt1, int elem_size) {
5496   Label DONE, SAME;
5497   Register tmp1 = rscratch1;
5498   Register tmp2 = rscratch2;
5499   Register cnt2 = tmp2;  // cnt2 only used in array length compare
5500   int elem_per_word = wordSize/elem_size;
5501   int log_elem_size = exact_log2(elem_size);
5502   int length_offset = arrayOopDesc::length_offset_in_bytes();
5503   int base_offset
5504     = arrayOopDesc::base_offset_in_bytes(elem_size == 2 ? T_CHAR : T_BYTE);
5505   int stubBytesThreshold = 3 * 64 + (UseSIMDForArrayEquals ? 0 : 16);
5506 
5507   assert(elem_size == 1 || elem_size == 2, "must be char or byte");
5508   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
5509 
5510 #ifndef PRODUCT
5511   {
5512     const char kind = (elem_size == 2) ? 'U' : 'L';
5513     char comment[64];
5514     snprintf(comment, sizeof comment, "array_equals%c{", kind);
5515     BLOCK_COMMENT(comment);
5516   }
5517 #endif
5518 
5519   // if (a1 == a2)
5520   //     return true;
5521   cmpoop(a1, a2); // May have read barriers for a1 and a2.
5522   br(EQ, SAME);
5523 
5524   if (UseSimpleArrayEquals) {
5525     Label NEXT_WORD, SHORT, TAIL03, TAIL01, A_MIGHT_BE_NULL, A_IS_NOT_NULL;
5526     // if (a1 == nullptr || a2 == nullptr)
5527     //     return false;
5528     // a1 & a2 == 0 means (some-pointer is null) or
5529     // (very-rare-or-even-probably-impossible-pointer-values)
5530     // so, we can save one branch in most cases
5531     tst(a1, a2);
5532     mov(result, false);
5533     br(EQ, A_MIGHT_BE_NULL);
5534     // if (a1.length != a2.length)
5535     //      return false;
5536     bind(A_IS_NOT_NULL);
5537     ldrw(cnt1, Address(a1, length_offset));
5538     ldrw(cnt2, Address(a2, length_offset));
5539     eorw(tmp5, cnt1, cnt2);
5540     cbnzw(tmp5, DONE);
5541     lea(a1, Address(a1, base_offset));
5542     lea(a2, Address(a2, base_offset));
5543     // Check for short strings, i.e. smaller than wordSize.
5544     subs(cnt1, cnt1, elem_per_word);
5545     br(Assembler::LT, SHORT);
5546     // Main 8 byte comparison loop.
5547     bind(NEXT_WORD); {
5548       ldr(tmp1, Address(post(a1, wordSize)));
5549       ldr(tmp2, Address(post(a2, wordSize)));
5550       subs(cnt1, cnt1, elem_per_word);
5551       eor(tmp5, tmp1, tmp2);
5552       cbnz(tmp5, DONE);
5553     } br(GT, NEXT_WORD);
5554     // Last longword.  In the case where length == 4 we compare the
5555     // same longword twice, but that's still faster than another
5556     // conditional branch.
5557     // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
5558     // length == 4.
5559     if (log_elem_size > 0)
5560       lsl(cnt1, cnt1, log_elem_size);
5561     ldr(tmp3, Address(a1, cnt1));
5562     ldr(tmp4, Address(a2, cnt1));
5563     eor(tmp5, tmp3, tmp4);
5564     cbnz(tmp5, DONE);
5565     b(SAME);
5566     bind(A_MIGHT_BE_NULL);
5567     // in case both a1 and a2 are not-null, proceed with loads
5568     cbz(a1, DONE);
5569     cbz(a2, DONE);
5570     b(A_IS_NOT_NULL);
5571     bind(SHORT);
5572 
5573     tbz(cnt1, 2 - log_elem_size, TAIL03); // 0-7 bytes left.
5574     {
5575       ldrw(tmp1, Address(post(a1, 4)));
5576       ldrw(tmp2, Address(post(a2, 4)));
5577       eorw(tmp5, tmp1, tmp2);
5578       cbnzw(tmp5, DONE);
5579     }
5580     bind(TAIL03);
5581     tbz(cnt1, 1 - log_elem_size, TAIL01); // 0-3 bytes left.
5582     {
5583       ldrh(tmp3, Address(post(a1, 2)));
5584       ldrh(tmp4, Address(post(a2, 2)));
5585       eorw(tmp5, tmp3, tmp4);
5586       cbnzw(tmp5, DONE);
5587     }
5588     bind(TAIL01);
5589     if (elem_size == 1) { // Only needed when comparing byte arrays.
5590       tbz(cnt1, 0, SAME); // 0-1 bytes left.
5591       {
5592         ldrb(tmp1, a1);
5593         ldrb(tmp2, a2);
5594         eorw(tmp5, tmp1, tmp2);
5595         cbnzw(tmp5, DONE);
5596       }
5597     }
5598   } else {
5599     Label NEXT_DWORD, SHORT, TAIL, TAIL2, STUB,
5600         CSET_EQ, LAST_CHECK;
5601     mov(result, false);
5602     cbz(a1, DONE);
5603     ldrw(cnt1, Address(a1, length_offset));
5604     cbz(a2, DONE);
5605     ldrw(cnt2, Address(a2, length_offset));
5606     // on most CPUs a2 is still "locked"(surprisingly) in ldrw and it's
5607     // faster to perform another branch before comparing a1 and a2
5608     cmp(cnt1, (u1)elem_per_word);
5609     br(LE, SHORT); // short or same
5610     ldr(tmp3, Address(pre(a1, base_offset)));
5611     subs(zr, cnt1, stubBytesThreshold);
5612     br(GE, STUB);
5613     ldr(tmp4, Address(pre(a2, base_offset)));
5614     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
5615     cmp(cnt2, cnt1);
5616     br(NE, DONE);
5617 
5618     // Main 16 byte comparison loop with 2 exits
5619     bind(NEXT_DWORD); {
5620       ldr(tmp1, Address(pre(a1, wordSize)));
5621       ldr(tmp2, Address(pre(a2, wordSize)));
5622       subs(cnt1, cnt1, 2 * elem_per_word);
5623       br(LE, TAIL);
5624       eor(tmp4, tmp3, tmp4);
5625       cbnz(tmp4, DONE);
5626       ldr(tmp3, Address(pre(a1, wordSize)));
5627       ldr(tmp4, Address(pre(a2, wordSize)));
5628       cmp(cnt1, (u1)elem_per_word);
5629       br(LE, TAIL2);
5630       cmp(tmp1, tmp2);
5631     } br(EQ, NEXT_DWORD);
5632     b(DONE);
5633 
5634     bind(TAIL);
5635     eor(tmp4, tmp3, tmp4);
5636     eor(tmp2, tmp1, tmp2);
5637     lslv(tmp2, tmp2, tmp5);
5638     orr(tmp5, tmp4, tmp2);
5639     cmp(tmp5, zr);
5640     b(CSET_EQ);
5641 
5642     bind(TAIL2);
5643     eor(tmp2, tmp1, tmp2);
5644     cbnz(tmp2, DONE);
5645     b(LAST_CHECK);
5646 
5647     bind(STUB);
5648     ldr(tmp4, Address(pre(a2, base_offset)));
5649     cmp(cnt2, cnt1);
5650     br(NE, DONE);
5651     if (elem_size == 2) { // convert to byte counter
5652       lsl(cnt1, cnt1, 1);
5653     }
5654     eor(tmp5, tmp3, tmp4);
5655     cbnz(tmp5, DONE);
5656     RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_array_equals());
5657     assert(stub.target() != nullptr, "array_equals_long stub has not been generated");
5658     address tpc = trampoline_call(stub);
5659     if (tpc == nullptr) {
5660       DEBUG_ONLY(reset_labels(SHORT, LAST_CHECK, CSET_EQ, SAME, DONE));
5661       postcond(pc() == badAddress);
5662       return nullptr;
5663     }
5664     b(DONE);
5665 
5666     // (a1 != null && a2 == null) || (a1 != null && a2 != null && a1 == a2)
5667     // so, if a2 == null => return false(0), else return true, so we can return a2
5668     mov(result, a2);
5669     b(DONE);
5670     bind(SHORT);
5671     cmp(cnt2, cnt1);
5672     br(NE, DONE);
5673     cbz(cnt1, SAME);
5674     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
5675     ldr(tmp3, Address(a1, base_offset));
5676     ldr(tmp4, Address(a2, base_offset));
5677     bind(LAST_CHECK);
5678     eor(tmp4, tmp3, tmp4);
5679     lslv(tmp5, tmp4, tmp5);
5680     cmp(tmp5, zr);
5681     bind(CSET_EQ);
5682     cset(result, EQ);
5683     b(DONE);
5684   }
5685 
5686   bind(SAME);
5687   mov(result, true);
5688   // That's it.
5689   bind(DONE);
5690 
5691   BLOCK_COMMENT("} array_equals");
5692   postcond(pc() != badAddress);
5693   return pc();
5694 }
5695 
5696 // Compare Strings
5697 
5698 // For Strings we're passed the address of the first characters in a1
5699 // and a2 and the length in cnt1.
5700 // elem_size is the element size in bytes: either 1 or 2.
5701 // There are two implementations.  For arrays >= 8 bytes, all
5702 // comparisons (including the final one, which may overlap) are
5703 // performed 8 bytes at a time.  For strings < 8 bytes, we compare a
5704 // halfword, then a short, and then a byte.
5705 
5706 void MacroAssembler::string_equals(Register a1, Register a2,
5707                                    Register result, Register cnt1, int elem_size)
5708 {
5709   Label SAME, DONE, SHORT, NEXT_WORD;
5710   Register tmp1 = rscratch1;
5711   Register tmp2 = rscratch2;
5712   Register cnt2 = tmp2;  // cnt2 only used in array length compare
5713 
5714   assert(elem_size == 1 || elem_size == 2, "must be 2 or 1 byte");
5715   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
5716 
5717 #ifndef PRODUCT
5718   {
5719     const char kind = (elem_size == 2) ? 'U' : 'L';
5720     char comment[64];
5721     snprintf(comment, sizeof comment, "{string_equals%c", kind);
5722     BLOCK_COMMENT(comment);
5723   }
5724 #endif
5725 
5726   mov(result, false);
5727 
5728   // Check for short strings, i.e. smaller than wordSize.
5729   subs(cnt1, cnt1, wordSize);
5730   br(Assembler::LT, SHORT);
5731   // Main 8 byte comparison loop.
5732   bind(NEXT_WORD); {
5733     ldr(tmp1, Address(post(a1, wordSize)));
5734     ldr(tmp2, Address(post(a2, wordSize)));
5735     subs(cnt1, cnt1, wordSize);
5736     eor(tmp1, tmp1, tmp2);
5737     cbnz(tmp1, DONE);
5738   } br(GT, NEXT_WORD);
5739   // Last longword.  In the case where length == 4 we compare the
5740   // same longword twice, but that's still faster than another
5741   // conditional branch.
5742   // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
5743   // length == 4.
5744   ldr(tmp1, Address(a1, cnt1));
5745   ldr(tmp2, Address(a2, cnt1));
5746   eor(tmp2, tmp1, tmp2);
5747   cbnz(tmp2, DONE);
5748   b(SAME);
5749 
5750   bind(SHORT);
5751   Label TAIL03, TAIL01;
5752 
5753   tbz(cnt1, 2, TAIL03); // 0-7 bytes left.
5754   {
5755     ldrw(tmp1, Address(post(a1, 4)));
5756     ldrw(tmp2, Address(post(a2, 4)));
5757     eorw(tmp1, tmp1, tmp2);
5758     cbnzw(tmp1, DONE);
5759   }
5760   bind(TAIL03);
5761   tbz(cnt1, 1, TAIL01); // 0-3 bytes left.
5762   {
5763     ldrh(tmp1, Address(post(a1, 2)));
5764     ldrh(tmp2, Address(post(a2, 2)));
5765     eorw(tmp1, tmp1, tmp2);
5766     cbnzw(tmp1, DONE);
5767   }
5768   bind(TAIL01);
5769   if (elem_size == 1) { // Only needed when comparing 1-byte elements
5770     tbz(cnt1, 0, SAME); // 0-1 bytes left.
5771     {
5772       ldrb(tmp1, a1);
5773       ldrb(tmp2, a2);
5774       eorw(tmp1, tmp1, tmp2);
5775       cbnzw(tmp1, DONE);
5776     }
5777   }
5778   // Arrays are equal.
5779   bind(SAME);
5780   mov(result, true);
5781 
5782   // That's it.
5783   bind(DONE);
5784   BLOCK_COMMENT("} string_equals");
5785 }
5786 
5787 
5788 // The size of the blocks erased by the zero_blocks stub.  We must
5789 // handle anything smaller than this ourselves in zero_words().
5790 const int MacroAssembler::zero_words_block_size = 8;
5791 
5792 // zero_words() is used by C2 ClearArray patterns and by
5793 // C1_MacroAssembler.  It is as small as possible, handling small word
5794 // counts locally and delegating anything larger to the zero_blocks
5795 // stub.  It is expanded many times in compiled code, so it is
5796 // important to keep it short.
5797 
5798 // ptr:   Address of a buffer to be zeroed.
5799 // cnt:   Count in HeapWords.
5800 //
5801 // ptr, cnt, rscratch1, and rscratch2 are clobbered.
5802 address MacroAssembler::zero_words(Register ptr, Register cnt)
5803 {
5804   assert(is_power_of_2(zero_words_block_size), "adjust this");
5805 
5806   BLOCK_COMMENT("zero_words {");
5807   assert(ptr == r10 && cnt == r11, "mismatch in register usage");
5808   RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
5809   assert(zero_blocks.target() != nullptr, "zero_blocks stub has not been generated");
5810 
5811   subs(rscratch1, cnt, zero_words_block_size);
5812   Label around;
5813   br(LO, around);
5814   {
5815     RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
5816     assert(zero_blocks.target() != nullptr, "zero_blocks stub has not been generated");
5817     // Make sure this is a C2 compilation. C1 allocates space only for
5818     // trampoline stubs generated by Call LIR ops, and in any case it
5819     // makes sense for a C1 compilation task to proceed as quickly as
5820     // possible.
5821     CompileTask* task;
5822     if (StubRoutines::aarch64::complete()
5823         && Thread::current()->is_Compiler_thread()
5824         && (task = ciEnv::current()->task())
5825         && is_c2_compile(task->comp_level())) {
5826       address tpc = trampoline_call(zero_blocks);
5827       if (tpc == nullptr) {
5828         DEBUG_ONLY(reset_labels(around));
5829         return nullptr;
5830       }
5831     } else {
5832       far_call(zero_blocks);
5833     }
5834   }
5835   bind(around);
5836 
5837   // We have a few words left to do. zero_blocks has adjusted r10 and r11
5838   // for us.
5839   for (int i = zero_words_block_size >> 1; i > 1; i >>= 1) {
5840     Label l;
5841     tbz(cnt, exact_log2(i), l);
5842     for (int j = 0; j < i; j += 2) {
5843       stp(zr, zr, post(ptr, 2 * BytesPerWord));
5844     }
5845     bind(l);
5846   }
5847   {
5848     Label l;
5849     tbz(cnt, 0, l);
5850     str(zr, Address(ptr));
5851     bind(l);
5852   }
5853 
5854   BLOCK_COMMENT("} zero_words");
5855   return pc();
5856 }
5857 
5858 // base:         Address of a buffer to be zeroed, 8 bytes aligned.
5859 // cnt:          Immediate count in HeapWords.
5860 //
5861 // r10, r11, rscratch1, and rscratch2 are clobbered.
5862 address MacroAssembler::zero_words(Register base, uint64_t cnt)
5863 {
5864   assert(wordSize <= BlockZeroingLowLimit,
5865             "increase BlockZeroingLowLimit");
5866   address result = nullptr;
5867   if (cnt <= (uint64_t)BlockZeroingLowLimit / BytesPerWord) {
5868 #ifndef PRODUCT
5869     {
5870       char buf[64];
5871       snprintf(buf, sizeof buf, "zero_words (count = %" PRIu64 ") {", cnt);
5872       BLOCK_COMMENT(buf);
5873     }
5874 #endif
5875     if (cnt >= 16) {
5876       uint64_t loops = cnt/16;
5877       if (loops > 1) {
5878         mov(rscratch2, loops - 1);
5879       }
5880       {
5881         Label loop;
5882         bind(loop);
5883         for (int i = 0; i < 16; i += 2) {
5884           stp(zr, zr, Address(base, i * BytesPerWord));
5885         }
5886         add(base, base, 16 * BytesPerWord);
5887         if (loops > 1) {
5888           subs(rscratch2, rscratch2, 1);
5889           br(GE, loop);
5890         }
5891       }
5892     }
5893     cnt %= 16;
5894     int i = cnt & 1;  // store any odd word to start
5895     if (i) str(zr, Address(base));
5896     for (; i < (int)cnt; i += 2) {
5897       stp(zr, zr, Address(base, i * wordSize));
5898     }
5899     BLOCK_COMMENT("} zero_words");
5900     result = pc();
5901   } else {
5902     mov(r10, base); mov(r11, cnt);
5903     result = zero_words(r10, r11);
5904   }
5905   return result;
5906 }
5907 
5908 // Zero blocks of memory by using DC ZVA.
5909 //
5910 // Aligns the base address first sufficiently for DC ZVA, then uses
5911 // DC ZVA repeatedly for every full block.  cnt is the size to be
5912 // zeroed in HeapWords.  Returns the count of words left to be zeroed
5913 // in cnt.
5914 //
5915 // NOTE: This is intended to be used in the zero_blocks() stub.  If
5916 // you want to use it elsewhere, note that cnt must be >= 2*zva_length.
5917 void MacroAssembler::zero_dcache_blocks(Register base, Register cnt) {
5918   Register tmp = rscratch1;
5919   Register tmp2 = rscratch2;
5920   int zva_length = VM_Version::zva_length();
5921   Label initial_table_end, loop_zva;
5922   Label fini;
5923 
5924   // Base must be 16 byte aligned. If not just return and let caller handle it
5925   tst(base, 0x0f);
5926   br(Assembler::NE, fini);
5927   // Align base with ZVA length.
5928   neg(tmp, base);
5929   andr(tmp, tmp, zva_length - 1);
5930 
5931   // tmp: the number of bytes to be filled to align the base with ZVA length.
5932   add(base, base, tmp);
5933   sub(cnt, cnt, tmp, Assembler::ASR, 3);
5934   adr(tmp2, initial_table_end);
5935   sub(tmp2, tmp2, tmp, Assembler::LSR, 2);
5936   br(tmp2);
5937 
5938   for (int i = -zva_length + 16; i < 0; i += 16)
5939     stp(zr, zr, Address(base, i));
5940   bind(initial_table_end);
5941 
5942   sub(cnt, cnt, zva_length >> 3);
5943   bind(loop_zva);
5944   dc(Assembler::ZVA, base);
5945   subs(cnt, cnt, zva_length >> 3);
5946   add(base, base, zva_length);
5947   br(Assembler::GE, loop_zva);
5948   add(cnt, cnt, zva_length >> 3); // count not zeroed by DC ZVA
5949   bind(fini);
5950 }
5951 
5952 // base:   Address of a buffer to be filled, 8 bytes aligned.
5953 // cnt:    Count in 8-byte unit.
5954 // value:  Value to be filled with.
5955 // base will point to the end of the buffer after filling.
5956 void MacroAssembler::fill_words(Register base, Register cnt, Register value)
5957 {
5958 //  Algorithm:
5959 //
5960 //    if (cnt == 0) {
5961 //      return;
5962 //    }
5963 //    if ((p & 8) != 0) {
5964 //      *p++ = v;
5965 //    }
5966 //
5967 //    scratch1 = cnt & 14;
5968 //    cnt -= scratch1;
5969 //    p += scratch1;
5970 //    switch (scratch1 / 2) {
5971 //      do {
5972 //        cnt -= 16;
5973 //          p[-16] = v;
5974 //          p[-15] = v;
5975 //        case 7:
5976 //          p[-14] = v;
5977 //          p[-13] = v;
5978 //        case 6:
5979 //          p[-12] = v;
5980 //          p[-11] = v;
5981 //          // ...
5982 //        case 1:
5983 //          p[-2] = v;
5984 //          p[-1] = v;
5985 //        case 0:
5986 //          p += 16;
5987 //      } while (cnt);
5988 //    }
5989 //    if ((cnt & 1) == 1) {
5990 //      *p++ = v;
5991 //    }
5992 
5993   assert_different_registers(base, cnt, value, rscratch1, rscratch2);
5994 
5995   Label fini, skip, entry, loop;
5996   const int unroll = 8; // Number of stp instructions we'll unroll
5997 
5998   cbz(cnt, fini);
5999   tbz(base, 3, skip);
6000   str(value, Address(post(base, 8)));
6001   sub(cnt, cnt, 1);
6002   bind(skip);
6003 
6004   andr(rscratch1, cnt, (unroll-1) * 2);
6005   sub(cnt, cnt, rscratch1);
6006   add(base, base, rscratch1, Assembler::LSL, 3);
6007   adr(rscratch2, entry);
6008   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 1);
6009   br(rscratch2);
6010 
6011   bind(loop);
6012   add(base, base, unroll * 16);
6013   for (int i = -unroll; i < 0; i++)
6014     stp(value, value, Address(base, i * 16));
6015   bind(entry);
6016   subs(cnt, cnt, unroll * 2);
6017   br(Assembler::GE, loop);
6018 
6019   tbz(cnt, 0, fini);
6020   str(value, Address(post(base, 8)));
6021   bind(fini);
6022 }
6023 
6024 // Intrinsic for
6025 //
6026 // - sun/nio/cs/ISO_8859_1$Encoder.implEncodeISOArray
6027 //     return the number of characters copied.
6028 // - java/lang/StringUTF16.compress
6029 //     return zero (0) if copy fails, otherwise 'len'.
6030 //
6031 // This version always returns the number of characters copied, and does not
6032 // clobber the 'len' register. A successful copy will complete with the post-
6033 // condition: 'res' == 'len', while an unsuccessful copy will exit with the
6034 // post-condition: 0 <= 'res' < 'len'.
6035 //
6036 // NOTE: Attempts to use 'ld2' (and 'umaxv' in the ISO part) has proven to
6037 //       degrade performance (on Ampere Altra - Neoverse N1), to an extent
6038 //       beyond the acceptable, even though the footprint would be smaller.
6039 //       Using 'umaxv' in the ASCII-case comes with a small penalty but does
6040 //       avoid additional bloat.
6041 //
6042 // Clobbers: src, dst, res, rscratch1, rscratch2, rflags
6043 void MacroAssembler::encode_iso_array(Register src, Register dst,
6044                                       Register len, Register res, bool ascii,
6045                                       FloatRegister vtmp0, FloatRegister vtmp1,
6046                                       FloatRegister vtmp2, FloatRegister vtmp3,
6047                                       FloatRegister vtmp4, FloatRegister vtmp5)
6048 {
6049   Register cnt = res;
6050   Register max = rscratch1;
6051   Register chk = rscratch2;
6052 
6053   prfm(Address(src), PLDL1STRM);
6054   movw(cnt, len);
6055 
6056 #define ASCII(insn) do { if (ascii) { insn; } } while (0)
6057 
6058   Label LOOP_32, DONE_32, FAIL_32;
6059 
6060   BIND(LOOP_32);
6061   {
6062     cmpw(cnt, 32);
6063     br(LT, DONE_32);
6064     ld1(vtmp0, vtmp1, vtmp2, vtmp3, T8H, Address(post(src, 64)));
6065     // Extract lower bytes.
6066     FloatRegister vlo0 = vtmp4;
6067     FloatRegister vlo1 = vtmp5;
6068     uzp1(vlo0, T16B, vtmp0, vtmp1);
6069     uzp1(vlo1, T16B, vtmp2, vtmp3);
6070     // Merge bits...
6071     orr(vtmp0, T16B, vtmp0, vtmp1);
6072     orr(vtmp2, T16B, vtmp2, vtmp3);
6073     // Extract merged upper bytes.
6074     FloatRegister vhix = vtmp0;
6075     uzp2(vhix, T16B, vtmp0, vtmp2);
6076     // ISO-check on hi-parts (all zero).
6077     //                          ASCII-check on lo-parts (no sign).
6078     FloatRegister vlox = vtmp1; // Merge lower bytes.
6079                                 ASCII(orr(vlox, T16B, vlo0, vlo1));
6080     umov(chk, vhix, D, 1);      ASCII(cm(LT, vlox, T16B, vlox));
6081     fmovd(max, vhix);           ASCII(umaxv(vlox, T16B, vlox));
6082     orr(chk, chk, max);         ASCII(umov(max, vlox, B, 0));
6083                                 ASCII(orr(chk, chk, max));
6084     cbnz(chk, FAIL_32);
6085     subw(cnt, cnt, 32);
6086     st1(vlo0, vlo1, T16B, Address(post(dst, 32)));
6087     b(LOOP_32);
6088   }
6089   BIND(FAIL_32);
6090   sub(src, src, 64);
6091   BIND(DONE_32);
6092 
6093   Label LOOP_8, SKIP_8;
6094 
6095   BIND(LOOP_8);
6096   {
6097     cmpw(cnt, 8);
6098     br(LT, SKIP_8);
6099     FloatRegister vhi = vtmp0;
6100     FloatRegister vlo = vtmp1;
6101     ld1(vtmp3, T8H, src);
6102     uzp1(vlo, T16B, vtmp3, vtmp3);
6103     uzp2(vhi, T16B, vtmp3, vtmp3);
6104     // ISO-check on hi-parts (all zero).
6105     //                          ASCII-check on lo-parts (no sign).
6106                                 ASCII(cm(LT, vtmp2, T16B, vlo));
6107     fmovd(chk, vhi);            ASCII(umaxv(vtmp2, T16B, vtmp2));
6108                                 ASCII(umov(max, vtmp2, B, 0));
6109                                 ASCII(orr(chk, chk, max));
6110     cbnz(chk, SKIP_8);
6111 
6112     strd(vlo, Address(post(dst, 8)));
6113     subw(cnt, cnt, 8);
6114     add(src, src, 16);
6115     b(LOOP_8);
6116   }
6117   BIND(SKIP_8);
6118 
6119 #undef ASCII
6120 
6121   Label LOOP, DONE;
6122 
6123   cbz(cnt, DONE);
6124   BIND(LOOP);
6125   {
6126     Register chr = rscratch1;
6127     ldrh(chr, Address(post(src, 2)));
6128     tst(chr, ascii ? 0xff80 : 0xff00);
6129     br(NE, DONE);
6130     strb(chr, Address(post(dst, 1)));
6131     subs(cnt, cnt, 1);
6132     br(GT, LOOP);
6133   }
6134   BIND(DONE);
6135   // Return index where we stopped.
6136   subw(res, len, cnt);
6137 }
6138 
6139 // Inflate byte[] array to char[].
6140 // Clobbers: src, dst, len, rflags, rscratch1, v0-v6
6141 address MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
6142                                            FloatRegister vtmp1, FloatRegister vtmp2,
6143                                            FloatRegister vtmp3, Register tmp4) {
6144   Label big, done, after_init, to_stub;
6145 
6146   assert_different_registers(src, dst, len, tmp4, rscratch1);
6147 
6148   fmovd(vtmp1, 0.0);
6149   lsrw(tmp4, len, 3);
6150   bind(after_init);
6151   cbnzw(tmp4, big);
6152   // Short string: less than 8 bytes.
6153   {
6154     Label loop, tiny;
6155 
6156     cmpw(len, 4);
6157     br(LT, tiny);
6158     // Use SIMD to do 4 bytes.
6159     ldrs(vtmp2, post(src, 4));
6160     zip1(vtmp3, T8B, vtmp2, vtmp1);
6161     subw(len, len, 4);
6162     strd(vtmp3, post(dst, 8));
6163 
6164     cbzw(len, done);
6165 
6166     // Do the remaining bytes by steam.
6167     bind(loop);
6168     ldrb(tmp4, post(src, 1));
6169     strh(tmp4, post(dst, 2));
6170     subw(len, len, 1);
6171 
6172     bind(tiny);
6173     cbnz(len, loop);
6174 
6175     b(done);
6176   }
6177 
6178   if (SoftwarePrefetchHintDistance >= 0) {
6179     bind(to_stub);
6180       RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_byte_array_inflate());
6181       assert(stub.target() != nullptr, "large_byte_array_inflate stub has not been generated");
6182       address tpc = trampoline_call(stub);
6183       if (tpc == nullptr) {
6184         DEBUG_ONLY(reset_labels(big, done));
6185         postcond(pc() == badAddress);
6186         return nullptr;
6187       }
6188       b(after_init);
6189   }
6190 
6191   // Unpack the bytes 8 at a time.
6192   bind(big);
6193   {
6194     Label loop, around, loop_last, loop_start;
6195 
6196     if (SoftwarePrefetchHintDistance >= 0) {
6197       const int large_loop_threshold = (64 + 16)/8;
6198       ldrd(vtmp2, post(src, 8));
6199       andw(len, len, 7);
6200       cmp(tmp4, (u1)large_loop_threshold);
6201       br(GE, to_stub);
6202       b(loop_start);
6203 
6204       bind(loop);
6205       ldrd(vtmp2, post(src, 8));
6206       bind(loop_start);
6207       subs(tmp4, tmp4, 1);
6208       br(EQ, loop_last);
6209       zip1(vtmp2, T16B, vtmp2, vtmp1);
6210       ldrd(vtmp3, post(src, 8));
6211       st1(vtmp2, T8H, post(dst, 16));
6212       subs(tmp4, tmp4, 1);
6213       zip1(vtmp3, T16B, vtmp3, vtmp1);
6214       st1(vtmp3, T8H, post(dst, 16));
6215       br(NE, loop);
6216       b(around);
6217       bind(loop_last);
6218       zip1(vtmp2, T16B, vtmp2, vtmp1);
6219       st1(vtmp2, T8H, post(dst, 16));
6220       bind(around);
6221       cbz(len, done);
6222     } else {
6223       andw(len, len, 7);
6224       bind(loop);
6225       ldrd(vtmp2, post(src, 8));
6226       sub(tmp4, tmp4, 1);
6227       zip1(vtmp3, T16B, vtmp2, vtmp1);
6228       st1(vtmp3, T8H, post(dst, 16));
6229       cbnz(tmp4, loop);
6230     }
6231   }
6232 
6233   // Do the tail of up to 8 bytes.
6234   add(src, src, len);
6235   ldrd(vtmp3, Address(src, -8));
6236   add(dst, dst, len, ext::uxtw, 1);
6237   zip1(vtmp3, T16B, vtmp3, vtmp1);
6238   strq(vtmp3, Address(dst, -16));
6239 
6240   bind(done);
6241   postcond(pc() != badAddress);
6242   return pc();
6243 }
6244 
6245 // Compress char[] array to byte[].
6246 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
6247                                          Register res,
6248                                          FloatRegister tmp0, FloatRegister tmp1,
6249                                          FloatRegister tmp2, FloatRegister tmp3,
6250                                          FloatRegister tmp4, FloatRegister tmp5) {
6251   encode_iso_array(src, dst, len, res, false, tmp0, tmp1, tmp2, tmp3, tmp4, tmp5);
6252   // Adjust result: res == len ? len : 0
6253   cmp(len, res);
6254   csel(res, res, zr, EQ);
6255 }
6256 
6257 // java.math.round(double a)
6258 // Returns the closest long to the argument, with ties rounding to
6259 // positive infinity.  This requires some fiddling for corner
6260 // cases. We take care to avoid double rounding in e.g. (jlong)(a + 0.5).
6261 void MacroAssembler::java_round_double(Register dst, FloatRegister src,
6262                                        FloatRegister ftmp) {
6263   Label DONE;
6264   BLOCK_COMMENT("java_round_double: { ");
6265   fmovd(rscratch1, src);
6266   // Use RoundToNearestTiesAway unless src small and -ve.
6267   fcvtasd(dst, src);
6268   // Test if src >= 0 || abs(src) >= 0x1.0p52
6269   eor(rscratch1, rscratch1, UCONST64(1) << 63); // flip sign bit
6270   mov(rscratch2, julong_cast(0x1.0p52));
6271   cmp(rscratch1, rscratch2);
6272   br(HS, DONE); {
6273     // src < 0 && abs(src) < 0x1.0p52
6274     // src may have a fractional part, so add 0.5
6275     fmovd(ftmp, 0.5);
6276     faddd(ftmp, src, ftmp);
6277     // Convert double to jlong, use RoundTowardsNegative
6278     fcvtmsd(dst, ftmp);
6279   }
6280   bind(DONE);
6281   BLOCK_COMMENT("} java_round_double");
6282 }
6283 
6284 void MacroAssembler::java_round_float(Register dst, FloatRegister src,
6285                                       FloatRegister ftmp) {
6286   Label DONE;
6287   BLOCK_COMMENT("java_round_float: { ");
6288   fmovs(rscratch1, src);
6289   // Use RoundToNearestTiesAway unless src small and -ve.
6290   fcvtassw(dst, src);
6291   // Test if src >= 0 || abs(src) >= 0x1.0p23
6292   eor(rscratch1, rscratch1, 0x80000000); // flip sign bit
6293   mov(rscratch2, jint_cast(0x1.0p23f));
6294   cmp(rscratch1, rscratch2);
6295   br(HS, DONE); {
6296     // src < 0 && |src| < 0x1.0p23
6297     // src may have a fractional part, so add 0.5
6298     fmovs(ftmp, 0.5f);
6299     fadds(ftmp, src, ftmp);
6300     // Convert float to jint, use RoundTowardsNegative
6301     fcvtmssw(dst, ftmp);
6302   }
6303   bind(DONE);
6304   BLOCK_COMMENT("} java_round_float");
6305 }
6306 
6307 // get_thread() can be called anywhere inside generated code so we
6308 // need to save whatever non-callee save context might get clobbered
6309 // by the call to JavaThread::aarch64_get_thread_helper() or, indeed,
6310 // the call setup code.
6311 //
6312 // On Linux, aarch64_get_thread_helper() clobbers only r0, r1, and flags.
6313 // On other systems, the helper is a usual C function.
6314 //
6315 void MacroAssembler::get_thread(Register dst) {
6316   RegSet saved_regs =
6317     LINUX_ONLY(RegSet::range(r0, r1)  + lr - dst)
6318     NOT_LINUX (RegSet::range(r0, r17) + lr - dst);
6319 
6320   protect_return_address();
6321   push(saved_regs, sp);
6322 
6323   mov(lr, CAST_FROM_FN_PTR(address, JavaThread::aarch64_get_thread_helper));
6324   blr(lr);
6325   if (dst != c_rarg0) {
6326     mov(dst, c_rarg0);
6327   }
6328 
6329   pop(saved_regs, sp);
6330   authenticate_return_address();
6331 }
6332 
6333 #ifdef COMPILER2
6334 // C2 compiled method's prolog code
6335 // Moved here from aarch64.ad to support Valhalla code belows
6336 void MacroAssembler::verified_entry(Compile* C, int sp_inc) {
6337   if (C->clinit_barrier_on_entry()) {
6338     assert(!C->method()->holder()->is_not_initialized(), "initialization should have been started");
6339 
6340     Label L_skip_barrier;
6341 
6342     mov_metadata(rscratch2, C->method()->holder()->constant_encoding());
6343     clinit_barrier(rscratch2, rscratch1, &L_skip_barrier);
6344     far_jump(RuntimeAddress(SharedRuntime::get_handle_wrong_method_stub()));
6345     bind(L_skip_barrier);
6346   }
6347 
6348   if (C->max_vector_size() > 0) {
6349     reinitialize_ptrue();
6350   }
6351 
6352   int bangsize = C->output()->bang_size_in_bytes();
6353   if (C->output()->need_stack_bang(bangsize))
6354     generate_stack_overflow_check(bangsize);
6355 
6356   // n.b. frame size includes space for return pc and rfp
6357   const long framesize = C->output()->frame_size_in_bytes();
6358   build_frame(framesize);
6359 
6360   if (C->needs_stack_repair()) {
6361     save_stack_increment(sp_inc, framesize);
6362   }
6363 
6364   if (VerifyStackAtCalls) {
6365     Unimplemented();
6366   }
6367 }
6368 #endif // COMPILER2
6369 
6370 int MacroAssembler::store_inline_type_fields_to_buf(ciInlineKlass* vk, bool from_interpreter) {
6371   assert(InlineTypeReturnedAsFields, "Inline types should never be returned as fields");
6372   // An inline type might be returned. If fields are in registers we
6373   // need to allocate an inline type instance and initialize it with
6374   // the value of the fields.
6375   Label skip;
6376   // We only need a new buffered inline type if a new one is not returned
6377   tbz(r0, 0, skip);
6378   int call_offset = -1;
6379 
6380   // Be careful not to clobber r1-7 which hold returned fields
6381   // Also do not use callee-saved registers as these may be live in the interpreter
6382   Register tmp1 = r13, tmp2 = r14, klass = r15, r0_preserved = r12;
6383 
6384   // The following code is similar to allocate_instance but has some slight differences,
6385   // e.g. object size is always not zero, sometimes it's constant; storing klass ptr after
6386   // allocating is not necessary if vk != nullptr, etc. allocate_instance is not aware of these.
6387   Label slow_case;
6388   // 1. Try to allocate a new buffered inline instance either from TLAB or eden space
6389   mov(r0_preserved, r0); // save r0 for slow_case since *_allocate may corrupt it when allocation failed
6390 
6391   if (vk != nullptr) {
6392     // Called from C1, where the return type is statically known.
6393     movptr(klass, (intptr_t)vk->get_InlineKlass());
6394     jint obj_size = vk->layout_helper();
6395     assert(obj_size != Klass::_lh_neutral_value, "inline class in return type must have been resolved");
6396     if (UseTLAB) {
6397       tlab_allocate(r0, noreg, obj_size, tmp1, tmp2, slow_case);
6398     } else {
6399       b(slow_case);
6400     }
6401   } else {
6402     // Call from interpreter. R0 contains ((the InlineKlass* of the return type) | 0x01)
6403     andr(klass, r0, -2);
6404     ldrw(tmp2, Address(klass, Klass::layout_helper_offset()));
6405     if (UseTLAB) {
6406       tlab_allocate(r0, tmp2, 0, tmp1, tmp2, slow_case);
6407     } else {
6408       b(slow_case);
6409     }
6410   }
6411   if (UseTLAB) {
6412     // 2. Initialize buffered inline instance header
6413     Register buffer_obj = r0;
6414     mov(rscratch1, (intptr_t)markWord::inline_type_prototype().value());
6415     str(rscratch1, Address(buffer_obj, oopDesc::mark_offset_in_bytes()));
6416     store_klass_gap(buffer_obj, zr);
6417     if (vk == nullptr) {
6418       // store_klass corrupts klass, so save it for later use (interpreter case only).
6419       mov(tmp1, klass);
6420     }
6421     store_klass(buffer_obj, klass);
6422     // 3. Initialize its fields with an inline class specific handler
6423     if (vk != nullptr) {
6424       far_call(RuntimeAddress(vk->pack_handler())); // no need for call info as this will not safepoint.
6425     } else {
6426       // tmp1 holds klass preserved above
6427       ldr(tmp1, Address(tmp1, InstanceKlass::adr_inlineklass_fixed_block_offset()));
6428       ldr(tmp1, Address(tmp1, InlineKlass::pack_handler_offset()));
6429       blr(tmp1);
6430     }
6431 
6432     membar(Assembler::StoreStore);
6433     b(skip);
6434   } else {
6435     // Must have already branched to slow_case above.
6436     DEBUG_ONLY(should_not_reach_here());
6437   }
6438   bind(slow_case);
6439   // We failed to allocate a new inline type, fall back to a runtime
6440   // call. Some oop field may be live in some registers but we can't
6441   // tell. That runtime call will take care of preserving them
6442   // across a GC if there's one.
6443   mov(r0, r0_preserved);
6444 
6445   if (from_interpreter) {
6446     super_call_VM_leaf(StubRoutines::store_inline_type_fields_to_buf());
6447   } else {
6448     far_call(RuntimeAddress(StubRoutines::store_inline_type_fields_to_buf()));
6449     call_offset = offset();
6450   }
6451   membar(Assembler::StoreStore);
6452 
6453   bind(skip);
6454   return call_offset;
6455 }
6456 
6457 // Move a value between registers/stack slots and update the reg_state
6458 bool MacroAssembler::move_helper(VMReg from, VMReg to, BasicType bt, RegState reg_state[]) {
6459   assert(from->is_valid() && to->is_valid(), "source and destination must be valid");
6460   if (reg_state[to->value()] == reg_written) {
6461     return true; // Already written
6462   }
6463 
6464   if (from != to && bt != T_VOID) {
6465     if (reg_state[to->value()] == reg_readonly) {
6466       return false; // Not yet writable
6467     }
6468     if (from->is_reg()) {
6469       if (to->is_reg()) {
6470         if (from->is_Register() && to->is_Register()) {
6471           mov(to->as_Register(), from->as_Register());
6472         } else if (from->is_FloatRegister() && to->is_FloatRegister()) {
6473           fmovd(to->as_FloatRegister(), from->as_FloatRegister());
6474         } else {
6475           ShouldNotReachHere();
6476         }
6477       } else {
6478         int st_off = to->reg2stack() * VMRegImpl::stack_slot_size;
6479         Address to_addr = Address(sp, st_off);
6480         if (from->is_FloatRegister()) {
6481           if (bt == T_DOUBLE) {
6482              strd(from->as_FloatRegister(), to_addr);
6483           } else {
6484              assert(bt == T_FLOAT, "must be float");
6485              strs(from->as_FloatRegister(), to_addr);
6486           }
6487         } else {
6488           str(from->as_Register(), to_addr);
6489         }
6490       }
6491     } else {
6492       Address from_addr = Address(sp, from->reg2stack() * VMRegImpl::stack_slot_size);
6493       if (to->is_reg()) {
6494         if (to->is_FloatRegister()) {
6495           if (bt == T_DOUBLE) {
6496             ldrd(to->as_FloatRegister(), from_addr);
6497           } else {
6498             assert(bt == T_FLOAT, "must be float");
6499             ldrs(to->as_FloatRegister(), from_addr);
6500           }
6501         } else {
6502           ldr(to->as_Register(), from_addr);
6503         }
6504       } else {
6505         int st_off = to->reg2stack() * VMRegImpl::stack_slot_size;
6506         ldr(rscratch1, from_addr);
6507         str(rscratch1, Address(sp, st_off));
6508       }
6509     }
6510   }
6511 
6512   // Update register states
6513   reg_state[from->value()] = reg_writable;
6514   reg_state[to->value()] = reg_written;
6515   return true;
6516 }
6517 
6518 // Calculate the extra stack space required for packing or unpacking inline
6519 // args and adjust the stack pointer
6520 int MacroAssembler::extend_stack_for_inline_args(int args_on_stack) {
6521   int sp_inc = args_on_stack * VMRegImpl::stack_slot_size;
6522   sp_inc = align_up(sp_inc, StackAlignmentInBytes);
6523   assert(sp_inc > 0, "sanity");
6524 
6525   // Save a copy of the FP and LR here for deoptimization patching and frame walking
6526   stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
6527 
6528   // Adjust the stack pointer. This will be repaired on return by MacroAssembler::remove_frame
6529   if (sp_inc < (1 << 9)) {
6530     sub(sp, sp, sp_inc);   // Fits in an immediate
6531   } else {
6532     mov(rscratch1, sp_inc);
6533     sub(sp, sp, rscratch1);
6534   }
6535 
6536   return sp_inc + 2 * wordSize;  // Account for the FP/LR space
6537 }
6538 
6539 // Read all fields from an inline type oop and store the values in registers/stack slots
6540 bool MacroAssembler::unpack_inline_helper(const GrowableArray<SigEntry>* sig, int& sig_index,
6541                                           VMReg from, int& from_index, VMRegPair* to, int to_count, int& to_index,
6542                                           RegState reg_state[]) {
6543   assert(sig->at(sig_index)._bt == T_VOID, "should be at end delimiter");
6544   assert(from->is_valid(), "source must be valid");
6545   bool progress = false;
6546 #ifdef ASSERT
6547   const int start_offset = offset();
6548 #endif
6549 
6550   Label L_null, L_notNull;
6551   // Don't use r14 as tmp because it's used for spilling (see MacroAssembler::spill_reg_for)
6552   Register tmp1 = r10;
6553   Register tmp2 = r11;
6554   Register fromReg = noreg;
6555   ScalarizedInlineArgsStream stream(sig, sig_index, to, to_count, to_index, -1);
6556   bool done = true;
6557   bool mark_done = true;
6558   VMReg toReg;
6559   BasicType bt;
6560   // Check if argument requires a null check
6561   bool null_check = false;
6562   VMReg nullCheckReg;
6563   while (stream.next(nullCheckReg, bt)) {
6564     if (sig->at(stream.sig_index())._offset == -1) {
6565       null_check = true;
6566       break;
6567     }
6568   }
6569   stream.reset(sig_index, to_index);
6570   while (stream.next(toReg, bt)) {
6571     assert(toReg->is_valid(), "destination must be valid");
6572     int idx = (int)toReg->value();
6573     if (reg_state[idx] == reg_readonly) {
6574       if (idx != from->value()) {
6575         mark_done = false;
6576       }
6577       done = false;
6578       continue;
6579     } else if (reg_state[idx] == reg_written) {
6580       continue;
6581     }
6582     assert(reg_state[idx] == reg_writable, "must be writable");
6583     reg_state[idx] = reg_written;
6584     progress = true;
6585 
6586     if (fromReg == noreg) {
6587       if (from->is_reg()) {
6588         fromReg = from->as_Register();
6589       } else {
6590         int st_off = from->reg2stack() * VMRegImpl::stack_slot_size;
6591         ldr(tmp1, Address(sp, st_off));
6592         fromReg = tmp1;
6593       }
6594       if (null_check) {
6595         // Nullable inline type argument, emit null check
6596         cbz(fromReg, L_null);
6597       }
6598     }
6599     int off = sig->at(stream.sig_index())._offset;
6600     if (off == -1) {
6601       assert(null_check, "Missing null check at");
6602       if (toReg->is_stack()) {
6603         int st_off = toReg->reg2stack() * VMRegImpl::stack_slot_size;
6604         mov(tmp2, 1);
6605         str(tmp2, Address(sp, st_off));
6606       } else {
6607         mov(toReg->as_Register(), 1);
6608       }
6609       continue;
6610     }
6611     assert(off > 0, "offset in object should be positive");
6612     Address fromAddr = Address(fromReg, off);
6613     if (!toReg->is_FloatRegister()) {
6614       Register dst = toReg->is_stack() ? tmp2 : toReg->as_Register();
6615       if (is_reference_type(bt)) {
6616         load_heap_oop(dst, fromAddr, rscratch1, rscratch2);
6617       } else {
6618         bool is_signed = (bt != T_CHAR) && (bt != T_BOOLEAN);
6619         load_sized_value(dst, fromAddr, type2aelembytes(bt), is_signed);
6620       }
6621       if (toReg->is_stack()) {
6622         int st_off = toReg->reg2stack() * VMRegImpl::stack_slot_size;
6623         str(dst, Address(sp, st_off));
6624       }
6625     } else if (bt == T_DOUBLE) {
6626       ldrd(toReg->as_FloatRegister(), fromAddr);
6627     } else {
6628       assert(bt == T_FLOAT, "must be float");
6629       ldrs(toReg->as_FloatRegister(), fromAddr);
6630     }
6631   }
6632   if (progress && null_check) {
6633     if (done) {
6634       b(L_notNull);
6635       bind(L_null);
6636       // Set IsInit field to zero to signal that the argument is null.
6637       // Also set all oop fields to zero to make the GC happy.
6638       stream.reset(sig_index, to_index);
6639       while (stream.next(toReg, bt)) {
6640         if (sig->at(stream.sig_index())._offset == -1 ||
6641             bt == T_OBJECT || bt == T_ARRAY) {
6642           if (toReg->is_stack()) {
6643             int st_off = toReg->reg2stack() * VMRegImpl::stack_slot_size;
6644             str(zr, Address(sp, st_off));
6645           } else {
6646             mov(toReg->as_Register(), zr);
6647           }
6648         }
6649       }
6650       bind(L_notNull);
6651     } else {
6652       bind(L_null);
6653     }
6654   }
6655 
6656   sig_index = stream.sig_index();
6657   to_index = stream.regs_index();
6658 
6659   if (mark_done && reg_state[from->value()] != reg_written) {
6660     // This is okay because no one else will write to that slot
6661     reg_state[from->value()] = reg_writable;
6662   }
6663   from_index--;
6664   assert(progress || (start_offset == offset()), "should not emit code");
6665   return done;
6666 }
6667 
6668 // Pack fields back into an inline type oop
6669 bool MacroAssembler::pack_inline_helper(const GrowableArray<SigEntry>* sig, int& sig_index, int vtarg_index,
6670                                         VMRegPair* from, int from_count, int& from_index, VMReg to,
6671                                         RegState reg_state[], Register val_array) {
6672   assert(sig->at(sig_index)._bt == T_METADATA, "should be at delimiter");
6673   assert(to->is_valid(), "destination must be valid");
6674 
6675   if (reg_state[to->value()] == reg_written) {
6676     skip_unpacked_fields(sig, sig_index, from, from_count, from_index);
6677     return true; // Already written
6678   }
6679 
6680   // The GC barrier expanded by store_heap_oop below may call into the
6681   // runtime so use callee-saved registers for any values that need to be
6682   // preserved. The GC barrier assembler should take care of saving the
6683   // Java argument registers.
6684   // TODO 8284443 Isn't it an issue if below code uses r14 as tmp when it contains a spilled value?
6685   // Be careful with r14 because it's used for spilling (see MacroAssembler::spill_reg_for).
6686   Register val_obj_tmp = r21;
6687   Register from_reg_tmp = r22;
6688   Register tmp1 = r14;
6689   Register tmp2 = r13;
6690   Register tmp3 = r12;
6691   Register val_obj = to->is_stack() ? val_obj_tmp : to->as_Register();
6692 
6693   assert_different_registers(val_obj_tmp, from_reg_tmp, tmp1, tmp2, tmp3, val_array);
6694 
6695   if (reg_state[to->value()] == reg_readonly) {
6696     if (!is_reg_in_unpacked_fields(sig, sig_index, to, from, from_count, from_index)) {
6697       skip_unpacked_fields(sig, sig_index, from, from_count, from_index);
6698       return false; // Not yet writable
6699     }
6700     val_obj = val_obj_tmp;
6701   }
6702 
6703   int index = arrayOopDesc::base_offset_in_bytes(T_OBJECT) + vtarg_index * type2aelembytes(T_OBJECT);
6704   load_heap_oop(val_obj, Address(val_array, index), tmp1, tmp2);
6705 
6706   ScalarizedInlineArgsStream stream(sig, sig_index, from, from_count, from_index);
6707   VMReg fromReg;
6708   BasicType bt;
6709   Label L_null;
6710   while (stream.next(fromReg, bt)) {
6711     assert(fromReg->is_valid(), "source must be valid");
6712     reg_state[fromReg->value()] = reg_writable;
6713 
6714     int off = sig->at(stream.sig_index())._offset;
6715     if (off == -1) {
6716       // Nullable inline type argument, emit null check
6717       Label L_notNull;
6718       if (fromReg->is_stack()) {
6719         int ld_off = fromReg->reg2stack() * VMRegImpl::stack_slot_size;
6720         ldrb(tmp2, Address(sp, ld_off));
6721         cbnz(tmp2, L_notNull);
6722       } else {
6723         cbnz(fromReg->as_Register(), L_notNull);
6724       }
6725       mov(val_obj, 0);
6726       b(L_null);
6727       bind(L_notNull);
6728       continue;
6729     }
6730 
6731     assert(off > 0, "offset in object should be positive");
6732     size_t size_in_bytes = is_java_primitive(bt) ? type2aelembytes(bt) : wordSize;
6733 
6734     // Pack the scalarized field into the value object.
6735     Address dst(val_obj, off);
6736 
6737     if (!fromReg->is_FloatRegister()) {
6738       Register src;
6739       if (fromReg->is_stack()) {
6740         src = from_reg_tmp;
6741         int ld_off = fromReg->reg2stack() * VMRegImpl::stack_slot_size;
6742         load_sized_value(src, Address(sp, ld_off), size_in_bytes, /* is_signed */ false);
6743       } else {
6744         src = fromReg->as_Register();
6745       }
6746       assert_different_registers(dst.base(), src, tmp1, tmp2, tmp3, val_array);
6747       if (is_reference_type(bt)) {
6748         store_heap_oop(dst, src, tmp1, tmp2, tmp3, IN_HEAP | ACCESS_WRITE | IS_DEST_UNINITIALIZED);
6749       } else {
6750         store_sized_value(dst, src, size_in_bytes);
6751       }
6752     } else if (bt == T_DOUBLE) {
6753       strd(fromReg->as_FloatRegister(), dst);
6754     } else {
6755       assert(bt == T_FLOAT, "must be float");
6756       strs(fromReg->as_FloatRegister(), dst);
6757     }
6758   }
6759   bind(L_null);
6760   sig_index = stream.sig_index();
6761   from_index = stream.regs_index();
6762 
6763   assert(reg_state[to->value()] == reg_writable, "must have already been read");
6764   bool success = move_helper(val_obj->as_VMReg(), to, T_OBJECT, reg_state);
6765   assert(success, "to register must be writeable");
6766 
6767   return true;
6768 }
6769 
6770 VMReg MacroAssembler::spill_reg_for(VMReg reg) {
6771   return (reg->is_FloatRegister()) ? v8->as_VMReg() : r14->as_VMReg();
6772 }
6773 
6774 void MacroAssembler::cache_wb(Address line) {
6775   assert(line.getMode() == Address::base_plus_offset, "mode should be base_plus_offset");
6776   assert(line.index() == noreg, "index should be noreg");
6777   assert(line.offset() == 0, "offset should be 0");
6778   // would like to assert this
6779   // assert(line._ext.shift == 0, "shift should be zero");
6780   if (VM_Version::supports_dcpop()) {
6781     // writeback using clear virtual address to point of persistence
6782     dc(Assembler::CVAP, line.base());
6783   } else {
6784     // no need to generate anything as Unsafe.writebackMemory should
6785     // never invoke this stub
6786   }
6787 }
6788 
6789 void MacroAssembler::cache_wbsync(bool is_pre) {
6790   // we only need a barrier post sync
6791   if (!is_pre) {
6792     membar(Assembler::AnyAny);
6793   }
6794 }
6795 
6796 void MacroAssembler::verify_sve_vector_length(Register tmp) {
6797   // Make sure that native code does not change SVE vector length.
6798   if (!UseSVE) return;
6799   Label verify_ok;
6800   movw(tmp, zr);
6801   sve_inc(tmp, B);
6802   subsw(zr, tmp, VM_Version::get_initial_sve_vector_length());
6803   br(EQ, verify_ok);
6804   stop("Error: SVE vector length has changed since jvm startup");
6805   bind(verify_ok);
6806 }
6807 
6808 void MacroAssembler::verify_ptrue() {
6809   Label verify_ok;
6810   if (!UseSVE) {
6811     return;
6812   }
6813   sve_cntp(rscratch1, B, ptrue, ptrue); // get true elements count.
6814   sve_dec(rscratch1, B);
6815   cbz(rscratch1, verify_ok);
6816   stop("Error: the preserved predicate register (p7) elements are not all true");
6817   bind(verify_ok);
6818 }
6819 
6820 void MacroAssembler::safepoint_isb() {
6821   isb();
6822 #ifndef PRODUCT
6823   if (VerifyCrossModifyFence) {
6824     // Clear the thread state.
6825     strb(zr, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
6826   }
6827 #endif
6828 }
6829 
6830 #ifndef PRODUCT
6831 void MacroAssembler::verify_cross_modify_fence_not_required() {
6832   if (VerifyCrossModifyFence) {
6833     // Check if thread needs a cross modify fence.
6834     ldrb(rscratch1, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
6835     Label fence_not_required;
6836     cbz(rscratch1, fence_not_required);
6837     // If it does then fail.
6838     lea(rscratch1, CAST_FROM_FN_PTR(address, JavaThread::verify_cross_modify_fence_failure));
6839     mov(c_rarg0, rthread);
6840     blr(rscratch1);
6841     bind(fence_not_required);
6842   }
6843 }
6844 #endif
6845 
6846 void MacroAssembler::spin_wait() {
6847   for (int i = 0; i < VM_Version::spin_wait_desc().inst_count(); ++i) {
6848     switch (VM_Version::spin_wait_desc().inst()) {
6849       case SpinWait::NOP:
6850         nop();
6851         break;
6852       case SpinWait::ISB:
6853         isb();
6854         break;
6855       case SpinWait::YIELD:
6856         yield();
6857         break;
6858       default:
6859         ShouldNotReachHere();
6860     }
6861   }
6862 }
6863 
6864 // Stack frame creation/removal
6865 
6866 void MacroAssembler::enter(bool strip_ret_addr) {
6867   if (strip_ret_addr) {
6868     // Addresses can only be signed once. If there are multiple nested frames being created
6869     // in the same function, then the return address needs stripping first.
6870     strip_return_address();
6871   }
6872   protect_return_address();
6873   stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
6874   mov(rfp, sp);
6875 }
6876 
6877 void MacroAssembler::leave() {
6878   mov(sp, rfp);
6879   ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
6880   authenticate_return_address();
6881 }
6882 
6883 // ROP Protection
6884 // Use the AArch64 PAC feature to add ROP protection for generated code. Use whenever creating/
6885 // destroying stack frames or whenever directly loading/storing the LR to memory.
6886 // If ROP protection is not set then these functions are no-ops.
6887 // For more details on PAC see pauth_aarch64.hpp.
6888 
6889 // Sign the LR. Use during construction of a stack frame, before storing the LR to memory.
6890 // Uses value zero as the modifier.
6891 //
6892 void MacroAssembler::protect_return_address() {
6893   if (VM_Version::use_rop_protection()) {
6894     check_return_address();
6895     paciaz();
6896   }
6897 }
6898 
6899 // Sign the return value in the given register. Use before updating the LR in the existing stack
6900 // frame for the current function.
6901 // Uses value zero as the modifier.
6902 //
6903 void MacroAssembler::protect_return_address(Register return_reg) {
6904   if (VM_Version::use_rop_protection()) {
6905     check_return_address(return_reg);
6906     paciza(return_reg);
6907   }
6908 }
6909 
6910 // Authenticate the LR. Use before function return, after restoring FP and loading LR from memory.
6911 // Uses value zero as the modifier.
6912 //
6913 void MacroAssembler::authenticate_return_address() {
6914   if (VM_Version::use_rop_protection()) {
6915     autiaz();
6916     check_return_address();
6917   }
6918 }
6919 
6920 // Authenticate the return value in the given register. Use before updating the LR in the existing
6921 // stack frame for the current function.
6922 // Uses value zero as the modifier.
6923 //
6924 void MacroAssembler::authenticate_return_address(Register return_reg) {
6925   if (VM_Version::use_rop_protection()) {
6926     autiza(return_reg);
6927     check_return_address(return_reg);
6928   }
6929 }
6930 
6931 // Strip any PAC data from LR without performing any authentication. Use with caution - only if
6932 // there is no guaranteed way of authenticating the LR.
6933 //
6934 void MacroAssembler::strip_return_address() {
6935   if (VM_Version::use_rop_protection()) {
6936     xpaclri();
6937   }
6938 }
6939 
6940 #ifndef PRODUCT
6941 // PAC failures can be difficult to debug. After an authentication failure, a segfault will only
6942 // occur when the pointer is used - ie when the program returns to the invalid LR. At this point
6943 // it is difficult to debug back to the callee function.
6944 // This function simply loads from the address in the given register.
6945 // Use directly after authentication to catch authentication failures.
6946 // Also use before signing to check that the pointer is valid and hasn't already been signed.
6947 //
6948 void MacroAssembler::check_return_address(Register return_reg) {
6949   if (VM_Version::use_rop_protection()) {
6950     ldr(zr, Address(return_reg));
6951   }
6952 }
6953 #endif
6954 
6955 // The java_calling_convention describes stack locations as ideal slots on
6956 // a frame with no abi restrictions. Since we must observe abi restrictions
6957 // (like the placement of the register window) the slots must be biased by
6958 // the following value.
6959 static int reg2offset_in(VMReg r) {
6960   // Account for saved rfp and lr
6961   // This should really be in_preserve_stack_slots
6962   return (r->reg2stack() + 4) * VMRegImpl::stack_slot_size;
6963 }
6964 
6965 static int reg2offset_out(VMReg r) {
6966   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
6967 }
6968 
6969 // On 64bit we will store integer like items to the stack as
6970 // 64bits items (AArch64 ABI) even though java would only store
6971 // 32bits for a parameter. On 32bit it will simply be 32bits
6972 // So this routine will do 32->32 on 32bit and 32->64 on 64bit
6973 void MacroAssembler::move32_64(VMRegPair src, VMRegPair dst, Register tmp) {
6974   if (src.first()->is_stack()) {
6975     if (dst.first()->is_stack()) {
6976       // stack to stack
6977       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
6978       str(tmp, Address(sp, reg2offset_out(dst.first())));
6979     } else {
6980       // stack to reg
6981       ldrsw(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
6982     }
6983   } else if (dst.first()->is_stack()) {
6984     // reg to stack
6985     str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
6986   } else {
6987     if (dst.first() != src.first()) {
6988       sxtw(dst.first()->as_Register(), src.first()->as_Register());
6989     }
6990   }
6991 }
6992 
6993 // An oop arg. Must pass a handle not the oop itself
6994 void MacroAssembler::object_move(
6995                         OopMap* map,
6996                         int oop_handle_offset,
6997                         int framesize_in_slots,
6998                         VMRegPair src,
6999                         VMRegPair dst,
7000                         bool is_receiver,
7001                         int* receiver_offset) {
7002 
7003   // must pass a handle. First figure out the location we use as a handle
7004 
7005   Register rHandle = dst.first()->is_stack() ? rscratch2 : dst.first()->as_Register();
7006 
7007   // See if oop is null if it is we need no handle
7008 
7009   if (src.first()->is_stack()) {
7010 
7011     // Oop is already on the stack as an argument
7012     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
7013     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
7014     if (is_receiver) {
7015       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
7016     }
7017 
7018     ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
7019     lea(rHandle, Address(rfp, reg2offset_in(src.first())));
7020     // conditionally move a null
7021     cmp(rscratch1, zr);
7022     csel(rHandle, zr, rHandle, Assembler::EQ);
7023   } else {
7024 
7025     // Oop is in an a register we must store it to the space we reserve
7026     // on the stack for oop_handles and pass a handle if oop is non-null
7027 
7028     const Register rOop = src.first()->as_Register();
7029     int oop_slot;
7030     if (rOop == j_rarg0)
7031       oop_slot = 0;
7032     else if (rOop == j_rarg1)
7033       oop_slot = 1;
7034     else if (rOop == j_rarg2)
7035       oop_slot = 2;
7036     else if (rOop == j_rarg3)
7037       oop_slot = 3;
7038     else if (rOop == j_rarg4)
7039       oop_slot = 4;
7040     else if (rOop == j_rarg5)
7041       oop_slot = 5;
7042     else if (rOop == j_rarg6)
7043       oop_slot = 6;
7044     else {
7045       assert(rOop == j_rarg7, "wrong register");
7046       oop_slot = 7;
7047     }
7048 
7049     oop_slot = oop_slot * VMRegImpl::slots_per_word + oop_handle_offset;
7050     int offset = oop_slot*VMRegImpl::stack_slot_size;
7051 
7052     map->set_oop(VMRegImpl::stack2reg(oop_slot));
7053     // Store oop in handle area, may be null
7054     str(rOop, Address(sp, offset));
7055     if (is_receiver) {
7056       *receiver_offset = offset;
7057     }
7058 
7059     cmp(rOop, zr);
7060     lea(rHandle, Address(sp, offset));
7061     // conditionally move a null
7062     csel(rHandle, zr, rHandle, Assembler::EQ);
7063   }
7064 
7065   // If arg is on the stack then place it otherwise it is already in correct reg.
7066   if (dst.first()->is_stack()) {
7067     str(rHandle, Address(sp, reg2offset_out(dst.first())));
7068   }
7069 }
7070 
7071 // A float arg may have to do float reg int reg conversion
7072 void MacroAssembler::float_move(VMRegPair src, VMRegPair dst, Register tmp) {
7073  if (src.first()->is_stack()) {
7074     if (dst.first()->is_stack()) {
7075       ldrw(tmp, Address(rfp, reg2offset_in(src.first())));
7076       strw(tmp, Address(sp, reg2offset_out(dst.first())));
7077     } else {
7078       ldrs(dst.first()->as_FloatRegister(), Address(rfp, reg2offset_in(src.first())));
7079     }
7080   } else if (src.first() != dst.first()) {
7081     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
7082       fmovs(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
7083     else
7084       strs(src.first()->as_FloatRegister(), Address(sp, reg2offset_out(dst.first())));
7085   }
7086 }
7087 
7088 // A long move
7089 void MacroAssembler::long_move(VMRegPair src, VMRegPair dst, Register tmp) {
7090   if (src.first()->is_stack()) {
7091     if (dst.first()->is_stack()) {
7092       // stack to stack
7093       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
7094       str(tmp, Address(sp, reg2offset_out(dst.first())));
7095     } else {
7096       // stack to reg
7097       ldr(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
7098     }
7099   } else if (dst.first()->is_stack()) {
7100     // reg to stack
7101     // Do we really have to sign extend???
7102     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
7103     str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
7104   } else {
7105     if (dst.first() != src.first()) {
7106       mov(dst.first()->as_Register(), src.first()->as_Register());
7107     }
7108   }
7109 }
7110 
7111 
7112 // A double move
7113 void MacroAssembler::double_move(VMRegPair src, VMRegPair dst, Register tmp) {
7114  if (src.first()->is_stack()) {
7115     if (dst.first()->is_stack()) {
7116       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
7117       str(tmp, Address(sp, reg2offset_out(dst.first())));
7118     } else {
7119       ldrd(dst.first()->as_FloatRegister(), Address(rfp, reg2offset_in(src.first())));
7120     }
7121   } else if (src.first() != dst.first()) {
7122     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
7123       fmovd(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
7124     else
7125       strd(src.first()->as_FloatRegister(), Address(sp, reg2offset_out(dst.first())));
7126   }
7127 }
7128 
7129 // Implements lightweight-locking.
7130 // Branches to slow upon failure to lock the object, with ZF cleared.
7131 // Falls through upon success with ZF set.
7132 //
7133 //  - obj: the object to be locked
7134 //  - hdr: the header, already loaded from obj, will be destroyed
7135 //  - t1, t2: temporary registers, will be destroyed
7136 void MacroAssembler::lightweight_lock(Register obj, Register hdr, Register t1, Register t2, Label& slow) {
7137   assert(LockingMode == LM_LIGHTWEIGHT, "only used with new lightweight locking");
7138   assert_different_registers(obj, hdr, t1, t2, rscratch1);
7139 
7140   // Check if we would have space on lock-stack for the object.
7141   ldrw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
7142   cmpw(t1, (unsigned)LockStack::end_offset() - 1);
7143   br(Assembler::GT, slow);
7144 
7145   // Load (object->mark() | 1) into hdr
7146   orr(hdr, hdr, markWord::unlocked_value);
7147   if (EnableValhalla) {
7148     // Mask inline_type bit such that we go to the slow path if object is an inline type
7149     andr(hdr, hdr, ~((int) markWord::inline_type_bit_in_place));
7150   }
7151 
7152   // Clear lock-bits, into t2
7153   eor(t2, hdr, markWord::unlocked_value);
7154   // Try to swing header from unlocked to locked
7155   // Clobbers rscratch1 when UseLSE is false
7156   cmpxchg(/*addr*/ obj, /*expected*/ hdr, /*new*/ t2, Assembler::xword,
7157           /*acquire*/ true, /*release*/ true, /*weak*/ false, t1);
7158   br(Assembler::NE, slow);
7159 
7160   // After successful lock, push object on lock-stack
7161   ldrw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
7162   str(obj, Address(rthread, t1));
7163   addw(t1, t1, oopSize);
7164   strw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
7165 }
7166 
7167 // Implements lightweight-unlocking.
7168 // Branches to slow upon failure, with ZF cleared.
7169 // Falls through upon success, with ZF set.
7170 //
7171 // - obj: the object to be unlocked
7172 // - hdr: the (pre-loaded) header of the object
7173 // - t1, t2: temporary registers
7174 void MacroAssembler::lightweight_unlock(Register obj, Register hdr, Register t1, Register t2, Label& slow) {
7175   assert(LockingMode == LM_LIGHTWEIGHT, "only used with new lightweight locking");
7176   assert_different_registers(obj, hdr, t1, t2, rscratch1);
7177 
7178 #ifdef ASSERT
7179   {
7180     // The following checks rely on the fact that LockStack is only ever modified by
7181     // its owning thread, even if the lock got inflated concurrently; removal of LockStack
7182     // entries after inflation will happen delayed in that case.
7183 
7184     // Check for lock-stack underflow.
7185     Label stack_ok;
7186     ldrw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
7187     cmpw(t1, (unsigned)LockStack::start_offset());
7188     br(Assembler::GT, stack_ok);
7189     STOP("Lock-stack underflow");
7190     bind(stack_ok);
7191   }
7192   {
7193     // Check if the top of the lock-stack matches the unlocked object.
7194     Label tos_ok;
7195     subw(t1, t1, oopSize);
7196     ldr(t1, Address(rthread, t1));
7197     cmpoop(t1, obj);
7198     br(Assembler::EQ, tos_ok);
7199     STOP("Top of lock-stack does not match the unlocked object");
7200     bind(tos_ok);
7201   }
7202   {
7203     // Check that hdr is fast-locked.
7204     Label hdr_ok;
7205     tst(hdr, markWord::lock_mask_in_place);
7206     br(Assembler::EQ, hdr_ok);
7207     STOP("Header is not fast-locked");
7208     bind(hdr_ok);
7209   }
7210 #endif
7211 
7212   // Load the new header (unlocked) into t1
7213   orr(t1, hdr, markWord::unlocked_value);
7214 
7215   // Try to swing header from locked to unlocked
7216   // Clobbers rscratch1 when UseLSE is false
7217   cmpxchg(obj, hdr, t1, Assembler::xword,
7218           /*acquire*/ true, /*release*/ true, /*weak*/ false, t2);
7219   br(Assembler::NE, slow);
7220 
7221   // After successful unlock, pop object from lock-stack
7222   ldrw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
7223   subw(t1, t1, oopSize);
7224 #ifdef ASSERT
7225   str(zr, Address(rthread, t1));
7226 #endif
7227   strw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
7228 }