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