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