rewriter.cpp 18.2 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26 27 28 29
#include "precompiled.hpp"
#include "interpreter/bytecodes.hpp"
#include "interpreter/interpreter.hpp"
#include "interpreter/rewriter.hpp"
#include "memory/gcLocker.hpp"
30
#include "memory/metadataFactory.hpp"
31 32 33 34 35 36
#include "memory/oopFactory.hpp"
#include "memory/resourceArea.hpp"
#include "oops/generateOopMap.hpp"
#include "oops/objArrayOop.hpp"
#include "oops/oop.inline.hpp"
#include "prims/methodComparator.hpp"
37
#include "prims/methodHandles.hpp"
D
duke 已提交
38

39
// Computes a CPC map (new_index -> original_index) for constant pool entries
D
duke 已提交
40
// that are referred to by the interpreter at runtime via the constant pool cache.
41 42 43 44
// Also computes a CP map (original_index -> new_index).
// Marks entries in CP which require additional processing.
void Rewriter::compute_index_maps() {
  const int length  = _pool->length();
45
  init_maps(length);
46
  bool saw_mh_symbol = false;
D
duke 已提交
47
  for (int i = 0; i < length; i++) {
48 49 50
    int tag = _pool->tag_at(i).value();
    switch (tag) {
      case JVM_CONSTANT_InterfaceMethodref:
D
duke 已提交
51 52
      case JVM_CONSTANT_Fieldref          : // fall through
      case JVM_CONSTANT_Methodref         : // fall through
53 54 55 56
        add_cp_cache_entry(i);
        break;
      case JVM_CONSTANT_String:
      case JVM_CONSTANT_Object:
57 58
      case JVM_CONSTANT_MethodHandle      : // fall through
      case JVM_CONSTANT_MethodType        : // fall through
59
        add_resolved_references_entry(i);
60
        break;
61 62 63 64
      case JVM_CONSTANT_Utf8:
        if (_pool->symbol_at(i) == vmSymbols::java_lang_invoke_MethodHandle())
          saw_mh_symbol = true;
        break;
D
duke 已提交
65 66
    }
  }
67

68 69 70
  // Record limits of resolved reference map for constant pool cache indices
  record_map_limits();

71 72
  guarantee((int)_cp_cache_map.length()-1 <= (int)((u2)-1),
            "all cp cache indexes fit in a u2");
73

74 75
  if (saw_mh_symbol)
    _method_handle_invokers.initialize(length, (int)0);
D
duke 已提交
76 77
}

78 79 80 81 82
// Unrewrite the bytecodes if an error occurs.
void Rewriter::restore_bytecodes() {
  int len = _methods->length();

  for (int i = len-1; i >= 0; i--) {
83
    Method* method = _methods->at(i);
84 85 86
    scan_method(method, true);
  }
}
D
duke 已提交
87

88 89 90
// Creates a constant pool cache given a CPC map
void Rewriter::make_constant_pool_cache(TRAPS) {
  const int length = _cp_cache_map.length();
91 92 93 94 95 96 97 98 99
  ClassLoaderData* loader_data = _pool->pool_holder()->class_loader_data();
  ConstantPoolCache* cache =
      ConstantPoolCache::allocate(loader_data, length, CHECK);

  // initialize object cache in constant pool
  _pool->initialize_resolved_references(loader_data, _resolved_references_map,
                                        _resolved_reference_limit,
                                        CHECK);

100
  No_Safepoint_Verifier nsv;
101
  cache->initialize(_cp_cache_map, _invokedynamic_references_map);
102 103
  _pool->set_cache(cache);
  cache->set_constant_pool(_pool());
D
duke 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
}



// The new finalization semantics says that registration of
// finalizable objects must be performed on successful return from the
// Object.<init> constructor.  We could implement this trivially if
// <init> were never rewritten but since JVMTI allows this to occur, a
// more complicated solution is required.  A special return bytecode
// is used only by Object.<init> to signal the finalization
// registration point.  Additionally local 0 must be preserved so it's
// available to pass to the registration function.  For simplicty we
// require that local 0 is never overwritten so it's available as an
// argument for registration.

void Rewriter::rewrite_Object_init(methodHandle method, TRAPS) {
  RawBytecodeStream bcs(method);
  while (!bcs.is_last_bytecode()) {
    Bytecodes::Code opcode = bcs.raw_next();
    switch (opcode) {
      case Bytecodes::_return: *bcs.bcp() = Bytecodes::_return_register_finalizer; break;

      case Bytecodes::_istore:
      case Bytecodes::_lstore:
      case Bytecodes::_fstore:
      case Bytecodes::_dstore:
      case Bytecodes::_astore:
        if (bcs.get_index() != 0) continue;

        // fall through
      case Bytecodes::_istore_0:
      case Bytecodes::_lstore_0:
      case Bytecodes::_fstore_0:
      case Bytecodes::_dstore_0:
      case Bytecodes::_astore_0:
        THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
                  "can't overwrite local 0 in Object.<init>");
        break;
    }
  }
}


147
// Rewrite a classfile-order CP index into a native-order CPC index.
148
void Rewriter::rewrite_member_reference(address bcp, int offset, bool reverse) {
149
  address p = bcp + offset;
150 151 152 153
  if (!reverse) {
    int  cp_index    = Bytes::get_Java_u2(p);
    int  cache_index = cp_entry_to_cp_cache(cp_index);
    Bytes::put_native_u2(p, cache_index);
154
    if (!_method_handle_invokers.is_empty())
155
      maybe_rewrite_invokehandle(p - 1, cp_index, cache_index, reverse);
156 157 158 159
  } else {
    int cache_index = Bytes::get_native_u2(p);
    int pool_index = cp_cache_entry_pool_index(cache_index);
    Bytes::put_Java_u2(p, pool_index);
160
    if (!_method_handle_invokers.is_empty())
161
      maybe_rewrite_invokehandle(p - 1, pool_index, cache_index, reverse);
162 163 164 165 166
  }
}


// Adjust the invocation bytecode for a signature-polymorphic method (MethodHandle.invoke, etc.)
167
void Rewriter::maybe_rewrite_invokehandle(address opc, int cp_index, int cache_index, bool reverse) {
168 169 170 171 172 173 174 175 176 177 178 179
  if (!reverse) {
    if ((*opc) == (u1)Bytecodes::_invokevirtual ||
        // allow invokespecial as an alias, although it would be very odd:
        (*opc) == (u1)Bytecodes::_invokespecial) {
      assert(_pool->tag_at(cp_index).is_method(), "wrong index");
      // Determine whether this is a signature-polymorphic method.
      if (cp_index >= _method_handle_invokers.length())  return;
      int status = _method_handle_invokers[cp_index];
      assert(status >= -1 && status <= 1, "oob tri-state");
      if (status == 0) {
        if (_pool->klass_ref_at_noresolve(cp_index) == vmSymbols::java_lang_invoke_MethodHandle() &&
            MethodHandles::is_signature_polymorphic_name(SystemDictionary::MethodHandle_klass(),
180 181
                                                         _pool->name_ref_at(cp_index))) {
          // we may need a resolved_refs entry for the appendix
182
          add_invokedynamic_resolved_references_entries(cp_index, cache_index);
183
          status = +1;
184
        } else {
185
          status = -1;
186
        }
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
        _method_handle_invokers[cp_index] = status;
      }
      // We use a special internal bytecode for such methods (if non-static).
      // The basic reason for this is that such methods need an extra "appendix" argument
      // to transmit the call site's intended call type.
      if (status > 0) {
        (*opc) = (u1)Bytecodes::_invokehandle;
      }
    }
  } else {
    // Do not need to look at cp_index.
    if ((*opc) == (u1)Bytecodes::_invokehandle) {
      (*opc) = (u1)Bytecodes::_invokevirtual;
      // Ignore corner case of original _invokespecial instruction.
      // This is safe because (a) the signature polymorphic method was final, and
      // (b) the implementation of MethodHandle will not call invokespecial on it.
    }
204
  }
205 206 207
}


208
void Rewriter::rewrite_invokedynamic(address bcp, int offset, bool reverse) {
209
  address p = bcp + offset;
210 211 212
  assert(p[-1] == Bytecodes::_invokedynamic, "not invokedynamic bytecode");
  if (!reverse) {
    int cp_index = Bytes::get_Java_u2(p);
213
    int cache_index = add_invokedynamic_cp_cache_entry(cp_index);
214
    add_invokedynamic_resolved_references_entries(cp_index, cache_index);
215 216 217 218 219 220 221 222
    // Replace the trailing four bytes with a CPC index for the dynamic
    // call site.  Unlike other CPC entries, there is one per bytecode,
    // not just one per distinct CP entry.  In other words, the
    // CPC-to-CP relation is many-to-one for invokedynamic entries.
    // This means we must use a larger index size than u2 to address
    // all these entries.  That is the main reason invokedynamic
    // must have a five-byte instruction format.  (Of course, other JVM
    // implementations can use the bytes for other purposes.)
223
    Bytes::put_native_u4(p, ConstantPool::encode_invokedynamic_index(cache_index));
224 225
    // Note: We use native_u4 format exclusively for 4-byte indexes.
  } else {
226 227
    // callsite index
    int cache_index = ConstantPool::decode_invokedynamic_index(
228
                        Bytes::get_native_u4(p));
229 230
    int cp_index = cp_cache_entry_pool_index(cache_index);
    assert(_pool->tag_at(cp_index).is_invoke_dynamic(), "wrong index");
231 232
    // zero out 4 bytes
    Bytes::put_Java_u4(p, 0);
233
    Bytes::put_Java_u2(p, cp_index);
234
  }
235 236 237
}


238
// Rewrite some ldc bytecodes to _fast_aldc
239 240 241 242 243 244 245
void Rewriter::maybe_rewrite_ldc(address bcp, int offset, bool is_wide,
                                 bool reverse) {
  if (!reverse) {
    assert((*bcp) == (is_wide ? Bytecodes::_ldc_w : Bytecodes::_ldc), "not ldc bytecode");
    address p = bcp + offset;
    int cp_index = is_wide ? Bytes::get_Java_u2(p) : (u1)(*p);
    constantTag tag = _pool->tag_at(cp_index).value();
246 247
    if (tag.is_method_handle() || tag.is_method_type() || tag.is_string() || tag.is_object()) {
      int ref_index = cp_entry_to_resolved_references(cp_index);
248 249
      if (is_wide) {
        (*bcp) = Bytecodes::_fast_aldc_w;
250 251
        assert(ref_index == (u2)ref_index, "index overflow");
        Bytes::put_native_u2(p, ref_index);
252 253
      } else {
        (*bcp) = Bytecodes::_fast_aldc;
254 255
        assert(ref_index == (u1)ref_index, "index overflow");
        (*p) = (u1)ref_index;
256 257 258 259 260 261 262
      }
    }
  } else {
    Bytecodes::Code rewritten_bc =
              (is_wide ? Bytecodes::_fast_aldc_w : Bytecodes::_fast_aldc);
    if ((*bcp) == rewritten_bc) {
      address p = bcp + offset;
263 264
      int ref_index = is_wide ? Bytes::get_native_u2(p) : (u1)(*p);
      int pool_index = resolved_references_entry_to_pool_index(ref_index);
265 266 267 268 269 270 271 272 273
      if (is_wide) {
        (*bcp) = Bytecodes::_ldc_w;
        assert(pool_index == (u2)pool_index, "index overflow");
        Bytes::put_Java_u2(p, pool_index);
      } else {
        (*bcp) = Bytecodes::_ldc;
        assert(pool_index == (u1)pool_index, "index overflow");
        (*p) = (u1)pool_index;
      }
274 275 276 277 278
    }
  }
}


D
duke 已提交
279
// Rewrites a method given the index_map information
280
void Rewriter::scan_method(Method* method, bool reverse) {
D
duke 已提交
281 282 283 284 285 286

  int nof_jsrs = 0;
  bool has_monitor_bytecodes = false;

  {
    // We cannot tolerate a GC in this block, because we've
287
    // cached the bytecodes in 'code_base'. If the Method*
D
duke 已提交
288 289 290 291 292 293 294 295 296 297 298
    // moves, the bytecodes will also move.
    No_Safepoint_Verifier nsv;
    Bytecodes::Code c;

    // Bytecodes and their length
    const address code_base = method->code_base();
    const int code_length = method->code_size();

    int bc_length;
    for (int bci = 0; bci < code_length; bci += bc_length) {
      address bcp = code_base + bci;
299
      int prefix_length = 0;
D
duke 已提交
300 301 302 303 304 305 306 307
      c = (Bytecodes::Code)(*bcp);

      // Since we have the code, see if we can get the length
      // directly. Some more complicated bytecodes will report
      // a length of zero, meaning we need to make another method
      // call to calculate the length.
      bc_length = Bytecodes::length_for(c);
      if (bc_length == 0) {
308
        bc_length = Bytecodes::length_at(method, bcp);
D
duke 已提交
309 310 311 312 313

        // length_at will put us at the bytecode after the one modified
        // by 'wide'. We don't currently examine any of the bytecodes
        // modified by wide, but in case we do in the future...
        if (c == Bytecodes::_wide) {
314
          prefix_length = 1;
D
duke 已提交
315 316 317 318 319 320 321 322 323
          c = (Bytecodes::Code)bcp[1];
        }
      }

      assert(bc_length != 0, "impossible bytecode length");

      switch (c) {
        case Bytecodes::_lookupswitch   : {
#ifndef CC_INTERP
324
          Bytecode_lookupswitch bc(method, bcp);
325
          (*bcp) = (
326
            bc.number_of_pairs() < BinarySwitchThreshold
D
duke 已提交
327 328 329
            ? Bytecodes::_fast_linearswitch
            : Bytecodes::_fast_binaryswitch
          );
330 331 332 333 334 335 336
#endif
          break;
        }
        case Bytecodes::_fast_linearswitch:
        case Bytecodes::_fast_binaryswitch: {
#ifndef CC_INTERP
          (*bcp) = Bytecodes::_lookupswitch;
D
duke 已提交
337 338 339 340 341 342 343 344 345
#endif
          break;
        }
        case Bytecodes::_getstatic      : // fall through
        case Bytecodes::_putstatic      : // fall through
        case Bytecodes::_getfield       : // fall through
        case Bytecodes::_putfield       : // fall through
        case Bytecodes::_invokevirtual  : // fall through
        case Bytecodes::_invokespecial  : // fall through
346 347
        case Bytecodes::_invokestatic   :
        case Bytecodes::_invokeinterface:
348
        case Bytecodes::_invokehandle   : // if reverse=true
349
          rewrite_member_reference(bcp, prefix_length+1, reverse);
350 351
          break;
        case Bytecodes::_invokedynamic:
352
          rewrite_invokedynamic(bcp, prefix_length+1, reverse);
D
duke 已提交
353
          break;
354
        case Bytecodes::_ldc:
355
        case Bytecodes::_fast_aldc:  // if reverse=true
356
          maybe_rewrite_ldc(bcp, prefix_length+1, false, reverse);
357 358
          break;
        case Bytecodes::_ldc_w:
359
        case Bytecodes::_fast_aldc_w:  // if reverse=true
360
          maybe_rewrite_ldc(bcp, prefix_length+1, true, reverse);
361
          break;
D
duke 已提交
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
        case Bytecodes::_jsr            : // fall through
        case Bytecodes::_jsr_w          : nof_jsrs++;                   break;
        case Bytecodes::_monitorenter   : // fall through
        case Bytecodes::_monitorexit    : has_monitor_bytecodes = true; break;
      }
    }
  }

  // Update access flags
  if (has_monitor_bytecodes) {
    method->set_has_monitor_bytecodes();
  }

  // The present of a jsr bytecode implies that the method might potentially
  // have to be rewritten, so we run the oopMapGenerator on the method
  if (nof_jsrs > 0) {
    method->set_has_jsrs();
379
    // Second pass will revisit this method.
380
    assert(method->has_jsrs(), "didn't we just set this?");
381 382
  }
}
D
duke 已提交
383

384 385
// After constant pool is created, revisit methods containing jsrs.
methodHandle Rewriter::rewrite_jsrs(methodHandle method, TRAPS) {
386
  ResourceMark rm(THREAD);
387 388 389 390 391 392 393
  ResolveOopMapConflicts romc(method);
  methodHandle original_method = method;
  method = romc.do_potential_rewrite(CHECK_(methodHandle()));
  // Update monitor matching info.
  if (romc.monitor_safe()) {
    method->set_guaranteed_monitor_matching();
  }
D
duke 已提交
394 395 396 397 398 399

  return method;
}

void Rewriter::rewrite(instanceKlassHandle klass, TRAPS) {
  ResourceMark rm(THREAD);
400
  Rewriter     rw(klass, klass->constants(), klass->methods(), CHECK);
401 402
  // (That's all, folks.)
}
D
duke 已提交
403

404

405
void Rewriter::rewrite(instanceKlassHandle klass, constantPoolHandle cpool, Array<Method*>* methods, TRAPS) {
406 407 408 409 410 411
  ResourceMark rm(THREAD);
  Rewriter     rw(klass, cpool, methods, CHECK);
  // (That's all, folks.)
}


412
Rewriter::Rewriter(instanceKlassHandle klass, constantPoolHandle cpool, Array<Method*>* methods, TRAPS)
413
  : _klass(klass),
414 415
    _pool(cpool),
    _methods(methods)
416 417
{
  assert(_pool->cache() == NULL, "constant pool cache must not be set yet");
D
duke 已提交
418

419
  // determine index maps for Method* rewriting
420
  compute_index_maps();
D
duke 已提交
421

422
  if (RegisterFinalizersAtInit && _klass->name() == vmSymbols::java_lang_Object()) {
423
    bool did_rewrite = false;
424
    int i = _methods->length();
D
duke 已提交
425
    while (i-- > 0) {
426
      Method* method = _methods->at(i);
D
duke 已提交
427 428 429 430 431
      if (method->intrinsic_id() == vmIntrinsics::_Object_init) {
        // rewrite the return bytecodes of Object.<init> to register the
        // object for finalization if needed.
        methodHandle m(THREAD, method);
        rewrite_Object_init(m, CHECK);
432
        did_rewrite = true;
D
duke 已提交
433 434 435
        break;
      }
    }
436
    assert(did_rewrite, "must find Object::<init> to rewrite it");
D
duke 已提交
437 438
  }

439
  // rewrite methods, in two passes
440
  int len = _methods->length();
441

442
  for (int i = len-1; i >= 0; i--) {
443
    Method* method = _methods->at(i);
444 445 446 447
    scan_method(method);
  }

  // allocate constant pool cache, now that we've seen all the bytecodes
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
  make_constant_pool_cache(THREAD);

  // Restore bytecodes to their unrewritten state if there are exceptions
  // rewriting bytecodes or allocating the cpCache
  if (HAS_PENDING_EXCEPTION) {
    restore_bytecodes();
    return;
  }
}

// Relocate jsr/rets in a method.  This can't be done with the rewriter
// stage because it can throw other exceptions, leaving the bytecodes
// pointing at constant pool cache entries.
// Link and check jvmti dependencies while we're iterating over the methods.
// JSR292 code calls with a different set of methods, so two entry points.
void Rewriter::relocate_and_link(instanceKlassHandle this_oop, TRAPS) {
464
  relocate_and_link(this_oop, this_oop->methods(), THREAD);
465
}
466

467
void Rewriter::relocate_and_link(instanceKlassHandle this_oop,
468
                                 Array<Method*>* methods, TRAPS) {
469 470
  int len = methods->length();
  for (int i = len-1; i >= 0; i--) {
471
    methodHandle m(THREAD, methods->at(i));
472 473 474

    if (m->has_jsrs()) {
      m = rewrite_jsrs(m, CHECK);
D
duke 已提交
475
      // Method might have gotten rewritten.
476
      methods->at_put(i, m());
D
duke 已提交
477
    }
478

479
    // Set up method entry points for compiler and interpreter    .
480
    m->link_method(m, CHECK);
481

482
    // This is for JVMTI and unrelated to relocator but the last thing we do
483 484 485 486 487
#ifdef ASSERT
    if (StressMethodComparator) {
      static int nmc = 0;
      for (int j = i; j >= 0 && j >= i-4; j--) {
        if ((++nmc % 1000) == 0)  tty->print_cr("Have run MethodComparator %d times...", nmc);
488
        bool z = MethodComparator::methods_EMCP(m(),
489
                   methods->at(j));
490 491 492 493 494 495 496
        if (j == i && !z) {
          tty->print("MethodComparator FAIL: "); m->print(); m->print_codes();
          assert(z, "method must compare equal to itself");
        }
      }
    }
#endif //ASSERT
D
duke 已提交
497 498
  }
}