src/cpu/ppc/vm/macroAssembler_ppc.cpp

Mon, 10 Mar 2014 12:58:02 +0100

author
goetz
date
Mon, 10 Mar 2014 12:58:02 +0100
changeset 6512
fd1b9f02cc91
parent 6511
31e80afe3fed
child 6515
71a71b0bc844
permissions
-rw-r--r--

8036976: PPC64: implement the template interpreter
Reviewed-by: kvn, coleenp
Contributed-by: axel.siebenborn@sap.com, martin.doerr@sap.com

     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 ori 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,        (xd)); // unsigned int
   226   return (int)((intptr_t)inst2_addr - (intptr_t)inst1_addr);
   227 }
   229 // Get compressed oop or klass constant.
   230 narrowOop MacroAssembler::get_narrow_oop(address a, address bound) {
   231   assert(UseCompressedOops, "Should only patch compressed oops");
   233   const address inst2_addr = a;
   234   const int inst2 = *(int *)inst2_addr;
   236   // The relocation points to the second instruction, the ori,
   237   // and the ori reads and writes the same register dst.
   238   const int dst = inv_rta_field(inst2);
   239   assert(is_ori(inst2) && inv_rs_field(inst2) == dst, "must be ori reading and writing dst");
   240   // Now, find the preceding lis which writes to dst.
   241   int inst1 = 0;
   242   address inst1_addr = inst2_addr - BytesPerInstWord;
   243   bool inst1_found = false;
   245   while (inst1_addr >= bound) {
   246     inst1 = *(int *) inst1_addr;
   247     if (is_lis(inst1) && inv_rs_field(inst1) == dst) { inst1_found = true; break;}
   248     inst1_addr -= BytesPerInstWord;
   249   }
   250   assert(inst1_found, "inst is not lis");
   252   uint xl = ((unsigned int) (get_imm(inst2_addr, 0) & 0xffff));
   253   uint xh = (((get_imm(inst1_addr, 0)) & 0xffff) << 16);
   255   return (int) (xl | xh);
   256 }
   257 #endif // _LP64
   259 void MacroAssembler::load_const_from_method_toc(Register dst, AddressLiteral& a, Register toc) {
   260   int toc_offset = 0;
   261   // Use RelocationHolder::none for the constant pool entry, otherwise
   262   // we will end up with a failing NativeCall::verify(x) where x is
   263   // the address of the constant pool entry.
   264   // FIXME: We should insert relocation information for oops at the constant
   265   // pool entries instead of inserting it at the loads; patching of a constant
   266   // pool entry should be less expensive.
   267   address oop_address = address_constant((address)a.value(), RelocationHolder::none);
   268   // Relocate at the pc of the load.
   269   relocate(a.rspec());
   270   toc_offset = (int)(oop_address - code()->consts()->start());
   271   ld_largeoffset_unchecked(dst, toc_offset, toc, true);
   272 }
   274 bool MacroAssembler::is_load_const_from_method_toc_at(address a) {
   275   const address inst1_addr = a;
   276   const int inst1 = *(int *)inst1_addr;
   278    // The relocation points to the ld or the addis.
   279    return (is_ld(inst1)) ||
   280           (is_addis(inst1) && inv_ra_field(inst1) != 0);
   281 }
   283 int MacroAssembler::get_offset_of_load_const_from_method_toc_at(address a) {
   284   assert(is_load_const_from_method_toc_at(a), "must be load_const_from_method_toc");
   286   const address inst1_addr = a;
   287   const int inst1 = *(int *)inst1_addr;
   289   if (is_ld(inst1)) {
   290     return inv_d1_field(inst1);
   291   } else if (is_addis(inst1)) {
   292     const int dst = inv_rt_field(inst1);
   294     // Now, find the succeeding ld which reads and writes to dst.
   295     address inst2_addr = inst1_addr + BytesPerInstWord;
   296     int inst2 = 0;
   297     while (true) {
   298       inst2 = *(int *) inst2_addr;
   299       if (is_ld(inst2) && inv_ra_field(inst2) == dst && inv_rt_field(inst2) == dst) {
   300         // Stop, found the ld which reads and writes dst.
   301         break;
   302       }
   303       inst2_addr += BytesPerInstWord;
   304     }
   305     return (inv_d1_field(inst1) << 16) + inv_d1_field(inst2);
   306   }
   307   ShouldNotReachHere();
   308   return 0;
   309 }
   311 // Get the constant from a `load_const' sequence.
   312 long MacroAssembler::get_const(address a) {
   313   assert(is_load_const_at(a), "not a load of a constant");
   314   const int *p = (const int*) a;
   315   unsigned long x = (((unsigned long) (get_imm(a,0) & 0xffff)) << 48);
   316   if (is_ori(*(p+1))) {
   317     x |= (((unsigned long) (get_imm(a,1) & 0xffff)) << 32);
   318     x |= (((unsigned long) (get_imm(a,3) & 0xffff)) << 16);
   319     x |= (((unsigned long) (get_imm(a,4) & 0xffff)));
   320   } else if (is_lis(*(p+1))) {
   321     x |= (((unsigned long) (get_imm(a,2) & 0xffff)) << 32);
   322     x |= (((unsigned long) (get_imm(a,1) & 0xffff)) << 16);
   323     x |= (((unsigned long) (get_imm(a,3) & 0xffff)));
   324   } else {
   325     ShouldNotReachHere();
   326     return (long) 0;
   327   }
   328   return (long) x;
   329 }
   331 // Patch the 64 bit constant of a `load_const' sequence. This is a low
   332 // level procedure. It neither flushes the instruction cache nor is it
   333 // mt safe.
   334 void MacroAssembler::patch_const(address a, long x) {
   335   assert(is_load_const_at(a), "not a load of a constant");
   336   int *p = (int*) a;
   337   if (is_ori(*(p+1))) {
   338     set_imm(0 + p, (x >> 48) & 0xffff);
   339     set_imm(1 + p, (x >> 32) & 0xffff);
   340     set_imm(3 + p, (x >> 16) & 0xffff);
   341     set_imm(4 + p, x & 0xffff);
   342   } else if (is_lis(*(p+1))) {
   343     set_imm(0 + p, (x >> 48) & 0xffff);
   344     set_imm(2 + p, (x >> 32) & 0xffff);
   345     set_imm(1 + p, (x >> 16) & 0xffff);
   346     set_imm(3 + p, x & 0xffff);
   347   } else {
   348     ShouldNotReachHere();
   349   }
   350 }
   352 AddressLiteral MacroAssembler::allocate_metadata_address(Metadata* obj) {
   353   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
   354   int index = oop_recorder()->allocate_metadata_index(obj);
   355   RelocationHolder rspec = metadata_Relocation::spec(index);
   356   return AddressLiteral((address)obj, rspec);
   357 }
   359 AddressLiteral MacroAssembler::constant_metadata_address(Metadata* obj) {
   360   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
   361   int index = oop_recorder()->find_index(obj);
   362   RelocationHolder rspec = metadata_Relocation::spec(index);
   363   return AddressLiteral((address)obj, rspec);
   364 }
   366 AddressLiteral MacroAssembler::allocate_oop_address(jobject obj) {
   367   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
   368   int oop_index = oop_recorder()->allocate_oop_index(obj);
   369   return AddressLiteral(address(obj), oop_Relocation::spec(oop_index));
   370 }
   372 AddressLiteral MacroAssembler::constant_oop_address(jobject obj) {
   373   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
   374   int oop_index = oop_recorder()->find_index(obj);
   375   return AddressLiteral(address(obj), oop_Relocation::spec(oop_index));
   376 }
   378 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
   379                                                       Register tmp, int offset) {
   380   intptr_t value = *delayed_value_addr;
   381   if (value != 0) {
   382     return RegisterOrConstant(value + offset);
   383   }
   385   // Load indirectly to solve generation ordering problem.
   386   // static address, no relocation
   387   int simm16_offset = load_const_optimized(tmp, delayed_value_addr, noreg, true);
   388   ld(tmp, simm16_offset, tmp); // must be aligned ((xa & 3) == 0)
   390   if (offset != 0) {
   391     addi(tmp, tmp, offset);
   392   }
   394   return RegisterOrConstant(tmp);
   395 }
   397 #ifndef PRODUCT
   398 void MacroAssembler::pd_print_patched_instruction(address branch) {
   399   Unimplemented(); // TODO: PPC port
   400 }
   401 #endif // ndef PRODUCT
   403 // Conditional far branch for destinations encodable in 24+2 bits.
   404 void MacroAssembler::bc_far(int boint, int biint, Label& dest, int optimize) {
   406   // If requested by flag optimize, relocate the bc_far as a
   407   // runtime_call and prepare for optimizing it when the code gets
   408   // relocated.
   409   if (optimize == bc_far_optimize_on_relocate) {
   410     relocate(relocInfo::runtime_call_type);
   411   }
   413   // variant 2:
   414   //
   415   //    b!cxx SKIP
   416   //    bxx   DEST
   417   //  SKIP:
   418   //
   420   const int opposite_boint = add_bhint_to_boint(opposite_bhint(inv_boint_bhint(boint)),
   421                                                 opposite_bcond(inv_boint_bcond(boint)));
   423   // We emit two branches.
   424   // First, a conditional branch which jumps around the far branch.
   425   const address not_taken_pc = pc() + 2 * BytesPerInstWord;
   426   const address bc_pc        = pc();
   427   bc(opposite_boint, biint, not_taken_pc);
   429   const int bc_instr = *(int*)bc_pc;
   430   assert(not_taken_pc == (address)inv_bd_field(bc_instr, (intptr_t)bc_pc), "postcondition");
   431   assert(opposite_boint == inv_bo_field(bc_instr), "postcondition");
   432   assert(boint == add_bhint_to_boint(opposite_bhint(inv_boint_bhint(inv_bo_field(bc_instr))),
   433                                      opposite_bcond(inv_boint_bcond(inv_bo_field(bc_instr)))),
   434          "postcondition");
   435   assert(biint == inv_bi_field(bc_instr), "postcondition");
   437   // Second, an unconditional far branch which jumps to dest.
   438   // Note: target(dest) remembers the current pc (see CodeSection::target)
   439   //       and returns the current pc if the label is not bound yet; when
   440   //       the label gets bound, the unconditional far branch will be patched.
   441   const address target_pc = target(dest);
   442   const address b_pc  = pc();
   443   b(target_pc);
   445   assert(not_taken_pc == pc(),                     "postcondition");
   446   assert(dest.is_bound() || target_pc == b_pc, "postcondition");
   447 }
   449 bool MacroAssembler::is_bc_far_at(address instruction_addr) {
   450   return is_bc_far_variant1_at(instruction_addr) ||
   451          is_bc_far_variant2_at(instruction_addr) ||
   452          is_bc_far_variant3_at(instruction_addr);
   453 }
   455 address MacroAssembler::get_dest_of_bc_far_at(address instruction_addr) {
   456   if (is_bc_far_variant1_at(instruction_addr)) {
   457     const address instruction_1_addr = instruction_addr;
   458     const int instruction_1 = *(int*)instruction_1_addr;
   459     return (address)inv_bd_field(instruction_1, (intptr_t)instruction_1_addr);
   460   } else if (is_bc_far_variant2_at(instruction_addr)) {
   461     const address instruction_2_addr = instruction_addr + 4;
   462     return bxx_destination(instruction_2_addr);
   463   } else if (is_bc_far_variant3_at(instruction_addr)) {
   464     return instruction_addr + 8;
   465   }
   466   // variant 4 ???
   467   ShouldNotReachHere();
   468   return NULL;
   469 }
   470 void MacroAssembler::set_dest_of_bc_far_at(address instruction_addr, address dest) {
   472   if (is_bc_far_variant3_at(instruction_addr)) {
   473     // variant 3, far cond branch to the next instruction, already patched to nops:
   474     //
   475     //    nop
   476     //    endgroup
   477     //  SKIP/DEST:
   478     //
   479     return;
   480   }
   482   // first, extract boint and biint from the current branch
   483   int boint = 0;
   484   int biint = 0;
   486   ResourceMark rm;
   487   const int code_size = 2 * BytesPerInstWord;
   488   CodeBuffer buf(instruction_addr, code_size);
   489   MacroAssembler masm(&buf);
   490   if (is_bc_far_variant2_at(instruction_addr) && dest == instruction_addr + 8) {
   491     // Far branch to next instruction: Optimize it by patching nops (produce variant 3).
   492     masm.nop();
   493     masm.endgroup();
   494   } else {
   495     if (is_bc_far_variant1_at(instruction_addr)) {
   496       // variant 1, the 1st instruction contains the destination address:
   497       //
   498       //    bcxx  DEST
   499       //    endgroup
   500       //
   501       const int instruction_1 = *(int*)(instruction_addr);
   502       boint = inv_bo_field(instruction_1);
   503       biint = inv_bi_field(instruction_1);
   504     } else if (is_bc_far_variant2_at(instruction_addr)) {
   505       // variant 2, the 2nd instruction contains the destination address:
   506       //
   507       //    b!cxx SKIP
   508       //    bxx   DEST
   509       //  SKIP:
   510       //
   511       const int instruction_1 = *(int*)(instruction_addr);
   512       boint = add_bhint_to_boint(opposite_bhint(inv_boint_bhint(inv_bo_field(instruction_1))),
   513           opposite_bcond(inv_boint_bcond(inv_bo_field(instruction_1))));
   514       biint = inv_bi_field(instruction_1);
   515     } else {
   516       // variant 4???
   517       ShouldNotReachHere();
   518     }
   520     // second, set the new branch destination and optimize the code
   521     if (dest != instruction_addr + 4 && // the bc_far is still unbound!
   522         masm.is_within_range_of_bcxx(dest, instruction_addr)) {
   523       // variant 1:
   524       //
   525       //    bcxx  DEST
   526       //    endgroup
   527       //
   528       masm.bc(boint, biint, dest);
   529       masm.endgroup();
   530     } else {
   531       // variant 2:
   532       //
   533       //    b!cxx SKIP
   534       //    bxx   DEST
   535       //  SKIP:
   536       //
   537       const int opposite_boint = add_bhint_to_boint(opposite_bhint(inv_boint_bhint(boint)),
   538                                                     opposite_bcond(inv_boint_bcond(boint)));
   539       const address not_taken_pc = masm.pc() + 2 * BytesPerInstWord;
   540       masm.bc(opposite_boint, biint, not_taken_pc);
   541       masm.b(dest);
   542     }
   543   }
   544   ICache::ppc64_flush_icache_bytes(instruction_addr, code_size);
   545 }
   547 // Emit a NOT mt-safe patchable 64 bit absolute call/jump.
   548 void MacroAssembler::bxx64_patchable(address dest, relocInfo::relocType rt, bool link) {
   549   // get current pc
   550   uint64_t start_pc = (uint64_t) pc();
   552   const address pc_of_bl = (address) (start_pc + (6*BytesPerInstWord)); // bl is last
   553   const address pc_of_b  = (address) (start_pc + (0*BytesPerInstWord)); // b is first
   555   // relocate here
   556   if (rt != relocInfo::none) {
   557     relocate(rt);
   558   }
   560   if ( ReoptimizeCallSequences &&
   561        (( link && is_within_range_of_b(dest, pc_of_bl)) ||
   562         (!link && is_within_range_of_b(dest, pc_of_b)))) {
   563     // variant 2:
   564     // Emit an optimized, pc-relative call/jump.
   566     if (link) {
   567       // some padding
   568       nop();
   569       nop();
   570       nop();
   571       nop();
   572       nop();
   573       nop();
   575       // do the call
   576       assert(pc() == pc_of_bl, "just checking");
   577       bl(dest, relocInfo::none);
   578     } else {
   579       // do the jump
   580       assert(pc() == pc_of_b, "just checking");
   581       b(dest, relocInfo::none);
   583       // some padding
   584       nop();
   585       nop();
   586       nop();
   587       nop();
   588       nop();
   589       nop();
   590     }
   592     // Assert that we can identify the emitted call/jump.
   593     assert(is_bxx64_patchable_variant2_at((address)start_pc, link),
   594            "can't identify emitted call");
   595   } else {
   596     // variant 1:
   597 #if defined(ABI_ELFv2)
   598     nop();
   599     calculate_address_from_global_toc(R12, dest, true, true, false);
   600     mtctr(R12);
   601     nop();
   602     nop();
   603 #else
   604     mr(R0, R11);  // spill R11 -> R0.
   606     // Load the destination address into CTR,
   607     // calculate destination relative to global toc.
   608     calculate_address_from_global_toc(R11, dest, true, true, false);
   610     mtctr(R11);
   611     mr(R11, R0);  // spill R11 <- R0.
   612     nop();
   613 #endif
   615     // do the call/jump
   616     if (link) {
   617       bctrl();
   618     } else{
   619       bctr();
   620     }
   621     // Assert that we can identify the emitted call/jump.
   622     assert(is_bxx64_patchable_variant1b_at((address)start_pc, link),
   623            "can't identify emitted call");
   624   }
   626   // Assert that we can identify the emitted call/jump.
   627   assert(is_bxx64_patchable_at((address)start_pc, link),
   628          "can't identify emitted call");
   629   assert(get_dest_of_bxx64_patchable_at((address)start_pc, link) == dest,
   630          "wrong encoding of dest address");
   631 }
   633 // Identify a bxx64_patchable instruction.
   634 bool MacroAssembler::is_bxx64_patchable_at(address instruction_addr, bool link) {
   635   return is_bxx64_patchable_variant1b_at(instruction_addr, link)
   636     //|| is_bxx64_patchable_variant1_at(instruction_addr, link)
   637       || is_bxx64_patchable_variant2_at(instruction_addr, link);
   638 }
   640 // Does the call64_patchable instruction use a pc-relative encoding of
   641 // the call destination?
   642 bool MacroAssembler::is_bxx64_patchable_pcrelative_at(address instruction_addr, bool link) {
   643   // variant 2 is pc-relative
   644   return is_bxx64_patchable_variant2_at(instruction_addr, link);
   645 }
   647 // Identify variant 1.
   648 bool MacroAssembler::is_bxx64_patchable_variant1_at(address instruction_addr, bool link) {
   649   unsigned int* instr = (unsigned int*) instruction_addr;
   650   return (link ? is_bctrl(instr[6]) : is_bctr(instr[6])) // bctr[l]
   651       && is_mtctr(instr[5]) // mtctr
   652     && is_load_const_at(instruction_addr);
   653 }
   655 // Identify variant 1b: load destination relative to global toc.
   656 bool MacroAssembler::is_bxx64_patchable_variant1b_at(address instruction_addr, bool link) {
   657   unsigned int* instr = (unsigned int*) instruction_addr;
   658   return (link ? is_bctrl(instr[6]) : is_bctr(instr[6])) // bctr[l]
   659     && is_mtctr(instr[3]) // mtctr
   660     && is_calculate_address_from_global_toc_at(instruction_addr + 2*BytesPerInstWord, instruction_addr);
   661 }
   663 // Identify variant 2.
   664 bool MacroAssembler::is_bxx64_patchable_variant2_at(address instruction_addr, bool link) {
   665   unsigned int* instr = (unsigned int*) instruction_addr;
   666   if (link) {
   667     return is_bl (instr[6])  // bl dest is last
   668       && is_nop(instr[0])  // nop
   669       && is_nop(instr[1])  // nop
   670       && is_nop(instr[2])  // nop
   671       && is_nop(instr[3])  // nop
   672       && is_nop(instr[4])  // nop
   673       && is_nop(instr[5]); // nop
   674   } else {
   675     return is_b  (instr[0])  // b  dest is first
   676       && is_nop(instr[1])  // nop
   677       && is_nop(instr[2])  // nop
   678       && is_nop(instr[3])  // nop
   679       && is_nop(instr[4])  // nop
   680       && is_nop(instr[5])  // nop
   681       && is_nop(instr[6]); // nop
   682   }
   683 }
   685 // Set dest address of a bxx64_patchable instruction.
   686 void MacroAssembler::set_dest_of_bxx64_patchable_at(address instruction_addr, address dest, bool link) {
   687   ResourceMark rm;
   688   int code_size = MacroAssembler::bxx64_patchable_size;
   689   CodeBuffer buf(instruction_addr, code_size);
   690   MacroAssembler masm(&buf);
   691   masm.bxx64_patchable(dest, relocInfo::none, link);
   692   ICache::ppc64_flush_icache_bytes(instruction_addr, code_size);
   693 }
   695 // Get dest address of a bxx64_patchable instruction.
   696 address MacroAssembler::get_dest_of_bxx64_patchable_at(address instruction_addr, bool link) {
   697   if (is_bxx64_patchable_variant1_at(instruction_addr, link)) {
   698     return (address) (unsigned long) get_const(instruction_addr);
   699   } else if (is_bxx64_patchable_variant2_at(instruction_addr, link)) {
   700     unsigned int* instr = (unsigned int*) instruction_addr;
   701     if (link) {
   702       const int instr_idx = 6; // bl is last
   703       int branchoffset = branch_destination(instr[instr_idx], 0);
   704       return instruction_addr + branchoffset + instr_idx*BytesPerInstWord;
   705     } else {
   706       const int instr_idx = 0; // b is first
   707       int branchoffset = branch_destination(instr[instr_idx], 0);
   708       return instruction_addr + branchoffset + instr_idx*BytesPerInstWord;
   709     }
   710   // Load dest relative to global toc.
   711   } else if (is_bxx64_patchable_variant1b_at(instruction_addr, link)) {
   712     return get_address_of_calculate_address_from_global_toc_at(instruction_addr + 2*BytesPerInstWord,
   713                                                                instruction_addr);
   714   } else {
   715     ShouldNotReachHere();
   716     return NULL;
   717   }
   718 }
   720 // Uses ordering which corresponds to ABI:
   721 //    _savegpr0_14:  std  r14,-144(r1)
   722 //    _savegpr0_15:  std  r15,-136(r1)
   723 //    _savegpr0_16:  std  r16,-128(r1)
   724 void MacroAssembler::save_nonvolatile_gprs(Register dst, int offset) {
   725   std(R14, offset, dst);   offset += 8;
   726   std(R15, offset, dst);   offset += 8;
   727   std(R16, offset, dst);   offset += 8;
   728   std(R17, offset, dst);   offset += 8;
   729   std(R18, offset, dst);   offset += 8;
   730   std(R19, offset, dst);   offset += 8;
   731   std(R20, offset, dst);   offset += 8;
   732   std(R21, offset, dst);   offset += 8;
   733   std(R22, offset, dst);   offset += 8;
   734   std(R23, offset, dst);   offset += 8;
   735   std(R24, offset, dst);   offset += 8;
   736   std(R25, offset, dst);   offset += 8;
   737   std(R26, offset, dst);   offset += 8;
   738   std(R27, offset, dst);   offset += 8;
   739   std(R28, offset, dst);   offset += 8;
   740   std(R29, offset, dst);   offset += 8;
   741   std(R30, offset, dst);   offset += 8;
   742   std(R31, offset, dst);   offset += 8;
   744   stfd(F14, offset, dst);   offset += 8;
   745   stfd(F15, offset, dst);   offset += 8;
   746   stfd(F16, offset, dst);   offset += 8;
   747   stfd(F17, offset, dst);   offset += 8;
   748   stfd(F18, offset, dst);   offset += 8;
   749   stfd(F19, offset, dst);   offset += 8;
   750   stfd(F20, offset, dst);   offset += 8;
   751   stfd(F21, offset, dst);   offset += 8;
   752   stfd(F22, offset, dst);   offset += 8;
   753   stfd(F23, offset, dst);   offset += 8;
   754   stfd(F24, offset, dst);   offset += 8;
   755   stfd(F25, offset, dst);   offset += 8;
   756   stfd(F26, offset, dst);   offset += 8;
   757   stfd(F27, offset, dst);   offset += 8;
   758   stfd(F28, offset, dst);   offset += 8;
   759   stfd(F29, offset, dst);   offset += 8;
   760   stfd(F30, offset, dst);   offset += 8;
   761   stfd(F31, offset, dst);
   762 }
   764 // Uses ordering which corresponds to ABI:
   765 //    _restgpr0_14:  ld   r14,-144(r1)
   766 //    _restgpr0_15:  ld   r15,-136(r1)
   767 //    _restgpr0_16:  ld   r16,-128(r1)
   768 void MacroAssembler::restore_nonvolatile_gprs(Register src, int offset) {
   769   ld(R14, offset, src);   offset += 8;
   770   ld(R15, offset, src);   offset += 8;
   771   ld(R16, offset, src);   offset += 8;
   772   ld(R17, offset, src);   offset += 8;
   773   ld(R18, offset, src);   offset += 8;
   774   ld(R19, offset, src);   offset += 8;
   775   ld(R20, offset, src);   offset += 8;
   776   ld(R21, offset, src);   offset += 8;
   777   ld(R22, offset, src);   offset += 8;
   778   ld(R23, offset, src);   offset += 8;
   779   ld(R24, offset, src);   offset += 8;
   780   ld(R25, offset, src);   offset += 8;
   781   ld(R26, offset, src);   offset += 8;
   782   ld(R27, offset, src);   offset += 8;
   783   ld(R28, offset, src);   offset += 8;
   784   ld(R29, offset, src);   offset += 8;
   785   ld(R30, offset, src);   offset += 8;
   786   ld(R31, offset, src);   offset += 8;
   788   // FP registers
   789   lfd(F14, offset, src);   offset += 8;
   790   lfd(F15, offset, src);   offset += 8;
   791   lfd(F16, offset, src);   offset += 8;
   792   lfd(F17, offset, src);   offset += 8;
   793   lfd(F18, offset, src);   offset += 8;
   794   lfd(F19, offset, src);   offset += 8;
   795   lfd(F20, offset, src);   offset += 8;
   796   lfd(F21, offset, src);   offset += 8;
   797   lfd(F22, offset, src);   offset += 8;
   798   lfd(F23, offset, src);   offset += 8;
   799   lfd(F24, offset, src);   offset += 8;
   800   lfd(F25, offset, src);   offset += 8;
   801   lfd(F26, offset, src);   offset += 8;
   802   lfd(F27, offset, src);   offset += 8;
   803   lfd(F28, offset, src);   offset += 8;
   804   lfd(F29, offset, src);   offset += 8;
   805   lfd(F30, offset, src);   offset += 8;
   806   lfd(F31, offset, src);
   807 }
   809 // For verify_oops.
   810 void MacroAssembler::save_volatile_gprs(Register dst, int offset) {
   811   std(R3,  offset, dst);   offset += 8;
   812   std(R4,  offset, dst);   offset += 8;
   813   std(R5,  offset, dst);   offset += 8;
   814   std(R6,  offset, dst);   offset += 8;
   815   std(R7,  offset, dst);   offset += 8;
   816   std(R8,  offset, dst);   offset += 8;
   817   std(R9,  offset, dst);   offset += 8;
   818   std(R10, offset, dst);   offset += 8;
   819   std(R11, offset, dst);   offset += 8;
   820   std(R12, offset, dst);
   821 }
   823 // For verify_oops.
   824 void MacroAssembler::restore_volatile_gprs(Register src, int offset) {
   825   ld(R3,  offset, src);   offset += 8;
   826   ld(R4,  offset, src);   offset += 8;
   827   ld(R5,  offset, src);   offset += 8;
   828   ld(R6,  offset, src);   offset += 8;
   829   ld(R7,  offset, src);   offset += 8;
   830   ld(R8,  offset, src);   offset += 8;
   831   ld(R9,  offset, src);   offset += 8;
   832   ld(R10, offset, src);   offset += 8;
   833   ld(R11, offset, src);   offset += 8;
   834   ld(R12, offset, src);
   835 }
   837 void MacroAssembler::save_LR_CR(Register tmp) {
   838   mfcr(tmp);
   839   std(tmp, _abi(cr), R1_SP);
   840   mflr(tmp);
   841   std(tmp, _abi(lr), R1_SP);
   842   // Tmp must contain lr on exit! (see return_addr and prolog in ppc64.ad)
   843 }
   845 void MacroAssembler::restore_LR_CR(Register tmp) {
   846   assert(tmp != R1_SP, "must be distinct");
   847   ld(tmp, _abi(lr), R1_SP);
   848   mtlr(tmp);
   849   ld(tmp, _abi(cr), R1_SP);
   850   mtcr(tmp);
   851 }
   853 address MacroAssembler::get_PC_trash_LR(Register result) {
   854   Label L;
   855   bl(L);
   856   bind(L);
   857   address lr_pc = pc();
   858   mflr(result);
   859   return lr_pc;
   860 }
   862 void MacroAssembler::resize_frame(Register offset, Register tmp) {
   863 #ifdef ASSERT
   864   assert_different_registers(offset, tmp, R1_SP);
   865   andi_(tmp, offset, frame::alignment_in_bytes-1);
   866   asm_assert_eq("resize_frame: unaligned", 0x204);
   867 #endif
   869   // tmp <- *(SP)
   870   ld(tmp, _abi(callers_sp), R1_SP);
   871   // addr <- SP + offset;
   872   // *(addr) <- tmp;
   873   // SP <- addr
   874   stdux(tmp, R1_SP, offset);
   875 }
   877 void MacroAssembler::resize_frame(int offset, Register tmp) {
   878   assert(is_simm(offset, 16), "too big an offset");
   879   assert_different_registers(tmp, R1_SP);
   880   assert((offset & (frame::alignment_in_bytes-1))==0, "resize_frame: unaligned");
   881   // tmp <- *(SP)
   882   ld(tmp, _abi(callers_sp), R1_SP);
   883   // addr <- SP + offset;
   884   // *(addr) <- tmp;
   885   // SP <- addr
   886   stdu(tmp, offset, R1_SP);
   887 }
   889 void MacroAssembler::resize_frame_absolute(Register addr, Register tmp1, Register tmp2) {
   890   // (addr == tmp1) || (addr == tmp2) is allowed here!
   891   assert(tmp1 != tmp2, "must be distinct");
   893   // compute offset w.r.t. current stack pointer
   894   // tmp_1 <- addr - SP (!)
   895   subf(tmp1, R1_SP, addr);
   897   // atomically update SP keeping back link.
   898   resize_frame(tmp1/* offset */, tmp2/* tmp */);
   899 }
   901 void MacroAssembler::push_frame(Register bytes, Register tmp) {
   902 #ifdef ASSERT
   903   assert(bytes != R0, "r0 not allowed here");
   904   andi_(R0, bytes, frame::alignment_in_bytes-1);
   905   asm_assert_eq("push_frame(Reg, Reg): unaligned", 0x203);
   906 #endif
   907   neg(tmp, bytes);
   908   stdux(R1_SP, R1_SP, tmp);
   909 }
   911 // Push a frame of size `bytes'.
   912 void MacroAssembler::push_frame(unsigned int bytes, Register tmp) {
   913   long offset = align_addr(bytes, frame::alignment_in_bytes);
   914   if (is_simm(-offset, 16)) {
   915     stdu(R1_SP, -offset, R1_SP);
   916   } else {
   917     load_const(tmp, -offset);
   918     stdux(R1_SP, R1_SP, tmp);
   919   }
   920 }
   922 // Push a frame of size `bytes' plus abi_reg_args on top.
   923 void MacroAssembler::push_frame_reg_args(unsigned int bytes, Register tmp) {
   924   push_frame(bytes + frame::abi_reg_args_size, tmp);
   925 }
   927 // Setup up a new C frame with a spill area for non-volatile GPRs and
   928 // additional space for local variables.
   929 void MacroAssembler::push_frame_reg_args_nonvolatiles(unsigned int bytes,
   930                                                       Register tmp) {
   931   push_frame(bytes + frame::abi_reg_args_size + frame::spill_nonvolatiles_size, tmp);
   932 }
   934 // Pop current C frame.
   935 void MacroAssembler::pop_frame() {
   936   ld(R1_SP, _abi(callers_sp), R1_SP);
   937 }
   939 #if defined(ABI_ELFv2)
   940 address MacroAssembler::branch_to(Register r_function_entry, bool and_link) {
   941   // TODO(asmundak): make sure the caller uses R12 as function descriptor
   942   // most of the times.
   943   if (R12 != r_function_entry) {
   944     mr(R12, r_function_entry);
   945   }
   946   mtctr(R12);
   947   // Do a call or a branch.
   948   if (and_link) {
   949     bctrl();
   950   } else {
   951     bctr();
   952   }
   953   _last_calls_return_pc = pc();
   955   return _last_calls_return_pc;
   956 }
   958 // Call a C function via a function descriptor and use full C
   959 // calling conventions. Updates and returns _last_calls_return_pc.
   960 address MacroAssembler::call_c(Register r_function_entry) {
   961   return branch_to(r_function_entry, /*and_link=*/true);
   962 }
   964 // For tail calls: only branch, don't link, so callee returns to caller of this function.
   965 address MacroAssembler::call_c_and_return_to_caller(Register r_function_entry) {
   966   return branch_to(r_function_entry, /*and_link=*/false);
   967 }
   969 address MacroAssembler::call_c(address function_entry, relocInfo::relocType rt) {
   970   load_const(R12, function_entry, R0);
   971   return branch_to(R12,  /*and_link=*/true);
   972 }
   974 #else
   975 // Generic version of a call to C function via a function descriptor
   976 // with variable support for C calling conventions (TOC, ENV, etc.).
   977 // Updates and returns _last_calls_return_pc.
   978 address MacroAssembler::branch_to(Register function_descriptor, bool and_link, bool save_toc_before_call,
   979                                   bool restore_toc_after_call, bool load_toc_of_callee, bool load_env_of_callee) {
   980   // we emit standard ptrgl glue code here
   981   assert((function_descriptor != R0), "function_descriptor cannot be R0");
   983   // retrieve necessary entries from the function descriptor
   984   ld(R0, in_bytes(FunctionDescriptor::entry_offset()), function_descriptor);
   985   mtctr(R0);
   987   if (load_toc_of_callee) {
   988     ld(R2_TOC, in_bytes(FunctionDescriptor::toc_offset()), function_descriptor);
   989   }
   990   if (load_env_of_callee) {
   991     ld(R11, in_bytes(FunctionDescriptor::env_offset()), function_descriptor);
   992   } else if (load_toc_of_callee) {
   993     li(R11, 0);
   994   }
   996   // do a call or a branch
   997   if (and_link) {
   998     bctrl();
   999   } else {
  1000     bctr();
  1002   _last_calls_return_pc = pc();
  1004   return _last_calls_return_pc;
  1007 // Call a C function via a function descriptor and use full C calling
  1008 // conventions.
  1009 // We don't use the TOC in generated code, so there is no need to save
  1010 // and restore its value.
  1011 address MacroAssembler::call_c(Register fd) {
  1012   return branch_to(fd, /*and_link=*/true,
  1013                        /*save toc=*/false,
  1014                        /*restore toc=*/false,
  1015                        /*load toc=*/true,
  1016                        /*load env=*/true);
  1019 address MacroAssembler::call_c_and_return_to_caller(Register fd) {
  1020   return branch_to(fd, /*and_link=*/false,
  1021                        /*save toc=*/false,
  1022                        /*restore toc=*/false,
  1023                        /*load toc=*/true,
  1024                        /*load env=*/true);
  1027 address MacroAssembler::call_c(const FunctionDescriptor* fd, relocInfo::relocType rt) {
  1028   if (rt != relocInfo::none) {
  1029     // this call needs to be relocatable
  1030     if (!ReoptimizeCallSequences
  1031         || (rt != relocInfo::runtime_call_type && rt != relocInfo::none)
  1032         || fd == NULL   // support code-size estimation
  1033         || !fd->is_friend_function()
  1034         || fd->entry() == NULL) {
  1035       // it's not a friend function as defined by class FunctionDescriptor,
  1036       // so do a full call-c here.
  1037       load_const(R11, (address)fd, R0);
  1039       bool has_env = (fd != NULL && fd->env() != NULL);
  1040       return branch_to(R11, /*and_link=*/true,
  1041                             /*save toc=*/false,
  1042                             /*restore toc=*/false,
  1043                             /*load toc=*/true,
  1044                             /*load env=*/has_env);
  1045     } else {
  1046       // It's a friend function. Load the entry point and don't care about
  1047       // toc and env. Use an optimizable call instruction, but ensure the
  1048       // same code-size as in the case of a non-friend function.
  1049       nop();
  1050       nop();
  1051       nop();
  1052       bl64_patchable(fd->entry(), rt);
  1053       _last_calls_return_pc = pc();
  1054       return _last_calls_return_pc;
  1056   } else {
  1057     // This call does not need to be relocatable, do more aggressive
  1058     // optimizations.
  1059     if (!ReoptimizeCallSequences
  1060       || !fd->is_friend_function()) {
  1061       // It's not a friend function as defined by class FunctionDescriptor,
  1062       // so do a full call-c here.
  1063       load_const(R11, (address)fd, R0);
  1064       return branch_to(R11, /*and_link=*/true,
  1065                             /*save toc=*/false,
  1066                             /*restore toc=*/false,
  1067                             /*load toc=*/true,
  1068                             /*load env=*/true);
  1069     } else {
  1070       // it's a friend function, load the entry point and don't care about
  1071       // toc and env.
  1072       address dest = fd->entry();
  1073       if (is_within_range_of_b(dest, pc())) {
  1074         bl(dest);
  1075       } else {
  1076         bl64_patchable(dest, rt);
  1078       _last_calls_return_pc = pc();
  1079       return _last_calls_return_pc;
  1084 // Call a C function.  All constants needed reside in TOC.
  1085 //
  1086 // Read the address to call from the TOC.
  1087 // Read env from TOC, if fd specifies an env.
  1088 // Read new TOC from TOC.
  1089 address MacroAssembler::call_c_using_toc(const FunctionDescriptor* fd,
  1090                                          relocInfo::relocType rt, Register toc) {
  1091   if (!ReoptimizeCallSequences
  1092     || (rt != relocInfo::runtime_call_type && rt != relocInfo::none)
  1093     || !fd->is_friend_function()) {
  1094     // It's not a friend function as defined by class FunctionDescriptor,
  1095     // so do a full call-c here.
  1096     assert(fd->entry() != NULL, "function must be linked");
  1098     AddressLiteral fd_entry(fd->entry());
  1099     load_const_from_method_toc(R11, fd_entry, toc);
  1100     mtctr(R11);
  1101     if (fd->env() == NULL) {
  1102       li(R11, 0);
  1103       nop();
  1104     } else {
  1105       AddressLiteral fd_env(fd->env());
  1106       load_const_from_method_toc(R11, fd_env, toc);
  1108     AddressLiteral fd_toc(fd->toc());
  1109     load_toc_from_toc(R2_TOC, fd_toc, toc);
  1110     // R2_TOC is killed.
  1111     bctrl();
  1112     _last_calls_return_pc = pc();
  1113   } else {
  1114     // It's a friend function, load the entry point and don't care about
  1115     // toc and env. Use an optimizable call instruction, but ensure the
  1116     // same code-size as in the case of a non-friend function.
  1117     nop();
  1118     bl64_patchable(fd->entry(), rt);
  1119     _last_calls_return_pc = pc();
  1121   return _last_calls_return_pc;
  1123 #endif
  1125 void MacroAssembler::call_VM_base(Register oop_result,
  1126                                   Register last_java_sp,
  1127                                   address  entry_point,
  1128                                   bool     check_exceptions) {
  1129   BLOCK_COMMENT("call_VM {");
  1130   // Determine last_java_sp register.
  1131   if (!last_java_sp->is_valid()) {
  1132     last_java_sp = R1_SP;
  1134   set_top_ijava_frame_at_SP_as_last_Java_frame(last_java_sp, R11_scratch1);
  1136   // ARG1 must hold thread address.
  1137   mr(R3_ARG1, R16_thread);
  1138 #if defined(ABI_ELFv2)
  1139   address return_pc = call_c(entry_point, relocInfo::none);
  1140 #else
  1141   address return_pc = call_c((FunctionDescriptor*)entry_point, relocInfo::none);
  1142 #endif
  1144   reset_last_Java_frame();
  1146   // Check for pending exceptions.
  1147   if (check_exceptions) {
  1148     // We don't check for exceptions here.
  1149     ShouldNotReachHere();
  1152   // Get oop result if there is one and reset the value in the thread.
  1153   if (oop_result->is_valid()) {
  1154     get_vm_result(oop_result);
  1157   _last_calls_return_pc = return_pc;
  1158   BLOCK_COMMENT("} call_VM");
  1161 void MacroAssembler::call_VM_leaf_base(address entry_point) {
  1162   BLOCK_COMMENT("call_VM_leaf {");
  1163 #if defined(ABI_ELFv2)
  1164   call_c(entry_point, relocInfo::none);
  1165 #else
  1166   call_c(CAST_FROM_FN_PTR(FunctionDescriptor*, entry_point), relocInfo::none);
  1167 #endif
  1168   BLOCK_COMMENT("} call_VM_leaf");
  1171 void MacroAssembler::call_VM(Register oop_result, address entry_point, bool check_exceptions) {
  1172   call_VM_base(oop_result, noreg, entry_point, check_exceptions);
  1175 void MacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1,
  1176                              bool check_exceptions) {
  1177   // R3_ARG1 is reserved for the thread.
  1178   mr_if_needed(R4_ARG2, arg_1);
  1179   call_VM(oop_result, entry_point, check_exceptions);
  1182 void MacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1, Register arg_2,
  1183                              bool check_exceptions) {
  1184   // R3_ARG1 is reserved for the thread
  1185   mr_if_needed(R4_ARG2, arg_1);
  1186   assert(arg_2 != R4_ARG2, "smashed argument");
  1187   mr_if_needed(R5_ARG3, arg_2);
  1188   call_VM(oop_result, entry_point, check_exceptions);
  1191 void MacroAssembler::call_VM_leaf(address entry_point) {
  1192   call_VM_leaf_base(entry_point);
  1195 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_1) {
  1196   mr_if_needed(R3_ARG1, arg_1);
  1197   call_VM_leaf(entry_point);
  1200 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_1, Register arg_2) {
  1201   mr_if_needed(R3_ARG1, arg_1);
  1202   assert(arg_2 != R3_ARG1, "smashed argument");
  1203   mr_if_needed(R4_ARG2, arg_2);
  1204   call_VM_leaf(entry_point);
  1207 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_1, Register arg_2, Register arg_3) {
  1208   mr_if_needed(R3_ARG1, arg_1);
  1209   assert(arg_2 != R3_ARG1, "smashed argument");
  1210   mr_if_needed(R4_ARG2, arg_2);
  1211   assert(arg_3 != R3_ARG1 && arg_3 != R4_ARG2, "smashed argument");
  1212   mr_if_needed(R5_ARG3, arg_3);
  1213   call_VM_leaf(entry_point);
  1216 // Check whether instruction is a read access to the polling page
  1217 // which was emitted by load_from_polling_page(..).
  1218 bool MacroAssembler::is_load_from_polling_page(int instruction, void* ucontext,
  1219                                                address* polling_address_ptr) {
  1220   if (!is_ld(instruction))
  1221     return false; // It's not a ld. Fail.
  1223   int rt = inv_rt_field(instruction);
  1224   int ra = inv_ra_field(instruction);
  1225   int ds = inv_ds_field(instruction);
  1226   if (!(ds == 0 && ra != 0 && rt == 0)) {
  1227     return false; // It's not a ld(r0, X, ra). Fail.
  1230   if (!ucontext) {
  1231     // Set polling address.
  1232     if (polling_address_ptr != NULL) {
  1233       *polling_address_ptr = NULL;
  1235     return true; // No ucontext given. Can't check value of ra. Assume true.
  1238 #ifdef LINUX
  1239   // Ucontext given. Check that register ra contains the address of
  1240   // the safepoing polling page.
  1241   ucontext_t* uc = (ucontext_t*) ucontext;
  1242   // Set polling address.
  1243   address addr = (address)uc->uc_mcontext.regs->gpr[ra] + (ssize_t)ds;
  1244   if (polling_address_ptr != NULL) {
  1245     *polling_address_ptr = addr;
  1247   return os::is_poll_address(addr);
  1248 #else
  1249   // Not on Linux, ucontext must be NULL.
  1250   ShouldNotReachHere();
  1251   return false;
  1252 #endif
  1255 bool MacroAssembler::is_memory_serialization(int instruction, JavaThread* thread, void* ucontext) {
  1256 #ifdef LINUX
  1257   ucontext_t* uc = (ucontext_t*) ucontext;
  1259   if (is_stwx(instruction) || is_stwux(instruction)) {
  1260     int ra = inv_ra_field(instruction);
  1261     int rb = inv_rb_field(instruction);
  1263     // look up content of ra and rb in ucontext
  1264     address ra_val=(address)uc->uc_mcontext.regs->gpr[ra];
  1265     long rb_val=(long)uc->uc_mcontext.regs->gpr[rb];
  1266     return os::is_memory_serialize_page(thread, ra_val+rb_val);
  1267   } else if (is_stw(instruction) || is_stwu(instruction)) {
  1268     int ra = inv_ra_field(instruction);
  1269     int d1 = inv_d1_field(instruction);
  1271     // look up content of ra in ucontext
  1272     address ra_val=(address)uc->uc_mcontext.regs->gpr[ra];
  1273     return os::is_memory_serialize_page(thread, ra_val+d1);
  1274   } else {
  1275     return false;
  1277 #else
  1278   // workaround not needed on !LINUX :-)
  1279   ShouldNotCallThis();
  1280   return false;
  1281 #endif
  1284 void MacroAssembler::bang_stack_with_offset(int offset) {
  1285   // When increasing the stack, the old stack pointer will be written
  1286   // to the new top of stack according to the PPC64 abi.
  1287   // Therefore, stack banging is not necessary when increasing
  1288   // the stack by <= os::vm_page_size() bytes.
  1289   // When increasing the stack by a larger amount, this method is
  1290   // called repeatedly to bang the intermediate pages.
  1292   // Stack grows down, caller passes positive offset.
  1293   assert(offset > 0, "must bang with positive offset");
  1295   long stdoffset = -offset;
  1297   if (is_simm(stdoffset, 16)) {
  1298     // Signed 16 bit offset, a simple std is ok.
  1299     if (UseLoadInstructionsForStackBangingPPC64) {
  1300       ld(R0, (int)(signed short)stdoffset, R1_SP);
  1301     } else {
  1302       std(R0,(int)(signed short)stdoffset, R1_SP);
  1304   } else if (is_simm(stdoffset, 31)) {
  1305     const int hi = MacroAssembler::largeoffset_si16_si16_hi(stdoffset);
  1306     const int lo = MacroAssembler::largeoffset_si16_si16_lo(stdoffset);
  1308     Register tmp = R11;
  1309     addis(tmp, R1_SP, hi);
  1310     if (UseLoadInstructionsForStackBangingPPC64) {
  1311       ld(R0,  lo, tmp);
  1312     } else {
  1313       std(R0, lo, tmp);
  1315   } else {
  1316     ShouldNotReachHere();
  1320 // If instruction is a stack bang of the form
  1321 //    std    R0,    x(Ry),       (see bang_stack_with_offset())
  1322 //    stdu   R1_SP, x(R1_SP),    (see push_frame(), resize_frame())
  1323 // or stdux  R1_SP, Rx, R1_SP    (see push_frame(), resize_frame())
  1324 // return the banged address. Otherwise, return 0.
  1325 address MacroAssembler::get_stack_bang_address(int instruction, void *ucontext) {
  1326 #ifdef LINUX
  1327   ucontext_t* uc = (ucontext_t*) ucontext;
  1328   int rs = inv_rs_field(instruction);
  1329   int ra = inv_ra_field(instruction);
  1330   if (   (is_ld(instruction)   && rs == 0 &&  UseLoadInstructionsForStackBangingPPC64)
  1331       || (is_std(instruction)  && rs == 0 && !UseLoadInstructionsForStackBangingPPC64)
  1332       || (is_stdu(instruction) && rs == 1)) {
  1333     int ds = inv_ds_field(instruction);
  1334     // return banged address
  1335     return ds+(address)uc->uc_mcontext.regs->gpr[ra];
  1336   } else if (is_stdux(instruction) && rs == 1) {
  1337     int rb = inv_rb_field(instruction);
  1338     address sp = (address)uc->uc_mcontext.regs->gpr[1];
  1339     long rb_val = (long)uc->uc_mcontext.regs->gpr[rb];
  1340     return ra != 1 || rb_val >= 0 ? NULL         // not a stack bang
  1341                                   : sp + rb_val; // banged address
  1343   return NULL; // not a stack bang
  1344 #else
  1345   // workaround not needed on !LINUX :-)
  1346   ShouldNotCallThis();
  1347   return NULL;
  1348 #endif
  1351 // CmpxchgX sets condition register to cmpX(current, compare).
  1352 void MacroAssembler::cmpxchgw(ConditionRegister flag, Register dest_current_value,
  1353                               Register compare_value, Register exchange_value,
  1354                               Register addr_base, int semantics, bool cmpxchgx_hint,
  1355                               Register int_flag_success, bool contention_hint) {
  1356   Label retry;
  1357   Label failed;
  1358   Label done;
  1360   // Save one branch if result is returned via register and
  1361   // result register is different from the other ones.
  1362   bool use_result_reg    = (int_flag_success != noreg);
  1363   bool preset_result_reg = (int_flag_success != dest_current_value && int_flag_success != compare_value &&
  1364                             int_flag_success != exchange_value && int_flag_success != addr_base);
  1366   // release/fence semantics
  1367   if (semantics & MemBarRel) {
  1368     release();
  1371   if (use_result_reg && preset_result_reg) {
  1372     li(int_flag_success, 0); // preset (assume cas failed)
  1375   // Add simple guard in order to reduce risk of starving under high contention (recommended by IBM).
  1376   if (contention_hint) { // Don't try to reserve if cmp fails.
  1377     lwz(dest_current_value, 0, addr_base);
  1378     cmpw(flag, dest_current_value, compare_value);
  1379     bne(flag, failed);
  1382   // atomic emulation loop
  1383   bind(retry);
  1385   lwarx(dest_current_value, addr_base, cmpxchgx_hint);
  1386   cmpw(flag, dest_current_value, compare_value);
  1387   if (UseStaticBranchPredictionInCompareAndSwapPPC64) {
  1388     bne_predict_not_taken(flag, failed);
  1389   } else {
  1390     bne(                  flag, failed);
  1392   // branch to done  => (flag == ne), (dest_current_value != compare_value)
  1393   // fall through    => (flag == eq), (dest_current_value == compare_value)
  1395   stwcx_(exchange_value, addr_base);
  1396   if (UseStaticBranchPredictionInCompareAndSwapPPC64) {
  1397     bne_predict_not_taken(CCR0, retry); // StXcx_ sets CCR0.
  1398   } else {
  1399     bne(                  CCR0, retry); // StXcx_ sets CCR0.
  1401   // fall through    => (flag == eq), (dest_current_value == compare_value), (swapped)
  1403   // Result in register (must do this at the end because int_flag_success can be the
  1404   // same register as one above).
  1405   if (use_result_reg) {
  1406     li(int_flag_success, 1);
  1409   if (semantics & MemBarFenceAfter) {
  1410     fence();
  1411   } else if (semantics & MemBarAcq) {
  1412     isync();
  1415   if (use_result_reg && !preset_result_reg) {
  1416     b(done);
  1419   bind(failed);
  1420   if (use_result_reg && !preset_result_reg) {
  1421     li(int_flag_success, 0);
  1424   bind(done);
  1425   // (flag == ne) => (dest_current_value != compare_value), (!swapped)
  1426   // (flag == eq) => (dest_current_value == compare_value), ( swapped)
  1429 // Preforms atomic compare exchange:
  1430 //   if (compare_value == *addr_base)
  1431 //     *addr_base = exchange_value
  1432 //     int_flag_success = 1;
  1433 //   else
  1434 //     int_flag_success = 0;
  1435 //
  1436 // ConditionRegister flag       = cmp(compare_value, *addr_base)
  1437 // Register dest_current_value  = *addr_base
  1438 // Register compare_value       Used to compare with value in memory
  1439 // Register exchange_value      Written to memory if compare_value == *addr_base
  1440 // Register addr_base           The memory location to compareXChange
  1441 // Register int_flag_success    Set to 1 if exchange_value was written to *addr_base
  1442 //
  1443 // To avoid the costly compare exchange the value is tested beforehand.
  1444 // Several special cases exist to avoid that unnecessary information is generated.
  1445 //
  1446 void MacroAssembler::cmpxchgd(ConditionRegister flag,
  1447                               Register dest_current_value, Register compare_value, Register exchange_value,
  1448                               Register addr_base, int semantics, bool cmpxchgx_hint,
  1449                               Register int_flag_success, Label* failed_ext, bool contention_hint) {
  1450   Label retry;
  1451   Label failed_int;
  1452   Label& failed = (failed_ext != NULL) ? *failed_ext : failed_int;
  1453   Label done;
  1455   // Save one branch if result is returned via register and result register is different from the other ones.
  1456   bool use_result_reg    = (int_flag_success!=noreg);
  1457   bool preset_result_reg = (int_flag_success!=dest_current_value && int_flag_success!=compare_value &&
  1458                             int_flag_success!=exchange_value && int_flag_success!=addr_base);
  1459   assert(int_flag_success == noreg || failed_ext == NULL, "cannot have both");
  1461   // release/fence semantics
  1462   if (semantics & MemBarRel) {
  1463     release();
  1466   if (use_result_reg && preset_result_reg) {
  1467     li(int_flag_success, 0); // preset (assume cas failed)
  1470   // Add simple guard in order to reduce risk of starving under high contention (recommended by IBM).
  1471   if (contention_hint) { // Don't try to reserve if cmp fails.
  1472     ld(dest_current_value, 0, addr_base);
  1473     cmpd(flag, dest_current_value, compare_value);
  1474     bne(flag, failed);
  1477   // atomic emulation loop
  1478   bind(retry);
  1480   ldarx(dest_current_value, addr_base, cmpxchgx_hint);
  1481   cmpd(flag, dest_current_value, compare_value);
  1482   if (UseStaticBranchPredictionInCompareAndSwapPPC64) {
  1483     bne_predict_not_taken(flag, failed);
  1484   } else {
  1485     bne(                  flag, failed);
  1488   stdcx_(exchange_value, addr_base);
  1489   if (UseStaticBranchPredictionInCompareAndSwapPPC64) {
  1490     bne_predict_not_taken(CCR0, retry); // stXcx_ sets CCR0
  1491   } else {
  1492     bne(                  CCR0, retry); // stXcx_ sets CCR0
  1495   // result in register (must do this at the end because int_flag_success can be the same register as one above)
  1496   if (use_result_reg) {
  1497     li(int_flag_success, 1);
  1500   // POWER6 doesn't need isync in CAS.
  1501   // Always emit isync to be on the safe side.
  1502   if (semantics & MemBarFenceAfter) {
  1503     fence();
  1504   } else if (semantics & MemBarAcq) {
  1505     isync();
  1508   if (use_result_reg && !preset_result_reg) {
  1509     b(done);
  1512   bind(failed_int);
  1513   if (use_result_reg && !preset_result_reg) {
  1514     li(int_flag_success, 0);
  1517   bind(done);
  1518   // (flag == ne) => (dest_current_value != compare_value), (!swapped)
  1519   // (flag == eq) => (dest_current_value == compare_value), ( swapped)
  1522 // Look up the method for a megamorphic invokeinterface call.
  1523 // The target method is determined by <intf_klass, itable_index>.
  1524 // The receiver klass is in recv_klass.
  1525 // On success, the result will be in method_result, and execution falls through.
  1526 // On failure, execution transfers to the given label.
  1527 void MacroAssembler::lookup_interface_method(Register recv_klass,
  1528                                              Register intf_klass,
  1529                                              RegisterOrConstant itable_index,
  1530                                              Register method_result,
  1531                                              Register scan_temp,
  1532                                              Register sethi_temp,
  1533                                              Label& L_no_such_interface) {
  1534   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
  1535   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
  1536          "caller must use same register for non-constant itable index as for method");
  1538   // Compute start of first itableOffsetEntry (which is at the end of the vtable).
  1539   int vtable_base = InstanceKlass::vtable_start_offset() * wordSize;
  1540   int itentry_off = itableMethodEntry::method_offset_in_bytes();
  1541   int logMEsize   = exact_log2(itableMethodEntry::size() * wordSize);
  1542   int scan_step   = itableOffsetEntry::size() * wordSize;
  1543   int log_vte_size= exact_log2(vtableEntry::size() * wordSize);
  1545   lwz(scan_temp, InstanceKlass::vtable_length_offset() * wordSize, recv_klass);
  1546   // %%% We should store the aligned, prescaled offset in the klassoop.
  1547   // Then the next several instructions would fold away.
  1549   sldi(scan_temp, scan_temp, log_vte_size);
  1550   addi(scan_temp, scan_temp, vtable_base);
  1551   add(scan_temp, recv_klass, scan_temp);
  1553   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
  1554   if (itable_index.is_register()) {
  1555     Register itable_offset = itable_index.as_register();
  1556     sldi(itable_offset, itable_offset, logMEsize);
  1557     if (itentry_off) addi(itable_offset, itable_offset, itentry_off);
  1558     add(recv_klass, itable_offset, recv_klass);
  1559   } else {
  1560     long itable_offset = (long)itable_index.as_constant();
  1561     load_const_optimized(sethi_temp, (itable_offset<<logMEsize)+itentry_off); // static address, no relocation
  1562     add(recv_klass, sethi_temp, recv_klass);
  1565   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
  1566   //   if (scan->interface() == intf) {
  1567   //     result = (klass + scan->offset() + itable_index);
  1568   //   }
  1569   // }
  1570   Label search, found_method;
  1572   for (int peel = 1; peel >= 0; peel--) {
  1573     // %%%% Could load both offset and interface in one ldx, if they were
  1574     // in the opposite order. This would save a load.
  1575     ld(method_result, itableOffsetEntry::interface_offset_in_bytes(), scan_temp);
  1577     // Check that this entry is non-null. A null entry means that
  1578     // the receiver class doesn't implement the interface, and wasn't the
  1579     // same as when the caller was compiled.
  1580     cmpd(CCR0, method_result, intf_klass);
  1582     if (peel) {
  1583       beq(CCR0, found_method);
  1584     } else {
  1585       bne(CCR0, search);
  1586       // (invert the test to fall through to found_method...)
  1589     if (!peel) break;
  1591     bind(search);
  1593     cmpdi(CCR0, method_result, 0);
  1594     beq(CCR0, L_no_such_interface);
  1595     addi(scan_temp, scan_temp, scan_step);
  1598   bind(found_method);
  1600   // Got a hit.
  1601   int ito_offset = itableOffsetEntry::offset_offset_in_bytes();
  1602   lwz(scan_temp, ito_offset, scan_temp);
  1603   ldx(method_result, scan_temp, recv_klass);
  1606 // virtual method calling
  1607 void MacroAssembler::lookup_virtual_method(Register recv_klass,
  1608                                            RegisterOrConstant vtable_index,
  1609                                            Register method_result) {
  1611   assert_different_registers(recv_klass, method_result, vtable_index.register_or_noreg());
  1613   const int base = InstanceKlass::vtable_start_offset() * wordSize;
  1614   assert(vtableEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
  1616   if (vtable_index.is_register()) {
  1617     sldi(vtable_index.as_register(), vtable_index.as_register(), LogBytesPerWord);
  1618     add(recv_klass, vtable_index.as_register(), recv_klass);
  1619   } else {
  1620     addi(recv_klass, recv_klass, vtable_index.as_constant() << LogBytesPerWord);
  1622   ld(R19_method, base + vtableEntry::method_offset_in_bytes(), recv_klass);
  1625 /////////////////////////////////////////// subtype checking ////////////////////////////////////////////
  1627 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
  1628                                                    Register super_klass,
  1629                                                    Register temp1_reg,
  1630                                                    Register temp2_reg,
  1631                                                    Label& L_success,
  1632                                                    Label& L_failure) {
  1634   const Register check_cache_offset = temp1_reg;
  1635   const Register cached_super       = temp2_reg;
  1637   assert_different_registers(sub_klass, super_klass, check_cache_offset, cached_super);
  1639   int sco_offset = in_bytes(Klass::super_check_offset_offset());
  1640   int sc_offset  = in_bytes(Klass::secondary_super_cache_offset());
  1642   // If the pointers are equal, we are done (e.g., String[] elements).
  1643   // This self-check enables sharing of secondary supertype arrays among
  1644   // non-primary types such as array-of-interface. Otherwise, each such
  1645   // type would need its own customized SSA.
  1646   // We move this check to the front of the fast path because many
  1647   // type checks are in fact trivially successful in this manner,
  1648   // so we get a nicely predicted branch right at the start of the check.
  1649   cmpd(CCR0, sub_klass, super_klass);
  1650   beq(CCR0, L_success);
  1652   // Check the supertype display:
  1653   lwz(check_cache_offset, sco_offset, super_klass);
  1654   // The loaded value is the offset from KlassOopDesc.
  1656   ldx(cached_super, check_cache_offset, sub_klass);
  1657   cmpd(CCR0, cached_super, super_klass);
  1658   beq(CCR0, L_success);
  1660   // This check has worked decisively for primary supers.
  1661   // Secondary supers are sought in the super_cache ('super_cache_addr').
  1662   // (Secondary supers are interfaces and very deeply nested subtypes.)
  1663   // This works in the same check above because of a tricky aliasing
  1664   // between the super_cache and the primary super display elements.
  1665   // (The 'super_check_addr' can address either, as the case requires.)
  1666   // Note that the cache is updated below if it does not help us find
  1667   // what we need immediately.
  1668   // So if it was a primary super, we can just fail immediately.
  1669   // Otherwise, it's the slow path for us (no success at this point).
  1671   cmpwi(CCR0, check_cache_offset, sc_offset);
  1672   bne(CCR0, L_failure);
  1673   // bind(slow_path); // fallthru
  1676 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
  1677                                                    Register super_klass,
  1678                                                    Register temp1_reg,
  1679                                                    Register temp2_reg,
  1680                                                    Label* L_success,
  1681                                                    Register result_reg) {
  1682   const Register array_ptr = temp1_reg; // current value from cache array
  1683   const Register temp      = temp2_reg;
  1685   assert_different_registers(sub_klass, super_klass, array_ptr, temp);
  1687   int source_offset = in_bytes(Klass::secondary_supers_offset());
  1688   int target_offset = in_bytes(Klass::secondary_super_cache_offset());
  1690   int length_offset = Array<Klass*>::length_offset_in_bytes();
  1691   int base_offset   = Array<Klass*>::base_offset_in_bytes();
  1693   Label hit, loop, failure, fallthru;
  1695   ld(array_ptr, source_offset, sub_klass);
  1697   //assert(4 == arrayOopDesc::length_length_in_bytes(), "precondition violated.");
  1698   lwz(temp, length_offset, array_ptr);
  1699   cmpwi(CCR0, temp, 0);
  1700   beq(CCR0, result_reg!=noreg ? failure : fallthru); // length 0
  1702   mtctr(temp); // load ctr
  1704   bind(loop);
  1705   // Oops in table are NO MORE compressed.
  1706   ld(temp, base_offset, array_ptr);
  1707   cmpd(CCR0, temp, super_klass);
  1708   beq(CCR0, hit);
  1709   addi(array_ptr, array_ptr, BytesPerWord);
  1710   bdnz(loop);
  1712   bind(failure);
  1713   if (result_reg!=noreg) li(result_reg, 1); // load non-zero result (indicates a miss)
  1714   b(fallthru);
  1716   bind(hit);
  1717   std(super_klass, target_offset, sub_klass); // save result to cache
  1718   if (result_reg != noreg) li(result_reg, 0); // load zero result (indicates a hit)
  1719   if (L_success != NULL) b(*L_success);
  1721   bind(fallthru);
  1724 // Try fast path, then go to slow one if not successful
  1725 void MacroAssembler::check_klass_subtype(Register sub_klass,
  1726                          Register super_klass,
  1727                          Register temp1_reg,
  1728                          Register temp2_reg,
  1729                          Label& L_success) {
  1730   Label L_failure;
  1731   check_klass_subtype_fast_path(sub_klass, super_klass, temp1_reg, temp2_reg, L_success, L_failure);
  1732   check_klass_subtype_slow_path(sub_klass, super_klass, temp1_reg, temp2_reg, &L_success);
  1733   bind(L_failure); // Fallthru if not successful.
  1736 void MacroAssembler::check_method_handle_type(Register mtype_reg, Register mh_reg,
  1737                                               Register temp_reg,
  1738                                               Label& wrong_method_type) {
  1739   assert_different_registers(mtype_reg, mh_reg, temp_reg);
  1740   // Compare method type against that of the receiver.
  1741   load_heap_oop_not_null(temp_reg, delayed_value(java_lang_invoke_MethodHandle::type_offset_in_bytes, temp_reg), mh_reg);
  1742   cmpd(CCR0, temp_reg, mtype_reg);
  1743   bne(CCR0, wrong_method_type);
  1746 RegisterOrConstant MacroAssembler::argument_offset(RegisterOrConstant arg_slot,
  1747                                                    Register temp_reg,
  1748                                                    int extra_slot_offset) {
  1749   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
  1750   int stackElementSize = Interpreter::stackElementSize;
  1751   int offset = extra_slot_offset * stackElementSize;
  1752   if (arg_slot.is_constant()) {
  1753     offset += arg_slot.as_constant() * stackElementSize;
  1754     return offset;
  1755   } else {
  1756     assert(temp_reg != noreg, "must specify");
  1757     sldi(temp_reg, arg_slot.as_register(), exact_log2(stackElementSize));
  1758     if (offset != 0)
  1759       addi(temp_reg, temp_reg, offset);
  1760     return temp_reg;
  1764 void MacroAssembler::biased_locking_enter(ConditionRegister cr_reg, Register obj_reg,
  1765                                           Register mark_reg, Register temp_reg,
  1766                                           Register temp2_reg, Label& done, Label* slow_case) {
  1767   assert(UseBiasedLocking, "why call this otherwise?");
  1769 #ifdef ASSERT
  1770   assert_different_registers(obj_reg, mark_reg, temp_reg, temp2_reg);
  1771 #endif
  1773   Label cas_label;
  1775   // Branch to done if fast path fails and no slow_case provided.
  1776   Label *slow_case_int = (slow_case != NULL) ? slow_case : &done;
  1778   // Biased locking
  1779   // See whether the lock is currently biased toward our thread and
  1780   // whether the epoch is still valid
  1781   // Note that the runtime guarantees sufficient alignment of JavaThread
  1782   // pointers to allow age to be placed into low bits
  1783   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits,
  1784          "biased locking makes assumptions about bit layout");
  1786   if (PrintBiasedLockingStatistics) {
  1787     load_const(temp_reg, (address) BiasedLocking::total_entry_count_addr(), temp2_reg);
  1788     lwz(temp2_reg, 0, temp_reg);
  1789     addi(temp2_reg, temp2_reg, 1);
  1790     stw(temp2_reg, 0, temp_reg);
  1793   andi(temp_reg, mark_reg, markOopDesc::biased_lock_mask_in_place);
  1794   cmpwi(cr_reg, temp_reg, markOopDesc::biased_lock_pattern);
  1795   bne(cr_reg, cas_label);
  1797   load_klass_with_trap_null_check(temp_reg, obj_reg);
  1799   load_const_optimized(temp2_reg, ~((int) markOopDesc::age_mask_in_place));
  1800   ld(temp_reg, in_bytes(Klass::prototype_header_offset()), temp_reg);
  1801   orr(temp_reg, R16_thread, temp_reg);
  1802   xorr(temp_reg, mark_reg, temp_reg);
  1803   andr(temp_reg, temp_reg, temp2_reg);
  1804   cmpdi(cr_reg, temp_reg, 0);
  1805   if (PrintBiasedLockingStatistics) {
  1806     Label l;
  1807     bne(cr_reg, l);
  1808     load_const(mark_reg, (address) BiasedLocking::biased_lock_entry_count_addr());
  1809     lwz(temp2_reg, 0, mark_reg);
  1810     addi(temp2_reg, temp2_reg, 1);
  1811     stw(temp2_reg, 0, mark_reg);
  1812     // restore mark_reg
  1813     ld(mark_reg, oopDesc::mark_offset_in_bytes(), obj_reg);
  1814     bind(l);
  1816   beq(cr_reg, done);
  1818   Label try_revoke_bias;
  1819   Label try_rebias;
  1821   // At this point we know that the header has the bias pattern and
  1822   // that we are not the bias owner in the current epoch. We need to
  1823   // figure out more details about the state of the header in order to
  1824   // know what operations can be legally performed on the object's
  1825   // header.
  1827   // If the low three bits in the xor result aren't clear, that means
  1828   // the prototype header is no longer biased and we have to revoke
  1829   // the bias on this object.
  1830   andi(temp2_reg, temp_reg, markOopDesc::biased_lock_mask_in_place);
  1831   cmpwi(cr_reg, temp2_reg, 0);
  1832   bne(cr_reg, try_revoke_bias);
  1834   // Biasing is still enabled for this data type. See whether the
  1835   // epoch of the current bias is still valid, meaning that the epoch
  1836   // bits of the mark word are equal to the epoch bits of the
  1837   // prototype header. (Note that the prototype header's epoch bits
  1838   // only change at a safepoint.) If not, attempt to rebias the object
  1839   // toward the current thread. Note that we must be absolutely sure
  1840   // that the current epoch is invalid in order to do this because
  1841   // otherwise the manipulations it performs on the mark word are
  1842   // illegal.
  1844   int shift_amount = 64 - markOopDesc::epoch_shift;
  1845   // rotate epoch bits to right (little) end and set other bits to 0
  1846   // [ big part | epoch | little part ] -> [ 0..0 | epoch ]
  1847   rldicl_(temp2_reg, temp_reg, shift_amount, 64 - markOopDesc::epoch_bits);
  1848   // branch if epoch bits are != 0, i.e. they differ, because the epoch has been incremented
  1849   bne(CCR0, try_rebias);
  1851   // The epoch of the current bias is still valid but we know nothing
  1852   // about the owner; it might be set or it might be clear. Try to
  1853   // acquire the bias of the object using an atomic operation. If this
  1854   // fails we will go in to the runtime to revoke the object's bias.
  1855   // Note that we first construct the presumed unbiased header so we
  1856   // don't accidentally blow away another thread's valid bias.
  1857   andi(mark_reg, mark_reg, (markOopDesc::biased_lock_mask_in_place |
  1858                                 markOopDesc::age_mask_in_place |
  1859                                 markOopDesc::epoch_mask_in_place));
  1860   orr(temp_reg, R16_thread, mark_reg);
  1862   assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
  1864   // CmpxchgX sets cr_reg to cmpX(temp2_reg, mark_reg).
  1865   fence(); // TODO: replace by MacroAssembler::MemBarRel | MacroAssembler::MemBarAcq ?
  1866   cmpxchgd(/*flag=*/cr_reg, /*current_value=*/temp2_reg,
  1867            /*compare_value=*/mark_reg, /*exchange_value=*/temp_reg,
  1868            /*where=*/obj_reg,
  1869            MacroAssembler::MemBarAcq,
  1870            MacroAssembler::cmpxchgx_hint_acquire_lock(),
  1871            noreg, slow_case_int); // bail out if failed
  1873   // If the biasing toward our thread failed, this means that
  1874   // another thread succeeded in biasing it toward itself and we
  1875   // need to revoke that bias. The revocation will occur in the
  1876   // interpreter runtime in the slow case.
  1877   if (PrintBiasedLockingStatistics) {
  1878     load_const(temp_reg, (address) BiasedLocking::anonymously_biased_lock_entry_count_addr(), temp2_reg);
  1879     lwz(temp2_reg, 0, temp_reg);
  1880     addi(temp2_reg, temp2_reg, 1);
  1881     stw(temp2_reg, 0, temp_reg);
  1883   b(done);
  1885   bind(try_rebias);
  1886   // At this point we know the epoch has expired, meaning that the
  1887   // current "bias owner", if any, is actually invalid. Under these
  1888   // circumstances _only_, we are allowed to use the current header's
  1889   // value as the comparison value when doing the cas to acquire the
  1890   // bias in the current epoch. In other words, we allow transfer of
  1891   // the bias from one thread to another directly in this situation.
  1892   andi(temp_reg, mark_reg, markOopDesc::age_mask_in_place);
  1893   orr(temp_reg, R16_thread, temp_reg);
  1894   load_klass_with_trap_null_check(temp2_reg, obj_reg);
  1895   ld(temp2_reg, in_bytes(Klass::prototype_header_offset()), temp2_reg);
  1896   orr(temp_reg, temp_reg, temp2_reg);
  1898   assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
  1900   // CmpxchgX sets cr_reg to cmpX(temp2_reg, mark_reg).
  1901   fence(); // TODO: replace by MacroAssembler::MemBarRel | MacroAssembler::MemBarAcq ?
  1902   cmpxchgd(/*flag=*/cr_reg, /*current_value=*/temp2_reg,
  1903                  /*compare_value=*/mark_reg, /*exchange_value=*/temp_reg,
  1904                  /*where=*/obj_reg,
  1905                  MacroAssembler::MemBarAcq,
  1906                  MacroAssembler::cmpxchgx_hint_acquire_lock(),
  1907                  noreg, slow_case_int); // bail out if failed
  1909   // If the biasing toward our thread failed, this means that
  1910   // another thread succeeded in biasing it toward itself and we
  1911   // need to revoke that bias. The revocation will occur in the
  1912   // interpreter runtime in the slow case.
  1913   if (PrintBiasedLockingStatistics) {
  1914     load_const(temp_reg, (address) BiasedLocking::rebiased_lock_entry_count_addr(), temp2_reg);
  1915     lwz(temp2_reg, 0, temp_reg);
  1916     addi(temp2_reg, temp2_reg, 1);
  1917     stw(temp2_reg, 0, temp_reg);
  1919   b(done);
  1921   bind(try_revoke_bias);
  1922   // The prototype mark in the klass doesn't have the bias bit set any
  1923   // more, indicating that objects of this data type are not supposed
  1924   // to be biased any more. We are going to try to reset the mark of
  1925   // this object to the prototype value and fall through to the
  1926   // CAS-based locking scheme. Note that if our CAS fails, it means
  1927   // that another thread raced us for the privilege of revoking the
  1928   // bias of this particular object, so it's okay to continue in the
  1929   // normal locking code.
  1930   load_klass_with_trap_null_check(temp_reg, obj_reg);
  1931   ld(temp_reg, in_bytes(Klass::prototype_header_offset()), temp_reg);
  1932   andi(temp2_reg, mark_reg, markOopDesc::age_mask_in_place);
  1933   orr(temp_reg, temp_reg, temp2_reg);
  1935   assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
  1937   // CmpxchgX sets cr_reg to cmpX(temp2_reg, mark_reg).
  1938   fence(); // TODO: replace by MacroAssembler::MemBarRel | MacroAssembler::MemBarAcq ?
  1939   cmpxchgd(/*flag=*/cr_reg, /*current_value=*/temp2_reg,
  1940                  /*compare_value=*/mark_reg, /*exchange_value=*/temp_reg,
  1941                  /*where=*/obj_reg,
  1942                  MacroAssembler::MemBarAcq,
  1943                  MacroAssembler::cmpxchgx_hint_acquire_lock());
  1945   // reload markOop in mark_reg before continuing with lightweight locking
  1946   ld(mark_reg, oopDesc::mark_offset_in_bytes(), obj_reg);
  1948   // Fall through to the normal CAS-based lock, because no matter what
  1949   // the result of the above CAS, some thread must have succeeded in
  1950   // removing the bias bit from the object's header.
  1951   if (PrintBiasedLockingStatistics) {
  1952     Label l;
  1953     bne(cr_reg, l);
  1954     load_const(temp_reg, (address) BiasedLocking::revoked_lock_entry_count_addr(), temp2_reg);
  1955     lwz(temp2_reg, 0, temp_reg);
  1956     addi(temp2_reg, temp2_reg, 1);
  1957     stw(temp2_reg, 0, temp_reg);
  1958     bind(l);
  1961   bind(cas_label);
  1964 void MacroAssembler::biased_locking_exit (ConditionRegister cr_reg, Register mark_addr, Register temp_reg, Label& done) {
  1965   // Check for biased locking unlock case, which is a no-op
  1966   // Note: we do not have to check the thread ID for two reasons.
  1967   // First, the interpreter checks for IllegalMonitorStateException at
  1968   // a higher level. Second, if the bias was revoked while we held the
  1969   // lock, the object could not be rebiased toward another thread, so
  1970   // the bias bit would be clear.
  1972   ld(temp_reg, 0, mark_addr);
  1973   andi(temp_reg, temp_reg, markOopDesc::biased_lock_mask_in_place);
  1975   cmpwi(cr_reg, temp_reg, markOopDesc::biased_lock_pattern);
  1976   beq(cr_reg, done);
  1979 // "The box" is the space on the stack where we copy the object mark.
  1980 void MacroAssembler::compiler_fast_lock_object(ConditionRegister flag, Register oop, Register box,
  1981                                                Register temp, Register displaced_header, Register current_header) {
  1982   assert_different_registers(oop, box, temp, displaced_header, current_header);
  1983   assert(flag != CCR0, "bad condition register");
  1984   Label cont;
  1985   Label object_has_monitor;
  1986   Label cas_failed;
  1988   // Load markOop from object into displaced_header.
  1989   ld(displaced_header, oopDesc::mark_offset_in_bytes(), oop);
  1992   // Always do locking in runtime.
  1993   if (EmitSync & 0x01) {
  1994     cmpdi(flag, oop, 0); // Oop can't be 0 here => always false.
  1995     return;
  1998   if (UseBiasedLocking) {
  1999     biased_locking_enter(flag, oop, displaced_header, temp, current_header, cont);
  2002   // Handle existing monitor.
  2003   if ((EmitSync & 0x02) == 0) {
  2004     // The object has an existing monitor iff (mark & monitor_value) != 0.
  2005     andi_(temp, displaced_header, markOopDesc::monitor_value);
  2006     bne(CCR0, object_has_monitor);
  2009   // Set displaced_header to be (markOop of object | UNLOCK_VALUE).
  2010   ori(displaced_header, displaced_header, markOopDesc::unlocked_value);
  2012   // Load Compare Value application register.
  2014   // Initialize the box. (Must happen before we update the object mark!)
  2015   std(displaced_header, BasicLock::displaced_header_offset_in_bytes(), box);
  2017   // Must fence, otherwise, preceding store(s) may float below cmpxchg.
  2018   // Compare object markOop with mark and if equal exchange scratch1 with object markOop.
  2019   // CmpxchgX sets cr_reg to cmpX(current, displaced).
  2020   membar(Assembler::StoreStore);
  2021   cmpxchgd(/*flag=*/flag,
  2022            /*current_value=*/current_header,
  2023            /*compare_value=*/displaced_header,
  2024            /*exchange_value=*/box,
  2025            /*where=*/oop,
  2026            MacroAssembler::MemBarAcq,
  2027            MacroAssembler::cmpxchgx_hint_acquire_lock(),
  2028            noreg,
  2029            &cas_failed);
  2030   assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
  2032   // If the compare-and-exchange succeeded, then we found an unlocked
  2033   // object and we have now locked it.
  2034   b(cont);
  2036   bind(cas_failed);
  2037   // We did not see an unlocked object so try the fast recursive case.
  2039   // Check if the owner is self by comparing the value in the markOop of object
  2040   // (current_header) with the stack pointer.
  2041   sub(current_header, current_header, R1_SP);
  2042   load_const_optimized(temp, (address) (~(os::vm_page_size()-1) |
  2043                                         markOopDesc::lock_mask_in_place));
  2045   and_(R0/*==0?*/, current_header, temp);
  2046   // If condition is true we are cont and hence we can store 0 as the
  2047   // displaced header in the box, which indicates that it is a recursive lock.
  2048   mcrf(flag,CCR0);
  2049   std(R0/*==0, perhaps*/, BasicLock::displaced_header_offset_in_bytes(), box);
  2051   // Handle existing monitor.
  2052   if ((EmitSync & 0x02) == 0) {
  2053     b(cont);
  2055     bind(object_has_monitor);
  2056     // The object's monitor m is unlocked iff m->owner == NULL,
  2057     // otherwise m->owner may contain a thread or a stack address.
  2058     //
  2059     // Try to CAS m->owner from NULL to current thread.
  2060     addi(temp, displaced_header, ObjectMonitor::owner_offset_in_bytes()-markOopDesc::monitor_value);
  2061     li(displaced_header, 0);
  2062     // CmpxchgX sets flag to cmpX(current, displaced).
  2063     cmpxchgd(/*flag=*/flag,
  2064              /*current_value=*/current_header,
  2065              /*compare_value=*/displaced_header,
  2066              /*exchange_value=*/R16_thread,
  2067              /*where=*/temp,
  2068              MacroAssembler::MemBarRel | MacroAssembler::MemBarAcq,
  2069              MacroAssembler::cmpxchgx_hint_acquire_lock());
  2071     // Store a non-null value into the box.
  2072     std(box, BasicLock::displaced_header_offset_in_bytes(), box);
  2074 #   ifdef ASSERT
  2075     bne(flag, cont);
  2076     // We have acquired the monitor, check some invariants.
  2077     addi(/*monitor=*/temp, temp, -ObjectMonitor::owner_offset_in_bytes());
  2078     // Invariant 1: _recursions should be 0.
  2079     //assert(ObjectMonitor::recursions_size_in_bytes() == 8, "unexpected size");
  2080     asm_assert_mem8_is_zero(ObjectMonitor::recursions_offset_in_bytes(), temp,
  2081                             "monitor->_recursions should be 0", -1);
  2082     // Invariant 2: OwnerIsThread shouldn't be 0.
  2083     //assert(ObjectMonitor::OwnerIsThread_size_in_bytes() == 4, "unexpected size");
  2084     //asm_assert_mem4_isnot_zero(ObjectMonitor::OwnerIsThread_offset_in_bytes(), temp,
  2085     //                           "monitor->OwnerIsThread shouldn't be 0", -1);
  2086 #   endif
  2089   bind(cont);
  2090   // flag == EQ indicates success
  2091   // flag == NE indicates failure
  2094 void MacroAssembler::compiler_fast_unlock_object(ConditionRegister flag, Register oop, Register box,
  2095                                                  Register temp, Register displaced_header, Register current_header) {
  2096   assert_different_registers(oop, box, temp, displaced_header, current_header);
  2097   assert(flag != CCR0, "bad condition register");
  2098   Label cont;
  2099   Label object_has_monitor;
  2101   // Always do locking in runtime.
  2102   if (EmitSync & 0x01) {
  2103     cmpdi(flag, oop, 0); // Oop can't be 0 here => always false.
  2104     return;
  2107   if (UseBiasedLocking) {
  2108     biased_locking_exit(flag, oop, current_header, cont);
  2111   // Find the lock address and load the displaced header from the stack.
  2112   ld(displaced_header, BasicLock::displaced_header_offset_in_bytes(), box);
  2114   // If the displaced header is 0, we have a recursive unlock.
  2115   cmpdi(flag, displaced_header, 0);
  2116   beq(flag, cont);
  2118   // Handle existing monitor.
  2119   if ((EmitSync & 0x02) == 0) {
  2120     // The object has an existing monitor iff (mark & monitor_value) != 0.
  2121     ld(current_header, oopDesc::mark_offset_in_bytes(), oop);
  2122     andi(temp, current_header, markOopDesc::monitor_value);
  2123     cmpdi(flag, temp, 0);
  2124     bne(flag, object_has_monitor);
  2128   // Check if it is still a light weight lock, this is is true if we see
  2129   // the stack address of the basicLock in the markOop of the object.
  2130   // Cmpxchg sets flag to cmpd(current_header, box).
  2131   cmpxchgd(/*flag=*/flag,
  2132            /*current_value=*/current_header,
  2133            /*compare_value=*/box,
  2134            /*exchange_value=*/displaced_header,
  2135            /*where=*/oop,
  2136            MacroAssembler::MemBarRel,
  2137            MacroAssembler::cmpxchgx_hint_release_lock(),
  2138            noreg,
  2139            &cont);
  2141   assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
  2143   // Handle existing monitor.
  2144   if ((EmitSync & 0x02) == 0) {
  2145     b(cont);
  2147     bind(object_has_monitor);
  2148     addi(current_header, current_header, -markOopDesc::monitor_value); // monitor
  2149     ld(temp,             ObjectMonitor::owner_offset_in_bytes(), current_header);
  2150     ld(displaced_header, ObjectMonitor::recursions_offset_in_bytes(), current_header);
  2151     xorr(temp, R16_thread, temp);      // Will be 0 if we are the owner.
  2152     orr(temp, temp, displaced_header); // Will be 0 if there are 0 recursions.
  2153     cmpdi(flag, temp, 0);
  2154     bne(flag, cont);
  2156     ld(temp,             ObjectMonitor::EntryList_offset_in_bytes(), current_header);
  2157     ld(displaced_header, ObjectMonitor::cxq_offset_in_bytes(), current_header);
  2158     orr(temp, temp, displaced_header); // Will be 0 if both are 0.
  2159     cmpdi(flag, temp, 0);
  2160     bne(flag, cont);
  2161     release();
  2162     std(temp, ObjectMonitor::owner_offset_in_bytes(), current_header);
  2165   bind(cont);
  2166   // flag == EQ indicates success
  2167   // flag == NE indicates failure
  2170 // Write serialization page so VM thread can do a pseudo remote membar.
  2171 // We use the current thread pointer to calculate a thread specific
  2172 // offset to write to within the page. This minimizes bus traffic
  2173 // due to cache line collision.
  2174 void MacroAssembler::serialize_memory(Register thread, Register tmp1, Register tmp2) {
  2175   srdi(tmp2, thread, os::get_serialize_page_shift_count());
  2177   int mask = os::vm_page_size() - sizeof(int);
  2178   if (Assembler::is_simm(mask, 16)) {
  2179     andi(tmp2, tmp2, mask);
  2180   } else {
  2181     lis(tmp1, (int)((signed short) (mask >> 16)));
  2182     ori(tmp1, tmp1, mask & 0x0000ffff);
  2183     andr(tmp2, tmp2, tmp1);
  2186   load_const(tmp1, (long) os::get_memory_serialize_page());
  2187   release();
  2188   stwx(R0, tmp1, tmp2);
  2192 // GC barrier helper macros
  2194 // Write the card table byte if needed.
  2195 void MacroAssembler::card_write_barrier_post(Register Rstore_addr, Register Rnew_val, Register Rtmp) {
  2196   CardTableModRefBS* bs = (CardTableModRefBS*) Universe::heap()->barrier_set();
  2197   assert(bs->kind() == BarrierSet::CardTableModRef ||
  2198          bs->kind() == BarrierSet::CardTableExtension, "wrong barrier");
  2199 #ifdef ASSERT
  2200   cmpdi(CCR0, Rnew_val, 0);
  2201   asm_assert_ne("null oop not allowed", 0x321);
  2202 #endif
  2203   card_table_write(bs->byte_map_base, Rtmp, Rstore_addr);
  2206 // Write the card table byte.
  2207 void MacroAssembler::card_table_write(jbyte* byte_map_base, Register Rtmp, Register Robj) {
  2208   assert_different_registers(Robj, Rtmp, R0);
  2209   load_const_optimized(Rtmp, (address)byte_map_base, R0);
  2210   srdi(Robj, Robj, CardTableModRefBS::card_shift);
  2211   li(R0, 0); // dirty
  2212   if (UseConcMarkSweepGC) membar(Assembler::StoreStore);
  2213   stbx(R0, Rtmp, Robj);
  2216 #ifndef SERIALGC
  2218 // General G1 pre-barrier generator.
  2219 // Goal: record the previous value if it is not null.
  2220 void MacroAssembler::g1_write_barrier_pre(Register Robj, RegisterOrConstant offset, Register Rpre_val,
  2221                                           Register Rtmp1, Register Rtmp2, bool needs_frame) {
  2222   Label runtime, filtered;
  2224   // Is marking active?
  2225   if (in_bytes(PtrQueue::byte_width_of_active()) == 4) {
  2226     lwz(Rtmp1, in_bytes(JavaThread::satb_mark_queue_offset() + PtrQueue::byte_offset_of_active()), R16_thread);
  2227   } else {
  2228     guarantee(in_bytes(PtrQueue::byte_width_of_active()) == 1, "Assumption");
  2229     lbz(Rtmp1, in_bytes(JavaThread::satb_mark_queue_offset() + PtrQueue::byte_offset_of_active()), R16_thread);
  2231   cmpdi(CCR0, Rtmp1, 0);
  2232   beq(CCR0, filtered);
  2234   // Do we need to load the previous value?
  2235   if (Robj != noreg) {
  2236     // Load the previous value...
  2237     if (UseCompressedOops) {
  2238       lwz(Rpre_val, offset, Robj);
  2239     } else {
  2240       ld(Rpre_val, offset, Robj);
  2242     // Previous value has been loaded into Rpre_val.
  2244   assert(Rpre_val != noreg, "must have a real register");
  2246   // Is the previous value null?
  2247   cmpdi(CCR0, Rpre_val, 0);
  2248   beq(CCR0, filtered);
  2250   if (Robj != noreg && UseCompressedOops) {
  2251     decode_heap_oop_not_null(Rpre_val);
  2254   // OK, it's not filtered, so we'll need to call enqueue. In the normal
  2255   // case, pre_val will be a scratch G-reg, but there are some cases in
  2256   // which it's an O-reg. In the first case, do a normal call. In the
  2257   // latter, do a save here and call the frameless version.
  2259   // Can we store original value in the thread's buffer?
  2260   // Is index == 0?
  2261   // (The index field is typed as size_t.)
  2262   const Register Rbuffer = Rtmp1, Rindex = Rtmp2;
  2264   ld(Rindex, in_bytes(JavaThread::satb_mark_queue_offset() + PtrQueue::byte_offset_of_index()), R16_thread);
  2265   cmpdi(CCR0, Rindex, 0);
  2266   beq(CCR0, runtime); // If index == 0, goto runtime.
  2267   ld(Rbuffer, in_bytes(JavaThread::satb_mark_queue_offset() + PtrQueue::byte_offset_of_buf()), R16_thread);
  2269   addi(Rindex, Rindex, -wordSize); // Decrement index.
  2270   std(Rindex, in_bytes(JavaThread::satb_mark_queue_offset() + PtrQueue::byte_offset_of_index()), R16_thread);
  2272   // Record the previous value.
  2273   stdx(Rpre_val, Rbuffer, Rindex);
  2274   b(filtered);
  2276   bind(runtime);
  2278   // VM call need frame to access(write) O register.
  2279   if (needs_frame) {
  2280     save_LR_CR(Rtmp1);
  2281     push_frame_reg_args(0, Rtmp2);
  2284   if (Rpre_val->is_volatile() && Robj == noreg) mr(R31, Rpre_val); // Save pre_val across C call if it was preloaded.
  2285   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), Rpre_val, R16_thread);
  2286   if (Rpre_val->is_volatile() && Robj == noreg) mr(Rpre_val, R31); // restore
  2288   if (needs_frame) {
  2289     pop_frame();
  2290     restore_LR_CR(Rtmp1);
  2293   bind(filtered);
  2296 // General G1 post-barrier generator
  2297 // Store cross-region card.
  2298 void MacroAssembler::g1_write_barrier_post(Register Rstore_addr, Register Rnew_val, Register Rtmp1, Register Rtmp2, Register Rtmp3, Label *filtered_ext) {
  2299   Label runtime, filtered_int;
  2300   Label& filtered = (filtered_ext != NULL) ? *filtered_ext : filtered_int;
  2301   assert_different_registers(Rstore_addr, Rnew_val, Rtmp1, Rtmp2);
  2303   G1SATBCardTableModRefBS* bs = (G1SATBCardTableModRefBS*) Universe::heap()->barrier_set();
  2304   assert(bs->kind() == BarrierSet::G1SATBCT ||
  2305          bs->kind() == BarrierSet::G1SATBCTLogging, "wrong barrier");
  2307   // Does store cross heap regions?
  2308   if (G1RSBarrierRegionFilter) {
  2309     xorr(Rtmp1, Rstore_addr, Rnew_val);
  2310     srdi_(Rtmp1, Rtmp1, HeapRegion::LogOfHRGrainBytes);
  2311     beq(CCR0, filtered);
  2314   // Crosses regions, storing NULL?
  2315 #ifdef ASSERT
  2316   cmpdi(CCR0, Rnew_val, 0);
  2317   asm_assert_ne("null oop not allowed (G1)", 0x322); // Checked by caller on PPC64, so following branch is obsolete:
  2318   //beq(CCR0, filtered);
  2319 #endif
  2321   // Storing region crossing non-NULL, is card already dirty?
  2322   assert(sizeof(*bs->byte_map_base) == sizeof(jbyte), "adjust this code");
  2323   const Register Rcard_addr = Rtmp1;
  2324   Register Rbase = Rtmp2;
  2325   load_const_optimized(Rbase, (address)bs->byte_map_base, /*temp*/ Rtmp3);
  2327   srdi(Rcard_addr, Rstore_addr, CardTableModRefBS::card_shift);
  2329   // Get the address of the card.
  2330   lbzx(/*card value*/ Rtmp3, Rbase, Rcard_addr);
  2332   assert(CardTableModRefBS::dirty_card_val() == 0, "otherwise check this code");
  2333   cmpwi(CCR0, Rtmp3 /* card value */, 0);
  2334   beq(CCR0, filtered);
  2336   // Storing a region crossing, non-NULL oop, card is clean.
  2337   // Dirty card and log.
  2338   li(Rtmp3, 0); // dirty
  2339   //release(); // G1: oops are allowed to get visible after dirty marking.
  2340   stbx(Rtmp3, Rbase, Rcard_addr);
  2342   add(Rcard_addr, Rbase, Rcard_addr); // This is the address which needs to get enqueued.
  2343   Rbase = noreg; // end of lifetime
  2345   const Register Rqueue_index = Rtmp2,
  2346                  Rqueue_buf   = Rtmp3;
  2347   ld(Rqueue_index, in_bytes(JavaThread::dirty_card_queue_offset() + PtrQueue::byte_offset_of_index()), R16_thread);
  2348   cmpdi(CCR0, Rqueue_index, 0);
  2349   beq(CCR0, runtime); // index == 0 then jump to runtime
  2350   ld(Rqueue_buf, in_bytes(JavaThread::dirty_card_queue_offset() + PtrQueue::byte_offset_of_buf()), R16_thread);
  2352   addi(Rqueue_index, Rqueue_index, -wordSize); // decrement index
  2353   std(Rqueue_index, in_bytes(JavaThread::dirty_card_queue_offset() + PtrQueue::byte_offset_of_index()), R16_thread);
  2355   stdx(Rcard_addr, Rqueue_buf, Rqueue_index); // store card
  2356   b(filtered);
  2358   bind(runtime);
  2360   // Save the live input values.
  2361   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), Rcard_addr, R16_thread);
  2363   bind(filtered_int);
  2365 #endif // SERIALGC
  2367 // Values for last_Java_pc, and last_Java_sp must comply to the rules
  2368 // in frame_ppc64.hpp.
  2369 void MacroAssembler::set_last_Java_frame(Register last_Java_sp, Register last_Java_pc) {
  2370   // Always set last_Java_pc and flags first because once last_Java_sp
  2371   // is visible has_last_Java_frame is true and users will look at the
  2372   // rest of the fields. (Note: flags should always be zero before we
  2373   // get here so doesn't need to be set.)
  2375   // Verify that last_Java_pc was zeroed on return to Java
  2376   asm_assert_mem8_is_zero(in_bytes(JavaThread::last_Java_pc_offset()), R16_thread,
  2377                           "last_Java_pc not zeroed before leaving Java", 0x200);
  2379   // When returning from calling out from Java mode the frame anchor's
  2380   // last_Java_pc will always be set to NULL. It is set here so that
  2381   // if we are doing a call to native (not VM) that we capture the
  2382   // known pc and don't have to rely on the native call having a
  2383   // standard frame linkage where we can find the pc.
  2384   if (last_Java_pc != noreg)
  2385     std(last_Java_pc, in_bytes(JavaThread::last_Java_pc_offset()), R16_thread);
  2387   // Set last_Java_sp last.
  2388   std(last_Java_sp, in_bytes(JavaThread::last_Java_sp_offset()), R16_thread);
  2391 void MacroAssembler::reset_last_Java_frame(void) {
  2392   asm_assert_mem8_isnot_zero(in_bytes(JavaThread::last_Java_sp_offset()),
  2393                              R16_thread, "SP was not set, still zero", 0x202);
  2395   BLOCK_COMMENT("reset_last_Java_frame {");
  2396   li(R0, 0);
  2398   // _last_Java_sp = 0
  2399   std(R0, in_bytes(JavaThread::last_Java_sp_offset()), R16_thread);
  2401   // _last_Java_pc = 0
  2402   std(R0, in_bytes(JavaThread::last_Java_pc_offset()), R16_thread);
  2403   BLOCK_COMMENT("} reset_last_Java_frame");
  2406 void MacroAssembler::set_top_ijava_frame_at_SP_as_last_Java_frame(Register sp, Register tmp1) {
  2407   assert_different_registers(sp, tmp1);
  2409   // sp points to a TOP_IJAVA_FRAME, retrieve frame's PC via
  2410   // TOP_IJAVA_FRAME_ABI.
  2411   // FIXME: assert that we really have a TOP_IJAVA_FRAME here!
  2412 #ifdef CC_INTERP
  2413   ld(tmp1/*pc*/, _top_ijava_frame_abi(frame_manager_lr), sp);
  2414 #else
  2415   address entry = pc();
  2416   load_const_optimized(tmp1, entry);
  2417 #endif
  2419   set_last_Java_frame(/*sp=*/sp, /*pc=*/tmp1);
  2422 void MacroAssembler::get_vm_result(Register oop_result) {
  2423   // Read:
  2424   //   R16_thread
  2425   //   R16_thread->in_bytes(JavaThread::vm_result_offset())
  2426   //
  2427   // Updated:
  2428   //   oop_result
  2429   //   R16_thread->in_bytes(JavaThread::vm_result_offset())
  2431   ld(oop_result, in_bytes(JavaThread::vm_result_offset()), R16_thread);
  2432   li(R0, 0);
  2433   std(R0, in_bytes(JavaThread::vm_result_offset()), R16_thread);
  2435   verify_oop(oop_result);
  2438 void MacroAssembler::get_vm_result_2(Register metadata_result) {
  2439   // Read:
  2440   //   R16_thread
  2441   //   R16_thread->in_bytes(JavaThread::vm_result_2_offset())
  2442   //
  2443   // Updated:
  2444   //   metadata_result
  2445   //   R16_thread->in_bytes(JavaThread::vm_result_2_offset())
  2447   ld(metadata_result, in_bytes(JavaThread::vm_result_2_offset()), R16_thread);
  2448   li(R0, 0);
  2449   std(R0, in_bytes(JavaThread::vm_result_2_offset()), R16_thread);
  2453 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
  2454   Register current = (src != noreg) ? src : dst; // Klass is in dst if no src provided.
  2455   if (Universe::narrow_klass_base() != 0) {
  2456     load_const(R0, Universe::narrow_klass_base(), (dst != current) ? dst : noreg); // Use dst as temp if it is free.
  2457     sub(dst, current, R0);
  2458     current = dst;
  2460   if (Universe::narrow_klass_shift() != 0) {
  2461     srdi(dst, current, Universe::narrow_klass_shift());
  2462     current = dst;
  2464   mr_if_needed(dst, current); // Move may be required.
  2467 void MacroAssembler::store_klass(Register dst_oop, Register klass, Register ck) {
  2468   if (UseCompressedClassPointers) {
  2469     encode_klass_not_null(ck, klass);
  2470     stw(ck, oopDesc::klass_offset_in_bytes(), dst_oop);
  2471   } else {
  2472     std(klass, oopDesc::klass_offset_in_bytes(), dst_oop);
  2476 void MacroAssembler::store_klass_gap(Register dst_oop, Register val) {
  2477   if (UseCompressedClassPointers) {
  2478     if (val == noreg) {
  2479       val = R0;
  2480       li(val, 0);
  2482     stw(val, oopDesc::klass_gap_offset_in_bytes(), dst_oop); // klass gap if compressed
  2486 int MacroAssembler::instr_size_for_decode_klass_not_null() {
  2487   if (!UseCompressedClassPointers) return 0;
  2488   int num_instrs = 1;  // shift or move
  2489   if (Universe::narrow_klass_base() != 0) num_instrs = 7;  // shift + load const + add
  2490   return num_instrs * BytesPerInstWord;
  2493 void MacroAssembler::decode_klass_not_null(Register dst, Register src) {
  2494   if (src == noreg) src = dst;
  2495   Register shifted_src = src;
  2496   if (Universe::narrow_klass_shift() != 0 ||
  2497       Universe::narrow_klass_base() == 0 && src != dst) {  // Move required.
  2498     shifted_src = dst;
  2499     sldi(shifted_src, src, Universe::narrow_klass_shift());
  2501   if (Universe::narrow_klass_base() != 0) {
  2502     load_const(R0, Universe::narrow_klass_base());
  2503     add(dst, shifted_src, R0);
  2507 void MacroAssembler::load_klass(Register dst, Register src) {
  2508   if (UseCompressedClassPointers) {
  2509     lwz(dst, oopDesc::klass_offset_in_bytes(), src);
  2510     // Attention: no null check here!
  2511     decode_klass_not_null(dst, dst);
  2512   } else {
  2513     ld(dst, oopDesc::klass_offset_in_bytes(), src);
  2517 void MacroAssembler::load_klass_with_trap_null_check(Register dst, Register src) {
  2518   if (!os::zero_page_read_protected()) {
  2519     if (TrapBasedNullChecks) {
  2520       trap_null_check(src);
  2523   load_klass(dst, src);
  2526 void MacroAssembler::reinit_heapbase(Register d, Register tmp) {
  2527   if (Universe::heap() != NULL) {
  2528     if (Universe::narrow_oop_base() == NULL) {
  2529       Assembler::xorr(R30, R30, R30);
  2530     } else {
  2531       load_const(R30, Universe::narrow_ptrs_base(), tmp);
  2533   } else {
  2534     load_const(R30, Universe::narrow_ptrs_base_addr(), tmp);
  2535     ld(R30, 0, R30);
  2539 // Clear Array
  2540 // Kills both input registers. tmp == R0 is allowed.
  2541 void MacroAssembler::clear_memory_doubleword(Register base_ptr, Register cnt_dwords, Register tmp) {
  2542   // Procedure for large arrays (uses data cache block zero instruction).
  2543     Label startloop, fast, fastloop, small_rest, restloop, done;
  2544     const int cl_size         = VM_Version::get_cache_line_size(),
  2545               cl_dwords       = cl_size>>3,
  2546               cl_dw_addr_bits = exact_log2(cl_dwords),
  2547               dcbz_min        = 1;                     // Min count of dcbz executions, needs to be >0.
  2549 //2:
  2550     cmpdi(CCR1, cnt_dwords, ((dcbz_min+1)<<cl_dw_addr_bits)-1); // Big enough? (ensure >=dcbz_min lines included).
  2551     blt(CCR1, small_rest);                                      // Too small.
  2552     rldicl_(tmp, base_ptr, 64-3, 64-cl_dw_addr_bits);           // Extract dword offset within first cache line.
  2553     beq(CCR0, fast);                                            // Already 128byte aligned.
  2555     subfic(tmp, tmp, cl_dwords);
  2556     mtctr(tmp);                        // Set ctr to hit 128byte boundary (0<ctr<cl_dwords).
  2557     subf(cnt_dwords, tmp, cnt_dwords); // rest.
  2558     li(tmp, 0);
  2559 //10:
  2560   bind(startloop);                     // Clear at the beginning to reach 128byte boundary.
  2561     std(tmp, 0, base_ptr);             // Clear 8byte aligned block.
  2562     addi(base_ptr, base_ptr, 8);
  2563     bdnz(startloop);
  2564 //13:
  2565   bind(fast);                                  // Clear 128byte blocks.
  2566     srdi(tmp, cnt_dwords, cl_dw_addr_bits);    // Loop count for 128byte loop (>0).
  2567     andi(cnt_dwords, cnt_dwords, cl_dwords-1); // Rest in dwords.
  2568     mtctr(tmp);                                // Load counter.
  2569 //16:
  2570   bind(fastloop);
  2571     dcbz(base_ptr);                    // Clear 128byte aligned block.
  2572     addi(base_ptr, base_ptr, cl_size);
  2573     bdnz(fastloop);
  2574     if (InsertEndGroupPPC64) { endgroup(); } else { nop(); }
  2575 //20:
  2576   bind(small_rest);
  2577     cmpdi(CCR0, cnt_dwords, 0);        // size 0?
  2578     beq(CCR0, done);                   // rest == 0
  2579     li(tmp, 0);
  2580     mtctr(cnt_dwords);                 // Load counter.
  2581 //24:
  2582   bind(restloop);                      // Clear rest.
  2583     std(tmp, 0, base_ptr);             // Clear 8byte aligned block.
  2584     addi(base_ptr, base_ptr, 8);
  2585     bdnz(restloop);
  2586 //27:
  2587   bind(done);
  2590 /////////////////////////////////////////// String intrinsics ////////////////////////////////////////////
  2592 // Search for a single jchar in an jchar[].
  2593 //
  2594 // Assumes that result differs from all other registers.
  2595 //
  2596 // Haystack, needle are the addresses of jchar-arrays.
  2597 // NeedleChar is needle[0] if it is known at compile time.
  2598 // Haycnt is the length of the haystack. We assume haycnt >=1.
  2599 //
  2600 // Preserves haystack, haycnt, kills all other registers.
  2601 //
  2602 // If needle == R0, we search for the constant needleChar.
  2603 void MacroAssembler::string_indexof_1(Register result, Register haystack, Register haycnt,
  2604                                       Register needle, jchar needleChar,
  2605                                       Register tmp1, Register tmp2) {
  2607   assert_different_registers(result, haystack, haycnt, needle, tmp1, tmp2);
  2609   Label L_InnerLoop, L_FinalCheck, L_Found1, L_Found2, L_Found3, L_NotFound, L_End;
  2610   Register needle0 = needle, // Contains needle[0].
  2611            addr = tmp1,
  2612            ch1 = tmp2,
  2613            ch2 = R0;
  2615 //2 (variable) or 3 (const):
  2616    if (needle != R0) lhz(needle0, 0, needle); // Preload needle character, needle has len==1.
  2617    dcbtct(haystack, 0x00);                        // Indicate R/O access to haystack.
  2619    srwi_(tmp2, haycnt, 1);   // Shift right by exact_log2(UNROLL_FACTOR).
  2620    mr(addr, haystack);
  2621    beq(CCR0, L_FinalCheck);
  2622    mtctr(tmp2);              // Move to count register.
  2623 //8:
  2624   bind(L_InnerLoop);             // Main work horse (2x unrolled search loop).
  2625    lhz(ch1, 0, addr);        // Load characters from haystack.
  2626    lhz(ch2, 2, addr);
  2627    (needle != R0) ? cmpw(CCR0, ch1, needle0) : cmplwi(CCR0, ch1, needleChar);
  2628    (needle != R0) ? cmpw(CCR1, ch2, needle0) : cmplwi(CCR1, ch2, needleChar);
  2629    beq(CCR0, L_Found1);   // Did we find the needle?
  2630    beq(CCR1, L_Found2);
  2631    addi(addr, addr, 4);
  2632    bdnz(L_InnerLoop);
  2633 //16:
  2634   bind(L_FinalCheck);
  2635    andi_(R0, haycnt, 1);
  2636    beq(CCR0, L_NotFound);
  2637    lhz(ch1, 0, addr);        // One position left at which we have to compare.
  2638    (needle != R0) ? cmpw(CCR1, ch1, needle0) : cmplwi(CCR1, ch1, needleChar);
  2639    beq(CCR1, L_Found3);
  2640 //21:
  2641   bind(L_NotFound);
  2642    li(result, -1);           // Not found.
  2643    b(L_End);
  2645   bind(L_Found2);
  2646    addi(addr, addr, 2);
  2647 //24:
  2648   bind(L_Found1);
  2649   bind(L_Found3);                  // Return index ...
  2650    subf(addr, haystack, addr); // relative to haystack,
  2651    srdi(result, addr, 1);      // in characters.
  2652   bind(L_End);
  2656 // Implementation of IndexOf for jchar arrays.
  2657 //
  2658 // The length of haystack and needle are not constant, i.e. passed in a register.
  2659 //
  2660 // Preserves registers haystack, needle.
  2661 // Kills registers haycnt, needlecnt.
  2662 // Assumes that result differs from all other registers.
  2663 // Haystack, needle are the addresses of jchar-arrays.
  2664 // Haycnt, needlecnt are the lengths of them, respectively.
  2665 //
  2666 // Needlecntval must be zero or 15-bit unsigned immediate and > 1.
  2667 void MacroAssembler::string_indexof(Register result, Register haystack, Register haycnt,
  2668                                     Register needle, ciTypeArray* needle_values, Register needlecnt, int needlecntval,
  2669                                     Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
  2671   // Ensure 0<needlecnt<=haycnt in ideal graph as prerequisite!
  2672   Label L_TooShort, L_Found, L_NotFound, L_End;
  2673   Register last_addr = haycnt, // Kill haycnt at the beginning.
  2674            addr      = tmp1,
  2675            n_start   = tmp2,
  2676            ch1       = tmp3,
  2677            ch2       = R0;
  2679   // **************************************************************************************************
  2680   // Prepare for main loop: optimized for needle count >=2, bail out otherwise.
  2681   // **************************************************************************************************
  2683 //1 (variable) or 3 (const):
  2684    dcbtct(needle, 0x00);    // Indicate R/O access to str1.
  2685    dcbtct(haystack, 0x00);  // Indicate R/O access to str2.
  2687   // Compute last haystack addr to use if no match gets found.
  2688   if (needlecntval == 0) { // variable needlecnt
  2689 //3:
  2690    subf(ch1, needlecnt, haycnt);      // Last character index to compare is haycnt-needlecnt.
  2691    addi(addr, haystack, -2);          // Accesses use pre-increment.
  2692    cmpwi(CCR6, needlecnt, 2);
  2693    blt(CCR6, L_TooShort);          // Variable needlecnt: handle short needle separately.
  2694    slwi(ch1, ch1, 1);                 // Scale to number of bytes.
  2695    lwz(n_start, 0, needle);           // Load first 2 characters of needle.
  2696    add(last_addr, haystack, ch1);     // Point to last address to compare (haystack+2*(haycnt-needlecnt)).
  2697    addi(needlecnt, needlecnt, -2);    // Rest of needle.
  2698   } else { // constant needlecnt
  2699   guarantee(needlecntval != 1, "IndexOf with single-character needle must be handled separately");
  2700   assert((needlecntval & 0x7fff) == needlecntval, "wrong immediate");
  2701 //5:
  2702    addi(ch1, haycnt, -needlecntval);  // Last character index to compare is haycnt-needlecnt.
  2703    lwz(n_start, 0, needle);           // Load first 2 characters of needle.
  2704    addi(addr, haystack, -2);          // Accesses use pre-increment.
  2705    slwi(ch1, ch1, 1);                 // Scale to number of bytes.
  2706    add(last_addr, haystack, ch1);     // Point to last address to compare (haystack+2*(haycnt-needlecnt)).
  2707    li(needlecnt, needlecntval-2);     // Rest of needle.
  2710   // Main Loop (now we have at least 3 characters).
  2711 //11:
  2712   Label L_OuterLoop, L_InnerLoop, L_FinalCheck, L_Comp1, L_Comp2, L_Comp3;
  2713   bind(L_OuterLoop); // Search for 1st 2 characters.
  2714   Register addr_diff = tmp4;
  2715    subf(addr_diff, addr, last_addr); // Difference between already checked address and last address to check.
  2716    addi(addr, addr, 2);              // This is the new address we want to use for comparing.
  2717    srdi_(ch2, addr_diff, 2);
  2718    beq(CCR0, L_FinalCheck);       // 2 characters left?
  2719    mtctr(ch2);                       // addr_diff/4
  2720 //16:
  2721   bind(L_InnerLoop);                // Main work horse (2x unrolled search loop)
  2722    lwz(ch1, 0, addr);           // Load 2 characters of haystack (ignore alignment).
  2723    lwz(ch2, 2, addr);
  2724    cmpw(CCR0, ch1, n_start); // Compare 2 characters (1 would be sufficient but try to reduce branches to CompLoop).
  2725    cmpw(CCR1, ch2, n_start);
  2726    beq(CCR0, L_Comp1);       // Did we find the needle start?
  2727    beq(CCR1, L_Comp2);
  2728    addi(addr, addr, 4);
  2729    bdnz(L_InnerLoop);
  2730 //24:
  2731   bind(L_FinalCheck);
  2732    rldicl_(addr_diff, addr_diff, 64-1, 63); // Remaining characters not covered by InnerLoop: (addr_diff>>1)&1.
  2733    beq(CCR0, L_NotFound);
  2734    lwz(ch1, 0, addr);                       // One position left at which we have to compare.
  2735    cmpw(CCR1, ch1, n_start);
  2736    beq(CCR1, L_Comp3);
  2737 //29:
  2738   bind(L_NotFound);
  2739    li(result, -1); // not found
  2740    b(L_End);
  2743    // **************************************************************************************************
  2744    // Special Case: unfortunately, the variable needle case can be called with needlecnt<2
  2745    // **************************************************************************************************
  2746 //31:
  2747  if ((needlecntval>>1) !=1 ) { // Const needlecnt is 2 or 3? Reduce code size.
  2748   int nopcnt = 5;
  2749   if (needlecntval !=0 ) ++nopcnt; // Balance alignment (other case: see below).
  2750   if (needlecntval == 0) {         // We have to handle these cases separately.
  2751   Label L_OneCharLoop;
  2752   bind(L_TooShort);
  2753    mtctr(haycnt);
  2754    lhz(n_start, 0, needle);    // First character of needle
  2755   bind(L_OneCharLoop);
  2756    lhzu(ch1, 2, addr);
  2757    cmpw(CCR1, ch1, n_start);
  2758    beq(CCR1, L_Found);      // Did we find the one character needle?
  2759    bdnz(L_OneCharLoop);
  2760    li(result, -1);             // Not found.
  2761    b(L_End);
  2762   } // 8 instructions, so no impact on alignment.
  2763   for (int x = 0; x < nopcnt; ++x) nop();
  2766   // **************************************************************************************************
  2767   // Regular Case Part II: compare rest of needle (first 2 characters have been compared already)
  2768   // **************************************************************************************************
  2770   // Compare the rest
  2771 //36 if needlecntval==0, else 37:
  2772   bind(L_Comp2);
  2773    addi(addr, addr, 2); // First comparison has failed, 2nd one hit.
  2774   bind(L_Comp1);            // Addr points to possible needle start.
  2775   bind(L_Comp3);            // Could have created a copy and use a different return address but saving code size here.
  2776   if (needlecntval != 2) {  // Const needlecnt==2?
  2777    if (needlecntval != 3) {
  2778     if (needlecntval == 0) beq(CCR6, L_Found); // Variable needlecnt==2?
  2779     Register ind_reg = tmp4;
  2780     li(ind_reg, 2*2);   // First 2 characters are already compared, use index 2.
  2781     mtctr(needlecnt);   // Decremented by 2, still > 0.
  2782 //40:
  2783    Label L_CompLoop;
  2784    bind(L_CompLoop);
  2785     lhzx(ch2, needle, ind_reg);
  2786     lhzx(ch1, addr, ind_reg);
  2787     cmpw(CCR1, ch1, ch2);
  2788     bne(CCR1, L_OuterLoop);
  2789     addi(ind_reg, ind_reg, 2);
  2790     bdnz(L_CompLoop);
  2791    } else { // No loop required if there's only one needle character left.
  2792     lhz(ch2, 2*2, needle);
  2793     lhz(ch1, 2*2, addr);
  2794     cmpw(CCR1, ch1, ch2);
  2795     bne(CCR1, L_OuterLoop);
  2798   // Return index ...
  2799 //46:
  2800   bind(L_Found);
  2801    subf(addr, haystack, addr); // relative to haystack, ...
  2802    srdi(result, addr, 1);      // in characters.
  2803 //48:
  2804   bind(L_End);
  2807 // Implementation of Compare for jchar arrays.
  2808 //
  2809 // Kills the registers str1, str2, cnt1, cnt2.
  2810 // Kills cr0, ctr.
  2811 // Assumes that result differes from the input registers.
  2812 void MacroAssembler::string_compare(Register str1_reg, Register str2_reg, Register cnt1_reg, Register cnt2_reg,
  2813                                     Register result_reg, Register tmp_reg) {
  2814    assert_different_registers(result_reg, str1_reg, str2_reg, cnt1_reg, cnt2_reg, tmp_reg);
  2816    Label Ldone, Lslow_case, Lslow_loop, Lfast_loop;
  2817    Register cnt_diff = R0,
  2818             limit_reg = cnt1_reg,
  2819             chr1_reg = result_reg,
  2820             chr2_reg = cnt2_reg,
  2821             addr_diff = str2_reg;
  2823    // Offset 0 should be 32 byte aligned.
  2824 //-4:
  2825     dcbtct(str1_reg, 0x00);  // Indicate R/O access to str1.
  2826     dcbtct(str2_reg, 0x00);  // Indicate R/O access to str2.
  2827 //-2:
  2828    // Compute min(cnt1, cnt2) and check if 0 (bail out if we don't need to compare characters).
  2829     subf(result_reg, cnt2_reg, cnt1_reg);  // difference between cnt1/2
  2830     subf_(addr_diff, str1_reg, str2_reg);  // alias?
  2831     beq(CCR0, Ldone);                   // return cnt difference if both ones are identical
  2832     srawi(limit_reg, result_reg, 31);      // generate signmask (cnt1/2 must be non-negative so cnt_diff can't overflow)
  2833     mr(cnt_diff, result_reg);
  2834     andr(limit_reg, result_reg, limit_reg); // difference or zero (negative): cnt1<cnt2 ? cnt1-cnt2 : 0
  2835     add_(limit_reg, cnt2_reg, limit_reg);  // min(cnt1, cnt2)==0?
  2836     beq(CCR0, Ldone);                   // return cnt difference if one has 0 length
  2838     lhz(chr1_reg, 0, str1_reg);            // optional: early out if first characters mismatch
  2839     lhzx(chr2_reg, str1_reg, addr_diff);   // optional: early out if first characters mismatch
  2840     addi(tmp_reg, limit_reg, -1);          // min(cnt1, cnt2)-1
  2841     subf_(result_reg, chr2_reg, chr1_reg); // optional: early out if first characters mismatch
  2842     bne(CCR0, Ldone);                   // optional: early out if first characters mismatch
  2844    // Set loop counter by scaling down tmp_reg
  2845     srawi_(chr2_reg, tmp_reg, exact_log2(4)); // (min(cnt1, cnt2)-1)/4
  2846     ble(CCR0, Lslow_case);                 // need >4 characters for fast loop
  2847     andi(limit_reg, tmp_reg, 4-1);            // remaining characters
  2849    // Adapt str1_reg str2_reg for the first loop iteration
  2850     mtctr(chr2_reg);                 // (min(cnt1, cnt2)-1)/4
  2851     addi(limit_reg, limit_reg, 4+1); // compare last 5-8 characters in slow_case if mismatch found in fast_loop
  2852 //16:
  2853    // Compare the rest of the characters
  2854    bind(Lfast_loop);
  2855     ld(chr1_reg, 0, str1_reg);
  2856     ldx(chr2_reg, str1_reg, addr_diff);
  2857     cmpd(CCR0, chr2_reg, chr1_reg);
  2858     bne(CCR0, Lslow_case); // return chr1_reg
  2859     addi(str1_reg, str1_reg, 4*2);
  2860     bdnz(Lfast_loop);
  2861     addi(limit_reg, limit_reg, -4); // no mismatch found in fast_loop, only 1-4 characters missing
  2862 //23:
  2863    bind(Lslow_case);
  2864     mtctr(limit_reg);
  2865 //24:
  2866    bind(Lslow_loop);
  2867     lhz(chr1_reg, 0, str1_reg);
  2868     lhzx(chr2_reg, str1_reg, addr_diff);
  2869     subf_(result_reg, chr2_reg, chr1_reg);
  2870     bne(CCR0, Ldone); // return chr1_reg
  2871     addi(str1_reg, str1_reg, 1*2);
  2872     bdnz(Lslow_loop);
  2873 //30:
  2874    // If strings are equal up to min length, return the length difference.
  2875     mr(result_reg, cnt_diff);
  2876     nop(); // alignment
  2877 //32:
  2878    // Otherwise, return the difference between the first mismatched chars.
  2879    bind(Ldone);
  2883 // Compare char[] arrays.
  2884 //
  2885 // str1_reg   USE only
  2886 // str2_reg   USE only
  2887 // cnt_reg    USE_DEF, due to tmp reg shortage
  2888 // result_reg DEF only, might compromise USE only registers
  2889 void MacroAssembler::char_arrays_equals(Register str1_reg, Register str2_reg, Register cnt_reg, Register result_reg,
  2890                                         Register tmp1_reg, Register tmp2_reg, Register tmp3_reg, Register tmp4_reg,
  2891                                         Register tmp5_reg) {
  2893   // Str1 may be the same register as str2 which can occur e.g. after scalar replacement.
  2894   assert_different_registers(result_reg, str1_reg, cnt_reg, tmp1_reg, tmp2_reg, tmp3_reg, tmp4_reg, tmp5_reg);
  2895   assert_different_registers(result_reg, str2_reg, cnt_reg, tmp1_reg, tmp2_reg, tmp3_reg, tmp4_reg, tmp5_reg);
  2897   // Offset 0 should be 32 byte aligned.
  2898   Label Linit_cbc, Lcbc, Lloop, Ldone_true, Ldone_false;
  2899   Register index_reg = tmp5_reg;
  2900   Register cbc_iter  = tmp4_reg;
  2902 //-1:
  2903   dcbtct(str1_reg, 0x00);  // Indicate R/O access to str1.
  2904   dcbtct(str2_reg, 0x00);  // Indicate R/O access to str2.
  2905 //1:
  2906   andi(cbc_iter, cnt_reg, 4-1);            // Remaining iterations after 4 java characters per iteration loop.
  2907   li(index_reg, 0); // init
  2908   li(result_reg, 0); // assume false
  2909   srwi_(tmp2_reg, cnt_reg, exact_log2(4)); // Div: 4 java characters per iteration (main loop).
  2911   cmpwi(CCR1, cbc_iter, 0);             // CCR1 = (cbc_iter==0)
  2912   beq(CCR0, Linit_cbc);                 // too short
  2913     mtctr(tmp2_reg);
  2914 //8:
  2915     bind(Lloop);
  2916       ldx(tmp1_reg, str1_reg, index_reg);
  2917       ldx(tmp2_reg, str2_reg, index_reg);
  2918       cmpd(CCR0, tmp1_reg, tmp2_reg);
  2919       bne(CCR0, Ldone_false);  // Unequal char pair found -> done.
  2920       addi(index_reg, index_reg, 4*sizeof(jchar));
  2921       bdnz(Lloop);
  2922 //14:
  2923   bind(Linit_cbc);
  2924   beq(CCR1, Ldone_true);
  2925     mtctr(cbc_iter);
  2926 //16:
  2927     bind(Lcbc);
  2928       lhzx(tmp1_reg, str1_reg, index_reg);
  2929       lhzx(tmp2_reg, str2_reg, index_reg);
  2930       cmpw(CCR0, tmp1_reg, tmp2_reg);
  2931       bne(CCR0, Ldone_false);  // Unequal char pair found -> done.
  2932       addi(index_reg, index_reg, 1*sizeof(jchar));
  2933       bdnz(Lcbc);
  2934     nop();
  2935   bind(Ldone_true);
  2936   li(result_reg, 1);
  2937 //24:
  2938   bind(Ldone_false);
  2942 void MacroAssembler::char_arrays_equalsImm(Register str1_reg, Register str2_reg, int cntval, Register result_reg,
  2943                                            Register tmp1_reg, Register tmp2_reg) {
  2944   // Str1 may be the same register as str2 which can occur e.g. after scalar replacement.
  2945   assert_different_registers(result_reg, str1_reg, tmp1_reg, tmp2_reg);
  2946   assert_different_registers(result_reg, str2_reg, tmp1_reg, tmp2_reg);
  2947   assert(sizeof(jchar) == 2, "must be");
  2948   assert(cntval >= 0 && ((cntval & 0x7fff) == cntval), "wrong immediate");
  2950   Label Ldone_false;
  2952   if (cntval < 16) { // short case
  2953     if (cntval != 0) li(result_reg, 0); // assume false
  2955     const int num_bytes = cntval*sizeof(jchar);
  2956     int index = 0;
  2957     for (int next_index; (next_index = index + 8) <= num_bytes; index = next_index) {
  2958       ld(tmp1_reg, index, str1_reg);
  2959       ld(tmp2_reg, index, str2_reg);
  2960       cmpd(CCR0, tmp1_reg, tmp2_reg);
  2961       bne(CCR0, Ldone_false);
  2963     if (cntval & 2) {
  2964       lwz(tmp1_reg, index, str1_reg);
  2965       lwz(tmp2_reg, index, str2_reg);
  2966       cmpw(CCR0, tmp1_reg, tmp2_reg);
  2967       bne(CCR0, Ldone_false);
  2968       index += 4;
  2970     if (cntval & 1) {
  2971       lhz(tmp1_reg, index, str1_reg);
  2972       lhz(tmp2_reg, index, str2_reg);
  2973       cmpw(CCR0, tmp1_reg, tmp2_reg);
  2974       bne(CCR0, Ldone_false);
  2976     // fallthrough: true
  2977   } else {
  2978     Label Lloop;
  2979     Register index_reg = tmp1_reg;
  2980     const int loopcnt = cntval/4;
  2981     assert(loopcnt > 0, "must be");
  2982     // Offset 0 should be 32 byte aligned.
  2983     //2:
  2984     dcbtct(str1_reg, 0x00);  // Indicate R/O access to str1.
  2985     dcbtct(str2_reg, 0x00);  // Indicate R/O access to str2.
  2986     li(tmp2_reg, loopcnt);
  2987     li(index_reg, 0); // init
  2988     li(result_reg, 0); // assume false
  2989     mtctr(tmp2_reg);
  2990     //8:
  2991     bind(Lloop);
  2992     ldx(R0, str1_reg, index_reg);
  2993     ldx(tmp2_reg, str2_reg, index_reg);
  2994     cmpd(CCR0, R0, tmp2_reg);
  2995     bne(CCR0, Ldone_false);  // Unequal char pair found -> done.
  2996     addi(index_reg, index_reg, 4*sizeof(jchar));
  2997     bdnz(Lloop);
  2998     //14:
  2999     if (cntval & 2) {
  3000       lwzx(R0, str1_reg, index_reg);
  3001       lwzx(tmp2_reg, str2_reg, index_reg);
  3002       cmpw(CCR0, R0, tmp2_reg);
  3003       bne(CCR0, Ldone_false);
  3004       if (cntval & 1) addi(index_reg, index_reg, 2*sizeof(jchar));
  3006     if (cntval & 1) {
  3007       lhzx(R0, str1_reg, index_reg);
  3008       lhzx(tmp2_reg, str2_reg, index_reg);
  3009       cmpw(CCR0, R0, tmp2_reg);
  3010       bne(CCR0, Ldone_false);
  3012     // fallthru: true
  3014   li(result_reg, 1);
  3015   bind(Ldone_false);
  3019 void MacroAssembler::asm_assert(bool check_equal, const char *msg, int id) {
  3020 #ifdef ASSERT
  3021   Label ok;
  3022   if (check_equal) {
  3023     beq(CCR0, ok);
  3024   } else {
  3025     bne(CCR0, ok);
  3027   stop(msg, id);
  3028   bind(ok);
  3029 #endif
  3032 void MacroAssembler::asm_assert_mems_zero(bool check_equal, int size, int mem_offset,
  3033                                           Register mem_base, const char* msg, int id) {
  3034 #ifdef ASSERT
  3035   switch (size) {
  3036     case 4:
  3037       lwz(R0, mem_offset, mem_base);
  3038       cmpwi(CCR0, R0, 0);
  3039       break;
  3040     case 8:
  3041       ld(R0, mem_offset, mem_base);
  3042       cmpdi(CCR0, R0, 0);
  3043       break;
  3044     default:
  3045       ShouldNotReachHere();
  3047   asm_assert(check_equal, msg, id);
  3048 #endif // ASSERT
  3051 void MacroAssembler::verify_thread() {
  3052   if (VerifyThread) {
  3053     unimplemented("'VerifyThread' currently not implemented on PPC");
  3057 // READ: oop. KILL: R0. Volatile floats perhaps.
  3058 void MacroAssembler::verify_oop(Register oop, const char* msg) {
  3059   if (!VerifyOops) {
  3060     return;
  3062   // Will be preserved.
  3063   Register tmp = R11;
  3064   assert(oop != tmp, "precondition");
  3065   unsigned int nbytes_save = 10*8; // 10 volatile gprs
  3066   address/* FunctionDescriptor** */fd = StubRoutines::verify_oop_subroutine_entry_address();
  3067   // save tmp
  3068   mr(R0, tmp);
  3069   // kill tmp
  3070   save_LR_CR(tmp);
  3071   push_frame_reg_args(nbytes_save, tmp);
  3072   // restore tmp
  3073   mr(tmp, R0);
  3074   save_volatile_gprs(R1_SP, 112); // except R0
  3075   // load FunctionDescriptor** / entry_address *
  3076   load_const(tmp, fd);
  3077   // load FunctionDescriptor* / entry_address
  3078   ld(tmp, 0, tmp);
  3079   mr(R4_ARG2, oop);
  3080   load_const(R3_ARG1, (address)msg);
  3081   // call destination for its side effect
  3082   call_c(tmp);
  3083   restore_volatile_gprs(R1_SP, 112); // except R0
  3084   pop_frame();
  3085   // save tmp
  3086   mr(R0, tmp);
  3087   // kill tmp
  3088   restore_LR_CR(tmp);
  3089   // restore tmp
  3090   mr(tmp, R0);
  3093 const char* stop_types[] = {
  3094   "stop",
  3095   "untested",
  3096   "unimplemented",
  3097   "shouldnotreachhere"
  3098 };
  3100 static void stop_on_request(int tp, const char* msg) {
  3101   tty->print("PPC assembly code requires stop: (%s) %s\n", (void *)stop_types[tp%/*stop_end*/4], msg);
  3102   guarantee(false, err_msg("PPC assembly code requires stop: %s", msg));
  3105 // Call a C-function that prints output.
  3106 void MacroAssembler::stop(int type, const char* msg, int id) {
  3107 #ifndef PRODUCT
  3108   block_comment(err_msg("stop: %s %s {", stop_types[type%stop_end], msg));
  3109 #else
  3110   block_comment("stop {");
  3111 #endif
  3113   // setup arguments
  3114   load_const_optimized(R3_ARG1, type);
  3115   load_const_optimized(R4_ARG2, (void *)msg, /*tmp=*/R0);
  3116   call_VM_leaf(CAST_FROM_FN_PTR(address, stop_on_request), R3_ARG1, R4_ARG2);
  3117   illtrap();
  3118   emit_int32(id);
  3119   block_comment("} stop;");
  3122 #ifndef PRODUCT
  3123 // Write pattern 0x0101010101010101 in memory region [low-before, high+after].
  3124 // Val, addr are temp registers.
  3125 // If low == addr, addr is killed.
  3126 // High is preserved.
  3127 void MacroAssembler::zap_from_to(Register low, int before, Register high, int after, Register val, Register addr) {
  3128   if (!ZapMemory) return;
  3130   assert_different_registers(low, val);
  3132   BLOCK_COMMENT("zap memory region {");
  3133   load_const_optimized(val, 0x0101010101010101);
  3134   int size = before + after;
  3135   if (low == high && size < 5 && size > 0) {
  3136     int offset = -before*BytesPerWord;
  3137     for (int i = 0; i < size; ++i) {
  3138       std(val, offset, low);
  3139       offset += (1*BytesPerWord);
  3141   } else {
  3142     addi(addr, low, -before*BytesPerWord);
  3143     assert_different_registers(high, val);
  3144     if (after) addi(high, high, after * BytesPerWord);
  3145     Label loop;
  3146     bind(loop);
  3147     std(val, 0, addr);
  3148     addi(addr, addr, 8);
  3149     cmpd(CCR6, addr, high);
  3150     ble(CCR6, loop);
  3151     if (after) addi(high, high, -after * BytesPerWord);  // Correct back to old value.
  3153   BLOCK_COMMENT("} zap memory region");
  3156 #endif // !PRODUCT
  3158 SkipIfEqualZero::SkipIfEqualZero(MacroAssembler* masm, Register temp, const bool* flag_addr) : _masm(masm), _label() {
  3159   int simm16_offset = masm->load_const_optimized(temp, (address)flag_addr, R0, true);
  3160   assert(sizeof(bool) == 1, "PowerPC ABI");
  3161   masm->lbz(temp, simm16_offset, temp);
  3162   masm->cmpwi(CCR0, temp, 0);
  3163   masm->beq(CCR0, _label);
  3166 SkipIfEqualZero::~SkipIfEqualZero() {
  3167   _masm->bind(_label);

mercurial