/* **************************************************************************** * * -X:JITCalls on another receiver: `o.m(a)' in a typed body, o a local or an instance variable, calls the typed body * of m that a call on an object of o's class would enter, without a call site, a scope or boxes. * * What the call would have resolved to is decided when compiling, from the class the profile saw o hold (TrySample), * and kept true by guards: * - o's class: checked where the call is, against the exact class (a subclass, a singleton class, an object that * was extended fails it). Where a call that may run Ruby code may be (RubyCall: the call ends a statement of a * body that resumes, is the value of `x = ...' or `@x = ...' there, or is the body's value), a miss is no deopt: * the call is made through a site as the generic body makes it (JitSelfCallSite with an explicit receiver, after * the arguments, on their values), and the body goes on under the rule of any such call - the next statement * checks the world, and the value is an object (Keep: a value the body's local cannot hold resumes the rest of the * call in the interpreter with it). Elsewhere (in the middle of an expression, `o.m(x) + 1') a miss deopts, and * the statement runs again generically (a body that resumes) or the body restarts (one that does not, only before * its first effect: the _canDeopt rule); * - the method table: the caller's entry checks the global method version, which every def, undef, remove_method, * alias, include/prepend, singleton method, visibility change and method added to a refinement bumps; the callee's * body is bound only if it was compiled at that same version (JitStub.BindCallee). A change made by Ruby code the * callee runs is the stale-caller rule's (RubyCall): such a call must end its statement, and the next statement * checks the world again; * - visibility: only a public method (as the lookup finds it, so `private :m' in a subclass counts), since an explicit * receiver sees no other; * - refinements: only where none are active where the caller was written. * The callee runs as its entry would run it, but for its entry's checks, which are the ones above, and its arguments * arrive as the types it was compiled for (EmitDirectCall's CoerceArgument; through a site, an argument of another type * sends the call to the site). Its deopts come back here before its first effect, as a self direct call's do; a callee * that resumes in the interpreter keeps its own. * * A public Ruby method that has no typed body to bind - not compiled yet after the caller has waited for it, declined, * or the caller itself on another object (`@left.count') - is called through the site alone where the site may be * (JitCallee.Unbound), rather than declining the caller. * * ***************************************************************************/ using System; using System.Collections.Generic; using IronRuby.Builtins; using IronRuby.Compiler.Ast; namespace IronRuby.Runtime.Jit { using MSA = System.Linq.Expressions; using Ast = System.Linq.Expressions.Expression; using RExpr = IronRuby.Compiler.Ast.Expression; internal sealed partial class JitCompiler { // -X:JITCalls: the typed body of the method a name resolves to on a class, for a call with so many arguments on an // object of that class (JitStub.ReceiverCallees); null where the body binds no such call. private Func _receiverCallees; // the body calls a typed body on another object (JitCode.ReceiverCalls) private bool _receiverCalls; // A call TryReceiverCall and TryUnknownReceiverSiteCall may take: none in a loop's copy or under refinements, and no // operator, element access, block, splat or keywords. private bool IsReceiverCallShape(MethodCall/*!*/ node, int argc) { if (_ast == null || _loop != null || _supplied >= 0 || _hints == null || !_refinements.IsEmpty || node.Block != null) { return false; } if (JitScreen.IsBinaryOperator(node.MethodName) || node.MethodName == "[]" || node.MethodName == "[]=" || node.MethodName == "call") { return false; } if (argc > JitStub.MaxArity) { return false; } for (int i = 0; i < argc; i++) { var arg = node.Arguments.Expressions[i]; if (arg is SplattedArgument || arg is HashConstructor) { return false; } } return true; } /// The call `o.m(a, ...)' bound to m's typed body (see the top of the file), or null. private MSA.Expression TryReceiverCall(MethodCall/*!*/ node, int argc, out JT type) { type = JT.None; if (!IsReceiverCallShape(node, argc)) { return null; } var cls = ReceiverClass(node.Target, 0); if (cls == null || cls.Context != _context) { return null; } var callee = _receiverCallees(cls, node.MethodName, argc); if (callee == null) { return null; } var use = SiteUse(node, argc); if (callee == JitCallee.Unbound) { if (use == ReceiverSiteUse.None) { return null; } return EmitReceiverSiteCall(node, argc, null, null, use, out type); } if (use != ReceiverSiteUse.None && callee.Code.ReturnType != JT.None && callee.Code.ReturnType != JT.Never) { return EmitReceiverSiteCall(node, argc, cls, callee, use, out type); } // a callee that resumes and is typed: where its value does not fit, only where it is dropped or returned bool throwsResumeResult = JitResumeInterp.ThrowsResumeResult(callee.Code); if (throwsResumeResult && !TakesResumeResult(node)) { return null; } // In the middle of an expression a miss deopts: not where the profile has seen the parameter hold another class too. var local = node.Target as LocalVariable; int parameter = (local != null) ? Array.IndexOf(_paramNames, local.Name) : -1; if (parameter >= 0 && _hints.ArgClasses != null && parameter < _hints.ArgClasses.Length) { var seen = _hints.ArgClasses[parameter]; if (seen == null || seen.Length > 1) { return null; } } JT rt; var r = Emit(node.Target, out rt); if (rt != JT.Obj) { throw Bail("call " + node.MethodName + " on a " + rt); } var receiver = Ast.Variable(typeof(object), "#recv"); // the class check, before the arguments: a miss runs the statement again generically with nothing done in it; one on // a parameter that keeps missing has the method profiled again (JitStub.OnDeopt), which then sees the other class _canDeopt = true; if (parameter >= 0) { _inlinedOnArgumentClass = _receiverGuardOnArgument = true; } var guard = Ast.Call(JitRuntime.M("GuardClass"), Ast.Constant(_context), receiver, Ast.Constant(cls, typeof(RubyClass))); var call = EmitDirectCall(node, callee, argc, receiver, out type); if (throwsResumeResult) { call = ResumeCallSite(node, call); } if (JitRuntime.Verbose) { Console.Error.WriteLine("[jit] direct call {0}#{1}/{2} from {3}", cls.Name, node.MethodName, argc, _ast.Name); } return Ast.Block(call.Type, new[] { receiver }, Ast.Assign(receiver, r), guard, call); } /// /// `o.m(a, ...)' where the profile has no sample of o (a local assigned from a call: Richards' `task = find_task(...)'), /// after every other way of compiling the call: through the site alone where a call through a site may be, rather /// than declining the body. Null for an o the profile saw hold something that is not an object of a Ruby class (an /// Array, a number: what the calls after this one compile) or whose class TryReceiverCall has seen. /// private MSA.Expression TryUnknownReceiverSiteCall(MethodCall/*!*/ node, int argc, out JT type) { type = JT.None; if (!IsReceiverCallShape(node, argc)) { return null; } object sample; if (TrySample(node.Target, out sample) || ReceiverClass(node.Target, 0) != null) { return null; } var use = SiteUse(node, argc); if (use == ReceiverSiteUse.None) { return null; } return EmitReceiverSiteCall(node, argc, null, null, use, out type); } // a call on a parameter deopts if the parameter's class is not the one the profile saw (JitCode.ReceiverGuardOnArgument) private bool _receiverGuardOnArgument; // the body would make a call through a site if it resumed (SiteUse) private bool _siteWouldResume; // IR_JIT_RECEIVER_SITES=0: a miss of the class check always deopts, and a method with no typed body is not called through a site private static readonly bool _receiverSites = Environment.GetEnvironmentVariable("IR_JIT_RECEIVER_SITES") != "0"; /// Where the value of a call made through a site goes (SiteUse). private enum ReceiverSiteUse { None, // the call may not be made through a site: it is in the middle of an expression Dropped, // a statement whose value nothing takes Returned, // the body's value Local, // `x = o.m(...)' Value, // anything else that ends a statement (`@x = o.m(...)'): an object } /// Whether the call `o.m(...)' at may be made through a site, which may run Ruby code (RubyCall). private ReceiverSiteUse SiteUse(MethodCall/*!*/ node, int argc) { if (!_receiverSites || argc > JitSelfCallSite.MaxArity || _constantScope == null || _ast == null) { return ReceiverSiteUse.None; } if (node == _rubyArgumentAllowed) { return ReceiverSiteUse.None; } if (_valueReturned == null) { ClassifyResultUses(); } if (_valueReturned.Contains(node)) { return ReceiverSiteUse.Returned; } if (!StatementEnds.Contains(node)) { return ReceiverSiteUse.None; } // (a body that resumes may: it is compiled so too, TryCompile) if (!_interp) { _siteWouldResume = _bailWouldResume = true; return ReceiverSiteUse.None; } if (_valueDropped.Contains(node)) { return ReceiverSiteUse.Dropped; } if (AssignedLocal(node) != null) { return ReceiverSiteUse.Local; } return ReceiverSiteUse.Value; } /// /// `o.m(a, ...)' where a call through a site may be (SiteUse): o's class checked, then m's typed body called, or the call /// made through the site (see the top of the file); with no , through the site alone. /// private MSA.Expression/*!*/ EmitReceiverSiteCall(MethodCall/*!*/ node, int argc, RubyClass cls, JitCallee callee, ReceiverSiteUse use, out JT type) { JT rt; var r = Emit(node.Target, out rt); var receiver = Ast.Variable(typeof(object), "#recv"); var variables = new List { receiver }; var body = new List { Ast.Assign(receiver, Coerce(r, rt, JT.Obj)) }; // the arguments, in order, once: the typed body takes them as its types, the site boxed var args = new MSA.ParameterExpression[argc]; var argTypes = new JT[argc]; int rubyArgument = -1; for (int i = 0; i < argc; i++) { JT at; int rubyCalls = _rubyCalls; var argument = node.Arguments.Expressions[i]; var savedAllowed = _rubyArgumentAllowed; // (an argument that may run Ruby code, followed only by ones that assume nothing: after it, the typed body is // called only if the world has not moved, as FallbackAfterRubyArgument) _rubyArgumentAllowed = (callee != null && rubyArgument < 0 && argument is MethodCall && AssumesNothing(node.Arguments.Expressions, i + 1)) ? argument : null; var a = Emit(argument, out at); _rubyArgumentAllowed = savedAllowed; if (_rubyCalls != rubyCalls) { rubyArgument = i; } if (at == JT.None || at == JT.Never) { throw Bail("call " + node.MethodName + " with an argument of no value"); } args[i] = Ast.Variable(ClrType(at), "#arg" + i); argTypes[i] = at; variables.Add(args[i]); body.Add(Ast.Assign(args[i], a)); } var boxed = new MSA.Expression[argc]; for (int i = 0; i < argc; i++) { boxed[i] = Coerce(args[i], argTypes[i], JT.Obj); } JitSelfCallSite siteObject; var site = EmitSiteCall(node, argc, receiver, boxed, out siteObject); if (callee == null) { // the call through the site runs code this body knows nothing of _pure = false; _effectNotOnSelf = true; RubyCall(node); if (JitRuntime.Verbose) { Console.Error.WriteLine("[jit] site call {0}/{1} from {2}", node.MethodName, argc, _ast.Name); } type = JT.Obj; body.Add(site); return Ast.Block(typeof(object), variables, body); } var code = callee.Code; if (code.RunsRuby) { callee = CalleeFor(node, callee); } MSA.Expression hit = Ast.Call(JitRuntime.M("IsOfClassObject"), receiver, Ast.Constant(cls, typeof(object))); var callArgs = new MSA.Expression[argc + 1]; callArgs[0] = receiver; for (int i = 0; i < argc; i++) { JT from = argTypes[i], to = code.ParameterTypes[i]; if (from == to || to == JT.Obj || (IsIntegral(from) && IsIntegral(to))) { callArgs[i + 1] = Coerce(args[i], from, to); } else if (from == JT.Obj && (to == JT.Int || to == JT.Dbl)) { // an argument of another type goes to the site var clr = ClrType(to); hit = Ast.AndAlso(hit, Ast.TypeIs(args[i], clr)); callArgs[i + 1] = Ast.Unbox(args[i], clr); } else if (from == JT.Obj && to == JT.Lng) { hit = Ast.AndAlso(hit, Ast.OrElse(Ast.TypeIs(args[i], typeof(int)), Ast.TypeIs(args[i], typeof(long)))); callArgs[i + 1] = Ast.Call(JitRuntime.M("GuardLong"), args[i]); } else { throw Bail("call: " + node.MethodName + " takes " + to + ", passed " + from); } } // after an argument that may have run Ruby code, the body bound may not be m's any more if (rubyArgument >= 0) { hit = Ast.AndAlso(hit, Ast.Not(WorldMoved())); } // (the callee's deopts come before its effects, and are its own: the call through the site is the other branch) TakeCallee(node, callee, true); _pure = false; _effectNotOnSelf = true; RubyCall(node); MSA.Expression invoke = Ast.Invoke(callee.Target, callArgs); if (code.InterpResumes && callee.Spec != null) { invoke = Ast.Block(invoke.Type, JitStub.CountEntry(callee.Spec), invoke); } // a callee that resumes and is typed: a resumed value that does not fit its type comes as a JitResumeResult, which a // dropped or returned call lets go as a resumed callee's (ResumeCallSite), and the others take as the site's value bool throwsResumeResult = JitResumeInterp.ThrowsResumeResult(code); if (throwsResumeResult && (use == ReceiverSiteUse.Dropped || use == ReceiverSiteUse.Returned)) { invoke = ResumeCallSite(node, invoke); throwsResumeResult = false; } if (JitRuntime.Verbose) { Console.Error.WriteLine("[jit] direct call {0}#{1}/{2} from {3}, else a site call", cls.Name, node.MethodName, argc, _ast.Name); } type = code.ReturnType; var clrType = invoke.Type; MSA.Expression miss; if (clrType == typeof(object)) { miss = site; } else if (use == ReceiverSiteUse.Dropped) { miss = Ast.Block(clrType, site, Ast.Default(clrType)); } else if (use == ReceiverSiteUse.Returned) { // a value the body's type cannot hold is the call's value, as a resumed callee's (JitResumeInterp.FitInt) _passesResumeResult = true; miss = Ast.Call(JitResumeInterp.FitMethod(clrType), site); } else if (use == ReceiverSiteUse.Local) { miss = KeepInLocal(siteObject, site, clrType); } else { type = JT.Obj; invoke = Coerce(invoke, code.ReturnType, JT.Obj); miss = site; } if (throwsResumeResult) { var passed = Ast.Variable(typeof(JitResumeResult), "#passed"); MSA.Expression value = Ast.Field(passed, nameof(JitResumeResult.Value)); invoke = Ast.TryCatch(invoke, Ast.Catch(passed, (invoke.Type == typeof(object)) ? value : KeepInLocal(siteObject, value, invoke.Type))); } body.Add(Ast.Condition(hit, invoke, miss)); return Ast.Block(invoke.Type, variables, body); } /// /// The call through the site with an explicit receiver: on a light scope first (JitSelfCallSite.InvokeLight0..3), and if /// that asks for the scope, again with one made of the typed locals (InvokeFull), which the body then resumes from at its /// next statement (CallReturnCheck). Its value, an object. /// private MSA.Expression/*!*/ EmitSiteCall(MethodCall/*!*/ node, int argc, MSA.ParameterExpression/*!*/ receiver, MSA.Expression[]/*!*/ boxed, out JitSelfCallSite/*!*/ site) { MSA.Expression[] live; site = NewCallSite(node, argc, true, out live); var siteConstant = Ast.Constant(site); var lightArgs = new MSA.Expression[argc + 2]; lightArgs[0] = siteConstant; lightArgs[1] = receiver; Array.Copy(boxed, 0, lightArgs, 2, argc); MSA.Expression made; if (_madeScope != null) { _madeScopeSet = true; made = _madeScope; } else { // a body that does not resume: only its value (SiteUse.Returned), after which nothing of the body runs made = Ast.New(typeof(JitCallScope)); } var result = Ast.Variable(typeof(object), "#site"); MSA.Expression full = HelperCall(node, typeof(JitSelfCallSite).GetMethod("InvokeFull"), siteConstant, _self, receiver, Ast.NewArrayInit(typeof(object), boxed), Ast.NewArrayInit(typeof(object), live), made); if (_madeScope != null) { full = Ast.Block(Ast.Assign(_madeScope, Ast.New(typeof(JitCallScope))), full); } return Ast.Block(typeof(object), new[] { result }, Ast.Assign(result, HelperCall(node, typeof(JitSelfCallSite).GetMethod("InvokeLight" + argc), lightArgs)), Ast.IfThen(Ast.ReferenceEqual(result, Ast.Field(null, typeof(RubyOps).GetField("LightScopeRequired"))), Ast.Assign(result, full)), result ); } /// /// `x = o.m(...)' with x of in the typed body: the site's value as that type, or if it is not /// one, kept in a scope of the locals (JitSelfCallSite.Keep) that the body resumes from at its next statement. /// private MSA.Expression/*!*/ KeepInLocal(JitSelfCallSite/*!*/ keepSite, MSA.Expression/*!*/ site, Type/*!*/ clrType) { var value = Ast.Variable(typeof(object), "#value"); MSA.Expression fits, unboxed; if (clrType == typeof(long)) { fits = Ast.OrElse(Ast.TypeIs(value, typeof(int)), Ast.TypeIs(value, typeof(long))); unboxed = Ast.Call(JitRuntime.M("GuardLong"), value); } else { fits = Ast.TypeIs(value, clrType); unboxed = Ast.Unbox(value, clrType); } var live = LiveValues(); _madeScopeSet = true; var keep = Ast.Block(clrType, Ast.Assign(_madeScope, Ast.New(typeof(JitCallScope))), Ast.Call(typeof(JitSelfCallSite).GetMethod("Keep"), Ast.Constant(keepSite), _self, value, Ast.NewArrayInit(typeof(object), live), _madeScope), Ast.Default(clrType) ); return Ast.Block(clrType, new[] { value }, Ast.Assign(value, site), Ast.Condition(fits, unboxed, keep)); } /// /// The class the profile says holds: its sample (TrySample), or for a local of the method /// assigned once, what it is assigned from - an instance variable, another local, self (`o = @o'), or a construction /// (ConstructedClass). Null: not known. /// private RubyClass ReceiverClass(RExpr/*!*/ target, int depth) { object sample; if (TrySample(target, out sample)) { return (sample is RubyObject) ? JitRuntime.ClassOf(_context, sample) : null; } var local = target as LocalVariable; var constructed = ConstructedClass(local); if (constructed != null || local == null || depth > 2) { return constructed; } RExpr source; if (_singleSources != null && local.DefinitionLexicalDepth == _scopeDepth && _singleSources.TryGetValue(local.Name, out source) && (source is InstanceVariable || source is SelfReference || source is LocalVariable && ((LocalVariable)source).Name != local.Name)) { return ReceiverClass(source, depth + 1); } return null; } /// /// The class a local of the method holds when its one assignment is `x = C.new(...)' (a construction, JitCompiler.IsConstruction): /// C as it resolves now, or null. Only a profile, as TrySample's: the call checks the class it finds. /// private RubyClass ConstructedClass(LocalVariable local) { if (local == null || _ast == null || _ast.Body == null || _constantScope == null || local.DefinitionLexicalDepth != _scopeDepth) { return null; } if (_singleSources == null) { var walker = new SingleSourceWalker(); walker.Walk(_ast.Body); _singleSources = walker.Sources(); _firstSources = walker.FirstSources(); } RExpr source; var call = _singleSources.TryGetValue(local.Name, out source) ? source as MethodCall : null; if (call == null || !IsConstruction(call)) { return null; } object value; RubyModule owner; if (JitFoldedConstant.Resolve(_context, _constantScope, (ConstantVariable)call.Target, out value, out owner) != null) { return null; } return value as RubyClass; } } }