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