EmitContext.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. //
  2. // EmitContext.cs
  3. //
  4. // Author:
  5. // Miguel de Icaza ([email protected])
  6. // Jb Evain ([email protected])
  7. //
  8. // (C) 2008 Novell, Inc. (http://www.novell.com)
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Collections.ObjectModel;
  31. using System.Collections.Generic;
  32. using System.IO;
  33. using System.Linq;
  34. using System.Reflection;
  35. using System.Reflection.Emit;
  36. using System.Runtime.CompilerServices;
  37. namespace System.Linq.Expressions {
  38. abstract class EmitContext {
  39. protected LambdaExpression owner;
  40. protected Type [] param_types;
  41. protected Type return_type;
  42. protected List<object> globals = new List<object> ();
  43. public ILGenerator ig;
  44. protected EmitContext (LambdaExpression lambda)
  45. {
  46. this.owner = lambda;
  47. param_types = CreateParameterTypes (owner.Parameters);
  48. return_type = owner.GetReturnType ();
  49. }
  50. static Type [] CreateParameterTypes (ReadOnlyCollection<ParameterExpression> parameters)
  51. {
  52. var types = new Type [parameters.Count + 1];
  53. types [0] = typeof (ExecutionScope);
  54. for (int i = 0; i < parameters.Count; i++)
  55. types [i + 1] = parameters [i].Type;
  56. return types;
  57. }
  58. public static EmitContext Create (LambdaExpression lambda)
  59. {
  60. #if !NET_2_1
  61. if (Environment.GetEnvironmentVariable ("LINQ_DBG") != null)
  62. return new DebugEmitContext (lambda);
  63. #endif
  64. return new DynamicEmitContext (lambda);
  65. }
  66. public int GetParameterPosition (ParameterExpression p)
  67. {
  68. int position = owner.Parameters.IndexOf (p);
  69. if (position == -1)
  70. throw new InvalidOperationException ("Parameter not in scope");
  71. return position + 1; // + 1 because 0 is the ExecutionScope
  72. }
  73. public abstract Delegate CreateDelegate ();
  74. public void Emit (Expression expression)
  75. {
  76. expression.Emit (this);
  77. }
  78. public LocalBuilder EmitStored (Expression expression)
  79. {
  80. var local = ig.DeclareLocal (expression.Type);
  81. expression.Emit (this);
  82. ig.Emit (OpCodes.Stloc, local);
  83. return local;
  84. }
  85. public void EmitLoadAddress (Expression expression)
  86. {
  87. ig.Emit (OpCodes.Ldloca, EmitStored (expression));
  88. }
  89. public void EmitLoadSubject (Expression expression)
  90. {
  91. if (expression.Type.IsValueType) {
  92. EmitLoadAddress (expression);
  93. return;
  94. }
  95. Emit (expression);
  96. }
  97. public void EmitLoadSubject (LocalBuilder local)
  98. {
  99. if (local.LocalType.IsValueType) {
  100. EmitLoadAddress (local);
  101. return;
  102. }
  103. EmitLoad (local);
  104. }
  105. public void EmitLoadAddress (LocalBuilder local)
  106. {
  107. ig.Emit (OpCodes.Ldloca, local);
  108. }
  109. public void EmitLoad (LocalBuilder local)
  110. {
  111. ig.Emit (OpCodes.Ldloc, local);
  112. }
  113. public void EmitCall (LocalBuilder local, ReadOnlyCollection<Expression> arguments, MethodInfo method)
  114. {
  115. EmitLoadSubject (local);
  116. EmitArguments (method, arguments);
  117. EmitCall (method);
  118. }
  119. public void EmitCall (LocalBuilder local, MethodInfo method)
  120. {
  121. EmitLoadSubject (local);
  122. EmitCall (method);
  123. }
  124. public void EmitCall (Expression expression, MethodInfo method)
  125. {
  126. if (!method.IsStatic)
  127. EmitLoadSubject (expression);
  128. EmitCall (method);
  129. }
  130. public void EmitCall (Expression expression, ReadOnlyCollection<Expression> arguments, MethodInfo method)
  131. {
  132. if (!method.IsStatic)
  133. EmitLoadSubject (expression);
  134. EmitArguments (method, arguments);
  135. EmitCall (method);
  136. }
  137. void EmitArguments (MethodInfo method, ReadOnlyCollection<Expression> arguments)
  138. {
  139. var parameters = method.GetParameters ();
  140. for (int i = 0; i < parameters.Length; i++) {
  141. var parameter = parameters [i];
  142. var argument = arguments [i];
  143. if (parameter.ParameterType.IsByRef) {
  144. ig.Emit (OpCodes.Ldloca, EmitStored (argument));
  145. return;
  146. }
  147. Emit (arguments [i]);
  148. }
  149. }
  150. public void EmitCall (MethodInfo method)
  151. {
  152. ig.Emit (
  153. method.IsVirtual ? OpCodes.Callvirt : OpCodes.Call,
  154. method);
  155. }
  156. public void EmitNullableHasValue (LocalBuilder local)
  157. {
  158. EmitCall (local, local.LocalType.GetMethod ("get_HasValue"));
  159. }
  160. public void EmitNullableInitialize (LocalBuilder local)
  161. {
  162. ig.Emit (OpCodes.Ldloca, local);
  163. ig.Emit (OpCodes.Initobj, local.LocalType);
  164. ig.Emit (OpCodes.Ldloc, local);
  165. }
  166. public void EmitNullableGetValue (LocalBuilder local)
  167. {
  168. EmitCall (local, local.LocalType.GetMethod ("get_Value", Type.EmptyTypes));
  169. }
  170. public void EmitNullableGetValueOrDefault (LocalBuilder local)
  171. {
  172. EmitCall (local, local.LocalType.GetMethod ("GetValueOrDefault", Type.EmptyTypes));
  173. }
  174. public void EmitNullableNew (Type of)
  175. {
  176. ig.Emit (OpCodes.Newobj, of.GetConstructor (new [] { of.GetFirstGenericArgument () }));
  177. }
  178. public void EmitCollection<T> (IEnumerable<T> collection) where T : Expression
  179. {
  180. foreach (var expression in collection)
  181. expression.Emit (this);
  182. }
  183. public void EmitCollection (IEnumerable<ElementInit> initializers, LocalBuilder local)
  184. {
  185. foreach (var initializer in initializers)
  186. initializer.Emit (this, local);
  187. }
  188. public void EmitCollection (IEnumerable<MemberBinding> bindings, LocalBuilder local)
  189. {
  190. foreach (var binding in bindings)
  191. binding.Emit (this, local);
  192. }
  193. public void EmitIsInst (Expression expression, Type candidate)
  194. {
  195. expression.Emit (this);
  196. if (expression.Type.IsValueType)
  197. ig.Emit (OpCodes.Box, expression.Type);
  198. ig.Emit (OpCodes.Isinst, candidate);
  199. }
  200. public void EmitConvert (LocalBuilder local, Type to)
  201. {
  202. }
  203. public void EmitScope ()
  204. {
  205. ig.Emit (OpCodes.Ldarg_0);
  206. }
  207. public void EmitReadGlobal (object global)
  208. {
  209. EmitReadGlobal (global, global.GetType ());
  210. }
  211. public void EmitReadGlobal (object global, Type type)
  212. {
  213. EmitScope ();
  214. ig.Emit (OpCodes.Ldfld, typeof (ExecutionScope).GetField ("Globals"));
  215. ig.Emit (OpCodes.Ldc_I4, AddGlobal (global, type));
  216. ig.Emit (OpCodes.Ldelem, typeof (object));
  217. var strongbox = type.MakeStrongBoxType ();
  218. ig.Emit (OpCodes.Isinst, strongbox);
  219. ig.Emit (OpCodes.Ldfld, strongbox.GetField ("Value"));
  220. }
  221. int AddGlobal (object value, Type type)
  222. {
  223. globals.Add (CreateStrongBox (value, type));
  224. return globals.Count - 1;
  225. }
  226. static object CreateStrongBox (object value, Type type)
  227. {
  228. return Activator.CreateInstance (
  229. type.MakeStrongBoxType (), value);
  230. }
  231. }
  232. class DynamicEmitContext : EmitContext {
  233. DynamicMethod method;
  234. public DynamicMethod Method {
  235. get { return method; }
  236. }
  237. public DynamicEmitContext (LambdaExpression lambda)
  238. : base (lambda)
  239. {
  240. // FIXME: Need to force this to be verifiable, see:
  241. // https://bugzilla.novell.com/show_bug.cgi?id=355005
  242. method = new DynamicMethod (GenerateName (), return_type, param_types, typeof (ExecutionScope), true);
  243. ig = method.GetILGenerator ();
  244. owner.EmitBody (this);
  245. }
  246. public override Delegate CreateDelegate ()
  247. {
  248. return method.CreateDelegate (owner.Type, new ExecutionScope (globals.ToArray ()));
  249. }
  250. protected virtual string GenerateName ()
  251. {
  252. return "lambda_method";
  253. }
  254. }
  255. #if !NET_2_1
  256. class DebugEmitContext : DynamicEmitContext {
  257. static object mlock = new object ();
  258. static int method_count;
  259. public DebugEmitContext (LambdaExpression lambda)
  260. : base (lambda)
  261. {
  262. var name = Method.Name;
  263. var file_name = name + ".dll";
  264. var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly (
  265. new AssemblyName (name), AssemblyBuilderAccess.RunAndSave, Path.GetTempPath ());
  266. var type = assembly.DefineDynamicModule (file_name, file_name).DefineType ("Linq", TypeAttributes.Public);
  267. var method = type.DefineMethod (name, MethodAttributes.Public | MethodAttributes.Static, return_type, param_types);
  268. ig = method.GetILGenerator ();
  269. owner.EmitBody (this);
  270. type.CreateType ();
  271. assembly.Save (file_name);
  272. }
  273. protected override string GenerateName ()
  274. {
  275. lock (mlock) {
  276. return "lambda_method-" + (method_count++);
  277. }
  278. }
  279. }
  280. #endif
  281. }