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