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