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