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;
15 using System.Diagnostics.SymbolStore;
17 namespace Mono.CSharp {
20 /// Code generator class.
22 public class CodeGen {
23 static AppDomain current_domain;
24 public static AssemblyBuilder AssemblyBuilder;
25 public static ModuleBuilder ModuleBuilder;
27 static public ISymbolWriter SymbolWriter;
29 public static string Basename (string name)
31 int pos = name.LastIndexOf ("/");
34 return name.Substring (pos + 1);
36 pos = name.LastIndexOf ("\\");
38 return name.Substring (pos + 1);
43 public static string Dirname (string name)
45 int pos = name.LastIndexOf ("/");
48 return name.Substring (0, pos);
50 pos = name.LastIndexOf ("\\");
52 return name.Substring (0, pos);
57 static string TrimExt (string name)
59 int pos = name.LastIndexOf (".");
61 return name.Substring (0, pos);
64 static public string FileName;
67 // This routine initializes the Mono runtime SymbolWriter.
69 static bool InitMonoSymbolWriter (string basename, string symbol_output,
70 string exe_output_file, string[] debug_args)
72 Type itype = SymbolWriter.GetType ();
76 Type[] arg_types = new Type [3];
77 arg_types [0] = typeof (string);
78 arg_types [1] = typeof (string);
79 arg_types [2] = typeof (string[]);
81 MethodInfo initialize = itype.GetMethod ("Initialize", arg_types);
82 if (initialize == null)
85 object[] args = new object [3];
86 args [0] = exe_output_file;
87 args [1] = symbol_output;
88 args [2] = debug_args;
90 initialize.Invoke (SymbolWriter, args);
95 // Initializes the symbol writer
97 static void InitializeSymbolWriter (string basename, string symbol_output,
98 string exe_output_file, string[] args)
100 SymbolWriter = ModuleBuilder.GetSymWriter ();
103 // If we got an ISymbolWriter instance, initialize it.
105 if (SymbolWriter == null) {
107 -18, "Cannot find any symbol writer");
112 // Due to lacking documentation about the first argument of the
113 // Initialize method, we cannot use Microsoft's default symbol
116 // If we're using the mono symbol writer, the SymbolWriter object
117 // is of type MonoSymbolWriter - but that's defined in a dynamically
118 // loaded DLL - that's why we're doing a comparision based on the type
119 // name here instead of using `SymbolWriter is MonoSymbolWriter'.
121 Type sym_type = ((object) SymbolWriter).GetType ();
123 switch (sym_type.Name){
124 case "MonoSymbolWriter":
125 if (!InitMonoSymbolWriter (basename, symbol_output,
126 exe_output_file, args))
128 -18, "Cannot initialize the symbol writer");
133 -18, "Cannot generate debugging information on this platform");
139 // Initializes the code generator variables
141 static public void Init (string name, string output, bool want_debugging_support,
147 an = new AssemblyName ();
148 an.Name = TrimExt (Basename (name));
149 current_domain = AppDomain.CurrentDomain;
150 AssemblyBuilder = current_domain.DefineDynamicAssembly (
151 an, AssemblyBuilderAccess.RunAndSave, Dirname (name));
154 // Pass a path-less name to DefineDynamicModule. Wonder how
155 // this copes with output in different directories then.
156 // FIXME: figure out how this copes with --output /tmp/blah
158 // If the third argument is true, the ModuleBuilder will dynamically
159 // load the default symbol writer.
161 ModuleBuilder = AssemblyBuilder.DefineDynamicModule (
162 Basename (name), Basename (output), want_debugging_support);
164 int pos = output.LastIndexOf (".");
168 basename = output.Substring (0, pos);
172 string symbol_output = basename + ".dbg";
174 if (want_debugging_support)
175 InitializeSymbolWriter (basename, symbol_output, output, debug_args);
178 File.Delete (symbol_output);
185 static public void Save (string name)
188 AssemblyBuilder.Save (Basename (name));
189 } catch (System.IO.IOException io){
190 Report.Error (16, "Coult not write to file `"+name+"', cause: " + io.Message);
194 static public void SaveSymbols ()
196 if (SymbolWriter != null) {
197 // If we have a symbol writer, call its Close() method to write
198 // the symbol file to disk.
200 // When using Mono's default symbol writer, the Close() method must
201 // be called after the assembly has already been written to disk since
202 // it opens the assembly and reads its metadata.
203 SymbolWriter.Close ();
209 /// An Emit Context is created for each body of code (from methods,
210 /// properties bodies, indexer bodies or constructor bodies)
212 public class EmitContext {
213 public DeclSpace DeclSpace;
214 public DeclSpace TypeContainer;
215 public ILGenerator ig;
218 /// This variable tracks the `checked' state of the compilation,
219 /// it controls whether we should generate code that does overflow
220 /// checking, or if we generate code that ignores overflows.
222 /// The default setting comes from the command line option to generate
223 /// checked or unchecked code plus any source code changes using the
224 /// checked/unchecked statements or expressions. Contrast this with
225 /// the ConstantCheckState flag.
228 public bool CheckState;
231 /// The constant check state is always set to `true' and cant be changed
232 /// from the command line. The source code can change this setting with
233 /// the `checked' and `unchecked' statements and expressions.
235 public bool ConstantCheckState;
238 /// Whether we are emitting code inside a static or instance method
240 public bool IsStatic;
243 /// Whether we are emitting a field initializer
245 public bool IsFieldInitializer;
248 /// The value that is allowed to be returned or NULL if there is no
251 public Type ReturnType;
254 /// Points to the Type (extracted from the TypeContainer) that
255 /// declares this body of code
257 public Type ContainerType;
260 /// Whether this is generating code for a constructor
262 public bool IsConstructor;
265 /// Whether we're control flow analysis enabled
267 public bool DoFlowAnalysis;
270 /// Keeps track of the Type to LocalBuilder temporary storage created
271 /// to store structures (used to compute the address of the structure
272 /// value on structure method invocations)
274 public Hashtable temporary_storage;
276 public Block CurrentBlock;
279 /// The location where we store the return value.
281 LocalBuilder return_value;
284 /// The location where return has to jump to return the
287 public Label ReturnLabel;
290 /// If we already defined the ReturnLabel
292 public bool HasReturnLabel;
295 /// Whether we are in a Finally block
297 public bool InFinally;
300 /// Whether we are in a Try block
305 /// Whether we are in a Catch block
310 /// Whether we are inside an unsafe block
312 public bool InUnsafe;
315 /// Location for this EmitContext
320 /// Used to flag that it is ok to define types recursively, as the
321 /// expressions are being evaluated as part of the type lookup
322 /// during the type resolution process
324 public bool ResolvingTypeTree;
327 /// Inside an enum definition, we do not resolve enumeration values
328 /// to their enumerations, but rather to the underlying type/value
329 /// This is so EnumVal + EnumValB can be evaluated.
331 /// There is no "E operator + (E x, E y)", so during an enum evaluation
332 /// we relax the rules
334 public bool InEnumContext;
336 protected Stack FlowStack;
338 public EmitContext (DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
339 Type return_type, int code_flags, bool is_constructor)
343 TypeContainer = parent;
345 CheckState = RootContext.Checked;
346 ConstantCheckState = true;
348 IsStatic = (code_flags & Modifiers.STATIC) != 0;
349 ReturnType = return_type;
350 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 FlowStack = new Stack ();
365 if (ReturnType == TypeManager.void_type)
369 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
370 Type return_type, int code_flags, bool is_constructor)
371 : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
375 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
376 Type return_type, int code_flags)
377 : this (tc, tc, l, ig, return_type, code_flags, false)
381 public FlowBranching CurrentBranching {
383 return (FlowBranching) FlowStack.Peek ();
388 // Starts a new code branching. This inherits the state of all local
389 // variables and parameters from the current branching.
391 public FlowBranching StartFlowBranching (FlowBranchingType type, Location loc)
393 FlowBranching cfb = new FlowBranching (CurrentBranching, type, null, loc);
395 FlowStack.Push (cfb);
401 // Starts a new code branching for block `block'.
403 public FlowBranching StartFlowBranching (Block block)
406 FlowBranchingType type;
408 if (CurrentBranching.Type == FlowBranchingType.SWITCH)
409 type = FlowBranchingType.SWITCH_SECTION;
411 type = FlowBranchingType.BLOCK;
413 cfb = new FlowBranching (CurrentBranching, type, block, block.StartLocation);
415 FlowStack.Push (cfb);
421 // Ends a code branching. Merges the state of locals and parameters
422 // from all the children of the ending branching.
424 public FlowReturns EndFlowBranching ()
426 FlowBranching cfb = (FlowBranching) FlowStack.Pop ();
428 return CurrentBranching.MergeChild (cfb);
432 // Kills the current code branching. This throws away any changed state
433 // information and should only be used in case of an error.
435 public void KillFlowBranching ()
437 FlowBranching cfb = (FlowBranching) FlowStack.Pop ();
441 // Checks whether the local variable `vi' is already initialized
442 // at the current point of the method's control flow.
443 // If this method returns false, the caller must report an
446 public bool IsVariableAssigned (VariableInfo vi)
449 return CurrentBranching.IsVariableAssigned (vi);
455 // Marks the local variable `vi' as being initialized at the current
456 // current point of the method's control flow.
458 public void SetVariableAssigned (VariableInfo vi)
461 CurrentBranching.SetVariableAssigned (vi);
465 // Checks whether the parameter `number' is already initialized
466 // at the current point of the method's control flow.
467 // If this method returns false, the caller must report an
468 // error 165. This is only necessary for `out' parameters and the
469 // call will always succeed for non-`out' parameters.
471 public bool IsParameterAssigned (int number)
474 return CurrentBranching.IsParameterAssigned (number);
480 // Marks the parameter `number' as being initialized at the current
481 // current point of the method's control flow. This is only necessary
482 // for `out' parameters.
484 public void SetParameterAssigned (int number)
487 CurrentBranching.SetParameterAssigned (number);
490 public void EmitTopBlock (Block block, InternalParameters ip, Location loc)
492 bool has_ret = false;
494 // Console.WriteLine ("Emitting: " + loc);
496 if (CodeGen.SymbolWriter != null)
501 int errors = Report.Errors;
503 block.EmitMeta (this, block);
505 if (Report.Errors == errors){
506 bool old_do_flow_analysis = DoFlowAnalysis;
507 DoFlowAnalysis = true;
509 FlowBranching cfb = new FlowBranching (block, ip, loc);
510 FlowStack.Push (cfb);
512 if (!block.Resolve (this)) {
514 DoFlowAnalysis = old_do_flow_analysis;
518 cfb = (FlowBranching) FlowStack.Pop ();
519 FlowReturns returns = cfb.MergeTopBlock ();
521 DoFlowAnalysis = old_do_flow_analysis;
523 has_ret = block.Emit (this);
525 if ((returns == FlowReturns.ALWAYS) ||
526 (returns == FlowReturns.EXCEPTION) ||
527 (returns == FlowReturns.UNREACHABLE))
530 if (Report.Errors == errors){
531 if (RootContext.WarningLevel >= 3)
532 block.UsageWarning ();
536 Console.WriteLine ("Exception caught by the compiler while compiling:");
537 Console.WriteLine (" Block that caused the problem begin at: " + loc);
538 Console.WriteLine (" Block being compiled: [{0},{1}]",
539 CurrentBlock.StartLocation, CurrentBlock.EndLocation);
544 if (ReturnType != null && !has_ret){
546 // FIXME: we need full flow analysis to implement this
547 // correctly and emit an error instead of a warning.
550 Report.Error (161, loc, "Not all code paths return a value");
555 ig.MarkLabel (ReturnLabel);
556 if (return_value != null){
557 ig.Emit (OpCodes.Ldloc, return_value);
558 ig.Emit (OpCodes.Ret);
561 if (!has_ret || HasReturnLabel)
562 ig.Emit (OpCodes.Ret);
568 /// This is called immediately before emitting an IL opcode to tell the symbol
569 /// writer to which source line this opcode belongs.
571 public void Mark (Location loc)
573 if ((CodeGen.SymbolWriter != null) && !Location.IsNull (loc)) {
574 ISymbolDocumentWriter doc = loc.SymbolDocument;
577 ig.MarkSequencePoint (doc, loc.Row, 0, loc.Row, 0);
582 /// Returns a temporary storage for a variable of type t as
583 /// a local variable in the current body.
585 public LocalBuilder GetTemporaryStorage (Type t)
587 LocalBuilder location;
589 if (temporary_storage != null){
590 location = (LocalBuilder) temporary_storage [t];
591 if (location != null)
595 location = ig.DeclareLocal (t);
600 public void FreeTemporaryStorage (LocalBuilder b)
606 /// Current loop begin and end labels.
608 public Label LoopBegin, LoopEnd;
611 /// Whether we are inside a loop and break/continue are possible.
616 /// This is incremented each time we enter a try/catch block and
617 /// decremented if we leave it.
619 public int TryCatchLevel;
622 /// The TryCatchLevel at the begin of the current loop.
624 public int LoopBeginTryCatchLevel;
627 /// Default target in a switch statement. Only valid if
630 public Label DefaultTarget;
633 /// If this is non-null, points to the current switch statement
635 public Switch Switch;
638 /// ReturnValue creates on demand the LocalBuilder for the
639 /// return value from the function. By default this is not
640 /// used. This is only required when returns are found inside
641 /// Try or Catch statements.
643 public LocalBuilder TemporaryReturn ()
645 if (return_value == null){
646 return_value = ig.DeclareLocal (ReturnType);
647 ReturnLabel = ig.DefineLabel ();
648 HasReturnLabel = true;
655 /// A dynamic This that is shared by all variables in a emitcontext.
656 /// Created on demand.
658 public Expression my_this;
659 public Expression This {
661 if (my_this == null) {
662 if (CurrentBlock != null)
663 my_this = new This (CurrentBlock, loc);
665 my_this = new This (loc);
667 my_this = my_this.Resolve (this);