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