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 () {
48 return handlers.Length;
51 internal void AddCatch (Type extype, int offset) {
55 i = handlers.Length - 1;
56 handlers [i].type = ILExceptionBlock.CATCH;
57 handlers [i].start = offset;
58 handlers [i].extype = extype;
61 internal void AddFinally (int offset) {
65 i = handlers.Length - 1;
66 handlers [i].type = ILExceptionBlock.FINALLY;
67 handlers [i].start = offset;
68 handlers [i].extype = null;
71 internal void End (int offset) {
74 int i = handlers.Length - 1;
76 handlers [i].len = offset - handlers [i].start;
79 internal int LastClauseType () {
81 return handlers [handlers.Length-1].type;
83 return ILExceptionBlock.CATCH;
86 internal void Debug (int b) {
88 System.Console.WriteLine ("Handler {0} at {1}, len: {2}", b, start, len);
89 for (int i = 0; i < handlers.Length; ++i)
90 handlers [i].Debug ();
94 void add_block (int offset) {
95 if (handlers != null) {
96 int i = handlers.Length;
97 ILExceptionBlock[] new_b = new ILExceptionBlock [i + 1];
98 System.Array.Copy (handlers, new_b, i);
100 handlers [i].len = offset - handlers [i].start;
102 handlers = new ILExceptionBlock [1];
103 len = offset - start;
108 internal struct ILTokenInfo {
109 public MemberInfo member;
113 public class ILGenerator: Object {
114 private struct LabelFixup {
116 public int pos; // the location of the fixup
117 public int label_base; // the base address for this fixup
118 public int label_idx;
120 static Type void_type = typeof (void);
122 private MethodBase mbuilder; /* a MethodBuilder or ConstructorBuilder */
123 private int code_len;
124 private int max_stack;
125 private int cur_stack;
126 private LocalBuilder[] locals;
127 private ILExceptionInfo[] ex_handlers;
128 private int num_token_fixups;
129 private ILTokenInfo[] token_fixups;
130 private int[] label_to_addr;
131 private int num_labels;
132 private LabelFixup[] fixups;
133 private int num_fixups;
134 private ModuleBuilder module;
135 private AssemblyBuilder abuilder;
136 private IMonoSymbolWriter sym_writer;
137 private Stack scopes;
138 private int cur_block;
139 private Stack open_blocks;
141 internal ILGenerator (MethodBase mb, int size) {
145 code = new byte [size];
147 cur_stack = max_stack = 0;
148 num_fixups = num_labels = 0;
149 label_to_addr = new int [8];
150 fixups = new LabelFixup [8];
151 token_fixups = new ILTokenInfo [8];
152 num_token_fixups = 0;
153 if (mb is MethodBuilder) {
154 module = (ModuleBuilder)((MethodBuilder)mb).TypeBuilder.Module;
155 } else if (mb is ConstructorBuilder) {
156 module = (ModuleBuilder)((ConstructorBuilder)mb).TypeBuilder.Module;
158 abuilder = (AssemblyBuilder)module.Assembly;
159 sym_writer = module.symbol_writer;
160 open_blocks = new Stack ();
163 private void add_token_fixup (MemberInfo mi) {
164 if (num_token_fixups == token_fixups.Length) {
165 ILTokenInfo[] ntf = new ILTokenInfo [num_token_fixups * 2];
166 token_fixups.CopyTo (ntf, 0);
169 token_fixups [num_token_fixups].member = mi;
170 token_fixups [num_token_fixups++].code_pos = code_len;
173 private void make_room (int nbytes) {
174 if (code_len + nbytes < code.Length)
176 byte[] new_code = new byte [(code_len + nbytes) * 2 + 128];
177 System.Array.Copy (code, 0, new_code, 0, code.Length);
180 private void emit_int (int val) {
181 code [code_len++] = (byte) (val & 0xFF);
182 code [code_len++] = (byte) ((val >> 8) & 0xFF);
183 code [code_len++] = (byte) ((val >> 16) & 0xFF);
184 code [code_len++] = (byte) ((val >> 24) & 0xFF);
186 /* change to pass by ref to avoid copy */
187 private void ll_emit (OpCode opcode) {
189 * there is already enough room allocated in code.
191 // access op1 and op2 directly since the Value property is useless
192 if (opcode.Size == 2)
193 code [code_len++] = opcode.op1;
194 code [code_len++] = opcode.op2;
196 * We should probably keep track of stack needs here.
197 * Or we may want to run the verifier on the code before saving it
198 * (this may be needed anyway when the ILGenerator is not used...).
200 switch (opcode.StackBehaviourPush) {
201 case StackBehaviour.Push1:
202 case StackBehaviour.Pushi:
203 case StackBehaviour.Pushi8:
204 case StackBehaviour.Pushr4:
205 case StackBehaviour.Pushr8:
206 case StackBehaviour.Pushref:
207 case StackBehaviour.Varpush: /* again we are conservative and assume it pushes 1 */
210 case StackBehaviour.Push1_push1:
214 if (max_stack < cur_stack)
215 max_stack = cur_stack;
218 * Note that we adjust for the pop behaviour _after_ setting max_stack.
220 switch (opcode.StackBehaviourPop) {
221 case StackBehaviour.Varpop:
222 break; /* we are conservative and assume it doesn't decrease the stack needs */
223 case StackBehaviour.Pop1:
224 case StackBehaviour.Popi:
225 case StackBehaviour.Popref:
228 case StackBehaviour.Pop1_pop1:
229 case StackBehaviour.Popi_pop1:
230 case StackBehaviour.Popi_popi:
231 case StackBehaviour.Popi_popi8:
232 case StackBehaviour.Popi_popr4:
233 case StackBehaviour.Popi_popr8:
234 case StackBehaviour.Popref_pop1:
235 case StackBehaviour.Popref_popi:
238 case StackBehaviour.Popi_popi_popi:
239 case StackBehaviour.Popref_popi_popi:
240 case StackBehaviour.Popref_popi_popi8:
241 case StackBehaviour.Popref_popi_popr4:
242 case StackBehaviour.Popref_popi_popr8:
243 case StackBehaviour.Popref_popi_popref:
249 private static int target_len (OpCode opcode) {
250 if (opcode.operandType == OperandType.InlineBrTarget)
255 private void InternalEndClause () {
256 switch (ex_handlers [cur_block].LastClauseType ()) {
257 case ILExceptionBlock.CATCH:
258 // how could we optimize code size here?
259 Emit (OpCodes.Leave, ex_handlers [cur_block].end);
261 case ILExceptionBlock.FAULT:
262 case ILExceptionBlock.FINALLY:
263 Emit (OpCodes.Endfinally);
265 case ILExceptionBlock.FILTER:
266 Emit (OpCodes.Endfilter);
271 public virtual void BeginCatchBlock (Type exceptionType) {
272 if (open_blocks.Count <= 0)
273 throw new NotSupportedException ("Not in an exception block");
274 InternalEndClause ();
275 ex_handlers [cur_block].AddCatch (exceptionType, code_len);
276 cur_stack = 1; // the exception object is on the stack by default
277 if (max_stack < cur_stack)
278 max_stack = cur_stack;
279 //System.Console.WriteLine ("Begin catch Block: {0} {1}",exceptionType.ToString(), max_stack);
280 //throw new NotImplementedException ();
282 public virtual void BeginExceptFilterBlock () {
283 throw new NotImplementedException ();
285 public virtual Label BeginExceptionBlock () {
286 //System.Console.WriteLine ("Begin Block");
288 if (ex_handlers != null) {
289 cur_block = ex_handlers.Length;
290 ILExceptionInfo[] new_ex = new ILExceptionInfo [cur_block + 1];
291 System.Array.Copy (ex_handlers, new_ex, cur_block);
292 ex_handlers = new_ex;
294 ex_handlers = new ILExceptionInfo [1];
297 open_blocks.Push (cur_block);
298 ex_handlers [cur_block].start = code_len;
299 return ex_handlers [cur_block].end = DefineLabel ();
301 public virtual void BeginFaultBlock() {
302 if (open_blocks.Count <= 0)
303 throw new NotSupportedException ("Not in an exception block");
304 //System.Console.WriteLine ("Begin fault Block");
305 //throw new NotImplementedException ();
307 public virtual void BeginFinallyBlock() {
308 if (open_blocks.Count <= 0)
309 throw new NotSupportedException ("Not in an exception block");
310 InternalEndClause ();
311 //System.Console.WriteLine ("Begin finally Block");
312 ex_handlers [cur_block].AddFinally (code_len);
314 public virtual void BeginScope () {
315 if (sym_writer != null) {
317 scopes = new Stack ();
318 scopes.Push (sym_writer.OpenScope (code_len));
321 public LocalBuilder DeclareLocal (Type localType) {
322 LocalBuilder res = new LocalBuilder (module, localType, this);
323 if (locals != null) {
324 LocalBuilder[] new_l = new LocalBuilder [locals.Length + 1];
325 System.Array.Copy (locals, new_l, locals.Length);
326 new_l [locals.Length] = res;
329 locals = new LocalBuilder [1];
332 res.position = (uint)(locals.Length - 1);
335 public virtual Label DefineLabel () {
336 if (num_labels >= label_to_addr.Length) {
337 int[] new_l = new int [label_to_addr.Length * 2];
338 System.Array.Copy (label_to_addr, new_l, label_to_addr.Length);
339 label_to_addr = new_l;
341 label_to_addr [num_labels] = -1;
342 return new Label (num_labels++);
344 public virtual void Emit (OpCode opcode) {
348 public virtual void Emit (OpCode opcode, Byte val) {
351 code [code_len++] = val;
353 public virtual void Emit (OpCode opcode, ConstructorInfo constructor) {
354 int token = abuilder.GetToken (constructor);
357 if (constructor.DeclaringType.Module == module)
358 add_token_fixup (constructor);
360 ParameterInfo[] mparams = constructor.GetParameters();
361 if ((opcode.StackBehaviourPop == StackBehaviour.Varpop) && (mparams != null))
362 cur_stack -= mparams.Length;
364 public virtual void Emit (OpCode opcode, double val) {
365 byte[] s = System.BitConverter.GetBytes (val);
368 if (BitConverter.IsLittleEndian){
369 System.Array.Copy (s, 0, code, code_len, 8);
372 code [code_len++] = s [7];
373 code [code_len++] = s [6];
374 code [code_len++] = s [5];
375 code [code_len++] = s [4];
376 code [code_len++] = s [3];
377 code [code_len++] = s [2];
378 code [code_len++] = s [1];
379 code [code_len++] = s [0];
382 public virtual void Emit (OpCode opcode, FieldInfo field) {
383 int token = abuilder.GetToken (field);
386 if (field.DeclaringType.Module == module)
387 add_token_fixup (field);
390 public virtual void Emit (OpCode opcode, Int16 val) {
393 code [code_len++] = (byte) (val & 0xFF);
394 code [code_len++] = (byte) ((val >> 8) & 0xFF);
396 public virtual void Emit (OpCode opcode, int val) {
401 public virtual void Emit (OpCode opcode, long val) {
404 code [code_len++] = (byte) (val & 0xFF);
405 code [code_len++] = (byte) ((val >> 8) & 0xFF);
406 code [code_len++] = (byte) ((val >> 16) & 0xFF);
407 code [code_len++] = (byte) ((val >> 24) & 0xFF);
408 code [code_len++] = (byte) ((val >> 32) & 0xFF);
409 code [code_len++] = (byte) ((val >> 40) & 0xFF);
410 code [code_len++] = (byte) ((val >> 48) & 0xFF);
411 code [code_len++] = (byte) ((val >> 56) & 0xFF);
413 public virtual void Emit (OpCode opcode, Label label) {
414 int tlen = target_len (opcode);
417 if (num_fixups >= fixups.Length) {
418 LabelFixup[] newf = new LabelFixup [fixups.Length + 16];
419 System.Array.Copy (fixups, newf, fixups.Length);
422 fixups [num_fixups].size = tlen;
423 fixups [num_fixups].pos = code_len;
424 fixups [num_fixups].label_base = code_len;
425 fixups [num_fixups].label_idx = label.label;
430 public virtual void Emit (OpCode opcode, Label[] labels) {
431 /* opcode needs to be switch. */
432 int count = labels.Length;
433 make_room (6 + count * 4);
435 int switch_base = code_len + count*4;
437 if (num_fixups + count >= fixups.Length) {
438 LabelFixup[] newf = new LabelFixup [fixups.Length + count + 16];
439 System.Array.Copy (fixups, newf, fixups.Length);
442 for (int i = 0; i < count; ++i) {
443 fixups [num_fixups].size = 4;
444 fixups [num_fixups].pos = code_len;
445 fixups [num_fixups].label_base = switch_base;
446 fixups [num_fixups].label_idx = labels [i].label;
451 public virtual void Emit (OpCode opcode, LocalBuilder lbuilder) {
452 uint pos = lbuilder.position;
453 bool load_addr = false;
454 bool is_store = false;
457 if (lbuilder.ilgen != this)
458 throw new Exception ("Trying to emit a local from a different ILGenerator.");
460 /* inline the code from ll_emit () to optimize il code size */
461 if (opcode.StackBehaviourPop == StackBehaviour.Pop1) {
466 if (cur_stack > max_stack)
467 max_stack = cur_stack;
468 load_addr = opcode.StackBehaviourPush == StackBehaviour.Pushi;
472 code [code_len++] = (byte)0x12;
473 code [code_len++] = (byte)pos;
475 code [code_len++] = (byte)0xfe;
476 code [code_len++] = (byte)0x0d;
477 code [code_len++] = (byte)(pos & 0xff);
478 code [code_len++] = (byte)((pos >> 8) & 0xff);
483 code [code_len++] = (byte)(0x0a + pos);
484 } else if (pos < 256) {
485 code [code_len++] = (byte)0x13;
486 code [code_len++] = (byte)pos;
488 code [code_len++] = (byte)0xfe;
489 code [code_len++] = (byte)0x0e;
490 code [code_len++] = (byte)(pos & 0xff);
491 code [code_len++] = (byte)((pos >> 8) & 0xff);
495 code [code_len++] = (byte)(0x06 + pos);
496 } else if (pos < 256) {
497 code [code_len++] = (byte)0x11;
498 code [code_len++] = (byte)pos;
500 code [code_len++] = (byte)0xfe;
501 code [code_len++] = (byte)0x0c;
502 code [code_len++] = (byte)(pos & 0xff);
503 code [code_len++] = (byte)((pos >> 8) & 0xff);
508 public virtual void Emit (OpCode opcode, MethodInfo method) {
510 throw new ArgumentNullException ("method");
512 int token = abuilder.GetToken (method);
515 if (method.DeclaringType.Module == module)
516 add_token_fixup (method);
518 if (method.ReturnType != void_type)
520 ParameterInfo[] mparams = method.GetParameters();
521 if ((opcode.StackBehaviourPop == StackBehaviour.Varpop) && (mparams != null))
522 cur_stack -= mparams.Length;
524 [CLSCompliant(false)]
525 public void Emit (OpCode opcode, sbyte val) {
528 code [code_len++] = (byte)val;
531 public virtual void Emit (OpCode opcode, SignatureHelper shelper) {
532 int token = abuilder.GetToken (shelper);
537 public virtual void Emit (OpCode opcode, float val) {
538 byte[] s = System.BitConverter.GetBytes (val);
541 if (BitConverter.IsLittleEndian){
542 System.Array.Copy (s, 0, code, code_len, 4);
545 code [code_len++] = s [3];
546 code [code_len++] = s [2];
547 code [code_len++] = s [1];
548 code [code_len++] = s [0];
551 public virtual void Emit (OpCode opcode, string val) {
552 int token = abuilder.GetToken (val);
557 public virtual void Emit (OpCode opcode, Type type) {
560 emit_int (abuilder.GetToken (type));
563 public void EmitCall (OpCode opcode, MethodInfo methodinfo, Type[] optionalParamTypes) {
564 throw new NotImplementedException ();
567 public void EmitCalli (OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] paramTypes) {
568 SignatureHelper helper
569 = SignatureHelper.GetMethodSigHelper (module, 0, unmanagedCallConv, returnType, paramTypes);
570 Emit (opcode, helper);
573 public void EmitCalli (OpCode opcode, CallingConventions callConv, Type returnType, Type[] paramTypes, Type[] optionalParamTypes) {
574 if (optionalParamTypes != null)
575 throw new NotImplementedException ();
577 SignatureHelper helper
578 = SignatureHelper.GetMethodSigHelper (module, callConv, 0, returnType, paramTypes);
579 Emit (opcode, helper);
582 public virtual void EmitWriteLine (FieldInfo field) {
583 throw new NotImplementedException ();
585 public virtual void EmitWriteLine (LocalBuilder lbuilder) {
586 throw new NotImplementedException ();
588 public virtual void EmitWriteLine (string val) {
589 Emit (OpCodes.Ldstr, val);
591 typeof (Console).GetMethod ("WriteLine",
592 new Type[1] { typeof(string)}));
595 public virtual void EndExceptionBlock () {
596 if (open_blocks.Count <= 0)
597 throw new NotSupportedException ("Not in an exception block");
598 InternalEndClause ();
599 MarkLabel (ex_handlers [cur_block].end);
600 ex_handlers [cur_block].End (code_len);
601 ex_handlers [cur_block].Debug (cur_block);
602 //System.Console.WriteLine ("End Block {0} (handlers: {1})", cur_block, ex_handlers [cur_block].NumHandlers ());
604 if (open_blocks.Count > 0)
605 cur_block = (int)open_blocks.Peek ();
606 //Console.WriteLine ("curblock restored to {0}", cur_block);
607 //throw new NotImplementedException ();
609 public virtual void EndScope () {
610 if (sym_writer != null) {
611 sym_writer.CloseScope (code_len);
613 throw new InvalidOperationException ();
617 public virtual void MarkLabel (Label loc) {
618 if (loc.label < 0 || loc.label >= num_labels)
619 throw new System.ArgumentException ("The label is not valid");
620 if (label_to_addr [loc.label] >= 0)
621 throw new System.ArgumentException ("The label was already defined");
622 label_to_addr [loc.label] = code_len;
624 public virtual void MarkSequencePoint (ISymbolDocumentWriter document, int startLine,
625 int startColumn, int endLine, int endColumn) {
626 if (sym_writer == null)
629 sym_writer.MarkSequencePoint (code_len, startLine, startColumn);
631 public virtual void ThrowException (Type exceptionType) {
632 throw new NotImplementedException ();
634 public void UsingNamespace (String usingNamespace) {
635 throw new NotImplementedException ();
638 internal void label_fixup () {
640 for (i = 0; i < num_fixups; ++i) {
641 int diff = label_to_addr [fixups [i].label_idx] - fixups [i].label_base;
642 if (fixups [i].size == 1) {
643 code [fixups [i].pos] = (byte)((sbyte) diff - 1);
645 int old_cl = code_len;
646 code_len = fixups [i].pos;