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