**** Merged r40625 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                 ///   Used to flag that it is ok to define types recursively, as the
393                 ///   expressions are being evaluated as part of the type lookup
394                 ///   during the type resolution process
395                 /// </summary>
396                 public bool ResolvingTypeTree;
397                 
398                 /// <summary>
399                 ///   Inside an enum definition, we do not resolve enumeration values
400                 ///   to their enumerations, but rather to the underlying type/value
401                 ///   This is so EnumVal + EnumValB can be evaluated.
402                 ///
403                 ///   There is no "E operator + (E x, E y)", so during an enum evaluation
404                 ///   we relax the rules
405                 /// </summary>
406                 public bool InEnumContext;
407
408                 /// <summary>
409                 ///   Anonymous methods can capture local variables and fields,
410                 ///   this object tracks it.  It is copied from the TopLevelBlock
411                 ///   field.
412                 /// </summary>
413                 public CaptureContext capture_context;
414
415                 /// <summary>
416                 /// Trace when method is called and is obsolete then this member suppress message
417                 /// when call is inside next [Obsolete] method or type.
418                 /// </summary>
419                 public bool TestObsoleteMethodUsage = true;
420
421                 /// <summary>
422                 ///    The current iterator
423                 /// </summary>
424                 public Iterator CurrentIterator;
425
426                 /// <summary>
427                 ///    Whether we are in the resolving stage or not
428                 /// </summary>
429                 enum Phase {
430                         Created,
431                         Resolving,
432                         Emitting
433                 }
434                 
435                 Phase current_phase;
436                 FlowBranching current_flow_branching;
437                 
438                 public EmitContext (DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
439                                     Type return_type, int code_flags, bool is_constructor)
440                 {
441                         this.ig = ig;
442
443                         TypeContainer = parent;
444                         DeclSpace = ds;
445                         CheckState = RootContext.Checked;
446                         ConstantCheckState = true;
447
448                         if ((return_type is TypeBuilder) && return_type.IsGenericTypeDefinition)
449                                 throw new Exception ("FUCK");
450                         
451                         IsStatic = (code_flags & Modifiers.STATIC) != 0;
452                         MethodIsStatic = IsStatic;
453                         InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
454                         RemapToProxy = InIterator;
455                         ReturnType = return_type;
456                         IsConstructor = is_constructor;
457                         CurrentBlock = null;
458                         CurrentFile = 0;
459                         current_phase = Phase.Created;
460                         
461                         if (parent != null){
462                                 // Can only be null for the ResolveType contexts.
463                                 ContainerType = parent.TypeBuilder;
464                                 if (parent.UnsafeContext)
465                                         InUnsafe = true;
466                                 else
467                                         InUnsafe = (code_flags & Modifiers.UNSAFE) != 0;
468                         }
469                         loc = l;
470
471                         if (ReturnType == TypeManager.void_type)
472                                 ReturnType = null;
473                 }
474
475                 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
476                                     Type return_type, int code_flags, bool is_constructor)
477                         : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
478                 {
479                 }
480
481                 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
482                                     Type return_type, int code_flags)
483                         : this (tc, tc, l, ig, return_type, code_flags, false)
484                 {
485                 }
486
487                 public FlowBranching CurrentBranching {
488                         get {
489                                 return current_flow_branching;
490                         }
491                 }
492
493                 public bool HaveCaptureInfo {
494                         get {
495                                 return capture_context != null;
496                         }
497                 }
498
499                 // <summary>
500                 //   Starts a new code branching.  This inherits the state of all local
501                 //   variables and parameters from the current branching.
502                 // </summary>
503                 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
504                 {
505                         current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
506                         return current_flow_branching;
507                 }
508
509                 // <summary>
510                 //   Starts a new code branching for block `block'.
511                 // </summary>
512                 public FlowBranching StartFlowBranching (Block block)
513                 {
514                         FlowBranching.BranchingType type;
515
516                         if (CurrentBranching.Type == FlowBranching.BranchingType.Switch)
517                                 type = FlowBranching.BranchingType.SwitchSection;
518                         else
519                                 type = FlowBranching.BranchingType.Block;
520
521                         current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, block, block.StartLocation);
522                         return current_flow_branching;
523                 }
524
525                 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
526                 {
527                         FlowBranchingException branching = new FlowBranchingException (
528                                 CurrentBranching, stmt);
529                         current_flow_branching = branching;
530                         return branching;
531                 }
532
533                 // <summary>
534                 //   Ends a code branching.  Merges the state of locals and parameters
535                 //   from all the children of the ending branching.
536                 // </summary>
537                 public FlowBranching.UsageVector DoEndFlowBranching ()
538                 {
539                         FlowBranching old = current_flow_branching;
540                         current_flow_branching = current_flow_branching.Parent;
541
542                         return current_flow_branching.MergeChild (old);
543                 }
544
545                 // <summary>
546                 //   Ends a code branching.  Merges the state of locals and parameters
547                 //   from all the children of the ending branching.
548                 // </summary>
549                 public FlowBranching.Reachability EndFlowBranching ()
550                 {
551                         FlowBranching.UsageVector vector = DoEndFlowBranching ();
552
553                         return vector.Reachability;
554                 }
555
556                 // <summary>
557                 //   Kills the current code branching.  This throws away any changed state
558                 //   information and should only be used in case of an error.
559                 // </summary>
560                 public void KillFlowBranching ()
561                 {
562                         current_flow_branching = current_flow_branching.Parent;
563                 }
564
565                 public void CaptureVariable (LocalInfo li)
566                 {
567                         capture_context.AddLocal (CurrentAnonymousMethod, li);
568                         li.IsCaptured = true;
569                 }
570
571                 public void CaptureParameter (string name, Type t, int idx)
572                 {
573                         capture_context.AddParameter (this, CurrentAnonymousMethod, name, t, idx);
574                 }
575
576                 public void CaptureThis ()
577                 {
578                         capture_context.CaptureThis ();
579                 }
580                 
581                 
582                 //
583                 // Use to register a field as captured
584                 //
585                 public void CaptureField (FieldExpr fe)
586                 {
587                         capture_context.AddField (fe);
588                 }
589
590                 //
591                 // Whether anonymous methods have captured variables
592                 //
593                 public bool HaveCapturedVariables ()
594                 {
595                         if (capture_context != null)
596                                 return capture_context.HaveCapturedVariables;
597                         return false;
598                 }
599
600                 //
601                 // Whether anonymous methods have captured fields or this.
602                 //
603                 public bool HaveCapturedFields ()
604                 {
605                         if (capture_context != null)
606                                 return capture_context.HaveCapturedFields;
607                         return false;
608                 }
609
610                 //
611                 // Emits the instance pointer for the host method
612                 //
613                 public void EmitMethodHostInstance (EmitContext target, AnonymousMethod am)
614                 {
615                         if (capture_context != null)
616                                 capture_context.EmitMethodHostInstance (target, am);
617                         else if (IsStatic)
618                                 target.ig.Emit (OpCodes.Ldnull);
619                         else
620                                 target.ig.Emit (OpCodes.Ldarg_0);
621                 }
622
623                 //
624                 // Returns whether the `local' variable has been captured by an anonymous
625                 // method
626                 //
627                 public bool IsCaptured (LocalInfo local)
628                 {
629                         return capture_context.IsCaptured (local);
630                 }
631
632                 public bool IsParameterCaptured (string name)
633                 {
634                         if (capture_context != null)
635                                 return capture_context.IsParameterCaptured (name);
636                         return false;
637                 }
638                 
639                 public void EmitMeta (ToplevelBlock b, InternalParameters ip)
640                 {
641                         if (capture_context != null)
642                                 capture_context.EmitAnonymousHelperClasses (this);
643                         b.EmitMeta (this);
644
645                         if (HasReturnLabel)
646                                 ReturnLabel = ig.DefineLabel ();
647                 }
648
649                 //
650                 // Here until we can fix the problem with Mono.CSharp.Switch, which
651                 // currently can not cope with ig == null during resolve (which must
652                 // be fixed for switch statements to work on anonymous methods).
653                 //
654                 public void EmitTopBlock (ToplevelBlock block, InternalParameters ip, Location loc)
655                 {
656                         if (block == null)
657                                 return;
658                         
659                         bool unreachable;
660                         
661                         if (ResolveTopBlock (null, block, ip, loc, out unreachable)){
662                                 EmitMeta (block, ip);
663
664                                 current_phase = Phase.Emitting;
665                                 EmitResolvedTopBlock (block, unreachable);
666                         }
667                 }
668
669                 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
670                                              InternalParameters ip, Location loc, out bool unreachable)
671                 {
672                         current_phase = Phase.Resolving;
673                         
674                         unreachable = false;
675
676                         capture_context = block.CaptureContext;
677
678                         if (!Location.IsNull (loc))
679                                 CurrentFile = loc.File;
680
681 #if PRODUCTION
682                             try {
683 #endif
684                                 int errors = Report.Errors;
685
686                                 block.ResolveMeta (block, this, ip);
687
688
689                                 if (Report.Errors == errors){
690                                         bool old_do_flow_analysis = DoFlowAnalysis;
691                                         DoFlowAnalysis = true;
692
693                                         if (anonymous_method_host != null)
694                                                 current_flow_branching = FlowBranching.CreateBranching (
695                                                 anonymous_method_host.CurrentBranching, FlowBranching.BranchingType.Block,
696                                                 block, loc);
697                                         else 
698                                         current_flow_branching = FlowBranching.CreateBranching (
699                                                 null, FlowBranching.BranchingType.Block, block, loc);
700
701                                         if (!block.Resolve (this)) {
702                                                 current_flow_branching = null;
703                                                 DoFlowAnalysis = old_do_flow_analysis;
704                                                 return false;
705                                         }
706
707                                         FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
708                                         current_flow_branching = null;
709
710                                         DoFlowAnalysis = old_do_flow_analysis;
711
712                                         if (reachability.AlwaysReturns ||
713                                             reachability.AlwaysThrows ||
714                                             reachability.IsUnreachable)
715                                                 unreachable = true;
716                                         }
717 #if PRODUCTION
718                             } catch (Exception e) {
719                                         Console.WriteLine ("Exception caught by the compiler while compiling:");
720                                         Console.WriteLine ("   Block that caused the problem begin at: " + loc);
721                                         
722                                         if (CurrentBlock != null){
723                                                 Console.WriteLine ("                     Block being compiled: [{0},{1}]",
724                                                                    CurrentBlock.StartLocation, CurrentBlock.EndLocation);
725                                         }
726                                         Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
727                                 throw;
728                         }
729 #endif
730
731                         if (ReturnType != null && !unreachable){
732                                 if (!InIterator){
733                                         if (CurrentAnonymousMethod != null){
734                                                 Report.Error (1643, loc, "Not all code paths return a value in anonymous method of type `{0}'",
735                                                               CurrentAnonymousMethod.Type);
736                                         } else {
737                                         Report.Error (161, loc, "Not all code paths return a value");
738                                         }
739
740                                         return false;
741                                 }
742                         }
743                         block.CompleteContexts ();
744
745                         return true;
746                 }
747
748                 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
749                 {
750                         if (block != null)
751                                 block.Emit (this);
752
753                         if (HasReturnLabel)
754                                 ig.MarkLabel (ReturnLabel);
755
756                         if (return_value != null){
757                                 ig.Emit (OpCodes.Ldloc, return_value);
758                                 ig.Emit (OpCodes.Ret);
759                         } else {
760                                 //
761                                 // If `HasReturnLabel' is set, then we already emitted a
762                                 // jump to the end of the method, so we must emit a `ret'
763                                 // there.
764                                 //
765                                 // Unfortunately, System.Reflection.Emit automatically emits
766                                 // a leave to the end of a finally block.  This is a problem
767                                 // if no code is following the try/finally block since we may
768                                 // jump to a point after the end of the method.
769                                 // As a workaround, we're always creating a return label in
770                                 // this case.
771                                 //
772
773                                 if ((block != null) && block.IsDestructor) {
774                                         // Nothing to do; S.R.E automatically emits a leave.
775                                 } else if (HasReturnLabel || (!unreachable && !InIterator)) {
776                                         if (ReturnType != null)
777                                                 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
778                                         ig.Emit (OpCodes.Ret);
779                                 }
780                         }
781
782                         //
783                         // Close pending helper classes if we are the toplevel
784                         //
785                         if (capture_context != null && capture_context.ParentToplevel == null)
786                                 capture_context.CloseAnonymousHelperClasses ();
787                 }
788
789                 /// <summary>
790                 ///   This is called immediately before emitting an IL opcode to tell the symbol
791                 ///   writer to which source line this opcode belongs.
792                 /// </summary>
793                 public void Mark (Location loc, bool check_file)
794                 {
795                         if ((CodeGen.SymbolWriter == null) || Location.IsNull (loc))
796                                 return;
797
798                         if (check_file && (CurrentFile != loc.File))
799                                 return;
800
801                         CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, 0);
802                 }
803
804                 public void DefineLocalVariable (string name, LocalBuilder builder)
805                 {
806                         if (CodeGen.SymbolWriter == null)
807                                 return;
808
809                         CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
810                 }
811
812                 /// <summary>
813                 ///   Returns a temporary storage for a variable of type t as 
814                 ///   a local variable in the current body.
815                 /// </summary>
816                 public LocalBuilder GetTemporaryLocal (Type t)
817                 {
818                         LocalBuilder location = null;
819                         
820                         if (temporary_storage != null){
821                                 object o = temporary_storage [t];
822                                 if (o != null){
823                                         if (o is ArrayList){
824                                                 ArrayList al = (ArrayList) o;
825                                                 
826                                                 for (int i = 0; i < al.Count; i++){
827                                                         if (al [i] != null){
828                                                                 location = (LocalBuilder) al [i];
829                                                                 al [i] = null;
830                                                                 break;
831                                                         }
832                                                 }
833                                         } else
834                                                 location = (LocalBuilder) o;
835                                         if (location != null)
836                                                 return location;
837                                 }
838                         }
839                         
840                         return ig.DeclareLocal (t);
841                 }
842
843                 public void FreeTemporaryLocal (LocalBuilder b, Type t)
844                 {
845                         if (temporary_storage == null){
846                                 temporary_storage = new Hashtable ();
847                                 temporary_storage [t] = b;
848                                 return;
849                         }
850                         object o = temporary_storage [t];
851                         if (o == null){
852                                 temporary_storage [t] = b;
853                                 return;
854                         }
855                         if (o is ArrayList){
856                                 ArrayList al = (ArrayList) o;
857                                 for (int i = 0; i < al.Count; i++){
858                                         if (al [i] == null){
859                                                 al [i] = b;
860                                                 return;
861                                         }
862                                 }
863                                 al.Add (b);
864                                 return;
865                         }
866                         ArrayList replacement = new ArrayList ();
867                         replacement.Add (o);
868                         temporary_storage.Remove (t);
869                         temporary_storage [t] = replacement;
870                 }
871
872                 /// <summary>
873                 ///   Current loop begin and end labels.
874                 /// </summary>
875                 public Label LoopBegin, LoopEnd;
876
877                 /// <summary>
878                 ///   Default target in a switch statement.   Only valid if
879                 ///   InSwitch is true
880                 /// </summary>
881                 public Label DefaultTarget;
882
883                 /// <summary>
884                 ///   If this is non-null, points to the current switch statement
885                 /// </summary>
886                 public Switch Switch;
887
888                 /// <summary>
889                 ///   ReturnValue creates on demand the LocalBuilder for the
890                 ///   return value from the function.  By default this is not
891                 ///   used.  This is only required when returns are found inside
892                 ///   Try or Catch statements.
893                 ///
894                 ///   This method is typically invoked from the Emit phase, so
895                 ///   we allow the creation of a return label if it was not
896                 ///   requested during the resolution phase.   Could be cleaned
897                 ///   up, but it would replicate a lot of logic in the Emit phase
898                 ///   of the code that uses it.
899                 /// </summary>
900                 public LocalBuilder TemporaryReturn ()
901                 {
902                         if (return_value == null){
903                                 return_value = ig.DeclareLocal (ReturnType);
904                                 if (!HasReturnLabel){
905                                 ReturnLabel = ig.DefineLabel ();
906                                 HasReturnLabel = true;
907                         }
908                         }
909
910                         return return_value;
911                 }
912
913                 /// <summary>
914                 ///   This method is used during the Resolution phase to flag the
915                 ///   need to define the ReturnLabel
916                 /// </summary>
917                 public void NeedReturnLabel ()
918                 {
919                         if (current_phase != Phase.Resolving){
920                                 //
921                                 // The reason is that the `ReturnLabel' is declared between
922                                 // resolution and emission
923                                 // 
924                                 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
925                         }
926                         
927                         if (!InIterator && !HasReturnLabel) 
928                                 HasReturnLabel = true;
929                         }
930
931                 //
932                 // Creates a field `name' with the type `t' on the proxy class
933                 //
934                 public FieldBuilder MapVariable (string name, Type t)
935                 {
936                         if (InIterator)
937                                 return CurrentIterator.MapVariable ("v_", name, t);
938
939                         throw new Exception ("MapVariable for an unknown state");
940                 }
941
942                 public Expression RemapParameter (int idx)
943                 {
944                         FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
945                         fe.InstanceExpression = new ProxyInstance ();
946                         return fe.DoResolve (this);
947                 }
948
949                 public Expression RemapParameterLValue (int idx, Expression right_side)
950                 {
951                         FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
952                         fe.InstanceExpression = new ProxyInstance ();
953                         return fe.DoResolveLValue (this, right_side);
954                 }
955                 
956                 //
957                 // Emits the proper object to address fields on a remapped
958                 // variable/parameter to field in anonymous-method/iterator proxy classes.
959                 //
960                 public void EmitThis ()
961                 {
962                         ig.Emit (OpCodes.Ldarg_0);
963                         if (InIterator){
964                                 if (!IsStatic){
965                                 FieldBuilder this_field = CurrentIterator.this_field.FieldBuilder;
966                                 if (TypeManager.IsValueType (this_field.FieldType))
967                                         ig.Emit (OpCodes.Ldflda, this_field);
968                                 else
969                                         ig.Emit (OpCodes.Ldfld, this_field);
970                         }
971                         } else if (capture_context != null && CurrentAnonymousMethod != null){
972                                 ScopeInfo si = CurrentAnonymousMethod.Scope;
973                                 while (si != null){
974                                         if (si.ParentLink != null)
975                                                 ig.Emit (OpCodes.Ldfld, si.ParentLink);
976                                         if (si.THIS != null){
977                                                 ig.Emit (OpCodes.Ldfld, si.THIS);
978                                                 break;
979                                         }
980                                         si = si.ParentScope;
981                                 }
982                         } 
983                 }
984
985                 //
986                 // Emits the code necessary to load the instance required
987                 // to access the captured LocalInfo
988                 //
989                 public void EmitCapturedVariableInstance (LocalInfo li)
990                 {
991                         if (RemapToProxy){
992                                 ig.Emit (OpCodes.Ldarg_0);
993                                 return;
994                         }
995                         
996                         if (capture_context == null)
997                                 throw new Exception ("Calling EmitCapturedContext when there is no capture_context");
998                         
999                         capture_context.EmitCapturedVariableInstance (this, li, CurrentAnonymousMethod);
1000                 }
1001
1002                 public void EmitParameter (string name)
1003                 {
1004                         capture_context.EmitParameter (this, name);
1005                 }
1006
1007                 public void EmitAssignParameter (string name, Expression source, bool leave_copy, bool prepare_for_load)
1008                 {
1009                         capture_context.EmitAssignParameter (this, name, source, leave_copy, prepare_for_load);
1010                 }
1011
1012                 public void EmitAddressOfParameter (string name)
1013                 {
1014                         capture_context.EmitAddressOfParameter (this, name);
1015                 }
1016
1017                 public Expression GetThis (Location loc)
1018                 {
1019                         This my_this;
1020                         if (CurrentBlock != null)
1021                                 my_this = new This (CurrentBlock, loc);
1022                         else
1023                                 my_this = new This (loc);
1024
1025                         if (!my_this.ResolveBase (this))
1026                                 my_this = null;
1027
1028                         return my_this;
1029                 }
1030         }
1031
1032
1033         public abstract class CommonAssemblyModulClass: Attributable {
1034                 protected CommonAssemblyModulClass ():
1035                         base (null)
1036                 {
1037                 }
1038
1039                 public void AddAttributes (ArrayList attrs)
1040                 {
1041                         if (OptAttributes == null) {
1042                                 OptAttributes = new Attributes (attrs);
1043                                 return;
1044                         }
1045                         OptAttributes.AddAttributes (attrs);
1046                 }
1047
1048                 public virtual void Emit (TypeContainer tc) 
1049                 {
1050                         if (OptAttributes == null)
1051                                 return;
1052
1053                         EmitContext ec = new EmitContext (tc, Mono.CSharp.Location.Null, null, null, 0, false);
1054                         OptAttributes.Emit (ec, this);
1055                 }
1056
1057                 protected Attribute GetClsCompliantAttribute ()
1058                 {
1059                         if (OptAttributes == null)
1060                                 return null;
1061
1062                         // Ensure that we only have GlobalAttributes, since the Search below isn't safe with other types.
1063                         if (!OptAttributes.CheckTargets (this))
1064                                 return null;
1065
1066                         EmitContext temp_ec = new EmitContext (RootContext.Tree.Types, Mono.CSharp.Location.Null, null, null, 0, false);
1067                         Attribute a = OptAttributes.Search (TypeManager.cls_compliant_attribute_type, temp_ec);
1068                         if (a != null) {
1069                                 a.Resolve (temp_ec);
1070                         }
1071                         return a;
1072                 }
1073         }
1074
1075         public class AssemblyClass: CommonAssemblyModulClass {
1076                 // TODO: make it private and move all builder based methods here
1077                 public AssemblyBuilder Builder;
1078                     
1079                 bool is_cls_compliant;
1080                 public Attribute ClsCompliantAttribute;
1081
1082                 ListDictionary declarative_security;
1083
1084                 static string[] attribute_targets = new string [] { "assembly" };
1085
1086                 public AssemblyClass (): base ()
1087                 {
1088                         is_cls_compliant = false;
1089                 }
1090
1091                 public bool IsClsCompliant {
1092                         get {
1093                                 return is_cls_compliant;
1094                         }
1095                         }
1096
1097                 public override AttributeTargets AttributeTargets {
1098                         get {
1099                                 return AttributeTargets.Assembly;
1100                         }
1101                 }
1102
1103                 public override bool IsClsCompliaceRequired(DeclSpace ds)
1104                 {
1105                         return is_cls_compliant;
1106                 }
1107
1108                 public void ResolveClsCompliance ()
1109                 {
1110                         ClsCompliantAttribute = GetClsCompliantAttribute ();
1111                         if (ClsCompliantAttribute == null)
1112                                 return;
1113
1114                         is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue (null);
1115                 }
1116
1117                 // fix bug #56621
1118                 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob) 
1119                 {
1120                         try {
1121                                 // check for possible ECMA key
1122                                 if (strongNameBlob.Length == 16) {
1123                                         // will be rejected if not "the" ECMA key
1124                                         an.SetPublicKey (strongNameBlob);
1125                                 }
1126                                 else {
1127                                         // take it, with or without, a private key
1128                                         RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1129                                         // and make sure we only feed the public part to Sys.Ref
1130                                         byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1131                                         
1132                                         // AssemblyName.SetPublicKey requires an additional header
1133                                         byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1134
1135                                         byte[] encodedPublicKey = new byte [12 + publickey.Length];
1136                                         Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1137                                         Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1138                                         an.SetPublicKey (encodedPublicKey);
1139                                 }
1140                         }
1141                         catch (Exception) {
1142                                 Report.Error (1548, "Could not strongname the assembly. File `" +
1143                                         RootContext.StrongNameKeyFile + "' incorrectly encoded.");
1144                                 Environment.Exit (1);
1145                         }
1146                 }
1147
1148                 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1149                 public AssemblyName GetAssemblyName (string name, string output) 
1150                 {
1151                         if (OptAttributes != null) {
1152                                foreach (Attribute a in OptAttributes.Attrs) {
1153                                        // cannot rely on any resolve-based members before you call Resolve
1154                                        if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1155                                                continue;
1156
1157                                        // TODO: This code is buggy: comparing Attribute name without resolving it is wrong.
1158                                        //       However, this is invoked by CodeGen.Init, at which time none of the namespaces
1159                                        //       are loaded yet.
1160                                         switch (a.Name) {
1161                                                 case "AssemblyKeyFile":
1162                                                case "AssemblyKeyFileAttribute":
1163                                                case "System.Reflection.AssemblyKeyFileAttribute":
1164                                                         if (RootContext.StrongNameKeyFile != null) {
1165                                                                 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1166                                                                 Report.Warning (1616, "Compiler option '{0}' overrides '{1}' given in source", "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1167                                                         }
1168                                                         else {
1169                                                                 string value = a.GetString ();
1170                                                                 if (value != String.Empty)
1171                                                                         RootContext.StrongNameKeyFile = value;
1172                                                         }
1173                                                         break;
1174                                                 case "AssemblyKeyName":
1175                                                case "AssemblyKeyNameAttribute":
1176                                                case "System.Reflection.AssemblyKeyNameAttribute":
1177                                                         if (RootContext.StrongNameKeyContainer != null) {
1178                                                                 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1179                                                                 Report.Warning (1616, "keycontainer", "Compiler option '{0}' overrides '{1}' given in source", "System.Reflection.AssemblyKeyNameAttribute");
1180                                                         }
1181                                                         else {
1182                                                                 string value = a.GetString ();
1183                                                                 if (value != String.Empty)
1184                                                                         RootContext.StrongNameKeyContainer = value;
1185                                                         }
1186                                                         break;
1187                                                 case "AssemblyDelaySign":
1188                                                case "AssemblyDelaySignAttribute":
1189                                                case "System.Reflection.AssemblyDelaySignAttribute":
1190                                                         RootContext.StrongNameDelaySign = a.GetBoolean ();
1191                                                         break;
1192                                         }
1193                                 }
1194                         }
1195
1196                         AssemblyName an = new AssemblyName ();
1197                         an.Name = Path.GetFileNameWithoutExtension (name);
1198
1199                         // note: delay doesn't apply when using a key container
1200                         if (RootContext.StrongNameKeyContainer != null) {
1201                                 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1202                                 return an;
1203                         }
1204
1205                         // strongname is optional
1206                         if (RootContext.StrongNameKeyFile == null)
1207                                 return an;
1208
1209                         string AssemblyDir = Path.GetDirectoryName (output);
1210
1211                         // the StrongName key file may be relative to (a) the compiled
1212                         // file or (b) to the output assembly. See bugzilla #55320
1213                         // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1214
1215                         // (a) relative to the compiled file
1216                         string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1217                         bool exist = File.Exists (filename);
1218                         if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1219                                 // (b) relative to the outputed assembly
1220                                 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1221                                 exist = File.Exists (filename);
1222                         }
1223
1224                         if (exist) {
1225                                 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1226                                         byte[] snkeypair = new byte [fs.Length];
1227                                         fs.Read (snkeypair, 0, snkeypair.Length);
1228
1229                                         if (RootContext.StrongNameDelaySign) {
1230                                                 // delayed signing - DO NOT include private key
1231                                                 SetPublicKey (an, snkeypair);
1232                                         }
1233                                         else {
1234                                                 // no delay so we make sure we have the private key
1235                                                 try {
1236                                                         CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1237                                                         an.KeyPair = new StrongNameKeyPair (snkeypair);
1238                                                 }
1239                                                 catch (CryptographicException) {
1240                                                         if (snkeypair.Length == 16) {
1241                                                                 // error # is different for ECMA key
1242                                                                 Report.Error (1606, "Could not strongname the assembly. " + 
1243                                                                         "ECMA key can only be used to delay-sign assemblies");
1244                                                         }
1245                                                         else {
1246                                                                 Report.Error (1548, "Could not strongname the assembly. File `" +
1247                                                                         RootContext.StrongNameKeyFile +
1248                                                                         "' doesn't have a private key.");
1249                                                         }
1250                                                         Environment.Exit (1);
1251                                                 }
1252                                         }
1253                                 }
1254                         }
1255                         else {
1256                                 Report.Error (1548, "Could not strongname the assembly. File `" +
1257                                         RootContext.StrongNameKeyFile + "' not found.");
1258                                 Environment.Exit (1);
1259                         }
1260                         return an;
1261                 }
1262
1263                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1264                 {
1265                         if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (true)) {
1266                                 if (declarative_security == null)
1267                                         declarative_security = new ListDictionary ();
1268
1269                                 a.ExtractSecurityPermissionSet (declarative_security);
1270                                 return;
1271                         }
1272
1273                         Builder.SetCustomAttribute (customBuilder);
1274                 }
1275
1276                 public override void Emit (TypeContainer tc)
1277                 {
1278                         base.Emit (tc);
1279
1280                         if (declarative_security != null) {
1281
1282                                 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1283                                 object builder_instance = Builder;
1284
1285                                 try {
1286                                         // Microsoft runtime hacking
1287                                         if (add_permission == null) {
1288                                                 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1289                                                 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1290
1291                                                 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1292                                                 builder_instance = fi.GetValue (Builder);
1293                                         }
1294
1295                                         object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1296                                                                                                   declarative_security [SecurityAction.RequestOptional],
1297                                                                                                   declarative_security [SecurityAction.RequestRefuse] };
1298                                         add_permission.Invoke (builder_instance, args);
1299                                 }
1300                                 catch {
1301                                         Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1302                                 }
1303                         }
1304                 }
1305
1306                 public override string[] ValidAttributeTargets {
1307                         get {
1308                                 return attribute_targets;
1309                         }
1310                 }
1311         }
1312
1313         public class ModuleClass: CommonAssemblyModulClass {
1314                 // TODO: make it private and move all builder based methods here
1315                 public ModuleBuilder Builder;
1316                 bool m_module_is_unsafe;
1317
1318                 static string[] attribute_targets = new string [] { "module" };
1319
1320                 public ModuleClass (bool is_unsafe)
1321                 {
1322                         m_module_is_unsafe = is_unsafe;
1323                 }
1324
1325                 public override AttributeTargets AttributeTargets {
1326                         get {
1327                                 return AttributeTargets.Module;
1328                         }
1329                 }
1330
1331                 public override bool IsClsCompliaceRequired(DeclSpace ds)
1332                 {
1333                         return CodeGen.Assembly.IsClsCompliant;
1334                         }
1335
1336                 public override void Emit (TypeContainer tc) 
1337                 {
1338                         base.Emit (tc);
1339
1340                         if (!m_module_is_unsafe)
1341                                 return;
1342
1343                         if (TypeManager.unverifiable_code_ctor == null) {
1344                                 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
1345                                 return;
1346                         }
1347                                 
1348                         Builder.SetCustomAttribute (new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
1349                 }
1350                 
1351                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1352                 {
1353                         if (a.Type == TypeManager.cls_compliant_attribute_type) {
1354                                 if (CodeGen.Assembly.ClsCompliantAttribute == null) {
1355                                         Report.Warning (3012, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1356                                 }
1357                                 else if (CodeGen.Assembly.IsClsCompliant != a.GetBoolean ()) {
1358                                         Report.SymbolRelatedToPreviousError (CodeGen.Assembly.ClsCompliantAttribute.Location, CodeGen.Assembly.ClsCompliantAttribute.Name);
1359                                         Report.Error (3017, a.Location, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
1360                                         return;
1361                                 }
1362                         }
1363
1364                         Builder.SetCustomAttribute (customBuilder);
1365                 }
1366
1367                 public override string[] ValidAttributeTargets {
1368                         get {
1369                                 return attribute_targets;
1370                         }
1371                 }
1372         }
1373 }