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 AppDomain current_domain;
23 AssemblyBuilder assembly_builder;
24 ModuleBuilder module_builder;
26 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 string TrimExt (string name)
44 int pos = name.LastIndexOf (".");
46 return name.Substring (0, pos);
49 public string FileName;
52 // This routine initializes the Mono runtime SymbolWriter.
54 void InitMonoSymbolWriter (string basename)
56 string symbol_output = basename + "-debug.s";
59 // Mono's default symbol writer ignores the first and third argument
62 SymbolWriter.Initialize (new IntPtr (0), symbol_output, true);
66 // Initializes the symbol writer
68 void InitializeSymbolWriter (string basename)
70 SymbolWriter = module_builder.GetSymWriter ();
73 // If we got an ISymbolWriter instance, initialize it.
75 if (SymbolWriter == null)
79 // Due to lacking documentation about the first argument of the
80 // Initialize method, we cannot use Microsoft's default symbol
83 // If we're using the mono symbol writer, the SymbolWriter object
84 // is of type MonoSymbolWriter - but that's defined in a dynamically
85 // loaded DLL - that's why we're doing a comparision based on the type
86 // name here instead of using `SymbolWriter is MonoSymbolWriter'.
88 Type sym_type = ((object) SymbolWriter).GetType ();
90 switch (sym_type.Name){
91 case "MonoSymbolWriter":
92 InitMonoSymbolWriter (basename);
97 -18, "Cannot generate debugging information on this platform");
102 public CodeGen (string name, string output, bool want_debugging_support)
107 an = new AssemblyName ();
108 an.Name = TrimExt (Basename (name));
109 current_domain = AppDomain.CurrentDomain;
110 assembly_builder = current_domain.DefineDynamicAssembly (
111 an, AssemblyBuilderAccess.RunAndSave);
114 // Pass a path-less name to DefineDynamicModule. Wonder how
115 // this copes with output in different directories then.
116 // FIXME: figure out how this copes with --output /tmp/blah
118 // If the third argument is true, the ModuleBuilder will dynamically
119 // load the default symbol writer.
121 module_builder = assembly_builder.DefineDynamicModule (
122 Basename (name), Basename (output), want_debugging_support);
124 if (want_debugging_support)
125 InitializeSymbolWriter (an.Name);
128 public AssemblyBuilder AssemblyBuilder {
130 return assembly_builder;
134 public ModuleBuilder ModuleBuilder {
136 return module_builder;
140 public void Save (string name)
143 assembly_builder.Save (Basename (name));
144 } catch (System.IO.IOException io){
145 Report.Error (16, "Coult not write to file `"+name+"', cause: " + io.Message);
149 public void SaveSymbols ()
151 if (SymbolWriter != null) {
152 // If we have a symbol writer, call its Close() method to write
153 // the symbol file to disk.
155 // When using Mono's default symbol writer, the Close() method must
156 // be called after the assembly has already been written to disk since
157 // it opens the assembly and reads its metadata.
158 SymbolWriter.Close ();
164 /// An Emit Context is created for each body of code (from methods,
165 /// properties bodies, indexer bodies or constructor bodies)
167 public class EmitContext {
168 public DeclSpace DeclSpace;
169 public TypeContainer TypeContainer;
170 public ILGenerator ig;
173 /// This variable tracks the `checked' state of the compilation,
174 /// it controls whether we should generate code that does overflow
175 /// checking, or if we generate code that ignores overflows.
177 /// The default setting comes from the command line option to generate
178 /// checked or unchecked code plus any source code changes using the
179 /// checked/unchecked statements or expressions. Contrast this with
180 /// the ConstantCheckState flag.
183 public bool CheckState;
186 /// The constant check state is always set to `true' and cant be changed
187 /// from the command line. The source code can change this setting with
188 /// the `checked' and `unchecked' statements and expressions.
190 public bool ConstantCheckState;
193 /// Whether we are emitting code inside a static or instance method
195 public bool IsStatic;
198 /// The value that is allowed to be returned or NULL if there is no
201 public Type ReturnType;
204 /// Points to the Type (extracted from the TypeContainer) that
205 /// declares this body of code
207 public Type ContainerType;
210 /// Whether this is generating code for a constructor
212 public bool IsConstructor;
215 /// Keeps track of the Type to LocalBuilder temporary storage created
216 /// to store structures (used to compute the address of the structure
217 /// value on structure method invocations)
219 public Hashtable temporary_storage;
221 public Block CurrentBlock;
224 /// The location where we store the return value.
226 LocalBuilder return_value;
229 /// The location where return has to jump to return the
232 public Label ReturnLabel;
235 /// Whether we are in a Finally block
237 public bool InFinally;
240 /// Whether we are in a Try block
245 /// Whether we are in a Catch block
250 /// Whether we are inside an unsafe block
252 public bool InUnsafe;
255 /// Location for this EmitContext
260 /// Used to "flag" the resolution process to only lookup types,
261 /// and nothing else. This is an out-of-band communication
262 /// path to SimpleName from the cast operation.
264 public bool OnlyLookupTypes;
266 public EmitContext (TypeContainer parent, DeclSpace ds, Location l, ILGenerator ig,
267 Type return_type, int code_flags, bool is_constructor)
271 TypeContainer = parent;
273 CheckState = RootContext.Checked;
274 ConstantCheckState = true;
276 IsStatic = (code_flags & Modifiers.STATIC) != 0;
277 ReturnType = return_type;
278 IsConstructor = is_constructor;
280 ContainerType = parent.TypeBuilder;
281 InUnsafe = ((parent.ModFlags | code_flags) & Modifiers.UNSAFE) != 0;
282 OnlyLookupTypes = false;
285 if (ReturnType == TypeManager.void_type)
289 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
290 Type return_type, int code_flags, bool is_constructor)
291 : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
295 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
296 Type return_type, int code_flags)
297 : this (tc, tc, l, ig, return_type, code_flags, false)
301 public void EmitTopBlock (Block block, Location loc)
303 bool has_ret = false;
305 // Console.WriteLine ("Emitting: " + loc);
307 if (RootContext.CodeGen.SymbolWriter != null)
311 int errors = Report.Errors;
313 block.EmitMeta (this, block);
315 if (Report.Errors == errors){
316 has_ret = block.Emit (this);
318 if (Report.Errors == errors){
319 if (RootContext.WarningLevel >= 3)
320 block.UsageWarning ();
325 if (ReturnType != null && !has_ret){
327 // FIXME: we need full flow analysis to implement this
328 // correctly and emit an error instead of a warning.
331 Report.Error (161, loc, "Not all code paths return a value");
335 if (return_value != null){
336 ig.MarkLabel (ReturnLabel);
337 ig.Emit (OpCodes.Ldloc, return_value);
338 ig.Emit (OpCodes.Ret);
342 ig.Emit (OpCodes.Ret);
348 /// This is called immediately before emitting an IL opcode to tell the symbol
349 /// writer to which source line this opcode belongs.
351 public void Mark (Location loc)
353 if (!Location.IsNull (loc)) {
354 ISymbolDocumentWriter doc = loc.SymbolDocument;
357 ig.MarkSequencePoint (doc, loc.Row, 0, loc.Row, 0);
362 /// Returns a temporary storage for a variable of type t as
363 /// a local variable in the current body.
365 public LocalBuilder GetTemporaryStorage (Type t)
367 LocalBuilder location;
369 if (temporary_storage != null){
370 location = (LocalBuilder) temporary_storage [t];
371 if (location != null)
375 location = ig.DeclareLocal (t);
380 public void FreeTemporaryStorage (LocalBuilder b)
386 /// Current loop begin and end labels.
388 public Label LoopBegin, LoopEnd;
391 /// Whether we are inside a loop and break/continue are possible.
396 /// Default target in a switch statement. Only valid if
399 public Label DefaultTarget;
402 /// If this is non-null, points to the current switch statement
404 public Switch Switch;
407 /// ReturnValue creates on demand the LocalBuilder for the
408 /// return value from the function. By default this is not
409 /// used. This is only required when returns are found inside
410 /// Try or Catch statements.
412 public LocalBuilder TemporaryReturn ()
414 if (return_value == null){
415 return_value = ig.DeclareLocal (ReturnType);
416 ReturnLabel = ig.DefineLabel ();
423 /// A dynamic This that is shared by all variables in a emitcontext.
424 /// Created on demand.
426 public Expression my_this;
427 public Expression This {
430 my_this = new This (loc).Resolve (this);