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