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