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