3 // System.Reflection.Emit/ILGenerator.cs
6 // Paolo Molaro (lupus@ximian.com)
8 // (C) 2001 Ximian, Inc. http://www.ximian.com
12 using System.Collections;
13 using System.Diagnostics.SymbolStore;
14 using System.Runtime.InteropServices;
15 using Mono.CSharp.Debugger;
17 namespace System.Reflection.Emit {
19 internal struct ILExceptionBlock {
20 public const int CATCH = 0;
21 public const int FILTER = 1;
22 public const int FINALLY = 2;
23 public const int FAULT = 4;
29 internal int filter_offset;
31 internal void Debug () {
33 System.Console.Write ("\ttype="+type.ToString()+" start="+start.ToString()+" len="+len.ToString());
35 System.Console.WriteLine (" extype="+extype.ToString());
37 System.Console.WriteLine ("");
41 internal struct ILExceptionInfo {
42 ILExceptionBlock[] handlers;
47 internal int NumHandlers ()
49 return handlers.Length;
52 internal void AddCatch (Type extype, int offset)
57 i = handlers.Length - 1;
58 handlers [i].type = ILExceptionBlock.CATCH;
59 handlers [i].start = offset;
60 handlers [i].extype = extype;
63 internal void AddFinally (int offset)
68 i = handlers.Length - 1;
69 handlers [i].type = ILExceptionBlock.FINALLY;
70 handlers [i].start = offset;
71 handlers [i].extype = null;
74 internal void End (int offset)
78 int i = handlers.Length - 1;
80 handlers [i].len = offset - handlers [i].start;
83 internal int LastClauseType ()
86 return handlers [handlers.Length-1].type;
88 return ILExceptionBlock.CATCH;
91 internal void Debug (int b)
94 System.Console.WriteLine ("Handler {0} at {1}, len: {2}", b, start, len);
95 for (int i = 0; i < handlers.Length; ++i)
96 handlers [i].Debug ();
100 void add_block (int offset)
102 if (handlers != null) {
103 int i = handlers.Length;
104 ILExceptionBlock[] new_b = new ILExceptionBlock [i + 1];
105 System.Array.Copy (handlers, new_b, i);
107 handlers [i].len = offset - handlers [i].start;
109 handlers = new ILExceptionBlock [1];
110 len = offset - start;
115 internal struct ILTokenInfo {
116 public MemberInfo member;
120 internal interface TokenGenerator {
121 int GetToken (string str);
123 int GetToken (MemberInfo member);
125 int GetToken (SignatureHelper helper);
128 public class ILGenerator: Object {
129 private struct LabelFixup {
130 public int offset; // The number of bytes between pos and the
131 // offset of the jump
132 public int pos; // Where offset of the label is placed
133 public int label_idx; // The label to jump to
137 public LabelData (int addr, int maxStack)
140 this.maxStack = maxStack;
147 static Type void_type = typeof (void);
148 #region Sync with reflection.h
150 private int code_len;
151 private int max_stack;
152 private int cur_stack;
153 private LocalBuilder[] locals;
154 private ILExceptionInfo[] ex_handlers;
155 private int num_token_fixups;
156 private ILTokenInfo[] token_fixups;
159 private LabelData [] labels;
160 private int num_labels;
161 private LabelFixup[] fixups;
162 private int num_fixups;
163 internal Module module;
164 internal IMonoSymbolWriter sym_writer;
165 private Stack scopes;
166 private int cur_block;
167 private Stack open_blocks;
168 private TokenGenerator token_gen;
170 const int defaultFixupSize = 8;
171 const int defaultLabelsSize = 8;
173 internal ILGenerator (Module m, TokenGenerator token_gen, int size)
178 code = new byte [size];
179 cur_stack = max_stack = 0;
180 num_fixups = num_labels = 0;
181 token_fixups = new ILTokenInfo [8];
182 num_token_fixups = 0;
184 if (module is ModuleBuilder)
185 sym_writer = ((ModuleBuilder)module).symbol_writer;
186 open_blocks = new Stack ();
187 this.token_gen = token_gen;
190 private void add_token_fixup (MemberInfo mi)
192 if (num_token_fixups == token_fixups.Length) {
193 ILTokenInfo[] ntf = new ILTokenInfo [num_token_fixups * 2];
194 token_fixups.CopyTo (ntf, 0);
197 token_fixups [num_token_fixups].member = mi;
198 token_fixups [num_token_fixups++].code_pos = code_len;
201 private void make_room (int nbytes)
203 if (code_len + nbytes < code.Length)
205 byte[] new_code = new byte [(code_len + nbytes) * 2 + 128];
206 System.Array.Copy (code, 0, new_code, 0, code.Length);
210 private void emit_int (int val)
212 code [code_len++] = (byte) (val & 0xFF);
213 code [code_len++] = (byte) ((val >> 8) & 0xFF);
214 code [code_len++] = (byte) ((val >> 16) & 0xFF);
215 code [code_len++] = (byte) ((val >> 24) & 0xFF);
218 /* change to pass by ref to avoid copy */
219 private void ll_emit (OpCode opcode)
222 * there is already enough room allocated in code.
224 // access op1 and op2 directly since the Value property is useless
225 if (opcode.Size == 2)
226 code [code_len++] = opcode.op1;
227 code [code_len++] = opcode.op2;
229 * We should probably keep track of stack needs here.
230 * Or we may want to run the verifier on the code before saving it
231 * (this may be needed anyway when the ILGenerator is not used...).
233 switch (opcode.StackBehaviourPush) {
234 case StackBehaviour.Push1:
235 case StackBehaviour.Pushi:
236 case StackBehaviour.Pushi8:
237 case StackBehaviour.Pushr4:
238 case StackBehaviour.Pushr8:
239 case StackBehaviour.Pushref:
240 case StackBehaviour.Varpush: /* again we are conservative and assume it pushes 1 */
243 case StackBehaviour.Push1_push1:
247 if (max_stack < cur_stack)
248 max_stack = cur_stack;
251 * Note that we adjust for the pop behaviour _after_ setting max_stack.
253 switch (opcode.StackBehaviourPop) {
254 case StackBehaviour.Varpop:
255 break; /* we are conservative and assume it doesn't decrease the stack needs */
256 case StackBehaviour.Pop1:
257 case StackBehaviour.Popi:
258 case StackBehaviour.Popref:
261 case StackBehaviour.Pop1_pop1:
262 case StackBehaviour.Popi_pop1:
263 case StackBehaviour.Popi_popi:
264 case StackBehaviour.Popi_popi8:
265 case StackBehaviour.Popi_popr4:
266 case StackBehaviour.Popi_popr8:
267 case StackBehaviour.Popref_pop1:
268 case StackBehaviour.Popref_popi:
271 case StackBehaviour.Popi_popi_popi:
272 case StackBehaviour.Popref_popi_popi:
273 case StackBehaviour.Popref_popi_popi8:
274 case StackBehaviour.Popref_popi_popr4:
275 case StackBehaviour.Popref_popi_popr8:
276 case StackBehaviour.Popref_popi_popref:
282 private static int target_len (OpCode opcode)
284 if (opcode.OperandType == OperandType.InlineBrTarget)
289 private void InternalEndClause ()
291 switch (ex_handlers [cur_block].LastClauseType ()) {
292 case ILExceptionBlock.CATCH:
293 // how could we optimize code size here?
294 Emit (OpCodes.Leave, ex_handlers [cur_block].end);
296 case ILExceptionBlock.FAULT:
297 case ILExceptionBlock.FINALLY:
298 Emit (OpCodes.Endfinally);
300 case ILExceptionBlock.FILTER:
301 Emit (OpCodes.Endfilter);
306 public virtual void BeginCatchBlock (Type exceptionType)
308 if (open_blocks.Count <= 0)
309 throw new NotSupportedException ("Not in an exception block");
310 InternalEndClause ();
311 ex_handlers [cur_block].AddCatch (exceptionType, code_len);
312 cur_stack = 1; // the exception object is on the stack by default
313 if (max_stack < cur_stack)
314 max_stack = cur_stack;
315 //System.Console.WriteLine ("Begin catch Block: {0} {1}",exceptionType.ToString(), max_stack);
316 //throw new NotImplementedException ();
320 public virtual void BeginExceptFilterBlock ()
322 throw new NotImplementedException ();
325 public virtual Label BeginExceptionBlock ()
327 //System.Console.WriteLine ("Begin Block");
329 if (ex_handlers != null) {
330 cur_block = ex_handlers.Length;
331 ILExceptionInfo[] new_ex = new ILExceptionInfo [cur_block + 1];
332 System.Array.Copy (ex_handlers, new_ex, cur_block);
333 ex_handlers = new_ex;
335 ex_handlers = new ILExceptionInfo [1];
338 open_blocks.Push (cur_block);
339 ex_handlers [cur_block].start = code_len;
340 return ex_handlers [cur_block].end = DefineLabel ();
343 public virtual void BeginFaultBlock()
345 if (open_blocks.Count <= 0)
346 throw new NotSupportedException ("Not in an exception block");
347 //System.Console.WriteLine ("Begin fault Block");
348 //throw new NotImplementedException ();
351 public virtual void BeginFinallyBlock()
353 if (open_blocks.Count <= 0)
354 throw new NotSupportedException ("Not in an exception block");
355 InternalEndClause ();
356 //System.Console.WriteLine ("Begin finally Block");
357 ex_handlers [cur_block].AddFinally (code_len);
360 public virtual void BeginScope ()
362 if (sym_writer != null) {
364 scopes = new Stack ();
365 scopes.Push (sym_writer.OpenScope (code_len));
369 public LocalBuilder DeclareLocal (Type localType)
371 LocalBuilder res = new LocalBuilder (localType, this);
372 if (locals != null) {
373 LocalBuilder[] new_l = new LocalBuilder [locals.Length + 1];
374 System.Array.Copy (locals, new_l, locals.Length);
375 new_l [locals.Length] = res;
378 locals = new LocalBuilder [1];
381 res.position = (uint)(locals.Length - 1);
385 public virtual Label DefineLabel ()
388 labels = new LabelData [defaultLabelsSize];
389 else if (num_labels >= labels.Length) {
390 LabelData [] t = new LabelData [labels.Length * 2];
391 Array.Copy (labels, t, labels.Length);
395 labels [num_labels] = new LabelData (-1, 0);
397 return new Label (num_labels++);
400 public virtual void Emit (OpCode opcode)
406 public virtual void Emit (OpCode opcode, Byte val)
410 code [code_len++] = val;
413 public virtual void Emit (OpCode opcode, ConstructorInfo constructor)
415 int token = token_gen.GetToken (constructor);
418 if (constructor.DeclaringType.Module == module)
419 add_token_fixup (constructor);
421 ParameterInfo[] mparams = constructor.GetParameters();
422 if ((opcode.StackBehaviourPop == StackBehaviour.Varpop) && (mparams != null))
423 cur_stack -= mparams.Length;
426 public virtual void Emit (OpCode opcode, double val)
428 Double.AssertEndianity (out val);
430 byte[] s = System.BitConverter.GetBytes (val);
433 if (BitConverter.IsLittleEndian){
434 System.Array.Copy (s, 0, code, code_len, 8);
437 code [code_len++] = s [7];
438 code [code_len++] = s [6];
439 code [code_len++] = s [5];
440 code [code_len++] = s [4];
441 code [code_len++] = s [3];
442 code [code_len++] = s [2];
443 code [code_len++] = s [1];
444 code [code_len++] = s [0];
448 public virtual void Emit (OpCode opcode, FieldInfo field)
450 int token = token_gen.GetToken (field);
453 if (field.DeclaringType.Module == module)
454 add_token_fixup (field);
458 public virtual void Emit (OpCode opcode, Int16 val)
462 code [code_len++] = (byte) (val & 0xFF);
463 code [code_len++] = (byte) ((val >> 8) & 0xFF);
466 public virtual void Emit (OpCode opcode, int val)
473 public virtual void Emit (OpCode opcode, long val)
477 code [code_len++] = (byte) (val & 0xFF);
478 code [code_len++] = (byte) ((val >> 8) & 0xFF);
479 code [code_len++] = (byte) ((val >> 16) & 0xFF);
480 code [code_len++] = (byte) ((val >> 24) & 0xFF);
481 code [code_len++] = (byte) ((val >> 32) & 0xFF);
482 code [code_len++] = (byte) ((val >> 40) & 0xFF);
483 code [code_len++] = (byte) ((val >> 48) & 0xFF);
484 code [code_len++] = (byte) ((val >> 56) & 0xFF);
487 public virtual void Emit (OpCode opcode, Label label)
489 int tlen = target_len (opcode);
492 if (cur_stack > labels [label.label].maxStack)
493 labels [label.label].maxStack = cur_stack;
496 fixups = new LabelFixup [defaultFixupSize];
497 else if (num_fixups >= fixups.Length) {
498 LabelFixup[] newf = new LabelFixup [fixups.Length + 16];
499 System.Array.Copy (fixups, newf, fixups.Length);
502 fixups [num_fixups].offset = tlen;
503 fixups [num_fixups].pos = code_len;
504 fixups [num_fixups].label_idx = label.label;
510 public virtual void Emit (OpCode opcode, Label[] labels)
512 /* opcode needs to be switch. */
513 int count = labels.Length;
514 make_room (6 + count * 4);
517 for (int i = 0; i < count; ++i)
518 if (cur_stack > this.labels [labels [i].label].maxStack)
519 this.labels [labels [i].label].maxStack = cur_stack;
523 fixups = new LabelFixup [defaultFixupSize + count];
524 else if (num_fixups + count >= fixups.Length) {
525 LabelFixup[] newf = new LabelFixup [fixups.Length + count + 16];
526 System.Array.Copy (fixups, newf, fixups.Length);
530 // ECMA 335, Partition III, p94 (7-10)
532 // The switch instruction implements a jump table. The format of
533 // the instruction is an unsigned int32 representing the number of targets N,
534 // followed by N int32 values specifying jump targets: these targets are
535 // represented as offsets (positive or negative) from the beginning of the
536 // instruction following this switch instruction.
538 // We must make sure it gets an offset from the *end* of the last label
539 // (eg, the beginning of the instruction following this).
541 // remaining is the number of bytes from the current instruction to the
542 // instruction that will be emitted.
544 for (int i = 0, remaining = count * 4; i < count; ++i, remaining -= 4) {
545 fixups [num_fixups].offset = remaining;
546 fixups [num_fixups].pos = code_len;
547 fixups [num_fixups].label_idx = labels [i].label;
553 public virtual void Emit (OpCode opcode, LocalBuilder lbuilder)
555 uint pos = lbuilder.position;
556 bool load_addr = false;
557 bool is_store = false;
560 if (lbuilder.ilgen != this)
561 throw new Exception ("Trying to emit a local from a different ILGenerator.");
563 /* inline the code from ll_emit () to optimize il code size */
564 if (opcode.StackBehaviourPop == StackBehaviour.Pop1) {
569 if (cur_stack > max_stack)
570 max_stack = cur_stack;
571 load_addr = opcode.StackBehaviourPush == StackBehaviour.Pushi;
575 code [code_len++] = (byte)0x12;
576 code [code_len++] = (byte)pos;
578 code [code_len++] = (byte)0xfe;
579 code [code_len++] = (byte)0x0d;
580 code [code_len++] = (byte)(pos & 0xff);
581 code [code_len++] = (byte)((pos >> 8) & 0xff);
586 code [code_len++] = (byte)(0x0a + pos);
587 } else if (pos < 256) {
588 code [code_len++] = (byte)0x13;
589 code [code_len++] = (byte)pos;
591 code [code_len++] = (byte)0xfe;
592 code [code_len++] = (byte)0x0e;
593 code [code_len++] = (byte)(pos & 0xff);
594 code [code_len++] = (byte)((pos >> 8) & 0xff);
598 code [code_len++] = (byte)(0x06 + pos);
599 } else if (pos < 256) {
600 code [code_len++] = (byte)0x11;
601 code [code_len++] = (byte)pos;
603 code [code_len++] = (byte)0xfe;
604 code [code_len++] = (byte)0x0c;
605 code [code_len++] = (byte)(pos & 0xff);
606 code [code_len++] = (byte)((pos >> 8) & 0xff);
612 public virtual void Emit (OpCode opcode, MethodInfo method)
615 throw new ArgumentNullException ("method");
617 int token = token_gen.GetToken (method);
620 if (method.DeclaringType.Module == module)
621 add_token_fixup (method);
623 if (method.ReturnType != void_type)
625 ParameterInfo[] mparams = method.GetParameters();
626 if ((opcode.StackBehaviourPop == StackBehaviour.Varpop) && (mparams != null))
627 cur_stack -= mparams.Length;
630 [CLSCompliant(false)]
631 public void Emit (OpCode opcode, sbyte val)
635 code [code_len++] = (byte)val;
638 public virtual void Emit (OpCode opcode, SignatureHelper shelper)
640 int token = token_gen.GetToken (shelper);
646 public virtual void Emit (OpCode opcode, float val)
648 byte[] s = System.BitConverter.GetBytes (val);
651 if (BitConverter.IsLittleEndian){
652 System.Array.Copy (s, 0, code, code_len, 4);
655 code [code_len++] = s [3];
656 code [code_len++] = s [2];
657 code [code_len++] = s [1];
658 code [code_len++] = s [0];
662 public virtual void Emit (OpCode opcode, string val)
664 int token = token_gen.GetToken (val);
670 public virtual void Emit (OpCode opcode, Type type)
674 emit_int (token_gen.GetToken (type));
677 [MonoTODO ("Do something about varargs method")]
678 public void EmitCall (OpCode opcode, MethodInfo methodinfo, Type[] optionalParamTypes)
680 if (methodinfo == null)
681 throw new ArgumentNullException ("methodinfo can not be null");
682 short value = opcode.Value;
683 if (!(value == OpCodes.Call.Value || value == OpCodes.Callvirt.Value))
684 throw new NotSupportedException ("Only Call and CallVirt are allowed");
685 if (optionalParamTypes != null){
686 if ((methodinfo.CallingConvention & CallingConventions.VarArgs) == 0){
687 throw new InvalidOperationException ("Method is not VarArgs method and optional types were passed");
690 Emit (opcode, methodinfo);
693 public void EmitCalli (OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] paramTypes)
695 SignatureHelper helper
696 = SignatureHelper.GetMethodSigHelper (module, 0, unmanagedCallConv, returnType, paramTypes);
697 Emit (opcode, helper);
700 public void EmitCalli (OpCode opcode, CallingConventions callConv, Type returnType, Type[] paramTypes, Type[] optionalParamTypes)
702 if (optionalParamTypes != null)
703 throw new NotImplementedException ();
705 SignatureHelper helper
706 = SignatureHelper.GetMethodSigHelper (module, callConv, 0, returnType, paramTypes);
707 Emit (opcode, helper);
710 public virtual void EmitWriteLine (FieldInfo field)
713 throw new ArgumentNullException ("field");
715 // The MS implementation does not check for valuetypes here but it
716 // should. Also, it should check that if the field is not static,
717 // then it is a member of this type.
719 Emit (OpCodes.Ldsfld, field);
721 Emit (OpCodes.Ldarg_0);
722 Emit (OpCodes.Ldfld, field);
725 typeof (Console).GetMethod ("WriteLine",
726 new Type[1] { field.FieldType }));
729 public virtual void EmitWriteLine (LocalBuilder lbuilder)
731 if (lbuilder == null)
732 throw new ArgumentNullException ("lbuilder");
733 if (lbuilder.LocalType is TypeBuilder)
734 throw new ArgumentException ("Output streams do not support TypeBuilders.");
735 // The MS implementation does not check for valuetypes here but it
737 Emit (OpCodes.Ldloc, lbuilder);
739 typeof (Console).GetMethod ("WriteLine",
740 new Type[1] { lbuilder.LocalType }));
743 public virtual void EmitWriteLine (string val)
745 Emit (OpCodes.Ldstr, val);
747 typeof (Console).GetMethod ("WriteLine",
748 new Type[1] { typeof(string)}));
751 public virtual void EndExceptionBlock ()
753 if (open_blocks.Count <= 0)
754 throw new NotSupportedException ("Not in an exception block");
755 InternalEndClause ();
756 MarkLabel (ex_handlers [cur_block].end);
757 ex_handlers [cur_block].End (code_len);
758 ex_handlers [cur_block].Debug (cur_block);
759 //System.Console.WriteLine ("End Block {0} (handlers: {1})", cur_block, ex_handlers [cur_block].NumHandlers ());
761 if (open_blocks.Count > 0)
762 cur_block = (int)open_blocks.Peek ();
763 //Console.WriteLine ("curblock restored to {0}", cur_block);
764 //throw new NotImplementedException ();
767 public virtual void EndScope ()
769 if (sym_writer != null) {
770 sym_writer.CloseScope (code_len);
772 throw new InvalidOperationException ();
777 public virtual void MarkLabel (Label loc)
779 if (loc.label < 0 || loc.label >= num_labels)
780 throw new System.ArgumentException ("The label is not valid");
781 if (labels [loc.label].addr >= 0)
782 throw new System.ArgumentException ("The label was already defined");
783 labels [loc.label].addr = code_len;
784 if (labels [loc.label].maxStack > cur_stack)
785 cur_stack = labels [loc.label].maxStack;
788 public virtual void MarkSequencePoint (ISymbolDocumentWriter document, int startLine,
789 int startColumn, int endLine, int endColumn)
791 if (sym_writer == null)
794 sym_writer.MarkSequencePoint (code_len, startLine, startColumn);
797 public virtual void ThrowException (Type exceptionType)
799 if (exceptionType == null)
800 throw new ArgumentNullException ("exceptionType");
801 if (! ((exceptionType == typeof (Exception)) ||
802 exceptionType.IsSubclassOf (typeof (Exception))))
803 throw new ArgumentException ("Type should be an exception type", "exceptionType");
804 ConstructorInfo ctor = exceptionType.GetConstructor (new Type[0]);
806 throw new ArgumentException ("Type should have a default constructor", "exceptionType");
807 Emit (OpCodes.Newobj, ctor);
808 Emit (OpCodes.Throw);
812 public void UsingNamespace (String usingNamespace)
814 throw new NotImplementedException ();
817 internal void label_fixup ()
819 for (int i = 0; i < num_fixups; ++i) {
821 // Diff is the offset from the end of the jump instruction to the address of the label
822 int diff = labels [fixups [i].label_idx].addr - (fixups [i].pos + fixups [i].offset);
823 if (fixups [i].offset == 1) {
824 code [fixups [i].pos] = (byte)((sbyte) diff);
826 int old_cl = code_len;
827 code_len = fixups [i].pos;