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 "asm/assembler.hpp"
  30 #include "asm/assembler.inline.hpp"
  31 #include "ci/ciEnv.hpp"
  32 #include "ci/ciInlineKlass.hpp"
  33 #include "compiler/compileTask.hpp"
  34 #include "compiler/disassembler.hpp"
  35 #include "compiler/oopMap.hpp"
  36 #include "gc/shared/barrierSet.hpp"
  37 #include "gc/shared/barrierSetAssembler.hpp"
  38 #include "gc/shared/cardTableBarrierSet.hpp"
  39 #include "gc/shared/cardTable.hpp"
  40 #include "gc/shared/collectedHeap.hpp"
  41 #include "gc/shared/tlab_globals.hpp"
  42 #include "interpreter/bytecodeHistogram.hpp"
  43 #include "interpreter/interpreter.hpp"
  44 #include "jvm.h"
  45 #include "memory/resourceArea.hpp"
  46 #include "memory/universe.hpp"
  47 #include "nativeInst_aarch64.hpp"
  48 #include "oops/accessDecorators.hpp"
  49 #include "oops/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, temp_reg, rscratch2);
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_status_offset()));
1730   andr(temp_reg, temp_reg, InstanceKlassMiscStatus::is_empty_inline_type_value());
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 int MacroAssembler::corrected_idivl(Register result, Register ra, Register rb,
2057                                     bool want_remainder, Register scratch)
2058 {
2059   // Full implementation of Java idiv and irem.  The function
2060   // returns the (pc) offset of the div instruction - may be needed
2061   // for implicit exceptions.
2062   //
2063   // constraint : ra/rb =/= scratch
2064   //         normal case
2065   //
2066   // input : ra: dividend
2067   //         rb: divisor
2068   //
2069   // result: either
2070   //         quotient  (= ra idiv rb)
2071   //         remainder (= ra irem rb)
2072 
2073   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
2074 
2075   int idivl_offset = offset();
2076   if (! want_remainder) {
2077     sdivw(result, ra, rb);
2078   } else {
2079     sdivw(scratch, ra, rb);
2080     Assembler::msubw(result, scratch, rb, ra);
2081   }
2082 
2083   return idivl_offset;
2084 }
2085 
2086 int MacroAssembler::corrected_idivq(Register result, Register ra, Register rb,
2087                                     bool want_remainder, Register scratch)
2088 {
2089   // Full implementation of Java ldiv and lrem.  The function
2090   // returns the (pc) offset of the div instruction - may be needed
2091   // for implicit exceptions.
2092   //
2093   // constraint : ra/rb =/= scratch
2094   //         normal case
2095   //
2096   // input : ra: dividend
2097   //         rb: divisor
2098   //
2099   // result: either
2100   //         quotient  (= ra idiv rb)
2101   //         remainder (= ra irem rb)
2102 
2103   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
2104 
2105   int idivq_offset = offset();
2106   if (! want_remainder) {
2107     sdiv(result, ra, rb);
2108   } else {
2109     sdiv(scratch, ra, rb);
2110     Assembler::msub(result, scratch, rb, ra);
2111   }
2112 
2113   return idivq_offset;
2114 }
2115 
2116 void MacroAssembler::membar(Membar_mask_bits order_constraint) {
2117   address prev = pc() - NativeMembar::instruction_size;
2118   address last = code()->last_insn();
2119   if (last != NULL && nativeInstruction_at(last)->is_Membar() && prev == last) {
2120     NativeMembar *bar = NativeMembar_at(prev);
2121     // We are merging two memory barrier instructions.  On AArch64 we
2122     // can do this simply by ORing them together.
2123     bar->set_kind(bar->get_kind() | order_constraint);
2124     BLOCK_COMMENT("merged membar");
2125   } else {
2126     code()->set_last_insn(pc());
2127     dmb(Assembler::barrier(order_constraint));
2128   }
2129 }
2130 
2131 bool MacroAssembler::try_merge_ldst(Register rt, const Address &adr, size_t size_in_bytes, bool is_store) {
2132   if (ldst_can_merge(rt, adr, size_in_bytes, is_store)) {
2133     merge_ldst(rt, adr, size_in_bytes, is_store);
2134     code()->clear_last_insn();
2135     return true;
2136   } else {
2137     assert(size_in_bytes == 8 || size_in_bytes == 4, "only 8 bytes or 4 bytes load/store is supported.");
2138     const uint64_t mask = size_in_bytes - 1;
2139     if (adr.getMode() == Address::base_plus_offset &&
2140         (adr.offset() & mask) == 0) { // only supports base_plus_offset.
2141       code()->set_last_insn(pc());
2142     }
2143     return false;
2144   }
2145 }
2146 
2147 void MacroAssembler::ldr(Register Rx, const Address &adr) {
2148   // We always try to merge two adjacent loads into one ldp.
2149   if (!try_merge_ldst(Rx, adr, 8, false)) {
2150     Assembler::ldr(Rx, adr);
2151   }
2152 }
2153 
2154 void MacroAssembler::ldrw(Register Rw, const Address &adr) {
2155   // We always try to merge two adjacent loads into one ldp.
2156   if (!try_merge_ldst(Rw, adr, 4, false)) {
2157     Assembler::ldrw(Rw, adr);
2158   }
2159 }
2160 
2161 void MacroAssembler::str(Register Rx, const Address &adr) {
2162   // We always try to merge two adjacent stores into one stp.
2163   if (!try_merge_ldst(Rx, adr, 8, true)) {
2164     Assembler::str(Rx, adr);
2165   }
2166 }
2167 
2168 void MacroAssembler::strw(Register Rw, const Address &adr) {
2169   // We always try to merge two adjacent stores into one stp.
2170   if (!try_merge_ldst(Rw, adr, 4, true)) {
2171     Assembler::strw(Rw, adr);
2172   }
2173 }
2174 
2175 // MacroAssembler routines found actually to be needed
2176 
2177 void MacroAssembler::push(Register src)
2178 {
2179   str(src, Address(pre(esp, -1 * wordSize)));
2180 }
2181 
2182 void MacroAssembler::pop(Register dst)
2183 {
2184   ldr(dst, Address(post(esp, 1 * wordSize)));
2185 }
2186 
2187 // Note: load_unsigned_short used to be called load_unsigned_word.
2188 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
2189   int off = offset();
2190   ldrh(dst, src);
2191   return off;
2192 }
2193 
2194 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
2195   int off = offset();
2196   ldrb(dst, src);
2197   return off;
2198 }
2199 
2200 int MacroAssembler::load_signed_short(Register dst, Address src) {
2201   int off = offset();
2202   ldrsh(dst, src);
2203   return off;
2204 }
2205 
2206 int MacroAssembler::load_signed_byte(Register dst, Address src) {
2207   int off = offset();
2208   ldrsb(dst, src);
2209   return off;
2210 }
2211 
2212 int MacroAssembler::load_signed_short32(Register dst, Address src) {
2213   int off = offset();
2214   ldrshw(dst, src);
2215   return off;
2216 }
2217 
2218 int MacroAssembler::load_signed_byte32(Register dst, Address src) {
2219   int off = offset();
2220   ldrsbw(dst, src);
2221   return off;
2222 }
2223 
2224 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed) {
2225   switch (size_in_bytes) {
2226   case  8:  ldr(dst, src); break;
2227   case  4:  ldrw(dst, src); break;
2228   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
2229   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
2230   default:  ShouldNotReachHere();
2231   }
2232 }
2233 
2234 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes) {
2235   switch (size_in_bytes) {
2236   case  8:  str(src, dst); break;
2237   case  4:  strw(src, dst); break;
2238   case  2:  strh(src, dst); break;
2239   case  1:  strb(src, dst); break;
2240   default:  ShouldNotReachHere();
2241   }
2242 }
2243 
2244 void MacroAssembler::decrementw(Register reg, int value)
2245 {
2246   if (value < 0)  { incrementw(reg, -value);      return; }
2247   if (value == 0) {                               return; }
2248   if (value < (1 << 12)) { subw(reg, reg, value); return; }
2249   /* else */ {
2250     guarantee(reg != rscratch2, "invalid dst for register decrement");
2251     movw(rscratch2, (unsigned)value);
2252     subw(reg, reg, rscratch2);
2253   }
2254 }
2255 
2256 void MacroAssembler::decrement(Register reg, int value)
2257 {
2258   if (value < 0)  { increment(reg, -value);      return; }
2259   if (value == 0) {                              return; }
2260   if (value < (1 << 12)) { sub(reg, reg, value); return; }
2261   /* else */ {
2262     assert(reg != rscratch2, "invalid dst for register decrement");
2263     mov(rscratch2, (uint64_t)value);
2264     sub(reg, reg, rscratch2);
2265   }
2266 }
2267 
2268 void MacroAssembler::decrementw(Address dst, int value)
2269 {
2270   assert(!dst.uses(rscratch1), "invalid dst for address decrement");
2271   if (dst.getMode() == Address::literal) {
2272     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2273     lea(rscratch2, dst);
2274     dst = Address(rscratch2);
2275   }
2276   ldrw(rscratch1, dst);
2277   decrementw(rscratch1, value);
2278   strw(rscratch1, dst);
2279 }
2280 
2281 void MacroAssembler::decrement(Address dst, int value)
2282 {
2283   assert(!dst.uses(rscratch1), "invalid address for decrement");
2284   if (dst.getMode() == Address::literal) {
2285     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2286     lea(rscratch2, dst);
2287     dst = Address(rscratch2);
2288   }
2289   ldr(rscratch1, dst);
2290   decrement(rscratch1, value);
2291   str(rscratch1, dst);
2292 }
2293 
2294 void MacroAssembler::incrementw(Register reg, int value)
2295 {
2296   if (value < 0)  { decrementw(reg, -value);      return; }
2297   if (value == 0) {                               return; }
2298   if (value < (1 << 12)) { addw(reg, reg, value); return; }
2299   /* else */ {
2300     assert(reg != rscratch2, "invalid dst for register increment");
2301     movw(rscratch2, (unsigned)value);
2302     addw(reg, reg, rscratch2);
2303   }
2304 }
2305 
2306 void MacroAssembler::increment(Register reg, int value)
2307 {
2308   if (value < 0)  { decrement(reg, -value);      return; }
2309   if (value == 0) {                              return; }
2310   if (value < (1 << 12)) { add(reg, reg, value); return; }
2311   /* else */ {
2312     assert(reg != rscratch2, "invalid dst for register increment");
2313     movw(rscratch2, (unsigned)value);
2314     add(reg, reg, rscratch2);
2315   }
2316 }
2317 
2318 void MacroAssembler::incrementw(Address dst, int value)
2319 {
2320   assert(!dst.uses(rscratch1), "invalid dst for address increment");
2321   if (dst.getMode() == Address::literal) {
2322     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2323     lea(rscratch2, dst);
2324     dst = Address(rscratch2);
2325   }
2326   ldrw(rscratch1, dst);
2327   incrementw(rscratch1, value);
2328   strw(rscratch1, dst);
2329 }
2330 
2331 void MacroAssembler::increment(Address dst, int value)
2332 {
2333   assert(!dst.uses(rscratch1), "invalid dst for address increment");
2334   if (dst.getMode() == Address::literal) {
2335     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2336     lea(rscratch2, dst);
2337     dst = Address(rscratch2);
2338   }
2339   ldr(rscratch1, dst);
2340   increment(rscratch1, value);
2341   str(rscratch1, dst);
2342 }
2343 
2344 // Push lots of registers in the bit set supplied.  Don't push sp.
2345 // Return the number of words pushed
2346 int MacroAssembler::push(unsigned int bitset, Register stack) {
2347   int words_pushed = 0;
2348 
2349   // Scan bitset to accumulate register pairs
2350   unsigned char regs[32];
2351   int count = 0;
2352   for (int reg = 0; reg <= 30; reg++) {
2353     if (1 & bitset)
2354       regs[count++] = reg;
2355     bitset >>= 1;
2356   }
2357   regs[count++] = zr->raw_encoding();
2358   count &= ~1;  // Only push an even number of regs
2359 
2360   if (count) {
2361     stp(as_Register(regs[0]), as_Register(regs[1]),
2362        Address(pre(stack, -count * wordSize)));
2363     words_pushed += 2;
2364   }
2365   for (int i = 2; i < count; i += 2) {
2366     stp(as_Register(regs[i]), as_Register(regs[i+1]),
2367        Address(stack, i * wordSize));
2368     words_pushed += 2;
2369   }
2370 
2371   assert(words_pushed == count, "oops, pushed != count");
2372 
2373   return count;
2374 }
2375 
2376 int MacroAssembler::pop(unsigned int bitset, Register stack) {
2377   int words_pushed = 0;
2378 
2379   // Scan bitset to accumulate register pairs
2380   unsigned char regs[32];
2381   int count = 0;
2382   for (int reg = 0; reg <= 30; reg++) {
2383     if (1 & bitset)
2384       regs[count++] = reg;
2385     bitset >>= 1;
2386   }
2387   regs[count++] = zr->raw_encoding();
2388   count &= ~1;
2389 
2390   for (int i = 2; i < count; i += 2) {
2391     ldp(as_Register(regs[i]), as_Register(regs[i+1]),
2392        Address(stack, i * wordSize));
2393     words_pushed += 2;
2394   }
2395   if (count) {
2396     ldp(as_Register(regs[0]), as_Register(regs[1]),
2397        Address(post(stack, count * wordSize)));
2398     words_pushed += 2;
2399   }
2400 
2401   assert(words_pushed == count, "oops, pushed != count");
2402 
2403   return count;
2404 }
2405 
2406 // Push lots of registers in the bit set supplied.  Don't push sp.
2407 // Return the number of dwords pushed
2408 int MacroAssembler::push_fp(unsigned int bitset, Register stack) {
2409   int words_pushed = 0;
2410   bool use_sve = false;
2411   int sve_vector_size_in_bytes = 0;
2412 
2413 #ifdef COMPILER2
2414   use_sve = Matcher::supports_scalable_vector();
2415   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
2416 #endif
2417 
2418   // Scan bitset to accumulate register pairs
2419   unsigned char regs[32];
2420   int count = 0;
2421   for (int reg = 0; reg <= 31; reg++) {
2422     if (1 & bitset)
2423       regs[count++] = reg;
2424     bitset >>= 1;
2425   }
2426 
2427   if (count == 0) {
2428     return 0;
2429   }
2430 
2431   // SVE
2432   if (use_sve && sve_vector_size_in_bytes > 16) {
2433     sub(stack, stack, sve_vector_size_in_bytes * count);
2434     for (int i = 0; i < count; i++) {
2435       sve_str(as_FloatRegister(regs[i]), Address(stack, i));
2436     }
2437     return count * sve_vector_size_in_bytes / 8;
2438   }
2439 
2440   // NEON
2441   if (count == 1) {
2442     strq(as_FloatRegister(regs[0]), Address(pre(stack, -wordSize * 2)));
2443     return 2;
2444   }
2445 
2446   bool odd = (count & 1) == 1;
2447   int push_slots = count + (odd ? 1 : 0);
2448 
2449   // Always pushing full 128 bit registers.
2450   stpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(pre(stack, -push_slots * wordSize * 2)));
2451   words_pushed += 2;
2452 
2453   for (int i = 2; i + 1 < count; i += 2) {
2454     stpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
2455     words_pushed += 2;
2456   }
2457 
2458   if (odd) {
2459     strq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
2460     words_pushed++;
2461   }
2462 
2463   assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
2464   return count * 2;
2465 }
2466 
2467 // Return the number of dwords popped
2468 int MacroAssembler::pop_fp(unsigned int bitset, Register stack) {
2469   int words_pushed = 0;
2470   bool use_sve = false;
2471   int sve_vector_size_in_bytes = 0;
2472 
2473 #ifdef COMPILER2
2474   use_sve = Matcher::supports_scalable_vector();
2475   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
2476 #endif
2477   // Scan bitset to accumulate register pairs
2478   unsigned char regs[32];
2479   int count = 0;
2480   for (int reg = 0; reg <= 31; reg++) {
2481     if (1 & bitset)
2482       regs[count++] = reg;
2483     bitset >>= 1;
2484   }
2485 
2486   if (count == 0) {
2487     return 0;
2488   }
2489 
2490   // SVE
2491   if (use_sve && sve_vector_size_in_bytes > 16) {
2492     for (int i = count - 1; i >= 0; i--) {
2493       sve_ldr(as_FloatRegister(regs[i]), Address(stack, i));
2494     }
2495     add(stack, stack, sve_vector_size_in_bytes * count);
2496     return count * sve_vector_size_in_bytes / 8;
2497   }
2498 
2499   // NEON
2500   if (count == 1) {
2501     ldrq(as_FloatRegister(regs[0]), Address(post(stack, wordSize * 2)));
2502     return 2;
2503   }
2504 
2505   bool odd = (count & 1) == 1;
2506   int push_slots = count + (odd ? 1 : 0);
2507 
2508   if (odd) {
2509     ldrq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
2510     words_pushed++;
2511   }
2512 
2513   for (int i = 2; i + 1 < count; i += 2) {
2514     ldpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
2515     words_pushed += 2;
2516   }
2517 
2518   ldpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(post(stack, push_slots * wordSize * 2)));
2519   words_pushed += 2;
2520 
2521   assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
2522 
2523   return count * 2;
2524 }
2525 
2526 // Return the number of dwords pushed
2527 int MacroAssembler::push_p(unsigned int bitset, Register stack) {
2528   bool use_sve = false;
2529   int sve_predicate_size_in_slots = 0;
2530 
2531 #ifdef COMPILER2
2532   use_sve = Matcher::supports_scalable_vector();
2533   if (use_sve) {
2534     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
2535   }
2536 #endif
2537 
2538   if (!use_sve) {
2539     return 0;
2540   }
2541 
2542   unsigned char regs[PRegister::number_of_registers];
2543   int count = 0;
2544   for (int reg = 0; reg < PRegister::number_of_registers; reg++) {
2545     if (1 & bitset)
2546       regs[count++] = reg;
2547     bitset >>= 1;
2548   }
2549 
2550   if (count == 0) {
2551     return 0;
2552   }
2553 
2554   int total_push_bytes = align_up(sve_predicate_size_in_slots *
2555                                   VMRegImpl::stack_slot_size * count, 16);
2556   sub(stack, stack, total_push_bytes);
2557   for (int i = 0; i < count; i++) {
2558     sve_str(as_PRegister(regs[i]), Address(stack, i));
2559   }
2560   return total_push_bytes / 8;
2561 }
2562 
2563 // Return the number of dwords popped
2564 int MacroAssembler::pop_p(unsigned int bitset, Register stack) {
2565   bool use_sve = false;
2566   int sve_predicate_size_in_slots = 0;
2567 
2568 #ifdef COMPILER2
2569   use_sve = Matcher::supports_scalable_vector();
2570   if (use_sve) {
2571     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
2572   }
2573 #endif
2574 
2575   if (!use_sve) {
2576     return 0;
2577   }
2578 
2579   unsigned char regs[PRegister::number_of_registers];
2580   int count = 0;
2581   for (int reg = 0; reg < PRegister::number_of_registers; reg++) {
2582     if (1 & bitset)
2583       regs[count++] = reg;
2584     bitset >>= 1;
2585   }
2586 
2587   if (count == 0) {
2588     return 0;
2589   }
2590 
2591   int total_pop_bytes = align_up(sve_predicate_size_in_slots *
2592                                  VMRegImpl::stack_slot_size * count, 16);
2593   for (int i = count - 1; i >= 0; i--) {
2594     sve_ldr(as_PRegister(regs[i]), Address(stack, i));
2595   }
2596   add(stack, stack, total_pop_bytes);
2597   return total_pop_bytes / 8;
2598 }
2599 
2600 #ifdef ASSERT
2601 void MacroAssembler::verify_heapbase(const char* msg) {
2602 #if 0
2603   assert (UseCompressedOops || UseCompressedClassPointers, "should be compressed");
2604   assert (Universe::heap() != NULL, "java heap should be initialized");
2605   if (!UseCompressedOops || Universe::ptr_base() == NULL) {
2606     // rheapbase is allocated as general register
2607     return;
2608   }
2609   if (CheckCompressedOops) {
2610     Label ok;
2611     push(1 << rscratch1->encoding(), sp); // cmpptr trashes rscratch1
2612     cmpptr(rheapbase, ExternalAddress(CompressedOops::ptrs_base_addr()));
2613     br(Assembler::EQ, ok);
2614     stop(msg);
2615     bind(ok);
2616     pop(1 << rscratch1->encoding(), sp);
2617   }
2618 #endif
2619 }
2620 #endif
2621 
2622 void MacroAssembler::resolve_jobject(Register value, Register tmp1, Register tmp2) {
2623   Label done, not_weak;
2624   cbz(value, done);           // Use NULL as-is.
2625 
2626   STATIC_ASSERT(JNIHandles::weak_tag_mask == 1u);
2627   tbz(value, 0, not_weak);    // Test for jweak tag.
2628 
2629   // Resolve jweak.
2630   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF, value,
2631                  Address(value, -JNIHandles::weak_tag_value), tmp1, tmp2);
2632   verify_oop(value);
2633   b(done);
2634 
2635   bind(not_weak);
2636   // Resolve (untagged) jobject.
2637   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, 0), tmp1, tmp2);
2638   verify_oop(value);
2639   bind(done);
2640 }
2641 
2642 void MacroAssembler::stop(const char* msg) {
2643   BLOCK_COMMENT(msg);
2644   dcps1(0xdeae);
2645   emit_int64((uintptr_t)msg);
2646 }
2647 
2648 void MacroAssembler::unimplemented(const char* what) {
2649   const char* buf = NULL;
2650   {
2651     ResourceMark rm;
2652     stringStream ss;
2653     ss.print("unimplemented: %s", what);
2654     buf = code_string(ss.as_string());
2655   }
2656   stop(buf);
2657 }
2658 
2659 void MacroAssembler::_assert_asm(Assembler::Condition cc, const char* msg) {
2660 #ifdef ASSERT
2661   Label OK;
2662   br(cc, OK);
2663   stop(msg);
2664   bind(OK);
2665 #endif
2666 }
2667 
2668 // If a constant does not fit in an immediate field, generate some
2669 // number of MOV instructions and then perform the operation.
2670 void MacroAssembler::wrap_add_sub_imm_insn(Register Rd, Register Rn, uint64_t imm,
2671                                            add_sub_imm_insn insn1,
2672                                            add_sub_reg_insn insn2,
2673                                            bool is32) {
2674   assert(Rd != zr, "Rd = zr and not setting flags?");
2675   bool fits = operand_valid_for_add_sub_immediate(is32 ? (int32_t)imm : imm);
2676   if (fits) {
2677     (this->*insn1)(Rd, Rn, imm);
2678   } else {
2679     if (uabs(imm) < (1 << 24)) {
2680        (this->*insn1)(Rd, Rn, imm & -(1 << 12));
2681        (this->*insn1)(Rd, Rd, imm & ((1 << 12)-1));
2682     } else {
2683        assert_different_registers(Rd, Rn);
2684        mov(Rd, imm);
2685        (this->*insn2)(Rd, Rn, Rd, LSL, 0);
2686     }
2687   }
2688 }
2689 
2690 // Separate vsn which sets the flags. Optimisations are more restricted
2691 // because we must set the flags correctly.
2692 void MacroAssembler::wrap_adds_subs_imm_insn(Register Rd, Register Rn, uint64_t imm,
2693                                              add_sub_imm_insn insn1,
2694                                              add_sub_reg_insn insn2,
2695                                              bool is32) {
2696   bool fits = operand_valid_for_add_sub_immediate(is32 ? (int32_t)imm : imm);
2697   if (fits) {
2698     (this->*insn1)(Rd, Rn, imm);
2699   } else {
2700     assert_different_registers(Rd, Rn);
2701     assert(Rd != zr, "overflow in immediate operand");
2702     mov(Rd, imm);
2703     (this->*insn2)(Rd, Rn, Rd, LSL, 0);
2704   }
2705 }
2706 
2707 
2708 void MacroAssembler::add(Register Rd, Register Rn, RegisterOrConstant increment) {
2709   if (increment.is_register()) {
2710     add(Rd, Rn, increment.as_register());
2711   } else {
2712     add(Rd, Rn, increment.as_constant());
2713   }
2714 }
2715 
2716 void MacroAssembler::addw(Register Rd, Register Rn, RegisterOrConstant increment) {
2717   if (increment.is_register()) {
2718     addw(Rd, Rn, increment.as_register());
2719   } else {
2720     addw(Rd, Rn, increment.as_constant());
2721   }
2722 }
2723 
2724 void MacroAssembler::sub(Register Rd, Register Rn, RegisterOrConstant decrement) {
2725   if (decrement.is_register()) {
2726     sub(Rd, Rn, decrement.as_register());
2727   } else {
2728     sub(Rd, Rn, decrement.as_constant());
2729   }
2730 }
2731 
2732 void MacroAssembler::subw(Register Rd, Register Rn, RegisterOrConstant decrement) {
2733   if (decrement.is_register()) {
2734     subw(Rd, Rn, decrement.as_register());
2735   } else {
2736     subw(Rd, Rn, decrement.as_constant());
2737   }
2738 }
2739 
2740 void MacroAssembler::reinit_heapbase()
2741 {
2742   if (UseCompressedOops) {
2743     if (Universe::is_fully_initialized()) {
2744       mov(rheapbase, CompressedOops::ptrs_base());
2745     } else {
2746       lea(rheapbase, ExternalAddress(CompressedOops::ptrs_base_addr()));
2747       ldr(rheapbase, Address(rheapbase));
2748     }
2749   }
2750 }
2751 
2752 // this simulates the behaviour of the x86 cmpxchg instruction using a
2753 // load linked/store conditional pair. we use the acquire/release
2754 // versions of these instructions so that we flush pending writes as
2755 // per Java semantics.
2756 
2757 // n.b the x86 version assumes the old value to be compared against is
2758 // in rax and updates rax with the value located in memory if the
2759 // cmpxchg fails. we supply a register for the old value explicitly
2760 
2761 // the aarch64 load linked/store conditional instructions do not
2762 // accept an offset. so, unlike x86, we must provide a plain register
2763 // to identify the memory word to be compared/exchanged rather than a
2764 // register+offset Address.
2765 
2766 void MacroAssembler::cmpxchgptr(Register oldv, Register newv, Register addr, Register tmp,
2767                                 Label &succeed, Label *fail) {
2768   // oldv holds comparison value
2769   // newv holds value to write in exchange
2770   // addr identifies memory word to compare against/update
2771   if (UseLSE) {
2772     mov(tmp, oldv);
2773     casal(Assembler::xword, oldv, newv, addr);
2774     cmp(tmp, oldv);
2775     br(Assembler::EQ, succeed);
2776     membar(AnyAny);
2777   } else {
2778     Label retry_load, nope;
2779     prfm(Address(addr), PSTL1STRM);
2780     bind(retry_load);
2781     // flush and load exclusive from the memory location
2782     // and fail if it is not what we expect
2783     ldaxr(tmp, addr);
2784     cmp(tmp, oldv);
2785     br(Assembler::NE, nope);
2786     // if we store+flush with no intervening write tmp will be zero
2787     stlxr(tmp, newv, addr);
2788     cbzw(tmp, succeed);
2789     // retry so we only ever return after a load fails to compare
2790     // ensures we don't return a stale value after a failed write.
2791     b(retry_load);
2792     // if the memory word differs we return it in oldv and signal a fail
2793     bind(nope);
2794     membar(AnyAny);
2795     mov(oldv, tmp);
2796   }
2797   if (fail)
2798     b(*fail);
2799 }
2800 
2801 void MacroAssembler::cmpxchg_obj_header(Register oldv, Register newv, Register obj, Register tmp,
2802                                         Label &succeed, Label *fail) {
2803   assert(oopDesc::mark_offset_in_bytes() == 0, "assumption");
2804   cmpxchgptr(oldv, newv, obj, tmp, succeed, fail);
2805 }
2806 
2807 void MacroAssembler::cmpxchgw(Register oldv, Register newv, Register addr, Register tmp,
2808                                 Label &succeed, Label *fail) {
2809   // oldv holds comparison value
2810   // newv holds value to write in exchange
2811   // addr identifies memory word to compare against/update
2812   // tmp returns 0/1 for success/failure
2813   if (UseLSE) {
2814     mov(tmp, oldv);
2815     casal(Assembler::word, oldv, newv, addr);
2816     cmp(tmp, oldv);
2817     br(Assembler::EQ, succeed);
2818     membar(AnyAny);
2819   } else {
2820     Label retry_load, nope;
2821     prfm(Address(addr), PSTL1STRM);
2822     bind(retry_load);
2823     // flush and load exclusive from the memory location
2824     // and fail if it is not what we expect
2825     ldaxrw(tmp, addr);
2826     cmp(tmp, oldv);
2827     br(Assembler::NE, nope);
2828     // if we store+flush with no intervening write tmp will be zero
2829     stlxrw(tmp, newv, addr);
2830     cbzw(tmp, succeed);
2831     // retry so we only ever return after a load fails to compare
2832     // ensures we don't return a stale value after a failed write.
2833     b(retry_load);
2834     // if the memory word differs we return it in oldv and signal a fail
2835     bind(nope);
2836     membar(AnyAny);
2837     mov(oldv, tmp);
2838   }
2839   if (fail)
2840     b(*fail);
2841 }
2842 
2843 // A generic CAS; success or failure is in the EQ flag.  A weak CAS
2844 // doesn't retry and may fail spuriously.  If the oldval is wanted,
2845 // Pass a register for the result, otherwise pass noreg.
2846 
2847 // Clobbers rscratch1
2848 void MacroAssembler::cmpxchg(Register addr, Register expected,
2849                              Register new_val,
2850                              enum operand_size size,
2851                              bool acquire, bool release,
2852                              bool weak,
2853                              Register result) {
2854   if (result == noreg)  result = rscratch1;
2855   BLOCK_COMMENT("cmpxchg {");
2856   if (UseLSE) {
2857     mov(result, expected);
2858     lse_cas(result, new_val, addr, size, acquire, release, /*not_pair*/ true);
2859     compare_eq(result, expected, size);
2860   } else {
2861     Label retry_load, done;
2862     prfm(Address(addr), PSTL1STRM);
2863     bind(retry_load);
2864     load_exclusive(result, addr, size, acquire);
2865     compare_eq(result, expected, size);
2866     br(Assembler::NE, done);
2867     store_exclusive(rscratch1, new_val, addr, size, release);
2868     if (weak) {
2869       cmpw(rscratch1, 0u);  // If the store fails, return NE to our caller.
2870     } else {
2871       cbnzw(rscratch1, retry_load);
2872     }
2873     bind(done);
2874   }
2875   BLOCK_COMMENT("} cmpxchg");
2876 }
2877 
2878 // A generic comparison. Only compares for equality, clobbers rscratch1.
2879 void MacroAssembler::compare_eq(Register rm, Register rn, enum operand_size size) {
2880   if (size == xword) {
2881     cmp(rm, rn);
2882   } else if (size == word) {
2883     cmpw(rm, rn);
2884   } else if (size == halfword) {
2885     eorw(rscratch1, rm, rn);
2886     ands(zr, rscratch1, 0xffff);
2887   } else if (size == byte) {
2888     eorw(rscratch1, rm, rn);
2889     ands(zr, rscratch1, 0xff);
2890   } else {
2891     ShouldNotReachHere();
2892   }
2893 }
2894 
2895 
2896 static bool different(Register a, RegisterOrConstant b, Register c) {
2897   if (b.is_constant())
2898     return a != c;
2899   else
2900     return a != b.as_register() && a != c && b.as_register() != c;
2901 }
2902 
2903 #define ATOMIC_OP(NAME, LDXR, OP, IOP, AOP, STXR, sz)                   \
2904 void MacroAssembler::atomic_##NAME(Register prev, RegisterOrConstant incr, Register addr) { \
2905   if (UseLSE) {                                                         \
2906     prev = prev->is_valid() ? prev : zr;                                \
2907     if (incr.is_register()) {                                           \
2908       AOP(sz, incr.as_register(), prev, addr);                          \
2909     } else {                                                            \
2910       mov(rscratch2, incr.as_constant());                               \
2911       AOP(sz, rscratch2, prev, addr);                                   \
2912     }                                                                   \
2913     return;                                                             \
2914   }                                                                     \
2915   Register result = rscratch2;                                          \
2916   if (prev->is_valid())                                                 \
2917     result = different(prev, incr, addr) ? prev : rscratch2;            \
2918                                                                         \
2919   Label retry_load;                                                     \
2920   prfm(Address(addr), PSTL1STRM);                                       \
2921   bind(retry_load);                                                     \
2922   LDXR(result, addr);                                                   \
2923   OP(rscratch1, result, incr);                                          \
2924   STXR(rscratch2, rscratch1, addr);                                     \
2925   cbnzw(rscratch2, retry_load);                                         \
2926   if (prev->is_valid() && prev != result) {                             \
2927     IOP(prev, rscratch1, incr);                                         \
2928   }                                                                     \
2929 }
2930 
2931 ATOMIC_OP(add, ldxr, add, sub, ldadd, stxr, Assembler::xword)
2932 ATOMIC_OP(addw, ldxrw, addw, subw, ldadd, stxrw, Assembler::word)
2933 ATOMIC_OP(addal, ldaxr, add, sub, ldaddal, stlxr, Assembler::xword)
2934 ATOMIC_OP(addalw, ldaxrw, addw, subw, ldaddal, stlxrw, Assembler::word)
2935 
2936 #undef ATOMIC_OP
2937 
2938 #define ATOMIC_XCHG(OP, AOP, LDXR, STXR, sz)                            \
2939 void MacroAssembler::atomic_##OP(Register prev, Register newv, Register addr) { \
2940   if (UseLSE) {                                                         \
2941     prev = prev->is_valid() ? prev : zr;                                \
2942     AOP(sz, newv, prev, addr);                                          \
2943     return;                                                             \
2944   }                                                                     \
2945   Register result = rscratch2;                                          \
2946   if (prev->is_valid())                                                 \
2947     result = different(prev, newv, addr) ? prev : rscratch2;            \
2948                                                                         \
2949   Label retry_load;                                                     \
2950   prfm(Address(addr), PSTL1STRM);                                       \
2951   bind(retry_load);                                                     \
2952   LDXR(result, addr);                                                   \
2953   STXR(rscratch1, newv, addr);                                          \
2954   cbnzw(rscratch1, retry_load);                                         \
2955   if (prev->is_valid() && prev != result)                               \
2956     mov(prev, result);                                                  \
2957 }
2958 
2959 ATOMIC_XCHG(xchg, swp, ldxr, stxr, Assembler::xword)
2960 ATOMIC_XCHG(xchgw, swp, ldxrw, stxrw, Assembler::word)
2961 ATOMIC_XCHG(xchgl, swpl, ldxr, stlxr, Assembler::xword)
2962 ATOMIC_XCHG(xchglw, swpl, ldxrw, stlxrw, Assembler::word)
2963 ATOMIC_XCHG(xchgal, swpal, ldaxr, stlxr, Assembler::xword)
2964 ATOMIC_XCHG(xchgalw, swpal, ldaxrw, stlxrw, Assembler::word)
2965 
2966 #undef ATOMIC_XCHG
2967 
2968 #ifndef PRODUCT
2969 extern "C" void findpc(intptr_t x);
2970 #endif
2971 
2972 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[])
2973 {
2974   // In order to get locks to work, we need to fake a in_VM state
2975   if (ShowMessageBoxOnError ) {
2976     JavaThread* thread = JavaThread::current();
2977     JavaThreadState saved_state = thread->thread_state();
2978     thread->set_thread_state(_thread_in_vm);
2979 #ifndef PRODUCT
2980     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
2981       ttyLocker ttyl;
2982       BytecodeCounter::print();
2983     }
2984 #endif
2985     if (os::message_box(msg, "Execution stopped, print registers?")) {
2986       ttyLocker ttyl;
2987       tty->print_cr(" pc = 0x%016" PRIx64, pc);
2988 #ifndef PRODUCT
2989       tty->cr();
2990       findpc(pc);
2991       tty->cr();
2992 #endif
2993       tty->print_cr(" r0 = 0x%016" PRIx64, regs[0]);
2994       tty->print_cr(" r1 = 0x%016" PRIx64, regs[1]);
2995       tty->print_cr(" r2 = 0x%016" PRIx64, regs[2]);
2996       tty->print_cr(" r3 = 0x%016" PRIx64, regs[3]);
2997       tty->print_cr(" r4 = 0x%016" PRIx64, regs[4]);
2998       tty->print_cr(" r5 = 0x%016" PRIx64, regs[5]);
2999       tty->print_cr(" r6 = 0x%016" PRIx64, regs[6]);
3000       tty->print_cr(" r7 = 0x%016" PRIx64, regs[7]);
3001       tty->print_cr(" r8 = 0x%016" PRIx64, regs[8]);
3002       tty->print_cr(" r9 = 0x%016" PRIx64, regs[9]);
3003       tty->print_cr("r10 = 0x%016" PRIx64, regs[10]);
3004       tty->print_cr("r11 = 0x%016" PRIx64, regs[11]);
3005       tty->print_cr("r12 = 0x%016" PRIx64, regs[12]);
3006       tty->print_cr("r13 = 0x%016" PRIx64, regs[13]);
3007       tty->print_cr("r14 = 0x%016" PRIx64, regs[14]);
3008       tty->print_cr("r15 = 0x%016" PRIx64, regs[15]);
3009       tty->print_cr("r16 = 0x%016" PRIx64, regs[16]);
3010       tty->print_cr("r17 = 0x%016" PRIx64, regs[17]);
3011       tty->print_cr("r18 = 0x%016" PRIx64, regs[18]);
3012       tty->print_cr("r19 = 0x%016" PRIx64, regs[19]);
3013       tty->print_cr("r20 = 0x%016" PRIx64, regs[20]);
3014       tty->print_cr("r21 = 0x%016" PRIx64, regs[21]);
3015       tty->print_cr("r22 = 0x%016" PRIx64, regs[22]);
3016       tty->print_cr("r23 = 0x%016" PRIx64, regs[23]);
3017       tty->print_cr("r24 = 0x%016" PRIx64, regs[24]);
3018       tty->print_cr("r25 = 0x%016" PRIx64, regs[25]);
3019       tty->print_cr("r26 = 0x%016" PRIx64, regs[26]);
3020       tty->print_cr("r27 = 0x%016" PRIx64, regs[27]);
3021       tty->print_cr("r28 = 0x%016" PRIx64, regs[28]);
3022       tty->print_cr("r30 = 0x%016" PRIx64, regs[30]);
3023       tty->print_cr("r31 = 0x%016" PRIx64, regs[31]);
3024       BREAKPOINT;
3025     }
3026   }
3027   fatal("DEBUG MESSAGE: %s", msg);
3028 }
3029 
3030 RegSet MacroAssembler::call_clobbered_gp_registers() {
3031   RegSet regs = RegSet::range(r0, r17) - RegSet::of(rscratch1, rscratch2);
3032 #ifndef R18_RESERVED
3033   regs += r18_tls;
3034 #endif
3035   return regs;
3036 }
3037 
3038 void MacroAssembler::push_call_clobbered_registers_except(RegSet exclude) {
3039   int step = 4 * wordSize;
3040   push(call_clobbered_gp_registers() - exclude, sp);
3041   sub(sp, sp, step);
3042   mov(rscratch1, -step);
3043   // Push v0-v7, v16-v31.
3044   for (int i = 31; i>= 4; i -= 4) {
3045     if (i <= v7->encoding() || i >= v16->encoding())
3046       st1(as_FloatRegister(i-3), as_FloatRegister(i-2), as_FloatRegister(i-1),
3047           as_FloatRegister(i), T1D, Address(post(sp, rscratch1)));
3048   }
3049   st1(as_FloatRegister(0), as_FloatRegister(1), as_FloatRegister(2),
3050       as_FloatRegister(3), T1D, Address(sp));
3051 }
3052 
3053 void MacroAssembler::pop_call_clobbered_registers_except(RegSet exclude) {
3054   for (int i = 0; i < 32; i += 4) {
3055     if (i <= v7->encoding() || i >= v16->encoding())
3056       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3057           as_FloatRegister(i+3), T1D, Address(post(sp, 4 * wordSize)));
3058   }
3059 
3060   reinitialize_ptrue();
3061 
3062   pop(call_clobbered_gp_registers() - exclude, sp);
3063 }
3064 
3065 void MacroAssembler::push_CPU_state(bool save_vectors, bool use_sve,
3066                                     int sve_vector_size_in_bytes, int total_predicate_in_bytes) {
3067   push(RegSet::range(r0, r29), sp); // integer registers except lr & sp
3068   if (save_vectors && use_sve && sve_vector_size_in_bytes > 16) {
3069     sub(sp, sp, sve_vector_size_in_bytes * FloatRegister::number_of_registers);
3070     for (int i = 0; i < FloatRegister::number_of_registers; i++) {
3071       sve_str(as_FloatRegister(i), Address(sp, i));
3072     }
3073   } else {
3074     int step = (save_vectors ? 8 : 4) * wordSize;
3075     mov(rscratch1, -step);
3076     sub(sp, sp, step);
3077     for (int i = 28; i >= 4; i -= 4) {
3078       st1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3079           as_FloatRegister(i+3), save_vectors ? T2D : T1D, Address(post(sp, rscratch1)));
3080     }
3081     st1(v0, v1, v2, v3, save_vectors ? T2D : T1D, sp);
3082   }
3083   if (save_vectors && use_sve && total_predicate_in_bytes > 0) {
3084     sub(sp, sp, total_predicate_in_bytes);
3085     for (int i = 0; i < PRegister::number_of_registers; i++) {
3086       sve_str(as_PRegister(i), Address(sp, i));
3087     }
3088   }
3089 }
3090 
3091 void MacroAssembler::pop_CPU_state(bool restore_vectors, bool use_sve,
3092                                    int sve_vector_size_in_bytes, int total_predicate_in_bytes) {
3093   if (restore_vectors && use_sve && total_predicate_in_bytes > 0) {
3094     for (int i = PRegister::number_of_registers - 1; i >= 0; i--) {
3095       sve_ldr(as_PRegister(i), Address(sp, i));
3096     }
3097     add(sp, sp, total_predicate_in_bytes);
3098   }
3099   if (restore_vectors && use_sve && sve_vector_size_in_bytes > 16) {
3100     for (int i = FloatRegister::number_of_registers - 1; i >= 0; i--) {
3101       sve_ldr(as_FloatRegister(i), Address(sp, i));
3102     }
3103     add(sp, sp, sve_vector_size_in_bytes * FloatRegister::number_of_registers);
3104   } else {
3105     int step = (restore_vectors ? 8 : 4) * wordSize;
3106     for (int i = 0; i <= 28; i += 4)
3107       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3108           as_FloatRegister(i+3), restore_vectors ? T2D : T1D, Address(post(sp, step)));
3109   }
3110 
3111   // We may use predicate registers and rely on ptrue with SVE,
3112   // regardless of wide vector (> 8 bytes) used or not.
3113   if (use_sve) {
3114     reinitialize_ptrue();
3115   }
3116 
3117   // integer registers except lr & sp
3118   pop(RegSet::range(r0, r17), sp);
3119 #ifdef R18_RESERVED
3120   ldp(zr, r19, Address(post(sp, 2 * wordSize)));
3121   pop(RegSet::range(r20, r29), sp);
3122 #else
3123   pop(RegSet::range(r18_tls, r29), sp);
3124 #endif
3125 }
3126 
3127 /**
3128  * Helpers for multiply_to_len().
3129  */
3130 void MacroAssembler::add2_with_carry(Register final_dest_hi, Register dest_hi, Register dest_lo,
3131                                      Register src1, Register src2) {
3132   adds(dest_lo, dest_lo, src1);
3133   adc(dest_hi, dest_hi, zr);
3134   adds(dest_lo, dest_lo, src2);
3135   adc(final_dest_hi, dest_hi, zr);
3136 }
3137 
3138 // Generate an address from (r + r1 extend offset).  "size" is the
3139 // size of the operand.  The result may be in rscratch2.
3140 Address MacroAssembler::offsetted_address(Register r, Register r1,
3141                                           Address::extend ext, int offset, int size) {
3142   if (offset || (ext.shift() % size != 0)) {
3143     lea(rscratch2, Address(r, r1, ext));
3144     return Address(rscratch2, offset);
3145   } else {
3146     return Address(r, r1, ext);
3147   }
3148 }
3149 
3150 Address MacroAssembler::spill_address(int size, int offset, Register tmp)
3151 {
3152   assert(offset >= 0, "spill to negative address?");
3153   // Offset reachable ?
3154   //   Not aligned - 9 bits signed offset
3155   //   Aligned - 12 bits unsigned offset shifted
3156   Register base = sp;
3157   if ((offset & (size-1)) && offset >= (1<<8)) {
3158     add(tmp, base, offset & ((1<<12)-1));
3159     base = tmp;
3160     offset &= -1u<<12;
3161   }
3162 
3163   if (offset >= (1<<12) * size) {
3164     add(tmp, base, offset & (((1<<12)-1)<<12));
3165     base = tmp;
3166     offset &= ~(((1<<12)-1)<<12);
3167   }
3168 
3169   return Address(base, offset);
3170 }
3171 
3172 Address MacroAssembler::sve_spill_address(int sve_reg_size_in_bytes, int offset, Register tmp) {
3173   assert(offset >= 0, "spill to negative address?");
3174 
3175   Register base = sp;
3176 
3177   // An immediate offset in the range 0 to 255 which is multiplied
3178   // by the current vector or predicate register size in bytes.
3179   if (offset % sve_reg_size_in_bytes == 0 && offset < ((1<<8)*sve_reg_size_in_bytes)) {
3180     return Address(base, offset / sve_reg_size_in_bytes);
3181   }
3182 
3183   add(tmp, base, offset);
3184   return Address(tmp);
3185 }
3186 
3187 // Checks whether offset is aligned.
3188 // Returns true if it is, else false.
3189 bool MacroAssembler::merge_alignment_check(Register base,
3190                                            size_t size,
3191                                            int64_t cur_offset,
3192                                            int64_t prev_offset) const {
3193   if (AvoidUnalignedAccesses) {
3194     if (base == sp) {
3195       // Checks whether low offset if aligned to pair of registers.
3196       int64_t pair_mask = size * 2 - 1;
3197       int64_t offset = prev_offset > cur_offset ? cur_offset : prev_offset;
3198       return (offset & pair_mask) == 0;
3199     } else { // If base is not sp, we can't guarantee the access is aligned.
3200       return false;
3201     }
3202   } else {
3203     int64_t mask = size - 1;
3204     // Load/store pair instruction only supports element size aligned offset.
3205     return (cur_offset & mask) == 0 && (prev_offset & mask) == 0;
3206   }
3207 }
3208 
3209 // Checks whether current and previous loads/stores can be merged.
3210 // Returns true if it can be merged, else false.
3211 bool MacroAssembler::ldst_can_merge(Register rt,
3212                                     const Address &adr,
3213                                     size_t cur_size_in_bytes,
3214                                     bool is_store) const {
3215   address prev = pc() - NativeInstruction::instruction_size;
3216   address last = code()->last_insn();
3217 
3218   if (last == NULL || !nativeInstruction_at(last)->is_Imm_LdSt()) {
3219     return false;
3220   }
3221 
3222   if (adr.getMode() != Address::base_plus_offset || prev != last) {
3223     return false;
3224   }
3225 
3226   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
3227   size_t prev_size_in_bytes = prev_ldst->size_in_bytes();
3228 
3229   assert(prev_size_in_bytes == 4 || prev_size_in_bytes == 8, "only supports 64/32bit merging.");
3230   assert(cur_size_in_bytes == 4 || cur_size_in_bytes == 8, "only supports 64/32bit merging.");
3231 
3232   if (cur_size_in_bytes != prev_size_in_bytes || is_store != prev_ldst->is_store()) {
3233     return false;
3234   }
3235 
3236   int64_t max_offset = 63 * prev_size_in_bytes;
3237   int64_t min_offset = -64 * prev_size_in_bytes;
3238 
3239   assert(prev_ldst->is_not_pre_post_index(), "pre-index or post-index is not supported to be merged.");
3240 
3241   // Only same base can be merged.
3242   if (adr.base() != prev_ldst->base()) {
3243     return false;
3244   }
3245 
3246   int64_t cur_offset = adr.offset();
3247   int64_t prev_offset = prev_ldst->offset();
3248   size_t diff = abs(cur_offset - prev_offset);
3249   if (diff != prev_size_in_bytes) {
3250     return false;
3251   }
3252 
3253   // Following cases can not be merged:
3254   // ldr x2, [x2, #8]
3255   // ldr x3, [x2, #16]
3256   // or:
3257   // ldr x2, [x3, #8]
3258   // ldr x2, [x3, #16]
3259   // If t1 and t2 is the same in "ldp t1, t2, [xn, #imm]", we'll get SIGILL.
3260   if (!is_store && (adr.base() == prev_ldst->target() || rt == prev_ldst->target())) {
3261     return false;
3262   }
3263 
3264   int64_t low_offset = prev_offset > cur_offset ? cur_offset : prev_offset;
3265   // Offset range must be in ldp/stp instruction's range.
3266   if (low_offset > max_offset || low_offset < min_offset) {
3267     return false;
3268   }
3269 
3270   if (merge_alignment_check(adr.base(), prev_size_in_bytes, cur_offset, prev_offset)) {
3271     return true;
3272   }
3273 
3274   return false;
3275 }
3276 
3277 // Merge current load/store with previous load/store into ldp/stp.
3278 void MacroAssembler::merge_ldst(Register rt,
3279                                 const Address &adr,
3280                                 size_t cur_size_in_bytes,
3281                                 bool is_store) {
3282 
3283   assert(ldst_can_merge(rt, adr, cur_size_in_bytes, is_store) == true, "cur and prev must be able to be merged.");
3284 
3285   Register rt_low, rt_high;
3286   address prev = pc() - NativeInstruction::instruction_size;
3287   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
3288 
3289   int64_t offset;
3290 
3291   if (adr.offset() < prev_ldst->offset()) {
3292     offset = adr.offset();
3293     rt_low = rt;
3294     rt_high = prev_ldst->target();
3295   } else {
3296     offset = prev_ldst->offset();
3297     rt_low = prev_ldst->target();
3298     rt_high = rt;
3299   }
3300 
3301   Address adr_p = Address(prev_ldst->base(), offset);
3302   // Overwrite previous generated binary.
3303   code_section()->set_end(prev);
3304 
3305   const size_t sz = prev_ldst->size_in_bytes();
3306   assert(sz == 8 || sz == 4, "only supports 64/32bit merging.");
3307   if (!is_store) {
3308     BLOCK_COMMENT("merged ldr pair");
3309     if (sz == 8) {
3310       ldp(rt_low, rt_high, adr_p);
3311     } else {
3312       ldpw(rt_low, rt_high, adr_p);
3313     }
3314   } else {
3315     BLOCK_COMMENT("merged str pair");
3316     if (sz == 8) {
3317       stp(rt_low, rt_high, adr_p);
3318     } else {
3319       stpw(rt_low, rt_high, adr_p);
3320     }
3321   }
3322 }
3323 
3324 /**
3325  * Multiply 64 bit by 64 bit first loop.
3326  */
3327 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
3328                                            Register y, Register y_idx, Register z,
3329                                            Register carry, Register product,
3330                                            Register idx, Register kdx) {
3331   //
3332   //  jlong carry, x[], y[], z[];
3333   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
3334   //    huge_128 product = y[idx] * x[xstart] + carry;
3335   //    z[kdx] = (jlong)product;
3336   //    carry  = (jlong)(product >>> 64);
3337   //  }
3338   //  z[xstart] = carry;
3339   //
3340 
3341   Label L_first_loop, L_first_loop_exit;
3342   Label L_one_x, L_one_y, L_multiply;
3343 
3344   subsw(xstart, xstart, 1);
3345   br(Assembler::MI, L_one_x);
3346 
3347   lea(rscratch1, Address(x, xstart, Address::lsl(LogBytesPerInt)));
3348   ldr(x_xstart, Address(rscratch1));
3349   ror(x_xstart, x_xstart, 32); // convert big-endian to little-endian
3350 
3351   bind(L_first_loop);
3352   subsw(idx, idx, 1);
3353   br(Assembler::MI, L_first_loop_exit);
3354   subsw(idx, idx, 1);
3355   br(Assembler::MI, L_one_y);
3356   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
3357   ldr(y_idx, Address(rscratch1));
3358   ror(y_idx, y_idx, 32); // convert big-endian to little-endian
3359   bind(L_multiply);
3360 
3361   // AArch64 has a multiply-accumulate instruction that we can't use
3362   // here because it has no way to process carries, so we have to use
3363   // separate add and adc instructions.  Bah.
3364   umulh(rscratch1, x_xstart, y_idx); // x_xstart * y_idx -> rscratch1:product
3365   mul(product, x_xstart, y_idx);
3366   adds(product, product, carry);
3367   adc(carry, rscratch1, zr);   // x_xstart * y_idx + carry -> carry:product
3368 
3369   subw(kdx, kdx, 2);
3370   ror(product, product, 32); // back to big-endian
3371   str(product, offsetted_address(z, kdx, Address::uxtw(LogBytesPerInt), 0, BytesPerLong));
3372 
3373   b(L_first_loop);
3374 
3375   bind(L_one_y);
3376   ldrw(y_idx, Address(y,  0));
3377   b(L_multiply);
3378 
3379   bind(L_one_x);
3380   ldrw(x_xstart, Address(x,  0));
3381   b(L_first_loop);
3382 
3383   bind(L_first_loop_exit);
3384 }
3385 
3386 /**
3387  * Multiply 128 bit by 128. Unrolled inner loop.
3388  *
3389  */
3390 void MacroAssembler::multiply_128_x_128_loop(Register y, Register z,
3391                                              Register carry, Register carry2,
3392                                              Register idx, Register jdx,
3393                                              Register yz_idx1, Register yz_idx2,
3394                                              Register tmp, Register tmp3, Register tmp4,
3395                                              Register tmp6, Register product_hi) {
3396 
3397   //   jlong carry, x[], y[], z[];
3398   //   int kdx = ystart+1;
3399   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
3400   //     huge_128 tmp3 = (y[idx+1] * product_hi) + z[kdx+idx+1] + carry;
3401   //     jlong carry2  = (jlong)(tmp3 >>> 64);
3402   //     huge_128 tmp4 = (y[idx]   * product_hi) + z[kdx+idx] + carry2;
3403   //     carry  = (jlong)(tmp4 >>> 64);
3404   //     z[kdx+idx+1] = (jlong)tmp3;
3405   //     z[kdx+idx] = (jlong)tmp4;
3406   //   }
3407   //   idx += 2;
3408   //   if (idx > 0) {
3409   //     yz_idx1 = (y[idx] * product_hi) + z[kdx+idx] + carry;
3410   //     z[kdx+idx] = (jlong)yz_idx1;
3411   //     carry  = (jlong)(yz_idx1 >>> 64);
3412   //   }
3413   //
3414 
3415   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
3416 
3417   lsrw(jdx, idx, 2);
3418 
3419   bind(L_third_loop);
3420 
3421   subsw(jdx, jdx, 1);
3422   br(Assembler::MI, L_third_loop_exit);
3423   subw(idx, idx, 4);
3424 
3425   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
3426 
3427   ldp(yz_idx2, yz_idx1, Address(rscratch1, 0));
3428 
3429   lea(tmp6, Address(z, idx, Address::uxtw(LogBytesPerInt)));
3430 
3431   ror(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
3432   ror(yz_idx2, yz_idx2, 32);
3433 
3434   ldp(rscratch2, rscratch1, Address(tmp6, 0));
3435 
3436   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
3437   umulh(tmp4, product_hi, yz_idx1);
3438 
3439   ror(rscratch1, rscratch1, 32); // convert big-endian to little-endian
3440   ror(rscratch2, rscratch2, 32);
3441 
3442   mul(tmp, product_hi, yz_idx2);   //  yz_idx2 * product_hi -> carry2:tmp
3443   umulh(carry2, product_hi, yz_idx2);
3444 
3445   // propagate sum of both multiplications into carry:tmp4:tmp3
3446   adds(tmp3, tmp3, carry);
3447   adc(tmp4, tmp4, zr);
3448   adds(tmp3, tmp3, rscratch1);
3449   adcs(tmp4, tmp4, tmp);
3450   adc(carry, carry2, zr);
3451   adds(tmp4, tmp4, rscratch2);
3452   adc(carry, carry, zr);
3453 
3454   ror(tmp3, tmp3, 32); // convert little-endian to big-endian
3455   ror(tmp4, tmp4, 32);
3456   stp(tmp4, tmp3, Address(tmp6, 0));
3457 
3458   b(L_third_loop);
3459   bind (L_third_loop_exit);
3460 
3461   andw (idx, idx, 0x3);
3462   cbz(idx, L_post_third_loop_done);
3463 
3464   Label L_check_1;
3465   subsw(idx, idx, 2);
3466   br(Assembler::MI, L_check_1);
3467 
3468   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
3469   ldr(yz_idx1, Address(rscratch1, 0));
3470   ror(yz_idx1, yz_idx1, 32);
3471   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
3472   umulh(tmp4, product_hi, yz_idx1);
3473   lea(rscratch1, Address(z, idx, Address::uxtw(LogBytesPerInt)));
3474   ldr(yz_idx2, Address(rscratch1, 0));
3475   ror(yz_idx2, yz_idx2, 32);
3476 
3477   add2_with_carry(carry, tmp4, tmp3, carry, yz_idx2);
3478 
3479   ror(tmp3, tmp3, 32);
3480   str(tmp3, Address(rscratch1, 0));
3481 
3482   bind (L_check_1);
3483 
3484   andw (idx, idx, 0x1);
3485   subsw(idx, idx, 1);
3486   br(Assembler::MI, L_post_third_loop_done);
3487   ldrw(tmp4, Address(y, idx, Address::uxtw(LogBytesPerInt)));
3488   mul(tmp3, tmp4, product_hi);  //  tmp4 * product_hi -> carry2:tmp3
3489   umulh(carry2, tmp4, product_hi);
3490   ldrw(tmp4, Address(z, idx, Address::uxtw(LogBytesPerInt)));
3491 
3492   add2_with_carry(carry2, tmp3, tmp4, carry);
3493 
3494   strw(tmp3, Address(z, idx, Address::uxtw(LogBytesPerInt)));
3495   extr(carry, carry2, tmp3, 32);
3496 
3497   bind(L_post_third_loop_done);
3498 }
3499 
3500 /**
3501  * Code for BigInteger::multiplyToLen() intrinsic.
3502  *
3503  * r0: x
3504  * r1: xlen
3505  * r2: y
3506  * r3: ylen
3507  * r4:  z
3508  * r5: zlen
3509  * r10: tmp1
3510  * r11: tmp2
3511  * r12: tmp3
3512  * r13: tmp4
3513  * r14: tmp5
3514  * r15: tmp6
3515  * r16: tmp7
3516  *
3517  */
3518 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen,
3519                                      Register z, Register zlen,
3520                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4,
3521                                      Register tmp5, Register tmp6, Register product_hi) {
3522 
3523   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6);
3524 
3525   const Register idx = tmp1;
3526   const Register kdx = tmp2;
3527   const Register xstart = tmp3;
3528 
3529   const Register y_idx = tmp4;
3530   const Register carry = tmp5;
3531   const Register product  = xlen;
3532   const Register x_xstart = zlen;  // reuse register
3533 
3534   // First Loop.
3535   //
3536   //  final static long LONG_MASK = 0xffffffffL;
3537   //  int xstart = xlen - 1;
3538   //  int ystart = ylen - 1;
3539   //  long carry = 0;
3540   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
3541   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
3542   //    z[kdx] = (int)product;
3543   //    carry = product >>> 32;
3544   //  }
3545   //  z[xstart] = (int)carry;
3546   //
3547 
3548   movw(idx, ylen);      // idx = ylen;
3549   movw(kdx, zlen);      // kdx = xlen+ylen;
3550   mov(carry, zr);       // carry = 0;
3551 
3552   Label L_done;
3553 
3554   movw(xstart, xlen);
3555   subsw(xstart, xstart, 1);
3556   br(Assembler::MI, L_done);
3557 
3558   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
3559 
3560   Label L_second_loop;
3561   cbzw(kdx, L_second_loop);
3562 
3563   Label L_carry;
3564   subw(kdx, kdx, 1);
3565   cbzw(kdx, L_carry);
3566 
3567   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
3568   lsr(carry, carry, 32);
3569   subw(kdx, kdx, 1);
3570 
3571   bind(L_carry);
3572   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
3573 
3574   // Second and third (nested) loops.
3575   //
3576   // for (int i = xstart-1; i >= 0; i--) { // Second loop
3577   //   carry = 0;
3578   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
3579   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
3580   //                    (z[k] & LONG_MASK) + carry;
3581   //     z[k] = (int)product;
3582   //     carry = product >>> 32;
3583   //   }
3584   //   z[i] = (int)carry;
3585   // }
3586   //
3587   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = product_hi
3588 
3589   const Register jdx = tmp1;
3590 
3591   bind(L_second_loop);
3592   mov(carry, zr);                // carry = 0;
3593   movw(jdx, ylen);               // j = ystart+1
3594 
3595   subsw(xstart, xstart, 1);      // i = xstart-1;
3596   br(Assembler::MI, L_done);
3597 
3598   str(z, Address(pre(sp, -4 * wordSize)));
3599 
3600   Label L_last_x;
3601   lea(z, offsetted_address(z, xstart, Address::uxtw(LogBytesPerInt), 4, BytesPerInt)); // z = z + k - j
3602   subsw(xstart, xstart, 1);       // i = xstart-1;
3603   br(Assembler::MI, L_last_x);
3604 
3605   lea(rscratch1, Address(x, xstart, Address::uxtw(LogBytesPerInt)));
3606   ldr(product_hi, Address(rscratch1));
3607   ror(product_hi, product_hi, 32);  // convert big-endian to little-endian
3608 
3609   Label L_third_loop_prologue;
3610   bind(L_third_loop_prologue);
3611 
3612   str(ylen, Address(sp, wordSize));
3613   stp(x, xstart, Address(sp, 2 * wordSize));
3614   multiply_128_x_128_loop(y, z, carry, x, jdx, ylen, product,
3615                           tmp2, x_xstart, tmp3, tmp4, tmp6, product_hi);
3616   ldp(z, ylen, Address(post(sp, 2 * wordSize)));
3617   ldp(x, xlen, Address(post(sp, 2 * wordSize)));   // copy old xstart -> xlen
3618 
3619   addw(tmp3, xlen, 1);
3620   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
3621   subsw(tmp3, tmp3, 1);
3622   br(Assembler::MI, L_done);
3623 
3624   lsr(carry, carry, 32);
3625   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
3626   b(L_second_loop);
3627 
3628   // Next infrequent code is moved outside loops.
3629   bind(L_last_x);
3630   ldrw(product_hi, Address(x,  0));
3631   b(L_third_loop_prologue);
3632 
3633   bind(L_done);
3634 }
3635 
3636 // Code for BigInteger::mulAdd intrinsic
3637 // out     = r0
3638 // in      = r1
3639 // offset  = r2  (already out.length-offset)
3640 // len     = r3
3641 // k       = r4
3642 //
3643 // pseudo code from java implementation:
3644 // carry = 0;
3645 // offset = out.length-offset - 1;
3646 // for (int j=len-1; j >= 0; j--) {
3647 //     product = (in[j] & LONG_MASK) * kLong + (out[offset] & LONG_MASK) + carry;
3648 //     out[offset--] = (int)product;
3649 //     carry = product >>> 32;
3650 // }
3651 // return (int)carry;
3652 void MacroAssembler::mul_add(Register out, Register in, Register offset,
3653       Register len, Register k) {
3654     Label LOOP, END;
3655     // pre-loop
3656     cmp(len, zr); // cmp, not cbz/cbnz: to use condition twice => less branches
3657     csel(out, zr, out, Assembler::EQ);
3658     br(Assembler::EQ, END);
3659     add(in, in, len, LSL, 2); // in[j+1] address
3660     add(offset, out, offset, LSL, 2); // out[offset + 1] address
3661     mov(out, zr); // used to keep carry now
3662     BIND(LOOP);
3663     ldrw(rscratch1, Address(pre(in, -4)));
3664     madd(rscratch1, rscratch1, k, out);
3665     ldrw(rscratch2, Address(pre(offset, -4)));
3666     add(rscratch1, rscratch1, rscratch2);
3667     strw(rscratch1, Address(offset));
3668     lsr(out, rscratch1, 32);
3669     subs(len, len, 1);
3670     br(Assembler::NE, LOOP);
3671     BIND(END);
3672 }
3673 
3674 /**
3675  * Emits code to update CRC-32 with a byte value according to constants in table
3676  *
3677  * @param [in,out]crc   Register containing the crc.
3678  * @param [in]val       Register containing the byte to fold into the CRC.
3679  * @param [in]table     Register containing the table of crc constants.
3680  *
3681  * uint32_t crc;
3682  * val = crc_table[(val ^ crc) & 0xFF];
3683  * crc = val ^ (crc >> 8);
3684  *
3685  */
3686 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
3687   eor(val, val, crc);
3688   andr(val, val, 0xff);
3689   ldrw(val, Address(table, val, Address::lsl(2)));
3690   eor(crc, val, crc, Assembler::LSR, 8);
3691 }
3692 
3693 /**
3694  * Emits code to update CRC-32 with a 32-bit value according to tables 0 to 3
3695  *
3696  * @param [in,out]crc   Register containing the crc.
3697  * @param [in]v         Register containing the 32-bit to fold into the CRC.
3698  * @param [in]table0    Register containing table 0 of crc constants.
3699  * @param [in]table1    Register containing table 1 of crc constants.
3700  * @param [in]table2    Register containing table 2 of crc constants.
3701  * @param [in]table3    Register containing table 3 of crc constants.
3702  *
3703  * uint32_t crc;
3704  *   v = crc ^ v
3705  *   crc = table3[v&0xff]^table2[(v>>8)&0xff]^table1[(v>>16)&0xff]^table0[v>>24]
3706  *
3707  */
3708 void MacroAssembler::update_word_crc32(Register crc, Register v, Register tmp,
3709         Register table0, Register table1, Register table2, Register table3,
3710         bool upper) {
3711   eor(v, crc, v, upper ? LSR:LSL, upper ? 32:0);
3712   uxtb(tmp, v);
3713   ldrw(crc, Address(table3, tmp, Address::lsl(2)));
3714   ubfx(tmp, v, 8, 8);
3715   ldrw(tmp, Address(table2, tmp, Address::lsl(2)));
3716   eor(crc, crc, tmp);
3717   ubfx(tmp, v, 16, 8);
3718   ldrw(tmp, Address(table1, tmp, Address::lsl(2)));
3719   eor(crc, crc, tmp);
3720   ubfx(tmp, v, 24, 8);
3721   ldrw(tmp, Address(table0, tmp, Address::lsl(2)));
3722   eor(crc, crc, tmp);
3723 }
3724 
3725 void MacroAssembler::kernel_crc32_using_crc32(Register crc, Register buf,
3726         Register len, Register tmp0, Register tmp1, Register tmp2,
3727         Register tmp3) {
3728     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
3729     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
3730 
3731     mvnw(crc, crc);
3732 
3733     subs(len, len, 128);
3734     br(Assembler::GE, CRC_by64_pre);
3735   BIND(CRC_less64);
3736     adds(len, len, 128-32);
3737     br(Assembler::GE, CRC_by32_loop);
3738   BIND(CRC_less32);
3739     adds(len, len, 32-4);
3740     br(Assembler::GE, CRC_by4_loop);
3741     adds(len, len, 4);
3742     br(Assembler::GT, CRC_by1_loop);
3743     b(L_exit);
3744 
3745   BIND(CRC_by32_loop);
3746     ldp(tmp0, tmp1, Address(post(buf, 16)));
3747     subs(len, len, 32);
3748     crc32x(crc, crc, tmp0);
3749     ldr(tmp2, Address(post(buf, 8)));
3750     crc32x(crc, crc, tmp1);
3751     ldr(tmp3, Address(post(buf, 8)));
3752     crc32x(crc, crc, tmp2);
3753     crc32x(crc, crc, tmp3);
3754     br(Assembler::GE, CRC_by32_loop);
3755     cmn(len, (u1)32);
3756     br(Assembler::NE, CRC_less32);
3757     b(L_exit);
3758 
3759   BIND(CRC_by4_loop);
3760     ldrw(tmp0, Address(post(buf, 4)));
3761     subs(len, len, 4);
3762     crc32w(crc, crc, tmp0);
3763     br(Assembler::GE, CRC_by4_loop);
3764     adds(len, len, 4);
3765     br(Assembler::LE, L_exit);
3766   BIND(CRC_by1_loop);
3767     ldrb(tmp0, Address(post(buf, 1)));
3768     subs(len, len, 1);
3769     crc32b(crc, crc, tmp0);
3770     br(Assembler::GT, CRC_by1_loop);
3771     b(L_exit);
3772 
3773   BIND(CRC_by64_pre);
3774     sub(buf, buf, 8);
3775     ldp(tmp0, tmp1, Address(buf, 8));
3776     crc32x(crc, crc, tmp0);
3777     ldr(tmp2, Address(buf, 24));
3778     crc32x(crc, crc, tmp1);
3779     ldr(tmp3, Address(buf, 32));
3780     crc32x(crc, crc, tmp2);
3781     ldr(tmp0, Address(buf, 40));
3782     crc32x(crc, crc, tmp3);
3783     ldr(tmp1, Address(buf, 48));
3784     crc32x(crc, crc, tmp0);
3785     ldr(tmp2, Address(buf, 56));
3786     crc32x(crc, crc, tmp1);
3787     ldr(tmp3, Address(pre(buf, 64)));
3788 
3789     b(CRC_by64_loop);
3790 
3791     align(CodeEntryAlignment);
3792   BIND(CRC_by64_loop);
3793     subs(len, len, 64);
3794     crc32x(crc, crc, tmp2);
3795     ldr(tmp0, Address(buf, 8));
3796     crc32x(crc, crc, tmp3);
3797     ldr(tmp1, Address(buf, 16));
3798     crc32x(crc, crc, tmp0);
3799     ldr(tmp2, Address(buf, 24));
3800     crc32x(crc, crc, tmp1);
3801     ldr(tmp3, Address(buf, 32));
3802     crc32x(crc, crc, tmp2);
3803     ldr(tmp0, Address(buf, 40));
3804     crc32x(crc, crc, tmp3);
3805     ldr(tmp1, Address(buf, 48));
3806     crc32x(crc, crc, tmp0);
3807     ldr(tmp2, Address(buf, 56));
3808     crc32x(crc, crc, tmp1);
3809     ldr(tmp3, Address(pre(buf, 64)));
3810     br(Assembler::GE, CRC_by64_loop);
3811 
3812     // post-loop
3813     crc32x(crc, crc, tmp2);
3814     crc32x(crc, crc, tmp3);
3815 
3816     sub(len, len, 64);
3817     add(buf, buf, 8);
3818     cmn(len, (u1)128);
3819     br(Assembler::NE, CRC_less64);
3820   BIND(L_exit);
3821     mvnw(crc, crc);
3822 }
3823 
3824 /**
3825  * @param crc   register containing existing CRC (32-bit)
3826  * @param buf   register pointing to input byte buffer (byte*)
3827  * @param len   register containing number of bytes
3828  * @param table register that will contain address of CRC table
3829  * @param tmp   scratch register
3830  */
3831 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len,
3832         Register table0, Register table1, Register table2, Register table3,
3833         Register tmp, Register tmp2, Register tmp3) {
3834   Label L_by16, L_by16_loop, L_by4, L_by4_loop, L_by1, L_by1_loop, L_exit;
3835 
3836   if (UseCRC32) {
3837       kernel_crc32_using_crc32(crc, buf, len, table0, table1, table2, table3);
3838       return;
3839   }
3840 
3841     mvnw(crc, crc);
3842 
3843     {
3844       uint64_t offset;
3845       adrp(table0, ExternalAddress(StubRoutines::crc_table_addr()), offset);
3846       add(table0, table0, offset);
3847     }
3848     add(table1, table0, 1*256*sizeof(juint));
3849     add(table2, table0, 2*256*sizeof(juint));
3850     add(table3, table0, 3*256*sizeof(juint));
3851 
3852   if (UseNeon) {
3853       cmp(len, (u1)64);
3854       br(Assembler::LT, L_by16);
3855       eor(v16, T16B, v16, v16);
3856 
3857     Label L_fold;
3858 
3859       add(tmp, table0, 4*256*sizeof(juint)); // Point at the Neon constants
3860 
3861       ld1(v0, v1, T2D, post(buf, 32));
3862       ld1r(v4, T2D, post(tmp, 8));
3863       ld1r(v5, T2D, post(tmp, 8));
3864       ld1r(v6, T2D, post(tmp, 8));
3865       ld1r(v7, T2D, post(tmp, 8));
3866       mov(v16, S, 0, crc);
3867 
3868       eor(v0, T16B, v0, v16);
3869       sub(len, len, 64);
3870 
3871     BIND(L_fold);
3872       pmull(v22, T8H, v0, v5, T8B);
3873       pmull(v20, T8H, v0, v7, T8B);
3874       pmull(v23, T8H, v0, v4, T8B);
3875       pmull(v21, T8H, v0, v6, T8B);
3876 
3877       pmull2(v18, T8H, v0, v5, T16B);
3878       pmull2(v16, T8H, v0, v7, T16B);
3879       pmull2(v19, T8H, v0, v4, T16B);
3880       pmull2(v17, T8H, v0, v6, T16B);
3881 
3882       uzp1(v24, T8H, v20, v22);
3883       uzp2(v25, T8H, v20, v22);
3884       eor(v20, T16B, v24, v25);
3885 
3886       uzp1(v26, T8H, v16, v18);
3887       uzp2(v27, T8H, v16, v18);
3888       eor(v16, T16B, v26, v27);
3889 
3890       ushll2(v22, T4S, v20, T8H, 8);
3891       ushll(v20, T4S, v20, T4H, 8);
3892 
3893       ushll2(v18, T4S, v16, T8H, 8);
3894       ushll(v16, T4S, v16, T4H, 8);
3895 
3896       eor(v22, T16B, v23, v22);
3897       eor(v18, T16B, v19, v18);
3898       eor(v20, T16B, v21, v20);
3899       eor(v16, T16B, v17, v16);
3900 
3901       uzp1(v17, T2D, v16, v20);
3902       uzp2(v21, T2D, v16, v20);
3903       eor(v17, T16B, v17, v21);
3904 
3905       ushll2(v20, T2D, v17, T4S, 16);
3906       ushll(v16, T2D, v17, T2S, 16);
3907 
3908       eor(v20, T16B, v20, v22);
3909       eor(v16, T16B, v16, v18);
3910 
3911       uzp1(v17, T2D, v20, v16);
3912       uzp2(v21, T2D, v20, v16);
3913       eor(v28, T16B, v17, v21);
3914 
3915       pmull(v22, T8H, v1, v5, T8B);
3916       pmull(v20, T8H, v1, v7, T8B);
3917       pmull(v23, T8H, v1, v4, T8B);
3918       pmull(v21, T8H, v1, v6, T8B);
3919 
3920       pmull2(v18, T8H, v1, v5, T16B);
3921       pmull2(v16, T8H, v1, v7, T16B);
3922       pmull2(v19, T8H, v1, v4, T16B);
3923       pmull2(v17, T8H, v1, v6, T16B);
3924 
3925       ld1(v0, v1, T2D, post(buf, 32));
3926 
3927       uzp1(v24, T8H, v20, v22);
3928       uzp2(v25, T8H, v20, v22);
3929       eor(v20, T16B, v24, v25);
3930 
3931       uzp1(v26, T8H, v16, v18);
3932       uzp2(v27, T8H, v16, v18);
3933       eor(v16, T16B, v26, v27);
3934 
3935       ushll2(v22, T4S, v20, T8H, 8);
3936       ushll(v20, T4S, v20, T4H, 8);
3937 
3938       ushll2(v18, T4S, v16, T8H, 8);
3939       ushll(v16, T4S, v16, T4H, 8);
3940 
3941       eor(v22, T16B, v23, v22);
3942       eor(v18, T16B, v19, v18);
3943       eor(v20, T16B, v21, v20);
3944       eor(v16, T16B, v17, v16);
3945 
3946       uzp1(v17, T2D, v16, v20);
3947       uzp2(v21, T2D, v16, v20);
3948       eor(v16, T16B, v17, v21);
3949 
3950       ushll2(v20, T2D, v16, T4S, 16);
3951       ushll(v16, T2D, v16, T2S, 16);
3952 
3953       eor(v20, T16B, v22, v20);
3954       eor(v16, T16B, v16, v18);
3955 
3956       uzp1(v17, T2D, v20, v16);
3957       uzp2(v21, T2D, v20, v16);
3958       eor(v20, T16B, v17, v21);
3959 
3960       shl(v16, T2D, v28, 1);
3961       shl(v17, T2D, v20, 1);
3962 
3963       eor(v0, T16B, v0, v16);
3964       eor(v1, T16B, v1, v17);
3965 
3966       subs(len, len, 32);
3967       br(Assembler::GE, L_fold);
3968 
3969       mov(crc, 0);
3970       mov(tmp, v0, D, 0);
3971       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3972       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3973       mov(tmp, v0, D, 1);
3974       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3975       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3976       mov(tmp, v1, D, 0);
3977       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3978       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3979       mov(tmp, v1, D, 1);
3980       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3981       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3982 
3983       add(len, len, 32);
3984   }
3985 
3986   BIND(L_by16);
3987     subs(len, len, 16);
3988     br(Assembler::GE, L_by16_loop);
3989     adds(len, len, 16-4);
3990     br(Assembler::GE, L_by4_loop);
3991     adds(len, len, 4);
3992     br(Assembler::GT, L_by1_loop);
3993     b(L_exit);
3994 
3995   BIND(L_by4_loop);
3996     ldrw(tmp, Address(post(buf, 4)));
3997     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3);
3998     subs(len, len, 4);
3999     br(Assembler::GE, L_by4_loop);
4000     adds(len, len, 4);
4001     br(Assembler::LE, L_exit);
4002   BIND(L_by1_loop);
4003     subs(len, len, 1);
4004     ldrb(tmp, Address(post(buf, 1)));
4005     update_byte_crc32(crc, tmp, table0);
4006     br(Assembler::GT, L_by1_loop);
4007     b(L_exit);
4008 
4009     align(CodeEntryAlignment);
4010   BIND(L_by16_loop);
4011     subs(len, len, 16);
4012     ldp(tmp, tmp3, Address(post(buf, 16)));
4013     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4014     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4015     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, false);
4016     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, true);
4017     br(Assembler::GE, L_by16_loop);
4018     adds(len, len, 16-4);
4019     br(Assembler::GE, L_by4_loop);
4020     adds(len, len, 4);
4021     br(Assembler::GT, L_by1_loop);
4022   BIND(L_exit);
4023     mvnw(crc, crc);
4024 }
4025 
4026 void MacroAssembler::kernel_crc32c_using_crc32c(Register crc, Register buf,
4027         Register len, Register tmp0, Register tmp1, Register tmp2,
4028         Register tmp3) {
4029     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
4030     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
4031 
4032     subs(len, len, 128);
4033     br(Assembler::GE, CRC_by64_pre);
4034   BIND(CRC_less64);
4035     adds(len, len, 128-32);
4036     br(Assembler::GE, CRC_by32_loop);
4037   BIND(CRC_less32);
4038     adds(len, len, 32-4);
4039     br(Assembler::GE, CRC_by4_loop);
4040     adds(len, len, 4);
4041     br(Assembler::GT, CRC_by1_loop);
4042     b(L_exit);
4043 
4044   BIND(CRC_by32_loop);
4045     ldp(tmp0, tmp1, Address(post(buf, 16)));
4046     subs(len, len, 32);
4047     crc32cx(crc, crc, tmp0);
4048     ldr(tmp2, Address(post(buf, 8)));
4049     crc32cx(crc, crc, tmp1);
4050     ldr(tmp3, Address(post(buf, 8)));
4051     crc32cx(crc, crc, tmp2);
4052     crc32cx(crc, crc, tmp3);
4053     br(Assembler::GE, CRC_by32_loop);
4054     cmn(len, (u1)32);
4055     br(Assembler::NE, CRC_less32);
4056     b(L_exit);
4057 
4058   BIND(CRC_by4_loop);
4059     ldrw(tmp0, Address(post(buf, 4)));
4060     subs(len, len, 4);
4061     crc32cw(crc, crc, tmp0);
4062     br(Assembler::GE, CRC_by4_loop);
4063     adds(len, len, 4);
4064     br(Assembler::LE, L_exit);
4065   BIND(CRC_by1_loop);
4066     ldrb(tmp0, Address(post(buf, 1)));
4067     subs(len, len, 1);
4068     crc32cb(crc, crc, tmp0);
4069     br(Assembler::GT, CRC_by1_loop);
4070     b(L_exit);
4071 
4072   BIND(CRC_by64_pre);
4073     sub(buf, buf, 8);
4074     ldp(tmp0, tmp1, Address(buf, 8));
4075     crc32cx(crc, crc, tmp0);
4076     ldr(tmp2, Address(buf, 24));
4077     crc32cx(crc, crc, tmp1);
4078     ldr(tmp3, Address(buf, 32));
4079     crc32cx(crc, crc, tmp2);
4080     ldr(tmp0, Address(buf, 40));
4081     crc32cx(crc, crc, tmp3);
4082     ldr(tmp1, Address(buf, 48));
4083     crc32cx(crc, crc, tmp0);
4084     ldr(tmp2, Address(buf, 56));
4085     crc32cx(crc, crc, tmp1);
4086     ldr(tmp3, Address(pre(buf, 64)));
4087 
4088     b(CRC_by64_loop);
4089 
4090     align(CodeEntryAlignment);
4091   BIND(CRC_by64_loop);
4092     subs(len, len, 64);
4093     crc32cx(crc, crc, tmp2);
4094     ldr(tmp0, Address(buf, 8));
4095     crc32cx(crc, crc, tmp3);
4096     ldr(tmp1, Address(buf, 16));
4097     crc32cx(crc, crc, tmp0);
4098     ldr(tmp2, Address(buf, 24));
4099     crc32cx(crc, crc, tmp1);
4100     ldr(tmp3, Address(buf, 32));
4101     crc32cx(crc, crc, tmp2);
4102     ldr(tmp0, Address(buf, 40));
4103     crc32cx(crc, crc, tmp3);
4104     ldr(tmp1, Address(buf, 48));
4105     crc32cx(crc, crc, tmp0);
4106     ldr(tmp2, Address(buf, 56));
4107     crc32cx(crc, crc, tmp1);
4108     ldr(tmp3, Address(pre(buf, 64)));
4109     br(Assembler::GE, CRC_by64_loop);
4110 
4111     // post-loop
4112     crc32cx(crc, crc, tmp2);
4113     crc32cx(crc, crc, tmp3);
4114 
4115     sub(len, len, 64);
4116     add(buf, buf, 8);
4117     cmn(len, (u1)128);
4118     br(Assembler::NE, CRC_less64);
4119   BIND(L_exit);
4120 }
4121 
4122 /**
4123  * @param crc   register containing existing CRC (32-bit)
4124  * @param buf   register pointing to input byte buffer (byte*)
4125  * @param len   register containing number of bytes
4126  * @param table register that will contain address of CRC table
4127  * @param tmp   scratch register
4128  */
4129 void MacroAssembler::kernel_crc32c(Register crc, Register buf, Register len,
4130         Register table0, Register table1, Register table2, Register table3,
4131         Register tmp, Register tmp2, Register tmp3) {
4132   kernel_crc32c_using_crc32c(crc, buf, len, table0, table1, table2, table3);
4133 }
4134 
4135 
4136 SkipIfEqual::SkipIfEqual(
4137     MacroAssembler* masm, const bool* flag_addr, bool value) {
4138   _masm = masm;
4139   uint64_t offset;
4140   _masm->adrp(rscratch1, ExternalAddress((address)flag_addr), offset);
4141   _masm->ldrb(rscratch1, Address(rscratch1, offset));
4142   if (value) {
4143     _masm->cbnzw(rscratch1, _label);
4144   } else {
4145     _masm->cbzw(rscratch1, _label);
4146   }
4147 }
4148 
4149 SkipIfEqual::~SkipIfEqual() {
4150   _masm->bind(_label);
4151 }
4152 
4153 void MacroAssembler::addptr(const Address &dst, int32_t src) {
4154   Address adr;
4155   switch(dst.getMode()) {
4156   case Address::base_plus_offset:
4157     // This is the expected mode, although we allow all the other
4158     // forms below.
4159     adr = form_address(rscratch2, dst.base(), dst.offset(), LogBytesPerWord);
4160     break;
4161   default:
4162     lea(rscratch2, dst);
4163     adr = Address(rscratch2);
4164     break;
4165   }
4166   ldr(rscratch1, adr);
4167   add(rscratch1, rscratch1, src);
4168   str(rscratch1, adr);
4169 }
4170 
4171 void MacroAssembler::cmpptr(Register src1, Address src2) {
4172   uint64_t offset;
4173   adrp(rscratch1, src2, offset);
4174   ldr(rscratch1, Address(rscratch1, offset));
4175   cmp(src1, rscratch1);
4176 }
4177 
4178 void MacroAssembler::cmpoop(Register obj1, Register obj2) {
4179   cmp(obj1, obj2);
4180 }
4181 
4182 void MacroAssembler::load_method_holder_cld(Register rresult, Register rmethod) {
4183   load_method_holder(rresult, rmethod);
4184   ldr(rresult, Address(rresult, InstanceKlass::class_loader_data_offset()));
4185 }
4186 
4187 void MacroAssembler::load_method_holder(Register holder, Register method) {
4188   ldr(holder, Address(method, Method::const_offset()));                      // ConstMethod*
4189   ldr(holder, Address(holder, ConstMethod::constants_offset()));             // ConstantPool*
4190   ldr(holder, Address(holder, ConstantPool::pool_holder_offset_in_bytes())); // InstanceKlass*
4191 }
4192 
4193 void MacroAssembler::load_metadata(Register dst, Register src) {
4194   if (UseCompressedClassPointers) {
4195     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
4196   } else {
4197     ldr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
4198   }
4199 }
4200 
4201 void MacroAssembler::load_klass(Register dst, Register src) {
4202   if (UseCompressedClassPointers) {
4203     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
4204     decode_klass_not_null(dst);
4205   } else {
4206     ldr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
4207   }
4208 }
4209 
4210 // ((OopHandle)result).resolve();
4211 void MacroAssembler::resolve_oop_handle(Register result, Register tmp1, Register tmp2) {
4212   // OopHandle::resolve is an indirection.
4213   access_load_at(T_OBJECT, IN_NATIVE, result, Address(result, 0), tmp1, tmp2);
4214 }
4215 
4216 // ((WeakHandle)result).resolve();
4217 void MacroAssembler::resolve_weak_handle(Register result, Register tmp1, Register tmp2) {
4218   assert_different_registers(result, tmp1, tmp2);
4219   Label resolved;
4220 
4221   // A null weak handle resolves to null.
4222   cbz(result, resolved);
4223 
4224   // Only 64 bit platforms support GCs that require a tmp register
4225   // WeakHandle::resolve is an indirection like jweak.
4226   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
4227                  result, Address(result), tmp1, tmp2);
4228   bind(resolved);
4229 }
4230 
4231 void MacroAssembler::load_mirror(Register dst, Register method, Register tmp1, Register tmp2) {
4232   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
4233   ldr(dst, Address(rmethod, Method::const_offset()));
4234   ldr(dst, Address(dst, ConstMethod::constants_offset()));
4235   ldr(dst, Address(dst, ConstantPool::pool_holder_offset_in_bytes()));
4236   ldr(dst, Address(dst, mirror_offset));
4237   resolve_oop_handle(dst, tmp1, tmp2);
4238 }
4239 
4240 void MacroAssembler::cmp_klass(Register oop, Register trial_klass, Register tmp) {
4241   if (UseCompressedClassPointers) {
4242     ldrw(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
4243     if (CompressedKlassPointers::base() == NULL) {
4244       cmp(trial_klass, tmp, LSL, CompressedKlassPointers::shift());
4245       return;
4246     } else if (((uint64_t)CompressedKlassPointers::base() & 0xffffffff) == 0
4247                && CompressedKlassPointers::shift() == 0) {
4248       // Only the bottom 32 bits matter
4249       cmpw(trial_klass, tmp);
4250       return;
4251     }
4252     decode_klass_not_null(tmp);
4253   } else {
4254     ldr(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
4255   }
4256   cmp(trial_klass, tmp);
4257 }
4258 
4259 void MacroAssembler::load_prototype_header(Register dst, Register src) {
4260   load_klass(dst, src);
4261   ldr(dst, Address(dst, Klass::prototype_header_offset()));
4262 }
4263 
4264 void MacroAssembler::store_klass(Register dst, Register src) {
4265   // FIXME: Should this be a store release?  concurrent gcs assumes
4266   // klass length is valid if klass field is not null.
4267   if (UseCompressedClassPointers) {
4268     encode_klass_not_null(src);
4269     strw(src, Address(dst, oopDesc::klass_offset_in_bytes()));
4270   } else {
4271     str(src, Address(dst, oopDesc::klass_offset_in_bytes()));
4272   }
4273 }
4274 
4275 void MacroAssembler::store_klass_gap(Register dst, Register src) {
4276   if (UseCompressedClassPointers) {
4277     // Store to klass gap in destination
4278     strw(src, Address(dst, oopDesc::klass_gap_offset_in_bytes()));
4279   }
4280 }
4281 
4282 // Algorithm must match CompressedOops::encode.
4283 void MacroAssembler::encode_heap_oop(Register d, Register s) {
4284 #ifdef ASSERT
4285   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
4286 #endif
4287   verify_oop_msg(s, "broken oop in encode_heap_oop");
4288   if (CompressedOops::base() == NULL) {
4289     if (CompressedOops::shift() != 0) {
4290       assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4291       lsr(d, s, LogMinObjAlignmentInBytes);
4292     } else {
4293       mov(d, s);
4294     }
4295   } else {
4296     subs(d, s, rheapbase);
4297     csel(d, d, zr, Assembler::HS);
4298     lsr(d, d, LogMinObjAlignmentInBytes);
4299 
4300     /*  Old algorithm: is this any worse?
4301     Label nonnull;
4302     cbnz(r, nonnull);
4303     sub(r, r, rheapbase);
4304     bind(nonnull);
4305     lsr(r, r, LogMinObjAlignmentInBytes);
4306     */
4307   }
4308 }
4309 
4310 void MacroAssembler::encode_heap_oop_not_null(Register r) {
4311 #ifdef ASSERT
4312   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
4313   if (CheckCompressedOops) {
4314     Label ok;
4315     cbnz(r, ok);
4316     stop("null oop passed to encode_heap_oop_not_null");
4317     bind(ok);
4318   }
4319 #endif
4320   verify_oop_msg(r, "broken oop in encode_heap_oop_not_null");
4321   if (CompressedOops::base() != NULL) {
4322     sub(r, r, rheapbase);
4323   }
4324   if (CompressedOops::shift() != 0) {
4325     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4326     lsr(r, r, LogMinObjAlignmentInBytes);
4327   }
4328 }
4329 
4330 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
4331 #ifdef ASSERT
4332   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
4333   if (CheckCompressedOops) {
4334     Label ok;
4335     cbnz(src, ok);
4336     stop("null oop passed to encode_heap_oop_not_null2");
4337     bind(ok);
4338   }
4339 #endif
4340   verify_oop_msg(src, "broken oop in encode_heap_oop_not_null2");
4341 
4342   Register data = src;
4343   if (CompressedOops::base() != NULL) {
4344     sub(dst, src, rheapbase);
4345     data = dst;
4346   }
4347   if (CompressedOops::shift() != 0) {
4348     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4349     lsr(dst, data, LogMinObjAlignmentInBytes);
4350     data = dst;
4351   }
4352   if (data == src)
4353     mov(dst, src);
4354 }
4355 
4356 void  MacroAssembler::decode_heap_oop(Register d, Register s) {
4357 #ifdef ASSERT
4358   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
4359 #endif
4360   if (CompressedOops::base() == NULL) {
4361     if (CompressedOops::shift() != 0 || d != s) {
4362       lsl(d, s, CompressedOops::shift());
4363     }
4364   } else {
4365     Label done;
4366     if (d != s)
4367       mov(d, s);
4368     cbz(s, done);
4369     add(d, rheapbase, s, Assembler::LSL, LogMinObjAlignmentInBytes);
4370     bind(done);
4371   }
4372   verify_oop_msg(d, "broken oop in decode_heap_oop");
4373 }
4374 
4375 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
4376   assert (UseCompressedOops, "should only be used for compressed headers");
4377   assert (Universe::heap() != NULL, "java heap should be initialized");
4378   // Cannot assert, unverified entry point counts instructions (see .ad file)
4379   // vtableStubs also counts instructions in pd_code_size_limit.
4380   // Also do not verify_oop as this is called by verify_oop.
4381   if (CompressedOops::shift() != 0) {
4382     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4383     if (CompressedOops::base() != NULL) {
4384       add(r, rheapbase, r, Assembler::LSL, LogMinObjAlignmentInBytes);
4385     } else {
4386       add(r, zr, r, Assembler::LSL, LogMinObjAlignmentInBytes);
4387     }
4388   } else {
4389     assert (CompressedOops::base() == NULL, "sanity");
4390   }
4391 }
4392 
4393 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
4394   assert (UseCompressedOops, "should only be used for compressed headers");
4395   assert (Universe::heap() != NULL, "java heap should be initialized");
4396   // Cannot assert, unverified entry point counts instructions (see .ad file)
4397   // vtableStubs also counts instructions in pd_code_size_limit.
4398   // Also do not verify_oop as this is called by verify_oop.
4399   if (CompressedOops::shift() != 0) {
4400     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4401     if (CompressedOops::base() != NULL) {
4402       add(dst, rheapbase, src, Assembler::LSL, LogMinObjAlignmentInBytes);
4403     } else {
4404       add(dst, zr, src, Assembler::LSL, LogMinObjAlignmentInBytes);
4405     }
4406   } else {
4407     assert (CompressedOops::base() == NULL, "sanity");
4408     if (dst != src) {
4409       mov(dst, src);
4410     }
4411   }
4412 }
4413 
4414 MacroAssembler::KlassDecodeMode MacroAssembler::_klass_decode_mode(KlassDecodeNone);
4415 
4416 MacroAssembler::KlassDecodeMode MacroAssembler::klass_decode_mode() {
4417   assert(UseCompressedClassPointers, "not using compressed class pointers");
4418   assert(Metaspace::initialized(), "metaspace not initialized yet");
4419 
4420   if (_klass_decode_mode != KlassDecodeNone) {
4421     return _klass_decode_mode;
4422   }
4423 
4424   assert(LogKlassAlignmentInBytes == CompressedKlassPointers::shift()
4425          || 0 == CompressedKlassPointers::shift(), "decode alg wrong");
4426 
4427   if (CompressedKlassPointers::base() == NULL) {
4428     return (_klass_decode_mode = KlassDecodeZero);
4429   }
4430 
4431   if (operand_valid_for_logical_immediate(
4432         /*is32*/false, (uint64_t)CompressedKlassPointers::base())) {
4433     const uint64_t range_mask =
4434       (1ULL << log2i(CompressedKlassPointers::range())) - 1;
4435     if (((uint64_t)CompressedKlassPointers::base() & range_mask) == 0) {
4436       return (_klass_decode_mode = KlassDecodeXor);
4437     }
4438   }
4439 
4440   const uint64_t shifted_base =
4441     (uint64_t)CompressedKlassPointers::base() >> CompressedKlassPointers::shift();
4442   guarantee((shifted_base & 0xffff0000ffffffff) == 0,
4443             "compressed class base bad alignment");
4444 
4445   return (_klass_decode_mode = KlassDecodeMovk);
4446 }
4447 
4448 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
4449   switch (klass_decode_mode()) {
4450   case KlassDecodeZero:
4451     if (CompressedKlassPointers::shift() != 0) {
4452       lsr(dst, src, LogKlassAlignmentInBytes);
4453     } else {
4454       if (dst != src) mov(dst, src);
4455     }
4456     break;
4457 
4458   case KlassDecodeXor:
4459     if (CompressedKlassPointers::shift() != 0) {
4460       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
4461       lsr(dst, dst, LogKlassAlignmentInBytes);
4462     } else {
4463       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
4464     }
4465     break;
4466 
4467   case KlassDecodeMovk:
4468     if (CompressedKlassPointers::shift() != 0) {
4469       ubfx(dst, src, LogKlassAlignmentInBytes, 32);
4470     } else {
4471       movw(dst, src);
4472     }
4473     break;
4474 
4475   case KlassDecodeNone:
4476     ShouldNotReachHere();
4477     break;
4478   }
4479 }
4480 
4481 void MacroAssembler::encode_klass_not_null(Register r) {
4482   encode_klass_not_null(r, r);
4483 }
4484 
4485 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
4486   assert (UseCompressedClassPointers, "should only be used for compressed headers");
4487 
4488   switch (klass_decode_mode()) {
4489   case KlassDecodeZero:
4490     if (CompressedKlassPointers::shift() != 0) {
4491       lsl(dst, src, LogKlassAlignmentInBytes);
4492     } else {
4493       if (dst != src) mov(dst, src);
4494     }
4495     break;
4496 
4497   case KlassDecodeXor:
4498     if (CompressedKlassPointers::shift() != 0) {
4499       lsl(dst, src, LogKlassAlignmentInBytes);
4500       eor(dst, dst, (uint64_t)CompressedKlassPointers::base());
4501     } else {
4502       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
4503     }
4504     break;
4505 
4506   case KlassDecodeMovk: {
4507     const uint64_t shifted_base =
4508       (uint64_t)CompressedKlassPointers::base() >> CompressedKlassPointers::shift();
4509 
4510     if (dst != src) movw(dst, src);
4511     movk(dst, shifted_base >> 32, 32);
4512 
4513     if (CompressedKlassPointers::shift() != 0) {
4514       lsl(dst, dst, LogKlassAlignmentInBytes);
4515     }
4516 
4517     break;
4518   }
4519 
4520   case KlassDecodeNone:
4521     ShouldNotReachHere();
4522     break;
4523   }
4524 }
4525 
4526 void  MacroAssembler::decode_klass_not_null(Register r) {
4527   decode_klass_not_null(r, r);
4528 }
4529 
4530 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
4531 #ifdef ASSERT
4532   {
4533     ThreadInVMfromUnknown tiv;
4534     assert (UseCompressedOops, "should only be used for compressed oops");
4535     assert (Universe::heap() != NULL, "java heap should be initialized");
4536     assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
4537     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
4538   }
4539 #endif
4540   int oop_index = oop_recorder()->find_index(obj);
4541   InstructionMark im(this);
4542   RelocationHolder rspec = oop_Relocation::spec(oop_index);
4543   code_section()->relocate(inst_mark(), rspec);
4544   movz(dst, 0xDEAD, 16);
4545   movk(dst, 0xBEEF);
4546 }
4547 
4548 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
4549   assert (UseCompressedClassPointers, "should only be used for compressed headers");
4550   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
4551   int index = oop_recorder()->find_index(k);
4552   assert(! Universe::heap()->is_in(k), "should not be an oop");
4553 
4554   InstructionMark im(this);
4555   RelocationHolder rspec = metadata_Relocation::spec(index);
4556   code_section()->relocate(inst_mark(), rspec);
4557   narrowKlass nk = CompressedKlassPointers::encode(k);
4558   movz(dst, (nk >> 16), 16);
4559   movk(dst, nk & 0xffff);
4560 }
4561 
4562 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators,
4563                                     Register dst, Address src,
4564                                     Register tmp1, Register tmp2) {
4565   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
4566   decorators = AccessInternal::decorator_fixup(decorators, type);
4567   bool as_raw = (decorators & AS_RAW) != 0;
4568   if (as_raw) {
4569     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, tmp2);
4570   } else {
4571     bs->load_at(this, decorators, type, dst, src, tmp1, tmp2);
4572   }
4573 }
4574 
4575 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators,
4576                                      Address dst, Register val,
4577                                      Register tmp1, Register tmp2, Register tmp3) {
4578   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
4579   decorators = AccessInternal::decorator_fixup(decorators, type);
4580   bool as_raw = (decorators & AS_RAW) != 0;
4581   if (as_raw) {
4582     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, val, tmp1, tmp2, tmp3);
4583   } else {
4584     bs->store_at(this, decorators, type, dst, val, tmp1, tmp2, tmp3);
4585   }
4586 }
4587 
4588 void MacroAssembler::access_value_copy(DecoratorSet decorators, Register src, Register dst,
4589                                        Register inline_klass) {
4590   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
4591   bs->value_copy(this, decorators, src, dst, inline_klass);
4592 }
4593 
4594 void MacroAssembler::first_field_offset(Register inline_klass, Register offset) {
4595   ldr(offset, Address(inline_klass, InstanceKlass::adr_inlineklass_fixed_block_offset()));
4596   ldrw(offset, Address(offset, InlineKlass::first_field_offset_offset()));
4597 }
4598 
4599 void MacroAssembler::data_for_oop(Register oop, Register data, Register inline_klass) {
4600   // ((address) (void*) o) + vk->first_field_offset();
4601   Register offset = (data == oop) ? rscratch1 : data;
4602   first_field_offset(inline_klass, offset);
4603   if (data == oop) {
4604     add(data, data, offset);
4605   } else {
4606     lea(data, Address(oop, offset));
4607   }
4608 }
4609 
4610 void MacroAssembler::data_for_value_array_index(Register array, Register array_klass,
4611                                                 Register index, Register data) {
4612   assert_different_registers(array, array_klass, index);
4613   assert_different_registers(rscratch1, array, index);
4614 
4615   // array->base() + (index << Klass::layout_helper_log2_element_size(lh));
4616   ldrw(rscratch1, Address(array_klass, Klass::layout_helper_offset()));
4617 
4618   // Klass::layout_helper_log2_element_size(lh)
4619   // (lh >> _lh_log2_element_size_shift) & _lh_log2_element_size_mask;
4620   lsr(rscratch1, rscratch1, Klass::_lh_log2_element_size_shift);
4621   andr(rscratch1, rscratch1, Klass::_lh_log2_element_size_mask);
4622   lslv(index, index, rscratch1);
4623 
4624   add(data, array, index);
4625   add(data, data, arrayOopDesc::base_offset_in_bytes(T_PRIMITIVE_OBJECT));
4626 }
4627 
4628 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
4629                                    Register tmp2, DecoratorSet decorators) {
4630   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2);
4631 }
4632 
4633 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
4634                                             Register tmp2, DecoratorSet decorators) {
4635   access_load_at(T_OBJECT, IN_HEAP | IS_NOT_NULL | decorators, dst, src, tmp1, tmp2);
4636 }
4637 
4638 void MacroAssembler::store_heap_oop(Address dst, Register val, Register tmp1,
4639                                     Register tmp2, Register tmp3, DecoratorSet decorators) {
4640   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, val, tmp1, tmp2, tmp3);
4641 }
4642 
4643 // Used for storing NULLs.
4644 void MacroAssembler::store_heap_oop_null(Address dst) {
4645   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg, noreg);
4646 }
4647 
4648 Address MacroAssembler::allocate_metadata_address(Metadata* obj) {
4649   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
4650   int index = oop_recorder()->allocate_metadata_index(obj);
4651   RelocationHolder rspec = metadata_Relocation::spec(index);
4652   return Address((address)obj, rspec);
4653 }
4654 
4655 // Move an oop into a register.
4656 void MacroAssembler::movoop(Register dst, jobject obj) {
4657   int oop_index;
4658   if (obj == NULL) {
4659     oop_index = oop_recorder()->allocate_oop_index(obj);
4660   } else {
4661 #ifdef ASSERT
4662     {
4663       ThreadInVMfromUnknown tiv;
4664       assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
4665     }
4666 #endif
4667     oop_index = oop_recorder()->find_index(obj);
4668   }
4669   RelocationHolder rspec = oop_Relocation::spec(oop_index);
4670 
4671   if (BarrierSet::barrier_set()->barrier_set_assembler()->supports_instruction_patching()) {
4672     mov(dst, Address((address)obj, rspec));
4673   } else {
4674     address dummy = address(uintptr_t(pc()) & -wordSize); // A nearby aligned address
4675     ldr_constant(dst, Address(dummy, rspec));
4676   }
4677 
4678 }
4679 
4680 // Move a metadata address into a register.
4681 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
4682   int oop_index;
4683   if (obj == NULL) {
4684     oop_index = oop_recorder()->allocate_metadata_index(obj);
4685   } else {
4686     oop_index = oop_recorder()->find_index(obj);
4687   }
4688   RelocationHolder rspec = metadata_Relocation::spec(oop_index);
4689   mov(dst, Address((address)obj, rspec));
4690 }
4691 
4692 Address MacroAssembler::constant_oop_address(jobject obj) {
4693 #ifdef ASSERT
4694   {
4695     ThreadInVMfromUnknown tiv;
4696     assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
4697     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "not an oop");
4698   }
4699 #endif
4700   int oop_index = oop_recorder()->find_index(obj);
4701   return Address((address)obj, oop_Relocation::spec(oop_index));
4702 }
4703 
4704 // Object / value buffer allocation...
4705 void MacroAssembler::allocate_instance(Register klass, Register new_obj,
4706                                        Register t1, Register t2,
4707                                        bool clear_fields, Label& alloc_failed)
4708 {
4709   Label done, initialize_header, initialize_object, slow_case, slow_case_no_pop;
4710   Register layout_size = t1;
4711   assert(new_obj == r0, "needs to be r0");
4712   assert_different_registers(klass, new_obj, t1, t2);
4713 
4714   // get instance_size in InstanceKlass (scaled to a count of bytes)
4715   ldrw(layout_size, Address(klass, Klass::layout_helper_offset()));
4716   // test to see if it has a finalizer or is malformed in some way
4717   tst(layout_size, Klass::_lh_instance_slow_path_bit);
4718   br(Assembler::NE, slow_case_no_pop);
4719 
4720   // Allocate the instance:
4721   //  If TLAB is enabled:
4722   //    Try to allocate in the TLAB.
4723   //    If fails, go to the slow path.
4724   //    Initialize the allocation.
4725   //    Exit.
4726   //
4727   //  Go to slow path.
4728 
4729   if (UseTLAB) {
4730     push(klass);
4731     tlab_allocate(new_obj, layout_size, 0, klass, t2, slow_case);
4732     if (ZeroTLAB || (!clear_fields)) {
4733       // the fields have been already cleared
4734       b(initialize_header);
4735     } else {
4736       // initialize both the header and fields
4737       b(initialize_object);
4738     }
4739 
4740     if (clear_fields) {
4741       // The object is initialized before the header.  If the object size is
4742       // zero, go directly to the header initialization.
4743       bind(initialize_object);
4744       subs(layout_size, layout_size, sizeof(oopDesc));
4745       br(Assembler::EQ, initialize_header);
4746 
4747       // Initialize topmost object field, divide size by 8, check if odd and
4748       // test if zero.
4749 
4750   #ifdef ASSERT
4751       // make sure instance_size was multiple of 8
4752       Label L;
4753       tst(layout_size, 7);
4754       br(Assembler::EQ, L);
4755       stop("object size is not multiple of 8 - adjust this code");
4756       bind(L);
4757       // must be > 0, no extra check needed here
4758   #endif
4759 
4760       lsr(layout_size, layout_size, LogBytesPerLong);
4761 
4762       // initialize remaining object fields: instance_size was a multiple of 8
4763       {
4764         Label loop;
4765         Register base = t2;
4766 
4767         bind(loop);
4768         add(rscratch1, new_obj, layout_size, Assembler::LSL, LogBytesPerLong);
4769         str(zr, Address(rscratch1, sizeof(oopDesc) - 1*oopSize));
4770         subs(layout_size, layout_size, 1);
4771         br(Assembler::NE, loop);
4772       }
4773     } // clear_fields
4774 
4775     // initialize object header only.
4776     bind(initialize_header);
4777     pop(klass);
4778     Register mark_word = t2;
4779     ldr(mark_word, Address(klass, Klass::prototype_header_offset()));
4780     str(mark_word, Address(new_obj, oopDesc::mark_offset_in_bytes ()));
4781     store_klass_gap(new_obj, zr);  // zero klass gap for compressed oops
4782     mov(t2, klass);         // preserve klass
4783     store_klass(new_obj, t2);  // src klass reg is potentially compressed
4784 
4785     // TODO: Valhalla removed SharedRuntime::dtrace_object_alloc from here ?
4786 
4787     b(done);
4788   }
4789 
4790   if (UseTLAB) {
4791     bind(slow_case);
4792     pop(klass);
4793   }
4794   bind(slow_case_no_pop);
4795   b(alloc_failed);
4796 
4797   bind(done);
4798 }
4799 
4800 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
4801 void MacroAssembler::tlab_allocate(Register obj,
4802                                    Register var_size_in_bytes,
4803                                    int con_size_in_bytes,
4804                                    Register t1,
4805                                    Register t2,
4806                                    Label& slow_case) {
4807   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
4808   bs->tlab_allocate(this, obj, var_size_in_bytes, con_size_in_bytes, t1, t2, slow_case);
4809 }
4810 
4811 void MacroAssembler::verify_tlab() {
4812 #ifdef ASSERT
4813   if (UseTLAB && VerifyOops) {
4814     Label next, ok;
4815 
4816     stp(rscratch2, rscratch1, Address(pre(sp, -16)));
4817 
4818     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4819     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
4820     cmp(rscratch2, rscratch1);
4821     br(Assembler::HS, next);
4822     STOP("assert(top >= start)");
4823     should_not_reach_here();
4824 
4825     bind(next);
4826     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
4827     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4828     cmp(rscratch2, rscratch1);
4829     br(Assembler::HS, ok);
4830     STOP("assert(top <= end)");
4831     should_not_reach_here();
4832 
4833     bind(ok);
4834     ldp(rscratch2, rscratch1, Address(post(sp, 16)));
4835   }
4836 #endif
4837 }
4838 
4839 void MacroAssembler::get_inline_type_field_klass(Register klass, Register index, Register inline_klass) {
4840   ldr(inline_klass, Address(klass, InstanceKlass::inline_type_field_klasses_offset()));
4841 #ifdef ASSERT
4842   {
4843     Label done;
4844     cbnz(inline_klass, done);
4845     stop("get_inline_type_field_klass contains no inline klass");
4846     bind(done);
4847   }
4848 #endif
4849   ldr(inline_klass, Address(inline_klass, index, Address::lsl(3)));
4850 }
4851 
4852 // Writes to stack successive pages until offset reached to check for
4853 // stack overflow + shadow pages.  This clobbers tmp.
4854 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
4855   assert_different_registers(tmp, size, rscratch1);
4856   mov(tmp, sp);
4857   // Bang stack for total size given plus shadow page size.
4858   // Bang one page at a time because large size can bang beyond yellow and
4859   // red zones.
4860   Label loop;
4861   mov(rscratch1, os::vm_page_size());
4862   bind(loop);
4863   lea(tmp, Address(tmp, -os::vm_page_size()));
4864   subsw(size, size, rscratch1);
4865   str(size, Address(tmp));
4866   br(Assembler::GT, loop);
4867 
4868   // Bang down shadow pages too.
4869   // At this point, (tmp-0) is the last address touched, so don't
4870   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
4871   // was post-decremented.)  Skip this address by starting at i=1, and
4872   // touch a few more pages below.  N.B.  It is important to touch all
4873   // the way down to and including i=StackShadowPages.
4874   for (int i = 0; i < (int)(StackOverflow::stack_shadow_zone_size() / os::vm_page_size()) - 1; i++) {
4875     // this could be any sized move but this is can be a debugging crumb
4876     // so the bigger the better.
4877     lea(tmp, Address(tmp, -os::vm_page_size()));
4878     str(size, Address(tmp));
4879   }
4880 }
4881 
4882 // Move the address of the polling page into dest.
4883 void MacroAssembler::get_polling_page(Register dest, relocInfo::relocType rtype) {
4884   ldr(dest, Address(rthread, JavaThread::polling_page_offset()));
4885 }
4886 
4887 // Read the polling page.  The address of the polling page must
4888 // already be in r.
4889 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
4890   address mark;
4891   {
4892     InstructionMark im(this);
4893     code_section()->relocate(inst_mark(), rtype);
4894     ldrw(zr, Address(r, 0));
4895     mark = inst_mark();
4896   }
4897   verify_cross_modify_fence_not_required();
4898   return mark;
4899 }
4900 
4901 void MacroAssembler::adrp(Register reg1, const Address &dest, uint64_t &byte_offset) {
4902   relocInfo::relocType rtype = dest.rspec().reloc()->type();
4903   uint64_t low_page = (uint64_t)CodeCache::low_bound() >> 12;
4904   uint64_t high_page = (uint64_t)(CodeCache::high_bound()-1) >> 12;
4905   uint64_t dest_page = (uint64_t)dest.target() >> 12;
4906   int64_t offset_low = dest_page - low_page;
4907   int64_t offset_high = dest_page - high_page;
4908 
4909   assert(is_valid_AArch64_address(dest.target()), "bad address");
4910   assert(dest.getMode() == Address::literal, "ADRP must be applied to a literal address");
4911 
4912   InstructionMark im(this);
4913   code_section()->relocate(inst_mark(), dest.rspec());
4914   // 8143067: Ensure that the adrp can reach the dest from anywhere within
4915   // the code cache so that if it is relocated we know it will still reach
4916   if (offset_high >= -(1<<20) && offset_low < (1<<20)) {
4917     _adrp(reg1, dest.target());
4918   } else {
4919     uint64_t target = (uint64_t)dest.target();
4920     uint64_t adrp_target
4921       = (target & 0xffffffffULL) | ((uint64_t)pc() & 0xffff00000000ULL);
4922 
4923     _adrp(reg1, (address)adrp_target);
4924     movk(reg1, target >> 32, 32);
4925   }
4926   byte_offset = (uint64_t)dest.target() & 0xfff;
4927 }
4928 
4929 void MacroAssembler::load_byte_map_base(Register reg) {
4930   CardTable::CardValue* byte_map_base =
4931     ((CardTableBarrierSet*)(BarrierSet::barrier_set()))->card_table()->byte_map_base();
4932 
4933   // Strictly speaking the byte_map_base isn't an address at all, and it might
4934   // even be negative. It is thus materialised as a constant.
4935   mov(reg, (uint64_t)byte_map_base);
4936 }
4937 
4938 void MacroAssembler::build_frame(int framesize) {
4939   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
4940   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
4941   protect_return_address();
4942   if (framesize < ((1 << 9) + 2 * wordSize)) {
4943     sub(sp, sp, framesize);
4944     stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4945     if (PreserveFramePointer) add(rfp, sp, framesize - 2 * wordSize);
4946   } else {
4947     stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
4948     if (PreserveFramePointer) mov(rfp, sp);
4949     if (framesize < ((1 << 12) + 2 * wordSize))
4950       sub(sp, sp, framesize - 2 * wordSize);
4951     else {
4952       mov(rscratch1, framesize - 2 * wordSize);
4953       sub(sp, sp, rscratch1);
4954     }
4955   }
4956   verify_cross_modify_fence_not_required();
4957 }
4958 
4959 void MacroAssembler::remove_frame(int framesize) {
4960   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
4961   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
4962   if (framesize < ((1 << 9) + 2 * wordSize)) {
4963     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4964     add(sp, sp, framesize);
4965   } else {
4966     if (framesize < ((1 << 12) + 2 * wordSize))
4967       add(sp, sp, framesize - 2 * wordSize);
4968     else {
4969       mov(rscratch1, framesize - 2 * wordSize);
4970       add(sp, sp, rscratch1);
4971     }
4972     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
4973   }
4974   authenticate_return_address();
4975 }
4976 
4977 void MacroAssembler::remove_frame(int initial_framesize, bool needs_stack_repair) {
4978   if (needs_stack_repair) {
4979     // Remove the extension of the caller's frame used for inline type unpacking
4980     //
4981     // Right now the stack looks like this:
4982     //
4983     // | Arguments from caller     |
4984     // |---------------------------|  <-- caller's SP
4985     // | Saved LR #1               |
4986     // | Saved FP #1               |
4987     // |---------------------------|
4988     // | Extension space for       |
4989     // |   inline arg (un)packing  |
4990     // |---------------------------|  <-- start of this method's frame
4991     // | Saved LR #2               |
4992     // | Saved FP #2               |
4993     // |---------------------------|  <-- FP
4994     // | sp_inc                    |
4995     // | method locals             |
4996     // |---------------------------|  <-- SP
4997     //
4998     // There are two copies of FP and LR on the stack. They will be identical
4999     // unless the caller has been deoptimized, in which case LR #1 will be patched
5000     // to point at the deopt blob, and LR #2 will still point into the old method.
5001     //
5002     // The sp_inc stack slot holds the total size of the frame including the
5003     // extension space minus two words for the saved FP and LR.
5004 
5005     int sp_inc_offset = initial_framesize - 3 * wordSize;  // Immediately below saved LR and FP
5006 
5007     ldr(rscratch1, Address(sp, sp_inc_offset));
5008     add(sp, sp, rscratch1);
5009     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
5010   } else {
5011     remove_frame(initial_framesize);
5012   }
5013 }
5014 
5015 void MacroAssembler::save_stack_increment(int sp_inc, int frame_size) {
5016   int real_frame_size = frame_size + sp_inc;
5017   assert(sp_inc == 0 || sp_inc > 2*wordSize, "invalid sp_inc value");
5018   assert(real_frame_size >= 2*wordSize, "frame size must include FP/LR space");
5019   assert((real_frame_size & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
5020 
5021   int sp_inc_offset = frame_size - 3 * wordSize;  // Immediately below saved LR and FP
5022 
5023   // Subtract two words for the saved FP and LR as these will be popped
5024   // separately. See remove_frame above.
5025   mov(rscratch1, real_frame_size - 2*wordSize);
5026   str(rscratch1, Address(sp, sp_inc_offset));
5027 }
5028 
5029 // This method counts leading positive bytes (highest bit not set) in provided byte array
5030 address MacroAssembler::count_positives(Register ary1, Register len, Register result) {
5031     // Simple and most common case of aligned small array which is not at the
5032     // end of memory page is placed here. All other cases are in stub.
5033     Label LOOP, END, STUB, STUB_LONG, SET_RESULT, DONE;
5034     const uint64_t UPPER_BIT_MASK=0x8080808080808080;
5035     assert_different_registers(ary1, len, result);
5036 
5037     mov(result, len);
5038     cmpw(len, 0);
5039     br(LE, DONE);
5040     cmpw(len, 4 * wordSize);
5041     br(GE, STUB_LONG); // size > 32 then go to stub
5042 
5043     int shift = 64 - exact_log2(os::vm_page_size());
5044     lsl(rscratch1, ary1, shift);
5045     mov(rscratch2, (size_t)(4 * wordSize) << shift);
5046     adds(rscratch2, rscratch1, rscratch2);  // At end of page?
5047     br(CS, STUB); // at the end of page then go to stub
5048     subs(len, len, wordSize);
5049     br(LT, END);
5050 
5051   BIND(LOOP);
5052     ldr(rscratch1, Address(post(ary1, wordSize)));
5053     tst(rscratch1, UPPER_BIT_MASK);
5054     br(NE, SET_RESULT);
5055     subs(len, len, wordSize);
5056     br(GE, LOOP);
5057     cmpw(len, -wordSize);
5058     br(EQ, DONE);
5059 
5060   BIND(END);
5061     ldr(rscratch1, Address(ary1));
5062     sub(rscratch2, zr, len, LSL, 3); // LSL 3 is to get bits from bytes
5063     lslv(rscratch1, rscratch1, rscratch2);
5064     tst(rscratch1, UPPER_BIT_MASK);
5065     br(NE, SET_RESULT);
5066     b(DONE);
5067 
5068   BIND(STUB);
5069     RuntimeAddress count_pos = RuntimeAddress(StubRoutines::aarch64::count_positives());
5070     assert(count_pos.target() != NULL, "count_positives stub has not been generated");
5071     address tpc1 = trampoline_call(count_pos);
5072     if (tpc1 == NULL) {
5073       DEBUG_ONLY(reset_labels(STUB_LONG, SET_RESULT, DONE));
5074       postcond(pc() == badAddress);
5075       return NULL;
5076     }
5077     b(DONE);
5078 
5079   BIND(STUB_LONG);
5080     RuntimeAddress count_pos_long = RuntimeAddress(StubRoutines::aarch64::count_positives_long());
5081     assert(count_pos_long.target() != NULL, "count_positives_long stub has not been generated");
5082     address tpc2 = trampoline_call(count_pos_long);
5083     if (tpc2 == NULL) {
5084       DEBUG_ONLY(reset_labels(SET_RESULT, DONE));
5085       postcond(pc() == badAddress);
5086       return NULL;
5087     }
5088     b(DONE);
5089 
5090   BIND(SET_RESULT);
5091 
5092     add(len, len, wordSize);
5093     sub(result, result, len);
5094 
5095   BIND(DONE);
5096   postcond(pc() != badAddress);
5097   return pc();
5098 }
5099 
5100 address MacroAssembler::arrays_equals(Register a1, Register a2, Register tmp3,
5101                                       Register tmp4, Register tmp5, Register result,
5102                                       Register cnt1, int elem_size) {
5103   Label DONE, SAME;
5104   Register tmp1 = rscratch1;
5105   Register tmp2 = rscratch2;
5106   Register cnt2 = tmp2;  // cnt2 only used in array length compare
5107   int elem_per_word = wordSize/elem_size;
5108   int log_elem_size = exact_log2(elem_size);
5109   int length_offset = arrayOopDesc::length_offset_in_bytes();
5110   int base_offset
5111     = arrayOopDesc::base_offset_in_bytes(elem_size == 2 ? T_CHAR : T_BYTE);
5112   int stubBytesThreshold = 3 * 64 + (UseSIMDForArrayEquals ? 0 : 16);
5113 
5114   assert(elem_size == 1 || elem_size == 2, "must be char or byte");
5115   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
5116 
5117 #ifndef PRODUCT
5118   {
5119     const char kind = (elem_size == 2) ? 'U' : 'L';
5120     char comment[64];
5121     snprintf(comment, sizeof comment, "array_equals%c{", kind);
5122     BLOCK_COMMENT(comment);
5123   }
5124 #endif
5125 
5126   // if (a1 == a2)
5127   //     return true;
5128   cmpoop(a1, a2); // May have read barriers for a1 and a2.
5129   br(EQ, SAME);
5130 
5131   if (UseSimpleArrayEquals) {
5132     Label NEXT_WORD, SHORT, TAIL03, TAIL01, A_MIGHT_BE_NULL, A_IS_NOT_NULL;
5133     // if (a1 == null || a2 == null)
5134     //     return false;
5135     // a1 & a2 == 0 means (some-pointer is null) or
5136     // (very-rare-or-even-probably-impossible-pointer-values)
5137     // so, we can save one branch in most cases
5138     tst(a1, a2);
5139     mov(result, false);
5140     br(EQ, A_MIGHT_BE_NULL);
5141     // if (a1.length != a2.length)
5142     //      return false;
5143     bind(A_IS_NOT_NULL);
5144     ldrw(cnt1, Address(a1, length_offset));
5145     ldrw(cnt2, Address(a2, length_offset));
5146     eorw(tmp5, cnt1, cnt2);
5147     cbnzw(tmp5, DONE);
5148     lea(a1, Address(a1, base_offset));
5149     lea(a2, Address(a2, base_offset));
5150     // Check for short strings, i.e. smaller than wordSize.
5151     subs(cnt1, cnt1, elem_per_word);
5152     br(Assembler::LT, SHORT);
5153     // Main 8 byte comparison loop.
5154     bind(NEXT_WORD); {
5155       ldr(tmp1, Address(post(a1, wordSize)));
5156       ldr(tmp2, Address(post(a2, wordSize)));
5157       subs(cnt1, cnt1, elem_per_word);
5158       eor(tmp5, tmp1, tmp2);
5159       cbnz(tmp5, DONE);
5160     } br(GT, NEXT_WORD);
5161     // Last longword.  In the case where length == 4 we compare the
5162     // same longword twice, but that's still faster than another
5163     // conditional branch.
5164     // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
5165     // length == 4.
5166     if (log_elem_size > 0)
5167       lsl(cnt1, cnt1, log_elem_size);
5168     ldr(tmp3, Address(a1, cnt1));
5169     ldr(tmp4, Address(a2, cnt1));
5170     eor(tmp5, tmp3, tmp4);
5171     cbnz(tmp5, DONE);
5172     b(SAME);
5173     bind(A_MIGHT_BE_NULL);
5174     // in case both a1 and a2 are not-null, proceed with loads
5175     cbz(a1, DONE);
5176     cbz(a2, DONE);
5177     b(A_IS_NOT_NULL);
5178     bind(SHORT);
5179 
5180     tbz(cnt1, 2 - log_elem_size, TAIL03); // 0-7 bytes left.
5181     {
5182       ldrw(tmp1, Address(post(a1, 4)));
5183       ldrw(tmp2, Address(post(a2, 4)));
5184       eorw(tmp5, tmp1, tmp2);
5185       cbnzw(tmp5, DONE);
5186     }
5187     bind(TAIL03);
5188     tbz(cnt1, 1 - log_elem_size, TAIL01); // 0-3 bytes left.
5189     {
5190       ldrh(tmp3, Address(post(a1, 2)));
5191       ldrh(tmp4, Address(post(a2, 2)));
5192       eorw(tmp5, tmp3, tmp4);
5193       cbnzw(tmp5, DONE);
5194     }
5195     bind(TAIL01);
5196     if (elem_size == 1) { // Only needed when comparing byte arrays.
5197       tbz(cnt1, 0, SAME); // 0-1 bytes left.
5198       {
5199         ldrb(tmp1, a1);
5200         ldrb(tmp2, a2);
5201         eorw(tmp5, tmp1, tmp2);
5202         cbnzw(tmp5, DONE);
5203       }
5204     }
5205   } else {
5206     Label NEXT_DWORD, SHORT, TAIL, TAIL2, STUB,
5207         CSET_EQ, LAST_CHECK;
5208     mov(result, false);
5209     cbz(a1, DONE);
5210     ldrw(cnt1, Address(a1, length_offset));
5211     cbz(a2, DONE);
5212     ldrw(cnt2, Address(a2, length_offset));
5213     // on most CPUs a2 is still "locked"(surprisingly) in ldrw and it's
5214     // faster to perform another branch before comparing a1 and a2
5215     cmp(cnt1, (u1)elem_per_word);
5216     br(LE, SHORT); // short or same
5217     ldr(tmp3, Address(pre(a1, base_offset)));
5218     subs(zr, cnt1, stubBytesThreshold);
5219     br(GE, STUB);
5220     ldr(tmp4, Address(pre(a2, base_offset)));
5221     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
5222     cmp(cnt2, cnt1);
5223     br(NE, DONE);
5224 
5225     // Main 16 byte comparison loop with 2 exits
5226     bind(NEXT_DWORD); {
5227       ldr(tmp1, Address(pre(a1, wordSize)));
5228       ldr(tmp2, Address(pre(a2, wordSize)));
5229       subs(cnt1, cnt1, 2 * elem_per_word);
5230       br(LE, TAIL);
5231       eor(tmp4, tmp3, tmp4);
5232       cbnz(tmp4, DONE);
5233       ldr(tmp3, Address(pre(a1, wordSize)));
5234       ldr(tmp4, Address(pre(a2, wordSize)));
5235       cmp(cnt1, (u1)elem_per_word);
5236       br(LE, TAIL2);
5237       cmp(tmp1, tmp2);
5238     } br(EQ, NEXT_DWORD);
5239     b(DONE);
5240 
5241     bind(TAIL);
5242     eor(tmp4, tmp3, tmp4);
5243     eor(tmp2, tmp1, tmp2);
5244     lslv(tmp2, tmp2, tmp5);
5245     orr(tmp5, tmp4, tmp2);
5246     cmp(tmp5, zr);
5247     b(CSET_EQ);
5248 
5249     bind(TAIL2);
5250     eor(tmp2, tmp1, tmp2);
5251     cbnz(tmp2, DONE);
5252     b(LAST_CHECK);
5253 
5254     bind(STUB);
5255     ldr(tmp4, Address(pre(a2, base_offset)));
5256     cmp(cnt2, cnt1);
5257     br(NE, DONE);
5258     if (elem_size == 2) { // convert to byte counter
5259       lsl(cnt1, cnt1, 1);
5260     }
5261     eor(tmp5, tmp3, tmp4);
5262     cbnz(tmp5, DONE);
5263     RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_array_equals());
5264     assert(stub.target() != NULL, "array_equals_long stub has not been generated");
5265     address tpc = trampoline_call(stub);
5266     if (tpc == NULL) {
5267       DEBUG_ONLY(reset_labels(SHORT, LAST_CHECK, CSET_EQ, SAME, DONE));
5268       postcond(pc() == badAddress);
5269       return NULL;
5270     }
5271     b(DONE);
5272 
5273     // (a1 != null && a2 == null) || (a1 != null && a2 != null && a1 == a2)
5274     // so, if a2 == null => return false(0), else return true, so we can return a2
5275     mov(result, a2);
5276     b(DONE);
5277     bind(SHORT);
5278     cmp(cnt2, cnt1);
5279     br(NE, DONE);
5280     cbz(cnt1, SAME);
5281     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
5282     ldr(tmp3, Address(a1, base_offset));
5283     ldr(tmp4, Address(a2, base_offset));
5284     bind(LAST_CHECK);
5285     eor(tmp4, tmp3, tmp4);
5286     lslv(tmp5, tmp4, tmp5);
5287     cmp(tmp5, zr);
5288     bind(CSET_EQ);
5289     cset(result, EQ);
5290     b(DONE);
5291   }
5292 
5293   bind(SAME);
5294   mov(result, true);
5295   // That's it.
5296   bind(DONE);
5297 
5298   BLOCK_COMMENT("} array_equals");
5299   postcond(pc() != badAddress);
5300   return pc();
5301 }
5302 
5303 // Compare Strings
5304 
5305 // For Strings we're passed the address of the first characters in a1
5306 // and a2 and the length in cnt1.
5307 // elem_size is the element size in bytes: either 1 or 2.
5308 // There are two implementations.  For arrays >= 8 bytes, all
5309 // comparisons (including the final one, which may overlap) are
5310 // performed 8 bytes at a time.  For strings < 8 bytes, we compare a
5311 // halfword, then a short, and then a byte.
5312 
5313 void MacroAssembler::string_equals(Register a1, Register a2,
5314                                    Register result, Register cnt1, int elem_size)
5315 {
5316   Label SAME, DONE, SHORT, NEXT_WORD;
5317   Register tmp1 = rscratch1;
5318   Register tmp2 = rscratch2;
5319   Register cnt2 = tmp2;  // cnt2 only used in array length compare
5320 
5321   assert(elem_size == 1 || elem_size == 2, "must be 2 or 1 byte");
5322   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
5323 
5324 #ifndef PRODUCT
5325   {
5326     const char kind = (elem_size == 2) ? 'U' : 'L';
5327     char comment[64];
5328     snprintf(comment, sizeof comment, "{string_equals%c", kind);
5329     BLOCK_COMMENT(comment);
5330   }
5331 #endif
5332 
5333   mov(result, false);
5334 
5335   // Check for short strings, i.e. smaller than wordSize.
5336   subs(cnt1, cnt1, wordSize);
5337   br(Assembler::LT, SHORT);
5338   // Main 8 byte comparison loop.
5339   bind(NEXT_WORD); {
5340     ldr(tmp1, Address(post(a1, wordSize)));
5341     ldr(tmp2, Address(post(a2, wordSize)));
5342     subs(cnt1, cnt1, wordSize);
5343     eor(tmp1, tmp1, tmp2);
5344     cbnz(tmp1, DONE);
5345   } br(GT, NEXT_WORD);
5346   // Last longword.  In the case where length == 4 we compare the
5347   // same longword twice, but that's still faster than another
5348   // conditional branch.
5349   // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
5350   // length == 4.
5351   ldr(tmp1, Address(a1, cnt1));
5352   ldr(tmp2, Address(a2, cnt1));
5353   eor(tmp2, tmp1, tmp2);
5354   cbnz(tmp2, DONE);
5355   b(SAME);
5356 
5357   bind(SHORT);
5358   Label TAIL03, TAIL01;
5359 
5360   tbz(cnt1, 2, TAIL03); // 0-7 bytes left.
5361   {
5362     ldrw(tmp1, Address(post(a1, 4)));
5363     ldrw(tmp2, Address(post(a2, 4)));
5364     eorw(tmp1, tmp1, tmp2);
5365     cbnzw(tmp1, DONE);
5366   }
5367   bind(TAIL03);
5368   tbz(cnt1, 1, TAIL01); // 0-3 bytes left.
5369   {
5370     ldrh(tmp1, Address(post(a1, 2)));
5371     ldrh(tmp2, Address(post(a2, 2)));
5372     eorw(tmp1, tmp1, tmp2);
5373     cbnzw(tmp1, DONE);
5374   }
5375   bind(TAIL01);
5376   if (elem_size == 1) { // Only needed when comparing 1-byte elements
5377     tbz(cnt1, 0, SAME); // 0-1 bytes left.
5378     {
5379       ldrb(tmp1, a1);
5380       ldrb(tmp2, a2);
5381       eorw(tmp1, tmp1, tmp2);
5382       cbnzw(tmp1, DONE);
5383     }
5384   }
5385   // Arrays are equal.
5386   bind(SAME);
5387   mov(result, true);
5388 
5389   // That's it.
5390   bind(DONE);
5391   BLOCK_COMMENT("} string_equals");
5392 }
5393 
5394 
5395 // The size of the blocks erased by the zero_blocks stub.  We must
5396 // handle anything smaller than this ourselves in zero_words().
5397 const int MacroAssembler::zero_words_block_size = 8;
5398 
5399 // zero_words() is used by C2 ClearArray patterns and by
5400 // C1_MacroAssembler.  It is as small as possible, handling small word
5401 // counts locally and delegating anything larger to the zero_blocks
5402 // stub.  It is expanded many times in compiled code, so it is
5403 // important to keep it short.
5404 
5405 // ptr:   Address of a buffer to be zeroed.
5406 // cnt:   Count in HeapWords.
5407 //
5408 // ptr, cnt, rscratch1, and rscratch2 are clobbered.
5409 address MacroAssembler::zero_words(Register ptr, Register cnt)
5410 {
5411   assert(is_power_of_2(zero_words_block_size), "adjust this");
5412 
5413   BLOCK_COMMENT("zero_words {");
5414   assert(ptr == r10 && cnt == r11, "mismatch in register usage");
5415   RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
5416   assert(zero_blocks.target() != NULL, "zero_blocks stub has not been generated");
5417 
5418   subs(rscratch1, cnt, zero_words_block_size);
5419   Label around;
5420   br(LO, around);
5421   {
5422     RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
5423     assert(zero_blocks.target() != NULL, "zero_blocks stub has not been generated");
5424     // Make sure this is a C2 compilation. C1 allocates space only for
5425     // trampoline stubs generated by Call LIR ops, and in any case it
5426     // makes sense for a C1 compilation task to proceed as quickly as
5427     // possible.
5428     CompileTask* task;
5429     if (StubRoutines::aarch64::complete()
5430         && Thread::current()->is_Compiler_thread()
5431         && (task = ciEnv::current()->task())
5432         && is_c2_compile(task->comp_level())) {
5433       address tpc = trampoline_call(zero_blocks);
5434       if (tpc == NULL) {
5435         DEBUG_ONLY(reset_labels(around));
5436         return NULL;
5437       }
5438     } else {
5439       far_call(zero_blocks);
5440     }
5441   }
5442   bind(around);
5443 
5444   // We have a few words left to do. zero_blocks has adjusted r10 and r11
5445   // for us.
5446   for (int i = zero_words_block_size >> 1; i > 1; i >>= 1) {
5447     Label l;
5448     tbz(cnt, exact_log2(i), l);
5449     for (int j = 0; j < i; j += 2) {
5450       stp(zr, zr, post(ptr, 2 * BytesPerWord));
5451     }
5452     bind(l);
5453   }
5454   {
5455     Label l;
5456     tbz(cnt, 0, l);
5457     str(zr, Address(ptr));
5458     bind(l);
5459   }
5460 
5461   BLOCK_COMMENT("} zero_words");
5462   return pc();
5463 }
5464 
5465 // base:         Address of a buffer to be zeroed, 8 bytes aligned.
5466 // cnt:          Immediate count in HeapWords.
5467 //
5468 // r10, r11, rscratch1, and rscratch2 are clobbered.
5469 address MacroAssembler::zero_words(Register base, uint64_t cnt)
5470 {
5471   assert(wordSize <= BlockZeroingLowLimit,
5472             "increase BlockZeroingLowLimit");
5473   address result = nullptr;
5474   if (cnt <= (uint64_t)BlockZeroingLowLimit / BytesPerWord) {
5475 #ifndef PRODUCT
5476     {
5477       char buf[64];
5478       snprintf(buf, sizeof buf, "zero_words (count = %" PRIu64 ") {", cnt);
5479       BLOCK_COMMENT(buf);
5480     }
5481 #endif
5482     if (cnt >= 16) {
5483       uint64_t loops = cnt/16;
5484       if (loops > 1) {
5485         mov(rscratch2, loops - 1);
5486       }
5487       {
5488         Label loop;
5489         bind(loop);
5490         for (int i = 0; i < 16; i += 2) {
5491           stp(zr, zr, Address(base, i * BytesPerWord));
5492         }
5493         add(base, base, 16 * BytesPerWord);
5494         if (loops > 1) {
5495           subs(rscratch2, rscratch2, 1);
5496           br(GE, loop);
5497         }
5498       }
5499     }
5500     cnt %= 16;
5501     int i = cnt & 1;  // store any odd word to start
5502     if (i) str(zr, Address(base));
5503     for (; i < (int)cnt; i += 2) {
5504       stp(zr, zr, Address(base, i * wordSize));
5505     }
5506     BLOCK_COMMENT("} zero_words");
5507     result = pc();
5508   } else {
5509     mov(r10, base); mov(r11, cnt);
5510     result = zero_words(r10, r11);
5511   }
5512   return result;
5513 }
5514 
5515 // Zero blocks of memory by using DC ZVA.
5516 //
5517 // Aligns the base address first sufficiently for DC ZVA, then uses
5518 // DC ZVA repeatedly for every full block.  cnt is the size to be
5519 // zeroed in HeapWords.  Returns the count of words left to be zeroed
5520 // in cnt.
5521 //
5522 // NOTE: This is intended to be used in the zero_blocks() stub.  If
5523 // you want to use it elsewhere, note that cnt must be >= 2*zva_length.
5524 void MacroAssembler::zero_dcache_blocks(Register base, Register cnt) {
5525   Register tmp = rscratch1;
5526   Register tmp2 = rscratch2;
5527   int zva_length = VM_Version::zva_length();
5528   Label initial_table_end, loop_zva;
5529   Label fini;
5530 
5531   // Base must be 16 byte aligned. If not just return and let caller handle it
5532   tst(base, 0x0f);
5533   br(Assembler::NE, fini);
5534   // Align base with ZVA length.
5535   neg(tmp, base);
5536   andr(tmp, tmp, zva_length - 1);
5537 
5538   // tmp: the number of bytes to be filled to align the base with ZVA length.
5539   add(base, base, tmp);
5540   sub(cnt, cnt, tmp, Assembler::ASR, 3);
5541   adr(tmp2, initial_table_end);
5542   sub(tmp2, tmp2, tmp, Assembler::LSR, 2);
5543   br(tmp2);
5544 
5545   for (int i = -zva_length + 16; i < 0; i += 16)
5546     stp(zr, zr, Address(base, i));
5547   bind(initial_table_end);
5548 
5549   sub(cnt, cnt, zva_length >> 3);
5550   bind(loop_zva);
5551   dc(Assembler::ZVA, base);
5552   subs(cnt, cnt, zva_length >> 3);
5553   add(base, base, zva_length);
5554   br(Assembler::GE, loop_zva);
5555   add(cnt, cnt, zva_length >> 3); // count not zeroed by DC ZVA
5556   bind(fini);
5557 }
5558 
5559 // base:   Address of a buffer to be filled, 8 bytes aligned.
5560 // cnt:    Count in 8-byte unit.
5561 // value:  Value to be filled with.
5562 // base will point to the end of the buffer after filling.
5563 void MacroAssembler::fill_words(Register base, Register cnt, Register value)
5564 {
5565 //  Algorithm:
5566 //
5567 //    if (cnt == 0) {
5568 //      return;
5569 //    }
5570 //    if ((p & 8) != 0) {
5571 //      *p++ = v;
5572 //    }
5573 //
5574 //    scratch1 = cnt & 14;
5575 //    cnt -= scratch1;
5576 //    p += scratch1;
5577 //    switch (scratch1 / 2) {
5578 //      do {
5579 //        cnt -= 16;
5580 //          p[-16] = v;
5581 //          p[-15] = v;
5582 //        case 7:
5583 //          p[-14] = v;
5584 //          p[-13] = v;
5585 //        case 6:
5586 //          p[-12] = v;
5587 //          p[-11] = v;
5588 //          // ...
5589 //        case 1:
5590 //          p[-2] = v;
5591 //          p[-1] = v;
5592 //        case 0:
5593 //          p += 16;
5594 //      } while (cnt);
5595 //    }
5596 //    if ((cnt & 1) == 1) {
5597 //      *p++ = v;
5598 //    }
5599 
5600   assert_different_registers(base, cnt, value, rscratch1, rscratch2);
5601 
5602   Label fini, skip, entry, loop;
5603   const int unroll = 8; // Number of stp instructions we'll unroll
5604 
5605   cbz(cnt, fini);
5606   tbz(base, 3, skip);
5607   str(value, Address(post(base, 8)));
5608   sub(cnt, cnt, 1);
5609   bind(skip);
5610 
5611   andr(rscratch1, cnt, (unroll-1) * 2);
5612   sub(cnt, cnt, rscratch1);
5613   add(base, base, rscratch1, Assembler::LSL, 3);
5614   adr(rscratch2, entry);
5615   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 1);
5616   br(rscratch2);
5617 
5618   bind(loop);
5619   add(base, base, unroll * 16);
5620   for (int i = -unroll; i < 0; i++)
5621     stp(value, value, Address(base, i * 16));
5622   bind(entry);
5623   subs(cnt, cnt, unroll * 2);
5624   br(Assembler::GE, loop);
5625 
5626   tbz(cnt, 0, fini);
5627   str(value, Address(post(base, 8)));
5628   bind(fini);
5629 }
5630 
5631 // Intrinsic for
5632 //
5633 // - sun/nio/cs/ISO_8859_1$Encoder.implEncodeISOArray
5634 //     return the number of characters copied.
5635 // - java/lang/StringUTF16.compress
5636 //     return zero (0) if copy fails, otherwise 'len'.
5637 //
5638 // This version always returns the number of characters copied, and does not
5639 // clobber the 'len' register. A successful copy will complete with the post-
5640 // condition: 'res' == 'len', while an unsuccessful copy will exit with the
5641 // post-condition: 0 <= 'res' < 'len'.
5642 //
5643 // NOTE: Attempts to use 'ld2' (and 'umaxv' in the ISO part) has proven to
5644 //       degrade performance (on Ampere Altra - Neoverse N1), to an extent
5645 //       beyond the acceptable, even though the footprint would be smaller.
5646 //       Using 'umaxv' in the ASCII-case comes with a small penalty but does
5647 //       avoid additional bloat.
5648 //
5649 void MacroAssembler::encode_iso_array(Register src, Register dst,
5650                                       Register len, Register res, bool ascii,
5651                                       FloatRegister vtmp0, FloatRegister vtmp1,
5652                                       FloatRegister vtmp2, FloatRegister vtmp3)
5653 {
5654   Register cnt = res;
5655   Register max = rscratch1;
5656   Register chk = rscratch2;
5657 
5658   prfm(Address(src), PLDL1STRM);
5659   movw(cnt, len);
5660 
5661 #define ASCII(insn) do { if (ascii) { insn; } } while (0)
5662 
5663   Label LOOP_32, DONE_32, FAIL_32;
5664 
5665   BIND(LOOP_32);
5666   {
5667     cmpw(cnt, 32);
5668     br(LT, DONE_32);
5669     ld1(vtmp0, vtmp1, vtmp2, vtmp3, T8H, Address(post(src, 64)));
5670     // Extract lower bytes.
5671     FloatRegister vlo0 = v4;
5672     FloatRegister vlo1 = v5;
5673     uzp1(vlo0, T16B, vtmp0, vtmp1);
5674     uzp1(vlo1, T16B, vtmp2, vtmp3);
5675     // Merge bits...
5676     orr(vtmp0, T16B, vtmp0, vtmp1);
5677     orr(vtmp2, T16B, vtmp2, vtmp3);
5678     // Extract merged upper bytes.
5679     FloatRegister vhix = vtmp0;
5680     uzp2(vhix, T16B, vtmp0, vtmp2);
5681     // ISO-check on hi-parts (all zero).
5682     //                          ASCII-check on lo-parts (no sign).
5683     FloatRegister vlox = vtmp1; // Merge lower bytes.
5684                                 ASCII(orr(vlox, T16B, vlo0, vlo1));
5685     umov(chk, vhix, D, 1);      ASCII(cmlt(vlox, T16B, vlox));
5686     fmovd(max, vhix);           ASCII(umaxv(vlox, T16B, vlox));
5687     orr(chk, chk, max);         ASCII(umov(max, vlox, B, 0));
5688                                 ASCII(orr(chk, chk, max));
5689     cbnz(chk, FAIL_32);
5690     subw(cnt, cnt, 32);
5691     st1(vlo0, vlo1, T16B, Address(post(dst, 32)));
5692     b(LOOP_32);
5693   }
5694   BIND(FAIL_32);
5695   sub(src, src, 64);
5696   BIND(DONE_32);
5697 
5698   Label LOOP_8, SKIP_8;
5699 
5700   BIND(LOOP_8);
5701   {
5702     cmpw(cnt, 8);
5703     br(LT, SKIP_8);
5704     FloatRegister vhi = vtmp0;
5705     FloatRegister vlo = vtmp1;
5706     ld1(vtmp3, T8H, src);
5707     uzp1(vlo, T16B, vtmp3, vtmp3);
5708     uzp2(vhi, T16B, vtmp3, vtmp3);
5709     // ISO-check on hi-parts (all zero).
5710     //                          ASCII-check on lo-parts (no sign).
5711                                 ASCII(cmlt(vtmp2, T16B, vlo));
5712     fmovd(chk, vhi);            ASCII(umaxv(vtmp2, T16B, vtmp2));
5713                                 ASCII(umov(max, vtmp2, B, 0));
5714                                 ASCII(orr(chk, chk, max));
5715     cbnz(chk, SKIP_8);
5716 
5717     strd(vlo, Address(post(dst, 8)));
5718     subw(cnt, cnt, 8);
5719     add(src, src, 16);
5720     b(LOOP_8);
5721   }
5722   BIND(SKIP_8);
5723 
5724 #undef ASCII
5725 
5726   Label LOOP, DONE;
5727 
5728   cbz(cnt, DONE);
5729   BIND(LOOP);
5730   {
5731     Register chr = rscratch1;
5732     ldrh(chr, Address(post(src, 2)));
5733     tst(chr, ascii ? 0xff80 : 0xff00);
5734     br(NE, DONE);
5735     strb(chr, Address(post(dst, 1)));
5736     subs(cnt, cnt, 1);
5737     br(GT, LOOP);
5738   }
5739   BIND(DONE);
5740   // Return index where we stopped.
5741   subw(res, len, cnt);
5742 }
5743 
5744 // Inflate byte[] array to char[].
5745 address MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
5746                                            FloatRegister vtmp1, FloatRegister vtmp2,
5747                                            FloatRegister vtmp3, Register tmp4) {
5748   Label big, done, after_init, to_stub;
5749 
5750   assert_different_registers(src, dst, len, tmp4, rscratch1);
5751 
5752   fmovd(vtmp1, 0.0);
5753   lsrw(tmp4, len, 3);
5754   bind(after_init);
5755   cbnzw(tmp4, big);
5756   // Short string: less than 8 bytes.
5757   {
5758     Label loop, tiny;
5759 
5760     cmpw(len, 4);
5761     br(LT, tiny);
5762     // Use SIMD to do 4 bytes.
5763     ldrs(vtmp2, post(src, 4));
5764     zip1(vtmp3, T8B, vtmp2, vtmp1);
5765     subw(len, len, 4);
5766     strd(vtmp3, post(dst, 8));
5767 
5768     cbzw(len, done);
5769 
5770     // Do the remaining bytes by steam.
5771     bind(loop);
5772     ldrb(tmp4, post(src, 1));
5773     strh(tmp4, post(dst, 2));
5774     subw(len, len, 1);
5775 
5776     bind(tiny);
5777     cbnz(len, loop);
5778 
5779     b(done);
5780   }
5781 
5782   if (SoftwarePrefetchHintDistance >= 0) {
5783     bind(to_stub);
5784       RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_byte_array_inflate());
5785       assert(stub.target() != NULL, "large_byte_array_inflate stub has not been generated");
5786       address tpc = trampoline_call(stub);
5787       if (tpc == NULL) {
5788         DEBUG_ONLY(reset_labels(big, done));
5789         postcond(pc() == badAddress);
5790         return NULL;
5791       }
5792       b(after_init);
5793   }
5794 
5795   // Unpack the bytes 8 at a time.
5796   bind(big);
5797   {
5798     Label loop, around, loop_last, loop_start;
5799 
5800     if (SoftwarePrefetchHintDistance >= 0) {
5801       const int large_loop_threshold = (64 + 16)/8;
5802       ldrd(vtmp2, post(src, 8));
5803       andw(len, len, 7);
5804       cmp(tmp4, (u1)large_loop_threshold);
5805       br(GE, to_stub);
5806       b(loop_start);
5807 
5808       bind(loop);
5809       ldrd(vtmp2, post(src, 8));
5810       bind(loop_start);
5811       subs(tmp4, tmp4, 1);
5812       br(EQ, loop_last);
5813       zip1(vtmp2, T16B, vtmp2, vtmp1);
5814       ldrd(vtmp3, post(src, 8));
5815       st1(vtmp2, T8H, post(dst, 16));
5816       subs(tmp4, tmp4, 1);
5817       zip1(vtmp3, T16B, vtmp3, vtmp1);
5818       st1(vtmp3, T8H, post(dst, 16));
5819       br(NE, loop);
5820       b(around);
5821       bind(loop_last);
5822       zip1(vtmp2, T16B, vtmp2, vtmp1);
5823       st1(vtmp2, T8H, post(dst, 16));
5824       bind(around);
5825       cbz(len, done);
5826     } else {
5827       andw(len, len, 7);
5828       bind(loop);
5829       ldrd(vtmp2, post(src, 8));
5830       sub(tmp4, tmp4, 1);
5831       zip1(vtmp3, T16B, vtmp2, vtmp1);
5832       st1(vtmp3, T8H, post(dst, 16));
5833       cbnz(tmp4, loop);
5834     }
5835   }
5836 
5837   // Do the tail of up to 8 bytes.
5838   add(src, src, len);
5839   ldrd(vtmp3, Address(src, -8));
5840   add(dst, dst, len, ext::uxtw, 1);
5841   zip1(vtmp3, T16B, vtmp3, vtmp1);
5842   strq(vtmp3, Address(dst, -16));
5843 
5844   bind(done);
5845   postcond(pc() != badAddress);
5846   return pc();
5847 }
5848 
5849 // Compress char[] array to byte[].
5850 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
5851                                          Register res,
5852                                          FloatRegister tmp0, FloatRegister tmp1,
5853                                          FloatRegister tmp2, FloatRegister tmp3) {
5854   encode_iso_array(src, dst, len, res, false, tmp0, tmp1, tmp2, tmp3);
5855   // Adjust result: res == len ? len : 0
5856   cmp(len, res);
5857   csel(res, res, zr, EQ);
5858 }
5859 
5860 // java.math.round(double a)
5861 // Returns the closest long to the argument, with ties rounding to
5862 // positive infinity.  This requires some fiddling for corner
5863 // cases. We take care to avoid double rounding in e.g. (jlong)(a + 0.5).
5864 void MacroAssembler::java_round_double(Register dst, FloatRegister src,
5865                                        FloatRegister ftmp) {
5866   Label DONE;
5867   BLOCK_COMMENT("java_round_double: { ");
5868   fmovd(rscratch1, src);
5869   // Use RoundToNearestTiesAway unless src small and -ve.
5870   fcvtasd(dst, src);
5871   // Test if src >= 0 || abs(src) >= 0x1.0p52
5872   eor(rscratch1, rscratch1, UCONST64(1) << 63); // flip sign bit
5873   mov(rscratch2, julong_cast(0x1.0p52));
5874   cmp(rscratch1, rscratch2);
5875   br(HS, DONE); {
5876     // src < 0 && abs(src) < 0x1.0p52
5877     // src may have a fractional part, so add 0.5
5878     fmovd(ftmp, 0.5);
5879     faddd(ftmp, src, ftmp);
5880     // Convert double to jlong, use RoundTowardsNegative
5881     fcvtmsd(dst, ftmp);
5882   }
5883   bind(DONE);
5884   BLOCK_COMMENT("} java_round_double");
5885 }
5886 
5887 void MacroAssembler::java_round_float(Register dst, FloatRegister src,
5888                                       FloatRegister ftmp) {
5889   Label DONE;
5890   BLOCK_COMMENT("java_round_float: { ");
5891   fmovs(rscratch1, src);
5892   // Use RoundToNearestTiesAway unless src small and -ve.
5893   fcvtassw(dst, src);
5894   // Test if src >= 0 || abs(src) >= 0x1.0p23
5895   eor(rscratch1, rscratch1, 0x80000000); // flip sign bit
5896   mov(rscratch2, jint_cast(0x1.0p23f));
5897   cmp(rscratch1, rscratch2);
5898   br(HS, DONE); {
5899     // src < 0 && |src| < 0x1.0p23
5900     // src may have a fractional part, so add 0.5
5901     fmovs(ftmp, 0.5f);
5902     fadds(ftmp, src, ftmp);
5903     // Convert float to jint, use RoundTowardsNegative
5904     fcvtmssw(dst, ftmp);
5905   }
5906   bind(DONE);
5907   BLOCK_COMMENT("} java_round_float");
5908 }
5909 
5910 // get_thread() can be called anywhere inside generated code so we
5911 // need to save whatever non-callee save context might get clobbered
5912 // by the call to JavaThread::aarch64_get_thread_helper() or, indeed,
5913 // the call setup code.
5914 //
5915 // On Linux, aarch64_get_thread_helper() clobbers only r0, r1, and flags.
5916 // On other systems, the helper is a usual C function.
5917 //
5918 void MacroAssembler::get_thread(Register dst) {
5919   RegSet saved_regs =
5920     LINUX_ONLY(RegSet::range(r0, r1)  + lr - dst)
5921     NOT_LINUX (RegSet::range(r0, r17) + lr - dst);
5922 
5923   protect_return_address();
5924   push(saved_regs, sp);
5925 
5926   mov(lr, CAST_FROM_FN_PTR(address, JavaThread::aarch64_get_thread_helper));
5927   blr(lr);
5928   if (dst != c_rarg0) {
5929     mov(dst, c_rarg0);
5930   }
5931 
5932   pop(saved_regs, sp);
5933   authenticate_return_address();
5934 }
5935 
5936 #ifdef COMPILER2
5937 // C2 compiled method's prolog code
5938 // Moved here from aarch64.ad to support Valhalla code belows
5939 void MacroAssembler::verified_entry(Compile* C, int sp_inc) {
5940   if (C->clinit_barrier_on_entry()) {
5941     assert(!C->method()->holder()->is_not_initialized(), "initialization should have been started");
5942 
5943     Label L_skip_barrier;
5944 
5945     mov_metadata(rscratch2, C->method()->holder()->constant_encoding());
5946     clinit_barrier(rscratch2, rscratch1, &L_skip_barrier);
5947     far_jump(RuntimeAddress(SharedRuntime::get_handle_wrong_method_stub()));
5948     bind(L_skip_barrier);
5949   }
5950 
5951   if (C->max_vector_size() > 0) {
5952     reinitialize_ptrue();
5953   }
5954 
5955   int bangsize = C->output()->bang_size_in_bytes();
5956   if (C->output()->need_stack_bang(bangsize))
5957     generate_stack_overflow_check(bangsize);
5958 
5959   // n.b. frame size includes space for return pc and rfp
5960   const long framesize = C->output()->frame_size_in_bytes();
5961   build_frame(framesize);
5962 
5963   if (C->needs_stack_repair()) {
5964     save_stack_increment(sp_inc, framesize);
5965   }
5966 
5967   if (VerifyStackAtCalls) {
5968     Unimplemented();
5969   }
5970 }
5971 #endif // COMPILER2
5972 
5973 int MacroAssembler::store_inline_type_fields_to_buf(ciInlineKlass* vk, bool from_interpreter) {
5974   assert(InlineTypeReturnedAsFields, "Inline types should never be returned as fields");
5975   // An inline type might be returned. If fields are in registers we
5976   // need to allocate an inline type instance and initialize it with
5977   // the value of the fields.
5978   Label skip;
5979   // We only need a new buffered inline type if a new one is not returned
5980   tbz(r0, 0, skip);
5981   int call_offset = -1;
5982 
5983   // Be careful not to clobber r1-7 which hold returned fields
5984   // Also do not use callee-saved registers as these may be live in the interpreter
5985   Register tmp1 = r13, tmp2 = r14, klass = r15, r0_preserved = r12;
5986 
5987   // The following code is similar to allocate_instance but has some slight differences,
5988   // e.g. object size is always not zero, sometimes it's constant; storing klass ptr after
5989   // allocating is not necessary if vk != NULL, etc. allocate_instance is not aware of these.
5990   Label slow_case;
5991   // 1. Try to allocate a new buffered inline instance either from TLAB or eden space
5992   mov(r0_preserved, r0); // save r0 for slow_case since *_allocate may corrupt it when allocation failed
5993 
5994   if (vk != NULL) {
5995     // Called from C1, where the return type is statically known.
5996     movptr(klass, (intptr_t)vk->get_InlineKlass());
5997     jint obj_size = vk->layout_helper();
5998     assert(obj_size != Klass::_lh_neutral_value, "inline class in return type must have been resolved");
5999     if (UseTLAB) {
6000       tlab_allocate(r0, noreg, obj_size, tmp1, tmp2, slow_case);
6001     } else {
6002       b(slow_case);
6003     }
6004   } else {
6005     // Call from interpreter. R0 contains ((the InlineKlass* of the return type) | 0x01)
6006     andr(klass, r0, -2);
6007     ldrw(tmp2, Address(klass, Klass::layout_helper_offset()));
6008     if (UseTLAB) {
6009       tlab_allocate(r0, tmp2, 0, tmp1, tmp2, slow_case);
6010     } else {
6011       b(slow_case);
6012     }
6013   }
6014   if (UseTLAB) {
6015     // 2. Initialize buffered inline instance header
6016     Register buffer_obj = r0;
6017     mov(rscratch1, (intptr_t)markWord::inline_type_prototype().value());
6018     str(rscratch1, Address(buffer_obj, oopDesc::mark_offset_in_bytes()));
6019     store_klass_gap(buffer_obj, zr);
6020     if (vk == NULL) {
6021       // store_klass corrupts klass, so save it for later use (interpreter case only).
6022       mov(tmp1, klass);
6023     }
6024     store_klass(buffer_obj, klass);
6025     // 3. Initialize its fields with an inline class specific handler
6026     if (vk != NULL) {
6027       far_call(RuntimeAddress(vk->pack_handler())); // no need for call info as this will not safepoint.
6028     } else {
6029       // tmp1 holds klass preserved above
6030       ldr(tmp1, Address(tmp1, InstanceKlass::adr_inlineklass_fixed_block_offset()));
6031       ldr(tmp1, Address(tmp1, InlineKlass::pack_handler_offset()));
6032       blr(tmp1);
6033     }
6034 
6035     membar(Assembler::StoreStore);
6036     b(skip);
6037   } else {
6038     // Must have already branched to slow_case above.
6039     DEBUG_ONLY(should_not_reach_here());
6040   }
6041   bind(slow_case);
6042   // We failed to allocate a new inline type, fall back to a runtime
6043   // call. Some oop field may be live in some registers but we can't
6044   // tell. That runtime call will take care of preserving them
6045   // across a GC if there's one.
6046   mov(r0, r0_preserved);
6047 
6048   if (from_interpreter) {
6049     super_call_VM_leaf(StubRoutines::store_inline_type_fields_to_buf());
6050   } else {
6051     far_call(RuntimeAddress(StubRoutines::store_inline_type_fields_to_buf()));
6052     call_offset = offset();
6053   }
6054   membar(Assembler::StoreStore);
6055 
6056   bind(skip);
6057   return call_offset;
6058 }
6059 
6060 // Move a value between registers/stack slots and update the reg_state
6061 bool MacroAssembler::move_helper(VMReg from, VMReg to, BasicType bt, RegState reg_state[]) {
6062   assert(from->is_valid() && to->is_valid(), "source and destination must be valid");
6063   if (reg_state[to->value()] == reg_written) {
6064     return true; // Already written
6065   }
6066 
6067   if (from != to && bt != T_VOID) {
6068     if (reg_state[to->value()] == reg_readonly) {
6069       return false; // Not yet writable
6070     }
6071     if (from->is_reg()) {
6072       if (to->is_reg()) {
6073         if (from->is_Register() && to->is_Register()) {
6074           mov(to->as_Register(), from->as_Register());
6075         } else if (from->is_FloatRegister() && to->is_FloatRegister()) {
6076           fmovd(to->as_FloatRegister(), from->as_FloatRegister());
6077         } else {
6078           ShouldNotReachHere();
6079         }
6080       } else {
6081         int st_off = to->reg2stack() * VMRegImpl::stack_slot_size;
6082         Address to_addr = Address(sp, st_off);
6083         if (from->is_FloatRegister()) {
6084           if (bt == T_DOUBLE) {
6085              strd(from->as_FloatRegister(), to_addr);
6086           } else {
6087              assert(bt == T_FLOAT, "must be float");
6088              strs(from->as_FloatRegister(), to_addr);
6089           }
6090         } else {
6091           str(from->as_Register(), to_addr);
6092         }
6093       }
6094     } else {
6095       Address from_addr = Address(sp, from->reg2stack() * VMRegImpl::stack_slot_size);
6096       if (to->is_reg()) {
6097         if (to->is_FloatRegister()) {
6098           if (bt == T_DOUBLE) {
6099             ldrd(to->as_FloatRegister(), from_addr);
6100           } else {
6101             assert(bt == T_FLOAT, "must be float");
6102             ldrs(to->as_FloatRegister(), from_addr);
6103           }
6104         } else {
6105           ldr(to->as_Register(), from_addr);
6106         }
6107       } else {
6108         int st_off = to->reg2stack() * VMRegImpl::stack_slot_size;
6109         ldr(rscratch1, from_addr);
6110         str(rscratch1, Address(sp, st_off));
6111       }
6112     }
6113   }
6114 
6115   // Update register states
6116   reg_state[from->value()] = reg_writable;
6117   reg_state[to->value()] = reg_written;
6118   return true;
6119 }
6120 
6121 // Calculate the extra stack space required for packing or unpacking inline
6122 // args and adjust the stack pointer
6123 int MacroAssembler::extend_stack_for_inline_args(int args_on_stack) {
6124   int sp_inc = args_on_stack * VMRegImpl::stack_slot_size;
6125   sp_inc = align_up(sp_inc, StackAlignmentInBytes);
6126   assert(sp_inc > 0, "sanity");
6127 
6128   // Save a copy of the FP and LR here for deoptimization patching and frame walking
6129   stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
6130 
6131   // Adjust the stack pointer. This will be repaired on return by MacroAssembler::remove_frame
6132   if (sp_inc < (1 << 9)) {
6133     sub(sp, sp, sp_inc);   // Fits in an immediate
6134   } else {
6135     mov(rscratch1, sp_inc);
6136     sub(sp, sp, rscratch1);
6137   }
6138 
6139   return sp_inc + 2 * wordSize;  // Account for the FP/LR space
6140 }
6141 
6142 // Read all fields from an inline type oop and store the values in registers/stack slots
6143 bool MacroAssembler::unpack_inline_helper(const GrowableArray<SigEntry>* sig, int& sig_index,
6144                                           VMReg from, int& from_index, VMRegPair* to, int to_count, int& to_index,
6145                                           RegState reg_state[]) {
6146   assert(sig->at(sig_index)._bt == T_VOID, "should be at end delimiter");
6147   assert(from->is_valid(), "source must be valid");
6148   bool progress = false;
6149 #ifdef ASSERT
6150   const int start_offset = offset();
6151 #endif
6152 
6153   Label L_null, L_notNull;
6154   // Don't use r14 as tmp because it's used for spilling (see MacroAssembler::spill_reg_for)
6155   Register tmp1 = r10;
6156   Register tmp2 = r11;
6157   Register fromReg = noreg;
6158   ScalarizedInlineArgsStream stream(sig, sig_index, to, to_count, to_index, -1);
6159   bool done = true;
6160   bool mark_done = true;
6161   VMReg toReg;
6162   BasicType bt;
6163   // Check if argument requires a null check
6164   bool null_check = false;
6165   VMReg nullCheckReg;
6166   while (stream.next(nullCheckReg, bt)) {
6167     if (sig->at(stream.sig_index())._offset == -1) {
6168       null_check = true;
6169       break;
6170     }
6171   }
6172   stream.reset(sig_index, to_index);
6173   while (stream.next(toReg, bt)) {
6174     assert(toReg->is_valid(), "destination must be valid");
6175     int idx = (int)toReg->value();
6176     if (reg_state[idx] == reg_readonly) {
6177       if (idx != from->value()) {
6178         mark_done = false;
6179       }
6180       done = false;
6181       continue;
6182     } else if (reg_state[idx] == reg_written) {
6183       continue;
6184     }
6185     assert(reg_state[idx] == reg_writable, "must be writable");
6186     reg_state[idx] = reg_written;
6187     progress = true;
6188 
6189     if (fromReg == noreg) {
6190       if (from->is_reg()) {
6191         fromReg = from->as_Register();
6192       } else {
6193         int st_off = from->reg2stack() * VMRegImpl::stack_slot_size;
6194         ldr(tmp1, Address(sp, st_off));
6195         fromReg = tmp1;
6196       }
6197       if (null_check) {
6198         // Nullable inline type argument, emit null check
6199         cbz(fromReg, L_null);
6200       }
6201     }
6202     int off = sig->at(stream.sig_index())._offset;
6203     if (off == -1) {
6204       assert(null_check, "Missing null check at");
6205       if (toReg->is_stack()) {
6206         int st_off = toReg->reg2stack() * VMRegImpl::stack_slot_size;
6207         mov(tmp2, 1);
6208         str(tmp2, Address(sp, st_off));
6209       } else {
6210         mov(toReg->as_Register(), 1);
6211       }
6212       continue;
6213     }
6214     assert(off > 0, "offset in object should be positive");
6215     Address fromAddr = Address(fromReg, off);
6216     if (!toReg->is_FloatRegister()) {
6217       Register dst = toReg->is_stack() ? tmp2 : toReg->as_Register();
6218       if (is_reference_type(bt)) {
6219         load_heap_oop(dst, fromAddr, rscratch1, rscratch2);
6220       } else {
6221         bool is_signed = (bt != T_CHAR) && (bt != T_BOOLEAN);
6222         load_sized_value(dst, fromAddr, type2aelembytes(bt), is_signed);
6223       }
6224       if (toReg->is_stack()) {
6225         int st_off = toReg->reg2stack() * VMRegImpl::stack_slot_size;
6226         str(dst, Address(sp, st_off));
6227       }
6228     } else if (bt == T_DOUBLE) {
6229       ldrd(toReg->as_FloatRegister(), fromAddr);
6230     } else {
6231       assert(bt == T_FLOAT, "must be float");
6232       ldrs(toReg->as_FloatRegister(), fromAddr);
6233     }
6234   }
6235   if (progress && null_check) {
6236     if (done) {
6237       b(L_notNull);
6238       bind(L_null);
6239       // Set IsInit field to zero to signal that the argument is null.
6240       // Also set all oop fields to zero to make the GC happy.
6241       stream.reset(sig_index, to_index);
6242       while (stream.next(toReg, bt)) {
6243         if (sig->at(stream.sig_index())._offset == -1 ||
6244             bt == T_OBJECT || bt == T_ARRAY) {
6245           if (toReg->is_stack()) {
6246             int st_off = toReg->reg2stack() * VMRegImpl::stack_slot_size;
6247             str(zr, Address(sp, st_off));
6248           } else {
6249             mov(toReg->as_Register(), zr);
6250           }
6251         }
6252       }
6253       bind(L_notNull);
6254     } else {
6255       bind(L_null);
6256     }
6257   }
6258 
6259   sig_index = stream.sig_index();
6260   to_index = stream.regs_index();
6261 
6262   if (mark_done && reg_state[from->value()] != reg_written) {
6263     // This is okay because no one else will write to that slot
6264     reg_state[from->value()] = reg_writable;
6265   }
6266   from_index--;
6267   assert(progress || (start_offset == offset()), "should not emit code");
6268   return done;
6269 }
6270 
6271 // Pack fields back into an inline type oop
6272 bool MacroAssembler::pack_inline_helper(const GrowableArray<SigEntry>* sig, int& sig_index, int vtarg_index,
6273                                         VMRegPair* from, int from_count, int& from_index, VMReg to,
6274                                         RegState reg_state[], Register val_array) {
6275   assert(sig->at(sig_index)._bt == T_PRIMITIVE_OBJECT, "should be at end delimiter");
6276   assert(to->is_valid(), "destination must be valid");
6277 
6278   if (reg_state[to->value()] == reg_written) {
6279     skip_unpacked_fields(sig, sig_index, from, from_count, from_index);
6280     return true; // Already written
6281   }
6282 
6283   // The GC barrier expanded by store_heap_oop below may call into the
6284   // runtime so use callee-saved registers for any values that need to be
6285   // preserved. The GC barrier assembler should take care of saving the
6286   // Java argument registers.
6287   // TODO 8284443 Isn't it an issue if below code uses r14 as tmp when it contains a spilled value?
6288   // Be careful with r14 because it's used for spilling (see MacroAssembler::spill_reg_for).
6289   Register val_obj_tmp = r21;
6290   Register from_reg_tmp = r22;
6291   Register tmp1 = r14;
6292   Register tmp2 = r13;
6293   Register tmp3 = r12;
6294   Register val_obj = to->is_stack() ? val_obj_tmp : to->as_Register();
6295 
6296   assert_different_registers(val_obj_tmp, from_reg_tmp, tmp1, tmp2, tmp3, val_array);
6297 
6298   if (reg_state[to->value()] == reg_readonly) {
6299     if (!is_reg_in_unpacked_fields(sig, sig_index, to, from, from_count, from_index)) {
6300       skip_unpacked_fields(sig, sig_index, from, from_count, from_index);
6301       return false; // Not yet writable
6302     }
6303     val_obj = val_obj_tmp;
6304   }
6305 
6306   int index = arrayOopDesc::base_offset_in_bytes(T_OBJECT) + vtarg_index * type2aelembytes(T_PRIMITIVE_OBJECT);
6307   load_heap_oop(val_obj, Address(val_array, index), tmp1, tmp2);
6308 
6309   ScalarizedInlineArgsStream stream(sig, sig_index, from, from_count, from_index);
6310   VMReg fromReg;
6311   BasicType bt;
6312   Label L_null;
6313   while (stream.next(fromReg, bt)) {
6314     assert(fromReg->is_valid(), "source must be valid");
6315     reg_state[fromReg->value()] = reg_writable;
6316 
6317     int off = sig->at(stream.sig_index())._offset;
6318     if (off == -1) {
6319       // Nullable inline type argument, emit null check
6320       Label L_notNull;
6321       if (fromReg->is_stack()) {
6322         int ld_off = fromReg->reg2stack() * VMRegImpl::stack_slot_size;
6323         ldr(tmp2, Address(sp, ld_off));
6324         cbnz(tmp2, L_notNull);
6325       } else {
6326         cbnz(fromReg->as_Register(), L_notNull);
6327       }
6328       mov(val_obj, 0);
6329       b(L_null);
6330       bind(L_notNull);
6331       continue;
6332     }
6333 
6334     assert(off > 0, "offset in object should be positive");
6335     size_t size_in_bytes = is_java_primitive(bt) ? type2aelembytes(bt) : wordSize;
6336 
6337     // Pack the scalarized field into the value object.
6338     Address dst(val_obj, off);
6339 
6340     if (!fromReg->is_FloatRegister()) {
6341       Register src;
6342       if (fromReg->is_stack()) {
6343         src = from_reg_tmp;
6344         int ld_off = fromReg->reg2stack() * VMRegImpl::stack_slot_size;
6345         load_sized_value(src, Address(sp, ld_off), size_in_bytes, /* is_signed */ false);
6346       } else {
6347         src = fromReg->as_Register();
6348       }
6349       assert_different_registers(dst.base(), src, tmp1, tmp2, tmp3, val_array);
6350       if (is_reference_type(bt)) {
6351         store_heap_oop(dst, src, tmp1, tmp2, tmp3, IN_HEAP | ACCESS_WRITE | IS_DEST_UNINITIALIZED);
6352       } else {
6353         store_sized_value(dst, src, size_in_bytes);
6354       }
6355     } else if (bt == T_DOUBLE) {
6356       strd(fromReg->as_FloatRegister(), dst);
6357     } else {
6358       assert(bt == T_FLOAT, "must be float");
6359       strs(fromReg->as_FloatRegister(), dst);
6360     }
6361   }
6362   bind(L_null);
6363   sig_index = stream.sig_index();
6364   from_index = stream.regs_index();
6365 
6366   assert(reg_state[to->value()] == reg_writable, "must have already been read");
6367   bool success = move_helper(val_obj->as_VMReg(), to, T_OBJECT, reg_state);
6368   assert(success, "to register must be writeable");
6369 
6370   return true;
6371 }
6372 
6373 VMReg MacroAssembler::spill_reg_for(VMReg reg) {
6374   return (reg->is_FloatRegister()) ? v0->as_VMReg() : r14->as_VMReg();
6375 }
6376 
6377 void MacroAssembler::cache_wb(Address line) {
6378   assert(line.getMode() == Address::base_plus_offset, "mode should be base_plus_offset");
6379   assert(line.index() == noreg, "index should be noreg");
6380   assert(line.offset() == 0, "offset should be 0");
6381   // would like to assert this
6382   // assert(line._ext.shift == 0, "shift should be zero");
6383   if (VM_Version::supports_dcpop()) {
6384     // writeback using clear virtual address to point of persistence
6385     dc(Assembler::CVAP, line.base());
6386   } else {
6387     // no need to generate anything as Unsafe.writebackMemory should
6388     // never invoke this stub
6389   }
6390 }
6391 
6392 void MacroAssembler::cache_wbsync(bool is_pre) {
6393   // we only need a barrier post sync
6394   if (!is_pre) {
6395     membar(Assembler::AnyAny);
6396   }
6397 }
6398 
6399 void MacroAssembler::verify_sve_vector_length(Register tmp) {
6400   // Make sure that native code does not change SVE vector length.
6401   if (!UseSVE) return;
6402   Label verify_ok;
6403   movw(tmp, zr);
6404   sve_inc(tmp, B);
6405   subsw(zr, tmp, VM_Version::get_initial_sve_vector_length());
6406   br(EQ, verify_ok);
6407   stop("Error: SVE vector length has changed since jvm startup");
6408   bind(verify_ok);
6409 }
6410 
6411 void MacroAssembler::verify_ptrue() {
6412   Label verify_ok;
6413   if (!UseSVE) {
6414     return;
6415   }
6416   sve_cntp(rscratch1, B, ptrue, ptrue); // get true elements count.
6417   sve_dec(rscratch1, B);
6418   cbz(rscratch1, verify_ok);
6419   stop("Error: the preserved predicate register (p7) elements are not all true");
6420   bind(verify_ok);
6421 }
6422 
6423 void MacroAssembler::safepoint_isb() {
6424   isb();
6425 #ifndef PRODUCT
6426   if (VerifyCrossModifyFence) {
6427     // Clear the thread state.
6428     strb(zr, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
6429   }
6430 #endif
6431 }
6432 
6433 #ifndef PRODUCT
6434 void MacroAssembler::verify_cross_modify_fence_not_required() {
6435   if (VerifyCrossModifyFence) {
6436     // Check if thread needs a cross modify fence.
6437     ldrb(rscratch1, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
6438     Label fence_not_required;
6439     cbz(rscratch1, fence_not_required);
6440     // If it does then fail.
6441     lea(rscratch1, CAST_FROM_FN_PTR(address, JavaThread::verify_cross_modify_fence_failure));
6442     mov(c_rarg0, rthread);
6443     blr(rscratch1);
6444     bind(fence_not_required);
6445   }
6446 }
6447 #endif
6448 
6449 void MacroAssembler::spin_wait() {
6450   for (int i = 0; i < VM_Version::spin_wait_desc().inst_count(); ++i) {
6451     switch (VM_Version::spin_wait_desc().inst()) {
6452       case SpinWait::NOP:
6453         nop();
6454         break;
6455       case SpinWait::ISB:
6456         isb();
6457         break;
6458       case SpinWait::YIELD:
6459         yield();
6460         break;
6461       default:
6462         ShouldNotReachHere();
6463     }
6464   }
6465 }
6466 
6467 // Stack frame creation/removal
6468 
6469 void MacroAssembler::enter(bool strip_ret_addr) {
6470   if (strip_ret_addr) {
6471     // Addresses can only be signed once. If there are multiple nested frames being created
6472     // in the same function, then the return address needs stripping first.
6473     strip_return_address();
6474   }
6475   protect_return_address();
6476   stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
6477   mov(rfp, sp);
6478 }
6479 
6480 void MacroAssembler::leave() {
6481   mov(sp, rfp);
6482   ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
6483   authenticate_return_address();
6484 }
6485 
6486 // ROP Protection
6487 // Use the AArch64 PAC feature to add ROP protection for generated code. Use whenever creating/
6488 // destroying stack frames or whenever directly loading/storing the LR to memory.
6489 // If ROP protection is not set then these functions are no-ops.
6490 // For more details on PAC see pauth_aarch64.hpp.
6491 
6492 // Sign the LR. Use during construction of a stack frame, before storing the LR to memory.
6493 // Uses the FP as the modifier.
6494 //
6495 void MacroAssembler::protect_return_address() {
6496   if (VM_Version::use_rop_protection()) {
6497     check_return_address();
6498     // The standard convention for C code is to use paciasp, which uses SP as the modifier. This
6499     // works because in C code, FP and SP match on function entry. In the JDK, SP and FP may not
6500     // match, so instead explicitly use the FP.
6501     pacia(lr, rfp);
6502   }
6503 }
6504 
6505 // Sign the return value in the given register. Use before updating the LR in the existing stack
6506 // frame for the current function.
6507 // Uses the FP from the start of the function as the modifier - which is stored at the address of
6508 // the current FP.
6509 //
6510 void MacroAssembler::protect_return_address(Register return_reg, Register temp_reg) {
6511   if (VM_Version::use_rop_protection()) {
6512     assert(PreserveFramePointer, "PreserveFramePointer must be set for ROP protection");
6513     check_return_address(return_reg);
6514     ldr(temp_reg, Address(rfp));
6515     pacia(return_reg, temp_reg);
6516   }
6517 }
6518 
6519 // Authenticate the LR. Use before function return, after restoring FP and loading LR from memory.
6520 //
6521 void MacroAssembler::authenticate_return_address(Register return_reg) {
6522   if (VM_Version::use_rop_protection()) {
6523     autia(return_reg, rfp);
6524     check_return_address(return_reg);
6525   }
6526 }
6527 
6528 // Authenticate the return value in the given register. Use before updating the LR in the existing
6529 // stack frame for the current function.
6530 // Uses the FP from the start of the function as the modifier - which is stored at the address of
6531 // the current FP.
6532 //
6533 void MacroAssembler::authenticate_return_address(Register return_reg, Register temp_reg) {
6534   if (VM_Version::use_rop_protection()) {
6535     assert(PreserveFramePointer, "PreserveFramePointer must be set for ROP protection");
6536     ldr(temp_reg, Address(rfp));
6537     autia(return_reg, temp_reg);
6538     check_return_address(return_reg);
6539   }
6540 }
6541 
6542 // Strip any PAC data from LR without performing any authentication. Use with caution - only if
6543 // there is no guaranteed way of authenticating the LR.
6544 //
6545 void MacroAssembler::strip_return_address() {
6546   if (VM_Version::use_rop_protection()) {
6547     xpaclri();
6548   }
6549 }
6550 
6551 #ifndef PRODUCT
6552 // PAC failures can be difficult to debug. After an authentication failure, a segfault will only
6553 // occur when the pointer is used - ie when the program returns to the invalid LR. At this point
6554 // it is difficult to debug back to the callee function.
6555 // This function simply loads from the address in the given register.
6556 // Use directly after authentication to catch authentication failures.
6557 // Also use before signing to check that the pointer is valid and hasn't already been signed.
6558 //
6559 void MacroAssembler::check_return_address(Register return_reg) {
6560   if (VM_Version::use_rop_protection()) {
6561     ldr(zr, Address(return_reg));
6562   }
6563 }
6564 #endif
6565 
6566 // The java_calling_convention describes stack locations as ideal slots on
6567 // a frame with no abi restrictions. Since we must observe abi restrictions
6568 // (like the placement of the register window) the slots must be biased by
6569 // the following value.
6570 static int reg2offset_in(VMReg r) {
6571   // Account for saved rfp and lr
6572   // This should really be in_preserve_stack_slots
6573   return (r->reg2stack() + 4) * VMRegImpl::stack_slot_size;
6574 }
6575 
6576 static int reg2offset_out(VMReg r) {
6577   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
6578 }
6579 
6580 // On 64bit we will store integer like items to the stack as
6581 // 64bits items (AArch64 ABI) even though java would only store
6582 // 32bits for a parameter. On 32bit it will simply be 32bits
6583 // So this routine will do 32->32 on 32bit and 32->64 on 64bit
6584 void MacroAssembler::move32_64(VMRegPair src, VMRegPair dst, Register tmp) {
6585   if (src.first()->is_stack()) {
6586     if (dst.first()->is_stack()) {
6587       // stack to stack
6588       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
6589       str(tmp, Address(sp, reg2offset_out(dst.first())));
6590     } else {
6591       // stack to reg
6592       ldrsw(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
6593     }
6594   } else if (dst.first()->is_stack()) {
6595     // reg to stack
6596     str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
6597   } else {
6598     if (dst.first() != src.first()) {
6599       sxtw(dst.first()->as_Register(), src.first()->as_Register());
6600     }
6601   }
6602 }
6603 
6604 // An oop arg. Must pass a handle not the oop itself
6605 void MacroAssembler::object_move(
6606                         OopMap* map,
6607                         int oop_handle_offset,
6608                         int framesize_in_slots,
6609                         VMRegPair src,
6610                         VMRegPair dst,
6611                         bool is_receiver,
6612                         int* receiver_offset) {
6613 
6614   // must pass a handle. First figure out the location we use as a handle
6615 
6616   Register rHandle = dst.first()->is_stack() ? rscratch2 : dst.first()->as_Register();
6617 
6618   // See if oop is NULL if it is we need no handle
6619 
6620   if (src.first()->is_stack()) {
6621 
6622     // Oop is already on the stack as an argument
6623     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
6624     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
6625     if (is_receiver) {
6626       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
6627     }
6628 
6629     ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
6630     lea(rHandle, Address(rfp, reg2offset_in(src.first())));
6631     // conditionally move a NULL
6632     cmp(rscratch1, zr);
6633     csel(rHandle, zr, rHandle, Assembler::EQ);
6634   } else {
6635 
6636     // Oop is in an a register we must store it to the space we reserve
6637     // on the stack for oop_handles and pass a handle if oop is non-NULL
6638 
6639     const Register rOop = src.first()->as_Register();
6640     int oop_slot;
6641     if (rOop == j_rarg0)
6642       oop_slot = 0;
6643     else if (rOop == j_rarg1)
6644       oop_slot = 1;
6645     else if (rOop == j_rarg2)
6646       oop_slot = 2;
6647     else if (rOop == j_rarg3)
6648       oop_slot = 3;
6649     else if (rOop == j_rarg4)
6650       oop_slot = 4;
6651     else if (rOop == j_rarg5)
6652       oop_slot = 5;
6653     else if (rOop == j_rarg6)
6654       oop_slot = 6;
6655     else {
6656       assert(rOop == j_rarg7, "wrong register");
6657       oop_slot = 7;
6658     }
6659 
6660     oop_slot = oop_slot * VMRegImpl::slots_per_word + oop_handle_offset;
6661     int offset = oop_slot*VMRegImpl::stack_slot_size;
6662 
6663     map->set_oop(VMRegImpl::stack2reg(oop_slot));
6664     // Store oop in handle area, may be NULL
6665     str(rOop, Address(sp, offset));
6666     if (is_receiver) {
6667       *receiver_offset = offset;
6668     }
6669 
6670     cmp(rOop, zr);
6671     lea(rHandle, Address(sp, offset));
6672     // conditionally move a NULL
6673     csel(rHandle, zr, rHandle, Assembler::EQ);
6674   }
6675 
6676   // If arg is on the stack then place it otherwise it is already in correct reg.
6677   if (dst.first()->is_stack()) {
6678     str(rHandle, Address(sp, reg2offset_out(dst.first())));
6679   }
6680 }
6681 
6682 // A float arg may have to do float reg int reg conversion
6683 void MacroAssembler::float_move(VMRegPair src, VMRegPair dst, Register tmp) {
6684  if (src.first()->is_stack()) {
6685     if (dst.first()->is_stack()) {
6686       ldrw(tmp, Address(rfp, reg2offset_in(src.first())));
6687       strw(tmp, Address(sp, reg2offset_out(dst.first())));
6688     } else {
6689       ldrs(dst.first()->as_FloatRegister(), Address(rfp, reg2offset_in(src.first())));
6690     }
6691   } else if (src.first() != dst.first()) {
6692     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
6693       fmovs(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
6694     else
6695       strs(src.first()->as_FloatRegister(), Address(sp, reg2offset_out(dst.first())));
6696   }
6697 }
6698 
6699 // A long move
6700 void MacroAssembler::long_move(VMRegPair src, VMRegPair dst, Register tmp) {
6701   if (src.first()->is_stack()) {
6702     if (dst.first()->is_stack()) {
6703       // stack to stack
6704       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
6705       str(tmp, Address(sp, reg2offset_out(dst.first())));
6706     } else {
6707       // stack to reg
6708       ldr(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
6709     }
6710   } else if (dst.first()->is_stack()) {
6711     // reg to stack
6712     // Do we really have to sign extend???
6713     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
6714     str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
6715   } else {
6716     if (dst.first() != src.first()) {
6717       mov(dst.first()->as_Register(), src.first()->as_Register());
6718     }
6719   }
6720 }
6721 
6722 
6723 // A double move
6724 void MacroAssembler::double_move(VMRegPair src, VMRegPair dst, Register tmp) {
6725  if (src.first()->is_stack()) {
6726     if (dst.first()->is_stack()) {
6727       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
6728       str(tmp, Address(sp, reg2offset_out(dst.first())));
6729     } else {
6730       ldrd(dst.first()->as_FloatRegister(), Address(rfp, reg2offset_in(src.first())));
6731     }
6732   } else if (src.first() != dst.first()) {
6733     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
6734       fmovd(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
6735     else
6736       strd(src.first()->as_FloatRegister(), Address(sp, reg2offset_out(dst.first())));
6737   }
6738 }