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