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/ciFlatArrayKlass.hpp"
  35 #include "ci/ciInlineKlass.hpp"
  36 #include "ci/ciInstance.hpp"
  37 #include "ci/ciObjArray.hpp"
  38 #include "ci/ciUtilities.hpp"
  39 #include "gc/shared/barrierSet.hpp"
  40 #include "gc/shared/c1/barrierSetC1.hpp"
  41 #include "oops/klass.inline.hpp"
  42 #include "runtime/sharedRuntime.hpp"
  43 #include "runtime/stubRoutines.hpp"
  44 #include "runtime/vm_version.hpp"
  45 #include "utilities/bitMap.inline.hpp"
  46 #include "utilities/macros.hpp"
  47 #include "utilities/powerOfTwo.hpp"
  48 
  49 #ifdef ASSERT
  50 #define __ gen()->lir(__FILE__, __LINE__)->
  51 #else
  52 #define __ gen()->lir()->
  53 #endif
  54 
  55 #ifndef PATCHED_ADDR
  56 #define PATCHED_ADDR  (max_jint)
  57 #endif
  58 
  59 void PhiResolverState::reset() {
  60   _virtual_operands.clear();
  61   _other_operands.clear();
  62   _vreg_table.clear();
  63 }
  64 
  65 
  66 //--------------------------------------------------------------
  67 // PhiResolver
  68 
  69 // Resolves cycles:
  70 //
  71 //  r1 := r2  becomes  temp := r1
  72 //  r2 := r1           r1 := r2
  73 //                     r2 := temp
  74 // and orders moves:
  75 //
  76 //  r2 := r3  becomes  r1 := r2
  77 //  r1 := r2           r2 := r3
  78 
  79 PhiResolver::PhiResolver(LIRGenerator* gen)
  80  : _gen(gen)
  81  , _state(gen->resolver_state())
  82  , _temp(LIR_OprFact::illegalOpr)
  83 {
  84   // reinitialize the shared state arrays
  85   _state.reset();
  86 }
  87 
  88 
  89 void PhiResolver::emit_move(LIR_Opr src, LIR_Opr dest) {
  90   assert(src->is_valid(), "");
  91   assert(dest->is_valid(), "");
  92   __ move(src, dest);
  93 }
  94 
  95 
  96 void PhiResolver::move_temp_to(LIR_Opr dest) {
  97   assert(_temp->is_valid(), "");
  98   emit_move(_temp, dest);
  99   NOT_PRODUCT(_temp = LIR_OprFact::illegalOpr);
 100 }
 101 
 102 
 103 void PhiResolver::move_to_temp(LIR_Opr src) {
 104   assert(_temp->is_illegal(), "");
 105   _temp = _gen->new_register(src->type());
 106   emit_move(src, _temp);
 107 }
 108 
 109 
 110 // Traverse assignment graph in depth first order and generate moves in post order
 111 // ie. two assignments: b := c, a := b start with node c:
 112 // Call graph: move(NULL, c) -> move(c, b) -> move(b, a)
 113 // Generates moves in this order: move b to a and move c to b
 114 // ie. cycle a := b, b := a start with node a
 115 // Call graph: move(NULL, a) -> move(a, b) -> move(b, a)
 116 // Generates moves in this order: move b to temp, move a to b, move temp to a
 117 void PhiResolver::move(ResolveNode* src, ResolveNode* dest) {
 118   if (!dest->visited()) {
 119     dest->set_visited();
 120     for (int i = dest->no_of_destinations()-1; i >= 0; i --) {
 121       move(dest, dest->destination_at(i));
 122     }
 123   } else if (!dest->start_node()) {
 124     // cylce in graph detected
 125     assert(_loop == NULL, "only one loop valid!");
 126     _loop = dest;
 127     move_to_temp(src->operand());
 128     return;
 129   } // else dest is a start node
 130 
 131   if (!dest->assigned()) {
 132     if (_loop == dest) {
 133       move_temp_to(dest->operand());
 134       dest->set_assigned();
 135     } else if (src != NULL) {
 136       emit_move(src->operand(), dest->operand());
 137       dest->set_assigned();
 138     }
 139   }
 140 }
 141 
 142 
 143 PhiResolver::~PhiResolver() {
 144   int i;
 145   // resolve any cycles in moves from and to virtual registers
 146   for (i = virtual_operands().length() - 1; i >= 0; i --) {
 147     ResolveNode* node = virtual_operands().at(i);
 148     if (!node->visited()) {
 149       _loop = NULL;
 150       move(NULL, node);
 151       node->set_start_node();
 152       assert(_temp->is_illegal(), "move_temp_to() call missing");
 153     }
 154   }
 155 
 156   // generate move for move from non virtual register to abitrary destination
 157   for (i = other_operands().length() - 1; i >= 0; i --) {
 158     ResolveNode* node = other_operands().at(i);
 159     for (int j = node->no_of_destinations() - 1; j >= 0; j --) {
 160       emit_move(node->operand(), node->destination_at(j)->operand());
 161     }
 162   }
 163 }
 164 
 165 
 166 ResolveNode* PhiResolver::create_node(LIR_Opr opr, bool source) {
 167   ResolveNode* node;
 168   if (opr->is_virtual()) {
 169     int vreg_num = opr->vreg_number();
 170     node = vreg_table().at_grow(vreg_num, NULL);
 171     assert(node == NULL || node->operand() == opr, "");
 172     if (node == NULL) {
 173       node = new ResolveNode(opr);
 174       vreg_table().at_put(vreg_num, node);
 175     }
 176     // Make sure that all virtual operands show up in the list when
 177     // they are used as the source of a move.
 178     if (source && !virtual_operands().contains(node)) {
 179       virtual_operands().append(node);
 180     }
 181   } else {
 182     assert(source, "");
 183     node = new ResolveNode(opr);
 184     other_operands().append(node);
 185   }
 186   return node;
 187 }
 188 
 189 
 190 void PhiResolver::move(LIR_Opr src, LIR_Opr dest) {
 191   assert(dest->is_virtual(), "");
 192   // tty->print("move "); src->print(); tty->print(" to "); dest->print(); tty->cr();
 193   assert(src->is_valid(), "");
 194   assert(dest->is_valid(), "");
 195   ResolveNode* source = source_node(src);
 196   source->append(destination_node(dest));
 197 }
 198 
 199 
 200 //--------------------------------------------------------------
 201 // LIRItem
 202 
 203 void LIRItem::set_result(LIR_Opr opr) {
 204   assert(value()->operand()->is_illegal() || value()->operand()->is_constant(), "operand should never change");
 205   value()->set_operand(opr);
 206 
 207   if (opr->is_virtual()) {
 208     _gen->_instruction_for_operand.at_put_grow(opr->vreg_number(), value(), NULL);
 209   }
 210 
 211   _result = opr;
 212 }
 213 
 214 void LIRItem::load_item() {
 215   assert(!_gen->in_conditional_code(), "LIRItem cannot be loaded in conditional code");
 216 
 217   if (result()->is_illegal()) {
 218     // update the items result
 219     _result = value()->operand();
 220   }
 221   if (!result()->is_register()) {
 222     LIR_Opr reg = _gen->new_register(value()->type());
 223     __ move(result(), reg);
 224     if (result()->is_constant()) {
 225       _result = reg;
 226     } else {
 227       set_result(reg);
 228     }
 229   }
 230 }
 231 
 232 
 233 void LIRItem::load_for_store(BasicType type) {
 234   if (_gen->can_store_as_constant(value(), type)) {
 235     _result = value()->operand();
 236     if (!_result->is_constant()) {
 237       _result = LIR_OprFact::value_type(value()->type());
 238     }
 239   } else if (type == T_BYTE || type == T_BOOLEAN) {
 240     load_byte_item();
 241   } else {
 242     load_item();
 243   }
 244 }
 245 
 246 void LIRItem::load_item_force(LIR_Opr reg) {
 247   LIR_Opr r = result();
 248   if (r != reg) {
 249 #if !defined(ARM) && !defined(E500V2)
 250     if (r->type() != reg->type()) {
 251       // moves between different types need an intervening spill slot
 252       r = _gen->force_to_spill(r, reg->type());
 253     }
 254 #endif
 255     __ move(r, reg);
 256     _result = reg;
 257   }
 258 }
 259 
 260 ciObject* LIRItem::get_jobject_constant() const {
 261   ObjectType* oc = type()->as_ObjectType();
 262   if (oc) {
 263     return oc->constant_value();
 264   }
 265   return NULL;
 266 }
 267 
 268 
 269 jint LIRItem::get_jint_constant() const {
 270   assert(is_constant() && value() != NULL, "");
 271   assert(type()->as_IntConstant() != NULL, "type check");
 272   return type()->as_IntConstant()->value();
 273 }
 274 
 275 
 276 jint LIRItem::get_address_constant() const {
 277   assert(is_constant() && value() != NULL, "");
 278   assert(type()->as_AddressConstant() != NULL, "type check");
 279   return type()->as_AddressConstant()->value();
 280 }
 281 
 282 
 283 jfloat LIRItem::get_jfloat_constant() const {
 284   assert(is_constant() && value() != NULL, "");
 285   assert(type()->as_FloatConstant() != NULL, "type check");
 286   return type()->as_FloatConstant()->value();
 287 }
 288 
 289 
 290 jdouble LIRItem::get_jdouble_constant() const {
 291   assert(is_constant() && value() != NULL, "");
 292   assert(type()->as_DoubleConstant() != NULL, "type check");
 293   return type()->as_DoubleConstant()->value();
 294 }
 295 
 296 
 297 jlong LIRItem::get_jlong_constant() const {
 298   assert(is_constant() && value() != NULL, "");
 299   assert(type()->as_LongConstant() != NULL, "type check");
 300   return type()->as_LongConstant()->value();
 301 }
 302 
 303 
 304 
 305 //--------------------------------------------------------------
 306 
 307 
 308 void LIRGenerator::block_do_prolog(BlockBegin* block) {
 309 #ifndef PRODUCT
 310   if (PrintIRWithLIR) {
 311     block->print();
 312   }
 313 #endif
 314 
 315   // set up the list of LIR instructions
 316   assert(block->lir() == NULL, "LIR list already computed for this block");
 317   _lir = new LIR_List(compilation(), block);
 318   block->set_lir(_lir);
 319 
 320   __ branch_destination(block->label());
 321 
 322   if (LIRTraceExecution &&
 323       Compilation::current()->hir()->start()->block_id() != block->block_id() &&
 324       !block->is_set(BlockBegin::exception_entry_flag)) {
 325     assert(block->lir()->instructions_list()->length() == 1, "should come right after br_dst");
 326     trace_block_entry(block);
 327   }
 328 }
 329 
 330 
 331 void LIRGenerator::block_do_epilog(BlockBegin* block) {
 332 #ifndef PRODUCT
 333   if (PrintIRWithLIR) {
 334     tty->cr();
 335   }
 336 #endif
 337 
 338   // LIR_Opr for unpinned constants shouldn't be referenced by other
 339   // blocks so clear them out after processing the block.
 340   for (int i = 0; i < _unpinned_constants.length(); i++) {
 341     _unpinned_constants.at(i)->clear_operand();
 342   }
 343   _unpinned_constants.trunc_to(0);
 344 
 345   // clear our any registers for other local constants
 346   _constants.trunc_to(0);
 347   _reg_for_constants.trunc_to(0);
 348 }
 349 
 350 
 351 void LIRGenerator::block_do(BlockBegin* block) {
 352   CHECK_BAILOUT();
 353 
 354   block_do_prolog(block);
 355   set_block(block);
 356 
 357   for (Instruction* instr = block; instr != NULL; instr = instr->next()) {
 358     if (instr->is_pinned()) do_root(instr);
 359   }
 360 
 361   set_block(NULL);
 362   block_do_epilog(block);
 363 }
 364 
 365 
 366 //-------------------------LIRGenerator-----------------------------
 367 
 368 // This is where the tree-walk starts; instr must be root;
 369 void LIRGenerator::do_root(Value instr) {
 370   CHECK_BAILOUT();
 371 
 372   InstructionMark im(compilation(), instr);
 373 
 374   assert(instr->is_pinned(), "use only with roots");
 375   assert(instr->subst() == instr, "shouldn't have missed substitution");
 376 
 377   instr->visit(this);
 378 
 379   assert(!instr->has_uses() || instr->operand()->is_valid() ||
 380          instr->as_Constant() != NULL || bailed_out(), "invalid item set");
 381 }
 382 
 383 
 384 // This is called for each node in tree; the walk stops if a root is reached
 385 void LIRGenerator::walk(Value instr) {
 386   InstructionMark im(compilation(), instr);
 387   //stop walk when encounter a root
 388   if ((instr->is_pinned() && instr->as_Phi() == NULL) || instr->operand()->is_valid()) {
 389     assert(instr->operand() != LIR_OprFact::illegalOpr || instr->as_Constant() != NULL, "this root has not yet been visited");
 390   } else {
 391     assert(instr->subst() == instr, "shouldn't have missed substitution");
 392     instr->visit(this);
 393     // assert(instr->use_count() > 0 || instr->as_Phi() != NULL, "leaf instruction must have a use");
 394   }
 395 }
 396 
 397 
 398 CodeEmitInfo* LIRGenerator::state_for(Instruction* x, ValueStack* state, bool ignore_xhandler) {
 399   assert(state != NULL, "state must be defined");
 400 
 401 #ifndef PRODUCT
 402   state->verify();
 403 #endif
 404 
 405   ValueStack* s = state;
 406   for_each_state(s) {
 407     if (s->kind() == ValueStack::EmptyExceptionState) {
 408       assert(s->stack_size() == 0 && s->locals_size() == 0 && (s->locks_size() == 0 || s->locks_size() == 1), "state must be empty");
 409       continue;
 410     }
 411 
 412     int index;
 413     Value value;
 414     for_each_stack_value(s, index, value) {
 415       assert(value->subst() == value, "missed substitution");
 416       if (!value->is_pinned() && value->as_Constant() == NULL && value->as_Local() == NULL) {
 417         walk(value);
 418         assert(value->operand()->is_valid(), "must be evaluated now");
 419       }
 420     }
 421 
 422     int bci = s->bci();
 423     IRScope* scope = s->scope();
 424     ciMethod* method = scope->method();
 425 
 426     MethodLivenessResult liveness = method->liveness_at_bci(bci);
 427     if (bci == SynchronizationEntryBCI) {
 428       if (x->as_ExceptionObject() || x->as_Throw()) {
 429         // all locals are dead on exit from the synthetic unlocker
 430         liveness.clear();
 431       } else {
 432         assert(x->as_MonitorEnter() || x->as_ProfileInvoke(), "only other cases are MonitorEnter and ProfileInvoke");
 433       }
 434     }
 435     if (!liveness.is_valid()) {
 436       // Degenerate or breakpointed method.
 437       bailout("Degenerate or breakpointed method");
 438     } else {
 439       assert((int)liveness.size() == s->locals_size(), "error in use of liveness");
 440       for_each_local_value(s, index, value) {
 441         assert(value->subst() == value, "missed substition");
 442         if (liveness.at(index) && !value->type()->is_illegal()) {
 443           if (!value->is_pinned() && value->as_Constant() == NULL && value->as_Local() == NULL) {
 444             walk(value);
 445             assert(value->operand()->is_valid(), "must be evaluated now");
 446           }
 447         } else {
 448           // NULL out this local so that linear scan can assume that all non-NULL values are live.
 449           s->invalidate_local(index);
 450         }
 451       }
 452     }
 453   }
 454 
 455   return new CodeEmitInfo(state, ignore_xhandler ? NULL : x->exception_handlers(), x->check_flag(Instruction::DeoptimizeOnException));
 456 }
 457 
 458 
 459 CodeEmitInfo* LIRGenerator::state_for(Instruction* x) {
 460   return state_for(x, x->exception_state());
 461 }
 462 
 463 
 464 void LIRGenerator::klass2reg_with_patching(LIR_Opr r, ciMetadata* obj, CodeEmitInfo* info, bool need_resolve) {
 465   /* C2 relies on constant pool entries being resolved (ciTypeFlow), so if tiered compilation
 466    * is active and the class hasn't yet been resolved we need to emit a patch that resolves
 467    * the class. */
 468   if ((!CompilerConfig::is_c1_only_no_jvmci() && need_resolve) || !obj->is_loaded() || PatchALot) {
 469     assert(info != NULL, "info must be set if class is not loaded");
 470     __ klass2reg_patch(NULL, r, info);
 471   } else {
 472     // no patching needed
 473     __ metadata2reg(obj->constant_encoding(), r);
 474   }
 475 }
 476 
 477 
 478 void LIRGenerator::array_range_check(LIR_Opr array, LIR_Opr index,
 479                                     CodeEmitInfo* null_check_info, CodeEmitInfo* range_check_info) {
 480   CodeStub* stub = new RangeCheckStub(range_check_info, index, array);
 481   if (index->is_constant()) {
 482     cmp_mem_int(lir_cond_belowEqual, array, arrayOopDesc::length_offset_in_bytes(),
 483                 index->as_jint(), null_check_info);
 484     __ branch(lir_cond_belowEqual, stub); // forward branch
 485   } else {
 486     cmp_reg_mem(lir_cond_aboveEqual, index, array,
 487                 arrayOopDesc::length_offset_in_bytes(), T_INT, null_check_info);
 488     __ branch(lir_cond_aboveEqual, stub); // forward branch
 489   }
 490 }
 491 
 492 void LIRGenerator::arithmetic_op(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, LIR_Opr tmp_op, CodeEmitInfo* info) {
 493   LIR_Opr result_op = result;
 494   LIR_Opr left_op   = left;
 495   LIR_Opr right_op  = right;
 496 
 497   if (TwoOperandLIRForm && left_op != result_op) {
 498     assert(right_op != result_op, "malformed");
 499     __ move(left_op, result_op);
 500     left_op = result_op;
 501   }
 502 
 503   switch(code) {
 504     case Bytecodes::_dadd:
 505     case Bytecodes::_fadd:
 506     case Bytecodes::_ladd:
 507     case Bytecodes::_iadd:  __ add(left_op, right_op, result_op); break;
 508     case Bytecodes::_fmul:
 509     case Bytecodes::_lmul:  __ mul(left_op, right_op, result_op); break;
 510 
 511     case Bytecodes::_dmul:  __ mul(left_op, right_op, result_op, tmp_op); break;
 512 
 513     case Bytecodes::_imul:
 514       {
 515         bool did_strength_reduce = false;
 516 
 517         if (right->is_constant()) {
 518           jint c = right->as_jint();
 519           if (c > 0 && is_power_of_2(c)) {
 520             // do not need tmp here
 521             __ shift_left(left_op, exact_log2(c), result_op);
 522             did_strength_reduce = true;
 523           } else {
 524             did_strength_reduce = strength_reduce_multiply(left_op, c, result_op, tmp_op);
 525           }
 526         }
 527         // we couldn't strength reduce so just emit the multiply
 528         if (!did_strength_reduce) {
 529           __ mul(left_op, right_op, result_op);
 530         }
 531       }
 532       break;
 533 
 534     case Bytecodes::_dsub:
 535     case Bytecodes::_fsub:
 536     case Bytecodes::_lsub:
 537     case Bytecodes::_isub: __ sub(left_op, right_op, result_op); break;
 538 
 539     case Bytecodes::_fdiv: __ div (left_op, right_op, result_op); break;
 540     // ldiv and lrem are implemented with a direct runtime call
 541 
 542     case Bytecodes::_ddiv: __ div(left_op, right_op, result_op, tmp_op); break;
 543 
 544     case Bytecodes::_drem:
 545     case Bytecodes::_frem: __ rem (left_op, right_op, result_op); break;
 546 
 547     default: ShouldNotReachHere();
 548   }
 549 }
 550 
 551 
 552 void LIRGenerator::arithmetic_op_int(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, LIR_Opr tmp) {
 553   arithmetic_op(code, result, left, right, tmp);
 554 }
 555 
 556 
 557 void LIRGenerator::arithmetic_op_long(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, CodeEmitInfo* info) {
 558   arithmetic_op(code, result, left, right, LIR_OprFact::illegalOpr, info);
 559 }
 560 
 561 
 562 void LIRGenerator::arithmetic_op_fpu(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, LIR_Opr tmp) {
 563   arithmetic_op(code, result, left, right, tmp);
 564 }
 565 
 566 
 567 void LIRGenerator::shift_op(Bytecodes::Code code, LIR_Opr result_op, LIR_Opr value, LIR_Opr count, LIR_Opr tmp) {
 568 
 569   if (TwoOperandLIRForm && value != result_op
 570       // Only 32bit right shifts require two operand form on S390.
 571       S390_ONLY(&& (code == Bytecodes::_ishr || code == Bytecodes::_iushr))) {
 572     assert(count != result_op, "malformed");
 573     __ move(value, result_op);
 574     value = result_op;
 575   }
 576 
 577   assert(count->is_constant() || count->is_register(), "must be");
 578   switch(code) {
 579   case Bytecodes::_ishl:
 580   case Bytecodes::_lshl: __ shift_left(value, count, result_op, tmp); break;
 581   case Bytecodes::_ishr:
 582   case Bytecodes::_lshr: __ shift_right(value, count, result_op, tmp); break;
 583   case Bytecodes::_iushr:
 584   case Bytecodes::_lushr: __ unsigned_shift_right(value, count, result_op, tmp); break;
 585   default: ShouldNotReachHere();
 586   }
 587 }
 588 
 589 
 590 void LIRGenerator::logic_op (Bytecodes::Code code, LIR_Opr result_op, LIR_Opr left_op, LIR_Opr right_op) {
 591   if (TwoOperandLIRForm && left_op != result_op) {
 592     assert(right_op != result_op, "malformed");
 593     __ move(left_op, result_op);
 594     left_op = result_op;
 595   }
 596 
 597   switch(code) {
 598     case Bytecodes::_iand:
 599     case Bytecodes::_land:  __ logical_and(left_op, right_op, result_op); break;
 600 
 601     case Bytecodes::_ior:
 602     case Bytecodes::_lor:   __ logical_or(left_op, right_op, result_op);  break;
 603 
 604     case Bytecodes::_ixor:
 605     case Bytecodes::_lxor:  __ logical_xor(left_op, right_op, result_op); break;
 606 
 607     default: ShouldNotReachHere();
 608   }
 609 }
 610 
 611 
 612 void LIRGenerator::monitor_enter(LIR_Opr object, LIR_Opr lock, LIR_Opr hdr, LIR_Opr scratch, int monitor_no,
 613                                  CodeEmitInfo* info_for_exception, CodeEmitInfo* info, CodeStub* throw_imse_stub) {
 614   if (!GenerateSynchronizationCode) return;
 615   // for slow path, use debug info for state after successful locking
 616   CodeStub* slow_path = new MonitorEnterStub(object, lock, info, throw_imse_stub, scratch);
 617   __ load_stack_address_monitor(monitor_no, lock);
 618   // for handling NullPointerException, use debug info representing just the lock stack before this monitorenter
 619   __ lock_object(hdr, object, lock, scratch, slow_path, info_for_exception, throw_imse_stub);
 620 }
 621 
 622 
 623 void LIRGenerator::monitor_exit(LIR_Opr object, LIR_Opr lock, LIR_Opr new_hdr, LIR_Opr scratch, int monitor_no) {
 624   if (!GenerateSynchronizationCode) return;
 625   // setup registers
 626   LIR_Opr hdr = lock;
 627   lock = new_hdr;
 628   CodeStub* slow_path = new MonitorExitStub(lock, !UseHeavyMonitors, monitor_no);
 629   __ load_stack_address_monitor(monitor_no, lock);
 630   __ unlock_object(hdr, object, lock, scratch, slow_path);
 631 }
 632 
 633 #ifndef PRODUCT
 634 void LIRGenerator::print_if_not_loaded(const NewInstance* new_instance) {
 635   if (PrintNotLoaded && !new_instance->klass()->is_loaded()) {
 636     tty->print_cr("   ###class not loaded at new bci %d", new_instance->printable_bci());
 637   } else if (PrintNotLoaded && (!CompilerConfig::is_c1_only_no_jvmci() && new_instance->is_unresolved())) {
 638     tty->print_cr("   ###class not resolved at new bci %d", new_instance->printable_bci());
 639   }
 640 }
 641 #endif
 642 
 643 void LIRGenerator::new_instance(LIR_Opr dst, ciInstanceKlass* klass, bool is_unresolved, bool allow_inline, LIR_Opr scratch1, LIR_Opr scratch2, LIR_Opr scratch3, LIR_Opr scratch4, LIR_Opr klass_reg, CodeEmitInfo* info) {
 644   if (allow_inline) {
 645     assert(!is_unresolved && klass->is_loaded(), "inline type klass should be resolved");
 646     __ metadata2reg(klass->constant_encoding(), klass_reg);
 647   } else {
 648     klass2reg_with_patching(klass_reg, klass, info, is_unresolved);
 649   }
 650   // If klass is not loaded we do not know if the klass has finalizers or is an unexpected inline klass
 651   if (UseFastNewInstance && klass->is_loaded() && (allow_inline || !klass->is_inlinetype())
 652       && !Klass::layout_helper_needs_slow_path(klass->layout_helper())) {
 653 
 654     Runtime1::StubID stub_id = klass->is_initialized() ? Runtime1::fast_new_instance_id : Runtime1::fast_new_instance_init_check_id;
 655 
 656     CodeStub* slow_path = new NewInstanceStub(klass_reg, dst, klass, info, stub_id);
 657 
 658     assert(klass->is_loaded(), "must be loaded");
 659     // allocate space for instance
 660     assert(klass->size_helper() > 0, "illegal instance size");
 661     const int instance_size = align_object_size(klass->size_helper());
 662     __ allocate_object(dst, scratch1, scratch2, scratch3, scratch4,
 663                        oopDesc::header_size(), instance_size, klass_reg, !klass->is_initialized(), slow_path);
 664   } else {
 665     CodeStub* slow_path = new NewInstanceStub(klass_reg, dst, klass, info, allow_inline ? Runtime1::new_instance_id : Runtime1::new_instance_no_inline_id);
 666     __ jump(slow_path);
 667     __ branch_destination(slow_path->continuation());
 668   }
 669 }
 670 
 671 
 672 static bool is_constant_zero(Instruction* inst) {
 673   IntConstant* c = inst->type()->as_IntConstant();
 674   if (c) {
 675     return (c->value() == 0);
 676   }
 677   return false;
 678 }
 679 
 680 
 681 static bool positive_constant(Instruction* inst) {
 682   IntConstant* c = inst->type()->as_IntConstant();
 683   if (c) {
 684     return (c->value() >= 0);
 685   }
 686   return false;
 687 }
 688 
 689 
 690 static ciArrayKlass* as_array_klass(ciType* type) {
 691   if (type != NULL && type->is_array_klass() && type->is_loaded()) {
 692     return (ciArrayKlass*)type;
 693   } else {
 694     return NULL;
 695   }
 696 }
 697 
 698 static ciType* phi_declared_type(Phi* phi) {
 699   ciType* t = phi->operand_at(0)->declared_type();
 700   if (t == NULL) {
 701     return NULL;
 702   }
 703   for(int i = 1; i < phi->operand_count(); i++) {
 704     if (t != phi->operand_at(i)->declared_type()) {
 705       return NULL;
 706     }
 707   }
 708   return t;
 709 }
 710 
 711 void LIRGenerator::arraycopy_helper(Intrinsic* x, int* flagsp, ciArrayKlass** expected_typep) {
 712   Instruction* src     = x->argument_at(0);
 713   Instruction* src_pos = x->argument_at(1);
 714   Instruction* dst     = x->argument_at(2);
 715   Instruction* dst_pos = x->argument_at(3);
 716   Instruction* length  = x->argument_at(4);
 717 
 718   // first try to identify the likely type of the arrays involved
 719   ciArrayKlass* expected_type = NULL;
 720   bool is_exact = false, src_objarray = false, dst_objarray = false;
 721   {
 722     ciArrayKlass* src_exact_type    = as_array_klass(src->exact_type());
 723     ciArrayKlass* src_declared_type = as_array_klass(src->declared_type());
 724     Phi* phi;
 725     if (src_declared_type == NULL && (phi = src->as_Phi()) != NULL) {
 726       src_declared_type = as_array_klass(phi_declared_type(phi));
 727     }
 728     ciArrayKlass* dst_exact_type    = as_array_klass(dst->exact_type());
 729     ciArrayKlass* dst_declared_type = as_array_klass(dst->declared_type());
 730     if (dst_declared_type == NULL && (phi = dst->as_Phi()) != NULL) {
 731       dst_declared_type = as_array_klass(phi_declared_type(phi));
 732     }
 733 
 734     if (src_exact_type != NULL && src_exact_type == dst_exact_type) {
 735       // the types exactly match so the type is fully known
 736       is_exact = true;
 737       expected_type = src_exact_type;
 738     } else if (dst_exact_type != NULL && dst_exact_type->is_obj_array_klass()) {
 739       ciArrayKlass* dst_type = (ciArrayKlass*) dst_exact_type;
 740       ciArrayKlass* src_type = NULL;
 741       if (src_exact_type != NULL && src_exact_type->is_obj_array_klass()) {
 742         src_type = (ciArrayKlass*) src_exact_type;
 743       } else if (src_declared_type != NULL && src_declared_type->is_obj_array_klass()) {
 744         src_type = (ciArrayKlass*) src_declared_type;
 745       }
 746       if (src_type != NULL) {
 747         if (src_type->element_type()->is_subtype_of(dst_type->element_type())) {
 748           is_exact = true;
 749           expected_type = dst_type;
 750         }
 751       }
 752     }
 753     // at least pass along a good guess
 754     if (expected_type == NULL) expected_type = dst_exact_type;
 755     if (expected_type == NULL) expected_type = src_declared_type;
 756     if (expected_type == NULL) expected_type = dst_declared_type;
 757 
 758     src_objarray = (src_exact_type && src_exact_type->is_obj_array_klass()) || (src_declared_type && src_declared_type->is_obj_array_klass());
 759     dst_objarray = (dst_exact_type && dst_exact_type->is_obj_array_klass()) || (dst_declared_type && dst_declared_type->is_obj_array_klass());
 760   }
 761 
 762   // if a probable array type has been identified, figure out if any
 763   // of the required checks for a fast case can be elided.
 764   int flags = LIR_OpArrayCopy::all_flags;
 765 
 766   if (!src->is_loaded_flattened_array() && !dst->is_loaded_flattened_array()) {
 767     flags &= ~LIR_OpArrayCopy::always_slow_path;
 768   }
 769   if (!src->maybe_flattened_array()) {
 770     flags &= ~LIR_OpArrayCopy::src_inlinetype_check;
 771   }
 772   if (!dst->maybe_flattened_array() && !dst->maybe_null_free_array()) {
 773     flags &= ~LIR_OpArrayCopy::dst_inlinetype_check;
 774   }
 775 
 776   if (!src_objarray)
 777     flags &= ~LIR_OpArrayCopy::src_objarray;
 778   if (!dst_objarray)
 779     flags &= ~LIR_OpArrayCopy::dst_objarray;
 780 
 781   if (!x->arg_needs_null_check(0))
 782     flags &= ~LIR_OpArrayCopy::src_null_check;
 783   if (!x->arg_needs_null_check(2))
 784     flags &= ~LIR_OpArrayCopy::dst_null_check;
 785 
 786 
 787   if (expected_type != NULL) {
 788     Value length_limit = NULL;
 789 
 790     IfOp* ifop = length->as_IfOp();
 791     if (ifop != NULL) {
 792       // look for expressions like min(v, a.length) which ends up as
 793       //   x > y ? y : x  or  x >= y ? y : x
 794       if ((ifop->cond() == If::gtr || ifop->cond() == If::geq) &&
 795           ifop->x() == ifop->fval() &&
 796           ifop->y() == ifop->tval()) {
 797         length_limit = ifop->y();
 798       }
 799     }
 800 
 801     // try to skip null checks and range checks
 802     NewArray* src_array = src->as_NewArray();
 803     if (src_array != NULL) {
 804       flags &= ~LIR_OpArrayCopy::src_null_check;
 805       if (length_limit != NULL &&
 806           src_array->length() == length_limit &&
 807           is_constant_zero(src_pos)) {
 808         flags &= ~LIR_OpArrayCopy::src_range_check;
 809       }
 810     }
 811 
 812     NewArray* dst_array = dst->as_NewArray();
 813     if (dst_array != NULL) {
 814       flags &= ~LIR_OpArrayCopy::dst_null_check;
 815       if (length_limit != NULL &&
 816           dst_array->length() == length_limit &&
 817           is_constant_zero(dst_pos)) {
 818         flags &= ~LIR_OpArrayCopy::dst_range_check;
 819       }
 820     }
 821 
 822     // check from incoming constant values
 823     if (positive_constant(src_pos))
 824       flags &= ~LIR_OpArrayCopy::src_pos_positive_check;
 825     if (positive_constant(dst_pos))
 826       flags &= ~LIR_OpArrayCopy::dst_pos_positive_check;
 827     if (positive_constant(length))
 828       flags &= ~LIR_OpArrayCopy::length_positive_check;
 829 
 830     // see if the range check can be elided, which might also imply
 831     // that src or dst is non-null.
 832     ArrayLength* al = length->as_ArrayLength();
 833     if (al != NULL) {
 834       if (al->array() == src) {
 835         // it's the length of the source array
 836         flags &= ~LIR_OpArrayCopy::length_positive_check;
 837         flags &= ~LIR_OpArrayCopy::src_null_check;
 838         if (is_constant_zero(src_pos))
 839           flags &= ~LIR_OpArrayCopy::src_range_check;
 840       }
 841       if (al->array() == dst) {
 842         // it's the length of the destination array
 843         flags &= ~LIR_OpArrayCopy::length_positive_check;
 844         flags &= ~LIR_OpArrayCopy::dst_null_check;
 845         if (is_constant_zero(dst_pos))
 846           flags &= ~LIR_OpArrayCopy::dst_range_check;
 847       }
 848     }
 849     if (is_exact) {
 850       flags &= ~LIR_OpArrayCopy::type_check;
 851     }
 852   }
 853 
 854   IntConstant* src_int = src_pos->type()->as_IntConstant();
 855   IntConstant* dst_int = dst_pos->type()->as_IntConstant();
 856   if (src_int && dst_int) {
 857     int s_offs = src_int->value();
 858     int d_offs = dst_int->value();
 859     if (src_int->value() >= dst_int->value()) {
 860       flags &= ~LIR_OpArrayCopy::overlapping;
 861     }
 862     if (expected_type != NULL) {
 863       BasicType t = expected_type->element_type()->basic_type();
 864       int element_size = type2aelembytes(t);
 865       if (((arrayOopDesc::base_offset_in_bytes(t) + s_offs * element_size) % HeapWordSize == 0) &&
 866           ((arrayOopDesc::base_offset_in_bytes(t) + d_offs * element_size) % HeapWordSize == 0)) {
 867         flags &= ~LIR_OpArrayCopy::unaligned;
 868       }
 869     }
 870   } else if (src_pos == dst_pos || is_constant_zero(dst_pos)) {
 871     // src and dest positions are the same, or dst is zero so assume
 872     // nonoverlapping copy.
 873     flags &= ~LIR_OpArrayCopy::overlapping;
 874   }
 875 
 876   if (src == dst) {
 877     // moving within a single array so no type checks are needed
 878     if (flags & LIR_OpArrayCopy::type_check) {
 879       flags &= ~LIR_OpArrayCopy::type_check;
 880     }
 881   }
 882   *flagsp = flags;
 883   *expected_typep = (ciArrayKlass*)expected_type;
 884 }
 885 
 886 
 887 LIR_Opr LIRGenerator::round_item(LIR_Opr opr) {
 888   assert(opr->is_register(), "why spill if item is not register?");
 889 
 890   if (strict_fp_requires_explicit_rounding) {
 891 #ifdef IA32
 892     if (UseSSE < 1 && opr->is_single_fpu()) {
 893       LIR_Opr result = new_register(T_FLOAT);
 894       set_vreg_flag(result, must_start_in_memory);
 895       assert(opr->is_register(), "only a register can be spilled");
 896       assert(opr->value_type()->is_float(), "rounding only for floats available");
 897       __ roundfp(opr, LIR_OprFact::illegalOpr, result);
 898       return result;
 899     }
 900 #else
 901     Unimplemented();
 902 #endif // IA32
 903   }
 904   return opr;
 905 }
 906 
 907 
 908 LIR_Opr LIRGenerator::force_to_spill(LIR_Opr value, BasicType t) {
 909   assert(type2size[t] == type2size[value->type()],
 910          "size mismatch: t=%s, value->type()=%s", type2name(t), type2name(value->type()));
 911   if (!value->is_register()) {
 912     // force into a register
 913     LIR_Opr r = new_register(value->type());
 914     __ move(value, r);
 915     value = r;
 916   }
 917 
 918   // create a spill location
 919   LIR_Opr tmp = new_register(t);
 920   set_vreg_flag(tmp, LIRGenerator::must_start_in_memory);
 921 
 922   // move from register to spill
 923   __ move(value, tmp);
 924   return tmp;
 925 }
 926 
 927 void LIRGenerator::profile_branch(If* if_instr, If::Condition cond) {
 928   if (if_instr->should_profile()) {
 929     ciMethod* method = if_instr->profiled_method();
 930     assert(method != NULL, "method should be set if branch is profiled");
 931     ciMethodData* md = method->method_data_or_null();
 932     assert(md != NULL, "Sanity");
 933     ciProfileData* data = md->bci_to_data(if_instr->profiled_bci());
 934     assert(data != NULL, "must have profiling data");
 935     assert(data->is_BranchData(), "need BranchData for two-way branches");
 936     int taken_count_offset     = md->byte_offset_of_slot(data, BranchData::taken_offset());
 937     int not_taken_count_offset = md->byte_offset_of_slot(data, BranchData::not_taken_offset());
 938     if (if_instr->is_swapped()) {
 939       int t = taken_count_offset;
 940       taken_count_offset = not_taken_count_offset;
 941       not_taken_count_offset = t;
 942     }
 943 
 944     LIR_Opr md_reg = new_register(T_METADATA);
 945     __ metadata2reg(md->constant_encoding(), md_reg);
 946 
 947     LIR_Opr data_offset_reg = new_pointer_register();
 948     __ cmove(lir_cond(cond),
 949              LIR_OprFact::intptrConst(taken_count_offset),
 950              LIR_OprFact::intptrConst(not_taken_count_offset),
 951              data_offset_reg, as_BasicType(if_instr->x()->type()));
 952 
 953     // MDO cells are intptr_t, so the data_reg width is arch-dependent.
 954     LIR_Opr data_reg = new_pointer_register();
 955     LIR_Address* data_addr = new LIR_Address(md_reg, data_offset_reg, data_reg->type());
 956     __ move(data_addr, data_reg);
 957     // Use leal instead of add to avoid destroying condition codes on x86
 958     LIR_Address* fake_incr_value = new LIR_Address(data_reg, DataLayout::counter_increment, T_INT);
 959     __ leal(LIR_OprFact::address(fake_incr_value), data_reg);
 960     __ move(data_reg, data_addr);
 961   }
 962 }
 963 
 964 // Phi technique:
 965 // This is about passing live values from one basic block to the other.
 966 // In code generated with Java it is rather rare that more than one
 967 // value is on the stack from one basic block to the other.
 968 // We optimize our technique for efficient passing of one value
 969 // (of type long, int, double..) but it can be extended.
 970 // When entering or leaving a basic block, all registers and all spill
 971 // slots are release and empty. We use the released registers
 972 // and spill slots to pass the live values from one block
 973 // to the other. The topmost value, i.e., the value on TOS of expression
 974 // stack is passed in registers. All other values are stored in spilling
 975 // area. Every Phi has an index which designates its spill slot
 976 // At exit of a basic block, we fill the register(s) and spill slots.
 977 // At entry of a basic block, the block_prolog sets up the content of phi nodes
 978 // and locks necessary registers and spilling slots.
 979 
 980 
 981 // move current value to referenced phi function
 982 void LIRGenerator::move_to_phi(PhiResolver* resolver, Value cur_val, Value sux_val) {
 983   Phi* phi = sux_val->as_Phi();
 984   // cur_val can be null without phi being null in conjunction with inlining
 985   if (phi != NULL && cur_val != NULL && cur_val != phi && !phi->is_illegal()) {
 986     if (phi->is_local()) {
 987       for (int i = 0; i < phi->operand_count(); i++) {
 988         Value op = phi->operand_at(i);
 989         if (op != NULL && op->type()->is_illegal()) {
 990           bailout("illegal phi operand");
 991         }
 992       }
 993     }
 994     Phi* cur_phi = cur_val->as_Phi();
 995     if (cur_phi != NULL && cur_phi->is_illegal()) {
 996       // Phi and local would need to get invalidated
 997       // (which is unexpected for Linear Scan).
 998       // But this case is very rare so we simply bail out.
 999       bailout("propagation of illegal phi");
1000       return;
1001     }
1002     LIR_Opr operand = cur_val->operand();
1003     if (operand->is_illegal()) {
1004       assert(cur_val->as_Constant() != NULL || cur_val->as_Local() != NULL,
1005              "these can be produced lazily");
1006       operand = operand_for_instruction(cur_val);
1007     }
1008     resolver->move(operand, operand_for_instruction(phi));
1009   }
1010 }
1011 
1012 
1013 // Moves all stack values into their PHI position
1014 void LIRGenerator::move_to_phi(ValueStack* cur_state) {
1015   BlockBegin* bb = block();
1016   if (bb->number_of_sux() == 1) {
1017     BlockBegin* sux = bb->sux_at(0);
1018     assert(sux->number_of_preds() > 0, "invalid CFG");
1019 
1020     // a block with only one predecessor never has phi functions
1021     if (sux->number_of_preds() > 1) {
1022       PhiResolver resolver(this);
1023 
1024       ValueStack* sux_state = sux->state();
1025       Value sux_value;
1026       int index;
1027 
1028       assert(cur_state->scope() == sux_state->scope(), "not matching");
1029       assert(cur_state->locals_size() == sux_state->locals_size(), "not matching");
1030       assert(cur_state->stack_size() == sux_state->stack_size(), "not matching");
1031 
1032       for_each_stack_value(sux_state, index, sux_value) {
1033         move_to_phi(&resolver, cur_state->stack_at(index), sux_value);
1034       }
1035 
1036       for_each_local_value(sux_state, index, sux_value) {
1037         move_to_phi(&resolver, cur_state->local_at(index), sux_value);
1038       }
1039 
1040       assert(cur_state->caller_state() == sux_state->caller_state(), "caller states must be equal");
1041     }
1042   }
1043 }
1044 
1045 
1046 LIR_Opr LIRGenerator::new_register(BasicType type) {
1047   int vreg_num = _virtual_register_number;
1048   // Add a little fudge factor for the bailout since the bailout is only checked periodically. This allows us to hand out
1049   // a few extra registers before we really run out which helps to avoid to trip over assertions.
1050   if (vreg_num + 20 >= LIR_Opr::vreg_max) {
1051     bailout("out of virtual registers in LIR generator");
1052     if (vreg_num + 2 >= LIR_Opr::vreg_max) {
1053       // Wrap it around and continue until bailout really happens to avoid hitting assertions.
1054       _virtual_register_number = LIR_Opr::vreg_base;
1055       vreg_num = LIR_Opr::vreg_base;
1056     }
1057   }
1058   _virtual_register_number += 1;
1059   LIR_Opr vreg = LIR_OprFact::virtual_register(vreg_num, type);
1060   assert(vreg != LIR_OprFact::illegal(), "ran out of virtual registers");
1061   return vreg;
1062 }
1063 
1064 
1065 // Try to lock using register in hint
1066 LIR_Opr LIRGenerator::rlock(Value instr) {
1067   return new_register(instr->type());
1068 }
1069 
1070 
1071 // does an rlock and sets result
1072 LIR_Opr LIRGenerator::rlock_result(Value x) {
1073   LIR_Opr reg = rlock(x);
1074   set_result(x, reg);
1075   return reg;
1076 }
1077 
1078 
1079 // does an rlock and sets result
1080 LIR_Opr LIRGenerator::rlock_result(Value x, BasicType type) {
1081   LIR_Opr reg;
1082   switch (type) {
1083   case T_BYTE:
1084   case T_BOOLEAN:
1085     reg = rlock_byte(type);
1086     break;
1087   default:
1088     reg = rlock(x);
1089     break;
1090   }
1091 
1092   set_result(x, reg);
1093   return reg;
1094 }
1095 
1096 
1097 //---------------------------------------------------------------------
1098 ciObject* LIRGenerator::get_jobject_constant(Value value) {
1099   ObjectType* oc = value->type()->as_ObjectType();
1100   if (oc) {
1101     return oc->constant_value();
1102   }
1103   return NULL;
1104 }
1105 
1106 
1107 void LIRGenerator::do_ExceptionObject(ExceptionObject* x) {
1108   assert(block()->is_set(BlockBegin::exception_entry_flag), "ExceptionObject only allowed in exception handler block");
1109   assert(block()->next() == x, "ExceptionObject must be first instruction of block");
1110 
1111   // no moves are created for phi functions at the begin of exception
1112   // handlers, so assign operands manually here
1113   for_each_phi_fun(block(), phi,
1114                    if (!phi->is_illegal()) { operand_for_instruction(phi); });
1115 
1116   LIR_Opr thread_reg = getThreadPointer();
1117   __ move_wide(new LIR_Address(thread_reg, in_bytes(JavaThread::exception_oop_offset()), T_OBJECT),
1118                exceptionOopOpr());
1119   __ move_wide(LIR_OprFact::oopConst(NULL),
1120                new LIR_Address(thread_reg, in_bytes(JavaThread::exception_oop_offset()), T_OBJECT));
1121   __ move_wide(LIR_OprFact::oopConst(NULL),
1122                new LIR_Address(thread_reg, in_bytes(JavaThread::exception_pc_offset()), T_OBJECT));
1123 
1124   LIR_Opr result = new_register(T_OBJECT);
1125   __ move(exceptionOopOpr(), result);
1126   set_result(x, result);
1127 }
1128 
1129 
1130 //----------------------------------------------------------------------
1131 //----------------------------------------------------------------------
1132 //----------------------------------------------------------------------
1133 //----------------------------------------------------------------------
1134 //                        visitor functions
1135 //----------------------------------------------------------------------
1136 //----------------------------------------------------------------------
1137 //----------------------------------------------------------------------
1138 //----------------------------------------------------------------------
1139 
1140 void LIRGenerator::do_Phi(Phi* x) {
1141   // phi functions are never visited directly
1142   ShouldNotReachHere();
1143 }
1144 
1145 
1146 // Code for a constant is generated lazily unless the constant is frequently used and can't be inlined.
1147 void LIRGenerator::do_Constant(Constant* x) {
1148   if (x->state_before() != NULL) {
1149     // Any constant with a ValueStack requires patching so emit the patch here
1150     LIR_Opr reg = rlock_result(x);
1151     CodeEmitInfo* info = state_for(x, x->state_before());
1152     __ oop2reg_patch(NULL, reg, info);
1153   } else if (x->use_count() > 1 && !can_inline_as_constant(x)) {
1154     if (!x->is_pinned()) {
1155       // unpinned constants are handled specially so that they can be
1156       // put into registers when they are used multiple times within a
1157       // block.  After the block completes their operand will be
1158       // cleared so that other blocks can't refer to that register.
1159       set_result(x, load_constant(x));
1160     } else {
1161       LIR_Opr res = x->operand();
1162       if (!res->is_valid()) {
1163         res = LIR_OprFact::value_type(x->type());
1164       }
1165       if (res->is_constant()) {
1166         LIR_Opr reg = rlock_result(x);
1167         __ move(res, reg);
1168       } else {
1169         set_result(x, res);
1170       }
1171     }
1172   } else {
1173     set_result(x, LIR_OprFact::value_type(x->type()));
1174   }
1175 }
1176 
1177 
1178 void LIRGenerator::do_Local(Local* x) {
1179   // operand_for_instruction has the side effect of setting the result
1180   // so there's no need to do it here.
1181   operand_for_instruction(x);
1182 }
1183 
1184 
1185 void LIRGenerator::do_Return(Return* x) {
1186   if (compilation()->env()->dtrace_method_probes()) {
1187     BasicTypeList signature;
1188     signature.append(LP64_ONLY(T_LONG) NOT_LP64(T_INT));    // thread
1189     signature.append(T_METADATA); // Method*
1190     LIR_OprList* args = new LIR_OprList();
1191     args->append(getThreadPointer());
1192     LIR_Opr meth = new_register(T_METADATA);
1193     __ metadata2reg(method()->constant_encoding(), meth);
1194     args->append(meth);
1195     call_runtime(&signature, args, CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit), voidType, NULL);
1196   }
1197 
1198   if (x->type()->is_void()) {
1199     __ return_op(LIR_OprFact::illegalOpr);
1200   } else {
1201     LIR_Opr reg = result_register_for(x->type(), /*callee=*/true);
1202     LIRItem result(x->result(), this);
1203 
1204     result.load_item_force(reg);
1205     __ return_op(result.result());
1206   }
1207   set_no_result(x);
1208 }
1209 
1210 // Examble: ref.get()
1211 // Combination of LoadField and g1 pre-write barrier
1212 void LIRGenerator::do_Reference_get(Intrinsic* x) {
1213 
1214   const int referent_offset = java_lang_ref_Reference::referent_offset();
1215 
1216   assert(x->number_of_arguments() == 1, "wrong type");
1217 
1218   LIRItem reference(x->argument_at(0), this);
1219   reference.load_item();
1220 
1221   // need to perform the null check on the reference objecy
1222   CodeEmitInfo* info = NULL;
1223   if (x->needs_null_check()) {
1224     info = state_for(x);
1225   }
1226 
1227   LIR_Opr result = rlock_result(x, T_OBJECT);
1228   access_load_at(IN_HEAP | ON_WEAK_OOP_REF, T_OBJECT,
1229                  reference, LIR_OprFact::intConst(referent_offset), result);
1230 }
1231 
1232 // Example: clazz.isInstance(object)
1233 void LIRGenerator::do_isInstance(Intrinsic* x) {
1234   assert(x->number_of_arguments() == 2, "wrong type");
1235 
1236   // TODO could try to substitute this node with an equivalent InstanceOf
1237   // if clazz is known to be a constant Class. This will pick up newly found
1238   // constants after HIR construction. I'll leave this to a future change.
1239 
1240   // as a first cut, make a simple leaf call to runtime to stay platform independent.
1241   // could follow the aastore example in a future change.
1242 
1243   LIRItem clazz(x->argument_at(0), this);
1244   LIRItem object(x->argument_at(1), this);
1245   clazz.load_item();
1246   object.load_item();
1247   LIR_Opr result = rlock_result(x);
1248 
1249   // need to perform null check on clazz
1250   if (x->needs_null_check()) {
1251     CodeEmitInfo* info = state_for(x);
1252     __ null_check(clazz.result(), info);
1253   }
1254 
1255   LIR_Opr call_result = call_runtime(clazz.value(), object.value(),
1256                                      CAST_FROM_FN_PTR(address, Runtime1::is_instance_of),
1257                                      x->type(),
1258                                      NULL); // NULL CodeEmitInfo results in a leaf call
1259   __ move(call_result, result);
1260 }
1261 
1262 void LIRGenerator::load_klass(LIR_Opr obj, LIR_Opr klass, CodeEmitInfo* null_check_info) {
1263   __ load_klass(obj, klass, null_check_info);
1264 }
1265 
1266 // Example: object.getClass ()
1267 void LIRGenerator::do_getClass(Intrinsic* x) {
1268   assert(x->number_of_arguments() == 1, "wrong type");
1269 
1270   LIRItem rcvr(x->argument_at(0), this);
1271   rcvr.load_item();
1272   LIR_Opr temp = new_register(T_ADDRESS);
1273   LIR_Opr result = rlock_result(x);
1274 
1275   // need to perform the null check on the rcvr
1276   CodeEmitInfo* info = NULL;
1277   if (x->needs_null_check()) {
1278     info = state_for(x);
1279   }
1280 
1281   LIR_Opr klass = new_register(T_METADATA);
1282   load_klass(rcvr.result(), klass, info);
1283   __ move_wide(new LIR_Address(klass, in_bytes(Klass::java_mirror_offset()), T_ADDRESS), temp);
1284   // mirror = ((OopHandle)mirror)->resolve();
1285   access_load(IN_NATIVE, T_OBJECT,
1286               LIR_OprFact::address(new LIR_Address(temp, T_OBJECT)), result);
1287 }
1288 
1289 // java.lang.Class::isPrimitive()
1290 void LIRGenerator::do_isPrimitive(Intrinsic* x) {
1291   assert(x->number_of_arguments() == 1, "wrong type");
1292 
1293   LIRItem rcvr(x->argument_at(0), this);
1294   rcvr.load_item();
1295   LIR_Opr temp = new_register(T_METADATA);
1296   LIR_Opr result = rlock_result(x);
1297 
1298   CodeEmitInfo* info = NULL;
1299   if (x->needs_null_check()) {
1300     info = state_for(x);
1301   }
1302 
1303   __ move(new LIR_Address(rcvr.result(), java_lang_Class::klass_offset(), T_ADDRESS), temp, info);
1304   __ cmp(lir_cond_notEqual, temp, LIR_OprFact::metadataConst(0));
1305   __ cmove(lir_cond_notEqual, LIR_OprFact::intConst(0), LIR_OprFact::intConst(1), result, T_BOOLEAN);
1306 }
1307 
1308 // Example: Foo.class.getModifiers()
1309 void LIRGenerator::do_getModifiers(Intrinsic* x) {
1310   assert(x->number_of_arguments() == 1, "wrong type");
1311 
1312   LIRItem receiver(x->argument_at(0), this);
1313   receiver.load_item();
1314   LIR_Opr result = rlock_result(x);
1315 
1316   CodeEmitInfo* info = NULL;
1317   if (x->needs_null_check()) {
1318     info = state_for(x);
1319   }
1320 
1321   LabelObj* L_not_prim = new LabelObj();
1322   LabelObj* L_done = new LabelObj();
1323 
1324   LIR_Opr klass = new_register(T_METADATA);
1325   // Checking if it's a java mirror of primitive type
1326   __ move(new LIR_Address(receiver.result(), java_lang_Class::klass_offset(), T_ADDRESS), klass, info);
1327   __ cmp(lir_cond_notEqual, klass, LIR_OprFact::metadataConst(0));
1328   __ branch(lir_cond_notEqual, L_not_prim->label());
1329   __ move(LIR_OprFact::intConst(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC), result);
1330   __ branch(lir_cond_always, L_done->label());
1331 
1332   __ branch_destination(L_not_prim->label());
1333   __ move(new LIR_Address(klass, in_bytes(Klass::modifier_flags_offset()), T_INT), result);
1334   __ branch_destination(L_done->label());
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   load_klass(value.result(), 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   if (!in_conditional_code()) {
1560     _constants.append(c);
1561     _reg_for_constants.append(result);
1562   }
1563   return result;
1564 }
1565 
1566 void LIRGenerator::set_in_conditional_code(bool v) {
1567   assert(v != _in_conditional_code, "must change state");
1568   _in_conditional_code = v;
1569 }
1570 
1571 
1572 //------------------------field access--------------------------------------
1573 
1574 void LIRGenerator::do_CompareAndSwap(Intrinsic* x, ValueType* type) {
1575   assert(x->number_of_arguments() == 4, "wrong type");
1576   LIRItem obj   (x->argument_at(0), this);  // object
1577   LIRItem offset(x->argument_at(1), this);  // offset of field
1578   LIRItem cmp   (x->argument_at(2), this);  // value to compare with field
1579   LIRItem val   (x->argument_at(3), this);  // replace field with val if matches cmp
1580   assert(obj.type()->tag() == objectTag, "invalid type");
1581   assert(cmp.type()->tag() == type->tag(), "invalid type");
1582   assert(val.type()->tag() == type->tag(), "invalid type");
1583 
1584   LIR_Opr result = access_atomic_cmpxchg_at(IN_HEAP, as_BasicType(type),
1585                                             obj, offset, cmp, val);
1586   set_result(x, result);
1587 }
1588 
1589 // Comment copied form templateTable_i486.cpp
1590 // ----------------------------------------------------------------------------
1591 // Volatile variables demand their effects be made known to all CPU's in
1592 // order.  Store buffers on most chips allow reads & writes to reorder; the
1593 // JMM's ReadAfterWrite.java test fails in -Xint mode without some kind of
1594 // memory barrier (i.e., it's not sufficient that the interpreter does not
1595 // reorder volatile references, the hardware also must not reorder them).
1596 //
1597 // According to the new Java Memory Model (JMM):
1598 // (1) All volatiles are serialized wrt to each other.
1599 // ALSO reads & writes act as aquire & release, so:
1600 // (2) A read cannot let unrelated NON-volatile memory refs that happen after
1601 // the read float up to before the read.  It's OK for non-volatile memory refs
1602 // that happen before the volatile read to float down below it.
1603 // (3) Similar a volatile write cannot let unrelated NON-volatile memory refs
1604 // that happen BEFORE the write float down to after the write.  It's OK for
1605 // non-volatile memory refs that happen after the volatile write to float up
1606 // before it.
1607 //
1608 // We only put in barriers around volatile refs (they are expensive), not
1609 // _between_ memory refs (that would require us to track the flavor of the
1610 // previous memory refs).  Requirements (2) and (3) require some barriers
1611 // before volatile stores and after volatile loads.  These nearly cover
1612 // requirement (1) but miss the volatile-store-volatile-load case.  This final
1613 // case is placed after volatile-stores although it could just as well go
1614 // before volatile-loads.
1615 
1616 
1617 void LIRGenerator::do_StoreField(StoreField* x) {
1618   bool needs_patching = x->needs_patching();
1619   bool is_volatile = x->field()->is_volatile();
1620   BasicType field_type = x->field_type();
1621 
1622   CodeEmitInfo* info = NULL;
1623   if (needs_patching) {
1624     assert(x->explicit_null_check() == NULL, "can't fold null check into patching field access");
1625     info = state_for(x, x->state_before());
1626   } else if (x->needs_null_check()) {
1627     NullCheck* nc = x->explicit_null_check();
1628     if (nc == NULL) {
1629       info = state_for(x);
1630     } else {
1631       info = state_for(nc);
1632     }
1633   }
1634 
1635   LIRItem object(x->obj(), this);
1636   LIRItem value(x->value(),  this);
1637 
1638   object.load_item();
1639 
1640   if (is_volatile || needs_patching) {
1641     // load item if field is volatile (fewer special cases for volatiles)
1642     // load item if field not initialized
1643     // load item if field not constant
1644     // because of code patching we cannot inline constants
1645     if (field_type == T_BYTE || field_type == T_BOOLEAN) {
1646       value.load_byte_item();
1647     } else  {
1648       value.load_item();
1649     }
1650   } else {
1651     value.load_for_store(field_type);
1652   }
1653 
1654   set_no_result(x);
1655 
1656 #ifndef PRODUCT
1657   if (PrintNotLoaded && needs_patching) {
1658     tty->print_cr("   ###class not loaded at store_%s bci %d",
1659                   x->is_static() ?  "static" : "field", x->printable_bci());
1660   }
1661 #endif
1662 
1663   if (!inline_type_field_access_prolog(x)) {
1664     // Field store will always deopt due to unloaded field or holder klass
1665     return;
1666   }
1667 
1668   if (x->needs_null_check() &&
1669       (needs_patching ||
1670        MacroAssembler::needs_explicit_null_check(x->offset()))) {
1671     // Emit an explicit null check because the offset is too large.
1672     // If the class is not loaded and the object is NULL, we need to deoptimize to throw a
1673     // NoClassDefFoundError in the interpreter instead of an implicit NPE from compiled code.
1674     __ null_check(object.result(), new CodeEmitInfo(info), /* deoptimize */ needs_patching);
1675   }
1676 
1677   DecoratorSet decorators = IN_HEAP;
1678   if (is_volatile) {
1679     decorators |= MO_SEQ_CST;
1680   }
1681   if (needs_patching) {
1682     decorators |= C1_NEEDS_PATCHING;
1683   }
1684 
1685   access_store_at(decorators, field_type, object, LIR_OprFact::intConst(x->offset()),
1686                   value.result(), info != NULL ? new CodeEmitInfo(info) : NULL, info);
1687 }
1688 
1689 // FIXME -- I can't find any other way to pass an address to access_load_at().
1690 class TempResolvedAddress: public Instruction {
1691  public:
1692   TempResolvedAddress(ValueType* type, LIR_Opr addr) : Instruction(type) {
1693     set_operand(addr);
1694   }
1695   virtual void input_values_do(ValueVisitor*) {}
1696   virtual void visit(InstructionVisitor* v)   {}
1697   virtual const char* name() const  { return "TempResolvedAddress"; }
1698 };
1699 
1700 LIR_Opr LIRGenerator::get_and_load_element_address(LIRItem& array, LIRItem& index) {
1701   ciType* array_type = array.value()->declared_type();
1702   ciFlatArrayKlass* flat_array_klass = array_type->as_flat_array_klass();
1703   assert(flat_array_klass->is_loaded(), "must be");
1704 
1705   int array_header_size = flat_array_klass->array_header_in_bytes();
1706   int shift = flat_array_klass->log2_element_size();
1707 
1708 #ifndef _LP64
1709   LIR_Opr index_op = new_register(T_INT);
1710   // FIXME -- on 32-bit, the shift below can overflow, so we need to check that
1711   // the top (shift+1) bits of index_op must be zero, or
1712   // else throw ArrayIndexOutOfBoundsException
1713   if (index.result()->is_constant()) {
1714     jint const_index = index.result()->as_jint();
1715     __ move(LIR_OprFact::intConst(const_index << shift), index_op);
1716   } else {
1717     __ shift_left(index_op, shift, index.result());
1718   }
1719 #else
1720   LIR_Opr index_op = new_register(T_LONG);
1721   if (index.result()->is_constant()) {
1722     jint const_index = index.result()->as_jint();
1723     __ move(LIR_OprFact::longConst(const_index << shift), index_op);
1724   } else {
1725     __ convert(Bytecodes::_i2l, index.result(), index_op);
1726     // Need to shift manually, as LIR_Address can scale only up to 3.
1727     __ shift_left(index_op, shift, index_op);
1728   }
1729 #endif
1730 
1731   LIR_Opr elm_op = new_pointer_register();
1732   LIR_Address* elm_address = generate_address(array.result(), index_op, 0, array_header_size, T_ADDRESS);
1733   __ leal(LIR_OprFact::address(elm_address), elm_op);
1734   return elm_op;
1735 }
1736 
1737 void LIRGenerator::access_sub_element(LIRItem& array, LIRItem& index, LIR_Opr& result, ciField* field, int sub_offset) {
1738   assert(field != NULL, "Need a subelement type specified");
1739 
1740   // Find the starting address of the source (inside the array)
1741   LIR_Opr elm_op = get_and_load_element_address(array, index);
1742 
1743   BasicType subelt_type = field->type()->basic_type();
1744   TempResolvedAddress* elm_resolved_addr = new TempResolvedAddress(as_ValueType(subelt_type), elm_op);
1745   LIRItem elm_item(elm_resolved_addr, this);
1746 
1747   DecoratorSet decorators = IN_HEAP;
1748   access_load_at(decorators, subelt_type,
1749                      elm_item, LIR_OprFact::intConst(sub_offset), result,
1750                      NULL, NULL);
1751 
1752   if (field->is_null_free()) {
1753     assert(field->type()->is_loaded(), "Must be");
1754     assert(field->type()->is_inlinetype(), "Must be if loaded");
1755     assert(field->type()->as_inline_klass()->is_initialized(), "Must be");
1756     LabelObj* L_end = new LabelObj();
1757     __ cmp(lir_cond_notEqual, result, LIR_OprFact::oopConst(NULL));
1758     __ branch(lir_cond_notEqual, L_end->label());
1759     set_in_conditional_code(true);
1760     Constant* default_value = new Constant(new InstanceConstant(field->type()->as_inline_klass()->default_instance()));
1761     if (default_value->is_pinned()) {
1762       __ move(LIR_OprFact::value_type(default_value->type()), result);
1763     } else {
1764       __ move(load_constant(default_value), result);
1765     }
1766     __ branch_destination(L_end->label());
1767     set_in_conditional_code(false);
1768   }
1769 }
1770 
1771 void LIRGenerator::access_flattened_array(bool is_load, LIRItem& array, LIRItem& index, LIRItem& obj_item,
1772                                           ciField* field, int sub_offset) {
1773   assert(sub_offset == 0 || field != NULL, "Sanity check");
1774 
1775   // Find the starting address of the source (inside the array)
1776   LIR_Opr elm_op = get_and_load_element_address(array, index);
1777 
1778   ciInlineKlass* elem_klass = NULL;
1779   if (field != NULL) {
1780     elem_klass = field->type()->as_inline_klass();
1781   } else {
1782     elem_klass = array.value()->declared_type()->as_flat_array_klass()->element_klass()->as_inline_klass();
1783   }
1784   for (int i = 0; i < elem_klass->nof_nonstatic_fields(); i++) {
1785     ciField* inner_field = elem_klass->nonstatic_field_at(i);
1786     assert(!inner_field->is_flattened(), "flattened fields must have been expanded");
1787     int obj_offset = inner_field->offset();
1788     int elm_offset = obj_offset - elem_klass->first_field_offset() + sub_offset; // object header is not stored in array.
1789     BasicType field_type = inner_field->type()->basic_type();
1790 
1791     // Types which are smaller than int are still passed in an int register.
1792     BasicType reg_type = field_type;
1793     switch (reg_type) {
1794     case T_BYTE:
1795     case T_BOOLEAN:
1796     case T_SHORT:
1797     case T_CHAR:
1798       reg_type = T_INT;
1799       break;
1800     default:
1801       break;
1802     }
1803 
1804     LIR_Opr temp = new_register(reg_type);
1805     TempResolvedAddress* elm_resolved_addr = new TempResolvedAddress(as_ValueType(field_type), elm_op);
1806     LIRItem elm_item(elm_resolved_addr, this);
1807 
1808     DecoratorSet decorators = IN_HEAP;
1809     if (is_load) {
1810       access_load_at(decorators, field_type,
1811                      elm_item, LIR_OprFact::intConst(elm_offset), temp,
1812                      NULL, NULL);
1813       access_store_at(decorators, field_type,
1814                       obj_item, LIR_OprFact::intConst(obj_offset), temp,
1815                       NULL, NULL);
1816     } else {
1817       access_load_at(decorators, field_type,
1818                      obj_item, LIR_OprFact::intConst(obj_offset), temp,
1819                      NULL, NULL);
1820       access_store_at(decorators, field_type,
1821                       elm_item, LIR_OprFact::intConst(elm_offset), temp,
1822                       NULL, NULL);
1823     }
1824   }
1825 }
1826 
1827 void LIRGenerator::check_flattened_array(LIR_Opr array, LIR_Opr value, CodeStub* slow_path) {
1828   LIR_Opr tmp = new_register(T_METADATA);
1829   __ check_flattened_array(array, value, tmp, slow_path);
1830 }
1831 
1832 void LIRGenerator::check_null_free_array(LIRItem& array, LIRItem& value, CodeEmitInfo* info) {
1833   LabelObj* L_end = new LabelObj();
1834   LIR_Opr tmp = new_register(T_METADATA);
1835   __ check_null_free_array(array.result(), tmp);
1836   __ branch(lir_cond_equal, L_end->label());
1837   __ null_check(value.result(), info);
1838   __ branch_destination(L_end->label());
1839 }
1840 
1841 bool LIRGenerator::needs_flattened_array_store_check(StoreIndexed* x) {
1842   if (x->elt_type() == T_OBJECT && x->array()->maybe_flattened_array()) {
1843     ciType* type = x->value()->declared_type();
1844     if (type != NULL && type->is_klass()) {
1845       ciKlass* klass = type->as_klass();
1846       if (!klass->can_be_inline_klass() || (klass->is_inlinetype() && !klass->as_inline_klass()->flatten_array())) {
1847         // This is known to be a non-flattened object. If the array is flattened,
1848         // it will be caught by the code generated by array_store_check().
1849         return false;
1850       }
1851     }
1852     // We're not 100% sure, so let's do the flattened_array_store_check.
1853     return true;
1854   }
1855   return false;
1856 }
1857 
1858 bool LIRGenerator::needs_null_free_array_store_check(StoreIndexed* x) {
1859   return x->elt_type() == T_OBJECT && x->array()->maybe_null_free_array();
1860 }
1861 
1862 void LIRGenerator::do_StoreIndexed(StoreIndexed* x) {
1863   assert(x->is_pinned(),"");
1864   assert(x->elt_type() != T_ARRAY, "never used");
1865   bool is_loaded_flattened_array = x->array()->is_loaded_flattened_array();
1866   bool needs_range_check = x->compute_needs_range_check();
1867   bool use_length = x->length() != NULL;
1868   bool obj_store = is_reference_type(x->elt_type());
1869   bool needs_store_check = obj_store && !(is_loaded_flattened_array && x->is_exact_flattened_array_store()) &&
1870                                         (x->value()->as_Constant() == NULL ||
1871                                          !get_jobject_constant(x->value())->is_null_object());
1872 
1873   LIRItem array(x->array(), this);
1874   LIRItem index(x->index(), this);
1875   LIRItem value(x->value(), this);
1876   LIRItem length(this);
1877 
1878   array.load_item();
1879   index.load_nonconstant();
1880 
1881   if (use_length && needs_range_check) {
1882     length.set_instruction(x->length());
1883     length.load_item();
1884   }
1885 
1886   if (needs_store_check || x->check_boolean()
1887       || is_loaded_flattened_array || needs_flattened_array_store_check(x) || needs_null_free_array_store_check(x)) {
1888     value.load_item();
1889   } else {
1890     value.load_for_store(x->elt_type());
1891   }
1892 
1893   set_no_result(x);
1894 
1895   // the CodeEmitInfo must be duplicated for each different
1896   // LIR-instruction because spilling can occur anywhere between two
1897   // instructions and so the debug information must be different
1898   CodeEmitInfo* range_check_info = state_for(x);
1899   CodeEmitInfo* null_check_info = NULL;
1900   if (x->needs_null_check()) {
1901     null_check_info = new CodeEmitInfo(range_check_info);
1902   }
1903 
1904   if (GenerateRangeChecks && needs_range_check) {
1905     if (use_length) {
1906       __ cmp(lir_cond_belowEqual, length.result(), index.result());
1907       __ branch(lir_cond_belowEqual, new RangeCheckStub(range_check_info, index.result(), array.result()));
1908     } else {
1909       array_range_check(array.result(), index.result(), null_check_info, range_check_info);
1910       // range_check also does the null check
1911       null_check_info = NULL;
1912     }
1913   }
1914 
1915   if (x->should_profile()) {
1916     if (x->array()->is_loaded_flattened_array()) {
1917       // No need to profile a store to a flattened array of known type. This can happen if
1918       // the type only became known after optimizations (for example, after the PhiSimplifier).
1919       x->set_should_profile(false);
1920     } else {
1921       ciMethodData* md = NULL;
1922       ciArrayLoadStoreData* load_store = NULL;
1923       profile_array_type(x, md, load_store);
1924       if (x->array()->maybe_null_free_array()) {
1925         profile_null_free_array(array, md, load_store);
1926       }
1927       profile_element_type(x->value(), md, load_store);
1928     }
1929   }
1930 
1931   if (GenerateArrayStoreCheck && needs_store_check) {
1932     CodeEmitInfo* store_check_info = new CodeEmitInfo(range_check_info);
1933     array_store_check(value.result(), array.result(), store_check_info, NULL, -1);
1934   }
1935 
1936   if (is_loaded_flattened_array) {
1937     if (!x->value()->is_null_free()) {
1938       __ null_check(value.result(), new CodeEmitInfo(range_check_info));
1939     }
1940     // If array element is an empty inline type, no need to copy anything
1941     if (!x->array()->declared_type()->as_flat_array_klass()->element_klass()->as_inline_klass()->is_empty()) {
1942       access_flattened_array(false, array, index, value);
1943     }
1944   } else {
1945     StoreFlattenedArrayStub* slow_path = NULL;
1946 
1947     if (needs_flattened_array_store_check(x)) {
1948       // Check if we indeed have a flattened array
1949       index.load_item();
1950       slow_path = new StoreFlattenedArrayStub(array.result(), index.result(), value.result(), state_for(x, x->state_before()));
1951       check_flattened_array(array.result(), value.result(), slow_path);
1952       set_in_conditional_code(true);
1953     } else if (needs_null_free_array_store_check(x)) {
1954       CodeEmitInfo* info = new CodeEmitInfo(range_check_info);
1955       check_null_free_array(array, value, info);
1956     }
1957 
1958     DecoratorSet decorators = IN_HEAP | IS_ARRAY;
1959     if (x->check_boolean()) {
1960       decorators |= C1_MASK_BOOLEAN;
1961     }
1962 
1963     access_store_at(decorators, x->elt_type(), array, index.result(), value.result(),
1964                     NULL, null_check_info);
1965     if (slow_path != NULL) {
1966       __ branch_destination(slow_path->continuation());
1967       set_in_conditional_code(false);
1968     }
1969   }
1970 }
1971 
1972 void LIRGenerator::access_load_at(DecoratorSet decorators, BasicType type,
1973                                   LIRItem& base, LIR_Opr offset, LIR_Opr result,
1974                                   CodeEmitInfo* patch_info, CodeEmitInfo* load_emit_info) {
1975   decorators |= ACCESS_READ;
1976   LIRAccess access(this, decorators, base, offset, type, patch_info, load_emit_info);
1977   if (access.is_raw()) {
1978     _barrier_set->BarrierSetC1::load_at(access, result);
1979   } else {
1980     _barrier_set->load_at(access, result);
1981   }
1982 }
1983 
1984 void LIRGenerator::access_load(DecoratorSet decorators, BasicType type,
1985                                LIR_Opr addr, LIR_Opr result) {
1986   decorators |= ACCESS_READ;
1987   LIRAccess access(this, decorators, LIR_OprFact::illegalOpr, LIR_OprFact::illegalOpr, type);
1988   access.set_resolved_addr(addr);
1989   if (access.is_raw()) {
1990     _barrier_set->BarrierSetC1::load(access, result);
1991   } else {
1992     _barrier_set->load(access, result);
1993   }
1994 }
1995 
1996 void LIRGenerator::access_store_at(DecoratorSet decorators, BasicType type,
1997                                    LIRItem& base, LIR_Opr offset, LIR_Opr value,
1998                                    CodeEmitInfo* patch_info, CodeEmitInfo* store_emit_info) {
1999   decorators |= ACCESS_WRITE;
2000   LIRAccess access(this, decorators, base, offset, type, patch_info, store_emit_info);
2001   if (access.is_raw()) {
2002     _barrier_set->BarrierSetC1::store_at(access, value);
2003   } else {
2004     _barrier_set->store_at(access, value);
2005   }
2006 }
2007 
2008 LIR_Opr LIRGenerator::access_atomic_cmpxchg_at(DecoratorSet decorators, BasicType type,
2009                                                LIRItem& base, LIRItem& offset, LIRItem& cmp_value, LIRItem& new_value) {
2010   decorators |= ACCESS_READ;
2011   decorators |= ACCESS_WRITE;
2012   // Atomic operations are SEQ_CST by default
2013   decorators |= ((decorators & MO_DECORATOR_MASK) == 0) ? MO_SEQ_CST : 0;
2014   LIRAccess access(this, decorators, base, offset, type);
2015   if (access.is_raw()) {
2016     return _barrier_set->BarrierSetC1::atomic_cmpxchg_at(access, cmp_value, new_value);
2017   } else {
2018     return _barrier_set->atomic_cmpxchg_at(access, cmp_value, new_value);
2019   }
2020 }
2021 
2022 LIR_Opr LIRGenerator::access_atomic_xchg_at(DecoratorSet decorators, BasicType type,
2023                                             LIRItem& base, LIRItem& offset, LIRItem& value) {
2024   decorators |= ACCESS_READ;
2025   decorators |= ACCESS_WRITE;
2026   // Atomic operations are SEQ_CST by default
2027   decorators |= ((decorators & MO_DECORATOR_MASK) == 0) ? MO_SEQ_CST : 0;
2028   LIRAccess access(this, decorators, base, offset, type);
2029   if (access.is_raw()) {
2030     return _barrier_set->BarrierSetC1::atomic_xchg_at(access, value);
2031   } else {
2032     return _barrier_set->atomic_xchg_at(access, value);
2033   }
2034 }
2035 
2036 LIR_Opr LIRGenerator::access_atomic_add_at(DecoratorSet decorators, BasicType type,
2037                                            LIRItem& base, LIRItem& offset, LIRItem& value) {
2038   decorators |= ACCESS_READ;
2039   decorators |= ACCESS_WRITE;
2040   // Atomic operations are SEQ_CST by default
2041   decorators |= ((decorators & MO_DECORATOR_MASK) == 0) ? MO_SEQ_CST : 0;
2042   LIRAccess access(this, decorators, base, offset, type);
2043   if (access.is_raw()) {
2044     return _barrier_set->BarrierSetC1::atomic_add_at(access, value);
2045   } else {
2046     return _barrier_set->atomic_add_at(access, value);
2047   }
2048 }
2049 
2050 bool LIRGenerator::inline_type_field_access_prolog(AccessField* x) {
2051   ciField* field = x->field();
2052   assert(!field->is_flattened(), "Flattened field access should have been expanded");
2053   if (!field->is_null_free()) {
2054     return true; // Not an inline type field
2055   }
2056   // Deoptimize if the access is non-static and requires patching (holder not loaded
2057   // or not accessible) because then we only have partial field information and the
2058   // field could be flattened (see ciField constructor).
2059   bool could_be_flat = !x->is_static() && x->needs_patching();
2060   // Deoptimize if we load from a static field with an uninitialized type because we
2061   // need to throw an exception if initialization of the type failed.
2062   bool not_initialized = x->is_static() && x->as_LoadField() != NULL &&
2063       !field->type()->as_instance_klass()->is_initialized();
2064   if (could_be_flat || not_initialized) {
2065     CodeEmitInfo* info = state_for(x, x->state_before());
2066     CodeStub* stub = new DeoptimizeStub(new CodeEmitInfo(info),
2067                                         Deoptimization::Reason_unloaded,
2068                                         Deoptimization::Action_make_not_entrant);
2069     __ jump(stub);
2070     return false;
2071   }
2072   return true;
2073 }
2074 
2075 void LIRGenerator::do_LoadField(LoadField* x) {
2076   bool needs_patching = x->needs_patching();
2077   bool is_volatile = x->field()->is_volatile();
2078   BasicType field_type = x->field_type();
2079 
2080   CodeEmitInfo* info = NULL;
2081   if (needs_patching) {
2082     assert(x->explicit_null_check() == NULL, "can't fold null check into patching field access");
2083     info = state_for(x, x->state_before());
2084   } else if (x->needs_null_check()) {
2085     NullCheck* nc = x->explicit_null_check();
2086     if (nc == NULL) {
2087       info = state_for(x);
2088     } else {
2089       info = state_for(nc);
2090     }
2091   }
2092 
2093   LIRItem object(x->obj(), this);
2094 
2095   object.load_item();
2096 
2097 #ifndef PRODUCT
2098   if (PrintNotLoaded && needs_patching) {
2099     tty->print_cr("   ###class not loaded at load_%s bci %d",
2100                   x->is_static() ?  "static" : "field", x->printable_bci());
2101   }
2102 #endif
2103 
2104   if (!inline_type_field_access_prolog(x)) {
2105     // Field load will always deopt due to unloaded field or holder klass
2106     LIR_Opr result = rlock_result(x, field_type);
2107     __ move(LIR_OprFact::oopConst(NULL), result);
2108     return;
2109   }
2110 
2111   bool stress_deopt = StressLoopInvariantCodeMotion && info && info->deoptimize_on_exception();
2112   if (x->needs_null_check() &&
2113       (needs_patching ||
2114        MacroAssembler::needs_explicit_null_check(x->offset()) ||
2115        stress_deopt)) {
2116     LIR_Opr obj = object.result();
2117     if (stress_deopt) {
2118       obj = new_register(T_OBJECT);
2119       __ move(LIR_OprFact::oopConst(NULL), obj);
2120     }
2121     // Emit an explicit null check because the offset is too large.
2122     // If the class is not loaded and the object is NULL, we need to deoptimize to throw a
2123     // NoClassDefFoundError in the interpreter instead of an implicit NPE from compiled code.
2124     __ null_check(obj, new CodeEmitInfo(info), /* deoptimize */ needs_patching);
2125   }
2126 
2127   DecoratorSet decorators = IN_HEAP;
2128   if (is_volatile) {
2129     decorators |= MO_SEQ_CST;
2130   }
2131   if (needs_patching) {
2132     decorators |= C1_NEEDS_PATCHING;
2133   }
2134 
2135   LIR_Opr result = rlock_result(x, field_type);
2136   access_load_at(decorators, field_type,
2137                  object, LIR_OprFact::intConst(x->offset()), result,
2138                  info ? new CodeEmitInfo(info) : NULL, info);
2139 
2140   ciField* field = x->field();
2141   if (field->is_null_free()) {
2142     // Load from non-flattened inline type field requires
2143     // a null check to replace null with the default value.
2144     ciInstanceKlass* holder = field->holder();
2145     if (field->is_static() && holder->is_loaded()) {
2146       ciObject* val = holder->java_mirror()->field_value(field).as_object();
2147       if (!val->is_null_object()) {
2148         // Static field is initialized, we don't need to perform a null check.
2149         return;
2150       }
2151     }
2152     ciInlineKlass* inline_klass = field->type()->as_inline_klass();
2153     if (inline_klass->is_initialized()) {
2154       LabelObj* L_end = new LabelObj();
2155       __ cmp(lir_cond_notEqual, result, LIR_OprFact::oopConst(NULL));
2156       __ branch(lir_cond_notEqual, L_end->label());
2157       set_in_conditional_code(true);
2158       Constant* default_value = new Constant(new InstanceConstant(inline_klass->default_instance()));
2159       if (default_value->is_pinned()) {
2160         __ move(LIR_OprFact::value_type(default_value->type()), result);
2161       } else {
2162         __ move(load_constant(default_value), result);
2163       }
2164       __ branch_destination(L_end->label());
2165       set_in_conditional_code(false);
2166     } else {
2167       __ cmp(lir_cond_equal, result, LIR_OprFact::oopConst(NULL));
2168       __ branch(lir_cond_equal, new DeoptimizeStub(info, Deoptimization::Reason_uninitialized,
2169                                                          Deoptimization::Action_make_not_entrant));
2170     }
2171   }
2172 }
2173 
2174 // int/long jdk.internal.util.Preconditions.checkIndex
2175 void LIRGenerator::do_PreconditionsCheckIndex(Intrinsic* x, BasicType type) {
2176   assert(x->number_of_arguments() == 3, "wrong type");
2177   LIRItem index(x->argument_at(0), this);
2178   LIRItem length(x->argument_at(1), this);
2179   LIRItem oobef(x->argument_at(2), this);
2180 
2181   index.load_item();
2182   length.load_item();
2183   oobef.load_item();
2184 
2185   LIR_Opr result = rlock_result(x);
2186   // x->state() is created from copy_state_for_exception, it does not contains arguments
2187   // we should prepare them before entering into interpreter mode due to deoptimization.
2188   ValueStack* state = x->state();
2189   for (int i = 0; i < x->number_of_arguments(); i++) {
2190     Value arg = x->argument_at(i);
2191     state->push(arg->type(), arg);
2192   }
2193   CodeEmitInfo* info = state_for(x, state);
2194 
2195   LIR_Opr len = length.result();
2196   LIR_Opr zero;
2197   if (type == T_INT) {
2198     zero = LIR_OprFact::intConst(0);
2199     if (length.result()->is_constant()){
2200       len = LIR_OprFact::intConst(length.result()->as_jint());
2201     }
2202   } else {
2203     assert(type == T_LONG, "sanity check");
2204     zero = LIR_OprFact::longConst(0);
2205     if (length.result()->is_constant()){
2206       len = LIR_OprFact::longConst(length.result()->as_jlong());
2207     }
2208   }
2209   // C1 can not handle the case that comparing index with constant value while condition
2210   // is neither lir_cond_equal nor lir_cond_notEqual, see LIR_Assembler::comp_op.
2211   LIR_Opr zero_reg = new_register(type);
2212   __ move(zero, zero_reg);
2213 #if defined(X86) && !defined(_LP64)
2214   // BEWARE! On 32-bit x86 cmp clobbers its left argument so we need a temp copy.
2215   LIR_Opr index_copy = new_register(index.type());
2216   // index >= 0
2217   __ move(index.result(), index_copy);
2218   __ cmp(lir_cond_less, index_copy, zero_reg);
2219   __ branch(lir_cond_less, new DeoptimizeStub(info, Deoptimization::Reason_range_check,
2220                                                     Deoptimization::Action_make_not_entrant));
2221   // index < length
2222   __ move(index.result(), index_copy);
2223   __ cmp(lir_cond_greaterEqual, index_copy, len);
2224   __ branch(lir_cond_greaterEqual, new DeoptimizeStub(info, Deoptimization::Reason_range_check,
2225                                                             Deoptimization::Action_make_not_entrant));
2226 #else
2227   // index >= 0
2228   __ cmp(lir_cond_less, index.result(), zero_reg);
2229   __ branch(lir_cond_less, new DeoptimizeStub(info, Deoptimization::Reason_range_check,
2230                                                     Deoptimization::Action_make_not_entrant));
2231   // index < length
2232   __ cmp(lir_cond_greaterEqual, index.result(), len);
2233   __ branch(lir_cond_greaterEqual, new DeoptimizeStub(info, Deoptimization::Reason_range_check,
2234                                                             Deoptimization::Action_make_not_entrant));
2235 #endif
2236   __ move(index.result(), result);
2237 }
2238 
2239 //------------------------array access--------------------------------------
2240 
2241 
2242 void LIRGenerator::do_ArrayLength(ArrayLength* x) {
2243   LIRItem array(x->array(), this);
2244   array.load_item();
2245   LIR_Opr reg = rlock_result(x);
2246 
2247   CodeEmitInfo* info = NULL;
2248   if (x->needs_null_check()) {
2249     NullCheck* nc = x->explicit_null_check();
2250     if (nc == NULL) {
2251       info = state_for(x);
2252     } else {
2253       info = state_for(nc);
2254     }
2255     if (StressLoopInvariantCodeMotion && info->deoptimize_on_exception()) {
2256       LIR_Opr obj = new_register(T_OBJECT);
2257       __ move(LIR_OprFact::oopConst(NULL), obj);
2258       __ null_check(obj, new CodeEmitInfo(info));
2259     }
2260   }
2261   __ load(new LIR_Address(array.result(), arrayOopDesc::length_offset_in_bytes(), T_INT), reg, info, lir_patch_none);
2262 }
2263 
2264 
2265 void LIRGenerator::do_LoadIndexed(LoadIndexed* x) {
2266   bool use_length = x->length() != NULL;
2267   LIRItem array(x->array(), this);
2268   LIRItem index(x->index(), this);
2269   LIRItem length(this);
2270   bool needs_range_check = x->compute_needs_range_check();
2271 
2272   if (use_length && needs_range_check) {
2273     length.set_instruction(x->length());
2274     length.load_item();
2275   }
2276 
2277   array.load_item();
2278   if (index.is_constant() && can_inline_as_constant(x->index())) {
2279     // let it be a constant
2280     index.dont_load_item();
2281   } else {
2282     index.load_item();
2283   }
2284 
2285   CodeEmitInfo* range_check_info = state_for(x);
2286   CodeEmitInfo* null_check_info = NULL;
2287   if (x->needs_null_check()) {
2288     NullCheck* nc = x->explicit_null_check();
2289     if (nc != NULL) {
2290       null_check_info = state_for(nc);
2291     } else {
2292       null_check_info = range_check_info;
2293     }
2294     if (StressLoopInvariantCodeMotion && null_check_info->deoptimize_on_exception()) {
2295       LIR_Opr obj = new_register(T_OBJECT);
2296       __ move(LIR_OprFact::oopConst(NULL), obj);
2297       __ null_check(obj, new CodeEmitInfo(null_check_info));
2298     }
2299   }
2300 
2301   if (GenerateRangeChecks && needs_range_check) {
2302     if (StressLoopInvariantCodeMotion && range_check_info->deoptimize_on_exception()) {
2303       __ branch(lir_cond_always, new RangeCheckStub(range_check_info, index.result(), array.result()));
2304     } else if (use_length) {
2305       // TODO: use a (modified) version of array_range_check that does not require a
2306       //       constant length to be loaded to a register
2307       __ cmp(lir_cond_belowEqual, length.result(), index.result());
2308       __ branch(lir_cond_belowEqual, new RangeCheckStub(range_check_info, index.result(), array.result()));
2309     } else {
2310       array_range_check(array.result(), index.result(), null_check_info, range_check_info);
2311       // The range check performs the null check, so clear it out for the load
2312       null_check_info = NULL;
2313     }
2314   }
2315 
2316   ciMethodData* md = NULL;
2317   ciArrayLoadStoreData* load_store = NULL;
2318   if (x->should_profile()) {
2319     if (x->array()->is_loaded_flattened_array()) {
2320       // No need to profile a load from a flattened array of known type. This can happen if
2321       // the type only became known after optimizations (for example, after the PhiSimplifier).
2322       x->set_should_profile(false);
2323     } else {
2324       profile_array_type(x, md, load_store);
2325     }
2326   }
2327 
2328   Value element;
2329   if (x->vt() != NULL) {
2330     assert(x->array()->is_loaded_flattened_array(), "must be");
2331     // Find the destination address (of the NewInlineTypeInstance).
2332     LIRItem obj_item(x->vt(), this);
2333 
2334     access_flattened_array(true, array, index, obj_item,
2335                            x->delayed() == NULL ? 0 : x->delayed()->field(),
2336                            x->delayed() == NULL ? 0 : x->delayed()->offset());
2337     set_no_result(x);
2338   } else if (x->delayed() != NULL) {
2339     assert(x->array()->is_loaded_flattened_array(), "must be");
2340     LIR_Opr result = rlock_result(x, x->delayed()->field()->type()->basic_type());
2341     access_sub_element(array, index, result, x->delayed()->field(), x->delayed()->offset());
2342   } else if (x->array() != NULL && x->array()->is_loaded_flattened_array() &&
2343              x->array()->declared_type()->as_flat_array_klass()->element_klass()->as_inline_klass()->is_initialized() &&
2344              x->array()->declared_type()->as_flat_array_klass()->element_klass()->as_inline_klass()->is_empty()) {
2345     // Load the default instance instead of reading the element
2346     ciInlineKlass* elem_klass = x->array()->declared_type()->as_flat_array_klass()->element_klass()->as_inline_klass();
2347     LIR_Opr result = rlock_result(x, x->elt_type());
2348     assert(elem_klass->is_initialized(), "Must be");
2349     Constant* default_value = new Constant(new InstanceConstant(elem_klass->default_instance()));
2350     if (default_value->is_pinned()) {
2351       __ move(LIR_OprFact::value_type(default_value->type()), result);
2352     } else {
2353       __ move(load_constant(default_value), result);
2354     }
2355   } else {
2356     LIR_Opr result = rlock_result(x, x->elt_type());
2357     LoadFlattenedArrayStub* slow_path = NULL;
2358 
2359     if (x->should_profile() && x->array()->maybe_null_free_array()) {
2360       profile_null_free_array(array, md, load_store);
2361     }
2362 
2363     if (x->elt_type() == T_OBJECT && x->array()->maybe_flattened_array()) {
2364       assert(x->delayed() == NULL, "Delayed LoadIndexed only apply to loaded_flattened_arrays");
2365       index.load_item();
2366       // if we are loading from flattened array, load it using a runtime call
2367       slow_path = new LoadFlattenedArrayStub(array.result(), index.result(), result, state_for(x, x->state_before()));
2368       check_flattened_array(array.result(), LIR_OprFact::illegalOpr, slow_path);
2369       set_in_conditional_code(true);
2370     }
2371 
2372     DecoratorSet decorators = IN_HEAP | IS_ARRAY;
2373     access_load_at(decorators, x->elt_type(),
2374                    array, index.result(), result,
2375                    NULL, null_check_info);
2376 
2377     if (slow_path != NULL) {
2378       __ branch_destination(slow_path->continuation());
2379       set_in_conditional_code(false);
2380     }
2381 
2382     element = x;
2383   }
2384 
2385   if (x->should_profile()) {
2386     profile_element_type(element, md, load_store);
2387   }
2388 }
2389 
2390 void LIRGenerator::do_Deoptimize(Deoptimize* x) {
2391   // This happens only when a class X uses the withfield/aconst_init bytecode
2392   // to refer to an inline class V, where V has not yet been loaded/resolved.
2393   // This is not a common case. Let's just deoptimize.
2394   CodeEmitInfo* info = state_for(x, x->state_before());
2395   CodeStub* stub = new DeoptimizeStub(new CodeEmitInfo(info),
2396                                       Deoptimization::Reason_unloaded,
2397                                       Deoptimization::Action_make_not_entrant);
2398   __ jump(stub);
2399   LIR_Opr reg = rlock_result(x, T_OBJECT);
2400   __ move(LIR_OprFact::oopConst(NULL), reg);
2401 }
2402 
2403 void LIRGenerator::do_NullCheck(NullCheck* x) {
2404   if (x->can_trap()) {
2405     LIRItem value(x->obj(), this);
2406     value.load_item();
2407     CodeEmitInfo* info = state_for(x);
2408     __ null_check(value.result(), info);
2409   }
2410 }
2411 
2412 
2413 void LIRGenerator::do_TypeCast(TypeCast* x) {
2414   LIRItem value(x->obj(), this);
2415   value.load_item();
2416   // the result is the same as from the node we are casting
2417   set_result(x, value.result());
2418 }
2419 
2420 
2421 void LIRGenerator::do_Throw(Throw* x) {
2422   LIRItem exception(x->exception(), this);
2423   exception.load_item();
2424   set_no_result(x);
2425   LIR_Opr exception_opr = exception.result();
2426   CodeEmitInfo* info = state_for(x, x->state());
2427 
2428 #ifndef PRODUCT
2429   if (PrintC1Statistics) {
2430     increment_counter(Runtime1::throw_count_address(), T_INT);
2431   }
2432 #endif
2433 
2434   // check if the instruction has an xhandler in any of the nested scopes
2435   bool unwind = false;
2436   if (info->exception_handlers()->length() == 0) {
2437     // this throw is not inside an xhandler
2438     unwind = true;
2439   } else {
2440     // get some idea of the throw type
2441     bool type_is_exact = true;
2442     ciType* throw_type = x->exception()->exact_type();
2443     if (throw_type == NULL) {
2444       type_is_exact = false;
2445       throw_type = x->exception()->declared_type();
2446     }
2447     if (throw_type != NULL && throw_type->is_instance_klass()) {
2448       ciInstanceKlass* throw_klass = (ciInstanceKlass*)throw_type;
2449       unwind = !x->exception_handlers()->could_catch(throw_klass, type_is_exact);
2450     }
2451   }
2452 
2453   // do null check before moving exception oop into fixed register
2454   // to avoid a fixed interval with an oop during the null check.
2455   // Use a copy of the CodeEmitInfo because debug information is
2456   // different for null_check and throw.
2457   if (x->exception()->as_NewInstance() == NULL && x->exception()->as_ExceptionObject() == NULL) {
2458     // if the exception object wasn't created using new then it might be null.
2459     __ null_check(exception_opr, new CodeEmitInfo(info, x->state()->copy(ValueStack::ExceptionState, x->state()->bci())));
2460   }
2461 
2462   if (compilation()->env()->jvmti_can_post_on_exceptions()) {
2463     // we need to go through the exception lookup path to get JVMTI
2464     // notification done
2465     unwind = false;
2466   }
2467 
2468   // move exception oop into fixed register
2469   __ move(exception_opr, exceptionOopOpr());
2470 
2471   if (unwind) {
2472     __ unwind_exception(exceptionOopOpr());
2473   } else {
2474     __ throw_exception(exceptionPcOpr(), exceptionOopOpr(), info);
2475   }
2476 }
2477 
2478 
2479 void LIRGenerator::do_RoundFP(RoundFP* x) {
2480   assert(strict_fp_requires_explicit_rounding, "not required");
2481 
2482   LIRItem input(x->input(), this);
2483   input.load_item();
2484   LIR_Opr input_opr = input.result();
2485   assert(input_opr->is_register(), "why round if value is not in a register?");
2486   assert(input_opr->is_single_fpu() || input_opr->is_double_fpu(), "input should be floating-point value");
2487   if (input_opr->is_single_fpu()) {
2488     set_result(x, round_item(input_opr)); // This code path not currently taken
2489   } else {
2490     LIR_Opr result = new_register(T_DOUBLE);
2491     set_vreg_flag(result, must_start_in_memory);
2492     __ roundfp(input_opr, LIR_OprFact::illegalOpr, result);
2493     set_result(x, result);
2494   }
2495 }
2496 
2497 
2498 void LIRGenerator::do_UnsafeGet(UnsafeGet* x) {
2499   BasicType type = x->basic_type();
2500   LIRItem src(x->object(), this);
2501   LIRItem off(x->offset(), this);
2502 
2503   off.load_item();
2504   src.load_item();
2505 
2506   DecoratorSet decorators = IN_HEAP | C1_UNSAFE_ACCESS;
2507 
2508   if (x->is_volatile()) {
2509     decorators |= MO_SEQ_CST;
2510   }
2511   if (type == T_BOOLEAN) {
2512     decorators |= C1_MASK_BOOLEAN;
2513   }
2514   if (is_reference_type(type)) {
2515     decorators |= ON_UNKNOWN_OOP_REF;
2516   }
2517 
2518   LIR_Opr result = rlock_result(x, type);
2519   if (!x->is_raw()) {
2520     access_load_at(decorators, type, src, off.result(), result);
2521   } else {
2522     // Currently it is only used in GraphBuilder::setup_osr_entry_block.
2523     // It reads the value from [src + offset] directly.
2524 #ifdef _LP64
2525     LIR_Opr offset = new_register(T_LONG);
2526     __ convert(Bytecodes::_i2l, off.result(), offset);
2527 #else
2528     LIR_Opr offset = off.result();
2529 #endif
2530     LIR_Address* addr = new LIR_Address(src.result(), offset, type);
2531     if (is_reference_type(type)) {
2532       __ move_wide(addr, result);
2533     } else {
2534       __ move(addr, result);
2535     }
2536   }
2537 }
2538 
2539 
2540 void LIRGenerator::do_UnsafePut(UnsafePut* x) {
2541   BasicType type = x->basic_type();
2542   LIRItem src(x->object(), this);
2543   LIRItem off(x->offset(), this);
2544   LIRItem data(x->value(), this);
2545 
2546   src.load_item();
2547   if (type == T_BOOLEAN || type == T_BYTE) {
2548     data.load_byte_item();
2549   } else {
2550     data.load_item();
2551   }
2552   off.load_item();
2553 
2554   set_no_result(x);
2555 
2556   DecoratorSet decorators = IN_HEAP | C1_UNSAFE_ACCESS;
2557   if (is_reference_type(type)) {
2558     decorators |= ON_UNKNOWN_OOP_REF;
2559   }
2560   if (x->is_volatile()) {
2561     decorators |= MO_SEQ_CST;
2562   }
2563   access_store_at(decorators, type, src, off.result(), data.result());
2564 }
2565 
2566 void LIRGenerator::do_UnsafeGetAndSet(UnsafeGetAndSet* x) {
2567   BasicType type = x->basic_type();
2568   LIRItem src(x->object(), this);
2569   LIRItem off(x->offset(), this);
2570   LIRItem value(x->value(), this);
2571 
2572   DecoratorSet decorators = IN_HEAP | C1_UNSAFE_ACCESS | MO_SEQ_CST;
2573 
2574   if (is_reference_type(type)) {
2575     decorators |= ON_UNKNOWN_OOP_REF;
2576   }
2577 
2578   LIR_Opr result;
2579   if (x->is_add()) {
2580     result = access_atomic_add_at(decorators, type, src, off, value);
2581   } else {
2582     result = access_atomic_xchg_at(decorators, type, src, off, value);
2583   }
2584   set_result(x, result);
2585 }
2586 
2587 void LIRGenerator::do_SwitchRanges(SwitchRangeArray* x, LIR_Opr value, BlockBegin* default_sux) {
2588   int lng = x->length();
2589 
2590   for (int i = 0; i < lng; i++) {
2591     C1SwitchRange* one_range = x->at(i);
2592     int low_key = one_range->low_key();
2593     int high_key = one_range->high_key();
2594     BlockBegin* dest = one_range->sux();
2595     if (low_key == high_key) {
2596       __ cmp(lir_cond_equal, value, low_key);
2597       __ branch(lir_cond_equal, dest);
2598     } else if (high_key - low_key == 1) {
2599       __ cmp(lir_cond_equal, value, low_key);
2600       __ branch(lir_cond_equal, dest);
2601       __ cmp(lir_cond_equal, value, high_key);
2602       __ branch(lir_cond_equal, dest);
2603     } else {
2604       LabelObj* L = new LabelObj();
2605       __ cmp(lir_cond_less, value, low_key);
2606       __ branch(lir_cond_less, L->label());
2607       __ cmp(lir_cond_lessEqual, value, high_key);
2608       __ branch(lir_cond_lessEqual, dest);
2609       __ branch_destination(L->label());
2610     }
2611   }
2612   __ jump(default_sux);
2613 }
2614 
2615 
2616 SwitchRangeArray* LIRGenerator::create_lookup_ranges(TableSwitch* x) {
2617   SwitchRangeList* res = new SwitchRangeList();
2618   int len = x->length();
2619   if (len > 0) {
2620     BlockBegin* sux = x->sux_at(0);
2621     int key = x->lo_key();
2622     BlockBegin* default_sux = x->default_sux();
2623     C1SwitchRange* range = new C1SwitchRange(key, sux);
2624     for (int i = 0; i < len; i++, key++) {
2625       BlockBegin* new_sux = x->sux_at(i);
2626       if (sux == new_sux) {
2627         // still in same range
2628         range->set_high_key(key);
2629       } else {
2630         // skip tests which explicitly dispatch to the default
2631         if (sux != default_sux) {
2632           res->append(range);
2633         }
2634         range = new C1SwitchRange(key, new_sux);
2635       }
2636       sux = new_sux;
2637     }
2638     if (res->length() == 0 || res->last() != range)  res->append(range);
2639   }
2640   return res;
2641 }
2642 
2643 
2644 // we expect the keys to be sorted by increasing value
2645 SwitchRangeArray* LIRGenerator::create_lookup_ranges(LookupSwitch* x) {
2646   SwitchRangeList* res = new SwitchRangeList();
2647   int len = x->length();
2648   if (len > 0) {
2649     BlockBegin* default_sux = x->default_sux();
2650     int key = x->key_at(0);
2651     BlockBegin* sux = x->sux_at(0);
2652     C1SwitchRange* range = new C1SwitchRange(key, sux);
2653     for (int i = 1; i < len; i++) {
2654       int new_key = x->key_at(i);
2655       BlockBegin* new_sux = x->sux_at(i);
2656       if (key+1 == new_key && sux == new_sux) {
2657         // still in same range
2658         range->set_high_key(new_key);
2659       } else {
2660         // skip tests which explicitly dispatch to the default
2661         if (range->sux() != default_sux) {
2662           res->append(range);
2663         }
2664         range = new C1SwitchRange(new_key, new_sux);
2665       }
2666       key = new_key;
2667       sux = new_sux;
2668     }
2669     if (res->length() == 0 || res->last() != range)  res->append(range);
2670   }
2671   return res;
2672 }
2673 
2674 
2675 void LIRGenerator::do_TableSwitch(TableSwitch* x) {
2676   LIRItem tag(x->tag(), this);
2677   tag.load_item();
2678   set_no_result(x);
2679 
2680   if (x->is_safepoint()) {
2681     __ safepoint(safepoint_poll_register(), state_for(x, x->state_before()));
2682   }
2683 
2684   // move values into phi locations
2685   move_to_phi(x->state());
2686 
2687   int lo_key = x->lo_key();
2688   int len = x->length();
2689   assert(lo_key <= (lo_key + (len - 1)), "integer overflow");
2690   LIR_Opr value = tag.result();
2691 
2692   if (compilation()->env()->comp_level() == CompLevel_full_profile && UseSwitchProfiling) {
2693     ciMethod* method = x->state()->scope()->method();
2694     ciMethodData* md = method->method_data_or_null();
2695     assert(md != NULL, "Sanity");
2696     ciProfileData* data = md->bci_to_data(x->state()->bci());
2697     assert(data != NULL, "must have profiling data");
2698     assert(data->is_MultiBranchData(), "bad profile data?");
2699     int default_count_offset = md->byte_offset_of_slot(data, MultiBranchData::default_count_offset());
2700     LIR_Opr md_reg = new_register(T_METADATA);
2701     __ metadata2reg(md->constant_encoding(), md_reg);
2702     LIR_Opr data_offset_reg = new_pointer_register();
2703     LIR_Opr tmp_reg = new_pointer_register();
2704 
2705     __ move(LIR_OprFact::intptrConst(default_count_offset), data_offset_reg);
2706     for (int i = 0; i < len; i++) {
2707       int count_offset = md->byte_offset_of_slot(data, MultiBranchData::case_count_offset(i));
2708       __ cmp(lir_cond_equal, value, i + lo_key);
2709       __ move(data_offset_reg, tmp_reg);
2710       __ cmove(lir_cond_equal,
2711                LIR_OprFact::intptrConst(count_offset),
2712                tmp_reg,
2713                data_offset_reg, T_INT);
2714     }
2715 
2716     LIR_Opr data_reg = new_pointer_register();
2717     LIR_Address* data_addr = new LIR_Address(md_reg, data_offset_reg, data_reg->type());
2718     __ move(data_addr, data_reg);
2719     __ add(data_reg, LIR_OprFact::intptrConst(1), data_reg);
2720     __ move(data_reg, data_addr);
2721   }
2722 
2723   if (UseTableRanges) {
2724     do_SwitchRanges(create_lookup_ranges(x), value, x->default_sux());
2725   } else {
2726     for (int i = 0; i < len; i++) {
2727       __ cmp(lir_cond_equal, value, i + lo_key);
2728       __ branch(lir_cond_equal, x->sux_at(i));
2729     }
2730     __ jump(x->default_sux());
2731   }
2732 }
2733 
2734 
2735 void LIRGenerator::do_LookupSwitch(LookupSwitch* x) {
2736   LIRItem tag(x->tag(), this);
2737   tag.load_item();
2738   set_no_result(x);
2739 
2740   if (x->is_safepoint()) {
2741     __ safepoint(safepoint_poll_register(), state_for(x, x->state_before()));
2742   }
2743 
2744   // move values into phi locations
2745   move_to_phi(x->state());
2746 
2747   LIR_Opr value = tag.result();
2748   int len = x->length();
2749 
2750   if (compilation()->env()->comp_level() == CompLevel_full_profile && UseSwitchProfiling) {
2751     ciMethod* method = x->state()->scope()->method();
2752     ciMethodData* md = method->method_data_or_null();
2753     assert(md != NULL, "Sanity");
2754     ciProfileData* data = md->bci_to_data(x->state()->bci());
2755     assert(data != NULL, "must have profiling data");
2756     assert(data->is_MultiBranchData(), "bad profile data?");
2757     int default_count_offset = md->byte_offset_of_slot(data, MultiBranchData::default_count_offset());
2758     LIR_Opr md_reg = new_register(T_METADATA);
2759     __ metadata2reg(md->constant_encoding(), md_reg);
2760     LIR_Opr data_offset_reg = new_pointer_register();
2761     LIR_Opr tmp_reg = new_pointer_register();
2762 
2763     __ move(LIR_OprFact::intptrConst(default_count_offset), data_offset_reg);
2764     for (int i = 0; i < len; i++) {
2765       int count_offset = md->byte_offset_of_slot(data, MultiBranchData::case_count_offset(i));
2766       __ cmp(lir_cond_equal, value, x->key_at(i));
2767       __ move(data_offset_reg, tmp_reg);
2768       __ cmove(lir_cond_equal,
2769                LIR_OprFact::intptrConst(count_offset),
2770                tmp_reg,
2771                data_offset_reg, T_INT);
2772     }
2773 
2774     LIR_Opr data_reg = new_pointer_register();
2775     LIR_Address* data_addr = new LIR_Address(md_reg, data_offset_reg, data_reg->type());
2776     __ move(data_addr, data_reg);
2777     __ add(data_reg, LIR_OprFact::intptrConst(1), data_reg);
2778     __ move(data_reg, data_addr);
2779   }
2780 
2781   if (UseTableRanges) {
2782     do_SwitchRanges(create_lookup_ranges(x), value, x->default_sux());
2783   } else {
2784     int len = x->length();
2785     for (int i = 0; i < len; i++) {
2786       __ cmp(lir_cond_equal, value, x->key_at(i));
2787       __ branch(lir_cond_equal, x->sux_at(i));
2788     }
2789     __ jump(x->default_sux());
2790   }
2791 }
2792 
2793 
2794 void LIRGenerator::do_Goto(Goto* x) {
2795   set_no_result(x);
2796 
2797   if (block()->next()->as_OsrEntry()) {
2798     // need to free up storage used for OSR entry point
2799     LIR_Opr osrBuffer = block()->next()->operand();
2800     BasicTypeList signature;
2801     signature.append(NOT_LP64(T_INT) LP64_ONLY(T_LONG)); // pass a pointer to osrBuffer
2802     CallingConvention* cc = frame_map()->c_calling_convention(&signature);
2803     __ move(osrBuffer, cc->args()->at(0));
2804     __ call_runtime_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::OSR_migration_end),
2805                          getThreadTemp(), LIR_OprFact::illegalOpr, cc->args());
2806   }
2807 
2808   if (x->is_safepoint()) {
2809     ValueStack* state = x->state_before() ? x->state_before() : x->state();
2810 
2811     // increment backedge counter if needed
2812     CodeEmitInfo* info = state_for(x, state);
2813     increment_backedge_counter(info, x->profiled_bci());
2814     CodeEmitInfo* safepoint_info = state_for(x, state);
2815     __ safepoint(safepoint_poll_register(), safepoint_info);
2816   }
2817 
2818   // Gotos can be folded Ifs, handle this case.
2819   if (x->should_profile()) {
2820     ciMethod* method = x->profiled_method();
2821     assert(method != NULL, "method should be set if branch is profiled");
2822     ciMethodData* md = method->method_data_or_null();
2823     assert(md != NULL, "Sanity");
2824     ciProfileData* data = md->bci_to_data(x->profiled_bci());
2825     assert(data != NULL, "must have profiling data");
2826     int offset;
2827     if (x->direction() == Goto::taken) {
2828       assert(data->is_BranchData(), "need BranchData for two-way branches");
2829       offset = md->byte_offset_of_slot(data, BranchData::taken_offset());
2830     } else if (x->direction() == Goto::not_taken) {
2831       assert(data->is_BranchData(), "need BranchData for two-way branches");
2832       offset = md->byte_offset_of_slot(data, BranchData::not_taken_offset());
2833     } else {
2834       assert(data->is_JumpData(), "need JumpData for branches");
2835       offset = md->byte_offset_of_slot(data, JumpData::taken_offset());
2836     }
2837     LIR_Opr md_reg = new_register(T_METADATA);
2838     __ metadata2reg(md->constant_encoding(), md_reg);
2839 
2840     increment_counter(new LIR_Address(md_reg, offset,
2841                                       NOT_LP64(T_INT) LP64_ONLY(T_LONG)), DataLayout::counter_increment);
2842   }
2843 
2844   // emit phi-instruction move after safepoint since this simplifies
2845   // describing the state as the safepoint.
2846   move_to_phi(x->state());
2847 
2848   __ jump(x->default_sux());
2849 }
2850 
2851 /**
2852  * Emit profiling code if needed for arguments, parameters, return value types
2853  *
2854  * @param md                    MDO the code will update at runtime
2855  * @param md_base_offset        common offset in the MDO for this profile and subsequent ones
2856  * @param md_offset             offset in the MDO (on top of md_base_offset) for this profile
2857  * @param profiled_k            current profile
2858  * @param obj                   IR node for the object to be profiled
2859  * @param mdp                   register to hold the pointer inside the MDO (md + md_base_offset).
2860  *                              Set once we find an update to make and use for next ones.
2861  * @param not_null              true if we know obj cannot be null
2862  * @param signature_at_call_k   signature at call for obj
2863  * @param callee_signature_k    signature of callee for obj
2864  *                              at call and callee signatures differ at method handle call
2865  * @return                      the only klass we know will ever be seen at this profile point
2866  */
2867 ciKlass* LIRGenerator::profile_type(ciMethodData* md, int md_base_offset, int md_offset, intptr_t profiled_k,
2868                                     Value obj, LIR_Opr& mdp, bool not_null, ciKlass* signature_at_call_k,
2869                                     ciKlass* callee_signature_k) {
2870   ciKlass* result = NULL;
2871   bool do_null = !not_null && !TypeEntries::was_null_seen(profiled_k);
2872   bool do_update = !TypeEntries::is_type_unknown(profiled_k);
2873   // known not to be null or null bit already set and already set to
2874   // unknown: nothing we can do to improve profiling
2875   if (!do_null && !do_update) {
2876     return result;
2877   }
2878 
2879   ciKlass* exact_klass = NULL;
2880   Compilation* comp = Compilation::current();
2881   if (do_update) {
2882     // try to find exact type, using CHA if possible, so that loading
2883     // the klass from the object can be avoided
2884     ciType* type = obj->exact_type();
2885     if (type == NULL) {
2886       type = obj->declared_type();
2887       type = comp->cha_exact_type(type);
2888     }
2889     assert(type == NULL || type->is_klass(), "type should be class");
2890     exact_klass = (type != NULL && type->is_loaded()) ? (ciKlass*)type : NULL;
2891 
2892     do_update = exact_klass == NULL || ciTypeEntries::valid_ciklass(profiled_k) != exact_klass;
2893   }
2894 
2895   if (!do_null && !do_update) {
2896     return result;
2897   }
2898 
2899   ciKlass* exact_signature_k = NULL;
2900   if (do_update && signature_at_call_k != NULL) {
2901     // Is the type from the signature exact (the only one possible)?
2902     exact_signature_k = signature_at_call_k->exact_klass();
2903     if (exact_signature_k == NULL) {
2904       exact_signature_k = comp->cha_exact_type(signature_at_call_k);
2905     } else {
2906       result = exact_signature_k;
2907       // Known statically. No need to emit any code: prevent
2908       // LIR_Assembler::emit_profile_type() from emitting useless code
2909       profiled_k = ciTypeEntries::with_status(result, profiled_k);
2910     }
2911     // exact_klass and exact_signature_k can be both non NULL but
2912     // different if exact_klass is loaded after the ciObject for
2913     // exact_signature_k is created.
2914     if (exact_klass == NULL && exact_signature_k != NULL && exact_klass != exact_signature_k) {
2915       // sometimes the type of the signature is better than the best type
2916       // the compiler has
2917       exact_klass = exact_signature_k;
2918     }
2919     if (callee_signature_k != NULL &&
2920         callee_signature_k != signature_at_call_k) {
2921       ciKlass* improved_klass = callee_signature_k->exact_klass();
2922       if (improved_klass == NULL) {
2923         improved_klass = comp->cha_exact_type(callee_signature_k);
2924       }
2925       if (exact_klass == NULL && improved_klass != NULL && exact_klass != improved_klass) {
2926         exact_klass = exact_signature_k;
2927       }
2928     }
2929     do_update = exact_klass == NULL || ciTypeEntries::valid_ciklass(profiled_k) != exact_klass;
2930   }
2931 
2932   if (!do_null && !do_update) {
2933     return result;
2934   }
2935 
2936   if (mdp == LIR_OprFact::illegalOpr) {
2937     mdp = new_register(T_METADATA);
2938     __ metadata2reg(md->constant_encoding(), mdp);
2939     if (md_base_offset != 0) {
2940       LIR_Address* base_type_address = new LIR_Address(mdp, md_base_offset, T_ADDRESS);
2941       mdp = new_pointer_register();
2942       __ leal(LIR_OprFact::address(base_type_address), mdp);
2943     }
2944   }
2945   LIRItem value(obj, this);
2946   value.load_item();
2947   __ profile_type(new LIR_Address(mdp, md_offset, T_METADATA),
2948                   value.result(), exact_klass, profiled_k, new_pointer_register(), not_null, exact_signature_k != NULL);
2949   return result;
2950 }
2951 
2952 // profile parameters on entry to the root of the compilation
2953 void LIRGenerator::profile_parameters(Base* x) {
2954   if (compilation()->profile_parameters()) {
2955     CallingConvention* args = compilation()->frame_map()->incoming_arguments();
2956     ciMethodData* md = scope()->method()->method_data_or_null();
2957     assert(md != NULL, "Sanity");
2958 
2959     if (md->parameters_type_data() != NULL) {
2960       ciParametersTypeData* parameters_type_data = md->parameters_type_data();
2961       ciTypeStackSlotEntries* parameters =  parameters_type_data->parameters();
2962       LIR_Opr mdp = LIR_OprFact::illegalOpr;
2963       for (int java_index = 0, i = 0, j = 0; j < parameters_type_data->number_of_parameters(); i++) {
2964         LIR_Opr src = args->at(i);
2965         assert(!src->is_illegal(), "check");
2966         BasicType t = src->type();
2967         if (is_reference_type(t)) {
2968           intptr_t profiled_k = parameters->type(j);
2969           Local* local = x->state()->local_at(java_index)->as_Local();
2970           ciKlass* exact = profile_type(md, md->byte_offset_of_slot(parameters_type_data, ParametersTypeData::type_offset(0)),
2971                                         in_bytes(ParametersTypeData::type_offset(j)) - in_bytes(ParametersTypeData::type_offset(0)),
2972                                         profiled_k, local, mdp, false, local->declared_type()->as_klass(), NULL);
2973           // If the profile is known statically set it once for all and do not emit any code
2974           if (exact != NULL) {
2975             md->set_parameter_type(j, exact);
2976           }
2977           j++;
2978         }
2979         java_index += type2size[t];
2980       }
2981     }
2982   }
2983 }
2984 
2985 void LIRGenerator::profile_flags(ciMethodData* md, ciProfileData* data, int flag, LIR_Condition condition) {
2986   assert(md != NULL && data != NULL, "should have been initialized");
2987   LIR_Opr mdp = new_register(T_METADATA);
2988   __ metadata2reg(md->constant_encoding(), mdp);
2989   LIR_Address* addr = new LIR_Address(mdp, md->byte_offset_of_slot(data, DataLayout::flags_offset()), T_BYTE);
2990   LIR_Opr flags = new_register(T_INT);
2991   __ move(addr, flags);
2992   if (condition != lir_cond_always) {
2993     LIR_Opr update = new_register(T_INT);
2994     __ cmove(condition, LIR_OprFact::intConst(0), LIR_OprFact::intConst(flag), update, T_INT);
2995   } else {
2996     __ logical_or(flags, LIR_OprFact::intConst(flag), flags);
2997   }
2998   __ store(flags, addr);
2999 }
3000 
3001 void LIRGenerator::profile_null_free_array(LIRItem array, ciMethodData* md, ciArrayLoadStoreData* load_store) {
3002   assert(compilation()->profile_array_accesses(), "array access profiling is disabled");
3003   LabelObj* L_end = new LabelObj();
3004   LIR_Opr tmp = new_register(T_METADATA);
3005   __ check_null_free_array(array.result(), tmp);
3006 
3007   profile_flags(md, load_store, ArrayLoadStoreData::null_free_array_byte_constant(), lir_cond_equal);
3008 }
3009 
3010 void LIRGenerator::profile_array_type(AccessIndexed* x, ciMethodData*& md, ciArrayLoadStoreData*& load_store) {
3011   assert(compilation()->profile_array_accesses(), "array access profiling is disabled");
3012   int bci = x->profiled_bci();
3013   md = x->profiled_method()->method_data();
3014   assert(md != NULL, "Sanity");
3015   ciProfileData* data = md->bci_to_data(bci);
3016   assert(data != NULL && data->is_ArrayLoadStoreData(), "incorrect profiling entry");
3017   load_store = (ciArrayLoadStoreData*)data;
3018   LIR_Opr mdp = LIR_OprFact::illegalOpr;
3019   profile_type(md, md->byte_offset_of_slot(load_store, ArrayLoadStoreData::array_offset()), 0,
3020                load_store->array()->type(), x->array(), mdp, true, NULL, NULL);
3021 }
3022 
3023 void LIRGenerator::profile_element_type(Value element, ciMethodData* md, ciArrayLoadStoreData* load_store) {
3024   assert(compilation()->profile_array_accesses(), "array access profiling is disabled");
3025   assert(md != NULL && load_store != NULL, "should have been initialized");
3026   LIR_Opr mdp = LIR_OprFact::illegalOpr;
3027   profile_type(md, md->byte_offset_of_slot(load_store, ArrayLoadStoreData::element_offset()), 0,
3028                load_store->element()->type(), element, mdp, false, NULL, NULL);
3029 }
3030 
3031 void LIRGenerator::do_Base(Base* x) {
3032   __ std_entry(LIR_OprFact::illegalOpr);
3033   // Emit moves from physical registers / stack slots to virtual registers
3034   CallingConvention* args = compilation()->frame_map()->incoming_arguments();
3035   IRScope* irScope = compilation()->hir()->top_scope();
3036   int java_index = 0;
3037   for (int i = 0; i < args->length(); i++) {
3038     LIR_Opr src = args->at(i);
3039     assert(!src->is_illegal(), "check");
3040     BasicType t = src->type();
3041 
3042     // Types which are smaller than int are passed as int, so
3043     // correct the type which passed.
3044     switch (t) {
3045     case T_BYTE:
3046     case T_BOOLEAN:
3047     case T_SHORT:
3048     case T_CHAR:
3049       t = T_INT;
3050       break;
3051     default:
3052       break;
3053     }
3054 
3055     LIR_Opr dest = new_register(t);
3056     __ move(src, dest);
3057 
3058     // Assign new location to Local instruction for this local
3059     Local* local = x->state()->local_at(java_index)->as_Local();
3060     assert(local != NULL, "Locals for incoming arguments must have been created");
3061 #ifndef __SOFTFP__
3062     // The java calling convention passes double as long and float as int.
3063     assert(as_ValueType(t)->tag() == local->type()->tag(), "check");
3064 #endif // __SOFTFP__
3065     local->set_operand(dest);
3066     _instruction_for_operand.at_put_grow(dest->vreg_number(), local, NULL);
3067     java_index += type2size[t];
3068   }
3069 
3070   if (compilation()->env()->dtrace_method_probes()) {
3071     BasicTypeList signature;
3072     signature.append(LP64_ONLY(T_LONG) NOT_LP64(T_INT));    // thread
3073     signature.append(T_METADATA); // Method*
3074     LIR_OprList* args = new LIR_OprList();
3075     args->append(getThreadPointer());
3076     LIR_Opr meth = new_register(T_METADATA);
3077     __ metadata2reg(method()->constant_encoding(), meth);
3078     args->append(meth);
3079     call_runtime(&signature, args, CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry), voidType, NULL);
3080   }
3081 
3082   if (method()->is_synchronized()) {
3083     LIR_Opr obj;
3084     if (method()->is_static()) {
3085       obj = new_register(T_OBJECT);
3086       __ oop2reg(method()->holder()->java_mirror()->constant_encoding(), obj);
3087     } else {
3088       Local* receiver = x->state()->local_at(0)->as_Local();
3089       assert(receiver != NULL, "must already exist");
3090       obj = receiver->operand();
3091     }
3092     assert(obj->is_valid(), "must be valid");
3093 
3094     if (method()->is_synchronized() && GenerateSynchronizationCode) {
3095       LIR_Opr lock = syncLockOpr();
3096       __ load_stack_address_monitor(0, lock);
3097 
3098       CodeEmitInfo* info = new CodeEmitInfo(scope()->start()->state()->copy(ValueStack::StateBefore, SynchronizationEntryBCI), NULL, x->check_flag(Instruction::DeoptimizeOnException));
3099       CodeStub* slow_path = new MonitorEnterStub(obj, lock, info);
3100 
3101       // receiver is guaranteed non-NULL so don't need CodeEmitInfo
3102       __ lock_object(syncTempOpr(), obj, lock, new_register(T_OBJECT), slow_path, NULL);
3103     }
3104   }
3105   if (compilation()->age_code()) {
3106     CodeEmitInfo* info = new CodeEmitInfo(scope()->start()->state()->copy(ValueStack::StateBefore, 0), NULL, false);
3107     decrement_age(info);
3108   }
3109   // increment invocation counters if needed
3110   if (!method()->is_accessor()) { // Accessors do not have MDOs, so no counting.
3111     profile_parameters(x);
3112     CodeEmitInfo* info = new CodeEmitInfo(scope()->start()->state()->copy(ValueStack::StateBefore, SynchronizationEntryBCI), NULL, false);
3113     increment_invocation_counter(info);
3114   }
3115   if (method()->has_scalarized_args()) {
3116     // Check if deoptimization was triggered (i.e. orig_pc was set) while buffering scalarized inline type arguments
3117     // in the entry point (see comments in frame::deoptimize). If so, deoptimize only now that we have the right state.
3118     CodeEmitInfo* info = new CodeEmitInfo(scope()->start()->state()->copy(ValueStack::StateBefore, 0), NULL, false);
3119     CodeStub* deopt_stub = new DeoptimizeStub(info, Deoptimization::Reason_none, Deoptimization::Action_none);
3120     __ append(new LIR_Op0(lir_check_orig_pc));
3121     __ branch(lir_cond_notEqual, deopt_stub);
3122   }
3123 
3124   // all blocks with a successor must end with an unconditional jump
3125   // to the successor even if they are consecutive
3126   __ jump(x->default_sux());
3127 }
3128 
3129 
3130 void LIRGenerator::do_OsrEntry(OsrEntry* x) {
3131   // construct our frame and model the production of incoming pointer
3132   // to the OSR buffer.
3133   __ osr_entry(LIR_Assembler::osrBufferPointer());
3134   LIR_Opr result = rlock_result(x);
3135   __ move(LIR_Assembler::osrBufferPointer(), result);
3136 }
3137 
3138 void LIRGenerator::invoke_load_one_argument(LIRItem* param, LIR_Opr loc) {
3139   if (loc->is_register()) {
3140     param->load_item_force(loc);
3141   } else {
3142     LIR_Address* addr = loc->as_address_ptr();
3143     param->load_for_store(addr->type());
3144     assert(addr->type() != T_PRIMITIVE_OBJECT, "not supported yet");
3145     if (addr->type() == T_OBJECT) {
3146       __ move_wide(param->result(), addr);
3147     } else {
3148       __ move(param->result(), addr);
3149     }
3150   }
3151 }
3152 
3153 void LIRGenerator::invoke_load_arguments(Invoke* x, LIRItemList* args, const LIR_OprList* arg_list) {
3154   assert(args->length() == arg_list->length(),
3155          "args=%d, arg_list=%d", args->length(), arg_list->length());
3156   for (int i = x->has_receiver() ? 1 : 0; i < args->length(); i++) {
3157     LIRItem* param = args->at(i);
3158     LIR_Opr loc = arg_list->at(i);
3159     invoke_load_one_argument(param, loc);
3160   }
3161 
3162   if (x->has_receiver()) {
3163     LIRItem* receiver = args->at(0);
3164     LIR_Opr loc = arg_list->at(0);
3165     if (loc->is_register()) {
3166       receiver->load_item_force(loc);
3167     } else {
3168       assert(loc->is_address(), "just checking");
3169       receiver->load_for_store(T_OBJECT);
3170       __ move_wide(receiver->result(), loc->as_address_ptr());
3171     }
3172   }
3173 }
3174 
3175 
3176 // Visits all arguments, returns appropriate items without loading them
3177 LIRItemList* LIRGenerator::invoke_visit_arguments(Invoke* x) {
3178   LIRItemList* argument_items = new LIRItemList();
3179   if (x->has_receiver()) {
3180     LIRItem* receiver = new LIRItem(x->receiver(), this);
3181     argument_items->append(receiver);
3182   }
3183   for (int i = 0; i < x->number_of_arguments(); i++) {
3184     LIRItem* param = new LIRItem(x->argument_at(i), this);
3185     argument_items->append(param);
3186   }
3187   return argument_items;
3188 }
3189 
3190 
3191 // The invoke with receiver has following phases:
3192 //   a) traverse and load/lock receiver;
3193 //   b) traverse all arguments -> item-array (invoke_visit_argument)
3194 //   c) push receiver on stack
3195 //   d) load each of the items and push on stack
3196 //   e) unlock receiver
3197 //   f) move receiver into receiver-register %o0
3198 //   g) lock result registers and emit call operation
3199 //
3200 // Before issuing a call, we must spill-save all values on stack
3201 // that are in caller-save register. "spill-save" moves those registers
3202 // either in a free callee-save register or spills them if no free
3203 // callee save register is available.
3204 //
3205 // The problem is where to invoke spill-save.
3206 // - if invoked between e) and f), we may lock callee save
3207 //   register in "spill-save" that destroys the receiver register
3208 //   before f) is executed
3209 // - if we rearrange f) to be earlier (by loading %o0) it
3210 //   may destroy a value on the stack that is currently in %o0
3211 //   and is waiting to be spilled
3212 // - if we keep the receiver locked while doing spill-save,
3213 //   we cannot spill it as it is spill-locked
3214 //
3215 void LIRGenerator::do_Invoke(Invoke* x) {
3216   CallingConvention* cc = frame_map()->java_calling_convention(x->signature(), true);
3217 
3218   LIR_OprList* arg_list = cc->args();
3219   LIRItemList* args = invoke_visit_arguments(x);
3220   LIR_Opr receiver = LIR_OprFact::illegalOpr;
3221 
3222   // setup result register
3223   LIR_Opr result_register = LIR_OprFact::illegalOpr;
3224   if (x->type() != voidType) {
3225     result_register = result_register_for(x->type());
3226   }
3227 
3228   CodeEmitInfo* info = state_for(x, x->state());
3229 
3230   invoke_load_arguments(x, args, arg_list);
3231 
3232   if (x->has_receiver()) {
3233     args->at(0)->load_item_force(LIR_Assembler::receiverOpr());
3234     receiver = args->at(0)->result();
3235   }
3236 
3237   // emit invoke code
3238   assert(receiver->is_illegal() || receiver->is_equal(LIR_Assembler::receiverOpr()), "must match");
3239 
3240   // JSR 292
3241   // Preserve the SP over MethodHandle call sites, if needed.
3242   ciMethod* target = x->target();
3243   bool is_method_handle_invoke = (// %%% FIXME: Are both of these relevant?
3244                                   target->is_method_handle_intrinsic() ||
3245                                   target->is_compiled_lambda_form());
3246   if (is_method_handle_invoke) {
3247     info->set_is_method_handle_invoke(true);
3248     if(FrameMap::method_handle_invoke_SP_save_opr() != LIR_OprFact::illegalOpr) {
3249         __ move(FrameMap::stack_pointer(), FrameMap::method_handle_invoke_SP_save_opr());
3250     }
3251   }
3252 
3253   switch (x->code()) {
3254     case Bytecodes::_invokestatic:
3255       __ call_static(target, result_register,
3256                      SharedRuntime::get_resolve_static_call_stub(),
3257                      arg_list, info);
3258       break;
3259     case Bytecodes::_invokespecial:
3260     case Bytecodes::_invokevirtual:
3261     case Bytecodes::_invokeinterface:
3262       // for loaded and final (method or class) target we still produce an inline cache,
3263       // in order to be able to call mixed mode
3264       if (x->code() == Bytecodes::_invokespecial || x->target_is_final()) {
3265         __ call_opt_virtual(target, receiver, result_register,
3266                             SharedRuntime::get_resolve_opt_virtual_call_stub(),
3267                             arg_list, info);
3268       } else {
3269         __ call_icvirtual(target, receiver, result_register,
3270                           SharedRuntime::get_resolve_virtual_call_stub(),
3271                           arg_list, info);
3272       }
3273       break;
3274     case Bytecodes::_invokedynamic: {
3275       __ call_dynamic(target, receiver, result_register,
3276                       SharedRuntime::get_resolve_static_call_stub(),
3277                       arg_list, info);
3278       break;
3279     }
3280     default:
3281       fatal("unexpected bytecode: %s", Bytecodes::name(x->code()));
3282       break;
3283   }
3284 
3285   // JSR 292
3286   // Restore the SP after MethodHandle call sites, if needed.
3287   if (is_method_handle_invoke
3288       && FrameMap::method_handle_invoke_SP_save_opr() != LIR_OprFact::illegalOpr) {
3289     __ move(FrameMap::method_handle_invoke_SP_save_opr(), FrameMap::stack_pointer());
3290   }
3291 
3292   if (result_register->is_valid()) {
3293     LIR_Opr result = rlock_result(x);
3294     __ move(result_register, result);
3295   }
3296 }
3297 
3298 
3299 void LIRGenerator::do_FPIntrinsics(Intrinsic* x) {
3300   assert(x->number_of_arguments() == 1, "wrong type");
3301   LIRItem value       (x->argument_at(0), this);
3302   LIR_Opr reg = rlock_result(x);
3303   value.load_item();
3304   LIR_Opr tmp = force_to_spill(value.result(), as_BasicType(x->type()));
3305   __ move(tmp, reg);
3306 }
3307 
3308 
3309 
3310 // Code for  :  x->x() {x->cond()} x->y() ? x->tval() : x->fval()
3311 void LIRGenerator::do_IfOp(IfOp* x) {
3312 #ifdef ASSERT
3313   {
3314     ValueTag xtag = x->x()->type()->tag();
3315     ValueTag ttag = x->tval()->type()->tag();
3316     assert(xtag == intTag || xtag == objectTag, "cannot handle others");
3317     assert(ttag == addressTag || ttag == intTag || ttag == objectTag || ttag == longTag, "cannot handle others");
3318     assert(ttag == x->fval()->type()->tag(), "cannot handle others");
3319   }
3320 #endif
3321 
3322   LIRItem left(x->x(), this);
3323   LIRItem right(x->y(), this);
3324   left.load_item();
3325   if (can_inline_as_constant(right.value()) && !x->substitutability_check()) {
3326     right.dont_load_item();
3327   } else {
3328     // substitutability_check() needs to use right as a base register.
3329     right.load_item();
3330   }
3331 
3332   LIRItem t_val(x->tval(), this);
3333   LIRItem f_val(x->fval(), this);
3334   t_val.dont_load_item();
3335   f_val.dont_load_item();
3336 
3337   if (x->substitutability_check()) {
3338     substitutability_check(x, left, right, t_val, f_val);
3339   } else {
3340     LIR_Opr reg = rlock_result(x);
3341     __ cmp(lir_cond(x->cond()), left.result(), right.result());
3342     __ cmove(lir_cond(x->cond()), t_val.result(), f_val.result(), reg, as_BasicType(x->x()->type()));
3343   }
3344 }
3345 
3346 void LIRGenerator::substitutability_check(IfOp* x, LIRItem& left, LIRItem& right, LIRItem& t_val, LIRItem& f_val) {
3347   assert(x->cond() == If::eql || x->cond() == If::neq, "must be");
3348   bool is_acmpeq = (x->cond() == If::eql);
3349   LIR_Opr equal_result     = is_acmpeq ? t_val.result() : f_val.result();
3350   LIR_Opr not_equal_result = is_acmpeq ? f_val.result() : t_val.result();
3351   LIR_Opr result = rlock_result(x);
3352   CodeEmitInfo* info = state_for(x, x->state_before());
3353 
3354   substitutability_check_common(x->x(), x->y(), left, right, equal_result, not_equal_result, result, info);
3355 }
3356 
3357 void LIRGenerator::substitutability_check(If* x, LIRItem& left, LIRItem& right) {
3358   LIR_Opr equal_result     = LIR_OprFact::intConst(1);
3359   LIR_Opr not_equal_result = LIR_OprFact::intConst(0);
3360   LIR_Opr result = new_register(T_INT);
3361   CodeEmitInfo* info = state_for(x, x->state_before());
3362 
3363   substitutability_check_common(x->x(), x->y(), left, right, equal_result, not_equal_result, result, info);
3364 
3365   assert(x->cond() == If::eql || x->cond() == If::neq, "must be");
3366   __ cmp(lir_cond(x->cond()), result, equal_result);
3367 }
3368 
3369 void LIRGenerator::substitutability_check_common(Value left_val, Value right_val, LIRItem& left, LIRItem& right,
3370                                                  LIR_Opr equal_result, LIR_Opr not_equal_result, LIR_Opr result,
3371                                                  CodeEmitInfo* info) {
3372   LIR_Opr tmp1 = LIR_OprFact::illegalOpr;
3373   LIR_Opr tmp2 = LIR_OprFact::illegalOpr;
3374   LIR_Opr left_klass_op = LIR_OprFact::illegalOpr;
3375   LIR_Opr right_klass_op = LIR_OprFact::illegalOpr;
3376 
3377   ciKlass* left_klass  = left_val ->as_loaded_klass_or_null();
3378   ciKlass* right_klass = right_val->as_loaded_klass_or_null();
3379 
3380   if ((left_klass == NULL || right_klass == NULL) ||// The klass is still unloaded, or came from a Phi node.
3381       !left_klass->is_inlinetype() || !right_klass->is_inlinetype()) {
3382     init_temps_for_substitutability_check(tmp1, tmp2);
3383   }
3384 
3385   if (left_klass != NULL && left_klass->is_inlinetype() && left_klass == right_klass) {
3386     // No need to load klass -- the operands are statically known to be the same inline klass.
3387   } else {
3388     BasicType t_klass = UseCompressedOops ? T_INT : T_METADATA;
3389     left_klass_op = new_register(t_klass);
3390     right_klass_op = new_register(t_klass);
3391   }
3392 
3393   CodeStub* slow_path = new SubstitutabilityCheckStub(left.result(), right.result(), info);
3394   __ substitutability_check(result, left.result(), right.result(), equal_result, not_equal_result,
3395                             tmp1, tmp2,
3396                             left_klass, right_klass, left_klass_op, right_klass_op, info, slow_path);
3397 }
3398 
3399 #ifdef JFR_HAVE_INTRINSICS
3400 
3401 void LIRGenerator::do_getEventWriter(Intrinsic* x) {
3402   LabelObj* L_end = new LabelObj();
3403 
3404   // FIXME T_ADDRESS should actually be T_METADATA but it can't because the
3405   // meaning of these two is mixed up (see JDK-8026837).
3406   LIR_Address* jobj_addr = new LIR_Address(getThreadPointer(),
3407                                            in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR),
3408                                            T_ADDRESS);
3409   LIR_Opr result = rlock_result(x);
3410   __ move(LIR_OprFact::oopConst(NULL), result);
3411   LIR_Opr jobj = new_register(T_METADATA);
3412   __ move_wide(jobj_addr, jobj);
3413   __ cmp(lir_cond_equal, jobj, LIR_OprFact::metadataConst(0));
3414   __ branch(lir_cond_equal, L_end->label());
3415 
3416   access_load(IN_NATIVE, T_OBJECT, LIR_OprFact::address(new LIR_Address(jobj, T_OBJECT)), result);
3417 
3418   __ branch_destination(L_end->label());
3419 }
3420 
3421 #endif
3422 
3423 
3424 void LIRGenerator::do_RuntimeCall(address routine, Intrinsic* x) {
3425   assert(x->number_of_arguments() == 0, "wrong type");
3426   // Enforce computation of _reserved_argument_area_size which is required on some platforms.
3427   BasicTypeList signature;
3428   CallingConvention* cc = frame_map()->c_calling_convention(&signature);
3429   LIR_Opr reg = result_register_for(x->type());
3430   __ call_runtime_leaf(routine, getThreadTemp(),
3431                        reg, new LIR_OprList());
3432   LIR_Opr result = rlock_result(x);
3433   __ move(reg, result);
3434 }
3435 
3436 
3437 
3438 void LIRGenerator::do_Intrinsic(Intrinsic* x) {
3439   switch (x->id()) {
3440   case vmIntrinsics::_intBitsToFloat      :
3441   case vmIntrinsics::_doubleToRawLongBits :
3442   case vmIntrinsics::_longBitsToDouble    :
3443   case vmIntrinsics::_floatToRawIntBits   : {
3444     do_FPIntrinsics(x);
3445     break;
3446   }
3447 
3448 #ifdef JFR_HAVE_INTRINSICS
3449   case vmIntrinsics::_getEventWriter:
3450     do_getEventWriter(x);
3451     break;
3452   case vmIntrinsics::_counterTime:
3453     do_RuntimeCall(CAST_FROM_FN_PTR(address, JFR_TIME_FUNCTION), x);
3454     break;
3455 #endif
3456 
3457   case vmIntrinsics::_currentTimeMillis:
3458     do_RuntimeCall(CAST_FROM_FN_PTR(address, os::javaTimeMillis), x);
3459     break;
3460 
3461   case vmIntrinsics::_nanoTime:
3462     do_RuntimeCall(CAST_FROM_FN_PTR(address, os::javaTimeNanos), x);
3463     break;
3464 
3465   case vmIntrinsics::_Object_init:    do_RegisterFinalizer(x); break;
3466   case vmIntrinsics::_isInstance:     do_isInstance(x);    break;
3467   case vmIntrinsics::_isPrimitive:    do_isPrimitive(x);   break;
3468   case vmIntrinsics::_getModifiers:   do_getModifiers(x);  break;
3469   case vmIntrinsics::_getClass:       do_getClass(x);      break;
3470   case vmIntrinsics::_currentThread:  do_currentThread(x); break;
3471   case vmIntrinsics::_getObjectSize:  do_getObjectSize(x); break;
3472 
3473   case vmIntrinsics::_dlog:           // fall through
3474   case vmIntrinsics::_dlog10:         // fall through
3475   case vmIntrinsics::_dabs:           // fall through
3476   case vmIntrinsics::_dsqrt:          // fall through
3477   case vmIntrinsics::_dsqrt_strict:   // fall through
3478   case vmIntrinsics::_dtan:           // fall through
3479   case vmIntrinsics::_dsin :          // fall through
3480   case vmIntrinsics::_dcos :          // fall through
3481   case vmIntrinsics::_dexp :          // fall through
3482   case vmIntrinsics::_dpow :          do_MathIntrinsic(x); break;
3483   case vmIntrinsics::_arraycopy:      do_ArrayCopy(x);     break;
3484 
3485   case vmIntrinsics::_fmaD:           do_FmaIntrinsic(x); break;
3486   case vmIntrinsics::_fmaF:           do_FmaIntrinsic(x); break;
3487 
3488   case vmIntrinsics::_Preconditions_checkIndex:
3489     do_PreconditionsCheckIndex(x, T_INT);
3490     break;
3491   case vmIntrinsics::_Preconditions_checkLongIndex:
3492     do_PreconditionsCheckIndex(x, T_LONG);
3493     break;
3494 
3495   case vmIntrinsics::_compareAndSetReference:
3496     do_CompareAndSwap(x, objectType);
3497     break;
3498   case vmIntrinsics::_compareAndSetInt:
3499     do_CompareAndSwap(x, intType);
3500     break;
3501   case vmIntrinsics::_compareAndSetLong:
3502     do_CompareAndSwap(x, longType);
3503     break;
3504 
3505   case vmIntrinsics::_loadFence :
3506     __ membar_acquire();
3507     break;
3508   case vmIntrinsics::_storeFence:
3509     __ membar_release();
3510     break;
3511   case vmIntrinsics::_storeStoreFence:
3512     __ membar_storestore();
3513     break;
3514   case vmIntrinsics::_fullFence :
3515     __ membar();
3516     break;
3517   case vmIntrinsics::_onSpinWait:
3518     __ on_spin_wait();
3519     break;
3520   case vmIntrinsics::_Reference_get:
3521     do_Reference_get(x);
3522     break;
3523 
3524   case vmIntrinsics::_updateCRC32:
3525   case vmIntrinsics::_updateBytesCRC32:
3526   case vmIntrinsics::_updateByteBufferCRC32:
3527     do_update_CRC32(x);
3528     break;
3529 
3530   case vmIntrinsics::_updateBytesCRC32C:
3531   case vmIntrinsics::_updateDirectByteBufferCRC32C:
3532     do_update_CRC32C(x);
3533     break;
3534 
3535   case vmIntrinsics::_vectorizedMismatch:
3536     do_vectorizedMismatch(x);
3537     break;
3538 
3539   case vmIntrinsics::_blackhole:
3540     do_blackhole(x);
3541     break;
3542 
3543   default: ShouldNotReachHere(); break;
3544   }
3545 }
3546 
3547 void LIRGenerator::profile_arguments(ProfileCall* x) {
3548   if (compilation()->profile_arguments()) {
3549     int bci = x->bci_of_invoke();
3550     ciMethodData* md = x->method()->method_data_or_null();
3551     assert(md != NULL, "Sanity");
3552     ciProfileData* data = md->bci_to_data(bci);
3553     if (data != NULL) {
3554       if ((data->is_CallTypeData() && data->as_CallTypeData()->has_arguments()) ||
3555           (data->is_VirtualCallTypeData() && data->as_VirtualCallTypeData()->has_arguments())) {
3556         ByteSize extra = data->is_CallTypeData() ? CallTypeData::args_data_offset() : VirtualCallTypeData::args_data_offset();
3557         int base_offset = md->byte_offset_of_slot(data, extra);
3558         LIR_Opr mdp = LIR_OprFact::illegalOpr;
3559         ciTypeStackSlotEntries* args = data->is_CallTypeData() ? ((ciCallTypeData*)data)->args() : ((ciVirtualCallTypeData*)data)->args();
3560 
3561         Bytecodes::Code bc = x->method()->java_code_at_bci(bci);
3562         int start = 0;
3563         int stop = data->is_CallTypeData() ? ((ciCallTypeData*)data)->number_of_arguments() : ((ciVirtualCallTypeData*)data)->number_of_arguments();
3564         if (x->callee()->is_loaded() && x->callee()->is_static() && Bytecodes::has_receiver(bc)) {
3565           // first argument is not profiled at call (method handle invoke)
3566           assert(x->method()->raw_code_at_bci(bci) == Bytecodes::_invokehandle, "invokehandle expected");
3567           start = 1;
3568         }
3569         ciSignature* callee_signature = x->callee()->signature();
3570         // method handle call to virtual method
3571         bool has_receiver = x->callee()->is_loaded() && !x->callee()->is_static() && !Bytecodes::has_receiver(bc);
3572         ciSignatureStream callee_signature_stream(callee_signature, has_receiver ? x->callee()->holder() : NULL);
3573 
3574         bool ignored_will_link;
3575         ciSignature* signature_at_call = NULL;
3576         x->method()->get_method_at_bci(bci, ignored_will_link, &signature_at_call);
3577         ciSignatureStream signature_at_call_stream(signature_at_call);
3578 
3579         // if called through method handle invoke, some arguments may have been popped
3580         for (int i = 0; i < stop && i+start < x->nb_profiled_args(); i++) {
3581           int off = in_bytes(TypeEntriesAtCall::argument_type_offset(i)) - in_bytes(TypeEntriesAtCall::args_data_offset());
3582           ciKlass* exact = profile_type(md, base_offset, off,
3583               args->type(i), x->profiled_arg_at(i+start), mdp,
3584               !x->arg_needs_null_check(i+start),
3585               signature_at_call_stream.next_klass(), callee_signature_stream.next_klass());
3586           if (exact != NULL) {
3587             md->set_argument_type(bci, i, exact);
3588           }
3589         }
3590       } else {
3591 #ifdef ASSERT
3592         Bytecodes::Code code = x->method()->raw_code_at_bci(x->bci_of_invoke());
3593         int n = x->nb_profiled_args();
3594         assert(MethodData::profile_parameters() && (MethodData::profile_arguments_jsr292_only() ||
3595             (x->inlined() && ((code == Bytecodes::_invokedynamic && n <= 1) || (code == Bytecodes::_invokehandle && n <= 2)))),
3596             "only at JSR292 bytecodes");
3597 #endif
3598       }
3599     }
3600   }
3601 }
3602 
3603 // profile parameters on entry to an inlined method
3604 void LIRGenerator::profile_parameters_at_call(ProfileCall* x) {
3605   if (compilation()->profile_parameters() && x->inlined()) {
3606     ciMethodData* md = x->callee()->method_data_or_null();
3607     if (md != NULL) {
3608       ciParametersTypeData* parameters_type_data = md->parameters_type_data();
3609       if (parameters_type_data != NULL) {
3610         ciTypeStackSlotEntries* parameters =  parameters_type_data->parameters();
3611         LIR_Opr mdp = LIR_OprFact::illegalOpr;
3612         bool has_receiver = !x->callee()->is_static();
3613         ciSignature* sig = x->callee()->signature();
3614         ciSignatureStream sig_stream(sig, has_receiver ? x->callee()->holder() : NULL);
3615         int i = 0; // to iterate on the Instructions
3616         Value arg = x->recv();
3617         bool not_null = false;
3618         int bci = x->bci_of_invoke();
3619         Bytecodes::Code bc = x->method()->java_code_at_bci(bci);
3620         // The first parameter is the receiver so that's what we start
3621         // with if it exists. One exception is method handle call to
3622         // virtual method: the receiver is in the args list
3623         if (arg == NULL || !Bytecodes::has_receiver(bc)) {
3624           i = 1;
3625           arg = x->profiled_arg_at(0);
3626           not_null = !x->arg_needs_null_check(0);
3627         }
3628         int k = 0; // to iterate on the profile data
3629         for (;;) {
3630           intptr_t profiled_k = parameters->type(k);
3631           ciKlass* exact = profile_type(md, md->byte_offset_of_slot(parameters_type_data, ParametersTypeData::type_offset(0)),
3632                                         in_bytes(ParametersTypeData::type_offset(k)) - in_bytes(ParametersTypeData::type_offset(0)),
3633                                         profiled_k, arg, mdp, not_null, sig_stream.next_klass(), NULL);
3634           // If the profile is known statically set it once for all and do not emit any code
3635           if (exact != NULL) {
3636             md->set_parameter_type(k, exact);
3637           }
3638           k++;
3639           if (k >= parameters_type_data->number_of_parameters()) {
3640 #ifdef ASSERT
3641             int extra = 0;
3642             if (MethodData::profile_arguments() && TypeProfileParmsLimit != -1 &&
3643                 x->nb_profiled_args() >= TypeProfileParmsLimit &&
3644                 x->recv() != NULL && Bytecodes::has_receiver(bc)) {
3645               extra += 1;
3646             }
3647             assert(i == x->nb_profiled_args() - extra || (TypeProfileParmsLimit != -1 && TypeProfileArgsLimit > TypeProfileParmsLimit), "unused parameters?");
3648 #endif
3649             break;
3650           }
3651           arg = x->profiled_arg_at(i);
3652           not_null = !x->arg_needs_null_check(i);
3653           i++;
3654         }
3655       }
3656     }
3657   }
3658 }
3659 
3660 void LIRGenerator::do_ProfileCall(ProfileCall* x) {
3661   // Need recv in a temporary register so it interferes with the other temporaries
3662   LIR_Opr recv = LIR_OprFact::illegalOpr;
3663   LIR_Opr mdo = new_register(T_METADATA);
3664   // tmp is used to hold the counters on SPARC
3665   LIR_Opr tmp = new_pointer_register();
3666 
3667   if (x->nb_profiled_args() > 0) {
3668     profile_arguments(x);
3669   }
3670 
3671   // profile parameters on inlined method entry including receiver
3672   if (x->recv() != NULL || x->nb_profiled_args() > 0) {
3673     profile_parameters_at_call(x);
3674   }
3675 
3676   if (x->recv() != NULL) {
3677     LIRItem value(x->recv(), this);
3678     value.load_item();
3679     recv = new_register(T_OBJECT);
3680     __ move(value.result(), recv);
3681   }
3682   __ profile_call(x->method(), x->bci_of_invoke(), x->callee(), mdo, recv, tmp, x->known_holder());
3683 }
3684 
3685 void LIRGenerator::do_ProfileReturnType(ProfileReturnType* x) {
3686   int bci = x->bci_of_invoke();
3687   ciMethodData* md = x->method()->method_data_or_null();
3688   assert(md != NULL, "Sanity");
3689   ciProfileData* data = md->bci_to_data(bci);
3690   if (data != NULL) {
3691     assert(data->is_CallTypeData() || data->is_VirtualCallTypeData(), "wrong profile data type");
3692     ciSingleTypeEntry* ret = data->is_CallTypeData() ? ((ciCallTypeData*)data)->ret() : ((ciVirtualCallTypeData*)data)->ret();
3693     LIR_Opr mdp = LIR_OprFact::illegalOpr;
3694 
3695     bool ignored_will_link;
3696     ciSignature* signature_at_call = NULL;
3697     x->method()->get_method_at_bci(bci, ignored_will_link, &signature_at_call);
3698 
3699     // The offset within the MDO of the entry to update may be too large
3700     // to be used in load/store instructions on some platforms. So have
3701     // profile_type() compute the address of the profile in a register.
3702     ciKlass* exact = profile_type(md, md->byte_offset_of_slot(data, ret->type_offset()), 0,
3703         ret->type(), x->ret(), mdp,
3704         !x->needs_null_check(),
3705         signature_at_call->return_type()->as_klass(),
3706         x->callee()->signature()->return_type()->as_klass());
3707     if (exact != NULL) {
3708       md->set_return_type(bci, exact);
3709     }
3710   }
3711 }
3712 
3713 bool LIRGenerator::profile_inline_klass(ciMethodData* md, ciProfileData* data, Value value, int flag) {
3714   ciKlass* klass = value->as_loaded_klass_or_null();
3715   if (klass != NULL) {
3716     if (klass->is_inlinetype()) {
3717       profile_flags(md, data, flag, lir_cond_always);
3718     } else if (klass->can_be_inline_klass()) {
3719       return false;
3720     }
3721   } else {
3722     return false;
3723   }
3724   return true;
3725 }
3726 
3727 
3728 void LIRGenerator::do_ProfileACmpTypes(ProfileACmpTypes* x) {
3729   ciMethod* method = x->method();
3730   assert(method != NULL, "method should be set if branch is profiled");
3731   ciMethodData* md = method->method_data_or_null();
3732   assert(md != NULL, "Sanity");
3733   ciProfileData* data = md->bci_to_data(x->bci());
3734   assert(data != NULL, "must have profiling data");
3735   assert(data->is_ACmpData(), "need BranchData for two-way branches");
3736   ciACmpData* acmp = (ciACmpData*)data;
3737   LIR_Opr mdp = LIR_OprFact::illegalOpr;
3738   profile_type(md, md->byte_offset_of_slot(acmp, ACmpData::left_offset()), 0,
3739                acmp->left()->type(), x->left(), mdp, !x->left_maybe_null(), NULL, NULL);
3740   int flags_offset = md->byte_offset_of_slot(data, DataLayout::flags_offset());
3741   if (!profile_inline_klass(md, acmp, x->left(), ACmpData::left_inline_type_byte_constant())) {
3742     LIR_Opr mdp = new_register(T_METADATA);
3743     __ metadata2reg(md->constant_encoding(), mdp);
3744     LIRItem value(x->left(), this);
3745     value.load_item();
3746     __ profile_inline_type(new LIR_Address(mdp, flags_offset, T_INT), value.result(), ACmpData::left_inline_type_byte_constant(), new_register(T_INT), !x->left_maybe_null());
3747   }
3748   profile_type(md, md->byte_offset_of_slot(acmp, ACmpData::left_offset()),
3749                in_bytes(ACmpData::right_offset()) - in_bytes(ACmpData::left_offset()),
3750                acmp->right()->type(), x->right(), mdp, !x->right_maybe_null(), NULL, NULL);
3751   if (!profile_inline_klass(md, acmp, x->right(), ACmpData::right_inline_type_byte_constant())) {
3752     LIR_Opr mdp = new_register(T_METADATA);
3753     __ metadata2reg(md->constant_encoding(), mdp);
3754     LIRItem value(x->right(), this);
3755     value.load_item();
3756     __ profile_inline_type(new LIR_Address(mdp, flags_offset, T_INT), value.result(), ACmpData::right_inline_type_byte_constant(), new_register(T_INT), !x->left_maybe_null());
3757   }
3758 }
3759 
3760 void LIRGenerator::do_ProfileInvoke(ProfileInvoke* x) {
3761   // We can safely ignore accessors here, since c2 will inline them anyway,
3762   // accessors are also always mature.
3763   if (!x->inlinee()->is_accessor()) {
3764     CodeEmitInfo* info = state_for(x, x->state(), true);
3765     // Notify the runtime very infrequently only to take care of counter overflows
3766     int freq_log = Tier23InlineeNotifyFreqLog;
3767     double scale;
3768     if (_method->has_option_value(CompileCommand::CompileThresholdScaling, scale)) {
3769       freq_log = CompilerConfig::scaled_freq_log(freq_log, scale);
3770     }
3771     increment_event_counter_impl(info, x->inlinee(), LIR_OprFact::intConst(InvocationCounter::count_increment), right_n_bits(freq_log), InvocationEntryBci, false, true);
3772   }
3773 }
3774 
3775 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) {
3776   if (compilation()->is_profiling()) {
3777 #if defined(X86) && !defined(_LP64)
3778     // BEWARE! On 32-bit x86 cmp clobbers its left argument so we need a temp copy.
3779     LIR_Opr left_copy = new_register(left->type());
3780     __ move(left, left_copy);
3781     __ cmp(cond, left_copy, right);
3782 #else
3783     __ cmp(cond, left, right);
3784 #endif
3785     LIR_Opr step = new_register(T_INT);
3786     LIR_Opr plus_one = LIR_OprFact::intConst(InvocationCounter::count_increment);
3787     LIR_Opr zero = LIR_OprFact::intConst(0);
3788     __ cmove(cond,
3789         (left_bci < bci) ? plus_one : zero,
3790         (right_bci < bci) ? plus_one : zero,
3791         step, left->type());
3792     increment_backedge_counter(info, step, bci);
3793   }
3794 }
3795 
3796 
3797 void LIRGenerator::increment_event_counter(CodeEmitInfo* info, LIR_Opr step, int bci, bool backedge) {
3798   int freq_log = 0;
3799   int level = compilation()->env()->comp_level();
3800   if (level == CompLevel_limited_profile) {
3801     freq_log = (backedge ? Tier2BackedgeNotifyFreqLog : Tier2InvokeNotifyFreqLog);
3802   } else if (level == CompLevel_full_profile) {
3803     freq_log = (backedge ? Tier3BackedgeNotifyFreqLog : Tier3InvokeNotifyFreqLog);
3804   } else {
3805     ShouldNotReachHere();
3806   }
3807   // Increment the appropriate invocation/backedge counter and notify the runtime.
3808   double scale;
3809   if (_method->has_option_value(CompileCommand::CompileThresholdScaling, scale)) {
3810     freq_log = CompilerConfig::scaled_freq_log(freq_log, scale);
3811   }
3812   increment_event_counter_impl(info, info->scope()->method(), step, right_n_bits(freq_log), bci, backedge, true);
3813 }
3814 
3815 void LIRGenerator::decrement_age(CodeEmitInfo* info) {
3816   ciMethod* method = info->scope()->method();
3817   MethodCounters* mc_adr = method->ensure_method_counters();
3818   if (mc_adr != NULL) {
3819     LIR_Opr mc = new_pointer_register();
3820     __ move(LIR_OprFact::intptrConst(mc_adr), mc);
3821     int offset = in_bytes(MethodCounters::nmethod_age_offset());
3822     LIR_Address* counter = new LIR_Address(mc, offset, T_INT);
3823     LIR_Opr result = new_register(T_INT);
3824     __ load(counter, result);
3825     __ sub(result, LIR_OprFact::intConst(1), result);
3826     __ store(result, counter);
3827     // DeoptimizeStub will reexecute from the current state in code info.
3828     CodeStub* deopt = new DeoptimizeStub(info, Deoptimization::Reason_tenured,
3829                                          Deoptimization::Action_make_not_entrant);
3830     __ cmp(lir_cond_lessEqual, result, LIR_OprFact::intConst(0));
3831     __ branch(lir_cond_lessEqual, deopt);
3832   }
3833 }
3834 
3835 
3836 void LIRGenerator::increment_event_counter_impl(CodeEmitInfo* info,
3837                                                 ciMethod *method, LIR_Opr step, int frequency,
3838                                                 int bci, bool backedge, bool notify) {
3839   assert(frequency == 0 || is_power_of_2(frequency + 1), "Frequency must be x^2 - 1 or 0");
3840   int level = _compilation->env()->comp_level();
3841   assert(level > CompLevel_simple, "Shouldn't be here");
3842 
3843   int offset = -1;
3844   LIR_Opr counter_holder;
3845   if (level == CompLevel_limited_profile) {
3846     MethodCounters* counters_adr = method->ensure_method_counters();
3847     if (counters_adr == NULL) {
3848       bailout("method counters allocation failed");
3849       return;
3850     }
3851     counter_holder = new_pointer_register();
3852     __ move(LIR_OprFact::intptrConst(counters_adr), counter_holder);
3853     offset = in_bytes(backedge ? MethodCounters::backedge_counter_offset() :
3854                                  MethodCounters::invocation_counter_offset());
3855   } else if (level == CompLevel_full_profile) {
3856     counter_holder = new_register(T_METADATA);
3857     offset = in_bytes(backedge ? MethodData::backedge_counter_offset() :
3858                                  MethodData::invocation_counter_offset());
3859     ciMethodData* md = method->method_data_or_null();
3860     assert(md != NULL, "Sanity");
3861     __ metadata2reg(md->constant_encoding(), counter_holder);
3862   } else {
3863     ShouldNotReachHere();
3864   }
3865   LIR_Address* counter = new LIR_Address(counter_holder, offset, T_INT);
3866   LIR_Opr result = new_register(T_INT);
3867   __ load(counter, result);
3868   __ add(result, step, result);
3869   __ store(result, counter);
3870   if (notify && (!backedge || UseOnStackReplacement)) {
3871     LIR_Opr meth = LIR_OprFact::metadataConst(method->constant_encoding());
3872     // The bci for info can point to cmp for if's we want the if bci
3873     CodeStub* overflow = new CounterOverflowStub(info, bci, meth);
3874     int freq = frequency << InvocationCounter::count_shift;
3875     if (freq == 0) {
3876       if (!step->is_constant()) {
3877         __ cmp(lir_cond_notEqual, step, LIR_OprFact::intConst(0));
3878         __ branch(lir_cond_notEqual, overflow);
3879       } else {
3880         __ branch(lir_cond_always, overflow);
3881       }
3882     } else {
3883       LIR_Opr mask = load_immediate(freq, T_INT);
3884       if (!step->is_constant()) {
3885         // If step is 0, make sure the overflow check below always fails
3886         __ cmp(lir_cond_notEqual, step, LIR_OprFact::intConst(0));
3887         __ cmove(lir_cond_notEqual, result, LIR_OprFact::intConst(InvocationCounter::count_increment), result, T_INT);
3888       }
3889       __ logical_and(result, mask, result);
3890       __ cmp(lir_cond_equal, result, LIR_OprFact::intConst(0));
3891       __ branch(lir_cond_equal, overflow);
3892     }
3893     __ branch_destination(overflow->continuation());
3894   }
3895 }
3896 
3897 void LIRGenerator::do_RuntimeCall(RuntimeCall* x) {
3898   LIR_OprList* args = new LIR_OprList(x->number_of_arguments());
3899   BasicTypeList* signature = new BasicTypeList(x->number_of_arguments());
3900 
3901   if (x->pass_thread()) {
3902     signature->append(LP64_ONLY(T_LONG) NOT_LP64(T_INT));    // thread
3903     args->append(getThreadPointer());
3904   }
3905 
3906   for (int i = 0; i < x->number_of_arguments(); i++) {
3907     Value a = x->argument_at(i);
3908     LIRItem* item = new LIRItem(a, this);
3909     item->load_item();
3910     args->append(item->result());
3911     signature->append(as_BasicType(a->type()));
3912   }
3913 
3914   LIR_Opr result = call_runtime(signature, args, x->entry(), x->type(), NULL);
3915   if (x->type() == voidType) {
3916     set_no_result(x);
3917   } else {
3918     __ move(result, rlock_result(x));
3919   }
3920 }
3921 
3922 #ifdef ASSERT
3923 void LIRGenerator::do_Assert(Assert *x) {
3924   ValueTag tag = x->x()->type()->tag();
3925   If::Condition cond = x->cond();
3926 
3927   LIRItem xitem(x->x(), this);
3928   LIRItem yitem(x->y(), this);
3929   LIRItem* xin = &xitem;
3930   LIRItem* yin = &yitem;
3931 
3932   assert(tag == intTag, "Only integer assertions are valid!");
3933 
3934   xin->load_item();
3935   yin->dont_load_item();
3936 
3937   set_no_result(x);
3938 
3939   LIR_Opr left = xin->result();
3940   LIR_Opr right = yin->result();
3941 
3942   __ lir_assert(lir_cond(x->cond()), left, right, x->message(), true);
3943 }
3944 #endif
3945 
3946 void LIRGenerator::do_RangeCheckPredicate(RangeCheckPredicate *x) {
3947 
3948 
3949   Instruction *a = x->x();
3950   Instruction *b = x->y();
3951   if (!a || StressRangeCheckElimination) {
3952     assert(!b || StressRangeCheckElimination, "B must also be null");
3953 
3954     CodeEmitInfo *info = state_for(x, x->state());
3955     CodeStub* stub = new PredicateFailedStub(info);
3956 
3957     __ jump(stub);
3958   } else if (a->type()->as_IntConstant() && b->type()->as_IntConstant()) {
3959     int a_int = a->type()->as_IntConstant()->value();
3960     int b_int = b->type()->as_IntConstant()->value();
3961 
3962     bool ok = false;
3963 
3964     switch(x->cond()) {
3965       case Instruction::eql: ok = (a_int == b_int); break;
3966       case Instruction::neq: ok = (a_int != b_int); break;
3967       case Instruction::lss: ok = (a_int < b_int); break;
3968       case Instruction::leq: ok = (a_int <= b_int); break;
3969       case Instruction::gtr: ok = (a_int > b_int); break;
3970       case Instruction::geq: ok = (a_int >= b_int); break;
3971       case Instruction::aeq: ok = ((unsigned int)a_int >= (unsigned int)b_int); break;
3972       case Instruction::beq: ok = ((unsigned int)a_int <= (unsigned int)b_int); break;
3973       default: ShouldNotReachHere();
3974     }
3975 
3976     if (ok) {
3977 
3978       CodeEmitInfo *info = state_for(x, x->state());
3979       CodeStub* stub = new PredicateFailedStub(info);
3980 
3981       __ jump(stub);
3982     }
3983   } else {
3984 
3985     ValueTag tag = x->x()->type()->tag();
3986     If::Condition cond = x->cond();
3987     LIRItem xitem(x->x(), this);
3988     LIRItem yitem(x->y(), this);
3989     LIRItem* xin = &xitem;
3990     LIRItem* yin = &yitem;
3991 
3992     assert(tag == intTag, "Only integer deoptimizations are valid!");
3993 
3994     xin->load_item();
3995     yin->dont_load_item();
3996     set_no_result(x);
3997 
3998     LIR_Opr left = xin->result();
3999     LIR_Opr right = yin->result();
4000 
4001     CodeEmitInfo *info = state_for(x, x->state());
4002     CodeStub* stub = new PredicateFailedStub(info);
4003 
4004     __ cmp(lir_cond(cond), left, right);
4005     __ branch(lir_cond(cond), stub);
4006   }
4007 }
4008 
4009 void LIRGenerator::do_blackhole(Intrinsic *x) {
4010   assert(!x->has_receiver(), "Should have been checked before: only static methods here");
4011   for (int c = 0; c < x->number_of_arguments(); c++) {
4012     // Load the argument
4013     LIRItem vitem(x->argument_at(c), this);
4014     vitem.load_item();
4015     // ...and leave it unused.
4016   }
4017 }
4018 
4019 LIR_Opr LIRGenerator::call_runtime(Value arg1, address entry, ValueType* result_type, CodeEmitInfo* info) {
4020   LIRItemList args(1);
4021   LIRItem value(arg1, this);
4022   args.append(&value);
4023   BasicTypeList signature;
4024   signature.append(as_BasicType(arg1->type()));
4025 
4026   return call_runtime(&signature, &args, entry, result_type, info);
4027 }
4028 
4029 
4030 LIR_Opr LIRGenerator::call_runtime(Value arg1, Value arg2, address entry, ValueType* result_type, CodeEmitInfo* info) {
4031   LIRItemList args(2);
4032   LIRItem value1(arg1, this);
4033   LIRItem value2(arg2, this);
4034   args.append(&value1);
4035   args.append(&value2);
4036   BasicTypeList signature;
4037   signature.append(as_BasicType(arg1->type()));
4038   signature.append(as_BasicType(arg2->type()));
4039 
4040   return call_runtime(&signature, &args, entry, result_type, info);
4041 }
4042 
4043 
4044 LIR_Opr LIRGenerator::call_runtime(BasicTypeArray* signature, LIR_OprList* args,
4045                                    address entry, ValueType* result_type, CodeEmitInfo* info) {
4046   // get a result register
4047   LIR_Opr phys_reg = LIR_OprFact::illegalOpr;
4048   LIR_Opr result = LIR_OprFact::illegalOpr;
4049   if (result_type->tag() != voidTag) {
4050     result = new_register(result_type);
4051     phys_reg = result_register_for(result_type);
4052   }
4053 
4054   // move the arguments into the correct location
4055   CallingConvention* cc = frame_map()->c_calling_convention(signature);
4056   assert(cc->length() == args->length(), "argument mismatch");
4057   for (int i = 0; i < args->length(); i++) {
4058     LIR_Opr arg = args->at(i);
4059     LIR_Opr loc = cc->at(i);
4060     if (loc->is_register()) {
4061       __ move(arg, loc);
4062     } else {
4063       LIR_Address* addr = loc->as_address_ptr();
4064 //           if (!can_store_as_constant(arg)) {
4065 //             LIR_Opr tmp = new_register(arg->type());
4066 //             __ move(arg, tmp);
4067 //             arg = tmp;
4068 //           }
4069       __ move(arg, addr);
4070     }
4071   }
4072 
4073   if (info) {
4074     __ call_runtime(entry, getThreadTemp(), phys_reg, cc->args(), info);
4075   } else {
4076     __ call_runtime_leaf(entry, getThreadTemp(), phys_reg, cc->args());
4077   }
4078   if (result->is_valid()) {
4079     __ move(phys_reg, result);
4080   }
4081   return result;
4082 }
4083 
4084 
4085 LIR_Opr LIRGenerator::call_runtime(BasicTypeArray* signature, LIRItemList* args,
4086                                    address entry, ValueType* result_type, CodeEmitInfo* info) {
4087   // get a result register
4088   LIR_Opr phys_reg = LIR_OprFact::illegalOpr;
4089   LIR_Opr result = LIR_OprFact::illegalOpr;
4090   if (result_type->tag() != voidTag) {
4091     result = new_register(result_type);
4092     phys_reg = result_register_for(result_type);
4093   }
4094 
4095   // move the arguments into the correct location
4096   CallingConvention* cc = frame_map()->c_calling_convention(signature);
4097 
4098   assert(cc->length() == args->length(), "argument mismatch");
4099   for (int i = 0; i < args->length(); i++) {
4100     LIRItem* arg = args->at(i);
4101     LIR_Opr loc = cc->at(i);
4102     if (loc->is_register()) {
4103       arg->load_item_force(loc);
4104     } else {
4105       LIR_Address* addr = loc->as_address_ptr();
4106       arg->load_for_store(addr->type());
4107       __ move(arg->result(), addr);
4108     }
4109   }
4110 
4111   if (info) {
4112     __ call_runtime(entry, getThreadTemp(), phys_reg, cc->args(), info);
4113   } else {
4114     __ call_runtime_leaf(entry, getThreadTemp(), phys_reg, cc->args());
4115   }
4116   if (result->is_valid()) {
4117     __ move(phys_reg, result);
4118   }
4119   return result;
4120 }
4121 
4122 void LIRGenerator::do_MemBar(MemBar* x) {
4123   LIR_Code code = x->code();
4124   switch(code) {
4125   case lir_membar_acquire   : __ membar_acquire(); break;
4126   case lir_membar_release   : __ membar_release(); break;
4127   case lir_membar           : __ membar(); break;
4128   case lir_membar_loadload  : __ membar_loadload(); break;
4129   case lir_membar_storestore: __ membar_storestore(); break;
4130   case lir_membar_loadstore : __ membar_loadstore(); break;
4131   case lir_membar_storeload : __ membar_storeload(); break;
4132   default                   : ShouldNotReachHere(); break;
4133   }
4134 }
4135 
4136 LIR_Opr LIRGenerator::mask_boolean(LIR_Opr array, LIR_Opr value, CodeEmitInfo*& null_check_info) {
4137   LIR_Opr value_fixed = rlock_byte(T_BYTE);
4138   if (TwoOperandLIRForm) {
4139     __ move(value, value_fixed);
4140     __ logical_and(value_fixed, LIR_OprFact::intConst(1), value_fixed);
4141   } else {
4142     __ logical_and(value, LIR_OprFact::intConst(1), value_fixed);
4143   }
4144   LIR_Opr klass = new_register(T_METADATA);
4145   load_klass(array, klass, null_check_info);
4146   null_check_info = NULL;
4147   LIR_Opr layout = new_register(T_INT);
4148   __ move(new LIR_Address(klass, in_bytes(Klass::layout_helper_offset()), T_INT), layout);
4149   int diffbit = Klass::layout_helper_boolean_diffbit();
4150   __ logical_and(layout, LIR_OprFact::intConst(diffbit), layout);
4151   __ cmp(lir_cond_notEqual, layout, LIR_OprFact::intConst(0));
4152   __ cmove(lir_cond_notEqual, value_fixed, value, value_fixed, T_BYTE);
4153   value = value_fixed;
4154   return value;
4155 }