1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 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 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
|
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Microsoft Public License. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Microsoft Public License, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Microsoft Public License.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Utils;
namespace Microsoft.Scripting.Interpreter {
/// <summary>
/// Manages creation of interpreted delegates. These delegates will get
/// compiled if they are executed often enough.
/// </summary>
internal sealed class LightDelegateCreator {
private readonly Interpreter _interpreter;
private readonly LambdaExpression _lambda;
private readonly IList<ParameterExpression> _closureVariables;
// Adaptive compilation support:
private Type _compiledDelegateType;
private Delegate _compiled;
private int _executionCount;
private readonly object _compileLock = new object();
private const int CompilationThreshold = 32;
internal LightDelegateCreator(Interpreter interpreter, LambdaExpression lambda, IList<ParameterExpression> closureVariables) {
_interpreter = interpreter;
_lambda = lambda;
_closureVariables = closureVariables;
}
internal IList<ParameterExpression> ClosureVariables {
get { return _closureVariables; }
}
internal Interpreter Interpreter {
get { return _interpreter; }
}
private bool HasClosure {
get { return _closureVariables.Count > 0; }
}
internal bool HasCompiled {
get { return _compiled != null; }
}
/// <summary>
/// true if the compiled delegate has the same type as the lambda;
/// false if the type was changed for interpretation.
/// </summary>
internal bool SameDelegateType {
get { return _compiledDelegateType == _lambda.Type; }
}
internal Delegate CreateDelegate() {
return CreateDelegate(null);
}
internal Delegate CreateDelegate(StrongBox<object>[] closure) {
if (_compiled != null) {
// If the delegate type we want is not a Func/Action, we can't
// use the compiled code directly. So instead just fall through
// and create an interpreted LightLambda, which will pick up
// the compiled delegate on its first run.
//
// Ideally, we would just rebind the compiled delegate using
// Delgate.CreateDelegate. Unfortunately, it doesn't work on
// dynamic methods.
if (SameDelegateType) {
return CreateCompiledDelegate(closure);
}
}
if (_interpreter == null) {
// We can't interpret, so force a compile
Compile(null);
Delegate compiled = CreateCompiledDelegate(closure);
Debug.Assert(compiled.GetType() == _lambda.Type);
return compiled;
}
// Otherwise, we'll create an interpreted LightLambda
return new LightLambda(this, closure).MakeDelegate(_lambda.Type);
}
/// <summary>
/// Used by LightLambda to get the compiled delegate.
/// </summary>
internal Delegate CreateCompiledDelegate(StrongBox<object>[] closure) {
Debug.Assert(HasClosure == (closure != null));
if (HasClosure) {
// We need to apply the closure to get the actual delegate.
var applyClosure = (Func<StrongBox<object>[], Delegate>)_compiled;
return applyClosure(closure);
}
return _compiled;
}
/// <summary>
/// Create a compiled delegate for the LightLambda, and saves it so
/// future calls to Run will execute the compiled code instead of
/// interpreting.
/// </summary>
internal void Compile(object state) {
if (_compiled != null) {
return;
}
// Compilation is expensive, we only want to do it once.
lock (_compileLock) {
if (_compiled != null) {
return;
}
// Interpreter needs a standard delegate type.
// So change the lambda's delegate type to Func<...> or
// Action<...> so it can be called from the LightLambda.Run
// methods.
LambdaExpression lambda = _lambda;
if (_interpreter != null) {
_compiledDelegateType = GetFuncOrAction(lambda);
lambda = Expression.Lambda(_compiledDelegateType, lambda.Body, lambda.Name, lambda.Parameters);
}
if (HasClosure) {
_compiled = LightLambdaClosureVisitor.BindLambda(lambda, _closureVariables);
} else {
_compiled = lambda.Compile();
}
}
}
private static Type GetFuncOrAction(LambdaExpression lambda) {
Type delegateType;
bool isVoid = lambda.ReturnType == typeof(void);
if (isVoid && lambda.Parameters.Count == 2 &&
lambda.Parameters[0].IsByRef && lambda.Parameters[1].IsByRef) {
return typeof(ActionRef<,>).MakeGenericType(lambda.Parameters.Map(p => p.Type));
} else {
Type[] types = lambda.Parameters.Map(p => p.IsByRef ? p.Type.MakeByRefType() : p.Type);
if (isVoid) {
if (Expression.TryGetActionType(types, out delegateType)) {
return delegateType;
}
} else {
types = types.AddLast(lambda.ReturnType);
if (Expression.TryGetFuncType(types, out delegateType)) {
return delegateType;
}
}
return lambda.Type;
}
}
/// <summary>
/// Updates the execution count of this light delegate. If a certain
/// threshold is reached, it will start a background compilation.
/// </summary>
internal void UpdateExecutionCount() {
Debug.Assert(_interpreter != null);
// Don't lock here, it's a frequently hit path.
//
// There could be multiple threads racing, but that is okay.
// Two bad things can happen:
// * We miss increments (one thread sets the counter back)
// * We might enter the "if" branch more than once.
//
// The first is okay, it just means we take longer to compile.
// The second we explicitly guard against inside of Compile().
//
if (++_executionCount >= CompilationThreshold) {
// Kick off the compile on another thread so this one can keep going
ThreadPool.QueueUserWorkItem(Compile, null);
}
}
}
}
|