2 // codegen.cs: The code generator
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, Inc.
12 using System.Collections;
13 using System.Reflection;
14 using System.Reflection.Emit;
16 namespace Mono.CSharp {
19 /// Code generator class.
21 public class CodeGen {
22 static AppDomain current_domain;
23 public static AssemblyBuilder AssemblyBuilder;
24 public static ModuleBuilder ModuleBuilder;
26 static public SymbolWriter SymbolWriter;
28 public static string Basename (string name)
30 int pos = name.LastIndexOf ('/');
33 return name.Substring (pos + 1);
35 pos = name.LastIndexOf ('\\');
37 return name.Substring (pos + 1);
42 public static string Dirname (string name)
44 int pos = name.LastIndexOf ('/');
47 return name.Substring (0, pos);
49 pos = name.LastIndexOf ('\\');
51 return name.Substring (0, pos);
56 static string TrimExt (string name)
58 int pos = name.LastIndexOf ('.');
60 return name.Substring (0, pos);
63 static public string FileName;
66 // Initializes the symbol writer
68 static void InitializeSymbolWriter ()
70 SymbolWriter = SymbolWriter.GetSymbolWriter (ModuleBuilder);
73 // If we got an ISymbolWriter instance, initialize it.
75 if (SymbolWriter == null) {
77 -18, "Could not find the symbol writer assembly (Mono.CSharp.Debugger.dll). This is normally an installation problem. Please make sure to compile and install the mcs/class/Mono.CSharp.Debugger directory.");
83 // Initializes the code generator variables
85 static public void Init (string name, string output, bool want_debugging_support)
90 an = new AssemblyName ();
91 an.Name = Path.GetFileNameWithoutExtension (name);
93 current_domain = AppDomain.CurrentDomain;
94 AssemblyBuilder = current_domain.DefineDynamicAssembly (
95 an, AssemblyBuilderAccess.Save, Dirname (name));
98 // Pass a path-less name to DefineDynamicModule. Wonder how
99 // this copes with output in different directories then.
100 // FIXME: figure out how this copes with --output /tmp/blah
102 // If the third argument is true, the ModuleBuilder will dynamically
103 // load the default symbol writer.
105 ModuleBuilder = AssemblyBuilder.DefineDynamicModule (
106 Basename (name), Basename (output), want_debugging_support);
108 if (want_debugging_support)
109 InitializeSymbolWriter ();
112 static public void Save (string name)
115 AssemblyBuilder.Save (Basename (name));
116 } catch (System.IO.IOException io){
117 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
123 // Provides "local" store across code that can yield: locals
124 // or fields, notice that this should not be used by anonymous
125 // methods to create local storage, those only require
128 public class VariableStorage {
135 public VariableStorage (EmitContext ec, Type t)
139 fb = IteratorHandler.Current.MapVariable ("s_", count.ToString (), t);
141 local = ec.ig.DeclareLocal (t);
145 public void EmitThis ()
148 ig.Emit (OpCodes.Ldarg_0);
151 public void EmitStore ()
154 ig.Emit (OpCodes.Stloc, local);
156 ig.Emit (OpCodes.Stfld, fb);
159 public void EmitLoad ()
162 ig.Emit (OpCodes.Ldloc, local);
164 ig.Emit (OpCodes.Ldfld, fb);
167 public void EmitCall (MethodInfo mi)
169 // FIXME : we should handle a call like tostring
170 // here, where boxing is needed. However, we will
171 // never encounter that with the current usage.
173 bool value_type_call;
176 value_type_call = local.LocalType.IsValueType;
179 ig.Emit (OpCodes.Ldloca, local);
181 ig.Emit (OpCodes.Ldloc, local);
183 value_type_call = fb.FieldType.IsValueType;
186 ig.Emit (OpCodes.Ldflda, fb);
188 ig.Emit (OpCodes.Ldfld, fb);
191 ig.Emit (value_type_call ? OpCodes.Call : OpCodes.Callvirt, mi);
196 /// An Emit Context is created for each body of code (from methods,
197 /// properties bodies, indexer bodies or constructor bodies)
199 public class EmitContext {
200 public DeclSpace DeclSpace;
201 public DeclSpace TypeContainer;
202 public ILGenerator ig;
205 /// This variable tracks the `checked' state of the compilation,
206 /// it controls whether we should generate code that does overflow
207 /// checking, or if we generate code that ignores overflows.
209 /// The default setting comes from the command line option to generate
210 /// checked or unchecked code plus any source code changes using the
211 /// checked/unchecked statements or expressions. Contrast this with
212 /// the ConstantCheckState flag.
215 public bool CheckState;
218 /// The constant check state is always set to `true' and cant be changed
219 /// from the command line. The source code can change this setting with
220 /// the `checked' and `unchecked' statements and expressions.
222 public bool ConstantCheckState;
225 /// Whether we are emitting code inside a static or instance method
227 public bool IsStatic;
230 /// Whether we are emitting a field initializer
232 public bool IsFieldInitializer;
235 /// The value that is allowed to be returned or NULL if there is no
238 public Type ReturnType;
241 /// Points to the Type (extracted from the TypeContainer) that
242 /// declares this body of code
244 public Type ContainerType;
247 /// Whether this is generating code for a constructor
249 public bool IsConstructor;
252 /// Whether we're control flow analysis enabled
254 public bool DoFlowAnalysis;
257 /// Keeps track of the Type to LocalBuilder temporary storage created
258 /// to store structures (used to compute the address of the structure
259 /// value on structure method invocations)
261 public Hashtable temporary_storage;
263 public Block CurrentBlock;
265 public int CurrentFile;
268 /// The location where we store the return value.
270 LocalBuilder return_value;
273 /// The location where return has to jump to return the
276 public Label ReturnLabel;
279 /// If we already defined the ReturnLabel
281 public bool HasReturnLabel;
284 /// Whether we are inside an iterator block.
286 public bool InIterator;
288 public bool IsLastStatement;
291 /// Whether remapping of locals, parameters and fields is turned on.
292 /// Used by iterators and anonymous methods.
294 public bool RemapToProxy;
297 /// Whether we are inside an unsafe block
299 public bool InUnsafe;
302 /// Whether we are in a `fixed' initialization
304 public bool InFixedInitializer;
307 /// Whether we are inside an anonymous method.
309 public bool InAnonymousMethod;
312 /// Location for this EmitContext
317 /// Used to flag that it is ok to define types recursively, as the
318 /// expressions are being evaluated as part of the type lookup
319 /// during the type resolution process
321 public bool ResolvingTypeTree;
324 /// Inside an enum definition, we do not resolve enumeration values
325 /// to their enumerations, but rather to the underlying type/value
326 /// This is so EnumVal + EnumValB can be evaluated.
328 /// There is no "E operator + (E x, E y)", so during an enum evaluation
329 /// we relax the rules
331 public bool InEnumContext;
333 FlowBranching current_flow_branching;
335 public EmitContext (DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
336 Type return_type, int code_flags, bool is_constructor)
340 TypeContainer = parent;
342 CheckState = RootContext.Checked;
343 ConstantCheckState = true;
345 IsStatic = (code_flags & Modifiers.STATIC) != 0;
346 InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
347 RemapToProxy = InIterator;
348 ReturnType = return_type;
349 IsConstructor = is_constructor;
354 // Can only be null for the ResolveType contexts.
355 ContainerType = parent.TypeBuilder;
356 if (parent.UnsafeContext)
359 InUnsafe = (code_flags & Modifiers.UNSAFE) != 0;
363 if (ReturnType == TypeManager.void_type)
367 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
368 Type return_type, int code_flags, bool is_constructor)
369 : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
373 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
374 Type return_type, int code_flags)
375 : this (tc, tc, l, ig, return_type, code_flags, false)
379 public FlowBranching CurrentBranching {
381 return current_flow_branching;
386 // Starts a new code branching. This inherits the state of all local
387 // variables and parameters from the current branching.
389 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
391 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
392 return current_flow_branching;
396 // Starts a new code branching for block `block'.
398 public FlowBranching StartFlowBranching (Block block)
400 FlowBranching.BranchingType type;
402 if (CurrentBranching.Type == FlowBranching.BranchingType.Switch)
403 type = FlowBranching.BranchingType.SwitchSection;
405 type = FlowBranching.BranchingType.Block;
407 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, block, block.StartLocation);
408 return current_flow_branching;
412 // Ends a code branching. Merges the state of locals and parameters
413 // from all the children of the ending branching.
415 public FlowBranching.UsageVector DoEndFlowBranching ()
417 FlowBranching old = current_flow_branching;
418 current_flow_branching = current_flow_branching.Parent;
420 return current_flow_branching.MergeChild (old);
424 // Ends a code branching. Merges the state of locals and parameters
425 // from all the children of the ending branching.
427 public FlowBranching.Reachability EndFlowBranching ()
429 FlowBranching.UsageVector vector = DoEndFlowBranching ();
431 return vector.Reachability;
435 // Kills the current code branching. This throws away any changed state
436 // information and should only be used in case of an error.
438 public void KillFlowBranching ()
440 current_flow_branching = current_flow_branching.Parent;
443 public void EmitTopBlock (Block block, InternalParameters ip, Location loc)
445 bool unreachable = false;
447 if (!Location.IsNull (loc))
448 CurrentFile = loc.File;
452 int errors = Report.Errors;
454 block.EmitMeta (this, ip);
456 if (Report.Errors == errors){
457 bool old_do_flow_analysis = DoFlowAnalysis;
458 DoFlowAnalysis = true;
460 current_flow_branching = FlowBranching.CreateBranching (
461 null, FlowBranching.BranchingType.Block, block, loc);
463 if (!block.Resolve (this)) {
464 current_flow_branching = null;
465 DoFlowAnalysis = old_do_flow_analysis;
469 FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
470 current_flow_branching = null;
472 DoFlowAnalysis = old_do_flow_analysis;
476 if (reachability.AlwaysReturns ||
477 reachability.AlwaysThrows ||
478 reachability.IsUnreachable)
481 } catch (Exception e) {
482 Console.WriteLine ("Exception caught by the compiler while compiling:");
483 Console.WriteLine (" Block that caused the problem begin at: " + loc);
485 if (CurrentBlock != null){
486 Console.WriteLine (" Block being compiled: [{0},{1}]",
487 CurrentBlock.StartLocation, CurrentBlock.EndLocation);
489 Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
490 Console.WriteLine (Report.FriendlyStackTrace (e));
492 Environment.Exit (1);
496 if (ReturnType != null && !unreachable){
498 Report.Error (161, loc, "Not all code paths return a value");
504 ig.MarkLabel (ReturnLabel);
505 if (return_value != null){
506 ig.Emit (OpCodes.Ldloc, return_value);
507 ig.Emit (OpCodes.Ret);
510 // If `HasReturnLabel' is set, then we already emitted a
511 // jump to the end of the method, so we must emit a `ret'
514 // Unfortunately, System.Reflection.Emit automatically emits
515 // a leave to the end of a finally block. This is a problem
516 // if no code is following the try/finally block since we may
517 // jump to a point after the end of the method.
518 // As a workaround, we're always creating a return label in
522 if ((block != null) && block.IsDestructor) {
523 // Nothing to do; S.R.E automatically emits a leave.
524 } else if (HasReturnLabel || (!unreachable && !InIterator)) {
525 if (ReturnType != null)
526 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
527 ig.Emit (OpCodes.Ret);
533 /// This is called immediately before emitting an IL opcode to tell the symbol
534 /// writer to which source line this opcode belongs.
536 public void Mark (Location loc, bool check_file)
538 if ((CodeGen.SymbolWriter == null) || Location.IsNull (loc))
541 if (check_file && (CurrentFile != loc.File))
544 ig.MarkSequencePoint (null, loc.Row, 0, 0, 0);
548 /// Returns a temporary storage for a variable of type t as
549 /// a local variable in the current body.
551 public LocalBuilder GetTemporaryLocal (Type t)
553 LocalBuilder location = null;
555 if (temporary_storage != null){
556 object o = temporary_storage [t];
559 ArrayList al = (ArrayList) o;
561 for (int i = 0; i < al.Count; i++){
563 location = (LocalBuilder) al [i];
569 location = (LocalBuilder) o;
570 if (location != null)
575 return ig.DeclareLocal (t);
578 public void FreeTemporaryLocal (LocalBuilder b, Type t)
580 if (temporary_storage == null){
581 temporary_storage = new Hashtable ();
582 temporary_storage [t] = b;
585 object o = temporary_storage [t];
587 temporary_storage [t] = b;
591 ArrayList al = (ArrayList) o;
592 for (int i = 0; i < al.Count; i++){
601 ArrayList replacement = new ArrayList ();
603 temporary_storage.Remove (t);
604 temporary_storage [t] = replacement;
608 /// Current loop begin and end labels.
610 public Label LoopBegin, LoopEnd;
613 /// Default target in a switch statement. Only valid if
616 public Label DefaultTarget;
619 /// If this is non-null, points to the current switch statement
621 public Switch Switch;
624 /// ReturnValue creates on demand the LocalBuilder for the
625 /// return value from the function. By default this is not
626 /// used. This is only required when returns are found inside
627 /// Try or Catch statements.
629 public LocalBuilder TemporaryReturn ()
631 if (return_value == null){
632 return_value = ig.DeclareLocal (ReturnType);
633 ReturnLabel = ig.DefineLabel ();
634 HasReturnLabel = true;
640 public void NeedReturnLabel ()
642 if (!HasReturnLabel) {
643 ReturnLabel = ig.DefineLabel ();
644 HasReturnLabel = true;
649 // Creates a field `name' with the type `t' on the proxy class
651 public FieldBuilder MapVariable (string name, Type t)
654 return IteratorHandler.Current.MapVariable ("v_", name, t);
657 throw new Exception ("MapVariable for an unknown state");
661 // Invoke this routine to remap a VariableInfo into the
662 // proper MemberAccess expression
664 public Expression RemapLocal (LocalInfo local_info)
666 FieldExpr fe = new FieldExpr (local_info.FieldBuilder, loc);
667 fe.InstanceExpression = new ProxyInstance ();
668 return fe.DoResolve (this);
671 public Expression RemapLocalLValue (LocalInfo local_info, Expression right_side)
673 FieldExpr fe = new FieldExpr (local_info.FieldBuilder, loc);
674 fe.InstanceExpression = new ProxyInstance ();
675 return fe.DoResolveLValue (this, right_side);
678 public Expression RemapParameter (int idx)
680 FieldExpr fe = new FieldExprNoAddress (IteratorHandler.Current.parameter_fields [idx], loc);
681 fe.InstanceExpression = new ProxyInstance ();
682 return fe.DoResolve (this);
685 public Expression RemapParameterLValue (int idx, Expression right_side)
687 FieldExpr fe = new FieldExprNoAddress (IteratorHandler.Current.parameter_fields [idx], loc);
688 fe.InstanceExpression = new ProxyInstance ();
689 return fe.DoResolveLValue (this, right_side);
693 // Emits the proper object to address fields on a remapped
694 // variable/parameter to field in anonymous-method/iterator proxy classes.
696 public void EmitThis ()
698 ig.Emit (OpCodes.Ldarg_0);
702 ig.Emit (OpCodes.Ldfld, IteratorHandler.Current.this_field);
704 throw new Exception ("EmitThis for an unknown state");
708 public Expression GetThis (Location loc)
711 if (CurrentBlock != null)
712 my_this = new This (CurrentBlock, loc);
714 my_this = new This (loc);
716 if (!my_this.ResolveBase (this))