src/cpu/ppc/vm/macroAssembler_ppc.cpp

Wed, 11 Dec 2013 00:06:11 +0100

author
goetz
date
Wed, 11 Dec 2013 00:06:11 +0100
changeset 6495
67fa91961822
parent 6486
b0133e4187d3
child 6501
c668f307a4c0
permissions
-rw-r--r--

8029940: PPC64 (part 122): C2 compiler port
Reviewed-by: kvn

     1 /*
     2  * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * Copyright 2012, 2013 SAP AG. 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  */
    26 #include "precompiled.hpp"
    27 #include "asm/assembler.hpp"
    28 #include "asm/assembler.inline.hpp"
    29 #include "asm/macroAssembler.inline.hpp"
    30 #include "compiler/disassembler.hpp"
    31 #include "gc_interface/collectedHeap.inline.hpp"
    32 #include "interpreter/interpreter.hpp"
    33 #include "memory/cardTableModRefBS.hpp"
    34 #include "memory/resourceArea.hpp"
    35 #include "prims/methodHandles.hpp"
    36 #include "runtime/biasedLocking.hpp"
    37 #include "runtime/interfaceSupport.hpp"
    38 #include "runtime/objectMonitor.hpp"
    39 #include "runtime/os.hpp"
    40 #include "runtime/sharedRuntime.hpp"
    41 #include "runtime/stubRoutines.hpp"
    42 #include "utilities/macros.hpp"
    43 #if INCLUDE_ALL_GCS
    44 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
    45 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
    46 #include "gc_implementation/g1/heapRegion.hpp"
    47 #endif // INCLUDE_ALL_GCS
    49 #ifdef PRODUCT
    50 #define BLOCK_COMMENT(str) // nothing
    51 #else
    52 #define BLOCK_COMMENT(str) block_comment(str)
    53 #endif
    55 #ifdef ASSERT
    56 // On RISC, there's no benefit to verifying instruction boundaries.
    57 bool AbstractAssembler::pd_check_instruction_mark() { return false; }
    58 #endif
    60 void MacroAssembler::ld_largeoffset_unchecked(Register d, int si31, Register a, int emit_filler_nop) {
    61   assert(Assembler::is_simm(si31, 31) && si31 >= 0, "si31 out of range");
    62   if (Assembler::is_simm(si31, 16)) {
    63     ld(d, si31, a);
    64     if (emit_filler_nop) nop();
    65   } else {
    66     const int hi = MacroAssembler::largeoffset_si16_si16_hi(si31);
    67     const int lo = MacroAssembler::largeoffset_si16_si16_lo(si31);
    68     addis(d, a, hi);
    69     ld(d, lo, d);
    70   }
    71 }
    73 void MacroAssembler::ld_largeoffset(Register d, int si31, Register a, int emit_filler_nop) {
    74   assert_different_registers(d, a);
    75   ld_largeoffset_unchecked(d, si31, a, emit_filler_nop);
    76 }
    78 void MacroAssembler::load_sized_value(Register dst, RegisterOrConstant offs, Register base,
    79                                       size_t size_in_bytes, bool is_signed) {
    80   switch (size_in_bytes) {
    81   case  8:              ld(dst, offs, base);                         break;
    82   case  4:  is_signed ? lwa(dst, offs, base) : lwz(dst, offs, base); break;
    83   case  2:  is_signed ? lha(dst, offs, base) : lhz(dst, offs, base); break;
    84   case  1:  lbz(dst, offs, base); if (is_signed) extsb(dst, dst);    break; // lba doesn't exist :(
    85   default:  ShouldNotReachHere();
    86   }
    87 }
    89 void MacroAssembler::store_sized_value(Register dst, RegisterOrConstant offs, Register base,
    90                                        size_t size_in_bytes) {
    91   switch (size_in_bytes) {
    92   case  8:  std(dst, offs, base); break;
    93   case  4:  stw(dst, offs, base); break;
    94   case  2:  sth(dst, offs, base); break;
    95   case  1:  stb(dst, offs, base); break;
    96   default:  ShouldNotReachHere();
    97   }
    98 }
   100 void MacroAssembler::align(int modulus, int max, int rem) {
   101   int padding = (rem + modulus - (offset() % modulus)) % modulus;
   102   if (padding > max) return;
   103   for (int c = (padding >> 2); c > 0; --c) { nop(); }
   104 }
   106 // Issue instructions that calculate given TOC from global TOC.
   107 void MacroAssembler::calculate_address_from_global_toc(Register dst, address addr, bool hi16, bool lo16,
   108                                                        bool add_relocation, bool emit_dummy_addr) {
   109   int offset = -1;
   110   if (emit_dummy_addr) {
   111     offset = -128; // dummy address
   112   } else if (addr != (address)(intptr_t)-1) {
   113     offset = MacroAssembler::offset_to_global_toc(addr);
   114   }
   116   if (hi16) {
   117     addis(dst, R29, MacroAssembler::largeoffset_si16_si16_hi(offset));
   118   }
   119   if (lo16) {
   120     if (add_relocation) {
   121       // Relocate at the addi to avoid confusion with a load from the method's TOC.
   122       relocate(internal_word_Relocation::spec(addr));
   123     }
   124     addi(dst, dst, MacroAssembler::largeoffset_si16_si16_lo(offset));
   125   }
   126 }
   128 int MacroAssembler::patch_calculate_address_from_global_toc_at(address a, address bound, address addr) {
   129   const int offset = MacroAssembler::offset_to_global_toc(addr);
   131   const address inst2_addr = a;
   132   const int inst2 = *(int *)inst2_addr;
   134   // The relocation points to the second instruction, the addi,
   135   // and the addi reads and writes the same register dst.
   136   const int dst = inv_rt_field(inst2);
   137   assert(is_addi(inst2) && inv_ra_field(inst2) == dst, "must be addi reading and writing dst");
   139   // Now, find the preceding addis which writes to dst.
   140   int inst1 = 0;
   141   address inst1_addr = inst2_addr - BytesPerInstWord;
   142   while (inst1_addr >= bound) {
   143     inst1 = *(int *) inst1_addr;
   144     if (is_addis(inst1) && inv_rt_field(inst1) == dst) {
   145       // Stop, found the addis which writes dst.
   146       break;
   147     }
   148     inst1_addr -= BytesPerInstWord;
   149   }
   151   assert(is_addis(inst1) && inv_ra_field(inst1) == 29 /* R29 */, "source must be global TOC");
   152   set_imm((int *)inst1_addr, MacroAssembler::largeoffset_si16_si16_hi(offset));
   153   set_imm((int *)inst2_addr, MacroAssembler::largeoffset_si16_si16_lo(offset));
   154   return (int)((intptr_t)addr - (intptr_t)inst1_addr);
   155 }
   157 address MacroAssembler::get_address_of_calculate_address_from_global_toc_at(address a, address bound) {
   158   const address inst2_addr = a;
   159   const int inst2 = *(int *)inst2_addr;
   161   // The relocation points to the second instruction, the addi,
   162   // and the addi reads and writes the same register dst.
   163   const int dst = inv_rt_field(inst2);
   164   assert(is_addi(inst2) && inv_ra_field(inst2) == dst, "must be addi reading and writing dst");
   166   // Now, find the preceding addis which writes to dst.
   167   int inst1 = 0;
   168   address inst1_addr = inst2_addr - BytesPerInstWord;
   169   while (inst1_addr >= bound) {
   170     inst1 = *(int *) inst1_addr;
   171     if (is_addis(inst1) && inv_rt_field(inst1) == dst) {
   172       // stop, found the addis which writes dst
   173       break;
   174     }
   175     inst1_addr -= BytesPerInstWord;
   176   }
   178   assert(is_addis(inst1) && inv_ra_field(inst1) == 29 /* R29 */, "source must be global TOC");
   180   int offset = (get_imm(inst1_addr, 0) << 16) + get_imm(inst2_addr, 0);
   181   // -1 is a special case
   182   if (offset == -1) {
   183     return (address)(intptr_t)-1;
   184   } else {
   185     return global_toc() + offset;
   186   }
   187 }
   189 #ifdef _LP64
   190 // Patch compressed oops or klass constants.
   191 // Assembler sequence is
   192 // 1) compressed oops:
   193 //    lis  rx = const.hi
   194 //    ori rx = rx | const.lo
   195 // 2) compressed klass:
   196 //    lis  rx = const.hi
   197 //    clrldi rx = rx & 0xFFFFffff // clearMS32b, optional
   198 //    ori rx = rx | const.lo
   199 // Clrldi will be passed by.
   200 int MacroAssembler::patch_set_narrow_oop(address a, address bound, narrowOop data) {
   201   assert(UseCompressedOops, "Should only patch compressed oops");
   203   const address inst2_addr = a;
   204   const int inst2 = *(int *)inst2_addr;
   206   // The relocation points to the second instruction, the ori,
   207   // and the ori reads and writes the same register dst.
   208   const int dst = inv_rta_field(inst2);
   209   assert(is_ori(inst2) && inv_rs_field(inst2) == dst, "must be addi reading and writing dst");
   210   // Now, find the preceding addis which writes to dst.
   211   int inst1 = 0;
   212   address inst1_addr = inst2_addr - BytesPerInstWord;
   213   bool inst1_found = false;
   214   while (inst1_addr >= bound) {
   215     inst1 = *(int *)inst1_addr;
   216     if (is_lis(inst1) && inv_rs_field(inst1) == dst) { inst1_found = true; break; }
   217     inst1_addr -= BytesPerInstWord;
   218   }
   219   assert(inst1_found, "inst is not lis");
   221   int xc = (data >> 16) & 0xffff;
   222   int xd = (data >>  0) & 0xffff;
   224   set_imm((int *)inst1_addr, (short)(xc)); // see enc_load_con_narrow_hi/_lo
   225   set_imm((int *)inst2_addr, (short)(xd));
   227   return (int)((intptr_t)inst2_addr - (intptr_t)inst1_addr);
   228 }
   230 // Get compressed oop or klass constant.
   231 narrowOop MacroAssembler::get_narrow_oop(address a, address bound) {
   232   assert(UseCompressedOops, "Should only patch compressed oops");
   234   const address inst2_addr = a;
   235   const int inst2 = *(int *)inst2_addr;
   237   // The relocation points to the second instruction, the ori,
   238   // and the ori reads and writes the same register dst.
   239   const int dst = inv_rta_field(inst2);
   240   assert(is_ori(inst2) && inv_rs_field(inst2) == dst, "must be addi reading and writing dst");
   241   // Now, find the preceding lis which writes to dst.
   242   int inst1 = 0;
   243   address inst1_addr = inst2_addr - BytesPerInstWord;
   244   bool inst1_found = false;
   246   while (inst1_addr >= bound) {
   247     inst1 = *(int *) inst1_addr;
   248     if (is_lis(inst1) && inv_rs_field(inst1) == dst) { inst1_found = true; break;}
   249     inst1_addr -= BytesPerInstWord;
   250   }
   251   assert(inst1_found, "inst is not lis");
   253   uint xl = ((unsigned int) (get_imm(inst2_addr, 0) & 0xffff));
   254   uint xh = (((get_imm(inst1_addr, 0)) & 0xffff) << 16);
   256   return (int) (xl | xh);
   257 }
   258 #endif // _LP64
   260 void MacroAssembler::load_const_from_method_toc(Register dst, AddressLiteral& a, Register toc) {
   261   int toc_offset = 0;
   262   // Use RelocationHolder::none for the constant pool entry, otherwise
   263   // we will end up with a failing NativeCall::verify(x) where x is
   264   // the address of the constant pool entry.
   265   // FIXME: We should insert relocation information for oops at the constant
   266   // pool entries instead of inserting it at the loads; patching of a constant
   267   // pool entry should be less expensive.
   268   address oop_address = address_constant((address)a.value(), RelocationHolder::none);
   269   // Relocate at the pc of the load.
   270   relocate(a.rspec());
   271   toc_offset = (int)(oop_address - code()->consts()->start());
   272   ld_largeoffset_unchecked(dst, toc_offset, toc, true);
   273 }
   275 bool MacroAssembler::is_load_const_from_method_toc_at(address a) {
   276   const address inst1_addr = a;
   277   const int inst1 = *(int *)inst1_addr;
   279    // The relocation points to the ld or the addis.
   280    return (is_ld(inst1)) ||
   281           (is_addis(inst1) && inv_ra_field(inst1) != 0);
   282 }
   284 int MacroAssembler::get_offset_of_load_const_from_method_toc_at(address a) {
   285   assert(is_load_const_from_method_toc_at(a), "must be load_const_from_method_toc");
   287   const address inst1_addr = a;
   288   const int inst1 = *(int *)inst1_addr;
   290   if (is_ld(inst1)) {
   291     return inv_d1_field(inst1);
   292   } else if (is_addis(inst1)) {
   293     const int dst = inv_rt_field(inst1);
   295     // Now, find the succeeding ld which reads and writes to dst.
   296     address inst2_addr = inst1_addr + BytesPerInstWord;
   297     int inst2 = 0;
   298     while (true) {
   299       inst2 = *(int *) inst2_addr;
   300       if (is_ld(inst2) && inv_ra_field(inst2) == dst && inv_rt_field(inst2) == dst) {
   301         // Stop, found the ld which reads and writes dst.
   302         break;
   303       }
   304       inst2_addr += BytesPerInstWord;
   305     }
   306     return (inv_d1_field(inst1) << 16) + inv_d1_field(inst2);
   307   }
   308   ShouldNotReachHere();
   309   return 0;
   310 }
   312 // Get the constant from a `load_const' sequence.
   313 long MacroAssembler::get_const(address a) {
   314   assert(is_load_const_at(a), "not a load of a constant");
   315   const int *p = (const int*) a;
   316   unsigned long x = (((unsigned long) (get_imm(a,0) & 0xffff)) << 48);
   317   if (is_ori(*(p+1))) {
   318     x |= (((unsigned long) (get_imm(a,1) & 0xffff)) << 32);
   319     x |= (((unsigned long) (get_imm(a,3) & 0xffff)) << 16);
   320     x |= (((unsigned long) (get_imm(a,4) & 0xffff)));
   321   } else if (is_lis(*(p+1))) {
   322     x |= (((unsigned long) (get_imm(a,2) & 0xffff)) << 32);
   323     x |= (((unsigned long) (get_imm(a,1) & 0xffff)) << 16);
   324     x |= (((unsigned long) (get_imm(a,3) & 0xffff)));
   325   } else {
   326     ShouldNotReachHere();
   327     return (long) 0;
   328   }
   329   return (long) x;
   330 }
   332 // Patch the 64 bit constant of a `load_const' sequence. This is a low
   333 // level procedure. It neither flushes the instruction cache nor is it
   334 // mt safe.
   335 void MacroAssembler::patch_const(address a, long x) {
   336   assert(is_load_const_at(a), "not a load of a constant");
   337   int *p = (int*) a;
   338   if (is_ori(*(p+1))) {
   339     set_imm(0 + p, (x >> 48) & 0xffff);
   340     set_imm(1 + p, (x >> 32) & 0xffff);
   341     set_imm(3 + p, (x >> 16) & 0xffff);
   342     set_imm(4 + p, x & 0xffff);
   343   } else if (is_lis(*(p+1))) {
   344     set_imm(0 + p, (x >> 48) & 0xffff);
   345     set_imm(2 + p, (x >> 32) & 0xffff);
   346     set_imm(1 + p, (x >> 16) & 0xffff);
   347     set_imm(3 + p, x & 0xffff);
   348   } else {
   349     ShouldNotReachHere();
   350   }
   351 }
   353 AddressLiteral MacroAssembler::allocate_metadata_address(Metadata* obj) {
   354   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
   355   int index = oop_recorder()->allocate_metadata_index(obj);
   356   RelocationHolder rspec = metadata_Relocation::spec(index);
   357   return AddressLiteral((address)obj, rspec);
   358 }
   360 AddressLiteral MacroAssembler::constant_metadata_address(Metadata* obj) {
   361   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
   362   int index = oop_recorder()->find_index(obj);
   363   RelocationHolder rspec = metadata_Relocation::spec(index);
   364   return AddressLiteral((address)obj, rspec);
   365 }
   367 AddressLiteral MacroAssembler::allocate_oop_address(jobject obj) {
   368   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
   369   int oop_index = oop_recorder()->allocate_oop_index(obj);
   370   return AddressLiteral(address(obj), oop_Relocation::spec(oop_index));
   371 }
   373 AddressLiteral MacroAssembler::constant_oop_address(jobject obj) {
   374   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
   375   int oop_index = oop_recorder()->find_index(obj);
   376   return AddressLiteral(address(obj), oop_Relocation::spec(oop_index));
   377 }
   379 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
   380                                                       Register tmp, int offset) {
   381   intptr_t value = *delayed_value_addr;
   382   if (value != 0) {
   383     return RegisterOrConstant(value + offset);
   384   }
   386   // Load indirectly to solve generation ordering problem.
   387   // static address, no relocation
   388   int simm16_offset = load_const_optimized(tmp, delayed_value_addr, noreg, true);
   389   ld(tmp, simm16_offset, tmp); // must be aligned ((xa & 3) == 0)
   391   if (offset != 0) {
   392     addi(tmp, tmp, offset);
   393   }
   395   return RegisterOrConstant(tmp);
   396 }
   398 #ifndef PRODUCT
   399 void MacroAssembler::pd_print_patched_instruction(address branch) {
   400   Unimplemented(); // TODO: PPC port
   401 }
   402 #endif // ndef PRODUCT
   404 // Conditional far branch for destinations encodable in 24+2 bits.
   405 void MacroAssembler::bc_far(int boint, int biint, Label& dest, int optimize) {
   407   // If requested by flag optimize, relocate the bc_far as a
   408   // runtime_call and prepare for optimizing it when the code gets
   409   // relocated.
   410   if (optimize == bc_far_optimize_on_relocate) {
   411     relocate(relocInfo::runtime_call_type);
   412   }
   414   // variant 2:
   415   //
   416   //    b!cxx SKIP
   417   //    bxx   DEST
   418   //  SKIP:
   419   //
   421   const int opposite_boint = add_bhint_to_boint(opposite_bhint(inv_boint_bhint(boint)),
   422                                                 opposite_bcond(inv_boint_bcond(boint)));
   424   // We emit two branches.
   425   // First, a conditional branch which jumps around the far branch.
   426   const address not_taken_pc = pc() + 2 * BytesPerInstWord;
   427   const address bc_pc        = pc();
   428   bc(opposite_boint, biint, not_taken_pc);
   430   const int bc_instr = *(int*)bc_pc;
   431   assert(not_taken_pc == (address)inv_bd_field(bc_instr, (intptr_t)bc_pc), "postcondition");
   432   assert(opposite_boint == inv_bo_field(bc_instr), "postcondition");
   433   assert(boint == add_bhint_to_boint(opposite_bhint(inv_boint_bhint(inv_bo_field(bc_instr))),
   434                                      opposite_bcond(inv_boint_bcond(inv_bo_field(bc_instr)))),
   435          "postcondition");
   436   assert(biint == inv_bi_field(bc_instr), "postcondition");
   438   // Second, an unconditional far branch which jumps to dest.
   439   // Note: target(dest) remembers the current pc (see CodeSection::target)
   440   //       and returns the current pc if the label is not bound yet; when
   441   //       the label gets bound, the unconditional far branch will be patched.
   442   const address target_pc = target(dest);
   443   const address b_pc  = pc();
   444   b(target_pc);
   446   assert(not_taken_pc == pc(),                     "postcondition");
   447   assert(dest.is_bound() || target_pc == b_pc, "postcondition");
   448 }
   450 bool MacroAssembler::is_bc_far_at(address instruction_addr) {
   451   return is_bc_far_variant1_at(instruction_addr) ||
   452          is_bc_far_variant2_at(instruction_addr) ||
   453          is_bc_far_variant3_at(instruction_addr);
   454 }
   456 address MacroAssembler::get_dest_of_bc_far_at(address instruction_addr) {
   457   if (is_bc_far_variant1_at(instruction_addr)) {
   458     const address instruction_1_addr = instruction_addr;
   459     const int instruction_1 = *(int*)instruction_1_addr;
   460     return (address)inv_bd_field(instruction_1, (intptr_t)instruction_1_addr);
   461   } else if (is_bc_far_variant2_at(instruction_addr)) {
   462     const address instruction_2_addr = instruction_addr + 4;
   463     return bxx_destination(instruction_2_addr);
   464   } else if (is_bc_far_variant3_at(instruction_addr)) {
   465     return instruction_addr + 8;
   466   }
   467   // variant 4 ???
   468   ShouldNotReachHere();
   469   return NULL;
   470 }
   471 void MacroAssembler::set_dest_of_bc_far_at(address instruction_addr, address dest) {
   473   if (is_bc_far_variant3_at(instruction_addr)) {
   474     // variant 3, far cond branch to the next instruction, already patched to nops:
   475     //
   476     //    nop
   477     //    endgroup
   478     //  SKIP/DEST:
   479     //
   480     return;
   481   }
   483   // first, extract boint and biint from the current branch
   484   int boint = 0;
   485   int biint = 0;
   487   ResourceMark rm;
   488   const int code_size = 2 * BytesPerInstWord;
   489   CodeBuffer buf(instruction_addr, code_size);
   490   MacroAssembler masm(&buf);
   491   if (is_bc_far_variant2_at(instruction_addr) && dest == instruction_addr + 8) {
   492     // Far branch to next instruction: Optimize it by patching nops (produce variant 3).
   493     masm.nop();
   494     masm.endgroup();
   495   } else {
   496     if (is_bc_far_variant1_at(instruction_addr)) {
   497       // variant 1, the 1st instruction contains the destination address:
   498       //
   499       //    bcxx  DEST
   500       //    endgroup
   501       //
   502       const int instruction_1 = *(int*)(instruction_addr);
   503       boint = inv_bo_field(instruction_1);
   504       biint = inv_bi_field(instruction_1);
   505     } else if (is_bc_far_variant2_at(instruction_addr)) {
   506       // variant 2, the 2nd instruction contains the destination address:
   507       //
   508       //    b!cxx SKIP
   509       //    bxx   DEST
   510       //  SKIP:
   511       //
   512       const int instruction_1 = *(int*)(instruction_addr);
   513       boint = add_bhint_to_boint(opposite_bhint(inv_boint_bhint(inv_bo_field(instruction_1))),
   514           opposite_bcond(inv_boint_bcond(inv_bo_field(instruction_1))));
   515       biint = inv_bi_field(instruction_1);
   516     } else {
   517       // variant 4???
   518       ShouldNotReachHere();
   519     }
   521     // second, set the new branch destination and optimize the code
   522     if (dest != instruction_addr + 4 && // the bc_far is still unbound!
   523         masm.is_within_range_of_bcxx(dest, instruction_addr)) {
   524       // variant 1:
   525       //
   526       //    bcxx  DEST
   527       //    endgroup
   528       //
   529       masm.bc(boint, biint, dest);
   530       masm.endgroup();
   531     } else {
   532       // variant 2:
   533       //
   534       //    b!cxx SKIP
   535       //    bxx   DEST
   536       //  SKIP:
   537       //
   538       const int opposite_boint = add_bhint_to_boint(opposite_bhint(inv_boint_bhint(boint)),
   539                                                     opposite_bcond(inv_boint_bcond(boint)));
   540       const address not_taken_pc = masm.pc() + 2 * BytesPerInstWord;
   541       masm.bc(opposite_boint, biint, not_taken_pc);
   542       masm.b(dest);
   543     }
   544   }
   545   ICache::ppc64_flush_icache_bytes(instruction_addr, code_size);
   546 }
   548 // Emit a NOT mt-safe patchable 64 bit absolute call/jump.
   549 void MacroAssembler::bxx64_patchable(address dest, relocInfo::relocType rt, bool link) {
   550   // get current pc
   551   uint64_t start_pc = (uint64_t) pc();
   553   const address pc_of_bl = (address) (start_pc + (6*BytesPerInstWord)); // bl is last
   554   const address pc_of_b  = (address) (start_pc + (0*BytesPerInstWord)); // b is first
   556   // relocate here
   557   if (rt != relocInfo::none) {
   558     relocate(rt);
   559   }
   561   if ( ReoptimizeCallSequences &&
   562        (( link && is_within_range_of_b(dest, pc_of_bl)) ||
   563         (!link && is_within_range_of_b(dest, pc_of_b)))) {
   564     // variant 2:
   565     // Emit an optimized, pc-relative call/jump.
   567     if (link) {
   568       // some padding
   569       nop();
   570       nop();
   571       nop();
   572       nop();
   573       nop();
   574       nop();
   576       // do the call
   577       assert(pc() == pc_of_bl, "just checking");
   578       bl(dest, relocInfo::none);
   579     } else {
   580       // do the jump
   581       assert(pc() == pc_of_b, "just checking");
   582       b(dest, relocInfo::none);
   584       // some padding
   585       nop();
   586       nop();
   587       nop();
   588       nop();
   589       nop();
   590       nop();
   591     }
   593     // Assert that we can identify the emitted call/jump.
   594     assert(is_bxx64_patchable_variant2_at((address)start_pc, link),
   595            "can't identify emitted call");
   596   } else {
   597     // variant 1:
   599     mr(R0, R11);  // spill R11 -> R0.
   601     // Load the destination address into CTR,
   602     // calculate destination relative to global toc.
   603     calculate_address_from_global_toc(R11, dest, true, true, false);
   605     mtctr(R11);
   606     mr(R11, R0);  // spill R11 <- R0.
   607     nop();
   609     // do the call/jump
   610     if (link) {
   611       bctrl();
   612     } else{
   613       bctr();
   614     }
   615     // Assert that we can identify the emitted call/jump.
   616     assert(is_bxx64_patchable_variant1b_at((address)start_pc, link),
   617            "can't identify emitted call");
   618   }
   620   // Assert that we can identify the emitted call/jump.
   621   assert(is_bxx64_patchable_at((address)start_pc, link),
   622          "can't identify emitted call");
   623   assert(get_dest_of_bxx64_patchable_at((address)start_pc, link) == dest,
   624          "wrong encoding of dest address");
   625 }
   627 // Identify a bxx64_patchable instruction.
   628 bool MacroAssembler::is_bxx64_patchable_at(address instruction_addr, bool link) {
   629   return is_bxx64_patchable_variant1b_at(instruction_addr, link)
   630     //|| is_bxx64_patchable_variant1_at(instruction_addr, link)
   631       || is_bxx64_patchable_variant2_at(instruction_addr, link);
   632 }
   634 // Does the call64_patchable instruction use a pc-relative encoding of
   635 // the call destination?
   636 bool MacroAssembler::is_bxx64_patchable_pcrelative_at(address instruction_addr, bool link) {
   637   // variant 2 is pc-relative
   638   return is_bxx64_patchable_variant2_at(instruction_addr, link);
   639 }
   641 // Identify variant 1.
   642 bool MacroAssembler::is_bxx64_patchable_variant1_at(address instruction_addr, bool link) {
   643   unsigned int* instr = (unsigned int*) instruction_addr;
   644   return (link ? is_bctrl(instr[6]) : is_bctr(instr[6])) // bctr[l]
   645       && is_mtctr(instr[5]) // mtctr
   646     && is_load_const_at(instruction_addr);
   647 }
   649 // Identify variant 1b: load destination relative to global toc.
   650 bool MacroAssembler::is_bxx64_patchable_variant1b_at(address instruction_addr, bool link) {
   651   unsigned int* instr = (unsigned int*) instruction_addr;
   652   return (link ? is_bctrl(instr[6]) : is_bctr(instr[6])) // bctr[l]
   653     && is_mtctr(instr[3]) // mtctr
   654     && is_calculate_address_from_global_toc_at(instruction_addr + 2*BytesPerInstWord, instruction_addr);
   655 }
   657 // Identify variant 2.
   658 bool MacroAssembler::is_bxx64_patchable_variant2_at(address instruction_addr, bool link) {
   659   unsigned int* instr = (unsigned int*) instruction_addr;
   660   if (link) {
   661     return is_bl (instr[6])  // bl dest is last
   662       && is_nop(instr[0])  // nop
   663       && is_nop(instr[1])  // nop
   664       && is_nop(instr[2])  // nop
   665       && is_nop(instr[3])  // nop
   666       && is_nop(instr[4])  // nop
   667       && is_nop(instr[5]); // nop
   668   } else {
   669     return is_b  (instr[0])  // b  dest is first
   670       && is_nop(instr[1])  // nop
   671       && is_nop(instr[2])  // nop
   672       && is_nop(instr[3])  // nop
   673       && is_nop(instr[4])  // nop
   674       && is_nop(instr[5])  // nop
   675       && is_nop(instr[6]); // nop
   676   }
   677 }
   679 // Set dest address of a bxx64_patchable instruction.
   680 void MacroAssembler::set_dest_of_bxx64_patchable_at(address instruction_addr, address dest, bool link) {
   681   ResourceMark rm;
   682   int code_size = MacroAssembler::bxx64_patchable_size;
   683   CodeBuffer buf(instruction_addr, code_size);
   684   MacroAssembler masm(&buf);
   685   masm.bxx64_patchable(dest, relocInfo::none, link);
   686   ICache::ppc64_flush_icache_bytes(instruction_addr, code_size);
   687 }
   689 // Get dest address of a bxx64_patchable instruction.
   690 address MacroAssembler::get_dest_of_bxx64_patchable_at(address instruction_addr, bool link) {
   691   if (is_bxx64_patchable_variant1_at(instruction_addr, link)) {
   692     return (address) (unsigned long) get_const(instruction_addr);
   693   } else if (is_bxx64_patchable_variant2_at(instruction_addr, link)) {
   694     unsigned int* instr = (unsigned int*) instruction_addr;
   695     if (link) {
   696       const int instr_idx = 6; // bl is last
   697       int branchoffset = branch_destination(instr[instr_idx], 0);
   698       return instruction_addr + branchoffset + instr_idx*BytesPerInstWord;
   699     } else {
   700       const int instr_idx = 0; // b is first
   701       int branchoffset = branch_destination(instr[instr_idx], 0);
   702       return instruction_addr + branchoffset + instr_idx*BytesPerInstWord;
   703     }
   704   // Load dest relative to global toc.
   705   } else if (is_bxx64_patchable_variant1b_at(instruction_addr, link)) {
   706     return get_address_of_calculate_address_from_global_toc_at(instruction_addr + 2*BytesPerInstWord,
   707                                                                instruction_addr);
   708   } else {
   709     ShouldNotReachHere();
   710     return NULL;
   711   }
   712 }
   714 // Uses ordering which corresponds to ABI:
   715 //    _savegpr0_14:  std  r14,-144(r1)
   716 //    _savegpr0_15:  std  r15,-136(r1)
   717 //    _savegpr0_16:  std  r16,-128(r1)
   718 void MacroAssembler::save_nonvolatile_gprs(Register dst, int offset) {
   719   std(R14, offset, dst);   offset += 8;
   720   std(R15, offset, dst);   offset += 8;
   721   std(R16, offset, dst);   offset += 8;
   722   std(R17, offset, dst);   offset += 8;
   723   std(R18, offset, dst);   offset += 8;
   724   std(R19, offset, dst);   offset += 8;
   725   std(R20, offset, dst);   offset += 8;
   726   std(R21, offset, dst);   offset += 8;
   727   std(R22, offset, dst);   offset += 8;
   728   std(R23, offset, dst);   offset += 8;
   729   std(R24, offset, dst);   offset += 8;
   730   std(R25, offset, dst);   offset += 8;
   731   std(R26, offset, dst);   offset += 8;
   732   std(R27, offset, dst);   offset += 8;
   733   std(R28, offset, dst);   offset += 8;
   734   std(R29, offset, dst);   offset += 8;
   735   std(R30, offset, dst);   offset += 8;
   736   std(R31, offset, dst);   offset += 8;
   738   stfd(F14, offset, dst);   offset += 8;
   739   stfd(F15, offset, dst);   offset += 8;
   740   stfd(F16, offset, dst);   offset += 8;
   741   stfd(F17, offset, dst);   offset += 8;
   742   stfd(F18, offset, dst);   offset += 8;
   743   stfd(F19, offset, dst);   offset += 8;
   744   stfd(F20, offset, dst);   offset += 8;
   745   stfd(F21, offset, dst);   offset += 8;
   746   stfd(F22, offset, dst);   offset += 8;
   747   stfd(F23, offset, dst);   offset += 8;
   748   stfd(F24, offset, dst);   offset += 8;
   749   stfd(F25, offset, dst);   offset += 8;
   750   stfd(F26, offset, dst);   offset += 8;
   751   stfd(F27, offset, dst);   offset += 8;
   752   stfd(F28, offset, dst);   offset += 8;
   753   stfd(F29, offset, dst);   offset += 8;
   754   stfd(F30, offset, dst);   offset += 8;
   755   stfd(F31, offset, dst);
   756 }
   758 // Uses ordering which corresponds to ABI:
   759 //    _restgpr0_14:  ld   r14,-144(r1)
   760 //    _restgpr0_15:  ld   r15,-136(r1)
   761 //    _restgpr0_16:  ld   r16,-128(r1)
   762 void MacroAssembler::restore_nonvolatile_gprs(Register src, int offset) {
   763   ld(R14, offset, src);   offset += 8;
   764   ld(R15, offset, src);   offset += 8;
   765   ld(R16, offset, src);   offset += 8;
   766   ld(R17, offset, src);   offset += 8;
   767   ld(R18, offset, src);   offset += 8;
   768   ld(R19, offset, src);   offset += 8;
   769   ld(R20, offset, src);   offset += 8;
   770   ld(R21, offset, src);   offset += 8;
   771   ld(R22, offset, src);   offset += 8;
   772   ld(R23, offset, src);   offset += 8;
   773   ld(R24, offset, src);   offset += 8;
   774   ld(R25, offset, src);   offset += 8;
   775   ld(R26, offset, src);   offset += 8;
   776   ld(R27, offset, src);   offset += 8;
   777   ld(R28, offset, src);   offset += 8;
   778   ld(R29, offset, src);   offset += 8;
   779   ld(R30, offset, src);   offset += 8;
   780   ld(R31, offset, src);   offset += 8;
   782   // FP registers
   783   lfd(F14, offset, src);   offset += 8;
   784   lfd(F15, offset, src);   offset += 8;
   785   lfd(F16, offset, src);   offset += 8;
   786   lfd(F17, offset, src);   offset += 8;
   787   lfd(F18, offset, src);   offset += 8;
   788   lfd(F19, offset, src);   offset += 8;
   789   lfd(F20, offset, src);   offset += 8;
   790   lfd(F21, offset, src);   offset += 8;
   791   lfd(F22, offset, src);   offset += 8;
   792   lfd(F23, offset, src);   offset += 8;
   793   lfd(F24, offset, src);   offset += 8;
   794   lfd(F25, offset, src);   offset += 8;
   795   lfd(F26, offset, src);   offset += 8;
   796   lfd(F27, offset, src);   offset += 8;
   797   lfd(F28, offset, src);   offset += 8;
   798   lfd(F29, offset, src);   offset += 8;
   799   lfd(F30, offset, src);   offset += 8;
   800   lfd(F31, offset, src);
   801 }
   803 // For verify_oops.
   804 void MacroAssembler::save_volatile_gprs(Register dst, int offset) {
   805   std(R3,  offset, dst);   offset += 8;
   806   std(R4,  offset, dst);   offset += 8;
   807   std(R5,  offset, dst);   offset += 8;
   808   std(R6,  offset, dst);   offset += 8;
   809   std(R7,  offset, dst);   offset += 8;
   810   std(R8,  offset, dst);   offset += 8;
   811   std(R9,  offset, dst);   offset += 8;
   812   std(R10, offset, dst);   offset += 8;
   813   std(R11, offset, dst);   offset += 8;
   814   std(R12, offset, dst);
   815 }
   817 // For verify_oops.
   818 void MacroAssembler::restore_volatile_gprs(Register src, int offset) {
   819   ld(R3,  offset, src);   offset += 8;
   820   ld(R4,  offset, src);   offset += 8;
   821   ld(R5,  offset, src);   offset += 8;
   822   ld(R6,  offset, src);   offset += 8;
   823   ld(R7,  offset, src);   offset += 8;
   824   ld(R8,  offset, src);   offset += 8;
   825   ld(R9,  offset, src);   offset += 8;
   826   ld(R10, offset, src);   offset += 8;
   827   ld(R11, offset, src);   offset += 8;
   828   ld(R12, offset, src);
   829 }
   831 void MacroAssembler::save_LR_CR(Register tmp) {
   832   mfcr(tmp);
   833   std(tmp, _abi(cr), R1_SP);
   834   mflr(tmp);
   835   std(tmp, _abi(lr), R1_SP);
   836   // Tmp must contain lr on exit! (see return_addr and prolog in ppc64.ad)
   837 }
   839 void MacroAssembler::restore_LR_CR(Register tmp) {
   840   assert(tmp != R1_SP, "must be distinct");
   841   ld(tmp, _abi(lr), R1_SP);
   842   mtlr(tmp);
   843   ld(tmp, _abi(cr), R1_SP);
   844   mtcr(tmp);
   845 }
   847 address MacroAssembler::get_PC_trash_LR(Register result) {
   848   Label L;
   849   bl(L);
   850   bind(L);
   851   address lr_pc = pc();
   852   mflr(result);
   853   return lr_pc;
   854 }
   856 void MacroAssembler::resize_frame(Register offset, Register tmp) {
   857 #ifdef ASSERT
   858   assert_different_registers(offset, tmp, R1_SP);
   859   andi_(tmp, offset, frame::alignment_in_bytes-1);
   860   asm_assert_eq("resize_frame: unaligned", 0x204);
   861 #endif
   863   // tmp <- *(SP)
   864   ld(tmp, _abi(callers_sp), R1_SP);
   865   // addr <- SP + offset;
   866   // *(addr) <- tmp;
   867   // SP <- addr
   868   stdux(tmp, R1_SP, offset);
   869 }
   871 void MacroAssembler::resize_frame(int offset, Register tmp) {
   872   assert(is_simm(offset, 16), "too big an offset");
   873   assert_different_registers(tmp, R1_SP);
   874   assert((offset & (frame::alignment_in_bytes-1))==0, "resize_frame: unaligned");
   875   // tmp <- *(SP)
   876   ld(tmp, _abi(callers_sp), R1_SP);
   877   // addr <- SP + offset;
   878   // *(addr) <- tmp;
   879   // SP <- addr
   880   stdu(tmp, offset, R1_SP);
   881 }
   883 void MacroAssembler::resize_frame_absolute(Register addr, Register tmp1, Register tmp2) {
   884   // (addr == tmp1) || (addr == tmp2) is allowed here!
   885   assert(tmp1 != tmp2, "must be distinct");
   887   // compute offset w.r.t. current stack pointer
   888   // tmp_1 <- addr - SP (!)
   889   subf(tmp1, R1_SP, addr);
   891   // atomically update SP keeping back link.
   892   resize_frame(tmp1/* offset */, tmp2/* tmp */);
   893 }
   895 void MacroAssembler::push_frame(Register bytes, Register tmp) {
   896 #ifdef ASSERT
   897   assert(bytes != R0, "r0 not allowed here");
   898   andi_(R0, bytes, frame::alignment_in_bytes-1);
   899   asm_assert_eq("push_frame(Reg, Reg): unaligned", 0x203);
   900 #endif
   901   neg(tmp, bytes);
   902   stdux(R1_SP, R1_SP, tmp);
   903 }
   905 // Push a frame of size `bytes'.
   906 void MacroAssembler::push_frame(unsigned int bytes, Register tmp) {
   907   long offset = align_addr(bytes, frame::alignment_in_bytes);
   908   if (is_simm(-offset, 16)) {
   909     stdu(R1_SP, -offset, R1_SP);
   910   } else {
   911     load_const(tmp, -offset);
   912     stdux(R1_SP, R1_SP, tmp);
   913   }
   914 }
   916 // Push a frame of size `bytes' plus abi112 on top.
   917 void MacroAssembler::push_frame_abi112(unsigned int bytes, Register tmp) {
   918   push_frame(bytes + frame::abi_112_size, tmp);
   919 }
   921 // Setup up a new C frame with a spill area for non-volatile GPRs and
   922 // additional space for local variables.
   923 void MacroAssembler::push_frame_abi112_nonvolatiles(unsigned int bytes,
   924                                                     Register tmp) {
   925   push_frame(bytes + frame::abi_112_size + frame::spill_nonvolatiles_size, tmp);
   926 }
   928 // Pop current C frame.
   929 void MacroAssembler::pop_frame() {
   930   ld(R1_SP, _abi(callers_sp), R1_SP);
   931 }
   933 // Generic version of a call to C function via a function descriptor
   934 // with variable support for C calling conventions (TOC, ENV, etc.).
   935 // Updates and returns _last_calls_return_pc.
   936 address MacroAssembler::branch_to(Register function_descriptor, bool and_link, bool save_toc_before_call,
   937                                   bool restore_toc_after_call, bool load_toc_of_callee, bool load_env_of_callee) {
   938   // we emit standard ptrgl glue code here
   939   assert((function_descriptor != R0), "function_descriptor cannot be R0");
   941   // retrieve necessary entries from the function descriptor
   942   ld(R0, in_bytes(FunctionDescriptor::entry_offset()), function_descriptor);
   943   mtctr(R0);
   945   if (load_toc_of_callee) {
   946     ld(R2_TOC, in_bytes(FunctionDescriptor::toc_offset()), function_descriptor);
   947   }
   948   if (load_env_of_callee) {
   949     ld(R11, in_bytes(FunctionDescriptor::env_offset()), function_descriptor);
   950   } else if (load_toc_of_callee) {
   951     li(R11, 0);
   952   }
   954   // do a call or a branch
   955   if (and_link) {
   956     bctrl();
   957   } else {
   958     bctr();
   959   }
   960   _last_calls_return_pc = pc();
   962   return _last_calls_return_pc;
   963 }
   965 // Call a C function via a function descriptor and use full C calling
   966 // conventions.
   967 // We don't use the TOC in generated code, so there is no need to save
   968 // and restore its value.
   969 address MacroAssembler::call_c(Register fd) {
   970   return branch_to(fd, /*and_link=*/true,
   971                        /*save toc=*/false,
   972                        /*restore toc=*/false,
   973                        /*load toc=*/true,
   974                        /*load env=*/true);
   975 }
   977 address MacroAssembler::call_c_and_return_to_caller(Register fd) {
   978   return branch_to(fd, /*and_link=*/false,
   979                        /*save toc=*/false,
   980                        /*restore toc=*/false,
   981                        /*load toc=*/true,
   982                        /*load env=*/true);
   983 }
   985 address MacroAssembler::call_c(const FunctionDescriptor* fd, relocInfo::relocType rt) {
   986   if (rt != relocInfo::none) {
   987     // this call needs to be relocatable
   988     if (!ReoptimizeCallSequences
   989         || (rt != relocInfo::runtime_call_type && rt != relocInfo::none)
   990         || fd == NULL   // support code-size estimation
   991         || !fd->is_friend_function()
   992         || fd->entry() == NULL) {
   993       // it's not a friend function as defined by class FunctionDescriptor,
   994       // so do a full call-c here.
   995       load_const(R11, (address)fd, R0);
   997       bool has_env = (fd != NULL && fd->env() != NULL);
   998       return branch_to(R11, /*and_link=*/true,
   999                                 /*save toc=*/false,
  1000                                 /*restore toc=*/false,
  1001                                 /*load toc=*/true,
  1002                                 /*load env=*/has_env);
  1003     } else {
  1004       // It's a friend function. Load the entry point and don't care about
  1005       // toc and env. Use an optimizable call instruction, but ensure the
  1006       // same code-size as in the case of a non-friend function.
  1007       nop();
  1008       nop();
  1009       nop();
  1010       bl64_patchable(fd->entry(), rt);
  1011       _last_calls_return_pc = pc();
  1012       return _last_calls_return_pc;
  1014   } else {
  1015     // This call does not need to be relocatable, do more aggressive
  1016     // optimizations.
  1017     if (!ReoptimizeCallSequences
  1018       || !fd->is_friend_function()) {
  1019       // It's not a friend function as defined by class FunctionDescriptor,
  1020       // so do a full call-c here.
  1021       load_const(R11, (address)fd, R0);
  1022       return branch_to(R11, /*and_link=*/true,
  1023                                 /*save toc=*/false,
  1024                                 /*restore toc=*/false,
  1025                                 /*load toc=*/true,
  1026                                 /*load env=*/true);
  1027     } else {
  1028       // it's a friend function, load the entry point and don't care about
  1029       // toc and env.
  1030       address dest = fd->entry();
  1031       if (is_within_range_of_b(dest, pc())) {
  1032         bl(dest);
  1033       } else {
  1034         bl64_patchable(dest, rt);
  1036       _last_calls_return_pc = pc();
  1037       return _last_calls_return_pc;
  1042 // Call a C function.  All constants needed reside in TOC.
  1043 //
  1044 // Read the address to call from the TOC.
  1045 // Read env from TOC, if fd specifies an env.
  1046 // Read new TOC from TOC.
  1047 address MacroAssembler::call_c_using_toc(const FunctionDescriptor* fd,
  1048                                          relocInfo::relocType rt, Register toc) {
  1049   if (!ReoptimizeCallSequences
  1050     || (rt != relocInfo::runtime_call_type && rt != relocInfo::none)
  1051     || !fd->is_friend_function()) {
  1052     // It's not a friend function as defined by class FunctionDescriptor,
  1053     // so do a full call-c here.
  1054     assert(fd->entry() != NULL, "function must be linked");
  1056     AddressLiteral fd_entry(fd->entry());
  1057     load_const_from_method_toc(R11, fd_entry, toc);
  1058     mtctr(R11);
  1059     if (fd->env() == NULL) {
  1060       li(R11, 0);
  1061       nop();
  1062     } else {
  1063       AddressLiteral fd_env(fd->env());
  1064       load_const_from_method_toc(R11, fd_env, toc);
  1066     AddressLiteral fd_toc(fd->toc());
  1067     load_toc_from_toc(R2_TOC, fd_toc, toc);
  1068     // R2_TOC is killed.
  1069     bctrl();
  1070     _last_calls_return_pc = pc();
  1071   } else {
  1072     // It's a friend function, load the entry point and don't care about
  1073     // toc and env. Use an optimizable call instruction, but ensure the
  1074     // same code-size as in the case of a non-friend function.
  1075     nop();
  1076     bl64_patchable(fd->entry(), rt);
  1077     _last_calls_return_pc = pc();
  1079   return _last_calls_return_pc;
  1082 void MacroAssembler::call_VM_base(Register oop_result,
  1083                                   Register last_java_sp,
  1084                                   address  entry_point,
  1085                                   bool     check_exceptions) {
  1086   BLOCK_COMMENT("call_VM {");
  1087   // Determine last_java_sp register.
  1088   if (!last_java_sp->is_valid()) {
  1089     last_java_sp = R1_SP;
  1091   set_top_ijava_frame_at_SP_as_last_Java_frame(last_java_sp, R11_scratch1);
  1093   // ARG1 must hold thread address.
  1094   mr(R3_ARG1, R16_thread);
  1096   address return_pc = call_c((FunctionDescriptor*)entry_point, relocInfo::none);
  1098   reset_last_Java_frame();
  1100   // Check for pending exceptions.
  1101   if (check_exceptions) {
  1102     // We don't check for exceptions here.
  1103     ShouldNotReachHere();
  1106   // Get oop result if there is one and reset the value in the thread.
  1107   if (oop_result->is_valid()) {
  1108     get_vm_result(oop_result);
  1111   _last_calls_return_pc = return_pc;
  1112   BLOCK_COMMENT("} call_VM");
  1115 void MacroAssembler::call_VM_leaf_base(address entry_point) {
  1116   BLOCK_COMMENT("call_VM_leaf {");
  1117   call_c(CAST_FROM_FN_PTR(FunctionDescriptor*, entry_point), relocInfo::none);
  1118   BLOCK_COMMENT("} call_VM_leaf");
  1121 void MacroAssembler::call_VM(Register oop_result, address entry_point, bool check_exceptions) {
  1122   call_VM_base(oop_result, noreg, entry_point, check_exceptions);
  1125 void MacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1,
  1126                              bool check_exceptions) {
  1127   // R3_ARG1 is reserved for the thread.
  1128   mr_if_needed(R4_ARG2, arg_1);
  1129   call_VM(oop_result, entry_point, check_exceptions);
  1132 void MacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1, Register arg_2,
  1133                              bool check_exceptions) {
  1134   // R3_ARG1 is reserved for the thread
  1135   mr_if_needed(R4_ARG2, arg_1);
  1136   assert(arg_2 != R4_ARG2, "smashed argument");
  1137   mr_if_needed(R5_ARG3, arg_2);
  1138   call_VM(oop_result, entry_point, check_exceptions);
  1141 void MacroAssembler::call_VM_leaf(address entry_point) {
  1142   call_VM_leaf_base(entry_point);
  1145 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_1) {
  1146   mr_if_needed(R3_ARG1, arg_1);
  1147   call_VM_leaf(entry_point);
  1150 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_1, Register arg_2) {
  1151   mr_if_needed(R3_ARG1, arg_1);
  1152   assert(arg_2 != R3_ARG1, "smashed argument");
  1153   mr_if_needed(R4_ARG2, arg_2);
  1154   call_VM_leaf(entry_point);
  1157 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_1, Register arg_2, Register arg_3) {
  1158   mr_if_needed(R3_ARG1, arg_1);
  1159   assert(arg_2 != R3_ARG1, "smashed argument");
  1160   mr_if_needed(R4_ARG2, arg_2);
  1161   assert(arg_3 != R3_ARG1 && arg_3 != R4_ARG2, "smashed argument");
  1162   mr_if_needed(R5_ARG3, arg_3);
  1163   call_VM_leaf(entry_point);
  1166 // Check whether instruction is a read access to the polling page
  1167 // which was emitted by load_from_polling_page(..).
  1168 bool MacroAssembler::is_load_from_polling_page(int instruction, void* ucontext,
  1169                                                address* polling_address_ptr) {
  1170   if (!is_ld(instruction))
  1171     return false; // It's not a ld. Fail.
  1173   int rt = inv_rt_field(instruction);
  1174   int ra = inv_ra_field(instruction);
  1175   int ds = inv_ds_field(instruction);
  1176   if (!(ds == 0 && ra != 0 && rt == 0)) {
  1177     return false; // It's not a ld(r0, X, ra). Fail.
  1180   if (!ucontext) {
  1181     // Set polling address.
  1182     if (polling_address_ptr != NULL) {
  1183       *polling_address_ptr = NULL;
  1185     return true; // No ucontext given. Can't check value of ra. Assume true.
  1188 #ifdef LINUX
  1189   // Ucontext given. Check that register ra contains the address of
  1190   // the safepoing polling page.
  1191   ucontext_t* uc = (ucontext_t*) ucontext;
  1192   // Set polling address.
  1193   address addr = (address)uc->uc_mcontext.regs->gpr[ra] + (ssize_t)ds;
  1194   if (polling_address_ptr != NULL) {
  1195     *polling_address_ptr = addr;
  1197   return os::is_poll_address(addr);
  1198 #else
  1199   // Not on Linux, ucontext must be NULL.
  1200   ShouldNotReachHere();
  1201   return false;
  1202 #endif
  1205 bool MacroAssembler::is_memory_serialization(int instruction, JavaThread* thread, void* ucontext) {
  1206 #ifdef LINUX
  1207   ucontext_t* uc = (ucontext_t*) ucontext;
  1209   if (is_stwx(instruction) || is_stwux(instruction)) {
  1210     int ra = inv_ra_field(instruction);
  1211     int rb = inv_rb_field(instruction);
  1213     // look up content of ra and rb in ucontext
  1214     address ra_val=(address)uc->uc_mcontext.regs->gpr[ra];
  1215     long rb_val=(long)uc->uc_mcontext.regs->gpr[rb];
  1216     return os::is_memory_serialize_page(thread, ra_val+rb_val);
  1217   } else if (is_stw(instruction) || is_stwu(instruction)) {
  1218     int ra = inv_ra_field(instruction);
  1219     int d1 = inv_d1_field(instruction);
  1221     // look up content of ra in ucontext
  1222     address ra_val=(address)uc->uc_mcontext.regs->gpr[ra];
  1223     return os::is_memory_serialize_page(thread, ra_val+d1);
  1224   } else {
  1225     return false;
  1227 #else
  1228   // workaround not needed on !LINUX :-)
  1229   ShouldNotCallThis();
  1230   return false;
  1231 #endif
  1234 void MacroAssembler::bang_stack_with_offset(int offset) {
  1235   // When increasing the stack, the old stack pointer will be written
  1236   // to the new top of stack according to the PPC64 abi.
  1237   // Therefore, stack banging is not necessary when increasing
  1238   // the stack by <= os::vm_page_size() bytes.
  1239   // When increasing the stack by a larger amount, this method is
  1240   // called repeatedly to bang the intermediate pages.
  1242   // Stack grows down, caller passes positive offset.
  1243   assert(offset > 0, "must bang with positive offset");
  1245   long stdoffset = -offset;
  1247   if (is_simm(stdoffset, 16)) {
  1248     // Signed 16 bit offset, a simple std is ok.
  1249     if (UseLoadInstructionsForStackBangingPPC64) {
  1250       ld(R0, (int)(signed short)stdoffset, R1_SP);
  1251     } else {
  1252       std(R0,(int)(signed short)stdoffset, R1_SP);
  1254   } else if (is_simm(stdoffset, 31)) {
  1255     const int hi = MacroAssembler::largeoffset_si16_si16_hi(stdoffset);
  1256     const int lo = MacroAssembler::largeoffset_si16_si16_lo(stdoffset);
  1258     Register tmp = R11;
  1259     addis(tmp, R1_SP, hi);
  1260     if (UseLoadInstructionsForStackBangingPPC64) {
  1261       ld(R0,  lo, tmp);
  1262     } else {
  1263       std(R0, lo, tmp);
  1265   } else {
  1266     ShouldNotReachHere();
  1270 // If instruction is a stack bang of the form
  1271 //    std    R0,    x(Ry),       (see bang_stack_with_offset())
  1272 //    stdu   R1_SP, x(R1_SP),    (see push_frame(), resize_frame())
  1273 // or stdux  R1_SP, Rx, R1_SP    (see push_frame(), resize_frame())
  1274 // return the banged address. Otherwise, return 0.
  1275 address MacroAssembler::get_stack_bang_address(int instruction, void *ucontext) {
  1276 #ifdef LINUX
  1277   ucontext_t* uc = (ucontext_t*) ucontext;
  1278   int rs = inv_rs_field(instruction);
  1279   int ra = inv_ra_field(instruction);
  1280   if (   (is_ld(instruction)   && rs == 0 &&  UseLoadInstructionsForStackBangingPPC64)
  1281       || (is_std(instruction)  && rs == 0 && !UseLoadInstructionsForStackBangingPPC64)
  1282       || (is_stdu(instruction) && rs == 1)) {
  1283     int ds = inv_ds_field(instruction);
  1284     // return banged address
  1285     return ds+(address)uc->uc_mcontext.regs->gpr[ra];
  1286   } else if (is_stdux(instruction) && rs == 1) {
  1287     int rb = inv_rb_field(instruction);
  1288     address sp = (address)uc->uc_mcontext.regs->gpr[1];
  1289     long rb_val = (long)uc->uc_mcontext.regs->gpr[rb];
  1290     return ra != 1 || rb_val >= 0 ? NULL         // not a stack bang
  1291                                   : sp + rb_val; // banged address
  1293   return NULL; // not a stack bang
  1294 #else
  1295   // workaround not needed on !LINUX :-)
  1296   ShouldNotCallThis();
  1297   return NULL;
  1298 #endif
  1301 // CmpxchgX sets condition register to cmpX(current, compare).
  1302 void MacroAssembler::cmpxchgw(ConditionRegister flag, Register dest_current_value,
  1303                               Register compare_value, Register exchange_value,
  1304                               Register addr_base, int semantics, bool cmpxchgx_hint,
  1305                               Register int_flag_success, bool contention_hint) {
  1306   Label retry;
  1307   Label failed;
  1308   Label done;
  1310   // Save one branch if result is returned via register and
  1311   // result register is different from the other ones.
  1312   bool use_result_reg    = (int_flag_success != noreg);
  1313   bool preset_result_reg = (int_flag_success != dest_current_value && int_flag_success != compare_value &&
  1314                             int_flag_success != exchange_value && int_flag_success != addr_base);
  1316   // release/fence semantics
  1317   if (semantics & MemBarRel) {
  1318     release();
  1321   if (use_result_reg && preset_result_reg) {
  1322     li(int_flag_success, 0); // preset (assume cas failed)
  1325   // Add simple guard in order to reduce risk of starving under high contention (recommended by IBM).
  1326   if (contention_hint) { // Don't try to reserve if cmp fails.
  1327     lwz(dest_current_value, 0, addr_base);
  1328     cmpw(flag, dest_current_value, compare_value);
  1329     bne(flag, failed);
  1332   // atomic emulation loop
  1333   bind(retry);
  1335   lwarx(dest_current_value, addr_base, cmpxchgx_hint);
  1336   cmpw(flag, dest_current_value, compare_value);
  1337   if (UseStaticBranchPredictionInCompareAndSwapPPC64) {
  1338     bne_predict_not_taken(flag, failed);
  1339   } else {
  1340     bne(                  flag, failed);
  1342   // branch to done  => (flag == ne), (dest_current_value != compare_value)
  1343   // fall through    => (flag == eq), (dest_current_value == compare_value)
  1345   stwcx_(exchange_value, addr_base);
  1346   if (UseStaticBranchPredictionInCompareAndSwapPPC64) {
  1347     bne_predict_not_taken(CCR0, retry); // StXcx_ sets CCR0.
  1348   } else {
  1349     bne(                  CCR0, retry); // StXcx_ sets CCR0.
  1351   // fall through    => (flag == eq), (dest_current_value == compare_value), (swapped)
  1353   // Result in register (must do this at the end because int_flag_success can be the
  1354   // same register as one above).
  1355   if (use_result_reg) {
  1356     li(int_flag_success, 1);
  1359   if (semantics & MemBarFenceAfter) {
  1360     fence();
  1361   } else if (semantics & MemBarAcq) {
  1362     isync();
  1365   if (use_result_reg && !preset_result_reg) {
  1366     b(done);
  1369   bind(failed);
  1370   if (use_result_reg && !preset_result_reg) {
  1371     li(int_flag_success, 0);
  1374   bind(done);
  1375   // (flag == ne) => (dest_current_value != compare_value), (!swapped)
  1376   // (flag == eq) => (dest_current_value == compare_value), ( swapped)
  1379 // Preforms atomic compare exchange:
  1380 //   if (compare_value == *addr_base)
  1381 //     *addr_base = exchange_value
  1382 //     int_flag_success = 1;
  1383 //   else
  1384 //     int_flag_success = 0;
  1385 //
  1386 // ConditionRegister flag       = cmp(compare_value, *addr_base)
  1387 // Register dest_current_value  = *addr_base
  1388 // Register compare_value       Used to compare with value in memory
  1389 // Register exchange_value      Written to memory if compare_value == *addr_base
  1390 // Register addr_base           The memory location to compareXChange
  1391 // Register int_flag_success    Set to 1 if exchange_value was written to *addr_base
  1392 //
  1393 // To avoid the costly compare exchange the value is tested beforehand.
  1394 // Several special cases exist to avoid that unnecessary information is generated.
  1395 //
  1396 void MacroAssembler::cmpxchgd(ConditionRegister flag,
  1397                               Register dest_current_value, Register compare_value, Register exchange_value,
  1398                               Register addr_base, int semantics, bool cmpxchgx_hint,
  1399                               Register int_flag_success, Label* failed_ext, bool contention_hint) {
  1400   Label retry;
  1401   Label failed_int;
  1402   Label& failed = (failed_ext != NULL) ? *failed_ext : failed_int;
  1403   Label done;
  1405   // Save one branch if result is returned via register and result register is different from the other ones.
  1406   bool use_result_reg    = (int_flag_success!=noreg);
  1407   bool preset_result_reg = (int_flag_success!=dest_current_value && int_flag_success!=compare_value &&
  1408                             int_flag_success!=exchange_value && int_flag_success!=addr_base);
  1409   assert(int_flag_success == noreg || failed_ext == NULL, "cannot have both");
  1411   // release/fence semantics
  1412   if (semantics & MemBarRel) {
  1413     release();
  1416   if (use_result_reg && preset_result_reg) {
  1417     li(int_flag_success, 0); // preset (assume cas failed)
  1420   // Add simple guard in order to reduce risk of starving under high contention (recommended by IBM).
  1421   if (contention_hint) { // Don't try to reserve if cmp fails.
  1422     ld(dest_current_value, 0, addr_base);
  1423     cmpd(flag, dest_current_value, compare_value);
  1424     bne(flag, failed);
  1427   // atomic emulation loop
  1428   bind(retry);
  1430   ldarx(dest_current_value, addr_base, cmpxchgx_hint);
  1431   cmpd(flag, dest_current_value, compare_value);
  1432   if (UseStaticBranchPredictionInCompareAndSwapPPC64) {
  1433     bne_predict_not_taken(flag, failed);
  1434   } else {
  1435     bne(                  flag, failed);
  1438   stdcx_(exchange_value, addr_base);
  1439   if (UseStaticBranchPredictionInCompareAndSwapPPC64) {
  1440     bne_predict_not_taken(CCR0, retry); // stXcx_ sets CCR0
  1441   } else {
  1442     bne(                  CCR0, retry); // stXcx_ sets CCR0
  1445   // result in register (must do this at the end because int_flag_success can be the same register as one above)
  1446   if (use_result_reg) {
  1447     li(int_flag_success, 1);
  1450   // POWER6 doesn't need isync in CAS.
  1451   // Always emit isync to be on the safe side.
  1452   if (semantics & MemBarFenceAfter) {
  1453     fence();
  1454   } else if (semantics & MemBarAcq) {
  1455     isync();
  1458   if (use_result_reg && !preset_result_reg) {
  1459     b(done);
  1462   bind(failed_int);
  1463   if (use_result_reg && !preset_result_reg) {
  1464     li(int_flag_success, 0);
  1467   bind(done);
  1468   // (flag == ne) => (dest_current_value != compare_value), (!swapped)
  1469   // (flag == eq) => (dest_current_value == compare_value), ( swapped)
  1472 // Look up the method for a megamorphic invokeinterface call.
  1473 // The target method is determined by <intf_klass, itable_index>.
  1474 // The receiver klass is in recv_klass.
  1475 // On success, the result will be in method_result, and execution falls through.
  1476 // On failure, execution transfers to the given label.
  1477 void MacroAssembler::lookup_interface_method(Register recv_klass,
  1478                                              Register intf_klass,
  1479                                              RegisterOrConstant itable_index,
  1480                                              Register method_result,
  1481                                              Register scan_temp,
  1482                                              Register sethi_temp,
  1483                                              Label& L_no_such_interface) {
  1484   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
  1485   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
  1486          "caller must use same register for non-constant itable index as for method");
  1488   // Compute start of first itableOffsetEntry (which is at the end of the vtable).
  1489   int vtable_base = InstanceKlass::vtable_start_offset() * wordSize;
  1490   int itentry_off = itableMethodEntry::method_offset_in_bytes();
  1491   int logMEsize   = exact_log2(itableMethodEntry::size() * wordSize);
  1492   int scan_step   = itableOffsetEntry::size() * wordSize;
  1493   int log_vte_size= exact_log2(vtableEntry::size() * wordSize);
  1495   lwz(scan_temp, InstanceKlass::vtable_length_offset() * wordSize, recv_klass);
  1496   // %%% We should store the aligned, prescaled offset in the klassoop.
  1497   // Then the next several instructions would fold away.
  1499   sldi(scan_temp, scan_temp, log_vte_size);
  1500   addi(scan_temp, scan_temp, vtable_base);
  1501   add(scan_temp, recv_klass, scan_temp);
  1503   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
  1504   if (itable_index.is_register()) {
  1505     Register itable_offset = itable_index.as_register();
  1506     sldi(itable_offset, itable_offset, logMEsize);
  1507     if (itentry_off) addi(itable_offset, itable_offset, itentry_off);
  1508     add(recv_klass, itable_offset, recv_klass);
  1509   } else {
  1510     long itable_offset = (long)itable_index.as_constant();
  1511     load_const_optimized(sethi_temp, (itable_offset<<logMEsize)+itentry_off); // static address, no relocation
  1512     add(recv_klass, sethi_temp, recv_klass);
  1515   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
  1516   //   if (scan->interface() == intf) {
  1517   //     result = (klass + scan->offset() + itable_index);
  1518   //   }
  1519   // }
  1520   Label search, found_method;
  1522   for (int peel = 1; peel >= 0; peel--) {
  1523     // %%%% Could load both offset and interface in one ldx, if they were
  1524     // in the opposite order. This would save a load.
  1525     ld(method_result, itableOffsetEntry::interface_offset_in_bytes(), scan_temp);
  1527     // Check that this entry is non-null. A null entry means that
  1528     // the receiver class doesn't implement the interface, and wasn't the
  1529     // same as when the caller was compiled.
  1530     cmpd(CCR0, method_result, intf_klass);
  1532     if (peel) {
  1533       beq(CCR0, found_method);
  1534     } else {
  1535       bne(CCR0, search);
  1536       // (invert the test to fall through to found_method...)
  1539     if (!peel) break;
  1541     bind(search);
  1543     cmpdi(CCR0, method_result, 0);
  1544     beq(CCR0, L_no_such_interface);
  1545     addi(scan_temp, scan_temp, scan_step);
  1548   bind(found_method);
  1550   // Got a hit.
  1551   int ito_offset = itableOffsetEntry::offset_offset_in_bytes();
  1552   lwz(scan_temp, ito_offset, scan_temp);
  1553   ldx(method_result, scan_temp, recv_klass);
  1556 // virtual method calling
  1557 void MacroAssembler::lookup_virtual_method(Register recv_klass,
  1558                                            RegisterOrConstant vtable_index,
  1559                                            Register method_result) {
  1561   assert_different_registers(recv_klass, method_result, vtable_index.register_or_noreg());
  1563   const int base = InstanceKlass::vtable_start_offset() * wordSize;
  1564   assert(vtableEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
  1566   if (vtable_index.is_register()) {
  1567     sldi(vtable_index.as_register(), vtable_index.as_register(), LogBytesPerWord);
  1568     add(recv_klass, vtable_index.as_register(), recv_klass);
  1569   } else {
  1570     addi(recv_klass, recv_klass, vtable_index.as_constant() << LogBytesPerWord);
  1572   ld(R19_method, base + vtableEntry::method_offset_in_bytes(), recv_klass);
  1575 /////////////////////////////////////////// subtype checking ////////////////////////////////////////////
  1577 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
  1578                                                    Register super_klass,
  1579                                                    Register temp1_reg,
  1580                                                    Register temp2_reg,
  1581                                                    Label& L_success,
  1582                                                    Label& L_failure) {
  1584   const Register check_cache_offset = temp1_reg;
  1585   const Register cached_super       = temp2_reg;
  1587   assert_different_registers(sub_klass, super_klass, check_cache_offset, cached_super);
  1589   int sco_offset = in_bytes(Klass::super_check_offset_offset());
  1590   int sc_offset  = in_bytes(Klass::secondary_super_cache_offset());
  1592   // If the pointers are equal, we are done (e.g., String[] elements).
  1593   // This self-check enables sharing of secondary supertype arrays among
  1594   // non-primary types such as array-of-interface. Otherwise, each such
  1595   // type would need its own customized SSA.
  1596   // We move this check to the front of the fast path because many
  1597   // type checks are in fact trivially successful in this manner,
  1598   // so we get a nicely predicted branch right at the start of the check.
  1599   cmpd(CCR0, sub_klass, super_klass);
  1600   beq(CCR0, L_success);
  1602   // Check the supertype display:
  1603   lwz(check_cache_offset, sco_offset, super_klass);
  1604   // The loaded value is the offset from KlassOopDesc.
  1606   ldx(cached_super, check_cache_offset, sub_klass);
  1607   cmpd(CCR0, cached_super, super_klass);
  1608   beq(CCR0, L_success);
  1610   // This check has worked decisively for primary supers.
  1611   // Secondary supers are sought in the super_cache ('super_cache_addr').
  1612   // (Secondary supers are interfaces and very deeply nested subtypes.)
  1613   // This works in the same check above because of a tricky aliasing
  1614   // between the super_cache and the primary super display elements.
  1615   // (The 'super_check_addr' can address either, as the case requires.)
  1616   // Note that the cache is updated below if it does not help us find
  1617   // what we need immediately.
  1618   // So if it was a primary super, we can just fail immediately.
  1619   // Otherwise, it's the slow path for us (no success at this point).
  1621   cmpwi(CCR0, check_cache_offset, sc_offset);
  1622   bne(CCR0, L_failure);
  1623   // bind(slow_path); // fallthru
  1626 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
  1627                                                    Register super_klass,
  1628                                                    Register temp1_reg,
  1629                                                    Register temp2_reg,
  1630                                                    Label* L_success,
  1631                                                    Register result_reg) {
  1632   const Register array_ptr = temp1_reg; // current value from cache array
  1633   const Register temp      = temp2_reg;
  1635   assert_different_registers(sub_klass, super_klass, array_ptr, temp);
  1637   int source_offset = in_bytes(Klass::secondary_supers_offset());
  1638   int target_offset = in_bytes(Klass::secondary_super_cache_offset());
  1640   int length_offset = Array<Klass*>::length_offset_in_bytes();
  1641   int base_offset   = Array<Klass*>::base_offset_in_bytes();
  1643   Label hit, loop, failure, fallthru;
  1645   ld(array_ptr, source_offset, sub_klass);
  1647   //assert(4 == arrayOopDesc::length_length_in_bytes(), "precondition violated.");
  1648   lwz(temp, length_offset, array_ptr);
  1649   cmpwi(CCR0, temp, 0);
  1650   beq(CCR0, result_reg!=noreg ? failure : fallthru); // length 0
  1652   mtctr(temp); // load ctr
  1654   bind(loop);
  1655   // Oops in table are NO MORE compressed.
  1656   ld(temp, base_offset, array_ptr);
  1657   cmpd(CCR0, temp, super_klass);
  1658   beq(CCR0, hit);
  1659   addi(array_ptr, array_ptr, BytesPerWord);
  1660   bdnz(loop);
  1662   bind(failure);
  1663   if (result_reg!=noreg) li(result_reg, 1); // load non-zero result (indicates a miss)
  1664   b(fallthru);
  1666   bind(hit);
  1667   std(super_klass, target_offset, sub_klass); // save result to cache
  1668   if (result_reg != noreg) li(result_reg, 0); // load zero result (indicates a hit)
  1669   if (L_success != NULL) b(*L_success);
  1671   bind(fallthru);
  1674 // Try fast path, then go to slow one if not successful
  1675 void MacroAssembler::check_klass_subtype(Register sub_klass,
  1676                          Register super_klass,
  1677                          Register temp1_reg,
  1678                          Register temp2_reg,
  1679                          Label& L_success) {
  1680   Label L_failure;
  1681   check_klass_subtype_fast_path(sub_klass, super_klass, temp1_reg, temp2_reg, L_success, L_failure);
  1682   check_klass_subtype_slow_path(sub_klass, super_klass, temp1_reg, temp2_reg, &L_success);
  1683   bind(L_failure); // Fallthru if not successful.
  1686 void MacroAssembler::check_method_handle_type(Register mtype_reg, Register mh_reg,
  1687                                               Register temp_reg,
  1688                                               Label& wrong_method_type) {
  1689   assert_different_registers(mtype_reg, mh_reg, temp_reg);
  1690   // Compare method type against that of the receiver.
  1691   load_heap_oop_not_null(temp_reg, delayed_value(java_lang_invoke_MethodHandle::type_offset_in_bytes, temp_reg), mh_reg);
  1692   cmpd(CCR0, temp_reg, mtype_reg);
  1693   bne(CCR0, wrong_method_type);
  1696 RegisterOrConstant MacroAssembler::argument_offset(RegisterOrConstant arg_slot,
  1697                                                    Register temp_reg,
  1698                                                    int extra_slot_offset) {
  1699   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
  1700   int stackElementSize = Interpreter::stackElementSize;
  1701   int offset = extra_slot_offset * stackElementSize;
  1702   if (arg_slot.is_constant()) {
  1703     offset += arg_slot.as_constant() * stackElementSize;
  1704     return offset;
  1705   } else {
  1706     assert(temp_reg != noreg, "must specify");
  1707     sldi(temp_reg, arg_slot.as_register(), exact_log2(stackElementSize));
  1708     if (offset != 0)
  1709       addi(temp_reg, temp_reg, offset);
  1710     return temp_reg;
  1714 void MacroAssembler::biased_locking_enter(ConditionRegister cr_reg, Register obj_reg,
  1715                                           Register mark_reg, Register temp_reg,
  1716                                           Register temp2_reg, Label& done, Label* slow_case) {
  1717   assert(UseBiasedLocking, "why call this otherwise?");
  1719 #ifdef ASSERT
  1720   assert_different_registers(obj_reg, mark_reg, temp_reg, temp2_reg);
  1721 #endif
  1723   Label cas_label;
  1725   // Branch to done if fast path fails and no slow_case provided.
  1726   Label *slow_case_int = (slow_case != NULL) ? slow_case : &done;
  1728   // Biased locking
  1729   // See whether the lock is currently biased toward our thread and
  1730   // whether the epoch is still valid
  1731   // Note that the runtime guarantees sufficient alignment of JavaThread
  1732   // pointers to allow age to be placed into low bits
  1733   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits,
  1734          "biased locking makes assumptions about bit layout");
  1736   if (PrintBiasedLockingStatistics) {
  1737     load_const(temp_reg, (address) BiasedLocking::total_entry_count_addr(), temp2_reg);
  1738     lwz(temp2_reg, 0, temp_reg);
  1739     addi(temp2_reg, temp2_reg, 1);
  1740     stw(temp2_reg, 0, temp_reg);
  1743   andi(temp_reg, mark_reg, markOopDesc::biased_lock_mask_in_place);
  1744   cmpwi(cr_reg, temp_reg, markOopDesc::biased_lock_pattern);
  1745   bne(cr_reg, cas_label);
  1747   load_klass_with_trap_null_check(temp_reg, obj_reg);
  1749   load_const_optimized(temp2_reg, ~((int) markOopDesc::age_mask_in_place));
  1750   ld(temp_reg, in_bytes(Klass::prototype_header_offset()), temp_reg);
  1751   orr(temp_reg, R16_thread, temp_reg);
  1752   xorr(temp_reg, mark_reg, temp_reg);
  1753   andr(temp_reg, temp_reg, temp2_reg);
  1754   cmpdi(cr_reg, temp_reg, 0);
  1755   if (PrintBiasedLockingStatistics) {
  1756     Label l;
  1757     bne(cr_reg, l);
  1758     load_const(mark_reg, (address) BiasedLocking::biased_lock_entry_count_addr());
  1759     lwz(temp2_reg, 0, mark_reg);
  1760     addi(temp2_reg, temp2_reg, 1);
  1761     stw(temp2_reg, 0, mark_reg);
  1762     // restore mark_reg
  1763     ld(mark_reg, oopDesc::mark_offset_in_bytes(), obj_reg);
  1764     bind(l);
  1766   beq(cr_reg, done);
  1768   Label try_revoke_bias;
  1769   Label try_rebias;
  1771   // At this point we know that the header has the bias pattern and
  1772   // that we are not the bias owner in the current epoch. We need to
  1773   // figure out more details about the state of the header in order to
  1774   // know what operations can be legally performed on the object's
  1775   // header.
  1777   // If the low three bits in the xor result aren't clear, that means
  1778   // the prototype header is no longer biased and we have to revoke
  1779   // the bias on this object.
  1780   andi(temp2_reg, temp_reg, markOopDesc::biased_lock_mask_in_place);
  1781   cmpwi(cr_reg, temp2_reg, 0);
  1782   bne(cr_reg, try_revoke_bias);
  1784   // Biasing is still enabled for this data type. See whether the
  1785   // epoch of the current bias is still valid, meaning that the epoch
  1786   // bits of the mark word are equal to the epoch bits of the
  1787   // prototype header. (Note that the prototype header's epoch bits
  1788   // only change at a safepoint.) If not, attempt to rebias the object
  1789   // toward the current thread. Note that we must be absolutely sure
  1790   // that the current epoch is invalid in order to do this because
  1791   // otherwise the manipulations it performs on the mark word are
  1792   // illegal.
  1794   int shift_amount = 64 - markOopDesc::epoch_shift;
  1795   // rotate epoch bits to right (little) end and set other bits to 0
  1796   // [ big part | epoch | little part ] -> [ 0..0 | epoch ]
  1797   rldicl_(temp2_reg, temp_reg, shift_amount, 64 - markOopDesc::epoch_bits);
  1798   // branch if epoch bits are != 0, i.e. they differ, because the epoch has been incremented
  1799   bne(CCR0, try_rebias);
  1801   // The epoch of the current bias is still valid but we know nothing
  1802   // about the owner; it might be set or it might be clear. Try to
  1803   // acquire the bias of the object using an atomic operation. If this
  1804   // fails we will go in to the runtime to revoke the object's bias.
  1805   // Note that we first construct the presumed unbiased header so we
  1806   // don't accidentally blow away another thread's valid bias.
  1807   andi(mark_reg, mark_reg, (markOopDesc::biased_lock_mask_in_place |
  1808                                 markOopDesc::age_mask_in_place |
  1809                                 markOopDesc::epoch_mask_in_place));
  1810   orr(temp_reg, R16_thread, mark_reg);
  1812   assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
  1814   // CmpxchgX sets cr_reg to cmpX(temp2_reg, mark_reg).
  1815   fence(); // TODO: replace by MacroAssembler::MemBarRel | MacroAssembler::MemBarAcq ?
  1816   cmpxchgd(/*flag=*/cr_reg, /*current_value=*/temp2_reg,
  1817            /*compare_value=*/mark_reg, /*exchange_value=*/temp_reg,
  1818            /*where=*/obj_reg,
  1819            MacroAssembler::MemBarAcq,
  1820            MacroAssembler::cmpxchgx_hint_acquire_lock(),
  1821            noreg, slow_case_int); // bail out if failed
  1823   // If the biasing toward our thread failed, this means that
  1824   // another thread succeeded in biasing it toward itself and we
  1825   // need to revoke that bias. The revocation will occur in the
  1826   // interpreter runtime in the slow case.
  1827   if (PrintBiasedLockingStatistics) {
  1828     load_const(temp_reg, (address) BiasedLocking::anonymously_biased_lock_entry_count_addr(), temp2_reg);
  1829     lwz(temp2_reg, 0, temp_reg);
  1830     addi(temp2_reg, temp2_reg, 1);
  1831     stw(temp2_reg, 0, temp_reg);
  1833   b(done);
  1835   bind(try_rebias);
  1836   // At this point we know the epoch has expired, meaning that the
  1837   // current "bias owner", if any, is actually invalid. Under these
  1838   // circumstances _only_, we are allowed to use the current header's
  1839   // value as the comparison value when doing the cas to acquire the
  1840   // bias in the current epoch. In other words, we allow transfer of
  1841   // the bias from one thread to another directly in this situation.
  1842   andi(temp_reg, mark_reg, markOopDesc::age_mask_in_place);
  1843   orr(temp_reg, R16_thread, temp_reg);
  1844   load_klass_with_trap_null_check(temp2_reg, obj_reg);
  1845   ld(temp2_reg, in_bytes(Klass::prototype_header_offset()), temp2_reg);
  1846   orr(temp_reg, temp_reg, temp2_reg);
  1848   assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
  1850   // CmpxchgX sets cr_reg to cmpX(temp2_reg, mark_reg).
  1851   fence(); // TODO: replace by MacroAssembler::MemBarRel | MacroAssembler::MemBarAcq ?
  1852   cmpxchgd(/*flag=*/cr_reg, /*current_value=*/temp2_reg,
  1853                  /*compare_value=*/mark_reg, /*exchange_value=*/temp_reg,
  1854                  /*where=*/obj_reg,
  1855                  MacroAssembler::MemBarAcq,
  1856                  MacroAssembler::cmpxchgx_hint_acquire_lock(),
  1857                  noreg, slow_case_int); // bail out if failed
  1859   // If the biasing toward our thread failed, this means that
  1860   // another thread succeeded in biasing it toward itself and we
  1861   // need to revoke that bias. The revocation will occur in the
  1862   // interpreter runtime in the slow case.
  1863   if (PrintBiasedLockingStatistics) {
  1864     load_const(temp_reg, (address) BiasedLocking::rebiased_lock_entry_count_addr(), temp2_reg);
  1865     lwz(temp2_reg, 0, temp_reg);
  1866     addi(temp2_reg, temp2_reg, 1);
  1867     stw(temp2_reg, 0, temp_reg);
  1869   b(done);
  1871   bind(try_revoke_bias);
  1872   // The prototype mark in the klass doesn't have the bias bit set any
  1873   // more, indicating that objects of this data type are not supposed
  1874   // to be biased any more. We are going to try to reset the mark of
  1875   // this object to the prototype value and fall through to the
  1876   // CAS-based locking scheme. Note that if our CAS fails, it means
  1877   // that another thread raced us for the privilege of revoking the
  1878   // bias of this particular object, so it's okay to continue in the
  1879   // normal locking code.
  1880   load_klass_with_trap_null_check(temp_reg, obj_reg);
  1881   ld(temp_reg, in_bytes(Klass::prototype_header_offset()), temp_reg);
  1882   andi(temp2_reg, mark_reg, markOopDesc::age_mask_in_place);
  1883   orr(temp_reg, temp_reg, temp2_reg);
  1885   assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
  1887   // CmpxchgX sets cr_reg to cmpX(temp2_reg, mark_reg).
  1888   fence(); // TODO: replace by MacroAssembler::MemBarRel | MacroAssembler::MemBarAcq ?
  1889   cmpxchgd(/*flag=*/cr_reg, /*current_value=*/temp2_reg,
  1890                  /*compare_value=*/mark_reg, /*exchange_value=*/temp_reg,
  1891                  /*where=*/obj_reg,
  1892                  MacroAssembler::MemBarAcq,
  1893                  MacroAssembler::cmpxchgx_hint_acquire_lock());
  1895   // reload markOop in mark_reg before continuing with lightweight locking
  1896   ld(mark_reg, oopDesc::mark_offset_in_bytes(), obj_reg);
  1898   // Fall through to the normal CAS-based lock, because no matter what
  1899   // the result of the above CAS, some thread must have succeeded in
  1900   // removing the bias bit from the object's header.
  1901   if (PrintBiasedLockingStatistics) {
  1902     Label l;
  1903     bne(cr_reg, l);
  1904     load_const(temp_reg, (address) BiasedLocking::revoked_lock_entry_count_addr(), temp2_reg);
  1905     lwz(temp2_reg, 0, temp_reg);
  1906     addi(temp2_reg, temp2_reg, 1);
  1907     stw(temp2_reg, 0, temp_reg);
  1908     bind(l);
  1911   bind(cas_label);
  1914 void MacroAssembler::biased_locking_exit (ConditionRegister cr_reg, Register mark_addr, Register temp_reg, Label& done) {
  1915   // Check for biased locking unlock case, which is a no-op
  1916   // Note: we do not have to check the thread ID for two reasons.
  1917   // First, the interpreter checks for IllegalMonitorStateException at
  1918   // a higher level. Second, if the bias was revoked while we held the
  1919   // lock, the object could not be rebiased toward another thread, so
  1920   // the bias bit would be clear.
  1922   ld(temp_reg, 0, mark_addr);
  1923   andi(temp_reg, temp_reg, markOopDesc::biased_lock_mask_in_place);
  1925   cmpwi(cr_reg, temp_reg, markOopDesc::biased_lock_pattern);
  1926   beq(cr_reg, done);
  1929 // "The box" is the space on the stack where we copy the object mark.
  1930 void MacroAssembler::compiler_fast_lock_object(ConditionRegister flag, Register oop, Register box,
  1931                                                Register temp, Register displaced_header, Register current_header) {
  1932   assert_different_registers(oop, box, temp, displaced_header, current_header);
  1933   assert(flag != CCR0, "bad condition register");
  1934   Label cont;
  1935   Label object_has_monitor;
  1936   Label cas_failed;
  1938   // Load markOop from object into displaced_header.
  1939   ld(displaced_header, oopDesc::mark_offset_in_bytes(), oop);
  1942   // Always do locking in runtime.
  1943   if (EmitSync & 0x01) {
  1944     cmpdi(flag, oop, 0); // Oop can't be 0 here => always false.
  1945     return;
  1948   if (UseBiasedLocking) {
  1949     biased_locking_enter(flag, oop, displaced_header, temp, current_header, cont);
  1952   // Handle existing monitor.
  1953   if ((EmitSync & 0x02) == 0) {
  1954     // The object has an existing monitor iff (mark & monitor_value) != 0.
  1955     andi_(temp, displaced_header, markOopDesc::monitor_value);
  1956     bne(CCR0, object_has_monitor);
  1959   // Set displaced_header to be (markOop of object | UNLOCK_VALUE).
  1960   ori(displaced_header, displaced_header, markOopDesc::unlocked_value);
  1962   // Load Compare Value application register.
  1964   // Initialize the box. (Must happen before we update the object mark!)
  1965   std(displaced_header, BasicLock::displaced_header_offset_in_bytes(), box);
  1967   // Must fence, otherwise, preceding store(s) may float below cmpxchg.
  1968   // Compare object markOop with mark and if equal exchange scratch1 with object markOop.
  1969   // CmpxchgX sets cr_reg to cmpX(current, displaced).
  1970   cmpxchgd(/*flag=*/flag,
  1971            /*current_value=*/current_header,
  1972            /*compare_value=*/displaced_header,
  1973            /*exchange_value=*/box,
  1974            /*where=*/oop,
  1975            MacroAssembler::MemBarRel | MacroAssembler::MemBarAcq,
  1976            MacroAssembler::cmpxchgx_hint_acquire_lock(),
  1977            noreg,
  1978            &cas_failed);
  1979   assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
  1981   // If the compare-and-exchange succeeded, then we found an unlocked
  1982   // object and we have now locked it.
  1983   b(cont);
  1985   bind(cas_failed);
  1986   // We did not see an unlocked object so try the fast recursive case.
  1988   // Check if the owner is self by comparing the value in the markOop of object
  1989   // (current_header) with the stack pointer.
  1990   sub(current_header, current_header, R1_SP);
  1991   load_const_optimized(temp, (address) (~(os::vm_page_size()-1) |
  1992                                         markOopDesc::lock_mask_in_place));
  1994   and_(R0/*==0?*/, current_header, temp);
  1995   // If condition is true we are cont and hence we can store 0 as the
  1996   // displaced header in the box, which indicates that it is a recursive lock.
  1997   mcrf(flag,CCR0);
  1998   std(R0/*==0, perhaps*/, BasicLock::displaced_header_offset_in_bytes(), box);
  2000   // Handle existing monitor.
  2001   if ((EmitSync & 0x02) == 0) {
  2002     b(cont);
  2004     bind(object_has_monitor);
  2005     // The object's monitor m is unlocked iff m->owner == NULL,
  2006     // otherwise m->owner may contain a thread or a stack address.
  2007     //
  2008     // Try to CAS m->owner from NULL to current thread.
  2009     addi(temp, displaced_header, ObjectMonitor::owner_offset_in_bytes()-markOopDesc::monitor_value);
  2010     li(displaced_header, 0);
  2011     // CmpxchgX sets flag to cmpX(current, displaced).
  2012     cmpxchgd(/*flag=*/flag,
  2013              /*current_value=*/current_header,
  2014              /*compare_value=*/displaced_header,
  2015              /*exchange_value=*/R16_thread,
  2016              /*where=*/temp,
  2017              MacroAssembler::MemBarRel | MacroAssembler::MemBarAcq,
  2018              MacroAssembler::cmpxchgx_hint_acquire_lock());
  2020     // Store a non-null value into the box.
  2021     std(box, BasicLock::displaced_header_offset_in_bytes(), box);
  2023 #   ifdef ASSERT
  2024     bne(flag, cont);
  2025     // We have acquired the monitor, check some invariants.
  2026     addi(/*monitor=*/temp, temp, -ObjectMonitor::owner_offset_in_bytes());
  2027     // Invariant 1: _recursions should be 0.
  2028     //assert(ObjectMonitor::recursions_size_in_bytes() == 8, "unexpected size");
  2029     asm_assert_mem8_is_zero(ObjectMonitor::recursions_offset_in_bytes(), temp,
  2030                             "monitor->_recursions should be 0", -1);
  2031     // Invariant 2: OwnerIsThread shouldn't be 0.
  2032     //assert(ObjectMonitor::OwnerIsThread_size_in_bytes() == 4, "unexpected size");
  2033     //asm_assert_mem4_isnot_zero(ObjectMonitor::OwnerIsThread_offset_in_bytes(), temp,
  2034     //                           "monitor->OwnerIsThread shouldn't be 0", -1);
  2035 #   endif
  2038   bind(cont);
  2039   // flag == EQ indicates success
  2040   // flag == NE indicates failure
  2043 void MacroAssembler::compiler_fast_unlock_object(ConditionRegister flag, Register oop, Register box,
  2044                                                  Register temp, Register displaced_header, Register current_header) {
  2045   assert_different_registers(oop, box, temp, displaced_header, current_header);
  2046   assert(flag != CCR0, "bad condition register");
  2047   Label cont;
  2048   Label object_has_monitor;
  2050   // Always do locking in runtime.
  2051   if (EmitSync & 0x01) {
  2052     cmpdi(flag, oop, 0); // Oop can't be 0 here => always false.
  2053     return;
  2056   if (UseBiasedLocking) {
  2057     biased_locking_exit(flag, oop, current_header, cont);
  2060   // Find the lock address and load the displaced header from the stack.
  2061   ld(displaced_header, BasicLock::displaced_header_offset_in_bytes(), box);
  2063   // If the displaced header is 0, we have a recursive unlock.
  2064   cmpdi(flag, displaced_header, 0);
  2065   beq(flag, cont);
  2067   // Handle existing monitor.
  2068   if ((EmitSync & 0x02) == 0) {
  2069     // The object has an existing monitor iff (mark & monitor_value) != 0.
  2070     ld(current_header, oopDesc::mark_offset_in_bytes(), oop);
  2071     andi(temp, current_header, markOopDesc::monitor_value);
  2072     cmpdi(flag, temp, 0);
  2073     bne(flag, object_has_monitor);
  2077   // Check if it is still a light weight lock, this is is true if we see
  2078   // the stack address of the basicLock in the markOop of the object.
  2079   // Cmpxchg sets flag to cmpd(current_header, box).
  2080   cmpxchgd(/*flag=*/flag,
  2081            /*current_value=*/current_header,
  2082            /*compare_value=*/box,
  2083            /*exchange_value=*/displaced_header,
  2084            /*where=*/oop,
  2085            MacroAssembler::MemBarRel,
  2086            MacroAssembler::cmpxchgx_hint_release_lock(),
  2087            noreg,
  2088            &cont);
  2090   assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
  2092   // Handle existing monitor.
  2093   if ((EmitSync & 0x02) == 0) {
  2094     b(cont);
  2096     bind(object_has_monitor);
  2097     addi(current_header, current_header, -markOopDesc::monitor_value); // monitor
  2098     ld(temp,             ObjectMonitor::owner_offset_in_bytes(), current_header);
  2099     ld(displaced_header, ObjectMonitor::recursions_offset_in_bytes(), current_header);
  2100     xorr(temp, R16_thread, temp);      // Will be 0 if we are the owner.
  2101     orr(temp, temp, displaced_header); // Will be 0 if there are 0 recursions.
  2102     cmpdi(flag, temp, 0);
  2103     bne(flag, cont);
  2105     ld(temp,             ObjectMonitor::EntryList_offset_in_bytes(), current_header);
  2106     ld(displaced_header, ObjectMonitor::cxq_offset_in_bytes(), current_header);
  2107     orr(temp, temp, displaced_header); // Will be 0 if both are 0.
  2108     cmpdi(flag, temp, 0);
  2109     bne(flag, cont);
  2110     release();
  2111     std(temp, ObjectMonitor::owner_offset_in_bytes(), current_header);
  2114   bind(cont);
  2115   // flag == EQ indicates success
  2116   // flag == NE indicates failure
  2119 // Write serialization page so VM thread can do a pseudo remote membar.
  2120 // We use the current thread pointer to calculate a thread specific
  2121 // offset to write to within the page. This minimizes bus traffic
  2122 // due to cache line collision.
  2123 void MacroAssembler::serialize_memory(Register thread, Register tmp1, Register tmp2) {
  2124   srdi(tmp2, thread, os::get_serialize_page_shift_count());
  2126   int mask = os::vm_page_size() - sizeof(int);
  2127   if (Assembler::is_simm(mask, 16)) {
  2128     andi(tmp2, tmp2, mask);
  2129   } else {
  2130     lis(tmp1, (int)((signed short) (mask >> 16)));
  2131     ori(tmp1, tmp1, mask & 0x0000ffff);
  2132     andr(tmp2, tmp2, tmp1);
  2135   load_const(tmp1, (long) os::get_memory_serialize_page());
  2136   release();
  2137   stwx(R0, tmp1, tmp2);
  2141 // GC barrier helper macros
  2143 // Write the card table byte if needed.
  2144 void MacroAssembler::card_write_barrier_post(Register Rstore_addr, Register Rnew_val, Register Rtmp) {
  2145   CardTableModRefBS* bs = (CardTableModRefBS*) Universe::heap()->barrier_set();
  2146   assert(bs->kind() == BarrierSet::CardTableModRef ||
  2147          bs->kind() == BarrierSet::CardTableExtension, "wrong barrier");
  2148 #ifdef ASSERT
  2149   cmpdi(CCR0, Rnew_val, 0);
  2150   asm_assert_ne("null oop not allowed", 0x321);
  2151 #endif
  2152   card_table_write(bs->byte_map_base, Rtmp, Rstore_addr);
  2155 // Write the card table byte.
  2156 void MacroAssembler::card_table_write(jbyte* byte_map_base, Register Rtmp, Register Robj) {
  2157   assert_different_registers(Robj, Rtmp, R0);
  2158   load_const_optimized(Rtmp, (address)byte_map_base, R0);
  2159   srdi(Robj, Robj, CardTableModRefBS::card_shift);
  2160   li(R0, 0); // dirty
  2161   if (UseConcMarkSweepGC) release();
  2162   stbx(R0, Rtmp, Robj);
  2165 #ifndef SERIALGC
  2167 // General G1 pre-barrier generator.
  2168 // Goal: record the previous value if it is not null.
  2169 void MacroAssembler::g1_write_barrier_pre(Register Robj, RegisterOrConstant offset, Register Rpre_val,
  2170                                           Register Rtmp1, Register Rtmp2, bool needs_frame) {
  2171   Label runtime, filtered;
  2173   // Is marking active?
  2174   if (in_bytes(PtrQueue::byte_width_of_active()) == 4) {
  2175     lwz(Rtmp1, in_bytes(JavaThread::satb_mark_queue_offset() + PtrQueue::byte_offset_of_active()), R16_thread);
  2176   } else {
  2177     guarantee(in_bytes(PtrQueue::byte_width_of_active()) == 1, "Assumption");
  2178     lbz(Rtmp1, in_bytes(JavaThread::satb_mark_queue_offset() + PtrQueue::byte_offset_of_active()), R16_thread);
  2180   cmpdi(CCR0, Rtmp1, 0);
  2181   beq(CCR0, filtered);
  2183   // Do we need to load the previous value?
  2184   if (Robj != noreg) {
  2185     // Load the previous value...
  2186     if (UseCompressedOops) {
  2187       lwz(Rpre_val, offset, Robj);
  2188     } else {
  2189       ld(Rpre_val, offset, Robj);
  2191     // Previous value has been loaded into Rpre_val.
  2193   assert(Rpre_val != noreg, "must have a real register");
  2195   // Is the previous value null?
  2196   cmpdi(CCR0, Rpre_val, 0);
  2197   beq(CCR0, filtered);
  2199   if (Robj != noreg && UseCompressedOops) {
  2200     decode_heap_oop_not_null(Rpre_val);
  2203   // OK, it's not filtered, so we'll need to call enqueue. In the normal
  2204   // case, pre_val will be a scratch G-reg, but there are some cases in
  2205   // which it's an O-reg. In the first case, do a normal call. In the
  2206   // latter, do a save here and call the frameless version.
  2208   // Can we store original value in the thread's buffer?
  2209   // Is index == 0?
  2210   // (The index field is typed as size_t.)
  2211   const Register Rbuffer = Rtmp1, Rindex = Rtmp2;
  2213   ld(Rindex, in_bytes(JavaThread::satb_mark_queue_offset() + PtrQueue::byte_offset_of_index()), R16_thread);
  2214   cmpdi(CCR0, Rindex, 0);
  2215   beq(CCR0, runtime); // If index == 0, goto runtime.
  2216   ld(Rbuffer, in_bytes(JavaThread::satb_mark_queue_offset() + PtrQueue::byte_offset_of_buf()), R16_thread);
  2218   addi(Rindex, Rindex, -wordSize); // Decrement index.
  2219   std(Rindex, in_bytes(JavaThread::satb_mark_queue_offset() + PtrQueue::byte_offset_of_index()), R16_thread);
  2221   // Record the previous value.
  2222   stdx(Rpre_val, Rbuffer, Rindex);
  2223   b(filtered);
  2225   bind(runtime);
  2227   // VM call need frame to access(write) O register.
  2228   if (needs_frame) {
  2229     save_LR_CR(Rtmp1);
  2230     push_frame_abi112(0, Rtmp2);
  2233   if (Rpre_val->is_volatile() && Robj == noreg) mr(R31, Rpre_val); // Save pre_val across C call if it was preloaded.
  2234   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), Rpre_val, R16_thread);
  2235   if (Rpre_val->is_volatile() && Robj == noreg) mr(Rpre_val, R31); // restore
  2237   if (needs_frame) {
  2238     pop_frame();
  2239     restore_LR_CR(Rtmp1);
  2242   bind(filtered);
  2245 // General G1 post-barrier generator
  2246 // Store cross-region card.
  2247 void MacroAssembler::g1_write_barrier_post(Register Rstore_addr, Register Rnew_val, Register Rtmp1, Register Rtmp2, Register Rtmp3, Label *filtered_ext) {
  2248   Label runtime, filtered_int;
  2249   Label& filtered = (filtered_ext != NULL) ? *filtered_ext : filtered_int;
  2250   assert_different_registers(Rstore_addr, Rnew_val, Rtmp1, Rtmp2);
  2252   G1SATBCardTableModRefBS* bs = (G1SATBCardTableModRefBS*) Universe::heap()->barrier_set();
  2253   assert(bs->kind() == BarrierSet::G1SATBCT ||
  2254          bs->kind() == BarrierSet::G1SATBCTLogging, "wrong barrier");
  2256   // Does store cross heap regions?
  2257   if (G1RSBarrierRegionFilter) {
  2258     xorr(Rtmp1, Rstore_addr, Rnew_val);
  2259     srdi_(Rtmp1, Rtmp1, HeapRegion::LogOfHRGrainBytes);
  2260     beq(CCR0, filtered);
  2263   // Crosses regions, storing NULL?
  2264 #ifdef ASSERT
  2265   cmpdi(CCR0, Rnew_val, 0);
  2266   asm_assert_ne("null oop not allowed (G1)", 0x322); // Checked by caller on PPC64, so following branch is obsolete:
  2267   //beq(CCR0, filtered);
  2268 #endif
  2270   // Storing region crossing non-NULL, is card already dirty?
  2271   assert(sizeof(*bs->byte_map_base) == sizeof(jbyte), "adjust this code");
  2272   const Register Rcard_addr = Rtmp1;
  2273   Register Rbase = Rtmp2;
  2274   load_const_optimized(Rbase, (address)bs->byte_map_base, /*temp*/ Rtmp3);
  2276   srdi(Rcard_addr, Rstore_addr, CardTableModRefBS::card_shift);
  2278   // Get the address of the card.
  2279   lbzx(/*card value*/ Rtmp3, Rbase, Rcard_addr);
  2281   assert(CardTableModRefBS::dirty_card_val() == 0, "otherwise check this code");
  2282   cmpwi(CCR0, Rtmp3 /* card value */, 0);
  2283   beq(CCR0, filtered);
  2285   // Storing a region crossing, non-NULL oop, card is clean.
  2286   // Dirty card and log.
  2287   li(Rtmp3, 0); // dirty
  2288   //release(); // G1: oops are allowed to get visible after dirty marking.
  2289   stbx(Rtmp3, Rbase, Rcard_addr);
  2291   add(Rcard_addr, Rbase, Rcard_addr); // This is the address which needs to get enqueued.
  2292   Rbase = noreg; // end of lifetime
  2294   const Register Rqueue_index = Rtmp2,
  2295                  Rqueue_buf   = Rtmp3;
  2296   ld(Rqueue_index, in_bytes(JavaThread::dirty_card_queue_offset() + PtrQueue::byte_offset_of_index()), R16_thread);
  2297   cmpdi(CCR0, Rqueue_index, 0);
  2298   beq(CCR0, runtime); // index == 0 then jump to runtime
  2299   ld(Rqueue_buf, in_bytes(JavaThread::dirty_card_queue_offset() + PtrQueue::byte_offset_of_buf()), R16_thread);
  2301   addi(Rqueue_index, Rqueue_index, -wordSize); // decrement index
  2302   std(Rqueue_index, in_bytes(JavaThread::dirty_card_queue_offset() + PtrQueue::byte_offset_of_index()), R16_thread);
  2304   stdx(Rcard_addr, Rqueue_buf, Rqueue_index); // store card
  2305   b(filtered);
  2307   bind(runtime);
  2309   // Save the live input values.
  2310   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), Rcard_addr, R16_thread);
  2312   bind(filtered_int);
  2314 #endif // SERIALGC
  2316 // Values for last_Java_pc, and last_Java_sp must comply to the rules
  2317 // in frame_ppc64.hpp.
  2318 void MacroAssembler::set_last_Java_frame(Register last_Java_sp, Register last_Java_pc) {
  2319   // Always set last_Java_pc and flags first because once last_Java_sp
  2320   // is visible has_last_Java_frame is true and users will look at the
  2321   // rest of the fields. (Note: flags should always be zero before we
  2322   // get here so doesn't need to be set.)
  2324   // Verify that last_Java_pc was zeroed on return to Java
  2325   asm_assert_mem8_is_zero(in_bytes(JavaThread::last_Java_pc_offset()), R16_thread,
  2326                           "last_Java_pc not zeroed before leaving Java", 0x200);
  2328   // When returning from calling out from Java mode the frame anchor's
  2329   // last_Java_pc will always be set to NULL. It is set here so that
  2330   // if we are doing a call to native (not VM) that we capture the
  2331   // known pc and don't have to rely on the native call having a
  2332   // standard frame linkage where we can find the pc.
  2333   if (last_Java_pc != noreg)
  2334     std(last_Java_pc, in_bytes(JavaThread::last_Java_pc_offset()), R16_thread);
  2336   // Set last_Java_sp last.
  2337   std(last_Java_sp, in_bytes(JavaThread::last_Java_sp_offset()), R16_thread);
  2340 void MacroAssembler::reset_last_Java_frame(void) {
  2341   asm_assert_mem8_isnot_zero(in_bytes(JavaThread::last_Java_sp_offset()),
  2342                              R16_thread, "SP was not set, still zero", 0x202);
  2344   BLOCK_COMMENT("reset_last_Java_frame {");
  2345   li(R0, 0);
  2347   // _last_Java_sp = 0
  2348   std(R0, in_bytes(JavaThread::last_Java_sp_offset()), R16_thread);
  2350   // _last_Java_pc = 0
  2351   std(R0, in_bytes(JavaThread::last_Java_pc_offset()), R16_thread);
  2352   BLOCK_COMMENT("} reset_last_Java_frame");
  2355 void MacroAssembler::set_top_ijava_frame_at_SP_as_last_Java_frame(Register sp, Register tmp1) {
  2356   assert_different_registers(sp, tmp1);
  2358   // sp points to a TOP_IJAVA_FRAME, retrieve frame's PC via
  2359   // TOP_IJAVA_FRAME_ABI.
  2360   // FIXME: assert that we really have a TOP_IJAVA_FRAME here!
  2361 #ifdef CC_INTERP
  2362   ld(tmp1/*pc*/, _top_ijava_frame_abi(frame_manager_lr), sp);
  2363 #else
  2364   Unimplemented();
  2365 #endif
  2367   set_last_Java_frame(/*sp=*/sp, /*pc=*/tmp1);
  2370 void MacroAssembler::get_vm_result(Register oop_result) {
  2371   // Read:
  2372   //   R16_thread
  2373   //   R16_thread->in_bytes(JavaThread::vm_result_offset())
  2374   //
  2375   // Updated:
  2376   //   oop_result
  2377   //   R16_thread->in_bytes(JavaThread::vm_result_offset())
  2379   ld(oop_result, in_bytes(JavaThread::vm_result_offset()), R16_thread);
  2380   li(R0, 0);
  2381   std(R0, in_bytes(JavaThread::vm_result_offset()), R16_thread);
  2383   verify_oop(oop_result);
  2386 void MacroAssembler::get_vm_result_2(Register metadata_result) {
  2387   // Read:
  2388   //   R16_thread
  2389   //   R16_thread->in_bytes(JavaThread::vm_result_2_offset())
  2390   //
  2391   // Updated:
  2392   //   metadata_result
  2393   //   R16_thread->in_bytes(JavaThread::vm_result_2_offset())
  2395   ld(metadata_result, in_bytes(JavaThread::vm_result_2_offset()), R16_thread);
  2396   li(R0, 0);
  2397   std(R0, in_bytes(JavaThread::vm_result_2_offset()), R16_thread);
  2401 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
  2402   if (src == noreg) src = dst;
  2403   if (Universe::narrow_klass_base() != 0) {
  2404     load_const(R0, Universe::narrow_klass_base());
  2405     sub(dst, src, R0);
  2407   if (Universe::narrow_klass_shift() != 0 ||
  2408       Universe::narrow_klass_base() == 0 && src != dst) {  // Move required.
  2409     srdi(dst, src, Universe::narrow_klass_shift());
  2413 void MacroAssembler::store_klass(Register dst_oop, Register klass, Register ck) {
  2414   if (UseCompressedClassPointers) {
  2415     encode_klass_not_null(ck, klass);
  2416     stw(ck, oopDesc::klass_offset_in_bytes(), dst_oop);
  2417   } else {
  2418     std(klass, oopDesc::klass_offset_in_bytes(), dst_oop);
  2422 int MacroAssembler::instr_size_for_decode_klass_not_null() {
  2423   if (!UseCompressedClassPointers) return 0;
  2424   int num_instrs = 1;  // shift or move
  2425   if (Universe::narrow_klass_base() != 0) num_instrs = 7;  // shift + load const + add
  2426   return num_instrs * BytesPerInstWord;
  2429 void MacroAssembler::decode_klass_not_null(Register dst, Register src) {
  2430   if (src == noreg) src = dst;
  2431   Register shifted_src = src;
  2432   if (Universe::narrow_klass_shift() != 0 ||
  2433       Universe::narrow_klass_base() == 0 && src != dst) {  // Move required.
  2434     shifted_src = dst;
  2435     sldi(shifted_src, src, Universe::narrow_klass_shift());
  2437   if (Universe::narrow_klass_base() != 0) {
  2438     load_const(R0, Universe::narrow_klass_base());
  2439     add(dst, shifted_src, R0);
  2443 void MacroAssembler::load_klass(Register dst, Register src) {
  2444   if (UseCompressedClassPointers) {
  2445     lwz(dst, oopDesc::klass_offset_in_bytes(), src);
  2446     // Attention: no null check here!
  2447     decode_klass_not_null(dst, dst);
  2448   } else {
  2449     ld(dst, oopDesc::klass_offset_in_bytes(), src);
  2453 void MacroAssembler::load_klass_with_trap_null_check(Register dst, Register src) {
  2454   if (!os::zero_page_read_protected()) {
  2455     if (TrapBasedNullChecks) {
  2456       trap_null_check(src);
  2459   load_klass(dst, src);
  2462 void MacroAssembler::reinit_heapbase(Register d, Register tmp) {
  2463   if (Universe::heap() != NULL) {
  2464     if (Universe::narrow_oop_base() == NULL) {
  2465       Assembler::xorr(R30, R30, R30);
  2466     } else {
  2467       load_const(R30, Universe::narrow_ptrs_base(), tmp);
  2469   } else {
  2470     load_const(R30, Universe::narrow_ptrs_base_addr(), tmp);
  2471     ld(R30, 0, R30);
  2475 // Clear Array
  2476 // Kills both input registers. tmp == R0 is allowed.
  2477 void MacroAssembler::clear_memory_doubleword(Register base_ptr, Register cnt_dwords, Register tmp) {
  2478   // Procedure for large arrays (uses data cache block zero instruction).
  2479     Label startloop, fast, fastloop, small_rest, restloop, done;
  2480     const int cl_size         = VM_Version::get_cache_line_size(),
  2481               cl_dwords       = cl_size>>3,
  2482               cl_dw_addr_bits = exact_log2(cl_dwords),
  2483               dcbz_min        = 1;                     // Min count of dcbz executions, needs to be >0.
  2485 //2:
  2486     cmpdi(CCR1, cnt_dwords, ((dcbz_min+1)<<cl_dw_addr_bits)-1); // Big enough? (ensure >=dcbz_min lines included).
  2487     blt(CCR1, small_rest);                                      // Too small.
  2488     rldicl_(tmp, base_ptr, 64-3, 64-cl_dw_addr_bits);           // Extract dword offset within first cache line.
  2489     beq(CCR0, fast);                                            // Already 128byte aligned.
  2491     subfic(tmp, tmp, cl_dwords);
  2492     mtctr(tmp);                        // Set ctr to hit 128byte boundary (0<ctr<cl_dwords).
  2493     subf(cnt_dwords, tmp, cnt_dwords); // rest.
  2494     li(tmp, 0);
  2495 //10:
  2496   bind(startloop);                     // Clear at the beginning to reach 128byte boundary.
  2497     std(tmp, 0, base_ptr);             // Clear 8byte aligned block.
  2498     addi(base_ptr, base_ptr, 8);
  2499     bdnz(startloop);
  2500 //13:
  2501   bind(fast);                                  // Clear 128byte blocks.
  2502     srdi(tmp, cnt_dwords, cl_dw_addr_bits);    // Loop count for 128byte loop (>0).
  2503     andi(cnt_dwords, cnt_dwords, cl_dwords-1); // Rest in dwords.
  2504     mtctr(tmp);                                // Load counter.
  2505 //16:
  2506   bind(fastloop);
  2507     dcbz(base_ptr);                    // Clear 128byte aligned block.
  2508     addi(base_ptr, base_ptr, cl_size);
  2509     bdnz(fastloop);
  2510     if (InsertEndGroupPPC64) { endgroup(); } else { nop(); }
  2511 //20:
  2512   bind(small_rest);
  2513     cmpdi(CCR0, cnt_dwords, 0);        // size 0?
  2514     beq(CCR0, done);                   // rest == 0
  2515     li(tmp, 0);
  2516     mtctr(cnt_dwords);                 // Load counter.
  2517 //24:
  2518   bind(restloop);                      // Clear rest.
  2519     std(tmp, 0, base_ptr);             // Clear 8byte aligned block.
  2520     addi(base_ptr, base_ptr, 8);
  2521     bdnz(restloop);
  2522 //27:
  2523   bind(done);
  2526 /////////////////////////////////////////// String intrinsics ////////////////////////////////////////////
  2528 // Search for a single jchar in an jchar[].
  2529 //
  2530 // Assumes that result differs from all other registers.
  2531 //
  2532 // Haystack, needle are the addresses of jchar-arrays.
  2533 // NeedleChar is needle[0] if it is known at compile time.
  2534 // Haycnt is the length of the haystack. We assume haycnt >=1.
  2535 //
  2536 // Preserves haystack, haycnt, kills all other registers.
  2537 //
  2538 // If needle == R0, we search for the constant needleChar.
  2539 void MacroAssembler::string_indexof_1(Register result, Register haystack, Register haycnt,
  2540                                       Register needle, jchar needleChar,
  2541                                       Register tmp1, Register tmp2) {
  2543   assert_different_registers(result, haystack, haycnt, needle, tmp1, tmp2);
  2545   Label L_InnerLoop, L_FinalCheck, L_Found1, L_Found2, L_Found3, L_NotFound, L_End;
  2546   Register needle0 = needle, // Contains needle[0].
  2547            addr = tmp1,
  2548            ch1 = tmp2,
  2549            ch2 = R0;
  2551 //2 (variable) or 3 (const):
  2552    if (needle != R0) lhz(needle0, 0, needle); // Preload needle character, needle has len==1.
  2553    dcbtct(haystack, 0x00);                        // Indicate R/O access to haystack.
  2555    srwi_(tmp2, haycnt, 1);   // Shift right by exact_log2(UNROLL_FACTOR).
  2556    mr(addr, haystack);
  2557    beq(CCR0, L_FinalCheck);
  2558    mtctr(tmp2);              // Move to count register.
  2559 //8:
  2560   bind(L_InnerLoop);             // Main work horse (2x unrolled search loop).
  2561    lhz(ch1, 0, addr);        // Load characters from haystack.
  2562    lhz(ch2, 2, addr);
  2563    (needle != R0) ? cmpw(CCR0, ch1, needle0) : cmplwi(CCR0, ch1, needleChar);
  2564    (needle != R0) ? cmpw(CCR1, ch2, needle0) : cmplwi(CCR1, ch2, needleChar);
  2565    beq(CCR0, L_Found1);   // Did we find the needle?
  2566    beq(CCR1, L_Found2);
  2567    addi(addr, addr, 4);
  2568    bdnz(L_InnerLoop);
  2569 //16:
  2570   bind(L_FinalCheck);
  2571    andi_(R0, haycnt, 1);
  2572    beq(CCR0, L_NotFound);
  2573    lhz(ch1, 0, addr);        // One position left at which we have to compare.
  2574    (needle != R0) ? cmpw(CCR1, ch1, needle0) : cmplwi(CCR1, ch1, needleChar);
  2575    beq(CCR1, L_Found3);
  2576 //21:
  2577   bind(L_NotFound);
  2578    li(result, -1);           // Not found.
  2579    b(L_End);
  2581   bind(L_Found2);
  2582    addi(addr, addr, 2);
  2583 //24:
  2584   bind(L_Found1);
  2585   bind(L_Found3);                  // Return index ...
  2586    subf(addr, haystack, addr); // relative to haystack,
  2587    srdi(result, addr, 1);      // in characters.
  2588   bind(L_End);
  2592 // Implementation of IndexOf for jchar arrays.
  2593 //
  2594 // The length of haystack and needle are not constant, i.e. passed in a register.
  2595 //
  2596 // Preserves registers haystack, needle.
  2597 // Kills registers haycnt, needlecnt.
  2598 // Assumes that result differs from all other registers.
  2599 // Haystack, needle are the addresses of jchar-arrays.
  2600 // Haycnt, needlecnt are the lengths of them, respectively.
  2601 //
  2602 // Needlecntval must be zero or 15-bit unsigned immediate and > 1.
  2603 void MacroAssembler::string_indexof(Register result, Register haystack, Register haycnt,
  2604                                     Register needle, ciTypeArray* needle_values, Register needlecnt, int needlecntval,
  2605                                     Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
  2607   // Ensure 0<needlecnt<=haycnt in ideal graph as prerequisite!
  2608   Label L_TooShort, L_Found, L_NotFound, L_End;
  2609   Register last_addr = haycnt, // Kill haycnt at the beginning.
  2610            addr      = tmp1,
  2611            n_start   = tmp2,
  2612            ch1       = tmp3,
  2613            ch2       = R0;
  2615   // **************************************************************************************************
  2616   // Prepare for main loop: optimized for needle count >=2, bail out otherwise.
  2617   // **************************************************************************************************
  2619 //1 (variable) or 3 (const):
  2620    dcbtct(needle, 0x00);    // Indicate R/O access to str1.
  2621    dcbtct(haystack, 0x00);  // Indicate R/O access to str2.
  2623   // Compute last haystack addr to use if no match gets found.
  2624   if (needlecntval == 0) { // variable needlecnt
  2625 //3:
  2626    subf(ch1, needlecnt, haycnt);      // Last character index to compare is haycnt-needlecnt.
  2627    addi(addr, haystack, -2);          // Accesses use pre-increment.
  2628    cmpwi(CCR6, needlecnt, 2);
  2629    blt(CCR6, L_TooShort);          // Variable needlecnt: handle short needle separately.
  2630    slwi(ch1, ch1, 1);                 // Scale to number of bytes.
  2631    lwz(n_start, 0, needle);           // Load first 2 characters of needle.
  2632    add(last_addr, haystack, ch1);     // Point to last address to compare (haystack+2*(haycnt-needlecnt)).
  2633    addi(needlecnt, needlecnt, -2);    // Rest of needle.
  2634   } else { // constant needlecnt
  2635   guarantee(needlecntval != 1, "IndexOf with single-character needle must be handled separately");
  2636   assert((needlecntval & 0x7fff) == needlecntval, "wrong immediate");
  2637 //5:
  2638    addi(ch1, haycnt, -needlecntval);  // Last character index to compare is haycnt-needlecnt.
  2639    lwz(n_start, 0, needle);           // Load first 2 characters of needle.
  2640    addi(addr, haystack, -2);          // Accesses use pre-increment.
  2641    slwi(ch1, ch1, 1);                 // Scale to number of bytes.
  2642    add(last_addr, haystack, ch1);     // Point to last address to compare (haystack+2*(haycnt-needlecnt)).
  2643    li(needlecnt, needlecntval-2);     // Rest of needle.
  2646   // Main Loop (now we have at least 3 characters).
  2647 //11:
  2648   Label L_OuterLoop, L_InnerLoop, L_FinalCheck, L_Comp1, L_Comp2, L_Comp3;
  2649   bind(L_OuterLoop); // Search for 1st 2 characters.
  2650   Register addr_diff = tmp4;
  2651    subf(addr_diff, addr, last_addr); // Difference between already checked address and last address to check.
  2652    addi(addr, addr, 2);              // This is the new address we want to use for comparing.
  2653    srdi_(ch2, addr_diff, 2);
  2654    beq(CCR0, L_FinalCheck);       // 2 characters left?
  2655    mtctr(ch2);                       // addr_diff/4
  2656 //16:
  2657   bind(L_InnerLoop);                // Main work horse (2x unrolled search loop)
  2658    lwz(ch1, 0, addr);           // Load 2 characters of haystack (ignore alignment).
  2659    lwz(ch2, 2, addr);
  2660    cmpw(CCR0, ch1, n_start); // Compare 2 characters (1 would be sufficient but try to reduce branches to CompLoop).
  2661    cmpw(CCR1, ch2, n_start);
  2662    beq(CCR0, L_Comp1);       // Did we find the needle start?
  2663    beq(CCR1, L_Comp2);
  2664    addi(addr, addr, 4);
  2665    bdnz(L_InnerLoop);
  2666 //24:
  2667   bind(L_FinalCheck);
  2668    rldicl_(addr_diff, addr_diff, 64-1, 63); // Remaining characters not covered by InnerLoop: (addr_diff>>1)&1.
  2669    beq(CCR0, L_NotFound);
  2670    lwz(ch1, 0, addr);                       // One position left at which we have to compare.
  2671    cmpw(CCR1, ch1, n_start);
  2672    beq(CCR1, L_Comp3);
  2673 //29:
  2674   bind(L_NotFound);
  2675    li(result, -1); // not found
  2676    b(L_End);
  2679    // **************************************************************************************************
  2680    // Special Case: unfortunately, the variable needle case can be called with needlecnt<2
  2681    // **************************************************************************************************
  2682 //31:
  2683  if ((needlecntval>>1) !=1 ) { // Const needlecnt is 2 or 3? Reduce code size.
  2684   int nopcnt = 5;
  2685   if (needlecntval !=0 ) ++nopcnt; // Balance alignment (other case: see below).
  2686   if (needlecntval == 0) {         // We have to handle these cases separately.
  2687   Label L_OneCharLoop;
  2688   bind(L_TooShort);
  2689    mtctr(haycnt);
  2690    lhz(n_start, 0, needle);    // First character of needle
  2691   bind(L_OneCharLoop);
  2692    lhzu(ch1, 2, addr);
  2693    cmpw(CCR1, ch1, n_start);
  2694    beq(CCR1, L_Found);      // Did we find the one character needle?
  2695    bdnz(L_OneCharLoop);
  2696    li(result, -1);             // Not found.
  2697    b(L_End);
  2698   } // 8 instructions, so no impact on alignment.
  2699   for (int x = 0; x < nopcnt; ++x) nop();
  2702   // **************************************************************************************************
  2703   // Regular Case Part II: compare rest of needle (first 2 characters have been compared already)
  2704   // **************************************************************************************************
  2706   // Compare the rest
  2707 //36 if needlecntval==0, else 37:
  2708   bind(L_Comp2);
  2709    addi(addr, addr, 2); // First comparison has failed, 2nd one hit.
  2710   bind(L_Comp1);            // Addr points to possible needle start.
  2711   bind(L_Comp3);            // Could have created a copy and use a different return address but saving code size here.
  2712   if (needlecntval != 2) {  // Const needlecnt==2?
  2713    if (needlecntval != 3) {
  2714     if (needlecntval == 0) beq(CCR6, L_Found); // Variable needlecnt==2?
  2715     Register ind_reg = tmp4;
  2716     li(ind_reg, 2*2);   // First 2 characters are already compared, use index 2.
  2717     mtctr(needlecnt);   // Decremented by 2, still > 0.
  2718 //40:
  2719    Label L_CompLoop;
  2720    bind(L_CompLoop);
  2721     lhzx(ch2, needle, ind_reg);
  2722     lhzx(ch1, addr, ind_reg);
  2723     cmpw(CCR1, ch1, ch2);
  2724     bne(CCR1, L_OuterLoop);
  2725     addi(ind_reg, ind_reg, 2);
  2726     bdnz(L_CompLoop);
  2727    } else { // No loop required if there's only one needle character left.
  2728     lhz(ch2, 2*2, needle);
  2729     lhz(ch1, 2*2, addr);
  2730     cmpw(CCR1, ch1, ch2);
  2731     bne(CCR1, L_OuterLoop);
  2734   // Return index ...
  2735 //46:
  2736   bind(L_Found);
  2737    subf(addr, haystack, addr); // relative to haystack, ...
  2738    srdi(result, addr, 1);      // in characters.
  2739 //48:
  2740   bind(L_End);
  2743 // Implementation of Compare for jchar arrays.
  2744 //
  2745 // Kills the registers str1, str2, cnt1, cnt2.
  2746 // Kills cr0, ctr.
  2747 // Assumes that result differes from the input registers.
  2748 void MacroAssembler::string_compare(Register str1_reg, Register str2_reg, Register cnt1_reg, Register cnt2_reg,
  2749                                     Register result_reg, Register tmp_reg) {
  2750    assert_different_registers(result_reg, str1_reg, str2_reg, cnt1_reg, cnt2_reg, tmp_reg);
  2752    Label Ldone, Lslow_case, Lslow_loop, Lfast_loop;
  2753    Register cnt_diff = R0,
  2754             limit_reg = cnt1_reg,
  2755             chr1_reg = result_reg,
  2756             chr2_reg = cnt2_reg,
  2757             addr_diff = str2_reg;
  2759    // Offset 0 should be 32 byte aligned.
  2760 //-4:
  2761     dcbtct(str1_reg, 0x00);  // Indicate R/O access to str1.
  2762     dcbtct(str2_reg, 0x00);  // Indicate R/O access to str2.
  2763 //-2:
  2764    // Compute min(cnt1, cnt2) and check if 0 (bail out if we don't need to compare characters).
  2765     subf(result_reg, cnt2_reg, cnt1_reg);  // difference between cnt1/2
  2766     subf_(addr_diff, str1_reg, str2_reg);  // alias?
  2767     beq(CCR0, Ldone);                   // return cnt difference if both ones are identical
  2768     srawi(limit_reg, result_reg, 31);      // generate signmask (cnt1/2 must be non-negative so cnt_diff can't overflow)
  2769     mr(cnt_diff, result_reg);
  2770     andr(limit_reg, result_reg, limit_reg); // difference or zero (negative): cnt1<cnt2 ? cnt1-cnt2 : 0
  2771     add_(limit_reg, cnt2_reg, limit_reg);  // min(cnt1, cnt2)==0?
  2772     beq(CCR0, Ldone);                   // return cnt difference if one has 0 length
  2774     lhz(chr1_reg, 0, str1_reg);            // optional: early out if first characters mismatch
  2775     lhzx(chr2_reg, str1_reg, addr_diff);   // optional: early out if first characters mismatch
  2776     addi(tmp_reg, limit_reg, -1);          // min(cnt1, cnt2)-1
  2777     subf_(result_reg, chr2_reg, chr1_reg); // optional: early out if first characters mismatch
  2778     bne(CCR0, Ldone);                   // optional: early out if first characters mismatch
  2780    // Set loop counter by scaling down tmp_reg
  2781     srawi_(chr2_reg, tmp_reg, exact_log2(4)); // (min(cnt1, cnt2)-1)/4
  2782     ble(CCR0, Lslow_case);                 // need >4 characters for fast loop
  2783     andi(limit_reg, tmp_reg, 4-1);            // remaining characters
  2785    // Adapt str1_reg str2_reg for the first loop iteration
  2786     mtctr(chr2_reg);                 // (min(cnt1, cnt2)-1)/4
  2787     addi(limit_reg, limit_reg, 4+1); // compare last 5-8 characters in slow_case if mismatch found in fast_loop
  2788 //16:
  2789    // Compare the rest of the characters
  2790    bind(Lfast_loop);
  2791     ld(chr1_reg, 0, str1_reg);
  2792     ldx(chr2_reg, str1_reg, addr_diff);
  2793     cmpd(CCR0, chr2_reg, chr1_reg);
  2794     bne(CCR0, Lslow_case); // return chr1_reg
  2795     addi(str1_reg, str1_reg, 4*2);
  2796     bdnz(Lfast_loop);
  2797     addi(limit_reg, limit_reg, -4); // no mismatch found in fast_loop, only 1-4 characters missing
  2798 //23:
  2799    bind(Lslow_case);
  2800     mtctr(limit_reg);
  2801 //24:
  2802    bind(Lslow_loop);
  2803     lhz(chr1_reg, 0, str1_reg);
  2804     lhzx(chr2_reg, str1_reg, addr_diff);
  2805     subf_(result_reg, chr2_reg, chr1_reg);
  2806     bne(CCR0, Ldone); // return chr1_reg
  2807     addi(str1_reg, str1_reg, 1*2);
  2808     bdnz(Lslow_loop);
  2809 //30:
  2810    // If strings are equal up to min length, return the length difference.
  2811     mr(result_reg, cnt_diff);
  2812     nop(); // alignment
  2813 //32:
  2814    // Otherwise, return the difference between the first mismatched chars.
  2815    bind(Ldone);
  2819 // Compare char[] arrays.
  2820 //
  2821 // str1_reg   USE only
  2822 // str2_reg   USE only
  2823 // cnt_reg    USE_DEF, due to tmp reg shortage
  2824 // result_reg DEF only, might compromise USE only registers
  2825 void MacroAssembler::char_arrays_equals(Register str1_reg, Register str2_reg, Register cnt_reg, Register result_reg,
  2826                                         Register tmp1_reg, Register tmp2_reg, Register tmp3_reg, Register tmp4_reg,
  2827                                         Register tmp5_reg) {
  2829   // Str1 may be the same register as str2 which can occur e.g. after scalar replacement.
  2830   assert_different_registers(result_reg, str1_reg, cnt_reg, tmp1_reg, tmp2_reg, tmp3_reg, tmp4_reg, tmp5_reg);
  2831   assert_different_registers(result_reg, str2_reg, cnt_reg, tmp1_reg, tmp2_reg, tmp3_reg, tmp4_reg, tmp5_reg);
  2833   // Offset 0 should be 32 byte aligned.
  2834   Label Linit_cbc, Lcbc, Lloop, Ldone_true, Ldone_false;
  2835   Register index_reg = tmp5_reg;
  2836   Register cbc_iter  = tmp4_reg;
  2838 //-1:
  2839   dcbtct(str1_reg, 0x00);  // Indicate R/O access to str1.
  2840   dcbtct(str2_reg, 0x00);  // Indicate R/O access to str2.
  2841 //1:
  2842   andi(cbc_iter, cnt_reg, 4-1);            // Remaining iterations after 4 java characters per iteration loop.
  2843   li(index_reg, 0); // init
  2844   li(result_reg, 0); // assume false
  2845   srwi_(tmp2_reg, cnt_reg, exact_log2(4)); // Div: 4 java characters per iteration (main loop).
  2847   cmpwi(CCR1, cbc_iter, 0);             // CCR1 = (cbc_iter==0)
  2848   beq(CCR0, Linit_cbc);                 // too short
  2849     mtctr(tmp2_reg);
  2850 //8:
  2851     bind(Lloop);
  2852       ldx(tmp1_reg, str1_reg, index_reg);
  2853       ldx(tmp2_reg, str2_reg, index_reg);
  2854       cmpd(CCR0, tmp1_reg, tmp2_reg);
  2855       bne(CCR0, Ldone_false);  // Unequal char pair found -> done.
  2856       addi(index_reg, index_reg, 4*sizeof(jchar));
  2857       bdnz(Lloop);
  2858 //14:
  2859   bind(Linit_cbc);
  2860   beq(CCR1, Ldone_true);
  2861     mtctr(cbc_iter);
  2862 //16:
  2863     bind(Lcbc);
  2864       lhzx(tmp1_reg, str1_reg, index_reg);
  2865       lhzx(tmp2_reg, str2_reg, index_reg);
  2866       cmpw(CCR0, tmp1_reg, tmp2_reg);
  2867       bne(CCR0, Ldone_false);  // Unequal char pair found -> done.
  2868       addi(index_reg, index_reg, 1*sizeof(jchar));
  2869       bdnz(Lcbc);
  2870     nop();
  2871   bind(Ldone_true);
  2872   li(result_reg, 1);
  2873 //24:
  2874   bind(Ldone_false);
  2878 void MacroAssembler::char_arrays_equalsImm(Register str1_reg, Register str2_reg, int cntval, Register result_reg,
  2879                                            Register tmp1_reg, Register tmp2_reg) {
  2880   // Str1 may be the same register as str2 which can occur e.g. after scalar replacement.
  2881   assert_different_registers(result_reg, str1_reg, tmp1_reg, tmp2_reg);
  2882   assert_different_registers(result_reg, str2_reg, tmp1_reg, tmp2_reg);
  2883   assert(sizeof(jchar) == 2, "must be");
  2884   assert(cntval >= 0 && ((cntval & 0x7fff) == cntval), "wrong immediate");
  2886   Label Ldone_false;
  2888   if (cntval < 16) { // short case
  2889     if (cntval != 0) li(result_reg, 0); // assume false
  2891     const int num_bytes = cntval*sizeof(jchar);
  2892     int index = 0;
  2893     for (int next_index; (next_index = index + 8) <= num_bytes; index = next_index) {
  2894       ld(tmp1_reg, index, str1_reg);
  2895       ld(tmp2_reg, index, str2_reg);
  2896       cmpd(CCR0, tmp1_reg, tmp2_reg);
  2897       bne(CCR0, Ldone_false);
  2899     if (cntval & 2) {
  2900       lwz(tmp1_reg, index, str1_reg);
  2901       lwz(tmp2_reg, index, str2_reg);
  2902       cmpw(CCR0, tmp1_reg, tmp2_reg);
  2903       bne(CCR0, Ldone_false);
  2904       index += 4;
  2906     if (cntval & 1) {
  2907       lhz(tmp1_reg, index, str1_reg);
  2908       lhz(tmp2_reg, index, str2_reg);
  2909       cmpw(CCR0, tmp1_reg, tmp2_reg);
  2910       bne(CCR0, Ldone_false);
  2912     // fallthrough: true
  2913   } else {
  2914     Label Lloop;
  2915     Register index_reg = tmp1_reg;
  2916     const int loopcnt = cntval/4;
  2917     assert(loopcnt > 0, "must be");
  2918     // Offset 0 should be 32 byte aligned.
  2919     //2:
  2920     dcbtct(str1_reg, 0x00);  // Indicate R/O access to str1.
  2921     dcbtct(str2_reg, 0x00);  // Indicate R/O access to str2.
  2922     li(tmp2_reg, loopcnt);
  2923     li(index_reg, 0); // init
  2924     li(result_reg, 0); // assume false
  2925     mtctr(tmp2_reg);
  2926     //8:
  2927     bind(Lloop);
  2928     ldx(R0, str1_reg, index_reg);
  2929     ldx(tmp2_reg, str2_reg, index_reg);
  2930     cmpd(CCR0, R0, tmp2_reg);
  2931     bne(CCR0, Ldone_false);  // Unequal char pair found -> done.
  2932     addi(index_reg, index_reg, 4*sizeof(jchar));
  2933     bdnz(Lloop);
  2934     //14:
  2935     if (cntval & 2) {
  2936       lwzx(R0, str1_reg, index_reg);
  2937       lwzx(tmp2_reg, str2_reg, index_reg);
  2938       cmpw(CCR0, R0, tmp2_reg);
  2939       bne(CCR0, Ldone_false);
  2940       if (cntval & 1) addi(index_reg, index_reg, 2*sizeof(jchar));
  2942     if (cntval & 1) {
  2943       lhzx(R0, str1_reg, index_reg);
  2944       lhzx(tmp2_reg, str2_reg, index_reg);
  2945       cmpw(CCR0, R0, tmp2_reg);
  2946       bne(CCR0, Ldone_false);
  2948     // fallthru: true
  2950   li(result_reg, 1);
  2951   bind(Ldone_false);
  2955 void MacroAssembler::asm_assert(bool check_equal, const char *msg, int id) {
  2956 #ifdef ASSERT
  2957   Label ok;
  2958   if (check_equal) {
  2959     beq(CCR0, ok);
  2960   } else {
  2961     bne(CCR0, ok);
  2963   stop(msg, id);
  2964   bind(ok);
  2965 #endif
  2968 void MacroAssembler::asm_assert_mems_zero(bool check_equal, int size, int mem_offset,
  2969                                           Register mem_base, const char* msg, int id) {
  2970 #ifdef ASSERT
  2971   switch (size) {
  2972     case 4:
  2973       lwz(R0, mem_offset, mem_base);
  2974       cmpwi(CCR0, R0, 0);
  2975       break;
  2976     case 8:
  2977       ld(R0, mem_offset, mem_base);
  2978       cmpdi(CCR0, R0, 0);
  2979       break;
  2980     default:
  2981       ShouldNotReachHere();
  2983   asm_assert(check_equal, msg, id);
  2984 #endif // ASSERT
  2987 void MacroAssembler::verify_thread() {
  2988   if (VerifyThread) {
  2989     unimplemented("'VerifyThread' currently not implemented on PPC");
  2993 // READ: oop. KILL: R0. Volatile floats perhaps.
  2994 void MacroAssembler::verify_oop(Register oop, const char* msg) {
  2995   if (!VerifyOops) {
  2996     return;
  2998   // Will be preserved.
  2999   Register tmp = R11;
  3000   assert(oop != tmp, "precondition");
  3001   unsigned int nbytes_save = 10*8; // 10 volatile gprs
  3002   address/* FunctionDescriptor** */fd = StubRoutines::verify_oop_subroutine_entry_address();
  3003   // save tmp
  3004   mr(R0, tmp);
  3005   // kill tmp
  3006   save_LR_CR(tmp);
  3007   push_frame_abi112(nbytes_save, tmp);
  3008   // restore tmp
  3009   mr(tmp, R0);
  3010   save_volatile_gprs(R1_SP, 112); // except R0
  3011   // load FunctionDescriptor**
  3012   load_const(tmp, fd);
  3013   // load FunctionDescriptor*
  3014   ld(tmp, 0, tmp);
  3015   mr(R4_ARG2, oop);
  3016   load_const(R3_ARG1, (address)msg);
  3017   // call destination for its side effect
  3018   call_c(tmp);
  3019   restore_volatile_gprs(R1_SP, 112); // except R0
  3020   pop_frame();
  3021   // save tmp
  3022   mr(R0, tmp);
  3023   // kill tmp
  3024   restore_LR_CR(tmp);
  3025   // restore tmp
  3026   mr(tmp, R0);
  3029 const char* stop_types[] = {
  3030   "stop",
  3031   "untested",
  3032   "unimplemented",
  3033   "shouldnotreachhere"
  3034 };
  3036 static void stop_on_request(int tp, const char* msg) {
  3037   tty->print("PPC assembly code requires stop: (%s) %s\n", (void *)stop_types[tp%/*stop_end*/4], msg);
  3038   guarantee(false, err_msg("PPC assembly code requires stop: %s", msg));
  3041 // Call a C-function that prints output.
  3042 void MacroAssembler::stop(int type, const char* msg, int id) {
  3043 #ifndef PRODUCT
  3044   block_comment(err_msg("stop: %s %s {", stop_types[type%stop_end], msg));
  3045 #else
  3046   block_comment("stop {");
  3047 #endif
  3049   // setup arguments
  3050   load_const_optimized(R3_ARG1, type);
  3051   load_const_optimized(R4_ARG2, (void *)msg, /*tmp=*/R0);
  3052   call_VM_leaf(CAST_FROM_FN_PTR(address, stop_on_request), R3_ARG1, R4_ARG2);
  3053   illtrap();
  3054   emit_int32(id);
  3055   block_comment("} stop;");
  3058 #ifndef PRODUCT
  3059 // Write pattern 0x0101010101010101 in memory region [low-before, high+after].
  3060 // Val, addr are temp registers.
  3061 // If low == addr, addr is killed.
  3062 // High is preserved.
  3063 void MacroAssembler::zap_from_to(Register low, int before, Register high, int after, Register val, Register addr) {
  3064   if (!ZapMemory) return;
  3066   assert_different_registers(low, val);
  3068   BLOCK_COMMENT("zap memory region {");
  3069   load_const_optimized(val, 0x0101010101010101);
  3070   int size = before + after;
  3071   if (low == high && size < 5 && size > 0) {
  3072     int offset = -before*BytesPerWord;
  3073     for (int i = 0; i < size; ++i) {
  3074       std(val, offset, low);
  3075       offset += (1*BytesPerWord);
  3077   } else {
  3078     addi(addr, low, -before*BytesPerWord);
  3079     assert_different_registers(high, val);
  3080     if (after) addi(high, high, after * BytesPerWord);
  3081     Label loop;
  3082     bind(loop);
  3083     std(val, 0, addr);
  3084     addi(addr, addr, 8);
  3085     cmpd(CCR6, addr, high);
  3086     ble(CCR6, loop);
  3087     if (after) addi(high, high, -after * BytesPerWord);  // Correct back to old value.
  3089   BLOCK_COMMENT("} zap memory region");
  3092 #endif // !PRODUCT

mercurial