2 // codegen.cs: The code generator
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, Inc.
11 using System.Collections;
12 using System.Reflection;
13 using System.Reflection.Emit;
14 using System.Diagnostics.SymbolStore;
16 namespace Mono.CSharp {
19 /// Code generator class.
21 public class CodeGen {
22 static AppDomain current_domain;
23 static AssemblyBuilder assembly_builder;
24 static ModuleBuilder module_builder;
26 static public ISymbolWriter 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 // This routine initializes the Mono runtime SymbolWriter.
68 static void InitMonoSymbolWriter (string basename)
70 string symbol_output = basename + "-debug.s";
73 // Mono's default symbol writer ignores the first and third argument
76 SymbolWriter.Initialize (new IntPtr (0), symbol_output, true);
80 // Initializes the symbol writer
82 static void InitializeSymbolWriter (string basename)
84 SymbolWriter = module_builder.GetSymWriter ();
87 // If we got an ISymbolWriter instance, initialize it.
89 if (SymbolWriter == null)
93 // Due to lacking documentation about the first argument of the
94 // Initialize method, we cannot use Microsoft's default symbol
97 // If we're using the mono symbol writer, the SymbolWriter object
98 // is of type MonoSymbolWriter - but that's defined in a dynamically
99 // loaded DLL - that's why we're doing a comparision based on the type
100 // name here instead of using `SymbolWriter is MonoSymbolWriter'.
102 Type sym_type = ((object) SymbolWriter).GetType ();
104 switch (sym_type.Name){
105 case "MonoSymbolWriter":
106 InitMonoSymbolWriter (basename);
111 -18, "Cannot generate debugging information on this platform");
117 // Initializes the code generator variables
119 static public void Init (string name, string output, bool want_debugging_support)
124 an = new AssemblyName ();
125 an.Name = TrimExt (Basename (name));
126 current_domain = AppDomain.CurrentDomain;
127 assembly_builder = current_domain.DefineDynamicAssembly (
128 an, AssemblyBuilderAccess.RunAndSave, Dirname (name));
131 // Pass a path-less name to DefineDynamicModule. Wonder how
132 // this copes with output in different directories then.
133 // FIXME: figure out how this copes with --output /tmp/blah
135 // If the third argument is true, the ModuleBuilder will dynamically
136 // load the default symbol writer.
138 module_builder = assembly_builder.DefineDynamicModule (
139 Basename (name), Basename (output), want_debugging_support);
141 if (want_debugging_support)
142 InitializeSymbolWriter (an.Name);
145 static public AssemblyBuilder AssemblyBuilder {
147 return assembly_builder;
151 static public ModuleBuilder ModuleBuilder {
153 return module_builder;
157 static public void Save (string name)
160 assembly_builder.Save (Basename (name));
161 } catch (System.IO.IOException io){
162 Report.Error (16, "Coult not write to file `"+name+"', cause: " + io.Message);
166 static public void SaveSymbols ()
168 if (SymbolWriter != null) {
169 // If we have a symbol writer, call its Close() method to write
170 // the symbol file to disk.
172 // When using Mono's default symbol writer, the Close() method must
173 // be called after the assembly has already been written to disk since
174 // it opens the assembly and reads its metadata.
175 SymbolWriter.Close ();
181 /// An Emit Context is created for each body of code (from methods,
182 /// properties bodies, indexer bodies or constructor bodies)
184 public class EmitContext {
185 public DeclSpace DeclSpace;
186 public TypeContainer TypeContainer;
187 public ILGenerator ig;
190 /// This variable tracks the `checked' state of the compilation,
191 /// it controls whether we should generate code that does overflow
192 /// checking, or if we generate code that ignores overflows.
194 /// The default setting comes from the command line option to generate
195 /// checked or unchecked code plus any source code changes using the
196 /// checked/unchecked statements or expressions. Contrast this with
197 /// the ConstantCheckState flag.
200 public bool CheckState;
203 /// The constant check state is always set to `true' and cant be changed
204 /// from the command line. The source code can change this setting with
205 /// the `checked' and `unchecked' statements and expressions.
207 public bool ConstantCheckState;
210 /// Whether we are emitting code inside a static or instance method
212 public bool IsStatic;
215 /// The value that is allowed to be returned or NULL if there is no
218 public Type ReturnType;
221 /// Points to the Type (extracted from the TypeContainer) that
222 /// declares this body of code
224 public Type ContainerType;
227 /// Whether this is generating code for a constructor
229 public bool IsConstructor;
232 /// Keeps track of the Type to LocalBuilder temporary storage created
233 /// to store structures (used to compute the address of the structure
234 /// value on structure method invocations)
236 public Hashtable temporary_storage;
238 public Block CurrentBlock;
241 /// The location where we store the return value.
243 LocalBuilder return_value;
246 /// The location where return has to jump to return the
249 public Label ReturnLabel;
252 /// Whether we are in a Finally block
254 public bool InFinally;
257 /// Whether we are in a Try block
262 /// Whether we are in a Catch block
267 /// Whether we are inside an unsafe block
269 public bool InUnsafe;
272 /// Location for this EmitContext
277 /// Used to "flag" the resolution process to only lookup types,
278 /// and nothing else. This is an out-of-band communication
279 /// path to SimpleName from the cast operation.
281 public bool OnlyLookupTypes;
284 /// Inside an enum definition, we do not resolve enumeration values
285 /// to their enumerations, but rather to the underlying type/value
286 /// This is so EnumVal + EnumValB can be evaluated.
288 /// There is no "E operator + (E x, E y)", so during an enum evaluation
289 /// we relax the rules
291 public bool InEnumContext;
293 public EmitContext (TypeContainer parent, DeclSpace ds, Location l, ILGenerator ig,
294 Type return_type, int code_flags, bool is_constructor)
298 TypeContainer = parent;
300 CheckState = RootContext.Checked;
301 ConstantCheckState = true;
303 IsStatic = (code_flags & Modifiers.STATIC) != 0;
304 ReturnType = return_type;
305 IsConstructor = is_constructor;
307 ContainerType = parent.TypeBuilder;
308 InUnsafe = ((parent.ModFlags | code_flags) & Modifiers.UNSAFE) != 0;
309 OnlyLookupTypes = false;
312 if (ReturnType == TypeManager.void_type)
316 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
317 Type return_type, int code_flags, bool is_constructor)
318 : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
322 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
323 Type return_type, int code_flags)
324 : this (tc, tc, l, ig, return_type, code_flags, false)
328 public void EmitTopBlock (Block block, Location loc)
330 bool has_ret = false;
332 // Console.WriteLine ("Emitting: " + loc);
334 if (CodeGen.SymbolWriter != null)
338 int errors = Report.Errors;
340 block.EmitMeta (this, block);
342 if (Report.Errors == errors){
343 if (!block.Resolve (this))
346 has_ret = block.Emit (this);
348 if (Report.Errors == errors){
349 if (RootContext.WarningLevel >= 3)
350 block.UsageWarning ();
355 if (ReturnType != null && !has_ret){
357 // FIXME: we need full flow analysis to implement this
358 // correctly and emit an error instead of a warning.
361 Report.Error (161, loc, "Not all code paths return a value");
365 if (return_value != null){
366 ig.MarkLabel (ReturnLabel);
367 ig.Emit (OpCodes.Ldloc, return_value);
368 ig.Emit (OpCodes.Ret);
372 ig.Emit (OpCodes.Ret);
378 /// This is called immediately before emitting an IL opcode to tell the symbol
379 /// writer to which source line this opcode belongs.
381 public void Mark (Location loc)
383 if (!Location.IsNull (loc)) {
384 ISymbolDocumentWriter doc = loc.SymbolDocument;
387 ig.MarkSequencePoint (doc, loc.Row, 0, loc.Row, 0);
392 /// Returns a temporary storage for a variable of type t as
393 /// a local variable in the current body.
395 public LocalBuilder GetTemporaryStorage (Type t)
397 LocalBuilder location;
399 if (temporary_storage != null){
400 location = (LocalBuilder) temporary_storage [t];
401 if (location != null)
405 location = ig.DeclareLocal (t);
410 public void FreeTemporaryStorage (LocalBuilder b)
416 /// Current loop begin and end labels.
418 public Label LoopBegin, LoopEnd;
421 /// Whether we are inside a loop and break/continue are possible.
426 /// Default target in a switch statement. Only valid if
429 public Label DefaultTarget;
432 /// If this is non-null, points to the current switch statement
434 public Switch Switch;
437 /// ReturnValue creates on demand the LocalBuilder for the
438 /// return value from the function. By default this is not
439 /// used. This is only required when returns are found inside
440 /// Try or Catch statements.
442 public LocalBuilder TemporaryReturn ()
444 if (return_value == null){
445 return_value = ig.DeclareLocal (ReturnType);
446 ReturnLabel = ig.DefineLabel ();
453 /// A dynamic This that is shared by all variables in a emitcontext.
454 /// Created on demand.
456 public Expression my_this;
457 public Expression This {
460 my_this = new This (loc).Resolve (this);