1 /*
   2  * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "c1/c1_Compilation.hpp"
  27 #include "c1/c1_Defs.hpp"
  28 #include "c1/c1_FrameMap.hpp"
  29 #include "c1/c1_Instruction.hpp"
  30 #include "c1/c1_LIRAssembler.hpp"
  31 #include "c1/c1_LIRGenerator.hpp"
  32 #include "c1/c1_ValueStack.hpp"
  33 #include "ci/ciArrayKlass.hpp"
  34 #include "ci/ciInstance.hpp"
  35 #include "ci/ciObjArray.hpp"
  36 #include "ci/ciUtilities.hpp"
  37 #include "gc/shared/barrierSet.hpp"
  38 #include "gc/shared/c1/barrierSetC1.hpp"
  39 #include "oops/klass.inline.hpp"
  40 #include "runtime/sharedRuntime.hpp"
  41 #include "runtime/stubRoutines.hpp"
  42 #include "runtime/vm_version.hpp"
  43 #include "utilities/bitMap.inline.hpp"
  44 #include "utilities/macros.hpp"
  45 #include "utilities/powerOfTwo.hpp"
  46 
  47 #ifdef ASSERT
  48 #define __ gen()->lir(__FILE__, __LINE__)->
  49 #else
  50 #define __ gen()->lir()->
  51 #endif
  52 
  53 #ifndef PATCHED_ADDR
  54 #define PATCHED_ADDR  (max_jint)
  55 #endif
  56 
  57 void PhiResolverState::reset() {
  58   _virtual_operands.clear();
  59   _other_operands.clear();
  60   _vreg_table.clear();
  61 }
  62 
  63 
  64 //--------------------------------------------------------------
  65 // PhiResolver
  66 
  67 // Resolves cycles:
  68 //
  69 //  r1 := r2  becomes  temp := r1
  70 //  r2 := r1           r1 := r2
  71 //                     r2 := temp
  72 // and orders moves:
  73 //
  74 //  r2 := r3  becomes  r1 := r2
  75 //  r1 := r2           r2 := r3
  76 
  77 PhiResolver::PhiResolver(LIRGenerator* gen)
  78  : _gen(gen)
  79  , _state(gen->resolver_state())
  80  , _temp(LIR_OprFact::illegalOpr)
  81 {
  82   // reinitialize the shared state arrays
  83   _state.reset();
  84 }
  85 
  86 
  87 void PhiResolver::emit_move(LIR_Opr src, LIR_Opr dest) {
  88   assert(src->is_valid(), "");
  89   assert(dest->is_valid(), "");
  90   __ move(src, dest);
  91 }
  92 
  93 
  94 void PhiResolver::move_temp_to(LIR_Opr dest) {
  95   assert(_temp->is_valid(), "");
  96   emit_move(_temp, dest);
  97   NOT_PRODUCT(_temp = LIR_OprFact::illegalOpr);
  98 }
  99 
 100 
 101 void PhiResolver::move_to_temp(LIR_Opr src) {
 102   assert(_temp->is_illegal(), "");
 103   _temp = _gen->new_register(src->type());
 104   emit_move(src, _temp);
 105 }
 106 
 107 
 108 // Traverse assignment graph in depth first order and generate moves in post order
 109 // ie. two assignments: b := c, a := b start with node c:
 110 // Call graph: move(NULL, c) -> move(c, b) -> move(b, a)
 111 // Generates moves in this order: move b to a and move c to b
 112 // ie. cycle a := b, b := a start with node a
 113 // Call graph: move(NULL, a) -> move(a, b) -> move(b, a)
 114 // Generates moves in this order: move b to temp, move a to b, move temp to a
 115 void PhiResolver::move(ResolveNode* src, ResolveNode* dest) {
 116   if (!dest->visited()) {
 117     dest->set_visited();
 118     for (int i = dest->no_of_destinations()-1; i >= 0; i --) {
 119       move(dest, dest->destination_at(i));
 120     }
 121   } else if (!dest->start_node()) {
 122     // cylce in graph detected
 123     assert(_loop == NULL, "only one loop valid!");
 124     _loop = dest;
 125     move_to_temp(src->operand());
 126     return;
 127   } // else dest is a start node
 128 
 129   if (!dest->assigned()) {
 130     if (_loop == dest) {
 131       move_temp_to(dest->operand());
 132       dest->set_assigned();
 133     } else if (src != NULL) {
 134       emit_move(src->operand(), dest->operand());
 135       dest->set_assigned();
 136     }
 137   }
 138 }
 139 
 140 
 141 PhiResolver::~PhiResolver() {
 142   int i;
 143   // resolve any cycles in moves from and to virtual registers
 144   for (i = virtual_operands().length() - 1; i >= 0; i --) {
 145     ResolveNode* node = virtual_operands().at(i);
 146     if (!node->visited()) {
 147       _loop = NULL;
 148       move(NULL, node);
 149       node->set_start_node();
 150       assert(_temp->is_illegal(), "move_temp_to() call missing");
 151     }
 152   }
 153 
 154   // generate move for move from non virtual register to abitrary destination
 155   for (i = other_operands().length() - 1; i >= 0; i --) {
 156     ResolveNode* node = other_operands().at(i);
 157     for (int j = node->no_of_destinations() - 1; j >= 0; j --) {
 158       emit_move(node->operand(), node->destination_at(j)->operand());
 159     }
 160   }
 161 }
 162 
 163 
 164 ResolveNode* PhiResolver::create_node(LIR_Opr opr, bool source) {
 165   ResolveNode* node;
 166   if (opr->is_virtual()) {
 167     int vreg_num = opr->vreg_number();
 168     node = vreg_table().at_grow(vreg_num, NULL);
 169     assert(node == NULL || node->operand() == opr, "");
 170     if (node == NULL) {
 171       node = new ResolveNode(opr);
 172       vreg_table().at_put(vreg_num, node);
 173     }
 174     // Make sure that all virtual operands show up in the list when
 175     // they are used as the source of a move.
 176     if (source && !virtual_operands().contains(node)) {
 177       virtual_operands().append(node);
 178     }
 179   } else {
 180     assert(source, "");
 181     node = new ResolveNode(opr);
 182     other_operands().append(node);
 183   }
 184   return node;
 185 }
 186 
 187 
 188 void PhiResolver::move(LIR_Opr src, LIR_Opr dest) {
 189   assert(dest->is_virtual(), "");
 190   // tty->print("move "); src->print(); tty->print(" to "); dest->print(); tty->cr();
 191   assert(src->is_valid(), "");
 192   assert(dest->is_valid(), "");
 193   ResolveNode* source = source_node(src);
 194   source->append(destination_node(dest));
 195 }
 196 
 197 
 198 //--------------------------------------------------------------
 199 // LIRItem
 200 
 201 void LIRItem::set_result(LIR_Opr opr) {
 202   assert(value()->operand()->is_illegal() || value()->operand()->is_constant(), "operand should never change");
 203   value()->set_operand(opr);
 204 
 205   if (opr->is_virtual()) {
 206     _gen->_instruction_for_operand.at_put_grow(opr->vreg_number(), value(), NULL);
 207   }
 208 
 209   _result = opr;
 210 }
 211 
 212 void LIRItem::load_item() {
 213   if (result()->is_illegal()) {
 214     // update the items result
 215     _result = value()->operand();
 216   }
 217   if (!result()->is_register()) {
 218     LIR_Opr reg = _gen->new_register(value()->type());
 219     __ move(result(), reg);
 220     if (result()->is_constant()) {
 221       _result = reg;
 222     } else {
 223       set_result(reg);
 224     }
 225   }
 226 }
 227 
 228 
 229 void LIRItem::load_for_store(BasicType type) {
 230   if (_gen->can_store_as_constant(value(), type)) {
 231     _result = value()->operand();
 232     if (!_result->is_constant()) {
 233       _result = LIR_OprFact::value_type(value()->type());
 234     }
 235   } else if (type == T_BYTE || type == T_BOOLEAN) {
 236     load_byte_item();
 237   } else {
 238     load_item();
 239   }
 240 }
 241 
 242 void LIRItem::load_item_force(LIR_Opr reg) {
 243   LIR_Opr r = result();
 244   if (r != reg) {
 245 #if !defined(ARM) && !defined(E500V2)
 246     if (r->type() != reg->type()) {
 247       // moves between different types need an intervening spill slot
 248       r = _gen->force_to_spill(r, reg->type());
 249     }
 250 #endif
 251     __ move(r, reg);
 252     _result = reg;
 253   }
 254 }
 255 
 256 ciObject* LIRItem::get_jobject_constant() const {
 257   ObjectType* oc = type()->as_ObjectType();
 258   if (oc) {
 259     return oc->constant_value();
 260   }
 261   return NULL;
 262 }
 263 
 264 
 265 jint LIRItem::get_jint_constant() const {
 266   assert(is_constant() && value() != NULL, "");
 267   assert(type()->as_IntConstant() != NULL, "type check");
 268   return type()->as_IntConstant()->value();
 269 }
 270 
 271 
 272 jint LIRItem::get_address_constant() const {
 273   assert(is_constant() && value() != NULL, "");
 274   assert(type()->as_AddressConstant() != NULL, "type check");
 275   return type()->as_AddressConstant()->value();
 276 }
 277 
 278 
 279 jfloat LIRItem::get_jfloat_constant() const {
 280   assert(is_constant() && value() != NULL, "");
 281   assert(type()->as_FloatConstant() != NULL, "type check");
 282   return type()->as_FloatConstant()->value();
 283 }
 284 
 285 
 286 jdouble LIRItem::get_jdouble_constant() const {
 287   assert(is_constant() && value() != NULL, "");
 288   assert(type()->as_DoubleConstant() != NULL, "type check");
 289   return type()->as_DoubleConstant()->value();
 290 }
 291 
 292 
 293 jlong LIRItem::get_jlong_constant() const {
 294   assert(is_constant() && value() != NULL, "");
 295   assert(type()->as_LongConstant() != NULL, "type check");
 296   return type()->as_LongConstant()->value();
 297 }
 298 
 299 
 300 
 301 //--------------------------------------------------------------
 302 
 303 
 304 void LIRGenerator::block_do_prolog(BlockBegin* block) {
 305 #ifndef PRODUCT
 306   if (PrintIRWithLIR) {
 307     block->print();
 308   }
 309 #endif
 310 
 311   // set up the list of LIR instructions
 312   assert(block->lir() == NULL, "LIR list already computed for this block");
 313   _lir = new LIR_List(compilation(), block);
 314   block->set_lir(_lir);
 315 
 316   __ branch_destination(block->label());
 317 
 318   if (LIRTraceExecution &&
 319       Compilation::current()->hir()->start()->block_id() != block->block_id() &&
 320       !block->is_set(BlockBegin::exception_entry_flag)) {
 321     assert(block->lir()->instructions_list()->length() == 1, "should come right after br_dst");
 322     trace_block_entry(block);
 323   }
 324 }
 325 
 326 
 327 void LIRGenerator::block_do_epilog(BlockBegin* block) {
 328 #ifndef PRODUCT
 329   if (PrintIRWithLIR) {
 330     tty->cr();
 331   }
 332 #endif
 333 
 334   // LIR_Opr for unpinned constants shouldn't be referenced by other
 335   // blocks so clear them out after processing the block.
 336   for (int i = 0; i < _unpinned_constants.length(); i++) {
 337     _unpinned_constants.at(i)->clear_operand();
 338   }
 339   _unpinned_constants.trunc_to(0);
 340 
 341   // clear our any registers for other local constants
 342   _constants.trunc_to(0);
 343   _reg_for_constants.trunc_to(0);
 344 }
 345 
 346 
 347 void LIRGenerator::block_do(BlockBegin* block) {
 348   CHECK_BAILOUT();
 349 
 350   block_do_prolog(block);
 351   set_block(block);
 352 
 353   for (Instruction* instr = block; instr != NULL; instr = instr->next()) {
 354     if (instr->is_pinned()) do_root(instr);
 355   }
 356 
 357   set_block(NULL);
 358   block_do_epilog(block);
 359 }
 360 
 361 
 362 //-------------------------LIRGenerator-----------------------------
 363 
 364 // This is where the tree-walk starts; instr must be root;
 365 void LIRGenerator::do_root(Value instr) {
 366   CHECK_BAILOUT();
 367 
 368   InstructionMark im(compilation(), instr);
 369 
 370   assert(instr->is_pinned(), "use only with roots");
 371   assert(instr->subst() == instr, "shouldn't have missed substitution");
 372 
 373   instr->visit(this);
 374 
 375   assert(!instr->has_uses() || instr->operand()->is_valid() ||
 376          instr->as_Constant() != NULL || bailed_out(), "invalid item set");
 377 }
 378 
 379 
 380 // This is called for each node in tree; the walk stops if a root is reached
 381 void LIRGenerator::walk(Value instr) {
 382   InstructionMark im(compilation(), instr);
 383   //stop walk when encounter a root
 384   if ((instr->is_pinned() && instr->as_Phi() == NULL) || instr->operand()->is_valid()) {
 385     assert(instr->operand() != LIR_OprFact::illegalOpr || instr->as_Constant() != NULL, "this root has not yet been visited");
 386   } else {
 387     assert(instr->subst() == instr, "shouldn't have missed substitution");
 388     instr->visit(this);
 389     // assert(instr->use_count() > 0 || instr->as_Phi() != NULL, "leaf instruction must have a use");
 390   }
 391 }
 392 
 393 
 394 CodeEmitInfo* LIRGenerator::state_for(Instruction* x, ValueStack* state, bool ignore_xhandler) {
 395   assert(state != NULL, "state must be defined");
 396 
 397 #ifndef PRODUCT
 398   state->verify();
 399 #endif
 400 
 401   ValueStack* s = state;
 402   for_each_state(s) {
 403     if (s->kind() == ValueStack::EmptyExceptionState) {
 404       assert(s->stack_size() == 0 && s->locals_size() == 0 && (s->locks_size() == 0 || s->locks_size() == 1), "state must be empty");
 405       continue;
 406     }
 407 
 408     int index;
 409     Value value;
 410     for_each_stack_value(s, index, value) {
 411       assert(value->subst() == value, "missed substitution");
 412       if (!value->is_pinned() && value->as_Constant() == NULL && value->as_Local() == NULL) {
 413         walk(value);
 414         assert(value->operand()->is_valid(), "must be evaluated now");
 415       }
 416     }
 417 
 418     int bci = s->bci();
 419     IRScope* scope = s->scope();
 420     ciMethod* method = scope->method();
 421 
 422     MethodLivenessResult liveness = method->liveness_at_bci(bci);
 423     if (bci == SynchronizationEntryBCI) {
 424       if (x->as_ExceptionObject() || x->as_Throw()) {
 425         // all locals are dead on exit from the synthetic unlocker
 426         liveness.clear();
 427       } else {
 428         assert(x->as_MonitorEnter() || x->as_ProfileInvoke(), "only other cases are MonitorEnter and ProfileInvoke");
 429       }
 430     }
 431     if (!liveness.is_valid()) {
 432       // Degenerate or breakpointed method.
 433       bailout("Degenerate or breakpointed method");
 434     } else {
 435       assert((int)liveness.size() == s->locals_size(), "error in use of liveness");
 436       for_each_local_value(s, index, value) {
 437         assert(value->subst() == value, "missed substition");
 438         if (liveness.at(index) && !value->type()->is_illegal()) {
 439           if (!value->is_pinned() && value->as_Constant() == NULL && value->as_Local() == NULL) {
 440             walk(value);
 441             assert(value->operand()->is_valid(), "must be evaluated now");
 442           }
 443         } else {
 444           // NULL out this local so that linear scan can assume that all non-NULL values are live.
 445           s->invalidate_local(index);
 446         }
 447       }
 448     }
 449   }
 450 
 451   return new CodeEmitInfo(state, ignore_xhandler ? NULL : x->exception_handlers(), x->check_flag(Instruction::DeoptimizeOnException));
 452 }
 453 
 454 
 455 CodeEmitInfo* LIRGenerator::state_for(Instruction* x) {
 456   return state_for(x, x->exception_state());
 457 }
 458 
 459 
 460 void LIRGenerator::klass2reg_with_patching(LIR_Opr r, ciMetadata* obj, CodeEmitInfo* info, bool need_resolve) {
 461   /* C2 relies on constant pool entries being resolved (ciTypeFlow), so if tiered compilation
 462    * is active and the class hasn't yet been resolved we need to emit a patch that resolves
 463    * the class. */
 464   if ((!CompilerConfig::is_c1_only_no_jvmci() && need_resolve) || !obj->is_loaded() || PatchALot) {
 465     assert(info != NULL, "info must be set if class is not loaded");
 466     __ klass2reg_patch(NULL, r, info);
 467   } else {
 468     // no patching needed
 469     __ metadata2reg(obj->constant_encoding(), r);
 470   }
 471 }
 472 
 473 
 474 void LIRGenerator::array_range_check(LIR_Opr array, LIR_Opr index,
 475                                     CodeEmitInfo* null_check_info, CodeEmitInfo* range_check_info) {
 476   CodeStub* stub = new RangeCheckStub(range_check_info, index, array);
 477   if (index->is_constant()) {
 478     cmp_mem_int(lir_cond_belowEqual, array, arrayOopDesc::length_offset_in_bytes(),
 479                 index->as_jint(), null_check_info);
 480     __ branch(lir_cond_belowEqual, stub); // forward branch
 481   } else {
 482     cmp_reg_mem(lir_cond_aboveEqual, index, array,
 483                 arrayOopDesc::length_offset_in_bytes(), T_INT, null_check_info);
 484     __ branch(lir_cond_aboveEqual, stub); // forward branch
 485   }
 486 }
 487 
 488 
 489 void LIRGenerator::nio_range_check(LIR_Opr buffer, LIR_Opr index, LIR_Opr result, CodeEmitInfo* info) {
 490   CodeStub* stub = new RangeCheckStub(info, index);
 491   if (index->is_constant()) {
 492     cmp_mem_int(lir_cond_belowEqual, buffer, java_nio_Buffer::limit_offset(), index->as_jint(), info);
 493     __ branch(lir_cond_belowEqual, stub); // forward branch
 494   } else {
 495     cmp_reg_mem(lir_cond_aboveEqual, index, buffer,
 496                 java_nio_Buffer::limit_offset(), T_INT, info);
 497     __ branch(lir_cond_aboveEqual, stub); // forward branch
 498   }
 499   __ move(index, result);
 500 }
 501 
 502 
 503 
 504 void LIRGenerator::arithmetic_op(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, LIR_Opr tmp_op, CodeEmitInfo* info) {
 505   LIR_Opr result_op = result;
 506   LIR_Opr left_op   = left;
 507   LIR_Opr right_op  = right;
 508 
 509   if (TwoOperandLIRForm && left_op != result_op) {
 510     assert(right_op != result_op, "malformed");
 511     __ move(left_op, result_op);
 512     left_op = result_op;
 513   }
 514 
 515   switch(code) {
 516     case Bytecodes::_dadd:
 517     case Bytecodes::_fadd:
 518     case Bytecodes::_ladd:
 519     case Bytecodes::_iadd:  __ add(left_op, right_op, result_op); break;
 520     case Bytecodes::_fmul:
 521     case Bytecodes::_lmul:  __ mul(left_op, right_op, result_op); break;
 522 
 523     case Bytecodes::_dmul:  __ mul(left_op, right_op, result_op, tmp_op); break;
 524 
 525     case Bytecodes::_imul:
 526       {
 527         bool did_strength_reduce = false;
 528 
 529         if (right->is_constant()) {
 530           jint c = right->as_jint();
 531           if (c > 0 && is_power_of_2(c)) {
 532             // do not need tmp here
 533             __ shift_left(left_op, exact_log2(c), result_op);
 534             did_strength_reduce = true;
 535           } else {
 536             did_strength_reduce = strength_reduce_multiply(left_op, c, result_op, tmp_op);
 537           }
 538         }
 539         // we couldn't strength reduce so just emit the multiply
 540         if (!did_strength_reduce) {
 541           __ mul(left_op, right_op, result_op);
 542         }
 543       }
 544       break;
 545 
 546     case Bytecodes::_dsub:
 547     case Bytecodes::_fsub:
 548     case Bytecodes::_lsub:
 549     case Bytecodes::_isub: __ sub(left_op, right_op, result_op); break;
 550 
 551     case Bytecodes::_fdiv: __ div (left_op, right_op, result_op); break;
 552     // ldiv and lrem are implemented with a direct runtime call
 553 
 554     case Bytecodes::_ddiv: __ div(left_op, right_op, result_op, tmp_op); break;
 555 
 556     case Bytecodes::_drem:
 557     case Bytecodes::_frem: __ rem (left_op, right_op, result_op); break;
 558 
 559     default: ShouldNotReachHere();
 560   }
 561 }
 562 
 563 
 564 void LIRGenerator::arithmetic_op_int(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, LIR_Opr tmp) {
 565   arithmetic_op(code, result, left, right, tmp);
 566 }
 567 
 568 
 569 void LIRGenerator::arithmetic_op_long(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, CodeEmitInfo* info) {
 570   arithmetic_op(code, result, left, right, LIR_OprFact::illegalOpr, info);
 571 }
 572 
 573 
 574 void LIRGenerator::arithmetic_op_fpu(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, LIR_Opr tmp) {
 575   arithmetic_op(code, result, left, right, tmp);
 576 }
 577 
 578 
 579 void LIRGenerator::shift_op(Bytecodes::Code code, LIR_Opr result_op, LIR_Opr value, LIR_Opr count, LIR_Opr tmp) {
 580 
 581   if (TwoOperandLIRForm && value != result_op
 582       // Only 32bit right shifts require two operand form on S390.
 583       S390_ONLY(&& (code == Bytecodes::_ishr || code == Bytecodes::_iushr))) {
 584     assert(count != result_op, "malformed");
 585     __ move(value, result_op);
 586     value = result_op;
 587   }
 588 
 589   assert(count->is_constant() || count->is_register(), "must be");
 590   switch(code) {
 591   case Bytecodes::_ishl:
 592   case Bytecodes::_lshl: __ shift_left(value, count, result_op, tmp); break;
 593   case Bytecodes::_ishr:
 594   case Bytecodes::_lshr: __ shift_right(value, count, result_op, tmp); break;
 595   case Bytecodes::_iushr:
 596   case Bytecodes::_lushr: __ unsigned_shift_right(value, count, result_op, tmp); break;
 597   default: ShouldNotReachHere();
 598   }
 599 }
 600 
 601 
 602 void LIRGenerator::logic_op (Bytecodes::Code code, LIR_Opr result_op, LIR_Opr left_op, LIR_Opr right_op) {
 603   if (TwoOperandLIRForm && left_op != result_op) {
 604     assert(right_op != result_op, "malformed");
 605     __ move(left_op, result_op);
 606     left_op = result_op;
 607   }
 608 
 609   switch(code) {
 610     case Bytecodes::_iand:
 611     case Bytecodes::_land:  __ logical_and(left_op, right_op, result_op); break;
 612 
 613     case Bytecodes::_ior:
 614     case Bytecodes::_lor:   __ logical_or(left_op, right_op, result_op);  break;
 615 
 616     case Bytecodes::_ixor:
 617     case Bytecodes::_lxor:  __ logical_xor(left_op, right_op, result_op); break;
 618 
 619     default: ShouldNotReachHere();
 620   }
 621 }
 622 
 623 
 624 void LIRGenerator::monitor_enter(LIR_Opr object, LIR_Opr lock, LIR_Opr hdr, LIR_Opr scratch, int monitor_no, CodeEmitInfo* info_for_exception, CodeEmitInfo* info) {
 625   if (!GenerateSynchronizationCode) return;
 626   // for slow path, use debug info for state after successful locking
 627   CodeStub* slow_path = new MonitorEnterStub(object, lock, info);
 628   __ load_stack_address_monitor(monitor_no, lock);
 629   // for handling NullPointerException, use debug info representing just the lock stack before this monitorenter
 630   __ lock_object(hdr, object, lock, scratch, slow_path, info_for_exception);
 631 }
 632 
 633 
 634 void LIRGenerator::monitor_exit(LIR_Opr object, LIR_Opr lock, LIR_Opr new_hdr, LIR_Opr scratch, int monitor_no) {
 635   if (!GenerateSynchronizationCode) return;
 636   // setup registers
 637   LIR_Opr hdr = lock;
 638   lock = new_hdr;
 639   CodeStub* slow_path = new MonitorExitStub(lock, UseFastLocking, monitor_no);
 640   __ load_stack_address_monitor(monitor_no, lock);
 641   __ unlock_object(hdr, object, lock, scratch, slow_path);
 642 }
 643 
 644 #ifndef PRODUCT
 645 void LIRGenerator::print_if_not_loaded(const NewInstance* new_instance) {
 646   if (PrintNotLoaded && !new_instance->klass()->is_loaded()) {
 647     tty->print_cr("   ###class not loaded at new bci %d", new_instance->printable_bci());
 648   } else if (PrintNotLoaded && (!CompilerConfig::is_c1_only_no_jvmci() && new_instance->is_unresolved())) {
 649     tty->print_cr("   ###class not resolved at new bci %d", new_instance->printable_bci());
 650   }
 651 }
 652 #endif
 653 
 654 void LIRGenerator::new_instance(LIR_Opr dst, ciInstanceKlass* klass, bool is_unresolved, LIR_Opr scratch1, LIR_Opr scratch2, LIR_Opr scratch3, LIR_Opr scratch4, LIR_Opr klass_reg, CodeEmitInfo* info) {
 655   klass2reg_with_patching(klass_reg, klass, info, is_unresolved);
 656   // If klass is not loaded we do not know if the klass has finalizers:
 657   if (UseFastNewInstance && klass->is_loaded()
 658       && !Klass::layout_helper_needs_slow_path(klass->layout_helper())) {
 659 
 660     Runtime1::StubID stub_id = klass->is_initialized() ? Runtime1::fast_new_instance_id : Runtime1::fast_new_instance_init_check_id;
 661 
 662     CodeStub* slow_path = new NewInstanceStub(klass_reg, dst, klass, info, stub_id);
 663 
 664     assert(klass->is_loaded(), "must be loaded");
 665     // allocate space for instance
 666     assert(klass->size_helper() > 0, "illegal instance size");
 667     const int instance_size = align_object_size(klass->size_helper());
 668     __ allocate_object(dst, scratch1, scratch2, scratch3, scratch4,
 669                        oopDesc::header_size(), instance_size, klass_reg, !klass->is_initialized(), slow_path);
 670   } else {
 671     CodeStub* slow_path = new NewInstanceStub(klass_reg, dst, klass, info, Runtime1::new_instance_id);
 672     __ branch(lir_cond_always, slow_path);
 673     __ branch_destination(slow_path->continuation());
 674   }
 675 }
 676 
 677 
 678 static bool is_constant_zero(Instruction* inst) {
 679   IntConstant* c = inst->type()->as_IntConstant();
 680   if (c) {
 681     return (c->value() == 0);
 682   }
 683   return false;
 684 }
 685 
 686 
 687 static bool positive_constant(Instruction* inst) {
 688   IntConstant* c = inst->type()->as_IntConstant();
 689   if (c) {
 690     return (c->value() >= 0);
 691   }
 692   return false;
 693 }
 694 
 695 
 696 static ciArrayKlass* as_array_klass(ciType* type) {
 697   if (type != NULL && type->is_array_klass() && type->is_loaded()) {
 698     return (ciArrayKlass*)type;
 699   } else {
 700     return NULL;
 701   }
 702 }
 703 
 704 static ciType* phi_declared_type(Phi* phi) {
 705   ciType* t = phi->operand_at(0)->declared_type();
 706   if (t == NULL) {
 707     return NULL;
 708   }
 709   for(int i = 1; i < phi->operand_count(); i++) {
 710     if (t != phi->operand_at(i)->declared_type()) {
 711       return NULL;
 712     }
 713   }
 714   return t;
 715 }
 716 
 717 void LIRGenerator::arraycopy_helper(Intrinsic* x, int* flagsp, ciArrayKlass** expected_typep) {
 718   Instruction* src     = x->argument_at(0);
 719   Instruction* src_pos = x->argument_at(1);
 720   Instruction* dst     = x->argument_at(2);
 721   Instruction* dst_pos = x->argument_at(3);
 722   Instruction* length  = x->argument_at(4);
 723 
 724   // first try to identify the likely type of the arrays involved
 725   ciArrayKlass* expected_type = NULL;
 726   bool is_exact = false, src_objarray = false, dst_objarray = false;
 727   {
 728     ciArrayKlass* src_exact_type    = as_array_klass(src->exact_type());
 729     ciArrayKlass* src_declared_type = as_array_klass(src->declared_type());
 730     Phi* phi;
 731     if (src_declared_type == NULL && (phi = src->as_Phi()) != NULL) {
 732       src_declared_type = as_array_klass(phi_declared_type(phi));
 733     }
 734     ciArrayKlass* dst_exact_type    = as_array_klass(dst->exact_type());
 735     ciArrayKlass* dst_declared_type = as_array_klass(dst->declared_type());
 736     if (dst_declared_type == NULL && (phi = dst->as_Phi()) != NULL) {
 737       dst_declared_type = as_array_klass(phi_declared_type(phi));
 738     }
 739 
 740     if (src_exact_type != NULL && src_exact_type == dst_exact_type) {
 741       // the types exactly match so the type is fully known
 742       is_exact = true;
 743       expected_type = src_exact_type;
 744     } else if (dst_exact_type != NULL && dst_exact_type->is_obj_array_klass()) {
 745       ciArrayKlass* dst_type = (ciArrayKlass*) dst_exact_type;
 746       ciArrayKlass* src_type = NULL;
 747       if (src_exact_type != NULL && src_exact_type->is_obj_array_klass()) {
 748         src_type = (ciArrayKlass*) src_exact_type;
 749       } else if (src_declared_type != NULL && src_declared_type->is_obj_array_klass()) {
 750         src_type = (ciArrayKlass*) src_declared_type;
 751       }
 752       if (src_type != NULL) {
 753         if (src_type->element_type()->is_subtype_of(dst_type->element_type())) {
 754           is_exact = true;
 755           expected_type = dst_type;
 756         }
 757       }
 758     }
 759     // at least pass along a good guess
 760     if (expected_type == NULL) expected_type = dst_exact_type;
 761     if (expected_type == NULL) expected_type = src_declared_type;
 762     if (expected_type == NULL) expected_type = dst_declared_type;
 763 
 764     src_objarray = (src_exact_type && src_exact_type->is_obj_array_klass()) || (src_declared_type && src_declared_type->is_obj_array_klass());
 765     dst_objarray = (dst_exact_type && dst_exact_type->is_obj_array_klass()) || (dst_declared_type && dst_declared_type->is_obj_array_klass());
 766   }
 767 
 768   // if a probable array type has been identified, figure out if any
 769   // of the required checks for a fast case can be elided.
 770   int flags = LIR_OpArrayCopy::all_flags;
 771 
 772   if (!src_objarray)
 773     flags &= ~LIR_OpArrayCopy::src_objarray;
 774   if (!dst_objarray)
 775     flags &= ~LIR_OpArrayCopy::dst_objarray;
 776 
 777   if (!x->arg_needs_null_check(0))
 778     flags &= ~LIR_OpArrayCopy::src_null_check;
 779   if (!x->arg_needs_null_check(2))
 780     flags &= ~LIR_OpArrayCopy::dst_null_check;
 781 
 782 
 783   if (expected_type != NULL) {
 784     Value length_limit = NULL;
 785 
 786     IfOp* ifop = length->as_IfOp();
 787     if (ifop != NULL) {
 788       // look for expressions like min(v, a.length) which ends up as
 789       //   x > y ? y : x  or  x >= y ? y : x
 790       if ((ifop->cond() == If::gtr || ifop->cond() == If::geq) &&
 791           ifop->x() == ifop->fval() &&
 792           ifop->y() == ifop->tval()) {
 793         length_limit = ifop->y();
 794       }
 795     }
 796 
 797     // try to skip null checks and range checks
 798     NewArray* src_array = src->as_NewArray();
 799     if (src_array != NULL) {
 800       flags &= ~LIR_OpArrayCopy::src_null_check;
 801       if (length_limit != NULL &&
 802           src_array->length() == length_limit &&
 803           is_constant_zero(src_pos)) {
 804         flags &= ~LIR_OpArrayCopy::src_range_check;
 805       }
 806     }
 807 
 808     NewArray* dst_array = dst->as_NewArray();
 809     if (dst_array != NULL) {
 810       flags &= ~LIR_OpArrayCopy::dst_null_check;
 811       if (length_limit != NULL &&
 812           dst_array->length() == length_limit &&
 813           is_constant_zero(dst_pos)) {
 814         flags &= ~LIR_OpArrayCopy::dst_range_check;
 815       }
 816     }
 817 
 818     // check from incoming constant values
 819     if (positive_constant(src_pos))
 820       flags &= ~LIR_OpArrayCopy::src_pos_positive_check;
 821     if (positive_constant(dst_pos))
 822       flags &= ~LIR_OpArrayCopy::dst_pos_positive_check;
 823     if (positive_constant(length))
 824       flags &= ~LIR_OpArrayCopy::length_positive_check;
 825 
 826     // see if the range check can be elided, which might also imply
 827     // that src or dst is non-null.
 828     ArrayLength* al = length->as_ArrayLength();
 829     if (al != NULL) {
 830       if (al->array() == src) {
 831         // it's the length of the source array
 832         flags &= ~LIR_OpArrayCopy::length_positive_check;
 833         flags &= ~LIR_OpArrayCopy::src_null_check;
 834         if (is_constant_zero(src_pos))
 835           flags &= ~LIR_OpArrayCopy::src_range_check;
 836       }
 837       if (al->array() == dst) {
 838         // it's the length of the destination array
 839         flags &= ~LIR_OpArrayCopy::length_positive_check;
 840         flags &= ~LIR_OpArrayCopy::dst_null_check;
 841         if (is_constant_zero(dst_pos))
 842           flags &= ~LIR_OpArrayCopy::dst_range_check;
 843       }
 844     }
 845     if (is_exact) {
 846       flags &= ~LIR_OpArrayCopy::type_check;
 847     }
 848   }
 849 
 850   IntConstant* src_int = src_pos->type()->as_IntConstant();
 851   IntConstant* dst_int = dst_pos->type()->as_IntConstant();
 852   if (src_int && dst_int) {
 853     int s_offs = src_int->value();
 854     int d_offs = dst_int->value();
 855     if (src_int->value() >= dst_int->value()) {
 856       flags &= ~LIR_OpArrayCopy::overlapping;
 857     }
 858     if (expected_type != NULL) {
 859       BasicType t = expected_type->element_type()->basic_type();
 860       int element_size = type2aelembytes(t);
 861       if (((arrayOopDesc::base_offset_in_bytes(t) + s_offs * element_size) % HeapWordSize == 0) &&
 862           ((arrayOopDesc::base_offset_in_bytes(t) + d_offs * element_size) % HeapWordSize == 0)) {
 863         flags &= ~LIR_OpArrayCopy::unaligned;
 864       }
 865     }
 866   } else if (src_pos == dst_pos || is_constant_zero(dst_pos)) {
 867     // src and dest positions are the same, or dst is zero so assume
 868     // nonoverlapping copy.
 869     flags &= ~LIR_OpArrayCopy::overlapping;
 870   }
 871 
 872   if (src == dst) {
 873     // moving within a single array so no type checks are needed
 874     if (flags & LIR_OpArrayCopy::type_check) {
 875       flags &= ~LIR_OpArrayCopy::type_check;
 876     }
 877   }
 878   *flagsp = flags;
 879   *expected_typep = (ciArrayKlass*)expected_type;
 880 }
 881 
 882 
 883 LIR_Opr LIRGenerator::round_item(LIR_Opr opr) {
 884   assert(opr->is_register(), "why spill if item is not register?");
 885 
 886   if (strict_fp_requires_explicit_rounding) {
 887 #ifdef IA32
 888     if (UseSSE < 1 && opr->is_single_fpu()) {
 889       LIR_Opr result = new_register(T_FLOAT);
 890       set_vreg_flag(result, must_start_in_memory);
 891       assert(opr->is_register(), "only a register can be spilled");
 892       assert(opr->value_type()->is_float(), "rounding only for floats available");
 893       __ roundfp(opr, LIR_OprFact::illegalOpr, result);
 894       return result;
 895     }
 896 #else
 897     Unimplemented();
 898 #endif // IA32
 899   }
 900   return opr;
 901 }
 902 
 903 
 904 LIR_Opr LIRGenerator::force_to_spill(LIR_Opr value, BasicType t) {
 905   assert(type2size[t] == type2size[value->type()],
 906          "size mismatch: t=%s, value->type()=%s", type2name(t), type2name(value->type()));
 907   if (!value->is_register()) {
 908     // force into a register
 909     LIR_Opr r = new_register(value->type());
 910     __ move(value, r);
 911     value = r;
 912   }
 913 
 914   // create a spill location
 915   LIR_Opr tmp = new_register(t);
 916   set_vreg_flag(tmp, LIRGenerator::must_start_in_memory);
 917 
 918   // move from register to spill
 919   __ move(value, tmp);
 920   return tmp;
 921 }
 922 
 923 void LIRGenerator::profile_branch(If* if_instr, If::Condition cond) {
 924   if (if_instr->should_profile()) {
 925     ciMethod* method = if_instr->profiled_method();
 926     assert(method != NULL, "method should be set if branch is profiled");
 927     ciMethodData* md = method->method_data_or_null();
 928     assert(md != NULL, "Sanity");
 929     ciProfileData* data = md->bci_to_data(if_instr->profiled_bci());
 930     assert(data != NULL, "must have profiling data");
 931     assert(data->is_BranchData(), "need BranchData for two-way branches");
 932     int taken_count_offset     = md->byte_offset_of_slot(data, BranchData::taken_offset());
 933     int not_taken_count_offset = md->byte_offset_of_slot(data, BranchData::not_taken_offset());
 934     if (if_instr->is_swapped()) {
 935       int t = taken_count_offset;
 936       taken_count_offset = not_taken_count_offset;
 937       not_taken_count_offset = t;
 938     }
 939 
 940     LIR_Opr md_reg = new_register(T_METADATA);
 941     __ metadata2reg(md->constant_encoding(), md_reg);
 942 
 943     LIR_Opr data_offset_reg = new_pointer_register();
 944     __ cmove(lir_cond(cond),
 945              LIR_OprFact::intptrConst(taken_count_offset),
 946              LIR_OprFact::intptrConst(not_taken_count_offset),
 947              data_offset_reg, as_BasicType(if_instr->x()->type()));
 948 
 949     // MDO cells are intptr_t, so the data_reg width is arch-dependent.
 950     LIR_Opr data_reg = new_pointer_register();
 951     LIR_Address* data_addr = new LIR_Address(md_reg, data_offset_reg, data_reg->type());
 952     __ move(data_addr, data_reg);
 953     // Use leal instead of add to avoid destroying condition codes on x86
 954     LIR_Address* fake_incr_value = new LIR_Address(data_reg, DataLayout::counter_increment, T_INT);
 955     __ leal(LIR_OprFact::address(fake_incr_value), data_reg);
 956     __ move(data_reg, data_addr);
 957   }
 958 }
 959 
 960 // Phi technique:
 961 // This is about passing live values from one basic block to the other.
 962 // In code generated with Java it is rather rare that more than one
 963 // value is on the stack from one basic block to the other.
 964 // We optimize our technique for efficient passing of one value
 965 // (of type long, int, double..) but it can be extended.
 966 // When entering or leaving a basic block, all registers and all spill
 967 // slots are release and empty. We use the released registers
 968 // and spill slots to pass the live values from one block
 969 // to the other. The topmost value, i.e., the value on TOS of expression
 970 // stack is passed in registers. All other values are stored in spilling
 971 // area. Every Phi has an index which designates its spill slot
 972 // At exit of a basic block, we fill the register(s) and spill slots.
 973 // At entry of a basic block, the block_prolog sets up the content of phi nodes
 974 // and locks necessary registers and spilling slots.
 975 
 976 
 977 // move current value to referenced phi function
 978 void LIRGenerator::move_to_phi(PhiResolver* resolver, Value cur_val, Value sux_val) {
 979   Phi* phi = sux_val->as_Phi();
 980   // cur_val can be null without phi being null in conjunction with inlining
 981   if (phi != NULL && cur_val != NULL && cur_val != phi && !phi->is_illegal()) {
 982     if (phi->is_local()) {
 983       for (int i = 0; i < phi->operand_count(); i++) {
 984         Value op = phi->operand_at(i);
 985         if (op != NULL && op->type()->is_illegal()) {
 986           bailout("illegal phi operand");
 987         }
 988       }
 989     }
 990     Phi* cur_phi = cur_val->as_Phi();
 991     if (cur_phi != NULL && cur_phi->is_illegal()) {
 992       // Phi and local would need to get invalidated
 993       // (which is unexpected for Linear Scan).
 994       // But this case is very rare so we simply bail out.
 995       bailout("propagation of illegal phi");
 996       return;
 997     }
 998     LIR_Opr operand = cur_val->operand();
 999     if (operand->is_illegal()) {
1000       assert(cur_val->as_Constant() != NULL || cur_val->as_Local() != NULL,
1001              "these can be produced lazily");
1002       operand = operand_for_instruction(cur_val);
1003     }
1004     resolver->move(operand, operand_for_instruction(phi));
1005   }
1006 }
1007 
1008 
1009 // Moves all stack values into their PHI position
1010 void LIRGenerator::move_to_phi(ValueStack* cur_state) {
1011   BlockBegin* bb = block();
1012   if (bb->number_of_sux() == 1) {
1013     BlockBegin* sux = bb->sux_at(0);
1014     assert(sux->number_of_preds() > 0, "invalid CFG");
1015 
1016     // a block with only one predecessor never has phi functions
1017     if (sux->number_of_preds() > 1) {
1018       PhiResolver resolver(this);
1019 
1020       ValueStack* sux_state = sux->state();
1021       Value sux_value;
1022       int index;
1023 
1024       assert(cur_state->scope() == sux_state->scope(), "not matching");
1025       assert(cur_state->locals_size() == sux_state->locals_size(), "not matching");
1026       assert(cur_state->stack_size() == sux_state->stack_size(), "not matching");
1027 
1028       for_each_stack_value(sux_state, index, sux_value) {
1029         move_to_phi(&resolver, cur_state->stack_at(index), sux_value);
1030       }
1031 
1032       for_each_local_value(sux_state, index, sux_value) {
1033         move_to_phi(&resolver, cur_state->local_at(index), sux_value);
1034       }
1035 
1036       assert(cur_state->caller_state() == sux_state->caller_state(), "caller states must be equal");
1037     }
1038   }
1039 }
1040 
1041 
1042 LIR_Opr LIRGenerator::new_register(BasicType type) {
1043   int vreg_num = _virtual_register_number;
1044   // Add a little fudge factor for the bailout since the bailout is only checked periodically. This allows us to hand out
1045   // a few extra registers before we really run out which helps to avoid to trip over assertions.
1046   if (vreg_num + 20 >= LIR_OprDesc::vreg_max) {
1047     bailout("out of virtual registers in LIR generator");
1048     if (vreg_num + 2 >= LIR_OprDesc::vreg_max) {
1049       // Wrap it around and continue until bailout really happens to avoid hitting assertions.
1050       _virtual_register_number = LIR_OprDesc::vreg_base;
1051       vreg_num = LIR_OprDesc::vreg_base;
1052     }
1053   }
1054   _virtual_register_number += 1;
1055   LIR_Opr vreg = LIR_OprFact::virtual_register(vreg_num, type);
1056   assert(vreg != LIR_OprFact::illegal(), "ran out of virtual registers");
1057   return vreg;
1058 }
1059 
1060 
1061 // Try to lock using register in hint
1062 LIR_Opr LIRGenerator::rlock(Value instr) {
1063   return new_register(instr->type());
1064 }
1065 
1066 
1067 // does an rlock and sets result
1068 LIR_Opr LIRGenerator::rlock_result(Value x) {
1069   LIR_Opr reg = rlock(x);
1070   set_result(x, reg);
1071   return reg;
1072 }
1073 
1074 
1075 // does an rlock and sets result
1076 LIR_Opr LIRGenerator::rlock_result(Value x, BasicType type) {
1077   LIR_Opr reg;
1078   switch (type) {
1079   case T_BYTE:
1080   case T_BOOLEAN:
1081     reg = rlock_byte(type);
1082     break;
1083   default:
1084     reg = rlock(x);
1085     break;
1086   }
1087 
1088   set_result(x, reg);
1089   return reg;
1090 }
1091 
1092 
1093 //---------------------------------------------------------------------
1094 ciObject* LIRGenerator::get_jobject_constant(Value value) {
1095   ObjectType* oc = value->type()->as_ObjectType();
1096   if (oc) {
1097     return oc->constant_value();
1098   }
1099   return NULL;
1100 }
1101 
1102 
1103 void LIRGenerator::do_ExceptionObject(ExceptionObject* x) {
1104   assert(block()->is_set(BlockBegin::exception_entry_flag), "ExceptionObject only allowed in exception handler block");
1105   assert(block()->next() == x, "ExceptionObject must be first instruction of block");
1106 
1107   // no moves are created for phi functions at the begin of exception
1108   // handlers, so assign operands manually here
1109   for_each_phi_fun(block(), phi,
1110                    if (!phi->is_illegal()) { operand_for_instruction(phi); });
1111 
1112   LIR_Opr thread_reg = getThreadPointer();
1113   __ move_wide(new LIR_Address(thread_reg, in_bytes(JavaThread::exception_oop_offset()), T_OBJECT),
1114                exceptionOopOpr());
1115   __ move_wide(LIR_OprFact::oopConst(NULL),
1116                new LIR_Address(thread_reg, in_bytes(JavaThread::exception_oop_offset()), T_OBJECT));
1117   __ move_wide(LIR_OprFact::oopConst(NULL),
1118                new LIR_Address(thread_reg, in_bytes(JavaThread::exception_pc_offset()), T_OBJECT));
1119 
1120   LIR_Opr result = new_register(T_OBJECT);
1121   __ move(exceptionOopOpr(), result);
1122   set_result(x, result);
1123 }
1124 
1125 
1126 //----------------------------------------------------------------------
1127 //----------------------------------------------------------------------
1128 //----------------------------------------------------------------------
1129 //----------------------------------------------------------------------
1130 //                        visitor functions
1131 //----------------------------------------------------------------------
1132 //----------------------------------------------------------------------
1133 //----------------------------------------------------------------------
1134 //----------------------------------------------------------------------
1135 
1136 void LIRGenerator::do_Phi(Phi* x) {
1137   // phi functions are never visited directly
1138   ShouldNotReachHere();
1139 }
1140 
1141 
1142 // Code for a constant is generated lazily unless the constant is frequently used and can't be inlined.
1143 void LIRGenerator::do_Constant(Constant* x) {
1144   if (x->state_before() != NULL) {
1145     // Any constant with a ValueStack requires patching so emit the patch here
1146     LIR_Opr reg = rlock_result(x);
1147     CodeEmitInfo* info = state_for(x, x->state_before());
1148     __ oop2reg_patch(NULL, reg, info);
1149   } else if (x->use_count() > 1 && !can_inline_as_constant(x)) {
1150     if (!x->is_pinned()) {
1151       // unpinned constants are handled specially so that they can be
1152       // put into registers when they are used multiple times within a
1153       // block.  After the block completes their operand will be
1154       // cleared so that other blocks can't refer to that register.
1155       set_result(x, load_constant(x));
1156     } else {
1157       LIR_Opr res = x->operand();
1158       if (!res->is_valid()) {
1159         res = LIR_OprFact::value_type(x->type());
1160       }
1161       if (res->is_constant()) {
1162         LIR_Opr reg = rlock_result(x);
1163         __ move(res, reg);
1164       } else {
1165         set_result(x, res);
1166       }
1167     }
1168   } else {
1169     set_result(x, LIR_OprFact::value_type(x->type()));
1170   }
1171 }
1172 
1173 
1174 void LIRGenerator::do_Local(Local* x) {
1175   // operand_for_instruction has the side effect of setting the result
1176   // so there's no need to do it here.
1177   operand_for_instruction(x);
1178 }
1179 
1180 
1181 void LIRGenerator::do_Return(Return* x) {
1182   if (compilation()->env()->dtrace_method_probes()) {
1183     BasicTypeList signature;
1184     signature.append(LP64_ONLY(T_LONG) NOT_LP64(T_INT));    // thread
1185     signature.append(T_METADATA); // Method*
1186     LIR_OprList* args = new LIR_OprList();
1187     args->append(getThreadPointer());
1188     LIR_Opr meth = new_register(T_METADATA);
1189     __ metadata2reg(method()->constant_encoding(), meth);
1190     args->append(meth);
1191     call_runtime(&signature, args, CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit), voidType, NULL);
1192   }
1193 
1194   if (x->type()->is_void()) {
1195     __ return_op(LIR_OprFact::illegalOpr);
1196   } else {
1197     LIR_Opr reg = result_register_for(x->type(), /*callee=*/true);
1198     LIRItem result(x->result(), this);
1199 
1200     result.load_item_force(reg);
1201     __ return_op(result.result());
1202   }
1203   set_no_result(x);
1204 }
1205 
1206 // Examble: ref.get()
1207 // Combination of LoadField and g1 pre-write barrier
1208 void LIRGenerator::do_Reference_get(Intrinsic* x) {
1209 
1210   const int referent_offset = java_lang_ref_Reference::referent_offset();
1211 
1212   assert(x->number_of_arguments() == 1, "wrong type");
1213 
1214   LIRItem reference(x->argument_at(0), this);
1215   reference.load_item();
1216 
1217   // need to perform the null check on the reference objecy
1218   CodeEmitInfo* info = NULL;
1219   if (x->needs_null_check()) {
1220     info = state_for(x);
1221   }
1222 
1223   LIR_Opr result = rlock_result(x, T_OBJECT);
1224   access_load_at(IN_HEAP | ON_WEAK_OOP_REF, T_OBJECT,
1225                  reference, LIR_OprFact::intConst(referent_offset), result);
1226 }
1227 
1228 // Example: clazz.isInstance(object)
1229 void LIRGenerator::do_isInstance(Intrinsic* x) {
1230   assert(x->number_of_arguments() == 2, "wrong type");
1231 
1232   // TODO could try to substitute this node with an equivalent InstanceOf
1233   // if clazz is known to be a constant Class. This will pick up newly found
1234   // constants after HIR construction. I'll leave this to a future change.
1235 
1236   // as a first cut, make a simple leaf call to runtime to stay platform independent.
1237   // could follow the aastore example in a future change.
1238 
1239   LIRItem clazz(x->argument_at(0), this);
1240   LIRItem object(x->argument_at(1), this);
1241   clazz.load_item();
1242   object.load_item();
1243   LIR_Opr result = rlock_result(x);
1244 
1245   // need to perform null check on clazz
1246   if (x->needs_null_check()) {
1247     CodeEmitInfo* info = state_for(x);
1248     __ null_check(clazz.result(), info);
1249   }
1250 
1251   LIR_Opr call_result = call_runtime(clazz.value(), object.value(),
1252                                      CAST_FROM_FN_PTR(address, Runtime1::is_instance_of),
1253                                      x->type(),
1254                                      NULL); // NULL CodeEmitInfo results in a leaf call
1255   __ move(call_result, result);
1256 }
1257 





1258 // Example: object.getClass ()
1259 void LIRGenerator::do_getClass(Intrinsic* x) {
1260   assert(x->number_of_arguments() == 1, "wrong type");
1261 
1262   LIRItem rcvr(x->argument_at(0), this);
1263   rcvr.load_item();
1264   LIR_Opr temp = new_register(T_METADATA);
1265   LIR_Opr result = rlock_result(x);
1266 
1267   // need to perform the null check on the rcvr
1268   CodeEmitInfo* info = NULL;
1269   if (x->needs_null_check()) {
1270     info = state_for(x);
1271   }
1272 
1273   // FIXME T_ADDRESS should actually be T_METADATA but it can't because the
1274   // meaning of these two is mixed up (see JDK-8026837).
1275   __ move(new LIR_Address(rcvr.result(), oopDesc::klass_offset_in_bytes(), T_ADDRESS), temp, info);
1276   __ move_wide(new LIR_Address(temp, in_bytes(Klass::java_mirror_offset()), T_ADDRESS), temp);
1277   // mirror = ((OopHandle)mirror)->resolve();
1278   access_load(IN_NATIVE, T_OBJECT,
1279               LIR_OprFact::address(new LIR_Address(temp, T_OBJECT)), result);
1280 }
1281 
1282 // java.lang.Class::isPrimitive()
1283 void LIRGenerator::do_isPrimitive(Intrinsic* x) {
1284   assert(x->number_of_arguments() == 1, "wrong type");
1285 
1286   LIRItem rcvr(x->argument_at(0), this);
1287   rcvr.load_item();
1288   LIR_Opr temp = new_register(T_METADATA);
1289   LIR_Opr result = rlock_result(x);
1290 
1291   CodeEmitInfo* info = NULL;
1292   if (x->needs_null_check()) {
1293     info = state_for(x);
1294   }
1295 
1296   __ move(new LIR_Address(rcvr.result(), java_lang_Class::klass_offset(), T_ADDRESS), temp, info);
1297   __ cmp(lir_cond_notEqual, temp, LIR_OprFact::metadataConst(0));
1298   __ cmove(lir_cond_notEqual, LIR_OprFact::intConst(0), LIR_OprFact::intConst(1), result, T_BOOLEAN);
1299 }
1300 
1301 // Example: Foo.class.getModifiers()
1302 void LIRGenerator::do_getModifiers(Intrinsic* x) {
1303   assert(x->number_of_arguments() == 1, "wrong type");
1304 
1305   LIRItem receiver(x->argument_at(0), this);
1306   receiver.load_item();
1307   LIR_Opr result = rlock_result(x);
1308 
1309   CodeEmitInfo* info = NULL;
1310   if (x->needs_null_check()) {
1311     info = state_for(x);
1312   }
1313 
1314   // While reading off the universal constant mirror is less efficient than doing
1315   // another branch and returning the constant answer, this branchless code runs into
1316   // much less risk of confusion for C1 register allocator. The choice of the universe
1317   // object here is correct as long as it returns the same modifiers we would expect
1318   // from the primitive class itself. See spec for Class.getModifiers that provides
1319   // the typed array klasses with similar modifiers as their component types.
1320 
1321   Klass* univ_klass_obj = Universe::byteArrayKlassObj();
1322   assert(univ_klass_obj->modifier_flags() == (JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC), "Sanity");
1323   LIR_Opr prim_klass = LIR_OprFact::metadataConst(univ_klass_obj);
1324 
1325   LIR_Opr recv_klass = new_register(T_METADATA);
1326   __ move(new LIR_Address(receiver.result(), java_lang_Class::klass_offset(), T_ADDRESS), recv_klass, info);
1327 
1328   // Check if this is a Java mirror of primitive type, and select the appropriate klass.
1329   LIR_Opr klass = new_register(T_METADATA);
1330   __ cmp(lir_cond_equal, recv_klass, LIR_OprFact::metadataConst(0));
1331   __ cmove(lir_cond_equal, prim_klass, recv_klass, klass, T_ADDRESS);
1332 
1333   // Get the answer.
1334   __ move(new LIR_Address(klass, in_bytes(Klass::modifier_flags_offset()), T_INT), result);
1335 }
1336 
1337 // Example: Thread.currentThread()
1338 void LIRGenerator::do_currentThread(Intrinsic* x) {
1339   assert(x->number_of_arguments() == 0, "wrong type");
1340   LIR_Opr temp = new_register(T_ADDRESS);
1341   LIR_Opr reg = rlock_result(x);
1342   __ move(new LIR_Address(getThreadPointer(), in_bytes(JavaThread::threadObj_offset()), T_ADDRESS), temp);
1343   // threadObj = ((OopHandle)_threadObj)->resolve();
1344   access_load(IN_NATIVE, T_OBJECT,
1345               LIR_OprFact::address(new LIR_Address(temp, T_OBJECT)), reg);
1346 }
1347 
1348 void LIRGenerator::do_getObjectSize(Intrinsic* x) {
1349   assert(x->number_of_arguments() == 3, "wrong type");
1350   LIR_Opr result_reg = rlock_result(x);
1351 
1352   LIRItem value(x->argument_at(2), this);
1353   value.load_item();
1354 
1355   LIR_Opr klass = new_register(T_METADATA);
1356   __ move(new LIR_Address(value.result(), oopDesc::klass_offset_in_bytes(), T_ADDRESS), klass, NULL);
1357   LIR_Opr layout = new_register(T_INT);
1358   __ move(new LIR_Address(klass, in_bytes(Klass::layout_helper_offset()), T_INT), layout);
1359 
1360   LabelObj* L_done = new LabelObj();
1361   LabelObj* L_array = new LabelObj();
1362 
1363   __ cmp(lir_cond_lessEqual, layout, 0);
1364   __ branch(lir_cond_lessEqual, L_array->label());
1365 
1366   // Instance case: the layout helper gives us instance size almost directly,
1367   // but we need to mask out the _lh_instance_slow_path_bit.
1368   __ convert(Bytecodes::_i2l, layout, result_reg);
1369 
1370   assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
1371   jlong mask = ~(jlong) right_n_bits(LogBytesPerLong);
1372   __ logical_and(result_reg, LIR_OprFact::longConst(mask), result_reg);
1373 
1374   __ branch(lir_cond_always, L_done->label());
1375 
1376   // Array case: size is round(header + element_size*arraylength).
1377   // Since arraylength is different for every array instance, we have to
1378   // compute the whole thing at runtime.
1379 
1380   __ branch_destination(L_array->label());
1381 
1382   int round_mask = MinObjAlignmentInBytes - 1;
1383 
1384   // Figure out header sizes first.
1385   LIR_Opr hss = LIR_OprFact::intConst(Klass::_lh_header_size_shift);
1386   LIR_Opr hsm = LIR_OprFact::intConst(Klass::_lh_header_size_mask);
1387 
1388   LIR_Opr header_size = new_register(T_INT);
1389   __ move(layout, header_size);
1390   LIR_Opr tmp = new_register(T_INT);
1391   __ unsigned_shift_right(header_size, hss, header_size, tmp);
1392   __ logical_and(header_size, hsm, header_size);
1393   __ add(header_size, LIR_OprFact::intConst(round_mask), header_size);
1394 
1395   // Figure out the array length in bytes
1396   assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
1397   LIR_Opr l2esm = LIR_OprFact::intConst(Klass::_lh_log2_element_size_mask);
1398   __ logical_and(layout, l2esm, layout);
1399 
1400   LIR_Opr length_int = new_register(T_INT);
1401   __ move(new LIR_Address(value.result(), arrayOopDesc::length_offset_in_bytes(), T_INT), length_int);
1402 
1403 #ifdef _LP64
1404   LIR_Opr length = new_register(T_LONG);
1405   __ convert(Bytecodes::_i2l, length_int, length);
1406 #endif
1407 
1408   // Shift-left awkwardness. Normally it is just:
1409   //   __ shift_left(length, layout, length);
1410   // But C1 cannot perform shift_left with non-constant count, so we end up
1411   // doing the per-bit loop dance here. x86_32 also does not know how to shift
1412   // longs, so we have to act on ints.
1413   LabelObj* L_shift_loop = new LabelObj();
1414   LabelObj* L_shift_exit = new LabelObj();
1415 
1416   __ branch_destination(L_shift_loop->label());
1417   __ cmp(lir_cond_equal, layout, 0);
1418   __ branch(lir_cond_equal, L_shift_exit->label());
1419 
1420 #ifdef _LP64
1421   __ shift_left(length, 1, length);
1422 #else
1423   __ shift_left(length_int, 1, length_int);
1424 #endif
1425 
1426   __ sub(layout, LIR_OprFact::intConst(1), layout);
1427 
1428   __ branch(lir_cond_always, L_shift_loop->label());
1429   __ branch_destination(L_shift_exit->label());
1430 
1431   // Mix all up, round, and push to the result.
1432 #ifdef _LP64
1433   LIR_Opr header_size_long = new_register(T_LONG);
1434   __ convert(Bytecodes::_i2l, header_size, header_size_long);
1435   __ add(length, header_size_long, length);
1436   if (round_mask != 0) {
1437     __ logical_and(length, LIR_OprFact::longConst(~round_mask), length);
1438   }
1439   __ move(length, result_reg);
1440 #else
1441   __ add(length_int, header_size, length_int);
1442   if (round_mask != 0) {
1443     __ logical_and(length_int, LIR_OprFact::intConst(~round_mask), length_int);
1444   }
1445   __ convert(Bytecodes::_i2l, length_int, result_reg);
1446 #endif
1447 
1448   __ branch_destination(L_done->label());
1449 }
1450 
1451 void LIRGenerator::do_RegisterFinalizer(Intrinsic* x) {
1452   assert(x->number_of_arguments() == 1, "wrong type");
1453   LIRItem receiver(x->argument_at(0), this);
1454 
1455   receiver.load_item();
1456   BasicTypeList signature;
1457   signature.append(T_OBJECT); // receiver
1458   LIR_OprList* args = new LIR_OprList();
1459   args->append(receiver.result());
1460   CodeEmitInfo* info = state_for(x, x->state());
1461   call_runtime(&signature, args,
1462                CAST_FROM_FN_PTR(address, Runtime1::entry_for(Runtime1::register_finalizer_id)),
1463                voidType, info);
1464 
1465   set_no_result(x);
1466 }
1467 
1468 
1469 //------------------------local access--------------------------------------
1470 
1471 LIR_Opr LIRGenerator::operand_for_instruction(Instruction* x) {
1472   if (x->operand()->is_illegal()) {
1473     Constant* c = x->as_Constant();
1474     if (c != NULL) {
1475       x->set_operand(LIR_OprFact::value_type(c->type()));
1476     } else {
1477       assert(x->as_Phi() || x->as_Local() != NULL, "only for Phi and Local");
1478       // allocate a virtual register for this local or phi
1479       x->set_operand(rlock(x));
1480       _instruction_for_operand.at_put_grow(x->operand()->vreg_number(), x, NULL);
1481     }
1482   }
1483   return x->operand();
1484 }
1485 
1486 
1487 Instruction* LIRGenerator::instruction_for_opr(LIR_Opr opr) {
1488   if (opr->is_virtual()) {
1489     return instruction_for_vreg(opr->vreg_number());
1490   }
1491   return NULL;
1492 }
1493 
1494 
1495 Instruction* LIRGenerator::instruction_for_vreg(int reg_num) {
1496   if (reg_num < _instruction_for_operand.length()) {
1497     return _instruction_for_operand.at(reg_num);
1498   }
1499   return NULL;
1500 }
1501 
1502 
1503 void LIRGenerator::set_vreg_flag(int vreg_num, VregFlag f) {
1504   if (_vreg_flags.size_in_bits() == 0) {
1505     BitMap2D temp(100, num_vreg_flags);
1506     _vreg_flags = temp;
1507   }
1508   _vreg_flags.at_put_grow(vreg_num, f, true);
1509 }
1510 
1511 bool LIRGenerator::is_vreg_flag_set(int vreg_num, VregFlag f) {
1512   if (!_vreg_flags.is_valid_index(vreg_num, f)) {
1513     return false;
1514   }
1515   return _vreg_flags.at(vreg_num, f);
1516 }
1517 
1518 
1519 // Block local constant handling.  This code is useful for keeping
1520 // unpinned constants and constants which aren't exposed in the IR in
1521 // registers.  Unpinned Constant instructions have their operands
1522 // cleared when the block is finished so that other blocks can't end
1523 // up referring to their registers.
1524 
1525 LIR_Opr LIRGenerator::load_constant(Constant* x) {
1526   assert(!x->is_pinned(), "only for unpinned constants");
1527   _unpinned_constants.append(x);
1528   return load_constant(LIR_OprFact::value_type(x->type())->as_constant_ptr());
1529 }
1530 
1531 
1532 LIR_Opr LIRGenerator::load_constant(LIR_Const* c) {
1533   BasicType t = c->type();
1534   for (int i = 0; i < _constants.length(); i++) {
1535     LIR_Const* other = _constants.at(i);
1536     if (t == other->type()) {
1537       switch (t) {
1538       case T_INT:
1539       case T_FLOAT:
1540         if (c->as_jint_bits() != other->as_jint_bits()) continue;
1541         break;
1542       case T_LONG:
1543       case T_DOUBLE:
1544         if (c->as_jint_hi_bits() != other->as_jint_hi_bits()) continue;
1545         if (c->as_jint_lo_bits() != other->as_jint_lo_bits()) continue;
1546         break;
1547       case T_OBJECT:
1548         if (c->as_jobject() != other->as_jobject()) continue;
1549         break;
1550       default:
1551         break;
1552       }
1553       return _reg_for_constants.at(i);
1554     }
1555   }
1556 
1557   LIR_Opr result = new_register(t);
1558   __ move((LIR_Opr)c, result);
1559   _constants.append(c);
1560   _reg_for_constants.append(result);
1561   return result;
1562 }
1563 
1564 //------------------------field access--------------------------------------
1565 
1566 void LIRGenerator::do_CompareAndSwap(Intrinsic* x, ValueType* type) {
1567   assert(x->number_of_arguments() == 4, "wrong type");
1568   LIRItem obj   (x->argument_at(0), this);  // object
1569   LIRItem offset(x->argument_at(1), this);  // offset of field
1570   LIRItem cmp   (x->argument_at(2), this);  // value to compare with field
1571   LIRItem val   (x->argument_at(3), this);  // replace field with val if matches cmp
1572   assert(obj.type()->tag() == objectTag, "invalid type");
1573   assert(cmp.type()->tag() == type->tag(), "invalid type");
1574   assert(val.type()->tag() == type->tag(), "invalid type");
1575 
1576   LIR_Opr result = access_atomic_cmpxchg_at(IN_HEAP, as_BasicType(type),
1577                                             obj, offset, cmp, val);
1578   set_result(x, result);
1579 }
1580 
1581 // Comment copied form templateTable_i486.cpp
1582 // ----------------------------------------------------------------------------
1583 // Volatile variables demand their effects be made known to all CPU's in
1584 // order.  Store buffers on most chips allow reads & writes to reorder; the
1585 // JMM's ReadAfterWrite.java test fails in -Xint mode without some kind of
1586 // memory barrier (i.e., it's not sufficient that the interpreter does not
1587 // reorder volatile references, the hardware also must not reorder them).
1588 //
1589 // According to the new Java Memory Model (JMM):
1590 // (1) All volatiles are serialized wrt to each other.
1591 // ALSO reads & writes act as aquire & release, so:
1592 // (2) A read cannot let unrelated NON-volatile memory refs that happen after
1593 // the read float up to before the read.  It's OK for non-volatile memory refs
1594 // that happen before the volatile read to float down below it.
1595 // (3) Similar a volatile write cannot let unrelated NON-volatile memory refs
1596 // that happen BEFORE the write float down to after the write.  It's OK for
1597 // non-volatile memory refs that happen after the volatile write to float up
1598 // before it.
1599 //
1600 // We only put in barriers around volatile refs (they are expensive), not
1601 // _between_ memory refs (that would require us to track the flavor of the
1602 // previous memory refs).  Requirements (2) and (3) require some barriers
1603 // before volatile stores and after volatile loads.  These nearly cover
1604 // requirement (1) but miss the volatile-store-volatile-load case.  This final
1605 // case is placed after volatile-stores although it could just as well go
1606 // before volatile-loads.
1607 
1608 
1609 void LIRGenerator::do_StoreField(StoreField* x) {
1610   bool needs_patching = x->needs_patching();
1611   bool is_volatile = x->field()->is_volatile();
1612   BasicType field_type = x->field_type();
1613 
1614   CodeEmitInfo* info = NULL;
1615   if (needs_patching) {
1616     assert(x->explicit_null_check() == NULL, "can't fold null check into patching field access");
1617     info = state_for(x, x->state_before());
1618   } else if (x->needs_null_check()) {
1619     NullCheck* nc = x->explicit_null_check();
1620     if (nc == NULL) {
1621       info = state_for(x);
1622     } else {
1623       info = state_for(nc);
1624     }
1625   }
1626 
1627   LIRItem object(x->obj(), this);
1628   LIRItem value(x->value(),  this);
1629 
1630   object.load_item();
1631 
1632   if (is_volatile || needs_patching) {
1633     // load item if field is volatile (fewer special cases for volatiles)
1634     // load item if field not initialized
1635     // load item if field not constant
1636     // because of code patching we cannot inline constants
1637     if (field_type == T_BYTE || field_type == T_BOOLEAN) {
1638       value.load_byte_item();
1639     } else  {
1640       value.load_item();
1641     }
1642   } else {
1643     value.load_for_store(field_type);
1644   }
1645 
1646   set_no_result(x);
1647 
1648 #ifndef PRODUCT
1649   if (PrintNotLoaded && needs_patching) {
1650     tty->print_cr("   ###class not loaded at store_%s bci %d",
1651                   x->is_static() ?  "static" : "field", x->printable_bci());
1652   }
1653 #endif
1654 
1655   if (x->needs_null_check() &&
1656       (needs_patching ||
1657        MacroAssembler::needs_explicit_null_check(x->offset()))) {
1658     // Emit an explicit null check because the offset is too large.
1659     // If the class is not loaded and the object is NULL, we need to deoptimize to throw a
1660     // NoClassDefFoundError in the interpreter instead of an implicit NPE from compiled code.
1661     __ null_check(object.result(), new CodeEmitInfo(info), /* deoptimize */ needs_patching);
1662   }
1663 
1664   DecoratorSet decorators = IN_HEAP;
1665   if (is_volatile) {
1666     decorators |= MO_SEQ_CST;
1667   }
1668   if (needs_patching) {
1669     decorators |= C1_NEEDS_PATCHING;
1670   }
1671 
1672   access_store_at(decorators, field_type, object, LIR_OprFact::intConst(x->offset()),
1673                   value.result(), info != NULL ? new CodeEmitInfo(info) : NULL, info);
1674 }
1675 
1676 void LIRGenerator::do_StoreIndexed(StoreIndexed* x) {
1677   assert(x->is_pinned(),"");
1678   bool needs_range_check = x->compute_needs_range_check();
1679   bool use_length = x->length() != NULL;
1680   bool obj_store = is_reference_type(x->elt_type());
1681   bool needs_store_check = obj_store && (x->value()->as_Constant() == NULL ||
1682                                          !get_jobject_constant(x->value())->is_null_object() ||
1683                                          x->should_profile());
1684 
1685   LIRItem array(x->array(), this);
1686   LIRItem index(x->index(), this);
1687   LIRItem value(x->value(), this);
1688   LIRItem length(this);
1689 
1690   array.load_item();
1691   index.load_nonconstant();
1692 
1693   if (use_length && needs_range_check) {
1694     length.set_instruction(x->length());
1695     length.load_item();
1696 
1697   }
1698   if (needs_store_check || x->check_boolean()) {
1699     value.load_item();
1700   } else {
1701     value.load_for_store(x->elt_type());
1702   }
1703 
1704   set_no_result(x);
1705 
1706   // the CodeEmitInfo must be duplicated for each different
1707   // LIR-instruction because spilling can occur anywhere between two
1708   // instructions and so the debug information must be different
1709   CodeEmitInfo* range_check_info = state_for(x);
1710   CodeEmitInfo* null_check_info = NULL;
1711   if (x->needs_null_check()) {
1712     null_check_info = new CodeEmitInfo(range_check_info);
1713   }
1714 
1715   if (GenerateRangeChecks && needs_range_check) {
1716     if (use_length) {
1717       __ cmp(lir_cond_belowEqual, length.result(), index.result());
1718       __ branch(lir_cond_belowEqual, new RangeCheckStub(range_check_info, index.result(), array.result()));
1719     } else {
1720       array_range_check(array.result(), index.result(), null_check_info, range_check_info);
1721       // range_check also does the null check
1722       null_check_info = NULL;
1723     }
1724   }
1725 
1726   if (GenerateArrayStoreCheck && needs_store_check) {
1727     CodeEmitInfo* store_check_info = new CodeEmitInfo(range_check_info);
1728     array_store_check(value.result(), array.result(), store_check_info, x->profiled_method(), x->profiled_bci());
1729   }
1730 
1731   DecoratorSet decorators = IN_HEAP | IS_ARRAY;
1732   if (x->check_boolean()) {
1733     decorators |= C1_MASK_BOOLEAN;
1734   }
1735 
1736   access_store_at(decorators, x->elt_type(), array, index.result(), value.result(),
1737                   NULL, null_check_info);
1738 }
1739 
1740 void LIRGenerator::access_load_at(DecoratorSet decorators, BasicType type,
1741                                   LIRItem& base, LIR_Opr offset, LIR_Opr result,
1742                                   CodeEmitInfo* patch_info, CodeEmitInfo* load_emit_info) {
1743   decorators |= ACCESS_READ;
1744   LIRAccess access(this, decorators, base, offset, type, patch_info, load_emit_info);
1745   if (access.is_raw()) {
1746     _barrier_set->BarrierSetC1::load_at(access, result);
1747   } else {
1748     _barrier_set->load_at(access, result);
1749   }
1750 }
1751 
1752 void LIRGenerator::access_load(DecoratorSet decorators, BasicType type,
1753                                LIR_Opr addr, LIR_Opr result) {
1754   decorators |= ACCESS_READ;
1755   LIRAccess access(this, decorators, LIR_OprFact::illegalOpr, LIR_OprFact::illegalOpr, type);
1756   access.set_resolved_addr(addr);
1757   if (access.is_raw()) {
1758     _barrier_set->BarrierSetC1::load(access, result);
1759   } else {
1760     _barrier_set->load(access, result);
1761   }
1762 }
1763 
1764 void LIRGenerator::access_store_at(DecoratorSet decorators, BasicType type,
1765                                    LIRItem& base, LIR_Opr offset, LIR_Opr value,
1766                                    CodeEmitInfo* patch_info, CodeEmitInfo* store_emit_info) {
1767   decorators |= ACCESS_WRITE;
1768   LIRAccess access(this, decorators, base, offset, type, patch_info, store_emit_info);
1769   if (access.is_raw()) {
1770     _barrier_set->BarrierSetC1::store_at(access, value);
1771   } else {
1772     _barrier_set->store_at(access, value);
1773   }
1774 }
1775 
1776 LIR_Opr LIRGenerator::access_atomic_cmpxchg_at(DecoratorSet decorators, BasicType type,
1777                                                LIRItem& base, LIRItem& offset, LIRItem& cmp_value, LIRItem& new_value) {
1778   decorators |= ACCESS_READ;
1779   decorators |= ACCESS_WRITE;
1780   // Atomic operations are SEQ_CST by default
1781   decorators |= ((decorators & MO_DECORATOR_MASK) == 0) ? MO_SEQ_CST : 0;
1782   LIRAccess access(this, decorators, base, offset, type);
1783   if (access.is_raw()) {
1784     return _barrier_set->BarrierSetC1::atomic_cmpxchg_at(access, cmp_value, new_value);
1785   } else {
1786     return _barrier_set->atomic_cmpxchg_at(access, cmp_value, new_value);
1787   }
1788 }
1789 
1790 LIR_Opr LIRGenerator::access_atomic_xchg_at(DecoratorSet decorators, BasicType type,
1791                                             LIRItem& base, LIRItem& offset, LIRItem& value) {
1792   decorators |= ACCESS_READ;
1793   decorators |= ACCESS_WRITE;
1794   // Atomic operations are SEQ_CST by default
1795   decorators |= ((decorators & MO_DECORATOR_MASK) == 0) ? MO_SEQ_CST : 0;
1796   LIRAccess access(this, decorators, base, offset, type);
1797   if (access.is_raw()) {
1798     return _barrier_set->BarrierSetC1::atomic_xchg_at(access, value);
1799   } else {
1800     return _barrier_set->atomic_xchg_at(access, value);
1801   }
1802 }
1803 
1804 LIR_Opr LIRGenerator::access_atomic_add_at(DecoratorSet decorators, BasicType type,
1805                                            LIRItem& base, LIRItem& offset, LIRItem& value) {
1806   decorators |= ACCESS_READ;
1807   decorators |= ACCESS_WRITE;
1808   // Atomic operations are SEQ_CST by default
1809   decorators |= ((decorators & MO_DECORATOR_MASK) == 0) ? MO_SEQ_CST : 0;
1810   LIRAccess access(this, decorators, base, offset, type);
1811   if (access.is_raw()) {
1812     return _barrier_set->BarrierSetC1::atomic_add_at(access, value);
1813   } else {
1814     return _barrier_set->atomic_add_at(access, value);
1815   }
1816 }
1817 
1818 void LIRGenerator::do_LoadField(LoadField* x) {
1819   bool needs_patching = x->needs_patching();
1820   bool is_volatile = x->field()->is_volatile();
1821   BasicType field_type = x->field_type();
1822 
1823   CodeEmitInfo* info = NULL;
1824   if (needs_patching) {
1825     assert(x->explicit_null_check() == NULL, "can't fold null check into patching field access");
1826     info = state_for(x, x->state_before());
1827   } else if (x->needs_null_check()) {
1828     NullCheck* nc = x->explicit_null_check();
1829     if (nc == NULL) {
1830       info = state_for(x);
1831     } else {
1832       info = state_for(nc);
1833     }
1834   }
1835 
1836   LIRItem object(x->obj(), this);
1837 
1838   object.load_item();
1839 
1840 #ifndef PRODUCT
1841   if (PrintNotLoaded && needs_patching) {
1842     tty->print_cr("   ###class not loaded at load_%s bci %d",
1843                   x->is_static() ?  "static" : "field", x->printable_bci());
1844   }
1845 #endif
1846 
1847   bool stress_deopt = StressLoopInvariantCodeMotion && info && info->deoptimize_on_exception();
1848   if (x->needs_null_check() &&
1849       (needs_patching ||
1850        MacroAssembler::needs_explicit_null_check(x->offset()) ||
1851        stress_deopt)) {
1852     LIR_Opr obj = object.result();
1853     if (stress_deopt) {
1854       obj = new_register(T_OBJECT);
1855       __ move(LIR_OprFact::oopConst(NULL), obj);
1856     }
1857     // Emit an explicit null check because the offset is too large.
1858     // If the class is not loaded and the object is NULL, we need to deoptimize to throw a
1859     // NoClassDefFoundError in the interpreter instead of an implicit NPE from compiled code.
1860     __ null_check(obj, new CodeEmitInfo(info), /* deoptimize */ needs_patching);
1861   }
1862 
1863   DecoratorSet decorators = IN_HEAP;
1864   if (is_volatile) {
1865     decorators |= MO_SEQ_CST;
1866   }
1867   if (needs_patching) {
1868     decorators |= C1_NEEDS_PATCHING;
1869   }
1870 
1871   LIR_Opr result = rlock_result(x, field_type);
1872   access_load_at(decorators, field_type,
1873                  object, LIR_OprFact::intConst(x->offset()), result,
1874                  info ? new CodeEmitInfo(info) : NULL, info);
1875 }
1876 
1877 
1878 //------------------------java.nio.Buffer.checkIndex------------------------
1879 
1880 // int java.nio.Buffer.checkIndex(int)
1881 void LIRGenerator::do_NIOCheckIndex(Intrinsic* x) {
1882   // NOTE: by the time we are in checkIndex() we are guaranteed that
1883   // the buffer is non-null (because checkIndex is package-private and
1884   // only called from within other methods in the buffer).
1885   assert(x->number_of_arguments() == 2, "wrong type");
1886   LIRItem buf  (x->argument_at(0), this);
1887   LIRItem index(x->argument_at(1), this);
1888   buf.load_item();
1889   index.load_item();
1890 
1891   LIR_Opr result = rlock_result(x);
1892   if (GenerateRangeChecks) {
1893     CodeEmitInfo* info = state_for(x);
1894     CodeStub* stub = new RangeCheckStub(info, index.result());
1895     if (index.result()->is_constant()) {
1896       cmp_mem_int(lir_cond_belowEqual, buf.result(), java_nio_Buffer::limit_offset(), index.result()->as_jint(), info);
1897       __ branch(lir_cond_belowEqual, stub);
1898     } else {
1899       cmp_reg_mem(lir_cond_aboveEqual, index.result(), buf.result(),
1900                   java_nio_Buffer::limit_offset(), T_INT, info);
1901       __ branch(lir_cond_aboveEqual, stub);
1902     }
1903     __ move(index.result(), result);
1904   } else {
1905     // Just load the index into the result register
1906     __ move(index.result(), result);
1907   }
1908 }
1909 
1910 
1911 //------------------------array access--------------------------------------
1912 
1913 
1914 void LIRGenerator::do_ArrayLength(ArrayLength* x) {
1915   LIRItem array(x->array(), this);
1916   array.load_item();
1917   LIR_Opr reg = rlock_result(x);
1918 
1919   CodeEmitInfo* info = NULL;
1920   if (x->needs_null_check()) {
1921     NullCheck* nc = x->explicit_null_check();
1922     if (nc == NULL) {
1923       info = state_for(x);
1924     } else {
1925       info = state_for(nc);
1926     }
1927     if (StressLoopInvariantCodeMotion && info->deoptimize_on_exception()) {
1928       LIR_Opr obj = new_register(T_OBJECT);
1929       __ move(LIR_OprFact::oopConst(NULL), obj);
1930       __ null_check(obj, new CodeEmitInfo(info));
1931     }
1932   }
1933   __ load(new LIR_Address(array.result(), arrayOopDesc::length_offset_in_bytes(), T_INT), reg, info, lir_patch_none);
1934 }
1935 
1936 
1937 void LIRGenerator::do_LoadIndexed(LoadIndexed* x) {
1938   bool use_length = x->length() != NULL;
1939   LIRItem array(x->array(), this);
1940   LIRItem index(x->index(), this);
1941   LIRItem length(this);
1942   bool needs_range_check = x->compute_needs_range_check();
1943 
1944   if (use_length && needs_range_check) {
1945     length.set_instruction(x->length());
1946     length.load_item();
1947   }
1948 
1949   array.load_item();
1950   if (index.is_constant() && can_inline_as_constant(x->index())) {
1951     // let it be a constant
1952     index.dont_load_item();
1953   } else {
1954     index.load_item();
1955   }
1956 
1957   CodeEmitInfo* range_check_info = state_for(x);
1958   CodeEmitInfo* null_check_info = NULL;
1959   if (x->needs_null_check()) {
1960     NullCheck* nc = x->explicit_null_check();
1961     if (nc != NULL) {
1962       null_check_info = state_for(nc);
1963     } else {
1964       null_check_info = range_check_info;
1965     }
1966     if (StressLoopInvariantCodeMotion && null_check_info->deoptimize_on_exception()) {
1967       LIR_Opr obj = new_register(T_OBJECT);
1968       __ move(LIR_OprFact::oopConst(NULL), obj);
1969       __ null_check(obj, new CodeEmitInfo(null_check_info));
1970     }
1971   }
1972 
1973   if (GenerateRangeChecks && needs_range_check) {
1974     if (StressLoopInvariantCodeMotion && range_check_info->deoptimize_on_exception()) {
1975       __ branch(lir_cond_always, new RangeCheckStub(range_check_info, index.result(), array.result()));
1976     } else if (use_length) {
1977       // TODO: use a (modified) version of array_range_check that does not require a
1978       //       constant length to be loaded to a register
1979       __ cmp(lir_cond_belowEqual, length.result(), index.result());
1980       __ branch(lir_cond_belowEqual, new RangeCheckStub(range_check_info, index.result(), array.result()));
1981     } else {
1982       array_range_check(array.result(), index.result(), null_check_info, range_check_info);
1983       // The range check performs the null check, so clear it out for the load
1984       null_check_info = NULL;
1985     }
1986   }
1987 
1988   DecoratorSet decorators = IN_HEAP | IS_ARRAY;
1989 
1990   LIR_Opr result = rlock_result(x, x->elt_type());
1991   access_load_at(decorators, x->elt_type(),
1992                  array, index.result(), result,
1993                  NULL, null_check_info);
1994 }
1995 
1996 
1997 void LIRGenerator::do_NullCheck(NullCheck* x) {
1998   if (x->can_trap()) {
1999     LIRItem value(x->obj(), this);
2000     value.load_item();
2001     CodeEmitInfo* info = state_for(x);
2002     __ null_check(value.result(), info);
2003   }
2004 }
2005 
2006 
2007 void LIRGenerator::do_TypeCast(TypeCast* x) {
2008   LIRItem value(x->obj(), this);
2009   value.load_item();
2010   // the result is the same as from the node we are casting
2011   set_result(x, value.result());
2012 }
2013 
2014 
2015 void LIRGenerator::do_Throw(Throw* x) {
2016   LIRItem exception(x->exception(), this);
2017   exception.load_item();
2018   set_no_result(x);
2019   LIR_Opr exception_opr = exception.result();
2020   CodeEmitInfo* info = state_for(x, x->state());
2021 
2022 #ifndef PRODUCT
2023   if (PrintC1Statistics) {
2024     increment_counter(Runtime1::throw_count_address(), T_INT);
2025   }
2026 #endif
2027 
2028   // check if the instruction has an xhandler in any of the nested scopes
2029   bool unwind = false;
2030   if (info->exception_handlers()->length() == 0) {
2031     // this throw is not inside an xhandler
2032     unwind = true;
2033   } else {
2034     // get some idea of the throw type
2035     bool type_is_exact = true;
2036     ciType* throw_type = x->exception()->exact_type();
2037     if (throw_type == NULL) {
2038       type_is_exact = false;
2039       throw_type = x->exception()->declared_type();
2040     }
2041     if (throw_type != NULL && throw_type->is_instance_klass()) {
2042       ciInstanceKlass* throw_klass = (ciInstanceKlass*)throw_type;
2043       unwind = !x->exception_handlers()->could_catch(throw_klass, type_is_exact);
2044     }
2045   }
2046 
2047   // do null check before moving exception oop into fixed register
2048   // to avoid a fixed interval with an oop during the null check.
2049   // Use a copy of the CodeEmitInfo because debug information is
2050   // different for null_check and throw.
2051   if (x->exception()->as_NewInstance() == NULL && x->exception()->as_ExceptionObject() == NULL) {
2052     // if the exception object wasn't created using new then it might be null.
2053     __ null_check(exception_opr, new CodeEmitInfo(info, x->state()->copy(ValueStack::ExceptionState, x->state()->bci())));
2054   }
2055 
2056   if (compilation()->env()->jvmti_can_post_on_exceptions()) {
2057     // we need to go through the exception lookup path to get JVMTI
2058     // notification done
2059     unwind = false;
2060   }
2061 
2062   // move exception oop into fixed register
2063   __ move(exception_opr, exceptionOopOpr());
2064 
2065   if (unwind) {
2066     __ unwind_exception(exceptionOopOpr());
2067   } else {
2068     __ throw_exception(exceptionPcOpr(), exceptionOopOpr(), info);
2069   }
2070 }
2071 
2072 
2073 void LIRGenerator::do_RoundFP(RoundFP* x) {
2074   assert(strict_fp_requires_explicit_rounding, "not required");
2075 
2076   LIRItem input(x->input(), this);
2077   input.load_item();
2078   LIR_Opr input_opr = input.result();
2079   assert(input_opr->is_register(), "why round if value is not in a register?");
2080   assert(input_opr->is_single_fpu() || input_opr->is_double_fpu(), "input should be floating-point value");
2081   if (input_opr->is_single_fpu()) {
2082     set_result(x, round_item(input_opr)); // This code path not currently taken
2083   } else {
2084     LIR_Opr result = new_register(T_DOUBLE);
2085     set_vreg_flag(result, must_start_in_memory);
2086     __ roundfp(input_opr, LIR_OprFact::illegalOpr, result);
2087     set_result(x, result);
2088   }
2089 }
2090 
2091 // Here UnsafeGetRaw may have x->base() and x->index() be int or long
2092 // on both 64 and 32 bits. Expecting x->base() to be always long on 64bit.
2093 void LIRGenerator::do_UnsafeGetRaw(UnsafeGetRaw* x) {
2094   LIRItem base(x->base(), this);
2095   LIRItem idx(this);
2096 
2097   base.load_item();
2098   if (x->has_index()) {
2099     idx.set_instruction(x->index());
2100     idx.load_nonconstant();
2101   }
2102 
2103   LIR_Opr reg = rlock_result(x, x->basic_type());
2104 
2105   int   log2_scale = 0;
2106   if (x->has_index()) {
2107     log2_scale = x->log2_scale();
2108   }
2109 
2110   assert(!x->has_index() || idx.value() == x->index(), "should match");
2111 
2112   LIR_Opr base_op = base.result();
2113   LIR_Opr index_op = idx.result();
2114 #ifndef _LP64
2115   if (base_op->type() == T_LONG) {
2116     base_op = new_register(T_INT);
2117     __ convert(Bytecodes::_l2i, base.result(), base_op);
2118   }
2119   if (x->has_index()) {
2120     if (index_op->type() == T_LONG) {
2121       LIR_Opr long_index_op = index_op;
2122       if (index_op->is_constant()) {
2123         long_index_op = new_register(T_LONG);
2124         __ move(index_op, long_index_op);
2125       }
2126       index_op = new_register(T_INT);
2127       __ convert(Bytecodes::_l2i, long_index_op, index_op);
2128     } else {
2129       assert(x->index()->type()->tag() == intTag, "must be");
2130     }
2131   }
2132   // At this point base and index should be all ints.
2133   assert(base_op->type() == T_INT && !base_op->is_constant(), "base should be an non-constant int");
2134   assert(!x->has_index() || index_op->type() == T_INT, "index should be an int");
2135 #else
2136   if (x->has_index()) {
2137     if (index_op->type() == T_INT) {
2138       if (!index_op->is_constant()) {
2139         index_op = new_register(T_LONG);
2140         __ convert(Bytecodes::_i2l, idx.result(), index_op);
2141       }
2142     } else {
2143       assert(index_op->type() == T_LONG, "must be");
2144       if (index_op->is_constant()) {
2145         index_op = new_register(T_LONG);
2146         __ move(idx.result(), index_op);
2147       }
2148     }
2149   }
2150   // At this point base is a long non-constant
2151   // Index is a long register or a int constant.
2152   // We allow the constant to stay an int because that would allow us a more compact encoding by
2153   // embedding an immediate offset in the address expression. If we have a long constant, we have to
2154   // move it into a register first.
2155   assert(base_op->type() == T_LONG && !base_op->is_constant(), "base must be a long non-constant");
2156   assert(!x->has_index() || (index_op->type() == T_INT && index_op->is_constant()) ||
2157                             (index_op->type() == T_LONG && !index_op->is_constant()), "unexpected index type");
2158 #endif
2159 
2160   BasicType dst_type = x->basic_type();
2161 
2162   LIR_Address* addr;
2163   if (index_op->is_constant()) {
2164     assert(log2_scale == 0, "must not have a scale");
2165     assert(index_op->type() == T_INT, "only int constants supported");
2166     addr = new LIR_Address(base_op, index_op->as_jint(), dst_type);
2167   } else {
2168 #ifdef X86
2169     addr = new LIR_Address(base_op, index_op, LIR_Address::Scale(log2_scale), 0, dst_type);
2170 #elif defined(GENERATE_ADDRESS_IS_PREFERRED)
2171     addr = generate_address(base_op, index_op, log2_scale, 0, dst_type);
2172 #else
2173     if (index_op->is_illegal() || log2_scale == 0) {
2174       addr = new LIR_Address(base_op, index_op, dst_type);
2175     } else {
2176       LIR_Opr tmp = new_pointer_register();
2177       __ shift_left(index_op, log2_scale, tmp);
2178       addr = new LIR_Address(base_op, tmp, dst_type);
2179     }
2180 #endif
2181   }
2182 
2183   if (x->may_be_unaligned() && (dst_type == T_LONG || dst_type == T_DOUBLE)) {
2184     __ unaligned_move(addr, reg);
2185   } else {
2186     if (dst_type == T_OBJECT && x->is_wide()) {
2187       __ move_wide(addr, reg);
2188     } else {
2189       __ move(addr, reg);
2190     }
2191   }
2192 }
2193 
2194 
2195 void LIRGenerator::do_UnsafePutRaw(UnsafePutRaw* x) {
2196   int  log2_scale = 0;
2197   BasicType type = x->basic_type();
2198 
2199   if (x->has_index()) {
2200     log2_scale = x->log2_scale();
2201   }
2202 
2203   LIRItem base(x->base(), this);
2204   LIRItem value(x->value(), this);
2205   LIRItem idx(this);
2206 
2207   base.load_item();
2208   if (x->has_index()) {
2209     idx.set_instruction(x->index());
2210     idx.load_item();
2211   }
2212 
2213   if (type == T_BYTE || type == T_BOOLEAN) {
2214     value.load_byte_item();
2215   } else {
2216     value.load_item();
2217   }
2218 
2219   set_no_result(x);
2220 
2221   LIR_Opr base_op = base.result();
2222   LIR_Opr index_op = idx.result();
2223 
2224 #ifdef GENERATE_ADDRESS_IS_PREFERRED
2225   LIR_Address* addr = generate_address(base_op, index_op, log2_scale, 0, x->basic_type());
2226 #else
2227 #ifndef _LP64
2228   if (base_op->type() == T_LONG) {
2229     base_op = new_register(T_INT);
2230     __ convert(Bytecodes::_l2i, base.result(), base_op);
2231   }
2232   if (x->has_index()) {
2233     if (index_op->type() == T_LONG) {
2234       index_op = new_register(T_INT);
2235       __ convert(Bytecodes::_l2i, idx.result(), index_op);
2236     }
2237   }
2238   // At this point base and index should be all ints and not constants
2239   assert(base_op->type() == T_INT && !base_op->is_constant(), "base should be an non-constant int");
2240   assert(!x->has_index() || (index_op->type() == T_INT && !index_op->is_constant()), "index should be an non-constant int");
2241 #else
2242   if (x->has_index()) {
2243     if (index_op->type() == T_INT) {
2244       index_op = new_register(T_LONG);
2245       __ convert(Bytecodes::_i2l, idx.result(), index_op);
2246     }
2247   }
2248   // At this point base and index are long and non-constant
2249   assert(base_op->type() == T_LONG && !base_op->is_constant(), "base must be a non-constant long");
2250   assert(!x->has_index() || (index_op->type() == T_LONG && !index_op->is_constant()), "index must be a non-constant long");
2251 #endif
2252 
2253   if (log2_scale != 0) {
2254     // temporary fix (platform dependent code without shift on Intel would be better)
2255     // TODO: ARM also allows embedded shift in the address
2256     LIR_Opr tmp = new_pointer_register();
2257     if (TwoOperandLIRForm) {
2258       __ move(index_op, tmp);
2259       index_op = tmp;
2260     }
2261     __ shift_left(index_op, log2_scale, tmp);
2262     if (!TwoOperandLIRForm) {
2263       index_op = tmp;
2264     }
2265   }
2266 
2267   LIR_Address* addr = new LIR_Address(base_op, index_op, x->basic_type());
2268 #endif // !GENERATE_ADDRESS_IS_PREFERRED
2269   __ move(value.result(), addr);
2270 }
2271 
2272 
2273 void LIRGenerator::do_UnsafeGetObject(UnsafeGetObject* x) {
2274   BasicType type = x->basic_type();
2275   LIRItem src(x->object(), this);
2276   LIRItem off(x->offset(), this);
2277 
2278   off.load_item();
2279   src.load_item();
2280 
2281   DecoratorSet decorators = IN_HEAP | C1_UNSAFE_ACCESS;
2282 
2283   if (x->is_volatile()) {
2284     decorators |= MO_SEQ_CST;
2285   }
2286   if (type == T_BOOLEAN) {
2287     decorators |= C1_MASK_BOOLEAN;
2288   }
2289   if (is_reference_type(type)) {
2290     decorators |= ON_UNKNOWN_OOP_REF;
2291   }
2292 
2293   LIR_Opr result = rlock_result(x, type);
2294   access_load_at(decorators, type,
2295                  src, off.result(), result);
2296 }
2297 
2298 
2299 void LIRGenerator::do_UnsafePutObject(UnsafePutObject* x) {
2300   BasicType type = x->basic_type();
2301   LIRItem src(x->object(), this);
2302   LIRItem off(x->offset(), this);
2303   LIRItem data(x->value(), this);
2304 
2305   src.load_item();
2306   if (type == T_BOOLEAN || type == T_BYTE) {
2307     data.load_byte_item();
2308   } else {
2309     data.load_item();
2310   }
2311   off.load_item();
2312 
2313   set_no_result(x);
2314 
2315   DecoratorSet decorators = IN_HEAP | C1_UNSAFE_ACCESS;
2316   if (is_reference_type(type)) {
2317     decorators |= ON_UNKNOWN_OOP_REF;
2318   }
2319   if (x->is_volatile()) {
2320     decorators |= MO_SEQ_CST;
2321   }
2322   access_store_at(decorators, type, src, off.result(), data.result());
2323 }
2324 
2325 void LIRGenerator::do_UnsafeGetAndSetObject(UnsafeGetAndSetObject* x) {
2326   BasicType type = x->basic_type();
2327   LIRItem src(x->object(), this);
2328   LIRItem off(x->offset(), this);
2329   LIRItem value(x->value(), this);
2330 
2331   DecoratorSet decorators = IN_HEAP | C1_UNSAFE_ACCESS | MO_SEQ_CST;
2332 
2333   if (is_reference_type(type)) {
2334     decorators |= ON_UNKNOWN_OOP_REF;
2335   }
2336 
2337   LIR_Opr result;
2338   if (x->is_add()) {
2339     result = access_atomic_add_at(decorators, type, src, off, value);
2340   } else {
2341     result = access_atomic_xchg_at(decorators, type, src, off, value);
2342   }
2343   set_result(x, result);
2344 }
2345 
2346 void LIRGenerator::do_SwitchRanges(SwitchRangeArray* x, LIR_Opr value, BlockBegin* default_sux) {
2347   int lng = x->length();
2348 
2349   for (int i = 0; i < lng; i++) {
2350     C1SwitchRange* one_range = x->at(i);
2351     int low_key = one_range->low_key();
2352     int high_key = one_range->high_key();
2353     BlockBegin* dest = one_range->sux();
2354     if (low_key == high_key) {
2355       __ cmp(lir_cond_equal, value, low_key);
2356       __ branch(lir_cond_equal, dest);
2357     } else if (high_key - low_key == 1) {
2358       __ cmp(lir_cond_equal, value, low_key);
2359       __ branch(lir_cond_equal, dest);
2360       __ cmp(lir_cond_equal, value, high_key);
2361       __ branch(lir_cond_equal, dest);
2362     } else {
2363       LabelObj* L = new LabelObj();
2364       __ cmp(lir_cond_less, value, low_key);
2365       __ branch(lir_cond_less, L->label());
2366       __ cmp(lir_cond_lessEqual, value, high_key);
2367       __ branch(lir_cond_lessEqual, dest);
2368       __ branch_destination(L->label());
2369     }
2370   }
2371   __ jump(default_sux);
2372 }
2373 
2374 
2375 SwitchRangeArray* LIRGenerator::create_lookup_ranges(TableSwitch* x) {
2376   SwitchRangeList* res = new SwitchRangeList();
2377   int len = x->length();
2378   if (len > 0) {
2379     BlockBegin* sux = x->sux_at(0);
2380     int key = x->lo_key();
2381     BlockBegin* default_sux = x->default_sux();
2382     C1SwitchRange* range = new C1SwitchRange(key, sux);
2383     for (int i = 0; i < len; i++, key++) {
2384       BlockBegin* new_sux = x->sux_at(i);
2385       if (sux == new_sux) {
2386         // still in same range
2387         range->set_high_key(key);
2388       } else {
2389         // skip tests which explicitly dispatch to the default
2390         if (sux != default_sux) {
2391           res->append(range);
2392         }
2393         range = new C1SwitchRange(key, new_sux);
2394       }
2395       sux = new_sux;
2396     }
2397     if (res->length() == 0 || res->last() != range)  res->append(range);
2398   }
2399   return res;
2400 }
2401 
2402 
2403 // we expect the keys to be sorted by increasing value
2404 SwitchRangeArray* LIRGenerator::create_lookup_ranges(LookupSwitch* x) {
2405   SwitchRangeList* res = new SwitchRangeList();
2406   int len = x->length();
2407   if (len > 0) {
2408     BlockBegin* default_sux = x->default_sux();
2409     int key = x->key_at(0);
2410     BlockBegin* sux = x->sux_at(0);
2411     C1SwitchRange* range = new C1SwitchRange(key, sux);
2412     for (int i = 1; i < len; i++) {
2413       int new_key = x->key_at(i);
2414       BlockBegin* new_sux = x->sux_at(i);
2415       if (key+1 == new_key && sux == new_sux) {
2416         // still in same range
2417         range->set_high_key(new_key);
2418       } else {
2419         // skip tests which explicitly dispatch to the default
2420         if (range->sux() != default_sux) {
2421           res->append(range);
2422         }
2423         range = new C1SwitchRange(new_key, new_sux);
2424       }
2425       key = new_key;
2426       sux = new_sux;
2427     }
2428     if (res->length() == 0 || res->last() != range)  res->append(range);
2429   }
2430   return res;
2431 }
2432 
2433 
2434 void LIRGenerator::do_TableSwitch(TableSwitch* x) {
2435   LIRItem tag(x->tag(), this);
2436   tag.load_item();
2437   set_no_result(x);
2438 
2439   if (x->is_safepoint()) {
2440     __ safepoint(safepoint_poll_register(), state_for(x, x->state_before()));
2441   }
2442 
2443   // move values into phi locations
2444   move_to_phi(x->state());
2445 
2446   int lo_key = x->lo_key();
2447   int len = x->length();
2448   assert(lo_key <= (lo_key + (len - 1)), "integer overflow");
2449   LIR_Opr value = tag.result();
2450 
2451   if (compilation()->env()->comp_level() == CompLevel_full_profile && UseSwitchProfiling) {
2452     ciMethod* method = x->state()->scope()->method();
2453     ciMethodData* md = method->method_data_or_null();
2454     assert(md != NULL, "Sanity");
2455     ciProfileData* data = md->bci_to_data(x->state()->bci());
2456     assert(data != NULL, "must have profiling data");
2457     assert(data->is_MultiBranchData(), "bad profile data?");
2458     int default_count_offset = md->byte_offset_of_slot(data, MultiBranchData::default_count_offset());
2459     LIR_Opr md_reg = new_register(T_METADATA);
2460     __ metadata2reg(md->constant_encoding(), md_reg);
2461     LIR_Opr data_offset_reg = new_pointer_register();
2462     LIR_Opr tmp_reg = new_pointer_register();
2463 
2464     __ move(LIR_OprFact::intptrConst(default_count_offset), data_offset_reg);
2465     for (int i = 0; i < len; i++) {
2466       int count_offset = md->byte_offset_of_slot(data, MultiBranchData::case_count_offset(i));
2467       __ cmp(lir_cond_equal, value, i + lo_key);
2468       __ move(data_offset_reg, tmp_reg);
2469       __ cmove(lir_cond_equal,
2470                LIR_OprFact::intptrConst(count_offset),
2471                tmp_reg,
2472                data_offset_reg, T_INT);
2473     }
2474 
2475     LIR_Opr data_reg = new_pointer_register();
2476     LIR_Address* data_addr = new LIR_Address(md_reg, data_offset_reg, data_reg->type());
2477     __ move(data_addr, data_reg);
2478     __ add(data_reg, LIR_OprFact::intptrConst(1), data_reg);
2479     __ move(data_reg, data_addr);
2480   }
2481 
2482   if (UseTableRanges) {
2483     do_SwitchRanges(create_lookup_ranges(x), value, x->default_sux());
2484   } else {
2485     for (int i = 0; i < len; i++) {
2486       __ cmp(lir_cond_equal, value, i + lo_key);
2487       __ branch(lir_cond_equal, x->sux_at(i));
2488     }
2489     __ jump(x->default_sux());
2490   }
2491 }
2492 
2493 
2494 void LIRGenerator::do_LookupSwitch(LookupSwitch* x) {
2495   LIRItem tag(x->tag(), this);
2496   tag.load_item();
2497   set_no_result(x);
2498 
2499   if (x->is_safepoint()) {
2500     __ safepoint(safepoint_poll_register(), state_for(x, x->state_before()));
2501   }
2502 
2503   // move values into phi locations
2504   move_to_phi(x->state());
2505 
2506   LIR_Opr value = tag.result();
2507   int len = x->length();
2508 
2509   if (compilation()->env()->comp_level() == CompLevel_full_profile && UseSwitchProfiling) {
2510     ciMethod* method = x->state()->scope()->method();
2511     ciMethodData* md = method->method_data_or_null();
2512     assert(md != NULL, "Sanity");
2513     ciProfileData* data = md->bci_to_data(x->state()->bci());
2514     assert(data != NULL, "must have profiling data");
2515     assert(data->is_MultiBranchData(), "bad profile data?");
2516     int default_count_offset = md->byte_offset_of_slot(data, MultiBranchData::default_count_offset());
2517     LIR_Opr md_reg = new_register(T_METADATA);
2518     __ metadata2reg(md->constant_encoding(), md_reg);
2519     LIR_Opr data_offset_reg = new_pointer_register();
2520     LIR_Opr tmp_reg = new_pointer_register();
2521 
2522     __ move(LIR_OprFact::intptrConst(default_count_offset), data_offset_reg);
2523     for (int i = 0; i < len; i++) {
2524       int count_offset = md->byte_offset_of_slot(data, MultiBranchData::case_count_offset(i));
2525       __ cmp(lir_cond_equal, value, x->key_at(i));
2526       __ move(data_offset_reg, tmp_reg);
2527       __ cmove(lir_cond_equal,
2528                LIR_OprFact::intptrConst(count_offset),
2529                tmp_reg,
2530                data_offset_reg, T_INT);
2531     }
2532 
2533     LIR_Opr data_reg = new_pointer_register();
2534     LIR_Address* data_addr = new LIR_Address(md_reg, data_offset_reg, data_reg->type());
2535     __ move(data_addr, data_reg);
2536     __ add(data_reg, LIR_OprFact::intptrConst(1), data_reg);
2537     __ move(data_reg, data_addr);
2538   }
2539 
2540   if (UseTableRanges) {
2541     do_SwitchRanges(create_lookup_ranges(x), value, x->default_sux());
2542   } else {
2543     int len = x->length();
2544     for (int i = 0; i < len; i++) {
2545       __ cmp(lir_cond_equal, value, x->key_at(i));
2546       __ branch(lir_cond_equal, x->sux_at(i));
2547     }
2548     __ jump(x->default_sux());
2549   }
2550 }
2551 
2552 
2553 void LIRGenerator::do_Goto(Goto* x) {
2554   set_no_result(x);
2555 
2556   if (block()->next()->as_OsrEntry()) {
2557     // need to free up storage used for OSR entry point
2558     LIR_Opr osrBuffer = block()->next()->operand();
2559     BasicTypeList signature;
2560     signature.append(NOT_LP64(T_INT) LP64_ONLY(T_LONG)); // pass a pointer to osrBuffer
2561     CallingConvention* cc = frame_map()->c_calling_convention(&signature);
2562     __ move(osrBuffer, cc->args()->at(0));
2563     __ call_runtime_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::OSR_migration_end),
2564                          getThreadTemp(), LIR_OprFact::illegalOpr, cc->args());
2565   }
2566 
2567   if (x->is_safepoint()) {
2568     ValueStack* state = x->state_before() ? x->state_before() : x->state();
2569 
2570     // increment backedge counter if needed
2571     CodeEmitInfo* info = state_for(x, state);
2572     increment_backedge_counter(info, x->profiled_bci());
2573     CodeEmitInfo* safepoint_info = state_for(x, state);
2574     __ safepoint(safepoint_poll_register(), safepoint_info);
2575   }
2576 
2577   // Gotos can be folded Ifs, handle this case.
2578   if (x->should_profile()) {
2579     ciMethod* method = x->profiled_method();
2580     assert(method != NULL, "method should be set if branch is profiled");
2581     ciMethodData* md = method->method_data_or_null();
2582     assert(md != NULL, "Sanity");
2583     ciProfileData* data = md->bci_to_data(x->profiled_bci());
2584     assert(data != NULL, "must have profiling data");
2585     int offset;
2586     if (x->direction() == Goto::taken) {
2587       assert(data->is_BranchData(), "need BranchData for two-way branches");
2588       offset = md->byte_offset_of_slot(data, BranchData::taken_offset());
2589     } else if (x->direction() == Goto::not_taken) {
2590       assert(data->is_BranchData(), "need BranchData for two-way branches");
2591       offset = md->byte_offset_of_slot(data, BranchData::not_taken_offset());
2592     } else {
2593       assert(data->is_JumpData(), "need JumpData for branches");
2594       offset = md->byte_offset_of_slot(data, JumpData::taken_offset());
2595     }
2596     LIR_Opr md_reg = new_register(T_METADATA);
2597     __ metadata2reg(md->constant_encoding(), md_reg);
2598 
2599     increment_counter(new LIR_Address(md_reg, offset,
2600                                       NOT_LP64(T_INT) LP64_ONLY(T_LONG)), DataLayout::counter_increment);
2601   }
2602 
2603   // emit phi-instruction move after safepoint since this simplifies
2604   // describing the state as the safepoint.
2605   move_to_phi(x->state());
2606 
2607   __ jump(x->default_sux());
2608 }
2609 
2610 /**
2611  * Emit profiling code if needed for arguments, parameters, return value types
2612  *
2613  * @param md                    MDO the code will update at runtime
2614  * @param md_base_offset        common offset in the MDO for this profile and subsequent ones
2615  * @param md_offset             offset in the MDO (on top of md_base_offset) for this profile
2616  * @param profiled_k            current profile
2617  * @param obj                   IR node for the object to be profiled
2618  * @param mdp                   register to hold the pointer inside the MDO (md + md_base_offset).
2619  *                              Set once we find an update to make and use for next ones.
2620  * @param not_null              true if we know obj cannot be null
2621  * @param signature_at_call_k   signature at call for obj
2622  * @param callee_signature_k    signature of callee for obj
2623  *                              at call and callee signatures differ at method handle call
2624  * @return                      the only klass we know will ever be seen at this profile point
2625  */
2626 ciKlass* LIRGenerator::profile_type(ciMethodData* md, int md_base_offset, int md_offset, intptr_t profiled_k,
2627                                     Value obj, LIR_Opr& mdp, bool not_null, ciKlass* signature_at_call_k,
2628                                     ciKlass* callee_signature_k) {
2629   ciKlass* result = NULL;
2630   bool do_null = !not_null && !TypeEntries::was_null_seen(profiled_k);
2631   bool do_update = !TypeEntries::is_type_unknown(profiled_k);
2632   // known not to be null or null bit already set and already set to
2633   // unknown: nothing we can do to improve profiling
2634   if (!do_null && !do_update) {
2635     return result;
2636   }
2637 
2638   ciKlass* exact_klass = NULL;
2639   Compilation* comp = Compilation::current();
2640   if (do_update) {
2641     // try to find exact type, using CHA if possible, so that loading
2642     // the klass from the object can be avoided
2643     ciType* type = obj->exact_type();
2644     if (type == NULL) {
2645       type = obj->declared_type();
2646       type = comp->cha_exact_type(type);
2647     }
2648     assert(type == NULL || type->is_klass(), "type should be class");
2649     exact_klass = (type != NULL && type->is_loaded()) ? (ciKlass*)type : NULL;
2650 
2651     do_update = exact_klass == NULL || ciTypeEntries::valid_ciklass(profiled_k) != exact_klass;
2652   }
2653 
2654   if (!do_null && !do_update) {
2655     return result;
2656   }
2657 
2658   ciKlass* exact_signature_k = NULL;
2659   if (do_update) {
2660     // Is the type from the signature exact (the only one possible)?
2661     exact_signature_k = signature_at_call_k->exact_klass();
2662     if (exact_signature_k == NULL) {
2663       exact_signature_k = comp->cha_exact_type(signature_at_call_k);
2664     } else {
2665       result = exact_signature_k;
2666       // Known statically. No need to emit any code: prevent
2667       // LIR_Assembler::emit_profile_type() from emitting useless code
2668       profiled_k = ciTypeEntries::with_status(result, profiled_k);
2669     }
2670     // exact_klass and exact_signature_k can be both non NULL but
2671     // different if exact_klass is loaded after the ciObject for
2672     // exact_signature_k is created.
2673     if (exact_klass == NULL && exact_signature_k != NULL && exact_klass != exact_signature_k) {
2674       // sometimes the type of the signature is better than the best type
2675       // the compiler has
2676       exact_klass = exact_signature_k;
2677     }
2678     if (callee_signature_k != NULL &&
2679         callee_signature_k != signature_at_call_k) {
2680       ciKlass* improved_klass = callee_signature_k->exact_klass();
2681       if (improved_klass == NULL) {
2682         improved_klass = comp->cha_exact_type(callee_signature_k);
2683       }
2684       if (exact_klass == NULL && improved_klass != NULL && exact_klass != improved_klass) {
2685         exact_klass = exact_signature_k;
2686       }
2687     }
2688     do_update = exact_klass == NULL || ciTypeEntries::valid_ciklass(profiled_k) != exact_klass;
2689   }
2690 
2691   if (!do_null && !do_update) {
2692     return result;
2693   }
2694 
2695   if (mdp == LIR_OprFact::illegalOpr) {
2696     mdp = new_register(T_METADATA);
2697     __ metadata2reg(md->constant_encoding(), mdp);
2698     if (md_base_offset != 0) {
2699       LIR_Address* base_type_address = new LIR_Address(mdp, md_base_offset, T_ADDRESS);
2700       mdp = new_pointer_register();
2701       __ leal(LIR_OprFact::address(base_type_address), mdp);
2702     }
2703   }
2704   LIRItem value(obj, this);
2705   value.load_item();
2706   __ profile_type(new LIR_Address(mdp, md_offset, T_METADATA),
2707                   value.result(), exact_klass, profiled_k, new_pointer_register(), not_null, exact_signature_k != NULL);
2708   return result;
2709 }
2710 
2711 // profile parameters on entry to the root of the compilation
2712 void LIRGenerator::profile_parameters(Base* x) {
2713   if (compilation()->profile_parameters()) {
2714     CallingConvention* args = compilation()->frame_map()->incoming_arguments();
2715     ciMethodData* md = scope()->method()->method_data_or_null();
2716     assert(md != NULL, "Sanity");
2717 
2718     if (md->parameters_type_data() != NULL) {
2719       ciParametersTypeData* parameters_type_data = md->parameters_type_data();
2720       ciTypeStackSlotEntries* parameters =  parameters_type_data->parameters();
2721       LIR_Opr mdp = LIR_OprFact::illegalOpr;
2722       for (int java_index = 0, i = 0, j = 0; j < parameters_type_data->number_of_parameters(); i++) {
2723         LIR_Opr src = args->at(i);
2724         assert(!src->is_illegal(), "check");
2725         BasicType t = src->type();
2726         if (is_reference_type(t)) {
2727           intptr_t profiled_k = parameters->type(j);
2728           Local* local = x->state()->local_at(java_index)->as_Local();
2729           ciKlass* exact = profile_type(md, md->byte_offset_of_slot(parameters_type_data, ParametersTypeData::type_offset(0)),
2730                                         in_bytes(ParametersTypeData::type_offset(j)) - in_bytes(ParametersTypeData::type_offset(0)),
2731                                         profiled_k, local, mdp, false, local->declared_type()->as_klass(), NULL);
2732           // If the profile is known statically set it once for all and do not emit any code
2733           if (exact != NULL) {
2734             md->set_parameter_type(j, exact);
2735           }
2736           j++;
2737         }
2738         java_index += type2size[t];
2739       }
2740     }
2741   }
2742 }
2743 
2744 void LIRGenerator::do_Base(Base* x) {
2745   __ std_entry(LIR_OprFact::illegalOpr);
2746   // Emit moves from physical registers / stack slots to virtual registers
2747   CallingConvention* args = compilation()->frame_map()->incoming_arguments();
2748   IRScope* irScope = compilation()->hir()->top_scope();
2749   int java_index = 0;
2750   for (int i = 0; i < args->length(); i++) {
2751     LIR_Opr src = args->at(i);
2752     assert(!src->is_illegal(), "check");
2753     BasicType t = src->type();
2754 
2755     // Types which are smaller than int are passed as int, so
2756     // correct the type which passed.
2757     switch (t) {
2758     case T_BYTE:
2759     case T_BOOLEAN:
2760     case T_SHORT:
2761     case T_CHAR:
2762       t = T_INT;
2763       break;
2764     default:
2765       break;
2766     }
2767 
2768     LIR_Opr dest = new_register(t);
2769     __ move(src, dest);
2770 
2771     // Assign new location to Local instruction for this local
2772     Local* local = x->state()->local_at(java_index)->as_Local();
2773     assert(local != NULL, "Locals for incoming arguments must have been created");
2774 #ifndef __SOFTFP__
2775     // The java calling convention passes double as long and float as int.
2776     assert(as_ValueType(t)->tag() == local->type()->tag(), "check");
2777 #endif // __SOFTFP__
2778     local->set_operand(dest);
2779     _instruction_for_operand.at_put_grow(dest->vreg_number(), local, NULL);
2780     java_index += type2size[t];
2781   }
2782 
2783   if (compilation()->env()->dtrace_method_probes()) {
2784     BasicTypeList signature;
2785     signature.append(LP64_ONLY(T_LONG) NOT_LP64(T_INT));    // thread
2786     signature.append(T_METADATA); // Method*
2787     LIR_OprList* args = new LIR_OprList();
2788     args->append(getThreadPointer());
2789     LIR_Opr meth = new_register(T_METADATA);
2790     __ metadata2reg(method()->constant_encoding(), meth);
2791     args->append(meth);
2792     call_runtime(&signature, args, CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry), voidType, NULL);
2793   }
2794 
2795   if (method()->is_synchronized()) {
2796     LIR_Opr obj;
2797     if (method()->is_static()) {
2798       obj = new_register(T_OBJECT);
2799       __ oop2reg(method()->holder()->java_mirror()->constant_encoding(), obj);
2800     } else {
2801       Local* receiver = x->state()->local_at(0)->as_Local();
2802       assert(receiver != NULL, "must already exist");
2803       obj = receiver->operand();
2804     }
2805     assert(obj->is_valid(), "must be valid");
2806 
2807     if (method()->is_synchronized() && GenerateSynchronizationCode) {
2808       LIR_Opr lock = syncLockOpr();
2809       __ load_stack_address_monitor(0, lock);
2810 
2811       CodeEmitInfo* info = new CodeEmitInfo(scope()->start()->state()->copy(ValueStack::StateBefore, SynchronizationEntryBCI), NULL, x->check_flag(Instruction::DeoptimizeOnException));
2812       CodeStub* slow_path = new MonitorEnterStub(obj, lock, info);
2813 
2814       // receiver is guaranteed non-NULL so don't need CodeEmitInfo
2815       __ lock_object(syncTempOpr(), obj, lock, new_register(T_OBJECT), slow_path, NULL);
2816     }
2817   }
2818   if (compilation()->age_code()) {
2819     CodeEmitInfo* info = new CodeEmitInfo(scope()->start()->state()->copy(ValueStack::StateBefore, 0), NULL, false);
2820     decrement_age(info);
2821   }
2822   // increment invocation counters if needed
2823   if (!method()->is_accessor()) { // Accessors do not have MDOs, so no counting.
2824     profile_parameters(x);
2825     CodeEmitInfo* info = new CodeEmitInfo(scope()->start()->state()->copy(ValueStack::StateBefore, SynchronizationEntryBCI), NULL, false);
2826     increment_invocation_counter(info);
2827   }
2828 
2829   // all blocks with a successor must end with an unconditional jump
2830   // to the successor even if they are consecutive
2831   __ jump(x->default_sux());
2832 }
2833 
2834 
2835 void LIRGenerator::do_OsrEntry(OsrEntry* x) {
2836   // construct our frame and model the production of incoming pointer
2837   // to the OSR buffer.
2838   __ osr_entry(LIR_Assembler::osrBufferPointer());
2839   LIR_Opr result = rlock_result(x);
2840   __ move(LIR_Assembler::osrBufferPointer(), result);
2841 }
2842 
2843 
2844 void LIRGenerator::invoke_load_arguments(Invoke* x, LIRItemList* args, const LIR_OprList* arg_list) {
2845   assert(args->length() == arg_list->length(),
2846          "args=%d, arg_list=%d", args->length(), arg_list->length());
2847   for (int i = x->has_receiver() ? 1 : 0; i < args->length(); i++) {
2848     LIRItem* param = args->at(i);
2849     LIR_Opr loc = arg_list->at(i);
2850     if (loc->is_register()) {
2851       param->load_item_force(loc);
2852     } else {
2853       LIR_Address* addr = loc->as_address_ptr();
2854       param->load_for_store(addr->type());
2855       if (addr->type() == T_OBJECT) {
2856         __ move_wide(param->result(), addr);
2857       } else
2858         if (addr->type() == T_LONG || addr->type() == T_DOUBLE) {
2859           __ unaligned_move(param->result(), addr);
2860         } else {
2861           __ move(param->result(), addr);
2862         }
2863     }
2864   }
2865 
2866   if (x->has_receiver()) {
2867     LIRItem* receiver = args->at(0);
2868     LIR_Opr loc = arg_list->at(0);
2869     if (loc->is_register()) {
2870       receiver->load_item_force(loc);
2871     } else {
2872       assert(loc->is_address(), "just checking");
2873       receiver->load_for_store(T_OBJECT);
2874       __ move_wide(receiver->result(), loc->as_address_ptr());
2875     }
2876   }
2877 }
2878 
2879 
2880 // Visits all arguments, returns appropriate items without loading them
2881 LIRItemList* LIRGenerator::invoke_visit_arguments(Invoke* x) {
2882   LIRItemList* argument_items = new LIRItemList();
2883   if (x->has_receiver()) {
2884     LIRItem* receiver = new LIRItem(x->receiver(), this);
2885     argument_items->append(receiver);
2886   }
2887   for (int i = 0; i < x->number_of_arguments(); i++) {
2888     LIRItem* param = new LIRItem(x->argument_at(i), this);
2889     argument_items->append(param);
2890   }
2891   return argument_items;
2892 }
2893 
2894 
2895 // The invoke with receiver has following phases:
2896 //   a) traverse and load/lock receiver;
2897 //   b) traverse all arguments -> item-array (invoke_visit_argument)
2898 //   c) push receiver on stack
2899 //   d) load each of the items and push on stack
2900 //   e) unlock receiver
2901 //   f) move receiver into receiver-register %o0
2902 //   g) lock result registers and emit call operation
2903 //
2904 // Before issuing a call, we must spill-save all values on stack
2905 // that are in caller-save register. "spill-save" moves those registers
2906 // either in a free callee-save register or spills them if no free
2907 // callee save register is available.
2908 //
2909 // The problem is where to invoke spill-save.
2910 // - if invoked between e) and f), we may lock callee save
2911 //   register in "spill-save" that destroys the receiver register
2912 //   before f) is executed
2913 // - if we rearrange f) to be earlier (by loading %o0) it
2914 //   may destroy a value on the stack that is currently in %o0
2915 //   and is waiting to be spilled
2916 // - if we keep the receiver locked while doing spill-save,
2917 //   we cannot spill it as it is spill-locked
2918 //
2919 void LIRGenerator::do_Invoke(Invoke* x) {
2920   CallingConvention* cc = frame_map()->java_calling_convention(x->signature(), true);
2921 
2922   LIR_OprList* arg_list = cc->args();
2923   LIRItemList* args = invoke_visit_arguments(x);
2924   LIR_Opr receiver = LIR_OprFact::illegalOpr;
2925 
2926   // setup result register
2927   LIR_Opr result_register = LIR_OprFact::illegalOpr;
2928   if (x->type() != voidType) {
2929     result_register = result_register_for(x->type());
2930   }
2931 
2932   CodeEmitInfo* info = state_for(x, x->state());
2933 
2934   invoke_load_arguments(x, args, arg_list);
2935 
2936   if (x->has_receiver()) {
2937     args->at(0)->load_item_force(LIR_Assembler::receiverOpr());
2938     receiver = args->at(0)->result();
2939   }
2940 
2941   // emit invoke code
2942   assert(receiver->is_illegal() || receiver->is_equal(LIR_Assembler::receiverOpr()), "must match");
2943 
2944   // JSR 292
2945   // Preserve the SP over MethodHandle call sites, if needed.
2946   ciMethod* target = x->target();
2947   bool is_method_handle_invoke = (// %%% FIXME: Are both of these relevant?
2948                                   target->is_method_handle_intrinsic() ||
2949                                   target->is_compiled_lambda_form());
2950   if (is_method_handle_invoke) {
2951     info->set_is_method_handle_invoke(true);
2952     if(FrameMap::method_handle_invoke_SP_save_opr() != LIR_OprFact::illegalOpr) {
2953         __ move(FrameMap::stack_pointer(), FrameMap::method_handle_invoke_SP_save_opr());
2954     }
2955   }
2956 
2957   switch (x->code()) {
2958     case Bytecodes::_invokestatic:
2959       __ call_static(target, result_register,
2960                      SharedRuntime::get_resolve_static_call_stub(),
2961                      arg_list, info);
2962       break;
2963     case Bytecodes::_invokespecial:
2964     case Bytecodes::_invokevirtual:
2965     case Bytecodes::_invokeinterface:
2966       // for loaded and final (method or class) target we still produce an inline cache,
2967       // in order to be able to call mixed mode
2968       if (x->code() == Bytecodes::_invokespecial || x->target_is_final()) {
2969         __ call_opt_virtual(target, receiver, result_register,
2970                             SharedRuntime::get_resolve_opt_virtual_call_stub(),
2971                             arg_list, info);
2972       } else {
2973         __ call_icvirtual(target, receiver, result_register,
2974                           SharedRuntime::get_resolve_virtual_call_stub(),
2975                           arg_list, info);
2976       }
2977       break;
2978     case Bytecodes::_invokedynamic: {
2979       __ call_dynamic(target, receiver, result_register,
2980                       SharedRuntime::get_resolve_static_call_stub(),
2981                       arg_list, info);
2982       break;
2983     }
2984     default:
2985       fatal("unexpected bytecode: %s", Bytecodes::name(x->code()));
2986       break;
2987   }
2988 
2989   // JSR 292
2990   // Restore the SP after MethodHandle call sites, if needed.
2991   if (is_method_handle_invoke
2992       && FrameMap::method_handle_invoke_SP_save_opr() != LIR_OprFact::illegalOpr) {
2993     __ move(FrameMap::method_handle_invoke_SP_save_opr(), FrameMap::stack_pointer());
2994   }
2995 
2996   if (result_register->is_valid()) {
2997     LIR_Opr result = rlock_result(x);
2998     __ move(result_register, result);
2999   }
3000 }
3001 
3002 
3003 void LIRGenerator::do_FPIntrinsics(Intrinsic* x) {
3004   assert(x->number_of_arguments() == 1, "wrong type");
3005   LIRItem value       (x->argument_at(0), this);
3006   LIR_Opr reg = rlock_result(x);
3007   value.load_item();
3008   LIR_Opr tmp = force_to_spill(value.result(), as_BasicType(x->type()));
3009   __ move(tmp, reg);
3010 }
3011 
3012 
3013 
3014 // Code for  :  x->x() {x->cond()} x->y() ? x->tval() : x->fval()
3015 void LIRGenerator::do_IfOp(IfOp* x) {
3016 #ifdef ASSERT
3017   {
3018     ValueTag xtag = x->x()->type()->tag();
3019     ValueTag ttag = x->tval()->type()->tag();
3020     assert(xtag == intTag || xtag == objectTag, "cannot handle others");
3021     assert(ttag == addressTag || ttag == intTag || ttag == objectTag || ttag == longTag, "cannot handle others");
3022     assert(ttag == x->fval()->type()->tag(), "cannot handle others");
3023   }
3024 #endif
3025 
3026   LIRItem left(x->x(), this);
3027   LIRItem right(x->y(), this);
3028   left.load_item();
3029   if (can_inline_as_constant(right.value())) {
3030     right.dont_load_item();
3031   } else {
3032     right.load_item();
3033   }
3034 
3035   LIRItem t_val(x->tval(), this);
3036   LIRItem f_val(x->fval(), this);
3037   t_val.dont_load_item();
3038   f_val.dont_load_item();
3039   LIR_Opr reg = rlock_result(x);
3040 
3041   __ cmp(lir_cond(x->cond()), left.result(), right.result());
3042   __ cmove(lir_cond(x->cond()), t_val.result(), f_val.result(), reg, as_BasicType(x->x()->type()));
3043 }
3044 
3045 #ifdef JFR_HAVE_INTRINSICS
3046 
3047 void LIRGenerator::do_getEventWriter(Intrinsic* x) {
3048   LabelObj* L_end = new LabelObj();
3049 
3050   // FIXME T_ADDRESS should actually be T_METADATA but it can't because the
3051   // meaning of these two is mixed up (see JDK-8026837).
3052   LIR_Address* jobj_addr = new LIR_Address(getThreadPointer(),
3053                                            in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR),
3054                                            T_ADDRESS);
3055   LIR_Opr result = rlock_result(x);
3056   __ move(LIR_OprFact::oopConst(NULL), result);
3057   LIR_Opr jobj = new_register(T_METADATA);
3058   __ move_wide(jobj_addr, jobj);
3059   __ cmp(lir_cond_equal, jobj, LIR_OprFact::metadataConst(0));
3060   __ branch(lir_cond_equal, L_end->label());
3061 
3062   access_load(IN_NATIVE, T_OBJECT, LIR_OprFact::address(new LIR_Address(jobj, T_OBJECT)), result);
3063 
3064   __ branch_destination(L_end->label());
3065 }
3066 
3067 #endif
3068 
3069 
3070 void LIRGenerator::do_RuntimeCall(address routine, Intrinsic* x) {
3071   assert(x->number_of_arguments() == 0, "wrong type");
3072   // Enforce computation of _reserved_argument_area_size which is required on some platforms.
3073   BasicTypeList signature;
3074   CallingConvention* cc = frame_map()->c_calling_convention(&signature);
3075   LIR_Opr reg = result_register_for(x->type());
3076   __ call_runtime_leaf(routine, getThreadTemp(),
3077                        reg, new LIR_OprList());
3078   LIR_Opr result = rlock_result(x);
3079   __ move(reg, result);
3080 }
3081 
3082 
3083 
3084 void LIRGenerator::do_Intrinsic(Intrinsic* x) {
3085   switch (x->id()) {
3086   case vmIntrinsics::_intBitsToFloat      :
3087   case vmIntrinsics::_doubleToRawLongBits :
3088   case vmIntrinsics::_longBitsToDouble    :
3089   case vmIntrinsics::_floatToRawIntBits   : {
3090     do_FPIntrinsics(x);
3091     break;
3092   }
3093 
3094 #ifdef JFR_HAVE_INTRINSICS
3095   case vmIntrinsics::_getEventWriter:
3096     do_getEventWriter(x);
3097     break;
3098   case vmIntrinsics::_counterTime:
3099     do_RuntimeCall(CAST_FROM_FN_PTR(address, JFR_TIME_FUNCTION), x);
3100     break;
3101 #endif
3102 
3103   case vmIntrinsics::_currentTimeMillis:
3104     do_RuntimeCall(CAST_FROM_FN_PTR(address, os::javaTimeMillis), x);
3105     break;
3106 
3107   case vmIntrinsics::_nanoTime:
3108     do_RuntimeCall(CAST_FROM_FN_PTR(address, os::javaTimeNanos), x);
3109     break;
3110 
3111   case vmIntrinsics::_Object_init:    do_RegisterFinalizer(x); break;
3112   case vmIntrinsics::_isInstance:     do_isInstance(x);    break;
3113   case vmIntrinsics::_isPrimitive:    do_isPrimitive(x);   break;
3114   case vmIntrinsics::_getModifiers:   do_getModifiers(x);  break;
3115   case vmIntrinsics::_getClass:       do_getClass(x);      break;
3116   case vmIntrinsics::_currentThread:  do_currentThread(x); break;
3117   case vmIntrinsics::_getObjectSize:  do_getObjectSize(x); break;
3118 
3119   case vmIntrinsics::_dlog:           // fall through
3120   case vmIntrinsics::_dlog10:         // fall through
3121   case vmIntrinsics::_dabs:           // fall through
3122   case vmIntrinsics::_dsqrt:          // fall through
3123   case vmIntrinsics::_dtan:           // fall through
3124   case vmIntrinsics::_dsin :          // fall through
3125   case vmIntrinsics::_dcos :          // fall through
3126   case vmIntrinsics::_dexp :          // fall through
3127   case vmIntrinsics::_dpow :          do_MathIntrinsic(x); break;
3128   case vmIntrinsics::_arraycopy:      do_ArrayCopy(x);     break;
3129 
3130   case vmIntrinsics::_fmaD:           do_FmaIntrinsic(x); break;
3131   case vmIntrinsics::_fmaF:           do_FmaIntrinsic(x); break;
3132 
3133   // java.nio.Buffer.checkIndex
3134   case vmIntrinsics::_checkIndex:     do_NIOCheckIndex(x); break;
3135 
3136   case vmIntrinsics::_compareAndSetReference:
3137     do_CompareAndSwap(x, objectType);
3138     break;
3139   case vmIntrinsics::_compareAndSetInt:
3140     do_CompareAndSwap(x, intType);
3141     break;
3142   case vmIntrinsics::_compareAndSetLong:
3143     do_CompareAndSwap(x, longType);
3144     break;
3145 
3146   case vmIntrinsics::_loadFence :
3147     __ membar_acquire();
3148     break;
3149   case vmIntrinsics::_storeFence:
3150     __ membar_release();
3151     break;
3152   case vmIntrinsics::_storeStoreFence:
3153     __ membar_storestore();
3154     break;
3155   case vmIntrinsics::_fullFence :
3156     __ membar();
3157     break;
3158   case vmIntrinsics::_onSpinWait:
3159     __ on_spin_wait();
3160     break;
3161   case vmIntrinsics::_Reference_get:
3162     do_Reference_get(x);
3163     break;
3164 
3165   case vmIntrinsics::_updateCRC32:
3166   case vmIntrinsics::_updateBytesCRC32:
3167   case vmIntrinsics::_updateByteBufferCRC32:
3168     do_update_CRC32(x);
3169     break;
3170 
3171   case vmIntrinsics::_updateBytesCRC32C:
3172   case vmIntrinsics::_updateDirectByteBufferCRC32C:
3173     do_update_CRC32C(x);
3174     break;
3175 
3176   case vmIntrinsics::_vectorizedMismatch:
3177     do_vectorizedMismatch(x);
3178     break;
3179 
3180   case vmIntrinsics::_blackhole:
3181     do_blackhole(x);
3182     break;
3183 
3184   default: ShouldNotReachHere(); break;
3185   }
3186 }
3187 
3188 void LIRGenerator::profile_arguments(ProfileCall* x) {
3189   if (compilation()->profile_arguments()) {
3190     int bci = x->bci_of_invoke();
3191     ciMethodData* md = x->method()->method_data_or_null();
3192     assert(md != NULL, "Sanity");
3193     ciProfileData* data = md->bci_to_data(bci);
3194     if (data != NULL) {
3195       if ((data->is_CallTypeData() && data->as_CallTypeData()->has_arguments()) ||
3196           (data->is_VirtualCallTypeData() && data->as_VirtualCallTypeData()->has_arguments())) {
3197         ByteSize extra = data->is_CallTypeData() ? CallTypeData::args_data_offset() : VirtualCallTypeData::args_data_offset();
3198         int base_offset = md->byte_offset_of_slot(data, extra);
3199         LIR_Opr mdp = LIR_OprFact::illegalOpr;
3200         ciTypeStackSlotEntries* args = data->is_CallTypeData() ? ((ciCallTypeData*)data)->args() : ((ciVirtualCallTypeData*)data)->args();
3201 
3202         Bytecodes::Code bc = x->method()->java_code_at_bci(bci);
3203         int start = 0;
3204         int stop = data->is_CallTypeData() ? ((ciCallTypeData*)data)->number_of_arguments() : ((ciVirtualCallTypeData*)data)->number_of_arguments();
3205         if (x->callee()->is_loaded() && x->callee()->is_static() && Bytecodes::has_receiver(bc)) {
3206           // first argument is not profiled at call (method handle invoke)
3207           assert(x->method()->raw_code_at_bci(bci) == Bytecodes::_invokehandle, "invokehandle expected");
3208           start = 1;
3209         }
3210         ciSignature* callee_signature = x->callee()->signature();
3211         // method handle call to virtual method
3212         bool has_receiver = x->callee()->is_loaded() && !x->callee()->is_static() && !Bytecodes::has_receiver(bc);
3213         ciSignatureStream callee_signature_stream(callee_signature, has_receiver ? x->callee()->holder() : NULL);
3214 
3215         bool ignored_will_link;
3216         ciSignature* signature_at_call = NULL;
3217         x->method()->get_method_at_bci(bci, ignored_will_link, &signature_at_call);
3218         ciSignatureStream signature_at_call_stream(signature_at_call);
3219 
3220         // if called through method handle invoke, some arguments may have been popped
3221         for (int i = 0; i < stop && i+start < x->nb_profiled_args(); i++) {
3222           int off = in_bytes(TypeEntriesAtCall::argument_type_offset(i)) - in_bytes(TypeEntriesAtCall::args_data_offset());
3223           ciKlass* exact = profile_type(md, base_offset, off,
3224               args->type(i), x->profiled_arg_at(i+start), mdp,
3225               !x->arg_needs_null_check(i+start),
3226               signature_at_call_stream.next_klass(), callee_signature_stream.next_klass());
3227           if (exact != NULL) {
3228             md->set_argument_type(bci, i, exact);
3229           }
3230         }
3231       } else {
3232 #ifdef ASSERT
3233         Bytecodes::Code code = x->method()->raw_code_at_bci(x->bci_of_invoke());
3234         int n = x->nb_profiled_args();
3235         assert(MethodData::profile_parameters() && (MethodData::profile_arguments_jsr292_only() ||
3236             (x->inlined() && ((code == Bytecodes::_invokedynamic && n <= 1) || (code == Bytecodes::_invokehandle && n <= 2)))),
3237             "only at JSR292 bytecodes");
3238 #endif
3239       }
3240     }
3241   }
3242 }
3243 
3244 // profile parameters on entry to an inlined method
3245 void LIRGenerator::profile_parameters_at_call(ProfileCall* x) {
3246   if (compilation()->profile_parameters() && x->inlined()) {
3247     ciMethodData* md = x->callee()->method_data_or_null();
3248     if (md != NULL) {
3249       ciParametersTypeData* parameters_type_data = md->parameters_type_data();
3250       if (parameters_type_data != NULL) {
3251         ciTypeStackSlotEntries* parameters =  parameters_type_data->parameters();
3252         LIR_Opr mdp = LIR_OprFact::illegalOpr;
3253         bool has_receiver = !x->callee()->is_static();
3254         ciSignature* sig = x->callee()->signature();
3255         ciSignatureStream sig_stream(sig, has_receiver ? x->callee()->holder() : NULL);
3256         int i = 0; // to iterate on the Instructions
3257         Value arg = x->recv();
3258         bool not_null = false;
3259         int bci = x->bci_of_invoke();
3260         Bytecodes::Code bc = x->method()->java_code_at_bci(bci);
3261         // The first parameter is the receiver so that's what we start
3262         // with if it exists. One exception is method handle call to
3263         // virtual method: the receiver is in the args list
3264         if (arg == NULL || !Bytecodes::has_receiver(bc)) {
3265           i = 1;
3266           arg = x->profiled_arg_at(0);
3267           not_null = !x->arg_needs_null_check(0);
3268         }
3269         int k = 0; // to iterate on the profile data
3270         for (;;) {
3271           intptr_t profiled_k = parameters->type(k);
3272           ciKlass* exact = profile_type(md, md->byte_offset_of_slot(parameters_type_data, ParametersTypeData::type_offset(0)),
3273                                         in_bytes(ParametersTypeData::type_offset(k)) - in_bytes(ParametersTypeData::type_offset(0)),
3274                                         profiled_k, arg, mdp, not_null, sig_stream.next_klass(), NULL);
3275           // If the profile is known statically set it once for all and do not emit any code
3276           if (exact != NULL) {
3277             md->set_parameter_type(k, exact);
3278           }
3279           k++;
3280           if (k >= parameters_type_data->number_of_parameters()) {
3281 #ifdef ASSERT
3282             int extra = 0;
3283             if (MethodData::profile_arguments() && TypeProfileParmsLimit != -1 &&
3284                 x->nb_profiled_args() >= TypeProfileParmsLimit &&
3285                 x->recv() != NULL && Bytecodes::has_receiver(bc)) {
3286               extra += 1;
3287             }
3288             assert(i == x->nb_profiled_args() - extra || (TypeProfileParmsLimit != -1 && TypeProfileArgsLimit > TypeProfileParmsLimit), "unused parameters?");
3289 #endif
3290             break;
3291           }
3292           arg = x->profiled_arg_at(i);
3293           not_null = !x->arg_needs_null_check(i);
3294           i++;
3295         }
3296       }
3297     }
3298   }
3299 }
3300 
3301 void LIRGenerator::do_ProfileCall(ProfileCall* x) {
3302   // Need recv in a temporary register so it interferes with the other temporaries
3303   LIR_Opr recv = LIR_OprFact::illegalOpr;
3304   LIR_Opr mdo = new_register(T_METADATA);
3305   // tmp is used to hold the counters on SPARC
3306   LIR_Opr tmp = new_pointer_register();
3307 
3308   if (x->nb_profiled_args() > 0) {
3309     profile_arguments(x);
3310   }
3311 
3312   // profile parameters on inlined method entry including receiver
3313   if (x->recv() != NULL || x->nb_profiled_args() > 0) {
3314     profile_parameters_at_call(x);
3315   }
3316 
3317   if (x->recv() != NULL) {
3318     LIRItem value(x->recv(), this);
3319     value.load_item();
3320     recv = new_register(T_OBJECT);
3321     __ move(value.result(), recv);
3322   }
3323   __ profile_call(x->method(), x->bci_of_invoke(), x->callee(), mdo, recv, tmp, x->known_holder());
3324 }
3325 
3326 void LIRGenerator::do_ProfileReturnType(ProfileReturnType* x) {
3327   int bci = x->bci_of_invoke();
3328   ciMethodData* md = x->method()->method_data_or_null();
3329   assert(md != NULL, "Sanity");
3330   ciProfileData* data = md->bci_to_data(bci);
3331   if (data != NULL) {
3332     assert(data->is_CallTypeData() || data->is_VirtualCallTypeData(), "wrong profile data type");
3333     ciReturnTypeEntry* ret = data->is_CallTypeData() ? ((ciCallTypeData*)data)->ret() : ((ciVirtualCallTypeData*)data)->ret();
3334     LIR_Opr mdp = LIR_OprFact::illegalOpr;
3335 
3336     bool ignored_will_link;
3337     ciSignature* signature_at_call = NULL;
3338     x->method()->get_method_at_bci(bci, ignored_will_link, &signature_at_call);
3339 
3340     // The offset within the MDO of the entry to update may be too large
3341     // to be used in load/store instructions on some platforms. So have
3342     // profile_type() compute the address of the profile in a register.
3343     ciKlass* exact = profile_type(md, md->byte_offset_of_slot(data, ret->type_offset()), 0,
3344         ret->type(), x->ret(), mdp,
3345         !x->needs_null_check(),
3346         signature_at_call->return_type()->as_klass(),
3347         x->callee()->signature()->return_type()->as_klass());
3348     if (exact != NULL) {
3349       md->set_return_type(bci, exact);
3350     }
3351   }
3352 }
3353 
3354 void LIRGenerator::do_ProfileInvoke(ProfileInvoke* x) {
3355   // We can safely ignore accessors here, since c2 will inline them anyway,
3356   // accessors are also always mature.
3357   if (!x->inlinee()->is_accessor()) {
3358     CodeEmitInfo* info = state_for(x, x->state(), true);
3359     // Notify the runtime very infrequently only to take care of counter overflows
3360     int freq_log = Tier23InlineeNotifyFreqLog;
3361     double scale;
3362     if (_method->has_option_value(CompileCommand::CompileThresholdScaling, scale)) {
3363       freq_log = CompilerConfig::scaled_freq_log(freq_log, scale);
3364     }
3365     increment_event_counter_impl(info, x->inlinee(), LIR_OprFact::intConst(InvocationCounter::count_increment), right_n_bits(freq_log), InvocationEntryBci, false, true);
3366   }
3367 }
3368 
3369 void LIRGenerator::increment_backedge_counter_conditionally(LIR_Condition cond, LIR_Opr left, LIR_Opr right, CodeEmitInfo* info, int left_bci, int right_bci, int bci) {
3370   if (compilation()->count_backedges()) {
3371 #if defined(X86) && !defined(_LP64)
3372     // BEWARE! On 32-bit x86 cmp clobbers its left argument so we need a temp copy.
3373     LIR_Opr left_copy = new_register(left->type());
3374     __ move(left, left_copy);
3375     __ cmp(cond, left_copy, right);
3376 #else
3377     __ cmp(cond, left, right);
3378 #endif
3379     LIR_Opr step = new_register(T_INT);
3380     LIR_Opr plus_one = LIR_OprFact::intConst(InvocationCounter::count_increment);
3381     LIR_Opr zero = LIR_OprFact::intConst(0);
3382     __ cmove(cond,
3383         (left_bci < bci) ? plus_one : zero,
3384         (right_bci < bci) ? plus_one : zero,
3385         step, left->type());
3386     increment_backedge_counter(info, step, bci);
3387   }
3388 }
3389 
3390 
3391 void LIRGenerator::increment_event_counter(CodeEmitInfo* info, LIR_Opr step, int bci, bool backedge) {
3392   int freq_log = 0;
3393   int level = compilation()->env()->comp_level();
3394   if (level == CompLevel_limited_profile) {
3395     freq_log = (backedge ? Tier2BackedgeNotifyFreqLog : Tier2InvokeNotifyFreqLog);
3396   } else if (level == CompLevel_full_profile) {
3397     freq_log = (backedge ? Tier3BackedgeNotifyFreqLog : Tier3InvokeNotifyFreqLog);
3398   } else {
3399     ShouldNotReachHere();
3400   }
3401   // Increment the appropriate invocation/backedge counter and notify the runtime.
3402   double scale;
3403   if (_method->has_option_value(CompileCommand::CompileThresholdScaling, scale)) {
3404     freq_log = CompilerConfig::scaled_freq_log(freq_log, scale);
3405   }
3406   increment_event_counter_impl(info, info->scope()->method(), step, right_n_bits(freq_log), bci, backedge, true);
3407 }
3408 
3409 void LIRGenerator::decrement_age(CodeEmitInfo* info) {
3410   ciMethod* method = info->scope()->method();
3411   MethodCounters* mc_adr = method->ensure_method_counters();
3412   if (mc_adr != NULL) {
3413     LIR_Opr mc = new_pointer_register();
3414     __ move(LIR_OprFact::intptrConst(mc_adr), mc);
3415     int offset = in_bytes(MethodCounters::nmethod_age_offset());
3416     LIR_Address* counter = new LIR_Address(mc, offset, T_INT);
3417     LIR_Opr result = new_register(T_INT);
3418     __ load(counter, result);
3419     __ sub(result, LIR_OprFact::intConst(1), result);
3420     __ store(result, counter);
3421     // DeoptimizeStub will reexecute from the current state in code info.
3422     CodeStub* deopt = new DeoptimizeStub(info, Deoptimization::Reason_tenured,
3423                                          Deoptimization::Action_make_not_entrant);
3424     __ cmp(lir_cond_lessEqual, result, LIR_OprFact::intConst(0));
3425     __ branch(lir_cond_lessEqual, deopt);
3426   }
3427 }
3428 
3429 
3430 void LIRGenerator::increment_event_counter_impl(CodeEmitInfo* info,
3431                                                 ciMethod *method, LIR_Opr step, int frequency,
3432                                                 int bci, bool backedge, bool notify) {
3433   assert(frequency == 0 || is_power_of_2(frequency + 1), "Frequency must be x^2 - 1 or 0");
3434   int level = _compilation->env()->comp_level();
3435   assert(level > CompLevel_simple, "Shouldn't be here");
3436 
3437   int offset = -1;
3438   LIR_Opr counter_holder = NULL;
3439   if (level == CompLevel_limited_profile) {
3440     MethodCounters* counters_adr = method->ensure_method_counters();
3441     if (counters_adr == NULL) {
3442       bailout("method counters allocation failed");
3443       return;
3444     }
3445     counter_holder = new_pointer_register();
3446     __ move(LIR_OprFact::intptrConst(counters_adr), counter_holder);
3447     offset = in_bytes(backedge ? MethodCounters::backedge_counter_offset() :
3448                                  MethodCounters::invocation_counter_offset());
3449   } else if (level == CompLevel_full_profile) {
3450     counter_holder = new_register(T_METADATA);
3451     offset = in_bytes(backedge ? MethodData::backedge_counter_offset() :
3452                                  MethodData::invocation_counter_offset());
3453     ciMethodData* md = method->method_data_or_null();
3454     assert(md != NULL, "Sanity");
3455     __ metadata2reg(md->constant_encoding(), counter_holder);
3456   } else {
3457     ShouldNotReachHere();
3458   }
3459   LIR_Address* counter = new LIR_Address(counter_holder, offset, T_INT);
3460   LIR_Opr result = new_register(T_INT);
3461   __ load(counter, result);
3462   __ add(result, step, result);
3463   __ store(result, counter);
3464   if (notify && (!backedge || UseOnStackReplacement)) {
3465     LIR_Opr meth = LIR_OprFact::metadataConst(method->constant_encoding());
3466     // The bci for info can point to cmp for if's we want the if bci
3467     CodeStub* overflow = new CounterOverflowStub(info, bci, meth);
3468     int freq = frequency << InvocationCounter::count_shift;
3469     if (freq == 0) {
3470       if (!step->is_constant()) {
3471         __ cmp(lir_cond_notEqual, step, LIR_OprFact::intConst(0));
3472         __ branch(lir_cond_notEqual, overflow);
3473       } else {
3474         __ branch(lir_cond_always, overflow);
3475       }
3476     } else {
3477       LIR_Opr mask = load_immediate(freq, T_INT);
3478       if (!step->is_constant()) {
3479         // If step is 0, make sure the overflow check below always fails
3480         __ cmp(lir_cond_notEqual, step, LIR_OprFact::intConst(0));
3481         __ cmove(lir_cond_notEqual, result, LIR_OprFact::intConst(InvocationCounter::count_increment), result, T_INT);
3482       }
3483       __ logical_and(result, mask, result);
3484       __ cmp(lir_cond_equal, result, LIR_OprFact::intConst(0));
3485       __ branch(lir_cond_equal, overflow);
3486     }
3487     __ branch_destination(overflow->continuation());
3488   }
3489 }
3490 
3491 void LIRGenerator::do_RuntimeCall(RuntimeCall* x) {
3492   LIR_OprList* args = new LIR_OprList(x->number_of_arguments());
3493   BasicTypeList* signature = new BasicTypeList(x->number_of_arguments());
3494 
3495   if (x->pass_thread()) {
3496     signature->append(LP64_ONLY(T_LONG) NOT_LP64(T_INT));    // thread
3497     args->append(getThreadPointer());
3498   }
3499 
3500   for (int i = 0; i < x->number_of_arguments(); i++) {
3501     Value a = x->argument_at(i);
3502     LIRItem* item = new LIRItem(a, this);
3503     item->load_item();
3504     args->append(item->result());
3505     signature->append(as_BasicType(a->type()));
3506   }
3507 
3508   LIR_Opr result = call_runtime(signature, args, x->entry(), x->type(), NULL);
3509   if (x->type() == voidType) {
3510     set_no_result(x);
3511   } else {
3512     __ move(result, rlock_result(x));
3513   }
3514 }
3515 
3516 #ifdef ASSERT
3517 void LIRGenerator::do_Assert(Assert *x) {
3518   ValueTag tag = x->x()->type()->tag();
3519   If::Condition cond = x->cond();
3520 
3521   LIRItem xitem(x->x(), this);
3522   LIRItem yitem(x->y(), this);
3523   LIRItem* xin = &xitem;
3524   LIRItem* yin = &yitem;
3525 
3526   assert(tag == intTag, "Only integer assertions are valid!");
3527 
3528   xin->load_item();
3529   yin->dont_load_item();
3530 
3531   set_no_result(x);
3532 
3533   LIR_Opr left = xin->result();
3534   LIR_Opr right = yin->result();
3535 
3536   __ lir_assert(lir_cond(x->cond()), left, right, x->message(), true);
3537 }
3538 #endif
3539 
3540 void LIRGenerator::do_RangeCheckPredicate(RangeCheckPredicate *x) {
3541 
3542 
3543   Instruction *a = x->x();
3544   Instruction *b = x->y();
3545   if (!a || StressRangeCheckElimination) {
3546     assert(!b || StressRangeCheckElimination, "B must also be null");
3547 
3548     CodeEmitInfo *info = state_for(x, x->state());
3549     CodeStub* stub = new PredicateFailedStub(info);
3550 
3551     __ jump(stub);
3552   } else if (a->type()->as_IntConstant() && b->type()->as_IntConstant()) {
3553     int a_int = a->type()->as_IntConstant()->value();
3554     int b_int = b->type()->as_IntConstant()->value();
3555 
3556     bool ok = false;
3557 
3558     switch(x->cond()) {
3559       case Instruction::eql: ok = (a_int == b_int); break;
3560       case Instruction::neq: ok = (a_int != b_int); break;
3561       case Instruction::lss: ok = (a_int < b_int); break;
3562       case Instruction::leq: ok = (a_int <= b_int); break;
3563       case Instruction::gtr: ok = (a_int > b_int); break;
3564       case Instruction::geq: ok = (a_int >= b_int); break;
3565       case Instruction::aeq: ok = ((unsigned int)a_int >= (unsigned int)b_int); break;
3566       case Instruction::beq: ok = ((unsigned int)a_int <= (unsigned int)b_int); break;
3567       default: ShouldNotReachHere();
3568     }
3569 
3570     if (ok) {
3571 
3572       CodeEmitInfo *info = state_for(x, x->state());
3573       CodeStub* stub = new PredicateFailedStub(info);
3574 
3575       __ jump(stub);
3576     }
3577   } else {
3578 
3579     ValueTag tag = x->x()->type()->tag();
3580     If::Condition cond = x->cond();
3581     LIRItem xitem(x->x(), this);
3582     LIRItem yitem(x->y(), this);
3583     LIRItem* xin = &xitem;
3584     LIRItem* yin = &yitem;
3585 
3586     assert(tag == intTag, "Only integer deoptimizations are valid!");
3587 
3588     xin->load_item();
3589     yin->dont_load_item();
3590     set_no_result(x);
3591 
3592     LIR_Opr left = xin->result();
3593     LIR_Opr right = yin->result();
3594 
3595     CodeEmitInfo *info = state_for(x, x->state());
3596     CodeStub* stub = new PredicateFailedStub(info);
3597 
3598     __ cmp(lir_cond(cond), left, right);
3599     __ branch(lir_cond(cond), stub);
3600   }
3601 }
3602 
3603 void LIRGenerator::do_blackhole(Intrinsic *x) {
3604   assert(!x->has_receiver(), "Should have been checked before: only static methods here");
3605   for (int c = 0; c < x->number_of_arguments(); c++) {
3606     // Load the argument
3607     LIRItem vitem(x->argument_at(c), this);
3608     vitem.load_item();
3609     // ...and leave it unused.
3610   }
3611 }
3612 
3613 LIR_Opr LIRGenerator::call_runtime(Value arg1, address entry, ValueType* result_type, CodeEmitInfo* info) {
3614   LIRItemList args(1);
3615   LIRItem value(arg1, this);
3616   args.append(&value);
3617   BasicTypeList signature;
3618   signature.append(as_BasicType(arg1->type()));
3619 
3620   return call_runtime(&signature, &args, entry, result_type, info);
3621 }
3622 
3623 
3624 LIR_Opr LIRGenerator::call_runtime(Value arg1, Value arg2, address entry, ValueType* result_type, CodeEmitInfo* info) {
3625   LIRItemList args(2);
3626   LIRItem value1(arg1, this);
3627   LIRItem value2(arg2, this);
3628   args.append(&value1);
3629   args.append(&value2);
3630   BasicTypeList signature;
3631   signature.append(as_BasicType(arg1->type()));
3632   signature.append(as_BasicType(arg2->type()));
3633 
3634   return call_runtime(&signature, &args, entry, result_type, info);
3635 }
3636 
3637 
3638 LIR_Opr LIRGenerator::call_runtime(BasicTypeArray* signature, LIR_OprList* args,
3639                                    address entry, ValueType* result_type, CodeEmitInfo* info) {
3640   // get a result register
3641   LIR_Opr phys_reg = LIR_OprFact::illegalOpr;
3642   LIR_Opr result = LIR_OprFact::illegalOpr;
3643   if (result_type->tag() != voidTag) {
3644     result = new_register(result_type);
3645     phys_reg = result_register_for(result_type);
3646   }
3647 
3648   // move the arguments into the correct location
3649   CallingConvention* cc = frame_map()->c_calling_convention(signature);
3650   assert(cc->length() == args->length(), "argument mismatch");
3651   for (int i = 0; i < args->length(); i++) {
3652     LIR_Opr arg = args->at(i);
3653     LIR_Opr loc = cc->at(i);
3654     if (loc->is_register()) {
3655       __ move(arg, loc);
3656     } else {
3657       LIR_Address* addr = loc->as_address_ptr();
3658 //           if (!can_store_as_constant(arg)) {
3659 //             LIR_Opr tmp = new_register(arg->type());
3660 //             __ move(arg, tmp);
3661 //             arg = tmp;
3662 //           }
3663       if (addr->type() == T_LONG || addr->type() == T_DOUBLE) {
3664         __ unaligned_move(arg, addr);
3665       } else {
3666         __ move(arg, addr);
3667       }
3668     }
3669   }
3670 
3671   if (info) {
3672     __ call_runtime(entry, getThreadTemp(), phys_reg, cc->args(), info);
3673   } else {
3674     __ call_runtime_leaf(entry, getThreadTemp(), phys_reg, cc->args());
3675   }
3676   if (result->is_valid()) {
3677     __ move(phys_reg, result);
3678   }
3679   return result;
3680 }
3681 
3682 
3683 LIR_Opr LIRGenerator::call_runtime(BasicTypeArray* signature, LIRItemList* args,
3684                                    address entry, ValueType* result_type, CodeEmitInfo* info) {
3685   // get a result register
3686   LIR_Opr phys_reg = LIR_OprFact::illegalOpr;
3687   LIR_Opr result = LIR_OprFact::illegalOpr;
3688   if (result_type->tag() != voidTag) {
3689     result = new_register(result_type);
3690     phys_reg = result_register_for(result_type);
3691   }
3692 
3693   // move the arguments into the correct location
3694   CallingConvention* cc = frame_map()->c_calling_convention(signature);
3695 
3696   assert(cc->length() == args->length(), "argument mismatch");
3697   for (int i = 0; i < args->length(); i++) {
3698     LIRItem* arg = args->at(i);
3699     LIR_Opr loc = cc->at(i);
3700     if (loc->is_register()) {
3701       arg->load_item_force(loc);
3702     } else {
3703       LIR_Address* addr = loc->as_address_ptr();
3704       arg->load_for_store(addr->type());
3705       if (addr->type() == T_LONG || addr->type() == T_DOUBLE) {
3706         __ unaligned_move(arg->result(), addr);
3707       } else {
3708         __ move(arg->result(), addr);
3709       }
3710     }
3711   }
3712 
3713   if (info) {
3714     __ call_runtime(entry, getThreadTemp(), phys_reg, cc->args(), info);
3715   } else {
3716     __ call_runtime_leaf(entry, getThreadTemp(), phys_reg, cc->args());
3717   }
3718   if (result->is_valid()) {
3719     __ move(phys_reg, result);
3720   }
3721   return result;
3722 }
3723 
3724 void LIRGenerator::do_MemBar(MemBar* x) {
3725   LIR_Code code = x->code();
3726   switch(code) {
3727   case lir_membar_acquire   : __ membar_acquire(); break;
3728   case lir_membar_release   : __ membar_release(); break;
3729   case lir_membar           : __ membar(); break;
3730   case lir_membar_loadload  : __ membar_loadload(); break;
3731   case lir_membar_storestore: __ membar_storestore(); break;
3732   case lir_membar_loadstore : __ membar_loadstore(); break;
3733   case lir_membar_storeload : __ membar_storeload(); break;
3734   default                   : ShouldNotReachHere(); break;
3735   }
3736 }
3737 
3738 LIR_Opr LIRGenerator::mask_boolean(LIR_Opr array, LIR_Opr value, CodeEmitInfo*& null_check_info) {
3739   LIR_Opr value_fixed = rlock_byte(T_BYTE);
3740   if (TwoOperandLIRForm) {
3741     __ move(value, value_fixed);
3742     __ logical_and(value_fixed, LIR_OprFact::intConst(1), value_fixed);
3743   } else {
3744     __ logical_and(value, LIR_OprFact::intConst(1), value_fixed);
3745   }
3746   LIR_Opr klass = new_register(T_METADATA);
3747   __ move(new LIR_Address(array, oopDesc::klass_offset_in_bytes(), T_ADDRESS), klass, null_check_info);
3748   null_check_info = NULL;
3749   LIR_Opr layout = new_register(T_INT);
3750   __ move(new LIR_Address(klass, in_bytes(Klass::layout_helper_offset()), T_INT), layout);
3751   int diffbit = Klass::layout_helper_boolean_diffbit();
3752   __ logical_and(layout, LIR_OprFact::intConst(diffbit), layout);
3753   __ cmp(lir_cond_notEqual, layout, LIR_OprFact::intConst(0));
3754   __ cmove(lir_cond_notEqual, value_fixed, value, value_fixed, T_BYTE);
3755   value = value_fixed;
3756   return value;
3757 }
3758 
3759 LIR_Opr LIRGenerator::maybe_mask_boolean(StoreIndexed* x, LIR_Opr array, LIR_Opr value, CodeEmitInfo*& null_check_info) {
3760   if (x->check_boolean()) {
3761     value = mask_boolean(array, value, null_check_info);
3762   }
3763   return value;
3764 }
--- EOF ---