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