Bugfixes
[libfirm] / ir / be / beraextern.c
index 873350e..cbd55d7 100644 (file)
@@ -6,9 +6,11 @@
  *
  * Implementation of the RA-Interface for an external, (non-SSA) register allocator.
  *
- * The external register allocator is a program taking 2 arguments:
- *   1) An input file in which the cfg is defined
- *   2) An output file containing the essential actions performed during allocation
+ * The external register allocator is a program:
+ *    PROG -i INPUTFILE -o OUTPUTFILE
+ *
+ *   1) Input file defines the interference graph
+ *   2) Output file contains the instructions to perform
  *
 
 
@@ -21,42 +23,35 @@ regs                ::= 'regs' regcount .                                           // Anzahl der register (0..regcount-1), die zur
 
 nodes          ::= 'nodes' '{' node* '}' .                                     // All nodes in the graph
 
-interf         ::= 'interferences' '{' edge* '}' .                     // Interference edges of the graph
+node           ::= node-info
+                         | node-info '<' reg-nr '>' .                          // Reg-nr is present in case of constraints
+
+node-info      ::= node-nr spill-costs .
 
-affinities     ::= 'affinities' '{' edge* '}' .                        // Affinity edges of the graph
+interf         ::= 'interferences' '{' i-edge* '}' .           // Interference edges of the graph
 
-node           ::= node-nr
-                         | node-nr '<' reg-nr '>' .                            // Reg-nr is present in case of constraints
+i-edge         ::= '(' node-nr ',' node-nr ')' .
 
-edge           ::= '(' node-nr node-nr ')' .
+affinities     ::= 'affinities' '{' a-edge* '}' .                      // Affinity edges of the graph
 
+a-edge         ::= '(' node-nr ',' node-nr ',' weight ')' .
 
-regcount, node-nr ::= integer .
 
+weight, regcount, node-nr ::= int32 .
+spill-costs ::= int32 .                                                                        // negative spill costs indicate unspillable
 
 The output file format
 -----------------------
 
 outputfile     ::= spills | allocs .
 
-spills         ::= 'spills' '{' node-nr+ '}' .
+spills         ::= 'spills' node-nr+ .
 
-allocs         ::= 'allocs' '{' alloc* '}' .
+allocs         ::= 'allocs' alloc* .
 
 alloc          ::= node-nr reg-nr .
 
 
-Constraints for output file
----------------------------
-1) The returned actions must result in a non-ssa-program
-   equivalent to the former input.
-2) All names (numbers) must be defined before their first use.
-   Numbers already occuring in the input file are implicitly defined in the output file.
-3) All spills of a variable must precede the first reload of this variable
-4) Each reload must define a new variable name
-
-
-
 ******** End of file format docu ********/
 
 #ifdef HAVE_CONFIG_H
@@ -71,6 +66,7 @@ Constraints for output file
 
 #include <stdio.h>
 #include <stdlib.h>
+#include <limits.h>
 #ifdef WITH_LIBCORE
 #include <libcore/lc_opts.h>
 #include <libcore/lc_opts_enum.h>
@@ -85,15 +81,20 @@ Constraints for output file
 #include "irnode_t.h"
 #include "irgraph_t.h"
 #include "irgwalk.h"
+#include "iredges_t.h"
 #include "irdom_t.h"
 #include "phiclass.h"
 
 #include "beraextern.h"
+#include "beabi.h"
 #include "bearch.h"
 #include "benode_t.h"
 #include "beirgmod.h"
-#include "besched.h"
+#include "besched_t.h"
 #include "beutil.h"
+#include "belive_t.h"
+
+#define DBG_LEVEL 2
 
 typedef struct _var_info_t var_info_t;
 
@@ -101,6 +102,7 @@ typedef struct _var_info_t var_info_t;
  * Environment with all the needed stuff
  */
 typedef struct _be_raext_env_t {
+       firm_dbg_module_t *dbg;
        arch_env_t *aenv;
        const arch_register_class_t *cls;
        ir_graph *irg;
@@ -108,10 +110,8 @@ typedef struct _be_raext_env_t {
 
        FILE *f;                                /**< file handle used for out- and input file */
        set *vars;                              /**< contains all var_info_t */
-       int n_cls_vars;
+       int n_cls_vars;                 /**< length of the array cls_vars */
        var_info_t **cls_vars;  /**< only the var_infos for current cls. needed for double iterating */
-       set *edges;                             /**< interference and affinity edges */
-       pmap *nodes;                    /**< maps nodes numbers (int) to the node (ir_node*) having that node_nr */
 } be_raext_env_t;
 
 
@@ -131,7 +131,6 @@ typedef struct _be_raext_env_t {
 #define pset_foreach(pset, irn)  for(irn=pset_first(pset); irn; irn=pset_next(pset))
 #define set_foreach(set, e)  for(e=set_first(set); e; e=set_next(set))
 
-
 /**
  * Checks if _the_ result of the irn belongs to the
  * current register class (raenv->cls)
@@ -139,33 +138,103 @@ typedef struct _be_raext_env_t {
  */
 #define is_res_in_reg_class(irn) arch_irn_has_reg_class(raenv->aenv, irn, -1, raenv->cls)
 
+static INLINE ir_node *get_first_non_phi(pset *s) {
+       ir_node *irn;
 
-/**
- * Checks if the irn uses or defines values of the
- * current register class (raenv->cls)
- */
-static INLINE int is_sth_in_reg_class(be_raext_env_t *raenv, const ir_node *irn) {
-       int max, i;
-
-       /* check arguments */
-       for (i=0, max=get_irn_arity(irn); i<max; ++i)
-               if (arch_irn_has_reg_class(raenv->aenv, get_irn_n(irn, i), -1, raenv->cls))
-                       return 1;
-
-       /* check result(s) */
-       if (get_irn_mode(irn) == mode_T) {
-               ir_node *proj;
-               for (proj = sched_next(irn); is_Proj(proj); proj = sched_next(proj))
-                       if (arch_irn_has_reg_class(raenv->aenv, proj, -1, raenv->cls))
-                               return 1;
-               return 0;
-       } else {
-               return arch_irn_has_reg_class(raenv->aenv, irn, -1, raenv->cls);
+       pset_foreach(s, irn)
+               if (!is_Phi(irn)) {
+                       pset_break(s);
+                       return irn;
+               }
+
+       assert(0 && "There must be a non-phi-irn in this");
+       return NULL;
+}
+
+static INLINE ir_node *get_first_phi(pset *s) {
+       ir_node *irn;
+
+       pset_foreach(s, irn)
+               if (is_Phi(irn)) {
+                       pset_break(s);
+                       return irn;
+               }
+
+       assert(0 && "There must be a phi in this");
+       return NULL;
+}
+
+static int get_loop_weight(ir_node *irn) {
+       int cost = 0;
+       ir_loop *loop = get_irn_loop(get_nodes_block(irn));
+
+       if (loop) {
+               int d = get_loop_depth(loop);
+               cost = d*d;
+       }
+       return cost+1;
+}
+
+#define get_const_weight(irn) (1)
+
+#define get_spill_weight(irn)    get_loop_weight(irn)
+#define get_reload_weight(irn)   get_loop_weight(irn)
+#define get_affinity_weight(irn) get_loop_weight(irn)
+
+/******************************************************************************
+    _____                _            _____            _
+   / ____|              | |          / ____|          (_)
+  | |     ___  _ __  ___| |_ _ __   | |     ___  _ __  _  ___  ___
+  | |    / _ \| '_ \/ __| __| '__|  | |    / _ \| '_ \| |/ _ \/ __|
+  | |___| (_) | | | \__ \ |_| |     | |___| (_) | |_) | |  __/\__ \
+   \_____\___/|_| |_|___/\__|_|      \_____\___/| .__/|_|\___||___/
+                                                | |
+                                                |_|
+ *****************************************************************************/
+
+static void handle_constraints_walker(ir_node *irn, void *env) {
+       be_raext_env_t *raenv = env;
+       arch_register_req_t req;
+       int pos, max;
+
+       /* handle output constraints
+        * user -> irn    becomes    user -> cpy -> irn
+        */
+       arch_get_register_req(raenv->aenv, &req, irn, -1);
+       if (arch_register_req_is(&req, limited)) {
+               ir_node *cpy = be_new_Copy(req.cls, raenv->irg, get_nodes_block(irn), irn);
+
+               /* all users of the irn use the copy instead */
+               sched_add_after(irn, cpy);
+               edges_reroute(irn, cpy, raenv->irg);
+       }
+
+
+       /* handle input constraints by converting them into output constraints
+        * of copies of the former argument
+        * irn -> arg   becomes  irn -> copy -> arg
+     */
+       for (pos = 0, max = get_irn_arity(irn); pos<max; ++pos) {
+               arch_get_register_req(raenv->aenv, &req, irn, pos);
+               if (arch_register_req_is(&req, limited)) {
+                       ir_node *arg = get_irn_n(irn, pos);
+                       ir_node *cpy = be_new_Copy(req.cls, raenv->irg, get_nodes_block(irn), arg);
+
+                       /* use the copy instead */
+                       sched_add_before(irn, cpy);
+                       set_irn_n(irn, pos, cpy);
+
+                       /* set an out constraint for the copy */
+                       be_set_constr_limited(cpy, -1, &req);
+               }
        }
+}
 
-       assert(0 && "Where did you come from???");
+static void handle_constraints(be_raext_env_t *raenv) {
+       irg_walk_graph(raenv->irg, NULL, handle_constraints_walker, raenv);
 }
 
+
 /******************************************************************************
      _____ _____              _____            _
     / ____/ ____|  /\        |  __ \          | |
@@ -218,9 +287,10 @@ static ir_node *insert_copies(be_raext_env_t *raenv, ir_node *start_phi, int pos
        if (has_been_done(start_phi, pos))
                return NULL;
 
-       /* In case this is a 'normal' phi we insert into
-        * the schedule before the pred_blk irn */
-       last_cpy = pred_blk;
+       /* In case this is a 'normal' phi we insert at the
+        * end of the pred block before cf nodes */
+       last_cpy = sched_skip(pred_blk, 0, sched_skip_cf_predicator, raenv->aenv);
+       last_cpy = sched_next(last_cpy);
 
        /* If we detect a loop stop recursion. */
        if (arg == start_phi) {
@@ -233,7 +303,7 @@ static ir_node *insert_copies(be_raext_env_t *raenv, ir_node *start_phi, int pos
                /* At least 2 phis are involved */
                /* Insert a loop breaking copy (an additional variable T) */
                loop_breaker = be_new_Copy(raenv->cls, raenv->irg, pred_blk, start_phi);
-               sched_add_before(pred_blk, loop_breaker);
+               sched_add_before(last_cpy, loop_breaker);
 
                arg = loop_breaker;
        }
@@ -275,6 +345,9 @@ static void ssa_destr_simple_walker(ir_node *blk, void *env) {
                        if (!is_Phi(phi))
                                break;
 
+                       if (arch_irn_is_ignore(raenv->aenv, phi))
+                               continue;
+
                        raenv->cls = arch_get_irn_reg_class(raenv->aenv, phi, -1);
                        insert_copies(raenv, phi, pos, phi);
                }
@@ -290,7 +363,8 @@ static void ssa_destr_simple(be_raext_env_t *raenv) {
 
 static void ssa_destr_rastello(be_raext_env_t *raenv) {
        assert(0 && "NYI");
-       /* TODO
+       exit(0xDeadBeef);
+       /*
        phi_class_compute(raenv->irg);
        irg_block_walk_graph(irg, ssa_destr_rastello, NULL, &raenv);
        */
@@ -306,18 +380,15 @@ static void ssa_destr_rastello(be_raext_env_t *raenv) {
  *****************************************************************************/
 
 /**
- * This struct maps a variable (nr) to
- *  1) the values belonging to this variable
- *  2) the spills of this variable
+ * This struct maps a variable (nr) to the values belonging to this variable
  */
 struct _var_info_t {
-       int var_nr;             /* the key for comparesion */
+       int var_nr;             /* the key */
        pset *values;   /* the ssa-values belonging to this variable */
-       pset *spills;   /* the spills of this variable */
-       pset *reloads;  /* the relaods of this variable */
-       unsigned reload_phase:1;        /* 0 initially, 1 if a reload of this var has been inserted */
 };
 
+#define SET_REMOVED -1
+
 /**
  * The link field of an irn points to the var_info struct
  * representing the corresponding variable.
@@ -325,19 +396,15 @@ struct _var_info_t {
 #define set_var_info(irn, vi)                          set_irn_link(irn, vi)
 #define get_var_info(irn)                                      ((var_info_t *)get_irn_link(irn))
 
-/* TODO insn-nr handling if ext defines new ones */
-#define pmap_insert_sth(pmap, key, val)        pmap_insert(pmap, (void *)key, (void *)val)
-#define pmap_get_sth(pmap, key)                        pmap_get(pmap, (void *)key)
-
-
 #define HASH_VAR_NR(var_nr) var_nr
 
-
-
 static int compare_var_infos(const void *e1, const void *e2, size_t size) {
        const var_info_t *v1 = e1;
        const var_info_t *v2 = e2;
 
+       if (v1->var_nr == SET_REMOVED || v2->var_nr == SET_REMOVED)
+               return 1;
+
        return v1->var_nr != v2->var_nr;
 }
 
@@ -355,11 +422,8 @@ static INLINE var_info_t *var_find_or_insert(set *vars, int var_nr) {
 
        found = set_insert(vars, &vi, sizeof(vi), HASH_VAR_NR(var_nr));
 
-       if (!found->values) {
+       if (!found->values)
                found->values  = pset_new_ptr(1);
-               found->spills  = pset_new_ptr(1);
-               found->reloads = pset_new_ptr(1);
-       }
 
        return found;
 }
@@ -379,79 +443,12 @@ static INLINE var_info_t *var_add_value(be_raext_env_t *raenv, int var_nr, ir_no
        return vi;
 }
 
-/**
- * Adds a spill to a variable. Sets all pointers accordingly.
- */
-static INLINE var_info_t *var_add_spill(be_raext_env_t *raenv, int var_to_spill, ir_node *before) {
-       var_info_t *vi = var_find_or_insert(raenv->vars, var_to_spill);
-       ir_node *blk, *tospill, *spill;
-
-       assert(pset_count(vi->values) && "There are no values associated to this variable");
-       assert(!vi->reload_phase && "I have already seen a reload for this variable, so you cant spill anymore!");
-
-       /* add spill to graph and schedule */
-       blk     = get_nodes_block(before);
-       tospill = dom_up_search(vi->values, before); /* which value gets spilled */
-       spill   = be_new_Spill(raenv->cls, raenv->irg, blk, tospill, tospill); /* the corresponding spill node */
-
-       sched_add_before(before, spill);
-
-       /* the spill also points to the var_info of the spilled node */
-       set_var_info(spill, vi);
-
-       /* remember the spill */
-       pset_insert_ptr(vi->spills, spill);
-
-       return vi;
-}
-
-/**
- * Adds a reload to a variable. Sets all pointers accordingly.
- */
-static INLINE var_info_t *var_add_reload(be_raext_env_t *raenv, int var_to_reload, int var_nr_for_reload, ir_node *before) {
-       var_info_t *vi = var_find_or_insert(raenv->vars, var_to_reload);
-       ir_node *blk, *spill, *reload;
-
-       assert(pset_count(vi->spills) && "There are no spills associated to this variable");
-       /* now we enter the reload phase, so no more spills are allowed */
-       vi->reload_phase = 1;
-
-       /* add reload to graph and schedule */
-       blk    = get_nodes_block(before);
-       spill  = pset_first(vi->spills); /* For now use an arbitrary spill node. This is corrected later in fix_reloads */
-       pset_break(vi->spills);
-       reload = be_new_Reload(raenv->cls, raenv->irg, blk, get_irn_mode(get_irn_n(spill, 0)), spill);
-
-       sched_add_before(before, reload);
-
-       /* create a new variable for the result of the reload */
-       assert(!var_find(raenv->vars, var_nr_for_reload) && "Each reload must define a new variable");
-       var_add_value(raenv, var_nr_for_reload, reload);
-
-       /* remember the reload */
-       pset_insert_ptr(vi->reloads, reload);
-
-       return vi;
-}
-
 static INLINE pset *get_var_values(be_raext_env_t *raenv, int var_nr) {
        var_info_t *vi = var_find(raenv->vars, var_nr);
-       assert(vi && "Variable does not (yet?) exist");
+       assert(vi && "Variable does not exist");
        return vi->values;
 }
 
-static INLINE pset *get_var_spills(be_raext_env_t *raenv, int var_nr) {
-       var_info_t *vi = var_find(raenv->vars, var_nr);
-       assert(vi && "Variable does not (yet?) exist");
-       return vi->spills;
-}
-
-static INLINE pset *get_var_reloads(be_raext_env_t *raenv, int var_nr) {
-       var_info_t *vi = var_find(raenv->vars, var_nr);
-       assert(vi && "Variable does not (yet?) exist");
-       return vi->reloads;
-}
-
 /**
  * Define variables (numbers) for all SSA-values.
  * All values in a phi class get assigned the same variable name.
@@ -459,23 +456,28 @@ static INLINE pset *get_var_reloads(be_raext_env_t *raenv, int var_nr) {
  */
 static void values_to_vars(ir_node *irn, void *env) {
        be_raext_env_t *raenv = env;
-       ir_node *n;
        int nr;
        pset *vals;
 
+       if(arch_get_irn_reg_class(raenv->aenv, irn, -1) == NULL)
+               return;
+
        vals = get_phi_class(irn);
 
-       if (!vals) {
+       if (vals) {
+               nr = get_irn_node_nr(get_first_phi(vals));
+       } else {
                /* not a phi class member, value == var */
+               nr = get_irn_node_nr(irn);
                vals = pset_new_ptr(1);
                pset_insert_ptr(vals, irn);
        }
 
        /* values <--> var mapping */
-       n = pset_first(vals);
-       nr = get_irn_node_nr(n);
-       for (; n; n=pset_next(vals))
-               var_add_value(raenv, nr, n);
+       pset_foreach(vals, irn) {
+               DBG((raenv->dbg, 0, "Var %d contains %+F\n", nr, irn));
+               var_add_value(raenv, nr, irn);
+       }
 }
 
 
@@ -491,32 +493,16 @@ static void values_to_vars(ir_node *irn, void *env) {
  *****************************************************************************/
 
 
-static INLINE ir_node *get_first_non_phi(pset *s) {
-       ir_node *irn;
-
-       pset_foreach(s, irn)
-               if (!is_Phi(irn)) {
-                       pset_break(s);
-                       return irn;
-               }
-
-       assert(0 && "There must be a non-phi-irn in this");
-       return NULL;
-}
-
 static void extract_vars_of_cls(be_raext_env_t *raenv) {
        int count = 0;
-       set_entry *e;
+       var_info_t *vi;
 
        raenv->cls_vars = malloc(set_count(raenv->vars) * sizeof(*raenv->cls_vars));
        assert(raenv->cls_vars);
 
-       set_foreach(raenv->vars, e) {
-               var_info_t *vi = (var_info_t *)e->dptr;
-
+       set_foreach(raenv->vars, vi)
                if (is_res_in_reg_class(get_first_non_phi(vi->values)))
                        raenv->cls_vars[count++] = vi;
-       }
 
        raenv->cls_vars = realloc(raenv->cls_vars, count * sizeof(*raenv->cls_vars));
        assert(raenv->cls_vars);
@@ -543,6 +529,32 @@ static INLINE void dump_constraint(be_raext_env_t *raenv, ir_node *irn, int pos)
        }
 }
 
+#define UNSPILLABLE -1
+
+static INLINE int get_spill_costs(be_raext_env_t *raenv, var_info_t *vi) {
+       ir_node *irn;
+       int c_spills=0, c_reloads=0;
+
+       pset_foreach(vi->values, irn) {
+               if (arch_irn_is_ignore(raenv->aenv, irn) || be_is_Reload(irn)) {
+                       pset_break(vi->values);
+                       return UNSPILLABLE;
+               }
+
+               if (is_Phi(irn)) {
+                       /* number of reloads is the number of non-phi uses of all values of this var */
+                       const ir_edge_t *edge;
+                       foreach_out_edge(irn, edge)
+                               if (!is_Phi(edge->src))
+                                       c_reloads += get_reload_weight(edge->src);
+               } else {
+                       /* number of spills is the number of non-phi values for this var */
+                       c_spills += get_spill_weight(irn);
+               }
+       }
+
+       return c_spills + c_reloads;
+}
 
 static void dump_nodes(be_raext_env_t *raenv) {
        FILE *f = raenv->f;
@@ -551,12 +563,18 @@ static void dump_nodes(be_raext_env_t *raenv) {
        fprintf(f, "\nnodes {\n");
 
        for (i=0; i<raenv->n_cls_vars; ++i) {
-               fprintf(f, "%d", raenv->cls_vars[i]->var_nr);
-               dump_constraint(raenv, get_first_non_phi(raenv->cls_vars[i]->values), -1);
+               var_info_t *vi = raenv->cls_vars[i];
+
+               if (vi->var_nr == SET_REMOVED)
+                       continue;
+
+               fprintf(f, "%d %d", vi->var_nr, get_spill_costs(raenv, vi));
+               dump_constraint(raenv, get_first_non_phi(vi->values), -1);
                fprintf(f, "\n");
        }
 
        fprintf(f, "}\n");
+       fflush(f);
 }
 
 
@@ -571,37 +589,68 @@ static void dump_interferences(be_raext_env_t *raenv) {
        for (i=0; i<raenv->n_cls_vars; ++i) {
                vi1 = raenv->cls_vars[i];
 
+               if (vi1->var_nr == SET_REMOVED)
+                       continue;
+
                for (o=i+1; o<raenv->n_cls_vars; ++o) {
                        vi2 = raenv->cls_vars[o];
 
+                       if (vi2->var_nr == SET_REMOVED)
+                               continue;
+
                        pset_foreach(vi1->values, irn1)
                                pset_foreach(vi2->values, irn2)
                                        if (values_interfere(irn1, irn2)) {
                                                pset_break(vi1->values);
                                                pset_break(vi2->values);
-                                               fprintf(f, "(%d %d)\n", vi1->var_nr, vi2->var_nr);
+                                               fprintf(f, "(%d, %d)\n", vi1->var_nr, vi2->var_nr);
+                                               goto NextVar;
                                        }
+
+NextVar: ;
                }
        }
        fprintf(f, "}\n");
 }
 
-
 static void dump_affinities_walker(ir_node *irn, void *env) {
        be_raext_env_t *raenv = env;
+       arch_register_req_t req;
+       int pos, max;
+       var_info_t *vi1, *vi2;
 
+       if (arch_get_irn_reg_class(raenv->aenv, irn, -1) != raenv->cls || arch_irn_is_ignore(raenv->aenv, irn))
+               return;
+
+       vi1 = get_var_info(irn);
+
+       /* copies have affinities */
        if (arch_irn_classify(raenv->aenv, irn) == arch_irn_class_copy) {
-               ir_node *src = get_irn_n(irn, 0);
-               var_info_t *vi1 = get_irn_link(irn);
-               var_info_t *vi2 = get_irn_link(src);
+               ir_node *other = get_irn_n(irn, be_pos_Copy_orig);
+
+               if (! arch_irn_is_ignore(raenv->aenv, other)) {
+                       vi2 = get_var_info(other);
 
-               fprintf(raenv->f, "(%d %d)\n",  vi1->var_nr, vi2->var_nr);
+                       fprintf(raenv->f, "(%d, %d, %d)\n",  vi1->var_nr, vi2->var_nr, get_affinity_weight(irn));
+               }
+       }
+
+
+       /* should_be_equal constraints are affinites */
+       for (pos = 0, max = get_irn_arity(irn); pos<max; ++pos) {
+               arch_get_register_req(raenv->aenv, &req, irn, pos);
+
+               if (arch_register_req_is(&req, should_be_same) && arch_irn_is_ignore(raenv->aenv, req.other_same)) {
+                       vi2 = get_var_info(req.other_same);
+
+                       fprintf(raenv->f, "(%d, %d, %d)\n",  vi1->var_nr, vi2->var_nr, get_affinity_weight(irn));
+               }
        }
 }
 
 
 static void dump_affinities(be_raext_env_t *raenv) {
-       fprintf(raenv->f, "\ninterferences {\n");
+       fprintf(raenv->f, "\naffinities {\n");
        irg_walk_graph(raenv->irg, NULL, dump_affinities_walker, raenv);
        fprintf(raenv->f, "}\n");
 }
@@ -615,6 +664,7 @@ static void dump_to_file(be_raext_env_t *raenv, char *filename) {
 
        if (!(f = fopen(filename, "wt"))) {
                fprintf(stderr, "Could not open file %s for writing\n", filename);
+               assert(0);
                exit(0xdeadbeef);
        }
        raenv->f = f;
@@ -647,10 +697,11 @@ static void execute(char *prog_to_call, char *out_file, char *result_file) {
        char cmd_line[1024];
        int ret_status;
 
-       snprintf(cmd_line, sizeof(cmd_line), "%s %s %s", prog_to_call, out_file, result_file);
+       snprintf(cmd_line, sizeof(cmd_line), "%s -i %s -o %s", prog_to_call, out_file, result_file);
 
        ret_status = system(cmd_line);
        assert(ret_status != -1 && "Invokation of external register allocator failed");
+       assert(ret_status == 0 && "External register allocator is unhappy with sth.");
 }
 
 /******************************************************************************
@@ -664,23 +715,109 @@ static void execute(char *prog_to_call, char *out_file, char *result_file) {
             |_|   |_|      |___/
  *****************************************************************************/
 
-#define INVALID_FILE_FORMAT assert(0 && "Invalid file format.")
+/**
+ * Spill a variable and add reloads before all uses.
+ */
+static INLINE void var_add_spills_and_reloads(be_raext_env_t *raenv, int var_nr) {
+       var_info_t *vi = var_find(raenv->vars, var_nr);
+       ir_node *spill=NULL, *ctx, *irn;
+       ir_mode *mode;
+       const ir_edge_t *edge, *ne;
+       pset *spills  = pset_new_ptr(4);        /* the spills of this variable */
+       pset *reloads = pset_new_ptr(4);        /* the reloads of this variable */
+       int new_size, n_spills, n_reloads;
+
+       assert(vi && "Variable nr does not exist!");
+       assert(pset_count(vi->values) && "There are no values associated to this variable");
 
-static INLINE int is_before(const char *s, size_t len) {
-       if (!strncmp(s, "before", len))
-               return 1;
-       if (!strncmp(s, "after", len))
-               return 0;
-       INVALID_FILE_FORMAT;
-       return -1;
-}
+       /* the spill context is set to an arbitrary node of the phi-class,
+        * or the node itself if it is not member of a phi class
+        */
+       if (pset_count(vi->values) == 1)
+               ctx = get_first_non_phi(vi->values);
+       else
+               ctx = get_first_phi(vi->values);
+
+       DBG((raenv->dbg, LEVEL_2, "Spill context: %+F\n", ctx));
+
+       /* for each value of this variable insert the spills */
+       pset_foreach(vi->values, irn) {
+               if (is_Phi(irn)) {
+                       sched_remove(irn);
+                       continue;
+               }
 
-static void fix_reloads(be_raext_env_t *raenv) {
-       var_info_t *vi;
-       set_foreach(raenv->vars, vi)
-               be_introduce_copies_pset(raenv->dom_info, vi->spills);
+               /* all ordinary nodes must be spilled */
+               DBG((raenv->dbg, LEVEL_2, "  spilling %+F\n", irn));
+               spill = be_spill(raenv->aenv, irn, ctx);
+
+               /* remember the spill */
+               pset_insert_ptr(spills, spill);
+       }
+
+       assert(spill && "There must be at least one non-phi-node");
+
+       mode = get_irn_mode(get_irn_n(spill, be_pos_Spill_val));
+
+       /* insert reloads and wire them arbitrary*/
+       pset_foreach(vi->values, irn)
+               foreach_out_edge_safe(irn, edge, ne) {
+                       ir_node *reload, *src = edge->src;
+                       if (is_Phi(src) || be_is_Spill(src))
+                               continue;
+
+                       /* all real uses must be reloaded */
+                       DBG((raenv->dbg, LEVEL_2, "  reloading before %+F\n", src));
+                       reload = be_reload(raenv->aenv, raenv->cls, edge->src, mode, spill);
+                       set_irn_n(edge->src, edge->pos, reload);
+
+                       /* remember the reload */
+                       pset_insert_ptr(reloads, reload);
+               }
+
+       /* correct the reload->spill pointers... */
+       be_ssa_constr_set(raenv->dom_info, spills);
+
+
+       /****** correct the variable <--> values mapping: ******
+        *
+        *  - if we had a phi class it gets split into several new variables
+        *  - all reloads are new variables
+        */
+       n_spills = pset_count(spills);
+       n_reloads = pset_count(reloads);
+
+       /* first make room for new pointers in the cls_var array */
+       new_size = raenv->n_cls_vars + n_reloads + ((n_spills>1) ? n_spills : 0);
+       raenv->cls_vars = realloc(raenv->cls_vars, (new_size) * sizeof(*raenv->cls_vars));
+       assert(raenv->cls_vars && "Out of mem!?");
+
+       /* if we had a real phi-class, we must... */
+       if (pset_count(spills) > 1) {
+               /* ...remove the old variable corresponding to the phi class */
+               vi->var_nr = SET_REMOVED;
+
+               /* ...add new vars for each non-phi-member */
+               pset_foreach(spills, irn) {
+                       ir_node *spilled = get_irn_n(irn, be_pos_Spill_val);
+                       raenv->cls_vars[raenv->n_cls_vars++] = var_add_value(raenv, get_irn_node_nr(spilled), spilled);
+               }
+       }
+
+       /* add new variables for all reloads */
+       pset_foreach(reloads, irn) {
+               assert(get_irn_node_nr(irn) != 1089);
+               raenv->cls_vars[raenv->n_cls_vars++] = var_add_value(raenv, get_irn_node_nr(irn), irn);
+       }
+
+       del_pset(spills);
+       del_pset(reloads);
 }
 
+#define INVALID_FILE_FORMAT assert(0 && "Invalid file format.")
+#define BUFLEN 32
+#define BUFCONV " %32s "
+
 /**
  * Read in the actions performed by the external allocator.
  * Apply these transformations to the irg.
@@ -688,97 +825,75 @@ static void fix_reloads(be_raext_env_t *raenv) {
  */
 static int read_and_apply_results(be_raext_env_t *raenv, char *filename) {
        FILE *f;
-       var_info_t *vi;
-       int phase=0;
+       char buf[BUFLEN];
+       int is_allocation = 0;
 
        if (!(f = fopen(filename, "rt"))) {
                fprintf(stderr, "Could not open file %s for reading\n", filename);
+               assert(0);
                exit(0xdeadbeef);
        }
        raenv->f = f;
 
-       /* parse the file */
-       while (phase == 0) {
-               int loc, var_use_ident, var_def_ident, pos;
-               char where[16];
-
-               /* handle a spill */
-               if (fscanf(f, " spill %6s %d %d ", &where, &loc, &var_use_ident) == 3) {
-
-                       /* determine the node to insert the spill before */
-                       ir_node *anchor = pmap_get_sth(raenv->nodes, loc);
-                       assert(anchor && "insn-nr does not exist");
-                       if (!is_before(where, sizeof(where)))
-                               anchor = sched_next(anchor);
+       /* read the action */
+       if (fscanf(f, BUFCONV, buf) != 1)
+               INVALID_FILE_FORMAT;
 
-                       var_add_spill(raenv, var_use_ident, anchor);
-               }
+       /* do we spill */
+       if (!strcmp(buf, "spills")) {
+               int var_nr;
+               while (fscanf(f, " %d ", &var_nr) == 1)
+                       var_add_spills_and_reloads(raenv, var_nr);
+       } else
 
-               /* handle a reload */
-               else if (fscanf(f, " reload %s %d %d %d ", &where, &loc, &var_def_ident, &var_use_ident) == 4) {
+       /* or do we allocate */
+       if (!strcmp(buf, "allocs")) {
+               int var_nr, reg_nr;
 
-                       /* determine the node to insert the spill before */
-                       ir_node *anchor = pmap_get_sth(raenv->nodes, loc);
-                       assert(anchor && "insn-nr does not exist");
-                       if (!is_before(where, sizeof(where)))
-                               anchor = sched_next(anchor);
+               is_allocation = 1;
+               while (fscanf(f, " %d %d ", &var_nr, &reg_nr) == 2) {
+                       ir_node *irn;
+                       pset *vals = get_var_values(raenv, var_nr);
 
-                       var_add_reload(raenv, var_use_ident, var_def_ident, anchor);
+                       assert(vals && "Variable nr does not exist!");
+                       pset_foreach(vals, irn)
+                               arch_set_irn_register(raenv->aenv, irn, arch_register_for_index(raenv->cls, reg_nr));
                }
+       } else
+               INVALID_FILE_FORMAT;
 
-               /* handle a set_irn_n */
-               else if (fscanf(f, " setarg %d %d %d ", &loc, &pos, &var_use_ident) == 3) {
-                       ir_node *to_change, *new_arg;
-                       var_info_t *vi = var_find(raenv->vars, var_use_ident);
-                       assert(vi && vi->values && "New argument does not exist");
+       if (!feof(f))
+               INVALID_FILE_FORMAT;
 
-                       to_change = pmap_get_sth(raenv->nodes, loc);
-                       assert(to_change && "insn-nr does not exist");
+       fclose(f);
 
-                       new_arg = dom_up_search(vi->values, to_change);
-                       set_irn_n(to_change, pos, new_arg);
-               }
+       return is_allocation;
+}
 
-               /* handle a copy insertion */
-               else if (fscanf(f, " copy %s %d %d %d ", &where, &loc, &var_def_ident, &var_use_ident) == 4) {
-                       /* TODO
-                               Ziel der Kopie ist Variable die bereits existiert
-                               Ziel der Kopie ist eine neue Variable
-                       */
-               }
+static void check_allocation(be_raext_env_t *raenv) {
+       int i, o;
 
-               else
-                       phase++;
-       }
+       for (i=0; i<raenv->n_cls_vars; ++i) {
+               var_info_t *vi1 = raenv->cls_vars[i];
 
-       fix_reloads(raenv);
+               if (vi1->var_nr == SET_REMOVED)
+                       continue;
 
-       while (phase == 1) {
-               int var_use_ident, reg_nr;
+               for (o=0; o<i; ++o) {
+                       var_info_t *vi2 = raenv->cls_vars[o];
+                       ir_node *irn1, *irn2;
 
-               /* assign register */
-               if (fscanf(f, " assign %d %d ", &var_use_ident, &reg_nr) == 2) {
-                       pset *vals = get_var_values(raenv, var_use_ident);
-                       ir_node *irn;
+                       if (vi2->var_nr == SET_REMOVED)
+                               continue;
 
-                       assert(vals && "Variable does not (yet?) exist!");
-                       pset_foreach(vals, irn)
-                               arch_set_irn_register(raenv->aenv, irn, arch_register_for_index(raenv->cls, var_use_ident));
+                       pset_foreach(vi1->values, irn1)
+                               pset_foreach(vi2->values, irn2)
+                                       if (values_interfere(irn1, irn2) && arch_get_irn_register(raenv->aenv, irn1) == arch_get_irn_register(raenv->aenv, irn2)) {
+                                               dump_ir_block_graph_sched(raenv->irg, "ERROR");
+                                               ir_fprintf(stdout, "SSA values %+F and %+F interfere. They belong to varible %d and %d respectively.\n", irn1, irn2, vi1->var_nr, vi2->var_nr);
+                                               assert(0 && "ERROR graph dumped");
+                                       }
                }
-               else
-                       phase++;
-       }
-
-       if (!feof(f))
-               INVALID_FILE_FORMAT;
-
-       fclose(f);
-
-       /* Free the psets held in the variable-infos */
-       set_foreach(raenv->vars, vi) {
-               del_pset(vi->values);
-               del_pset(vi->spills);
-               del_pset(vi->reloads);
        }
 }
 
@@ -795,7 +910,8 @@ static int read_and_apply_results(be_raext_env_t *raenv, char *filename) {
  * Default values for options
  */
 static void (*ssa_destr)(be_raext_env_t*) = ssa_destr_simple;
-static char callee[128] = "echo";
+static char callee[128] = "\"E:/user/kimohoff/public/register allocator\"";
+//static char callee[128] = "/ben/kimohoff/ipd-registerallocator/register_allocator";
 
 
 /**
@@ -807,57 +923,76 @@ static char callee[128] = "echo";
  * Read in results and apply them
  *
  */
-static void be_ra_extern_main(const be_main_env_t *env, ir_graph *irg) {
-       be_raext_env_t raenv;
+static void be_ra_extern_main(const be_irg_t *bi) {
+       be_main_env_t *env = bi->main_env;
+       ir_graph *irg = bi->irg;
+
+       be_raext_env_t raenv;
        int clsnr, clss;
+       var_info_t *vi;
 
        compute_doms(irg);
+       edges_assure(irg);
 
        raenv.irg      = irg;
        raenv.aenv     = env->arch_env;
        raenv.dom_info = be_compute_dominance_frontiers(irg);
        raenv.vars     = new_set(compare_var_infos, 64);
-       raenv.nodes    = pmap_create();
+       raenv.dbg      = firm_dbg_register("ir.be.raextern");
+       firm_dbg_set_mask(raenv.dbg, DBG_LEVEL);
 
-       /* Insert copies */
+       /* Insert copies for constraints */
+       handle_constraints(&raenv);
+       be_dump(irg, "-extern-constr", dump_ir_block_graph_sched);
 
-       //TODO
-
-       /* SSA destruction */
+       /* SSA destruction respectively transformation into "Conventional SSA" */
        ssa_destr(&raenv);
+       be_dump(irg, "-extern-ssadestr", dump_ir_block_graph_sched);
 
        /* Mapping of SSA-Values <--> Variables */
        phi_class_compute(irg);
        be_clear_links(irg);
        irg_walk_graph(irg, values_to_vars, NULL, &raenv);
 
-       dump_ir_block_graph_sched(irg, "-extern-ssadestr");
 
        /* For all register classes */
        for(clsnr = 0, clss = arch_isa_get_n_reg_class(raenv.aenv->isa); clsnr < clss; ++clsnr) {
-               int done = 0;
+               int done, round = 1;
                char out[256], in[256];
 
                raenv.cls = arch_isa_get_reg_class(raenv.aenv->isa, clsnr);
-               ir_snprintf(out, sizeof(out), "%F-%s.ra", irg, raenv.cls->name);
-               ir_snprintf(in, sizeof(in), "%F-%s.ra.res", irg, raenv.cls->name);
 
                extract_vars_of_cls(&raenv);
 
-               while (!done) {
+               do {
+                       ir_snprintf(out, sizeof(out), "%F-%s-%d.ra", irg, raenv.cls->name, round);
+                       ir_snprintf(in, sizeof(in), "%F-%s-%d.ra.res", irg, raenv.cls->name, round);
+
+                       be_liveness(irg);
+
                        dump_to_file(&raenv, out);
                        execute(callee, out, in);
                        done = read_and_apply_results(&raenv, in);
-               }
+                       be_abi_fix_stack_nodes(bi->abi);
+
+                       ir_snprintf(in, sizeof(in), "-extern-%s-round-%d", raenv.cls->name, round);
+                       be_dump(irg, in, dump_ir_block_graph_sched);
+
+                       round++;
+               } while (!done);
+
+               check_allocation(&raenv);
 
                free(raenv.cls_vars);
        }
 
+       be_dump(irg, "-extern-alloc", dump_ir_block_graph_sched);
+
        /* Clean up */
-       pmap_destroy(raenv.nodes);
+       set_foreach(raenv.vars, vi)
+               del_pset(vi->values);
        del_set(raenv.vars);
        be_free_dominance_frontiers(raenv.dom_info);
-
 }
 
 /******************************************************************************
@@ -873,14 +1008,15 @@ static void be_ra_extern_main(const be_main_env_t *env, ir_graph *irg) {
 
 #ifdef WITH_LIBCORE
 
-static const lc_opt_enum_const_ptr_items_t ssa_destr_items[] = {
-       { "simple",    ssa_destr_simple },
-       { "rastello",  ssa_destr_rastello },
+
+static const lc_opt_enum_func_ptr_items_t ssa_destr_items[] = {
+       { "simple",     (int (*)()) ssa_destr_simple }, /* TODO make (void*) casts nicer */
+       { "rastello",   (int (*)()) ssa_destr_rastello },
        { NULL,      NULL }
 };
 
-static lc_opt_enum_const_ptr_var_t ssa_destr_var = {
-       (const void **) &ssa_destr, ssa_destr_items
+static lc_opt_enum_func_ptr_var_t ssa_destr_var = {
+        (int (**)()) &ssa_destr, ssa_destr_items
 };
 
 static const lc_opt_table_entry_t be_ra_extern_options[] = {