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