2004-10-17 Miguel de Icaza <miguel@ximian.com>
[mono.git] / mcs / mcs / codegen.cs
1 //
2 // codegen.cs: The code generator
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 2004 Novell, Inc.
9 //
10 //#define PRODUCTION
11 using System;
12 using System.IO;
13 using System.Collections;
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Runtime.InteropServices;
17 using System.Security.Cryptography;
18
19 using Mono.Security.Cryptography;
20
21 namespace Mono.CSharp {
22
23         /// <summary>
24         ///    Code generator class.
25         /// </summary>
26         public class CodeGen {
27                 static AppDomain current_domain;
28                 static public SymbolWriter SymbolWriter;
29
30                 public static AssemblyClass Assembly;
31                 public static ModuleClass Module;
32
33                 static CodeGen ()
34                 {
35                         Assembly = new AssemblyClass ();
36                         Module = new ModuleClass (RootContext.Unsafe);
37                 }
38
39                 public static string Basename (string name)
40                 {
41                         int pos = name.LastIndexOf ('/');
42
43                         if (pos != -1)
44                                 return name.Substring (pos + 1);
45
46                         pos = name.LastIndexOf ('\\');
47                         if (pos != -1)
48                                 return name.Substring (pos + 1);
49
50                         return name;
51                 }
52
53                 public static string Dirname (string name)
54                 {
55                         int pos = name.LastIndexOf ('/');
56
57                         if (pos != -1)
58                                 return name.Substring (0, pos);
59
60                         pos = name.LastIndexOf ('\\');
61                         if (pos != -1)
62                                 return name.Substring (0, pos);
63
64                         return ".";
65                 }
66
67                 static string TrimExt (string name)
68                 {
69                         int pos = name.LastIndexOf ('.');
70
71                         return name.Substring (0, pos);
72                 }
73
74                 static public string FileName;
75
76                 //
77                 // Initializes the symbol writer
78                 //
79                 static void InitializeSymbolWriter (string filename)
80                 {
81                         SymbolWriter = SymbolWriter.GetSymbolWriter (Module.Builder, filename);
82
83                         //
84                         // If we got an ISymbolWriter instance, initialize it.
85                         //
86                         if (SymbolWriter == null) {
87                                 Report.Warning (
88                                         -18, "Could not find the symbol writer assembly (Mono.CSharp.Debugger.dll). This is normally an installation problem. Please make sure to compile and install the mcs/class/Mono.CSharp.Debugger directory.");
89                                 return;
90                         }
91                 }
92
93                 //
94                 // Initializes the code generator variables
95                 //
96                 static public void Init (string name, string output, bool want_debugging_support)
97                 {
98                         FileName = output;
99                         AssemblyName an = Assembly.GetAssemblyName (name, output);
100
101                         if (an.KeyPair != null) {
102                                 // If we are going to strong name our assembly make
103                                 // sure all its refs are strong named
104                                 foreach (Assembly a in TypeManager.GetAssemblies ()) {
105                                         AssemblyName ref_name = a.GetName ();
106                                         byte [] b = ref_name.GetPublicKeyToken ();
107                                         if (b == null || b.Length == 0) {
108                                                 Report.Warning (1577, "Assembly generation failed " +
109                                                                 "-- Referenced assembly '" +
110                                                                 ref_name.Name +
111                                                                 "' does not have a strong name.");
112                                                 //Environment.Exit (1);
113                                         }
114                                 }
115                         }
116                         
117                         current_domain = AppDomain.CurrentDomain;
118
119                         try {
120                                 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
121                                         AssemblyBuilderAccess.Save, Dirname (name));
122                         }
123                         catch (ArgumentException) {
124                                 // specified key may not be exportable outside it's container
125                                 if (RootContext.StrongNameKeyContainer != null) {
126                                         Report.Error (1548, "Could not access the key inside the container `" +
127                                                 RootContext.StrongNameKeyContainer + "'.");
128                                         Environment.Exit (1);
129                                 }
130                                 throw;
131                         }
132                         catch (CryptographicException) {
133                                 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
134                                         Report.Error (1548, "Could not use the specified key to strongname the assembly.");
135                                         Environment.Exit (1);
136                                 }
137                                 throw;
138                         }
139
140                         //
141                         // Pass a path-less name to DefineDynamicModule.  Wonder how
142                         // this copes with output in different directories then.
143                         // FIXME: figure out how this copes with --output /tmp/blah
144                         //
145                         // If the third argument is true, the ModuleBuilder will dynamically
146                         // load the default symbol writer.
147                         //
148                         Module.Builder = Assembly.Builder.DefineDynamicModule (
149                                 Basename (name), Basename (output), false);
150
151                         if (want_debugging_support)
152                                 InitializeSymbolWriter (output);
153                 }
154
155                 static public void Save (string name)
156                 {
157                         try {
158                                 Assembly.Builder.Save (Basename (name));
159                         }
160                         catch (COMException) {
161                                 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
162                                         throw;
163
164                                 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies 
165                                 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
166                                         RootContext.StrongNameKeyFile +
167                                         "', Use MCS with the Mono runtime or CSC to compile this assembly.");
168                         }
169                         catch (System.IO.IOException io) {
170                                 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
171                         }
172
173                         if (SymbolWriter != null)
174                                 SymbolWriter.WriteSymbolFile ();
175                 }
176         }
177
178         //
179         // Provides "local" store across code that can yield: locals
180         // or fields, notice that this should not be used by anonymous
181         // methods to create local storage, those only require
182         // variable mapping.
183         //
184         public class VariableStorage {
185                 FieldBuilder fb;
186                 LocalBuilder local;
187                 
188                 static int count;
189                 
190                 public VariableStorage (EmitContext ec, Type t)
191                 {
192                         count++;
193                         if (ec.InIterator)
194                                 fb = ec.CurrentIterator.MapVariable ("s_", count.ToString (), t);
195                         else
196                                 local = ec.ig.DeclareLocal (t);
197                 }
198
199                 public void EmitThis (ILGenerator ig)
200                 {
201                         if (fb != null)
202                                 ig.Emit (OpCodes.Ldarg_0);
203                 }
204
205                 public void EmitStore (ILGenerator ig)
206                 {
207                         if (fb == null)
208                                 ig.Emit (OpCodes.Stloc, local);
209                         else
210                                 ig.Emit (OpCodes.Stfld, fb);
211                 }
212
213                 public void EmitLoad (ILGenerator ig)
214                 {
215                         if (fb == null)
216                                 ig.Emit (OpCodes.Ldloc, local);
217                         else 
218                                 ig.Emit (OpCodes.Ldfld, fb);
219                 }
220
221                 public void EmitLoadAddress (ILGenerator ig)
222                 {
223                         if (fb == null)
224                                 ig.Emit (OpCodes.Ldloca, local);
225                         else 
226                                 ig.Emit (OpCodes.Ldflda, fb);
227                 }
228                 
229                 public void EmitCall (ILGenerator ig, MethodInfo mi)
230                 {
231                         // FIXME : we should handle a call like tostring
232                         // here, where boxing is needed. However, we will
233                         // never encounter that with the current usage.
234                         
235                         bool value_type_call;
236                         EmitThis (ig);
237                         if (fb == null) {
238                                 value_type_call = local.LocalType.IsValueType;
239                                 
240                                 if (value_type_call)
241                                         ig.Emit (OpCodes.Ldloca, local);
242                                 else
243                                         ig.Emit (OpCodes.Ldloc, local);
244                         } else {
245                                 value_type_call = fb.FieldType.IsValueType;
246                                 
247                                 if (value_type_call)
248                                         ig.Emit (OpCodes.Ldflda, fb);
249                                 else
250                                         ig.Emit (OpCodes.Ldfld, fb);
251                         }
252                         
253                         ig.Emit (value_type_call ? OpCodes.Call : OpCodes.Callvirt, mi);
254                 }
255         }
256
257         /// <summary>
258         ///   An Emit Context is created for each body of code (from methods,
259         ///   properties bodies, indexer bodies or constructor bodies)
260         /// </summary>
261         public class EmitContext {
262                 public DeclSpace DeclSpace;
263                 public DeclSpace TypeContainer;
264                 public ILGenerator   ig;
265
266                 /// <summary>
267                 ///   This variable tracks the `checked' state of the compilation,
268                 ///   it controls whether we should generate code that does overflow
269                 ///   checking, or if we generate code that ignores overflows.
270                 ///
271                 ///   The default setting comes from the command line option to generate
272                 ///   checked or unchecked code plus any source code changes using the
273                 ///   checked/unchecked statements or expressions.   Contrast this with
274                 ///   the ConstantCheckState flag.
275                 /// </summary>
276                 
277                 public bool CheckState;
278
279                 /// <summary>
280                 ///   The constant check state is always set to `true' and cant be changed
281                 ///   from the command line.  The source code can change this setting with
282                 ///   the `checked' and `unchecked' statements and expressions. 
283                 /// </summary>
284                 public bool ConstantCheckState;
285
286                 /// <summary>
287                 ///   Whether we are emitting code inside a static or instance method
288                 /// </summary>
289                 public bool IsStatic;
290
291                 /// <summary>
292                 ///   Whether we are emitting a field initializer
293                 /// </summary>
294                 public bool IsFieldInitializer;
295
296                 /// <summary>
297                 ///   The value that is allowed to be returned or NULL if there is no
298                 ///   return type.
299                 /// </summary>
300                 public Type ReturnType;
301
302                 /// <summary>
303                 ///   Points to the Type (extracted from the TypeContainer) that
304                 ///   declares this body of code
305                 /// </summary>
306                 public Type ContainerType;
307                 
308                 /// <summary>
309                 ///   Whether this is generating code for a constructor
310                 /// </summary>
311                 public bool IsConstructor;
312
313                 /// <summary>
314                 ///   Whether we're control flow analysis enabled
315                 /// </summary>
316                 public bool DoFlowAnalysis;
317                 
318                 /// <summary>
319                 ///   Keeps track of the Type to LocalBuilder temporary storage created
320                 ///   to store structures (used to compute the address of the structure
321                 ///   value on structure method invocations)
322                 /// </summary>
323                 public Hashtable temporary_storage;
324
325                 public Block CurrentBlock;
326
327                 public int CurrentFile;
328
329                 /// <summary>
330                 ///   The location where we store the return value.
331                 /// </summary>
332                 LocalBuilder return_value;
333
334                 /// <summary>
335                 ///   The location where return has to jump to return the
336                 ///   value
337                 /// </summary>
338                 public Label ReturnLabel;
339
340                 /// <summary>
341                 ///   If we already defined the ReturnLabel
342                 /// </summary>
343                 public bool HasReturnLabel;
344
345                 /// <summary>
346                 ///   Whether we are inside an iterator block.
347                 /// </summary>
348                 public bool InIterator;
349
350                 public bool IsLastStatement;
351
352                 /// <summary>
353                 ///   Whether remapping of locals, parameters and fields is turned on.
354                 ///   Used by iterators and anonymous methods.
355                 /// </summary>
356                 public bool RemapToProxy;
357
358                 /// <summary>
359                 ///  Whether we are inside an unsafe block
360                 /// </summary>
361                 public bool InUnsafe;
362
363                 /// <summary>
364                 ///  Whether we are in a `fixed' initialization
365                 /// </summary>
366                 public bool InFixedInitializer;
367
368                 /// <summary>
369                 ///  Whether we are inside an anonymous method.
370                 /// </summary>
371                 public AnonymousMethod CurrentAnonymousMethod;
372                 
373                 /// <summary>
374                 ///   Location for this EmitContext
375                 /// </summary>
376                 public Location loc;
377
378                 /// <summary>
379                 ///   Used to flag that it is ok to define types recursively, as the
380                 ///   expressions are being evaluated as part of the type lookup
381                 ///   during the type resolution process
382                 /// </summary>
383                 public bool ResolvingTypeTree;
384                 
385                 /// <summary>
386                 ///   Inside an enum definition, we do not resolve enumeration values
387                 ///   to their enumerations, but rather to the underlying type/value
388                 ///   This is so EnumVal + EnumValB can be evaluated.
389                 ///
390                 ///   There is no "E operator + (E x, E y)", so during an enum evaluation
391                 ///   we relax the rules
392                 /// </summary>
393                 public bool InEnumContext;
394
395                 /// <summary>
396                 ///   Anonymous methods can capture local variables and fields,
397                 ///   this object tracks it.  It is copied from the TopLevelBlock
398                 ///   field.
399                 /// </summary>
400                 public CaptureContext capture_context;
401
402                 /// <summary>
403                 /// Trace when method is called and is obsolete then this member suppress message
404                 /// when call is inside next [Obsolete] method or type.
405                 /// </summary>
406                 public bool TestObsoleteMethodUsage = true;
407
408                 /// <summary>
409                 ///    The current iterator
410                 /// </summary>
411                 public Iterator CurrentIterator;
412
413                 /// <summary>
414                 ///    Whether we are in the resolving stage or not
415                 /// </summary>
416                 enum Phase {
417                         Created,
418                         Resolving,
419                         Emitting
420                 }
421                 
422                 Phase current_phase;
423                 
424                 FlowBranching current_flow_branching;
425
426                 public EmitContext (DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
427                                     Type return_type, int code_flags, bool is_constructor)
428                 {
429                         this.ig = ig;
430
431                         TypeContainer = parent;
432                         DeclSpace = ds;
433                         CheckState = RootContext.Checked;
434                         ConstantCheckState = true;
435
436                         IsStatic = (code_flags & Modifiers.STATIC) != 0;
437                         InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
438                         RemapToProxy = InIterator;
439                         ReturnType = return_type;
440                         IsConstructor = is_constructor;
441                         CurrentBlock = null;
442                         CurrentFile = 0;
443                         current_phase = Phase.Created;
444                         
445                         if (parent != null){
446                                 // Can only be null for the ResolveType contexts.
447                                 ContainerType = parent.TypeBuilder;
448                                 if (parent.UnsafeContext)
449                                         InUnsafe = true;
450                                 else
451                                         InUnsafe = (code_flags & Modifiers.UNSAFE) != 0;
452                         }
453                         loc = l;
454
455                         if (ReturnType == TypeManager.void_type)
456                                 ReturnType = null;
457                 }
458
459                 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
460                                     Type return_type, int code_flags, bool is_constructor)
461                         : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
462                 {
463                 }
464
465                 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
466                                     Type return_type, int code_flags)
467                         : this (tc, tc, l, ig, return_type, code_flags, false)
468                 {
469                 }
470
471                 public FlowBranching CurrentBranching {
472                         get {
473                                 return current_flow_branching;
474                         }
475                 }
476
477                 public bool HaveCaptureInfo {
478                         get {
479                                 return capture_context != null;
480                         }
481                 }
482
483                 // <summary>
484                 //   Starts a new code branching.  This inherits the state of all local
485                 //   variables and parameters from the current branching.
486                 // </summary>
487                 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
488                 {
489                         current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
490                         return current_flow_branching;
491                 }
492
493                 // <summary>
494                 //   Starts a new code branching for block `block'.
495                 // </summary>
496                 public FlowBranching StartFlowBranching (Block block)
497                 {
498                         FlowBranching.BranchingType type;
499
500                         if (CurrentBranching.Type == FlowBranching.BranchingType.Switch)
501                                 type = FlowBranching.BranchingType.SwitchSection;
502                         else
503                                 type = FlowBranching.BranchingType.Block;
504
505                         current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, block, block.StartLocation);
506                         return current_flow_branching;
507                 }
508
509                 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
510                 {
511                         FlowBranchingException branching = new FlowBranchingException (
512                                 CurrentBranching, stmt);
513                         current_flow_branching = branching;
514                         return branching;
515                 }
516
517                 // <summary>
518                 //   Ends a code branching.  Merges the state of locals and parameters
519                 //   from all the children of the ending branching.
520                 // </summary>
521                 public FlowBranching.UsageVector DoEndFlowBranching ()
522                 {
523                         FlowBranching old = current_flow_branching;
524                         current_flow_branching = current_flow_branching.Parent;
525
526                         return current_flow_branching.MergeChild (old);
527                 }
528
529                 // <summary>
530                 //   Ends a code branching.  Merges the state of locals and parameters
531                 //   from all the children of the ending branching.
532                 // </summary>
533                 public FlowBranching.Reachability EndFlowBranching ()
534                 {
535                         FlowBranching.UsageVector vector = DoEndFlowBranching ();
536
537                         return vector.Reachability;
538                 }
539
540                 // <summary>
541                 //   Kills the current code branching.  This throws away any changed state
542                 //   information and should only be used in case of an error.
543                 // </summary>
544                 public void KillFlowBranching ()
545                 {
546                         current_flow_branching = current_flow_branching.Parent;
547                 }
548
549                 public void CaptureVariable (LocalInfo li)
550                 {
551                         capture_context.AddLocal (CurrentAnonymousMethod, li);
552                         li.IsCaptured = true;
553                 }
554
555                 public void CaptureParameter (string name, Type t, int idx)
556                 {
557                         
558                         capture_context.AddParameter (this, CurrentAnonymousMethod, name, t, idx);
559                 }
560                 
561                 //
562                 // Use to register a field as captured
563                 //
564                 public void CaptureField (FieldExpr fe)
565                 {
566                         capture_context.AddField (fe);
567                 }
568
569                 //
570                 // Whether anonymous methods have captured variables
571                 //
572                 public bool HaveCapturedVariables ()
573                 {
574                         if (capture_context != null)
575                                 return capture_context.HaveCapturedVariables;
576                         return false;
577                 }
578
579                 //
580                 // Whether anonymous methods have captured fields or this.
581                 //
582                 public bool HaveCapturedFields ()
583                 {
584                         if (capture_context != null)
585                                 return capture_context.HaveCapturedFields;
586                         return false;
587                 }
588
589                 //
590                 // Emits the instance pointer for the host method
591                 //
592                 public void EmitMethodHostInstance (EmitContext target, AnonymousMethod am)
593                 {
594                         if (capture_context != null)
595                                 capture_context.EmitMethodHostInstance (target, am);
596                         else if (IsStatic)
597                                 target.ig.Emit (OpCodes.Ldnull);
598                         else
599                                 target.ig.Emit (OpCodes.Ldarg_0);
600                 }
601
602                 //
603                 // Returns whether the `local' variable has been captured by an anonymous
604                 // method
605                 //
606                 public bool IsCaptured (LocalInfo local)
607                 {
608                         return capture_context.IsCaptured (local);
609                 }
610
611                 public bool IsParameterCaptured (string name)
612                 {
613                         if (capture_context != null)
614                                 return capture_context.IsParameterCaptured (name);
615                         return false;
616                 }
617                 
618                 public void EmitMeta (ToplevelBlock b, InternalParameters ip)
619                 {
620                         if (capture_context != null)
621                                 capture_context.EmitHelperClasses (this);
622                         b.EmitMeta (this);
623
624                         if (HasReturnLabel)
625                                 ReturnLabel = ig.DefineLabel ();
626                 }
627
628                 //
629                 // Here until we can fix the problem with Mono.CSharp.Switch, which
630                 // currently can not cope with ig == null during resolve (which must
631                 // be fixed for switch statements to work on anonymous methods).
632                 //
633                 public void EmitTopBlock (ToplevelBlock block, InternalParameters ip, Location loc)
634                 {
635                         if (block == null)
636                                 return;
637                         
638                         bool unreachable;
639                         
640                         if (ResolveTopBlock (null, block, ip, loc, out unreachable)){
641                                 EmitMeta (block, ip);
642
643                                 current_phase = Phase.Emitting;
644                                 EmitResolvedTopBlock (block, unreachable);
645                         }
646                 }
647
648                 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
649                                              InternalParameters ip, Location loc, out bool unreachable)
650                 {
651                         current_phase = Phase.Resolving;
652                         
653                         unreachable = false;
654
655                         capture_context = block.CaptureContext;
656                         
657                         if (!Location.IsNull (loc))
658                                 CurrentFile = loc.File;
659
660 #if PRODUCTION
661                         try {
662 #endif
663                                 int errors = Report.Errors;
664
665                                 block.ResolveMeta (block, this, ip);
666
667                                 
668                                 if (Report.Errors == errors){
669                                         bool old_do_flow_analysis = DoFlowAnalysis;
670                                         DoFlowAnalysis = true;
671
672                                         if (anonymous_method_host != null)
673                                                 current_flow_branching = FlowBranching.CreateBranching (
674                                                 anonymous_method_host.CurrentBranching, FlowBranching.BranchingType.Block,
675                                                 block, loc);
676                                         else 
677                                                 current_flow_branching = FlowBranching.CreateBranching (
678                                                         null, FlowBranching.BranchingType.Block, block, loc);
679
680                                         if (!block.Resolve (this)) {
681                                                 current_flow_branching = null;
682                                                 DoFlowAnalysis = old_do_flow_analysis;
683                                                 return false;
684                                         }
685
686                                         FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
687                                         current_flow_branching = null;
688                                         
689                                         DoFlowAnalysis = old_do_flow_analysis;
690
691                                         if (reachability.AlwaysReturns ||
692                                             reachability.AlwaysThrows ||
693                                             reachability.IsUnreachable)
694                                                 unreachable = true;
695                                 }
696 #if PRODUCTION
697                         } catch (Exception e) {
698                                         Console.WriteLine ("Exception caught by the compiler while compiling:");
699                                         Console.WriteLine ("   Block that caused the problem begin at: " + loc);
700                                         
701                                         if (CurrentBlock != null){
702                                                 Console.WriteLine ("                     Block being compiled: [{0},{1}]",
703                                                                    CurrentBlock.StartLocation, CurrentBlock.EndLocation);
704                                         }
705                                         Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
706                                         throw;
707                         }
708 #endif
709
710                         if (ReturnType != null && !unreachable){
711                                 if (!InIterator){
712                                         if (CurrentAnonymousMethod != null){
713                                                 Report.Error (1643, loc, "Not all code paths return a value in anonymous method of type `{0}'",
714                                                               CurrentAnonymousMethod.Type);
715                                         } else {
716                                                 Report.Error (161, loc, "Not all code paths return a value");
717                                         }
718                                         
719                                         return false;
720                                 }
721                         }
722                         block.CompleteContexts ();
723                         
724                         return true;
725                 }
726
727                 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
728                 {
729                         if (block != null)
730                                 block.Emit (this);
731                         
732                         if (HasReturnLabel)
733                                 ig.MarkLabel (ReturnLabel);
734                         
735                         if (return_value != null){
736                                 ig.Emit (OpCodes.Ldloc, return_value);
737                                 ig.Emit (OpCodes.Ret);
738                         } else {
739                                 //
740                                 // If `HasReturnLabel' is set, then we already emitted a
741                                 // jump to the end of the method, so we must emit a `ret'
742                                 // there.
743                                 //
744                                 // Unfortunately, System.Reflection.Emit automatically emits
745                                 // a leave to the end of a finally block.  This is a problem
746                                 // if no code is following the try/finally block since we may
747                                 // jump to a point after the end of the method.
748                                 // As a workaround, we're always creating a return label in
749                                 // this case.
750                                 //
751
752                                 if ((block != null) && block.IsDestructor) {
753                                         // Nothing to do; S.R.E automatically emits a leave.
754                                 } else if (HasReturnLabel || (!unreachable && !InIterator)) {
755                                         if (ReturnType != null)
756                                                 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
757                                         ig.Emit (OpCodes.Ret);
758                                 }
759                         }
760
761                         //
762                         // Close pending helper classes if we are the toplevel
763                         //
764                         if (capture_context != null && capture_context.ParentToplevel == null)
765                                 capture_context.CloseHelperClasses ();
766                 }
767
768                 /// <summary>
769                 ///   This is called immediately before emitting an IL opcode to tell the symbol
770                 ///   writer to which source line this opcode belongs.
771                 /// </summary>
772                 public void Mark (Location loc, bool check_file)
773                 {
774                         if ((CodeGen.SymbolWriter == null) || Location.IsNull (loc))
775                                 return;
776
777                         if (check_file && (CurrentFile != loc.File))
778                                 return;
779
780                         CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, 0);
781                 }
782
783                 public void DefineLocalVariable (string name, LocalBuilder builder)
784                 {
785                         if (CodeGen.SymbolWriter == null)
786                                 return;
787
788                         CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
789                 }
790
791                 /// <summary>
792                 ///   Returns a temporary storage for a variable of type t as 
793                 ///   a local variable in the current body.
794                 /// </summary>
795                 public LocalBuilder GetTemporaryLocal (Type t)
796                 {
797                         LocalBuilder location = null;
798                         
799                         if (temporary_storage != null){
800                                 object o = temporary_storage [t];
801                                 if (o != null){
802                                         if (o is ArrayList){
803                                                 ArrayList al = (ArrayList) o;
804                                                 
805                                                 for (int i = 0; i < al.Count; i++){
806                                                         if (al [i] != null){
807                                                                 location = (LocalBuilder) al [i];
808                                                                 al [i] = null;
809                                                                 break;
810                                                         }
811                                                 }
812                                         } else
813                                                 location = (LocalBuilder) o;
814                                         if (location != null)
815                                                 return location;
816                                 }
817                         }
818                         
819                         return ig.DeclareLocal (t);
820                 }
821
822                 public void FreeTemporaryLocal (LocalBuilder b, Type t)
823                 {
824                         if (temporary_storage == null){
825                                 temporary_storage = new Hashtable ();
826                                 temporary_storage [t] = b;
827                                 return;
828                         }
829                         object o = temporary_storage [t];
830                         if (o == null){
831                                 temporary_storage [t] = b;
832                                 return;
833                         }
834                         if (o is ArrayList){
835                                 ArrayList al = (ArrayList) o;
836                                 for (int i = 0; i < al.Count; i++){
837                                         if (al [i] == null){
838                                                 al [i] = b;
839                                                 return;
840                                         }
841                                 }
842                                 al.Add (b);
843                                 return;
844                         }
845                         ArrayList replacement = new ArrayList ();
846                         replacement.Add (o);
847                         temporary_storage.Remove (t);
848                         temporary_storage [t] = replacement;
849                 }
850
851                 /// <summary>
852                 ///   Current loop begin and end labels.
853                 /// </summary>
854                 public Label LoopBegin, LoopEnd;
855
856                 /// <summary>
857                 ///   Default target in a switch statement.   Only valid if
858                 ///   InSwitch is true
859                 /// </summary>
860                 public Label DefaultTarget;
861
862                 /// <summary>
863                 ///   If this is non-null, points to the current switch statement
864                 /// </summary>
865                 public Switch Switch;
866
867                 /// <summary>
868                 ///   ReturnValue creates on demand the LocalBuilder for the
869                 ///   return value from the function.  By default this is not
870                 ///   used.  This is only required when returns are found inside
871                 ///   Try or Catch statements.
872                 ///
873                 ///   This method is typically invoked from the Emit phase, so
874                 ///   we allow the creation of a return label if it was not
875                 ///   requested during the resolution phase.   Could be cleaned
876                 ///   up, but it would replicate a lot of logic in the Emit phase
877                 ///   of the code that uses it.
878                 /// </summary>
879                 public LocalBuilder TemporaryReturn ()
880                 {
881                         if (return_value == null){
882                                 return_value = ig.DeclareLocal (ReturnType);
883                                 if (!HasReturnLabel){
884                                         ReturnLabel = ig.DefineLabel ();
885                                         HasReturnLabel = true;
886                                 }
887                         }
888
889                         return return_value;
890                 }
891
892                 /// <summary>
893                 ///   This method is used during the Resolution phase to flag the
894                 ///   need to define the ReturnLabel
895                 /// </summary>
896                 public void NeedReturnLabel ()
897                 {
898                         if (current_phase != Phase.Resolving){
899                                 //
900                                 // The reason is that the `ReturnLabel' is declared between
901                                 // resolution and emission
902                                 // 
903                                 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
904                         }
905                         
906                         if (!InIterator && !HasReturnLabel) 
907                                 HasReturnLabel = true;
908                 }
909
910                 //
911                 // Creates a field `name' with the type `t' on the proxy class
912                 //
913                 public FieldBuilder MapVariable (string name, Type t)
914                 {
915                         if (InIterator)
916                                 return CurrentIterator.MapVariable ("v_", name, t);
917
918                         throw new Exception ("MapVariable for an unknown state");
919                 }
920
921                 public Expression RemapParameter (int idx)
922                 {
923                         FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
924                         fe.InstanceExpression = new ProxyInstance ();
925                         return fe.DoResolve (this);
926                 }
927
928                 public Expression RemapParameterLValue (int idx, Expression right_side)
929                 {
930                         FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
931                         fe.InstanceExpression = new ProxyInstance ();
932                         return fe.DoResolveLValue (this, right_side);
933                 }
934                 
935                 //
936                 // Emits the proper object to address fields on a remapped
937                 // variable/parameter to field in anonymous-method/iterator proxy classes.
938                 //
939                 public void EmitThis ()
940                 {
941                         ig.Emit (OpCodes.Ldarg_0);
942                         if (InIterator){
943                                 if (!IsStatic){
944                                         FieldBuilder this_field = CurrentIterator.this_field.FieldBuilder;
945                                         if (TypeManager.IsValueType (this_field.FieldType))
946                                                 ig.Emit (OpCodes.Ldflda, this_field);
947                                         else
948                                                 ig.Emit (OpCodes.Ldfld, this_field);
949                                 } 
950                         } else if (capture_context != null && CurrentAnonymousMethod != null){
951                                 ScopeInfo si = CurrentAnonymousMethod.Scope;
952                                 while (si != null){
953                                         if (si.ParentLink != null)
954                                                 ig.Emit (OpCodes.Ldfld, si.ParentLink);
955                                         if (si.THIS != null){
956                                                 ig.Emit (OpCodes.Ldfld, si.THIS);
957                                                 break;
958                                         }
959                                         si = si.ParentScope;
960                                 }
961                         } 
962                 }
963
964                 //
965                 // Emits the code necessary to load the instance required
966                 // to access the captured LocalInfo
967                 //
968                 public void EmitCapturedVariableInstance (LocalInfo li)
969                 {
970                         if (RemapToProxy){
971                                 ig.Emit (OpCodes.Ldarg_0);
972                                 return;
973                         }
974                         
975                         if (capture_context == null)
976                                 throw new Exception ("Calling EmitCapturedContext when there is no capture_context");
977                         
978                         capture_context.EmitCapturedVariableInstance (this, li, CurrentAnonymousMethod);
979                 }
980
981                 public void EmitParameter (string name)
982                 {
983                         capture_context.EmitParameter (this, name);
984                 }
985
986                 public void EmitAssignParameter (string name, Expression source, bool leave_copy, bool prepare_for_load)
987                 {
988                         capture_context.EmitAssignParameter (this, name, source, leave_copy, prepare_for_load);
989                 }
990
991                 public void EmitAddressOfParameter (string name)
992                 {
993                         capture_context.EmitAddressOfParameter (this, name);
994                 }
995                 
996                 public Expression GetThis (Location loc)
997                 {
998                         This my_this;
999                         if (CurrentBlock != null)
1000                                 my_this = new This (CurrentBlock, loc);
1001                         else
1002                                 my_this = new This (loc);
1003
1004                         if (!my_this.ResolveBase (this))
1005                                 my_this = null;
1006
1007                         return my_this;
1008                 }
1009         }
1010
1011
1012         public abstract class CommonAssemblyModulClass: Attributable {
1013                 protected CommonAssemblyModulClass ():
1014                         base (null)
1015                 {
1016                 }
1017
1018                 public void AddAttributes (ArrayList attrs)
1019                 {
1020                         if (OptAttributes == null) {
1021                                 OptAttributes = new Attributes (attrs);
1022                                 return;
1023                         }
1024                         OptAttributes.AddAttributes (attrs);
1025                         OptAttributes.CheckTargets (this);
1026                 }
1027
1028                 public virtual void Emit (TypeContainer tc) 
1029                 {
1030                         if (OptAttributes == null)
1031                                 return;
1032
1033                         EmitContext ec = new EmitContext (tc, Mono.CSharp.Location.Null, null, null, 0, false);
1034                         OptAttributes.Emit (ec, this);
1035                 }
1036                 
1037                 protected Attribute GetClsCompliantAttribute ()
1038                 {
1039                         if (OptAttributes == null)
1040                                 return null;
1041
1042                         EmitContext temp_ec = new EmitContext (new RootTypes (), Mono.CSharp.Location.Null, null, null, 0, false);
1043                         Attribute a = OptAttributes.Search (TypeManager.cls_compliant_attribute_type, temp_ec);
1044                         if (a != null) {
1045                                 a.Resolve (temp_ec);
1046                         }
1047                         return a;
1048                 }
1049         }
1050                 
1051         public class AssemblyClass: CommonAssemblyModulClass {
1052                 // TODO: make it private and move all builder based methods here
1053                 public AssemblyBuilder Builder;
1054                 bool is_cls_compliant;
1055
1056                 static string[] attribute_targets = new string [] { "assembly" };
1057
1058                 public AssemblyClass (): base ()
1059                 {
1060                         is_cls_compliant = false;
1061                 }
1062
1063                 public bool IsClsCompliant {
1064                         get {
1065                                 return is_cls_compliant;
1066                         }
1067                 }
1068
1069                 public override AttributeTargets AttributeTargets {
1070                         get {
1071                                 return AttributeTargets.Assembly;
1072                         }
1073                 }
1074
1075                 public override bool IsClsCompliaceRequired(DeclSpace ds)
1076                 {
1077                         return is_cls_compliant;
1078                 }
1079
1080                 public void ResolveClsCompliance ()
1081                 {
1082                         Attribute a = GetClsCompliantAttribute ();
1083                         if (a == null)
1084                                 return;
1085
1086                         is_cls_compliant = a.GetClsCompliantAttributeValue (null);
1087                 }
1088
1089                 // fix bug #56621
1090                 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob) 
1091                 {
1092                         try {
1093                                 // check for possible ECMA key
1094                                 if (strongNameBlob.Length == 16) {
1095                                         // will be rejected if not "the" ECMA key
1096                                         an.SetPublicKey (strongNameBlob);
1097                                 }
1098                                 else {
1099                                         // take it, with or without, a private key
1100                                         RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1101                                         // and make sure we only feed the public part to Sys.Ref
1102                                         byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1103                                         
1104                                         // AssemblyName.SetPublicKey requires an additional header
1105                                         byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1106
1107                                         byte[] encodedPublicKey = new byte [12 + publickey.Length];
1108                                         Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1109                                         Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1110                                         an.SetPublicKey (encodedPublicKey);
1111                                 }
1112                         }
1113                         catch (Exception) {
1114                                 Report.Error (1548, "Could not strongname the assembly. File `" +
1115                                         RootContext.StrongNameKeyFile + "' incorrectly encoded.");
1116                                 Environment.Exit (1);
1117                         }
1118                 }
1119
1120                 public AssemblyName GetAssemblyName (string name, string output) 
1121                 {
1122                         if (OptAttributes != null) {
1123                                 foreach (Attribute a in OptAttributes.Attrs) {
1124                                         if (a.Target != AttributeTargets.Assembly)
1125                                                 continue;
1126                                         // TODO: This code is buggy: comparing Attribute name without resolving it is wrong.
1127                                         //       However, this is invoked by CodeGen.Init, at which time none of the namespaces
1128                                         //       are loaded yet.
1129                                         switch (a.Name) {
1130                                                 case "AssemblyKeyFile":
1131                                                 case "AssemblyKeyFileAttribute":
1132                                                 case "System.Reflection.AssemblyKeyFileAttribute":
1133                                                         if (RootContext.StrongNameKeyFile != null) {
1134                                                                 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1135                                                                 Report.Warning (1616, "Compiler option '{0}' overrides '{1}' given in source", "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1136                                                         }
1137                                                         else {
1138                                                                 string value = a.GetString ();
1139                                                                 if (value != String.Empty)
1140                                                                         RootContext.StrongNameKeyFile = value;
1141                                                         }
1142                                                         break;
1143                                                 case "AssemblyKeyName":
1144                                                 case "AssemblyKeyNameAttribute":
1145                                                 case "System.Reflection.AssemblyKeyNameAttribute":
1146                                                         if (RootContext.StrongNameKeyContainer != null) {
1147                                                                 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1148                                                                 Report.Warning (1616, "keycontainer", "Compiler option '{0}' overrides '{1}' given in source", "System.Reflection.AssemblyKeyNameAttribute");
1149                                                         }
1150                                                         else {
1151                                                                 string value = a.GetString ();
1152                                                                 if (value != String.Empty)
1153                                                                         RootContext.StrongNameKeyContainer = value;
1154                                                         }
1155                                                         break;
1156                                                 case "AssemblyDelaySign":
1157                                                 case "AssemblyDelaySignAttribute":
1158                                                 case "System.Reflection.AssemblyDelaySignAttribute":
1159                                                         RootContext.StrongNameDelaySign = a.GetBoolean ();
1160                                                         break;
1161                                         }
1162                                 }
1163                         }
1164
1165                         AssemblyName an = new AssemblyName ();
1166                         an.Name = Path.GetFileNameWithoutExtension (name);
1167
1168                         // note: delay doesn't apply when using a key container
1169                         if (RootContext.StrongNameKeyContainer != null) {
1170                                 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1171                                 return an;
1172                         }
1173
1174                         // strongname is optional
1175                         if (RootContext.StrongNameKeyFile == null)
1176                                 return an;
1177
1178                         string AssemblyDir = Path.GetDirectoryName (output);
1179
1180                         // the StrongName key file may be relative to (a) the compiled
1181                         // file or (b) to the output assembly. See bugzilla #55320
1182                         // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1183
1184                         // (a) relative to the compiled file
1185                         string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1186                         bool exist = File.Exists (filename);
1187                         if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1188                                 // (b) relative to the outputed assembly
1189                                 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1190                                 exist = File.Exists (filename);
1191                         }
1192
1193                         if (exist) {
1194                                 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1195                                         byte[] snkeypair = new byte [fs.Length];
1196                                         fs.Read (snkeypair, 0, snkeypair.Length);
1197
1198                                         if (RootContext.StrongNameDelaySign) {
1199                                                 // delayed signing - DO NOT include private key
1200                                                 SetPublicKey (an, snkeypair);
1201                                         }
1202                                         else {
1203                                                 // no delay so we make sure we have the private key
1204                                                 try {
1205                                                         CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1206                                                         an.KeyPair = new StrongNameKeyPair (snkeypair);
1207                                                 }
1208                                                 catch (CryptographicException) {
1209                                                         if (snkeypair.Length == 16) {
1210                                                                 // error # is different for ECMA key
1211                                                                 Report.Error (1606, "Could not strongname the assembly. " + 
1212                                                                         "ECMA key can only be used to delay-sign assemblies");
1213                                                         }
1214                                                         else {
1215                                                                 Report.Error (1548, "Could not strongname the assembly. File `" +
1216                                                                         RootContext.StrongNameKeyFile +
1217                                                                         "' doesn't have a private key.");
1218                                                         }
1219                                                         Environment.Exit (1);
1220                                                 }
1221                                         }
1222                                 }
1223                         }
1224                         else {
1225                                 Report.Error (1548, "Could not strongname the assembly. File `" +
1226                                         RootContext.StrongNameKeyFile + "' not found.");
1227                                 Environment.Exit (1);
1228                         }
1229                         return an;
1230                 }
1231
1232                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1233                 {
1234                         Builder.SetCustomAttribute (customBuilder);
1235                 }
1236
1237                 public override string[] ValidAttributeTargets {
1238                         get {
1239                                 return attribute_targets;
1240                         }
1241                 }
1242         }
1243
1244         public class ModuleClass: CommonAssemblyModulClass {
1245                 // TODO: make it private and move all builder based methods here
1246                 public ModuleBuilder Builder;
1247                 bool m_module_is_unsafe;
1248
1249                 static string[] attribute_targets = new string [] { "module" };
1250
1251                 public ModuleClass (bool is_unsafe)
1252                 {
1253                         m_module_is_unsafe = is_unsafe;
1254                 }
1255
1256                 public override AttributeTargets AttributeTargets {
1257                         get {
1258                                 return AttributeTargets.Module;
1259                         }
1260                 }
1261
1262                 public override bool IsClsCompliaceRequired(DeclSpace ds)
1263                 {
1264                         return CodeGen.Assembly.IsClsCompliant;
1265                 }
1266
1267                 public override void Emit (TypeContainer tc) 
1268                 {
1269                         base.Emit (tc);
1270
1271                         if (!m_module_is_unsafe)
1272                                 return;
1273
1274                         if (TypeManager.unverifiable_code_ctor == null) {
1275                                 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
1276                                 return;
1277                         }
1278                                 
1279                         ApplyAttributeBuilder (null, new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
1280                 }
1281                 
1282                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1283                 {
1284                         if (a != null && a.Type == TypeManager.cls_compliant_attribute_type) {
1285                                 Report.Warning (3012, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1286                                 return;
1287                         }
1288
1289                         Builder.SetCustomAttribute (customBuilder);
1290                 }
1291
1292                 public override string[] ValidAttributeTargets {
1293                         get {
1294                                 return attribute_targets;
1295                         }
1296                 }
1297         }
1298 }