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