Thu Mar 7 17:10:42 CET 2002 Paolo Molaro <lupus@ximian.com>
[mono.git] / mcs / class / corlib / System.Reflection.Emit / ILGenerator.cs
1
2 //
3 // System.Reflection.Emit/ILGenerator.cs
4 //
5 // Author:
6 //   Paolo Molaro (lupus@ximian.com)
7 //
8 // (C) 2001 Ximian, Inc.  http://www.ximian.com
9 //
10
11 using System;
12 using System.Diagnostics.SymbolStore;
13
14 namespace System.Reflection.Emit {
15
16         internal struct ILExceptionBlock {
17                 public const int CATCH = 0;
18                 public const int FILTER = 1;
19                 public const int FINALLY = 2;
20                 public const int FAULT = 4;
21
22                 internal Type extype;
23                 internal int type;
24                 internal int start;
25                 internal int len;
26                 internal int filter_offset;
27                 
28                 internal void Debug () {
29                         System.Console.Write ("\ttype="+type.ToString()+" start="+start.ToString()+" len="+len.ToString());
30                         if (extype != null)
31                                 System.Console.WriteLine (" extype="+extype.ToString());
32                         else
33                                 System.Console.WriteLine ("");
34                 }
35         }
36         internal struct ILExceptionInfo {
37                 ILExceptionBlock[] handlers;
38                 internal int start;
39                 int len;
40                 internal Label end;
41
42                 internal void AddCatch (Type extype, int offset) {
43                         int i;
44                         End (offset);
45                         add_block (offset);
46                         i = handlers.Length - 1;
47                         handlers [i].type = ILExceptionBlock.CATCH;
48                         handlers [i].start = offset;
49                         handlers [i].extype = extype;
50                 }
51
52                 internal void AddFinally (int offset) {
53                         int i;
54                         End (offset);
55                         add_block (offset);
56                         i = handlers.Length - 1;
57                         handlers [i].type = ILExceptionBlock.FINALLY;
58                         handlers [i].start = offset;
59                         handlers [i].extype = null;
60                 }
61
62                 internal void End (int offset) {
63                         if (handlers == null)
64                                 return;
65                         int i = handlers.Length - 1;
66                         if (i >= 0)
67                                 handlers [i].len = offset - handlers [i].start;
68                 }
69
70                 internal int LastClauseType () {
71                         if (handlers != null)
72                                 return handlers [handlers.Length-1].type;
73                         else
74                                 return ILExceptionBlock.CATCH;
75                 }
76
77                 internal void Debug () {
78                         if (false) {
79                         System.Console.WriteLine ("Handler at "+start.ToString()+ " len: "+len.ToString());
80                         for (int i = 0; i < handlers.Length; ++i)
81                                 handlers [i].Debug ();
82                         }
83                 }
84
85                 void add_block (int offset) {
86                         if (handlers != null) {
87                                 int i = handlers.Length;
88                                 ILExceptionBlock[] new_b = new ILExceptionBlock [i + 1];
89                                 System.Array.Copy (handlers, new_b, i);
90                                 handlers = new_b;
91                                 handlers [i].len = offset - handlers [i].start;
92                         } else {
93                                 handlers = new ILExceptionBlock [1];
94                                 len = offset - start;
95                         }
96                 }
97         }
98         
99         internal struct ILTokenInfo {
100                 public MemberInfo member;
101                 public int code_pos;
102         }
103
104         public class ILGenerator: Object {
105                 private struct LabelFixup {
106                         public int size;
107                         public int pos;
108                         public int label_idx;
109                 };
110                 private byte[] code;
111                 private MethodBase mbuilder; /* a MethodBuilder or ConstructorBuilder */
112                 private int code_len;
113                 private int max_stack;
114                 private int cur_stack;
115                 private LocalBuilder[] locals;
116                 private ILExceptionInfo[] ex_handlers;
117                 private int num_token_fixups;
118                 private ILTokenInfo[] token_fixups;
119                 private int[] label_to_addr;
120                 private int num_labels;
121                 private LabelFixup[] fixups;
122                 private int num_fixups;
123                 private AssemblyBuilder abuilder;
124                 private int cur_block;
125                 private int open_blocks;
126
127                 internal ILGenerator (MethodBase mb, int size) {
128                         if (size < 0)
129                                 size = 256;
130                         code_len = 0;
131                         code = new byte [size];
132                         mbuilder = mb;
133                         cur_stack = max_stack = 0;
134                         num_fixups = num_labels = 0;
135                         label_to_addr = new int [16];
136                         fixups = new LabelFixup [16];
137                         token_fixups = new ILTokenInfo [16];
138                         num_token_fixups = 0;
139                         if (mb is MethodBuilder) {
140                                 abuilder = (AssemblyBuilder)((MethodBuilder)mb).TypeBuilder.Module.Assembly;
141                         } else if (mb is ConstructorBuilder) {
142                                 abuilder = (AssemblyBuilder)((ConstructorBuilder)mb).TypeBuilder.Module.Assembly;
143                         }
144                 }
145
146                 private void add_token_fixup (MemberInfo mi) {
147                         if (num_token_fixups == token_fixups.Length) {
148                                 ILTokenInfo[] ntf = new ILTokenInfo [num_token_fixups * 2];
149                                 token_fixups.CopyTo (ntf, 0);
150                                 token_fixups = ntf;
151                         }
152                         token_fixups [num_token_fixups].member = mi;
153                         token_fixups [num_token_fixups++].code_pos = code_len;
154                 }
155
156                 private void make_room (int nbytes) {
157                         if (code_len + nbytes < code.Length)
158                                 return;
159                         byte[] new_code = new byte [code.Length * 2 + 128];
160                         System.Array.Copy (code, 0, new_code, 0, code.Length);
161                         code = new_code;
162                 }
163                 private void emit_int (int val) {
164                         code [code_len++] = (byte) (val & 0xFF);
165                         code [code_len++] = (byte) ((val >> 8) & 0xFF);
166                         code [code_len++] = (byte) ((val >> 16) & 0xFF);
167                         code [code_len++] = (byte) ((val >> 24) & 0xFF);
168                 }
169                 /* change to pass by ref to avoid copy */
170                 private void ll_emit (OpCode opcode) {
171                         /* 
172                          * there is already enough room allocated in code.
173                          */
174                         // access op1 and op2 directly since the Value property is useless
175                         if (opcode.Size == 2)
176                                 code [code_len++] = opcode.op1;
177                         code [code_len++] = opcode.op2;
178                         /*
179                          * We should probably keep track of stack needs here.
180                          * Or we may want to run the verifier on the code before saving it
181                          * (this may be needed anyway when the ILGenerator is not used...).
182                          */
183                         switch (opcode.StackBehaviourPush) {
184                         case StackBehaviour.Push1:
185                         case StackBehaviour.Pushi:
186                         case StackBehaviour.Pushi8:
187                         case StackBehaviour.Pushr4:
188                         case StackBehaviour.Pushr8:
189                         case StackBehaviour.Pushref:
190                         case StackBehaviour.Varpush: /* again we are conservative and assume it pushes 1 */
191                                 cur_stack ++;
192                                 break;
193                         case StackBehaviour.Push1_push1:
194                                 cur_stack += 2;
195                                 break;
196                         }
197                         if (max_stack < cur_stack)
198                                 max_stack = cur_stack;
199                         /* 
200                          * Note that we adjust for the pop behaviour _after_ setting max_stack.
201                          */
202                         switch (opcode.StackBehaviourPop) {
203                         case StackBehaviour.Varpop:
204                                 break; /* we are conservative and assume it doesn't decrease the stack needs */
205                         case StackBehaviour.Pop1:
206                         case StackBehaviour.Popi:
207                         case StackBehaviour.Popref:
208                                 cur_stack --;
209                                 break;
210                         case StackBehaviour.Pop1_pop1:
211                         case StackBehaviour.Popi_pop1:
212                         case StackBehaviour.Popi_popi:
213                         case StackBehaviour.Popi_popi8:
214                         case StackBehaviour.Popi_popr4:
215                         case StackBehaviour.Popi_popr8:
216                         case StackBehaviour.Popref_pop1:
217                         case StackBehaviour.Popref_popi:
218                                 cur_stack -= 2;
219                                 break;
220                         case StackBehaviour.Popi_popi_popi:
221                         case StackBehaviour.Popref_popi_popi:
222                         case StackBehaviour.Popref_popi_popi8:
223                         case StackBehaviour.Popref_popi_popr4:
224                         case StackBehaviour.Popref_popi_popr8:
225                         case StackBehaviour.Popref_popi_popref:
226                                 cur_stack -= 3;
227                                 break;
228                         }
229                 }
230
231                 private static int target_len (OpCode opcode) {
232                         if (opcode.operandType == OperandType.InlineBrTarget)
233                                 return 4;
234                         return 1;
235                 }
236
237                 private void InternalEndClause () {
238                         switch (ex_handlers [cur_block].LastClauseType ()) {
239                         case ILExceptionBlock.CATCH:
240                                 // how could we optimize code size here?
241                                 Emit (OpCodes.Leave, ex_handlers [cur_block].end);
242                                 break;
243                         case ILExceptionBlock.FAULT:
244                         case ILExceptionBlock.FINALLY:
245                                 Emit (OpCodes.Endfinally);
246                                 break;
247                         case ILExceptionBlock.FILTER:
248                                 Emit (OpCodes.Endfilter);
249                                 break;
250                         }
251                 }
252
253                 public virtual void BeginCatchBlock (Type exceptionType) {
254                         if (open_blocks <= 0)
255                                 throw new NotSupportedException ("Not in an exception block");
256                         InternalEndClause ();
257                         ex_handlers [cur_block].AddCatch (exceptionType, code_len);
258                         //System.Console.WriteLine ("Begin catch Block: "+exceptionType.ToString());
259                         //throw new NotImplementedException ();
260                 }
261                 public virtual void BeginExceptFilterBlock () {
262                         throw new NotImplementedException ();
263                 }
264                 public virtual Label BeginExceptionBlock () {
265                         //System.Console.WriteLine ("Begin Block");
266                         
267                         if (ex_handlers != null) {
268                                 cur_block = ex_handlers.Length;
269                                 ILExceptionInfo[] new_ex = new ILExceptionInfo [cur_block + 1];
270                                 System.Array.Copy (ex_handlers, new_ex, cur_block);
271                                 ex_handlers = new_ex;
272                         } else {
273                                 ex_handlers = new ILExceptionInfo [1];
274                                 cur_block = 0;
275                         }
276                         open_blocks++;
277                         ex_handlers [cur_block].start = code_len;
278                         return ex_handlers [cur_block].end = DefineLabel ();
279                 }
280                 public virtual void BeginFaultBlock() {
281                         if (open_blocks <= 0)
282                                 throw new NotSupportedException ("Not in an exception block");
283                         //System.Console.WriteLine ("Begin fault Block");
284                         //throw new NotImplementedException ();
285                 }
286                 public virtual void BeginFinallyBlock() {
287                         if (open_blocks <= 0)
288                                 throw new NotSupportedException ("Not in an exception block");
289                         //System.Console.WriteLine ("Begin finally Block");
290                         InternalEndClause ();
291                         ex_handlers [cur_block].AddFinally (code_len);
292                         //throw new NotImplementedException ();
293                 }
294                 public virtual void BeginScope () {
295                         throw new NotImplementedException ();
296                 }
297                 public virtual LocalBuilder DeclareLocal (Type localType) {
298                         LocalBuilder res = new LocalBuilder (localType);
299                         if (locals != null) {
300                                 LocalBuilder[] new_l = new LocalBuilder [locals.Length + 1];
301                                 System.Array.Copy (locals, new_l, locals.Length);
302                                 new_l [locals.Length] = res;
303                                 locals = new_l;
304                         } else {
305                                 locals = new LocalBuilder [1];
306                                 locals [0] = res;
307                         }
308                         res.position = locals.Length - 1;
309                         return res;
310                 }
311                 public virtual Label DefineLabel () {
312                         if (num_labels >= label_to_addr.Length) {
313                                 int[] new_l = new int [label_to_addr.Length + 16];
314                                 System.Array.Copy (label_to_addr, new_l, label_to_addr.Length);
315                                 label_to_addr = new_l;
316                         }
317                         label_to_addr [num_labels] = -1;
318                         return new Label (num_labels++);
319                 }
320                 public virtual void Emit (OpCode opcode) {
321                         make_room (2);
322                         ll_emit (opcode);
323                 }
324                 public virtual void Emit (OpCode opcode, Byte val) {
325                         make_room (3);
326                         ll_emit (opcode);
327                         code [code_len++] = val;
328                 }
329                 public virtual void Emit (OpCode opcode, ConstructorInfo constructor) {
330                         int token = abuilder.GetToken (constructor);
331                         make_room (6);
332                         ll_emit (opcode);
333                         if (constructor is ConstructorBuilder)
334                                 add_token_fixup (constructor);
335                         emit_int (token);
336                 }
337                 public virtual void Emit (OpCode opcode, Double val) {
338                         byte[] s = System.BitConverter.GetBytes (val);
339                         make_room (10);
340                         ll_emit (opcode);
341                         System.Array.Copy (s, 0, code, code_len, 8);
342                         code_len += 8;
343                 }
344                 public virtual void Emit (OpCode opcode, FieldInfo field) {
345                         int token = abuilder.GetToken (field);
346                         make_room (6);
347                         ll_emit (opcode);
348                         if (field is FieldBuilder)
349                                 add_token_fixup (field);
350                         emit_int (token);
351                 }
352                 public virtual void Emit (OpCode opcode, Int16 val) {
353                         make_room (4);
354                         ll_emit (opcode);
355                         code [code_len++] = (byte) (val & 0xFF);
356                         code [code_len++] = (byte) ((val >> 8) & 0xFF);
357                 }
358                 public virtual void Emit (OpCode opcode, Int32 val) {
359                         make_room (6);
360                         ll_emit (opcode);
361                         emit_int (val);
362                 }
363                 public virtual void Emit (OpCode opcode, Int64 val) {
364                         make_room (10);
365                         ll_emit (opcode);
366                         code [code_len++] = (byte) (val & 0xFF);
367                         code [code_len++] = (byte) ((val >> 8) & 0xFF);
368                         code [code_len++] = (byte) ((val >> 16) & 0xFF);
369                         code [code_len++] = (byte) ((val >> 24) & 0xFF);
370                         code [code_len++] = (byte) ((val >> 32) & 0xFF);
371                         code [code_len++] = (byte) ((val >> 40) & 0xFF);
372                         code [code_len++] = (byte) ((val >> 48) & 0xFF);
373                         code [code_len++] = (byte) ((val >> 56) & 0xFF);
374                 }
375                 public virtual void Emit (OpCode opcode, Label label) {
376                         int tlen = target_len (opcode);
377                         make_room (6);
378                         ll_emit (opcode);
379                         if (num_fixups >= fixups.Length) {
380                                 LabelFixup[] newf = new LabelFixup [fixups.Length + 16];
381                                 System.Array.Copy (fixups, newf, fixups.Length);
382                                 fixups = newf;
383                         }
384                         fixups [num_fixups].size = tlen;
385                         fixups [num_fixups].pos = code_len;
386                         fixups [num_fixups].label_idx = label.label;
387                         num_fixups++;
388                         code_len += tlen;
389
390                 }
391                 public virtual void Emit (OpCode opcode, Label[] labels) {
392                         /* opcode needs to be switch. */
393                         int count = labels.Length;
394                         make_room (6 + count * 4);
395                         ll_emit (opcode);
396                         emit_int (count);
397                         if (num_fixups + count >= fixups.Length) {
398                                 LabelFixup[] newf = new LabelFixup [fixups.Length + count + 16];
399                                 System.Array.Copy (fixups, newf, fixups.Length);
400                                 fixups = newf;
401                         }
402                         for (int i = 0; i < count; ++i) {
403                                 fixups [num_fixups].size = 4;
404                                 fixups [num_fixups].pos = code_len;
405                                 fixups [num_fixups].label_idx = labels [i].label;
406                                 num_fixups++;
407                                 code_len += 4;
408                         }
409                 }
410                 public virtual void Emit (OpCode opcode, LocalBuilder lbuilder) {
411                         make_room (6);
412                         ll_emit (opcode);
413                         code [code_len++] = (byte) (lbuilder.position & 0xFF);
414                         if (opcode.operandType == OperandType.InlineVar) {
415                                 code [code_len++] = (byte) ((lbuilder.position >> 8) & 0xFF);
416                         }
417                 }
418                 public virtual void Emit (OpCode opcode, MethodInfo method) {
419                         int token = abuilder.GetToken (method);
420                         make_room (6);
421                         ll_emit (opcode);
422                         if (method is MethodBuilder)
423                                 add_token_fixup (method);
424                         emit_int (token);
425                 }
426                 [CLSCompliant(false)]
427                 public virtual void Emit (OpCode opcode, sbyte val) {
428                         make_room (3);
429                         ll_emit (opcode);
430                         code [code_len++] = (byte)val;
431                 }
432
433                 [MonoTODO]
434                 public virtual void Emit (OpCode opcode, SignatureHelper shelper) {
435                         int token = 0; // FIXME: request a token from the modulebuilder
436                         make_room (6);
437                         ll_emit (opcode);
438                         emit_int (token);
439                 }
440                 public virtual void Emit (OpCode opcode, float val) {
441                         byte[] s = System.BitConverter.GetBytes (val);
442                         make_room (6);
443                         ll_emit (opcode);
444                         System.Array.Copy (s, 0, code, code_len, 4);
445                         code_len += 4;
446                 }
447                 public virtual void Emit (OpCode opcode, string val) {
448                         int token = abuilder.GetToken (val);
449                         make_room (6);
450                         ll_emit (opcode);
451                         emit_int (token);
452                 }
453                 public virtual void Emit (OpCode opcode, Type type) {
454                         make_room (6);
455                         ll_emit (opcode);
456                         emit_int (abuilder.GetToken (type));
457                 }
458
459                 public void EmitCall (OpCode opcode, MethodInfo methodinfo, Type[] optionalParamTypes) {
460                         throw new NotImplementedException ();
461                 }
462                 public void EmitCalli (OpCode opcode, CallingConventions call_conv, Type returnType, Type[] paramTypes, Type[] optionalParamTypes) {
463                         throw new NotImplementedException ();
464                 }
465
466                 public virtual void EmitWriteLine (FieldInfo field) {
467                         throw new NotImplementedException ();
468                 }
469                 public virtual void EmitWriteLine (LocalBuilder lbuilder) {
470                         throw new NotImplementedException ();
471                 }
472                 public virtual void EmitWriteLine (string val) {
473                         throw new NotImplementedException ();
474                 }
475
476                 public virtual void EndExceptionBlock () {
477                         if (open_blocks <= 0)
478                                 throw new NotSupportedException ("Not in an exception block");
479                         InternalEndClause ();
480                         MarkLabel (ex_handlers [cur_block].end);
481                         ex_handlers [cur_block].End (code_len);
482                         ex_handlers [cur_block].Debug ();
483                         --cur_block;
484                         --open_blocks;
485                         //System.Console.WriteLine ("End Block");
486                         //throw new NotImplementedException ();
487                 }
488                 public virtual void EndScope () {
489                         throw new NotImplementedException ();
490                 }
491                 public virtual void MarkLabel (Label loc) {
492                         if (loc.label < 0 || loc.label >= num_labels)
493                                 throw new System.ArgumentException ("The label is not valid");
494                         if (label_to_addr [loc.label] >= 0)
495                                 throw new System.ArgumentException ("The label was already defined");
496                         label_to_addr [loc.label] = code_len;
497                 }
498                 public virtual void MarkSequencePoint (ISymbolDocumentWriter document, int startLine, int startColumn, int endLine, int EndColumn) {
499                         throw new NotImplementedException ();
500                 }
501                 public virtual void ThrowException (Type exceptionType) {
502                         throw new NotImplementedException ();
503                 }
504                 public virtual void UsingNamespace (String usingNamespace) {
505                         throw new NotImplementedException ();
506                 }
507
508                 internal void label_fixup () {
509                         int i;
510                         for (i = 0; i < num_fixups; ++i) {
511                                 int diff = label_to_addr [fixups [i].label_idx] - fixups [i].pos;
512                                 if (fixups [i].size == 1) {
513                                         code [fixups [i].pos] = (byte)((sbyte) diff - 1);
514                                 } else {
515                                         int old_cl = code_len;
516                                         code_len = fixups [i].pos;
517                                         emit_int (diff - 4);
518                                         code_len = old_cl;
519                                 }
520                         }
521                 }
522         }
523 }