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