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