mono-2.6.7-for-amiga /mcs/class/System.Core/System.Linq.Expressions/EmitContext.cs

Language C# Lines 587
MD5 Hash 77e4077bc4dae51f9c5b850d0de22871 Estimated Cost $11,437 (why?)
Repository https://bitbucket.org/steenlund/mono-2.6.7-for-amiga View Raw File View Project SPDX
  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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
//
// EmitContext.cs
//
// Author:
//   Miguel de Icaza (miguel@novell.com)
//   Jb Evain (jbevain@novell.com)
//
// (C) 2008 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;

namespace System.Linq.Expressions {

	class CompilationContext {

		class ParameterReplacer : ExpressionTransformer {

			CompilationContext context;
			ExecutionScope scope;
			object [] locals;

			public ParameterReplacer (CompilationContext context, ExecutionScope scope, object [] locals)
			{
				this.context = context;
				this.scope = scope;
				this.locals = locals;
			}

			protected override Expression VisitParameter (ParameterExpression parameter)
			{
				var scope = this.scope;
				var locals = this.locals;

				while (scope != null) {
					int position = IndexOfHoistedLocal (scope, parameter);
					if (position != -1)
						return ReadHoistedLocalFromArray (locals, position);

					locals = scope.Locals;
					scope = scope.Parent;
				}

				return parameter;
			}

			Expression ReadHoistedLocalFromArray (object [] locals, int position)
			{
				return Expression.Field (
					Expression.Convert (
						Expression.ArrayIndex (
							Expression.Constant (locals),
							Expression.Constant (position)),
						locals [position].GetType ()),
					"Value");
			}

			int IndexOfHoistedLocal (ExecutionScope scope, ParameterExpression parameter)
			{
				return context.units [scope.compilation_unit].IndexOfHoistedLocal (parameter);
			}
		}

		class HoistedVariableDetector : ExpressionVisitor {

			Dictionary<ParameterExpression, LambdaExpression> parameter_to_lambda =
				new Dictionary<ParameterExpression, LambdaExpression> ();

			Dictionary<LambdaExpression, List<ParameterExpression>> hoisted_map;

			LambdaExpression lambda;

			public Dictionary<LambdaExpression, List<ParameterExpression>> Process (LambdaExpression lambda)
			{
				Visit (lambda);
				return hoisted_map;
			}

			protected override void VisitLambda (LambdaExpression lambda)
			{
				this.lambda = lambda;
				foreach (var parameter in lambda.Parameters)
					parameter_to_lambda [parameter] = lambda;
				base.VisitLambda (lambda);
			}

			protected override void VisitParameter (ParameterExpression parameter)
			{
				if (lambda.Parameters.Contains (parameter))
					return;

				Hoist (parameter);
			}

			void Hoist (ParameterExpression parameter)
			{
				LambdaExpression lambda;
				if (!parameter_to_lambda.TryGetValue (parameter, out lambda))
					return;

				if (hoisted_map == null)
					hoisted_map = new Dictionary<LambdaExpression, List<ParameterExpression>> ();

				List<ParameterExpression> hoisted;
				if (!hoisted_map.TryGetValue (lambda, out hoisted)) {
					hoisted = new List<ParameterExpression> ();
					hoisted_map [lambda] = hoisted;
				}

				hoisted.Add (parameter);
			}
		}

		List<object> globals = new List<object> ();
		List<EmitContext> units = new List<EmitContext> ();
		Dictionary<LambdaExpression, List<ParameterExpression>> hoisted_map;

		public int AddGlobal (object global)
		{
			return AddItemToList (global, globals);
		}

		public object [] GetGlobals ()
		{
			return globals.ToArray ();
		}

		static int AddItemToList<T> (T item, IList<T> list)
		{
			list.Add (item);
			return list.Count - 1;
		}

		public int AddCompilationUnit (LambdaExpression lambda)
		{
			DetectHoistedVariables (lambda);
			return AddCompilationUnit (null, lambda);
		}

		public int AddCompilationUnit (EmitContext parent, LambdaExpression lambda)
		{
			var context = new EmitContext (this, parent, lambda);
			var unit = AddItemToList (context, units);
			context.Emit ();
			return unit;
		}

		void DetectHoistedVariables (LambdaExpression lambda)
		{
			hoisted_map = new HoistedVariableDetector ().Process (lambda);
		}

		public List<ParameterExpression> GetHoistedLocals (LambdaExpression lambda)
		{
			if (hoisted_map == null)
				return null;

			List<ParameterExpression> hoisted;
			hoisted_map.TryGetValue (lambda, out hoisted);
			return hoisted;
		}

		public object [] CreateHoistedLocals (int unit)
		{
			var hoisted = GetHoistedLocals (units [unit].Lambda);
			return new object [hoisted == null ? 0 : hoisted.Count];
		}

		public Expression IsolateExpression (ExecutionScope scope, object [] locals, Expression expression)
		{
			return new ParameterReplacer (this, scope, locals).Transform (expression);
		}

		public Delegate CreateDelegate ()
		{
			return CreateDelegate (0, new ExecutionScope (this));
		}

		public Delegate CreateDelegate (int unit, ExecutionScope scope)
		{
			return units [unit].CreateDelegate (scope);
		}
	}

	class EmitContext {

		CompilationContext context;
		EmitContext parent;
		LambdaExpression lambda;
		DynamicMethod method;
		LocalBuilder hoisted_store;
		List<ParameterExpression> hoisted;

		public readonly ILGenerator ig;

		public bool HasHoistedLocals {
			get { return hoisted != null && hoisted.Count > 0; }
		}

		public LambdaExpression Lambda {
			get { return lambda; }
		}

		public EmitContext (CompilationContext context, EmitContext parent, LambdaExpression lambda)
		{
			this.context = context;
			this.parent = parent;
			this.lambda = lambda;
			this.hoisted = context.GetHoistedLocals (lambda);

			method = new DynamicMethod (
				"lambda_method",
				lambda.GetReturnType (),
				CreateParameterTypes (lambda.Parameters),
				typeof (ExecutionScope),
				true);

			ig = method.GetILGenerator ();
		}

		public void Emit ()
		{
			if (HasHoistedLocals)
				EmitStoreHoistedLocals ();

			lambda.EmitBody (this);
		}

		static Type [] CreateParameterTypes (IList<ParameterExpression> parameters)
		{
			var types = new Type [parameters.Count + 1];
			types [0] = typeof (ExecutionScope);

			for (int i = 0; i < parameters.Count; i++)
				types [i + 1] = parameters [i].Type;

			return types;
		}

		public bool IsLocalParameter (ParameterExpression parameter, ref int position)
		{
			position = lambda.Parameters.IndexOf (parameter);
			if (position > -1) {
				position++;
				return true;
			}

			return false;
		}

		public Delegate CreateDelegate (ExecutionScope scope)
		{
			return method.CreateDelegate (lambda.Type, scope);
		}

		public void Emit (Expression expression)
		{
			expression.Emit (this);
		}

		public LocalBuilder EmitStored (Expression expression)
		{
			var local = ig.DeclareLocal (expression.Type);
			expression.Emit (this);
			ig.Emit (OpCodes.Stloc, local);

			return local;
		}

		public void EmitLoadAddress (Expression expression)
		{
			ig.Emit (OpCodes.Ldloca, EmitStored (expression));
		}

		public void EmitLoadSubject (Expression expression)
		{
			if (expression.Type.IsValueType) {
				EmitLoadAddress (expression);
				return;
			}

			Emit (expression);
		}

		public void EmitLoadSubject (LocalBuilder local)
		{
			if (local.LocalType.IsValueType) {
				EmitLoadAddress (local);
				return;
			}

			EmitLoad (local);
		}

		public void EmitLoadAddress (LocalBuilder local)
		{
			ig.Emit (OpCodes.Ldloca, local);
		}

		public void EmitLoad (LocalBuilder local)
		{
			ig.Emit (OpCodes.Ldloc, local);
		}

		public void EmitCall (LocalBuilder local, IList<Expression> arguments, MethodInfo method)
		{
			EmitLoadSubject (local);
			EmitArguments (method, arguments);
			EmitCall (method);
		}

		public void EmitCall (LocalBuilder local, MethodInfo method)
		{
			EmitLoadSubject (local);
			EmitCall (method);
		}

		public void EmitCall (Expression expression, MethodInfo method)
		{
			if (!method.IsStatic)
				EmitLoadSubject (expression);

			EmitCall (method);
		}

		public void EmitCall (Expression expression, IList<Expression> arguments, MethodInfo method)
		{
			if (!method.IsStatic)
				EmitLoadSubject (expression);

			EmitArguments (method, arguments);
			EmitCall (method);
		}

		void EmitArguments (MethodInfo method, IList<Expression> arguments)
		{
			var parameters = method.GetParameters ();

			for (int i = 0; i < parameters.Length; i++) {
				var parameter = parameters [i];
				var argument = arguments [i];

				if (parameter.ParameterType.IsByRef) {
					ig.Emit (OpCodes.Ldloca, EmitStored (argument));
					continue;
				}

				Emit (arguments [i]);
			}
		}

		public void EmitCall (MethodInfo method)
		{
			ig.Emit (
				method.IsVirtual ? OpCodes.Callvirt : OpCodes.Call,
				method);
		}

		public void EmitNullableHasValue (LocalBuilder local)
		{
			EmitCall (local, "get_HasValue");
		}

		public void EmitNullableInitialize (LocalBuilder local)
		{
			ig.Emit (OpCodes.Ldloca, local);
			ig.Emit (OpCodes.Initobj, local.LocalType);
			ig.Emit (OpCodes.Ldloc, local);
		}

		public void EmitNullableGetValue (LocalBuilder local)
		{
			EmitCall (local, "get_Value");
		}

		public void EmitNullableGetValueOrDefault (LocalBuilder local)
		{
			EmitCall (local, "GetValueOrDefault");
		}

		void EmitCall (LocalBuilder local, string method_name)
		{
			EmitCall (local, local.LocalType.GetMethod (method_name, Type.EmptyTypes));
		}

		public void EmitNullableNew (Type of)
		{
			ig.Emit (OpCodes.Newobj, of.GetConstructor (new [] { of.GetFirstGenericArgument () }));
		}

		public void EmitCollection<T> (IEnumerable<T> collection) where T : Expression
		{
			foreach (var expression in collection)
				expression.Emit (this);
		}

		public void EmitCollection (IEnumerable<ElementInit> initializers, LocalBuilder local)
		{
			foreach (var initializer in initializers)
				initializer.Emit (this, local);
		}

		public void EmitCollection (IEnumerable<MemberBinding> bindings, LocalBuilder local)
		{
			foreach (var binding in bindings)
				binding.Emit (this, local);
		}

		public void EmitIsInst (Expression expression, Type candidate)
		{
			expression.Emit (this);

			var type = expression.Type;

			if (type.IsValueType)
				ig.Emit (OpCodes.Box, type);

			ig.Emit (OpCodes.Isinst, candidate);
		}

		public void EmitScope ()
		{
			ig.Emit (OpCodes.Ldarg_0);
		}

		public void EmitReadGlobal (object global)
		{
			EmitReadGlobal (global, global.GetType ());
		}

		public void EmitLoadGlobals ()
		{
			EmitScope ();

			ig.Emit (OpCodes.Ldfld, typeof (ExecutionScope).GetField ("Globals"));
		}

		public void EmitReadGlobal (object global, Type type)
		{
			EmitLoadGlobals ();

			ig.Emit (OpCodes.Ldc_I4, AddGlobal (global, type));
			ig.Emit (OpCodes.Ldelem, typeof (object));

			EmitLoadStrongBoxValue (type);
		}

		public void EmitLoadStrongBoxValue (Type type)
		{
			var strongbox = type.MakeStrongBoxType ();

			ig.Emit (OpCodes.Isinst, strongbox);
			ig.Emit (OpCodes.Ldfld, strongbox.GetField ("Value"));
		}

		int AddGlobal (object value, Type type)
		{
			return context.AddGlobal (CreateStrongBox (value, type));
		}

		public void EmitCreateDelegate (LambdaExpression lambda)
		{
			EmitScope ();

			ig.Emit (OpCodes.Ldc_I4, AddChildContext (lambda));
			if (hoisted_store != null)
				ig.Emit (OpCodes.Ldloc, hoisted_store);
			else
				ig.Emit (OpCodes.Ldnull);

			ig.Emit (OpCodes.Callvirt, typeof (ExecutionScope).GetMethod ("CreateDelegate"));

			ig.Emit (OpCodes.Castclass, lambda.Type);
		}

		void EmitStoreHoistedLocals ()
		{
			EmitHoistedLocalsStore ();
			for (int i = 0; i < hoisted.Count; i++)
				EmitStoreHoistedLocal (i, hoisted [i]);
		}

		void EmitStoreHoistedLocal (int position, ParameterExpression parameter)
		{
			ig.Emit (OpCodes.Ldloc, hoisted_store);
			ig.Emit (OpCodes.Ldc_I4, position);
			parameter.Emit (this);
			EmitCreateStrongBox (parameter.Type);
			ig.Emit (OpCodes.Stelem, typeof (object));
		}

		public void EmitLoadHoistedLocalsStore ()
		{
			ig.Emit (OpCodes.Ldloc, hoisted_store);
		}

		void EmitCreateStrongBox (Type type)
		{
			ig.Emit (OpCodes.Newobj, type.MakeStrongBoxType ().GetConstructor (new [] { type }));
		}

		void EmitHoistedLocalsStore ()
		{
			EmitScope ();
			hoisted_store = ig.DeclareLocal (typeof (object []));
			ig.Emit (OpCodes.Callvirt, typeof (ExecutionScope).GetMethod ("CreateHoistedLocals"));
			ig.Emit (OpCodes.Stloc, hoisted_store);
		}

		public void EmitLoadLocals ()
		{
			ig.Emit (OpCodes.Ldfld, typeof (ExecutionScope).GetField ("Locals"));
		}

		public void EmitParentScope ()
		{
			ig.Emit (OpCodes.Ldfld, typeof (ExecutionScope).GetField ("Parent"));
		}

		public void EmitIsolateExpression ()
		{
			ig.Emit (OpCodes.Callvirt, typeof (ExecutionScope).GetMethod ("IsolateExpression"));
		}

		public int IndexOfHoistedLocal (ParameterExpression parameter)
		{
			if (!HasHoistedLocals)
				return -1;

			return hoisted.IndexOf (parameter);
		}

		public bool IsHoistedLocal (ParameterExpression parameter, ref int level, ref int position)
		{
			if (parent == null)
				return false;

			if (parent.hoisted != null) {
				position = parent.hoisted.IndexOf (parameter);
				if (position > -1)
					return true;
			}

			level++;

			return parent.IsHoistedLocal (parameter, ref level, ref position);
		}

		int AddChildContext (LambdaExpression lambda)
		{
			return context.AddCompilationUnit (this, lambda);
		}

		static object CreateStrongBox (object value, Type type)
		{
			return Activator.CreateInstance (
				type.MakeStrongBoxType (), value);
		}
	}
}
Back to Top