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;
283 public EmitContext (TypeContainer parent, DeclSpace ds, Location l, ILGenerator ig,
284 Type return_type, int code_flags, bool is_constructor)
288 TypeContainer = parent;
290 CheckState = RootContext.Checked;
291 ConstantCheckState = true;
293 IsStatic = (code_flags & Modifiers.STATIC) != 0;
294 ReturnType = return_type;
295 IsConstructor = is_constructor;
297 ContainerType = parent.TypeBuilder;
298 InUnsafe = ((parent.ModFlags | code_flags) & Modifiers.UNSAFE) != 0;
299 OnlyLookupTypes = false;
302 if (ReturnType == TypeManager.void_type)
306 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
307 Type return_type, int code_flags, bool is_constructor)
308 : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
312 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
313 Type return_type, int code_flags)
314 : this (tc, tc, l, ig, return_type, code_flags, false)
318 public void EmitTopBlock (Block block, Location loc)
320 bool has_ret = false;
322 // Console.WriteLine ("Emitting: " + loc);
324 if (CodeGen.SymbolWriter != null)
328 int errors = Report.Errors;
330 block.EmitMeta (this, block);
332 if (Report.Errors == errors){
333 has_ret = block.Emit (this);
335 if (Report.Errors == errors){
336 if (RootContext.WarningLevel >= 3)
337 block.UsageWarning ();
342 if (ReturnType != null && !has_ret){
344 // FIXME: we need full flow analysis to implement this
345 // correctly and emit an error instead of a warning.
348 Report.Error (161, loc, "Not all code paths return a value");
352 if (return_value != null){
353 ig.MarkLabel (ReturnLabel);
354 ig.Emit (OpCodes.Ldloc, return_value);
355 ig.Emit (OpCodes.Ret);
359 ig.Emit (OpCodes.Ret);
365 /// This is called immediately before emitting an IL opcode to tell the symbol
366 /// writer to which source line this opcode belongs.
368 public void Mark (Location loc)
370 if (!Location.IsNull (loc)) {
371 ISymbolDocumentWriter doc = loc.SymbolDocument;
374 ig.MarkSequencePoint (doc, loc.Row, 0, loc.Row, 0);
379 /// Returns a temporary storage for a variable of type t as
380 /// a local variable in the current body.
382 public LocalBuilder GetTemporaryStorage (Type t)
384 LocalBuilder location;
386 if (temporary_storage != null){
387 location = (LocalBuilder) temporary_storage [t];
388 if (location != null)
392 location = ig.DeclareLocal (t);
397 public void FreeTemporaryStorage (LocalBuilder b)
403 /// Current loop begin and end labels.
405 public Label LoopBegin, LoopEnd;
408 /// Whether we are inside a loop and break/continue are possible.
413 /// Default target in a switch statement. Only valid if
416 public Label DefaultTarget;
419 /// If this is non-null, points to the current switch statement
421 public Switch Switch;
424 /// ReturnValue creates on demand the LocalBuilder for the
425 /// return value from the function. By default this is not
426 /// used. This is only required when returns are found inside
427 /// Try or Catch statements.
429 public LocalBuilder TemporaryReturn ()
431 if (return_value == null){
432 return_value = ig.DeclareLocal (ReturnType);
433 ReturnLabel = ig.DefineLabel ();
440 /// A dynamic This that is shared by all variables in a emitcontext.
441 /// Created on demand.
443 public Expression my_this;
444 public Expression This {
447 my_this = new This (loc).Resolve (this);