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