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