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