2005-01-22 Miguel de Icaza <miguel@ximian.com>
[mono.git] / mono / mini / driver.c
1 /*
2  * driver.c: The new mono JIT compiler.
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * (C) 2002-2003 Ximian, Inc.
9  * (C) 2003-2004 Novell, Inc.
10  */
11
12 #include <config.h>
13 #include <signal.h>
14 #include <unistd.h>
15
16 #include <mono/metadata/assembly.h>
17 #include <mono/metadata/loader.h>
18 #include <mono/metadata/cil-coff.h>
19 #include <mono/metadata/tabledefs.h>
20 #include <mono/metadata/class.h>
21 #include <mono/metadata/object.h>
22 #include <mono/metadata/exception.h>
23 #include <mono/metadata/opcodes.h>
24 #include <mono/metadata/mono-endian.h>
25 #include <mono/metadata/tokentype.h>
26 #include <mono/metadata/tabledefs.h>
27 #include <mono/metadata/threads.h>
28 #include <mono/metadata/marshal.h>
29 #include <mono/metadata/socket-io.h>
30 #include <mono/metadata/appdomain.h>
31 #include <mono/metadata/debug-helpers.h>
32 #include <mono/io-layer/io-layer.h>
33 #include "mono/metadata/profiler.h"
34 #include <mono/metadata/profiler-private.h>
35 #include <mono/metadata/mono-config.h>
36 #include <mono/metadata/environment.h>
37 #include <mono/metadata/verify.h>
38 #include <mono/metadata/mono-debug.h>
39 #include <mono/metadata/mono-debug-debugger.h>
40 #include <mono/os/gc_wrapper.h>
41
42 #include "mini.h"
43 #include "jit.h"
44 #include <string.h>
45 #include <ctype.h>
46 #include "inssel.h"
47 #include <locale.h>
48
49 static FILE *mini_stats_fd = NULL;
50
51 static void mini_usage (void);
52
53 typedef void (*OptFunc) (const char *p);
54
55 /* keep in sync with enum in mini.h */
56 typedef struct {
57         const char* name;
58         const char* desc;
59         const OptFunc func;
60 } OptName;
61
62 static const OptName 
63 opt_names [] = {
64         {"peephole", "Peephole postpass"},
65         {"branch",   "Branch optimizations"},
66         {"inline",   "Inline method calls"},
67         {"cfold",    "Constant folding"},
68         {"consprop", "Constant propagation"},
69         {"copyprop", "Copy propagation"},
70         {"deadce",   "Dead code elimination"},
71         {"linears",  "Linear scan global reg allocation"},
72         {"cmov",     "Conditional moves"},
73         {"shared",   "Emit per-domain code"},
74         {"sched",    "Instruction scheduling"},
75         {"intrins",  "Intrinsic method implementations"},
76         {"tailc",    "Tail recursion and tail calls"},
77         {"loop",     "Loop related optimizations"},
78         {"fcmov",    "Fast x86 FP compares"},
79         {"leaf",     "Leaf procedures optimizations"},
80         {"aot",      "Usage of Ahead Of Time compiled code"},
81         {"precomp",  "Precompile all methods before executing Main"},
82         {"abcrem",   "Array bound checks removal"},     
83         {"ssapre",   "SSA based Partial Redundancy Elimination"}
84 };
85
86 #define DEFAULT_OPTIMIZATIONS ( \
87         MONO_OPT_PEEPHOLE |     \
88         MONO_OPT_CFOLD |        \
89         MONO_OPT_BRANCH |       \
90         MONO_OPT_LINEARS |      \
91         MONO_OPT_INTRINS |  \
92         MONO_OPT_LOOP |  \
93         MONO_OPT_AOT)
94
95 /* SSAPRE does not work correctly on non x86 platforms (bug #70637) */
96 #define EXCLUDED_FROM_ALL (MONO_OPT_SHARED | MONO_OPT_PRECOMP)
97
98 static guint32
99 parse_optimizations (const char* p)
100 {
101         /* the default value */
102         guint32 opt = DEFAULT_OPTIMIZATIONS;
103         guint32 exclude = 0;
104         const char *n;
105         int i, invert, len;
106
107         /* call out to cpu detection code here that sets the defaults ... */
108         opt |= mono_arch_cpu_optimizazions (&exclude);
109         opt &= ~exclude;
110         if (!p)
111                 return opt;
112
113         while (*p) {
114                 if (*p == '-') {
115                         p++;
116                         invert = TRUE;
117                 } else {
118                         invert = FALSE;
119                 }
120                 for (i = 0; i < G_N_ELEMENTS (opt_names); ++i) {
121                         n = opt_names [i].name;
122                         len = strlen (n);
123                         if (strncmp (p, n, len) == 0) {
124                                 if (invert)
125                                         opt &= ~ (1 << i);
126                                 else
127                                         opt |= 1 << i;
128                                 p += len;
129                                 if (*p == ',') {
130                                         p++;
131                                         break;
132                                 } else if (*p == '=') {
133                                         p++;
134                                         if (opt_names [i].func)
135                                                 opt_names [i].func (p);
136                                         while (*p && *p++ != ',');
137                                         break;
138                                 }
139                                 /* error out */
140                                 break;
141                         }
142                 }
143                 if (i == G_N_ELEMENTS (opt_names)) {
144                         if (strncmp (p, "all", 3) == 0) {
145                                 if (invert)
146                                         opt = 0;
147                                 else
148                                         opt = ~(EXCLUDED_FROM_ALL | exclude);
149                                 p += 3;
150                                 if (*p == ',')
151                                         p++;
152                         } else {
153                                 fprintf (stderr, "Invalid optimization name `%s'\n", p);
154                                 exit (1);
155                         }
156                 }
157         }
158         return opt;
159 }
160
161 typedef struct {
162         const char* name;
163         const char* desc;
164         MonoGraphOptions value;
165 } GraphName;
166
167 static const GraphName 
168 graph_names [] = {
169         {"cfg",      "Control Flow Graph (CFG)" ,               MONO_GRAPH_CFG},
170         {"dtree",    "Dominator Tree",                          MONO_GRAPH_DTREE},
171         {"code",     "CFG showing code",                        MONO_GRAPH_CFG_CODE},
172         {"ssa",      "CFG showing code after SSA translation",  MONO_GRAPH_CFG_SSA},
173         {"optcode",  "CFG showing code after IR optimizations", MONO_GRAPH_CFG_OPTCODE}
174 };
175
176 static MonoGraphOptions
177 mono_parse_graph_options (const char* p)
178 {
179         const char *n;
180         int i, len;
181
182         for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
183                 n = graph_names [i].name;
184                 len = strlen (n);
185                 if (strncmp (p, n, len) == 0)
186                         return graph_names [i].value;
187         }
188
189         fprintf (stderr, "Invalid graph name provided: %s\n", p);
190         exit (1);
191 }
192
193 int
194 mono_parse_default_optimizations (const char* p)
195 {
196         guint32 opt;
197
198         opt = parse_optimizations (p);
199         return opt;
200 }
201
202 static char*
203 opt_descr (guint32 flags) {
204         GString *str = g_string_new ("");
205         int i, need_comma;
206
207         need_comma = 0;
208         for (i = 0; i < G_N_ELEMENTS (opt_names); ++i) {
209                 if (flags & (1 << i)) {
210                         if (need_comma)
211                                 g_string_append_c (str, ',');
212                         g_string_append (str, opt_names [i].name);
213                         need_comma = 1;
214                 }
215         }
216         return g_string_free (str, FALSE);
217 }
218
219 static const guint32
220 opt_sets [] = {
221        0,
222        MONO_OPT_PEEPHOLE,
223        MONO_OPT_BRANCH,
224        MONO_OPT_CFOLD,
225        MONO_OPT_FCMOV,
226        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_INTRINS,
227        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS,
228        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP,
229        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_CFOLD,
230        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE,
231        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS,
232        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_ABCREM,
233        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_SSAPRE,
234        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_ABCREM | MONO_OPT_SHARED
235 };
236
237 typedef int (*TestMethod) (void);
238
239 #if 0
240 static void
241 domain_dump_native_code (MonoDomain *domain) {
242         // need to poke into the domain, move to metadata/domain.c
243         // need to empty jit_info_table and code_mp
244 }
245 #endif
246
247 static int
248 mini_regression (MonoImage *image, int verbose, int *total_run) {
249         guint32 i, opt, opt_flags;
250         MonoMethod *method;
251         MonoCompile *cfg;
252         char *n;
253         int result, expected, failed, cfailed, run, code_size, total;
254         TestMethod func;
255         GTimer *timer = g_timer_new ();
256
257         if (mini_stats_fd) {
258                 fprintf (mini_stats_fd, "$stattitle = \'Mono Benchmark Results (various optimizations)\';\n");
259
260                 fprintf (mini_stats_fd, "$graph->set_legend(qw(");
261                 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); opt++) {
262                         opt_flags = opt_sets [opt];
263                         n = opt_descr (opt_flags);
264                         if (!n [0])
265                                 n = (char *)"none";
266                         if (opt)
267                                 fprintf (mini_stats_fd, " ");
268                         fprintf (mini_stats_fd, "%s", n);
269                 
270
271                 }
272                 fprintf (mini_stats_fd, "));\n");
273
274                 fprintf (mini_stats_fd, "@data = (\n");
275                 fprintf (mini_stats_fd, "[");
276         }
277
278         /* load the metadata */
279         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
280                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
281                 mono_class_init (method->klass);
282
283                 if (!strncmp (method->name, "test_", 5) && mini_stats_fd) {
284                         fprintf (mini_stats_fd, "\"%s\",", method->name);
285                 }
286         }
287         if (mini_stats_fd)
288                 fprintf (mini_stats_fd, "],\n");
289
290
291         total = 0;
292         *total_run = 0;
293         for (opt = 0; opt < G_N_ELEMENTS (opt_sets); ++opt) {
294                 double elapsed, comp_time, start_time;
295                 MonoJitInfo *jinfo;
296
297                 opt_flags = opt_sets [opt];
298                 mono_set_defaults (verbose, opt_flags);
299                 n = opt_descr (opt_flags);
300                 g_print ("Test run: image=%s, opts=%s\n", mono_image_get_filename (image), n);
301                 g_free (n);
302                 cfailed = failed = run = code_size = 0;
303                 comp_time = elapsed = 0.0;
304
305                 /* fixme: ugly hack - delete all previously compiled methods */
306                 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
307                         method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
308                         method->info = NULL;
309                 }
310
311                 g_timer_start (timer);
312                 if (mini_stats_fd)
313                         fprintf (mini_stats_fd, "[");
314                 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
315                         method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
316                         if (strncmp (method->name, "test_", 5) == 0) {
317                                 expected = atoi (method->name + 5);
318                                 run++;
319                                 start_time = g_timer_elapsed (timer, NULL);
320                                 comp_time -= start_time; 
321                                 cfg = mini_method_compile (method, opt_flags, mono_get_root_domain (), TRUE, FALSE, 0);
322                                 comp_time += g_timer_elapsed (timer, NULL);
323                                 if (cfg) {
324                                         if (verbose >= 2)
325                                                 g_print ("Running '%s' ...\n", method->name);
326 #ifdef MONO_USE_AOT_COMPILER
327                                         if ((jinfo = mono_aot_get_method (mono_get_root_domain (), method)))
328                                                 func = jinfo->code_start;
329                                         else
330 #endif
331                                                 func = (TestMethod)cfg->native_code;
332                                         result = func ();
333                                         if (result != expected) {
334                                                 failed++;
335                                                 if (verbose)
336                                                         g_print ("Test '%s' failed result (got %d, expected %d).\n", method->name, result, expected);
337                                         }
338                                         code_size += cfg->code_len;
339                                         mono_destroy_compile (cfg);
340
341                                 } else {
342                                         cfailed++;
343                                         if (verbose)
344                                                 g_print ("Test '%s' failed compilation.\n", method->name);
345                                 }
346                                 if (mini_stats_fd)
347                                         fprintf (mini_stats_fd, "%f, ", 
348                                                  g_timer_elapsed (timer, NULL) - start_time);
349                         }
350                 }
351                 if (mini_stats_fd)
352                         fprintf (mini_stats_fd, "],\n");
353                 g_timer_stop (timer);
354                 elapsed = g_timer_elapsed (timer, NULL);
355                 g_print ("Results: total tests: %d, failed: %d, cfailed: %d (pass: %.2f%%)\n", 
356                         run, failed, cfailed, 100.0*(run-failed-cfailed)/run);
357                 g_print ("Elapsed time: %f secs (%f, %f), Code size: %d\n\n", elapsed, 
358                          elapsed - comp_time, comp_time, code_size);
359                 total += failed + cfailed;
360                 *total_run += run;
361         }
362
363         if (mini_stats_fd) {
364                 fprintf (mini_stats_fd, ");\n");
365                 fflush (mini_stats_fd);
366         }
367
368         g_timer_destroy (timer);
369         return total;
370 }
371
372 static int
373 mini_regression_list (int verbose, int count, char *images [])
374 {
375         int i, total, total_run, run;
376         MonoAssembly *ass;
377         
378         total_run =  total = 0;
379         for (i = 0; i < count; ++i) {
380                 ass = mono_assembly_open (images [i], NULL);
381                 if (!ass) {
382                         g_warning ("failed to load assembly: %s", images [i]);
383                         continue;
384                 }
385                 total += mini_regression (mono_assembly_get_image (ass), verbose, &run);
386                 total_run += run;
387         }
388         g_print ("Overall results: tests: %d, failed: %d, opt combinations: %d (pass: %.2f%%)\n", 
389                 total_run, total, (int)G_N_ELEMENTS (opt_sets), 100.0*(total_run-total)/total_run);
390         return total;
391 }
392
393 enum {
394         DO_BENCH,
395         DO_REGRESSION,
396         DO_COMPILE,
397         DO_EXEC,
398         DO_DRAW
399 };
400
401 typedef struct CompileAllThreadArgs {
402         MonoAssembly *ass;
403         int verbose;
404 } CompileAllThreadArgs;
405
406 static void
407 compile_all_methods_thread_main (CompileAllThreadArgs *args)
408 {
409         MonoAssembly *ass = args->ass;
410         int verbose = args->verbose;
411         MonoImage *image = mono_assembly_get_image (ass);
412         MonoMethod *method;
413         int i, count = 0;
414
415         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
416                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
417                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
418                         continue;
419                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
420                         continue;
421
422                 count++;
423                 if (verbose) {
424                         char * desc = mono_method_full_name (method, TRUE);
425                         g_print ("Compiling %d %s\n", count, desc);
426                         g_free (desc);
427                 }
428                 mono_compile_method (method);
429         }
430
431 }
432
433 static void
434 compile_all_methods (MonoAssembly *ass, int verbose)
435 {
436         CompileAllThreadArgs args;
437
438         args.ass = ass;
439         args.verbose = verbose;
440
441         /* 
442          * Need to create a mono thread since compilation might trigger
443          * running of managed code.
444          */
445         mono_thread_create (mono_domain_get (), compile_all_methods_thread_main, &args);
446
447         mono_thread_manage ();
448 }
449
450 /**
451  * mono_jit_exec:
452  * @assembly: reference to an assembly
453  * @argc: argument count
454  * @argv: argument vector
455  *
456  * Start execution of a program.
457  */
458 int 
459 mono_jit_exec (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])
460 {
461         MonoImage *image = mono_assembly_get_image (assembly);
462         MonoMethod *method;
463         guint32 entry = mono_image_get_entry_point (image);
464
465         if (!entry) {
466                 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
467                 /* FIXME: remove this silly requirement. */
468                 mono_environment_exitcode_set (1);
469                 return 1;
470         }
471
472         method = mono_get_method (image, entry, NULL);
473
474         return mono_runtime_run_main (method, argc, argv, NULL);
475 }
476
477 typedef struct 
478 {
479         MonoDomain *domain;
480         const char *file;
481         int argc;
482         char **argv;
483         guint32 opts;
484         char *aot_options;
485 } MainThreadArgs;
486
487 static void main_thread_handler (gpointer user_data)
488 {
489         MainThreadArgs *main_args = user_data;
490         MonoAssembly *assembly;
491
492         assembly = mono_domain_assembly_open (main_args->domain, main_args->file);
493         if (!assembly){
494                 fprintf (stderr, "Can not open image %s\n", main_args->file);
495                 exit (1);
496         }
497
498         if (mono_compile_aot) {
499                 int res = mono_compile_assembly (assembly, main_args->opts, main_args->aot_options);
500                 printf ("AOT RESULT %d\n", res);
501         } else {
502                 /* 
503                  * This must be done in a thread managed by mono since it can invoke
504                  * managed code.
505                  */
506                 if (main_args->opts & MONO_OPT_PRECOMP)
507                         mono_precompile_assemblies ();
508
509                 mono_jit_exec (main_args->domain, assembly, main_args->argc, main_args->argv);
510         }
511 }
512
513 static void
514 mini_usage_jitdeveloper ()
515 {
516         int i;
517         
518         fprintf (stdout,
519                  "Runtime and JIT debugging options:\n"
520                  "    --breakonex            Inserts a breakpoint on exceptions\n"
521                  "    --break METHOD         Inserts a breakpoint at METHOD entry\n"
522                  "    --compile METHOD       Just compile METHOD in assembly\n"
523                  "    --compile-all          Compiles all the methods in the assembly\n"
524                  "    --ncompile N           Number of times to compile METHOD (default: 1)\n"
525                  "    --print-vtable         Print the vtable of all used classes\n"
526                  "    --regression           Runs the regression test contained in the assembly\n"
527                  "    --statfile FILE        Sets the stat file to FILE\n"
528                  "    --stats                Print statistics about the JIT operations\n"
529                  "\n"
530                  "Other options:\n" 
531                  "    --graph[=TYPE] METHOD  Draws a graph of the specified method:\n");
532         
533         for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
534                 fprintf (stdout, "                           %-10s %s\n", graph_names [i].name, graph_names [i].desc);
535         }
536 }
537
538 static void
539 mini_usage_list_opt ()
540 {
541         int i;
542         
543         for (i = 0; i < G_N_ELEMENTS (opt_names); ++i)
544                 fprintf (stdout, "                           %-10s %s\n", opt_names [i].name, opt_names [i].desc);
545 }
546
547 static void
548 mini_usage (void)
549 {
550         fprintf (stdout,
551                 "Usage is: mono [options] program [program-options]\n"
552                 "\n"
553                 "Development:\n"
554                 "    --aot                  Compiles the assembly to native code\n"
555                 "    --debug                Enable debugging support\n"
556                 "    --profile[=profiler]   Runs in profiling mode with the specified profiler module\n"
557                 "    --trace[=EXPR]         Enable tracing, use --help-trace for details\n"
558                 "    --help-devel           Shows more options available to developers\n"
559                 "\n"
560                 "Runtime:\n"
561                 "    --config FILE          Loads FILE as the Mono config\n"
562                 "    --verbose, -v          Increases the verbosity level\n"
563                 "    --help, -h             Show usage information\n"
564                 "    --version, -V          Show version information\n"
565                 "    --optimize=OPT         Turns on or off a specific optimization\n"
566                 "                           Use --list-opt to get a list of optimizations\n"
567                 "    --security             Turns on the security manager (unsupported, default is off)\n");
568 }
569
570 static void
571 mini_trace_usage (void)
572 {
573         fprintf (stdout,
574                  "Tracing options:\n"
575                  "   --trace[=EXPR]        Trace every call, optional EXPR controls the scope\n"
576                  "\n"
577                  "EXPR is composed of:\n"
578                  "    all                  All assemblies\n"
579                  "    none                 No assemblies\n"
580                  "    program              Entry point assembly\n"
581                  "    assembly             Specifies an assembly\n"
582                  "    M:Type:Method        Specifies a method\n"
583                  "    N:Namespace          Specifies a namespace\n"
584                  "    T:Type               Specifies a type\n"
585                  "    +EXPR                Includes expression\n"
586                  "    -EXPR                Excludes expression\n");
587 }
588
589 static const char *info = ""
590 #ifdef HAVE_KW_THREAD
591         "\tTLS:           __thread\n"
592 #else
593         "\tTLS:           normal\n"
594 #endif /* HAVE_KW_THREAD */
595 #ifdef HAVE_BOEHM_GC
596 #ifdef USE_INCLUDED_LIBGC
597         "\tGC:            Included Boehm (with typed GC)\n"
598 #else
599 #if HAVE_GC_GCJ_MALLOC
600         "\tGC:            System Boehm (with typed GC)\n"
601 #else
602         "\tGC:            System Boehm (no typed GC available)\n"
603 #endif
604 #endif
605 #else
606         "\tGC:            none\n"
607 #endif /* HAVE_BOEHM_GC */
608 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
609     "\tSIGSEGV      : altstack\n"
610 #else
611     "\tSIGSEGV      : normal\n"
612 #endif
613 #ifdef HAVE_ICU
614         "\tGlobalization: ICU\n"
615 #else
616         "\tGlobalization: none\n"
617 #endif /* HAVE_ICU */
618         "";
619
620 int
621 mono_main (int argc, char* argv[])
622 {
623         MainThreadArgs main_args;
624         MonoAssembly *assembly;
625         MonoMethodDesc *desc;
626         MonoMethod *method;
627         MonoCompile *cfg;
628         MonoDomain *domain;
629         const char* aname, *mname = NULL;
630         char *config_file = NULL;
631         int i, count = 1;
632         int enable_debugging = FALSE;
633         guint32 opt, action = DO_EXEC;
634         MonoGraphOptions mono_graph_options = 0;
635         int mini_verbose = 0;
636         gboolean enable_profile = FALSE;
637         char *trace_options = NULL;
638         char *profile_options = NULL;
639         char *aot_options = NULL;
640
641         setlocale (LC_ALL, "");
642
643         g_log_set_always_fatal (G_LOG_LEVEL_ERROR);
644         g_log_set_fatal_mask (G_LOG_DOMAIN, G_LOG_LEVEL_ERROR);
645
646         opt = parse_optimizations (NULL);
647
648         for (i = 1; i < argc; ++i) {
649                 if (argv [i] [0] != '-')
650                         break;
651                 if (strcmp (argv [i], "--regression") == 0) {
652                         action = DO_REGRESSION;
653                 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
654                         mini_verbose++;
655                 } else if (strcmp (argv [i], "--version") == 0 || strcmp (argv [i], "-V") == 0) {
656                         g_print ("Mono JIT compiler version %s, (C) 2002-2004 Novell, Inc and Contributors. www.go-mono.com\n", VERSION);
657                         g_print (info);
658                         if (mini_verbose) {
659                                 const guchar *cerror;
660                                 const guchar *clibpath;
661                                 mono_init ("mono");
662                                 cerror = mono_check_corlib_version ();
663                                 clibpath = mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown";
664                                 if (cerror) {
665                                         g_print ("The currently installed mscorlib doesn't match this runtime version.\n");
666                                         g_print ("The error is: %s\n", cerror);
667                                         g_print ("mscorlib.dll loaded at: %s\n", clibpath);
668                                         return 1;
669                                 }
670                         }
671                         return 0;
672                 } else if (strcmp (argv [i], "--help") == 0 || strcmp (argv [i], "-h") == 0) {
673                         mini_usage ();
674                         return 0;
675                 } else if (strcmp (argv [i], "--help-trace") == 0){
676                         mini_trace_usage ();
677                         return 0;
678                 } else if (strcmp (argv [i], "--help-devel") == 0){
679                         mini_usage_jitdeveloper ();
680                         return 0;
681                 } else if (strcmp (argv [i], "--list-opt") == 0){
682                         mini_usage_list_opt ();
683                         return 0;
684                 } else if (strncmp (argv [i], "--statfile", 10) == 0) {
685                         mini_stats_fd = fopen (argv [++i], "w+");
686                 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
687                         opt = parse_optimizations (argv [i] + 11);
688                 } else if (strncmp (argv [i], "-O=", 3) == 0) {
689                         opt = parse_optimizations (argv [i] + 3);
690                 } else if (strcmp (argv [i], "--config") == 0) {
691                         config_file = argv [++i];
692                 } else if (strcmp (argv [i], "--ncompile") == 0) {
693                         count = atoi (argv [++i]);
694                         action = DO_BENCH;
695                 } else if (strcmp (argv [i], "--trace") == 0) {
696                         trace_options = (char*)"";
697                 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
698                         trace_options = &argv [i][8];
699                 } else if (strcmp (argv [i], "--breakonex") == 0) {
700                         mono_break_on_exc = TRUE;
701                 } else if (strcmp (argv [i], "--break") == 0) {
702                         if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
703                                 g_error ("Invalid method name '%s'", argv [i]);
704                 } else if (strcmp (argv [i], "--print-vtable") == 0) {
705                         mono_print_vtable = TRUE;
706                 } else if (strcmp (argv [i], "--stats") == 0) {
707                         mono_stats.enabled = TRUE;
708                         mono_jit_stats.enabled = TRUE;
709 #ifndef DISABLE_AOT
710                 } else if (strcmp (argv [i], "--aot") == 0) {
711                         mono_compile_aot = TRUE;
712                 } else if (strncmp (argv [i], "--aot=", 6) == 0) {
713                         mono_compile_aot = TRUE;
714                         aot_options = &argv [i][6];
715 #endif
716                 } else if (strcmp (argv [i], "--compile-all") == 0) {
717                         action = DO_COMPILE;
718                 } else if (strcmp (argv [i], "--profile") == 0) {
719                         enable_profile = TRUE;
720                         profile_options = NULL;
721                 } else if (strncmp (argv [i], "--profile=", 10) == 0) {
722                         enable_profile = TRUE;
723                         profile_options = argv [i] + 10;
724                 } else if (strcmp (argv [i], "--compile") == 0) {
725                         mname = argv [++i];
726                         action = DO_BENCH;
727                 } else if (strncmp (argv [i], "--graph=", 8) == 0) {
728                         mono_graph_options = mono_parse_graph_options (argv [i] + 8);
729                         mname = argv [++i];
730                         action = DO_DRAW;
731                 } else if (strcmp (argv [i], "--graph") == 0) {
732                         mname = argv [++i];
733                         mono_graph_options = MONO_GRAPH_CFG;
734                         action = DO_DRAW;
735                 } else if (strcmp (argv [i], "--debug") == 0) {
736                         enable_debugging = TRUE;
737                 } else if (strcmp (argv [i], "--security") == 0) {
738                         mono_use_security_manager = TRUE;
739                 } else {
740                         fprintf (stderr, "Unknown command line option: '%s'\n", argv [i]);
741                         return 1;
742                 }
743         }
744
745         if (!argv [i]) {
746                 mini_usage ();
747                 return 1;
748         }
749
750         if (mono_compile_aot || action == DO_EXEC) {
751                 g_set_prgname (argv[i]);
752         }
753
754         if (enable_profile) {
755                 /* Needed because of TLS accesses in mono_profiler_load () */
756                 MONO_GC_PRE_INIT ();
757                 mono_profiler_load (profile_options);
758         }
759
760         if (trace_options != NULL){
761                 /* 
762                  * Need to call this before mini_init () so we can trace methods 
763                  * compiled there too.
764                  */
765                 mono_jit_trace_calls = mono_trace_parse_options (trace_options);
766                 if (mono_jit_trace_calls == NULL)
767                         exit (1);
768         }
769
770         if (mono_compile_aot && mono_use_security_manager) {
771                 mono_use_security_manager = FALSE;
772                 g_warning ("Current security manager implementation isn't compatible with AOT - disabling security manager.");
773         }
774
775         mono_set_defaults (mini_verbose, opt);
776         domain = mini_init (argv [i]);
777         
778         switch (action) {
779         case DO_REGRESSION:
780                 if (mini_regression_list (mini_verbose, argc -i, argv + i)) {
781                         g_print ("Regression ERRORS!\n");
782                         mini_cleanup (domain);
783                         return 1;
784                 }
785                 mini_cleanup (domain);
786                 return 0;
787         case DO_BENCH:
788                 if (argc - i != 1 || mname == NULL) {
789                         g_print ("Usage: mini --ncompile num --compile method assembly\n");
790                         mini_cleanup (domain);
791                         return 1;
792                 }
793                 aname = argv [i];
794                 break;
795         case DO_COMPILE:
796                 if (argc - i != 1) {
797                         mini_usage ();
798                         mini_cleanup (domain);
799                         return 1;
800                 }
801                 aname = argv [i];
802                 break;
803         case DO_DRAW:
804                 if (argc - i != 1 || mname == NULL) {
805                         mini_usage ();
806                         mini_cleanup (domain);
807                         return 1;
808                 }
809                 aname = argv [i];
810                 break;
811         default:
812                 if (argc - i < 1) {
813                         mini_usage ();
814                         mini_cleanup (domain);
815                         return 1;
816                 }
817                 aname = argv [i];
818                 break;
819         }
820
821         if (enable_debugging) {
822                 mono_debug_init (MONO_DEBUG_FORMAT_MONO);
823                 mono_debug_init_1 (domain);
824         }
825
826         /* Parse gac loading options before loading assemblies. */
827         if (mono_compile_aot || action == DO_EXEC) {
828                 mono_config_parse (config_file);
829         }
830
831         assembly = mono_assembly_open (aname, NULL);
832         if (!assembly) {
833                 fprintf (stderr, "cannot open assembly %s\n", aname);
834                 mini_cleanup (domain);
835                 return 2;
836         }
837
838         if (trace_options != NULL)
839                 mono_trace_set_assembly (assembly);
840
841         if (enable_debugging)
842                 mono_debug_init_2 (assembly);
843
844         if (mono_compile_aot || action == DO_EXEC) {
845                 const guchar *error;
846
847                 //mono_set_rootdir ();
848
849                 error = mono_check_corlib_version ();
850                 if (error) {
851                         fprintf (stderr, "Corlib not in sync with this runtime: %s\n", error);
852                         fprintf (stderr, "Download a newer corlib or a newer runtime at http://www.go-mono.com/daily.\n");
853                         exit (1);
854                 }
855
856                 main_args.domain = domain;
857                 main_args.file = aname;         
858                 main_args.argc = argc - i;
859                 main_args.argv = argv + i;
860                 main_args.opts = opt;
861                 main_args.aot_options = aot_options;
862 #if RUN_IN_SUBTHREAD
863                 mono_runtime_exec_managed_code (domain, main_thread_handler, &main_args);
864 #else
865                 main_thread_handler (&main_args);
866                 mono_thread_manage ();
867 #endif
868                 mini_cleanup (domain);
869
870                 /* Look up return value from System.Environment.ExitCode */
871                 i = mono_environment_exitcode_get ();
872                 return i;
873         } else if (action == DO_COMPILE) {
874                 compile_all_methods (assembly, mini_verbose);
875                 mini_cleanup (domain);
876                 return 0;
877         }
878         desc = mono_method_desc_new (mname, 0);
879         if (!desc) {
880                 g_print ("Invalid method name %s\n", mname);
881                 mini_cleanup (domain);
882                 return 3;
883         }
884         method = mono_method_desc_search_in_image (desc, mono_assembly_get_image (assembly));
885         if (!method) {
886                 g_print ("Cannot find method %s\n", mname);
887                 mini_cleanup (domain);
888                 return 3;
889         }
890
891         if (action == DO_DRAW) {
892                 int part = 0;
893
894                 switch (mono_graph_options) {
895                 case MONO_GRAPH_DTREE:
896                         part = 1;
897                         opt |= MONO_OPT_LOOP;
898                         break;
899                 case MONO_GRAPH_CFG_CODE:
900                         part = 1;
901                         break;
902                 case MONO_GRAPH_CFG_SSA:
903                         part = 2;
904                         break;
905                 case MONO_GRAPH_CFG_OPTCODE:
906                         part = 3;
907                         break;
908                 default:
909                         break;
910                 }
911
912                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
913                         (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
914                         MonoMethod *nm;
915                         nm = mono_marshal_get_native_wrapper (method);
916                         cfg = mini_method_compile (nm, opt, mono_get_root_domain (), FALSE, FALSE, part);
917                 }
918                 else
919                         cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, part);
920                 if ((mono_graph_options & MONO_GRAPH_CFG_SSA) && !(cfg->comp_done & MONO_COMP_SSA)) {
921                         g_warning ("no SSA info available (use -O=deadce)");
922                         return 1;
923                 }
924                 mono_draw_graph (cfg, mono_graph_options);
925                 mono_destroy_compile (cfg);
926
927         } else if (action == DO_BENCH) {
928                 if (mini_stats_fd) {
929                         const char *n;
930                         double no_opt_time = 0.0;
931                         GTimer *timer = g_timer_new ();
932                         fprintf (mini_stats_fd, "$stattitle = \'Compilations times for %s\';\n", 
933                                  mono_method_full_name (method, TRUE));
934                         fprintf (mini_stats_fd, "@data = (\n");
935                         fprintf (mini_stats_fd, "[");
936                         for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
937                                 opt = opt_sets [i];
938                                 n = opt_descr (opt);
939                                 if (!n [0])
940                                         n = "none";
941                                 fprintf (mini_stats_fd, "\"%s\",", n);
942                         }
943                         fprintf (mini_stats_fd, "],\n[");
944
945                         for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
946                                 int j;
947                                 double elapsed;
948                                 opt = opt_sets [i];
949                                 g_timer_start (timer);
950                                 for (j = 0; j < count; ++j) {
951                                         cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
952                                         mono_destroy_compile (cfg);
953                                 }
954                                 g_timer_stop (timer);
955                                 elapsed = g_timer_elapsed (timer, NULL);
956                                 if (!opt)
957                                         no_opt_time = elapsed;
958                                 fprintf (mini_stats_fd, "%f, ", elapsed);
959                         }
960                         fprintf (mini_stats_fd, "]");
961                         if (no_opt_time > 0.0) {
962                                 fprintf (mini_stats_fd, ", \n[");
963                                 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) 
964                                         fprintf (mini_stats_fd, "%f,", no_opt_time);
965                                 fprintf (mini_stats_fd, "]");
966                         }
967                         fprintf (mini_stats_fd, ");\n");
968                 } else {
969                         for (i = 0; i < count; ++i) {
970                                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
971                                         (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
972                                         method = mono_marshal_get_native_wrapper (method);
973
974                                 cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
975                                 mono_destroy_compile (cfg);
976                         }
977                 }
978         } else {
979                 cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
980                 mono_destroy_compile (cfg);
981         }
982
983         mini_cleanup (domain);
984         return 0;
985 }
986
987 MonoDomain * 
988 mono_jit_init (const char *file)
989 {
990         return mini_init (file);
991 }
992
993 void        
994 mono_jit_cleanup (MonoDomain *domain)
995 {
996         mini_cleanup (domain);
997 }