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