1 /*
   2  * Copyright (c) 1998, 2018, 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 "compiler/compileLog.hpp"
  27 #include "interpreter/linkResolver.hpp"
  28 #include "memory/universe.hpp"
  29 #include "oops/objArrayKlass.hpp"
  30 #include "oops/valueArrayKlass.hpp"
  31 #include "opto/addnode.hpp"
  32 #include "opto/castnode.hpp"
  33 #include "opto/memnode.hpp"
  34 #include "opto/parse.hpp"
  35 #include "opto/rootnode.hpp"
  36 #include "opto/runtime.hpp"
  37 #include "opto/subnode.hpp"
  38 #include "opto/valuetypenode.hpp"
  39 #include "runtime/deoptimization.hpp"
  40 #include "runtime/handles.inline.hpp"
  41 
  42 //=============================================================================
  43 // Helper methods for _get* and _put* bytecodes
  44 //=============================================================================
  45 bool Parse::static_field_ok_in_clinit(ciField *field, ciMethod *method) {
  46   // Could be the field_holder's <clinit> method, or <clinit> for a subklass.
  47   // Better to check now than to Deoptimize as soon as we execute
  48   assert( field->is_static(), "Only check if field is static");
  49   // is_being_initialized() is too generous.  It allows access to statics
  50   // by threads that are not running the <clinit> before the <clinit> finishes.
  51   // return field->holder()->is_being_initialized();
  52 
  53   // The following restriction is correct but conservative.
  54   // It is also desirable to allow compilation of methods called from <clinit>
  55   // but this generated code will need to be made safe for execution by
  56   // other threads, or the transition from interpreted to compiled code would
  57   // need to be guarded.
  58   ciInstanceKlass *field_holder = field->holder();
  59 
  60   if (method->holder()->is_subclass_of(field_holder)) {
  61     if (method->is_static_initializer()) {
  62       // OK to access static fields inside initializer
  63       return true;
  64     } else if (method->is_object_initializer()) {
  65       // It's also OK to access static fields inside a constructor,
  66       // because any thread calling the constructor must first have
  67       // synchronized on the class by executing a '_new' bytecode.
  68       return true;
  69     }
  70   }
  71   if (C->is_compiling_clinit_for(field_holder)) {
  72     return true; // access in the context of static initializer
  73   }
  74   return false;
  75 }
  76 
  77 
  78 void Parse::do_field_access(bool is_get, bool is_field) {
  79   bool will_link;
  80   ciField* field = iter().get_field(will_link);
  81   assert(will_link, "getfield: typeflow responsibility");
  82 
  83   ciInstanceKlass* field_holder = field->holder();
  84 
  85   if (is_field && field_holder->is_valuetype() && peek()->is_ValueType()) {
  86     assert(is_get, "value type field store not supported");
  87     ValueTypeNode* vt = pop()->as_ValueType();
  88     Node* value = vt->field_value_by_offset(field->offset());
  89     push_node(field->layout_type(), value);
  90     return;
  91   }
  92 
  93   if (is_field == field->is_static()) {
  94     // Interpreter will throw java_lang_IncompatibleClassChangeError
  95     // Check this before allowing <clinit> methods to access static fields
  96     uncommon_trap(Deoptimization::Reason_unhandled,
  97                   Deoptimization::Action_none);
  98     return;
  99   }
 100 
 101   if (!is_field && !field_holder->is_initialized()) {
 102     if (!static_field_ok_in_clinit(field, method())) {
 103       uncommon_trap(Deoptimization::Reason_uninitialized,
 104                     Deoptimization::Action_reinterpret,
 105                     NULL, "!static_field_ok_in_clinit");
 106       return;
 107     }
 108   }
 109 
 110   // Deoptimize on putfield writes to call site target field.
 111   if (!is_get && field->is_call_site_target()) {
 112     uncommon_trap(Deoptimization::Reason_unhandled,
 113                   Deoptimization::Action_reinterpret,
 114                   NULL, "put to call site target field");
 115     return;
 116   }
 117 
 118   assert(field->will_link(method(), bc()), "getfield: typeflow responsibility");
 119 
 120   // Note:  We do not check for an unloaded field type here any more.
 121 
 122   // Generate code for the object pointer.
 123   Node* obj;
 124   if (is_field) {
 125     int obj_depth = is_get ? 0 : field->type()->size();
 126     obj = null_check(peek(obj_depth));
 127     // Compile-time detect of null-exception?
 128     if (stopped())  return;
 129 
 130 #ifdef ASSERT
 131     const TypeInstPtr *tjp = TypeInstPtr::make(TypePtr::NotNull, iter().get_declared_field_holder());
 132     assert(_gvn.type(obj)->higher_equal(tjp), "cast_up is no longer needed");
 133 #endif
 134 
 135     if (is_get) {
 136       (void) pop();  // pop receiver before getting
 137       do_get_xxx(obj, field, is_field);
 138     } else {
 139       do_put_xxx(obj, field, is_field);
 140       if (stopped()) {
 141         return;
 142       }
 143       (void) pop();  // pop receiver after putting
 144     }
 145   } else {
 146     const TypeInstPtr* tip = TypeInstPtr::make(field_holder->java_mirror());
 147     obj = _gvn.makecon(tip);
 148     if (is_get) {
 149       do_get_xxx(obj, field, is_field);
 150     } else {
 151       do_put_xxx(obj, field, is_field);
 152     }
 153   }
 154 }
 155 
 156 void Parse::do_get_xxx(Node* obj, ciField* field, bool is_field) {
 157   BasicType bt = field->layout_type();
 158 
 159   // Does this field have a constant value?  If so, just push the value.
 160   if (field->is_constant() &&
 161       // Keep consistent with types found by ciTypeFlow: for an
 162       // unloaded field type, ciTypeFlow::StateVector::do_getstatic()
 163       // speculates the field is null. The code in the rest of this
 164       // method does the same. We must not bypass it and use a non
 165       // null constant here.
 166       (bt != T_OBJECT || field->type()->is_loaded())) {
 167     // final or stable field
 168     Node* con = make_constant_from_field(field, obj);
 169     if (con != NULL) {
 170       push_node(field->layout_type(), con);
 171       return;
 172     }
 173   }
 174 
 175   ciType* field_klass = field->type();
 176   bool is_vol = field->is_volatile();
 177   bool flattened = field->is_flattened();
 178   bool flattenable = field->is_flattenable();
 179 
 180   // Compute address and memory type.
 181   int offset = field->offset_in_bytes();
 182   const TypePtr* adr_type = C->alias_type(field)->adr_type();
 183   Node *adr = basic_plus_adr(obj, obj, offset);
 184 
 185   // Build the resultant type of the load
 186   const Type *type;
 187 
 188   bool must_assert_null = false;
 189 
 190   if (bt == T_OBJECT || bt == T_ARRAY || bt == T_VALUETYPE) {
 191     if (!field->type()->is_loaded()) {
 192       type = TypeInstPtr::BOTTOM;
 193       must_assert_null = true;
 194     } else if (field->is_static_constant()) {
 195       // This can happen if the constant oop is non-perm.
 196       ciObject* con = field->constant_value().as_object();
 197       // Do not "join" in the previous type; it doesn't add value,
 198       // and may yield a vacuous result if the field is of interface type.
 199       if (con->is_null_object()) {
 200         type = TypePtr::NULL_PTR;
 201       } else {
 202         type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
 203       }
 204       assert(type != NULL, "field singleton type must be consistent");
 205     } else {
 206       type = TypeOopPtr::make_from_klass(field_klass->as_klass());
 207       if (bt == T_VALUETYPE && field->is_static()) {
 208         // Check if static value type field is already initialized
 209         assert(!flattened, "static fields should not be flattened");
 210         ciInstance* mirror = field->holder()->java_mirror();
 211         ciObject* val = mirror->field_value(field).as_object();
 212         if (!val->is_null_object()) {
 213           type = type->join_speculative(TypePtr::NOTNULL);
 214         }
 215       }
 216     }
 217   } else {
 218     type = Type::get_const_basic_type(bt);
 219   }
 220 
 221   Node* ld = NULL;
 222   if (flattened) {
 223     // Load flattened value type
 224     ld = ValueTypeNode::make_from_flattened(this, field_klass->as_value_klass(), obj, obj, field->holder(), offset);
 225   } else {
 226     DecoratorSet decorators = IN_HEAP;
 227     decorators |= is_vol ? MO_SEQ_CST : MO_UNORDERED;
 228     ld = access_load_at(obj, adr, adr_type, type, bt, decorators);
 229     if (flattenable) {
 230       // Load a non-flattened but flattenable value type from memory
 231       if (field_klass->as_value_klass()->is_scalarizable()) {
 232         ld = ValueTypeNode::make_from_oop(this, ld, field_klass->as_value_klass());
 233       } else {
 234         ld = null2default(ld, field_klass->as_value_klass());
 235       }
 236     }
 237   }
 238 
 239   // Adjust Java stack
 240   if (type2size[bt] == 1)
 241     push(ld);
 242   else
 243     push_pair(ld);
 244 
 245   if (must_assert_null) {
 246     // Do not take a trap here.  It's possible that the program
 247     // will never load the field's class, and will happily see
 248     // null values in this field forever.  Don't stumble into a
 249     // trap for such a program, or we might get a long series
 250     // of useless recompilations.  (Or, we might load a class
 251     // which should not be loaded.)  If we ever see a non-null
 252     // value, we will then trap and recompile.  (The trap will
 253     // not need to mention the class index, since the class will
 254     // already have been loaded if we ever see a non-null value.)
 255     // uncommon_trap(iter().get_field_signature_index());
 256     if (PrintOpto && (Verbose || WizardMode)) {
 257       method()->print_name(); tty->print_cr(" asserting nullness of field at bci: %d", bci());
 258     }
 259     if (C->log() != NULL) {
 260       C->log()->elem("assert_null reason='field' klass='%d'",
 261                      C->log()->identify(field->type()));
 262     }
 263     // If there is going to be a trap, put it at the next bytecode:
 264     set_bci(iter().next_bci());
 265     null_assert(peek());
 266     set_bci(iter().cur_bci()); // put it back
 267   }
 268 }
 269 
 270 void Parse::do_put_xxx(Node* obj, ciField* field, bool is_field) {
 271   bool is_vol = field->is_volatile();
 272 
 273   // Compute address and memory type.
 274   int offset = field->offset_in_bytes();
 275   const TypePtr* adr_type = C->alias_type(field)->adr_type();
 276   Node* adr = basic_plus_adr(obj, obj, offset);
 277   BasicType bt = field->layout_type();
 278   // Value to be stored
 279   Node* val = type2size[bt] == 1 ? pop() : pop_pair();
 280 
 281   DecoratorSet decorators = IN_HEAP;
 282   decorators |= is_vol ? MO_SEQ_CST : MO_UNORDERED;
 283 
 284   // Store the value.
 285   const Type* field_type;
 286   if (!field->type()->is_loaded()) {
 287     field_type = TypeInstPtr::BOTTOM;
 288   } else {
 289     if (bt == T_OBJECT || bt == T_ARRAY || bt == T_VALUETYPE) {
 290       field_type = TypeOopPtr::make_from_klass(field->type()->as_klass());
 291     } else {
 292       field_type = Type::BOTTOM;
 293     }
 294   }
 295 
 296   if (field->is_flattenable() && !val->is_ValueType()) {
 297     inc_sp(1);
 298     val = null_check(val);
 299     dec_sp(1);
 300     if (stopped()) return;
 301   }
 302 
 303   if (field->is_flattened()) {
 304     // Store flattened value type to a non-static field
 305     if (!val->is_ValueType()) {
 306       assert(!gvn().type(val)->maybe_null(), "should never be null");
 307       val = ValueTypeNode::make_from_oop(this, val, field->type()->as_value_klass());
 308     }
 309     val->as_ValueType()->store_flattened(this, obj, obj, field->holder(), offset);
 310   } else {
 311     access_store_at(obj, adr, adr_type, val, field_type, bt, decorators);
 312   }
 313 
 314   if (is_field) {
 315     // Remember we wrote a volatile field.
 316     // For not multiple copy atomic cpu (ppc64) a barrier should be issued
 317     // in constructors which have such stores. See do_exits() in parse1.cpp.
 318     if (is_vol) {
 319       set_wrote_volatile(true);
 320     }
 321     set_wrote_fields(true);
 322 
 323     // If the field is final, the rules of Java say we are in <init> or <clinit>.
 324     // Note the presence of writes to final non-static fields, so that we
 325     // can insert a memory barrier later on to keep the writes from floating
 326     // out of the constructor.
 327     // Any method can write a @Stable field; insert memory barriers after those also.
 328     if (field->is_final()) {
 329       set_wrote_final(true);
 330       if (AllocateNode::Ideal_allocation(obj, &_gvn) != NULL) {
 331         // Preserve allocation ptr to create precedent edge to it in membar
 332         // generated on exit from constructor.
 333         // Can't bind stable with its allocation, only record allocation for final field.
 334         set_alloc_with_final(obj);
 335       }
 336     }
 337     if (field->is_stable()) {
 338       set_wrote_stable(true);
 339     }
 340   }
 341 }
 342 
 343 //=============================================================================
 344 
 345 void Parse::do_newarray() {
 346   bool will_link;
 347   ciKlass* klass = iter().get_klass(will_link);
 348 
 349   // Uncommon Trap when class that array contains is not loaded
 350   // we need the loaded class for the rest of graph; do not
 351   // initialize the container class (see Java spec)!!!
 352   assert(will_link, "newarray: typeflow responsibility");
 353 
 354   ciArrayKlass* array_klass = ciArrayKlass::make(klass);
 355   // Check that array_klass object is loaded
 356   if (!array_klass->is_loaded()) {
 357     // Generate uncommon_trap for unloaded array_class
 358     uncommon_trap(Deoptimization::Reason_unloaded,
 359                   Deoptimization::Action_reinterpret,
 360                   array_klass);
 361     return;
 362   } else if (array_klass->element_klass() != NULL &&
 363              array_klass->element_klass()->is_valuetype() &&
 364              !array_klass->element_klass()->as_value_klass()->is_initialized()) {
 365     uncommon_trap(Deoptimization::Reason_uninitialized,
 366                   Deoptimization::Action_reinterpret,
 367                   NULL);
 368     return;
 369   }
 370 
 371   kill_dead_locals();
 372 
 373   const TypeKlassPtr* array_klass_type = TypeKlassPtr::make(array_klass);
 374   Node* count_val = pop();
 375   Node* obj = new_array(makecon(array_klass_type), count_val, 1);
 376   push(obj);
 377 }
 378 
 379 
 380 void Parse::do_newarray(BasicType elem_type) {
 381   kill_dead_locals();
 382 
 383   Node*   count_val = pop();
 384   const TypeKlassPtr* array_klass = TypeKlassPtr::make(ciTypeArrayKlass::make(elem_type));
 385   Node*   obj = new_array(makecon(array_klass), count_val, 1);
 386   // Push resultant oop onto stack
 387   push(obj);
 388 }
 389 
 390 // Expand simple expressions like new int[3][5] and new Object[2][nonConLen].
 391 // Also handle the degenerate 1-dimensional case of anewarray.
 392 Node* Parse::expand_multianewarray(ciArrayKlass* array_klass, Node* *lengths, int ndimensions, int nargs) {
 393   Node* length = lengths[0];
 394   assert(length != NULL, "");
 395   Node* array = new_array(makecon(TypeKlassPtr::make(array_klass)), length, nargs);
 396   if (ndimensions > 1) {
 397     jint length_con = find_int_con(length, -1);
 398     guarantee(length_con >= 0, "non-constant multianewarray");
 399     ciArrayKlass* array_klass_1 = array_klass->as_obj_array_klass()->element_klass()->as_array_klass();
 400     const TypePtr* adr_type = TypeAryPtr::OOPS;
 401     const TypeOopPtr*    elemtype = _gvn.type(array)->is_aryptr()->elem()->make_oopptr();
 402     const intptr_t header   = arrayOopDesc::base_offset_in_bytes(T_OBJECT);
 403     for (jint i = 0; i < length_con; i++) {
 404       Node*    elem   = expand_multianewarray(array_klass_1, &lengths[1], ndimensions-1, nargs);
 405       intptr_t offset = header + ((intptr_t)i << LogBytesPerHeapOop);
 406       Node*    eaddr  = basic_plus_adr(array, offset);
 407       access_store_at(array, eaddr, adr_type, elem, elemtype, T_OBJECT, IN_HEAP | IS_ARRAY);
 408     }
 409   }
 410   return array;
 411 }
 412 
 413 void Parse::do_multianewarray() {
 414   int ndimensions = iter().get_dimensions();
 415 
 416   // the m-dimensional array
 417   bool will_link;
 418   ciArrayKlass* array_klass = iter().get_klass(will_link)->as_array_klass();
 419   assert(will_link, "multianewarray: typeflow responsibility");
 420 
 421   // Note:  Array classes are always initialized; no is_initialized check.
 422 
 423   kill_dead_locals();
 424 
 425   // get the lengths from the stack (first dimension is on top)
 426   Node** length = NEW_RESOURCE_ARRAY(Node*, ndimensions + 1);
 427   length[ndimensions] = NULL;  // terminating null for make_runtime_call
 428   int j;
 429   for (j = ndimensions-1; j >= 0 ; j--) length[j] = pop();
 430 
 431   // The original expression was of this form: new T[length0][length1]...
 432   // It is often the case that the lengths are small (except the last).
 433   // If that happens, use the fast 1-d creator a constant number of times.
 434   const int expand_limit = MIN2((int)MultiArrayExpandLimit, 100);
 435   int expand_count = 1;        // count of allocations in the expansion
 436   int expand_fanout = 1;       // running total fanout
 437   for (j = 0; j < ndimensions-1; j++) {
 438     int dim_con = find_int_con(length[j], -1);
 439     expand_fanout *= dim_con;
 440     expand_count  += expand_fanout; // count the level-J sub-arrays
 441     if (dim_con <= 0
 442         || dim_con > expand_limit
 443         || expand_count > expand_limit) {
 444       expand_count = 0;
 445       break;
 446     }
 447   }
 448 
 449   // Can use multianewarray instead of [a]newarray if only one dimension,
 450   // or if all non-final dimensions are small constants.
 451   if (ndimensions == 1 || (1 <= expand_count && expand_count <= expand_limit)) {
 452     Node* obj = NULL;
 453     // Set the original stack and the reexecute bit for the interpreter
 454     // to reexecute the multianewarray bytecode if deoptimization happens.
 455     // Do it unconditionally even for one dimension multianewarray.
 456     // Note: the reexecute bit will be set in GraphKit::add_safepoint_edges()
 457     // when AllocateArray node for newarray is created.
 458     { PreserveReexecuteState preexecs(this);
 459       inc_sp(ndimensions);
 460       // Pass 0 as nargs since uncommon trap code does not need to restore stack.
 461       obj = expand_multianewarray(array_klass, &length[0], ndimensions, 0);
 462     } //original reexecute and sp are set back here
 463     push(obj);
 464     return;
 465   }
 466 
 467   address fun = NULL;
 468   switch (ndimensions) {
 469   case 1: ShouldNotReachHere(); break;
 470   case 2: fun = OptoRuntime::multianewarray2_Java(); break;
 471   case 3: fun = OptoRuntime::multianewarray3_Java(); break;
 472   case 4: fun = OptoRuntime::multianewarray4_Java(); break;
 473   case 5: fun = OptoRuntime::multianewarray5_Java(); break;
 474   };
 475   Node* c = NULL;
 476 
 477   if (fun != NULL) {
 478     c = make_runtime_call(RC_NO_LEAF | RC_NO_IO,
 479                           OptoRuntime::multianewarray_Type(ndimensions),
 480                           fun, NULL, TypeRawPtr::BOTTOM,
 481                           makecon(TypeKlassPtr::make(array_klass)),
 482                           length[0], length[1], length[2],
 483                           (ndimensions > 2) ? length[3] : NULL,
 484                           (ndimensions > 3) ? length[4] : NULL);
 485   } else {
 486     // Create a java array for dimension sizes
 487     Node* dims = NULL;
 488     { PreserveReexecuteState preexecs(this);
 489       inc_sp(ndimensions);
 490       Node* dims_array_klass = makecon(TypeKlassPtr::make(ciArrayKlass::make(ciType::make(T_INT))));
 491       dims = new_array(dims_array_klass, intcon(ndimensions), 0);
 492 
 493       // Fill-in it with values
 494       for (j = 0; j < ndimensions; j++) {
 495         Node *dims_elem = array_element_address(dims, intcon(j), T_INT);
 496         store_to_memory(control(), dims_elem, length[j], T_INT, TypeAryPtr::INTS, MemNode::unordered);
 497       }
 498     }
 499 
 500     c = make_runtime_call(RC_NO_LEAF | RC_NO_IO,
 501                           OptoRuntime::multianewarrayN_Type(),
 502                           OptoRuntime::multianewarrayN_Java(), NULL, TypeRawPtr::BOTTOM,
 503                           makecon(TypeKlassPtr::make(array_klass)),
 504                           dims);
 505   }
 506   make_slow_call_ex(c, env()->Throwable_klass(), false);
 507 
 508   Node* res = _gvn.transform(new ProjNode(c, TypeFunc::Parms));
 509 
 510   const Type* type = TypeOopPtr::make_from_klass_raw(array_klass);
 511 
 512   // Improve the type:  We know it's not null, exact, and of a given length.
 513   type = type->is_ptr()->cast_to_ptr_type(TypePtr::NotNull);
 514   type = type->is_aryptr()->cast_to_exactness(true);
 515 
 516   const TypeInt* ltype = _gvn.find_int_type(length[0]);
 517   if (ltype != NULL)
 518     type = type->is_aryptr()->cast_to_size(ltype);
 519 
 520     // We cannot sharpen the nested sub-arrays, since the top level is mutable.
 521 
 522   Node* cast = _gvn.transform( new CheckCastPPNode(control(), res, type) );
 523   push(cast);
 524 
 525   // Possible improvements:
 526   // - Make a fast path for small multi-arrays.  (W/ implicit init. loops.)
 527   // - Issue CastII against length[*] values, to TypeInt::POS.
 528 }