1 /*
   2  * Copyright (c) 2010, 2013, 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.nashorn.internal.runtime;
  27 
  28 import static jdk.nashorn.internal.lookup.Lookup.MH;
  29 
  30 import java.lang.invoke.MethodHandle;
  31 import java.lang.invoke.MethodHandles;
  32 import java.lang.invoke.MethodType;
  33 import java.util.ArrayList;
  34 import java.util.Arrays;
  35 import java.util.LinkedList;
  36 import jdk.internal.dynalink.support.NameCodec;
  37 
  38 import jdk.nashorn.internal.codegen.Compiler;
  39 import jdk.nashorn.internal.codegen.CompilerConstants;
  40 import jdk.nashorn.internal.codegen.FunctionSignature;
  41 import jdk.nashorn.internal.codegen.types.Type;
  42 import jdk.nashorn.internal.ir.FunctionNode;
  43 import jdk.nashorn.internal.ir.FunctionNode.CompilationState;
  44 import jdk.nashorn.internal.parser.Token;
  45 import jdk.nashorn.internal.parser.TokenType;
  46 
  47 /**
  48  * This is a subclass that represents a script function that may be regenerated,
  49  * for example with specialization based on call site types, or lazily generated.
  50  * The common denominator is that it can get new invokers during its lifespan,
  51  * unlike {@code FinalScriptFunctionData}
  52  */
  53 public final class RecompilableScriptFunctionData extends ScriptFunctionData {
  54 
  55     /** FunctionNode with the code for this ScriptFunction */
  56     private FunctionNode functionNode;
  57 
  58     /** Source from which FunctionNode was parsed. */
  59     private final Source source;
  60 
  61     /** Token of this function within the source. */
  62     private final long token;
  63 
  64     /** Allocator map from makeMap() */
  65     private final PropertyMap allocatorMap;
  66 
  67     /** Code installer used for all further recompilation/specialization of this ScriptFunction */
  68     private CodeInstaller<ScriptEnvironment> installer;
  69 
  70     /** Name of class where allocator function resides */
  71     private final String allocatorClassName;
  72 
  73     /** lazily generated allocator */
  74     private MethodHandle allocator;
  75 
  76     private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
  77 
  78     /**
  79      * Used for specialization based on runtime arguments. Whenever we specialize on
  80      * callsite parameter types at runtime, we need to use a parameter type guard to
  81      * ensure that the specialized version of the script function continues to be
  82      * applicable for a particular callsite *
  83      */
  84     private static final MethodHandle PARAM_TYPE_GUARD = findOwnMH("paramTypeGuard", boolean.class, Type[].class,  Object[].class);
  85 
  86     /**
  87      * It is usually a good gamble whever we detect a runtime callsite with a double
  88      * (or java.lang.Number instance) to specialize the parameter to an integer, if the
  89      * parameter in question can be represented as one. The double typically only exists
  90      * because the compiler doesn't know any better than "a number type" and conservatively
  91      * picks doubles when it can't prove that an integer addition wouldn't overflow
  92      */
  93     private static final MethodHandle ENSURE_INT = findOwnMH("ensureInt", int.class, Object.class);
  94 
  95     /**
  96      * Constructor - public as scripts use it
  97      *
  98      * @param functionNode       functionNode that represents this function code
  99      * @param installer          installer for code regeneration versions of this function
 100      * @param allocatorClassName name of our allocator class, will be looked up dynamically if used as a constructor
 101      * @param allocatorMap       allocator map to seed instances with, when constructing
 102      */
 103     public RecompilableScriptFunctionData(final FunctionNode functionNode, final CodeInstaller<ScriptEnvironment> installer, final String allocatorClassName, final PropertyMap allocatorMap) {
 104         super(functionName(functionNode),
 105               functionNode.getParameters().size(),
 106               functionNode.isStrict(),
 107               false,
 108               true);
 109 
 110         this.functionNode       = functionNode;
 111         this.source             = functionNode.getSource();
 112         this.token              = tokenFor(functionNode);
 113         this.installer          = installer;
 114         this.allocatorClassName = allocatorClassName;
 115         this.allocatorMap       = allocatorMap;
 116     }
 117 
 118     @Override
 119     String toSource() {
 120         if (source != null && token != 0) {
 121             return source.getString(Token.descPosition(token), Token.descLength(token));
 122         }
 123 
 124         return "function " + (name == null ? "" : name) + "() { [native code] }";
 125     }
 126 
 127     @Override
 128     public String toString() {
 129         final StringBuilder sb = new StringBuilder();
 130 
 131         if (source != null) {
 132             sb.append(source.getName())
 133                 .append(':')
 134                 .append(functionNode.getLineNumber())
 135                 .append(' ');

 136         }
 137 
 138         return sb.toString() + super.toString();
 139     }
 140 
 141     private static String functionName(final FunctionNode fn) {
 142         if (fn.isAnonymous()) {
 143             return "";
 144         } else {
 145             final FunctionNode.Kind kind = fn.getKind();
 146             if (kind == FunctionNode.Kind.GETTER || kind == FunctionNode.Kind.SETTER) {
 147                 final String name = NameCodec.decode(fn.getIdent().getName());
 148                 return name.substring(4); // 4 is "get " or "set "
 149             } else {
 150                 return fn.getIdent().getName();
 151             }
 152         }
 153     }
 154 
 155     private static long tokenFor(final FunctionNode fn) {
 156         final int  position   = Token.descPosition(fn.getFirstToken());
 157         final int  length     = Token.descPosition(fn.getLastToken()) - position + Token.descLength(fn.getLastToken());
 158 
 159         return Token.toDesc(TokenType.FUNCTION, position, length);
 160     }
 161 














 162     @Override
 163     ScriptObject allocate(final PropertyMap map) {
 164         try {
 165             ensureHasAllocator(); //if allocatorClass name is set to null (e.g. for bound functions) we don't even try
 166             return allocator == null ? null : (ScriptObject)allocator.invokeExact(map);
 167         } catch (final RuntimeException | Error e) {
 168             throw e;
 169         } catch (final Throwable t) {
 170             throw new RuntimeException(t);
 171         }
 172     }
 173 
 174     private void ensureHasAllocator() throws ClassNotFoundException {
 175         if (allocator == null && allocatorClassName != null) {
 176             this.allocator = MH.findStatic(LOOKUP, Context.forStructureClass(allocatorClassName), CompilerConstants.ALLOCATE.symbolName(), MH.type(ScriptObject.class, PropertyMap.class));
 177         }
 178     }
 179 
 180     @Override
 181     PropertyMap getAllocatorMap() {
 182         return allocatorMap;
 183     }
 184 
 185     @Override
 186     protected synchronized void ensureCodeGenerated() {
 187          if (!code.isEmpty()) {
 188              return; // nothing to do, we have code, at least some.
 189          }
 190 
 191          if (functionNode.isLazy()) {


 192              Compiler.LOG.info("Trampoline hit: need to do lazy compilation of '", functionNode.getName(), "'");
 193              final Compiler compiler = new Compiler(installer);
 194              functionNode = compiler.compile(functionNode);
 195              assert !functionNode.isLazy();
 196              compiler.install(functionNode);



 197 
 198              /*
 199               * We don't need to update any flags - varArgs and needsCallee are instrincic
 200               * in the function world we need to get a destination node from the compile instead
 201               * and replace it with our function node. TODO
 202               */
 203          }
 204 


 205          /*
 206           * We can't get to this program point unless we have bytecode, either from
 207           * eager compilation or from running a lazy compile on the lines above
 208           */
 209 
 210          assert functionNode.hasState(CompilationState.EMITTED) : functionNode.getName() + " " + functionNode.getState() + " " + Debug.id(functionNode);
 211 
 212          // code exists - look it up and add it into the automatically sorted invoker list
 213          addCode(functionNode);
 214 
 215          if (! functionNode.canSpecialize()) {
 216              // allow GC to claim IR stuff that is not needed anymore
 217              functionNode = null;
 218              installer = null;
 219          }
 220     }
 221 
 222     private MethodHandle addCode(final FunctionNode fn) {
 223         return addCode(fn, null, null, null);
 224     }
 225 
 226     private MethodHandle addCode(final FunctionNode fn, final MethodType runtimeType, final MethodHandle guard, final MethodHandle fallback) {
 227         final MethodType targetType = new FunctionSignature(fn).getMethodType();
 228         MethodHandle target =
 229             MH.findStatic(
 230                     LOOKUP,
 231                     fn.getCompileUnit().getCode(),
 232                     fn.getName(),
 233                     targetType);
 234 
 235         /*
 236          * For any integer argument. a double that is representable as an integer is OK.
 237          * otherwise the guard would have failed. in that case introduce a filter that
 238          * casts the double to an integer, which we know will preserve all precision.
 239          */
 240         for (int i = 0; i < targetType.parameterCount(); i++) {
 241             if (targetType.parameterType(i) == int.class) {
 242                 //representable as int
 243                 target = MH.filterArguments(target, i, ENSURE_INT);
 244             }
 245         }
 246 
 247         MethodHandle mh = target;
 248         if (guard != null) {
 249             mh = MH.guardWithTest(MH.asCollector(guard, Object[].class, target.type().parameterCount()), MH.asType(target, fallback.type()), fallback);
 250         }
 251 
 252         final CompiledFunction cf = new CompiledFunction(runtimeType == null ? targetType : runtimeType, mh);
 253         code.add(cf);
 254 
 255         return cf.getInvoker();
 256     }
 257 
 258     private static Type runtimeType(final Object arg) {
 259         if (arg == null) {
 260             return Type.OBJECT;
 261         }
 262 
 263         final Class<?> clazz = arg.getClass();
 264         assert !clazz.isPrimitive() : "always boxed";
 265         if (clazz == Double.class) {
 266             return JSType.isRepresentableAsInt((double)arg) ? Type.INT : Type.NUMBER;
 267         } else if (clazz == Integer.class) {
 268             return Type.INT;
 269         } else if (clazz == Long.class) {
 270             return Type.LONG;
 271         } else if (clazz == String.class) {
 272             return Type.STRING;
 273         }
 274         return Type.OBJECT;
 275     }
 276 
 277     private static boolean canCoerce(final Object arg, final Type type) {
 278         Type argType = runtimeType(arg);
 279         if (Type.widest(argType, type) == type || arg == ScriptRuntime.UNDEFINED) {
 280             return true;
 281         }
 282         System.err.println(arg + " does not fit in "+ argType + " " + type + " " + arg.getClass());
 283         new Throwable().printStackTrace();
 284         return false;
 285     }
 286 
 287     @SuppressWarnings("unused")
 288     private static boolean paramTypeGuard(final Type[] paramTypes, final Object... args) {
 289         final int length = args.length;
 290         assert args.length >= paramTypes.length;
 291 
 292         //i==start, skip the this, callee params etc
 293         int start = args.length - paramTypes.length;
 294         for (int i = start; i < args.length; i++) {
 295             final Object arg = args[i];
 296             if (!canCoerce(arg, paramTypes[i - start])) {
 297                 return false;
 298             }
 299         }
 300         return true;
 301     }
 302 
 303     @SuppressWarnings("unused")
 304     private static int ensureInt(final Object arg) {
 305         if (arg instanceof Number) {
 306             return ((Number)arg).intValue();
 307         } else if (arg instanceof Undefined) {
 308             return 0;
 309         }
 310         throw new AssertionError(arg);
 311     }
 312 
 313     /**
 314      * Given the runtime callsite args, compute a method type that is equivalent to what
 315      * was passed - this is typically a lot more specific that what the compiler has been
 316      * able to deduce
 317      * @param callSiteType callsite type for the compiled callsite target
 318      * @param args runtime arguments to the compiled callsite target
 319      * @return adjusted method type, narrowed as to conform to runtime callsite type instead
 320      */
 321     private static MethodType runtimeType(final MethodType callSiteType, final Object[] args) {
 322         if (args == null) {
 323             //for example bound, or otherwise runtime arguments to callsite unavailable, then
 324             //do not change the type
 325             return callSiteType;
 326         }
 327         final Class<?>[] paramTypes = new Class<?>[callSiteType.parameterCount()];
 328         final int        start      = args.length - callSiteType.parameterCount();
 329         for (int i = start; i < args.length; i++) {
 330             paramTypes[i - start] = runtimeType(args[i]).getTypeClass();
 331         }
 332         return MH.type(callSiteType.returnType(), paramTypes);
 333     }
 334 
 335     private static ArrayList<Type> runtimeType(final MethodType mt) {
 336         final ArrayList<Type> type = new ArrayList<>();
 337         for (int i = 0; i < mt.parameterCount(); i++) {
 338             type.add(Type.typeFor(mt.parameterType(i)));
 339         }
 340         return type;
 341     }
 342 
 343     @Override
 344     synchronized MethodHandle getBestInvoker(final MethodType callSiteType, final Object[] args) {
 345         final MethodType runtimeType = runtimeType(callSiteType, args);
 346         assert runtimeType.parameterCount() == callSiteType.parameterCount();
 347 
 348         final MethodHandle mh = super.getBestInvoker(runtimeType, args);
 349 
 350         /*
 351          * Not all functions can be specialized, for example, if we deemed memory
 352          * footprint too large to store a parse snapshot, or if it is meaningless
 353          * to do so, such as e.g. for runScript
 354          */
 355         if (functionNode == null || !functionNode.canSpecialize()) {
 356             return mh;
 357         }
 358 
 359         /*
 360          * Check if best invoker is equally specific or more specific than runtime
 361          * type. In that case, we don't need further specialization, but can use
 362          * whatever we have already. We know that it will match callSiteType, or it
 363          * would not have been returned from getBestInvoker
 364          */
 365         if (!code.isLessSpecificThan(runtimeType)) {
 366             return mh;
 367         }
 368 
 369         int i;
 370         final FunctionNode snapshot = functionNode.getSnapshot();
 371         assert snapshot != null;
 372 
 373         /*
 374          * Create a list of the arg types that the compiler knows about
 375          * typically, the runtime args are a lot more specific, and we should aggressively
 376          * try to use those whenever possible
 377          * We WILL try to make an aggressive guess as possible, and add guards if needed.
 378          * For example, if the compiler can deduce that we have a number type, but the runtime
 379          * passes and int, we might still want to keep it an int, and the gamble to
 380          * check that whatever is passed is int representable usually pays off
 381          * If the compiler only knows that a parameter is an "Object", it is still worth
 382          * it to try to specialize it by looking at the runtime arg.
 383          */
 384         final LinkedList<Type> compileTimeArgs = new LinkedList<>();
 385         for (i = callSiteType.parameterCount() - 1; i >= 0 && compileTimeArgs.size() < snapshot.getParameters().size(); i--) {
 386             compileTimeArgs.addFirst(Type.typeFor(callSiteType.parameterType(i)));
 387         }
 388 
 389         /*
 390          * The classes known at compile time are a safe to generate as primitives without parameter guards
 391          * But the classes known at runtime (if more specific than compile time types) are safe to generate as primitives
 392          * IFF there are parameter guards
 393          */
 394         MethodHandle guard = null;
 395         final ArrayList<Type> runtimeParamTypes = runtimeType(runtimeType);
 396         while (runtimeParamTypes.size() > functionNode.getParameters().size()) {
 397             runtimeParamTypes.remove(0);
 398         }
 399         for (i = 0; i < compileTimeArgs.size(); i++) {
 400             final Type rparam = Type.typeFor(runtimeType.parameterType(i));
 401             final Type cparam = compileTimeArgs.get(i);
 402 
 403             if (cparam.isObject() && !rparam.isObject()) {
 404                 //check that the runtime object is still coercible to the runtime type, because compiler can't prove it's always primitive
 405                 if (guard == null) {
 406                     guard = MH.insertArguments(PARAM_TYPE_GUARD, 0, (Object)runtimeParamTypes.toArray(new Type[runtimeParamTypes.size()]));
 407                 }
 408             }
 409         }
 410 
 411         Compiler.LOG.info("Callsite specialized ", name, " runtimeType=", runtimeType, " parameters=", snapshot.getParameters(), " args=", Arrays.asList(args));
 412 
 413         assert snapshot != null;
 414         assert snapshot != functionNode;
 415 
 416         final Compiler compiler = new Compiler(installer);
 417 
 418         final FunctionNode compiledSnapshot = compiler.compile(
 419             snapshot.setHints(
 420                 null,
 421                 new Compiler.Hints(runtimeParamTypes.toArray(new Type[runtimeParamTypes.size()]))));
 422 
 423         /*
 424          * No matter how narrow your types were, they can never be narrower than Attr during recompile made them. I.e. you
 425          * can put an int into the function here, if you see it as a runtime type, but if the function uses a multiplication
 426          * on it, it will still need to be a double. At least until we have overflow checks. Similarly, if an int is
 427          * passed but it is used as a string, it makes no sense to make the parameter narrower than Object. At least until
 428          * the "different types for one symbol in difference places" work is done
 429          */
 430         compiler.install(compiledSnapshot);
 431 
 432         return addCode(compiledSnapshot, runtimeType, guard, mh);
 433     }
 434 
 435     private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) {
 436         return MH.findStatic(MethodHandles.lookup(), RecompilableScriptFunctionData.class, name, MH.type(rtype, types));
 437     }
 438 
 439 }
 440 
--- EOF ---