1 /*
   2  * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2014, 2015, Red Hat Inc. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include <sys/types.h>
  27 
  28 #include "precompiled.hpp"
  29 #include "jvm.h"
  30 #include "asm/assembler.hpp"
  31 #include "asm/assembler.inline.hpp"
  32 #include "interpreter/interpreter.hpp"
  33 
  34 #include "compiler/disassembler.hpp"
  35 #include "memory/resourceArea.hpp"
  36 #include "nativeInst_aarch64.hpp"
  37 #include "oops/klass.inline.hpp"
  38 #include "oops/oop.inline.hpp"
  39 #include "opto/compile.hpp"
  40 #include "opto/intrinsicnode.hpp"
  41 #include "opto/node.hpp"
  42 #include "runtime/biasedLocking.hpp"
  43 #include "runtime/icache.hpp"
  44 #include "runtime/interfaceSupport.hpp"
  45 #include "runtime/sharedRuntime.hpp"
  46 #include "runtime/thread.hpp"
  47 
  48 #if INCLUDE_ALL_GCS
  49 #include "gc/g1/g1CollectedHeap.inline.hpp"
  50 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  51 #include "gc/g1/heapRegion.hpp"
  52 #endif
  53 
  54 #ifdef PRODUCT
  55 #define BLOCK_COMMENT(str) /* nothing */
  56 #define STOP(error) stop(error)
  57 #else
  58 #define BLOCK_COMMENT(str) block_comment(str)
  59 #define STOP(error) block_comment(error); stop(error)
  60 #endif
  61 
  62 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  63 
  64 // Patch any kind of instruction; there may be several instructions.
  65 // Return the total length (in bytes) of the instructions.
  66 int MacroAssembler::pd_patch_instruction_size(address branch, address target) {
  67   int instructions = 1;
  68   assert((uint64_t)target < (1ul << 48), "48-bit overflow in address constant");
  69   long offset = (target - branch) >> 2;
  70   unsigned insn = *(unsigned*)branch;
  71   if ((Instruction_aarch64::extract(insn, 29, 24) & 0b111011) == 0b011000) {
  72     // Load register (literal)
  73     Instruction_aarch64::spatch(branch, 23, 5, offset);
  74   } else if (Instruction_aarch64::extract(insn, 30, 26) == 0b00101) {
  75     // Unconditional branch (immediate)
  76     Instruction_aarch64::spatch(branch, 25, 0, offset);
  77   } else if (Instruction_aarch64::extract(insn, 31, 25) == 0b0101010) {
  78     // Conditional branch (immediate)
  79     Instruction_aarch64::spatch(branch, 23, 5, offset);
  80   } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011010) {
  81     // Compare & branch (immediate)
  82     Instruction_aarch64::spatch(branch, 23, 5, offset);
  83   } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011011) {
  84     // Test & branch (immediate)
  85     Instruction_aarch64::spatch(branch, 18, 5, offset);
  86   } else if (Instruction_aarch64::extract(insn, 28, 24) == 0b10000) {
  87     // PC-rel. addressing
  88     offset = target-branch;
  89     int shift = Instruction_aarch64::extract(insn, 31, 31);
  90     if (shift) {
  91       u_int64_t dest = (u_int64_t)target;
  92       uint64_t pc_page = (uint64_t)branch >> 12;
  93       uint64_t adr_page = (uint64_t)target >> 12;
  94       unsigned offset_lo = dest & 0xfff;
  95       offset = adr_page - pc_page;
  96 
  97       // We handle 4 types of PC relative addressing
  98       //   1 - adrp    Rx, target_page
  99       //       ldr/str Ry, [Rx, #offset_in_page]
 100       //   2 - adrp    Rx, target_page
 101       //       add     Ry, Rx, #offset_in_page
 102       //   3 - adrp    Rx, target_page (page aligned reloc, offset == 0)
 103       //       movk    Rx, #imm16<<32
 104       //   4 - adrp    Rx, target_page (page aligned reloc, offset == 0)
 105       // In the first 3 cases we must check that Rx is the same in the adrp and the
 106       // subsequent ldr/str, add or movk instruction. Otherwise we could accidentally end
 107       // up treating a type 4 relocation as a type 1, 2 or 3 just because it happened
 108       // to be followed by a random unrelated ldr/str, add or movk instruction.
 109       //
 110       unsigned insn2 = ((unsigned*)branch)[1];
 111       if (Instruction_aarch64::extract(insn2, 29, 24) == 0b111001 &&
 112                 Instruction_aarch64::extract(insn, 4, 0) ==
 113                         Instruction_aarch64::extract(insn2, 9, 5)) {
 114         // Load/store register (unsigned immediate)
 115         unsigned size = Instruction_aarch64::extract(insn2, 31, 30);
 116         Instruction_aarch64::patch(branch + sizeof (unsigned),
 117                                     21, 10, offset_lo >> size);
 118         guarantee(((dest >> size) << size) == dest, "misaligned target");
 119         instructions = 2;
 120       } else if (Instruction_aarch64::extract(insn2, 31, 22) == 0b1001000100 &&
 121                 Instruction_aarch64::extract(insn, 4, 0) ==
 122                         Instruction_aarch64::extract(insn2, 4, 0)) {
 123         // add (immediate)
 124         Instruction_aarch64::patch(branch + sizeof (unsigned),
 125                                    21, 10, offset_lo);
 126         instructions = 2;
 127       } else if (Instruction_aarch64::extract(insn2, 31, 21) == 0b11110010110 &&
 128                    Instruction_aarch64::extract(insn, 4, 0) ==
 129                      Instruction_aarch64::extract(insn2, 4, 0)) {
 130         // movk #imm16<<32
 131         Instruction_aarch64::patch(branch + 4, 20, 5, (uint64_t)target >> 32);
 132         long dest = ((long)target & 0xffffffffL) | ((long)branch & 0xffff00000000L);
 133         long pc_page = (long)branch >> 12;
 134         long adr_page = (long)dest >> 12;
 135         offset = adr_page - pc_page;
 136         instructions = 2;
 137       }
 138     }
 139     int offset_lo = offset & 3;
 140     offset >>= 2;
 141     Instruction_aarch64::spatch(branch, 23, 5, offset);
 142     Instruction_aarch64::patch(branch, 30, 29, offset_lo);
 143   } else if (Instruction_aarch64::extract(insn, 31, 21) == 0b11010010100) {
 144     u_int64_t dest = (u_int64_t)target;
 145     // Move wide constant
 146     assert(nativeInstruction_at(branch+4)->is_movk(), "wrong insns in patch");
 147     assert(nativeInstruction_at(branch+8)->is_movk(), "wrong insns in patch");
 148     Instruction_aarch64::patch(branch, 20, 5, dest & 0xffff);
 149     Instruction_aarch64::patch(branch+4, 20, 5, (dest >>= 16) & 0xffff);
 150     Instruction_aarch64::patch(branch+8, 20, 5, (dest >>= 16) & 0xffff);
 151     assert(target_addr_for_insn(branch) == target, "should be");
 152     instructions = 3;
 153   } else if (Instruction_aarch64::extract(insn, 31, 22) == 0b1011100101 &&
 154              Instruction_aarch64::extract(insn, 4, 0) == 0b11111) {
 155     // nothing to do
 156     assert(target == 0, "did not expect to relocate target for polling page load");
 157   } else {
 158     ShouldNotReachHere();
 159   }
 160   return instructions * NativeInstruction::instruction_size;
 161 }
 162 
 163 int MacroAssembler::patch_oop(address insn_addr, address o) {
 164   int instructions;
 165   unsigned insn = *(unsigned*)insn_addr;
 166   assert(nativeInstruction_at(insn_addr+4)->is_movk(), "wrong insns in patch");
 167 
 168   // OOPs are either narrow (32 bits) or wide (48 bits).  We encode
 169   // narrow OOPs by setting the upper 16 bits in the first
 170   // instruction.
 171   if (Instruction_aarch64::extract(insn, 31, 21) == 0b11010010101) {
 172     // Move narrow OOP
 173     narrowOop n = oopDesc::encode_heap_oop((oop)o);
 174     Instruction_aarch64::patch(insn_addr, 20, 5, n >> 16);
 175     Instruction_aarch64::patch(insn_addr+4, 20, 5, n & 0xffff);
 176     instructions = 2;
 177   } else {
 178     // Move wide OOP
 179     assert(nativeInstruction_at(insn_addr+8)->is_movk(), "wrong insns in patch");
 180     uintptr_t dest = (uintptr_t)o;
 181     Instruction_aarch64::patch(insn_addr, 20, 5, dest & 0xffff);
 182     Instruction_aarch64::patch(insn_addr+4, 20, 5, (dest >>= 16) & 0xffff);
 183     Instruction_aarch64::patch(insn_addr+8, 20, 5, (dest >>= 16) & 0xffff);
 184     instructions = 3;
 185   }
 186   return instructions * NativeInstruction::instruction_size;
 187 }
 188 
 189 int MacroAssembler::patch_narrow_klass(address insn_addr, narrowKlass n) {
 190   // Metatdata pointers are either narrow (32 bits) or wide (48 bits).
 191   // We encode narrow ones by setting the upper 16 bits in the first
 192   // instruction.
 193   NativeInstruction *insn = nativeInstruction_at(insn_addr);
 194   assert(Instruction_aarch64::extract(insn->encoding(), 31, 21) == 0b11010010101 &&
 195          nativeInstruction_at(insn_addr+4)->is_movk(), "wrong insns in patch");
 196 
 197   Instruction_aarch64::patch(insn_addr, 20, 5, n >> 16);
 198   Instruction_aarch64::patch(insn_addr+4, 20, 5, n & 0xffff);
 199   return 2 * NativeInstruction::instruction_size;
 200 }
 201 
 202 address MacroAssembler::target_addr_for_insn(address insn_addr, unsigned insn) {
 203   long offset = 0;
 204   if ((Instruction_aarch64::extract(insn, 29, 24) & 0b011011) == 0b00011000) {
 205     // Load register (literal)
 206     offset = Instruction_aarch64::sextract(insn, 23, 5);
 207     return address(((uint64_t)insn_addr + (offset << 2)));
 208   } else if (Instruction_aarch64::extract(insn, 30, 26) == 0b00101) {
 209     // Unconditional branch (immediate)
 210     offset = Instruction_aarch64::sextract(insn, 25, 0);
 211   } else if (Instruction_aarch64::extract(insn, 31, 25) == 0b0101010) {
 212     // Conditional branch (immediate)
 213     offset = Instruction_aarch64::sextract(insn, 23, 5);
 214   } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011010) {
 215     // Compare & branch (immediate)
 216     offset = Instruction_aarch64::sextract(insn, 23, 5);
 217    } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011011) {
 218     // Test & branch (immediate)
 219     offset = Instruction_aarch64::sextract(insn, 18, 5);
 220   } else if (Instruction_aarch64::extract(insn, 28, 24) == 0b10000) {
 221     // PC-rel. addressing
 222     offset = Instruction_aarch64::extract(insn, 30, 29);
 223     offset |= Instruction_aarch64::sextract(insn, 23, 5) << 2;
 224     int shift = Instruction_aarch64::extract(insn, 31, 31) ? 12 : 0;
 225     if (shift) {
 226       offset <<= shift;
 227       uint64_t target_page = ((uint64_t)insn_addr) + offset;
 228       target_page &= ((uint64_t)-1) << shift;
 229       // Return the target address for the following sequences
 230       //   1 - adrp    Rx, target_page
 231       //       ldr/str Ry, [Rx, #offset_in_page]
 232       //   2 - adrp    Rx, target_page
 233       //       add     Ry, Rx, #offset_in_page
 234       //   3 - adrp    Rx, target_page (page aligned reloc, offset == 0)
 235       //       movk    Rx, #imm12<<32
 236       //   4 - adrp    Rx, target_page (page aligned reloc, offset == 0)
 237       //
 238       // In the first two cases  we check that the register is the same and
 239       // return the target_page + the offset within the page.
 240       // Otherwise we assume it is a page aligned relocation and return
 241       // the target page only.
 242       //
 243       unsigned insn2 = ((unsigned*)insn_addr)[1];
 244       if (Instruction_aarch64::extract(insn2, 29, 24) == 0b111001 &&
 245                 Instruction_aarch64::extract(insn, 4, 0) ==
 246                         Instruction_aarch64::extract(insn2, 9, 5)) {
 247         // Load/store register (unsigned immediate)
 248         unsigned int byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 249         unsigned int size = Instruction_aarch64::extract(insn2, 31, 30);
 250         return address(target_page + (byte_offset << size));
 251       } else if (Instruction_aarch64::extract(insn2, 31, 22) == 0b1001000100 &&
 252                 Instruction_aarch64::extract(insn, 4, 0) ==
 253                         Instruction_aarch64::extract(insn2, 4, 0)) {
 254         // add (immediate)
 255         unsigned int byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 256         return address(target_page + byte_offset);
 257       } else {
 258         if (Instruction_aarch64::extract(insn2, 31, 21) == 0b11110010110  &&
 259                Instruction_aarch64::extract(insn, 4, 0) ==
 260                  Instruction_aarch64::extract(insn2, 4, 0)) {
 261           target_page = (target_page & 0xffffffff) |
 262                          ((uint64_t)Instruction_aarch64::extract(insn2, 20, 5) << 32);
 263         }
 264         return (address)target_page;
 265       }
 266     } else {
 267       ShouldNotReachHere();
 268     }
 269   } else if (Instruction_aarch64::extract(insn, 31, 23) == 0b110100101) {
 270     u_int32_t *insns = (u_int32_t *)insn_addr;
 271     // Move wide constant: movz, movk, movk.  See movptr().
 272     assert(nativeInstruction_at(insns+1)->is_movk(), "wrong insns in patch");
 273     assert(nativeInstruction_at(insns+2)->is_movk(), "wrong insns in patch");
 274     return address(u_int64_t(Instruction_aarch64::extract(insns[0], 20, 5))
 275                    + (u_int64_t(Instruction_aarch64::extract(insns[1], 20, 5)) << 16)
 276                    + (u_int64_t(Instruction_aarch64::extract(insns[2], 20, 5)) << 32));
 277   } else if (Instruction_aarch64::extract(insn, 31, 22) == 0b1011100101 &&
 278              Instruction_aarch64::extract(insn, 4, 0) == 0b11111) {
 279     return 0;
 280   } else {
 281     ShouldNotReachHere();
 282   }
 283   return address(((uint64_t)insn_addr + (offset << 2)));
 284 }
 285 
 286 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
 287   dsb(Assembler::SY);
 288 }
 289 
 290 void MacroAssembler::safepoint_poll(Label& slow_path) {
 291   if (SafepointMechanism::uses_thread_local_poll()) {
 292     ldr(rscratch1, Address(rthread, Thread::polling_page_offset()));
 293     tbnz(rscratch1, exact_log2(SafepointMechanism::poll_bit()), slow_path);
 294   } else {
 295     unsigned long offset;
 296     adrp(rscratch1, ExternalAddress(SafepointSynchronize::address_of_state()), offset);
 297     ldrw(rscratch1, Address(rscratch1, offset));
 298     assert(SafepointSynchronize::_not_synchronized == 0, "rewrite this code");
 299     cbnz(rscratch1, slow_path);
 300   }
 301 }
 302 
 303 // Just like safepoint_poll, but use an acquiring load for thread-
 304 // local polling.
 305 //
 306 // We need an acquire here to ensure that any subsequent load of the
 307 // global SafepointSynchronize::_state flag is ordered after this load
 308 // of the local Thread::_polling page.  We don't want this poll to
 309 // return false (i.e. not safepointing) and a later poll of the global
 310 // SafepointSynchronize::_state spuriously to return true.
 311 //
 312 // This is to avoid a race when we're in a native->Java transition
 313 // racing the code which wakes up from a safepoint.
 314 //
 315 void MacroAssembler::safepoint_poll_acquire(Label& slow_path) {
 316   if (SafepointMechanism::uses_thread_local_poll()) {
 317     lea(rscratch1, Address(rthread, Thread::polling_page_offset()));
 318     ldar(rscratch1, rscratch1);
 319     tbnz(rscratch1, exact_log2(SafepointMechanism::poll_bit()), slow_path);
 320   } else {
 321     safepoint_poll(slow_path);
 322   }
 323 }
 324 
 325 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 326   // we must set sp to zero to clear frame
 327   str(zr, Address(rthread, JavaThread::last_Java_sp_offset()));
 328 
 329   // must clear fp, so that compiled frames are not confused; it is
 330   // possible that we need it only for debugging
 331   if (clear_fp) {
 332     str(zr, Address(rthread, JavaThread::last_Java_fp_offset()));
 333   }
 334 
 335   // Always clear the pc because it could have been set by make_walkable()
 336   str(zr, Address(rthread, JavaThread::last_Java_pc_offset()));
 337 }
 338 
 339 // Calls to C land
 340 //
 341 // When entering C land, the rfp, & resp of the last Java frame have to be recorded
 342 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
 343 // has to be reset to 0. This is required to allow proper stack traversal.
 344 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 345                                          Register last_java_fp,
 346                                          Register last_java_pc,
 347                                          Register scratch) {
 348 
 349   if (last_java_pc->is_valid()) {
 350       str(last_java_pc, Address(rthread,
 351                                 JavaThread::frame_anchor_offset()
 352                                 + JavaFrameAnchor::last_Java_pc_offset()));
 353     }
 354 
 355   // determine last_java_sp register
 356   if (last_java_sp == sp) {
 357     mov(scratch, sp);
 358     last_java_sp = scratch;
 359   } else if (!last_java_sp->is_valid()) {
 360     last_java_sp = esp;
 361   }
 362 
 363   str(last_java_sp, Address(rthread, JavaThread::last_Java_sp_offset()));
 364 
 365   // last_java_fp is optional
 366   if (last_java_fp->is_valid()) {
 367     str(last_java_fp, Address(rthread, JavaThread::last_Java_fp_offset()));
 368   }
 369 }
 370 
 371 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 372                                          Register last_java_fp,
 373                                          address  last_java_pc,
 374                                          Register scratch) {
 375   if (last_java_pc != NULL) {
 376     adr(scratch, last_java_pc);
 377   } else {
 378     // FIXME: This is almost never correct.  We should delete all
 379     // cases of set_last_Java_frame with last_java_pc=NULL and use the
 380     // correct return address instead.
 381     adr(scratch, pc());
 382   }
 383 
 384   str(scratch, Address(rthread,
 385                        JavaThread::frame_anchor_offset()
 386                        + JavaFrameAnchor::last_Java_pc_offset()));
 387 
 388   set_last_Java_frame(last_java_sp, last_java_fp, noreg, scratch);
 389 }
 390 
 391 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 392                                          Register last_java_fp,
 393                                          Label &L,
 394                                          Register scratch) {
 395   if (L.is_bound()) {
 396     set_last_Java_frame(last_java_sp, last_java_fp, target(L), scratch);
 397   } else {
 398     InstructionMark im(this);
 399     L.add_patch_at(code(), locator());
 400     set_last_Java_frame(last_java_sp, last_java_fp, (address)NULL, scratch);
 401   }
 402 }
 403 
 404 void MacroAssembler::far_call(Address entry, CodeBuffer *cbuf, Register tmp) {
 405   assert(ReservedCodeCacheSize < 4*G, "branch out of range");
 406   assert(CodeCache::find_blob(entry.target()) != NULL,
 407          "destination of far call not found in code cache");
 408   if (far_branches()) {
 409     unsigned long offset;
 410     // We can use ADRP here because we know that the total size of
 411     // the code cache cannot exceed 2Gb.
 412     adrp(tmp, entry, offset);
 413     add(tmp, tmp, offset);
 414     if (cbuf) cbuf->set_insts_mark();
 415     blr(tmp);
 416   } else {
 417     if (cbuf) cbuf->set_insts_mark();
 418     bl(entry);
 419   }
 420 }
 421 
 422 void MacroAssembler::far_jump(Address entry, CodeBuffer *cbuf, Register tmp) {
 423   assert(ReservedCodeCacheSize < 4*G, "branch out of range");
 424   assert(CodeCache::find_blob(entry.target()) != NULL,
 425          "destination of far call not found in code cache");
 426   if (far_branches()) {
 427     unsigned long offset;
 428     // We can use ADRP here because we know that the total size of
 429     // the code cache cannot exceed 2Gb.
 430     adrp(tmp, entry, offset);
 431     add(tmp, tmp, offset);
 432     if (cbuf) cbuf->set_insts_mark();
 433     br(tmp);
 434   } else {
 435     if (cbuf) cbuf->set_insts_mark();
 436     b(entry);
 437   }
 438 }
 439 
 440 void MacroAssembler::reserved_stack_check() {
 441     // testing if reserved zone needs to be enabled
 442     Label no_reserved_zone_enabling;
 443 
 444     ldr(rscratch1, Address(rthread, JavaThread::reserved_stack_activation_offset()));
 445     cmp(sp, rscratch1);
 446     br(Assembler::LO, no_reserved_zone_enabling);
 447 
 448     enter();   // LR and FP are live.
 449     lea(rscratch1, CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone));
 450     mov(c_rarg0, rthread);
 451     blr(rscratch1);
 452     leave();
 453 
 454     // We have already removed our own frame.
 455     // throw_delayed_StackOverflowError will think that it's been
 456     // called by our caller.
 457     lea(rscratch1, RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
 458     br(rscratch1);
 459     should_not_reach_here();
 460 
 461     bind(no_reserved_zone_enabling);
 462 }
 463 
 464 int MacroAssembler::biased_locking_enter(Register lock_reg,
 465                                          Register obj_reg,
 466                                          Register swap_reg,
 467                                          Register tmp_reg,
 468                                          bool swap_reg_contains_mark,
 469                                          Label& done,
 470                                          Label* slow_case,
 471                                          BiasedLockingCounters* counters) {
 472   assert(UseBiasedLocking, "why call this otherwise?");
 473   assert_different_registers(lock_reg, obj_reg, swap_reg);
 474 
 475   if (PrintBiasedLockingStatistics && counters == NULL)
 476     counters = BiasedLocking::counters();
 477 
 478   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg, rscratch1, rscratch2, noreg);
 479   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
 480   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
 481   Address klass_addr     (obj_reg, oopDesc::klass_offset_in_bytes());
 482   Address saved_mark_addr(lock_reg, 0);
 483 
 484   // Biased locking
 485   // See whether the lock is currently biased toward our thread and
 486   // whether the epoch is still valid
 487   // Note that the runtime guarantees sufficient alignment of JavaThread
 488   // pointers to allow age to be placed into low bits
 489   // First check to see whether biasing is even enabled for this object
 490   Label cas_label;
 491   int null_check_offset = -1;
 492   if (!swap_reg_contains_mark) {
 493     null_check_offset = offset();
 494     ldr(swap_reg, mark_addr);
 495   }
 496   andr(tmp_reg, swap_reg, markOopDesc::biased_lock_mask_in_place);
 497   cmp(tmp_reg, markOopDesc::biased_lock_pattern);
 498   br(Assembler::NE, cas_label);
 499   // The bias pattern is present in the object's header. Need to check
 500   // whether the bias owner and the epoch are both still current.
 501   load_prototype_header(tmp_reg, obj_reg);
 502   orr(tmp_reg, tmp_reg, rthread);
 503   eor(tmp_reg, swap_reg, tmp_reg);
 504   andr(tmp_reg, tmp_reg, ~((int) markOopDesc::age_mask_in_place));
 505   if (counters != NULL) {
 506     Label around;
 507     cbnz(tmp_reg, around);
 508     atomic_incw(Address((address)counters->biased_lock_entry_count_addr()), tmp_reg, rscratch1, rscratch2);
 509     b(done);
 510     bind(around);
 511   } else {
 512     cbz(tmp_reg, done);
 513   }
 514 
 515   Label try_revoke_bias;
 516   Label try_rebias;
 517 
 518   // At this point we know that the header has the bias pattern and
 519   // that we are not the bias owner in the current epoch. We need to
 520   // figure out more details about the state of the header in order to
 521   // know what operations can be legally performed on the object's
 522   // header.
 523 
 524   // If the low three bits in the xor result aren't clear, that means
 525   // the prototype header is no longer biased and we have to revoke
 526   // the bias on this object.
 527   andr(rscratch1, tmp_reg, markOopDesc::biased_lock_mask_in_place);
 528   cbnz(rscratch1, try_revoke_bias);
 529 
 530   // Biasing is still enabled for this data type. See whether the
 531   // epoch of the current bias is still valid, meaning that the epoch
 532   // bits of the mark word are equal to the epoch bits of the
 533   // prototype header. (Note that the prototype header's epoch bits
 534   // only change at a safepoint.) If not, attempt to rebias the object
 535   // toward the current thread. Note that we must be absolutely sure
 536   // that the current epoch is invalid in order to do this because
 537   // otherwise the manipulations it performs on the mark word are
 538   // illegal.
 539   andr(rscratch1, tmp_reg, markOopDesc::epoch_mask_in_place);
 540   cbnz(rscratch1, try_rebias);
 541 
 542   // The epoch of the current bias is still valid but we know nothing
 543   // about the owner; it might be set or it might be clear. Try to
 544   // acquire the bias of the object using an atomic operation. If this
 545   // fails we will go in to the runtime to revoke the object's bias.
 546   // Note that we first construct the presumed unbiased header so we
 547   // don't accidentally blow away another thread's valid bias.
 548   {
 549     Label here;
 550     mov(rscratch1, markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
 551     andr(swap_reg, swap_reg, rscratch1);
 552     orr(tmp_reg, swap_reg, rthread);
 553     cmpxchg_obj_header(swap_reg, tmp_reg, obj_reg, rscratch1, here, slow_case);
 554     // If the biasing toward our thread failed, this means that
 555     // another thread succeeded in biasing it toward itself and we
 556     // need to revoke that bias. The revocation will occur in the
 557     // interpreter runtime in the slow case.
 558     bind(here);
 559     if (counters != NULL) {
 560       atomic_incw(Address((address)counters->anonymously_biased_lock_entry_count_addr()),
 561                   tmp_reg, rscratch1, rscratch2);
 562     }
 563   }
 564   b(done);
 565 
 566   bind(try_rebias);
 567   // At this point we know the epoch has expired, meaning that the
 568   // current "bias owner", if any, is actually invalid. Under these
 569   // circumstances _only_, we are allowed to use the current header's
 570   // value as the comparison value when doing the cas to acquire the
 571   // bias in the current epoch. In other words, we allow transfer of
 572   // the bias from one thread to another directly in this situation.
 573   //
 574   // FIXME: due to a lack of registers we currently blow away the age
 575   // bits in this situation. Should attempt to preserve them.
 576   {
 577     Label here;
 578     load_prototype_header(tmp_reg, obj_reg);
 579     orr(tmp_reg, rthread, tmp_reg);
 580     cmpxchg_obj_header(swap_reg, tmp_reg, obj_reg, rscratch1, here, slow_case);
 581     // If the biasing toward our thread failed, then another thread
 582     // succeeded in biasing it toward itself and we need to revoke that
 583     // bias. The revocation will occur in the runtime in the slow case.
 584     bind(here);
 585     if (counters != NULL) {
 586       atomic_incw(Address((address)counters->rebiased_lock_entry_count_addr()),
 587                   tmp_reg, rscratch1, rscratch2);
 588     }
 589   }
 590   b(done);
 591 
 592   bind(try_revoke_bias);
 593   // The prototype mark in the klass doesn't have the bias bit set any
 594   // more, indicating that objects of this data type are not supposed
 595   // to be biased any more. We are going to try to reset the mark of
 596   // this object to the prototype value and fall through to the
 597   // CAS-based locking scheme. Note that if our CAS fails, it means
 598   // that another thread raced us for the privilege of revoking the
 599   // bias of this particular object, so it's okay to continue in the
 600   // normal locking code.
 601   //
 602   // FIXME: due to a lack of registers we currently blow away the age
 603   // bits in this situation. Should attempt to preserve them.
 604   {
 605     Label here, nope;
 606     load_prototype_header(tmp_reg, obj_reg);
 607     cmpxchg_obj_header(swap_reg, tmp_reg, obj_reg, rscratch1, here, &nope);
 608     bind(here);
 609 
 610     // Fall through to the normal CAS-based lock, because no matter what
 611     // the result of the above CAS, some thread must have succeeded in
 612     // removing the bias bit from the object's header.
 613     if (counters != NULL) {
 614       atomic_incw(Address((address)counters->revoked_lock_entry_count_addr()), tmp_reg,
 615                   rscratch1, rscratch2);
 616     }
 617     bind(nope);
 618   }
 619 
 620   bind(cas_label);
 621 
 622   return null_check_offset;
 623 }
 624 
 625 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
 626   assert(UseBiasedLocking, "why call this otherwise?");
 627 
 628   // Check for biased locking unlock case, which is a no-op
 629   // Note: we do not have to check the thread ID for two reasons.
 630   // First, the interpreter checks for IllegalMonitorStateException at
 631   // a higher level. Second, if the bias was revoked while we held the
 632   // lock, the object could not be rebiased toward another thread, so
 633   // the bias bit would be clear.
 634   ldr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
 635   andr(temp_reg, temp_reg, markOopDesc::biased_lock_mask_in_place);
 636   cmp(temp_reg, markOopDesc::biased_lock_pattern);
 637   br(Assembler::EQ, done);
 638 }
 639 
 640 static void pass_arg0(MacroAssembler* masm, Register arg) {
 641   if (c_rarg0 != arg ) {
 642     masm->mov(c_rarg0, arg);
 643   }
 644 }
 645 
 646 static void pass_arg1(MacroAssembler* masm, Register arg) {
 647   if (c_rarg1 != arg ) {
 648     masm->mov(c_rarg1, arg);
 649   }
 650 }
 651 
 652 static void pass_arg2(MacroAssembler* masm, Register arg) {
 653   if (c_rarg2 != arg ) {
 654     masm->mov(c_rarg2, arg);
 655   }
 656 }
 657 
 658 static void pass_arg3(MacroAssembler* masm, Register arg) {
 659   if (c_rarg3 != arg ) {
 660     masm->mov(c_rarg3, arg);
 661   }
 662 }
 663 
 664 void MacroAssembler::call_VM_base(Register oop_result,
 665                                   Register java_thread,
 666                                   Register last_java_sp,
 667                                   address  entry_point,
 668                                   int      number_of_arguments,
 669                                   bool     check_exceptions) {
 670    // determine java_thread register
 671   if (!java_thread->is_valid()) {
 672     java_thread = rthread;
 673   }
 674 
 675   // determine last_java_sp register
 676   if (!last_java_sp->is_valid()) {
 677     last_java_sp = esp;
 678   }
 679 
 680   // debugging support
 681   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
 682   assert(java_thread == rthread, "unexpected register");
 683 #ifdef ASSERT
 684   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
 685   // if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");
 686 #endif // ASSERT
 687 
 688   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
 689   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
 690 
 691   // push java thread (becomes first argument of C function)
 692 
 693   mov(c_rarg0, java_thread);
 694 
 695   // set last Java frame before call
 696   assert(last_java_sp != rfp, "can't use rfp");
 697 
 698   Label l;
 699   set_last_Java_frame(last_java_sp, rfp, l, rscratch1);
 700 
 701   // do the call, remove parameters
 702   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments, &l);
 703 
 704   // reset last Java frame
 705   // Only interpreter should have to clear fp
 706   reset_last_Java_frame(true);
 707 
 708    // C++ interp handles this in the interpreter
 709   check_and_handle_popframe(java_thread);
 710   check_and_handle_earlyret(java_thread);
 711 
 712   if (check_exceptions) {
 713     // check for pending exceptions (java_thread is set upon return)
 714     ldr(rscratch1, Address(java_thread, in_bytes(Thread::pending_exception_offset())));
 715     Label ok;
 716     cbz(rscratch1, ok);
 717     lea(rscratch1, RuntimeAddress(StubRoutines::forward_exception_entry()));
 718     br(rscratch1);
 719     bind(ok);
 720   }
 721 
 722   // get oop result if there is one and reset the value in the thread
 723   if (oop_result->is_valid()) {
 724     get_vm_result(oop_result, java_thread);
 725   }
 726 }
 727 
 728 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
 729   call_VM_base(oop_result, noreg, noreg, entry_point, number_of_arguments, check_exceptions);
 730 }
 731 
 732 // Maybe emit a call via a trampoline.  If the code cache is small
 733 // trampolines won't be emitted.
 734 
 735 address MacroAssembler::trampoline_call(Address entry, CodeBuffer *cbuf) {
 736   assert(JavaThread::current()->is_Compiler_thread(), "just checking");
 737   assert(entry.rspec().type() == relocInfo::runtime_call_type
 738          || entry.rspec().type() == relocInfo::opt_virtual_call_type
 739          || entry.rspec().type() == relocInfo::static_call_type
 740          || entry.rspec().type() == relocInfo::virtual_call_type, "wrong reloc type");
 741 
 742   unsigned int start_offset = offset();
 743   if (far_branches() && !Compile::current()->in_scratch_emit_size()) {
 744     address stub = emit_trampoline_stub(start_offset, entry.target());
 745     if (stub == NULL) {
 746       return NULL; // CodeCache is full
 747     }
 748   }
 749 
 750   if (cbuf) cbuf->set_insts_mark();
 751   relocate(entry.rspec());
 752   if (!far_branches()) {
 753     bl(entry.target());
 754   } else {
 755     bl(pc());
 756   }
 757   // just need to return a non-null address
 758   return pc();
 759 }
 760 
 761 
 762 // Emit a trampoline stub for a call to a target which is too far away.
 763 //
 764 // code sequences:
 765 //
 766 // call-site:
 767 //   branch-and-link to <destination> or <trampoline stub>
 768 //
 769 // Related trampoline stub for this call site in the stub section:
 770 //   load the call target from the constant pool
 771 //   branch (LR still points to the call site above)
 772 
 773 address MacroAssembler::emit_trampoline_stub(int insts_call_instruction_offset,
 774                                              address dest) {
 775   address stub = start_a_stub(Compile::MAX_stubs_size/2);
 776   if (stub == NULL) {
 777     return NULL;  // CodeBuffer::expand failed
 778   }
 779 
 780   // Create a trampoline stub relocation which relates this trampoline stub
 781   // with the call instruction at insts_call_instruction_offset in the
 782   // instructions code-section.
 783   align(wordSize);
 784   relocate(trampoline_stub_Relocation::spec(code()->insts()->start()
 785                                             + insts_call_instruction_offset));
 786   const int stub_start_offset = offset();
 787 
 788   // Now, create the trampoline stub's code:
 789   // - load the call
 790   // - call
 791   Label target;
 792   ldr(rscratch1, target);
 793   br(rscratch1);
 794   bind(target);
 795   assert(offset() - stub_start_offset == NativeCallTrampolineStub::data_offset,
 796          "should be");
 797   emit_int64((int64_t)dest);
 798 
 799   const address stub_start_addr = addr_at(stub_start_offset);
 800 
 801   assert(is_NativeCallTrampolineStub_at(stub_start_addr), "doesn't look like a trampoline");
 802 
 803   end_a_stub();
 804   return stub;
 805 }
 806 
 807 address MacroAssembler::ic_call(address entry, jint method_index) {
 808   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
 809   // address const_ptr = long_constant((jlong)Universe::non_oop_word());
 810   // unsigned long offset;
 811   // ldr_constant(rscratch2, const_ptr);
 812   movptr(rscratch2, (uintptr_t)Universe::non_oop_word());
 813   return trampoline_call(Address(entry, rh));
 814 }
 815 
 816 // Implementation of call_VM versions
 817 
 818 void MacroAssembler::call_VM(Register oop_result,
 819                              address entry_point,
 820                              bool check_exceptions) {
 821   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
 822 }
 823 
 824 void MacroAssembler::call_VM(Register oop_result,
 825                              address entry_point,
 826                              Register arg_1,
 827                              bool check_exceptions) {
 828   pass_arg1(this, arg_1);
 829   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
 830 }
 831 
 832 void MacroAssembler::call_VM(Register oop_result,
 833                              address entry_point,
 834                              Register arg_1,
 835                              Register arg_2,
 836                              bool check_exceptions) {
 837   assert(arg_1 != c_rarg2, "smashed arg");
 838   pass_arg2(this, arg_2);
 839   pass_arg1(this, arg_1);
 840   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
 841 }
 842 
 843 void MacroAssembler::call_VM(Register oop_result,
 844                              address entry_point,
 845                              Register arg_1,
 846                              Register arg_2,
 847                              Register arg_3,
 848                              bool check_exceptions) {
 849   assert(arg_1 != c_rarg3, "smashed arg");
 850   assert(arg_2 != c_rarg3, "smashed arg");
 851   pass_arg3(this, arg_3);
 852 
 853   assert(arg_1 != c_rarg2, "smashed arg");
 854   pass_arg2(this, arg_2);
 855 
 856   pass_arg1(this, arg_1);
 857   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
 858 }
 859 
 860 void MacroAssembler::call_VM(Register oop_result,
 861                              Register last_java_sp,
 862                              address entry_point,
 863                              int number_of_arguments,
 864                              bool check_exceptions) {
 865   call_VM_base(oop_result, rthread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
 866 }
 867 
 868 void MacroAssembler::call_VM(Register oop_result,
 869                              Register last_java_sp,
 870                              address entry_point,
 871                              Register arg_1,
 872                              bool check_exceptions) {
 873   pass_arg1(this, arg_1);
 874   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
 875 }
 876 
 877 void MacroAssembler::call_VM(Register oop_result,
 878                              Register last_java_sp,
 879                              address entry_point,
 880                              Register arg_1,
 881                              Register arg_2,
 882                              bool check_exceptions) {
 883 
 884   assert(arg_1 != c_rarg2, "smashed arg");
 885   pass_arg2(this, arg_2);
 886   pass_arg1(this, arg_1);
 887   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
 888 }
 889 
 890 void MacroAssembler::call_VM(Register oop_result,
 891                              Register last_java_sp,
 892                              address entry_point,
 893                              Register arg_1,
 894                              Register arg_2,
 895                              Register arg_3,
 896                              bool check_exceptions) {
 897   assert(arg_1 != c_rarg3, "smashed arg");
 898   assert(arg_2 != c_rarg3, "smashed arg");
 899   pass_arg3(this, arg_3);
 900   assert(arg_1 != c_rarg2, "smashed arg");
 901   pass_arg2(this, arg_2);
 902   pass_arg1(this, arg_1);
 903   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
 904 }
 905 
 906 
 907 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
 908   ldr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
 909   str(zr, Address(java_thread, JavaThread::vm_result_offset()));
 910   verify_oop(oop_result, "broken oop in call_VM_base");
 911 }
 912 
 913 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
 914   ldr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
 915   str(zr, Address(java_thread, JavaThread::vm_result_2_offset()));
 916 }
 917 
 918 void MacroAssembler::align(int modulus) {
 919   while (offset() % modulus != 0) nop();
 920 }
 921 
 922 // these are no-ops overridden by InterpreterMacroAssembler
 923 
 924 void MacroAssembler::check_and_handle_earlyret(Register java_thread) { }
 925 
 926 void MacroAssembler::check_and_handle_popframe(Register java_thread) { }
 927 
 928 
 929 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
 930                                                       Register tmp,
 931                                                       int offset) {
 932   intptr_t value = *delayed_value_addr;
 933   if (value != 0)
 934     return RegisterOrConstant(value + offset);
 935 
 936   // load indirectly to solve generation ordering problem
 937   ldr(tmp, ExternalAddress((address) delayed_value_addr));
 938 
 939   if (offset != 0)
 940     add(tmp, tmp, offset);
 941 
 942   return RegisterOrConstant(tmp);
 943 }
 944 
 945 
 946 void MacroAssembler:: notify(int type) {
 947   if (type == bytecode_start) {
 948     // set_last_Java_frame(esp, rfp, (address)NULL);
 949     Assembler:: notify(type);
 950     // reset_last_Java_frame(true);
 951   }
 952   else
 953     Assembler:: notify(type);
 954 }
 955 
 956 // Look up the method for a megamorphic invokeinterface call.
 957 // The target method is determined by <intf_klass, itable_index>.
 958 // The receiver klass is in recv_klass.
 959 // On success, the result will be in method_result, and execution falls through.
 960 // On failure, execution transfers to the given label.
 961 void MacroAssembler::lookup_interface_method(Register recv_klass,
 962                                              Register intf_klass,
 963                                              RegisterOrConstant itable_index,
 964                                              Register method_result,
 965                                              Register scan_temp,
 966                                              Label& L_no_such_interface) {
 967   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
 968   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
 969          "caller must use same register for non-constant itable index as for method");
 970 
 971   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
 972   int vtable_base = in_bytes(Klass::vtable_start_offset());
 973   int itentry_off = itableMethodEntry::method_offset_in_bytes();
 974   int scan_step   = itableOffsetEntry::size() * wordSize;
 975   int vte_size    = vtableEntry::size_in_bytes();
 976   assert(vte_size == wordSize, "else adjust times_vte_scale");
 977 
 978   ldrw(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
 979 
 980   // %%% Could store the aligned, prescaled offset in the klassoop.
 981   // lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
 982   lea(scan_temp, Address(recv_klass, scan_temp, Address::lsl(3)));
 983   add(scan_temp, scan_temp, vtable_base);
 984 
 985   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
 986   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
 987   // lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
 988   lea(recv_klass, Address(recv_klass, itable_index, Address::lsl(3)));
 989   if (itentry_off)
 990     add(recv_klass, recv_klass, itentry_off);
 991 
 992   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
 993   //   if (scan->interface() == intf) {
 994   //     result = (klass + scan->offset() + itable_index);
 995   //   }
 996   // }
 997   Label search, found_method;
 998 
 999   for (int peel = 1; peel >= 0; peel--) {
1000     ldr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
1001     cmp(intf_klass, method_result);
1002 
1003     if (peel) {
1004       br(Assembler::EQ, found_method);
1005     } else {
1006       br(Assembler::NE, search);
1007       // (invert the test to fall through to found_method...)
1008     }
1009 
1010     if (!peel)  break;
1011 
1012     bind(search);
1013 
1014     // Check that the previous entry is non-null.  A null entry means that
1015     // the receiver class doesn't implement the interface, and wasn't the
1016     // same as when the caller was compiled.
1017     cbz(method_result, L_no_such_interface);
1018     add(scan_temp, scan_temp, scan_step);
1019   }
1020 
1021   bind(found_method);
1022 
1023   // Got a hit.
1024   ldr(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
1025   ldr(method_result, Address(recv_klass, scan_temp));
1026 }
1027 
1028 // virtual method calling
1029 void MacroAssembler::lookup_virtual_method(Register recv_klass,
1030                                            RegisterOrConstant vtable_index,
1031                                            Register method_result) {
1032   const int base = in_bytes(Klass::vtable_start_offset());
1033   assert(vtableEntry::size() * wordSize == 8,
1034          "adjust the scaling in the code below");
1035   int vtable_offset_in_bytes = base + vtableEntry::method_offset_in_bytes();
1036 
1037   if (vtable_index.is_register()) {
1038     lea(method_result, Address(recv_klass,
1039                                vtable_index.as_register(),
1040                                Address::lsl(LogBytesPerWord)));
1041     ldr(method_result, Address(method_result, vtable_offset_in_bytes));
1042   } else {
1043     vtable_offset_in_bytes += vtable_index.as_constant() * wordSize;
1044     ldr(method_result, Address(recv_klass, vtable_offset_in_bytes));
1045   }
1046 }
1047 
1048 void MacroAssembler::check_klass_subtype(Register sub_klass,
1049                            Register super_klass,
1050                            Register temp_reg,
1051                            Label& L_success) {
1052   Label L_failure;
1053   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
1054   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
1055   bind(L_failure);
1056 }
1057 
1058 
1059 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
1060                                                    Register super_klass,
1061                                                    Register temp_reg,
1062                                                    Label* L_success,
1063                                                    Label* L_failure,
1064                                                    Label* L_slow_path,
1065                                         RegisterOrConstant super_check_offset) {
1066   assert_different_registers(sub_klass, super_klass, temp_reg);
1067   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
1068   if (super_check_offset.is_register()) {
1069     assert_different_registers(sub_klass, super_klass,
1070                                super_check_offset.as_register());
1071   } else if (must_load_sco) {
1072     assert(temp_reg != noreg, "supply either a temp or a register offset");
1073   }
1074 
1075   Label L_fallthrough;
1076   int label_nulls = 0;
1077   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
1078   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
1079   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
1080   assert(label_nulls <= 1, "at most one NULL in the batch");
1081 
1082   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
1083   int sco_offset = in_bytes(Klass::super_check_offset_offset());
1084   Address super_check_offset_addr(super_klass, sco_offset);
1085 
1086   // Hacked jmp, which may only be used just before L_fallthrough.
1087 #define final_jmp(label)                                                \
1088   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
1089   else                            b(label)                /*omit semi*/
1090 
1091   // If the pointers are equal, we are done (e.g., String[] elements).
1092   // This self-check enables sharing of secondary supertype arrays among
1093   // non-primary types such as array-of-interface.  Otherwise, each such
1094   // type would need its own customized SSA.
1095   // We move this check to the front of the fast path because many
1096   // type checks are in fact trivially successful in this manner,
1097   // so we get a nicely predicted branch right at the start of the check.
1098   cmp(sub_klass, super_klass);
1099   br(Assembler::EQ, *L_success);
1100 
1101   // Check the supertype display:
1102   if (must_load_sco) {
1103     ldrw(temp_reg, super_check_offset_addr);
1104     super_check_offset = RegisterOrConstant(temp_reg);
1105   }
1106   Address super_check_addr(sub_klass, super_check_offset);
1107   ldr(rscratch1, super_check_addr);
1108   cmp(super_klass, rscratch1); // load displayed supertype
1109 
1110   // This check has worked decisively for primary supers.
1111   // Secondary supers are sought in the super_cache ('super_cache_addr').
1112   // (Secondary supers are interfaces and very deeply nested subtypes.)
1113   // This works in the same check above because of a tricky aliasing
1114   // between the super_cache and the primary super display elements.
1115   // (The 'super_check_addr' can address either, as the case requires.)
1116   // Note that the cache is updated below if it does not help us find
1117   // what we need immediately.
1118   // So if it was a primary super, we can just fail immediately.
1119   // Otherwise, it's the slow path for us (no success at this point).
1120 
1121   if (super_check_offset.is_register()) {
1122     br(Assembler::EQ, *L_success);
1123     cmp(super_check_offset.as_register(), sc_offset);
1124     if (L_failure == &L_fallthrough) {
1125       br(Assembler::EQ, *L_slow_path);
1126     } else {
1127       br(Assembler::NE, *L_failure);
1128       final_jmp(*L_slow_path);
1129     }
1130   } else if (super_check_offset.as_constant() == sc_offset) {
1131     // Need a slow path; fast failure is impossible.
1132     if (L_slow_path == &L_fallthrough) {
1133       br(Assembler::EQ, *L_success);
1134     } else {
1135       br(Assembler::NE, *L_slow_path);
1136       final_jmp(*L_success);
1137     }
1138   } else {
1139     // No slow path; it's a fast decision.
1140     if (L_failure == &L_fallthrough) {
1141       br(Assembler::EQ, *L_success);
1142     } else {
1143       br(Assembler::NE, *L_failure);
1144       final_jmp(*L_success);
1145     }
1146   }
1147 
1148   bind(L_fallthrough);
1149 
1150 #undef final_jmp
1151 }
1152 
1153 // These two are taken from x86, but they look generally useful
1154 
1155 // scans count pointer sized words at [addr] for occurence of value,
1156 // generic
1157 void MacroAssembler::repne_scan(Register addr, Register value, Register count,
1158                                 Register scratch) {
1159   Label Lloop, Lexit;
1160   cbz(count, Lexit);
1161   bind(Lloop);
1162   ldr(scratch, post(addr, wordSize));
1163   cmp(value, scratch);
1164   br(EQ, Lexit);
1165   sub(count, count, 1);
1166   cbnz(count, Lloop);
1167   bind(Lexit);
1168 }
1169 
1170 // scans count 4 byte words at [addr] for occurence of value,
1171 // generic
1172 void MacroAssembler::repne_scanw(Register addr, Register value, Register count,
1173                                 Register scratch) {
1174   Label Lloop, Lexit;
1175   cbz(count, Lexit);
1176   bind(Lloop);
1177   ldrw(scratch, post(addr, wordSize));
1178   cmpw(value, scratch);
1179   br(EQ, Lexit);
1180   sub(count, count, 1);
1181   cbnz(count, Lloop);
1182   bind(Lexit);
1183 }
1184 
1185 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
1186                                                    Register super_klass,
1187                                                    Register temp_reg,
1188                                                    Register temp2_reg,
1189                                                    Label* L_success,
1190                                                    Label* L_failure,
1191                                                    bool set_cond_codes) {
1192   assert_different_registers(sub_klass, super_klass, temp_reg);
1193   if (temp2_reg != noreg)
1194     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg, rscratch1);
1195 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
1196 
1197   Label L_fallthrough;
1198   int label_nulls = 0;
1199   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
1200   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
1201   assert(label_nulls <= 1, "at most one NULL in the batch");
1202 
1203   // a couple of useful fields in sub_klass:
1204   int ss_offset = in_bytes(Klass::secondary_supers_offset());
1205   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
1206   Address secondary_supers_addr(sub_klass, ss_offset);
1207   Address super_cache_addr(     sub_klass, sc_offset);
1208 
1209   BLOCK_COMMENT("check_klass_subtype_slow_path");
1210 
1211   // Do a linear scan of the secondary super-klass chain.
1212   // This code is rarely used, so simplicity is a virtue here.
1213   // The repne_scan instruction uses fixed registers, which we must spill.
1214   // Don't worry too much about pre-existing connections with the input regs.
1215 
1216   assert(sub_klass != r0, "killed reg"); // killed by mov(r0, super)
1217   assert(sub_klass != r2, "killed reg"); // killed by lea(r2, &pst_counter)
1218 
1219   // Get super_klass value into r0 (even if it was in r5 or r2).
1220   RegSet pushed_registers;
1221   if (!IS_A_TEMP(r2))    pushed_registers += r2;
1222   if (!IS_A_TEMP(r5))    pushed_registers += r5;
1223 
1224   if (super_klass != r0 || UseCompressedOops) {
1225     if (!IS_A_TEMP(r0))   pushed_registers += r0;
1226   }
1227 
1228   push(pushed_registers, sp);
1229 
1230 #ifndef PRODUCT
1231   mov(rscratch2, (address)&SharedRuntime::_partial_subtype_ctr);
1232   Address pst_counter_addr(rscratch2);
1233   ldr(rscratch1, pst_counter_addr);
1234   add(rscratch1, rscratch1, 1);
1235   str(rscratch1, pst_counter_addr);
1236 #endif //PRODUCT
1237 
1238   // We will consult the secondary-super array.
1239   ldr(r5, secondary_supers_addr);
1240   // Load the array length.
1241   ldrw(r2, Address(r5, Array<Klass*>::length_offset_in_bytes()));
1242   // Skip to start of data.
1243   add(r5, r5, Array<Klass*>::base_offset_in_bytes());
1244 
1245   cmp(sp, zr); // Clear Z flag; SP is never zero
1246   // Scan R2 words at [R5] for an occurrence of R0.
1247   // Set NZ/Z based on last compare.
1248   repne_scan(r5, r0, r2, rscratch1);
1249 
1250   // Unspill the temp. registers:
1251   pop(pushed_registers, sp);
1252 
1253   br(Assembler::NE, *L_failure);
1254 
1255   // Success.  Cache the super we found and proceed in triumph.
1256   str(super_klass, super_cache_addr);
1257 
1258   if (L_success != &L_fallthrough) {
1259     b(*L_success);
1260   }
1261 
1262 #undef IS_A_TEMP
1263 
1264   bind(L_fallthrough);
1265 }
1266 
1267 
1268 void MacroAssembler::verify_oop(Register reg, const char* s) {
1269   if (!VerifyOops) return;
1270 
1271   // Pass register number to verify_oop_subroutine
1272   const char* b = NULL;
1273   {
1274     ResourceMark rm;
1275     stringStream ss;
1276     ss.print("verify_oop: %s: %s", reg->name(), s);
1277     b = code_string(ss.as_string());
1278   }
1279   BLOCK_COMMENT("verify_oop {");
1280 
1281   stp(r0, rscratch1, Address(pre(sp, -2 * wordSize)));
1282   stp(rscratch2, lr, Address(pre(sp, -2 * wordSize)));
1283 
1284   mov(r0, reg);
1285   mov(rscratch1, (address)b);
1286 
1287   // call indirectly to solve generation ordering problem
1288   lea(rscratch2, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
1289   ldr(rscratch2, Address(rscratch2));
1290   blr(rscratch2);
1291 
1292   ldp(rscratch2, lr, Address(post(sp, 2 * wordSize)));
1293   ldp(r0, rscratch1, Address(post(sp, 2 * wordSize)));
1294 
1295   BLOCK_COMMENT("} verify_oop");
1296 }
1297 
1298 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
1299   if (!VerifyOops) return;
1300 
1301   const char* b = NULL;
1302   {
1303     ResourceMark rm;
1304     stringStream ss;
1305     ss.print("verify_oop_addr: %s", s);
1306     b = code_string(ss.as_string());
1307   }
1308   BLOCK_COMMENT("verify_oop_addr {");
1309 
1310   stp(r0, rscratch1, Address(pre(sp, -2 * wordSize)));
1311   stp(rscratch2, lr, Address(pre(sp, -2 * wordSize)));
1312 
1313   // addr may contain sp so we will have to adjust it based on the
1314   // pushes that we just did.
1315   if (addr.uses(sp)) {
1316     lea(r0, addr);
1317     ldr(r0, Address(r0, 4 * wordSize));
1318   } else {
1319     ldr(r0, addr);
1320   }
1321   mov(rscratch1, (address)b);
1322 
1323   // call indirectly to solve generation ordering problem
1324   lea(rscratch2, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
1325   ldr(rscratch2, Address(rscratch2));
1326   blr(rscratch2);
1327 
1328   ldp(rscratch2, lr, Address(post(sp, 2 * wordSize)));
1329   ldp(r0, rscratch1, Address(post(sp, 2 * wordSize)));
1330 
1331   BLOCK_COMMENT("} verify_oop_addr");
1332 }
1333 
1334 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
1335                                          int extra_slot_offset) {
1336   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
1337   int stackElementSize = Interpreter::stackElementSize;
1338   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
1339 #ifdef ASSERT
1340   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
1341   assert(offset1 - offset == stackElementSize, "correct arithmetic");
1342 #endif
1343   if (arg_slot.is_constant()) {
1344     return Address(esp, arg_slot.as_constant() * stackElementSize
1345                    + offset);
1346   } else {
1347     add(rscratch1, esp, arg_slot.as_register(),
1348         ext::uxtx, exact_log2(stackElementSize));
1349     return Address(rscratch1, offset);
1350   }
1351 }
1352 
1353 void MacroAssembler::call_VM_leaf_base(address entry_point,
1354                                        int number_of_arguments,
1355                                        Label *retaddr) {
1356   call_VM_leaf_base1(entry_point, number_of_arguments, 0, ret_type_integral, retaddr);
1357 }
1358 
1359 void MacroAssembler::call_VM_leaf_base1(address entry_point,
1360                                         int number_of_gp_arguments,
1361                                         int number_of_fp_arguments,
1362                                         ret_type type,
1363                                         Label *retaddr) {
1364   Label E, L;
1365 
1366   stp(rscratch1, rmethod, Address(pre(sp, -2 * wordSize)));
1367 
1368   // We add 1 to number_of_arguments because the thread in arg0 is
1369   // not counted
1370   mov(rscratch1, entry_point);
1371   blrt(rscratch1, number_of_gp_arguments + 1, number_of_fp_arguments, type);
1372   if (retaddr)
1373     bind(*retaddr);
1374 
1375   ldp(rscratch1, rmethod, Address(post(sp, 2 * wordSize)));
1376   maybe_isb();
1377 }
1378 
1379 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
1380   call_VM_leaf_base(entry_point, number_of_arguments);
1381 }
1382 
1383 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
1384   pass_arg0(this, arg_0);
1385   call_VM_leaf_base(entry_point, 1);
1386 }
1387 
1388 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
1389   pass_arg0(this, arg_0);
1390   pass_arg1(this, arg_1);
1391   call_VM_leaf_base(entry_point, 2);
1392 }
1393 
1394 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0,
1395                                   Register arg_1, Register arg_2) {
1396   pass_arg0(this, arg_0);
1397   pass_arg1(this, arg_1);
1398   pass_arg2(this, arg_2);
1399   call_VM_leaf_base(entry_point, 3);
1400 }
1401 
1402 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
1403   pass_arg0(this, arg_0);
1404   MacroAssembler::call_VM_leaf_base(entry_point, 1);
1405 }
1406 
1407 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
1408 
1409   assert(arg_0 != c_rarg1, "smashed arg");
1410   pass_arg1(this, arg_1);
1411   pass_arg0(this, arg_0);
1412   MacroAssembler::call_VM_leaf_base(entry_point, 2);
1413 }
1414 
1415 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
1416   assert(arg_0 != c_rarg2, "smashed arg");
1417   assert(arg_1 != c_rarg2, "smashed arg");
1418   pass_arg2(this, arg_2);
1419   assert(arg_0 != c_rarg1, "smashed arg");
1420   pass_arg1(this, arg_1);
1421   pass_arg0(this, arg_0);
1422   MacroAssembler::call_VM_leaf_base(entry_point, 3);
1423 }
1424 
1425 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
1426   assert(arg_0 != c_rarg3, "smashed arg");
1427   assert(arg_1 != c_rarg3, "smashed arg");
1428   assert(arg_2 != c_rarg3, "smashed arg");
1429   pass_arg3(this, arg_3);
1430   assert(arg_0 != c_rarg2, "smashed arg");
1431   assert(arg_1 != c_rarg2, "smashed arg");
1432   pass_arg2(this, arg_2);
1433   assert(arg_0 != c_rarg1, "smashed arg");
1434   pass_arg1(this, arg_1);
1435   pass_arg0(this, arg_0);
1436   MacroAssembler::call_VM_leaf_base(entry_point, 4);
1437 }
1438 
1439 void MacroAssembler::null_check(Register reg, int offset) {
1440   if (needs_explicit_null_check(offset)) {
1441     // provoke OS NULL exception if reg = NULL by
1442     // accessing M[reg] w/o changing any registers
1443     // NOTE: this is plenty to provoke a segv
1444     ldr(zr, Address(reg));
1445   } else {
1446     // nothing to do, (later) access of M[reg + offset]
1447     // will provoke OS NULL exception if reg = NULL
1448   }
1449 }
1450 
1451 // MacroAssembler protected routines needed to implement
1452 // public methods
1453 
1454 void MacroAssembler::mov(Register r, Address dest) {
1455   code_section()->relocate(pc(), dest.rspec());
1456   u_int64_t imm64 = (u_int64_t)dest.target();
1457   movptr(r, imm64);
1458 }
1459 
1460 // Move a constant pointer into r.  In AArch64 mode the virtual
1461 // address space is 48 bits in size, so we only need three
1462 // instructions to create a patchable instruction sequence that can
1463 // reach anywhere.
1464 void MacroAssembler::movptr(Register r, uintptr_t imm64) {
1465 #ifndef PRODUCT
1466   {
1467     char buffer[64];
1468     snprintf(buffer, sizeof(buffer), "0x%"PRIX64, imm64);
1469     block_comment(buffer);
1470   }
1471 #endif
1472   assert(imm64 < (1ul << 48), "48-bit overflow in address constant");
1473   movz(r, imm64 & 0xffff);
1474   imm64 >>= 16;
1475   movk(r, imm64 & 0xffff, 16);
1476   imm64 >>= 16;
1477   movk(r, imm64 & 0xffff, 32);
1478 }
1479 
1480 // Macro to mov replicated immediate to vector register.
1481 //  Vd will get the following values for different arrangements in T
1482 //   imm32 == hex 000000gh  T8B:  Vd = ghghghghghghghgh
1483 //   imm32 == hex 000000gh  T16B: Vd = ghghghghghghghghghghghghghghghgh
1484 //   imm32 == hex 0000efgh  T4H:  Vd = efghefghefghefgh
1485 //   imm32 == hex 0000efgh  T8H:  Vd = efghefghefghefghefghefghefghefgh
1486 //   imm32 == hex abcdefgh  T2S:  Vd = abcdefghabcdefgh
1487 //   imm32 == hex abcdefgh  T4S:  Vd = abcdefghabcdefghabcdefghabcdefgh
1488 //   T1D/T2D: invalid
1489 void MacroAssembler::mov(FloatRegister Vd, SIMD_Arrangement T, u_int32_t imm32) {
1490   assert(T != T1D && T != T2D, "invalid arrangement");
1491   if (T == T8B || T == T16B) {
1492     assert((imm32 & ~0xff) == 0, "extraneous bits in unsigned imm32 (T8B/T16B)");
1493     movi(Vd, T, imm32 & 0xff, 0);
1494     return;
1495   }
1496   u_int32_t nimm32 = ~imm32;
1497   if (T == T4H || T == T8H) {
1498     assert((imm32  & ~0xffff) == 0, "extraneous bits in unsigned imm32 (T4H/T8H)");
1499     imm32 &= 0xffff;
1500     nimm32 &= 0xffff;
1501   }
1502   u_int32_t x = imm32;
1503   int movi_cnt = 0;
1504   int movn_cnt = 0;
1505   while (x) { if (x & 0xff) movi_cnt++; x >>= 8; }
1506   x = nimm32;
1507   while (x) { if (x & 0xff) movn_cnt++; x >>= 8; }
1508   if (movn_cnt < movi_cnt) imm32 = nimm32;
1509   unsigned lsl = 0;
1510   while (imm32 && (imm32 & 0xff) == 0) { lsl += 8; imm32 >>= 8; }
1511   if (movn_cnt < movi_cnt)
1512     mvni(Vd, T, imm32 & 0xff, lsl);
1513   else
1514     movi(Vd, T, imm32 & 0xff, lsl);
1515   imm32 >>= 8; lsl += 8;
1516   while (imm32) {
1517     while ((imm32 & 0xff) == 0) { lsl += 8; imm32 >>= 8; }
1518     if (movn_cnt < movi_cnt)
1519       bici(Vd, T, imm32 & 0xff, lsl);
1520     else
1521       orri(Vd, T, imm32 & 0xff, lsl);
1522     lsl += 8; imm32 >>= 8;
1523   }
1524 }
1525 
1526 void MacroAssembler::mov_immediate64(Register dst, u_int64_t imm64)
1527 {
1528 #ifndef PRODUCT
1529   {
1530     char buffer[64];
1531     snprintf(buffer, sizeof(buffer), "0x%"PRIX64, imm64);
1532     block_comment(buffer);
1533   }
1534 #endif
1535   if (operand_valid_for_logical_immediate(false, imm64)) {
1536     orr(dst, zr, imm64);
1537   } else {
1538     // we can use a combination of MOVZ or MOVN with
1539     // MOVK to build up the constant
1540     u_int64_t imm_h[4];
1541     int zero_count = 0;
1542     int neg_count = 0;
1543     int i;
1544     for (i = 0; i < 4; i++) {
1545       imm_h[i] = ((imm64 >> (i * 16)) & 0xffffL);
1546       if (imm_h[i] == 0) {
1547         zero_count++;
1548       } else if (imm_h[i] == 0xffffL) {
1549         neg_count++;
1550       }
1551     }
1552     if (zero_count == 4) {
1553       // one MOVZ will do
1554       movz(dst, 0);
1555     } else if (neg_count == 4) {
1556       // one MOVN will do
1557       movn(dst, 0);
1558     } else if (zero_count == 3) {
1559       for (i = 0; i < 4; i++) {
1560         if (imm_h[i] != 0L) {
1561           movz(dst, (u_int32_t)imm_h[i], (i << 4));
1562           break;
1563         }
1564       }
1565     } else if (neg_count == 3) {
1566       // one MOVN will do
1567       for (int i = 0; i < 4; i++) {
1568         if (imm_h[i] != 0xffffL) {
1569           movn(dst, (u_int32_t)imm_h[i] ^ 0xffffL, (i << 4));
1570           break;
1571         }
1572       }
1573     } else if (zero_count == 2) {
1574       // one MOVZ and one MOVK will do
1575       for (i = 0; i < 3; i++) {
1576         if (imm_h[i] != 0L) {
1577           movz(dst, (u_int32_t)imm_h[i], (i << 4));
1578           i++;
1579           break;
1580         }
1581       }
1582       for (;i < 4; i++) {
1583         if (imm_h[i] != 0L) {
1584           movk(dst, (u_int32_t)imm_h[i], (i << 4));
1585         }
1586       }
1587     } else if (neg_count == 2) {
1588       // one MOVN and one MOVK will do
1589       for (i = 0; i < 4; i++) {
1590         if (imm_h[i] != 0xffffL) {
1591           movn(dst, (u_int32_t)imm_h[i] ^ 0xffffL, (i << 4));
1592           i++;
1593           break;
1594         }
1595       }
1596       for (;i < 4; i++) {
1597         if (imm_h[i] != 0xffffL) {
1598           movk(dst, (u_int32_t)imm_h[i], (i << 4));
1599         }
1600       }
1601     } else if (zero_count == 1) {
1602       // one MOVZ and two MOVKs will do
1603       for (i = 0; i < 4; i++) {
1604         if (imm_h[i] != 0L) {
1605           movz(dst, (u_int32_t)imm_h[i], (i << 4));
1606           i++;
1607           break;
1608         }
1609       }
1610       for (;i < 4; i++) {
1611         if (imm_h[i] != 0x0L) {
1612           movk(dst, (u_int32_t)imm_h[i], (i << 4));
1613         }
1614       }
1615     } else if (neg_count == 1) {
1616       // one MOVN and two MOVKs will do
1617       for (i = 0; i < 4; i++) {
1618         if (imm_h[i] != 0xffffL) {
1619           movn(dst, (u_int32_t)imm_h[i] ^ 0xffffL, (i << 4));
1620           i++;
1621           break;
1622         }
1623       }
1624       for (;i < 4; i++) {
1625         if (imm_h[i] != 0xffffL) {
1626           movk(dst, (u_int32_t)imm_h[i], (i << 4));
1627         }
1628       }
1629     } else {
1630       // use a MOVZ and 3 MOVKs (makes it easier to debug)
1631       movz(dst, (u_int32_t)imm_h[0], 0);
1632       for (i = 1; i < 4; i++) {
1633         movk(dst, (u_int32_t)imm_h[i], (i << 4));
1634       }
1635     }
1636   }
1637 }
1638 
1639 void MacroAssembler::mov_immediate32(Register dst, u_int32_t imm32)
1640 {
1641 #ifndef PRODUCT
1642     {
1643       char buffer[64];
1644       snprintf(buffer, sizeof(buffer), "0x%"PRIX32, imm32);
1645       block_comment(buffer);
1646     }
1647 #endif
1648   if (operand_valid_for_logical_immediate(true, imm32)) {
1649     orrw(dst, zr, imm32);
1650   } else {
1651     // we can use MOVZ, MOVN or two calls to MOVK to build up the
1652     // constant
1653     u_int32_t imm_h[2];
1654     imm_h[0] = imm32 & 0xffff;
1655     imm_h[1] = ((imm32 >> 16) & 0xffff);
1656     if (imm_h[0] == 0) {
1657       movzw(dst, imm_h[1], 16);
1658     } else if (imm_h[0] == 0xffff) {
1659       movnw(dst, imm_h[1] ^ 0xffff, 16);
1660     } else if (imm_h[1] == 0) {
1661       movzw(dst, imm_h[0], 0);
1662     } else if (imm_h[1] == 0xffff) {
1663       movnw(dst, imm_h[0] ^ 0xffff, 0);
1664     } else {
1665       // use a MOVZ and MOVK (makes it easier to debug)
1666       movzw(dst, imm_h[0], 0);
1667       movkw(dst, imm_h[1], 16);
1668     }
1669   }
1670 }
1671 
1672 // Form an address from base + offset in Rd.  Rd may or may
1673 // not actually be used: you must use the Address that is returned.
1674 // It is up to you to ensure that the shift provided matches the size
1675 // of your data.
1676 Address MacroAssembler::form_address(Register Rd, Register base, long byte_offset, int shift) {
1677   if (Address::offset_ok_for_immed(byte_offset, shift))
1678     // It fits; no need for any heroics
1679     return Address(base, byte_offset);
1680 
1681   // Don't do anything clever with negative or misaligned offsets
1682   unsigned mask = (1 << shift) - 1;
1683   if (byte_offset < 0 || byte_offset & mask) {
1684     mov(Rd, byte_offset);
1685     add(Rd, base, Rd);
1686     return Address(Rd);
1687   }
1688 
1689   // See if we can do this with two 12-bit offsets
1690   {
1691     unsigned long word_offset = byte_offset >> shift;
1692     unsigned long masked_offset = word_offset & 0xfff000;
1693     if (Address::offset_ok_for_immed(word_offset - masked_offset)
1694         && Assembler::operand_valid_for_add_sub_immediate(masked_offset << shift)) {
1695       add(Rd, base, masked_offset << shift);
1696       word_offset -= masked_offset;
1697       return Address(Rd, word_offset << shift);
1698     }
1699   }
1700 
1701   // Do it the hard way
1702   mov(Rd, byte_offset);
1703   add(Rd, base, Rd);
1704   return Address(Rd);
1705 }
1706 
1707 void MacroAssembler::atomic_incw(Register counter_addr, Register tmp, Register tmp2) {
1708   if (UseLSE) {
1709     mov(tmp, 1);
1710     ldadd(Assembler::word, tmp, zr, counter_addr);
1711     return;
1712   }
1713   Label retry_load;
1714   if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))
1715     prfm(Address(counter_addr), PSTL1STRM);
1716   bind(retry_load);
1717   // flush and load exclusive from the memory location
1718   ldxrw(tmp, counter_addr);
1719   addw(tmp, tmp, 1);
1720   // if we store+flush with no intervening write tmp wil be zero
1721   stxrw(tmp2, tmp, counter_addr);
1722   cbnzw(tmp2, retry_load);
1723 }
1724 
1725 
1726 int MacroAssembler::corrected_idivl(Register result, Register ra, Register rb,
1727                                     bool want_remainder, Register scratch)
1728 {
1729   // Full implementation of Java idiv and irem.  The function
1730   // returns the (pc) offset of the div instruction - may be needed
1731   // for implicit exceptions.
1732   //
1733   // constraint : ra/rb =/= scratch
1734   //         normal case
1735   //
1736   // input : ra: dividend
1737   //         rb: divisor
1738   //
1739   // result: either
1740   //         quotient  (= ra idiv rb)
1741   //         remainder (= ra irem rb)
1742 
1743   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
1744 
1745   int idivl_offset = offset();
1746   if (! want_remainder) {
1747     sdivw(result, ra, rb);
1748   } else {
1749     sdivw(scratch, ra, rb);
1750     Assembler::msubw(result, scratch, rb, ra);
1751   }
1752 
1753   return idivl_offset;
1754 }
1755 
1756 int MacroAssembler::corrected_idivq(Register result, Register ra, Register rb,
1757                                     bool want_remainder, Register scratch)
1758 {
1759   // Full implementation of Java ldiv and lrem.  The function
1760   // returns the (pc) offset of the div instruction - may be needed
1761   // for implicit exceptions.
1762   //
1763   // constraint : ra/rb =/= scratch
1764   //         normal case
1765   //
1766   // input : ra: dividend
1767   //         rb: divisor
1768   //
1769   // result: either
1770   //         quotient  (= ra idiv rb)
1771   //         remainder (= ra irem rb)
1772 
1773   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
1774 
1775   int idivq_offset = offset();
1776   if (! want_remainder) {
1777     sdiv(result, ra, rb);
1778   } else {
1779     sdiv(scratch, ra, rb);
1780     Assembler::msub(result, scratch, rb, ra);
1781   }
1782 
1783   return idivq_offset;
1784 }
1785 
1786 void MacroAssembler::membar(Membar_mask_bits order_constraint) {
1787   address prev = pc() - NativeMembar::instruction_size;
1788   if (prev == code()->last_membar()) {
1789     NativeMembar *bar = NativeMembar_at(prev);
1790     // We are merging two memory barrier instructions.  On AArch64 we
1791     // can do this simply by ORing them together.
1792     bar->set_kind(bar->get_kind() | order_constraint);
1793     BLOCK_COMMENT("merged membar");
1794   } else {
1795     code()->set_last_membar(pc());
1796     dmb(Assembler::barrier(order_constraint));
1797   }
1798 }
1799 
1800 // MacroAssembler routines found actually to be needed
1801 
1802 void MacroAssembler::push(Register src)
1803 {
1804   str(src, Address(pre(esp, -1 * wordSize)));
1805 }
1806 
1807 void MacroAssembler::pop(Register dst)
1808 {
1809   ldr(dst, Address(post(esp, 1 * wordSize)));
1810 }
1811 
1812 // Note: load_unsigned_short used to be called load_unsigned_word.
1813 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
1814   int off = offset();
1815   ldrh(dst, src);
1816   return off;
1817 }
1818 
1819 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
1820   int off = offset();
1821   ldrb(dst, src);
1822   return off;
1823 }
1824 
1825 int MacroAssembler::load_signed_short(Register dst, Address src) {
1826   int off = offset();
1827   ldrsh(dst, src);
1828   return off;
1829 }
1830 
1831 int MacroAssembler::load_signed_byte(Register dst, Address src) {
1832   int off = offset();
1833   ldrsb(dst, src);
1834   return off;
1835 }
1836 
1837 int MacroAssembler::load_signed_short32(Register dst, Address src) {
1838   int off = offset();
1839   ldrshw(dst, src);
1840   return off;
1841 }
1842 
1843 int MacroAssembler::load_signed_byte32(Register dst, Address src) {
1844   int off = offset();
1845   ldrsbw(dst, src);
1846   return off;
1847 }
1848 
1849 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
1850   switch (size_in_bytes) {
1851   case  8:  ldr(dst, src); break;
1852   case  4:  ldrw(dst, src); break;
1853   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
1854   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
1855   default:  ShouldNotReachHere();
1856   }
1857 }
1858 
1859 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
1860   switch (size_in_bytes) {
1861   case  8:  str(src, dst); break;
1862   case  4:  strw(src, dst); break;
1863   case  2:  strh(src, dst); break;
1864   case  1:  strb(src, dst); break;
1865   default:  ShouldNotReachHere();
1866   }
1867 }
1868 
1869 void MacroAssembler::decrementw(Register reg, int value)
1870 {
1871   if (value < 0)  { incrementw(reg, -value);      return; }
1872   if (value == 0) {                               return; }
1873   if (value < (1 << 12)) { subw(reg, reg, value); return; }
1874   /* else */ {
1875     guarantee(reg != rscratch2, "invalid dst for register decrement");
1876     movw(rscratch2, (unsigned)value);
1877     subw(reg, reg, rscratch2);
1878   }
1879 }
1880 
1881 void MacroAssembler::decrement(Register reg, int value)
1882 {
1883   if (value < 0)  { increment(reg, -value);      return; }
1884   if (value == 0) {                              return; }
1885   if (value < (1 << 12)) { sub(reg, reg, value); return; }
1886   /* else */ {
1887     assert(reg != rscratch2, "invalid dst for register decrement");
1888     mov(rscratch2, (unsigned long)value);
1889     sub(reg, reg, rscratch2);
1890   }
1891 }
1892 
1893 void MacroAssembler::decrementw(Address dst, int value)
1894 {
1895   assert(!dst.uses(rscratch1), "invalid dst for address decrement");
1896   ldrw(rscratch1, dst);
1897   decrementw(rscratch1, value);
1898   strw(rscratch1, dst);
1899 }
1900 
1901 void MacroAssembler::decrement(Address dst, int value)
1902 {
1903   assert(!dst.uses(rscratch1), "invalid address for decrement");
1904   ldr(rscratch1, dst);
1905   decrement(rscratch1, value);
1906   str(rscratch1, dst);
1907 }
1908 
1909 void MacroAssembler::incrementw(Register reg, int value)
1910 {
1911   if (value < 0)  { decrementw(reg, -value);      return; }
1912   if (value == 0) {                               return; }
1913   if (value < (1 << 12)) { addw(reg, reg, value); return; }
1914   /* else */ {
1915     assert(reg != rscratch2, "invalid dst for register increment");
1916     movw(rscratch2, (unsigned)value);
1917     addw(reg, reg, rscratch2);
1918   }
1919 }
1920 
1921 void MacroAssembler::increment(Register reg, int value)
1922 {
1923   if (value < 0)  { decrement(reg, -value);      return; }
1924   if (value == 0) {                              return; }
1925   if (value < (1 << 12)) { add(reg, reg, value); return; }
1926   /* else */ {
1927     assert(reg != rscratch2, "invalid dst for register increment");
1928     movw(rscratch2, (unsigned)value);
1929     add(reg, reg, rscratch2);
1930   }
1931 }
1932 
1933 void MacroAssembler::incrementw(Address dst, int value)
1934 {
1935   assert(!dst.uses(rscratch1), "invalid dst for address increment");
1936   ldrw(rscratch1, dst);
1937   incrementw(rscratch1, value);
1938   strw(rscratch1, dst);
1939 }
1940 
1941 void MacroAssembler::increment(Address dst, int value)
1942 {
1943   assert(!dst.uses(rscratch1), "invalid dst for address increment");
1944   ldr(rscratch1, dst);
1945   increment(rscratch1, value);
1946   str(rscratch1, dst);
1947 }
1948 
1949 
1950 void MacroAssembler::pusha() {
1951   push(0x7fffffff, sp);
1952 }
1953 
1954 void MacroAssembler::popa() {
1955   pop(0x7fffffff, sp);
1956 }
1957 
1958 // Push lots of registers in the bit set supplied.  Don't push sp.
1959 // Return the number of words pushed
1960 int MacroAssembler::push(unsigned int bitset, Register stack) {
1961   int words_pushed = 0;
1962 
1963   // Scan bitset to accumulate register pairs
1964   unsigned char regs[32];
1965   int count = 0;
1966   for (int reg = 0; reg <= 30; reg++) {
1967     if (1 & bitset)
1968       regs[count++] = reg;
1969     bitset >>= 1;
1970   }
1971   regs[count++] = zr->encoding_nocheck();
1972   count &= ~1;  // Only push an even nuber of regs
1973 
1974   if (count) {
1975     stp(as_Register(regs[0]), as_Register(regs[1]),
1976        Address(pre(stack, -count * wordSize)));
1977     words_pushed += 2;
1978   }
1979   for (int i = 2; i < count; i += 2) {
1980     stp(as_Register(regs[i]), as_Register(regs[i+1]),
1981        Address(stack, i * wordSize));
1982     words_pushed += 2;
1983   }
1984 
1985   assert(words_pushed == count, "oops, pushed != count");
1986 
1987   return count;
1988 }
1989 
1990 int MacroAssembler::pop(unsigned int bitset, Register stack) {
1991   int words_pushed = 0;
1992 
1993   // Scan bitset to accumulate register pairs
1994   unsigned char regs[32];
1995   int count = 0;
1996   for (int reg = 0; reg <= 30; reg++) {
1997     if (1 & bitset)
1998       regs[count++] = reg;
1999     bitset >>= 1;
2000   }
2001   regs[count++] = zr->encoding_nocheck();
2002   count &= ~1;
2003 
2004   for (int i = 2; i < count; i += 2) {
2005     ldp(as_Register(regs[i]), as_Register(regs[i+1]),
2006        Address(stack, i * wordSize));
2007     words_pushed += 2;
2008   }
2009   if (count) {
2010     ldp(as_Register(regs[0]), as_Register(regs[1]),
2011        Address(post(stack, count * wordSize)));
2012     words_pushed += 2;
2013   }
2014 
2015   assert(words_pushed == count, "oops, pushed != count");
2016 
2017   return count;
2018 }
2019 #ifdef ASSERT
2020 void MacroAssembler::verify_heapbase(const char* msg) {
2021 #if 0
2022   assert (UseCompressedOops || UseCompressedClassPointers, "should be compressed");
2023   assert (Universe::heap() != NULL, "java heap should be initialized");
2024   if (CheckCompressedOops) {
2025     Label ok;
2026     push(1 << rscratch1->encoding(), sp); // cmpptr trashes rscratch1
2027     cmpptr(rheapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
2028     br(Assembler::EQ, ok);
2029     stop(msg);
2030     bind(ok);
2031     pop(1 << rscratch1->encoding(), sp);
2032   }
2033 #endif
2034 }
2035 #endif
2036 
2037 void MacroAssembler::stop(const char* msg) {
2038   address ip = pc();
2039   pusha();
2040   mov(c_rarg0, (address)msg);
2041   mov(c_rarg1, (address)ip);
2042   mov(c_rarg2, sp);
2043   mov(c_rarg3, CAST_FROM_FN_PTR(address, MacroAssembler::debug64));
2044   // call(c_rarg3);
2045   blrt(c_rarg3, 3, 0, 1);
2046   hlt(0);
2047 }
2048 
2049 void MacroAssembler::unimplemented(const char* what) {
2050   char* b = new char[1024];
2051   jio_snprintf(b, 1024, "unimplemented: %s", what);
2052   stop(b);
2053 }
2054 
2055 // If a constant does not fit in an immediate field, generate some
2056 // number of MOV instructions and then perform the operation.
2057 void MacroAssembler::wrap_add_sub_imm_insn(Register Rd, Register Rn, unsigned imm,
2058                                            add_sub_imm_insn insn1,
2059                                            add_sub_reg_insn insn2) {
2060   assert(Rd != zr, "Rd = zr and not setting flags?");
2061   if (operand_valid_for_add_sub_immediate((int)imm)) {
2062     (this->*insn1)(Rd, Rn, imm);
2063   } else {
2064     if (uabs(imm) < (1 << 24)) {
2065        (this->*insn1)(Rd, Rn, imm & -(1 << 12));
2066        (this->*insn1)(Rd, Rd, imm & ((1 << 12)-1));
2067     } else {
2068        assert_different_registers(Rd, Rn);
2069        mov(Rd, (uint64_t)imm);
2070        (this->*insn2)(Rd, Rn, Rd, LSL, 0);
2071     }
2072   }
2073 }
2074 
2075 // Seperate vsn which sets the flags. Optimisations are more restricted
2076 // because we must set the flags correctly.
2077 void MacroAssembler::wrap_adds_subs_imm_insn(Register Rd, Register Rn, unsigned imm,
2078                                            add_sub_imm_insn insn1,
2079                                            add_sub_reg_insn insn2) {
2080   if (operand_valid_for_add_sub_immediate((int)imm)) {
2081     (this->*insn1)(Rd, Rn, imm);
2082   } else {
2083     assert_different_registers(Rd, Rn);
2084     assert(Rd != zr, "overflow in immediate operand");
2085     mov(Rd, (uint64_t)imm);
2086     (this->*insn2)(Rd, Rn, Rd, LSL, 0);
2087   }
2088 }
2089 
2090 
2091 void MacroAssembler::add(Register Rd, Register Rn, RegisterOrConstant increment) {
2092   if (increment.is_register()) {
2093     add(Rd, Rn, increment.as_register());
2094   } else {
2095     add(Rd, Rn, increment.as_constant());
2096   }
2097 }
2098 
2099 void MacroAssembler::addw(Register Rd, Register Rn, RegisterOrConstant increment) {
2100   if (increment.is_register()) {
2101     addw(Rd, Rn, increment.as_register());
2102   } else {
2103     addw(Rd, Rn, increment.as_constant());
2104   }
2105 }
2106 
2107 void MacroAssembler::sub(Register Rd, Register Rn, RegisterOrConstant decrement) {
2108   if (decrement.is_register()) {
2109     sub(Rd, Rn, decrement.as_register());
2110   } else {
2111     sub(Rd, Rn, decrement.as_constant());
2112   }
2113 }
2114 
2115 void MacroAssembler::subw(Register Rd, Register Rn, RegisterOrConstant decrement) {
2116   if (decrement.is_register()) {
2117     subw(Rd, Rn, decrement.as_register());
2118   } else {
2119     subw(Rd, Rn, decrement.as_constant());
2120   }
2121 }
2122 
2123 void MacroAssembler::reinit_heapbase()
2124 {
2125   if (UseCompressedOops) {
2126     if (Universe::is_fully_initialized()) {
2127       mov(rheapbase, Universe::narrow_ptrs_base());
2128     } else {
2129       lea(rheapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
2130       ldr(rheapbase, Address(rheapbase));
2131     }
2132   }
2133 }
2134 
2135 // this simulates the behaviour of the x86 cmpxchg instruction using a
2136 // load linked/store conditional pair. we use the acquire/release
2137 // versions of these instructions so that we flush pending writes as
2138 // per Java semantics.
2139 
2140 // n.b the x86 version assumes the old value to be compared against is
2141 // in rax and updates rax with the value located in memory if the
2142 // cmpxchg fails. we supply a register for the old value explicitly
2143 
2144 // the aarch64 load linked/store conditional instructions do not
2145 // accept an offset. so, unlike x86, we must provide a plain register
2146 // to identify the memory word to be compared/exchanged rather than a
2147 // register+offset Address.
2148 
2149 void MacroAssembler::cmpxchgptr(Register oldv, Register newv, Register addr, Register tmp,
2150                                 Label &succeed, Label *fail) {
2151   // oldv holds comparison value
2152   // newv holds value to write in exchange
2153   // addr identifies memory word to compare against/update
2154   if (UseLSE) {
2155     mov(tmp, oldv);
2156     casal(Assembler::xword, oldv, newv, addr);
2157     cmp(tmp, oldv);
2158     br(Assembler::EQ, succeed);
2159     membar(AnyAny);
2160   } else {
2161     Label retry_load, nope;
2162     if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))
2163       prfm(Address(addr), PSTL1STRM);
2164     bind(retry_load);
2165     // flush and load exclusive from the memory location
2166     // and fail if it is not what we expect
2167     ldaxr(tmp, addr);
2168     cmp(tmp, oldv);
2169     br(Assembler::NE, nope);
2170     // if we store+flush with no intervening write tmp wil be zero
2171     stlxr(tmp, newv, addr);
2172     cbzw(tmp, succeed);
2173     // retry so we only ever return after a load fails to compare
2174     // ensures we don't return a stale value after a failed write.
2175     b(retry_load);
2176     // if the memory word differs we return it in oldv and signal a fail
2177     bind(nope);
2178     membar(AnyAny);
2179     mov(oldv, tmp);
2180   }
2181   if (fail)
2182     b(*fail);
2183 }
2184 
2185 void MacroAssembler::cmpxchg_obj_header(Register oldv, Register newv, Register obj, Register tmp,
2186                                         Label &succeed, Label *fail) {
2187   assert(oopDesc::mark_offset_in_bytes() == 0, "assumption");
2188   cmpxchgptr(oldv, newv, obj, tmp, succeed, fail);
2189 }
2190 
2191 void MacroAssembler::cmpxchgw(Register oldv, Register newv, Register addr, Register tmp,
2192                                 Label &succeed, Label *fail) {
2193   // oldv holds comparison value
2194   // newv holds value to write in exchange
2195   // addr identifies memory word to compare against/update
2196   // tmp returns 0/1 for success/failure
2197   if (UseLSE) {
2198     mov(tmp, oldv);
2199     casal(Assembler::word, oldv, newv, addr);
2200     cmp(tmp, oldv);
2201     br(Assembler::EQ, succeed);
2202     membar(AnyAny);
2203   } else {
2204     Label retry_load, nope;
2205     if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))
2206       prfm(Address(addr), PSTL1STRM);
2207     bind(retry_load);
2208     // flush and load exclusive from the memory location
2209     // and fail if it is not what we expect
2210     ldaxrw(tmp, addr);
2211     cmp(tmp, oldv);
2212     br(Assembler::NE, nope);
2213     // if we store+flush with no intervening write tmp wil be zero
2214     stlxrw(tmp, newv, addr);
2215     cbzw(tmp, succeed);
2216     // retry so we only ever return after a load fails to compare
2217     // ensures we don't return a stale value after a failed write.
2218     b(retry_load);
2219     // if the memory word differs we return it in oldv and signal a fail
2220     bind(nope);
2221     membar(AnyAny);
2222     mov(oldv, tmp);
2223   }
2224   if (fail)
2225     b(*fail);
2226 }
2227 
2228 // A generic CAS; success or failure is in the EQ flag.  A weak CAS
2229 // doesn't retry and may fail spuriously.  If the oldval is wanted,
2230 // Pass a register for the result, otherwise pass noreg.
2231 
2232 // Clobbers rscratch1
2233 void MacroAssembler::cmpxchg(Register addr, Register expected,
2234                              Register new_val,
2235                              enum operand_size size,
2236                              bool acquire, bool release,
2237                              bool weak,
2238                              Register result) {
2239   if (result == noreg)  result = rscratch1;
2240   if (UseLSE) {
2241     mov(result, expected);
2242     lse_cas(result, new_val, addr, size, acquire, release, /*not_pair*/ true);
2243     cmp(result, expected);
2244   } else {
2245     BLOCK_COMMENT("cmpxchg {");
2246     Label retry_load, done;
2247     if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))
2248       prfm(Address(addr), PSTL1STRM);
2249     bind(retry_load);
2250     load_exclusive(result, addr, size, acquire);
2251     if (size == xword)
2252       cmp(result, expected);
2253     else
2254       cmpw(result, expected);
2255     br(Assembler::NE, done);
2256     store_exclusive(rscratch1, new_val, addr, size, release);
2257     if (weak) {
2258       cmpw(rscratch1, 0u);  // If the store fails, return NE to our caller.
2259     } else {
2260       cbnzw(rscratch1, retry_load);
2261     }
2262     bind(done);
2263     BLOCK_COMMENT("} cmpxchg");
2264   }
2265 }
2266 
2267 static bool different(Register a, RegisterOrConstant b, Register c) {
2268   if (b.is_constant())
2269     return a != c;
2270   else
2271     return a != b.as_register() && a != c && b.as_register() != c;
2272 }
2273 
2274 #define ATOMIC_OP(NAME, LDXR, OP, IOP, AOP, STXR, sz)                   \
2275 void MacroAssembler::atomic_##NAME(Register prev, RegisterOrConstant incr, Register addr) { \
2276   if (UseLSE) {                                                         \
2277     prev = prev->is_valid() ? prev : zr;                                \
2278     if (incr.is_register()) {                                           \
2279       AOP(sz, incr.as_register(), prev, addr);                          \
2280     } else {                                                            \
2281       mov(rscratch2, incr.as_constant());                               \
2282       AOP(sz, rscratch2, prev, addr);                                   \
2283     }                                                                   \
2284     return;                                                             \
2285   }                                                                     \
2286   Register result = rscratch2;                                          \
2287   if (prev->is_valid())                                                 \
2288     result = different(prev, incr, addr) ? prev : rscratch2;            \
2289                                                                         \
2290   Label retry_load;                                                     \
2291   if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))         \
2292     prfm(Address(addr), PSTL1STRM);                                     \
2293   bind(retry_load);                                                     \
2294   LDXR(result, addr);                                                   \
2295   OP(rscratch1, result, incr);                                          \
2296   STXR(rscratch2, rscratch1, addr);                                     \
2297   cbnzw(rscratch2, retry_load);                                         \
2298   if (prev->is_valid() && prev != result) {                             \
2299     IOP(prev, rscratch1, incr);                                         \
2300   }                                                                     \
2301 }
2302 
2303 ATOMIC_OP(add, ldxr, add, sub, ldadd, stxr, Assembler::xword)
2304 ATOMIC_OP(addw, ldxrw, addw, subw, ldadd, stxrw, Assembler::word)
2305 ATOMIC_OP(addal, ldaxr, add, sub, ldaddal, stlxr, Assembler::xword)
2306 ATOMIC_OP(addalw, ldaxrw, addw, subw, ldaddal, stlxrw, Assembler::word)
2307 
2308 #undef ATOMIC_OP
2309 
2310 #define ATOMIC_XCHG(OP, AOP, LDXR, STXR, sz)                            \
2311 void MacroAssembler::atomic_##OP(Register prev, Register newv, Register addr) { \
2312   if (UseLSE) {                                                         \
2313     prev = prev->is_valid() ? prev : zr;                                \
2314     AOP(sz, newv, prev, addr);                                          \
2315     return;                                                             \
2316   }                                                                     \
2317   Register result = rscratch2;                                          \
2318   if (prev->is_valid())                                                 \
2319     result = different(prev, newv, addr) ? prev : rscratch2;            \
2320                                                                         \
2321   Label retry_load;                                                     \
2322   if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))         \
2323     prfm(Address(addr), PSTL1STRM);                                     \
2324   bind(retry_load);                                                     \
2325   LDXR(result, addr);                                                   \
2326   STXR(rscratch1, newv, addr);                                          \
2327   cbnzw(rscratch1, retry_load);                                         \
2328   if (prev->is_valid() && prev != result)                               \
2329     mov(prev, result);                                                  \
2330 }
2331 
2332 ATOMIC_XCHG(xchg, swp, ldxr, stxr, Assembler::xword)
2333 ATOMIC_XCHG(xchgw, swp, ldxrw, stxrw, Assembler::word)
2334 ATOMIC_XCHG(xchgal, swpal, ldaxr, stlxr, Assembler::xword)
2335 ATOMIC_XCHG(xchgalw, swpal, ldaxrw, stlxrw, Assembler::word)
2336 
2337 #undef ATOMIC_XCHG
2338 
2339 void MacroAssembler::incr_allocated_bytes(Register thread,
2340                                           Register var_size_in_bytes,
2341                                           int con_size_in_bytes,
2342                                           Register t1) {
2343   if (!thread->is_valid()) {
2344     thread = rthread;
2345   }
2346   assert(t1->is_valid(), "need temp reg");
2347 
2348   ldr(t1, Address(thread, in_bytes(JavaThread::allocated_bytes_offset())));
2349   if (var_size_in_bytes->is_valid()) {
2350     add(t1, t1, var_size_in_bytes);
2351   } else {
2352     add(t1, t1, con_size_in_bytes);
2353   }
2354   str(t1, Address(thread, in_bytes(JavaThread::allocated_bytes_offset())));
2355 }
2356 
2357 #ifndef PRODUCT
2358 extern "C" void findpc(intptr_t x);
2359 #endif
2360 
2361 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[])
2362 {
2363   // In order to get locks to work, we need to fake a in_VM state
2364   if (ShowMessageBoxOnError ) {
2365     JavaThread* thread = JavaThread::current();
2366     JavaThreadState saved_state = thread->thread_state();
2367     thread->set_thread_state(_thread_in_vm);
2368 #ifndef PRODUCT
2369     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
2370       ttyLocker ttyl;
2371       BytecodeCounter::print();
2372     }
2373 #endif
2374     if (os::message_box(msg, "Execution stopped, print registers?")) {
2375       ttyLocker ttyl;
2376       tty->print_cr(" pc = 0x%016lx", pc);
2377 #ifndef PRODUCT
2378       tty->cr();
2379       findpc(pc);
2380       tty->cr();
2381 #endif
2382       tty->print_cr(" r0 = 0x%016lx", regs[0]);
2383       tty->print_cr(" r1 = 0x%016lx", regs[1]);
2384       tty->print_cr(" r2 = 0x%016lx", regs[2]);
2385       tty->print_cr(" r3 = 0x%016lx", regs[3]);
2386       tty->print_cr(" r4 = 0x%016lx", regs[4]);
2387       tty->print_cr(" r5 = 0x%016lx", regs[5]);
2388       tty->print_cr(" r6 = 0x%016lx", regs[6]);
2389       tty->print_cr(" r7 = 0x%016lx", regs[7]);
2390       tty->print_cr(" r8 = 0x%016lx", regs[8]);
2391       tty->print_cr(" r9 = 0x%016lx", regs[9]);
2392       tty->print_cr("r10 = 0x%016lx", regs[10]);
2393       tty->print_cr("r11 = 0x%016lx", regs[11]);
2394       tty->print_cr("r12 = 0x%016lx", regs[12]);
2395       tty->print_cr("r13 = 0x%016lx", regs[13]);
2396       tty->print_cr("r14 = 0x%016lx", regs[14]);
2397       tty->print_cr("r15 = 0x%016lx", regs[15]);
2398       tty->print_cr("r16 = 0x%016lx", regs[16]);
2399       tty->print_cr("r17 = 0x%016lx", regs[17]);
2400       tty->print_cr("r18 = 0x%016lx", regs[18]);
2401       tty->print_cr("r19 = 0x%016lx", regs[19]);
2402       tty->print_cr("r20 = 0x%016lx", regs[20]);
2403       tty->print_cr("r21 = 0x%016lx", regs[21]);
2404       tty->print_cr("r22 = 0x%016lx", regs[22]);
2405       tty->print_cr("r23 = 0x%016lx", regs[23]);
2406       tty->print_cr("r24 = 0x%016lx", regs[24]);
2407       tty->print_cr("r25 = 0x%016lx", regs[25]);
2408       tty->print_cr("r26 = 0x%016lx", regs[26]);
2409       tty->print_cr("r27 = 0x%016lx", regs[27]);
2410       tty->print_cr("r28 = 0x%016lx", regs[28]);
2411       tty->print_cr("r30 = 0x%016lx", regs[30]);
2412       tty->print_cr("r31 = 0x%016lx", regs[31]);
2413       BREAKPOINT;
2414     }
2415     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
2416   } else {
2417     ttyLocker ttyl;
2418     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
2419                     msg);
2420     assert(false, "DEBUG MESSAGE: %s", msg);
2421   }
2422 }
2423 
2424 #ifdef BUILTIN_SIM
2425 // routine to generate an x86 prolog for a stub function which
2426 // bootstraps into the generated ARM code which directly follows the
2427 // stub
2428 //
2429 // the argument encodes the number of general and fp registers
2430 // passed by the caller and the callng convention (currently just
2431 // the number of general registers and assumes C argument passing)
2432 
2433 extern "C" {
2434 int aarch64_stub_prolog_size();
2435 void aarch64_stub_prolog();
2436 void aarch64_prolog();
2437 }
2438 
2439 void MacroAssembler::c_stub_prolog(int gp_arg_count, int fp_arg_count, int ret_type,
2440                                    address *prolog_ptr)
2441 {
2442   int calltype = (((ret_type & 0x3) << 8) |
2443                   ((fp_arg_count & 0xf) << 4) |
2444                   (gp_arg_count & 0xf));
2445 
2446   // the addresses for the x86 to ARM entry code we need to use
2447   address start = pc();
2448   // printf("start = %lx\n", start);
2449   int byteCount =  aarch64_stub_prolog_size();
2450   // printf("byteCount = %x\n", byteCount);
2451   int instructionCount = (byteCount + 3)/ 4;
2452   // printf("instructionCount = %x\n", instructionCount);
2453   for (int i = 0; i < instructionCount; i++) {
2454     nop();
2455   }
2456 
2457   memcpy(start, (void*)aarch64_stub_prolog, byteCount);
2458 
2459   // write the address of the setup routine and the call format at the
2460   // end of into the copied code
2461   u_int64_t *patch_end = (u_int64_t *)(start + byteCount);
2462   if (prolog_ptr)
2463     patch_end[-2] = (u_int64_t)prolog_ptr;
2464   patch_end[-1] = calltype;
2465 }
2466 #endif
2467 
2468 void MacroAssembler::push_call_clobbered_registers() {
2469   push(RegSet::range(r0, r18) - RegSet::of(rscratch1, rscratch2), sp);
2470 
2471   // Push v0-v7, v16-v31.
2472   for (int i = 30; i >= 0; i -= 2) {
2473     if (i <= v7->encoding() || i >= v16->encoding()) {
2474         stpd(as_FloatRegister(i), as_FloatRegister(i+1),
2475              Address(pre(sp, -2 * wordSize)));
2476     }
2477   }
2478 }
2479 
2480 void MacroAssembler::pop_call_clobbered_registers() {
2481 
2482   for (int i = 0; i < 32; i += 2) {
2483     if (i <= v7->encoding() || i >= v16->encoding()) {
2484       ldpd(as_FloatRegister(i), as_FloatRegister(i+1),
2485            Address(post(sp, 2 * wordSize)));
2486     }
2487   }
2488 
2489   pop(RegSet::range(r0, r18) - RegSet::of(rscratch1, rscratch2), sp);
2490 }
2491 
2492 void MacroAssembler::push_CPU_state(bool save_vectors) {
2493   push(0x3fffffff, sp);         // integer registers except lr & sp
2494 
2495   if (!save_vectors) {
2496     for (int i = 30; i >= 0; i -= 2)
2497       stpd(as_FloatRegister(i), as_FloatRegister(i+1),
2498            Address(pre(sp, -2 * wordSize)));
2499   } else {
2500     for (int i = 30; i >= 0; i -= 2)
2501       stpq(as_FloatRegister(i), as_FloatRegister(i+1),
2502            Address(pre(sp, -4 * wordSize)));
2503   }
2504 }
2505 
2506 void MacroAssembler::pop_CPU_state(bool restore_vectors) {
2507   if (!restore_vectors) {
2508     for (int i = 0; i < 32; i += 2)
2509       ldpd(as_FloatRegister(i), as_FloatRegister(i+1),
2510            Address(post(sp, 2 * wordSize)));
2511   } else {
2512     for (int i = 0; i < 32; i += 2)
2513       ldpq(as_FloatRegister(i), as_FloatRegister(i+1),
2514            Address(post(sp, 4 * wordSize)));
2515   }
2516 
2517   pop(0x3fffffff, sp);         // integer registers except lr & sp
2518 }
2519 
2520 /**
2521  * Helpers for multiply_to_len().
2522  */
2523 void MacroAssembler::add2_with_carry(Register final_dest_hi, Register dest_hi, Register dest_lo,
2524                                      Register src1, Register src2) {
2525   adds(dest_lo, dest_lo, src1);
2526   adc(dest_hi, dest_hi, zr);
2527   adds(dest_lo, dest_lo, src2);
2528   adc(final_dest_hi, dest_hi, zr);
2529 }
2530 
2531 // Generate an address from (r + r1 extend offset).  "size" is the
2532 // size of the operand.  The result may be in rscratch2.
2533 Address MacroAssembler::offsetted_address(Register r, Register r1,
2534                                           Address::extend ext, int offset, int size) {
2535   if (offset || (ext.shift() % size != 0)) {
2536     lea(rscratch2, Address(r, r1, ext));
2537     return Address(rscratch2, offset);
2538   } else {
2539     return Address(r, r1, ext);
2540   }
2541 }
2542 
2543 Address MacroAssembler::spill_address(int size, int offset, Register tmp)
2544 {
2545   assert(offset >= 0, "spill to negative address?");
2546   // Offset reachable ?
2547   //   Not aligned - 9 bits signed offset
2548   //   Aligned - 12 bits unsigned offset shifted
2549   Register base = sp;
2550   if ((offset & (size-1)) && offset >= (1<<8)) {
2551     add(tmp, base, offset & ((1<<12)-1));
2552     base = tmp;
2553     offset &= -1<<12;
2554   }
2555 
2556   if (offset >= (1<<12) * size) {
2557     add(tmp, base, offset & (((1<<12)-1)<<12));
2558     base = tmp;
2559     offset &= ~(((1<<12)-1)<<12);
2560   }
2561 
2562   return Address(base, offset);
2563 }
2564 
2565 /**
2566  * Multiply 64 bit by 64 bit first loop.
2567  */
2568 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
2569                                            Register y, Register y_idx, Register z,
2570                                            Register carry, Register product,
2571                                            Register idx, Register kdx) {
2572   //
2573   //  jlong carry, x[], y[], z[];
2574   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
2575   //    huge_128 product = y[idx] * x[xstart] + carry;
2576   //    z[kdx] = (jlong)product;
2577   //    carry  = (jlong)(product >>> 64);
2578   //  }
2579   //  z[xstart] = carry;
2580   //
2581 
2582   Label L_first_loop, L_first_loop_exit;
2583   Label L_one_x, L_one_y, L_multiply;
2584 
2585   subsw(xstart, xstart, 1);
2586   br(Assembler::MI, L_one_x);
2587 
2588   lea(rscratch1, Address(x, xstart, Address::lsl(LogBytesPerInt)));
2589   ldr(x_xstart, Address(rscratch1));
2590   ror(x_xstart, x_xstart, 32); // convert big-endian to little-endian
2591 
2592   bind(L_first_loop);
2593   subsw(idx, idx, 1);
2594   br(Assembler::MI, L_first_loop_exit);
2595   subsw(idx, idx, 1);
2596   br(Assembler::MI, L_one_y);
2597   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2598   ldr(y_idx, Address(rscratch1));
2599   ror(y_idx, y_idx, 32); // convert big-endian to little-endian
2600   bind(L_multiply);
2601 
2602   // AArch64 has a multiply-accumulate instruction that we can't use
2603   // here because it has no way to process carries, so we have to use
2604   // separate add and adc instructions.  Bah.
2605   umulh(rscratch1, x_xstart, y_idx); // x_xstart * y_idx -> rscratch1:product
2606   mul(product, x_xstart, y_idx);
2607   adds(product, product, carry);
2608   adc(carry, rscratch1, zr);   // x_xstart * y_idx + carry -> carry:product
2609 
2610   subw(kdx, kdx, 2);
2611   ror(product, product, 32); // back to big-endian
2612   str(product, offsetted_address(z, kdx, Address::uxtw(LogBytesPerInt), 0, BytesPerLong));
2613 
2614   b(L_first_loop);
2615 
2616   bind(L_one_y);
2617   ldrw(y_idx, Address(y,  0));
2618   b(L_multiply);
2619 
2620   bind(L_one_x);
2621   ldrw(x_xstart, Address(x,  0));
2622   b(L_first_loop);
2623 
2624   bind(L_first_loop_exit);
2625 }
2626 
2627 /**
2628  * Multiply 128 bit by 128. Unrolled inner loop.
2629  *
2630  */
2631 void MacroAssembler::multiply_128_x_128_loop(Register y, Register z,
2632                                              Register carry, Register carry2,
2633                                              Register idx, Register jdx,
2634                                              Register yz_idx1, Register yz_idx2,
2635                                              Register tmp, Register tmp3, Register tmp4,
2636                                              Register tmp6, Register product_hi) {
2637 
2638   //   jlong carry, x[], y[], z[];
2639   //   int kdx = ystart+1;
2640   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
2641   //     huge_128 tmp3 = (y[idx+1] * product_hi) + z[kdx+idx+1] + carry;
2642   //     jlong carry2  = (jlong)(tmp3 >>> 64);
2643   //     huge_128 tmp4 = (y[idx]   * product_hi) + z[kdx+idx] + carry2;
2644   //     carry  = (jlong)(tmp4 >>> 64);
2645   //     z[kdx+idx+1] = (jlong)tmp3;
2646   //     z[kdx+idx] = (jlong)tmp4;
2647   //   }
2648   //   idx += 2;
2649   //   if (idx > 0) {
2650   //     yz_idx1 = (y[idx] * product_hi) + z[kdx+idx] + carry;
2651   //     z[kdx+idx] = (jlong)yz_idx1;
2652   //     carry  = (jlong)(yz_idx1 >>> 64);
2653   //   }
2654   //
2655 
2656   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
2657 
2658   lsrw(jdx, idx, 2);
2659 
2660   bind(L_third_loop);
2661 
2662   subsw(jdx, jdx, 1);
2663   br(Assembler::MI, L_third_loop_exit);
2664   subw(idx, idx, 4);
2665 
2666   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2667 
2668   ldp(yz_idx2, yz_idx1, Address(rscratch1, 0));
2669 
2670   lea(tmp6, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2671 
2672   ror(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
2673   ror(yz_idx2, yz_idx2, 32);
2674 
2675   ldp(rscratch2, rscratch1, Address(tmp6, 0));
2676 
2677   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
2678   umulh(tmp4, product_hi, yz_idx1);
2679 
2680   ror(rscratch1, rscratch1, 32); // convert big-endian to little-endian
2681   ror(rscratch2, rscratch2, 32);
2682 
2683   mul(tmp, product_hi, yz_idx2);   //  yz_idx2 * product_hi -> carry2:tmp
2684   umulh(carry2, product_hi, yz_idx2);
2685 
2686   // propagate sum of both multiplications into carry:tmp4:tmp3
2687   adds(tmp3, tmp3, carry);
2688   adc(tmp4, tmp4, zr);
2689   adds(tmp3, tmp3, rscratch1);
2690   adcs(tmp4, tmp4, tmp);
2691   adc(carry, carry2, zr);
2692   adds(tmp4, tmp4, rscratch2);
2693   adc(carry, carry, zr);
2694 
2695   ror(tmp3, tmp3, 32); // convert little-endian to big-endian
2696   ror(tmp4, tmp4, 32);
2697   stp(tmp4, tmp3, Address(tmp6, 0));
2698 
2699   b(L_third_loop);
2700   bind (L_third_loop_exit);
2701 
2702   andw (idx, idx, 0x3);
2703   cbz(idx, L_post_third_loop_done);
2704 
2705   Label L_check_1;
2706   subsw(idx, idx, 2);
2707   br(Assembler::MI, L_check_1);
2708 
2709   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2710   ldr(yz_idx1, Address(rscratch1, 0));
2711   ror(yz_idx1, yz_idx1, 32);
2712   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
2713   umulh(tmp4, product_hi, yz_idx1);
2714   lea(rscratch1, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2715   ldr(yz_idx2, Address(rscratch1, 0));
2716   ror(yz_idx2, yz_idx2, 32);
2717 
2718   add2_with_carry(carry, tmp4, tmp3, carry, yz_idx2);
2719 
2720   ror(tmp3, tmp3, 32);
2721   str(tmp3, Address(rscratch1, 0));
2722 
2723   bind (L_check_1);
2724 
2725   andw (idx, idx, 0x1);
2726   subsw(idx, idx, 1);
2727   br(Assembler::MI, L_post_third_loop_done);
2728   ldrw(tmp4, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2729   mul(tmp3, tmp4, product_hi);  //  tmp4 * product_hi -> carry2:tmp3
2730   umulh(carry2, tmp4, product_hi);
2731   ldrw(tmp4, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2732 
2733   add2_with_carry(carry2, tmp3, tmp4, carry);
2734 
2735   strw(tmp3, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2736   extr(carry, carry2, tmp3, 32);
2737 
2738   bind(L_post_third_loop_done);
2739 }
2740 
2741 /**
2742  * Code for BigInteger::multiplyToLen() instrinsic.
2743  *
2744  * r0: x
2745  * r1: xlen
2746  * r2: y
2747  * r3: ylen
2748  * r4:  z
2749  * r5: zlen
2750  * r10: tmp1
2751  * r11: tmp2
2752  * r12: tmp3
2753  * r13: tmp4
2754  * r14: tmp5
2755  * r15: tmp6
2756  * r16: tmp7
2757  *
2758  */
2759 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen,
2760                                      Register z, Register zlen,
2761                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4,
2762                                      Register tmp5, Register tmp6, Register product_hi) {
2763 
2764   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6);
2765 
2766   const Register idx = tmp1;
2767   const Register kdx = tmp2;
2768   const Register xstart = tmp3;
2769 
2770   const Register y_idx = tmp4;
2771   const Register carry = tmp5;
2772   const Register product  = xlen;
2773   const Register x_xstart = zlen;  // reuse register
2774 
2775   // First Loop.
2776   //
2777   //  final static long LONG_MASK = 0xffffffffL;
2778   //  int xstart = xlen - 1;
2779   //  int ystart = ylen - 1;
2780   //  long carry = 0;
2781   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
2782   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
2783   //    z[kdx] = (int)product;
2784   //    carry = product >>> 32;
2785   //  }
2786   //  z[xstart] = (int)carry;
2787   //
2788 
2789   movw(idx, ylen);      // idx = ylen;
2790   movw(kdx, zlen);      // kdx = xlen+ylen;
2791   mov(carry, zr);       // carry = 0;
2792 
2793   Label L_done;
2794 
2795   movw(xstart, xlen);
2796   subsw(xstart, xstart, 1);
2797   br(Assembler::MI, L_done);
2798 
2799   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
2800 
2801   Label L_second_loop;
2802   cbzw(kdx, L_second_loop);
2803 
2804   Label L_carry;
2805   subw(kdx, kdx, 1);
2806   cbzw(kdx, L_carry);
2807 
2808   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
2809   lsr(carry, carry, 32);
2810   subw(kdx, kdx, 1);
2811 
2812   bind(L_carry);
2813   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
2814 
2815   // Second and third (nested) loops.
2816   //
2817   // for (int i = xstart-1; i >= 0; i--) { // Second loop
2818   //   carry = 0;
2819   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
2820   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
2821   //                    (z[k] & LONG_MASK) + carry;
2822   //     z[k] = (int)product;
2823   //     carry = product >>> 32;
2824   //   }
2825   //   z[i] = (int)carry;
2826   // }
2827   //
2828   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = product_hi
2829 
2830   const Register jdx = tmp1;
2831 
2832   bind(L_second_loop);
2833   mov(carry, zr);                // carry = 0;
2834   movw(jdx, ylen);               // j = ystart+1
2835 
2836   subsw(xstart, xstart, 1);      // i = xstart-1;
2837   br(Assembler::MI, L_done);
2838 
2839   str(z, Address(pre(sp, -4 * wordSize)));
2840 
2841   Label L_last_x;
2842   lea(z, offsetted_address(z, xstart, Address::uxtw(LogBytesPerInt), 4, BytesPerInt)); // z = z + k - j
2843   subsw(xstart, xstart, 1);       // i = xstart-1;
2844   br(Assembler::MI, L_last_x);
2845 
2846   lea(rscratch1, Address(x, xstart, Address::uxtw(LogBytesPerInt)));
2847   ldr(product_hi, Address(rscratch1));
2848   ror(product_hi, product_hi, 32);  // convert big-endian to little-endian
2849 
2850   Label L_third_loop_prologue;
2851   bind(L_third_loop_prologue);
2852 
2853   str(ylen, Address(sp, wordSize));
2854   stp(x, xstart, Address(sp, 2 * wordSize));
2855   multiply_128_x_128_loop(y, z, carry, x, jdx, ylen, product,
2856                           tmp2, x_xstart, tmp3, tmp4, tmp6, product_hi);
2857   ldp(z, ylen, Address(post(sp, 2 * wordSize)));
2858   ldp(x, xlen, Address(post(sp, 2 * wordSize)));   // copy old xstart -> xlen
2859 
2860   addw(tmp3, xlen, 1);
2861   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
2862   subsw(tmp3, tmp3, 1);
2863   br(Assembler::MI, L_done);
2864 
2865   lsr(carry, carry, 32);
2866   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
2867   b(L_second_loop);
2868 
2869   // Next infrequent code is moved outside loops.
2870   bind(L_last_x);
2871   ldrw(product_hi, Address(x,  0));
2872   b(L_third_loop_prologue);
2873 
2874   bind(L_done);
2875 }
2876 
2877 // Code for BigInteger::mulAdd instrinsic
2878 // out     = r0
2879 // in      = r1
2880 // offset  = r2  (already out.length-offset)
2881 // len     = r3
2882 // k       = r4
2883 //
2884 // pseudo code from java implementation:
2885 // carry = 0;
2886 // offset = out.length-offset - 1;
2887 // for (int j=len-1; j >= 0; j--) {
2888 //     product = (in[j] & LONG_MASK) * kLong + (out[offset] & LONG_MASK) + carry;
2889 //     out[offset--] = (int)product;
2890 //     carry = product >>> 32;
2891 // }
2892 // return (int)carry;
2893 void MacroAssembler::mul_add(Register out, Register in, Register offset,
2894       Register len, Register k) {
2895     Label LOOP, END;
2896     // pre-loop
2897     cmp(len, zr); // cmp, not cbz/cbnz: to use condition twice => less branches
2898     csel(out, zr, out, Assembler::EQ);
2899     br(Assembler::EQ, END);
2900     add(in, in, len, LSL, 2); // in[j+1] address
2901     add(offset, out, offset, LSL, 2); // out[offset + 1] address
2902     mov(out, zr); // used to keep carry now
2903     BIND(LOOP);
2904     ldrw(rscratch1, Address(pre(in, -4)));
2905     madd(rscratch1, rscratch1, k, out);
2906     ldrw(rscratch2, Address(pre(offset, -4)));
2907     add(rscratch1, rscratch1, rscratch2);
2908     strw(rscratch1, Address(offset));
2909     lsr(out, rscratch1, 32);
2910     subs(len, len, 1);
2911     br(Assembler::NE, LOOP);
2912     BIND(END);
2913 }
2914 
2915 /**
2916  * Emits code to update CRC-32 with a byte value according to constants in table
2917  *
2918  * @param [in,out]crc   Register containing the crc.
2919  * @param [in]val       Register containing the byte to fold into the CRC.
2920  * @param [in]table     Register containing the table of crc constants.
2921  *
2922  * uint32_t crc;
2923  * val = crc_table[(val ^ crc) & 0xFF];
2924  * crc = val ^ (crc >> 8);
2925  *
2926  */
2927 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
2928   eor(val, val, crc);
2929   andr(val, val, 0xff);
2930   ldrw(val, Address(table, val, Address::lsl(2)));
2931   eor(crc, val, crc, Assembler::LSR, 8);
2932 }
2933 
2934 /**
2935  * Emits code to update CRC-32 with a 32-bit value according to tables 0 to 3
2936  *
2937  * @param [in,out]crc   Register containing the crc.
2938  * @param [in]v         Register containing the 32-bit to fold into the CRC.
2939  * @param [in]table0    Register containing table 0 of crc constants.
2940  * @param [in]table1    Register containing table 1 of crc constants.
2941  * @param [in]table2    Register containing table 2 of crc constants.
2942  * @param [in]table3    Register containing table 3 of crc constants.
2943  *
2944  * uint32_t crc;
2945  *   v = crc ^ v
2946  *   crc = table3[v&0xff]^table2[(v>>8)&0xff]^table1[(v>>16)&0xff]^table0[v>>24]
2947  *
2948  */
2949 void MacroAssembler::update_word_crc32(Register crc, Register v, Register tmp,
2950         Register table0, Register table1, Register table2, Register table3,
2951         bool upper) {
2952   eor(v, crc, v, upper ? LSR:LSL, upper ? 32:0);
2953   uxtb(tmp, v);
2954   ldrw(crc, Address(table3, tmp, Address::lsl(2)));
2955   ubfx(tmp, v, 8, 8);
2956   ldrw(tmp, Address(table2, tmp, Address::lsl(2)));
2957   eor(crc, crc, tmp);
2958   ubfx(tmp, v, 16, 8);
2959   ldrw(tmp, Address(table1, tmp, Address::lsl(2)));
2960   eor(crc, crc, tmp);
2961   ubfx(tmp, v, 24, 8);
2962   ldrw(tmp, Address(table0, tmp, Address::lsl(2)));
2963   eor(crc, crc, tmp);
2964 }
2965 
2966 void MacroAssembler::kernel_crc32_using_crc32(Register crc, Register buf,
2967         Register len, Register tmp0, Register tmp1, Register tmp2,
2968         Register tmp3) {
2969     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
2970     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
2971 
2972     mvnw(crc, crc);
2973 
2974     subs(len, len, 128);
2975     br(Assembler::GE, CRC_by64_pre);
2976   BIND(CRC_less64);
2977     adds(len, len, 128-32);
2978     br(Assembler::GE, CRC_by32_loop);
2979   BIND(CRC_less32);
2980     adds(len, len, 32-4);
2981     br(Assembler::GE, CRC_by4_loop);
2982     adds(len, len, 4);
2983     br(Assembler::GT, CRC_by1_loop);
2984     b(L_exit);
2985 
2986   BIND(CRC_by32_loop);
2987     ldp(tmp0, tmp1, Address(post(buf, 16)));
2988     subs(len, len, 32);
2989     crc32x(crc, crc, tmp0);
2990     ldr(tmp2, Address(post(buf, 8)));
2991     crc32x(crc, crc, tmp1);
2992     ldr(tmp3, Address(post(buf, 8)));
2993     crc32x(crc, crc, tmp2);
2994     crc32x(crc, crc, tmp3);
2995     br(Assembler::GE, CRC_by32_loop);
2996     cmn(len, 32);
2997     br(Assembler::NE, CRC_less32);
2998     b(L_exit);
2999 
3000   BIND(CRC_by4_loop);
3001     ldrw(tmp0, Address(post(buf, 4)));
3002     subs(len, len, 4);
3003     crc32w(crc, crc, tmp0);
3004     br(Assembler::GE, CRC_by4_loop);
3005     adds(len, len, 4);
3006     br(Assembler::LE, L_exit);
3007   BIND(CRC_by1_loop);
3008     ldrb(tmp0, Address(post(buf, 1)));
3009     subs(len, len, 1);
3010     crc32b(crc, crc, tmp0);
3011     br(Assembler::GT, CRC_by1_loop);
3012     b(L_exit);
3013 
3014   BIND(CRC_by64_pre);
3015     sub(buf, buf, 8);
3016     ldp(tmp0, tmp1, Address(buf, 8));
3017     crc32x(crc, crc, tmp0);
3018     ldr(tmp2, Address(buf, 24));
3019     crc32x(crc, crc, tmp1);
3020     ldr(tmp3, Address(buf, 32));
3021     crc32x(crc, crc, tmp2);
3022     ldr(tmp0, Address(buf, 40));
3023     crc32x(crc, crc, tmp3);
3024     ldr(tmp1, Address(buf, 48));
3025     crc32x(crc, crc, tmp0);
3026     ldr(tmp2, Address(buf, 56));
3027     crc32x(crc, crc, tmp1);
3028     ldr(tmp3, Address(pre(buf, 64)));
3029 
3030     b(CRC_by64_loop);
3031 
3032     align(CodeEntryAlignment);
3033   BIND(CRC_by64_loop);
3034     subs(len, len, 64);
3035     crc32x(crc, crc, tmp2);
3036     ldr(tmp0, Address(buf, 8));
3037     crc32x(crc, crc, tmp3);
3038     ldr(tmp1, Address(buf, 16));
3039     crc32x(crc, crc, tmp0);
3040     ldr(tmp2, Address(buf, 24));
3041     crc32x(crc, crc, tmp1);
3042     ldr(tmp3, Address(buf, 32));
3043     crc32x(crc, crc, tmp2);
3044     ldr(tmp0, Address(buf, 40));
3045     crc32x(crc, crc, tmp3);
3046     ldr(tmp1, Address(buf, 48));
3047     crc32x(crc, crc, tmp0);
3048     ldr(tmp2, Address(buf, 56));
3049     crc32x(crc, crc, tmp1);
3050     ldr(tmp3, Address(pre(buf, 64)));
3051     br(Assembler::GE, CRC_by64_loop);
3052 
3053     // post-loop
3054     crc32x(crc, crc, tmp2);
3055     crc32x(crc, crc, tmp3);
3056 
3057     sub(len, len, 64);
3058     add(buf, buf, 8);
3059     cmn(len, 128);
3060     br(Assembler::NE, CRC_less64);
3061   BIND(L_exit);
3062     mvnw(crc, crc);
3063 }
3064 
3065 /**
3066  * @param crc   register containing existing CRC (32-bit)
3067  * @param buf   register pointing to input byte buffer (byte*)
3068  * @param len   register containing number of bytes
3069  * @param table register that will contain address of CRC table
3070  * @param tmp   scratch register
3071  */
3072 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len,
3073         Register table0, Register table1, Register table2, Register table3,
3074         Register tmp, Register tmp2, Register tmp3) {
3075   Label L_by16, L_by16_loop, L_by4, L_by4_loop, L_by1, L_by1_loop, L_exit;
3076   unsigned long offset;
3077 
3078   if (UseCRC32) {
3079       kernel_crc32_using_crc32(crc, buf, len, table0, table1, table2, table3);
3080       return;
3081   }
3082 
3083     mvnw(crc, crc);
3084 
3085     adrp(table0, ExternalAddress(StubRoutines::crc_table_addr()), offset);
3086     if (offset) add(table0, table0, offset);
3087     add(table1, table0, 1*256*sizeof(juint));
3088     add(table2, table0, 2*256*sizeof(juint));
3089     add(table3, table0, 3*256*sizeof(juint));
3090 
3091   if (UseNeon) {
3092       cmp(len, 64);
3093       br(Assembler::LT, L_by16);
3094       eor(v16, T16B, v16, v16);
3095 
3096     Label L_fold;
3097 
3098       add(tmp, table0, 4*256*sizeof(juint)); // Point at the Neon constants
3099 
3100       ld1(v0, v1, T2D, post(buf, 32));
3101       ld1r(v4, T2D, post(tmp, 8));
3102       ld1r(v5, T2D, post(tmp, 8));
3103       ld1r(v6, T2D, post(tmp, 8));
3104       ld1r(v7, T2D, post(tmp, 8));
3105       mov(v16, T4S, 0, crc);
3106 
3107       eor(v0, T16B, v0, v16);
3108       sub(len, len, 64);
3109 
3110     BIND(L_fold);
3111       pmull(v22, T8H, v0, v5, T8B);
3112       pmull(v20, T8H, v0, v7, T8B);
3113       pmull(v23, T8H, v0, v4, T8B);
3114       pmull(v21, T8H, v0, v6, T8B);
3115 
3116       pmull2(v18, T8H, v0, v5, T16B);
3117       pmull2(v16, T8H, v0, v7, T16B);
3118       pmull2(v19, T8H, v0, v4, T16B);
3119       pmull2(v17, T8H, v0, v6, T16B);
3120 
3121       uzp1(v24, v20, v22, T8H);
3122       uzp2(v25, v20, v22, T8H);
3123       eor(v20, T16B, v24, v25);
3124 
3125       uzp1(v26, v16, v18, T8H);
3126       uzp2(v27, v16, v18, T8H);
3127       eor(v16, T16B, v26, v27);
3128 
3129       ushll2(v22, T4S, v20, T8H, 8);
3130       ushll(v20, T4S, v20, T4H, 8);
3131 
3132       ushll2(v18, T4S, v16, T8H, 8);
3133       ushll(v16, T4S, v16, T4H, 8);
3134 
3135       eor(v22, T16B, v23, v22);
3136       eor(v18, T16B, v19, v18);
3137       eor(v20, T16B, v21, v20);
3138       eor(v16, T16B, v17, v16);
3139 
3140       uzp1(v17, v16, v20, T2D);
3141       uzp2(v21, v16, v20, T2D);
3142       eor(v17, T16B, v17, v21);
3143 
3144       ushll2(v20, T2D, v17, T4S, 16);
3145       ushll(v16, T2D, v17, T2S, 16);
3146 
3147       eor(v20, T16B, v20, v22);
3148       eor(v16, T16B, v16, v18);
3149 
3150       uzp1(v17, v20, v16, T2D);
3151       uzp2(v21, v20, v16, T2D);
3152       eor(v28, T16B, v17, v21);
3153 
3154       pmull(v22, T8H, v1, v5, T8B);
3155       pmull(v20, T8H, v1, v7, T8B);
3156       pmull(v23, T8H, v1, v4, T8B);
3157       pmull(v21, T8H, v1, v6, T8B);
3158 
3159       pmull2(v18, T8H, v1, v5, T16B);
3160       pmull2(v16, T8H, v1, v7, T16B);
3161       pmull2(v19, T8H, v1, v4, T16B);
3162       pmull2(v17, T8H, v1, v6, T16B);
3163 
3164       ld1(v0, v1, T2D, post(buf, 32));
3165 
3166       uzp1(v24, v20, v22, T8H);
3167       uzp2(v25, v20, v22, T8H);
3168       eor(v20, T16B, v24, v25);
3169 
3170       uzp1(v26, v16, v18, T8H);
3171       uzp2(v27, v16, v18, T8H);
3172       eor(v16, T16B, v26, v27);
3173 
3174       ushll2(v22, T4S, v20, T8H, 8);
3175       ushll(v20, T4S, v20, T4H, 8);
3176 
3177       ushll2(v18, T4S, v16, T8H, 8);
3178       ushll(v16, T4S, v16, T4H, 8);
3179 
3180       eor(v22, T16B, v23, v22);
3181       eor(v18, T16B, v19, v18);
3182       eor(v20, T16B, v21, v20);
3183       eor(v16, T16B, v17, v16);
3184 
3185       uzp1(v17, v16, v20, T2D);
3186       uzp2(v21, v16, v20, T2D);
3187       eor(v16, T16B, v17, v21);
3188 
3189       ushll2(v20, T2D, v16, T4S, 16);
3190       ushll(v16, T2D, v16, T2S, 16);
3191 
3192       eor(v20, T16B, v22, v20);
3193       eor(v16, T16B, v16, v18);
3194 
3195       uzp1(v17, v20, v16, T2D);
3196       uzp2(v21, v20, v16, T2D);
3197       eor(v20, T16B, v17, v21);
3198 
3199       shl(v16, T2D, v28, 1);
3200       shl(v17, T2D, v20, 1);
3201 
3202       eor(v0, T16B, v0, v16);
3203       eor(v1, T16B, v1, v17);
3204 
3205       subs(len, len, 32);
3206       br(Assembler::GE, L_fold);
3207 
3208       mov(crc, 0);
3209       mov(tmp, v0, T1D, 0);
3210       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3211       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3212       mov(tmp, v0, T1D, 1);
3213       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3214       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3215       mov(tmp, v1, T1D, 0);
3216       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3217       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3218       mov(tmp, v1, T1D, 1);
3219       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3220       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3221 
3222       add(len, len, 32);
3223   }
3224 
3225   BIND(L_by16);
3226     subs(len, len, 16);
3227     br(Assembler::GE, L_by16_loop);
3228     adds(len, len, 16-4);
3229     br(Assembler::GE, L_by4_loop);
3230     adds(len, len, 4);
3231     br(Assembler::GT, L_by1_loop);
3232     b(L_exit);
3233 
3234   BIND(L_by4_loop);
3235     ldrw(tmp, Address(post(buf, 4)));
3236     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3);
3237     subs(len, len, 4);
3238     br(Assembler::GE, L_by4_loop);
3239     adds(len, len, 4);
3240     br(Assembler::LE, L_exit);
3241   BIND(L_by1_loop);
3242     subs(len, len, 1);
3243     ldrb(tmp, Address(post(buf, 1)));
3244     update_byte_crc32(crc, tmp, table0);
3245     br(Assembler::GT, L_by1_loop);
3246     b(L_exit);
3247 
3248     align(CodeEntryAlignment);
3249   BIND(L_by16_loop);
3250     subs(len, len, 16);
3251     ldp(tmp, tmp3, Address(post(buf, 16)));
3252     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3253     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3254     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, false);
3255     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, true);
3256     br(Assembler::GE, L_by16_loop);
3257     adds(len, len, 16-4);
3258     br(Assembler::GE, L_by4_loop);
3259     adds(len, len, 4);
3260     br(Assembler::GT, L_by1_loop);
3261   BIND(L_exit);
3262     mvnw(crc, crc);
3263 }
3264 
3265 void MacroAssembler::kernel_crc32c_using_crc32c(Register crc, Register buf,
3266         Register len, Register tmp0, Register tmp1, Register tmp2,
3267         Register tmp3) {
3268     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
3269     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
3270 
3271     subs(len, len, 128);
3272     br(Assembler::GE, CRC_by64_pre);
3273   BIND(CRC_less64);
3274     adds(len, len, 128-32);
3275     br(Assembler::GE, CRC_by32_loop);
3276   BIND(CRC_less32);
3277     adds(len, len, 32-4);
3278     br(Assembler::GE, CRC_by4_loop);
3279     adds(len, len, 4);
3280     br(Assembler::GT, CRC_by1_loop);
3281     b(L_exit);
3282 
3283   BIND(CRC_by32_loop);
3284     ldp(tmp0, tmp1, Address(post(buf, 16)));
3285     subs(len, len, 32);
3286     crc32cx(crc, crc, tmp0);
3287     ldr(tmp2, Address(post(buf, 8)));
3288     crc32cx(crc, crc, tmp1);
3289     ldr(tmp3, Address(post(buf, 8)));
3290     crc32cx(crc, crc, tmp2);
3291     crc32cx(crc, crc, tmp3);
3292     br(Assembler::GE, CRC_by32_loop);
3293     cmn(len, 32);
3294     br(Assembler::NE, CRC_less32);
3295     b(L_exit);
3296 
3297   BIND(CRC_by4_loop);
3298     ldrw(tmp0, Address(post(buf, 4)));
3299     subs(len, len, 4);
3300     crc32cw(crc, crc, tmp0);
3301     br(Assembler::GE, CRC_by4_loop);
3302     adds(len, len, 4);
3303     br(Assembler::LE, L_exit);
3304   BIND(CRC_by1_loop);
3305     ldrb(tmp0, Address(post(buf, 1)));
3306     subs(len, len, 1);
3307     crc32cb(crc, crc, tmp0);
3308     br(Assembler::GT, CRC_by1_loop);
3309     b(L_exit);
3310 
3311   BIND(CRC_by64_pre);
3312     sub(buf, buf, 8);
3313     ldp(tmp0, tmp1, Address(buf, 8));
3314     crc32cx(crc, crc, tmp0);
3315     ldr(tmp2, Address(buf, 24));
3316     crc32cx(crc, crc, tmp1);
3317     ldr(tmp3, Address(buf, 32));
3318     crc32cx(crc, crc, tmp2);
3319     ldr(tmp0, Address(buf, 40));
3320     crc32cx(crc, crc, tmp3);
3321     ldr(tmp1, Address(buf, 48));
3322     crc32cx(crc, crc, tmp0);
3323     ldr(tmp2, Address(buf, 56));
3324     crc32cx(crc, crc, tmp1);
3325     ldr(tmp3, Address(pre(buf, 64)));
3326 
3327     b(CRC_by64_loop);
3328 
3329     align(CodeEntryAlignment);
3330   BIND(CRC_by64_loop);
3331     subs(len, len, 64);
3332     crc32cx(crc, crc, tmp2);
3333     ldr(tmp0, Address(buf, 8));
3334     crc32cx(crc, crc, tmp3);
3335     ldr(tmp1, Address(buf, 16));
3336     crc32cx(crc, crc, tmp0);
3337     ldr(tmp2, Address(buf, 24));
3338     crc32cx(crc, crc, tmp1);
3339     ldr(tmp3, Address(buf, 32));
3340     crc32cx(crc, crc, tmp2);
3341     ldr(tmp0, Address(buf, 40));
3342     crc32cx(crc, crc, tmp3);
3343     ldr(tmp1, Address(buf, 48));
3344     crc32cx(crc, crc, tmp0);
3345     ldr(tmp2, Address(buf, 56));
3346     crc32cx(crc, crc, tmp1);
3347     ldr(tmp3, Address(pre(buf, 64)));
3348     br(Assembler::GE, CRC_by64_loop);
3349 
3350     // post-loop
3351     crc32cx(crc, crc, tmp2);
3352     crc32cx(crc, crc, tmp3);
3353 
3354     sub(len, len, 64);
3355     add(buf, buf, 8);
3356     cmn(len, 128);
3357     br(Assembler::NE, CRC_less64);
3358   BIND(L_exit);
3359 }
3360 
3361 /**
3362  * @param crc   register containing existing CRC (32-bit)
3363  * @param buf   register pointing to input byte buffer (byte*)
3364  * @param len   register containing number of bytes
3365  * @param table register that will contain address of CRC table
3366  * @param tmp   scratch register
3367  */
3368 void MacroAssembler::kernel_crc32c(Register crc, Register buf, Register len,
3369         Register table0, Register table1, Register table2, Register table3,
3370         Register tmp, Register tmp2, Register tmp3) {
3371   kernel_crc32c_using_crc32c(crc, buf, len, table0, table1, table2, table3);
3372 }
3373 
3374 
3375 SkipIfEqual::SkipIfEqual(
3376     MacroAssembler* masm, const bool* flag_addr, bool value) {
3377   _masm = masm;
3378   unsigned long offset;
3379   _masm->adrp(rscratch1, ExternalAddress((address)flag_addr), offset);
3380   _masm->ldrb(rscratch1, Address(rscratch1, offset));
3381   _masm->cbzw(rscratch1, _label);
3382 }
3383 
3384 SkipIfEqual::~SkipIfEqual() {
3385   _masm->bind(_label);
3386 }
3387 
3388 void MacroAssembler::addptr(const Address &dst, int32_t src) {
3389   Address adr;
3390   switch(dst.getMode()) {
3391   case Address::base_plus_offset:
3392     // This is the expected mode, although we allow all the other
3393     // forms below.
3394     adr = form_address(rscratch2, dst.base(), dst.offset(), LogBytesPerWord);
3395     break;
3396   default:
3397     lea(rscratch2, dst);
3398     adr = Address(rscratch2);
3399     break;
3400   }
3401   ldr(rscratch1, adr);
3402   add(rscratch1, rscratch1, src);
3403   str(rscratch1, adr);
3404 }
3405 
3406 void MacroAssembler::cmpptr(Register src1, Address src2) {
3407   unsigned long offset;
3408   adrp(rscratch1, src2, offset);
3409   ldr(rscratch1, Address(rscratch1, offset));
3410   cmp(src1, rscratch1);
3411 }
3412 
3413 void MacroAssembler::store_check(Register obj, Address dst) {
3414   store_check(obj);
3415 }
3416 
3417 void MacroAssembler::store_check(Register obj) {
3418   // Does a store check for the oop in register obj. The content of
3419   // register obj is destroyed afterwards.
3420 
3421   BarrierSet* bs = Universe::heap()->barrier_set();
3422   assert(bs->kind() == BarrierSet::CardTableForRS ||
3423          bs->kind() == BarrierSet::CardTableExtension,
3424          "Wrong barrier set kind");
3425 
3426   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
3427   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
3428 
3429   lsr(obj, obj, CardTableModRefBS::card_shift);
3430 
3431   assert(CardTableModRefBS::dirty_card_val() == 0, "must be");
3432 
3433   load_byte_map_base(rscratch1);
3434 
3435   if (UseCondCardMark) {
3436     Label L_already_dirty;
3437     membar(StoreLoad);
3438     ldrb(rscratch2,  Address(obj, rscratch1));
3439     cbz(rscratch2, L_already_dirty);
3440     strb(zr, Address(obj, rscratch1));
3441     bind(L_already_dirty);
3442   } else {
3443     if (UseConcMarkSweepGC && CMSPrecleaningEnabled) {
3444       membar(StoreStore);
3445     }
3446     strb(zr, Address(obj, rscratch1));
3447   }
3448 }
3449 
3450 void MacroAssembler::load_klass(Register dst, Register src) {
3451   if (UseCompressedClassPointers) {
3452     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3453     decode_klass_not_null(dst);
3454   } else {
3455     ldr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3456   }
3457 }
3458 
3459 // ((OopHandle)result).resolve();
3460 void MacroAssembler::resolve_oop_handle(Register result) {
3461   // OopHandle::resolve is an indirection.
3462   ldr(result, Address(result, 0));
3463 }
3464 
3465 void MacroAssembler::load_mirror(Register dst, Register method) {
3466   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
3467   ldr(dst, Address(rmethod, Method::const_offset()));
3468   ldr(dst, Address(dst, ConstMethod::constants_offset()));
3469   ldr(dst, Address(dst, ConstantPool::pool_holder_offset_in_bytes()));
3470   ldr(dst, Address(dst, mirror_offset));
3471   resolve_oop_handle(dst);
3472 }
3473 
3474 void MacroAssembler::cmp_klass(Register oop, Register trial_klass, Register tmp) {
3475   if (UseCompressedClassPointers) {
3476     ldrw(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
3477     if (Universe::narrow_klass_base() == NULL) {
3478       cmp(trial_klass, tmp, LSL, Universe::narrow_klass_shift());
3479       return;
3480     } else if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3481                && Universe::narrow_klass_shift() == 0) {
3482       // Only the bottom 32 bits matter
3483       cmpw(trial_klass, tmp);
3484       return;
3485     }
3486     decode_klass_not_null(tmp);
3487   } else {
3488     ldr(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
3489   }
3490   cmp(trial_klass, tmp);
3491 }
3492 
3493 void MacroAssembler::load_prototype_header(Register dst, Register src) {
3494   load_klass(dst, src);
3495   ldr(dst, Address(dst, Klass::prototype_header_offset()));
3496 }
3497 
3498 void MacroAssembler::store_klass(Register dst, Register src) {
3499   // FIXME: Should this be a store release?  concurrent gcs assumes
3500   // klass length is valid if klass field is not null.
3501   if (UseCompressedClassPointers) {
3502     encode_klass_not_null(src);
3503     strw(src, Address(dst, oopDesc::klass_offset_in_bytes()));
3504   } else {
3505     str(src, Address(dst, oopDesc::klass_offset_in_bytes()));
3506   }
3507 }
3508 
3509 void MacroAssembler::store_klass_gap(Register dst, Register src) {
3510   if (UseCompressedClassPointers) {
3511     // Store to klass gap in destination
3512     strw(src, Address(dst, oopDesc::klass_gap_offset_in_bytes()));
3513   }
3514 }
3515 
3516 // Algorithm must match oop.inline.hpp encode_heap_oop.
3517 void MacroAssembler::encode_heap_oop(Register d, Register s) {
3518 #ifdef ASSERT
3519   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
3520 #endif
3521   verify_oop(s, "broken oop in encode_heap_oop");
3522   if (Universe::narrow_oop_base() == NULL) {
3523     if (Universe::narrow_oop_shift() != 0) {
3524       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3525       lsr(d, s, LogMinObjAlignmentInBytes);
3526     } else {
3527       mov(d, s);
3528     }
3529   } else {
3530     subs(d, s, rheapbase);
3531     csel(d, d, zr, Assembler::HS);
3532     lsr(d, d, LogMinObjAlignmentInBytes);
3533 
3534     /*  Old algorithm: is this any worse?
3535     Label nonnull;
3536     cbnz(r, nonnull);
3537     sub(r, r, rheapbase);
3538     bind(nonnull);
3539     lsr(r, r, LogMinObjAlignmentInBytes);
3540     */
3541   }
3542 }
3543 
3544 void MacroAssembler::encode_heap_oop_not_null(Register r) {
3545 #ifdef ASSERT
3546   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
3547   if (CheckCompressedOops) {
3548     Label ok;
3549     cbnz(r, ok);
3550     stop("null oop passed to encode_heap_oop_not_null");
3551     bind(ok);
3552   }
3553 #endif
3554   verify_oop(r, "broken oop in encode_heap_oop_not_null");
3555   if (Universe::narrow_oop_base() != NULL) {
3556     sub(r, r, rheapbase);
3557   }
3558   if (Universe::narrow_oop_shift() != 0) {
3559     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3560     lsr(r, r, LogMinObjAlignmentInBytes);
3561   }
3562 }
3563 
3564 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
3565 #ifdef ASSERT
3566   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
3567   if (CheckCompressedOops) {
3568     Label ok;
3569     cbnz(src, ok);
3570     stop("null oop passed to encode_heap_oop_not_null2");
3571     bind(ok);
3572   }
3573 #endif
3574   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
3575 
3576   Register data = src;
3577   if (Universe::narrow_oop_base() != NULL) {
3578     sub(dst, src, rheapbase);
3579     data = dst;
3580   }
3581   if (Universe::narrow_oop_shift() != 0) {
3582     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3583     lsr(dst, data, LogMinObjAlignmentInBytes);
3584     data = dst;
3585   }
3586   if (data == src)
3587     mov(dst, src);
3588 }
3589 
3590 void  MacroAssembler::decode_heap_oop(Register d, Register s) {
3591 #ifdef ASSERT
3592   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
3593 #endif
3594   if (Universe::narrow_oop_base() == NULL) {
3595     if (Universe::narrow_oop_shift() != 0 || d != s) {
3596       lsl(d, s, Universe::narrow_oop_shift());
3597     }
3598   } else {
3599     Label done;
3600     if (d != s)
3601       mov(d, s);
3602     cbz(s, done);
3603     add(d, rheapbase, s, Assembler::LSL, LogMinObjAlignmentInBytes);
3604     bind(done);
3605   }
3606   verify_oop(d, "broken oop in decode_heap_oop");
3607 }
3608 
3609 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
3610   assert (UseCompressedOops, "should only be used for compressed headers");
3611   assert (Universe::heap() != NULL, "java heap should be initialized");
3612   // Cannot assert, unverified entry point counts instructions (see .ad file)
3613   // vtableStubs also counts instructions in pd_code_size_limit.
3614   // Also do not verify_oop as this is called by verify_oop.
3615   if (Universe::narrow_oop_shift() != 0) {
3616     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3617     if (Universe::narrow_oop_base() != NULL) {
3618       add(r, rheapbase, r, Assembler::LSL, LogMinObjAlignmentInBytes);
3619     } else {
3620       add(r, zr, r, Assembler::LSL, LogMinObjAlignmentInBytes);
3621     }
3622   } else {
3623     assert (Universe::narrow_oop_base() == NULL, "sanity");
3624   }
3625 }
3626 
3627 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
3628   assert (UseCompressedOops, "should only be used for compressed headers");
3629   assert (Universe::heap() != NULL, "java heap should be initialized");
3630   // Cannot assert, unverified entry point counts instructions (see .ad file)
3631   // vtableStubs also counts instructions in pd_code_size_limit.
3632   // Also do not verify_oop as this is called by verify_oop.
3633   if (Universe::narrow_oop_shift() != 0) {
3634     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3635     if (Universe::narrow_oop_base() != NULL) {
3636       add(dst, rheapbase, src, Assembler::LSL, LogMinObjAlignmentInBytes);
3637     } else {
3638       add(dst, zr, src, Assembler::LSL, LogMinObjAlignmentInBytes);
3639     }
3640   } else {
3641     assert (Universe::narrow_oop_base() == NULL, "sanity");
3642     if (dst != src) {
3643       mov(dst, src);
3644     }
3645   }
3646 }
3647 
3648 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
3649   if (Universe::narrow_klass_base() == NULL) {
3650     if (Universe::narrow_klass_shift() != 0) {
3651       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3652       lsr(dst, src, LogKlassAlignmentInBytes);
3653     } else {
3654       if (dst != src) mov(dst, src);
3655     }
3656     return;
3657   }
3658 
3659   if (use_XOR_for_compressed_class_base) {
3660     if (Universe::narrow_klass_shift() != 0) {
3661       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3662       lsr(dst, dst, LogKlassAlignmentInBytes);
3663     } else {
3664       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3665     }
3666     return;
3667   }
3668 
3669   if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3670       && Universe::narrow_klass_shift() == 0) {
3671     movw(dst, src);
3672     return;
3673   }
3674 
3675 #ifdef ASSERT
3676   verify_heapbase("MacroAssembler::encode_klass_not_null2: heap base corrupted?");
3677 #endif
3678 
3679   Register rbase = dst;
3680   if (dst == src) rbase = rheapbase;
3681   mov(rbase, (uint64_t)Universe::narrow_klass_base());
3682   sub(dst, src, rbase);
3683   if (Universe::narrow_klass_shift() != 0) {
3684     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3685     lsr(dst, dst, LogKlassAlignmentInBytes);
3686   }
3687   if (dst == src) reinit_heapbase();
3688 }
3689 
3690 void MacroAssembler::encode_klass_not_null(Register r) {
3691   encode_klass_not_null(r, r);
3692 }
3693 
3694 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
3695   Register rbase = dst;
3696   assert (UseCompressedClassPointers, "should only be used for compressed headers");
3697 
3698   if (Universe::narrow_klass_base() == NULL) {
3699     if (Universe::narrow_klass_shift() != 0) {
3700       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3701       lsl(dst, src, LogKlassAlignmentInBytes);
3702     } else {
3703       if (dst != src) mov(dst, src);
3704     }
3705     return;
3706   }
3707 
3708   if (use_XOR_for_compressed_class_base) {
3709     if (Universe::narrow_klass_shift() != 0) {
3710       lsl(dst, src, LogKlassAlignmentInBytes);
3711       eor(dst, dst, (uint64_t)Universe::narrow_klass_base());
3712     } else {
3713       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3714     }
3715     return;
3716   }
3717 
3718   if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3719       && Universe::narrow_klass_shift() == 0) {
3720     if (dst != src)
3721       movw(dst, src);
3722     movk(dst, (uint64_t)Universe::narrow_klass_base() >> 32, 32);
3723     return;
3724   }
3725 
3726   // Cannot assert, unverified entry point counts instructions (see .ad file)
3727   // vtableStubs also counts instructions in pd_code_size_limit.
3728   // Also do not verify_oop as this is called by verify_oop.
3729   if (dst == src) rbase = rheapbase;
3730   mov(rbase, (uint64_t)Universe::narrow_klass_base());
3731   if (Universe::narrow_klass_shift() != 0) {
3732     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3733     add(dst, rbase, src, Assembler::LSL, LogKlassAlignmentInBytes);
3734   } else {
3735     add(dst, rbase, src);
3736   }
3737   if (dst == src) reinit_heapbase();
3738 }
3739 
3740 void  MacroAssembler::decode_klass_not_null(Register r) {
3741   decode_klass_not_null(r, r);
3742 }
3743 
3744 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
3745   assert (UseCompressedOops, "should only be used for compressed oops");
3746   assert (Universe::heap() != NULL, "java heap should be initialized");
3747   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
3748 
3749   int oop_index = oop_recorder()->find_index(obj);
3750   assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "should be real oop");
3751 
3752   InstructionMark im(this);
3753   RelocationHolder rspec = oop_Relocation::spec(oop_index);
3754   code_section()->relocate(inst_mark(), rspec);
3755   movz(dst, 0xDEAD, 16);
3756   movk(dst, 0xBEEF);
3757 }
3758 
3759 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
3760   assert (UseCompressedClassPointers, "should only be used for compressed headers");
3761   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
3762   int index = oop_recorder()->find_index(k);
3763   assert(! Universe::heap()->is_in_reserved(k), "should not be an oop");
3764 
3765   InstructionMark im(this);
3766   RelocationHolder rspec = metadata_Relocation::spec(index);
3767   code_section()->relocate(inst_mark(), rspec);
3768   narrowKlass nk = Klass::encode_klass(k);
3769   movz(dst, (nk >> 16), 16);
3770   movk(dst, nk & 0xffff);
3771 }
3772 
3773 void MacroAssembler::load_heap_oop(Register dst, Address src)
3774 {
3775   if (UseCompressedOops) {
3776     ldrw(dst, src);
3777     decode_heap_oop(dst);
3778   } else {
3779     ldr(dst, src);
3780   }
3781 }
3782 
3783 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src)
3784 {
3785   if (UseCompressedOops) {
3786     ldrw(dst, src);
3787     decode_heap_oop_not_null(dst);
3788   } else {
3789     ldr(dst, src);
3790   }
3791 }
3792 
3793 void MacroAssembler::store_heap_oop(Address dst, Register src) {
3794   if (UseCompressedOops) {
3795     assert(!dst.uses(src), "not enough registers");
3796     encode_heap_oop(src);
3797     strw(src, dst);
3798   } else
3799     str(src, dst);
3800 }
3801 
3802 // Used for storing NULLs.
3803 void MacroAssembler::store_heap_oop_null(Address dst) {
3804   if (UseCompressedOops) {
3805     strw(zr, dst);
3806   } else
3807     str(zr, dst);
3808 }
3809 
3810 #if INCLUDE_ALL_GCS
3811 /*
3812  * g1_write_barrier_pre -- G1GC pre-write barrier for store of new_val at
3813  * store_addr.
3814  *
3815  * Allocates rscratch1
3816  */
3817 void MacroAssembler::g1_write_barrier_pre(Register obj,
3818                                           Register pre_val,
3819                                           Register thread,
3820                                           Register tmp,
3821                                           bool tosca_live,
3822                                           bool expand_call) {
3823   // If expand_call is true then we expand the call_VM_leaf macro
3824   // directly to skip generating the check by
3825   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
3826 
3827   assert(thread == rthread, "must be");
3828 
3829   Label done;
3830   Label runtime;
3831 
3832   assert_different_registers(obj, pre_val, tmp, rscratch1);
3833   assert(pre_val != noreg &&  tmp != noreg, "expecting a register");
3834 
3835   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
3836                                        SATBMarkQueue::byte_offset_of_active()));
3837   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
3838                                        SATBMarkQueue::byte_offset_of_index()));
3839   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
3840                                        SATBMarkQueue::byte_offset_of_buf()));
3841 
3842 
3843   // Is marking active?
3844   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
3845     ldrw(tmp, in_progress);
3846   } else {
3847     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
3848     ldrb(tmp, in_progress);
3849   }
3850   cbzw(tmp, done);
3851 
3852   // Do we need to load the previous value?
3853   if (obj != noreg) {
3854     load_heap_oop(pre_val, Address(obj, 0));
3855   }
3856 
3857   // Is the previous value null?
3858   cbz(pre_val, done);
3859 
3860   // Can we store original value in the thread's buffer?
3861   // Is index == 0?
3862   // (The index field is typed as size_t.)
3863 
3864   ldr(tmp, index);                      // tmp := *index_adr
3865   cbz(tmp, runtime);                    // tmp == 0?
3866                                         // If yes, goto runtime
3867 
3868   sub(tmp, tmp, wordSize);              // tmp := tmp - wordSize
3869   str(tmp, index);                      // *index_adr := tmp
3870   ldr(rscratch1, buffer);
3871   add(tmp, tmp, rscratch1);             // tmp := tmp + *buffer_adr
3872 
3873   // Record the previous value
3874   str(pre_val, Address(tmp, 0));
3875   b(done);
3876 
3877   bind(runtime);
3878   // save the live input values
3879   push(r0->bit(tosca_live) | obj->bit(obj != noreg) | pre_val->bit(true), sp);
3880 
3881   // Calling the runtime using the regular call_VM_leaf mechanism generates
3882   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
3883   // that checks that the *(rfp+frame::interpreter_frame_last_sp) == NULL.
3884   //
3885   // If we care generating the pre-barrier without a frame (e.g. in the
3886   // intrinsified Reference.get() routine) then ebp might be pointing to
3887   // the caller frame and so this check will most likely fail at runtime.
3888   //
3889   // Expanding the call directly bypasses the generation of the check.
3890   // So when we do not have have a full interpreter frame on the stack
3891   // expand_call should be passed true.
3892 
3893   if (expand_call) {
3894     assert(pre_val != c_rarg1, "smashed arg");
3895     pass_arg1(this, thread);
3896     pass_arg0(this, pre_val);
3897     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
3898   } else {
3899     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
3900   }
3901 
3902   pop(r0->bit(tosca_live) | obj->bit(obj != noreg) | pre_val->bit(true), sp);
3903 
3904   bind(done);
3905 }
3906 
3907 /*
3908  * g1_write_barrier_post -- G1GC post-write barrier for store of new_val at
3909  * store_addr
3910  *
3911  * Allocates rscratch1
3912  */
3913 void MacroAssembler::g1_write_barrier_post(Register store_addr,
3914                                            Register new_val,
3915                                            Register thread,
3916                                            Register tmp,
3917                                            Register tmp2) {
3918   assert(thread == rthread, "must be");
3919   assert_different_registers(store_addr, new_val, thread, tmp, tmp2,
3920                              rscratch1);
3921   assert(store_addr != noreg && new_val != noreg && tmp != noreg
3922          && tmp2 != noreg, "expecting a register");
3923 
3924   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
3925                                        DirtyCardQueue::byte_offset_of_index()));
3926   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
3927                                        DirtyCardQueue::byte_offset_of_buf()));
3928 
3929   BarrierSet* bs = Universe::heap()->barrier_set();
3930   CardTableModRefBS* ct = (CardTableModRefBS*)bs;
3931   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
3932 
3933   Label done;
3934   Label runtime;
3935 
3936   // Does store cross heap regions?
3937 
3938   eor(tmp, store_addr, new_val);
3939   lsr(tmp, tmp, HeapRegion::LogOfHRGrainBytes);
3940   cbz(tmp, done);
3941 
3942   // crosses regions, storing NULL?
3943 
3944   cbz(new_val, done);
3945 
3946   // storing region crossing non-NULL, is card already dirty?
3947 
3948   ExternalAddress cardtable((address) ct->byte_map_base);
3949   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
3950   const Register card_addr = tmp;
3951 
3952   lsr(card_addr, store_addr, CardTableModRefBS::card_shift);
3953 
3954   // get the address of the card
3955   load_byte_map_base(tmp2);
3956   add(card_addr, card_addr, tmp2);
3957   ldrb(tmp2, Address(card_addr));
3958   cmpw(tmp2, (int)G1SATBCardTableModRefBS::g1_young_card_val());
3959   br(Assembler::EQ, done);
3960 
3961   assert((int)CardTableModRefBS::dirty_card_val() == 0, "must be 0");
3962 
3963   membar(Assembler::StoreLoad);
3964 
3965   ldrb(tmp2, Address(card_addr));
3966   cbzw(tmp2, done);
3967 
3968   // storing a region crossing, non-NULL oop, card is clean.
3969   // dirty card and log.
3970 
3971   strb(zr, Address(card_addr));
3972 
3973   ldr(rscratch1, queue_index);
3974   cbz(rscratch1, runtime);
3975   sub(rscratch1, rscratch1, wordSize);
3976   str(rscratch1, queue_index);
3977 
3978   ldr(tmp2, buffer);
3979   str(card_addr, Address(tmp2, rscratch1));
3980   b(done);
3981 
3982   bind(runtime);
3983   // save the live input values
3984   push(store_addr->bit(true) | new_val->bit(true), sp);
3985   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
3986   pop(store_addr->bit(true) | new_val->bit(true), sp);
3987 
3988   bind(done);
3989 }
3990 
3991 #endif // INCLUDE_ALL_GCS
3992 
3993 Address MacroAssembler::allocate_metadata_address(Metadata* obj) {
3994   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
3995   int index = oop_recorder()->allocate_metadata_index(obj);
3996   RelocationHolder rspec = metadata_Relocation::spec(index);
3997   return Address((address)obj, rspec);
3998 }
3999 
4000 // Move an oop into a register.  immediate is true if we want
4001 // immediate instrcutions, i.e. we are not going to patch this
4002 // instruction while the code is being executed by another thread.  In
4003 // that case we can use move immediates rather than the constant pool.
4004 void MacroAssembler::movoop(Register dst, jobject obj, bool immediate) {
4005   int oop_index;
4006   if (obj == NULL) {
4007     oop_index = oop_recorder()->allocate_oop_index(obj);
4008   } else {
4009     oop_index = oop_recorder()->find_index(obj);
4010     assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "should be real oop");
4011   }
4012   RelocationHolder rspec = oop_Relocation::spec(oop_index);
4013   if (! immediate) {
4014     address dummy = address(uintptr_t(pc()) & -wordSize); // A nearby aligned address
4015     ldr_constant(dst, Address(dummy, rspec));
4016   } else
4017     mov(dst, Address((address)obj, rspec));
4018 }
4019 
4020 // Move a metadata address into a register.
4021 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
4022   int oop_index;
4023   if (obj == NULL) {
4024     oop_index = oop_recorder()->allocate_metadata_index(obj);
4025   } else {
4026     oop_index = oop_recorder()->find_index(obj);
4027   }
4028   RelocationHolder rspec = metadata_Relocation::spec(oop_index);
4029   mov(dst, Address((address)obj, rspec));
4030 }
4031 
4032 Address MacroAssembler::constant_oop_address(jobject obj) {
4033   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
4034   assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "not an oop");
4035   int oop_index = oop_recorder()->find_index(obj);
4036   return Address((address)obj, oop_Relocation::spec(oop_index));
4037 }
4038 
4039 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
4040 void MacroAssembler::tlab_allocate(Register obj,
4041                                    Register var_size_in_bytes,
4042                                    int con_size_in_bytes,
4043                                    Register t1,
4044                                    Register t2,
4045                                    Label& slow_case) {
4046   assert_different_registers(obj, t2);
4047   assert_different_registers(obj, var_size_in_bytes);
4048   Register end = t2;
4049 
4050   // verify_tlab();
4051 
4052   ldr(obj, Address(rthread, JavaThread::tlab_top_offset()));
4053   if (var_size_in_bytes == noreg) {
4054     lea(end, Address(obj, con_size_in_bytes));
4055   } else {
4056     lea(end, Address(obj, var_size_in_bytes));
4057   }
4058   ldr(rscratch1, Address(rthread, JavaThread::tlab_end_offset()));
4059   cmp(end, rscratch1);
4060   br(Assembler::HI, slow_case);
4061 
4062   // update the tlab top pointer
4063   str(end, Address(rthread, JavaThread::tlab_top_offset()));
4064 
4065   // recover var_size_in_bytes if necessary
4066   if (var_size_in_bytes == end) {
4067     sub(var_size_in_bytes, var_size_in_bytes, obj);
4068   }
4069   // verify_tlab();
4070 }
4071 
4072 // Preserves r19, and r3.
4073 Register MacroAssembler::tlab_refill(Label& retry,
4074                                      Label& try_eden,
4075                                      Label& slow_case) {
4076   Register top = r0;
4077   Register t1  = r2;
4078   Register t2  = r4;
4079   assert_different_registers(top, rthread, t1, t2, /* preserve: */ r19, r3);
4080   Label do_refill, discard_tlab;
4081 
4082   if (!Universe::heap()->supports_inline_contig_alloc()) {
4083     // No allocation in the shared eden.
4084     b(slow_case);
4085   }
4086 
4087   ldr(top, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4088   ldr(t1,  Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
4089 
4090   // calculate amount of free space
4091   sub(t1, t1, top);
4092   lsr(t1, t1, LogHeapWordSize);
4093 
4094   // Retain tlab and allocate object in shared space if
4095   // the amount free in the tlab is too large to discard.
4096 
4097   ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
4098   cmp(t1, rscratch1);
4099   br(Assembler::LE, discard_tlab);
4100 
4101   // Retain
4102   // ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
4103   mov(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
4104   add(rscratch1, rscratch1, t2);
4105   str(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
4106 
4107   if (TLABStats) {
4108     // increment number of slow_allocations
4109     addmw(Address(rthread, in_bytes(JavaThread::tlab_slow_allocations_offset())),
4110          1, rscratch1);
4111   }
4112   b(try_eden);
4113 
4114   bind(discard_tlab);
4115   if (TLABStats) {
4116     // increment number of refills
4117     addmw(Address(rthread, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1,
4118          rscratch1);
4119     // accumulate wastage -- t1 is amount free in tlab
4120     addmw(Address(rthread, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1,
4121          rscratch1);
4122   }
4123 
4124   // if tlab is currently allocated (top or end != null) then
4125   // fill [top, end + alignment_reserve) with array object
4126   cbz(top, do_refill);
4127 
4128   // set up the mark word
4129   mov(rscratch1, (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
4130   str(rscratch1, Address(top, oopDesc::mark_offset_in_bytes()));
4131   // set the length to the remaining space
4132   sub(t1, t1, typeArrayOopDesc::header_size(T_INT));
4133   add(t1, t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
4134   lsl(t1, t1, log2_intptr(HeapWordSize/sizeof(jint)));
4135   strw(t1, Address(top, arrayOopDesc::length_offset_in_bytes()));
4136   // set klass to intArrayKlass
4137   {
4138     unsigned long offset;
4139     // dubious reloc why not an oop reloc?
4140     adrp(rscratch1, ExternalAddress((address)Universe::intArrayKlassObj_addr()),
4141          offset);
4142     ldr(t1, Address(rscratch1, offset));
4143   }
4144   // store klass last.  concurrent gcs assumes klass length is valid if
4145   // klass field is not null.
4146   store_klass(top, t1);
4147 
4148   mov(t1, top);
4149   ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
4150   sub(t1, t1, rscratch1);
4151   incr_allocated_bytes(rthread, t1, 0, rscratch1);
4152 
4153   // refill the tlab with an eden allocation
4154   bind(do_refill);
4155   ldr(t1, Address(rthread, in_bytes(JavaThread::tlab_size_offset())));
4156   lsl(t1, t1, LogHeapWordSize);
4157   // allocate new tlab, address returned in top
4158   eden_allocate(top, t1, 0, t2, slow_case);
4159 
4160   // Check that t1 was preserved in eden_allocate.
4161 #ifdef ASSERT
4162   if (UseTLAB) {
4163     Label ok;
4164     Register tsize = r4;
4165     assert_different_registers(tsize, rthread, t1);
4166     str(tsize, Address(pre(sp, -16)));
4167     ldr(tsize, Address(rthread, in_bytes(JavaThread::tlab_size_offset())));
4168     lsl(tsize, tsize, LogHeapWordSize);
4169     cmp(t1, tsize);
4170     br(Assembler::EQ, ok);
4171     STOP("assert(t1 != tlab size)");
4172     should_not_reach_here();
4173 
4174     bind(ok);
4175     ldr(tsize, Address(post(sp, 16)));
4176   }
4177 #endif
4178   str(top, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
4179   str(top, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4180   add(top, top, t1);
4181   sub(top, top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
4182   str(top, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
4183 
4184   if (ZeroTLAB) {
4185     // This is a fast TLAB refill, therefore the GC is not notified of it.
4186     // So compiled code must fill the new TLAB with zeroes.
4187     ldr(top, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
4188     zero_memory(top,t1,t2);
4189   }
4190 
4191   verify_tlab();
4192   b(retry);
4193 
4194   return rthread; // for use by caller
4195 }
4196 
4197 // Zero words; len is in bytes
4198 // Destroys all registers except addr
4199 // len must be a nonzero multiple of wordSize
4200 void MacroAssembler::zero_memory(Register addr, Register len, Register t1) {
4201   assert_different_registers(addr, len, t1, rscratch1, rscratch2);
4202 
4203 #ifdef ASSERT
4204   { Label L;
4205     tst(len, BytesPerWord - 1);
4206     br(Assembler::EQ, L);
4207     stop("len is not a multiple of BytesPerWord");
4208     bind(L);
4209   }
4210 #endif
4211 
4212 #ifndef PRODUCT
4213   block_comment("zero memory");
4214 #endif
4215 
4216   Label loop;
4217   Label entry;
4218 
4219 //  Algorithm:
4220 //
4221 //    scratch1 = cnt & 7;
4222 //    cnt -= scratch1;
4223 //    p += scratch1;
4224 //    switch (scratch1) {
4225 //      do {
4226 //        cnt -= 8;
4227 //          p[-8] = 0;
4228 //        case 7:
4229 //          p[-7] = 0;
4230 //        case 6:
4231 //          p[-6] = 0;
4232 //          // ...
4233 //        case 1:
4234 //          p[-1] = 0;
4235 //        case 0:
4236 //          p += 8;
4237 //      } while (cnt);
4238 //    }
4239 
4240   const int unroll = 8; // Number of str(zr) instructions we'll unroll
4241 
4242   lsr(len, len, LogBytesPerWord);
4243   andr(rscratch1, len, unroll - 1);  // tmp1 = cnt % unroll
4244   sub(len, len, rscratch1);      // cnt -= unroll
4245   // t1 always points to the end of the region we're about to zero
4246   add(t1, addr, rscratch1, Assembler::LSL, LogBytesPerWord);
4247   adr(rscratch2, entry);
4248   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 2);
4249   br(rscratch2);
4250   bind(loop);
4251   sub(len, len, unroll);
4252   for (int i = -unroll; i < 0; i++)
4253     str(zr, Address(t1, i * wordSize));
4254   bind(entry);
4255   add(t1, t1, unroll * wordSize);
4256   cbnz(len, loop);
4257 }
4258 
4259 // Defines obj, preserves var_size_in_bytes
4260 void MacroAssembler::eden_allocate(Register obj,
4261                                    Register var_size_in_bytes,
4262                                    int con_size_in_bytes,
4263                                    Register t1,
4264                                    Label& slow_case) {
4265   assert_different_registers(obj, var_size_in_bytes, t1);
4266   if (!Universe::heap()->supports_inline_contig_alloc()) {
4267     b(slow_case);
4268   } else {
4269     Register end = t1;
4270     Register heap_end = rscratch2;
4271     Label retry;
4272     bind(retry);
4273     {
4274       unsigned long offset;
4275       adrp(rscratch1, ExternalAddress((address) Universe::heap()->end_addr()), offset);
4276       ldr(heap_end, Address(rscratch1, offset));
4277     }
4278 
4279     ExternalAddress heap_top((address) Universe::heap()->top_addr());
4280 
4281     // Get the current top of the heap
4282     {
4283       unsigned long offset;
4284       adrp(rscratch1, heap_top, offset);
4285       // Use add() here after ARDP, rather than lea().
4286       // lea() does not generate anything if its offset is zero.
4287       // However, relocs expect to find either an ADD or a load/store
4288       // insn after an ADRP.  add() always generates an ADD insn, even
4289       // for add(Rn, Rn, 0).
4290       add(rscratch1, rscratch1, offset);
4291       ldaxr(obj, rscratch1);
4292     }
4293 
4294     // Adjust it my the size of our new object
4295     if (var_size_in_bytes == noreg) {
4296       lea(end, Address(obj, con_size_in_bytes));
4297     } else {
4298       lea(end, Address(obj, var_size_in_bytes));
4299     }
4300 
4301     // if end < obj then we wrapped around high memory
4302     cmp(end, obj);
4303     br(Assembler::LO, slow_case);
4304 
4305     cmp(end, heap_end);
4306     br(Assembler::HI, slow_case);
4307 
4308     // If heap_top hasn't been changed by some other thread, update it.
4309     stlxr(rscratch2, end, rscratch1);
4310     cbnzw(rscratch2, retry);
4311   }
4312 }
4313 
4314 void MacroAssembler::verify_tlab() {
4315 #ifdef ASSERT
4316   if (UseTLAB && VerifyOops) {
4317     Label next, ok;
4318 
4319     stp(rscratch2, rscratch1, Address(pre(sp, -16)));
4320 
4321     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4322     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
4323     cmp(rscratch2, rscratch1);
4324     br(Assembler::HS, next);
4325     STOP("assert(top >= start)");
4326     should_not_reach_here();
4327 
4328     bind(next);
4329     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
4330     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4331     cmp(rscratch2, rscratch1);
4332     br(Assembler::HS, ok);
4333     STOP("assert(top <= end)");
4334     should_not_reach_here();
4335 
4336     bind(ok);
4337     ldp(rscratch2, rscratch1, Address(post(sp, 16)));
4338   }
4339 #endif
4340 }
4341 
4342 // Writes to stack successive pages until offset reached to check for
4343 // stack overflow + shadow pages.  This clobbers tmp.
4344 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
4345   assert_different_registers(tmp, size, rscratch1);
4346   mov(tmp, sp);
4347   // Bang stack for total size given plus shadow page size.
4348   // Bang one page at a time because large size can bang beyond yellow and
4349   // red zones.
4350   Label loop;
4351   mov(rscratch1, os::vm_page_size());
4352   bind(loop);
4353   lea(tmp, Address(tmp, -os::vm_page_size()));
4354   subsw(size, size, rscratch1);
4355   str(size, Address(tmp));
4356   br(Assembler::GT, loop);
4357 
4358   // Bang down shadow pages too.
4359   // At this point, (tmp-0) is the last address touched, so don't
4360   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
4361   // was post-decremented.)  Skip this address by starting at i=1, and
4362   // touch a few more pages below.  N.B.  It is important to touch all
4363   // the way down to and including i=StackShadowPages.
4364   for (int i = 0; i < (int)(JavaThread::stack_shadow_zone_size() / os::vm_page_size()) - 1; i++) {
4365     // this could be any sized move but this is can be a debugging crumb
4366     // so the bigger the better.
4367     lea(tmp, Address(tmp, -os::vm_page_size()));
4368     str(size, Address(tmp));
4369   }
4370 }
4371 
4372 
4373 // Move the address of the polling page into dest.
4374 void MacroAssembler::get_polling_page(Register dest, address page, relocInfo::relocType rtype) {
4375   if (SafepointMechanism::uses_thread_local_poll()) {
4376     ldr(dest, Address(rthread, Thread::polling_page_offset()));
4377   } else {
4378     unsigned long off;
4379     adrp(dest, Address(page, rtype), off);
4380     assert(off == 0, "polling page must be page aligned");
4381   }
4382 }
4383 
4384 // Move the address of the polling page into r, then read the polling
4385 // page.
4386 address MacroAssembler::read_polling_page(Register r, address page, relocInfo::relocType rtype) {
4387   get_polling_page(r, page, rtype);
4388   return read_polling_page(r, rtype);
4389 }
4390 
4391 // Read the polling page.  The address of the polling page must
4392 // already be in r.
4393 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
4394   InstructionMark im(this);
4395   code_section()->relocate(inst_mark(), rtype);
4396   ldrw(zr, Address(r, 0));
4397   return inst_mark();
4398 }
4399 
4400 void MacroAssembler::adrp(Register reg1, const Address &dest, unsigned long &byte_offset) {
4401   relocInfo::relocType rtype = dest.rspec().reloc()->type();
4402   unsigned long low_page = (unsigned long)CodeCache::low_bound() >> 12;
4403   unsigned long high_page = (unsigned long)(CodeCache::high_bound()-1) >> 12;
4404   unsigned long dest_page = (unsigned long)dest.target() >> 12;
4405   long offset_low = dest_page - low_page;
4406   long offset_high = dest_page - high_page;
4407 
4408   assert(is_valid_AArch64_address(dest.target()), "bad address");
4409   assert(dest.getMode() == Address::literal, "ADRP must be applied to a literal address");
4410 
4411   InstructionMark im(this);
4412   code_section()->relocate(inst_mark(), dest.rspec());
4413   // 8143067: Ensure that the adrp can reach the dest from anywhere within
4414   // the code cache so that if it is relocated we know it will still reach
4415   if (offset_high >= -(1<<20) && offset_low < (1<<20)) {
4416     _adrp(reg1, dest.target());
4417   } else {
4418     unsigned long target = (unsigned long)dest.target();
4419     unsigned long adrp_target
4420       = (target & 0xffffffffUL) | ((unsigned long)pc() & 0xffff00000000UL);
4421 
4422     _adrp(reg1, (address)adrp_target);
4423     movk(reg1, target >> 32, 32);
4424   }
4425   byte_offset = (unsigned long)dest.target() & 0xfff;
4426 }
4427 
4428 void MacroAssembler::load_byte_map_base(Register reg) {
4429   jbyte *byte_map_base =
4430     ((CardTableModRefBS*)(Universe::heap()->barrier_set()))->byte_map_base;
4431 
4432   if (is_valid_AArch64_address((address)byte_map_base)) {
4433     // Strictly speaking the byte_map_base isn't an address at all,
4434     // and it might even be negative.
4435     unsigned long offset;
4436     adrp(reg, ExternalAddress((address)byte_map_base), offset);
4437     // We expect offset to be zero with most collectors.
4438     if (offset != 0) {
4439       add(reg, reg, offset);
4440     }
4441   } else {
4442     mov(reg, (uint64_t)byte_map_base);
4443   }
4444 }
4445 
4446 void MacroAssembler::build_frame(int framesize) {
4447   assert(framesize > 0, "framesize must be > 0");
4448   if (framesize < ((1 << 9) + 2 * wordSize)) {
4449     sub(sp, sp, framesize);
4450     stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4451     if (PreserveFramePointer) add(rfp, sp, framesize - 2 * wordSize);
4452   } else {
4453     stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
4454     if (PreserveFramePointer) mov(rfp, sp);
4455     if (framesize < ((1 << 12) + 2 * wordSize))
4456       sub(sp, sp, framesize - 2 * wordSize);
4457     else {
4458       mov(rscratch1, framesize - 2 * wordSize);
4459       sub(sp, sp, rscratch1);
4460     }
4461   }
4462 }
4463 
4464 void MacroAssembler::remove_frame(int framesize) {
4465   assert(framesize > 0, "framesize must be > 0");
4466   if (framesize < ((1 << 9) + 2 * wordSize)) {
4467     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4468     add(sp, sp, framesize);
4469   } else {
4470     if (framesize < ((1 << 12) + 2 * wordSize))
4471       add(sp, sp, framesize - 2 * wordSize);
4472     else {
4473       mov(rscratch1, framesize - 2 * wordSize);
4474       add(sp, sp, rscratch1);
4475     }
4476     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
4477   }
4478 }
4479 
4480 typedef void (MacroAssembler::* chr_insn)(Register Rt, const Address &adr);
4481 
4482 // Search for str1 in str2 and return index or -1
4483 void MacroAssembler::string_indexof(Register str2, Register str1,
4484                                     Register cnt2, Register cnt1,
4485                                     Register tmp1, Register tmp2,
4486                                     Register tmp3, Register tmp4,
4487                                     int icnt1, Register result, int ae) {
4488   Label BM, LINEARSEARCH, DONE, NOMATCH, MATCH;
4489 
4490   Register ch1 = rscratch1;
4491   Register ch2 = rscratch2;
4492   Register cnt1tmp = tmp1;
4493   Register cnt2tmp = tmp2;
4494   Register cnt1_neg = cnt1;
4495   Register cnt2_neg = cnt2;
4496   Register result_tmp = tmp4;
4497 
4498   bool isL = ae == StrIntrinsicNode::LL;
4499 
4500   bool str1_isL = ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL;
4501   bool str2_isL = ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::LU;
4502   int str1_chr_shift = str1_isL ? 0:1;
4503   int str2_chr_shift = str2_isL ? 0:1;
4504   int str1_chr_size = str1_isL ? 1:2;
4505   int str2_chr_size = str2_isL ? 1:2;
4506   chr_insn str1_load_1chr = str1_isL ? (chr_insn)&MacroAssembler::ldrb :
4507                                       (chr_insn)&MacroAssembler::ldrh;
4508   chr_insn str2_load_1chr = str2_isL ? (chr_insn)&MacroAssembler::ldrb :
4509                                       (chr_insn)&MacroAssembler::ldrh;
4510   chr_insn load_2chr = isL ? (chr_insn)&MacroAssembler::ldrh : (chr_insn)&MacroAssembler::ldrw;
4511   chr_insn load_4chr = isL ? (chr_insn)&MacroAssembler::ldrw : (chr_insn)&MacroAssembler::ldr;
4512 
4513   // Note, inline_string_indexOf() generates checks:
4514   // if (substr.count > string.count) return -1;
4515   // if (substr.count == 0) return 0;
4516 
4517 // We have two strings, a source string in str2, cnt2 and a pattern string
4518 // in str1, cnt1. Find the 1st occurence of pattern in source or return -1.
4519 
4520 // For larger pattern and source we use a simplified Boyer Moore algorithm.
4521 // With a small pattern and source we use linear scan.
4522 
4523   if (icnt1 == -1) {
4524     cmp(cnt1, 256);             // Use Linear Scan if cnt1 < 8 || cnt1 >= 256
4525     ccmp(cnt1, 8, 0b0000, LO);  // Can't handle skip >= 256 because we use
4526     br(LO, LINEARSEARCH);       // a byte array.
4527     cmp(cnt1, cnt2, LSR, 2);    // Source must be 4 * pattern for BM
4528     br(HS, LINEARSEARCH);
4529   }
4530 
4531 // The Boyer Moore alogorithm is based on the description here:-
4532 //
4533 // http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm
4534 //
4535 // This describes and algorithm with 2 shift rules. The 'Bad Character' rule
4536 // and the 'Good Suffix' rule.
4537 //
4538 // These rules are essentially heuristics for how far we can shift the
4539 // pattern along the search string.
4540 //
4541 // The implementation here uses the 'Bad Character' rule only because of the
4542 // complexity of initialisation for the 'Good Suffix' rule.
4543 //
4544 // This is also known as the Boyer-Moore-Horspool algorithm:-
4545 //
4546 // http://en.wikipedia.org/wiki/Boyer-Moore-Horspool_algorithm
4547 //
4548 // #define ASIZE 128
4549 //
4550 //    int bm(unsigned char *x, int m, unsigned char *y, int n) {
4551 //       int i, j;
4552 //       unsigned c;
4553 //       unsigned char bc[ASIZE];
4554 //
4555 //       /* Preprocessing */
4556 //       for (i = 0; i < ASIZE; ++i)
4557 //          bc[i] = 0;
4558 //       for (i = 0; i < m - 1; ) {
4559 //          c = x[i];
4560 //          ++i;
4561 //          if (c < ASIZE) bc[c] = i;
4562 //       }
4563 //
4564 //       /* Searching */
4565 //       j = 0;
4566 //       while (j <= n - m) {
4567 //          c = y[i+j];
4568 //          if (x[m-1] == c)
4569 //            for (i = m - 2; i >= 0 && x[i] == y[i + j]; --i);
4570 //          if (i < 0) return j;
4571 //          if (c < ASIZE)
4572 //            j = j - bc[y[j+m-1]] + m;
4573 //          else
4574 //            j += 1; // Advance by 1 only if char >= ASIZE
4575 //       }
4576 //    }
4577 
4578   if (icnt1 == -1) {
4579     BIND(BM);
4580 
4581     Label ZLOOP, BCLOOP, BCSKIP, BMLOOPSTR2, BMLOOPSTR1, BMSKIP;
4582     Label BMADV, BMMATCH, BMCHECKEND;
4583 
4584     Register cnt1end = tmp2;
4585     Register str2end = cnt2;
4586     Register skipch = tmp2;
4587 
4588     // Restrict ASIZE to 128 to reduce stack space/initialisation.
4589     // The presence of chars >= ASIZE in the target string does not affect
4590     // performance, but we must be careful not to initialise them in the stack
4591     // array.
4592     // The presence of chars >= ASIZE in the source string may adversely affect
4593     // performance since we can only advance by one when we encounter one.
4594 
4595       stp(zr, zr, pre(sp, -128));
4596       for (int i = 1; i < 8; i++)
4597           stp(zr, zr, Address(sp, i*16));
4598 
4599       mov(cnt1tmp, 0);
4600       sub(cnt1end, cnt1, 1);
4601     BIND(BCLOOP);
4602       (this->*str1_load_1chr)(ch1, Address(str1, cnt1tmp, Address::lsl(str1_chr_shift)));
4603       cmp(ch1, 128);
4604       add(cnt1tmp, cnt1tmp, 1);
4605       br(HS, BCSKIP);
4606       strb(cnt1tmp, Address(sp, ch1));
4607     BIND(BCSKIP);
4608       cmp(cnt1tmp, cnt1end);
4609       br(LT, BCLOOP);
4610 
4611       mov(result_tmp, str2);
4612 
4613       sub(cnt2, cnt2, cnt1);
4614       add(str2end, str2, cnt2, LSL, str2_chr_shift);
4615     BIND(BMLOOPSTR2);
4616       sub(cnt1tmp, cnt1, 1);
4617       (this->*str1_load_1chr)(ch1, Address(str1, cnt1tmp, Address::lsl(str1_chr_shift)));
4618       (this->*str2_load_1chr)(skipch, Address(str2, cnt1tmp, Address::lsl(str2_chr_shift)));
4619       cmp(ch1, skipch);
4620       br(NE, BMSKIP);
4621       subs(cnt1tmp, cnt1tmp, 1);
4622       br(LT, BMMATCH);
4623     BIND(BMLOOPSTR1);
4624       (this->*str1_load_1chr)(ch1, Address(str1, cnt1tmp, Address::lsl(str1_chr_shift)));
4625       (this->*str2_load_1chr)(ch2, Address(str2, cnt1tmp, Address::lsl(str2_chr_shift)));
4626       cmp(ch1, ch2);
4627       br(NE, BMSKIP);
4628       subs(cnt1tmp, cnt1tmp, 1);
4629       br(GE, BMLOOPSTR1);
4630     BIND(BMMATCH);
4631       sub(result, str2, result_tmp);
4632       if (!str2_isL) lsr(result, result, 1);
4633       add(sp, sp, 128);
4634       b(DONE);
4635     BIND(BMADV);
4636       add(str2, str2, str2_chr_size);
4637       b(BMCHECKEND);
4638     BIND(BMSKIP);
4639       cmp(skipch, 128);
4640       br(HS, BMADV);
4641       ldrb(ch2, Address(sp, skipch));
4642       add(str2, str2, cnt1, LSL, str2_chr_shift);
4643       sub(str2, str2, ch2, LSL, str2_chr_shift);
4644     BIND(BMCHECKEND);
4645       cmp(str2, str2end);
4646       br(LE, BMLOOPSTR2);
4647       add(sp, sp, 128);
4648       b(NOMATCH);
4649   }
4650 
4651   BIND(LINEARSEARCH);
4652   {
4653     Label DO1, DO2, DO3;
4654 
4655     Register str2tmp = tmp2;
4656     Register first = tmp3;
4657 
4658     if (icnt1 == -1)
4659     {
4660         Label DOSHORT, FIRST_LOOP, STR2_NEXT, STR1_LOOP, STR1_NEXT;
4661 
4662         cmp(cnt1, str1_isL == str2_isL ? 4 : 2);
4663         br(LT, DOSHORT);
4664 
4665         sub(cnt2, cnt2, cnt1);
4666         mov(result_tmp, cnt2);
4667 
4668         lea(str1, Address(str1, cnt1, Address::lsl(str1_chr_shift)));
4669         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4670         sub(cnt1_neg, zr, cnt1, LSL, str1_chr_shift);
4671         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4672         (this->*str1_load_1chr)(first, Address(str1, cnt1_neg));
4673 
4674       BIND(FIRST_LOOP);
4675         (this->*str2_load_1chr)(ch2, Address(str2, cnt2_neg));
4676         cmp(first, ch2);
4677         br(EQ, STR1_LOOP);
4678       BIND(STR2_NEXT);
4679         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4680         br(LE, FIRST_LOOP);
4681         b(NOMATCH);
4682 
4683       BIND(STR1_LOOP);
4684         adds(cnt1tmp, cnt1_neg, str1_chr_size);
4685         add(cnt2tmp, cnt2_neg, str2_chr_size);
4686         br(GE, MATCH);
4687 
4688       BIND(STR1_NEXT);
4689         (this->*str1_load_1chr)(ch1, Address(str1, cnt1tmp));
4690         (this->*str2_load_1chr)(ch2, Address(str2, cnt2tmp));
4691         cmp(ch1, ch2);
4692         br(NE, STR2_NEXT);
4693         adds(cnt1tmp, cnt1tmp, str1_chr_size);
4694         add(cnt2tmp, cnt2tmp, str2_chr_size);
4695         br(LT, STR1_NEXT);
4696         b(MATCH);
4697 
4698       BIND(DOSHORT);
4699       if (str1_isL == str2_isL) {
4700         cmp(cnt1, 2);
4701         br(LT, DO1);
4702         br(GT, DO3);
4703       }
4704     }
4705 
4706     if (icnt1 == 4) {
4707       Label CH1_LOOP;
4708 
4709         (this->*load_4chr)(ch1, str1);
4710         sub(cnt2, cnt2, 4);
4711         mov(result_tmp, cnt2);
4712         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4713         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4714 
4715       BIND(CH1_LOOP);
4716         (this->*load_4chr)(ch2, Address(str2, cnt2_neg));
4717         cmp(ch1, ch2);
4718         br(EQ, MATCH);
4719         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4720         br(LE, CH1_LOOP);
4721         b(NOMATCH);
4722     }
4723 
4724     if ((icnt1 == -1 && str1_isL == str2_isL) || icnt1 == 2) {
4725       Label CH1_LOOP;
4726 
4727       BIND(DO2);
4728         (this->*load_2chr)(ch1, str1);
4729         sub(cnt2, cnt2, 2);
4730         mov(result_tmp, cnt2);
4731         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4732         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4733 
4734       BIND(CH1_LOOP);
4735         (this->*load_2chr)(ch2, Address(str2, cnt2_neg));
4736         cmp(ch1, ch2);
4737         br(EQ, MATCH);
4738         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4739         br(LE, CH1_LOOP);
4740         b(NOMATCH);
4741     }
4742 
4743     if ((icnt1 == -1 && str1_isL == str2_isL) || icnt1 == 3) {
4744       Label FIRST_LOOP, STR2_NEXT, STR1_LOOP;
4745 
4746       BIND(DO3);
4747         (this->*load_2chr)(first, str1);
4748         (this->*str1_load_1chr)(ch1, Address(str1, 2*str1_chr_size));
4749 
4750         sub(cnt2, cnt2, 3);
4751         mov(result_tmp, cnt2);
4752         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4753         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4754 
4755       BIND(FIRST_LOOP);
4756         (this->*load_2chr)(ch2, Address(str2, cnt2_neg));
4757         cmpw(first, ch2);
4758         br(EQ, STR1_LOOP);
4759       BIND(STR2_NEXT);
4760         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4761         br(LE, FIRST_LOOP);
4762         b(NOMATCH);
4763 
4764       BIND(STR1_LOOP);
4765         add(cnt2tmp, cnt2_neg, 2*str2_chr_size);
4766         (this->*str2_load_1chr)(ch2, Address(str2, cnt2tmp));
4767         cmp(ch1, ch2);
4768         br(NE, STR2_NEXT);
4769         b(MATCH);
4770     }
4771 
4772     if (icnt1 == -1 || icnt1 == 1) {
4773       Label CH1_LOOP, HAS_ZERO;
4774       Label DO1_SHORT, DO1_LOOP;
4775 
4776       BIND(DO1);
4777         (this->*str1_load_1chr)(ch1, str1);
4778         cmp(cnt2, 8);
4779         br(LT, DO1_SHORT);
4780 
4781         if (str2_isL) {
4782           if (!str1_isL) {
4783             tst(ch1, 0xff00);
4784             br(NE, NOMATCH);
4785           }
4786           orr(ch1, ch1, ch1, LSL, 8);
4787         }
4788         orr(ch1, ch1, ch1, LSL, 16);
4789         orr(ch1, ch1, ch1, LSL, 32);
4790 
4791         sub(cnt2, cnt2, 8/str2_chr_size);
4792         mov(result_tmp, cnt2);
4793         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4794         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4795 
4796         mov(tmp3, str2_isL ? 0x0101010101010101 : 0x0001000100010001);
4797       BIND(CH1_LOOP);
4798         ldr(ch2, Address(str2, cnt2_neg));
4799         eor(ch2, ch1, ch2);
4800         sub(tmp1, ch2, tmp3);
4801         orr(tmp2, ch2, str2_isL ? 0x7f7f7f7f7f7f7f7f : 0x7fff7fff7fff7fff);
4802         bics(tmp1, tmp1, tmp2);
4803         br(NE, HAS_ZERO);
4804         adds(cnt2_neg, cnt2_neg, 8);
4805         br(LT, CH1_LOOP);
4806 
4807         cmp(cnt2_neg, 8);
4808         mov(cnt2_neg, 0);
4809         br(LT, CH1_LOOP);
4810         b(NOMATCH);
4811 
4812       BIND(HAS_ZERO);
4813         rev(tmp1, tmp1);
4814         clz(tmp1, tmp1);
4815         add(cnt2_neg, cnt2_neg, tmp1, LSR, 3);
4816         b(MATCH);
4817 
4818       BIND(DO1_SHORT);
4819         mov(result_tmp, cnt2);
4820         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4821         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4822       BIND(DO1_LOOP);
4823         (this->*str2_load_1chr)(ch2, Address(str2, cnt2_neg));
4824         cmpw(ch1, ch2);
4825         br(EQ, MATCH);
4826         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4827         br(LT, DO1_LOOP);
4828     }
4829   }
4830   BIND(NOMATCH);
4831     mov(result, -1);
4832     b(DONE);
4833   BIND(MATCH);
4834     add(result, result_tmp, cnt2_neg, ASR, str2_chr_shift);
4835   BIND(DONE);
4836 }
4837 
4838 typedef void (MacroAssembler::* chr_insn)(Register Rt, const Address &adr);
4839 typedef void (MacroAssembler::* uxt_insn)(Register Rd, Register Rn);
4840 
4841 void MacroAssembler::string_indexof_char(Register str1, Register cnt1,
4842                                          Register ch, Register result,
4843                                          Register tmp1, Register tmp2, Register tmp3)
4844 {
4845   Label CH1_LOOP, HAS_ZERO, DO1_SHORT, DO1_LOOP, MATCH, NOMATCH, DONE;
4846   Register cnt1_neg = cnt1;
4847   Register ch1 = rscratch1;
4848   Register result_tmp = rscratch2;
4849 
4850   cmp(cnt1, 4);
4851   br(LT, DO1_SHORT);
4852 
4853   orr(ch, ch, ch, LSL, 16);
4854   orr(ch, ch, ch, LSL, 32);
4855 
4856   sub(cnt1, cnt1, 4);
4857   mov(result_tmp, cnt1);
4858   lea(str1, Address(str1, cnt1, Address::uxtw(1)));
4859   sub(cnt1_neg, zr, cnt1, LSL, 1);
4860 
4861   mov(tmp3, 0x0001000100010001);
4862 
4863   BIND(CH1_LOOP);
4864     ldr(ch1, Address(str1, cnt1_neg));
4865     eor(ch1, ch, ch1);
4866     sub(tmp1, ch1, tmp3);
4867     orr(tmp2, ch1, 0x7fff7fff7fff7fff);
4868     bics(tmp1, tmp1, tmp2);
4869     br(NE, HAS_ZERO);
4870     adds(cnt1_neg, cnt1_neg, 8);
4871     br(LT, CH1_LOOP);
4872 
4873     cmp(cnt1_neg, 8);
4874     mov(cnt1_neg, 0);
4875     br(LT, CH1_LOOP);
4876     b(NOMATCH);
4877 
4878   BIND(HAS_ZERO);
4879     rev(tmp1, tmp1);
4880     clz(tmp1, tmp1);
4881     add(cnt1_neg, cnt1_neg, tmp1, LSR, 3);
4882     b(MATCH);
4883 
4884   BIND(DO1_SHORT);
4885     mov(result_tmp, cnt1);
4886     lea(str1, Address(str1, cnt1, Address::uxtw(1)));
4887     sub(cnt1_neg, zr, cnt1, LSL, 1);
4888   BIND(DO1_LOOP);
4889     ldrh(ch1, Address(str1, cnt1_neg));
4890     cmpw(ch, ch1);
4891     br(EQ, MATCH);
4892     adds(cnt1_neg, cnt1_neg, 2);
4893     br(LT, DO1_LOOP);
4894   BIND(NOMATCH);
4895     mov(result, -1);
4896     b(DONE);
4897   BIND(MATCH);
4898     add(result, result_tmp, cnt1_neg, ASR, 1);
4899   BIND(DONE);
4900 }
4901 
4902 // Compare strings.
4903 void MacroAssembler::string_compare(Register str1, Register str2,
4904                                     Register cnt1, Register cnt2, Register result,
4905                                     Register tmp1,
4906                                     FloatRegister vtmp, FloatRegister vtmpZ, int ae) {
4907   Label LENGTH_DIFF, DONE, SHORT_LOOP, SHORT_STRING,
4908     NEXT_WORD, DIFFERENCE;
4909 
4910   bool isLL = ae == StrIntrinsicNode::LL;
4911   bool isLU = ae == StrIntrinsicNode::LU;
4912   bool isUL = ae == StrIntrinsicNode::UL;
4913 
4914   bool str1_isL = isLL || isLU;
4915   bool str2_isL = isLL || isUL;
4916 
4917   int str1_chr_shift = str1_isL ? 0 : 1;
4918   int str2_chr_shift = str2_isL ? 0 : 1;
4919   int str1_chr_size = str1_isL ? 1 : 2;
4920   int str2_chr_size = str2_isL ? 1 : 2;
4921 
4922   chr_insn str1_load_chr = str1_isL ? (chr_insn)&MacroAssembler::ldrb :
4923                                       (chr_insn)&MacroAssembler::ldrh;
4924   chr_insn str2_load_chr = str2_isL ? (chr_insn)&MacroAssembler::ldrb :
4925                                       (chr_insn)&MacroAssembler::ldrh;
4926   uxt_insn ext_chr = isLL ? (uxt_insn)&MacroAssembler::uxtbw :
4927                             (uxt_insn)&MacroAssembler::uxthw;
4928 
4929   BLOCK_COMMENT("string_compare {");
4930 
4931   // Bizzarely, the counts are passed in bytes, regardless of whether they
4932   // are L or U strings, however the result is always in characters.
4933   if (!str1_isL) asrw(cnt1, cnt1, 1);
4934   if (!str2_isL) asrw(cnt2, cnt2, 1);
4935 
4936   // Compute the minimum of the string lengths and save the difference.
4937   subsw(tmp1, cnt1, cnt2);
4938   cselw(cnt2, cnt1, cnt2, Assembler::LE); // min
4939 
4940   // A very short string
4941   cmpw(cnt2, isLL ? 8:4);
4942   br(Assembler::LT, SHORT_STRING);
4943 
4944   // Check if the strings start at the same location.
4945   cmp(str1, str2);
4946   br(Assembler::EQ, LENGTH_DIFF);
4947 
4948   // Compare longwords
4949   {
4950     subw(cnt2, cnt2, isLL ? 8:4); // The last longword is a special case
4951 
4952     // Move both string pointers to the last longword of their
4953     // strings, negate the remaining count, and convert it to bytes.
4954     lea(str1, Address(str1, cnt2, Address::uxtw(str1_chr_shift)));
4955     lea(str2, Address(str2, cnt2, Address::uxtw(str2_chr_shift)));
4956     if (isLU || isUL) {
4957       sub(cnt1, zr, cnt2, LSL, str1_chr_shift);
4958       eor(vtmpZ, T16B, vtmpZ, vtmpZ);
4959     }
4960     sub(cnt2, zr, cnt2, LSL, str2_chr_shift);
4961 
4962     // Loop, loading longwords and comparing them into rscratch2.
4963     bind(NEXT_WORD);
4964     if (isLU) {
4965       ldrs(vtmp, Address(str1, cnt1));
4966       zip1(vtmp, T8B, vtmp, vtmpZ);
4967       umov(result, vtmp, D, 0);
4968     } else {
4969       ldr(result, Address(str1, isUL ? cnt1:cnt2));
4970     }
4971     if (isUL) {
4972       ldrs(vtmp, Address(str2, cnt2));
4973       zip1(vtmp, T8B, vtmp, vtmpZ);
4974       umov(rscratch1, vtmp, D, 0);
4975     } else {
4976       ldr(rscratch1, Address(str2, cnt2));
4977     }
4978     adds(cnt2, cnt2, isUL ? 4:8);
4979     if (isLU || isUL) add(cnt1, cnt1, isLU ? 4:8);
4980     eor(rscratch2, result, rscratch1);
4981     cbnz(rscratch2, DIFFERENCE);
4982     br(Assembler::LT, NEXT_WORD);
4983 
4984     // Last longword.  In the case where length == 4 we compare the
4985     // same longword twice, but that's still faster than another
4986     // conditional branch.
4987 
4988     if (isLU) {
4989       ldrs(vtmp, Address(str1));
4990       zip1(vtmp, T8B, vtmp, vtmpZ);
4991       umov(result, vtmp, D, 0);
4992     } else {
4993       ldr(result, Address(str1));
4994     }
4995     if (isUL) {
4996       ldrs(vtmp, Address(str2));
4997       zip1(vtmp, T8B, vtmp, vtmpZ);
4998       umov(rscratch1, vtmp, D, 0);
4999     } else {
5000       ldr(rscratch1, Address(str2));
5001     }
5002     eor(rscratch2, result, rscratch1);
5003     cbz(rscratch2, LENGTH_DIFF);
5004 
5005     // Find the first different characters in the longwords and
5006     // compute their difference.
5007     bind(DIFFERENCE);
5008     rev(rscratch2, rscratch2);
5009     clz(rscratch2, rscratch2);
5010     andr(rscratch2, rscratch2, isLL ? -8 : -16);
5011     lsrv(result, result, rscratch2);
5012     (this->*ext_chr)(result, result);
5013     lsrv(rscratch1, rscratch1, rscratch2);
5014     (this->*ext_chr)(rscratch1, rscratch1);
5015     subw(result, result, rscratch1);
5016     b(DONE);
5017   }
5018 
5019   bind(SHORT_STRING);
5020   // Is the minimum length zero?
5021   cbz(cnt2, LENGTH_DIFF);
5022 
5023   bind(SHORT_LOOP);
5024   (this->*str1_load_chr)(result, Address(post(str1, str1_chr_size)));
5025   (this->*str2_load_chr)(cnt1, Address(post(str2, str2_chr_size)));
5026   subw(result, result, cnt1);
5027   cbnz(result, DONE);
5028   sub(cnt2, cnt2, 1);
5029   cbnz(cnt2, SHORT_LOOP);
5030 
5031   // Strings are equal up to min length.  Return the length difference.
5032   bind(LENGTH_DIFF);
5033   mov(result, tmp1);
5034 
5035   // That's it
5036   bind(DONE);
5037 
5038   BLOCK_COMMENT("} string_compare");
5039 }
5040 
5041 // This method checks if provided byte array contains byte with highest bit set.
5042 void MacroAssembler::has_negatives(Register ary1, Register len, Register result) {
5043     // Simple and most common case of aligned small array which is not at the
5044     // end of memory page is placed here. All other cases are in stub.
5045     Label LOOP, END, STUB, STUB_LONG, SET_RESULT, DONE;
5046     const uint64_t UPPER_BIT_MASK=0x8080808080808080;
5047     assert_different_registers(ary1, len, result);
5048 
5049     cmpw(len, 0);
5050     br(LE, SET_RESULT);
5051     cmpw(len, 4 * wordSize);
5052     br(GE, STUB_LONG); // size > 32 then go to stub
5053 
5054     int shift = 64 - exact_log2(os::vm_page_size());
5055     lsl(rscratch1, ary1, shift);
5056     mov(rscratch2, (size_t)(4 * wordSize) << shift);
5057     adds(rscratch2, rscratch1, rscratch2);  // At end of page?
5058     br(CS, STUB); // at the end of page then go to stub
5059     subs(len, len, wordSize);
5060     br(LT, END);
5061 
5062   BIND(LOOP);
5063     ldr(rscratch1, Address(post(ary1, wordSize)));
5064     tst(rscratch1, UPPER_BIT_MASK);
5065     br(NE, SET_RESULT);
5066     subs(len, len, wordSize);
5067     br(GE, LOOP);
5068     cmpw(len, -wordSize);
5069     br(EQ, SET_RESULT);
5070 
5071   BIND(END);
5072     ldr(result, Address(ary1));
5073     sub(len, zr, len, LSL, 3); // LSL 3 is to get bits from bytes
5074     lslv(result, result, len);
5075     tst(result, UPPER_BIT_MASK);
5076     b(SET_RESULT);
5077 
5078   BIND(STUB);
5079     RuntimeAddress has_neg =  RuntimeAddress(StubRoutines::aarch64::has_negatives());
5080     assert(has_neg.target() != NULL, "has_negatives stub has not been generated");
5081     trampoline_call(has_neg);
5082     b(DONE);
5083 
5084   BIND(STUB_LONG);
5085     RuntimeAddress has_neg_long =  RuntimeAddress(
5086             StubRoutines::aarch64::has_negatives_long());
5087     assert(has_neg_long.target() != NULL, "has_negatives stub has not been generated");
5088     trampoline_call(has_neg_long);
5089     b(DONE);
5090 
5091   BIND(SET_RESULT);
5092     cset(result, NE); // set true or false
5093 
5094   BIND(DONE);
5095 }
5096 
5097 // Compare Strings or char/byte arrays.
5098 
5099 // is_string is true iff this is a string comparison.
5100 
5101 // For Strings we're passed the address of the first characters in a1
5102 // and a2 and the length in cnt1.
5103 
5104 // For byte and char arrays we're passed the arrays themselves and we
5105 // have to extract length fields and do null checks here.
5106 
5107 // elem_size is the element size in bytes: either 1 or 2.
5108 
5109 // There are two implementations.  For arrays >= 8 bytes, all
5110 // comparisons (including the final one, which may overlap) are
5111 // performed 8 bytes at a time.  For arrays < 8 bytes, we compare a
5112 // halfword, then a short, and then a byte.
5113 
5114 void MacroAssembler::arrays_equals(Register a1, Register a2,
5115                                    Register result, Register cnt1,
5116                                    int elem_size, bool is_string)
5117 {
5118   Label SAME, DONE, SHORT, NEXT_WORD, ONE;
5119   Register tmp1 = rscratch1;
5120   Register tmp2 = rscratch2;
5121   Register cnt2 = tmp2;  // cnt2 only used in array length compare
5122   int elem_per_word = wordSize/elem_size;
5123   int log_elem_size = exact_log2(elem_size);
5124   int length_offset = arrayOopDesc::length_offset_in_bytes();
5125   int base_offset
5126     = arrayOopDesc::base_offset_in_bytes(elem_size == 2 ? T_CHAR : T_BYTE);
5127 
5128   assert(elem_size == 1 || elem_size == 2, "must be char or byte");
5129   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
5130 
5131 #ifndef PRODUCT
5132   {
5133     const char kind = (elem_size == 2) ? 'U' : 'L';
5134     char comment[64];
5135     snprintf(comment, sizeof comment, "%s%c%s {",
5136              is_string ? "string_equals" : "array_equals",
5137              kind, "{");
5138     BLOCK_COMMENT(comment);
5139   }
5140 #endif
5141 
5142   mov(result, false);
5143 
5144   if (!is_string) {
5145     // if (a==a2)
5146     //     return true;
5147     eor(rscratch1, a1, a2);
5148     cbz(rscratch1, SAME);
5149     // if (a==null || a2==null)
5150     //     return false;
5151     cbz(a1, DONE);
5152     cbz(a2, DONE);
5153     // if (a1.length != a2.length)
5154     //      return false;
5155     ldrw(cnt1, Address(a1, length_offset));
5156     ldrw(cnt2, Address(a2, length_offset));
5157     eorw(tmp1, cnt1, cnt2);
5158     cbnzw(tmp1, DONE);
5159 
5160     lea(a1, Address(a1, base_offset));
5161     lea(a2, Address(a2, base_offset));
5162   }
5163 
5164   // Check for short strings, i.e. smaller than wordSize.
5165   subs(cnt1, cnt1, elem_per_word);
5166   br(Assembler::LT, SHORT);
5167   // Main 8 byte comparison loop.
5168   bind(NEXT_WORD); {
5169     ldr(tmp1, Address(post(a1, wordSize)));
5170     ldr(tmp2, Address(post(a2, wordSize)));
5171     subs(cnt1, cnt1, elem_per_word);
5172     eor(tmp1, tmp1, tmp2);
5173     cbnz(tmp1, DONE);
5174   } br(GT, NEXT_WORD);
5175   // Last longword.  In the case where length == 4 we compare the
5176   // same longword twice, but that's still faster than another
5177   // conditional branch.
5178   // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
5179   // length == 4.
5180   if (log_elem_size > 0)
5181     lsl(cnt1, cnt1, log_elem_size);
5182   ldr(tmp1, Address(a1, cnt1));
5183   ldr(tmp2, Address(a2, cnt1));
5184   eor(tmp1, tmp1, tmp2);
5185   cbnz(tmp1, DONE);
5186   b(SAME);
5187 
5188   bind(SHORT);
5189   Label TAIL03, TAIL01;
5190 
5191   tbz(cnt1, 2 - log_elem_size, TAIL03); // 0-7 bytes left.
5192   {
5193     ldrw(tmp1, Address(post(a1, 4)));
5194     ldrw(tmp2, Address(post(a2, 4)));
5195     eorw(tmp1, tmp1, tmp2);
5196     cbnzw(tmp1, DONE);
5197   }
5198   bind(TAIL03);
5199   tbz(cnt1, 1 - log_elem_size, TAIL01); // 0-3 bytes left.
5200   {
5201     ldrh(tmp1, Address(post(a1, 2)));
5202     ldrh(tmp2, Address(post(a2, 2)));
5203     eorw(tmp1, tmp1, tmp2);
5204     cbnzw(tmp1, DONE);
5205   }
5206   bind(TAIL01);
5207   if (elem_size == 1) { // Only needed when comparing byte arrays.
5208     tbz(cnt1, 0, SAME); // 0-1 bytes left.
5209     {
5210       ldrb(tmp1, a1);
5211       ldrb(tmp2, a2);
5212       eorw(tmp1, tmp1, tmp2);
5213       cbnzw(tmp1, DONE);
5214     }
5215   }
5216   // Arrays are equal.
5217   bind(SAME);
5218   mov(result, true);
5219 
5220   // That's it.
5221   bind(DONE);
5222   BLOCK_COMMENT(is_string ? "} string_equals" : "} array_equals");
5223 }
5224 
5225 
5226 // The size of the blocks erased by the zero_blocks stub.  We must
5227 // handle anything smaller than this ourselves in zero_words().
5228 const int MacroAssembler::zero_words_block_size = 8;
5229 
5230 // zero_words() is used by C2 ClearArray patterns.  It is as small as
5231 // possible, handling small word counts locally and delegating
5232 // anything larger to the zero_blocks stub.  It is expanded many times
5233 // in compiled code, so it is important to keep it short.
5234 
5235 // ptr:   Address of a buffer to be zeroed.
5236 // cnt:   Count in HeapWords.
5237 //
5238 // ptr, cnt, rscratch1, and rscratch2 are clobbered.
5239 void MacroAssembler::zero_words(Register ptr, Register cnt)
5240 {
5241   assert(is_power_of_2(zero_words_block_size), "adjust this");
5242   assert(ptr == r10 && cnt == r11, "mismatch in register usage");
5243 
5244   BLOCK_COMMENT("zero_words {");
5245   cmp(cnt, zero_words_block_size);
5246   Label around, done, done16;
5247   br(LO, around);
5248   {
5249     RuntimeAddress zero_blocks =  RuntimeAddress(StubRoutines::aarch64::zero_blocks());
5250     assert(zero_blocks.target() != NULL, "zero_blocks stub has not been generated");
5251     if (StubRoutines::aarch64::complete()) {
5252       trampoline_call(zero_blocks);
5253     } else {
5254       bl(zero_blocks);
5255     }
5256   }
5257   bind(around);
5258   for (int i = zero_words_block_size >> 1; i > 1; i >>= 1) {
5259     Label l;
5260     tbz(cnt, exact_log2(i), l);
5261     for (int j = 0; j < i; j += 2) {
5262       stp(zr, zr, post(ptr, 16));
5263     }
5264     bind(l);
5265   }
5266   {
5267     Label l;
5268     tbz(cnt, 0, l);
5269     str(zr, Address(ptr));
5270     bind(l);
5271   }
5272   BLOCK_COMMENT("} zero_words");
5273 }
5274 
5275 // base:         Address of a buffer to be zeroed, 8 bytes aligned.
5276 // cnt:          Immediate count in HeapWords.
5277 #define SmallArraySize (18 * BytesPerLong)
5278 void MacroAssembler::zero_words(Register base, u_int64_t cnt)
5279 {
5280   BLOCK_COMMENT("zero_words {");
5281   int i = cnt & 1;  // store any odd word to start
5282   if (i) str(zr, Address(base));
5283 
5284   if (cnt <= SmallArraySize / BytesPerLong) {
5285     for (; i < (int)cnt; i += 2)
5286       stp(zr, zr, Address(base, i * wordSize));
5287   } else {
5288     const int unroll = 4; // Number of stp(zr, zr) instructions we'll unroll
5289     int remainder = cnt % (2 * unroll);
5290     for (; i < remainder; i += 2)
5291       stp(zr, zr, Address(base, i * wordSize));
5292 
5293     Label loop;
5294     Register cnt_reg = rscratch1;
5295     Register loop_base = rscratch2;
5296     cnt = cnt - remainder;
5297     mov(cnt_reg, cnt);
5298     // adjust base and prebias by -2 * wordSize so we can pre-increment
5299     add(loop_base, base, (remainder - 2) * wordSize);
5300     bind(loop);
5301     sub(cnt_reg, cnt_reg, 2 * unroll);
5302     for (i = 1; i < unroll; i++)
5303       stp(zr, zr, Address(loop_base, 2 * i * wordSize));
5304     stp(zr, zr, Address(pre(loop_base, 2 * unroll * wordSize)));
5305     cbnz(cnt_reg, loop);
5306   }
5307   BLOCK_COMMENT("} zero_words");
5308 }
5309 
5310 // Zero blocks of memory by using DC ZVA.
5311 //
5312 // Aligns the base address first sufficently for DC ZVA, then uses
5313 // DC ZVA repeatedly for every full block.  cnt is the size to be
5314 // zeroed in HeapWords.  Returns the count of words left to be zeroed
5315 // in cnt.
5316 //
5317 // NOTE: This is intended to be used in the zero_blocks() stub.  If
5318 // you want to use it elsewhere, note that cnt must be >= 2*zva_length.
5319 void MacroAssembler::zero_dcache_blocks(Register base, Register cnt) {
5320   Register tmp = rscratch1;
5321   Register tmp2 = rscratch2;
5322   int zva_length = VM_Version::zva_length();
5323   Label initial_table_end, loop_zva;
5324   Label fini;
5325 
5326   // Base must be 16 byte aligned. If not just return and let caller handle it
5327   tst(base, 0x0f);
5328   br(Assembler::NE, fini);
5329   // Align base with ZVA length.
5330   neg(tmp, base);
5331   andr(tmp, tmp, zva_length - 1);
5332 
5333   // tmp: the number of bytes to be filled to align the base with ZVA length.
5334   add(base, base, tmp);
5335   sub(cnt, cnt, tmp, Assembler::ASR, 3);
5336   adr(tmp2, initial_table_end);
5337   sub(tmp2, tmp2, tmp, Assembler::LSR, 2);
5338   br(tmp2);
5339 
5340   for (int i = -zva_length + 16; i < 0; i += 16)
5341     stp(zr, zr, Address(base, i));
5342   bind(initial_table_end);
5343 
5344   sub(cnt, cnt, zva_length >> 3);
5345   bind(loop_zva);
5346   dc(Assembler::ZVA, base);
5347   subs(cnt, cnt, zva_length >> 3);
5348   add(base, base, zva_length);
5349   br(Assembler::GE, loop_zva);
5350   add(cnt, cnt, zva_length >> 3); // count not zeroed by DC ZVA
5351   bind(fini);
5352 }
5353 
5354 // base:   Address of a buffer to be filled, 8 bytes aligned.
5355 // cnt:    Count in 8-byte unit.
5356 // value:  Value to be filled with.
5357 // base will point to the end of the buffer after filling.
5358 void MacroAssembler::fill_words(Register base, Register cnt, Register value)
5359 {
5360 //  Algorithm:
5361 //
5362 //    scratch1 = cnt & 7;
5363 //    cnt -= scratch1;
5364 //    p += scratch1;
5365 //    switch (scratch1) {
5366 //      do {
5367 //        cnt -= 8;
5368 //          p[-8] = v;
5369 //        case 7:
5370 //          p[-7] = v;
5371 //        case 6:
5372 //          p[-6] = v;
5373 //          // ...
5374 //        case 1:
5375 //          p[-1] = v;
5376 //        case 0:
5377 //          p += 8;
5378 //      } while (cnt);
5379 //    }
5380 
5381   assert_different_registers(base, cnt, value, rscratch1, rscratch2);
5382 
5383   Label fini, skip, entry, loop;
5384   const int unroll = 8; // Number of stp instructions we'll unroll
5385 
5386   cbz(cnt, fini);
5387   tbz(base, 3, skip);
5388   str(value, Address(post(base, 8)));
5389   sub(cnt, cnt, 1);
5390   bind(skip);
5391 
5392   andr(rscratch1, cnt, (unroll-1) * 2);
5393   sub(cnt, cnt, rscratch1);
5394   add(base, base, rscratch1, Assembler::LSL, 3);
5395   adr(rscratch2, entry);
5396   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 1);
5397   br(rscratch2);
5398 
5399   bind(loop);
5400   add(base, base, unroll * 16);
5401   for (int i = -unroll; i < 0; i++)
5402     stp(value, value, Address(base, i * 16));
5403   bind(entry);
5404   subs(cnt, cnt, unroll * 2);
5405   br(Assembler::GE, loop);
5406 
5407   tbz(cnt, 0, fini);
5408   str(value, Address(post(base, 8)));
5409   bind(fini);
5410 }
5411 
5412 // Intrinsic for sun/nio/cs/ISO_8859_1$Encoder.implEncodeISOArray and
5413 // java/lang/StringUTF16.compress.
5414 void MacroAssembler::encode_iso_array(Register src, Register dst,
5415                       Register len, Register result,
5416                       FloatRegister Vtmp1, FloatRegister Vtmp2,
5417                       FloatRegister Vtmp3, FloatRegister Vtmp4)
5418 {
5419     Label DONE, NEXT_32, LOOP_8, NEXT_8, LOOP_1, NEXT_1;
5420     Register tmp1 = rscratch1;
5421 
5422       mov(result, len); // Save initial len
5423 
5424 #ifndef BUILTIN_SIM
5425       subs(len, len, 32);
5426       br(LT, LOOP_8);
5427 
5428 // The following code uses the SIMD 'uqxtn' and 'uqxtn2' instructions
5429 // to convert chars to bytes. These set the 'QC' bit in the FPSR if
5430 // any char could not fit in a byte, so clear the FPSR so we can test it.
5431       clear_fpsr();
5432 
5433     BIND(NEXT_32);
5434       ld1(Vtmp1, Vtmp2, Vtmp3, Vtmp4, T8H, src);
5435       uqxtn(Vtmp1, T8B, Vtmp1, T8H);  // uqxtn  - write bottom half
5436       uqxtn(Vtmp1, T16B, Vtmp2, T8H); // uqxtn2 - write top half
5437       uqxtn(Vtmp2, T8B, Vtmp3, T8H);
5438       uqxtn(Vtmp2, T16B, Vtmp4, T8H); // uqxtn2
5439       get_fpsr(tmp1);
5440       cbnzw(tmp1, LOOP_8);
5441       st1(Vtmp1, Vtmp2, T16B, post(dst, 32));
5442       subs(len, len, 32);
5443       add(src, src, 64);
5444       br(GE, NEXT_32);
5445 
5446     BIND(LOOP_8);
5447       adds(len, len, 32-8);
5448       br(LT, LOOP_1);
5449       clear_fpsr(); // QC may be set from loop above, clear again
5450     BIND(NEXT_8);
5451       ld1(Vtmp1, T8H, src);
5452       uqxtn(Vtmp1, T8B, Vtmp1, T8H);
5453       get_fpsr(tmp1);
5454       cbnzw(tmp1, LOOP_1);
5455       st1(Vtmp1, T8B, post(dst, 8));
5456       subs(len, len, 8);
5457       add(src, src, 16);
5458       br(GE, NEXT_8);
5459 
5460     BIND(LOOP_1);
5461       adds(len, len, 8);
5462       br(LE, DONE);
5463 #else
5464       cbz(len, DONE);
5465 #endif
5466     BIND(NEXT_1);
5467       ldrh(tmp1, Address(post(src, 2)));
5468       tst(tmp1, 0xff00);
5469       br(NE, DONE);
5470       strb(tmp1, Address(post(dst, 1)));
5471       subs(len, len, 1);
5472       br(GT, NEXT_1);
5473 
5474     BIND(DONE);
5475       sub(result, result, len); // Return index where we stopped
5476                                 // Return len == 0 if we processed all
5477                                 // characters
5478 }
5479 
5480 
5481 // Inflate byte[] array to char[].
5482 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
5483                                         FloatRegister vtmp1, FloatRegister vtmp2, FloatRegister vtmp3,
5484                                         Register tmp4) {
5485   Label big, done;
5486 
5487   assert_different_registers(src, dst, len, tmp4, rscratch1);
5488 
5489   fmovd(vtmp1 , zr);
5490   lsrw(rscratch1, len, 3);
5491 
5492   cbnzw(rscratch1, big);
5493 
5494   // Short string: less than 8 bytes.
5495   {
5496     Label loop, around, tiny;
5497 
5498     subsw(len, len, 4);
5499     andw(len, len, 3);
5500     br(LO, tiny);
5501 
5502     // Use SIMD to do 4 bytes.
5503     ldrs(vtmp2, post(src, 4));
5504     zip1(vtmp3, T8B, vtmp2, vtmp1);
5505     strd(vtmp3, post(dst, 8));
5506 
5507     cbzw(len, done);
5508 
5509     // Do the remaining bytes by steam.
5510     bind(loop);
5511     ldrb(tmp4, post(src, 1));
5512     strh(tmp4, post(dst, 2));
5513     subw(len, len, 1);
5514 
5515     bind(tiny);
5516     cbnz(len, loop);
5517 
5518     bind(around);
5519     b(done);
5520   }
5521 
5522   // Unpack the bytes 8 at a time.
5523   bind(big);
5524   andw(len, len, 7);
5525 
5526   {
5527     Label loop, around;
5528 
5529     bind(loop);
5530     ldrd(vtmp2, post(src, 8));
5531     sub(rscratch1, rscratch1, 1);
5532     zip1(vtmp3, T16B, vtmp2, vtmp1);
5533     st1(vtmp3, T8H, post(dst, 16));
5534     cbnz(rscratch1, loop);
5535 
5536     bind(around);
5537   }
5538 
5539   // Do the tail of up to 8 bytes.
5540   sub(src, src, 8);
5541   add(src, src, len, ext::uxtw, 0);
5542   ldrd(vtmp2, Address(src));
5543   sub(dst, dst, 16);
5544   add(dst, dst, len, ext::uxtw, 1);
5545   zip1(vtmp3, T16B, vtmp2, vtmp1);
5546   st1(vtmp3, T8H, Address(dst));
5547 
5548   bind(done);
5549 }
5550 
5551 // Compress char[] array to byte[].
5552 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
5553                                          FloatRegister tmp1Reg, FloatRegister tmp2Reg,
5554                                          FloatRegister tmp3Reg, FloatRegister tmp4Reg,
5555                                          Register result) {
5556   encode_iso_array(src, dst, len, result,
5557                    tmp1Reg, tmp2Reg, tmp3Reg, tmp4Reg);
5558   cmp(len, zr);
5559   csel(result, result, zr, EQ);
5560 }
5561 
5562 // get_thread() can be called anywhere inside generated code so we
5563 // need to save whatever non-callee save context might get clobbered
5564 // by the call to JavaThread::aarch64_get_thread_helper() or, indeed,
5565 // the call setup code.
5566 //
5567 // aarch64_get_thread_helper() clobbers only r0, r1, and flags.
5568 //
5569 void MacroAssembler::get_thread(Register dst) {
5570   RegSet saved_regs = RegSet::range(r0, r1) + lr - dst;
5571   push(saved_regs, sp);
5572 
5573   mov(lr, CAST_FROM_FN_PTR(address, JavaThread::aarch64_get_thread_helper));
5574   blrt(lr, 1, 0, 1);
5575   if (dst != c_rarg0) {
5576     mov(dst, c_rarg0);
5577   }
5578 
5579   pop(saved_regs, sp);
5580 }