* driver.c: Re-enabled SSAPRE.
[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/metadata/security-manager.h>
41 #include <mono/os/gc_wrapper.h>
42
43 #include "mini.h"
44 #include "jit.h"
45 #include <string.h>
46 #include <ctype.h>
47 #include "inssel.h"
48 #include <locale.h>
49
50 static FILE *mini_stats_fd = NULL;
51
52 static void mini_usage (void);
53
54 typedef void (*OptFunc) (const char *p);
55
56 /* keep in sync with enum in mini.h */
57 typedef struct {
58         const char* name;
59         const char* desc;
60         const OptFunc func;
61 } OptName;
62
63 static const OptName 
64 opt_names [] = {
65         {"peephole", "Peephole postpass"},
66         {"branch",   "Branch optimizations"},
67         {"inline",   "Inline method calls"},
68         {"cfold",    "Constant folding"},
69         {"consprop", "Constant propagation"},
70         {"copyprop", "Copy propagation"},
71         {"deadce",   "Dead code elimination"},
72         {"linears",  "Linear scan global reg allocation"},
73         {"cmov",     "Conditional moves"},
74         {"shared",   "Emit per-domain code"},
75         {"sched",    "Instruction scheduling"},
76         {"intrins",  "Intrinsic method implementations"},
77         {"tailc",    "Tail recursion and tail calls"},
78         {"loop",     "Loop related optimizations"},
79         {"fcmov",    "Fast x86 FP compares"},
80         {"leaf",     "Leaf procedures optimizations"},
81         {"aot",      "Usage of Ahead Of Time compiled code"},
82         {"precomp",  "Precompile all methods before executing Main"},
83         {"abcrem",   "Array bound checks removal"},     
84         {"ssapre",   "SSA based Partial Redundancy Elimination"}
85 };
86
87 #define DEFAULT_OPTIMIZATIONS ( \
88         MONO_OPT_PEEPHOLE |     \
89         MONO_OPT_CFOLD |        \
90         MONO_OPT_BRANCH |       \
91         MONO_OPT_LINEARS |      \
92         MONO_OPT_INTRINS |  \
93         MONO_OPT_LOOP |  \
94         MONO_OPT_AOT)
95
96 #define EXCLUDED_FROM_ALL (MONO_OPT_SHARED | MONO_OPT_PRECOMP | MONO_OPT_SSAPRE)
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         MonoCompile *cfg;
414         int i, count = 0;
415
416         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
417                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
418                 MonoMethodSignature *sig;
419
420                 if (mono_metadata_has_generic_params (image, token))
421                         continue;
422
423                 method = mono_get_method (image, token, NULL);
424                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
425                     (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
426                     (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
427                     (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
428                         continue;
429
430                 if (method->klass->generic_container)
431                         continue;
432                 sig = mono_method_signature (method);
433                 if (sig->has_type_parameters)
434                         continue;
435
436                 count++;
437                 if (verbose) {
438                         char * desc = mono_method_full_name (method, TRUE);
439                         g_print ("Compiling %d %s\n", count, desc);
440                         g_free (desc);
441                 }
442                 cfg = mini_method_compile (method, DEFAULT_OPTIMIZATIONS, mono_get_root_domain (), FALSE, FALSE, 0);
443                 mono_destroy_compile (cfg);
444         }
445
446 }
447
448 static void
449 compile_all_methods (MonoAssembly *ass, int verbose)
450 {
451         CompileAllThreadArgs args;
452
453         args.ass = ass;
454         args.verbose = verbose;
455
456         /* 
457          * Need to create a mono thread since compilation might trigger
458          * running of managed code.
459          */
460         mono_thread_create (mono_domain_get (), compile_all_methods_thread_main, &args);
461
462         mono_thread_manage ();
463 }
464
465 /**
466  * mono_jit_exec:
467  * @assembly: reference to an assembly
468  * @argc: argument count
469  * @argv: argument vector
470  *
471  * Start execution of a program.
472  */
473 int 
474 mono_jit_exec (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])
475 {
476         MonoImage *image = mono_assembly_get_image (assembly);
477         MonoMethod *method;
478         guint32 entry = mono_image_get_entry_point (image);
479
480         if (!entry) {
481                 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
482                 /* FIXME: remove this silly requirement. */
483                 mono_environment_exitcode_set (1);
484                 return 1;
485         }
486
487         method = mono_get_method (image, entry, NULL);
488
489         return mono_runtime_run_main (method, argc, argv, NULL);
490 }
491
492 typedef struct 
493 {
494         MonoDomain *domain;
495         const char *file;
496         int argc;
497         char **argv;
498         guint32 opts;
499         char *aot_options;
500 } MainThreadArgs;
501
502 static void main_thread_handler (gpointer user_data)
503 {
504         MainThreadArgs *main_args = user_data;
505         MonoAssembly *assembly;
506
507         assembly = mono_domain_assembly_open (main_args->domain, main_args->file);
508         if (!assembly){
509                 fprintf (stderr, "Can not open image %s\n", main_args->file);
510                 exit (1);
511         }
512
513         if (mono_compile_aot) {
514                 int res = mono_compile_assembly (assembly, main_args->opts, main_args->aot_options);
515                 printf ("AOT RESULT %d\n", res);
516         } else {
517                 /* 
518                  * This must be done in a thread managed by mono since it can invoke
519                  * managed code.
520                  */
521                 if (main_args->opts & MONO_OPT_PRECOMP)
522                         mono_precompile_assemblies ();
523
524                 mono_jit_exec (main_args->domain, assembly, main_args->argc, main_args->argv);
525         }
526 }
527
528 static void
529 mini_usage_jitdeveloper (void)
530 {
531         int i;
532         
533         fprintf (stdout,
534                  "Runtime and JIT debugging options:\n"
535                  "    --breakonex            Inserts a breakpoint on exceptions\n"
536                  "    --break METHOD         Inserts a breakpoint at METHOD entry\n"
537                  "    --compile METHOD       Just compile METHOD in assembly\n"
538                  "    --compile-all          Compiles all the methods in the assembly\n"
539                  "    --ncompile N           Number of times to compile METHOD (default: 1)\n"
540                  "    --print-vtable         Print the vtable of all used classes\n"
541                  "    --regression           Runs the regression test contained in the assembly\n"
542                  "    --statfile FILE        Sets the stat file to FILE\n"
543                  "    --stats                Print statistics about the JIT operations\n"
544                  "\n"
545                  "Other options:\n" 
546                  "    --graph[=TYPE] METHOD  Draws a graph of the specified method:\n");
547         
548         for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
549                 fprintf (stdout, "                           %-10s %s\n", graph_names [i].name, graph_names [i].desc);
550         }
551 }
552
553 static void
554 mini_usage_list_opt (void)
555 {
556         int i;
557         
558         for (i = 0; i < G_N_ELEMENTS (opt_names); ++i)
559                 fprintf (stdout, "                           %-10s %s\n", opt_names [i].name, opt_names [i].desc);
560 }
561
562 static void
563 mini_usage (void)
564 {
565         fprintf (stdout,
566                 "Usage is: mono [options] program [program-options]\n"
567                 "\n"
568                 "Development:\n"
569                 "    --aot                  Compiles the assembly to native code\n"
570                 "    --debug                Enable debugging support\n"
571                 "    --profile[=profiler]   Runs in profiling mode with the specified profiler module\n"
572                 "    --trace[=EXPR]         Enable tracing, use --help-trace for details\n"
573                 "    --help-devel           Shows more options available to developers\n"
574                 "\n"
575                 "Runtime:\n"
576                 "    --config FILE          Loads FILE as the Mono config\n"
577                 "    --verbose, -v          Increases the verbosity level\n"
578                 "    --help, -h             Show usage information\n"
579                 "    --version, -V          Show version information\n"
580                 "    --optimize=OPT         Turns on or off a specific optimization\n"
581                 "                           Use --list-opt to get a list of optimizations\n"
582                 "    --security             Turns on the security manager (unsupported, default is off)\n");
583 }
584
585 static void
586 mini_trace_usage (void)
587 {
588         fprintf (stdout,
589                  "Tracing options:\n"
590                  "   --trace[=EXPR]        Trace every call, optional EXPR controls the scope\n"
591                  "\n"
592                  "EXPR is composed of:\n"
593                  "    all                  All assemblies\n"
594                  "    none                 No assemblies\n"
595                  "    program              Entry point assembly\n"
596                  "    assembly             Specifies an assembly\n"
597                  "    M:Type:Method        Specifies a method\n"
598                  "    N:Namespace          Specifies a namespace\n"
599                  "    T:Type               Specifies a type\n"
600                  "    +EXPR                Includes expression\n"
601                  "    -EXPR                Excludes expression\n");
602 }
603
604 static const char *info = ""
605 #ifdef HAVE_KW_THREAD
606         "\tTLS:           __thread\n"
607 #else
608         "\tTLS:           normal\n"
609 #endif /* HAVE_KW_THREAD */
610 #ifdef HAVE_BOEHM_GC
611 #ifdef USE_INCLUDED_LIBGC
612         "\tGC:            Included Boehm (with typed GC)\n"
613 #else
614 #if HAVE_GC_GCJ_MALLOC
615         "\tGC:            System Boehm (with typed GC)\n"
616 #else
617         "\tGC:            System Boehm (no typed GC available)\n"
618 #endif
619 #endif
620 #else
621         "\tGC:            none\n"
622 #endif /* HAVE_BOEHM_GC */
623 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
624     "\tSIGSEGV      : altstack\n"
625 #else
626     "\tSIGSEGV      : normal\n"
627 #endif
628 #ifdef HAVE_ICU
629         "\tGlobalization: ICU\n"
630 #else
631         "\tGlobalization: none\n"
632 #endif /* HAVE_ICU */
633         "";
634
635 int
636 mono_main (int argc, char* argv[])
637 {
638         MainThreadArgs main_args;
639         MonoAssembly *assembly;
640         MonoMethodDesc *desc;
641         MonoMethod *method;
642         MonoCompile *cfg;
643         MonoDomain *domain;
644         const char* aname, *mname = NULL;
645         char *config_file = NULL;
646         int i, count = 1;
647         int enable_debugging = FALSE;
648         guint32 opt, action = DO_EXEC;
649         MonoGraphOptions mono_graph_options = 0;
650         int mini_verbose = 0;
651         gboolean enable_profile = FALSE;
652         char *trace_options = NULL;
653         char *profile_options = NULL;
654         char *aot_options = NULL;
655
656         setlocale (LC_ALL, "");
657
658         if (mono_running_on_valgrind () && getenv ("MONO_VALGRIND_LEAK_CHECK")) {
659                 GMemVTable mem_vtable;
660
661                 /* 
662                  * Instruct glib to use the system allocation functions so valgrind
663                  * can track the memory allocated by the g_... functions.
664                  */
665                 memset (&mem_vtable, 0, sizeof (mem_vtable));
666                 mem_vtable.malloc = malloc;
667                 mem_vtable.realloc = realloc;
668                 mem_vtable.free = free;
669                 mem_vtable.calloc = calloc;
670
671                 g_mem_set_vtable (&mem_vtable);
672         }
673
674         g_log_set_always_fatal (G_LOG_LEVEL_ERROR);
675         g_log_set_fatal_mask (G_LOG_DOMAIN, G_LOG_LEVEL_ERROR);
676
677         opt = parse_optimizations (NULL);
678
679         for (i = 1; i < argc; ++i) {
680                 if (argv [i] [0] != '-')
681                         break;
682                 if (strcmp (argv [i], "--regression") == 0) {
683                         action = DO_REGRESSION;
684                 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
685                         mini_verbose++;
686                 } else if (strcmp (argv [i], "--version") == 0 || strcmp (argv [i], "-V") == 0) {
687                         g_print ("Mono JIT compiler version %s, (C) 2002-2004 Novell, Inc and Contributors. www.go-mono.com\n", VERSION);
688                         g_print (info);
689                         if (mini_verbose) {
690                                 const guchar *cerror;
691                                 const guchar *clibpath;
692                                 mono_init ("mono");
693                                 cerror = mono_check_corlib_version ();
694                                 clibpath = mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown";
695                                 if (cerror) {
696                                         g_print ("The currently installed mscorlib doesn't match this runtime version.\n");
697                                         g_print ("The error is: %s\n", cerror);
698                                         g_print ("mscorlib.dll loaded at: %s\n", clibpath);
699                                         return 1;
700                                 }
701                         }
702                         return 0;
703                 } else if (strcmp (argv [i], "--help") == 0 || strcmp (argv [i], "-h") == 0) {
704                         mini_usage ();
705                         return 0;
706                 } else if (strcmp (argv [i], "--help-trace") == 0){
707                         mini_trace_usage ();
708                         return 0;
709                 } else if (strcmp (argv [i], "--help-devel") == 0){
710                         mini_usage_jitdeveloper ();
711                         return 0;
712                 } else if (strcmp (argv [i], "--list-opt") == 0){
713                         mini_usage_list_opt ();
714                         return 0;
715                 } else if (strncmp (argv [i], "--statfile", 10) == 0) {
716                         mini_stats_fd = fopen (argv [++i], "w+");
717                 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
718                         opt = parse_optimizations (argv [i] + 11);
719                 } else if (strncmp (argv [i], "-O=", 3) == 0) {
720                         opt = parse_optimizations (argv [i] + 3);
721                 } else if (strcmp (argv [i], "--config") == 0) {
722                         config_file = argv [++i];
723                 } else if (strcmp (argv [i], "--ncompile") == 0) {
724                         count = atoi (argv [++i]);
725                         action = DO_BENCH;
726                 } else if (strcmp (argv [i], "--trace") == 0) {
727                         trace_options = (char*)"";
728                 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
729                         trace_options = &argv [i][8];
730                 } else if (strcmp (argv [i], "--breakonex") == 0) {
731                         mono_break_on_exc = TRUE;
732                 } else if (strcmp (argv [i], "--break") == 0) {
733                         if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
734                                 g_error ("Invalid method name '%s'", argv [i]);
735                 } else if (strcmp (argv [i], "--print-vtable") == 0) {
736                         mono_print_vtable = TRUE;
737                 } else if (strcmp (argv [i], "--stats") == 0) {
738                         mono_stats.enabled = TRUE;
739                         mono_jit_stats.enabled = TRUE;
740 #ifndef DISABLE_AOT
741                 } else if (strcmp (argv [i], "--aot") == 0) {
742                         mono_compile_aot = TRUE;
743                 } else if (strncmp (argv [i], "--aot=", 6) == 0) {
744                         mono_compile_aot = TRUE;
745                         aot_options = &argv [i][6];
746 #endif
747                 } else if (strcmp (argv [i], "--compile-all") == 0) {
748                         action = DO_COMPILE;
749                 } else if (strcmp (argv [i], "--profile") == 0) {
750                         enable_profile = TRUE;
751                         profile_options = NULL;
752                 } else if (strncmp (argv [i], "--profile=", 10) == 0) {
753                         enable_profile = TRUE;
754                         profile_options = argv [i] + 10;
755                 } else if (strcmp (argv [i], "--compile") == 0) {
756                         mname = argv [++i];
757                         action = DO_BENCH;
758                 } else if (strncmp (argv [i], "--graph=", 8) == 0) {
759                         mono_graph_options = mono_parse_graph_options (argv [i] + 8);
760                         mname = argv [++i];
761                         action = DO_DRAW;
762                 } else if (strcmp (argv [i], "--graph") == 0) {
763                         mname = argv [++i];
764                         mono_graph_options = MONO_GRAPH_CFG;
765                         action = DO_DRAW;
766                 } else if (strcmp (argv [i], "--debug") == 0) {
767                         enable_debugging = TRUE;
768                 } else if (strcmp (argv [i], "--security") == 0) {
769                         mono_use_security_manager = TRUE;
770                         mono_activate_security_manager ();
771                 } else {
772                         fprintf (stderr, "Unknown command line option: '%s'\n", argv [i]);
773                         return 1;
774                 }
775         }
776
777         if (!argv [i]) {
778                 mini_usage ();
779                 return 1;
780         }
781
782         if (mono_compile_aot || action == DO_EXEC) {
783                 g_set_prgname (argv[i]);
784         }
785
786         if (enable_profile) {
787                 /* Needed because of TLS accesses in mono_profiler_load () */
788                 MONO_GC_PRE_INIT ();
789                 mono_profiler_load (profile_options);
790         }
791
792         if (trace_options != NULL){
793                 /* 
794                  * Need to call this before mini_init () so we can trace methods 
795                  * compiled there too.
796                  */
797                 mono_jit_trace_calls = mono_trace_parse_options (trace_options);
798                 if (mono_jit_trace_calls == NULL)
799                         exit (1);
800         }
801
802         mono_set_defaults (mini_verbose, opt);
803         domain = mini_init (argv [i]);
804         
805         switch (action) {
806         case DO_REGRESSION:
807                 if (mini_regression_list (mini_verbose, argc -i, argv + i)) {
808                         g_print ("Regression ERRORS!\n");
809                         mini_cleanup (domain);
810                         return 1;
811                 }
812                 mini_cleanup (domain);
813                 return 0;
814         case DO_BENCH:
815                 if (argc - i != 1 || mname == NULL) {
816                         g_print ("Usage: mini --ncompile num --compile method assembly\n");
817                         mini_cleanup (domain);
818                         return 1;
819                 }
820                 aname = argv [i];
821                 break;
822         case DO_COMPILE:
823                 if (argc - i != 1) {
824                         mini_usage ();
825                         mini_cleanup (domain);
826                         return 1;
827                 }
828                 aname = argv [i];
829                 break;
830         case DO_DRAW:
831                 if (argc - i != 1 || mname == NULL) {
832                         mini_usage ();
833                         mini_cleanup (domain);
834                         return 1;
835                 }
836                 aname = argv [i];
837                 break;
838         default:
839                 if (argc - i < 1) {
840                         mini_usage ();
841                         mini_cleanup (domain);
842                         return 1;
843                 }
844                 aname = argv [i];
845                 break;
846         }
847
848         if (enable_debugging) {
849                 mono_debug_init (MONO_DEBUG_FORMAT_MONO);
850                 mono_debug_init_1 (domain);
851         }
852
853         /* Parse gac loading options before loading assemblies. */
854         if (mono_compile_aot || action == DO_EXEC) {
855                 mono_config_parse (config_file);
856         }
857
858         assembly = mono_assembly_open (aname, NULL);
859         if (!assembly) {
860                 fprintf (stderr, "cannot open assembly %s\n", aname);
861                 mini_cleanup (domain);
862                 return 2;
863         }
864
865         if (trace_options != NULL)
866                 mono_trace_set_assembly (assembly);
867
868         if (enable_debugging)
869                 mono_debug_init_2 (assembly);
870
871         if (mono_compile_aot || action == DO_EXEC) {
872                 const guchar *error;
873
874                 //mono_set_rootdir ();
875
876                 error = mono_check_corlib_version ();
877                 if (error) {
878                         fprintf (stderr, "Corlib not in sync with this runtime: %s\n", error);
879                         fprintf (stderr, "Download a newer corlib or a newer runtime at http://www.go-mono.com/daily.\n");
880                         exit (1);
881                 }
882
883                 main_args.domain = domain;
884                 main_args.file = aname;         
885                 main_args.argc = argc - i;
886                 main_args.argv = argv + i;
887                 main_args.opts = opt;
888                 main_args.aot_options = aot_options;
889 #if RUN_IN_SUBTHREAD
890                 mono_runtime_exec_managed_code (domain, main_thread_handler, &main_args);
891 #else
892                 main_thread_handler (&main_args);
893                 mono_thread_manage ();
894 #endif
895                 mini_cleanup (domain);
896
897                 /* Look up return value from System.Environment.ExitCode */
898                 i = mono_environment_exitcode_get ();
899                 return i;
900         } else if (action == DO_COMPILE) {
901                 compile_all_methods (assembly, mini_verbose);
902                 mini_cleanup (domain);
903                 return 0;
904         }
905         desc = mono_method_desc_new (mname, 0);
906         if (!desc) {
907                 g_print ("Invalid method name %s\n", mname);
908                 mini_cleanup (domain);
909                 return 3;
910         }
911         method = mono_method_desc_search_in_image (desc, mono_assembly_get_image (assembly));
912         if (!method) {
913                 g_print ("Cannot find method %s\n", mname);
914                 mini_cleanup (domain);
915                 return 3;
916         }
917
918         if (action == DO_DRAW) {
919                 int part = 0;
920
921                 switch (mono_graph_options) {
922                 case MONO_GRAPH_DTREE:
923                         part = 1;
924                         opt |= MONO_OPT_LOOP;
925                         break;
926                 case MONO_GRAPH_CFG_CODE:
927                         part = 1;
928                         break;
929                 case MONO_GRAPH_CFG_SSA:
930                         part = 2;
931                         break;
932                 case MONO_GRAPH_CFG_OPTCODE:
933                         part = 3;
934                         break;
935                 default:
936                         break;
937                 }
938
939                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
940                         (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
941                         MonoMethod *nm;
942                         nm = mono_marshal_get_native_wrapper (method);
943                         cfg = mini_method_compile (nm, opt, mono_get_root_domain (), FALSE, FALSE, part);
944                 }
945                 else
946                         cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, part);
947                 if ((mono_graph_options & MONO_GRAPH_CFG_SSA) && !(cfg->comp_done & MONO_COMP_SSA)) {
948                         g_warning ("no SSA info available (use -O=deadce)");
949                         return 1;
950                 }
951                 mono_draw_graph (cfg, mono_graph_options);
952                 mono_destroy_compile (cfg);
953
954         } else if (action == DO_BENCH) {
955                 if (mini_stats_fd) {
956                         const char *n;
957                         double no_opt_time = 0.0;
958                         GTimer *timer = g_timer_new ();
959                         fprintf (mini_stats_fd, "$stattitle = \'Compilations times for %s\';\n", 
960                                  mono_method_full_name (method, TRUE));
961                         fprintf (mini_stats_fd, "@data = (\n");
962                         fprintf (mini_stats_fd, "[");
963                         for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
964                                 opt = opt_sets [i];
965                                 n = opt_descr (opt);
966                                 if (!n [0])
967                                         n = "none";
968                                 fprintf (mini_stats_fd, "\"%s\",", n);
969                         }
970                         fprintf (mini_stats_fd, "],\n[");
971
972                         for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
973                                 int j;
974                                 double elapsed;
975                                 opt = opt_sets [i];
976                                 g_timer_start (timer);
977                                 for (j = 0; j < count; ++j) {
978                                         cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
979                                         mono_destroy_compile (cfg);
980                                 }
981                                 g_timer_stop (timer);
982                                 elapsed = g_timer_elapsed (timer, NULL);
983                                 if (!opt)
984                                         no_opt_time = elapsed;
985                                 fprintf (mini_stats_fd, "%f, ", elapsed);
986                         }
987                         fprintf (mini_stats_fd, "]");
988                         if (no_opt_time > 0.0) {
989                                 fprintf (mini_stats_fd, ", \n[");
990                                 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) 
991                                         fprintf (mini_stats_fd, "%f,", no_opt_time);
992                                 fprintf (mini_stats_fd, "]");
993                         }
994                         fprintf (mini_stats_fd, ");\n");
995                 } else {
996                         for (i = 0; i < count; ++i) {
997                                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
998                                         (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
999                                         method = mono_marshal_get_native_wrapper (method);
1000
1001                                 cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
1002                                 mono_destroy_compile (cfg);
1003                         }
1004                 }
1005         } else {
1006                 cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
1007                 mono_destroy_compile (cfg);
1008         }
1009
1010         mini_cleanup (domain);
1011         return 0;
1012 }
1013
1014 MonoDomain * 
1015 mono_jit_init (const char *file)
1016 {
1017         return mini_init (file);
1018 }
1019
1020 void        
1021 mono_jit_cleanup (MonoDomain *domain)
1022 {
1023         mini_cleanup (domain);
1024 }