1 /*
   2  * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2012, 2021 SAP SE. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 #include "asm/macroAssembler.inline.hpp"
  28 #include "code/debugInfoRec.hpp"
  29 #include "code/icBuffer.hpp"
  30 #include "code/vtableStubs.hpp"
  31 #include "frame_ppc.hpp"
  32 #include "compiler/oopMap.hpp"
  33 #include "gc/shared/gcLocker.hpp"
  34 #include "interpreter/interpreter.hpp"
  35 #include "interpreter/interp_masm.hpp"
  36 #include "memory/resourceArea.hpp"
  37 #include "oops/compiledICHolder.hpp"
  38 #include "oops/klass.inline.hpp"
  39 #include "prims/methodHandles.hpp"
  40 #include "runtime/jniHandles.hpp"
  41 #include "runtime/safepointMechanism.hpp"
  42 #include "runtime/sharedRuntime.hpp"
  43 #include "runtime/signature.hpp"
  44 #include "runtime/stubRoutines.hpp"
  45 #include "runtime/vframeArray.hpp"
  46 #include "utilities/align.hpp"
  47 #include "vmreg_ppc.inline.hpp"
  48 #ifdef COMPILER1
  49 #include "c1/c1_Runtime1.hpp"
  50 #endif
  51 #ifdef COMPILER2
  52 #include "opto/ad.hpp"
  53 #include "opto/runtime.hpp"
  54 #endif
  55 
  56 #include <alloca.h>
  57 
  58 #define __ masm->
  59 
  60 #ifdef PRODUCT
  61 #define BLOCK_COMMENT(str) // nothing
  62 #else
  63 #define BLOCK_COMMENT(str) __ block_comment(str)
  64 #endif
  65 
  66 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  67 
  68 
  69 class RegisterSaver {
  70  // Used for saving volatile registers.
  71  public:
  72 
  73   // Support different return pc locations.
  74   enum ReturnPCLocation {
  75     return_pc_is_lr,
  76     return_pc_is_pre_saved,
  77     return_pc_is_thread_saved_exception_pc
  78   };
  79 
  80   static OopMap* push_frame_reg_args_and_save_live_registers(MacroAssembler* masm,
  81                          int* out_frame_size_in_bytes,
  82                          bool generate_oop_map,
  83                          int return_pc_adjustment,
  84                          ReturnPCLocation return_pc_location,
  85                          bool save_vectors = false);
  86   static void    restore_live_registers_and_pop_frame(MacroAssembler* masm,
  87                          int frame_size_in_bytes,
  88                          bool restore_ctr,
  89                          bool save_vectors = false);
  90 
  91   static void push_frame_and_save_argument_registers(MacroAssembler* masm,
  92                          Register r_temp,
  93                          int frame_size,
  94                          int total_args,
  95                          const VMRegPair *regs, const VMRegPair *regs2 = NULL);
  96   static void restore_argument_registers_and_pop_frame(MacroAssembler*masm,
  97                          int frame_size,
  98                          int total_args,
  99                          const VMRegPair *regs, const VMRegPair *regs2 = NULL);
 100 
 101   // During deoptimization only the result registers need to be restored
 102   // all the other values have already been extracted.
 103   static void restore_result_registers(MacroAssembler* masm, int frame_size_in_bytes);
 104 
 105   // Constants and data structures:
 106 
 107   typedef enum {
 108     int_reg,
 109     float_reg,
 110     special_reg,
 111     vs_reg
 112   } RegisterType;
 113 
 114   typedef enum {
 115     reg_size          = 8,
 116     half_reg_size     = reg_size / 2,
 117     vs_reg_size       = 16
 118   } RegisterConstants;
 119 
 120   typedef struct {
 121     RegisterType        reg_type;
 122     int                 reg_num;
 123     VMReg               vmreg;
 124   } LiveRegType;
 125 };
 126 
 127 
 128 #define RegisterSaver_LiveIntReg(regname) \
 129   { RegisterSaver::int_reg,     regname->encoding(), regname->as_VMReg() }
 130 
 131 #define RegisterSaver_LiveFloatReg(regname) \
 132   { RegisterSaver::float_reg,   regname->encoding(), regname->as_VMReg() }
 133 
 134 #define RegisterSaver_LiveSpecialReg(regname) \
 135   { RegisterSaver::special_reg, regname->encoding(), regname->as_VMReg() }
 136 
 137 #define RegisterSaver_LiveVSReg(regname) \
 138   { RegisterSaver::vs_reg,      regname->encoding(), regname->as_VMReg() }
 139 
 140 static const RegisterSaver::LiveRegType RegisterSaver_LiveRegs[] = {
 141   // Live registers which get spilled to the stack. Register
 142   // positions in this array correspond directly to the stack layout.
 143 
 144   //
 145   // live special registers:
 146   //
 147   RegisterSaver_LiveSpecialReg(SR_CTR),
 148   //
 149   // live float registers:
 150   //
 151   RegisterSaver_LiveFloatReg( F0  ),
 152   RegisterSaver_LiveFloatReg( F1  ),
 153   RegisterSaver_LiveFloatReg( F2  ),
 154   RegisterSaver_LiveFloatReg( F3  ),
 155   RegisterSaver_LiveFloatReg( F4  ),
 156   RegisterSaver_LiveFloatReg( F5  ),
 157   RegisterSaver_LiveFloatReg( F6  ),
 158   RegisterSaver_LiveFloatReg( F7  ),
 159   RegisterSaver_LiveFloatReg( F8  ),
 160   RegisterSaver_LiveFloatReg( F9  ),
 161   RegisterSaver_LiveFloatReg( F10 ),
 162   RegisterSaver_LiveFloatReg( F11 ),
 163   RegisterSaver_LiveFloatReg( F12 ),
 164   RegisterSaver_LiveFloatReg( F13 ),
 165   RegisterSaver_LiveFloatReg( F14 ),
 166   RegisterSaver_LiveFloatReg( F15 ),
 167   RegisterSaver_LiveFloatReg( F16 ),
 168   RegisterSaver_LiveFloatReg( F17 ),
 169   RegisterSaver_LiveFloatReg( F18 ),
 170   RegisterSaver_LiveFloatReg( F19 ),
 171   RegisterSaver_LiveFloatReg( F20 ),
 172   RegisterSaver_LiveFloatReg( F21 ),
 173   RegisterSaver_LiveFloatReg( F22 ),
 174   RegisterSaver_LiveFloatReg( F23 ),
 175   RegisterSaver_LiveFloatReg( F24 ),
 176   RegisterSaver_LiveFloatReg( F25 ),
 177   RegisterSaver_LiveFloatReg( F26 ),
 178   RegisterSaver_LiveFloatReg( F27 ),
 179   RegisterSaver_LiveFloatReg( F28 ),
 180   RegisterSaver_LiveFloatReg( F29 ),
 181   RegisterSaver_LiveFloatReg( F30 ),
 182   RegisterSaver_LiveFloatReg( F31 ),
 183   //
 184   // live integer registers:
 185   //
 186   RegisterSaver_LiveIntReg(   R0  ),
 187   //RegisterSaver_LiveIntReg( R1  ), // stack pointer
 188   RegisterSaver_LiveIntReg(   R2  ),
 189   RegisterSaver_LiveIntReg(   R3  ),
 190   RegisterSaver_LiveIntReg(   R4  ),
 191   RegisterSaver_LiveIntReg(   R5  ),
 192   RegisterSaver_LiveIntReg(   R6  ),
 193   RegisterSaver_LiveIntReg(   R7  ),
 194   RegisterSaver_LiveIntReg(   R8  ),
 195   RegisterSaver_LiveIntReg(   R9  ),
 196   RegisterSaver_LiveIntReg(   R10 ),
 197   RegisterSaver_LiveIntReg(   R11 ),
 198   RegisterSaver_LiveIntReg(   R12 ),
 199   //RegisterSaver_LiveIntReg( R13 ), // system thread id
 200   RegisterSaver_LiveIntReg(   R14 ),
 201   RegisterSaver_LiveIntReg(   R15 ),
 202   RegisterSaver_LiveIntReg(   R16 ),
 203   RegisterSaver_LiveIntReg(   R17 ),
 204   RegisterSaver_LiveIntReg(   R18 ),
 205   RegisterSaver_LiveIntReg(   R19 ),
 206   RegisterSaver_LiveIntReg(   R20 ),
 207   RegisterSaver_LiveIntReg(   R21 ),
 208   RegisterSaver_LiveIntReg(   R22 ),
 209   RegisterSaver_LiveIntReg(   R23 ),
 210   RegisterSaver_LiveIntReg(   R24 ),
 211   RegisterSaver_LiveIntReg(   R25 ),
 212   RegisterSaver_LiveIntReg(   R26 ),
 213   RegisterSaver_LiveIntReg(   R27 ),
 214   RegisterSaver_LiveIntReg(   R28 ),
 215   RegisterSaver_LiveIntReg(   R29 ),
 216   RegisterSaver_LiveIntReg(   R30 ),
 217   RegisterSaver_LiveIntReg(   R31 )  // must be the last register (see save/restore functions below)
 218 };
 219 
 220 static const RegisterSaver::LiveRegType RegisterSaver_LiveVSRegs[] = {
 221   //
 222   // live vector scalar registers (optional, only these ones are used by C2):
 223   //
 224   RegisterSaver_LiveVSReg( VSR32 ),
 225   RegisterSaver_LiveVSReg( VSR33 ),
 226   RegisterSaver_LiveVSReg( VSR34 ),
 227   RegisterSaver_LiveVSReg( VSR35 ),
 228   RegisterSaver_LiveVSReg( VSR36 ),
 229   RegisterSaver_LiveVSReg( VSR37 ),
 230   RegisterSaver_LiveVSReg( VSR38 ),
 231   RegisterSaver_LiveVSReg( VSR39 ),
 232   RegisterSaver_LiveVSReg( VSR40 ),
 233   RegisterSaver_LiveVSReg( VSR41 ),
 234   RegisterSaver_LiveVSReg( VSR42 ),
 235   RegisterSaver_LiveVSReg( VSR43 ),
 236   RegisterSaver_LiveVSReg( VSR44 ),
 237   RegisterSaver_LiveVSReg( VSR45 ),
 238   RegisterSaver_LiveVSReg( VSR46 ),
 239   RegisterSaver_LiveVSReg( VSR47 ),
 240   RegisterSaver_LiveVSReg( VSR48 ),
 241   RegisterSaver_LiveVSReg( VSR49 ),
 242   RegisterSaver_LiveVSReg( VSR50 ),
 243   RegisterSaver_LiveVSReg( VSR51 )
 244 };
 245 
 246 
 247 OopMap* RegisterSaver::push_frame_reg_args_and_save_live_registers(MacroAssembler* masm,
 248                          int* out_frame_size_in_bytes,
 249                          bool generate_oop_map,
 250                          int return_pc_adjustment,
 251                          ReturnPCLocation return_pc_location,
 252                          bool save_vectors) {
 253   // Push an abi_reg_args-frame and store all registers which may be live.
 254   // If requested, create an OopMap: Record volatile registers as
 255   // callee-save values in an OopMap so their save locations will be
 256   // propagated to the RegisterMap of the caller frame during
 257   // StackFrameStream construction (needed for deoptimization; see
 258   // compiledVFrame::create_stack_value).
 259   // If return_pc_adjustment != 0 adjust the return pc by return_pc_adjustment.
 260   // Updated return pc is returned in R31 (if not return_pc_is_pre_saved).
 261 
 262   // calcualte frame size
 263   const int regstosave_num       = sizeof(RegisterSaver_LiveRegs) /
 264                                    sizeof(RegisterSaver::LiveRegType);
 265   const int vsregstosave_num     = save_vectors ? (sizeof(RegisterSaver_LiveVSRegs) /
 266                                                    sizeof(RegisterSaver::LiveRegType))
 267                                                 : 0;
 268   const int register_save_size   = regstosave_num * reg_size + vsregstosave_num * vs_reg_size;
 269   const int frame_size_in_bytes  = align_up(register_save_size, frame::alignment_in_bytes)
 270                                    + frame::abi_reg_args_size;
 271 
 272   *out_frame_size_in_bytes       = frame_size_in_bytes;
 273   const int frame_size_in_slots  = frame_size_in_bytes / sizeof(jint);
 274   const int register_save_offset = frame_size_in_bytes - register_save_size;
 275 
 276   // OopMap frame size is in c2 stack slots (sizeof(jint)) not bytes or words.
 277   OopMap* map = generate_oop_map ? new OopMap(frame_size_in_slots, 0) : NULL;
 278 
 279   BLOCK_COMMENT("push_frame_reg_args_and_save_live_registers {");
 280 
 281   // push a new frame
 282   __ push_frame(frame_size_in_bytes, noreg);
 283 
 284   // Save some registers in the last (non-vector) slots of the new frame so we
 285   // can use them as scratch regs or to determine the return pc.
 286   __ std(R31, frame_size_in_bytes -   reg_size - vsregstosave_num * vs_reg_size, R1_SP);
 287   __ std(R30, frame_size_in_bytes - 2*reg_size - vsregstosave_num * vs_reg_size, R1_SP);
 288 
 289   // save the flags
 290   // Do the save_LR_CR by hand and adjust the return pc if requested.
 291   __ mfcr(R30);
 292   __ std(R30, frame_size_in_bytes + _abi0(cr), R1_SP);
 293   switch (return_pc_location) {
 294     case return_pc_is_lr: __ mflr(R31); break;
 295     case return_pc_is_pre_saved: assert(return_pc_adjustment == 0, "unsupported"); break;
 296     case return_pc_is_thread_saved_exception_pc: __ ld(R31, thread_(saved_exception_pc)); break;
 297     default: ShouldNotReachHere();
 298   }
 299   if (return_pc_location != return_pc_is_pre_saved) {
 300     if (return_pc_adjustment != 0) {
 301       __ addi(R31, R31, return_pc_adjustment);
 302     }
 303     __ std(R31, frame_size_in_bytes + _abi0(lr), R1_SP);
 304   }
 305 
 306   // save all registers (ints and floats)
 307   int offset = register_save_offset;
 308 
 309   for (int i = 0; i < regstosave_num; i++) {
 310     int reg_num  = RegisterSaver_LiveRegs[i].reg_num;
 311     int reg_type = RegisterSaver_LiveRegs[i].reg_type;
 312 
 313     switch (reg_type) {
 314       case RegisterSaver::int_reg: {
 315         if (reg_num < 30) { // We spilled R30-31 right at the beginning.
 316           __ std(as_Register(reg_num), offset, R1_SP);
 317         }
 318         break;
 319       }
 320       case RegisterSaver::float_reg: {
 321         __ stfd(as_FloatRegister(reg_num), offset, R1_SP);
 322         break;
 323       }
 324       case RegisterSaver::special_reg: {
 325         if (reg_num == SR_CTR_SpecialRegisterEnumValue) {
 326           __ mfctr(R30);
 327           __ std(R30, offset, R1_SP);
 328         } else {
 329           Unimplemented();
 330         }
 331         break;
 332       }
 333       default:
 334         ShouldNotReachHere();
 335     }
 336 
 337     if (generate_oop_map) {
 338       map->set_callee_saved(VMRegImpl::stack2reg(offset>>2),
 339                             RegisterSaver_LiveRegs[i].vmreg);
 340       map->set_callee_saved(VMRegImpl::stack2reg((offset + half_reg_size)>>2),
 341                             RegisterSaver_LiveRegs[i].vmreg->next());
 342     }
 343     offset += reg_size;
 344   }
 345 
 346   for (int i = 0; i < vsregstosave_num; i++) {
 347     int reg_num  = RegisterSaver_LiveVSRegs[i].reg_num;
 348     int reg_type = RegisterSaver_LiveVSRegs[i].reg_type;
 349 
 350     __ li(R30, offset);
 351     __ stxvd2x(as_VectorSRegister(reg_num), R30, R1_SP);
 352 
 353     if (generate_oop_map) {
 354       map->set_callee_saved(VMRegImpl::stack2reg(offset>>2),
 355                             RegisterSaver_LiveVSRegs[i].vmreg);
 356     }
 357     offset += vs_reg_size;
 358   }
 359 
 360   assert(offset == frame_size_in_bytes, "consistency check");
 361 
 362   BLOCK_COMMENT("} push_frame_reg_args_and_save_live_registers");
 363 
 364   // And we're done.
 365   return map;
 366 }
 367 
 368 
 369 // Pop the current frame and restore all the registers that we
 370 // saved.
 371 void RegisterSaver::restore_live_registers_and_pop_frame(MacroAssembler* masm,
 372                                                          int frame_size_in_bytes,
 373                                                          bool restore_ctr,
 374                                                          bool save_vectors) {
 375   const int regstosave_num       = sizeof(RegisterSaver_LiveRegs) /
 376                                    sizeof(RegisterSaver::LiveRegType);
 377   const int vsregstosave_num     = save_vectors ? (sizeof(RegisterSaver_LiveVSRegs) /
 378                                                    sizeof(RegisterSaver::LiveRegType))
 379                                                 : 0;
 380   const int register_save_size   = regstosave_num * reg_size + vsregstosave_num * vs_reg_size;
 381 
 382   const int register_save_offset = frame_size_in_bytes - register_save_size;
 383 
 384   BLOCK_COMMENT("restore_live_registers_and_pop_frame {");
 385 
 386   // restore all registers (ints and floats)
 387   int offset = register_save_offset;
 388 
 389   for (int i = 0; i < regstosave_num; i++) {
 390     int reg_num  = RegisterSaver_LiveRegs[i].reg_num;
 391     int reg_type = RegisterSaver_LiveRegs[i].reg_type;
 392 
 393     switch (reg_type) {
 394       case RegisterSaver::int_reg: {
 395         if (reg_num != 31) // R31 restored at the end, it's the tmp reg!
 396           __ ld(as_Register(reg_num), offset, R1_SP);
 397         break;
 398       }
 399       case RegisterSaver::float_reg: {
 400         __ lfd(as_FloatRegister(reg_num), offset, R1_SP);
 401         break;
 402       }
 403       case RegisterSaver::special_reg: {
 404         if (reg_num == SR_CTR_SpecialRegisterEnumValue) {
 405           if (restore_ctr) { // Nothing to do here if ctr already contains the next address.
 406             __ ld(R31, offset, R1_SP);
 407             __ mtctr(R31);
 408           }
 409         } else {
 410           Unimplemented();
 411         }
 412         break;
 413       }
 414       default:
 415         ShouldNotReachHere();
 416     }
 417     offset += reg_size;
 418   }
 419 
 420   for (int i = 0; i < vsregstosave_num; i++) {
 421     int reg_num  = RegisterSaver_LiveVSRegs[i].reg_num;
 422     int reg_type = RegisterSaver_LiveVSRegs[i].reg_type;
 423 
 424     __ li(R31, offset);
 425     __ lxvd2x(as_VectorSRegister(reg_num), R31, R1_SP);
 426 
 427     offset += vs_reg_size;
 428   }
 429 
 430   assert(offset == frame_size_in_bytes, "consistency check");
 431 
 432   // restore link and the flags
 433   __ ld(R31, frame_size_in_bytes + _abi0(lr), R1_SP);
 434   __ mtlr(R31);
 435 
 436   __ ld(R31, frame_size_in_bytes + _abi0(cr), R1_SP);
 437   __ mtcr(R31);
 438 
 439   // restore scratch register's value
 440   __ ld(R31, frame_size_in_bytes - reg_size - vsregstosave_num * vs_reg_size, R1_SP);
 441 
 442   // pop the frame
 443   __ addi(R1_SP, R1_SP, frame_size_in_bytes);
 444 
 445   BLOCK_COMMENT("} restore_live_registers_and_pop_frame");
 446 }
 447 
 448 void RegisterSaver::push_frame_and_save_argument_registers(MacroAssembler* masm, Register r_temp,
 449                                                            int frame_size,int total_args, const VMRegPair *regs,
 450                                                            const VMRegPair *regs2) {
 451   __ push_frame(frame_size, r_temp);
 452   int st_off = frame_size - wordSize;
 453   for (int i = 0; i < total_args; i++) {
 454     VMReg r_1 = regs[i].first();
 455     VMReg r_2 = regs[i].second();
 456     if (!r_1->is_valid()) {
 457       assert(!r_2->is_valid(), "");
 458       continue;
 459     }
 460     if (r_1->is_Register()) {
 461       Register r = r_1->as_Register();
 462       __ std(r, st_off, R1_SP);
 463       st_off -= wordSize;
 464     } else if (r_1->is_FloatRegister()) {
 465       FloatRegister f = r_1->as_FloatRegister();
 466       __ stfd(f, st_off, R1_SP);
 467       st_off -= wordSize;
 468     }
 469   }
 470   if (regs2 != NULL) {
 471     for (int i = 0; i < total_args; i++) {
 472       VMReg r_1 = regs2[i].first();
 473       VMReg r_2 = regs2[i].second();
 474       if (!r_1->is_valid()) {
 475         assert(!r_2->is_valid(), "");
 476         continue;
 477       }
 478       if (r_1->is_Register()) {
 479         Register r = r_1->as_Register();
 480         __ std(r, st_off, R1_SP);
 481         st_off -= wordSize;
 482       } else if (r_1->is_FloatRegister()) {
 483         FloatRegister f = r_1->as_FloatRegister();
 484         __ stfd(f, st_off, R1_SP);
 485         st_off -= wordSize;
 486       }
 487     }
 488   }
 489 }
 490 
 491 void RegisterSaver::restore_argument_registers_and_pop_frame(MacroAssembler*masm, int frame_size,
 492                                                              int total_args, const VMRegPair *regs,
 493                                                              const VMRegPair *regs2) {
 494   int st_off = frame_size - wordSize;
 495   for (int i = 0; i < total_args; i++) {
 496     VMReg r_1 = regs[i].first();
 497     VMReg r_2 = regs[i].second();
 498     if (r_1->is_Register()) {
 499       Register r = r_1->as_Register();
 500       __ ld(r, st_off, R1_SP);
 501       st_off -= wordSize;
 502     } else if (r_1->is_FloatRegister()) {
 503       FloatRegister f = r_1->as_FloatRegister();
 504       __ lfd(f, st_off, R1_SP);
 505       st_off -= wordSize;
 506     }
 507   }
 508   if (regs2 != NULL)
 509     for (int i = 0; i < total_args; i++) {
 510       VMReg r_1 = regs2[i].first();
 511       VMReg r_2 = regs2[i].second();
 512       if (r_1->is_Register()) {
 513         Register r = r_1->as_Register();
 514         __ ld(r, st_off, R1_SP);
 515         st_off -= wordSize;
 516       } else if (r_1->is_FloatRegister()) {
 517         FloatRegister f = r_1->as_FloatRegister();
 518         __ lfd(f, st_off, R1_SP);
 519         st_off -= wordSize;
 520       }
 521     }
 522   __ pop_frame();
 523 }
 524 
 525 // Restore the registers that might be holding a result.
 526 void RegisterSaver::restore_result_registers(MacroAssembler* masm, int frame_size_in_bytes) {
 527   const int regstosave_num       = sizeof(RegisterSaver_LiveRegs) /
 528                                    sizeof(RegisterSaver::LiveRegType);
 529   const int register_save_size   = regstosave_num * reg_size; // VS registers not relevant here.
 530   const int register_save_offset = frame_size_in_bytes - register_save_size;
 531 
 532   // restore all result registers (ints and floats)
 533   int offset = register_save_offset;
 534   for (int i = 0; i < regstosave_num; i++) {
 535     int reg_num  = RegisterSaver_LiveRegs[i].reg_num;
 536     int reg_type = RegisterSaver_LiveRegs[i].reg_type;
 537     switch (reg_type) {
 538       case RegisterSaver::int_reg: {
 539         if (as_Register(reg_num)==R3_RET) // int result_reg
 540           __ ld(as_Register(reg_num), offset, R1_SP);
 541         break;
 542       }
 543       case RegisterSaver::float_reg: {
 544         if (as_FloatRegister(reg_num)==F1_RET) // float result_reg
 545           __ lfd(as_FloatRegister(reg_num), offset, R1_SP);
 546         break;
 547       }
 548       case RegisterSaver::special_reg: {
 549         // Special registers don't hold a result.
 550         break;
 551       }
 552       default:
 553         ShouldNotReachHere();
 554     }
 555     offset += reg_size;
 556   }
 557 
 558   assert(offset == frame_size_in_bytes, "consistency check");
 559 }
 560 
 561 // Is vector's size (in bytes) bigger than a size saved by default?
 562 bool SharedRuntime::is_wide_vector(int size) {
 563   // Note, MaxVectorSize == 8/16 on PPC64.
 564   assert(size <= (SuperwordUseVSX ? 16 : 8), "%d bytes vectors are not supported", size);
 565   return size > 8;
 566 }
 567 
 568 static int reg2slot(VMReg r) {
 569   return r->reg2stack() + SharedRuntime::out_preserve_stack_slots();
 570 }
 571 
 572 static int reg2offset(VMReg r) {
 573   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
 574 }
 575 
 576 // ---------------------------------------------------------------------------
 577 // Read the array of BasicTypes from a signature, and compute where the
 578 // arguments should go. Values in the VMRegPair regs array refer to 4-byte
 579 // quantities. Values less than VMRegImpl::stack0 are registers, those above
 580 // refer to 4-byte stack slots. All stack slots are based off of the stack pointer
 581 // as framesizes are fixed.
 582 // VMRegImpl::stack0 refers to the first slot 0(sp).
 583 // and VMRegImpl::stack0+1 refers to the memory word 4-bytes higher. Register
 584 // up to RegisterImpl::number_of_registers) are the 64-bit
 585 // integer registers.
 586 
 587 // Note: the INPUTS in sig_bt are in units of Java argument words, which are
 588 // either 32-bit or 64-bit depending on the build. The OUTPUTS are in 32-bit
 589 // units regardless of build. Of course for i486 there is no 64 bit build
 590 
 591 // The Java calling convention is a "shifted" version of the C ABI.
 592 // By skipping the first C ABI register we can call non-static jni methods
 593 // with small numbers of arguments without having to shuffle the arguments
 594 // at all. Since we control the java ABI we ought to at least get some
 595 // advantage out of it.
 596 
 597 const VMReg java_iarg_reg[8] = {
 598   R3->as_VMReg(),
 599   R4->as_VMReg(),
 600   R5->as_VMReg(),
 601   R6->as_VMReg(),
 602   R7->as_VMReg(),
 603   R8->as_VMReg(),
 604   R9->as_VMReg(),
 605   R10->as_VMReg()
 606 };
 607 
 608 const VMReg java_farg_reg[13] = {
 609   F1->as_VMReg(),
 610   F2->as_VMReg(),
 611   F3->as_VMReg(),
 612   F4->as_VMReg(),
 613   F5->as_VMReg(),
 614   F6->as_VMReg(),
 615   F7->as_VMReg(),
 616   F8->as_VMReg(),
 617   F9->as_VMReg(),
 618   F10->as_VMReg(),
 619   F11->as_VMReg(),
 620   F12->as_VMReg(),
 621   F13->as_VMReg()
 622 };
 623 
 624 const int num_java_iarg_registers = sizeof(java_iarg_reg) / sizeof(java_iarg_reg[0]);
 625 const int num_java_farg_registers = sizeof(java_farg_reg) / sizeof(java_farg_reg[0]);
 626 
 627 int SharedRuntime::java_calling_convention(const BasicType *sig_bt,
 628                                            VMRegPair *regs,
 629                                            int total_args_passed) {
 630   // C2c calling conventions for compiled-compiled calls.
 631   // Put 8 ints/longs into registers _AND_ 13 float/doubles into
 632   // registers _AND_ put the rest on the stack.
 633 
 634   const int inc_stk_for_intfloat   = 1; // 1 slots for ints and floats
 635   const int inc_stk_for_longdouble = 2; // 2 slots for longs and doubles
 636 
 637   int i;
 638   VMReg reg;
 639   int stk = 0;
 640   int ireg = 0;
 641   int freg = 0;
 642 
 643   // We put the first 8 arguments into registers and the rest on the
 644   // stack, float arguments are already in their argument registers
 645   // due to c2c calling conventions (see calling_convention).
 646   for (int i = 0; i < total_args_passed; ++i) {
 647     switch(sig_bt[i]) {
 648     case T_BOOLEAN:
 649     case T_CHAR:
 650     case T_BYTE:
 651     case T_SHORT:
 652     case T_INT:
 653       if (ireg < num_java_iarg_registers) {
 654         // Put int/ptr in register
 655         reg = java_iarg_reg[ireg];
 656         ++ireg;
 657       } else {
 658         // Put int/ptr on stack.
 659         reg = VMRegImpl::stack2reg(stk);
 660         stk += inc_stk_for_intfloat;
 661       }
 662       regs[i].set1(reg);
 663       break;
 664     case T_LONG:
 665       assert((i + 1) < total_args_passed && sig_bt[i+1] == T_VOID, "expecting half");
 666       if (ireg < num_java_iarg_registers) {
 667         // Put long in register.
 668         reg = java_iarg_reg[ireg];
 669         ++ireg;
 670       } else {
 671         // Put long on stack. They must be aligned to 2 slots.
 672         if (stk & 0x1) ++stk;
 673         reg = VMRegImpl::stack2reg(stk);
 674         stk += inc_stk_for_longdouble;
 675       }
 676       regs[i].set2(reg);
 677       break;
 678     case T_OBJECT:
 679     case T_ARRAY:
 680     case T_ADDRESS:
 681       if (ireg < num_java_iarg_registers) {
 682         // Put ptr in register.
 683         reg = java_iarg_reg[ireg];
 684         ++ireg;
 685       } else {
 686         // Put ptr on stack. Objects must be aligned to 2 slots too,
 687         // because "64-bit pointers record oop-ishness on 2 aligned
 688         // adjacent registers." (see OopFlow::build_oop_map).
 689         if (stk & 0x1) ++stk;
 690         reg = VMRegImpl::stack2reg(stk);
 691         stk += inc_stk_for_longdouble;
 692       }
 693       regs[i].set2(reg);
 694       break;
 695     case T_FLOAT:
 696       if (freg < num_java_farg_registers) {
 697         // Put float in register.
 698         reg = java_farg_reg[freg];
 699         ++freg;
 700       } else {
 701         // Put float on stack.
 702         reg = VMRegImpl::stack2reg(stk);
 703         stk += inc_stk_for_intfloat;
 704       }
 705       regs[i].set1(reg);
 706       break;
 707     case T_DOUBLE:
 708       assert((i + 1) < total_args_passed && sig_bt[i+1] == T_VOID, "expecting half");
 709       if (freg < num_java_farg_registers) {
 710         // Put double in register.
 711         reg = java_farg_reg[freg];
 712         ++freg;
 713       } else {
 714         // Put double on stack. They must be aligned to 2 slots.
 715         if (stk & 0x1) ++stk;
 716         reg = VMRegImpl::stack2reg(stk);
 717         stk += inc_stk_for_longdouble;
 718       }
 719       regs[i].set2(reg);
 720       break;
 721     case T_VOID:
 722       // Do not count halves.
 723       regs[i].set_bad();
 724       break;
 725     default:
 726       ShouldNotReachHere();
 727     }
 728   }
 729   return align_up(stk, 2);
 730 }
 731 
 732 #if defined(COMPILER1) || defined(COMPILER2)
 733 // Calling convention for calling C code.
 734 int SharedRuntime::c_calling_convention(const BasicType *sig_bt,
 735                                         VMRegPair *regs,
 736                                         VMRegPair *regs2,
 737                                         int total_args_passed) {
 738   // Calling conventions for C runtime calls and calls to JNI native methods.
 739   //
 740   // PPC64 convention: Hoist the first 8 int/ptr/long's in the first 8
 741   // int regs, leaving int regs undefined if the arg is flt/dbl. Hoist
 742   // the first 13 flt/dbl's in the first 13 fp regs but additionally
 743   // copy flt/dbl to the stack if they are beyond the 8th argument.
 744 
 745   const VMReg iarg_reg[8] = {
 746     R3->as_VMReg(),
 747     R4->as_VMReg(),
 748     R5->as_VMReg(),
 749     R6->as_VMReg(),
 750     R7->as_VMReg(),
 751     R8->as_VMReg(),
 752     R9->as_VMReg(),
 753     R10->as_VMReg()
 754   };
 755 
 756   const VMReg farg_reg[13] = {
 757     F1->as_VMReg(),
 758     F2->as_VMReg(),
 759     F3->as_VMReg(),
 760     F4->as_VMReg(),
 761     F5->as_VMReg(),
 762     F6->as_VMReg(),
 763     F7->as_VMReg(),
 764     F8->as_VMReg(),
 765     F9->as_VMReg(),
 766     F10->as_VMReg(),
 767     F11->as_VMReg(),
 768     F12->as_VMReg(),
 769     F13->as_VMReg()
 770   };
 771 
 772   // Check calling conventions consistency.
 773   assert(sizeof(iarg_reg) / sizeof(iarg_reg[0]) == Argument::n_int_register_parameters_c &&
 774          sizeof(farg_reg) / sizeof(farg_reg[0]) == Argument::n_float_register_parameters_c,
 775          "consistency");
 776 
 777   // `Stk' counts stack slots. Due to alignment, 32 bit values occupy
 778   // 2 such slots, like 64 bit values do.
 779   const int inc_stk_for_intfloat   = 2; // 2 slots for ints and floats
 780   const int inc_stk_for_longdouble = 2; // 2 slots for longs and doubles
 781 
 782   int i;
 783   VMReg reg;
 784   // Leave room for C-compatible ABI_REG_ARGS.
 785   int stk = (frame::abi_reg_args_size - frame::jit_out_preserve_size) / VMRegImpl::stack_slot_size;
 786   int arg = 0;
 787   int freg = 0;
 788 
 789   // Avoid passing C arguments in the wrong stack slots.
 790 #if defined(ABI_ELFv2)
 791   assert((SharedRuntime::out_preserve_stack_slots() + stk) * VMRegImpl::stack_slot_size == 96,
 792          "passing C arguments in wrong stack slots");
 793 #else
 794   assert((SharedRuntime::out_preserve_stack_slots() + stk) * VMRegImpl::stack_slot_size == 112,
 795          "passing C arguments in wrong stack slots");
 796 #endif
 797   // We fill-out regs AND regs2 if an argument must be passed in a
 798   // register AND in a stack slot. If regs2 is NULL in such a
 799   // situation, we bail-out with a fatal error.
 800   for (int i = 0; i < total_args_passed; ++i, ++arg) {
 801     // Initialize regs2 to BAD.
 802     if (regs2 != NULL) regs2[i].set_bad();
 803 
 804     switch(sig_bt[i]) {
 805 
 806     //
 807     // If arguments 0-7 are integers, they are passed in integer registers.
 808     // Argument i is placed in iarg_reg[i].
 809     //
 810     case T_BOOLEAN:
 811     case T_CHAR:
 812     case T_BYTE:
 813     case T_SHORT:
 814     case T_INT:
 815       // We must cast ints to longs and use full 64 bit stack slots
 816       // here.  Thus fall through, handle as long.
 817     case T_LONG:
 818     case T_OBJECT:
 819     case T_ARRAY:
 820     case T_ADDRESS:
 821     case T_METADATA:
 822       // Oops are already boxed if required (JNI).
 823       if (arg < Argument::n_int_register_parameters_c) {
 824         reg = iarg_reg[arg];
 825       } else {
 826         reg = VMRegImpl::stack2reg(stk);
 827         stk += inc_stk_for_longdouble;
 828       }
 829       regs[i].set2(reg);
 830       break;
 831 
 832     //
 833     // Floats are treated differently from int regs:  The first 13 float arguments
 834     // are passed in registers (not the float args among the first 13 args).
 835     // Thus argument i is NOT passed in farg_reg[i] if it is float.  It is passed
 836     // in farg_reg[j] if argument i is the j-th float argument of this call.
 837     //
 838     case T_FLOAT:
 839 #if defined(LINUX)
 840       // Linux uses ELF ABI. Both original ELF and ELFv2 ABIs have float
 841       // in the least significant word of an argument slot.
 842 #if defined(VM_LITTLE_ENDIAN)
 843 #define FLOAT_WORD_OFFSET_IN_SLOT 0
 844 #else
 845 #define FLOAT_WORD_OFFSET_IN_SLOT 1
 846 #endif
 847 #elif defined(AIX)
 848       // Although AIX runs on big endian CPU, float is in the most
 849       // significant word of an argument slot.
 850 #define FLOAT_WORD_OFFSET_IN_SLOT 0
 851 #else
 852 #error "unknown OS"
 853 #endif
 854       if (freg < Argument::n_float_register_parameters_c) {
 855         // Put float in register ...
 856         reg = farg_reg[freg];
 857         ++freg;
 858 
 859         // Argument i for i > 8 is placed on the stack even if it's
 860         // placed in a register (if it's a float arg). Aix disassembly
 861         // shows that xlC places these float args on the stack AND in
 862         // a register. This is not documented, but we follow this
 863         // convention, too.
 864         if (arg >= Argument::n_regs_not_on_stack_c) {
 865           // ... and on the stack.
 866           guarantee(regs2 != NULL, "must pass float in register and stack slot");
 867           VMReg reg2 = VMRegImpl::stack2reg(stk + FLOAT_WORD_OFFSET_IN_SLOT);
 868           regs2[i].set1(reg2);
 869           stk += inc_stk_for_intfloat;
 870         }
 871 
 872       } else {
 873         // Put float on stack.
 874         reg = VMRegImpl::stack2reg(stk + FLOAT_WORD_OFFSET_IN_SLOT);
 875         stk += inc_stk_for_intfloat;
 876       }
 877       regs[i].set1(reg);
 878       break;
 879     case T_DOUBLE:
 880       assert((i + 1) < total_args_passed && sig_bt[i+1] == T_VOID, "expecting half");
 881       if (freg < Argument::n_float_register_parameters_c) {
 882         // Put double in register ...
 883         reg = farg_reg[freg];
 884         ++freg;
 885 
 886         // Argument i for i > 8 is placed on the stack even if it's
 887         // placed in a register (if it's a double arg). Aix disassembly
 888         // shows that xlC places these float args on the stack AND in
 889         // a register. This is not documented, but we follow this
 890         // convention, too.
 891         if (arg >= Argument::n_regs_not_on_stack_c) {
 892           // ... and on the stack.
 893           guarantee(regs2 != NULL, "must pass float in register and stack slot");
 894           VMReg reg2 = VMRegImpl::stack2reg(stk);
 895           regs2[i].set2(reg2);
 896           stk += inc_stk_for_longdouble;
 897         }
 898       } else {
 899         // Put double on stack.
 900         reg = VMRegImpl::stack2reg(stk);
 901         stk += inc_stk_for_longdouble;
 902       }
 903       regs[i].set2(reg);
 904       break;
 905 
 906     case T_VOID:
 907       // Do not count halves.
 908       regs[i].set_bad();
 909       --arg;
 910       break;
 911     default:
 912       ShouldNotReachHere();
 913     }
 914   }
 915 
 916   return align_up(stk, 2);
 917 }
 918 #endif // COMPILER2
 919 
 920 int SharedRuntime::vector_calling_convention(VMRegPair *regs,
 921                                              uint num_bits,
 922                                              uint total_args_passed) {
 923   Unimplemented();
 924   return 0;
 925 }
 926 
 927 static address gen_c2i_adapter(MacroAssembler *masm,
 928                             int total_args_passed,
 929                             int comp_args_on_stack,
 930                             const BasicType *sig_bt,
 931                             const VMRegPair *regs,
 932                             Label& call_interpreter,
 933                             const Register& ientry) {
 934 
 935   address c2i_entrypoint;
 936 
 937   const Register sender_SP = R21_sender_SP; // == R21_tmp1
 938   const Register code      = R22_tmp2;
 939   //const Register ientry  = R23_tmp3;
 940   const Register value_regs[] = { R24_tmp4, R25_tmp5, R26_tmp6 };
 941   const int num_value_regs = sizeof(value_regs) / sizeof(Register);
 942   int value_regs_index = 0;
 943 
 944   const Register return_pc = R27_tmp7;
 945   const Register tmp       = R28_tmp8;
 946 
 947   assert_different_registers(sender_SP, code, ientry, return_pc, tmp);
 948 
 949   // Adapter needs TOP_IJAVA_FRAME_ABI.
 950   const int adapter_size = frame::top_ijava_frame_abi_size +
 951                            align_up(total_args_passed * wordSize, frame::alignment_in_bytes);
 952 
 953   // regular (verified) c2i entry point
 954   c2i_entrypoint = __ pc();
 955 
 956   // Does compiled code exists? If yes, patch the caller's callsite.
 957   __ ld(code, method_(code));
 958   __ cmpdi(CCR0, code, 0);
 959   __ ld(ientry, method_(interpreter_entry)); // preloaded
 960   __ beq(CCR0, call_interpreter);
 961 
 962 
 963   // Patch caller's callsite, method_(code) was not NULL which means that
 964   // compiled code exists.
 965   __ mflr(return_pc);
 966   __ std(return_pc, _abi0(lr), R1_SP);
 967   RegisterSaver::push_frame_and_save_argument_registers(masm, tmp, adapter_size, total_args_passed, regs);
 968 
 969   __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite), R19_method, return_pc);
 970 
 971   RegisterSaver::restore_argument_registers_and_pop_frame(masm, adapter_size, total_args_passed, regs);
 972   __ ld(return_pc, _abi0(lr), R1_SP);
 973   __ ld(ientry, method_(interpreter_entry)); // preloaded
 974   __ mtlr(return_pc);
 975 
 976 
 977   // Call the interpreter.
 978   __ BIND(call_interpreter);
 979   __ mtctr(ientry);
 980 
 981   // Get a copy of the current SP for loading caller's arguments.
 982   __ mr(sender_SP, R1_SP);
 983 
 984   // Add space for the adapter.
 985   __ resize_frame(-adapter_size, R12_scratch2);
 986 
 987   int st_off = adapter_size - wordSize;
 988 
 989   // Write the args into the outgoing interpreter space.
 990   for (int i = 0; i < total_args_passed; i++) {
 991     VMReg r_1 = regs[i].first();
 992     VMReg r_2 = regs[i].second();
 993     if (!r_1->is_valid()) {
 994       assert(!r_2->is_valid(), "");
 995       continue;
 996     }
 997     if (r_1->is_stack()) {
 998       Register tmp_reg = value_regs[value_regs_index];
 999       value_regs_index = (value_regs_index + 1) % num_value_regs;
1000       // The calling convention produces OptoRegs that ignore the out
1001       // preserve area (JIT's ABI). We must account for it here.
1002       int ld_off = (r_1->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
1003       if (!r_2->is_valid()) {
1004         __ lwz(tmp_reg, ld_off, sender_SP);
1005       } else {
1006         __ ld(tmp_reg, ld_off, sender_SP);
1007       }
1008       // Pretend stack targets were loaded into tmp_reg.
1009       r_1 = tmp_reg->as_VMReg();
1010     }
1011 
1012     if (r_1->is_Register()) {
1013       Register r = r_1->as_Register();
1014       if (!r_2->is_valid()) {
1015         __ stw(r, st_off, R1_SP);
1016         st_off-=wordSize;
1017       } else {
1018         // Longs are given 2 64-bit slots in the interpreter, but the
1019         // data is passed in only 1 slot.
1020         if (sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
1021           DEBUG_ONLY( __ li(tmp, 0); __ std(tmp, st_off, R1_SP); )
1022           st_off-=wordSize;
1023         }
1024         __ std(r, st_off, R1_SP);
1025         st_off-=wordSize;
1026       }
1027     } else {
1028       assert(r_1->is_FloatRegister(), "");
1029       FloatRegister f = r_1->as_FloatRegister();
1030       if (!r_2->is_valid()) {
1031         __ stfs(f, st_off, R1_SP);
1032         st_off-=wordSize;
1033       } else {
1034         // In 64bit, doubles are given 2 64-bit slots in the interpreter, but the
1035         // data is passed in only 1 slot.
1036         // One of these should get known junk...
1037         DEBUG_ONLY( __ li(tmp, 0); __ std(tmp, st_off, R1_SP); )
1038         st_off-=wordSize;
1039         __ stfd(f, st_off, R1_SP);
1040         st_off-=wordSize;
1041       }
1042     }
1043   }
1044 
1045   // Jump to the interpreter just as if interpreter was doing it.
1046 
1047   __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R11_scratch1);
1048 
1049   // load TOS
1050   __ addi(R15_esp, R1_SP, st_off);
1051 
1052   // Frame_manager expects initial_caller_sp (= SP without resize by c2i) in R21_tmp1.
1053   assert(sender_SP == R21_sender_SP, "passing initial caller's SP in wrong register");
1054   __ bctr();
1055 
1056   return c2i_entrypoint;
1057 }
1058 
1059 void SharedRuntime::gen_i2c_adapter(MacroAssembler *masm,
1060                                     int total_args_passed,
1061                                     int comp_args_on_stack,
1062                                     const BasicType *sig_bt,
1063                                     const VMRegPair *regs) {
1064 
1065   // Load method's entry-point from method.
1066   __ ld(R12_scratch2, in_bytes(Method::from_compiled_offset()), R19_method);
1067   __ mtctr(R12_scratch2);
1068 
1069   // We will only enter here from an interpreted frame and never from after
1070   // passing thru a c2i. Azul allowed this but we do not. If we lose the
1071   // race and use a c2i we will remain interpreted for the race loser(s).
1072   // This removes all sorts of headaches on the x86 side and also eliminates
1073   // the possibility of having c2i -> i2c -> c2i -> ... endless transitions.
1074 
1075   // Note: r13 contains the senderSP on entry. We must preserve it since
1076   // we may do a i2c -> c2i transition if we lose a race where compiled
1077   // code goes non-entrant while we get args ready.
1078   // In addition we use r13 to locate all the interpreter args as
1079   // we must align the stack to 16 bytes on an i2c entry else we
1080   // lose alignment we expect in all compiled code and register
1081   // save code can segv when fxsave instructions find improperly
1082   // aligned stack pointer.
1083 
1084   const Register ld_ptr = R15_esp;
1085   const Register value_regs[] = { R22_tmp2, R23_tmp3, R24_tmp4, R25_tmp5, R26_tmp6 };
1086   const int num_value_regs = sizeof(value_regs) / sizeof(Register);
1087   int value_regs_index = 0;
1088 
1089   int ld_offset = total_args_passed*wordSize;
1090 
1091   // Cut-out for having no stack args. Since up to 2 int/oop args are passed
1092   // in registers, we will occasionally have no stack args.
1093   int comp_words_on_stack = 0;
1094   if (comp_args_on_stack) {
1095     // Sig words on the stack are greater-than VMRegImpl::stack0. Those in
1096     // registers are below. By subtracting stack0, we either get a negative
1097     // number (all values in registers) or the maximum stack slot accessed.
1098 
1099     // Convert 4-byte c2 stack slots to words.
1100     comp_words_on_stack = align_up(comp_args_on_stack*VMRegImpl::stack_slot_size, wordSize)>>LogBytesPerWord;
1101     // Round up to miminum stack alignment, in wordSize.
1102     comp_words_on_stack = align_up(comp_words_on_stack, 2);
1103     __ resize_frame(-comp_words_on_stack * wordSize, R11_scratch1);
1104   }
1105 
1106   // Now generate the shuffle code.  Pick up all register args and move the
1107   // rest through register value=Z_R12.
1108   BLOCK_COMMENT("Shuffle arguments");
1109   for (int i = 0; i < total_args_passed; i++) {
1110     if (sig_bt[i] == T_VOID) {
1111       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
1112       continue;
1113     }
1114 
1115     // Pick up 0, 1 or 2 words from ld_ptr.
1116     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(),
1117             "scrambled load targets?");
1118     VMReg r_1 = regs[i].first();
1119     VMReg r_2 = regs[i].second();
1120     if (!r_1->is_valid()) {
1121       assert(!r_2->is_valid(), "");
1122       continue;
1123     }
1124     if (r_1->is_FloatRegister()) {
1125       if (!r_2->is_valid()) {
1126         __ lfs(r_1->as_FloatRegister(), ld_offset, ld_ptr);
1127         ld_offset-=wordSize;
1128       } else {
1129         // Skip the unused interpreter slot.
1130         __ lfd(r_1->as_FloatRegister(), ld_offset-wordSize, ld_ptr);
1131         ld_offset-=2*wordSize;
1132       }
1133     } else {
1134       Register r;
1135       if (r_1->is_stack()) {
1136         // Must do a memory to memory move thru "value".
1137         r = value_regs[value_regs_index];
1138         value_regs_index = (value_regs_index + 1) % num_value_regs;
1139       } else {
1140         r = r_1->as_Register();
1141       }
1142       if (!r_2->is_valid()) {
1143         // Not sure we need to do this but it shouldn't hurt.
1144         if (is_reference_type(sig_bt[i]) || sig_bt[i] == T_ADDRESS) {
1145           __ ld(r, ld_offset, ld_ptr);
1146           ld_offset-=wordSize;
1147         } else {
1148           __ lwz(r, ld_offset, ld_ptr);
1149           ld_offset-=wordSize;
1150         }
1151       } else {
1152         // In 64bit, longs are given 2 64-bit slots in the interpreter, but the
1153         // data is passed in only 1 slot.
1154         if (sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
1155           ld_offset-=wordSize;
1156         }
1157         __ ld(r, ld_offset, ld_ptr);
1158         ld_offset-=wordSize;
1159       }
1160 
1161       if (r_1->is_stack()) {
1162         // Now store value where the compiler expects it
1163         int st_off = (r_1->reg2stack() + SharedRuntime::out_preserve_stack_slots())*VMRegImpl::stack_slot_size;
1164 
1165         if (sig_bt[i] == T_INT   || sig_bt[i] == T_FLOAT ||sig_bt[i] == T_BOOLEAN ||
1166             sig_bt[i] == T_SHORT || sig_bt[i] == T_CHAR  || sig_bt[i] == T_BYTE) {
1167           __ stw(r, st_off, R1_SP);
1168         } else {
1169           __ std(r, st_off, R1_SP);
1170         }
1171       }
1172     }
1173   }
1174 
1175   BLOCK_COMMENT("Store method");
1176   // Store method into thread->callee_target.
1177   // We might end up in handle_wrong_method if the callee is
1178   // deoptimized as we race thru here. If that happens we don't want
1179   // to take a safepoint because the caller frame will look
1180   // interpreted and arguments are now "compiled" so it is much better
1181   // to make this transition invisible to the stack walking
1182   // code. Unfortunately if we try and find the callee by normal means
1183   // a safepoint is possible. So we stash the desired callee in the
1184   // thread and the vm will find there should this case occur.
1185   __ std(R19_method, thread_(callee_target));
1186 
1187   // Jump to the compiled code just as if compiled code was doing it.
1188   __ bctr();
1189 }
1190 
1191 AdapterHandlerEntry* SharedRuntime::generate_i2c2i_adapters(MacroAssembler *masm,
1192                                                             int total_args_passed,
1193                                                             int comp_args_on_stack,
1194                                                             const BasicType *sig_bt,
1195                                                             const VMRegPair *regs,
1196                                                             AdapterFingerPrint* fingerprint) {
1197   address i2c_entry;
1198   address c2i_unverified_entry;
1199   address c2i_entry;
1200 
1201 
1202   // entry: i2c
1203 
1204   __ align(CodeEntryAlignment);
1205   i2c_entry = __ pc();
1206   gen_i2c_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs);
1207 
1208 
1209   // entry: c2i unverified
1210 
1211   __ align(CodeEntryAlignment);
1212   BLOCK_COMMENT("c2i unverified entry");
1213   c2i_unverified_entry = __ pc();
1214 
1215   // inline_cache contains a compiledICHolder
1216   const Register ic             = R19_method;
1217   const Register ic_klass       = R11_scratch1;
1218   const Register receiver_klass = R12_scratch2;
1219   const Register code           = R21_tmp1;
1220   const Register ientry         = R23_tmp3;
1221 
1222   assert_different_registers(ic, ic_klass, receiver_klass, R3_ARG1, code, ientry);
1223   assert(R11_scratch1 == R11, "need prologue scratch register");
1224 
1225   Label call_interpreter;
1226 
1227   assert(!MacroAssembler::needs_explicit_null_check(oopDesc::klass_offset_in_bytes()),
1228          "klass offset should reach into any page");
1229   // Check for NULL argument if we don't have implicit null checks.
1230   if (!ImplicitNullChecks || !os::zero_page_read_protected()) {
1231     if (TrapBasedNullChecks) {
1232       __ trap_null_check(R3_ARG1);
1233     } else {
1234       Label valid;
1235       __ cmpdi(CCR0, R3_ARG1, 0);
1236       __ bne_predict_taken(CCR0, valid);
1237       // We have a null argument, branch to ic_miss_stub.
1238       __ b64_patchable((address)SharedRuntime::get_ic_miss_stub(),
1239                        relocInfo::runtime_call_type);
1240       __ BIND(valid);
1241     }
1242   }
1243   // Assume argument is not NULL, load klass from receiver.
1244   __ load_klass(receiver_klass, R3_ARG1);
1245 
1246   __ ld(ic_klass, CompiledICHolder::holder_klass_offset(), ic);
1247 
1248   if (TrapBasedICMissChecks) {
1249     __ trap_ic_miss_check(receiver_klass, ic_klass);
1250   } else {
1251     Label valid;
1252     __ cmpd(CCR0, receiver_klass, ic_klass);
1253     __ beq_predict_taken(CCR0, valid);
1254     // We have an unexpected klass, branch to ic_miss_stub.
1255     __ b64_patchable((address)SharedRuntime::get_ic_miss_stub(),
1256                      relocInfo::runtime_call_type);
1257     __ BIND(valid);
1258   }
1259 
1260   // Argument is valid and klass is as expected, continue.
1261 
1262   // Extract method from inline cache, verified entry point needs it.
1263   __ ld(R19_method, CompiledICHolder::holder_metadata_offset(), ic);
1264   assert(R19_method == ic, "the inline cache register is dead here");
1265 
1266   __ ld(code, method_(code));
1267   __ cmpdi(CCR0, code, 0);
1268   __ ld(ientry, method_(interpreter_entry)); // preloaded
1269   __ beq_predict_taken(CCR0, call_interpreter);
1270 
1271   // Branch to ic_miss_stub.
1272   __ b64_patchable((address)SharedRuntime::get_ic_miss_stub(), relocInfo::runtime_call_type);
1273 
1274   // entry: c2i
1275 
1276   c2i_entry = __ pc();
1277 
1278   // Class initialization barrier for static methods
1279   address c2i_no_clinit_check_entry = NULL;
1280   if (VM_Version::supports_fast_class_init_checks()) {
1281     Label L_skip_barrier;
1282 
1283     { // Bypass the barrier for non-static methods
1284       __ lwz(R0, in_bytes(Method::access_flags_offset()), R19_method);
1285       __ andi_(R0, R0, JVM_ACC_STATIC);
1286       __ beq(CCR0, L_skip_barrier); // non-static
1287     }
1288 
1289     Register klass = R11_scratch1;
1290     __ load_method_holder(klass, R19_method);
1291     __ clinit_barrier(klass, R16_thread, &L_skip_barrier /*L_fast_path*/);
1292 
1293     __ load_const_optimized(klass, SharedRuntime::get_handle_wrong_method_stub(), R0);
1294     __ mtctr(klass);
1295     __ bctr();
1296 
1297     __ bind(L_skip_barrier);
1298     c2i_no_clinit_check_entry = __ pc();
1299   }
1300 
1301   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
1302   bs->c2i_entry_barrier(masm, /* tmp register*/ ic_klass, /* tmp register*/ receiver_klass, /* tmp register*/ code);
1303 
1304   gen_c2i_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs, call_interpreter, ientry);
1305 
1306   return AdapterHandlerLibrary::new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry,
1307                                           c2i_no_clinit_check_entry);
1308 }
1309 
1310 // An oop arg. Must pass a handle not the oop itself.
1311 static void object_move(MacroAssembler* masm,
1312                         int frame_size_in_slots,
1313                         OopMap* oop_map, int oop_handle_offset,
1314                         bool is_receiver, int* receiver_offset,
1315                         VMRegPair src, VMRegPair dst,
1316                         Register r_caller_sp, Register r_temp_1, Register r_temp_2) {
1317   assert(!is_receiver || (is_receiver && (*receiver_offset == -1)),
1318          "receiver has already been moved");
1319 
1320   // We must pass a handle. First figure out the location we use as a handle.
1321 
1322   if (src.first()->is_stack()) {
1323     // stack to stack or reg
1324 
1325     const Register r_handle = dst.first()->is_stack() ? r_temp_1 : dst.first()->as_Register();
1326     Label skip;
1327     const int oop_slot_in_callers_frame = reg2slot(src.first());
1328 
1329     guarantee(!is_receiver, "expecting receiver in register");
1330     oop_map->set_oop(VMRegImpl::stack2reg(oop_slot_in_callers_frame + frame_size_in_slots));
1331 
1332     __ addi(r_handle, r_caller_sp, reg2offset(src.first()));
1333     __ ld(  r_temp_2, reg2offset(src.first()), r_caller_sp);
1334     __ cmpdi(CCR0, r_temp_2, 0);
1335     __ bne(CCR0, skip);
1336     // Use a NULL handle if oop is NULL.
1337     __ li(r_handle, 0);
1338     __ bind(skip);
1339 
1340     if (dst.first()->is_stack()) {
1341       // stack to stack
1342       __ std(r_handle, reg2offset(dst.first()), R1_SP);
1343     } else {
1344       // stack to reg
1345       // Nothing to do, r_handle is already the dst register.
1346     }
1347   } else {
1348     // reg to stack or reg
1349     const Register r_oop      = src.first()->as_Register();
1350     const Register r_handle   = dst.first()->is_stack() ? r_temp_1 : dst.first()->as_Register();
1351     const int oop_slot        = (r_oop->encoding()-R3_ARG1->encoding()) * VMRegImpl::slots_per_word
1352                                 + oop_handle_offset; // in slots
1353     const int oop_offset = oop_slot * VMRegImpl::stack_slot_size;
1354     Label skip;
1355 
1356     if (is_receiver) {
1357       *receiver_offset = oop_offset;
1358     }
1359     oop_map->set_oop(VMRegImpl::stack2reg(oop_slot));
1360 
1361     __ std( r_oop,    oop_offset, R1_SP);
1362     __ addi(r_handle, R1_SP, oop_offset);
1363 
1364     __ cmpdi(CCR0, r_oop, 0);
1365     __ bne(CCR0, skip);
1366     // Use a NULL handle if oop is NULL.
1367     __ li(r_handle, 0);
1368     __ bind(skip);
1369 
1370     if (dst.first()->is_stack()) {
1371       // reg to stack
1372       __ std(r_handle, reg2offset(dst.first()), R1_SP);
1373     } else {
1374       // reg to reg
1375       // Nothing to do, r_handle is already the dst register.
1376     }
1377   }
1378 }
1379 
1380 static void int_move(MacroAssembler*masm,
1381                      VMRegPair src, VMRegPair dst,
1382                      Register r_caller_sp, Register r_temp) {
1383   assert(src.first()->is_valid(), "incoming must be int");
1384   assert(dst.first()->is_valid() && dst.second() == dst.first()->next(), "outgoing must be long");
1385 
1386   if (src.first()->is_stack()) {
1387     if (dst.first()->is_stack()) {
1388       // stack to stack
1389       __ lwa(r_temp, reg2offset(src.first()), r_caller_sp);
1390       __ std(r_temp, reg2offset(dst.first()), R1_SP);
1391     } else {
1392       // stack to reg
1393       __ lwa(dst.first()->as_Register(), reg2offset(src.first()), r_caller_sp);
1394     }
1395   } else if (dst.first()->is_stack()) {
1396     // reg to stack
1397     __ extsw(r_temp, src.first()->as_Register());
1398     __ std(r_temp, reg2offset(dst.first()), R1_SP);
1399   } else {
1400     // reg to reg
1401     __ extsw(dst.first()->as_Register(), src.first()->as_Register());
1402   }
1403 }
1404 
1405 static void long_move(MacroAssembler*masm,
1406                       VMRegPair src, VMRegPair dst,
1407                       Register r_caller_sp, Register r_temp) {
1408   assert(src.first()->is_valid() && src.second() == src.first()->next(), "incoming must be long");
1409   assert(dst.first()->is_valid() && dst.second() == dst.first()->next(), "outgoing must be long");
1410 
1411   if (src.first()->is_stack()) {
1412     if (dst.first()->is_stack()) {
1413       // stack to stack
1414       __ ld( r_temp, reg2offset(src.first()), r_caller_sp);
1415       __ std(r_temp, reg2offset(dst.first()), R1_SP);
1416     } else {
1417       // stack to reg
1418       __ ld(dst.first()->as_Register(), reg2offset(src.first()), r_caller_sp);
1419     }
1420   } else if (dst.first()->is_stack()) {
1421     // reg to stack
1422     __ std(src.first()->as_Register(), reg2offset(dst.first()), R1_SP);
1423   } else {
1424     // reg to reg
1425     if (dst.first()->as_Register() != src.first()->as_Register())
1426       __ mr(dst.first()->as_Register(), src.first()->as_Register());
1427   }
1428 }
1429 
1430 static void float_move(MacroAssembler*masm,
1431                        VMRegPair src, VMRegPair dst,
1432                        Register r_caller_sp, Register r_temp) {
1433   assert(src.first()->is_valid() && !src.second()->is_valid(), "incoming must be float");
1434   assert(dst.first()->is_valid() && !dst.second()->is_valid(), "outgoing must be float");
1435 
1436   if (src.first()->is_stack()) {
1437     if (dst.first()->is_stack()) {
1438       // stack to stack
1439       __ lwz(r_temp, reg2offset(src.first()), r_caller_sp);
1440       __ stw(r_temp, reg2offset(dst.first()), R1_SP);
1441     } else {
1442       // stack to reg
1443       __ lfs(dst.first()->as_FloatRegister(), reg2offset(src.first()), r_caller_sp);
1444     }
1445   } else if (dst.first()->is_stack()) {
1446     // reg to stack
1447     __ stfs(src.first()->as_FloatRegister(), reg2offset(dst.first()), R1_SP);
1448   } else {
1449     // reg to reg
1450     if (dst.first()->as_FloatRegister() != src.first()->as_FloatRegister())
1451       __ fmr(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
1452   }
1453 }
1454 
1455 static void double_move(MacroAssembler*masm,
1456                         VMRegPair src, VMRegPair dst,
1457                         Register r_caller_sp, Register r_temp) {
1458   assert(src.first()->is_valid() && src.second() == src.first()->next(), "incoming must be double");
1459   assert(dst.first()->is_valid() && dst.second() == dst.first()->next(), "outgoing must be double");
1460 
1461   if (src.first()->is_stack()) {
1462     if (dst.first()->is_stack()) {
1463       // stack to stack
1464       __ ld( r_temp, reg2offset(src.first()), r_caller_sp);
1465       __ std(r_temp, reg2offset(dst.first()), R1_SP);
1466     } else {
1467       // stack to reg
1468       __ lfd(dst.first()->as_FloatRegister(), reg2offset(src.first()), r_caller_sp);
1469     }
1470   } else if (dst.first()->is_stack()) {
1471     // reg to stack
1472     __ stfd(src.first()->as_FloatRegister(), reg2offset(dst.first()), R1_SP);
1473   } else {
1474     // reg to reg
1475     if (dst.first()->as_FloatRegister() != src.first()->as_FloatRegister())
1476       __ fmr(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
1477   }
1478 }
1479 
1480 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1481   switch (ret_type) {
1482     case T_BOOLEAN:
1483     case T_CHAR:
1484     case T_BYTE:
1485     case T_SHORT:
1486     case T_INT:
1487       __ stw (R3_RET,  frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1488       break;
1489     case T_ARRAY:
1490     case T_OBJECT:
1491     case T_LONG:
1492       __ std (R3_RET,  frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1493       break;
1494     case T_FLOAT:
1495       __ stfs(F1_RET, frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1496       break;
1497     case T_DOUBLE:
1498       __ stfd(F1_RET, frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1499       break;
1500     case T_VOID:
1501       break;
1502     default:
1503       ShouldNotReachHere();
1504       break;
1505   }
1506 }
1507 
1508 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1509   switch (ret_type) {
1510     case T_BOOLEAN:
1511     case T_CHAR:
1512     case T_BYTE:
1513     case T_SHORT:
1514     case T_INT:
1515       __ lwz(R3_RET,  frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1516       break;
1517     case T_ARRAY:
1518     case T_OBJECT:
1519     case T_LONG:
1520       __ ld (R3_RET,  frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1521       break;
1522     case T_FLOAT:
1523       __ lfs(F1_RET, frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1524       break;
1525     case T_DOUBLE:
1526       __ lfd(F1_RET, frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1527       break;
1528     case T_VOID:
1529       break;
1530     default:
1531       ShouldNotReachHere();
1532       break;
1533   }
1534 }
1535 
1536 static void verify_oop_args(MacroAssembler* masm,
1537                             const methodHandle& method,
1538                             const BasicType* sig_bt,
1539                             const VMRegPair* regs) {
1540   Register temp_reg = R19_method;  // not part of any compiled calling seq
1541   if (VerifyOops) {
1542     for (int i = 0; i < method->size_of_parameters(); i++) {
1543       if (is_reference_type(sig_bt[i])) {
1544         VMReg r = regs[i].first();
1545         assert(r->is_valid(), "bad oop arg");
1546         if (r->is_stack()) {
1547           __ ld(temp_reg, reg2offset(r), R1_SP);
1548           __ verify_oop(temp_reg, FILE_AND_LINE);
1549         } else {
1550           __ verify_oop(r->as_Register(), FILE_AND_LINE);
1551         }
1552       }
1553     }
1554   }
1555 }
1556 
1557 static void gen_special_dispatch(MacroAssembler* masm,
1558                                  const methodHandle& method,
1559                                  const BasicType* sig_bt,
1560                                  const VMRegPair* regs) {
1561   verify_oop_args(masm, method, sig_bt, regs);
1562   vmIntrinsics::ID iid = method->intrinsic_id();
1563 
1564   // Now write the args into the outgoing interpreter space
1565   bool     has_receiver   = false;
1566   Register receiver_reg   = noreg;
1567   int      member_arg_pos = -1;
1568   Register member_reg     = noreg;
1569   int      ref_kind       = MethodHandles::signature_polymorphic_intrinsic_ref_kind(iid);
1570   if (ref_kind != 0) {
1571     member_arg_pos = method->size_of_parameters() - 1;  // trailing MemberName argument
1572     member_reg = R19_method;  // known to be free at this point
1573     has_receiver = MethodHandles::ref_kind_has_receiver(ref_kind);
1574   } else if (iid == vmIntrinsics::_invokeBasic) {
1575     has_receiver = true;
1576   } else if (iid == vmIntrinsics::_linkToNative) {
1577     member_arg_pos = method->size_of_parameters() - 1;  // trailing NativeEntryPoint argument
1578     member_reg = R19_method;  // known to be free at this point
1579   } else {
1580     fatal("unexpected intrinsic id %d", vmIntrinsics::as_int(iid));
1581   }
1582 
1583   if (member_reg != noreg) {
1584     // Load the member_arg into register, if necessary.
1585     SharedRuntime::check_member_name_argument_is_last_argument(method, sig_bt, regs);
1586     VMReg r = regs[member_arg_pos].first();
1587     if (r->is_stack()) {
1588       __ ld(member_reg, reg2offset(r), R1_SP);
1589     } else {
1590       // no data motion is needed
1591       member_reg = r->as_Register();
1592     }
1593   }
1594 
1595   if (has_receiver) {
1596     // Make sure the receiver is loaded into a register.
1597     assert(method->size_of_parameters() > 0, "oob");
1598     assert(sig_bt[0] == T_OBJECT, "receiver argument must be an object");
1599     VMReg r = regs[0].first();
1600     assert(r->is_valid(), "bad receiver arg");
1601     if (r->is_stack()) {
1602       // Porting note:  This assumes that compiled calling conventions always
1603       // pass the receiver oop in a register.  If this is not true on some
1604       // platform, pick a temp and load the receiver from stack.
1605       fatal("receiver always in a register");
1606       receiver_reg = R11_scratch1;  // TODO (hs24): is R11_scratch1 really free at this point?
1607       __ ld(receiver_reg, reg2offset(r), R1_SP);
1608     } else {
1609       // no data motion is needed
1610       receiver_reg = r->as_Register();
1611     }
1612   }
1613 
1614   // Figure out which address we are really jumping to:
1615   MethodHandles::generate_method_handle_dispatch(masm, iid,
1616                                                  receiver_reg, member_reg, /*for_compiler_entry:*/ true);
1617 }
1618 
1619 // ---------------------------------------------------------------------------
1620 // Generate a native wrapper for a given method. The method takes arguments
1621 // in the Java compiled code convention, marshals them to the native
1622 // convention (handlizes oops, etc), transitions to native, makes the call,
1623 // returns to java state (possibly blocking), unhandlizes any result and
1624 // returns.
1625 //
1626 // Critical native functions are a shorthand for the use of
1627 // GetPrimtiveArrayCritical and disallow the use of any other JNI
1628 // functions.  The wrapper is expected to unpack the arguments before
1629 // passing them to the callee. Critical native functions leave the state _in_Java,
1630 // since they cannot stop for GC.
1631 // Some other parts of JNI setup are skipped like the tear down of the JNI handle
1632 // block and the check for pending exceptions it's impossible for them
1633 // to be thrown.
1634 //
1635 nmethod *SharedRuntime::generate_native_wrapper(MacroAssembler *masm,
1636                                                 const methodHandle& method,
1637                                                 int compile_id,
1638                                                 BasicType *in_sig_bt,
1639                                                 VMRegPair *in_regs,
1640                                                 BasicType ret_type) {
1641   if (method->is_method_handle_intrinsic()) {
1642     vmIntrinsics::ID iid = method->intrinsic_id();
1643     intptr_t start = (intptr_t)__ pc();
1644     int vep_offset = ((intptr_t)__ pc()) - start;
1645     gen_special_dispatch(masm,
1646                          method,
1647                          in_sig_bt,
1648                          in_regs);
1649     int frame_complete = ((intptr_t)__ pc()) - start;  // not complete, period
1650     __ flush();
1651     int stack_slots = SharedRuntime::out_preserve_stack_slots();  // no out slots at all, actually
1652     return nmethod::new_native_nmethod(method,
1653                                        compile_id,
1654                                        masm->code(),
1655                                        vep_offset,
1656                                        frame_complete,
1657                                        stack_slots / VMRegImpl::slots_per_word,
1658                                        in_ByteSize(-1),
1659                                        in_ByteSize(-1),
1660                                        (OopMapSet*)NULL);
1661   }
1662 
1663   address native_func = method->native_function();
1664   assert(native_func != NULL, "must have function");
1665 
1666   // First, create signature for outgoing C call
1667   // --------------------------------------------------------------------------
1668 
1669   int total_in_args = method->size_of_parameters();
1670   // We have received a description of where all the java args are located
1671   // on entry to the wrapper. We need to convert these args to where
1672   // the jni function will expect them. To figure out where they go
1673   // we convert the java signature to a C signature by inserting
1674   // the hidden arguments as arg[0] and possibly arg[1] (static method)
1675 
1676   // Calculate the total number of C arguments and create arrays for the
1677   // signature and the outgoing registers.
1678   // On ppc64, we have two arrays for the outgoing registers, because
1679   // some floating-point arguments must be passed in registers _and_
1680   // in stack locations.
1681   bool method_is_static = method->is_static();
1682   int  total_c_args     = total_in_args + (method_is_static ? 2 : 1);
1683 
1684   BasicType *out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1685   VMRegPair *out_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1686   VMRegPair *out_regs2  = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1687   BasicType* in_elem_bt = NULL;
1688 
1689   // Create the signature for the C call:
1690   //   1) add the JNIEnv*
1691   //   2) add the class if the method is static
1692   //   3) copy the rest of the incoming signature (shifted by the number of
1693   //      hidden arguments).
1694 
1695   int argc = 0;
1696   out_sig_bt[argc++] = T_ADDRESS;
1697   if (method->is_static()) {
1698     out_sig_bt[argc++] = T_OBJECT;
1699   }
1700 
1701   for (int i = 0; i < total_in_args ; i++ ) {
1702     out_sig_bt[argc++] = in_sig_bt[i];
1703   }
1704 
1705 
1706   // Compute the wrapper's frame size.
1707   // --------------------------------------------------------------------------
1708 
1709   // Now figure out where the args must be stored and how much stack space
1710   // they require.
1711   //
1712   // Compute framesize for the wrapper. We need to handlize all oops in
1713   // incoming registers.
1714   //
1715   // Calculate the total number of stack slots we will need:
1716   //   1) abi requirements
1717   //   2) outgoing arguments
1718   //   3) space for inbound oop handle area
1719   //   4) space for handlizing a klass if static method
1720   //   5) space for a lock if synchronized method
1721   //   6) workspace for saving return values, int <-> float reg moves, etc.
1722   //   7) alignment
1723   //
1724   // Layout of the native wrapper frame:
1725   // (stack grows upwards, memory grows downwards)
1726   //
1727   // NW     [ABI_REG_ARGS]             <-- 1) R1_SP
1728   //        [outgoing arguments]       <-- 2) R1_SP + out_arg_slot_offset
1729   //        [oopHandle area]           <-- 3) R1_SP + oop_handle_offset
1730   //        klass                      <-- 4) R1_SP + klass_offset
1731   //        lock                       <-- 5) R1_SP + lock_offset
1732   //        [workspace]                <-- 6) R1_SP + workspace_offset
1733   //        [alignment] (optional)     <-- 7)
1734   // caller [JIT_TOP_ABI_48]           <-- r_callers_sp
1735   //
1736   // - *_slot_offset Indicates offset from SP in number of stack slots.
1737   // - *_offset      Indicates offset from SP in bytes.
1738 
1739   int stack_slots = c_calling_convention(out_sig_bt, out_regs, out_regs2, total_c_args) + // 1+2)
1740                     SharedRuntime::out_preserve_stack_slots(); // See c_calling_convention.
1741 
1742   // Now the space for the inbound oop handle area.
1743   int total_save_slots = num_java_iarg_registers * VMRegImpl::slots_per_word;
1744 
1745   int oop_handle_slot_offset = stack_slots;
1746   stack_slots += total_save_slots;                                                // 3)
1747 
1748   int klass_slot_offset = 0;
1749   int klass_offset      = -1;
1750   if (method_is_static) {                                                         // 4)
1751     klass_slot_offset  = stack_slots;
1752     klass_offset       = klass_slot_offset * VMRegImpl::stack_slot_size;
1753     stack_slots       += VMRegImpl::slots_per_word;
1754   }
1755 
1756   int lock_slot_offset = 0;
1757   int lock_offset      = -1;
1758   if (method->is_synchronized()) {                                                // 5)
1759     lock_slot_offset   = stack_slots;
1760     lock_offset        = lock_slot_offset * VMRegImpl::stack_slot_size;
1761     stack_slots       += VMRegImpl::slots_per_word;
1762   }
1763 
1764   int workspace_slot_offset = stack_slots;                                        // 6)
1765   stack_slots         += 2;
1766 
1767   // Now compute actual number of stack words we need.
1768   // Rounding to make stack properly aligned.
1769   stack_slots = align_up(stack_slots,                                             // 7)
1770                          frame::alignment_in_bytes / VMRegImpl::stack_slot_size);
1771   int frame_size_in_bytes = stack_slots * VMRegImpl::stack_slot_size;
1772 
1773 
1774   // Now we can start generating code.
1775   // --------------------------------------------------------------------------
1776 
1777   intptr_t start_pc = (intptr_t)__ pc();
1778   intptr_t vep_start_pc;
1779   intptr_t frame_done_pc;
1780   intptr_t oopmap_pc;
1781 
1782   Label    ic_miss;
1783   Label    handle_pending_exception;
1784 
1785   Register r_callers_sp = R21;
1786   Register r_temp_1     = R22;
1787   Register r_temp_2     = R23;
1788   Register r_temp_3     = R24;
1789   Register r_temp_4     = R25;
1790   Register r_temp_5     = R26;
1791   Register r_temp_6     = R27;
1792   Register r_return_pc  = R28;
1793 
1794   Register r_carg1_jnienv        = noreg;
1795   Register r_carg2_classorobject = noreg;
1796   r_carg1_jnienv        = out_regs[0].first()->as_Register();
1797   r_carg2_classorobject = out_regs[1].first()->as_Register();
1798 
1799 
1800   // Generate the Unverified Entry Point (UEP).
1801   // --------------------------------------------------------------------------
1802   assert(start_pc == (intptr_t)__ pc(), "uep must be at start");
1803 
1804   // Check ic: object class == cached class?
1805   if (!method_is_static) {
1806   Register ic = R19_inline_cache_reg;
1807   Register receiver_klass = r_temp_1;
1808 
1809   __ cmpdi(CCR0, R3_ARG1, 0);
1810   __ beq(CCR0, ic_miss);
1811   __ verify_oop(R3_ARG1, FILE_AND_LINE);
1812   __ load_klass(receiver_klass, R3_ARG1);
1813 
1814   __ cmpd(CCR0, receiver_klass, ic);
1815   __ bne(CCR0, ic_miss);
1816   }
1817 
1818 
1819   // Generate the Verified Entry Point (VEP).
1820   // --------------------------------------------------------------------------
1821   vep_start_pc = (intptr_t)__ pc();
1822 
1823   if (UseRTMLocking) {
1824     // Abort RTM transaction before calling JNI
1825     // because critical section can be large and
1826     // abort anyway. Also nmethod can be deoptimized.
1827     __ tabort_();
1828   }
1829 
1830   if (VM_Version::supports_fast_class_init_checks() && method->needs_clinit_barrier()) {
1831     Label L_skip_barrier;
1832     Register klass = r_temp_1;
1833     // Notify OOP recorder (don't need the relocation)
1834     AddressLiteral md = __ constant_metadata_address(method->method_holder());
1835     __ load_const_optimized(klass, md.value(), R0);
1836     __ clinit_barrier(klass, R16_thread, &L_skip_barrier /*L_fast_path*/);
1837 
1838     __ load_const_optimized(klass, SharedRuntime::get_handle_wrong_method_stub(), R0);
1839     __ mtctr(klass);
1840     __ bctr();
1841 
1842     __ bind(L_skip_barrier);
1843   }
1844 
1845   __ save_LR_CR(r_temp_1);
1846   __ generate_stack_overflow_check(frame_size_in_bytes); // Check before creating frame.
1847   __ mr(r_callers_sp, R1_SP);                            // Remember frame pointer.
1848   __ push_frame(frame_size_in_bytes, r_temp_1);          // Push the c2n adapter's frame.
1849 
1850   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
1851   bs->nmethod_entry_barrier(masm, r_temp_1);
1852 
1853   frame_done_pc = (intptr_t)__ pc();
1854 
1855   __ verify_thread();
1856 
1857   // Native nmethod wrappers never take possesion of the oop arguments.
1858   // So the caller will gc the arguments.
1859   // The only thing we need an oopMap for is if the call is static.
1860   //
1861   // An OopMap for lock (and class if static), and one for the VM call itself.
1862   OopMapSet *oop_maps = new OopMapSet();
1863   OopMap    *oop_map  = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1864 
1865   // Move arguments from register/stack to register/stack.
1866   // --------------------------------------------------------------------------
1867   //
1868   // We immediately shuffle the arguments so that for any vm call we have
1869   // to make from here on out (sync slow path, jvmti, etc.) we will have
1870   // captured the oops from our caller and have a valid oopMap for them.
1871   //
1872   // Natives require 1 or 2 extra arguments over the normal ones: the JNIEnv*
1873   // (derived from JavaThread* which is in R16_thread) and, if static,
1874   // the class mirror instead of a receiver. This pretty much guarantees that
1875   // register layout will not match. We ignore these extra arguments during
1876   // the shuffle. The shuffle is described by the two calling convention
1877   // vectors we have in our possession. We simply walk the java vector to
1878   // get the source locations and the c vector to get the destinations.
1879 
1880   // Record sp-based slot for receiver on stack for non-static methods.
1881   int receiver_offset = -1;
1882 
1883   // We move the arguments backward because the floating point registers
1884   // destination will always be to a register with a greater or equal
1885   // register number or the stack.
1886   //   in  is the index of the incoming Java arguments
1887   //   out is the index of the outgoing C arguments
1888 
1889 #ifdef ASSERT
1890   bool reg_destroyed[RegisterImpl::number_of_registers];
1891   bool freg_destroyed[FloatRegisterImpl::number_of_registers];
1892   for (int r = 0 ; r < RegisterImpl::number_of_registers ; r++) {
1893     reg_destroyed[r] = false;
1894   }
1895   for (int f = 0 ; f < FloatRegisterImpl::number_of_registers ; f++) {
1896     freg_destroyed[f] = false;
1897   }
1898 #endif // ASSERT
1899 
1900   for (int in = total_in_args - 1, out = total_c_args - 1; in >= 0 ; in--, out--) {
1901 
1902 #ifdef ASSERT
1903     if (in_regs[in].first()->is_Register()) {
1904       assert(!reg_destroyed[in_regs[in].first()->as_Register()->encoding()], "ack!");
1905     } else if (in_regs[in].first()->is_FloatRegister()) {
1906       assert(!freg_destroyed[in_regs[in].first()->as_FloatRegister()->encoding()], "ack!");
1907     }
1908     if (out_regs[out].first()->is_Register()) {
1909       reg_destroyed[out_regs[out].first()->as_Register()->encoding()] = true;
1910     } else if (out_regs[out].first()->is_FloatRegister()) {
1911       freg_destroyed[out_regs[out].first()->as_FloatRegister()->encoding()] = true;
1912     }
1913     if (out_regs2[out].first()->is_Register()) {
1914       reg_destroyed[out_regs2[out].first()->as_Register()->encoding()] = true;
1915     } else if (out_regs2[out].first()->is_FloatRegister()) {
1916       freg_destroyed[out_regs2[out].first()->as_FloatRegister()->encoding()] = true;
1917     }
1918 #endif // ASSERT
1919 
1920     switch (in_sig_bt[in]) {
1921       case T_BOOLEAN:
1922       case T_CHAR:
1923       case T_BYTE:
1924       case T_SHORT:
1925       case T_INT:
1926         // Move int and do sign extension.
1927         int_move(masm, in_regs[in], out_regs[out], r_callers_sp, r_temp_1);
1928         break;
1929       case T_LONG:
1930         long_move(masm, in_regs[in], out_regs[out], r_callers_sp, r_temp_1);
1931         break;
1932       case T_ARRAY:
1933       case T_OBJECT:
1934         object_move(masm, stack_slots,
1935                     oop_map, oop_handle_slot_offset,
1936                     ((in == 0) && (!method_is_static)), &receiver_offset,
1937                     in_regs[in], out_regs[out],
1938                     r_callers_sp, r_temp_1, r_temp_2);
1939         break;
1940       case T_VOID:
1941         break;
1942       case T_FLOAT:
1943         float_move(masm, in_regs[in], out_regs[out], r_callers_sp, r_temp_1);
1944         if (out_regs2[out].first()->is_valid()) {
1945           float_move(masm, in_regs[in], out_regs2[out], r_callers_sp, r_temp_1);
1946         }
1947         break;
1948       case T_DOUBLE:
1949         double_move(masm, in_regs[in], out_regs[out], r_callers_sp, r_temp_1);
1950         if (out_regs2[out].first()->is_valid()) {
1951           double_move(masm, in_regs[in], out_regs2[out], r_callers_sp, r_temp_1);
1952         }
1953         break;
1954       case T_ADDRESS:
1955         fatal("found type (T_ADDRESS) in java args");
1956         break;
1957       default:
1958         ShouldNotReachHere();
1959         break;
1960     }
1961   }
1962 
1963   // Pre-load a static method's oop into ARG2.
1964   // Used both by locking code and the normal JNI call code.
1965   if (method_is_static) {
1966     __ set_oop_constant(JNIHandles::make_local(method->method_holder()->java_mirror()),
1967                         r_carg2_classorobject);
1968 
1969     // Now handlize the static class mirror in carg2. It's known not-null.
1970     __ std(r_carg2_classorobject, klass_offset, R1_SP);
1971     oop_map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
1972     __ addi(r_carg2_classorobject, R1_SP, klass_offset);
1973   }
1974 
1975   // Get JNIEnv* which is first argument to native.
1976   __ addi(r_carg1_jnienv, R16_thread, in_bytes(JavaThread::jni_environment_offset()));
1977 
1978   // NOTE:
1979   //
1980   // We have all of the arguments setup at this point.
1981   // We MUST NOT touch any outgoing regs from this point on.
1982   // So if we must call out we must push a new frame.
1983 
1984   // Get current pc for oopmap, and load it patchable relative to global toc.
1985   oopmap_pc = (intptr_t) __ pc();
1986   __ calculate_address_from_global_toc(r_return_pc, (address)oopmap_pc, true, true, true, true);
1987 
1988   // We use the same pc/oopMap repeatedly when we call out.
1989   oop_maps->add_gc_map(oopmap_pc - start_pc, oop_map);
1990 
1991   // r_return_pc now has the pc loaded that we will use when we finally call
1992   // to native.
1993 
1994   // Make sure that thread is non-volatile; it crosses a bunch of VM calls below.
1995   assert(R16_thread->is_nonvolatile(), "thread must be in non-volatile register");
1996 
1997 # if 0
1998   // DTrace method entry
1999 # endif
2000 
2001   // Lock a synchronized method.
2002   // --------------------------------------------------------------------------
2003 
2004   if (method->is_synchronized()) {
2005     ConditionRegister r_flag = CCR1;
2006     Register          r_oop  = r_temp_4;
2007     const Register    r_box  = r_temp_5;
2008     Label             done, locked;
2009 
2010     // Load the oop for the object or class. r_carg2_classorobject contains
2011     // either the handlized oop from the incoming arguments or the handlized
2012     // class mirror (if the method is static).
2013     __ ld(r_oop, 0, r_carg2_classorobject);
2014 
2015     // Get the lock box slot's address.
2016     __ addi(r_box, R1_SP, lock_offset);
2017 
2018     // Try fastpath for locking.
2019     // fast_lock kills r_temp_1, r_temp_2, r_temp_3.
2020     __ compiler_fast_lock_object(r_flag, r_oop, r_box, r_temp_1, r_temp_2, r_temp_3);
2021     __ beq(r_flag, locked);
2022 
2023     // None of the above fast optimizations worked so we have to get into the
2024     // slow case of monitor enter. Inline a special case of call_VM that
2025     // disallows any pending_exception.
2026 
2027     // Save argument registers and leave room for C-compatible ABI_REG_ARGS.
2028     int frame_size = frame::abi_reg_args_size + align_up(total_c_args * wordSize, frame::alignment_in_bytes);
2029     __ mr(R11_scratch1, R1_SP);
2030     RegisterSaver::push_frame_and_save_argument_registers(masm, R12_scratch2, frame_size, total_c_args, out_regs, out_regs2);
2031 
2032     // Do the call.
2033     __ set_last_Java_frame(R11_scratch1, r_return_pc);
2034     assert(r_return_pc->is_nonvolatile(), "expecting return pc to be in non-volatile register");
2035     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C), r_oop, r_box, R16_thread);
2036     __ reset_last_Java_frame();
2037 
2038     RegisterSaver::restore_argument_registers_and_pop_frame(masm, frame_size, total_c_args, out_regs, out_regs2);
2039 
2040     __ asm_assert_mem8_is_zero(thread_(pending_exception),
2041        "no pending exception allowed on exit from SharedRuntime::complete_monitor_locking_C");
2042 
2043     __ bind(locked);
2044   }
2045 
2046   // Use that pc we placed in r_return_pc a while back as the current frame anchor.
2047   __ set_last_Java_frame(R1_SP, r_return_pc);
2048 
2049   // Publish thread state
2050   // --------------------------------------------------------------------------
2051 
2052   // Transition from _thread_in_Java to _thread_in_native.
2053   __ li(R0, _thread_in_native);
2054   __ release();
2055   // TODO: PPC port assert(4 == JavaThread::sz_thread_state(), "unexpected field size");
2056   __ stw(R0, thread_(thread_state));
2057 
2058 
2059   // The JNI call
2060   // --------------------------------------------------------------------------
2061 #if defined(ABI_ELFv2)
2062   __ call_c(native_func, relocInfo::runtime_call_type);
2063 #else
2064   FunctionDescriptor* fd_native_method = (FunctionDescriptor*) native_func;
2065   __ call_c(fd_native_method, relocInfo::runtime_call_type);
2066 #endif
2067 
2068 
2069   // Now, we are back from the native code.
2070 
2071 
2072   // Unpack the native result.
2073   // --------------------------------------------------------------------------
2074 
2075   // For int-types, we do any needed sign-extension required.
2076   // Care must be taken that the return values (R3_RET and F1_RET)
2077   // will survive any VM calls for blocking or unlocking.
2078   // An OOP result (handle) is done specially in the slow-path code.
2079 
2080   switch (ret_type) {
2081     case T_VOID:    break;        // Nothing to do!
2082     case T_FLOAT:   break;        // Got it where we want it (unless slow-path).
2083     case T_DOUBLE:  break;        // Got it where we want it (unless slow-path).
2084     case T_LONG:    break;        // Got it where we want it (unless slow-path).
2085     case T_OBJECT:  break;        // Really a handle.
2086                                   // Cannot de-handlize until after reclaiming jvm_lock.
2087     case T_ARRAY:   break;
2088 
2089     case T_BOOLEAN: {             // 0 -> false(0); !0 -> true(1)
2090       Label skip_modify;
2091       __ cmpwi(CCR0, R3_RET, 0);
2092       __ beq(CCR0, skip_modify);
2093       __ li(R3_RET, 1);
2094       __ bind(skip_modify);
2095       break;
2096       }
2097     case T_BYTE: {                // sign extension
2098       __ extsb(R3_RET, R3_RET);
2099       break;
2100       }
2101     case T_CHAR: {                // unsigned result
2102       __ andi(R3_RET, R3_RET, 0xffff);
2103       break;
2104       }
2105     case T_SHORT: {               // sign extension
2106       __ extsh(R3_RET, R3_RET);
2107       break;
2108       }
2109     case T_INT:                   // nothing to do
2110       break;
2111     default:
2112       ShouldNotReachHere();
2113       break;
2114   }
2115 
2116   Label after_transition;
2117 
2118   // Publish thread state
2119   // --------------------------------------------------------------------------
2120 
2121   // Switch thread to "native transition" state before reading the
2122   // synchronization state. This additional state is necessary because reading
2123   // and testing the synchronization state is not atomic w.r.t. GC, as this
2124   // scenario demonstrates:
2125   //   - Java thread A, in _thread_in_native state, loads _not_synchronized
2126   //     and is preempted.
2127   //   - VM thread changes sync state to synchronizing and suspends threads
2128   //     for GC.
2129   //   - Thread A is resumed to finish this native method, but doesn't block
2130   //     here since it didn't see any synchronization in progress, and escapes.
2131 
2132   // Transition from _thread_in_native to _thread_in_native_trans.
2133   __ li(R0, _thread_in_native_trans);
2134   __ release();
2135   // TODO: PPC port assert(4 == JavaThread::sz_thread_state(), "unexpected field size");
2136   __ stw(R0, thread_(thread_state));
2137 
2138 
2139   // Must we block?
2140   // --------------------------------------------------------------------------
2141 
2142   // Block, if necessary, before resuming in _thread_in_Java state.
2143   // In order for GC to work, don't clear the last_Java_sp until after blocking.
2144   {
2145     Label no_block, sync;
2146 
2147     // Force this write out before the read below.
2148     __ fence();
2149 
2150     Register sync_state_addr = r_temp_4;
2151     Register sync_state      = r_temp_5;
2152     Register suspend_flags   = r_temp_6;
2153 
2154     // No synchronization in progress nor yet synchronized
2155     // (cmp-br-isync on one path, release (same as acquire on PPC64) on the other path).
2156     __ safepoint_poll(sync, sync_state, true /* at_return */, false /* in_nmethod */);
2157 
2158     // Not suspended.
2159     // TODO: PPC port assert(4 == Thread::sz_suspend_flags(), "unexpected field size");
2160     __ lwz(suspend_flags, thread_(suspend_flags));
2161     __ cmpwi(CCR1, suspend_flags, 0);
2162     __ beq(CCR1, no_block);
2163 
2164     // Block. Save any potential method result value before the operation and
2165     // use a leaf call to leave the last_Java_frame setup undisturbed. Doing this
2166     // lets us share the oopMap we used when we went native rather than create
2167     // a distinct one for this pc.
2168     __ bind(sync);
2169     __ isync();
2170 
2171     address entry_point =
2172       CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans);
2173     save_native_result(masm, ret_type, workspace_slot_offset);
2174     __ call_VM_leaf(entry_point, R16_thread);
2175     restore_native_result(masm, ret_type, workspace_slot_offset);
2176 
2177     __ bind(no_block);
2178 
2179     // Publish thread state.
2180     // --------------------------------------------------------------------------
2181 
2182     // Thread state is thread_in_native_trans. Any safepoint blocking has
2183     // already happened so we can now change state to _thread_in_Java.
2184 
2185     // Transition from _thread_in_native_trans to _thread_in_Java.
2186     __ li(R0, _thread_in_Java);
2187     __ lwsync(); // Acquire safepoint and suspend state, release thread state.
2188     // TODO: PPC port assert(4 == JavaThread::sz_thread_state(), "unexpected field size");
2189     __ stw(R0, thread_(thread_state));
2190     __ bind(after_transition);
2191   }
2192 
2193   // Reguard any pages if necessary.
2194   // --------------------------------------------------------------------------
2195 
2196   Label no_reguard;
2197   __ lwz(r_temp_1, thread_(stack_guard_state));
2198   __ cmpwi(CCR0, r_temp_1, StackOverflow::stack_guard_yellow_reserved_disabled);
2199   __ bne(CCR0, no_reguard);
2200 
2201   save_native_result(masm, ret_type, workspace_slot_offset);
2202   __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages));
2203   restore_native_result(masm, ret_type, workspace_slot_offset);
2204 
2205   __ bind(no_reguard);
2206 
2207 
2208   // Unlock
2209   // --------------------------------------------------------------------------
2210 
2211   if (method->is_synchronized()) {
2212 
2213     ConditionRegister r_flag   = CCR1;
2214     const Register r_oop       = r_temp_4;
2215     const Register r_box       = r_temp_5;
2216     const Register r_exception = r_temp_6;
2217     Label done;
2218 
2219     // Get oop and address of lock object box.
2220     if (method_is_static) {
2221       assert(klass_offset != -1, "");
2222       __ ld(r_oop, klass_offset, R1_SP);
2223     } else {
2224       assert(receiver_offset != -1, "");
2225       __ ld(r_oop, receiver_offset, R1_SP);
2226     }
2227     __ addi(r_box, R1_SP, lock_offset);
2228 
2229     // Try fastpath for unlocking.
2230     __ compiler_fast_unlock_object(r_flag, r_oop, r_box, r_temp_1, r_temp_2, r_temp_3);
2231     __ beq(r_flag, done);
2232 
2233     // Save and restore any potential method result value around the unlocking operation.
2234     save_native_result(masm, ret_type, workspace_slot_offset);
2235 
2236     // Must save pending exception around the slow-path VM call. Since it's a
2237     // leaf call, the pending exception (if any) can be kept in a register.
2238     __ ld(r_exception, thread_(pending_exception));
2239     assert(r_exception->is_nonvolatile(), "exception register must be non-volatile");
2240     __ li(R0, 0);
2241     __ std(R0, thread_(pending_exception));
2242 
2243     // Slow case of monitor enter.
2244     // Inline a special case of call_VM that disallows any pending_exception.
2245     // Arguments are (oop obj, BasicLock* lock, JavaThread* thread).
2246     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C), r_oop, r_box, R16_thread);
2247 
2248     __ asm_assert_mem8_is_zero(thread_(pending_exception),
2249        "no pending exception allowed on exit from SharedRuntime::complete_monitor_unlocking_C");
2250 
2251     restore_native_result(masm, ret_type, workspace_slot_offset);
2252 
2253     // Check_forward_pending_exception jump to forward_exception if any pending
2254     // exception is set. The forward_exception routine expects to see the
2255     // exception in pending_exception and not in a register. Kind of clumsy,
2256     // since all folks who branch to forward_exception must have tested
2257     // pending_exception first and hence have it in a register already.
2258     __ std(r_exception, thread_(pending_exception));
2259 
2260     __ bind(done);
2261   }
2262 
2263 # if 0
2264   // DTrace method exit
2265 # endif
2266 
2267   // Clear "last Java frame" SP and PC.
2268   // --------------------------------------------------------------------------
2269 
2270   __ reset_last_Java_frame();
2271 
2272   // Unbox oop result, e.g. JNIHandles::resolve value.
2273   // --------------------------------------------------------------------------
2274 
2275   if (is_reference_type(ret_type)) {
2276     __ resolve_jobject(R3_RET, r_temp_1, r_temp_2, MacroAssembler::PRESERVATION_NONE);
2277   }
2278 
2279   if (CheckJNICalls) {
2280     // clear_pending_jni_exception_check
2281     __ load_const_optimized(R0, 0L);
2282     __ st_ptr(R0, JavaThread::pending_jni_exception_check_fn_offset(), R16_thread);
2283   }
2284 
2285   // Reset handle block.
2286   // --------------------------------------------------------------------------
2287   __ ld(r_temp_1, thread_(active_handles));
2288   // TODO: PPC port assert(4 == JNIHandleBlock::top_size_in_bytes(), "unexpected field size");
2289   __ li(r_temp_2, 0);
2290   __ stw(r_temp_2, JNIHandleBlock::top_offset_in_bytes(), r_temp_1);
2291 
2292 
2293   // Check for pending exceptions.
2294   // --------------------------------------------------------------------------
2295   __ ld(r_temp_2, thread_(pending_exception));
2296   __ cmpdi(CCR0, r_temp_2, 0);
2297   __ bne(CCR0, handle_pending_exception);
2298 
2299   // Return
2300   // --------------------------------------------------------------------------
2301 
2302   __ pop_frame();
2303   __ restore_LR_CR(R11);
2304   __ blr();
2305 
2306 
2307   // Handler for pending exceptions (out-of-line).
2308   // --------------------------------------------------------------------------
2309   // Since this is a native call, we know the proper exception handler
2310   // is the empty function. We just pop this frame and then jump to
2311   // forward_exception_entry.
2312   __ bind(handle_pending_exception);
2313 
2314   __ pop_frame();
2315   __ restore_LR_CR(R11);
2316   __ b64_patchable((address)StubRoutines::forward_exception_entry(),
2317                        relocInfo::runtime_call_type);
2318 
2319   // Handler for a cache miss (out-of-line).
2320   // --------------------------------------------------------------------------
2321 
2322   if (!method_is_static) {
2323   __ bind(ic_miss);
2324 
2325   __ b64_patchable((address)SharedRuntime::get_ic_miss_stub(),
2326                        relocInfo::runtime_call_type);
2327   }
2328 
2329   // Done.
2330   // --------------------------------------------------------------------------
2331 
2332   __ flush();
2333 
2334   nmethod *nm = nmethod::new_native_nmethod(method,
2335                                             compile_id,
2336                                             masm->code(),
2337                                             vep_start_pc-start_pc,
2338                                             frame_done_pc-start_pc,
2339                                             stack_slots / VMRegImpl::slots_per_word,
2340                                             (method_is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2341                                             in_ByteSize(lock_offset),
2342                                             oop_maps);
2343 
2344   return nm;
2345 }
2346 
2347 // This function returns the adjust size (in number of words) to a c2i adapter
2348 // activation for use during deoptimization.
2349 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals) {
2350   return align_up((callee_locals - callee_parameters) * Interpreter::stackElementWords, frame::alignment_in_bytes);
2351 }
2352 
2353 uint SharedRuntime::in_preserve_stack_slots() {
2354   return frame::jit_in_preserve_size / VMRegImpl::stack_slot_size;
2355 }
2356 
2357 uint SharedRuntime::out_preserve_stack_slots() {
2358 #if defined(COMPILER1) || defined(COMPILER2)
2359   return frame::jit_out_preserve_size / VMRegImpl::stack_slot_size;
2360 #else
2361   return 0;
2362 #endif
2363 }
2364 
2365 #if defined(COMPILER1) || defined(COMPILER2)
2366 // Frame generation for deopt and uncommon trap blobs.
2367 static void push_skeleton_frame(MacroAssembler* masm, bool deopt,
2368                                 /* Read */
2369                                 Register unroll_block_reg,
2370                                 /* Update */
2371                                 Register frame_sizes_reg,
2372                                 Register number_of_frames_reg,
2373                                 Register pcs_reg,
2374                                 /* Invalidate */
2375                                 Register frame_size_reg,
2376                                 Register pc_reg) {
2377 
2378   __ ld(pc_reg, 0, pcs_reg);
2379   __ ld(frame_size_reg, 0, frame_sizes_reg);
2380   __ std(pc_reg, _abi0(lr), R1_SP);
2381   __ push_frame(frame_size_reg, R0/*tmp*/);
2382   __ std(R1_SP, _ijava_state_neg(sender_sp), R1_SP);
2383   __ addi(number_of_frames_reg, number_of_frames_reg, -1);
2384   __ addi(frame_sizes_reg, frame_sizes_reg, wordSize);
2385   __ addi(pcs_reg, pcs_reg, wordSize);
2386 }
2387 
2388 // Loop through the UnrollBlock info and create new frames.
2389 static void push_skeleton_frames(MacroAssembler* masm, bool deopt,
2390                                  /* read */
2391                                  Register unroll_block_reg,
2392                                  /* invalidate */
2393                                  Register frame_sizes_reg,
2394                                  Register number_of_frames_reg,
2395                                  Register pcs_reg,
2396                                  Register frame_size_reg,
2397                                  Register pc_reg) {
2398   Label loop;
2399 
2400  // _number_of_frames is of type int (deoptimization.hpp)
2401   __ lwa(number_of_frames_reg,
2402              Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes(),
2403              unroll_block_reg);
2404   __ ld(pcs_reg,
2405             Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes(),
2406             unroll_block_reg);
2407   __ ld(frame_sizes_reg,
2408             Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes(),
2409             unroll_block_reg);
2410 
2411   // stack: (caller_of_deoptee, ...).
2412 
2413   // At this point we either have an interpreter frame or a compiled
2414   // frame on top of stack. If it is a compiled frame we push a new c2i
2415   // adapter here
2416 
2417   // Memorize top-frame stack-pointer.
2418   __ mr(frame_size_reg/*old_sp*/, R1_SP);
2419 
2420   // Resize interpreter top frame OR C2I adapter.
2421 
2422   // At this moment, the top frame (which is the caller of the deoptee) is
2423   // an interpreter frame or a newly pushed C2I adapter or an entry frame.
2424   // The top frame has a TOP_IJAVA_FRAME_ABI and the frame contains the
2425   // outgoing arguments.
2426   //
2427   // In order to push the interpreter frame for the deoptee, we need to
2428   // resize the top frame such that we are able to place the deoptee's
2429   // locals in the frame.
2430   // Additionally, we have to turn the top frame's TOP_IJAVA_FRAME_ABI
2431   // into a valid PARENT_IJAVA_FRAME_ABI.
2432 
2433   __ lwa(R11_scratch1,
2434              Deoptimization::UnrollBlock::caller_adjustment_offset_in_bytes(),
2435              unroll_block_reg);
2436   __ neg(R11_scratch1, R11_scratch1);
2437 
2438   // R11_scratch1 contains size of locals for frame resizing.
2439   // R12_scratch2 contains top frame's lr.
2440 
2441   // Resize frame by complete frame size prevents TOC from being
2442   // overwritten by locals. A more stack space saving way would be
2443   // to copy the TOC to its location in the new abi.
2444   __ addi(R11_scratch1, R11_scratch1, - frame::parent_ijava_frame_abi_size);
2445 
2446   // now, resize the frame
2447   __ resize_frame(R11_scratch1, pc_reg/*tmp*/);
2448 
2449   // In the case where we have resized a c2i frame above, the optional
2450   // alignment below the locals has size 32 (why?).
2451   __ std(R12_scratch2, _abi0(lr), R1_SP);
2452 
2453   // Initialize initial_caller_sp.
2454  __ std(frame_size_reg, _ijava_state_neg(sender_sp), R1_SP);
2455 
2456 #ifdef ASSERT
2457   // Make sure that there is at least one entry in the array.
2458   __ cmpdi(CCR0, number_of_frames_reg, 0);
2459   __ asm_assert_ne("array_size must be > 0");
2460 #endif
2461 
2462   // Now push the new interpreter frames.
2463   //
2464   __ bind(loop);
2465   // Allocate a new frame, fill in the pc.
2466   push_skeleton_frame(masm, deopt,
2467                       unroll_block_reg,
2468                       frame_sizes_reg,
2469                       number_of_frames_reg,
2470                       pcs_reg,
2471                       frame_size_reg,
2472                       pc_reg);
2473   __ cmpdi(CCR0, number_of_frames_reg, 0);
2474   __ bne(CCR0, loop);
2475 
2476   // Get the return address pointing into the frame manager.
2477   __ ld(R0, 0, pcs_reg);
2478   // Store it in the top interpreter frame.
2479   __ std(R0, _abi0(lr), R1_SP);
2480   // Initialize frame_manager_lr of interpreter top frame.
2481 }
2482 #endif
2483 
2484 void SharedRuntime::generate_deopt_blob() {
2485   // Allocate space for the code
2486   ResourceMark rm;
2487   // Setup code generation tools
2488   CodeBuffer buffer("deopt_blob", 2048, 1024);
2489   InterpreterMacroAssembler* masm = new InterpreterMacroAssembler(&buffer);
2490   Label exec_mode_initialized;
2491   int frame_size_in_words;
2492   OopMap* map = NULL;
2493   OopMapSet *oop_maps = new OopMapSet();
2494 
2495   // size of ABI112 plus spill slots for R3_RET and F1_RET.
2496   const int frame_size_in_bytes = frame::abi_reg_args_spill_size;
2497   const int frame_size_in_slots = frame_size_in_bytes / sizeof(jint);
2498   int first_frame_size_in_bytes = 0; // frame size of "unpack frame" for call to fetch_unroll_info.
2499 
2500   const Register exec_mode_reg = R21_tmp1;
2501 
2502   const address start = __ pc();
2503 
2504 #if defined(COMPILER1) || defined(COMPILER2)
2505   // --------------------------------------------------------------------------
2506   // Prolog for non exception case!
2507 
2508   // We have been called from the deopt handler of the deoptee.
2509   //
2510   // deoptee:
2511   //                      ...
2512   //                      call X
2513   //                      ...
2514   //  deopt_handler:      call_deopt_stub
2515   //  cur. return pc  --> ...
2516   //
2517   // So currently SR_LR points behind the call in the deopt handler.
2518   // We adjust it such that it points to the start of the deopt handler.
2519   // The return_pc has been stored in the frame of the deoptee and
2520   // will replace the address of the deopt_handler in the call
2521   // to Deoptimization::fetch_unroll_info below.
2522   // We can't grab a free register here, because all registers may
2523   // contain live values, so let the RegisterSaver do the adjustment
2524   // of the return pc.
2525   const int return_pc_adjustment_no_exception = -MacroAssembler::bl64_patchable_size;
2526 
2527   // Push the "unpack frame"
2528   // Save everything in sight.
2529   map = RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
2530                                                                    &first_frame_size_in_bytes,
2531                                                                    /*generate_oop_map=*/ true,
2532                                                                    return_pc_adjustment_no_exception,
2533                                                                    RegisterSaver::return_pc_is_lr);
2534   assert(map != NULL, "OopMap must have been created");
2535 
2536   __ li(exec_mode_reg, Deoptimization::Unpack_deopt);
2537   // Save exec mode for unpack_frames.
2538   __ b(exec_mode_initialized);
2539 
2540   // --------------------------------------------------------------------------
2541   // Prolog for exception case
2542 
2543   // An exception is pending.
2544   // We have been called with a return (interpreter) or a jump (exception blob).
2545   //
2546   // - R3_ARG1: exception oop
2547   // - R4_ARG2: exception pc
2548 
2549   int exception_offset = __ pc() - start;
2550 
2551   BLOCK_COMMENT("Prolog for exception case");
2552 
2553   // Store exception oop and pc in thread (location known to GC).
2554   // This is needed since the call to "fetch_unroll_info()" may safepoint.
2555   __ std(R3_ARG1, in_bytes(JavaThread::exception_oop_offset()), R16_thread);
2556   __ std(R4_ARG2, in_bytes(JavaThread::exception_pc_offset()),  R16_thread);
2557   __ std(R4_ARG2, _abi0(lr), R1_SP);
2558 
2559   // Vanilla deoptimization with an exception pending in exception_oop.
2560   int exception_in_tls_offset = __ pc() - start;
2561 
2562   // Push the "unpack frame".
2563   // Save everything in sight.
2564   RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
2565                                                              &first_frame_size_in_bytes,
2566                                                              /*generate_oop_map=*/ false,
2567                                                              /*return_pc_adjustment_exception=*/ 0,
2568                                                              RegisterSaver::return_pc_is_pre_saved);
2569 
2570   // Deopt during an exception. Save exec mode for unpack_frames.
2571   __ li(exec_mode_reg, Deoptimization::Unpack_exception);
2572 
2573   // fall through
2574 
2575   int reexecute_offset = 0;
2576 #ifdef COMPILER1
2577   __ b(exec_mode_initialized);
2578 
2579   // Reexecute entry, similar to c2 uncommon trap
2580   reexecute_offset = __ pc() - start;
2581 
2582   RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
2583                                                              &first_frame_size_in_bytes,
2584                                                              /*generate_oop_map=*/ false,
2585                                                              /*return_pc_adjustment_reexecute=*/ 0,
2586                                                              RegisterSaver::return_pc_is_pre_saved);
2587   __ li(exec_mode_reg, Deoptimization::Unpack_reexecute);
2588 #endif
2589 
2590   // --------------------------------------------------------------------------
2591   __ BIND(exec_mode_initialized);
2592 
2593   {
2594   const Register unroll_block_reg = R22_tmp2;
2595 
2596   // We need to set `last_Java_frame' because `fetch_unroll_info' will
2597   // call `last_Java_frame()'. The value of the pc in the frame is not
2598   // particularly important. It just needs to identify this blob.
2599   __ set_last_Java_frame(R1_SP, noreg);
2600 
2601   // With EscapeAnalysis turned on, this call may safepoint!
2602   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info), R16_thread, exec_mode_reg);
2603   address calls_return_pc = __ last_calls_return_pc();
2604   // Set an oopmap for the call site that describes all our saved registers.
2605   oop_maps->add_gc_map(calls_return_pc - start, map);
2606 
2607   __ reset_last_Java_frame();
2608   // Save the return value.
2609   __ mr(unroll_block_reg, R3_RET);
2610 
2611   // Restore only the result registers that have been saved
2612   // by save_volatile_registers(...).
2613   RegisterSaver::restore_result_registers(masm, first_frame_size_in_bytes);
2614 
2615   // reload the exec mode from the UnrollBlock (it might have changed)
2616   __ lwz(exec_mode_reg, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes(), unroll_block_reg);
2617   // In excp_deopt_mode, restore and clear exception oop which we
2618   // stored in the thread during exception entry above. The exception
2619   // oop will be the return value of this stub.
2620   Label skip_restore_excp;
2621   __ cmpdi(CCR0, exec_mode_reg, Deoptimization::Unpack_exception);
2622   __ bne(CCR0, skip_restore_excp);
2623   __ ld(R3_RET, in_bytes(JavaThread::exception_oop_offset()), R16_thread);
2624   __ ld(R4_ARG2, in_bytes(JavaThread::exception_pc_offset()), R16_thread);
2625   __ li(R0, 0);
2626   __ std(R0, in_bytes(JavaThread::exception_pc_offset()),  R16_thread);
2627   __ std(R0, in_bytes(JavaThread::exception_oop_offset()), R16_thread);
2628   __ BIND(skip_restore_excp);
2629 
2630   __ pop_frame();
2631 
2632   // stack: (deoptee, optional i2c, caller of deoptee, ...).
2633 
2634   // pop the deoptee's frame
2635   __ pop_frame();
2636 
2637   // stack: (caller_of_deoptee, ...).
2638 
2639   // Loop through the `UnrollBlock' info and create interpreter frames.
2640   push_skeleton_frames(masm, true/*deopt*/,
2641                        unroll_block_reg,
2642                        R23_tmp3,
2643                        R24_tmp4,
2644                        R25_tmp5,
2645                        R26_tmp6,
2646                        R27_tmp7);
2647 
2648   // stack: (skeletal interpreter frame, ..., optional skeletal
2649   // interpreter frame, optional c2i, caller of deoptee, ...).
2650   }
2651 
2652   // push an `unpack_frame' taking care of float / int return values.
2653   __ push_frame(frame_size_in_bytes, R0/*tmp*/);
2654 
2655   // stack: (unpack frame, skeletal interpreter frame, ..., optional
2656   // skeletal interpreter frame, optional c2i, caller of deoptee,
2657   // ...).
2658 
2659   // Spill live volatile registers since we'll do a call.
2660   __ std( R3_RET, _abi_reg_args_spill(spill_ret),  R1_SP);
2661   __ stfd(F1_RET, _abi_reg_args_spill(spill_fret), R1_SP);
2662 
2663   // Let the unpacker layout information in the skeletal frames just
2664   // allocated.
2665   __ get_PC_trash_LR(R3_RET);
2666   __ set_last_Java_frame(/*sp*/R1_SP, /*pc*/R3_RET);
2667   // This is a call to a LEAF method, so no oop map is required.
2668   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames),
2669                   R16_thread/*thread*/, exec_mode_reg/*exec_mode*/);
2670   __ reset_last_Java_frame();
2671 
2672   // Restore the volatiles saved above.
2673   __ ld( R3_RET, _abi_reg_args_spill(spill_ret),  R1_SP);
2674   __ lfd(F1_RET, _abi_reg_args_spill(spill_fret), R1_SP);
2675 
2676   // Pop the unpack frame.
2677   __ pop_frame();
2678   __ restore_LR_CR(R0);
2679 
2680   // stack: (top interpreter frame, ..., optional interpreter frame,
2681   // optional c2i, caller of deoptee, ...).
2682 
2683   // Initialize R14_state.
2684   __ restore_interpreter_state(R11_scratch1);
2685   __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R11_scratch1);
2686 
2687   // Return to the interpreter entry point.
2688   __ blr();
2689   __ flush();
2690 #else // COMPILER2
2691   __ unimplemented("deopt blob needed only with compiler");
2692   int exception_offset = __ pc() - start;
2693 #endif // COMPILER2
2694 
2695   _deopt_blob = DeoptimizationBlob::create(&buffer, oop_maps, 0, exception_offset,
2696                                            reexecute_offset, first_frame_size_in_bytes / wordSize);
2697   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
2698 }
2699 
2700 #ifdef COMPILER2
2701 void SharedRuntime::generate_uncommon_trap_blob() {
2702   // Allocate space for the code.
2703   ResourceMark rm;
2704   // Setup code generation tools.
2705   CodeBuffer buffer("uncommon_trap_blob", 2048, 1024);
2706   InterpreterMacroAssembler* masm = new InterpreterMacroAssembler(&buffer);
2707   address start = __ pc();
2708 
2709   if (UseRTMLocking) {
2710     // Abort RTM transaction before possible nmethod deoptimization.
2711     __ tabort_();
2712   }
2713 
2714   Register unroll_block_reg = R21_tmp1;
2715   Register klass_index_reg  = R22_tmp2;
2716   Register unc_trap_reg     = R23_tmp3;
2717 
2718   OopMapSet* oop_maps = new OopMapSet();
2719   int frame_size_in_bytes = frame::abi_reg_args_size;
2720   OopMap* map = new OopMap(frame_size_in_bytes / sizeof(jint), 0);
2721 
2722   // stack: (deoptee, optional i2c, caller_of_deoptee, ...).
2723 
2724   // Push a dummy `unpack_frame' and call
2725   // `Deoptimization::uncommon_trap' to pack the compiled frame into a
2726   // vframe array and return the `UnrollBlock' information.
2727 
2728   // Save LR to compiled frame.
2729   __ save_LR_CR(R11_scratch1);
2730 
2731   // Push an "uncommon_trap" frame.
2732   __ push_frame_reg_args(0, R11_scratch1);
2733 
2734   // stack: (unpack frame, deoptee, optional i2c, caller_of_deoptee, ...).
2735 
2736   // Set the `unpack_frame' as last_Java_frame.
2737   // `Deoptimization::uncommon_trap' expects it and considers its
2738   // sender frame as the deoptee frame.
2739   // Remember the offset of the instruction whose address will be
2740   // moved to R11_scratch1.
2741   address gc_map_pc = __ get_PC_trash_LR(R11_scratch1);
2742 
2743   __ set_last_Java_frame(/*sp*/R1_SP, /*pc*/R11_scratch1);
2744 
2745   __ mr(klass_index_reg, R3);
2746   __ li(R5_ARG3, Deoptimization::Unpack_uncommon_trap);
2747   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap),
2748                   R16_thread, klass_index_reg, R5_ARG3);
2749 
2750   // Set an oopmap for the call site.
2751   oop_maps->add_gc_map(gc_map_pc - start, map);
2752 
2753   __ reset_last_Java_frame();
2754 
2755   // Pop the `unpack frame'.
2756   __ pop_frame();
2757 
2758   // stack: (deoptee, optional i2c, caller_of_deoptee, ...).
2759 
2760   // Save the return value.
2761   __ mr(unroll_block_reg, R3_RET);
2762 
2763   // Pop the uncommon_trap frame.
2764   __ pop_frame();
2765 
2766   // stack: (caller_of_deoptee, ...).
2767 
2768 #ifdef ASSERT
2769   __ lwz(R22_tmp2, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes(), unroll_block_reg);
2770   __ cmpdi(CCR0, R22_tmp2, (unsigned)Deoptimization::Unpack_uncommon_trap);
2771   __ asm_assert_eq("SharedRuntime::generate_deopt_blob: expected Unpack_uncommon_trap");
2772 #endif
2773 
2774   // Allocate new interpreter frame(s) and possibly a c2i adapter
2775   // frame.
2776   push_skeleton_frames(masm, false/*deopt*/,
2777                        unroll_block_reg,
2778                        R22_tmp2,
2779                        R23_tmp3,
2780                        R24_tmp4,
2781                        R25_tmp5,
2782                        R26_tmp6);
2783 
2784   // stack: (skeletal interpreter frame, ..., optional skeletal
2785   // interpreter frame, optional c2i, caller of deoptee, ...).
2786 
2787   // Push a dummy `unpack_frame' taking care of float return values.
2788   // Call `Deoptimization::unpack_frames' to layout information in the
2789   // interpreter frames just created.
2790 
2791   // Push a simple "unpack frame" here.
2792   __ push_frame_reg_args(0, R11_scratch1);
2793 
2794   // stack: (unpack frame, skeletal interpreter frame, ..., optional
2795   // skeletal interpreter frame, optional c2i, caller of deoptee,
2796   // ...).
2797 
2798   // Set the "unpack_frame" as last_Java_frame.
2799   __ get_PC_trash_LR(R11_scratch1);
2800   __ set_last_Java_frame(/*sp*/R1_SP, /*pc*/R11_scratch1);
2801 
2802   // Indicate it is the uncommon trap case.
2803   __ li(unc_trap_reg, Deoptimization::Unpack_uncommon_trap);
2804   // Let the unpacker layout information in the skeletal frames just
2805   // allocated.
2806   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames),
2807                   R16_thread, unc_trap_reg);
2808 
2809   __ reset_last_Java_frame();
2810   // Pop the `unpack frame'.
2811   __ pop_frame();
2812   // Restore LR from top interpreter frame.
2813   __ restore_LR_CR(R11_scratch1);
2814 
2815   // stack: (top interpreter frame, ..., optional interpreter frame,
2816   // optional c2i, caller of deoptee, ...).
2817 
2818   __ restore_interpreter_state(R11_scratch1);
2819   __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R11_scratch1);
2820 
2821   // Return to the interpreter entry point.
2822   __ blr();
2823 
2824   masm->flush();
2825 
2826   _uncommon_trap_blob = UncommonTrapBlob::create(&buffer, oop_maps, frame_size_in_bytes/wordSize);
2827 }
2828 #endif // COMPILER2
2829 
2830 // Generate a special Compile2Runtime blob that saves all registers, and setup oopmap.
2831 SafepointBlob* SharedRuntime::generate_handler_blob(address call_ptr, int poll_type) {
2832   assert(StubRoutines::forward_exception_entry() != NULL,
2833          "must be generated before");
2834 
2835   ResourceMark rm;
2836   OopMapSet *oop_maps = new OopMapSet();
2837   OopMap* map;
2838 
2839   // Allocate space for the code. Setup code generation tools.
2840   CodeBuffer buffer("handler_blob", 2048, 1024);
2841   MacroAssembler* masm = new MacroAssembler(&buffer);
2842 
2843   address start = __ pc();
2844   int frame_size_in_bytes = 0;
2845 
2846   RegisterSaver::ReturnPCLocation return_pc_location;
2847   bool cause_return = (poll_type == POLL_AT_RETURN);
2848   if (cause_return) {
2849     // Nothing to do here. The frame has already been popped in MachEpilogNode.
2850     // Register LR already contains the return pc.
2851     return_pc_location = RegisterSaver::return_pc_is_pre_saved;
2852   } else {
2853     // Use thread()->saved_exception_pc() as return pc.
2854     return_pc_location = RegisterSaver::return_pc_is_thread_saved_exception_pc;
2855   }
2856 
2857   if (UseRTMLocking) {
2858     // Abort RTM transaction before calling runtime
2859     // because critical section can be large and so
2860     // will abort anyway. Also nmethod can be deoptimized.
2861     __ tabort_();
2862   }
2863 
2864   bool save_vectors = (poll_type == POLL_AT_VECTOR_LOOP);
2865 
2866   // Save registers, fpu state, and flags. Set R31 = return pc.
2867   map = RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
2868                                                                    &frame_size_in_bytes,
2869                                                                    /*generate_oop_map=*/ true,
2870                                                                    /*return_pc_adjustment=*/0,
2871                                                                    return_pc_location, save_vectors);
2872 
2873   // The following is basically a call_VM. However, we need the precise
2874   // address of the call in order to generate an oopmap. Hence, we do all the
2875   // work outselves.
2876   __ set_last_Java_frame(/*sp=*/R1_SP, /*pc=*/noreg);
2877 
2878   // The return address must always be correct so that the frame constructor
2879   // never sees an invalid pc.
2880 
2881   // Do the call
2882   __ call_VM_leaf(call_ptr, R16_thread);
2883   address calls_return_pc = __ last_calls_return_pc();
2884 
2885   // Set an oopmap for the call site. This oopmap will map all
2886   // oop-registers and debug-info registers as callee-saved. This
2887   // will allow deoptimization at this safepoint to find all possible
2888   // debug-info recordings, as well as let GC find all oops.
2889   oop_maps->add_gc_map(calls_return_pc - start, map);
2890 
2891   Label noException;
2892 
2893   // Clear the last Java frame.
2894   __ reset_last_Java_frame();
2895 
2896   BLOCK_COMMENT("  Check pending exception.");
2897   const Register pending_exception = R0;
2898   __ ld(pending_exception, thread_(pending_exception));
2899   __ cmpdi(CCR0, pending_exception, 0);
2900   __ beq(CCR0, noException);
2901 
2902   // Exception pending
2903   RegisterSaver::restore_live_registers_and_pop_frame(masm,
2904                                                       frame_size_in_bytes,
2905                                                       /*restore_ctr=*/true, save_vectors);
2906 
2907   BLOCK_COMMENT("  Jump to forward_exception_entry.");
2908   // Jump to forward_exception_entry, with the issuing PC in LR
2909   // so it looks like the original nmethod called forward_exception_entry.
2910   __ b64_patchable(StubRoutines::forward_exception_entry(), relocInfo::runtime_call_type);
2911 
2912   // No exception case.
2913   __ BIND(noException);
2914 
2915   if (!cause_return) {
2916     Label no_adjust;
2917     // If our stashed return pc was modified by the runtime we avoid touching it
2918     __ ld(R0, frame_size_in_bytes + _abi0(lr), R1_SP);
2919     __ cmpd(CCR0, R0, R31);
2920     __ bne(CCR0, no_adjust);
2921 
2922     // Adjust return pc forward to step over the safepoint poll instruction
2923     __ addi(R31, R31, 4);
2924     __ std(R31, frame_size_in_bytes + _abi0(lr), R1_SP);
2925 
2926     __ bind(no_adjust);
2927   }
2928 
2929   // Normal exit, restore registers and exit.
2930   RegisterSaver::restore_live_registers_and_pop_frame(masm,
2931                                                       frame_size_in_bytes,
2932                                                       /*restore_ctr=*/true, save_vectors);
2933 
2934   __ blr();
2935 
2936   // Make sure all code is generated
2937   masm->flush();
2938 
2939   // Fill-out other meta info
2940   // CodeBlob frame size is in words.
2941   return SafepointBlob::create(&buffer, oop_maps, frame_size_in_bytes / wordSize);
2942 }
2943 
2944 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss)
2945 //
2946 // Generate a stub that calls into the vm to find out the proper destination
2947 // of a java call. All the argument registers are live at this point
2948 // but since this is generic code we don't know what they are and the caller
2949 // must do any gc of the args.
2950 //
2951 RuntimeStub* SharedRuntime::generate_resolve_blob(address destination, const char* name) {
2952 
2953   // allocate space for the code
2954   ResourceMark rm;
2955 
2956   CodeBuffer buffer(name, 1000, 512);
2957   MacroAssembler* masm = new MacroAssembler(&buffer);
2958 
2959   int frame_size_in_bytes;
2960 
2961   OopMapSet *oop_maps = new OopMapSet();
2962   OopMap* map = NULL;
2963 
2964   address start = __ pc();
2965 
2966   map = RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
2967                                                                    &frame_size_in_bytes,
2968                                                                    /*generate_oop_map*/ true,
2969                                                                    /*return_pc_adjustment*/ 0,
2970                                                                    RegisterSaver::return_pc_is_lr);
2971 
2972   // Use noreg as last_Java_pc, the return pc will be reconstructed
2973   // from the physical frame.
2974   __ set_last_Java_frame(/*sp*/R1_SP, noreg);
2975 
2976   int frame_complete = __ offset();
2977 
2978   // Pass R19_method as 2nd (optional) argument, used by
2979   // counter_overflow_stub.
2980   __ call_VM_leaf(destination, R16_thread, R19_method);
2981   address calls_return_pc = __ last_calls_return_pc();
2982   // Set an oopmap for the call site.
2983   // We need this not only for callee-saved registers, but also for volatile
2984   // registers that the compiler might be keeping live across a safepoint.
2985   // Create the oopmap for the call's return pc.
2986   oop_maps->add_gc_map(calls_return_pc - start, map);
2987 
2988   // R3_RET contains the address we are going to jump to assuming no exception got installed.
2989 
2990   // clear last_Java_sp
2991   __ reset_last_Java_frame();
2992 
2993   // Check for pending exceptions.
2994   BLOCK_COMMENT("Check for pending exceptions.");
2995   Label pending;
2996   __ ld(R11_scratch1, thread_(pending_exception));
2997   __ cmpdi(CCR0, R11_scratch1, 0);
2998   __ bne(CCR0, pending);
2999 
3000   __ mtctr(R3_RET); // Ctr will not be touched by restore_live_registers_and_pop_frame.
3001 
3002   RegisterSaver::restore_live_registers_and_pop_frame(masm, frame_size_in_bytes, /*restore_ctr*/ false);
3003 
3004   // Get the returned method.
3005   __ get_vm_result_2(R19_method);
3006 
3007   __ bctr();
3008 
3009 
3010   // Pending exception after the safepoint.
3011   __ BIND(pending);
3012 
3013   RegisterSaver::restore_live_registers_and_pop_frame(masm, frame_size_in_bytes, /*restore_ctr*/ true);
3014 
3015   // exception pending => remove activation and forward to exception handler
3016 
3017   __ li(R11_scratch1, 0);
3018   __ ld(R3_ARG1, thread_(pending_exception));
3019   __ std(R11_scratch1, in_bytes(JavaThread::vm_result_offset()), R16_thread);
3020   __ b64_patchable(StubRoutines::forward_exception_entry(), relocInfo::runtime_call_type);
3021 
3022   // -------------
3023   // Make sure all code is generated.
3024   masm->flush();
3025 
3026   // return the blob
3027   // frame_size_words or bytes??
3028   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_in_bytes/wordSize,
3029                                        oop_maps, true);
3030 }
3031 
3032 
3033 //------------------------------Montgomery multiplication------------------------
3034 //
3035 
3036 // Subtract 0:b from carry:a. Return carry.
3037 static unsigned long
3038 sub(unsigned long a[], unsigned long b[], unsigned long carry, long len) {
3039   long i = 0;
3040   unsigned long tmp, tmp2;
3041   __asm__ __volatile__ (
3042     "subfc  %[tmp], %[tmp], %[tmp]   \n" // pre-set CA
3043     "mtctr  %[len]                   \n"
3044     "0:                              \n"
3045     "ldx    %[tmp], %[i], %[a]       \n"
3046     "ldx    %[tmp2], %[i], %[b]      \n"
3047     "subfe  %[tmp], %[tmp2], %[tmp]  \n" // subtract extended
3048     "stdx   %[tmp], %[i], %[a]       \n"
3049     "addi   %[i], %[i], 8            \n"
3050     "bdnz   0b                       \n"
3051     "addme  %[tmp], %[carry]         \n" // carry + CA - 1
3052     : [i]"+b"(i), [tmp]"=&r"(tmp), [tmp2]"=&r"(tmp2)
3053     : [a]"r"(a), [b]"r"(b), [carry]"r"(carry), [len]"r"(len)
3054     : "ctr", "xer", "memory"
3055   );
3056   return tmp;
3057 }
3058 
3059 // Multiply (unsigned) Long A by Long B, accumulating the double-
3060 // length result into the accumulator formed of T0, T1, and T2.
3061 inline void MACC(unsigned long A, unsigned long B, unsigned long &T0, unsigned long &T1, unsigned long &T2) {
3062   unsigned long hi, lo;
3063   __asm__ __volatile__ (
3064     "mulld  %[lo], %[A], %[B]    \n"
3065     "mulhdu %[hi], %[A], %[B]    \n"
3066     "addc   %[T0], %[T0], %[lo]  \n"
3067     "adde   %[T1], %[T1], %[hi]  \n"
3068     "addze  %[T2], %[T2]         \n"
3069     : [hi]"=&r"(hi), [lo]"=&r"(lo), [T0]"+r"(T0), [T1]"+r"(T1), [T2]"+r"(T2)
3070     : [A]"r"(A), [B]"r"(B)
3071     : "xer"
3072   );
3073 }
3074 
3075 // As above, but add twice the double-length result into the
3076 // accumulator.
3077 inline void MACC2(unsigned long A, unsigned long B, unsigned long &T0, unsigned long &T1, unsigned long &T2) {
3078   unsigned long hi, lo;
3079   __asm__ __volatile__ (
3080     "mulld  %[lo], %[A], %[B]    \n"
3081     "mulhdu %[hi], %[A], %[B]    \n"
3082     "addc   %[T0], %[T0], %[lo]  \n"
3083     "adde   %[T1], %[T1], %[hi]  \n"
3084     "addze  %[T2], %[T2]         \n"
3085     "addc   %[T0], %[T0], %[lo]  \n"
3086     "adde   %[T1], %[T1], %[hi]  \n"
3087     "addze  %[T2], %[T2]         \n"
3088     : [hi]"=&r"(hi), [lo]"=&r"(lo), [T0]"+r"(T0), [T1]"+r"(T1), [T2]"+r"(T2)
3089     : [A]"r"(A), [B]"r"(B)
3090     : "xer"
3091   );
3092 }
3093 
3094 // Fast Montgomery multiplication. The derivation of the algorithm is
3095 // in "A Cryptographic Library for the Motorola DSP56000,
3096 // Dusse and Kaliski, Proc. EUROCRYPT 90, pp. 230-237".
3097 static void
3098 montgomery_multiply(unsigned long a[], unsigned long b[], unsigned long n[],
3099                     unsigned long m[], unsigned long inv, int len) {
3100   unsigned long t0 = 0, t1 = 0, t2 = 0; // Triple-precision accumulator
3101   int i;
3102 
3103   assert(inv * n[0] == -1UL, "broken inverse in Montgomery multiply");
3104 
3105   for (i = 0; i < len; i++) {
3106     int j;
3107     for (j = 0; j < i; j++) {
3108       MACC(a[j], b[i-j], t0, t1, t2);
3109       MACC(m[j], n[i-j], t0, t1, t2);
3110     }
3111     MACC(a[i], b[0], t0, t1, t2);
3112     m[i] = t0 * inv;
3113     MACC(m[i], n[0], t0, t1, t2);
3114 
3115     assert(t0 == 0, "broken Montgomery multiply");
3116 
3117     t0 = t1; t1 = t2; t2 = 0;
3118   }
3119 
3120   for (i = len; i < 2*len; i++) {
3121     int j;
3122     for (j = i-len+1; j < len; j++) {
3123       MACC(a[j], b[i-j], t0, t1, t2);
3124       MACC(m[j], n[i-j], t0, t1, t2);
3125     }
3126     m[i-len] = t0;
3127     t0 = t1; t1 = t2; t2 = 0;
3128   }
3129 
3130   while (t0) {
3131     t0 = sub(m, n, t0, len);
3132   }
3133 }
3134 
3135 // Fast Montgomery squaring. This uses asymptotically 25% fewer
3136 // multiplies so it should be up to 25% faster than Montgomery
3137 // multiplication. However, its loop control is more complex and it
3138 // may actually run slower on some machines.
3139 static void
3140 montgomery_square(unsigned long a[], unsigned long n[],
3141                   unsigned long m[], unsigned long inv, int len) {
3142   unsigned long t0 = 0, t1 = 0, t2 = 0; // Triple-precision accumulator
3143   int i;
3144 
3145   assert(inv * n[0] == -1UL, "broken inverse in Montgomery multiply");
3146 
3147   for (i = 0; i < len; i++) {
3148     int j;
3149     int end = (i+1)/2;
3150     for (j = 0; j < end; j++) {
3151       MACC2(a[j], a[i-j], t0, t1, t2);
3152       MACC(m[j], n[i-j], t0, t1, t2);
3153     }
3154     if ((i & 1) == 0) {
3155       MACC(a[j], a[j], t0, t1, t2);
3156     }
3157     for (; j < i; j++) {
3158       MACC(m[j], n[i-j], t0, t1, t2);
3159     }
3160     m[i] = t0 * inv;
3161     MACC(m[i], n[0], t0, t1, t2);
3162 
3163     assert(t0 == 0, "broken Montgomery square");
3164 
3165     t0 = t1; t1 = t2; t2 = 0;
3166   }
3167 
3168   for (i = len; i < 2*len; i++) {
3169     int start = i-len+1;
3170     int end = start + (len - start)/2;
3171     int j;
3172     for (j = start; j < end; j++) {
3173       MACC2(a[j], a[i-j], t0, t1, t2);
3174       MACC(m[j], n[i-j], t0, t1, t2);
3175     }
3176     if ((i & 1) == 0) {
3177       MACC(a[j], a[j], t0, t1, t2);
3178     }
3179     for (; j < len; j++) {
3180       MACC(m[j], n[i-j], t0, t1, t2);
3181     }
3182     m[i-len] = t0;
3183     t0 = t1; t1 = t2; t2 = 0;
3184   }
3185 
3186   while (t0) {
3187     t0 = sub(m, n, t0, len);
3188   }
3189 }
3190 
3191 // The threshold at which squaring is advantageous was determined
3192 // experimentally on an i7-3930K (Ivy Bridge) CPU @ 3.5GHz.
3193 // Doesn't seem to be relevant for Power8 so we use the same value.
3194 #define MONTGOMERY_SQUARING_THRESHOLD 64
3195 
3196 // Copy len longwords from s to d, word-swapping as we go. The
3197 // destination array is reversed.
3198 static void reverse_words(unsigned long *s, unsigned long *d, int len) {
3199   d += len;
3200   while(len-- > 0) {
3201     d--;
3202     unsigned long s_val = *s;
3203     // Swap words in a longword on little endian machines.
3204 #ifdef VM_LITTLE_ENDIAN
3205      s_val = (s_val << 32) | (s_val >> 32);
3206 #endif
3207     *d = s_val;
3208     s++;
3209   }
3210 }
3211 
3212 void SharedRuntime::montgomery_multiply(jint *a_ints, jint *b_ints, jint *n_ints,
3213                                         jint len, jlong inv,
3214                                         jint *m_ints) {
3215   len = len & 0x7fffFFFF; // C2 does not respect int to long conversion for stub calls.
3216   assert(len % 2 == 0, "array length in montgomery_multiply must be even");
3217   int longwords = len/2;
3218 
3219   // Make very sure we don't use so much space that the stack might
3220   // overflow. 512 jints corresponds to an 16384-bit integer and
3221   // will use here a total of 8k bytes of stack space.
3222   int total_allocation = longwords * sizeof (unsigned long) * 4;
3223   guarantee(total_allocation <= 8192, "must be");
3224   unsigned long *scratch = (unsigned long *)alloca(total_allocation);
3225 
3226   // Local scratch arrays
3227   unsigned long
3228     *a = scratch + 0 * longwords,
3229     *b = scratch + 1 * longwords,
3230     *n = scratch + 2 * longwords,
3231     *m = scratch + 3 * longwords;
3232 
3233   reverse_words((unsigned long *)a_ints, a, longwords);
3234   reverse_words((unsigned long *)b_ints, b, longwords);
3235   reverse_words((unsigned long *)n_ints, n, longwords);
3236 
3237   ::montgomery_multiply(a, b, n, m, (unsigned long)inv, longwords);
3238 
3239   reverse_words(m, (unsigned long *)m_ints, longwords);
3240 }
3241 
3242 void SharedRuntime::montgomery_square(jint *a_ints, jint *n_ints,
3243                                       jint len, jlong inv,
3244                                       jint *m_ints) {
3245   len = len & 0x7fffFFFF; // C2 does not respect int to long conversion for stub calls.
3246   assert(len % 2 == 0, "array length in montgomery_square must be even");
3247   int longwords = len/2;
3248 
3249   // Make very sure we don't use so much space that the stack might
3250   // overflow. 512 jints corresponds to an 16384-bit integer and
3251   // will use here a total of 6k bytes of stack space.
3252   int total_allocation = longwords * sizeof (unsigned long) * 3;
3253   guarantee(total_allocation <= 8192, "must be");
3254   unsigned long *scratch = (unsigned long *)alloca(total_allocation);
3255 
3256   // Local scratch arrays
3257   unsigned long
3258     *a = scratch + 0 * longwords,
3259     *n = scratch + 1 * longwords,
3260     *m = scratch + 2 * longwords;
3261 
3262   reverse_words((unsigned long *)a_ints, a, longwords);
3263   reverse_words((unsigned long *)n_ints, n, longwords);
3264 
3265   if (len >= MONTGOMERY_SQUARING_THRESHOLD) {
3266     ::montgomery_square(a, n, m, (unsigned long)inv, longwords);
3267   } else {
3268     ::montgomery_multiply(a, a, n, m, (unsigned long)inv, longwords);
3269   }
3270 
3271   reverse_words(m, (unsigned long *)m_ints, longwords);
3272 }