Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ILGenerator.Mono.cs « Emit « Reflection « System « src « System.Private.CoreLib « netcore - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 4a513c5d22cc8fa372fe1c58b4627fd1566ddce7 (plain)
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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
#nullable disable

//
// Copyright (C) 2004 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.
//

//
// System.Reflection.Emit/ILGenerator.cs
//
// Author:
//   Paolo Molaro (lupus@ximian.com)
//
// (C) 2001 Ximian, Inc.  http://www.ximian.com
//

#if MONO_FEATURE_SRE
using System;
using System.Collections.Generic;
using System.Diagnostics.SymbolStore;
using System.Runtime.InteropServices;

namespace System.Reflection.Emit {

	internal struct ILExceptionBlock {
		public const int CATCH = 0;
		public const int FILTER = 1;
		public const int FINALLY = 2;
		public const int FAULT = 4;
		public const int FILTER_START = -1;

		internal Type extype;
		internal int type;
		internal int start;
		internal int len;
		internal int filter_offset;
		
		internal void Debug () {
#if FALSE
			System.Console.Write ("\ttype="+type.ToString()+" start="+start.ToString()+" len="+len.ToString());
			if (extype != null)
				System.Console.WriteLine (" extype="+extype.ToString());
			else
				System.Console.WriteLine (String.Empty);
#endif
		}
	}
	internal struct ILExceptionInfo {
#pragma warning disable 169
#pragma warning disable 414
		internal ILExceptionBlock[] handlers;
		internal int start;
		internal int len;
		internal Label end;
#pragma warning restore 169
#pragma warning restore 414

		internal int NumHandlers ()
		{
			return handlers.Length;
		}
		
		internal void AddCatch (Type extype, int offset)
		{
			int i;
			End (offset);
			add_block (offset);
			i = handlers.Length - 1;
			handlers [i].type = ILExceptionBlock.CATCH;
			handlers [i].start = offset;
			handlers [i].extype = extype;
		}

		internal void AddFinally (int offset)
		{
			int i;
			End (offset);
			add_block (offset);
			i = handlers.Length - 1;
			handlers [i].type = ILExceptionBlock.FINALLY;
			handlers [i].start = offset;
			handlers [i].extype = null;
		}

		internal void AddFault (int offset)
		{
			int i;
			End (offset);
			add_block (offset);
			i = handlers.Length - 1;
			handlers [i].type = ILExceptionBlock.FAULT;
			handlers [i].start = offset;
			handlers [i].extype = null;
		}

		internal void AddFilter (int offset)
		{
			int i;
			End (offset);
			add_block (offset);
			i = handlers.Length - 1;
			handlers [i].type = ILExceptionBlock.FILTER_START;
			handlers [i].extype = null;
			handlers [i].filter_offset = offset;
		}

		internal void End (int offset)
		{
			if (handlers == null)
				return;
			int i = handlers.Length - 1;
			if (i >= 0)
				handlers [i].len = offset - handlers [i].start;
		}

		internal int LastClauseType ()
		{
			if (handlers != null)
				return handlers [handlers.Length-1].type;
			else
				return ILExceptionBlock.CATCH;
		}

		internal void PatchFilterClause (int start)
		{
			if (handlers != null && handlers.Length > 0) {
				handlers [handlers.Length - 1].start = start;
				handlers [handlers.Length - 1].type = ILExceptionBlock.FILTER;
			}
		}

		internal void Debug (int b)
		{
#if FALSE
			System.Console.WriteLine ("Handler {0} at {1}, len: {2}", b, start, len);
			for (int i = 0; i < handlers.Length; ++i)
				handlers [i].Debug ();
#endif
		}

		void add_block (int offset)
		{
			if (handlers != null) {
				int i = handlers.Length;
				ILExceptionBlock[] new_b = new ILExceptionBlock [i + 1];
				System.Array.Copy (handlers, new_b, i);
				handlers = new_b;
				handlers [i].len = offset - handlers [i].start;
			} else {
				handlers = new ILExceptionBlock [1];
				len = offset - start;
			}
		}
	}
	
	internal struct ILTokenInfo {
		public MemberInfo member;
		public int code_pos;
	}

	internal interface TokenGenerator {
		int GetToken (string str);

		int GetToken (MemberInfo member, bool create_open_instance);

		int GetToken (MethodBase method, Type[] opt_param_types);

		int GetToken (SignatureHelper helper);
	}		

	[StructLayout (LayoutKind.Sequential)]
	public partial class ILGenerator {
		private struct LabelFixup {
			public int offset;    // The number of bytes between pos and the
							      // offset of the jump
			public int pos;	      // Where offset of the label is placed
			public int label_idx; // The label to jump to
		};
		
		struct LabelData {
			public LabelData (int addr, int maxStack)
			{
				this.addr = addr;
				this.maxStack = maxStack;
			}
			
			public int addr;
			public int maxStack; 
		}
		
		#region Sync with reflection.h
		private byte[] code;
		private int code_len;
		private int max_stack;
		private int cur_stack;
		private LocalBuilder[] locals;
		private ILExceptionInfo[] ex_handlers;
		private int num_token_fixups;
		private object token_fixups;
		#endregion
		
		private LabelData [] labels;
		private int num_labels;
		private LabelFixup[] fixups;
		private int num_fixups;
		internal Module module;
		private int cur_block;
		private Stack open_blocks;
		private TokenGenerator token_gen;
		
		const int defaultFixupSize = 4;
		const int defaultLabelsSize = 4;
		const int defaultExceptionStackSize = 2;
		
		List<SequencePointList> sequencePointLists;
		SequencePointList currentSequence;

		internal ILGenerator (Module m, TokenGenerator token_gen, int size)
		{
			if (size < 0)
				size = 128;
			code = new byte [size];
			module = m;
			this.token_gen = token_gen;
		}

		private void make_room (int nbytes)
		{
			if (code_len + nbytes < code.Length)
				return;
			byte[] new_code = new byte [(code_len + nbytes) * 2 + 128];
			System.Array.Copy (code, 0, new_code, 0, code.Length);
			code = new_code;
		}

		private void emit_int (int val)
		{
			code [code_len++] = (byte) (val & 0xFF);
			code [code_len++] = (byte) ((val >> 8) & 0xFF);
			code [code_len++] = (byte) ((val >> 16) & 0xFF);
			code [code_len++] = (byte) ((val >> 24) & 0xFF);
		}

		/* change to pass by ref to avoid copy */
		private void ll_emit (OpCode opcode)
		{
			/* 
			 * there is already enough room allocated in code.
			 */
			if (opcode.Size == 2)
				code [code_len++] = (byte)(opcode.Value >> 8);
			code [code_len++] = (byte)(opcode.Value & 0xff);
			/*
			 * We should probably keep track of stack needs here.
			 * Or we may want to run the verifier on the code before saving it
			 * (this may be needed anyway when the ILGenerator is not used...).
			 */
			switch (opcode.StackBehaviourPush) {
			case StackBehaviour.Push1:
			case StackBehaviour.Pushi:
			case StackBehaviour.Pushi8:
			case StackBehaviour.Pushr4:
			case StackBehaviour.Pushr8:
			case StackBehaviour.Pushref:
			case StackBehaviour.Varpush: /* again we are conservative and assume it pushes 1 */
				cur_stack ++;
				break;
			case StackBehaviour.Push1_push1:
				cur_stack += 2;
				break;
			}
			if (max_stack < cur_stack)
				max_stack = cur_stack;

			/* 
			 * Note that we adjust for the pop behaviour _after_ setting max_stack.
			 */
			switch (opcode.StackBehaviourPop) {
			case StackBehaviour.Varpop:
				break; /* we are conservative and assume it doesn't decrease the stack needs */
			case StackBehaviour.Pop1:
			case StackBehaviour.Popi:
			case StackBehaviour.Popref:
				cur_stack --;
				break;
			case StackBehaviour.Pop1_pop1:
			case StackBehaviour.Popi_pop1:
			case StackBehaviour.Popi_popi:
			case StackBehaviour.Popi_popi8:
			case StackBehaviour.Popi_popr4:
			case StackBehaviour.Popi_popr8:
			case StackBehaviour.Popref_pop1:
			case StackBehaviour.Popref_popi:
				cur_stack -= 2;
				break;
			case StackBehaviour.Popi_popi_popi:
			case StackBehaviour.Popref_popi_popi:
			case StackBehaviour.Popref_popi_popi8:
			case StackBehaviour.Popref_popi_popr4:
			case StackBehaviour.Popref_popi_popr8:
			case StackBehaviour.Popref_popi_popref:
				cur_stack -= 3;
				break;
			}
		}

		private static int target_len (OpCode opcode)
		{
			if (opcode.OperandType == OperandType.InlineBrTarget)
				return 4;
			return 1;
		}

		private void InternalEndClause ()
		{
			switch (ex_handlers [cur_block].LastClauseType ()) {
			case ILExceptionBlock.CATCH:
			case ILExceptionBlock.FILTER:
			case ILExceptionBlock.FILTER_START:
				// how could we optimize code size here?
				Emit (OpCodes.Leave, ex_handlers [cur_block].end);
				break;
			case ILExceptionBlock.FAULT:
			case ILExceptionBlock.FINALLY:
				Emit (OpCodes.Endfinally);
				break;
			}
		}

		public virtual void BeginCatchBlock (Type exceptionType)
		{
			if (open_blocks == null)
				open_blocks = new Stack (defaultExceptionStackSize);

			if (open_blocks.Count <= 0)
				throw new NotSupportedException ("Not in an exception block");
			if (exceptionType != null && exceptionType.IsUserType)
				throw new NotSupportedException ("User defined subclasses of System.Type are not yet supported.");
			if (ex_handlers [cur_block].LastClauseType () == ILExceptionBlock.FILTER_START) {
				if (exceptionType != null)
					throw new ArgumentException ("Do not supply an exception type for filter clause");
				Emit (OpCodes.Endfilter);
				ex_handlers [cur_block].PatchFilterClause (code_len);
			} else {
				InternalEndClause ();
				ex_handlers [cur_block].AddCatch (exceptionType, code_len);
			}
			
			cur_stack = 1; // the exception object is on the stack by default
			if (max_stack < cur_stack)
				max_stack = cur_stack;

			//System.Console.WriteLine ("Begin catch Block: {0} {1}",exceptionType.ToString(), max_stack);
		}

		public virtual void BeginExceptFilterBlock ()
		{
			if (open_blocks == null)
				open_blocks = new Stack (defaultExceptionStackSize);
			
			if (open_blocks.Count <= 0)
				throw new NotSupportedException ("Not in an exception block");
			InternalEndClause ();

			ex_handlers [cur_block].AddFilter (code_len);
		}

		public virtual Label BeginExceptionBlock ()
		{
			//System.Console.WriteLine ("Begin Block");
			if (open_blocks == null)
				open_blocks = new Stack (defaultExceptionStackSize);
			
			if (ex_handlers != null) {
				cur_block = ex_handlers.Length;
				ILExceptionInfo[] new_ex = new ILExceptionInfo [cur_block + 1];
				System.Array.Copy (ex_handlers, new_ex, cur_block);
				ex_handlers = new_ex;
			} else {
				ex_handlers = new ILExceptionInfo [1];
				cur_block = 0;
			}
			open_blocks.Push (cur_block);
			ex_handlers [cur_block].start = code_len;
			return ex_handlers [cur_block].end = DefineLabel ();
		}

		public virtual void BeginFaultBlock()
		{
			if (open_blocks == null)
				open_blocks = new Stack (defaultExceptionStackSize);
			
			if (open_blocks.Count <= 0)
				throw new NotSupportedException ("Not in an exception block");

			if (ex_handlers [cur_block].LastClauseType () == ILExceptionBlock.FILTER_START) {
				Emit (OpCodes.Leave, ex_handlers [cur_block].end);
				ex_handlers [cur_block].PatchFilterClause (code_len);
			}
			
			InternalEndClause ();
			//System.Console.WriteLine ("Begin fault Block");
			ex_handlers [cur_block].AddFault (code_len);
		}
		
		public virtual void BeginFinallyBlock()
		{
			if (open_blocks == null)
				open_blocks = new Stack (defaultExceptionStackSize);
			
			if (open_blocks.Count <= 0)
				throw new NotSupportedException ("Not in an exception block");

			InternalEndClause ();

			if (ex_handlers [cur_block].LastClauseType () == ILExceptionBlock.FILTER_START) {
				Emit (OpCodes.Leave, ex_handlers [cur_block].end);
				ex_handlers [cur_block].PatchFilterClause (code_len);
			}

			//System.Console.WriteLine ("Begin finally Block");
			ex_handlers [cur_block].AddFinally (code_len);
		}
		
		public virtual void BeginScope ()
		{ }

		public virtual LocalBuilder DeclareLocal (Type localType)
		{
			return DeclareLocal (localType, false);
		}


		public virtual LocalBuilder DeclareLocal (Type localType, bool pinned)
		{
			if (localType == null)
				throw new ArgumentNullException ("localType");
			if (localType.IsUserType)
				throw new NotSupportedException ("User defined subclasses of System.Type are not yet supported.");
			LocalBuilder res = new LocalBuilder (localType, this);
			res.is_pinned = pinned;
			
			if (locals != null) {
				LocalBuilder[] new_l = new LocalBuilder [locals.Length + 1];
				System.Array.Copy (locals, new_l, locals.Length);
				new_l [locals.Length] = res;
				locals = new_l;
			} else {
				locals = new LocalBuilder [1];
				locals [0] = res;
			}
			res.position = (ushort)(locals.Length - 1);
			return res;
		}
		
		public virtual Label DefineLabel ()
		{
			if (labels == null)
				labels = new LabelData [defaultLabelsSize];
			else if (num_labels >= labels.Length) {
				LabelData [] t = new LabelData [labels.Length * 2];
				Array.Copy (labels, t, labels.Length);
				labels = t;
			}
			
			labels [num_labels] = new LabelData (-1, 0);
			
			return new Label (num_labels++);
		}
		
		public virtual void Emit (OpCode opcode)
		{
			make_room (2);
			ll_emit (opcode);
		}
		
		public virtual void Emit (OpCode opcode, Byte arg)
		{
			make_room (3);
			ll_emit (opcode);
			code [code_len++] = arg;
		}
		
		[ComVisible (true)]
		public virtual void Emit (OpCode opcode, ConstructorInfo con)
		{
			int token = token_gen.GetToken (con, true);
			make_room (6);
			ll_emit (opcode);
			emit_int (token);
			
			if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
				cur_stack -= con.GetParametersCount ();
		}
		
		public virtual void Emit (OpCode opcode, double arg)
		{
			byte[] s = System.BitConverter.GetBytes (arg);
			make_room (10);
			ll_emit (opcode);
			if (BitConverter.IsLittleEndian){
				System.Array.Copy (s, 0, code, code_len, 8);
				code_len += 8;
			} else {
				code [code_len++] = s [7];
				code [code_len++] = s [6];
				code [code_len++] = s [5];
				code [code_len++] = s [4];
				code [code_len++] = s [3];
				code [code_len++] = s [2];
				code [code_len++] = s [1];
				code [code_len++] = s [0];
			}
		}
		
		public virtual void Emit (OpCode opcode, FieldInfo field)
		{
			int token = token_gen.GetToken (field, true);
			make_room (6);
			ll_emit (opcode);
			emit_int (token);
		}
		
		public virtual void Emit (OpCode opcode, Int16 arg)
		{
			make_room (4);
			ll_emit (opcode);
			code [code_len++] = (byte) (arg & 0xFF);
			code [code_len++] = (byte) ((arg >> 8) & 0xFF);
		}
		
		public virtual void Emit (OpCode opcode, int arg)
		{
			make_room (6);
			ll_emit (opcode);
			emit_int (arg);
		}
		
		public virtual void Emit (OpCode opcode, long arg)
		{
			make_room (10);
			ll_emit (opcode);
			code [code_len++] = (byte) (arg & 0xFF);
			code [code_len++] = (byte) ((arg >> 8) & 0xFF);
			code [code_len++] = (byte) ((arg >> 16) & 0xFF);
			code [code_len++] = (byte) ((arg >> 24) & 0xFF);
			code [code_len++] = (byte) ((arg >> 32) & 0xFF);
			code [code_len++] = (byte) ((arg >> 40) & 0xFF);
			code [code_len++] = (byte) ((arg >> 48) & 0xFF);
			code [code_len++] = (byte) ((arg >> 56) & 0xFF);
		}
		
		public virtual void Emit (OpCode opcode, Label label)
		{
			int tlen = target_len (opcode);
			make_room (6);
			ll_emit (opcode);
			if (cur_stack > labels [label.m_label].maxStack)
				labels [label.m_label].maxStack = cur_stack;
			
			if (fixups == null)
				fixups = new LabelFixup [defaultFixupSize]; 
			else if (num_fixups >= fixups.Length) {
				LabelFixup[] newf = new LabelFixup [fixups.Length * 2];
				System.Array.Copy (fixups, newf, fixups.Length);
				fixups = newf;
			}
			fixups [num_fixups].offset = tlen;
			fixups [num_fixups].pos = code_len;
			fixups [num_fixups].label_idx = label.m_label;
			num_fixups++;
			code_len += tlen;

		}
		
		public virtual void Emit (OpCode opcode, Label[] labels)
		{
			if (labels == null)
				throw new ArgumentNullException ("labels");

			/* opcode needs to be switch. */
			int count = labels.Length;
			make_room (6 + count * 4);
			ll_emit (opcode);

			for (int i = 0; i < count; ++i)
				if (cur_stack > this.labels [labels [i].m_label].maxStack)
					this.labels [labels [i].m_label].maxStack = cur_stack;

			emit_int (count);
			if (fixups == null)
				fixups = new LabelFixup [defaultFixupSize + count]; 
			else if (num_fixups + count >= fixups.Length) {
				LabelFixup[] newf = new LabelFixup [count + fixups.Length * 2];
				System.Array.Copy (fixups, newf, fixups.Length);
				fixups = newf;
			}
			
			// ECMA 335, Partition III, p94 (7-10)
			//
			// The switch instruction implements a jump table. The format of 
			// the instruction is an unsigned int32 representing the number of targets N,
			// followed by N int32 values specifying jump targets: these targets are
			// represented as offsets (positive or negative) from the beginning of the 
			// instruction following this switch instruction.
			//
			// We must make sure it gets an offset from the *end* of the last label
			// (eg, the beginning of the instruction following this).
			//
			// remaining is the number of bytes from the current instruction to the
			// instruction that will be emitted.
			
			for (int i = 0, remaining = count * 4; i < count; ++i, remaining -= 4) {
				fixups [num_fixups].offset = remaining;
				fixups [num_fixups].pos = code_len;
				fixups [num_fixups].label_idx = labels [i].m_label;
				num_fixups++;
				code_len += 4;
			}
		}

		public virtual void Emit (OpCode opcode, LocalBuilder local)
		{
			if (local == null)
				throw new ArgumentNullException ("local");
			if (local.ilgen != this)
				throw new ArgumentException ("Trying to emit a local from a different ILGenerator.");

			uint pos = local.position;
			bool load_addr = false;
			bool is_store = false;
			bool is_load = false;
			make_room (6);

			/* inline the code from ll_emit () to optimize il code size */
			if (opcode.StackBehaviourPop == StackBehaviour.Pop1) {
				cur_stack --;
				is_store = true;
			} else if (opcode.StackBehaviourPush == StackBehaviour.Push1 || opcode.StackBehaviourPush == StackBehaviour.Pushi) {
				cur_stack++;
				is_load = true;
				if (cur_stack > max_stack)
					max_stack = cur_stack;
				load_addr = opcode.StackBehaviourPush == StackBehaviour.Pushi;
			}
			if (load_addr) {
				if (pos < 256) {
					code [code_len++] = (byte)0x12;
					code [code_len++] = (byte)pos;
				} else {
					code [code_len++] = (byte)0xfe;
					code [code_len++] = (byte)0x0d;
					code [code_len++] = (byte)(pos & 0xff);
					code [code_len++] = (byte)((pos >> 8) & 0xff);
				}
			} else {
				if (is_store) {
					if (pos < 4) {
						code [code_len++] = (byte)(0x0a + pos);
					} else if (pos < 256) {
						code [code_len++] = (byte)0x13;
						code [code_len++] = (byte)pos;
					} else {
						code [code_len++] = (byte)0xfe;
						code [code_len++] = (byte)0x0e;
						code [code_len++] = (byte)(pos & 0xff);
						code [code_len++] = (byte)((pos >> 8) & 0xff);
					}
				} else if (is_load) {
					if (pos < 4) {
						code [code_len++] = (byte)(0x06 + pos);
					} else if (pos < 256) {
						code [code_len++] = (byte)0x11;
						code [code_len++] = (byte)pos;
					} else {
						code [code_len++] = (byte)0xfe;
						code [code_len++] = (byte)0x0c;
						code [code_len++] = (byte)(pos & 0xff);
						code [code_len++] = (byte)((pos >> 8) & 0xff);
					}
				} else {
					ll_emit (opcode);
				}
			}
		}

		public virtual void Emit (OpCode opcode, MethodInfo meth)
		{
			if (meth == null)
				throw new ArgumentNullException ("meth");

			// For compatibility with MS
			if ((meth is DynamicMethod) && ((opcode == OpCodes.Ldftn) || (opcode == OpCodes.Ldvirtftn) || (opcode == OpCodes.Ldtoken)))
				throw new ArgumentException ("Ldtoken, Ldftn and Ldvirtftn OpCodes cannot target DynamicMethods.");

			int token = token_gen.GetToken (meth, true);
			make_room (6);
			ll_emit (opcode);
			Type declaringType = meth.DeclaringType;
			emit_int (token);
			if (meth.ReturnType != typeof (void))
				cur_stack ++;

			if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
				cur_stack -= meth.GetParametersCount ();
		}

		private void Emit (OpCode opcode, MethodInfo method, int token)
		{
			make_room (6);
			ll_emit (opcode);
			emit_int (token);
			if (method.ReturnType != typeof (void))
				cur_stack ++;

			if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
				cur_stack -= method.GetParametersCount ();
		}

		[CLSCompliant(false)]
		public void Emit (OpCode opcode, sbyte arg)
		{
			make_room (3);
			ll_emit (opcode);
			code [code_len++] = (byte)arg;
		}

		public virtual void Emit (OpCode opcode, SignatureHelper signature)
		{
			int token = token_gen.GetToken (signature);
			make_room (6);
			ll_emit (opcode);
			emit_int (token);
		}

		public virtual void Emit (OpCode opcode, float arg)
		{
			byte[] s = System.BitConverter.GetBytes (arg);
			make_room (6);
			ll_emit (opcode);
			if (BitConverter.IsLittleEndian){
				System.Array.Copy (s, 0, code, code_len, 4);
				code_len += 4;
			} else {
				code [code_len++] = s [3];
				code [code_len++] = s [2];
				code [code_len++] = s [1];
				code [code_len++] = s [0];
			}
		}

		public virtual void Emit (OpCode opcode, string str)
		{
			int token = token_gen.GetToken (str);
			make_room (6);
			ll_emit (opcode);
			emit_int (token);
		}

		public virtual void Emit (OpCode opcode, Type cls)
		{
			if (cls != null && cls.IsByRef)
				throw new ArgumentException ("Cannot get TypeToken for a ByRef type.");

			make_room (6);
			ll_emit (opcode);
			int token = token_gen.GetToken (cls, opcode != OpCodes.Ldtoken);
			emit_int (token);
		}

		// FIXME: vararg methods are not supported
		public virtual void EmitCall (OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
		{
			if (methodInfo == null)
				throw new ArgumentNullException ("methodInfo");
			short value = opcode.Value;
			if (!(value == OpCodes.Call.Value || value == OpCodes.Callvirt.Value))
				throw new NotSupportedException ("Only Call and CallVirt are allowed");
			if ((methodInfo.CallingConvention & CallingConventions.VarArgs)  == 0)
				optionalParameterTypes = null;
			if (optionalParameterTypes != null){
				if ((methodInfo.CallingConvention & CallingConventions.VarArgs)  == 0){
					throw new InvalidOperationException ("Method is not VarArgs method and optional types were passed");
				}

				int token = token_gen.GetToken (methodInfo, optionalParameterTypes);
				Emit (opcode, methodInfo, token);
				return;
			}
			Emit (opcode, methodInfo);
		}

		public virtual void EmitCalli (OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes)
		{
			// GetMethodSigHelper expects a ModuleBuilder or null, and module might be
			// a normal module when using dynamic methods.
			SignatureHelper helper = SignatureHelper.GetMethodSigHelper (module as ModuleBuilder, 0, unmanagedCallConv, returnType, parameterTypes);
			Emit (opcode, helper);
		}

		public virtual void EmitCalli (OpCode opcode, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes)
		{
			if (optionalParameterTypes != null)
				throw new NotImplementedException ();

			SignatureHelper helper = SignatureHelper.GetMethodSigHelper (module as ModuleBuilder, callingConvention, 0, returnType, parameterTypes);
			Emit (opcode, helper);
		}

        static Type GetConsoleType ()
        {
            return Type.GetType ("System.Console, System.Console", throwOnError: true);
        }
		
		public virtual void EmitWriteLine (FieldInfo fld)
		{
			if (fld == null)
				throw new ArgumentNullException ("fld");
			
			// The MS implementation does not check for valuetypes here but it
			// should. Also, it should check that if the field is not static,
			// then it is a member of this type.
			if (fld.IsStatic)
				Emit (OpCodes.Ldsfld, fld);
			else {
				Emit (OpCodes.Ldarg_0);
				Emit (OpCodes.Ldfld, fld);
			}
			Emit (OpCodes.Call, GetConsoleType ().GetMethod ("WriteLine", new Type[1] { fld.FieldType }));
		}

		public virtual void EmitWriteLine (LocalBuilder localBuilder)
		{
			if (localBuilder == null)
				throw new ArgumentNullException ("localBuilder");
			if (localBuilder.LocalType is TypeBuilder)
				throw new  ArgumentException ("Output streams do not support TypeBuilders.");
			// The MS implementation does not check for valuetypes here but it
			// should.
			Emit (OpCodes.Ldloc, localBuilder);
			Emit (OpCodes.Call, GetConsoleType ().GetMethod ("WriteLine", new Type[1] { localBuilder.LocalType }));
		}
		
		public virtual void EmitWriteLine (string value)
		{
			Emit (OpCodes.Ldstr, value);
			Emit (OpCodes.Call, GetConsoleType ().GetMethod ("WriteLine", new Type[1] { typeof(string)}));
		}

		public virtual void EndExceptionBlock ()
		{
			if (open_blocks == null)
				open_blocks = new Stack (defaultExceptionStackSize);
			
			if (open_blocks.Count <= 0)
				throw new NotSupportedException ("Not in an exception block");

			if (ex_handlers [cur_block].LastClauseType () == ILExceptionBlock.FILTER_START)
				throw new InvalidOperationException ("Incorrect code generation for exception block.");

			InternalEndClause ();
			MarkLabel (ex_handlers [cur_block].end);
			ex_handlers [cur_block].End (code_len);
			ex_handlers [cur_block].Debug (cur_block);
			//System.Console.WriteLine ("End Block {0} (handlers: {1})", cur_block, ex_handlers [cur_block].NumHandlers ());
			open_blocks.Pop ();
			if (open_blocks.Count > 0)
				cur_block = (int)open_blocks.Peek ();
			//Console.WriteLine ("curblock restored to {0}", cur_block);
			//throw new NotImplementedException ();
		}

		public virtual void EndScope ()
		{ }

		public virtual void MarkLabel (Label loc)
		{
			if (loc.m_label < 0 || loc.m_label >= num_labels)
				throw new System.ArgumentException ("The label is not valid");
			if (labels [loc.m_label].addr >= 0)
				throw new System.ArgumentException ("The label was already defined");
			labels [loc.m_label].addr = code_len;
			if (labels [loc.m_label].maxStack > cur_stack)
				cur_stack = labels [loc.m_label].maxStack;
		}

		public virtual void MarkSequencePoint (ISymbolDocumentWriter document, int startLine,
						       int startColumn, int endLine, int endColumn)
		{
			if (currentSequence == null || currentSequence.Document != document) {
				if (sequencePointLists == null)
					sequencePointLists = new List<SequencePointList> ();
				currentSequence = new SequencePointList (document);
				sequencePointLists.Add (currentSequence);
			}
			
			currentSequence.AddSequencePoint (code_len, startLine, startColumn, endLine, endColumn);
		}
		
/*		
		internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
		{
			if (sequencePointLists != null) {
				SequencePointList first = (SequencePointList) sequencePointLists [0];
				SequencePointList last = (SequencePointList) sequencePointLists [sequencePointLists.Count - 1];
				symbolWriter.SetMethodSourceRange (first.Document, first.StartLine, first.StartColumn, last.Document, last.EndLine, last.EndColumn);
				
				foreach (SequencePointList list in sequencePointLists)
					symbolWriter.DefineSequencePoints (list.Document, list.GetOffsets(), list.GetLines(), list.GetColumns(), list.GetEndLines(), list.GetEndColumns());
				
				if (locals != null) {
					foreach (LocalBuilder local in locals) {
						if (local.Name != null && local.Name.Length > 0) {
							SignatureHelper sighelper = SignatureHelper.GetLocalVarSigHelper (module as ModuleBuilder);
							sighelper.AddArgument (local.LocalType);
							byte[] signature = sighelper.GetSignature ();
							symbolWriter.DefineLocalVariable (local.Name, FieldAttributes.Public, signature, SymAddressKind.ILOffset, local.position, 0, 0, local.StartOffset, local.EndOffset);
						}
					}
				}
				sequencePointLists = null;
			}
		}
*/

		internal bool HasDebugInfo
		{
			get { return sequencePointLists != null; }
		}

		public virtual void ThrowException (Type excType)
		{
			if (excType == null)
				throw new ArgumentNullException ("excType");
			if (! ((excType == typeof (Exception)) || 
				   excType.IsSubclassOf (typeof (Exception))))
				throw new ArgumentException ("Type should be an exception type", "excType");
			ConstructorInfo ctor = excType.GetConstructor (Type.EmptyTypes);
			if (ctor == null)
				throw new ArgumentException ("Type should have a default constructor", "excType");
			Emit (OpCodes.Newobj, ctor);
			Emit (OpCodes.Throw);
		}

		// FIXME: "Not implemented"
		public virtual void UsingNamespace (String usingNamespace)
		{
			throw new NotImplementedException ();
		}

		internal void label_fixup (MethodBase mb)
		{
			for (int i = 0; i < num_fixups; ++i) {
				if (labels [fixups [i].label_idx].addr < 0)
					throw new ArgumentException (string.Format ("Label #{0} is not marked in method `{1}'", fixups [i].label_idx + 1, mb.Name));
				// Diff is the offset from the end of the jump instruction to the address of the label
				int diff = labels [fixups [i].label_idx].addr - (fixups [i].pos + fixups [i].offset);
				if (fixups [i].offset == 1) {
					code [fixups [i].pos] = (byte)((sbyte) diff);
				} else {
					int old_cl = code_len;
					code_len = fixups [i].pos;
					emit_int (diff);
					code_len = old_cl;
				}
			}
		}

		// Used by DynamicILGenerator and MethodBuilder.SetMethodBody
		internal void SetCode (byte[] code, int max_stack) {
			// Make a copy to avoid possible security problems
			this.code = (byte[])code.Clone ();
			this.code_len = code.Length;
			this.max_stack = max_stack;
			this.cur_stack = 0;
		}

		internal unsafe void SetCode (byte *code, int code_size, int max_stack) {
			// Make a copy to avoid possible security problems
			this.code = new byte [code_size];
			for (int i = 0; i < code_size; ++i)
				this.code [i] = code [i];
			this.code_len = code_size;
			this.max_stack = max_stack;
			this.cur_stack = 0;
		}

		internal TokenGenerator TokenGenerator {
			get {
				return token_gen;
			}
		}

		public virtual int ILOffset {
			get { return code_len; }
		}
	}
	
	internal class SequencePointList
	{
		ISymbolDocumentWriter doc;
		SequencePoint[] points;
		int count;
		const int arrayGrow = 10;
		
		public SequencePointList (ISymbolDocumentWriter doc)
		{
			this.doc = doc;
		}
		
		public ISymbolDocumentWriter Document {
			get { return doc; }
		}
		
		public int[] GetOffsets()
		{
			int[] data = new int [count];
			for (int n=0; n<count; n++) data [n] = points[n].Offset;
			return data; 
		}
		public int[] GetLines()
		{
			int[] data = new int [count];
			for (int n=0; n<count; n++) data [n] = points[n].Line;
			return data; 
		}
		public int[] GetColumns()
		{
			int[] data = new int [count];
			for (int n=0; n<count; n++) data [n] = points[n].Col;
			return data; 
		}
		public int[] GetEndLines()
		{
			int[] data = new int [count];
			for (int n=0; n<count; n++) data [n] = points[n].EndLine;
			return data; 
		}
		public int[] GetEndColumns()
		{
			int[] data = new int [count];
			for (int n=0; n<count; n++) data [n] = points[n].EndCol;
			return data; 
		}
		public int StartLine {
			get { return points[0].Line; }
		}
		public int EndLine {
			get { return points[count - 1].Line; }
		}
		public int StartColumn {
			get { return points[0].Col; }
		}
		public int EndColumn {
			get { return points[count - 1].Col; }
		}
		
		public void AddSequencePoint (int offset, int line, int col, int endLine, int endCol)
		{
			SequencePoint s = new SequencePoint ();
			s.Offset = offset;
			s.Line = line;
			s.Col = col;
			s.EndLine = endLine;
			s.EndCol = endCol;
			
			if (points == null) {
				points = new SequencePoint [arrayGrow];
			} else if (count >= points.Length) {
				SequencePoint[] temp = new SequencePoint [count + arrayGrow];
				Array.Copy (points, temp, points.Length);
				points = temp;
			}
			
			points [count] = s;
			count++;
		}
	}
	
	struct SequencePoint {
		public int Offset;
		public int Line;
		public int Col;
		public int EndLine;
		public int EndCol;
	}

    class Stack
    {
        Object[] _array;
        int _size;
        int _version;

        private const int _defaultCapacity = 10;

        public Stack()
        {
            _array = new Object[_defaultCapacity];
            _size = 0;
            _version = 0;
        }

        public Stack(int initialCapacity)
        {
            if (initialCapacity < 0)
                throw new ArgumentOutOfRangeException(nameof(initialCapacity), SR.ArgumentOutOfRange_NeedNonNegNum);

            if (initialCapacity < _defaultCapacity)
                initialCapacity = _defaultCapacity;
            _array = new Object[initialCapacity];
            _size = 0;
            _version = 0;
        }

        public virtual int Count
        {
            get
            {
                return _size;
            }
        }

        public virtual Object Peek()
        {
            if (_size == 0)
                throw new InvalidOperationException ();

            return _array[_size - 1];
        }

        public virtual Object Pop()
        {
            if (_size == 0)
                throw new InvalidOperationException ();

            _version++;
            Object obj = _array[--_size];
            _array[_size] = null;
            return obj;
        }

        public virtual void Push(Object obj)
        {
            if (_size == _array.Length)
            {
                Object[] newArray = new Object[2 * _array.Length];
                Array.Copy(_array, 0, newArray, 0, _size);
                _array = newArray;
            }
            _array[_size++] = obj;
            _version++;
        }
	}
}
#endif