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