995ccd3e6f8a83c532b752355477bdba3b02f270
[libfirm] / ir / be / beraextern.c
1 /**
2  * Author:      Daniel Grund
3  * Date:                17.01.2006
4  * Copyright:   (c) Universitaet Karlsruhe
5  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
6  *
7  * Implementation of the RA-Interface for an external, (non-SSA) register allocator.
8  *
9  * The external register allocator is a program:
10  *    PROG -i INPUTFILE -o OUTPUTFILE
11  *
12  *   1) Input file defines the interference graph
13  *   2) Output file contains the instructions to perform
14  *
15
16
17 The input file format
18 ----------------------
19
20 inputfile       ::= regs nodes interf affinities .
21
22 regs            ::= 'regs' regcount .                                           // Anzahl der register (0..regcount-1), die zur Verfuegung stehen
23
24 nodes           ::= 'nodes' '{' node* '}' .                                     // All nodes in the graph
25
26 node            ::= node-info
27                           | node-info '<' reg-nr '>' .                          // Reg-nr is present in case of constraints
28
29 node-info       ::= node-nr spill-costs .
30
31 interf          ::= 'interferences' '{' i-edge* '}' .           // Interference edges of the graph
32
33 i-edge          ::= '(' node-nr ',' node-nr ')' .
34
35 affinities      ::= 'affinities' '{' a-edge* '}' .                      // Affinity edges of the graph
36
37 a-edge          ::= '(' node-nr ',' node-nr ',' weight ')' .
38
39
40 weight, regcount, node-nr ::= int32 .
41 spill-costs ::= int32 .                                                                 // negative spill costs indicate unspillable
42
43 The output file format
44 -----------------------
45
46 outputfile      ::= spills | allocs .
47
48 spills          ::= 'spills' node-nr+ .
49
50 allocs          ::= 'allocs' alloc* .
51
52 alloc           ::= node-nr reg-nr .
53
54
55 ******** End of file format docu ********/
56
57 #ifdef HAVE_CONFIG_H
58 #include "config.h"
59 #endif
60
61 #ifdef WIN32
62 #include <malloc.h>
63 #else
64 #include <alloca.h>
65 #endif
66
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <limits.h>
70 #ifdef WITH_LIBCORE
71 #include <libcore/lc_opts.h>
72 #include <libcore/lc_opts_enum.h>
73 #endif
74
75 #include "set.h"
76 #include "pset.h"
77 #include "pmap.h"
78 #include "bitset.h"
79
80 #include "irprintf_t.h"
81 #include "irnode_t.h"
82 #include "irgraph_t.h"
83 #include "irgwalk.h"
84 #include "iredges_t.h"
85 #include "irdom_t.h"
86 #include "phiclass.h"
87
88 #include "beraextern.h"
89 #include "bearch.h"
90 #include "benode_t.h"
91 #include "beirgmod.h"
92 #include "besched.h"
93 #include "beutil.h"
94 #include "belive_t.h"
95
96 #define DBG_LEVEL 2
97
98 typedef struct _var_info_t var_info_t;
99
100 /**
101  * Environment with all the needed stuff
102  */
103 typedef struct _be_raext_env_t {
104         firm_dbg_module_t *dbg;
105         arch_env_t *aenv;
106         const arch_register_class_t *cls;
107         ir_graph *irg;
108         dom_front_info_t *dom_info;
109
110         FILE *f;                                /**< file handle used for out- and input file */
111         set *vars;                              /**< contains all var_info_t */
112         int n_cls_vars;                 /**< length of the array cls_vars */
113         var_info_t **cls_vars;  /**< only the var_infos for current cls. needed for double iterating */
114 } be_raext_env_t;
115
116
117
118 /******************************************************************************
119     _    _      _
120    | |  | |    | |
121    | |__| | ___| |_ __   ___ _ __ ___
122    |  __  |/ _ \ | '_ \ / _ \ '__/ __|
123    | |  | |  __/ | |_) |  __/ |  \__ \
124    |_|  |_|\___|_| .__/ \___|_|  |___/
125                  | |
126                  |_|
127  *****************************************************************************/
128
129
130 #define pset_foreach(pset, irn)  for(irn=pset_first(pset); irn; irn=pset_next(pset))
131 #define set_foreach(set, e)  for(e=set_first(set); e; e=set_next(set))
132
133 /**
134  * Checks if _the_ result of the irn belongs to the
135  * current register class (raenv->cls)
136  * NOTE: Only the first result is checked.
137  */
138 #define is_res_in_reg_class(irn) arch_irn_has_reg_class(raenv->aenv, irn, -1, raenv->cls)
139
140 static INLINE ir_node *get_first_non_phi(pset *s) {
141         ir_node *irn;
142
143         pset_foreach(s, irn)
144                 if (!is_Phi(irn)) {
145                         pset_break(s);
146                         return irn;
147                 }
148
149         assert(0 && "There must be a non-phi-irn in this");
150         return NULL;
151 }
152
153 static INLINE ir_node *get_first_phi(pset *s) {
154         ir_node *irn;
155
156         pset_foreach(s, irn)
157                 if (is_Phi(irn)) {
158                         pset_break(s);
159                         return irn;
160                 }
161
162         assert(0 && "There must be a phi in this");
163         return NULL;
164 }
165
166 /******************************************************************************
167     _____                _            _____            _
168    / ____|              | |          / ____|          (_)
169   | |     ___  _ __  ___| |_ _ __   | |     ___  _ __  _  ___  ___
170   | |    / _ \| '_ \/ __| __| '__|  | |    / _ \| '_ \| |/ _ \/ __|
171   | |___| (_) | | | \__ \ |_| |     | |___| (_) | |_) | |  __/\__ \
172    \_____\___/|_| |_|___/\__|_|      \_____\___/| .__/|_|\___||___/
173                                                 | |
174                                                 |_|
175  *****************************************************************************/
176
177 static void handle_constraints_walker(ir_node *irn, void *env) {
178         be_raext_env_t *raenv = env;
179         arch_register_req_t req;
180         int pos, max;
181
182         /* handle output constraints
183          * user -> irn    becomes    user -> cpy -> irn
184          */
185         arch_get_register_req(raenv->aenv, &req, irn, -1);
186         if (arch_register_req_is(&req, limited)) {
187                 ir_node *cpy = be_new_Copy(req.cls, raenv->irg, get_nodes_block(irn), irn);
188                 const ir_edge_t *edge;
189
190                 /* all users of the irn use the copy instead */
191                 sched_add_after(irn, cpy);
192                 foreach_out_edge(irn, edge)
193                         set_irn_n(edge->src, edge->pos, cpy);
194         }
195
196
197         /* handle input constraints by converting them into output constraints
198          * of copies of the former argument
199          * irn -> arg   becomes  irn -> copy -> arg
200      */
201         for (pos = 0, max = get_irn_arity(irn); pos<max; ++pos) {
202                 arch_get_register_req(raenv->aenv, &req, irn, pos);
203                 if (arch_register_req_is(&req, limited)) {
204                         ir_node *arg = get_irn_n(irn, pos);
205                         ir_node *cpy = be_new_Copy(req.cls, raenv->irg, get_nodes_block(irn), arg);
206
207                         /* use the copy instead */
208                         sched_add_before(irn, cpy);
209                         set_irn_n(irn, pos, cpy);
210
211                         /* set an out constraint for the copy */
212                         be_set_constr_limited(cpy, -1, &req);
213                 }
214         }
215 }
216
217 static void handle_constraints(be_raext_env_t *raenv) {
218         irg_block_walk_graph(raenv->irg, NULL, handle_constraints_walker, raenv);
219 }
220
221
222 /******************************************************************************
223      _____ _____              _____            _
224     / ____/ ____|  /\        |  __ \          | |
225    | (___| (___   /  \ ______| |  | | ___  ___| |_ _ __
226     \___ \\___ \ / /\ \______| |  | |/ _ \/ __| __| '__|
227     ____) |___) / ____ \     | |__| |  __/\__ \ |_| |
228    |_____/_____/_/    \_\    |_____/ \___||___/\__|_|
229
230  *****************************************************************************/
231
232 #define mark_as_done(irn, pos)                  set_irn_link(irn, INT_TO_PTR(pos+1))
233 #define has_been_done(irn, pos)                 (PTR_TO_INT(get_irn_link(irn)) > pos)
234
235 /**
236  * Insert a copy for the argument of @p start_phi found at position @p pos.
237  * Also searches a phi-loop of arbitrary length to detect and resolve
238  *   the class of phi-swap-problems. To search for a loop recursion is used.
239  *
240  * 1) Simplest case (phi with a non-phi arg):
241  *     A single copy is inserted.
242  *
243  * 2) Phi chain (phi (with phi-arg)* with non=phi arg):
244  *     Several copies are placed, each after returning from recursion.
245  *
246  * 3) Phi-loop:
247  *     On detection a loop breaker is inserted, which is a copy of the start_phi.
248  *     This copy then pretends beeing the argumnent of the last phi.
249  *     Now case 2) can be used.
250  *
251  * The values of @p start_phi and @p pos never change during recursion.
252  *
253  * @p raenv      Environment with all the stuff needed
254  * @p start_phi  Phi node to process
255  * @p pos        Argument position to insert copy/copies for
256  * @p curr_phi   Phi node currently processed during recursion. Equals start_phi on initial call
257  *
258  * @return NULL  If no copy is necessary
259  *         NULL  If the phi has already been processed at this pos
260  *               Link field is used to keep track of processed positions
261  *         In all other cases the ir_node *copy which was placed is returned.
262  */
263 static ir_node *insert_copies(be_raext_env_t *raenv, ir_node *start_phi, int pos, ir_node *curr_phi) {
264         ir_node *arg = get_irn_n(curr_phi, pos);
265         ir_node *arg_blk = get_nodes_block(arg);
266         ir_node *pred_blk = get_Block_cfgpred_block(get_nodes_block(curr_phi), pos);
267         ir_node *curr_cpy, *last_cpy;
268
269         assert(is_Phi(start_phi) && is_Phi(curr_phi));
270
271         if (has_been_done(start_phi, pos))
272                 return NULL;
273
274         /* In case this is a 'normal' phi we insert into
275          * the schedule before the pred_blk irn */
276         last_cpy = pred_blk;
277
278         /* If we detect a loop stop recursion. */
279         if (arg == start_phi) {
280                 ir_node *loop_breaker;
281                 if (start_phi == curr_phi) {
282                         /* Phi directly uses itself. No copy necessary */
283                         return NULL;
284                 }
285
286                 /* At least 2 phis are involved */
287                 /* Insert a loop breaking copy (an additional variable T) */
288                 loop_breaker = be_new_Copy(raenv->cls, raenv->irg, pred_blk, start_phi);
289                 sched_add_before(pred_blk, loop_breaker);
290
291                 arg = loop_breaker;
292         }
293
294         /* If arg is a phi in the same block we have to continue search */
295         if (is_Phi(arg) && arg_blk == get_nodes_block(start_phi))
296                 last_cpy = insert_copies(raenv, start_phi, pos, arg);
297
298         /* Insert copy of argument (may be the loop-breaker) */
299         curr_cpy = be_new_Copy(raenv->cls, raenv->irg, pred_blk, arg);
300         set_irn_n(curr_phi, pos, curr_cpy);
301         mark_as_done(curr_phi, pos);
302         sched_add_before(last_cpy, curr_cpy);
303         return curr_cpy;
304 }
305
306
307 /**
308  * Perform simple SSA-destruction with copies.
309  * The order of processing _must_ be
310  *  for all positions {
311  *    for all phis {
312  *      doit
313  *    }
314  *  }
315  * else the magic to keep track of processed phi-positions will fail in
316  * function 'insert_copies'
317  */
318 static void ssa_destr_simple_walker(ir_node *blk, void *env) {
319         be_raext_env_t *raenv = env;
320         int pos, max;
321         ir_node *phi;
322
323         /* for all argument positions of the phis */
324         for (pos=0, max=get_irn_arity(blk); pos<max; ++pos) {
325
326                 /* for all phi nodes (which are scheduled first) */
327                 sched_foreach(blk, phi) {
328                         if (!is_Phi(phi))
329                                 break;
330
331                         raenv->cls = arch_get_irn_reg_class(raenv->aenv, phi, -1);
332                         insert_copies(raenv, phi, pos, phi);
333                 }
334         }
335 }
336
337
338 static void ssa_destr_simple(be_raext_env_t *raenv) {
339         be_clear_links(raenv->irg);
340         irg_block_walk_graph(raenv->irg, ssa_destr_simple_walker, NULL, raenv);
341 }
342
343
344 static void ssa_destr_rastello(be_raext_env_t *raenv) {
345         assert(0 && "NYI");
346         exit(0xDeadBeef);
347         /*
348         phi_class_compute(raenv->irg);
349         irg_block_walk_graph(irg, ssa_destr_rastello, NULL, &raenv);
350         */
351 }
352
353 /******************************************************************************
354    __      __   _       ___   __      __
355    \ \    / /  | |     |__ \  \ \    / /
356     \ \  / /_ _| |___     ) |  \ \  / /_ _ _ __ ___
357      \ \/ / _` | / __|   / /    \ \/ / _` | '__/ __|
358       \  / (_| | \__ \  / /_     \  / (_| | |  \__ \
359        \/ \__,_|_|___/ |____|     \/ \__,_|_|  |___/
360  *****************************************************************************/
361
362 /**
363  * This struct maps a variable (nr) to the values belonging to this variable
364  */
365 struct _var_info_t {
366         int var_nr;             /* the key */
367         pset *values;   /* the ssa-values belonging to this variable */
368 };
369
370 #define SET_REMOVED -1
371
372 /**
373  * The link field of an irn points to the var_info struct
374  * representing the corresponding variable.
375  */
376 #define set_var_info(irn, vi)                           set_irn_link(irn, vi)
377 #define get_var_info(irn)                                       ((var_info_t *)get_irn_link(irn))
378
379 #define HASH_VAR_NR(var_nr) var_nr
380
381 static int compare_var_infos(const void *e1, const void *e2, size_t size) {
382         const var_info_t *v1 = e1;
383         const var_info_t *v2 = e2;
384
385         if (v1->var_nr == SET_REMOVED || v2->var_nr == SET_REMOVED)
386                 return 1;
387
388         return v1->var_nr != v2->var_nr;
389 }
390
391 static INLINE var_info_t *var_find(set *vars, int var_nr) {
392         var_info_t vi;
393         vi.var_nr = var_nr;
394
395         return set_find(vars, &vi, sizeof(vi), HASH_VAR_NR(var_nr));
396 }
397
398 static INLINE var_info_t *var_find_or_insert(set *vars, int var_nr) {
399         var_info_t vi, *found;
400         memset(&vi, 0, sizeof(vi));
401         vi.var_nr = var_nr;
402
403         found = set_insert(vars, &vi, sizeof(vi), HASH_VAR_NR(var_nr));
404
405         if (!found->values)
406                 found->values  = pset_new_ptr(1);
407
408         return found;
409 }
410
411 /**
412  * Adds a value to a variable. Sets all pointers accordingly.
413  */
414 static INLINE var_info_t *var_add_value(be_raext_env_t *raenv, int var_nr, ir_node *irn) {
415         var_info_t *vi = var_find_or_insert(raenv->vars, var_nr);
416
417         /* var 2 value mapping */
418         pset_insert_ptr(vi->values, irn);
419
420         /* value 2 var mapping */
421         set_var_info(irn, vi);
422
423         return vi;
424 }
425
426 static INLINE pset *get_var_values(be_raext_env_t *raenv, int var_nr) {
427         var_info_t *vi = var_find(raenv->vars, var_nr);
428         assert(vi && "Variable does not exist");
429         return vi->values;
430 }
431
432 /**
433  * Define variables (numbers) for all SSA-values.
434  * All values in a phi class get assigned the same variable name.
435  * The link field maps values to the var-name
436  */
437 static void values_to_vars(ir_node *irn, void *env) {
438         be_raext_env_t *raenv = env;
439         int nr;
440         pset *vals;
441
442         if(arch_get_irn_reg_class(raenv->aenv, irn, -1) == NULL)
443                 return;
444
445         vals = get_phi_class(irn);
446
447         if (vals) {
448                 nr = get_irn_node_nr(get_first_phi(vals));
449         } else {
450                 /* not a phi class member, value == var */
451                 nr = get_irn_node_nr(irn);
452                 vals = pset_new_ptr(1);
453                 pset_insert_ptr(vals, irn);
454         }
455
456         /* values <--> var mapping */
457         pset_foreach(vals, irn)
458                 var_add_value(raenv, nr, irn);
459 }
460
461
462 /******************************************************************************
463     _____
464    |  __ \
465    | |  | |_   _ _ __ ___  _ __   ___ _ __
466    | |  | | | | | '_ ` _ \| '_ \ / _ \ '__|
467    | |__| | |_| | | | | | | |_) |  __/ |
468    |_____/ \__,_|_| |_| |_| .__/ \___|_|
469                           | |
470                           |_|
471  *****************************************************************************/
472
473
474 static void extract_vars_of_cls(be_raext_env_t *raenv) {
475         int count = 0;
476         var_info_t *vi;
477
478         raenv->cls_vars = malloc(set_count(raenv->vars) * sizeof(*raenv->cls_vars));
479         assert(raenv->cls_vars);
480
481         set_foreach(raenv->vars, vi)
482                 if (is_res_in_reg_class(get_first_non_phi(vi->values)))
483                         raenv->cls_vars[count++] = vi;
484
485         raenv->cls_vars = realloc(raenv->cls_vars, count * sizeof(*raenv->cls_vars));
486         assert(raenv->cls_vars);
487
488         raenv->n_cls_vars = count;
489 }
490
491
492 /**
493  * Check if node irn has a limited-constraint at position pos.
494  * If yes, dump it to FILE raenv->f
495  */
496 static INLINE void dump_constraint(be_raext_env_t *raenv, ir_node *irn, int pos) {
497         bitset_t *bs = bitset_alloca(raenv->cls->n_regs);
498         arch_register_req_t req;
499
500         arch_get_register_req(raenv->aenv, &req, irn, pos);
501         if (arch_register_req_is(&req, limited)) {
502                 int reg_nr;
503                 req.limited(req.limited_env, bs);
504                 reg_nr = bitset_next_set(bs, 0);
505                 fprintf(raenv->f, "<%d>", reg_nr);
506                 assert(-1 == bitset_next_set(bs, reg_nr+1) && "Constraints with more than 1 possible register are not supported");
507         }
508 }
509
510 static INLINE unsigned int get_spill_costs(be_raext_env_t *raenv, var_info_t *vi) {
511         ir_node *irn;
512         int n_spills=0, n_reloads=0;
513
514         pset_foreach(vi->values, irn) {
515                 if (arch_irn_is_ignore(raenv->aenv, irn)) {
516                         pset_break(vi->values);
517                         return -1;
518                 }
519
520                 if (is_Phi(irn)) {
521                         /* number of reloads is the number of non-phi uses of all values of this var */
522                         const ir_edge_t *edge;
523                         foreach_out_edge(irn, edge)
524                                 if (!is_Phi(edge->src))
525                                         n_reloads++;
526                 } else {
527                         /* number of spills is the number of non-phi values for this var */
528                         n_spills++;
529                 }
530         }
531
532         return n_spills + n_reloads;
533 }
534
535 static void dump_nodes(be_raext_env_t *raenv) {
536         FILE *f = raenv->f;
537         int i;
538
539         fprintf(f, "\nnodes {\n");
540
541         for (i=0; i<raenv->n_cls_vars; ++i) {
542                 var_info_t *vi = raenv->cls_vars[i];
543
544                 if (vi->var_nr == SET_REMOVED)
545                         continue;
546
547                 fprintf(f, "%d %u", vi->var_nr, get_spill_costs(raenv, vi));
548                 dump_constraint(raenv, get_first_non_phi(vi->values), -1);
549                 fprintf(f, "\n");
550         }
551
552         fprintf(f, "}\n");
553 }
554
555
556 static void dump_interferences(be_raext_env_t *raenv) {
557         int i,o;
558         var_info_t *vi1, *vi2;
559         ir_node *irn1, *irn2;
560         FILE *f = raenv->f;
561
562         fprintf(f, "\ninterferences {\n");
563
564         for (i=0; i<raenv->n_cls_vars; ++i) {
565                 vi1 = raenv->cls_vars[i];
566
567                 if (vi1->var_nr == SET_REMOVED)
568                         continue;
569
570                 for (o=i+1; o<raenv->n_cls_vars; ++o) {
571                         vi2 = raenv->cls_vars[o];
572
573                         if (vi2->var_nr == SET_REMOVED)
574                                 continue;
575
576                         pset_foreach(vi1->values, irn1)
577                                 pset_foreach(vi2->values, irn2)
578                                         if (values_interfere(irn1, irn2)) {
579                                                 pset_break(vi1->values);
580                                                 pset_break(vi2->values);
581                                                 fprintf(f, "(%d, %d)\n", vi1->var_nr, vi2->var_nr);
582                                         }
583                 }
584         }
585         fprintf(f, "}\n");
586 }
587
588
589 static int get_weight(ir_node *irn) {
590         int cost = 0;
591         ir_loop *loop = get_irn_loop(get_nodes_block(irn));
592
593         if (loop) {
594                 int d = get_loop_depth(loop);
595                 cost = d*d;
596         }
597         return cost+1;
598 }
599
600 static void dump_affinities_walker(ir_node *irn, void *env) {
601         be_raext_env_t *raenv = env;
602         arch_register_req_t req;
603         int pos, max;
604         var_info_t *vi1, *vi2;
605
606         if (arch_get_irn_reg_class(raenv->aenv, irn, -1) == NULL || arch_irn_is_ignore(raenv->aenv, irn))
607                 return;
608
609         vi1 = get_var_info(irn);
610
611         /* copies have affinities */
612         if (arch_irn_classify(raenv->aenv, irn) == arch_irn_class_copy) {
613                 ir_node *other = get_irn_n(irn, 0);
614
615                 if (! arch_irn_is_ignore(raenv->aenv, other)) {
616                         vi2 = get_var_info(other);
617
618                         fprintf(raenv->f, "(%d, %d, %d)\n",  vi1->var_nr, vi2->var_nr, get_weight(irn));
619                 }
620         }
621
622
623         /* should_be_equal constraints are affinites */
624         for (pos = 0, max = get_irn_arity(irn); pos<max; ++pos) {
625                 arch_get_register_req(raenv->aenv, &req, irn, pos);
626
627                 if (arch_register_req_is(&req, should_be_same) && arch_irn_is_ignore(raenv->aenv, req.other_same)) {
628                         vi2 = get_var_info(req.other_same);
629
630                         fprintf(raenv->f, "(%d, %d, %d)\n",  vi1->var_nr, vi2->var_nr, get_weight(irn));
631                 }
632         }
633 }
634
635
636 static void dump_affinities(be_raext_env_t *raenv) {
637         fprintf(raenv->f, "\naffinities {\n");
638         irg_walk_graph(raenv->irg, NULL, dump_affinities_walker, raenv);
639         fprintf(raenv->f, "}\n");
640 }
641
642 /**
643  * Dump all information needed by the external
644  * register allocator to a single file.
645  */
646 static void dump_to_file(be_raext_env_t *raenv, char *filename) {
647         FILE *f;
648
649         if (!(f = fopen(filename, "wt"))) {
650                 fprintf(stderr, "Could not open file %s for writing\n", filename);
651                 assert(0);
652                 exit(0xdeadbeef);
653         }
654         raenv->f = f;
655
656         /* dump register info */
657         fprintf(f, "regs %d\n", arch_register_class_n_regs(raenv->cls));
658
659         /* dump the interference graph */
660         dump_nodes(raenv);
661         dump_interferences(raenv);
662         dump_affinities(raenv);
663
664         fclose(f);
665 }
666
667 /******************************************************************************
668     ______                     _
669    |  ____|                   | |
670    | |__  __  _____  ___ _   _| |_ ___
671    |  __| \ \/ / _ \/ __| | | | __/ _ \
672    | |____ >  <  __/ (__| |_| | ||  __/
673    |______/_/\_\___|\___|\__,_|\__\___|
674  *****************************************************************************/
675
676 /**
677  * Execute the external register allocator specified in the
678  * firm-option firm.be.ra.ext.callee
679  */
680 static void execute(char *prog_to_call, char *out_file, char *result_file) {
681         char cmd_line[1024];
682         int ret_status;
683
684         snprintf(cmd_line, sizeof(cmd_line), "%s -i %s -o %s", prog_to_call, out_file, result_file);
685
686         ret_status = system(cmd_line);
687         assert(ret_status != -1 && "Invokation of external register allocator failed");
688 }
689
690 /******************************************************************************
691                          _         _____                 _ _
692        /\               | |       |  __ \               | | |
693       /  \   _ __  _ __ | |_   _  | |__) |___  ___ _   _| | |_
694      / /\ \ | '_ \| '_ \| | | | | |  _  // _ \/ __| | | | | __|
695     / ____ \| |_) | |_) | | |_| | | | \ \  __/\__ \ |_| | | |_
696    /_/    \_\ .__/| .__/|_|\__, | |_|  \_\___||___/\__,_|_|\__|
697             | |   | |       __/ |
698             |_|   |_|      |___/
699  *****************************************************************************/
700
701 /**
702  * Spill a variable and add reloads before all uses.
703  */
704 static INLINE void var_add_spills_and_reloads(be_raext_env_t *raenv, int var_nr) {
705         var_info_t *vi = var_find(raenv->vars, var_nr);
706         ir_node *spill=NULL, *ctx, *irn;
707         const ir_edge_t *edge, *ne;
708         pset *spills  = pset_new_ptr(4);        /* the spills of this variable */
709         pset *reloads = pset_new_ptr(4);        /* the reloads of this variable */
710         int new_size, n_spills, n_reloads;
711
712         assert(vi && "Variable nr does not exist!");
713         assert(pset_count(vi->values) && "There are no values associated to this variable");
714
715         /* the spill context is set to an arbitrary node of the phi-class,
716          * or the node itself if it is not member of a phi class
717          */
718         if (pset_count(vi->values) == 1)
719                 ctx = get_first_non_phi(vi->values);
720         else
721                 ctx = get_first_phi(vi->values);
722
723         DBG((raenv->dbg, LEVEL_2, "Spill context: %+F\n", ctx));
724
725         /* for each value of this variable insert the spills */
726         pset_foreach(vi->values, irn) {
727                 if (is_Phi(irn)) {
728                         sched_remove(irn);
729                         continue;
730                 }
731
732                 /* all ordinary nodes must be spilled */
733                 DBG((raenv->dbg, LEVEL_2, "  spilling %+F\n", irn));
734                 spill = be_spill(raenv->aenv, irn, ctx);
735
736                 /* remember the spill */
737                 pset_insert_ptr(spills, spill);
738         }
739
740         assert(spill && "There must be at least one non-phi-node");
741
742         /* insert reloads and wire them arbitrary*/
743         pset_foreach(vi->values, irn)
744                 foreach_out_edge_safe(irn, edge, ne) {
745                         ir_node *reload, *src = edge->src;
746                         if (is_Phi(src) || be_is_Spill(src))
747                                 continue;
748
749                         /* all real uses must be reloaded */
750                         DBG((raenv->dbg, LEVEL_2, "  reloading before %+F\n", src));
751                         reload = be_reload(raenv->aenv, raenv->cls, edge->src, edge->pos, get_irn_mode(get_irn_n(spill, 0)), spill);
752
753                         /* remember the reload */
754                         pset_insert_ptr(reloads, reload);
755                 }
756
757         /* correct the reload->spill pointers... */
758         be_ssa_constr_set(raenv->dom_info, spills);
759
760
761         /****** correct the variable <--> values mapping: ******
762          *
763          *  - if we had a phi class it gets split into several new variables
764          *  - all reloads are new variables
765          */
766         n_spills = pset_count(spills);
767         n_reloads = pset_count(reloads);
768
769         /* first make room for new pointers in the cls_var array */
770         new_size = raenv->n_cls_vars + n_reloads + ((n_spills>1) ? n_spills : 0);
771         raenv->cls_vars = realloc(raenv->cls_vars, (new_size) * sizeof(*raenv->cls_vars));
772         assert(raenv->cls_vars && "Out of mem!?");
773
774         /* if we had a real phi-class, we must... */
775         if (pset_count(spills) > 1) {
776                 /* ...remove the old variable corresponding to the phi class */
777                 vi->var_nr = SET_REMOVED;
778
779                 /* ...add new vars for each non-phi-member */
780                 pset_foreach(spills, irn) {
781                         ir_node *spilled = get_irn_n(irn, 0);
782                         raenv->cls_vars[raenv->n_cls_vars++] = var_add_value(raenv, get_irn_node_nr(spilled), spilled);
783                 }
784         }
785
786         /* add new variables for all reloads */
787         pset_foreach(reloads, irn)
788                 raenv->cls_vars[raenv->n_cls_vars++] = var_add_value(raenv, get_irn_node_nr(irn), irn);
789
790         del_pset(spills);
791         del_pset(reloads);
792 }
793
794 #define INVALID_FILE_FORMAT assert(0 && "Invalid file format.")
795 #define BUFLEN 32
796 #define BUFCONV " %32s "
797
798 /**
799  * Read in the actions performed by the external allocator.
800  * Apply these transformations to the irg.
801  * @return 1 if an allocation was read in. 0 otherwise.
802  */
803 static int read_and_apply_results(be_raext_env_t *raenv, char *filename) {
804         FILE *f;
805         char buf[BUFLEN];
806         int is_allocation = 0;
807
808         if (!(f = fopen(filename, "rt"))) {
809                 fprintf(stderr, "Could not open file %s for reading\n", filename);
810                 assert(0);
811                 exit(0xdeadbeef);
812         }
813         raenv->f = f;
814
815         /* read the action */
816         if (fscanf(f, BUFCONV, buf) != 1)
817                 INVALID_FILE_FORMAT;
818
819         /* do we spill */
820         if (!strcmp(buf, "spills")) {
821                 int var_nr;
822                 while (fscanf(f, " %d ", &var_nr) == 1)
823                         var_add_spills_and_reloads(raenv, var_nr);
824         } else
825
826         /* or do we allocate */
827         if (!strcmp(buf, "allocs")) {
828                 int var_nr, reg_nr;
829
830                 is_allocation = 1;
831                 while (fscanf(f, " %d %d ", &var_nr, &reg_nr) == 2) {
832                         ir_node *irn;
833                         pset *vals = get_var_values(raenv, var_nr);
834
835                         assert(vals && "Variable nr does not exist!");
836                         pset_foreach(vals, irn)
837                                 arch_set_irn_register(raenv->aenv, irn, arch_register_for_index(raenv->cls, reg_nr));
838                 }
839         } else
840                 INVALID_FILE_FORMAT;
841
842         if (!feof(f))
843                 INVALID_FILE_FORMAT;
844
845         fclose(f);
846
847         return is_allocation;
848 }
849
850 /******************************************************************************
851     __  __       _
852    |  \/  |     (_)
853    | \  / | __ _ _ _ __
854    | |\/| |/ _` | | '_ \
855    | |  | | (_| | | | | |
856    |_|  |_|\__,_|_|_| |_|
857  *****************************************************************************/
858
859 /**
860  * Default values for options
861  */
862 static void (*ssa_destr)(be_raext_env_t*) = ssa_destr_simple;
863 static char callee[128] = "\"E:/user/kimohoff/ipd-registerallocator/win32/register allocator\"";
864 //static char callee[128] = "/ben/kimohoff/ipd-registerallocator/register_allocator";
865
866
867 /**
868  * Allocate registers with an external program using a text-file interface.
869  *
870  * Do some computations (SSA-destruction and mapping of values--vars)
871  * Write file
872  * Execute external program
873  * Read in results and apply them
874  *
875  */
876 static void be_ra_extern_main(const be_irg_t *bi) {
877         be_main_env_t *env = bi->main_env;
878         ir_graph *irg = bi->irg;
879
880         be_raext_env_t raenv;
881         int clsnr, clss;
882         var_info_t *vi;
883
884         compute_doms(irg);
885
886         raenv.irg      = irg;
887         raenv.aenv     = env->arch_env;
888         raenv.dom_info = be_compute_dominance_frontiers(irg);
889         raenv.vars     = new_set(compare_var_infos, 64);
890         raenv.dbg      = firm_dbg_register("ir.be.raextern");
891         firm_dbg_set_mask(raenv.dbg, DBG_LEVEL);
892
893         /* Insert copies for constraints */
894         handle_constraints(&raenv);
895         dump_ir_block_graph_sched(irg, "-extern-constr");
896
897         /* SSA destruction respectively transformation into "Conventional SSA" */
898         ssa_destr(&raenv);
899         dump_ir_block_graph_sched(irg, "-extern-ssadestr");
900
901         /* Mapping of SSA-Values <--> Variables */
902         phi_class_compute(irg);
903         be_clear_links(irg);
904         irg_walk_graph(irg, values_to_vars, NULL, &raenv);
905
906
907         /* For all register classes */
908         for(clsnr = 0, clss = arch_isa_get_n_reg_class(raenv.aenv->isa); clsnr < clss; ++clsnr) {
909                 int done, round = 1;
910                 char out[256], in[256];
911
912                 raenv.cls = arch_isa_get_reg_class(raenv.aenv->isa, clsnr);
913
914                 extract_vars_of_cls(&raenv);
915
916                 do {
917                         ir_snprintf(out, sizeof(out), "%F-%s-%d.ra", irg, raenv.cls->name, round);
918                         ir_snprintf(in, sizeof(in), "%F-%s-%d.ra.res", irg, raenv.cls->name, round);
919
920                         be_liveness(irg);
921
922                         dump_to_file(&raenv, out);
923                         execute(callee, out, in);
924                         done = read_and_apply_results(&raenv, in);
925
926                         ir_snprintf(in, sizeof(in), "-extern-%s-round-%d", raenv.cls->name, round);
927                         dump_ir_block_graph_sched(irg, in);
928
929                         round++;
930                 } while (!done);
931
932                 free(raenv.cls_vars);
933         }
934
935         dump_ir_block_graph_sched(irg, "-extern-alloc");
936
937         /* Clean up */
938         set_foreach(raenv.vars, vi)
939                 del_pset(vi->values);
940         del_set(raenv.vars);
941         be_free_dominance_frontiers(raenv.dom_info);
942 }
943
944 /******************************************************************************
945      ____        _   _
946     / __ \      | | (_)
947    | |  | |_ __ | |_ _  ___  _ __  ___
948    | |  | | '_ \| __| |/ _ \| '_ \/ __|
949    | |__| | |_) | |_| | (_) | | | \__ \
950     \____/| .__/ \__|_|\___/|_| |_|___/
951           | |
952           |_|
953  *****************************************************************************/
954
955 #ifdef WITH_LIBCORE
956
957
958 static const lc_opt_enum_func_ptr_items_t ssa_destr_items[] = {
959         { "simple",     (int (*)()) ssa_destr_simple }, /* TODO make (void*) casts nicer */
960         { "rastello",   (int (*)()) ssa_destr_rastello },
961         { NULL,      NULL }
962 };
963
964 static lc_opt_enum_func_ptr_var_t ssa_destr_var = {
965          (int (**)()) &ssa_destr, ssa_destr_items
966 };
967
968 static const lc_opt_table_entry_t be_ra_extern_options[] = {
969         LC_OPT_ENT_ENUM_FUNC_PTR("ssa_destr", "SSA destruction flavor", &ssa_destr_var),
970         LC_OPT_ENT_STR("callee", "The external program to call", callee, sizeof(callee)),
971         { NULL }
972 };
973
974 static void be_ra_extern_register_options(lc_opt_entry_t *root) {
975         lc_opt_entry_t *grp = lc_opt_get_grp(root, "ext");
976
977         lc_opt_add_table(grp, be_ra_extern_options);
978 }
979
980 #endif /* WITH_LIBCORE */
981
982 const be_ra_t be_ra_external_allocator = {
983 #ifdef WITH_LIBCORE
984         be_ra_extern_register_options,
985 #endif
986         be_ra_extern_main
987 };