CompiledFunction.java revision 1088:7e62d98d4625
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 */
25package jdk.nashorn.internal.runtime;
26
27import static jdk.nashorn.internal.lookup.Lookup.MH;
28import static jdk.nashorn.internal.runtime.UnwarrantedOptimismException.INVALID_PROGRAM_POINT;
29import static jdk.nashorn.internal.runtime.UnwarrantedOptimismException.isValid;
30import java.lang.invoke.CallSite;
31import java.lang.invoke.MethodHandle;
32import java.lang.invoke.MethodHandles;
33import java.lang.invoke.MethodType;
34import java.lang.invoke.MutableCallSite;
35import java.lang.invoke.SwitchPoint;
36import java.util.Collection;
37import java.util.Collections;
38import java.util.Iterator;
39import java.util.Map;
40import java.util.TreeMap;
41import java.util.function.Supplier;
42import java.util.logging.Level;
43import jdk.internal.dynalink.linker.GuardedInvocation;
44import jdk.nashorn.internal.codegen.Compiler;
45import jdk.nashorn.internal.codegen.Compiler.CompilationPhases;
46import jdk.nashorn.internal.codegen.TypeMap;
47import jdk.nashorn.internal.codegen.types.ArrayType;
48import jdk.nashorn.internal.codegen.types.Type;
49import jdk.nashorn.internal.ir.FunctionNode;
50import jdk.nashorn.internal.objects.annotations.SpecializedFunction.LinkLogic;
51import jdk.nashorn.internal.runtime.events.RecompilationEvent;
52import jdk.nashorn.internal.runtime.linker.Bootstrap;
53import jdk.nashorn.internal.runtime.logging.DebugLogger;
54
55/**
56 * An version of a JavaScript function, native or JavaScript.
57 * Supports lazily generating a constructor version of the invocation.
58 */
59final class CompiledFunction {
60
61    private static final MethodHandle NEWFILTER = findOwnMH("newFilter", Object.class, Object.class, Object.class);
62    private static final MethodHandle RELINK_COMPOSABLE_INVOKER = findOwnMH("relinkComposableInvoker", void.class, CallSite.class, CompiledFunction.class, boolean.class);
63    private static final MethodHandle HANDLE_REWRITE_EXCEPTION = findOwnMH("handleRewriteException", MethodHandle.class, CompiledFunction.class, OptimismInfo.class, RewriteException.class);
64    private static final MethodHandle RESTOF_INVOKER = MethodHandles.exactInvoker(MethodType.methodType(Object.class, RewriteException.class));
65
66    private final DebugLogger log;
67
68    static final Collection<CompiledFunction> NO_FUNCTIONS = Collections.emptySet();
69
70    /**
71     * The method type may be more specific than the invoker, if. e.g.
72     * the invoker is guarded, and a guard with a generic object only
73     * fallback, while the target is more specific, we still need the
74     * more specific type for sorting
75     */
76    private MethodHandle invoker;
77    private MethodHandle constructor;
78    private OptimismInfo optimismInfo;
79    private final int flags; // from FunctionNode
80    private final MethodType callSiteType;
81
82    private final Specialization specialization;
83
84    CompiledFunction(final MethodHandle invoker) {
85        this(invoker, null, null);
86    }
87
88    static CompiledFunction createBuiltInConstructor(final MethodHandle invoker, final Specialization specialization) {
89        return new CompiledFunction(MH.insertArguments(invoker, 0, false), createConstructorFromInvoker(MH.insertArguments(invoker, 0, true)), specialization);
90    }
91
92    CompiledFunction(final MethodHandle invoker, final MethodHandle constructor, final Specialization specialization) {
93        this(invoker, constructor, 0, null, specialization, DebugLogger.DISABLED_LOGGER);
94    }
95
96    CompiledFunction(final MethodHandle invoker, final MethodHandle constructor, final int flags, final MethodType callSiteType, final Specialization specialization, final DebugLogger log) {
97        this.specialization = specialization;
98        if (specialization != null && specialization.isOptimistic()) {
99            /*
100             * An optimistic builtin with isOptimistic=true works like any optimistic generated function, i.e. it
101             * can throw unwarranted optimism exceptions. As native functions trivially can't have parts of them
102             * regenerated as restof methods, this only works if the methods are atomic/functional in their behavior
103             * and doesn't modify state before an UOE can be thrown. If they aren't, we can reexecute a wider version
104             * of the same builtin in a recompilation handler for FinalScriptFunctionData. There are several
105             * candidate methods in Native* that would benefit from this, but I haven't had time to implement any
106             * of them currently. In order to fit in with the relinking framework, the current thinking is
107             * that the methods still take a program point to fit in with other optimistic functions, but
108             * it is set to "first", which is the beginning of the method. The relinker can tell the difference
109             * between builtin and JavaScript functions. This might change. TODO
110             */
111            this.invoker = MH.insertArguments(invoker, invoker.type().parameterCount() - 1, UnwarrantedOptimismException.FIRST_PROGRAM_POINT);
112            throw new AssertionError("Optimistic (UnwarrantedOptimismException throwing) builtin functions are currently not in use");
113        }
114        this.invoker = invoker;
115        this.constructor = constructor;
116        this.flags = flags;
117        this.callSiteType = callSiteType;
118        this.log = log;
119    }
120
121    CompiledFunction(final MethodHandle invoker, final RecompilableScriptFunctionData functionData,
122            final Map<Integer, Type> invalidatedProgramPoints, final MethodType callSiteType, final int flags) {
123        this(invoker, null, flags, callSiteType, null, functionData.getLogger());
124        if ((flags & FunctionNode.IS_DEOPTIMIZABLE) != 0) {
125            optimismInfo = new OptimismInfo(functionData, invalidatedProgramPoints);
126        } else {
127            optimismInfo = null;
128        }
129    }
130
131    static CompiledFunction createBuiltInConstructor(final MethodHandle invoker) {
132        return new CompiledFunction(MH.insertArguments(invoker, 0, false), createConstructorFromInvoker(MH.insertArguments(invoker, 0, true)), null);
133    }
134
135    boolean isSpecialization() {
136        return specialization != null;
137    }
138
139    boolean hasLinkLogic() {
140        return getLinkLogicClass() != null;
141    }
142
143    Class<? extends LinkLogic> getLinkLogicClass() {
144        if (isSpecialization()) {
145            final Class<? extends LinkLogic> linkLogicClass = specialization.getLinkLogicClass();
146            assert !LinkLogic.isEmpty(linkLogicClass) : "empty link logic classes should have been removed by nasgen";
147            return linkLogicClass;
148        }
149        return null;
150    }
151
152    int getFlags() {
153        return flags;
154    }
155
156    /**
157     * An optimistic specialization is one that can throw UnwarrantedOptimismException.
158     * This is allowed for native methods, as long as they are functional, i.e. don't change
159     * any state between entering and throwing the UOE. Then we can re-execute a wider version
160     * of the method in the continuation. Rest-of method generation for optimistic builtins is
161     * of course not possible, but this approach works and fits into the same relinking
162     * framework
163     *
164     * @return true if optimistic builtin
165     */
166    boolean isOptimistic() {
167        return isSpecialization() ? specialization.isOptimistic() : false;
168    }
169
170    boolean isApplyToCall() {
171        return (flags & FunctionNode.HAS_APPLY_TO_CALL_SPECIALIZATION) != 0;
172    }
173
174    boolean isVarArg() {
175        return isVarArgsType(invoker.type());
176    }
177
178    @Override
179    public String toString() {
180        final StringBuilder sb = new StringBuilder();
181        final Class<? extends LinkLogic> linkLogicClass = getLinkLogicClass();
182
183        sb.append("[invokerType=").
184            append(invoker.type()).
185            append(" ctor=").
186            append(constructor).
187            append(" weight=").
188            append(weight()).
189            append(" linkLogic=").
190            append(linkLogicClass != null ? linkLogicClass.getSimpleName() : "none");
191
192        return sb.toString();
193    }
194
195    boolean needsCallee() {
196        return ScriptFunctionData.needsCallee(invoker);
197    }
198
199    /**
200     * Returns an invoker method handle for this function. Note that the handle is safely composable in
201     * the sense that you can compose it with other handles using any combinators even if you can't affect call site
202     * invalidation. If this compiled function is non-optimistic, then it returns the same value as
203     * {@link #getInvokerOrConstructor(boolean)}. However, if the function is optimistic, then this handle will
204     * incur an overhead as it will add an intermediate internal call site that can relink itself when the function
205     * needs to regenerate its code to always point at the latest generated code version.
206     * @return a guaranteed composable invoker method handle for this function.
207     */
208    MethodHandle createComposableInvoker() {
209        return createComposableInvoker(false);
210    }
211
212    /**
213     * Returns an invoker method handle for this function when invoked as a constructor. Note that the handle should be
214     * considered non-composable in the sense that you can only compose it with other handles using any combinators if
215     * you can ensure that the composition is guarded by {@link #getOptimisticAssumptionsSwitchPoint()} if it's
216     * non-null, and that you can relink the call site it is set into as a target if the switch point is invalidated. In
217     * all other cases, use {@link #createComposableConstructor()}.
218     * @return a direct constructor method handle for this function.
219     */
220    private MethodHandle getConstructor() {
221        if (constructor == null) {
222            constructor = createConstructorFromInvoker(createInvokerForPessimisticCaller());
223        }
224
225        return constructor;
226    }
227
228    /**
229     * Creates a version of the invoker intended for a pessimistic caller (return type is Object, no caller optimistic
230     * program point available).
231     * @return a version of the invoker intended for a pessimistic caller.
232     */
233    private MethodHandle createInvokerForPessimisticCaller() {
234        return createInvoker(Object.class, INVALID_PROGRAM_POINT);
235    }
236
237    /**
238     * Compose a constructor from an invoker.
239     *
240     * @param invoker         invoker
241     * @return the composed constructor
242     */
243    private static MethodHandle createConstructorFromInvoker(final MethodHandle invoker) {
244        final boolean needsCallee = ScriptFunctionData.needsCallee(invoker);
245        // If it was (callee, this, args...), permute it to (this, callee, args...). We're doing this because having
246        // "this" in the first argument position is what allows the elegant folded composition of
247        // (newFilter x constructor x allocator) further down below in the code. Also, ensure the composite constructor
248        // always returns Object.
249        final MethodHandle swapped = needsCallee ? swapCalleeAndThis(invoker) : invoker;
250
251        final MethodHandle returnsObject = MH.asType(swapped, swapped.type().changeReturnType(Object.class));
252
253        final MethodType ctorType = returnsObject.type();
254
255        // Construct a dropping type list for NEWFILTER, but don't include constructor "this" into it, so it's actually
256        // captured as "allocation" parameter of NEWFILTER after we fold the constructor into it.
257        // (this, [callee, ]args...) => ([callee, ]args...)
258        final Class<?>[] ctorArgs = ctorType.dropParameterTypes(0, 1).parameterArray();
259
260        // Fold constructor into newFilter that replaces the return value from the constructor with the originally
261        // allocated value when the originally allocated value is a JS primitive (String, Boolean, Number).
262        // (result, this, [callee, ]args...) x (this, [callee, ]args...) => (this, [callee, ]args...)
263        final MethodHandle filtered = MH.foldArguments(MH.dropArguments(NEWFILTER, 2, ctorArgs), returnsObject);
264
265        // allocate() takes a ScriptFunction and returns a newly allocated ScriptObject...
266        if (needsCallee) {
267            // ...we either fold it into the previous composition, if we need both the ScriptFunction callee object and
268            // the newly allocated object in the arguments, so (this, callee, args...) x (callee) => (callee, args...),
269            // or...
270            return MH.foldArguments(filtered, ScriptFunction.ALLOCATE);
271        }
272
273        // ...replace the ScriptFunction argument with the newly allocated object, if it doesn't need the callee
274        // (this, args...) filter (callee) => (callee, args...)
275        return MH.filterArguments(filtered, 0, ScriptFunction.ALLOCATE);
276    }
277
278    /**
279     * Permutes the parameters in the method handle from {@code (callee, this, ...)} to {@code (this, callee, ...)}.
280     * Used when creating a constructor handle.
281     * @param mh a method handle with order of arguments {@code (callee, this, ...)}
282     * @return a method handle with order of arguments {@code (this, callee, ...)}
283     */
284    private static MethodHandle swapCalleeAndThis(final MethodHandle mh) {
285        final MethodType type = mh.type();
286        assert type.parameterType(0) == ScriptFunction.class : type;
287        assert type.parameterType(1) == Object.class : type;
288        final MethodType newType = type.changeParameterType(0, Object.class).changeParameterType(1, ScriptFunction.class);
289        final int[] reorder = new int[type.parameterCount()];
290        reorder[0] = 1;
291        assert reorder[1] == 0;
292        for (int i = 2; i < reorder.length; ++i) {
293            reorder[i] = i;
294        }
295        return MethodHandles.permuteArguments(mh, newType, reorder);
296    }
297
298    /**
299     * Returns an invoker method handle for this function when invoked as a constructor. Note that the handle is safely
300     * composable in the sense that you can compose it with other handles using any combinators even if you can't affect
301     * call site invalidation. If this compiled function is non-optimistic, then it returns the same value as
302     * {@link #getConstructor()}. However, if the function is optimistic, then this handle will incur an overhead as it
303     * will add an intermediate internal call site that can relink itself when the function needs to regenerate its code
304     * to always point at the latest generated code version.
305     * @return a guaranteed composable constructor method handle for this function.
306     */
307    MethodHandle createComposableConstructor() {
308        return createComposableInvoker(true);
309    }
310
311    boolean hasConstructor() {
312        return constructor != null;
313    }
314
315    MethodType type() {
316        return invoker.type();
317    }
318
319    int weight() {
320        return weight(type());
321    }
322
323    private static int weight(final MethodType type) {
324        if (isVarArgsType(type)) {
325            return Integer.MAX_VALUE; //if there is a varargs it should be the heavist and last fallback
326        }
327
328        int weight = Type.typeFor(type.returnType()).getWeight();
329        for (int i = 0 ; i < type.parameterCount() ; i++) {
330            final Class<?> paramType = type.parameterType(i);
331            final int pweight = Type.typeFor(paramType).getWeight() * 2; //params are more important than call types as return values are always specialized
332            weight += pweight;
333        }
334
335        weight += type.parameterCount(); //more params outweigh few parameters
336
337        return weight;
338    }
339
340    static boolean isVarArgsType(final MethodType type) {
341        assert type.parameterCount() >= 1 : type;
342        return type.parameterType(type.parameterCount() - 1) == Object[].class;
343    }
344
345    static boolean moreGenericThan(final MethodType mt0, final MethodType mt1) {
346        return weight(mt0) > weight(mt1);
347    }
348
349    boolean betterThanFinal(final CompiledFunction other, final MethodType callSiteMethodType) {
350        // Prefer anything over nothing, as we can't compile new versions.
351        if (other == null) {
352            return true;
353        }
354        return betterThanFinal(this, other, callSiteMethodType);
355    }
356
357    private static boolean betterThanFinal(final CompiledFunction cf, final CompiledFunction other, final MethodType callSiteMethodType) {
358        final MethodType thisMethodType  = cf.type();
359        final MethodType otherMethodType = other.type();
360        final int thisParamCount = getParamCount(thisMethodType);
361        final int otherParamCount = getParamCount(otherMethodType);
362        final int callSiteRawParamCount = getParamCount(callSiteMethodType);
363        final boolean csVarArg = callSiteRawParamCount == Integer.MAX_VALUE;
364        // Subtract 1 for callee for non-vararg call sites
365        final int callSiteParamCount = csVarArg ? callSiteRawParamCount : callSiteRawParamCount - 1;
366
367        // Prefer the function that discards less parameters
368        final int thisDiscardsParams = Math.max(callSiteParamCount - thisParamCount, 0);
369        final int otherDiscardsParams = Math.max(callSiteParamCount - otherParamCount, 0);
370        if(thisDiscardsParams < otherDiscardsParams) {
371            return true;
372        }
373        if(thisDiscardsParams > otherDiscardsParams) {
374            return false;
375        }
376
377        final boolean thisVarArg = thisParamCount == Integer.MAX_VALUE;
378        final boolean otherVarArg = otherParamCount == Integer.MAX_VALUE;
379        if(!(thisVarArg && otherVarArg && csVarArg)) {
380            // At least one of them isn't vararg
381            final Type[] thisType = toTypeWithoutCallee(thisMethodType, 0); // Never has callee
382            final Type[] otherType = toTypeWithoutCallee(otherMethodType, 0); // Never has callee
383            final Type[] callSiteType = toTypeWithoutCallee(callSiteMethodType, 1); // Always has callee
384
385            int narrowWeightDelta = 0;
386            int widenWeightDelta = 0;
387            final int minParamsCount = Math.min(Math.min(thisParamCount, otherParamCount), callSiteParamCount);
388            for(int i = 0; i < minParamsCount; ++i) {
389                final int callSiteParamWeight = getParamType(i, callSiteType, csVarArg).getWeight();
390                // Delta is negative for narrowing, positive for widening
391                final int thisParamWeightDelta = getParamType(i, thisType, thisVarArg).getWeight() - callSiteParamWeight;
392                final int otherParamWeightDelta = getParamType(i, otherType, otherVarArg).getWeight() - callSiteParamWeight;
393                // Only count absolute values of narrowings
394                narrowWeightDelta += Math.max(-thisParamWeightDelta, 0) - Math.max(-otherParamWeightDelta, 0);
395                // Only count absolute values of widenings
396                widenWeightDelta += Math.max(thisParamWeightDelta, 0) - Math.max(otherParamWeightDelta, 0);
397            }
398
399            // If both functions accept more arguments than what is passed at the call site, account for ability
400            // to receive Undefined un-narrowed in the remaining arguments.
401            if(!thisVarArg) {
402                for(int i = callSiteParamCount; i < thisParamCount; ++i) {
403                    narrowWeightDelta += Math.max(Type.OBJECT.getWeight() - thisType[i].getWeight(), 0);
404                }
405            }
406            if(!otherVarArg) {
407                for(int i = callSiteParamCount; i < otherParamCount; ++i) {
408                    narrowWeightDelta -= Math.max(Type.OBJECT.getWeight() - otherType[i].getWeight(), 0);
409                }
410            }
411
412            // Prefer function that narrows less
413            if(narrowWeightDelta < 0) {
414                return true;
415            }
416            if(narrowWeightDelta > 0) {
417                return false;
418            }
419
420            // Prefer function that widens less
421            if(widenWeightDelta < 0) {
422                return true;
423            }
424            if(widenWeightDelta > 0) {
425                return false;
426            }
427        }
428
429        // Prefer the function that exactly matches the arity of the call site.
430        if(thisParamCount == callSiteParamCount && otherParamCount != callSiteParamCount) {
431            return true;
432        }
433        if(thisParamCount != callSiteParamCount && otherParamCount == callSiteParamCount) {
434            return false;
435        }
436
437        // Otherwise, neither function matches arity exactly. We also know that at this point, they both can receive
438        // more arguments than call site, otherwise we would've already chosen the one that discards less parameters.
439        // Note that variable arity methods are preferred, as they actually match the call site arity better, since they
440        // really have arbitrary arity.
441        if(thisVarArg) {
442            if(!otherVarArg) {
443                return true; //
444            }
445        } else if(otherVarArg) {
446            return false;
447        }
448
449        // Neither is variable arity; chose the one that has less extra parameters.
450        final int fnParamDelta = thisParamCount - otherParamCount;
451        if(fnParamDelta < 0) {
452            return true;
453        }
454        if(fnParamDelta > 0) {
455            return false;
456        }
457
458        final int callSiteRetWeight = Type.typeFor(callSiteMethodType.returnType()).getWeight();
459        // Delta is negative for narrower return type, positive for wider return type
460        final int thisRetWeightDelta = Type.typeFor(thisMethodType.returnType()).getWeight() - callSiteRetWeight;
461        final int otherRetWeightDelta = Type.typeFor(otherMethodType.returnType()).getWeight() - callSiteRetWeight;
462
463        // Prefer function that returns a less wide return type
464        final int widenRetDelta = Math.max(thisRetWeightDelta, 0) - Math.max(otherRetWeightDelta, 0);
465        if(widenRetDelta < 0) {
466            return true;
467        }
468        if(widenRetDelta > 0) {
469            return false;
470        }
471
472        // Prefer function that returns a less narrow return type
473        final int narrowRetDelta = Math.max(-thisRetWeightDelta, 0) - Math.max(-otherRetWeightDelta, 0);
474        if(narrowRetDelta < 0) {
475            return true;
476        }
477        if(narrowRetDelta > 0) {
478            return false;
479        }
480
481        //if they are equal, pick the specialized one first
482        if (cf.isSpecialization() != other.isSpecialization()) {
483            return cf.isSpecialization(); //always pick the specialized version if we can
484        }
485
486        if (cf.isSpecialization() && other.isSpecialization()) {
487            return cf.getLinkLogicClass() != null; //pick link logic specialization above generic specializations
488        }
489
490        // Signatures are identical
491        throw new AssertionError(thisMethodType + " identically applicable to " + otherMethodType + " for " + callSiteMethodType);
492    }
493
494    private static Type[] toTypeWithoutCallee(final MethodType type, final int thisIndex) {
495        final int paramCount = type.parameterCount();
496        final Type[] t = new Type[paramCount - thisIndex];
497        for(int i = thisIndex; i < paramCount; ++i) {
498            t[i - thisIndex] = Type.typeFor(type.parameterType(i));
499        }
500        return t;
501    }
502
503    private static Type getParamType(final int i, final Type[] paramTypes, final boolean isVarArg) {
504        final int fixParamCount = paramTypes.length - (isVarArg ? 1 : 0);
505        if(i < fixParamCount) {
506            return paramTypes[i];
507        }
508        assert isVarArg;
509        return ((ArrayType)paramTypes[paramTypes.length - 1]).getElementType();
510    }
511
512    boolean matchesCallSite(final MethodType other, final boolean pickVarArg) {
513        if (other.equals(this.callSiteType)) {
514            return true;
515        }
516        final MethodType type  = type();
517        final int fnParamCount = getParamCount(type);
518        final boolean isVarArg = fnParamCount == Integer.MAX_VALUE;
519        if (isVarArg) {
520            return pickVarArg;
521        }
522
523        final int csParamCount = getParamCount(other);
524        final boolean csIsVarArg = csParamCount == Integer.MAX_VALUE;
525        final int thisThisIndex = needsCallee() ? 1 : 0; // Index of "this" parameter in this function's type
526
527        final int fnParamCountNoCallee = fnParamCount - thisThisIndex;
528        final int minParams = Math.min(csParamCount - 1, fnParamCountNoCallee); // callSiteType always has callee, so subtract 1
529        // We must match all incoming parameters, except "this". Starting from 1 to skip "this".
530        for(int i = 1; i < minParams; ++i) {
531            final Type fnType = Type.typeFor(type.parameterType(i + thisThisIndex));
532            final Type csType = csIsVarArg ? Type.OBJECT : Type.typeFor(other.parameterType(i + 1));
533            if(!fnType.isEquivalentTo(csType)) {
534                return false;
535            }
536        }
537
538        // Must match any undefined parameters to Object type.
539        for(int i = minParams; i < fnParamCountNoCallee; ++i) {
540            if(!Type.typeFor(type.parameterType(i + thisThisIndex)).isEquivalentTo(Type.OBJECT)) {
541                return false;
542            }
543        }
544
545        return true;
546    }
547
548    private static int getParamCount(final MethodType type) {
549        final int paramCount = type.parameterCount();
550        return type.parameterType(paramCount - 1).isArray() ? Integer.MAX_VALUE : paramCount;
551    }
552
553    private boolean canBeDeoptimized() {
554        return optimismInfo != null;
555    }
556
557    private MethodHandle createComposableInvoker(final boolean isConstructor) {
558        final MethodHandle handle = getInvokerOrConstructor(isConstructor);
559
560        // If compiled function is not optimistic, it can't ever change its invoker/constructor, so just return them
561        // directly.
562        if(!canBeDeoptimized()) {
563            return handle;
564        }
565
566        // Otherwise, we need a new level of indirection; need to introduce a mutable call site that can relink itslef
567        // to the compiled function's changed target whenever the optimistic assumptions are invalidated.
568        final CallSite cs = new MutableCallSite(handle.type());
569        relinkComposableInvoker(cs, this, isConstructor);
570        return cs.dynamicInvoker();
571    }
572
573    private static class HandleAndAssumptions {
574        final MethodHandle handle;
575        final SwitchPoint assumptions;
576
577        HandleAndAssumptions(final MethodHandle handle, final SwitchPoint assumptions) {
578            this.handle = handle;
579            this.assumptions = assumptions;
580        }
581
582        GuardedInvocation createInvocation() {
583            return new GuardedInvocation(handle, assumptions);
584        }
585    }
586
587    /**
588     * Returns a pair of an invocation created with a passed-in supplier and a non-invalidated switch point for
589     * optimistic assumptions (or null for the switch point if the function can not be deoptimized). While the method
590     * makes a best effort to return a non-invalidated switch point (compensating for possible deoptimizing
591     * recompilation happening on another thread) it is still possible that by the time this method returns the
592     * switchpoint has been invalidated by a {@code RewriteException} triggered on another thread for this function.
593     * This is not a problem, though, as these switch points are always used to produce call sites that fall back to
594     * relinking when they are invalidated, and in this case the execution will end up here again. What this method
595     * basically does is minimize such busy-loop relinking while the function is being recompiled on a different thread.
596     * @param invocationSupplier the supplier that constructs the actual invocation method handle; should use the
597     * {@code CompiledFunction} method itself in some capacity.
598     * @return a tuple object containing the method handle as created by the supplier and an optimistic assumptions
599     * switch point that is guaranteed to not have been invalidated before the call to this method (or null if the
600     * function can't be further deoptimized).
601     */
602    private synchronized HandleAndAssumptions getValidOptimisticInvocation(final Supplier<MethodHandle> invocationSupplier) {
603        for(;;) {
604            final MethodHandle handle = invocationSupplier.get();
605            final SwitchPoint assumptions = canBeDeoptimized() ? optimismInfo.optimisticAssumptions : null;
606            if(assumptions != null && assumptions.hasBeenInvalidated()) {
607                // We can be in a situation where one thread is in the middle of a deoptimizing compilation when we hit
608                // this and thus, it has invalidated the old switch point, but hasn't created the new one yet. Note that
609                // the behavior of invalidating the old switch point before recompilation, and only creating the new one
610                // after recompilation is by design. If we didn't wait here for the recompilation to complete, we would
611                // be busy looping through the fallback path of the invalidated switch point, relinking the call site
612                // again with the same invalidated switch point, invoking the fallback, etc. stealing CPU cycles from
613                // the recompilation task we're dependent on. This can still happen if the switch point gets invalidated
614                // after we grabbed it here, in which case we'll indeed do one busy relink immediately.
615                try {
616                    wait();
617                } catch (final InterruptedException e) {
618                    // Intentionally ignored. There's nothing meaningful we can do if we're interrupted
619                }
620            } else {
621                return new HandleAndAssumptions(handle, assumptions);
622            }
623        }
624    }
625
626    private static void relinkComposableInvoker(final CallSite cs, final CompiledFunction inv, final boolean constructor) {
627        final HandleAndAssumptions handleAndAssumptions = inv.getValidOptimisticInvocation(new Supplier<MethodHandle>() {
628            @Override
629            public MethodHandle get() {
630                return inv.getInvokerOrConstructor(constructor);
631            }
632        });
633        final MethodHandle handle = handleAndAssumptions.handle;
634        final SwitchPoint assumptions = handleAndAssumptions.assumptions;
635        final MethodHandle target;
636        if(assumptions == null) {
637            target = handle;
638        } else {
639            final MethodHandle relink = MethodHandles.insertArguments(RELINK_COMPOSABLE_INVOKER, 0, cs, inv, constructor);
640            target = assumptions.guardWithTest(handle, MethodHandles.foldArguments(cs.dynamicInvoker(), relink));
641        }
642        cs.setTarget(target.asType(cs.type()));
643    }
644
645    private MethodHandle getInvokerOrConstructor(final boolean selectCtor) {
646        return selectCtor ? getConstructor() : createInvokerForPessimisticCaller();
647    }
648
649    /**
650     * Returns a guarded invocation for this function when not invoked as a constructor. The guarded invocation has no
651     * guard but it potentially has an optimistic assumptions switch point. As such, it will probably not be used as a
652     * final guarded invocation, but rather as a holder for an invocation handle and switch point to be decomposed and
653     * reassembled into a different final invocation by the user of this method. Any recompositions should take care to
654     * continue to use the switch point. If that is not possible, use {@link #createComposableInvoker()} instead.
655     * @return a guarded invocation for an ordinary (non-constructor) invocation of this function.
656     */
657    GuardedInvocation createFunctionInvocation(final Class<?> callSiteReturnType, final int callerProgramPoint) {
658        return getValidOptimisticInvocation(new Supplier<MethodHandle>() {
659            @Override
660            public MethodHandle get() {
661                return createInvoker(callSiteReturnType, callerProgramPoint);
662            }
663        }).createInvocation();
664    }
665
666    /**
667     * Returns a guarded invocation for this function when invoked as a constructor. The guarded invocation has no guard
668     * but it potentially has an optimistic assumptions switch point. As such, it will probably not be used as a final
669     * guarded invocation, but rather as a holder for an invocation handle and switch point to be decomposed and
670     * reassembled into a different final invocation by the user of this method. Any recompositions should take care to
671     * continue to use the switch point. If that is not possible, use {@link #createComposableConstructor()} instead.
672     * @return a guarded invocation for invocation of this function as a constructor.
673     */
674    GuardedInvocation createConstructorInvocation() {
675        return getValidOptimisticInvocation(new Supplier<MethodHandle>() {
676            @Override
677            public MethodHandle get() {
678                return getConstructor();
679            }
680        }).createInvocation();
681    }
682
683    private MethodHandle createInvoker(final Class<?> callSiteReturnType, final int callerProgramPoint) {
684        final boolean isOptimistic = canBeDeoptimized();
685        MethodHandle handleRewriteException = isOptimistic ? createRewriteExceptionHandler() : null;
686
687        MethodHandle inv = invoker;
688        if(isValid(callerProgramPoint)) {
689            inv = OptimisticReturnFilters.filterOptimisticReturnValue(inv, callSiteReturnType, callerProgramPoint);
690            inv = changeReturnType(inv, callSiteReturnType);
691            if(callSiteReturnType.isPrimitive() && handleRewriteException != null) {
692                // because handleRewriteException always returns Object
693                handleRewriteException = OptimisticReturnFilters.filterOptimisticReturnValue(handleRewriteException,
694                        callSiteReturnType, callerProgramPoint);
695            }
696        } else if(isOptimistic) {
697            // Required so that rewrite exception has the same return type. It'd be okay to do it even if we weren't
698            // optimistic, but it isn't necessary as the linker upstream will eventually convert the return type.
699            inv = changeReturnType(inv, callSiteReturnType);
700        }
701
702        if(isOptimistic) {
703            assert handleRewriteException != null;
704            final MethodHandle typedHandleRewriteException = changeReturnType(handleRewriteException, inv.type().returnType());
705            return MH.catchException(inv, RewriteException.class, typedHandleRewriteException);
706        }
707        return inv;
708    }
709
710    private MethodHandle createRewriteExceptionHandler() {
711        return MH.foldArguments(RESTOF_INVOKER, MH.insertArguments(HANDLE_REWRITE_EXCEPTION, 0, this, optimismInfo));
712    }
713
714    private static MethodHandle changeReturnType(final MethodHandle mh, final Class<?> newReturnType) {
715        return Bootstrap.getLinkerServices().asType(mh, mh.type().changeReturnType(newReturnType));
716    }
717
718    @SuppressWarnings("unused")
719    private static MethodHandle handleRewriteException(final CompiledFunction function, final OptimismInfo oldOptimismInfo, final RewriteException re) {
720        return function.handleRewriteException(oldOptimismInfo, re);
721    }
722
723    /**
724     * Debug function for printing out all invalidated program points and their
725     * invalidation mapping to next type
726     * @param ipp
727     * @return string describing the ipp map
728     */
729    private static String toStringInvalidations(final Map<Integer, Type> ipp) {
730        if (ipp == null) {
731            return "";
732        }
733
734        final StringBuilder sb = new StringBuilder();
735
736        for (final Iterator<Map.Entry<Integer, Type>> iter = ipp.entrySet().iterator(); iter.hasNext(); ) {
737            final Map.Entry<Integer, Type> entry = iter.next();
738            final char bct = entry.getValue().getBytecodeStackType();
739
740            sb.append('[').
741                    append(entry.getKey()).
742                    append("->").
743                    append(bct == 'A' ? 'O' : bct).
744                    append(']');
745
746            if (iter.hasNext()) {
747                sb.append(' ');
748            }
749        }
750
751        return sb.toString();
752    }
753
754    private void logRecompile(final String reason, final FunctionNode fn, final MethodType type, final Map<Integer, Type> ipp) {
755        if (log.isEnabled()) {
756            log.info(reason, DebugLogger.quote(fn.getName()), " signature: ", type, " ", toStringInvalidations(ipp));
757        }
758    }
759
760    /**
761     * Handles a {@link RewriteException} raised during the execution of this function by recompiling (if needed) the
762     * function with an optimistic assumption invalidated at the program point indicated by the exception, and then
763     * executing a rest-of method to complete the execution with the deoptimized version.
764     * @param oldOptInfo the optimism info of this function. We must store it explicitly as a bound argument in the
765     * method handle, otherwise it could be null for handling a rewrite exception in an outer invocation of a recursive
766     * function when recursive invocations of the function have completely deoptimized it.
767     * @param re the rewrite exception that was raised
768     * @return the method handle for the rest-of method, for folding composition.
769     */
770    private synchronized MethodHandle handleRewriteException(final OptimismInfo oldOptInfo, final RewriteException re) {
771        if (log.isEnabled()) {
772            log.info(new RecompilationEvent(Level.INFO, re, re.getReturnValueNonDestructive()), "RewriteException ", re.getMessageShort());
773        }
774
775        final MethodType type = type();
776
777        // Compiler needs a call site type as its input, which always has a callee parameter, so we must add it if
778        // this function doesn't have a callee parameter.
779        final MethodType ct = type.parameterType(0) == ScriptFunction.class ?
780                type :
781                type.insertParameterTypes(0, ScriptFunction.class);
782        final OptimismInfo currentOptInfo = optimismInfo;
783        final boolean shouldRecompile = currentOptInfo != null && currentOptInfo.requestRecompile(re);
784
785        // Effective optimism info, for subsequent use. We'll normally try to use the current (latest) one, but if it
786        // isn't available, we'll use the old one bound into the call site.
787        final OptimismInfo effectiveOptInfo = currentOptInfo != null ? currentOptInfo : oldOptInfo;
788        FunctionNode fn = effectiveOptInfo.reparse();
789        final boolean serialized = effectiveOptInfo.isSerialized();
790        final Compiler compiler = effectiveOptInfo.getCompiler(fn, ct, re); //set to non rest-of
791
792        if (!shouldRecompile) {
793            // It didn't necessarily recompile, e.g. for an outer invocation of a recursive function if we already
794            // recompiled a deoptimized version for an inner invocation.
795            // We still need to do the rest of from the beginning
796            logRecompile("Rest-of compilation [STANDALONE] ", fn, ct, effectiveOptInfo.invalidatedProgramPoints);
797            return restOfHandle(effectiveOptInfo, compiler.compile(fn, serialized ? CompilationPhases.COMPILE_SERIALIZED_RESTOF : CompilationPhases.COMPILE_ALL_RESTOF), currentOptInfo != null);
798        }
799
800        logRecompile("Deoptimizing recompilation (up to bytecode) ", fn, ct, effectiveOptInfo.invalidatedProgramPoints);
801        fn = compiler.compile(fn, serialized ? CompilationPhases.RECOMPILE_SERIALIZED_UPTO_BYTECODE : CompilationPhases.COMPILE_UPTO_BYTECODE);
802        log.info("Reusable IR generated");
803
804        // compile the rest of the function, and install it
805        log.info("Generating and installing bytecode from reusable IR...");
806        logRecompile("Rest-of compilation [CODE PIPELINE REUSE] ", fn, ct, effectiveOptInfo.invalidatedProgramPoints);
807        final FunctionNode normalFn = compiler.compile(fn, CompilationPhases.GENERATE_BYTECODE_AND_INSTALL);
808
809        if (effectiveOptInfo.data.usePersistentCodeCache()) {
810            final RecompilableScriptFunctionData data = effectiveOptInfo.data;
811            final int functionNodeId = data.getFunctionNodeId();
812            final TypeMap typeMap = data.typeMap(ct);
813            final Type[] paramTypes = typeMap == null ? null : typeMap.getParameterTypes(functionNodeId);
814            final String cacheKey = CodeStore.getCacheKey(functionNodeId, paramTypes);
815            compiler.persistClassInfo(cacheKey, normalFn);
816        }
817
818        log.info("Done.");
819
820        final boolean canBeDeoptimized = normalFn.canBeDeoptimized();
821
822        if (log.isEnabled()) {
823            log.info("Recompiled '", fn.getName(), "' (", Debug.id(this), ") ", canBeDeoptimized ? " can still be deoptimized." : " is completely deoptimized.");
824        }
825
826        log.info("Looking up invoker...");
827
828        final MethodHandle newInvoker = effectiveOptInfo.data.lookup(fn);
829        invoker     = newInvoker.asType(type.changeReturnType(newInvoker.type().returnType()));
830        constructor = null; // Will be regenerated when needed
831
832        log.info("Done: ", invoker);
833        final MethodHandle restOf = restOfHandle(effectiveOptInfo, compiler.compile(fn, CompilationPhases.GENERATE_BYTECODE_AND_INSTALL_RESTOF), canBeDeoptimized);
834
835        // Note that we only adjust the switch point after we set the invoker/constructor. This is important.
836        if (canBeDeoptimized) {
837            effectiveOptInfo.newOptimisticAssumptions(); // Otherwise, set a new switch point.
838        } else {
839            optimismInfo = null; // If we got to a point where we no longer have optimistic assumptions, let the optimism info go.
840        }
841        notifyAll();
842
843        return restOf;
844    }
845
846    private MethodHandle restOfHandle(final OptimismInfo info, final FunctionNode restOfFunction, final boolean canBeDeoptimized) {
847        assert info != null;
848        assert restOfFunction.getCompileUnit().getUnitClassName().contains("restOf");
849        final MethodHandle restOf =
850                changeReturnType(
851                        info.data.lookupCodeMethod(
852                                restOfFunction.getCompileUnit().getCode(),
853                                MH.type(restOfFunction.getReturnType().getTypeClass(),
854                                        RewriteException.class)),
855                        Object.class);
856
857        if (!canBeDeoptimized) {
858            return restOf;
859        }
860
861        // If rest-of is itself optimistic, we must make sure that we can repeat a deoptimization if it, too hits an exception.
862        return MH.catchException(restOf, RewriteException.class, createRewriteExceptionHandler());
863
864    }
865
866    private static class OptimismInfo {
867        // TODO: this is pointing to its owning ScriptFunctionData. Re-evaluate if that's okay.
868        private final RecompilableScriptFunctionData data;
869        private final Map<Integer, Type> invalidatedProgramPoints;
870        private SwitchPoint optimisticAssumptions;
871        private final DebugLogger log;
872
873        @SuppressWarnings("unused")
874        OptimismInfo(final RecompilableScriptFunctionData data, final Map<Integer, Type> invalidatedProgramPoints) {
875            this.data = data;
876            this.log  = data.getLogger();
877            this.invalidatedProgramPoints = invalidatedProgramPoints == null ? new TreeMap<Integer, Type>() : invalidatedProgramPoints;
878            newOptimisticAssumptions();
879        }
880
881        private void newOptimisticAssumptions() {
882            optimisticAssumptions = new SwitchPoint();
883        }
884
885        boolean requestRecompile(final RewriteException e) {
886            final Type retType            = e.getReturnType();
887            final Type previousFailedType = invalidatedProgramPoints.put(e.getProgramPoint(), retType);
888
889            if (previousFailedType != null && !previousFailedType.narrowerThan(retType)) {
890                final StackTraceElement[] stack      = e.getStackTrace();
891                final String              functionId = stack.length == 0 ?
892                        data.getName() :
893                        stack[0].getClassName() + "." + stack[0].getMethodName();
894
895                log.info("RewriteException for an already invalidated program point ", e.getProgramPoint(), " in ", functionId, ". This is okay for a recursive function invocation, but a bug otherwise.");
896
897                return false;
898            }
899
900            SwitchPoint.invalidateAll(new SwitchPoint[] { optimisticAssumptions });
901
902            return true;
903        }
904
905        Compiler getCompiler(final FunctionNode fn, final MethodType actualCallSiteType, final RewriteException e) {
906            return data.getCompiler(fn, actualCallSiteType, e.getRuntimeScope(), invalidatedProgramPoints, getEntryPoints(e));
907        }
908
909        private static int[] getEntryPoints(final RewriteException e) {
910            final int[] prevEntryPoints = e.getPreviousContinuationEntryPoints();
911            final int[] entryPoints;
912            if (prevEntryPoints == null) {
913                entryPoints = new int[1];
914            } else {
915                final int l = prevEntryPoints.length;
916                entryPoints = new int[l + 1];
917                System.arraycopy(prevEntryPoints, 0, entryPoints, 1, l);
918            }
919            entryPoints[0] = e.getProgramPoint();
920            return entryPoints;
921        }
922
923        FunctionNode reparse() {
924            return data.reparse();
925        }
926
927        boolean isSerialized() {
928            return data.isSerialized();
929        }
930    }
931
932    @SuppressWarnings("unused")
933    private static Object newFilter(final Object result, final Object allocation) {
934        return (result instanceof ScriptObject || !JSType.isPrimitive(result))? result : allocation;
935    }
936
937    private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) {
938        return MH.findStatic(MethodHandles.lookup(), CompiledFunction.class, name, MH.type(rtype, types));
939    }
940}
941