37d6a6e771ddad40d953ad862e427c8881206e86
[libfirm] / ir / be / beilpsched.c
1 /**
2  * Scheduling algorithms.
3  * An ILP scheduler based on
4  * "ILP-based Instruction Scheduling for IA-64"
5  * by Daniel Kaestner and Sebastian Winkel
6  *
7  * @date   22.10.2005
8  * @author Christian Wuerdig
9  * @cvs-id $Id$
10  */
11 #ifdef HAVE_CONFIG_H
12 #include "config.h"
13 #endif
14
15 #ifdef WITH_ILP
16
17 #include <math.h>
18
19 #ifndef _WIN32
20 #include <strings.h>
21 #endif /* _WIN32 */
22
23 #include "irnode_t.h"
24 #include "irgwalk.h"
25 #include "irbitset.h"
26 #include "irphase_t.h"
27 #include "height.h"
28 #include "iredges.h"
29 #include "pdeq.h"
30 #include "debug.h"
31 #include "irtools.h"
32 #include "irdump.h"
33 #include "plist.h"
34
35 #include <lpp/lpp.h>
36 #include <lpp/lpp_net.h>
37
38 #include <libcore/lc_opts.h>
39 #include <libcore/lc_opts_enum.h>
40 #include <libcore/lc_timing.h>
41
42 #include "be.h"
43 #include "benode_t.h"
44 #include "besched_t.h"
45 #include "beilpsched.h"
46 #include "beutil.h"
47
48 typedef struct _ilpsched_options_t {
49         unsigned regpress;
50         unsigned time_limit;
51         char     log_file[1024];
52 } ilpsched_options_t;
53
54 typedef struct _unit_type_info_t {
55         int                            n_units;
56         const be_execution_unit_type_t *tp;
57 } unit_type_info_t;
58
59 /**
60  * holding the ILP variables of the different types
61  */
62 typedef struct _ilp_var_types_t {
63         int *x;   /* x_{nt}^k variables */
64         int *a;   /* a_{nt}^k variables */
65         int *y;   /* y_{nt}^k variables */
66 } ilp_var_types_t;
67
68 /**
69  * Holds alive variables for a node live-in to a block.
70  */
71 typedef struct _ilp_livein_node_t {
72         ir_node  *irn;
73         unsigned max_alive_steps;
74         int      *a;
75 } ilp_livein_node_t;
76
77 /* attributes for a node */
78 typedef struct _ilpsched_node_attr_t {
79         unsigned asap;                     /**< The ASAP scheduling control step */
80         unsigned alap;                     /**< The ALAP scheduling control step */
81         unsigned latency;                  /**< Latency of this node (needed for sorting) */
82         unsigned sched_point;              /**< the step in which the node is finally scheduled */
83         unsigned visit_idx;                /**< Index of the node having visited this node last */
84         unsigned consumer_idx;             /**< Index of the node having counted this node as consumer last */
85         unsigned n_consumer;               /**< Number of consumers */
86         ir_node  **block_consumer;         /**< List of consumer being in the same block */
87         waitq    *projkeeps;               /**< A List of Projs and Keeps belonging to this node */
88         unsigned block_idx     : 30;       /**< A unique per block index */
89         unsigned alap_changed  : 1;        /**< the current ALAP has changed, revisit preds */
90         unsigned is_dummy_node : 1;        /**< this node is assigned to DUMMY unit */
91         bitset_t *transitive_block_nodes;  /**< Set of transitive block nodes (predecessors
92                                                                                         for ASAP, successors for ALAP */
93         unsigned         n_unit_types;     /**< number of allowed execution unit types */
94         unit_type_info_t *type_info;       /**< list of allowed execution unit types */
95         ilp_var_types_t  ilp_vars;         /**< the different ILP variables */
96 } ilpsched_node_attr_t;
97
98 /* attributes for a block */
99 typedef struct _ilpsched_block_attr_t {
100         unsigned block_last_idx;        /**< The highest node index in block so far */
101         unsigned n_interesting_nodes;   /**< The number of nodes interesting for scheduling */
102         unsigned max_steps;             /**< Upper bound for block execution */
103         plist_t  *root_nodes;           /**< A list of nodes having no user in current block */
104         ir_node  *head_ilp_nodes;       /**< A linked list of nodes which will contribute to ILP */
105         pset     *livein_nodes;         /**< A set of nodes which are live-in to this block */
106 } ilpsched_block_attr_t;
107
108 typedef union _ilpsched_attr_ {
109         ilpsched_node_attr_t  node_attr;
110         ilpsched_block_attr_t block_attr;
111 } ilpsched_attr_t;
112
113 /* A irn for the phase and it's attributes (either node or block) */
114 typedef struct {
115         ir_node         *irn;
116         ilpsched_attr_t attr;
117 } be_ilpsched_irn_t;
118
119 /* The ILP scheduling environment */
120 typedef struct {
121         phase_t              ph;            /**< The phase */
122         ir_graph             *irg;          /**< The current irg */
123         heights_t            *height;       /**< The heights object of the irg */
124         void                 *irg_env;      /**< An environment for the irg scheduling, provided by the backend */
125         void                 *block_env;    /**< An environment for scheduling a block, provided by the backend */
126         const arch_env_t     *arch_env;
127         const arch_isa_t     *isa;          /**< The ISA */
128         const be_main_env_t  *main_env;
129         const be_machine_t   *cpu;          /**< the current abstract machine */
130         ilpsched_options_t   *opts;         /**< the ilp options for current irg */
131         const ilp_sched_selector_t *sel;    /**< The ILP sched selector provided by the backend */
132         DEBUG_ONLY(firm_dbg_module_t *dbg);
133 } be_ilpsched_env_t;
134
135 /* convenience macros to handle phase irn data */
136 #define get_ilpsched_irn(ilpsched_env, irn) (phase_get_or_set_irn_data(&(ilpsched_env)->ph, (irn)))
137 #define is_ilpsched_block(node)             (is_Block((node)->irn))
138 #define get_ilpsched_block_attr(block)      (&(block)->attr.block_attr)
139 #define get_ilpsched_node_attr(node)        (&(node)->attr.node_attr)
140
141 /* check if node is considered for ILP scheduling */
142 #define consider_for_sched(isa, irn) \
143         (! (is_Block(irn)            ||  \
144                 is_normal_Proj(isa, irn) ||  \
145                 is_Phi(irn)              ||  \
146                 is_NoMem(irn)            ||  \
147                 is_Unknown(irn)          ||  \
148                 is_End(irn)                  \
149                 ))
150
151 /* gives the valid scheduling time step interval for a node */
152 #define VALID_SCHED_INTERVAL(na) ((na)->alap - (na)->asap + 1)
153
154 /* gives the valid interval where a node can die */
155 #define VALID_KILL_INTERVAL(ba, na) ((ba)->max_steps - (na)->asap + 1)
156
157 /* gives the corresponding ILP variable for given node, unit and time step */
158 #define ILPVAR_IDX(na, unit, control_step) \
159         ((unit) * VALID_SCHED_INTERVAL((na)) + (control_step) - (na)->asap + 1)
160
161 /* gives the corresponding dead nodes ILP variable for given node, unit and time step */
162 #define ILPVAR_IDX_DEAD(ba, na, unit, control_step) \
163         ((unit) * VALID_KILL_INTERVAL((ba), (na)) + (control_step) - (na)->asap + 1)
164
165 /* check if a double value is within an epsilon environment of 0 */
166 #define LPP_VALUE_IS_0(dbl) (fabs((dbl)) <= 1e-10)
167
168 #define ilp_timer_push(t)         lc_timer_push((t))
169 #define ilp_timer_pop()           lc_timer_pop()
170 #define ilp_timer_elapsed_usec(t) lc_timer_elapsed_usec((t))
171
172 /* option variable */
173 static ilpsched_options_t ilp_opts = {
174         1,     /* default is with register pressure constraints */
175         300,   /* 300 sec per block time limit */
176         ""     /* no log file */
177 };
178
179 /* ILP options */
180 static const lc_opt_table_entry_t ilpsched_option_table[] = {
181         LC_OPT_ENT_BOOL("regpress",  "Use register pressure constraints", &ilp_opts.regpress),
182         LC_OPT_ENT_INT("time_limit", "ILP time limit per block", &ilp_opts.time_limit),
183         LC_OPT_ENT_STR("lpp_log",    "LPP logfile (stderr and stdout are supported)", ilp_opts.log_file, sizeof(ilp_opts.log_file)),
184         { NULL }
185 };
186
187 /*
188         We need this global variable as we compare nodes dependent on heights,
189         but we cannot pass any information to the qsort compare function.
190 */
191 static heights_t *glob_heights;
192
193 /**
194  * Check if irn is a Proj, which has no execution units assigned.
195  * @return 1 if irn is a Proj having no execution units assigned, 0 otherwise
196  */
197 static INLINE int is_normal_Proj(const arch_isa_t *isa, const ir_node *irn) {
198         return is_Proj(irn) && (arch_isa_get_allowed_execution_units(isa, irn) == NULL);
199 }
200
201 /**
202  * Skips normal Projs.
203  * @return predecessor if irn is a normal Proj, otherwise irn.
204  */
205 static INLINE ir_node *skip_normal_Proj(const arch_isa_t *isa, ir_node *irn) {
206         if (is_normal_Proj(isa, irn))
207                 return get_Proj_pred(irn);
208         return irn;
209 }
210
211 static INLINE int fixed_latency(const ilp_sched_selector_t *sel, ir_node *irn, void *env) {
212         unsigned lat = be_ilp_sched_latency(sel, irn, env);
213         if (lat == 0 && ! is_Proj(irn) && ! be_is_Keep(irn))
214                 lat = 1;
215         return lat;
216 }
217
218 static int cmp_live_in_nodes(const void *a, const void *b) {
219         const ilp_livein_node_t *n1 = a;
220         const ilp_livein_node_t *n2 = b;
221
222         return n1->irn != n2->irn;
223 }
224
225 /**
226  * Compare scheduling time steps of two be_ilpsched_irn's.
227  */
228 static int cmp_ilpsched_irn(const void *a, const void *b) {
229         be_ilpsched_irn_t    *n1   = *(be_ilpsched_irn_t **)a;
230         be_ilpsched_irn_t    *n2   = *(be_ilpsched_irn_t **)b;
231         ilpsched_node_attr_t *n1_a = get_ilpsched_node_attr(n1);
232         ilpsched_node_attr_t *n2_a = get_ilpsched_node_attr(n2);
233
234         if (n1_a->sched_point == n2_a->sched_point) {
235                 ir_node *irn_a = n1->irn;
236                 ir_node *irn_b = n2->irn;
237
238                 if (heights_reachable_in_block(glob_heights, irn_a, irn_b))
239                         return 1;
240                 if (heights_reachable_in_block(glob_heights, irn_b, irn_a))
241                         return -1;
242
243                 /*
244                         Ok, timestep is equal and the nodes are parallel,
245                         so check latency and schedule high latency first.
246                 */
247                 return QSORT_CMP(n2_a->latency, n1_a->latency);
248         }
249         else
250                 return QSORT_CMP(n1_a->sched_point, n2_a->sched_point);
251 }
252
253 /**
254  * In case there is no phase information for irn, initialize it.
255  */
256 static void *init_ilpsched_irn(phase_t *ph, ir_node *irn, void *old) {
257         be_ilpsched_irn_t *res = old ? old : phase_alloc(ph, sizeof(res[0]));
258
259         if (res == old) {
260                 /* if we have already some data: check for reinitialization */
261
262                 if (! is_Block(irn)) {
263                         ilpsched_node_attr_t *na = get_ilpsched_node_attr(res);
264
265                         if (! na->transitive_block_nodes) {
266                                 ir_node               *block      = get_nodes_block(irn);
267                                 be_ilpsched_irn_t     *block_node = phase_get_or_set_irn_data(ph, block);
268                                 ilpsched_block_attr_t *ba         = get_ilpsched_block_attr(block_node);
269
270                                 /* we are called after the block indices have been build: create bitset */
271                                 na->transitive_block_nodes = bitset_obstack_alloc(phase_obst(ph), ba->block_last_idx);
272                         }
273                         else {
274                                 /* we are called from reinit block data: clear the bitset */
275                                 bitset_clear_all(na->transitive_block_nodes);
276                                 na->visit_idx    = 0;
277                                 na->alap_changed = 1;
278                         }
279                 }
280                 return old;
281         }
282
283         res->irn = irn;
284
285         /* set ilpsched irn attributes (either block or irn) */
286         if (is_Block(irn)) {
287                 ilpsched_block_attr_t *ba = get_ilpsched_block_attr(res);
288
289                 ba->n_interesting_nodes = 0;
290                 ba->block_last_idx      = 0;
291                 ba->root_nodes          = plist_new();
292                 ba->head_ilp_nodes      = NULL;
293                 ba->livein_nodes        = new_pset(cmp_live_in_nodes, 16);
294                 ba->max_steps           = 0;
295         }
296         else {
297                 ilpsched_node_attr_t *na = get_ilpsched_node_attr(res);
298                 memset(na, 0, sizeof(*na));
299         }
300
301         return res;
302 }
303
304 /**
305  * Assign a per block unique number to each node.
306  */
307 static void build_block_idx(ir_node *irn, void *walk_env) {
308         be_ilpsched_env_t     *env = walk_env;
309         be_ilpsched_irn_t     *node, *block_node;
310         ilpsched_node_attr_t  *na;
311         ilpsched_block_attr_t *ba;
312
313         if (! consider_for_sched(env->arch_env->isa, irn))
314                 return;
315
316         node       = get_ilpsched_irn(env, irn);
317         na         = get_ilpsched_node_attr(node);
318         block_node = get_ilpsched_irn(env, get_nodes_block(irn));
319         ba         = get_ilpsched_block_attr(block_node);
320
321         na->block_idx = ba->block_last_idx++;
322 }
323
324 /********************************************************
325  *                              __        _
326  *                             / /       | |
327  *   __ _ ___  __ _ _ __      / /    __ _| | __ _ _ __
328  *  / _` / __|/ _` | '_ \    / /    / _` | |/ _` | '_ \
329  * | (_| \__ \ (_| | |_) |  / /    | (_| | | (_| | |_) |
330  *  \__,_|___/\__,_| .__/  /_/      \__,_|_|\__,_| .__/
331  *                 | |                           | |
332  *                 |_|                           |_|
333  ********************************************************/
334
335 /**
336  * Add all nodes having no user in current block to last_nodes list.
337  */
338 static void collect_alap_root_nodes(ir_node *irn, void *walk_env) {
339         ir_node               *block;
340         const ir_edge_t       *edge;
341         be_ilpsched_irn_t     *block_node, *node;
342         ilpsched_block_attr_t *ba;
343         ilpsched_node_attr_t  *na;
344         int                   i, j;
345         be_ilpsched_env_t     *env           = walk_env;
346         int                   has_block_user = 0;
347         unsigned              n_consumer     = 0;
348         ir_edge_kind_t        ekind[2]       = { EDGE_KIND_NORMAL, EDGE_KIND_DEP };
349         ir_node               **consumer;
350         int                   idx;
351
352         if (! consider_for_sched(env->arch_env->isa, irn))
353                 return;
354
355         block    = get_nodes_block(irn);
356     idx      = get_irn_idx(irn);
357         consumer = NEW_ARR_F(ir_node *, 0);
358
359         DBG((env->dbg, LEVEL_3, "%+F (%+F) is interesting, examining ... ", irn, block));
360
361         /* check data and dependency out edges */
362         for (i = 0; i < 2 && ! has_block_user; ++i) {
363                 foreach_out_edge_kind(irn, edge, ekind[i]) {
364                         ir_node *user = get_edge_src_irn(edge);
365
366                         if (is_normal_Proj(env->arch_env->isa, user)) {
367                                 const ir_edge_t *user_edge;
368
369                                 if (get_irn_mode(user) == mode_X)
370                                         continue;
371
372                                 /* The ABI ensures, that there will be no ProjT nodes in the graph. */
373                                 for (j = 0; j < 2; ++j) {
374                                         foreach_out_edge_kind(user, user_edge, ekind[j]) {
375                                                 ir_node *real_user = get_edge_src_irn(user_edge);
376
377                                                 if (! is_Phi(real_user) && ! is_Block(real_user)) {
378                                                         be_ilpsched_irn_t    *node = get_ilpsched_irn(env, real_user);
379                                                         ilpsched_node_attr_t *ua   = get_ilpsched_node_attr(node);
380
381                                                         /* skip already visited nodes */
382                                                         if (ua->consumer_idx == idx)
383                                                                 continue;
384
385                                                         /* check if node has user in this block and collect the user if it's a data user */
386                                                         if (get_nodes_block(real_user) == block) {
387                                                                 if (i == 0 && j == 0)
388                                                                         ARR_APP1(ir_node *, consumer, real_user);
389                                                                 has_block_user = 1;
390                                                         }
391
392                                                         /* only count data consumer */
393                                                         if (i == 0)
394                                                                 n_consumer++;
395
396                                                         /* mark user as visited by this node */
397                                                         ua->consumer_idx = idx;
398                                                 }
399                                         }
400                                 }
401                         }
402                         else if (is_Block(user)) {
403                                 continue;
404                         }
405                         else if (! is_Phi(user)) {
406                                 be_ilpsched_irn_t    *node = get_ilpsched_irn(env, user);
407                                 ilpsched_node_attr_t *ua   = get_ilpsched_node_attr(node);
408
409                                 /* skip already visited nodes */
410                                 if (ua->consumer_idx == idx)
411                                         continue;
412
413                                 /* check if node has user in this block and collect the user if it's a data user */
414                                 if (get_nodes_block(user) == block) {
415                                         if (i == 0)
416                                                 ARR_APP1(ir_node *, consumer, user);
417                                         has_block_user = 1;
418                                 }
419
420                                 /* only count data consumer */
421                                 if (i == 0)
422                                         n_consumer++;
423
424                                 /* mark user visited by this node */
425                                 ua->consumer_idx = idx;
426                         }
427                         else if (get_nodes_block(user) != block) {
428                                 n_consumer++;
429                         }
430                 }
431         }
432
433         block_node = get_ilpsched_irn(env, block);
434         ba         = get_ilpsched_block_attr(block_node);
435
436         ba->n_interesting_nodes++;
437
438         /* current irn has no user inside this block, add to queue */
439         if (! has_block_user) {
440                 DB((env->dbg, LEVEL_3, "root node\n"));
441                 plist_insert_back(ba->root_nodes, irn);
442         }
443         else {
444                 DB((env->dbg, LEVEL_3, "normal node\n"));
445         }
446
447         /* record number of all consumer and the consumer within the same block */
448         node = get_ilpsched_irn(env, irn);
449         na   = get_ilpsched_node_attr(node);
450         na->n_consumer     = n_consumer;
451         na->block_consumer = NEW_ARR_D(ir_node *, phase_obst(&env->ph), ARR_LEN(consumer));
452         memcpy(na->block_consumer, consumer, ARR_LEN(consumer) * sizeof(na->block_consumer[0]));
453         DEL_ARR_F(consumer);
454 }
455
456 /**
457  * Calculate the ASAP scheduling step for current irn.
458  */
459 static void calculate_irn_asap(ir_node *irn, void *walk_env) {
460         be_ilpsched_env_t     *env = walk_env;
461         int                   i;
462         ir_node               *block;
463         be_ilpsched_irn_t     *node, *block_node;
464         ilpsched_node_attr_t  *na;
465         ilpsched_block_attr_t *ba;
466
467         /* These nodes are handled separate */
468         if (! consider_for_sched(env->arch_env->isa, irn))
469                 return;
470
471         DBG((env->dbg, LEVEL_2, "Calculating ASAP of node %+F ... ", irn));
472
473         block    = get_nodes_block(irn);
474         node     = get_ilpsched_irn(env, irn);
475         na       = get_ilpsched_node_attr(node);
476         na->asap = 1;
477
478         for (i = get_irn_ins_or_deps(irn) - 1; i >= 0; --i) {
479                 ir_node *pred = skip_normal_Proj(env->arch_env->isa, get_irn_in_or_dep(irn, i));
480
481                 /* check for greatest distance to top */
482                 if (! is_Phi(pred) && ! is_NoMem(pred) && get_nodes_block(pred) == block) {
483                         be_ilpsched_irn_t    *pred_node = get_ilpsched_irn(env, pred);
484                         ilpsched_node_attr_t *pna       = get_ilpsched_node_attr(pred_node);
485                         unsigned             lat;
486
487                         lat         = fixed_latency(env->sel, pred, env->block_env);
488                         na->latency = lat;
489                         na->asap    = MAX(na->asap, pna->asap + lat);
490                 }
491         }
492
493         /* add node to ILP node list and update max_steps */
494         block_node = get_ilpsched_irn(env, block);
495         ba         = get_ilpsched_block_attr(block_node);
496
497         set_irn_link(irn, ba->head_ilp_nodes);
498         ba->head_ilp_nodes = irn;
499         ba->max_steps     += fixed_latency(env->sel, irn, env->block_env);
500
501         DB((env->dbg, LEVEL_2, "%u\n", na->asap));
502 }
503
504 /**
505  * Calculate the ALAP scheduling step of all irns in current block.
506  * Depends on max_steps being calculated.
507  */
508 static void calculate_block_alap(ir_node *block, void *walk_env) {
509         be_ilpsched_env_t     *env        = walk_env;
510         be_ilpsched_irn_t     *block_node = get_ilpsched_irn(env, block);
511         ilpsched_block_attr_t *ba         = get_ilpsched_block_attr(block_node);
512         waitq                 *cur_queue  = new_waitq();
513         plist_element_t       *el;
514
515         assert(is_Block(block));
516
517         DBG((env->dbg, LEVEL_2, "Calculating ALAP for nodes in %+F (%u nodes, %u max steps)\n",
518                 block, ba->n_interesting_nodes, ba->max_steps));
519
520         /* TODO: Might be faster to use out edges and call phase_reinit_single_irn_data */
521         //phase_reinit_block_irn_data(&env->ph, block);
522
523         /* init start queue */
524         foreach_plist(ba->root_nodes, el) {
525                 waitq_put(cur_queue, plist_element_get_value(el));
526         }
527
528         /* repeat until all nodes are processed */
529         while (! waitq_empty(cur_queue)) {
530                 waitq *next_queue = new_waitq();
531
532                 /* process all nodes in current step */
533                 while (! waitq_empty(cur_queue)) {
534                         ir_node              *cur_irn = waitq_get(cur_queue);
535                         be_ilpsched_irn_t    *node    = get_ilpsched_irn(env, cur_irn);
536                         ilpsched_node_attr_t *na      = get_ilpsched_node_attr(node);
537                         int                  i;
538
539                         /* cur_node has no alap set -> it's a root node, set to max alap */
540                         if (na->alap == 0) {
541                                 na->alap = ba->max_steps;
542                                 DBG((env->dbg, LEVEL_2, "setting ALAP of node %+F to %u, handling preds:\n",
543                                         cur_irn, na->alap));
544                         }
545                         else {
546                                 DBG((env->dbg, LEVEL_2, "ALAP of node %+F is %u, handling preds:\n",
547                                         cur_irn, na->alap));
548                         }
549
550                         /* set the alap's of all predecessors */
551                         for (i = get_irn_ins_or_deps(cur_irn) - 1; i >= 0; --i) {
552                                 ir_node *pred = skip_normal_Proj(env->arch_env->isa, get_irn_in_or_dep(cur_irn, i));
553
554                                 /* check for greatest distance to bottom */
555                                 if (! is_Phi(pred) && ! is_NoMem(pred) && get_nodes_block(pred) == block) {
556                                         be_ilpsched_irn_t    *pred_node = get_ilpsched_irn(env, pred);
557                                         ilpsched_node_attr_t *pna       = get_ilpsched_node_attr(pred_node);
558                                         unsigned             lat;
559
560                                         /* mark the predecessor as visited by current irn */
561                                         if (pna->visit_idx == get_irn_idx(cur_irn) && ! na->alap_changed)
562                                                 continue;
563                                         pna->visit_idx = get_irn_idx(cur_irn);
564
565                                         lat = fixed_latency(env->sel, pred, env->block_env);
566
567                                         /* set ALAP of current pred */
568                                         if (pna->alap == 0) {
569                                                 /* current ALAP is 0: node has not yet been visited */
570                                                 pna->alap_changed = 1;
571                                                 pna->alap         = na->alap - lat;
572                                         }
573                                         else if (pna->alap > na->alap - lat) {
574                                                 /* we found a longer path to root node: change ALAP */
575                                                 pna->alap         = na->alap - lat;
576                                                 pna->alap_changed = 1;
577                                         }
578                                         else {
579                                                 /* current ALAP is best found so far: keep it */
580                                                 pna->alap_changed = 0;
581                                         }
582
583                                         DBG((env->dbg, LEVEL_2, "\tsetting ALAP of node %+F to %u\n", pred, pna->alap));
584
585                                         /* enqueue node for next iteration */
586                                         if (get_irn_ins_or_deps(pred) > 0)
587                                                 waitq_put(next_queue, pred);
588                                 }
589                         }
590                 }
591
592                 /* prepare for next iteration */
593                 del_waitq(cur_queue);
594                 cur_queue = next_queue;
595         }
596 }
597
598 /**
599  * Free list of root nodes and the set of live-in nodes.
600  */
601 static void clear_unwanted_data(ir_node *block, void *walk_env) {
602         be_ilpsched_env_t     *env        = walk_env;
603         be_ilpsched_irn_t     *block_node = get_ilpsched_irn(env, block);
604         ilpsched_block_attr_t *ba         = get_ilpsched_block_attr(block_node);
605
606         plist_free(ba->root_nodes);
607         ba->root_nodes = NULL;
608         del_pset(ba->livein_nodes);
609         ba->livein_nodes = NULL;
610 }
611
612 /**
613  * Refine the {ASAP(n), ALAP(n)} interval for the nodes.
614  * Set the ASAP/ALAP times of Projs and Keeps to their ancestor ones.
615  */
616 static void refine_asap_alap_times(ir_node *irn, void *walk_env) {
617         be_ilpsched_env_t    *env  = walk_env;
618         ir_node              *pred = irn;
619         be_ilpsched_irn_t    *node, *pred_node;
620         ilpsched_node_attr_t *na, *pna;
621
622         if (! consider_for_sched(env->arch_env->isa, irn))
623                 return;
624
625         if (! is_Proj(irn) && ! be_is_Keep(irn))
626                 return;
627
628         /* go to the ancestor */
629         if (be_is_Keep(irn))
630                 pred = get_irn_n(irn, 0);
631         pred = skip_Proj(pred);
632
633         node      = get_ilpsched_irn(env, irn);
634         pred_node = get_ilpsched_irn(env, pred);
635         na        = get_ilpsched_node_attr(node);
636         pna       = get_ilpsched_node_attr(pred_node);
637
638         na->asap = pna->asap;
639         na->alap = pna->alap;
640
641         /* record all Projs and Keeps for this node */
642         if (! pna->projkeeps)
643                 pna->projkeeps = new_waitq();
644         waitq_put(pna->projkeeps, irn);
645
646         DBG((env->dbg, LEVEL_2, "fixing ASAP/ALAP of %+F to %u/%u\n", irn, na->asap, na->alap));
647 }
648
649 /*******************************************
650  *           _              _       _
651  *          | |            | |     | |
652  *  ___  ___| |__   ___  __| |_   _| | ___
653  * / __|/ __| '_ \ / _ \/ _` | | | | |/ _ \
654  * \__ \ (__| | | |  __/ (_| | |_| | |  __/
655  * |___/\___|_| |_|\___|\__,_|\__,_|_|\___|
656  *
657  *******************************************/
658
659 static INLINE void check_for_keeps(waitq *keeps, ir_node *block, ir_node *irn) {
660         const ir_edge_t *edge;
661
662         foreach_out_edge(irn, edge) {
663                 ir_node *user = get_edge_src_irn(edge);
664
665                 if (be_is_Keep(user)) {
666                         assert(get_nodes_block(user) == block && "Keep must not be in different block.");
667                         waitq_put(keeps, user);
668                 }
669         }
670 }
671
672 /**
673  * Inserts @p irn before @p before into schedule and notifies backend.
674  */
675 static INLINE void notified_sched_add_before(be_ilpsched_env_t *env,
676         ir_node *before, ir_node *irn, unsigned cycle)
677 {
678         be_ilp_sched_node_scheduled(env->sel, irn, cycle, env->block_env);
679         sched_add_before(before, irn);
680 }
681
682 /**
683  * Adds a node, it's Projs (in case of mode_T nodes) and
684  * it's Keeps to schedule.
685  */
686 static void add_to_sched(be_ilpsched_env_t *env, ir_node *block, ir_node *irn, unsigned cycle) {
687         const ir_edge_t *edge;
688         waitq           *keeps = new_waitq();
689
690         /* mode_M nodes are not scheduled */
691         if (get_irn_mode(irn) == mode_M)
692                 return;
693
694         if (! sched_is_scheduled(irn))
695                 notified_sched_add_before(env, block, irn, cycle);
696
697         /* add Projs */
698         if (get_irn_mode(irn) == mode_T) {
699                 foreach_out_edge(irn, edge) {
700                         ir_node *user = get_edge_src_irn(edge);
701
702                         if ((to_appear_in_schedule(user) || get_irn_mode(user) == mode_b) &&
703                                 get_irn_n_edges(user) > 0)
704                         {
705                                 notified_sched_add_before(env, block, user, cycle);
706                         }
707
708                         check_for_keeps(keeps, block, user);
709                 }
710         }
711         else {
712                 check_for_keeps(keeps, block, irn);
713         }
714
715         /* add Keeps */
716         while (! waitq_empty(keeps)) {
717                 ir_node *keep = waitq_get(keeps);
718                 if (! sched_is_scheduled(keep))
719                         notified_sched_add_before(env, block, keep, cycle);
720         }
721
722         del_waitq(keeps);
723 }
724
725 /**
726  * Schedule all nodes in the given block, according to the ILP solution.
727  */
728 static void apply_solution(be_ilpsched_env_t *env, lpp_t *lpp, ir_node *block) {
729         be_ilpsched_irn_t     *block_node = get_ilpsched_irn(env, block);
730         ilpsched_block_attr_t *ba         = get_ilpsched_block_attr(block_node);
731         sched_info_t          *info       = get_irn_sched_info(block);
732         be_ilpsched_irn_t     **sched_nodes;
733         unsigned              i, l;
734         ir_node               *cfop, *irn;
735         const ir_edge_t       *edge;
736
737         /* init block schedule list */
738         INIT_LIST_HEAD(&info->list);
739         info->scheduled = 1;
740
741         /* collect nodes and their scheduling time step */
742         sched_nodes = NEW_ARR_F(be_ilpsched_irn_t *, 0);
743         if (ba->n_interesting_nodes == 0) {
744                 /* ignore */
745         }
746         else if (ba->n_interesting_nodes == 1) {
747                 be_ilpsched_irn_t *node = get_ilpsched_irn(env, ba->head_ilp_nodes);
748
749                 /* add the single node */
750                 ARR_APP1(be_ilpsched_irn_t *, sched_nodes, node);
751         }
752         else {
753                 /* check all nodes for their positive solution */
754                 foreach_linked_irns(ba->head_ilp_nodes, irn) {
755                         be_ilpsched_irn_t    *node;
756                         ilpsched_node_attr_t *na;
757                         int                  tp_idx, found;
758                         unsigned             cur_var, t;
759
760                         node    = get_ilpsched_irn(env, irn);
761                         na      = get_ilpsched_node_attr(node);
762                         cur_var = 0;
763                         found   = 0;
764
765                         if (! na->is_dummy_node) {
766                                 for (tp_idx = na->n_unit_types - 1; ! found && tp_idx >= 0; --tp_idx) {
767                                         for (t = na->asap - 1; ! found && t <= na->alap - 1; ++t) {
768                                                 double cost = lpp_get_var_sol(lpp, na->ilp_vars.y[cur_var]);
769
770                                                 if (! LPP_VALUE_IS_0(cost)) {
771                                                         DBG((env->dbg, LEVEL_3, "%+F has additional regpressure costs of %f\n", irn, cost));
772                                                         found = 1;
773                                                 }
774                                         }
775                                 }
776                         }
777
778                         found = 0;
779                         /* go over all variables of a node until the non-zero one is found */
780                         for (tp_idx = na->n_unit_types - 1; ! found && tp_idx >= 0; --tp_idx) {
781                                 for (t = na->asap - 1; ! found && t <= na->alap - 1; ++t) {
782                                         double val = lpp_get_var_sol(lpp, na->ilp_vars.x[cur_var++]);
783
784                                         /* check, if variable is set to one (it's not zero then :) */
785                                         if (! LPP_VALUE_IS_0(val)) {
786                                                 na->sched_point = t;
787                                                 ARR_APP1(be_ilpsched_irn_t *, sched_nodes, node);
788                                                 DBG((env->dbg, LEVEL_2, "Schedpoint of %+F is %u at unit type %s\n",
789                                                         irn, t, na->type_info[tp_idx].tp->name));
790                                                 found = 1;
791                                         }
792                                 }
793                         }
794                 }
795
796                 glob_heights = env->height;
797                 /* sort nodes ascending by scheduling time step */
798                 qsort(sched_nodes, ARR_LEN(sched_nodes), sizeof(sched_nodes[0]), cmp_ilpsched_irn);
799         }
800
801         /* make all Phis ready and remember the single cf op */
802         cfop = NULL;
803         foreach_out_edge(block, edge) {
804                 irn = get_edge_src_irn(edge);
805
806                 switch (get_irn_opcode(irn)) {
807                         case iro_Phi:
808                                 add_to_sched(env, block, irn, 0);
809                                 break;
810                         case iro_Start:
811                         case iro_End:
812                         case iro_Proj:
813                         case iro_Bad:
814                         case iro_Unknown:
815                                 break;
816                         default:
817                                 if (is_cfop(irn)) {
818                                         assert(cfop == NULL && "Highlander - there can be only one");
819                                         cfop = irn;
820                                 }
821                         break;
822                 }
823         }
824
825         /* add all nodes from list */
826         for (i = 0, l = ARR_LEN(sched_nodes); i < l; ++i) {
827                 ilpsched_node_attr_t *na = get_ilpsched_node_attr(sched_nodes[i]);
828                 if (sched_nodes[i]->irn != cfop)
829                         add_to_sched(env, block, sched_nodes[i]->irn, na->sched_point);
830         }
831
832         /* schedule control flow node if not already done */
833         if (cfop && ! sched_is_scheduled(cfop))
834                 add_to_sched(env, block, cfop, 0);
835
836         DEL_ARR_F(sched_nodes);
837 }
838
839 /***************************************************************
840  *   _____ _      _____     _____           _   _
841  *  |_   _| |    |  __ \   / ____|         | | (_)
842  *    | | | |    | |__) | | (___   ___  ___| |_ _  ___  _ __
843  *    | | | |    |  ___/   \___ \ / _ \/ __| __| |/ _ \| '_ \
844  *   _| |_| |____| |       ____) |  __/ (__| |_| | (_) | | | |
845  *  |_____|______|_|      |_____/ \___|\___|\__|_|\___/|_| |_|
846  *
847  ***************************************************************/
848
849 /**
850  * Check if node can be executed on given unit type.
851  */
852 static INLINE int is_valid_unit_type_for_node(const be_execution_unit_type_t *tp, be_ilpsched_irn_t *node) {
853         int                  i;
854         ilpsched_node_attr_t *na = get_ilpsched_node_attr(node);
855
856         for (i = na->n_unit_types - 1; i >= 0; --i) {
857                 if (na->type_info[i].tp == tp)
858                         return i;
859         }
860
861         return -1;
862 }
863
864 /************************************************
865  *                   _       _     _
866  *                  (_)     | |   | |
867  *  __   ____ _ _ __ _  __ _| |__ | | ___  ___
868  *  \ \ / / _` | '__| |/ _` | '_ \| |/ _ \/ __|
869  *   \ V / (_| | |  | | (_| | |_) | |  __/\__ \
870  *    \_/ \__,_|_|  |_|\__,_|_.__/|_|\___||___/
871  *
872  ************************************************/
873
874 static int be_ilpsched_set_type_info(be_ilpsched_env_t *env, ir_node *irn, struct obstack *obst) {
875         const be_execution_unit_t ***execunits = arch_isa_get_allowed_execution_units(env->arch_env->isa, irn);
876         unsigned                  n_unit_types = 0;
877         be_ilpsched_irn_t         *node;
878         ilpsched_node_attr_t      *na;
879         unsigned                  unit_idx, tp_idx;
880
881         /* count number of available unit types for this node */
882         for (n_unit_types = 0; execunits[n_unit_types]; ++n_unit_types)
883                 /* just count */ ;
884
885         node = get_ilpsched_irn(env, irn);
886         na   = get_ilpsched_node_attr(node);
887
888         if (! na->type_info) {
889                 na->n_unit_types = n_unit_types;
890                 na->type_info    = NEW_ARR_D(unit_type_info_t, obst, n_unit_types);
891
892                 /* fill the type info array */
893                 for (tp_idx = 0; tp_idx < n_unit_types; ++tp_idx) {
894                         for (unit_idx = 0; execunits[tp_idx][unit_idx]; ++unit_idx) {
895                                 /* beware: we also count number of available units here */
896                                 if (be_machine_is_dummy_unit(execunits[tp_idx][unit_idx]))
897                                         na->is_dummy_node = 1;
898                         }
899
900                         na->type_info[tp_idx].tp      = execunits[tp_idx][0]->tp;
901                         na->type_info[tp_idx].n_units = unit_idx;
902                 }
903         }
904
905         return n_unit_types;
906 }
907
908 /**
909  * Returns the largest alap time of a user of @p irn.
910  * The user must be in block @p block.
911  */
912 static unsigned be_ilpsched_get_max_alap_user(be_ilpsched_env_t *env, ir_node *irn, ir_node *block) {
913         const ir_edge_t *edge;
914         unsigned        max_alap = 0;
915
916         foreach_out_edge(irn, edge) {
917                 ir_node *user = get_edge_src_irn(edge);
918
919                 if (get_nodes_block(user) == block) {
920                         be_ilpsched_irn_t    *node = get_ilpsched_irn(env, user);
921                         ilpsched_node_attr_t *na   = get_ilpsched_node_attr(node);
922
923                         max_alap = MAX(max_alap, na->alap);
924                 }
925         }
926
927         assert(max_alap > 0);
928         return max_alap;
929 }
930
931 /**
932  * Create the following variables:
933  * - x_{nt}^k    binary     weigthed with: t
934  *      node n is scheduled at time step t to unit type k
935  * ==>> These variables represent the schedule
936  *
937  * - a_{nt}^k    binary     weighted with num_nodes
938  *      node n is alive at time step t on unit type k
939  *
940  * - y_{nt}^k    continuous  weighted with: num_nodes^2
941  *      register pressure over limit for unit type k
942  * ==>> These variables represent the register pressure
943  *
944  */
945 static void create_variables(be_ilpsched_env_t *env, lpp_t *lpp, be_ilpsched_irn_t *block_node, struct obstack *var_obst) {
946         char                  buf[1024];
947         ir_node               *irn;
948         unsigned              num_block_var, num_nodes;
949         ilp_livein_node_t     *livein;
950         ilpsched_block_attr_t *ba      = get_ilpsched_block_attr(block_node);
951         unsigned              weigth_y = ba->n_interesting_nodes * ba->n_interesting_nodes;
952         lc_timer_t            *t_var   = lc_timer_register("beilpsched_var", "create ilp variables");
953
954         ilp_timer_push(t_var);
955         num_block_var = num_nodes = 0;
956         foreach_linked_irns(ba->head_ilp_nodes, irn) {
957                 be_ilpsched_irn_t    *node;
958                 ilpsched_node_attr_t *na;
959                 unsigned             n_unit_types, tp_idx, n_var, cur_unit;
960                 unsigned             cur_var_ad, cur_var_x, cur_var_y, num_ad;
961                 int                  i;
962
963                 node         = get_ilpsched_irn(env, irn);
964                 na           = get_ilpsched_node_attr(node);
965                 n_unit_types = be_ilpsched_set_type_info(env, irn, var_obst);
966
967                 /* allocate space for ilp variables */
968                 na->ilp_vars.x = NEW_ARR_D(int, var_obst, n_unit_types * VALID_SCHED_INTERVAL(na));
969                 memset(na->ilp_vars.x, -1, ARR_LEN(na->ilp_vars.x) * sizeof(na->ilp_vars.x[0]));
970
971                 /* we need these variables only for "real" nodes */
972                 if (! na->is_dummy_node) {
973                         na->ilp_vars.y = NEW_ARR_D(int, var_obst, n_unit_types * VALID_SCHED_INTERVAL(na));
974                         memset(na->ilp_vars.y, -1, ARR_LEN(na->ilp_vars.y) * sizeof(na->ilp_vars.y[0]));
975
976                         num_ad         = ba->max_steps - na->asap + 1;
977                         na->ilp_vars.a = NEW_ARR_D(int, var_obst, n_unit_types * num_ad);
978                         memset(na->ilp_vars.a, -1, ARR_LEN(na->ilp_vars.a) * sizeof(na->ilp_vars.a[0]));
979                 }
980
981                 DBG((env->dbg, LEVEL_3, "\thandling %+F (asap %u, alap %u, unit types %u):\n",
982                         irn, na->asap, na->alap, na->n_unit_types));
983
984                 cur_var_x = cur_var_ad = cur_var_y = cur_unit = n_var = 0;
985                 /* create variables */
986                 for (tp_idx = 0; tp_idx < n_unit_types; ++tp_idx) {
987                         unsigned t;
988
989                         for (t = na->asap - 1; t <= na->alap - 1; ++t) {
990                                 /* x_{nt}^k variables */
991                                 snprintf(buf, sizeof(buf), "x_n%u_%s_%u",
992                                         get_irn_idx(irn), na->type_info[tp_idx].tp->name, t);
993                                 na->ilp_vars.x[cur_var_x++] = lpp_add_var(lpp, buf, lpp_binary, (double)(t + 1));
994                                 DBG((env->dbg, LEVEL_4, "\t\tcreated ILP variable %s\n", buf));
995                                 /* variable counter */
996                                 n_var++;
997                                 num_block_var++;
998
999                                 if (! na->is_dummy_node) {
1000                                         /* y_{nt}^k variables */
1001                                         snprintf(buf, sizeof(buf), "y_n%u_%s_%u",
1002                                                 get_irn_idx(irn), na->type_info[tp_idx].tp->name, t);
1003                                         na->ilp_vars.y[cur_var_y++] = lpp_add_var(lpp, buf, lpp_continous, (double)(weigth_y));
1004                                         DBG((env->dbg, LEVEL_4, "\t\tcreated ILP variable %s\n", buf));
1005
1006                                         /* variable counter */
1007                                         n_var++;
1008                                         num_block_var++;
1009                                 }
1010                         }
1011
1012                         /* a node can die at any step t: asap(n) <= t <= U */
1013                         if (! na->is_dummy_node) {
1014                                 for (t = na->asap - 1; t <= ba->max_steps; ++t) {
1015
1016                                         /* a_{nt}^k variables */
1017                                         snprintf(buf, sizeof(buf), "a_n%u_%s_%u",
1018                                                 get_irn_idx(irn), na->type_info[tp_idx].tp->name, t);
1019                                         na->ilp_vars.a[cur_var_ad++] = lpp_add_var(lpp, buf, lpp_binary, (double)(ba->n_interesting_nodes));
1020                                         DBG((env->dbg, LEVEL_4, "\t\tcreated ILP variable %s\n", buf));
1021
1022                                         /* variable counter */
1023                                         n_var++;
1024                                         num_block_var++;
1025                                 }
1026                         }
1027
1028                         /* collect live-in nodes */
1029                         for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
1030                                 ir_node *pred = get_irn_n(irn, i);
1031
1032                                 if (get_nodes_block(pred) != block_node->irn && consider_for_sched(env->arch_env->isa, pred)) {
1033                                         be_ilpsched_set_type_info(env, pred, var_obst);
1034                                         if (! na->is_dummy_node) {
1035                                                 ilp_livein_node_t *entry = obstack_alloc(var_obst, sizeof(*entry));
1036                                                 entry->irn = pred;
1037                                                 entry->a   = NULL;
1038                                                 pset_insert(ba->livein_nodes, entry, (unsigned)get_irn_idx(pred));
1039                                         }
1040                                 }
1041                         }
1042                 }
1043
1044                 DB((env->dbg, LEVEL_3, "%u variables created\n", n_var));
1045                 num_nodes++;
1046         }
1047
1048         /* create alive variables a_{nt}^k for live-ins */
1049         foreach_pset(ba->livein_nodes, livein) {
1050                 be_ilpsched_irn_t    *node;
1051                 ilpsched_node_attr_t *na;
1052                 unsigned             tp_idx, var_idx;
1053                 ir_node              *irn;
1054
1055                 irn  = livein->irn;
1056                 node = get_ilpsched_irn(env, irn);
1057                 na   = get_ilpsched_node_attr(node);
1058
1059                 livein->max_alive_steps = be_ilpsched_get_max_alap_user(env, irn, block_node->irn);
1060
1061                 livein->a = NEW_ARR_D(int, var_obst, na->n_unit_types * livein->max_alive_steps);
1062                 var_idx   = 0;
1063
1064                 /* create variables */
1065                 for (tp_idx = 0; tp_idx < na->n_unit_types; ++tp_idx) {
1066                         unsigned t;
1067
1068                         for (t = 0; t < livein->max_alive_steps; ++t) {
1069                                 /* a_{nt}^k variables */
1070                                 snprintf(buf, sizeof(buf), "al_n%u_%s_%u",
1071                                         get_irn_idx(irn), na->type_info[tp_idx].tp->name, t);
1072                                 livein->a[var_idx++] = lpp_add_var(lpp, buf, lpp_binary, (double)(ba->n_interesting_nodes));
1073                                 DBG((env->dbg, LEVEL_4, "\t\tcreated ILP variable %s\n", buf));
1074                                 num_block_var++;
1075                         }
1076                 }
1077         }
1078
1079         ilp_timer_pop();
1080         DBG((env->dbg, LEVEL_1, "... %u variables for %u nodes created (%g sec)\n",
1081                 num_block_var, num_nodes, ilp_timer_elapsed_usec(t_var) / 1000000.0));
1082 }
1083
1084 /*******************************************************
1085  *                      _             _       _
1086  *                     | |           (_)     | |
1087  *   ___ ___  _ __  ___| |_ _ __ __ _ _ _ __ | |_ ___
1088  *  / __/ _ \| '_ \/ __| __| '__/ _` | | '_ \| __/ __|
1089  * | (_| (_) | | | \__ \ |_| | | (_| | | | | | |_\__ \
1090  *  \___\___/|_| |_|___/\__|_|  \__,_|_|_| |_|\__|___/
1091  *
1092  *******************************************************/
1093
1094 /**
1095  * Create following ILP constraints:
1096  * - the assignment constraints:
1097  *     assure each node is executed once by exactly one (allowed) execution unit
1098  * - the dead node assignment constraints:
1099  *     assure a node can only die at most once
1100  * - the precedence constraints:
1101  *     assure that no data dependencies are violated
1102  */
1103 static void create_assignment_and_precedence_constraints(be_ilpsched_env_t *env, lpp_t *lpp, be_ilpsched_irn_t *block_node) {
1104         unsigned              num_cst_assign, num_cst_prec, num_cst_dead;
1105         char                  buf[1024];
1106         ir_node               *irn;
1107         ilpsched_block_attr_t *ba            = get_ilpsched_block_attr(block_node);
1108         bitset_t              *bs_block_irns = bitset_alloca(ba->block_last_idx);
1109         lc_timer_t            *t_cst_assign  = lc_timer_register("beilpsched_cst_assign", "create assignment constraints");
1110         lc_timer_t            *t_cst_prec    = lc_timer_register("beilpsched_cst_prec",   "create precedence constraints");
1111
1112         num_cst_assign = num_cst_prec = num_cst_dead = 0;
1113         foreach_linked_irns(ba->head_ilp_nodes, irn) {
1114                 int                  cst, tp_idx, i;
1115                 unsigned             cur_var;
1116                 be_ilpsched_irn_t    *node;
1117                 ilpsched_node_attr_t *na;
1118
1119                 node    = get_ilpsched_irn(env, irn);
1120                 na      = get_ilpsched_node_attr(node);
1121                 cur_var = 0;
1122
1123                 /* the assignment constraint */
1124                 ilp_timer_push(t_cst_assign);
1125                 snprintf(buf, sizeof(buf), "assignment_cst_n%u", get_irn_idx(irn));
1126                 cst = lpp_add_cst_uniq(lpp, buf, lpp_equal, 1.0);
1127                 DBG((env->dbg, LEVEL_2, "added constraint %s\n", buf));
1128                 num_cst_assign++;
1129
1130                 lpp_set_factor_fast_bulk(lpp, cst, na->ilp_vars.x, ARR_LEN(na->ilp_vars.x), 1.0);
1131                 ilp_timer_pop();
1132
1133                 /* We have separate constraints for Projs and Keeps */
1134                 // ILP becomes infeasible ?!?
1135 //              if (is_Proj(irn) || be_is_Keep(irn))
1136 //                      continue;
1137
1138                 /* the precedence constraints */
1139                 ilp_timer_push(t_cst_prec);
1140                 bs_block_irns = bitset_clear_all(bs_block_irns);
1141                 for (i = get_irn_ins_or_deps(irn) - 1; i >= 0; --i) {
1142                         ir_node              *pred = skip_normal_Proj(env->arch_env->isa, get_irn_in_or_dep(irn, i));
1143                         unsigned             t_low, t_high, t;
1144                         be_ilpsched_irn_t    *pred_node;
1145                         ilpsched_node_attr_t *pna;
1146                         unsigned             delay;
1147
1148                         if (is_Phi(pred) || block_node->irn != get_nodes_block(pred) || is_NoMem(pred))
1149                                 continue;
1150
1151                         pred_node = get_ilpsched_irn(env, pred);
1152                         pna       = get_ilpsched_node_attr(pred_node);
1153
1154                         assert(pna->asap > 0 && pna->alap >= pna->asap && "Invalid scheduling interval.");
1155
1156                         if (! bitset_is_set(bs_block_irns, pna->block_idx))
1157                                 bitset_set(bs_block_irns, pna->block_idx);
1158                         else
1159                                 continue;
1160
1161                         /* irn = n, pred = m */
1162                         delay  = fixed_latency(env->sel, pred, env->block_env);
1163                         t_low  = MAX(na->asap, pna->asap + delay - 1);
1164                         t_high = MIN(na->alap, pna->alap + delay - 1);
1165                         for (t = t_low - 1; t <= t_high - 1; ++t) {
1166                                 unsigned tn, tm;
1167                                 int      *tmp_var_idx = NEW_ARR_F(int, 0);
1168
1169                                 snprintf(buf, sizeof(buf), "precedence_n%u_n%u_%u", get_irn_idx(pred), get_irn_idx(irn), t);
1170                                 cst = lpp_add_cst_uniq(lpp, buf, lpp_less, 1.0);
1171                                 DBG((env->dbg, LEVEL_2, "added constraint %s\n", buf));
1172                                 num_cst_prec++;
1173
1174                                 /* lpp_set_factor_fast_bulk needs variables sorted ascending by index */
1175                                 if (na->ilp_vars.x[0] < pna->ilp_vars.x[0]) {
1176                                         /* node variables have smaller index than pred variables */
1177                                         for (tp_idx = na->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1178                                                 for (tn = na->asap - 1; tn <= t; ++tn) {
1179                                                         unsigned idx = ILPVAR_IDX(na, tp_idx, tn);
1180                                                         ARR_APP1(int, tmp_var_idx, na->ilp_vars.x[idx]);
1181                                                 }
1182                                         }
1183
1184                                         for (tp_idx = pna->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1185                                                 for (tm = t - delay + 1; tm < pna->alap; ++tm) {
1186                                                         unsigned idx = ILPVAR_IDX(pna, tp_idx, tm);
1187                                                         ARR_APP1(int, tmp_var_idx, pna->ilp_vars.x[idx]);
1188                                                 }
1189                                         }
1190                                 }
1191                                 else {
1192                                         /* pred variables have smaller index than node variables */
1193                                         for (tp_idx = pna->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1194                                                 for (tm = t - delay + 1; tm < pna->alap; ++tm) {
1195                                                         unsigned idx = ILPVAR_IDX(pna, tp_idx, tm);
1196                                                         ARR_APP1(int, tmp_var_idx, pna->ilp_vars.x[idx]);
1197                                                 }
1198                                         }
1199
1200                                         for (tp_idx = na->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1201                                                 for (tn = na->asap - 1; tn <= t; ++tn) {
1202                                                         unsigned idx = ILPVAR_IDX(na, tp_idx, tn);
1203                                                         ARR_APP1(int, tmp_var_idx, na->ilp_vars.x[idx]);
1204                                                 }
1205                                         }
1206                                 }
1207
1208                                 if (ARR_LEN(tmp_var_idx) > 0)
1209                                         lpp_set_factor_fast_bulk(lpp, cst, tmp_var_idx, ARR_LEN(tmp_var_idx), 1.0);
1210
1211                                 DEL_ARR_F(tmp_var_idx);
1212                         }
1213                 }
1214                 ilp_timer_pop();
1215         }
1216         DBG((env->dbg, LEVEL_1, "\t%u assignement constraints (%g sec)\n",
1217                 num_cst_assign, ilp_timer_elapsed_usec(t_cst_assign) / 1000000.0));
1218         DBG((env->dbg, LEVEL_1, "\t%u precedence constraints (%g sec)\n",
1219                 num_cst_prec, ilp_timer_elapsed_usec(t_cst_prec) / 1000000.0));
1220 }
1221
1222 /**
1223  * Create ILP resource constraints:
1224  * - assure that for each time step not more instructions are scheduled
1225  *   to the same unit types as units of this type are available
1226  */
1227 static void create_ressource_constraints(be_ilpsched_env_t *env, lpp_t *lpp, be_ilpsched_irn_t *block_node) {
1228         int                   glob_type_idx;
1229         char                  buf[1024];
1230         unsigned              num_cst_resrc = 0;
1231         ilpsched_block_attr_t *ba           = get_ilpsched_block_attr(block_node);
1232         lc_timer_t            *t_cst_rsrc   = lc_timer_register("beilpsched_cst_rsrc",   "create resource constraints");
1233
1234         ilp_timer_push(t_cst_rsrc);
1235         for (glob_type_idx = env->cpu->n_unit_types - 1; glob_type_idx >= 0; --glob_type_idx) {
1236                 unsigned                 t;
1237                 be_execution_unit_type_t *cur_tp = &env->cpu->unit_types[glob_type_idx];
1238
1239                 /* BEWARE: the DUMMY unit type is not in CPU, so it's skipped automatically */
1240
1241                 /* check each time step */
1242                 for (t = 0; t < ba->max_steps; ++t) {
1243                         ir_node *irn;
1244                         int     cst;
1245                         int     *tmp_var_idx = NEW_ARR_F(int, 0);
1246
1247                         snprintf(buf, sizeof(buf), "resource_cst_%s_%u", cur_tp->name, t);
1248                         cst = lpp_add_cst_uniq(lpp, buf, lpp_less, (double)cur_tp->n_units);
1249                         DBG((env->dbg, LEVEL_2, "added constraint %s\n", buf));
1250                         num_cst_resrc++;
1251
1252                         foreach_linked_irns(ba->head_ilp_nodes, irn) {
1253                                 be_ilpsched_irn_t    *node = get_ilpsched_irn(env, irn);
1254                                 ilpsched_node_attr_t *na   = get_ilpsched_node_attr(node);
1255                                 int                  tp_idx;
1256
1257                                 tp_idx = is_valid_unit_type_for_node(cur_tp, node);
1258
1259                                 if (tp_idx >= 0 && t >= na->asap - 1 && t <= na->alap - 1) {
1260                                         int cur_var = ILPVAR_IDX(na, tp_idx, t);
1261                                         ARR_APP1(int, tmp_var_idx, na->ilp_vars.x[cur_var]);
1262                                 }
1263                         }
1264
1265                         /* set constraints if we have some */
1266                         if (ARR_LEN(tmp_var_idx) > 0)
1267                                 lpp_set_factor_fast_bulk(lpp, cst, tmp_var_idx, ARR_LEN(tmp_var_idx), 1.0);
1268
1269                         DEL_ARR_F(tmp_var_idx);
1270                 }
1271         }
1272         ilp_timer_pop();
1273         DBG((env->dbg, LEVEL_1, "\t%u resource constraints (%g sec)\n",
1274                 num_cst_resrc, ilp_timer_elapsed_usec(t_cst_rsrc) / 1000000.0));
1275 }
1276
1277 /**
1278  * Create ILP bundle constraints:
1279  * - assure, at most bundle_size * bundles_per_cycle instructions
1280  *   can be started at a certain point.
1281  */
1282 static void create_bundle_constraints(be_ilpsched_env_t *env, lpp_t *lpp, be_ilpsched_irn_t *block_node) {
1283         char                  buf[1024];
1284         unsigned              t;
1285         unsigned              num_cst_bundle = 0;
1286         unsigned              n_instr_max    = env->cpu->bundle_size * env->cpu->bundels_per_cycle;
1287         ilpsched_block_attr_t *ba            = get_ilpsched_block_attr(block_node);
1288         lc_timer_t            *t_cst_bundle  = lc_timer_register("beilpsched_cst_bundle", "create bundle constraints");
1289
1290         ilp_timer_push(t_cst_bundle);
1291         for (t = 0; t < ba->max_steps; ++t) {
1292                 ir_node *irn;
1293                 int     cst;
1294                 int     *tmp_var_idx = NEW_ARR_F(int, 0);
1295
1296                 snprintf(buf, sizeof(buf), "bundle_cst_%u", t);
1297                 cst = lpp_add_cst_uniq(lpp, buf, lpp_less, (double)n_instr_max);
1298                 DBG((env->dbg, LEVEL_2, "added constraint %s\n", buf));
1299                 num_cst_bundle++;
1300
1301                 foreach_linked_irns(ba->head_ilp_nodes, irn) {
1302                         be_ilpsched_irn_t    *node;
1303                         ilpsched_node_attr_t *na;
1304                         int                  tp_idx;
1305
1306                         /* Projs and Keeps do not contribute to bundle size */
1307                         if (is_Proj(irn) || be_is_Keep(irn))
1308                                 continue;
1309
1310                         node = get_ilpsched_irn(env, irn);
1311                         na   = get_ilpsched_node_attr(node);
1312
1313                         /* nodes assigned to DUMMY unit do not contribute to bundle size */
1314                         if (na->is_dummy_node)
1315                                 continue;
1316
1317                         if (t >= na->asap - 1 && t <= na->alap - 1) {
1318                                 for (tp_idx = na->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1319                                         int idx = ILPVAR_IDX(na, tp_idx, t);
1320                                         ARR_APP1(int, tmp_var_idx, na->ilp_vars.x[idx]);
1321                                 }
1322                         }
1323                 }
1324
1325                 if (ARR_LEN(tmp_var_idx) > 0)
1326                         lpp_set_factor_fast_bulk(lpp, cst, tmp_var_idx, ARR_LEN(tmp_var_idx), 1.0);
1327
1328                 DEL_ARR_F(tmp_var_idx);
1329         }
1330         ilp_timer_pop();
1331         DBG((env->dbg, LEVEL_1, "\t%u bundle constraints (%g sec)\n",
1332                 num_cst_bundle, ilp_timer_elapsed_usec(t_cst_bundle) / 1000000.0));
1333 }
1334
1335 /**
1336  * Create ILP alive nodes constraints:
1337  * - set variable a_{nt}^k to 1 if nodes n is alive at step t on unit k
1338  */
1339 static void create_alive_nodes_constraint(be_ilpsched_env_t *env, lpp_t *lpp, be_ilpsched_irn_t *block_node) {
1340         char                  buf[1024];
1341         ir_node               *irn;
1342         unsigned              num_cst = 0;
1343         ilpsched_block_attr_t *ba     = get_ilpsched_block_attr(block_node);
1344         lc_timer_t            *t_cst  = lc_timer_register("beilpsched_cst_alive_nodes", "create alive nodes constraints");
1345
1346         ilp_timer_push(t_cst);
1347         /* for each node */
1348         foreach_linked_irns(ba->head_ilp_nodes, irn) {
1349                 be_ilpsched_irn_t    *node = get_ilpsched_irn(env, irn);
1350                 ilpsched_node_attr_t *na   = get_ilpsched_node_attr(node);
1351                 unsigned             t;
1352
1353                 /* we ignore nodes assigned to dummy unit here */
1354                 if (na->is_dummy_node)
1355                         continue;
1356
1357                 /* check check all time steps: asap(n) <= t <= U */
1358                 for (t = na->asap - 1; t < ba->max_steps; ++t) {
1359                         int node_tp_idx;
1360
1361                         /* for all unit types available for this node */
1362                         for (node_tp_idx = na->n_unit_types - 1; node_tp_idx >= 0; --node_tp_idx) {
1363                                 unsigned tn, tn_max, idx;
1364                                 int      cst, i;
1365                                 int      *tmp_var_idx_n = NEW_ARR_F(int, 0);
1366                                 int      *tmp_var_idx_m = NEW_ARR_F(int, 0);
1367
1368                                 snprintf(buf, sizeof(buf), "alive_node_cst_%u_n%u_%s",
1369                                         t, get_irn_idx(irn), na->type_info[node_tp_idx].tp->name);
1370                                 cst = lpp_add_cst_uniq(lpp, buf, lpp_less, 0.0);
1371                                 DBG((env->dbg, LEVEL_2, "added constraint %s\n", buf));
1372                                 num_cst++;
1373
1374                                 tn_max = MIN(na->alap - 1, t);
1375                                 /* check if the node has been scheduled so far */
1376                                 for (tn = na->asap - 1; tn <= tn_max; ++tn) {
1377                                         int idx = ILPVAR_IDX(na, node_tp_idx, tn);
1378                                         ARR_APP1(int, tmp_var_idx_n, na->ilp_vars.x[idx]);
1379                                 }
1380
1381                                 if (ARR_LEN(tmp_var_idx_n) > 0)
1382                                         lpp_set_factor_fast_bulk(lpp, cst, tmp_var_idx_n, ARR_LEN(tmp_var_idx_n), (double)(na->n_consumer));
1383                                 DEL_ARR_F(tmp_var_idx_n);
1384
1385                                 /* subtract the number of consumer scheduled so far */
1386                                 for (i = ARR_LEN(na->block_consumer) - 1; i >= 0; --i) {
1387                                         be_ilpsched_irn_t    *cons = get_ilpsched_irn(env, na->block_consumer[i]);
1388                                         ilpsched_node_attr_t *ca   = get_ilpsched_node_attr(cons);
1389                                         int                  tp_idx;
1390                                         unsigned             tm, tm_max;
1391
1392                                         tm_max = MIN(ca->alap - 1, t);
1393                                         for (tp_idx = ca->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1394                                                 for (tm = ca->asap - 1; tm <= tm_max; ++tm) {
1395                                                         int idx = ILPVAR_IDX(ca, tp_idx, tm);
1396                                                         ARR_APP1(int, tmp_var_idx_m, ca->ilp_vars.x[idx]);
1397                                                 }
1398                                         }
1399                                 }
1400
1401                                 if (ARR_LEN(tmp_var_idx_m) > 0)
1402                                         lpp_set_factor_fast_bulk(lpp, cst, tmp_var_idx_m, ARR_LEN(tmp_var_idx_m), -1.0);
1403                                 DEL_ARR_F(tmp_var_idx_m);
1404
1405                                 /* -c * a_{nt}^k */
1406                                 idx = ILPVAR_IDX_DEAD(ba, na, node_tp_idx, t);
1407                                 lpp_set_factor_fast(lpp, cst, na->ilp_vars.a[idx], 0.0 - (double)(na->n_consumer));
1408
1409                         }
1410                 }
1411         }
1412         ilp_timer_pop();
1413         DBG((env->dbg, LEVEL_1, "\t%u alive nodes constraints (%g sec)\n",
1414                 num_cst, ilp_timer_elapsed_usec(t_cst) / 1000000.0));
1415 }
1416
1417 /**
1418  * Create ILP alive nodes constraints for live-in nodes:
1419  * - set variable a_{nt}^k to 1 if nodes n is alive at step t on unit k
1420  */
1421 static void create_alive_livein_nodes_constraint(be_ilpsched_env_t *env, lpp_t *lpp, be_ilpsched_irn_t *block_node) {
1422         char                  buf[1024];
1423         ilp_livein_node_t     *livein;
1424         unsigned              num_cst = 0;
1425         ilpsched_block_attr_t *ba     = get_ilpsched_block_attr(block_node);
1426         lc_timer_t            *t_cst  = lc_timer_register("beilpsched_cst_alive_livein_nodes", "create alive livein nodes constraints");
1427
1428         ilp_timer_push(t_cst);
1429         /* for each node */
1430         foreach_pset(ba->livein_nodes, livein) {
1431                 ir_node              *irn  = livein->irn;
1432                 be_ilpsched_irn_t    *node = get_ilpsched_irn(env, irn);
1433                 ilpsched_node_attr_t *na   = get_ilpsched_node_attr(node);
1434                 unsigned             t;
1435
1436                 /* check check all time steps: 0 <= t < max_alive_steps */
1437                 for (t = 0; t < livein->max_alive_steps; ++t) {
1438                         int node_tp_idx;
1439
1440                         /* for all unit types available for this node */
1441                         for (node_tp_idx = na->n_unit_types - 1; node_tp_idx >= 0; --node_tp_idx) {
1442                                 const ir_edge_t *edge;
1443                                 unsigned idx;
1444                                 int      cst, num_block_user;
1445                                 int      *tmp_var_idx_m = NEW_ARR_F(int, 0);
1446
1447                                 /* check the number of consumer scheduled so far */
1448                                 num_block_user = 0;
1449                                 foreach_out_edge(irn, edge) {
1450                                         ir_node              *user = get_edge_src_irn(edge);
1451                                         be_ilpsched_irn_t    *cons;
1452                                         ilpsched_node_attr_t *ca;
1453                                         int                  tp_idx;
1454                                         unsigned             tm, tm_max;
1455
1456                                         /* check only users within current block */
1457                                         if (get_nodes_block(user) != block_node->irn)
1458                                                 continue;
1459
1460                                         num_block_user++;
1461                                         cons = get_ilpsched_irn(env, user);
1462                                         ca   = get_ilpsched_node_attr(cons);
1463
1464                                         tm_max = MIN(ca->alap - 1, t);
1465                                         for (tp_idx = ca->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1466                                                 for (tm = ca->asap - 1; tm <= tm_max; ++tm) {
1467                                                         int idx = ILPVAR_IDX(ca, tp_idx, tm);
1468                                                         ARR_APP1(int, tmp_var_idx_m, ca->ilp_vars.x[idx]);
1469                                                 }
1470                                         }
1471                                 }
1472
1473                                 snprintf(buf, sizeof(buf), "alive_livein_node_cst_%u_n%u_%s",
1474                                         t, get_irn_idx(irn), na->type_info[node_tp_idx].tp->name);
1475                                 cst = lpp_add_cst_uniq(lpp, buf, lpp_greater, (double)num_block_user);
1476                                 DBG((env->dbg, LEVEL_2, "added constraint %s\n", buf));
1477                                 num_cst++;
1478
1479                                 /* sum(scheduled users) */
1480                                 if (ARR_LEN(tmp_var_idx_m) > 0)
1481                                         lpp_set_factor_fast_bulk(lpp, cst, tmp_var_idx_m, ARR_LEN(tmp_var_idx_m), 1.0);
1482                                 DEL_ARR_F(tmp_var_idx_m);
1483
1484                                 /* + c * a_{nt}^k */
1485                                 idx = node_tp_idx * livein->max_alive_steps + t;
1486                                 lpp_set_factor_fast(lpp, cst, livein->a[idx], (double)(num_block_user));
1487                         }
1488                 }
1489         }
1490         ilp_timer_pop();
1491         DBG((env->dbg, LEVEL_1, "\t%u alive livein nodes constraints (%g sec)\n",
1492                 num_cst, ilp_timer_elapsed_usec(t_cst) / 1000000.0));
1493 }
1494
1495 /**
1496  * Create ILP pressure constraints, based on alive nodes:
1497  * - add additional costs to objective function if a node is scheduled
1498  *   on a unit although all units of this type are currently occupied
1499  */
1500 static void create_pressure_alive_constraint(be_ilpsched_env_t *env, lpp_t *lpp, be_ilpsched_irn_t *block_node) {
1501         char                  buf[1024];
1502         ir_node               *cur_irn;
1503         unsigned              num_cst = 0;
1504         ilpsched_block_attr_t *ba     = get_ilpsched_block_attr(block_node);
1505         lc_timer_t            *t_cst  = lc_timer_register("beilpsched_cst_pressure", "create pressure constraints");
1506
1507         ilp_timer_push(t_cst);
1508         /* y_{nt}^k is set for each node and timestep and unit type */
1509         foreach_linked_irns(ba->head_ilp_nodes, cur_irn) {
1510                 unsigned             cur_idx   = get_irn_idx(cur_irn);
1511                 be_ilpsched_irn_t    *cur_node = get_ilpsched_irn(env, cur_irn);
1512                 ilpsched_node_attr_t *cur_na   = get_ilpsched_node_attr(cur_node);
1513                 int                  glob_type_idx;
1514
1515                 /* we ignore nodes assigned to DUMMY unit here */
1516                 if (cur_na->is_dummy_node)
1517                         continue;
1518
1519                 /* for all types */
1520                 for (glob_type_idx = env->cpu->n_unit_types - 1; glob_type_idx >= 0; --glob_type_idx) {
1521                         be_execution_unit_type_t *cur_tp   = &env->cpu->unit_types[glob_type_idx];
1522                         int                      cur_tp_idx;
1523                         unsigned                 t;
1524
1525                         /* BEWARE: the DUMMY unit types is not in CPU, so it's skipped automatically */
1526
1527                         /* check if node can be executed on this unit type */
1528                         cur_tp_idx = is_valid_unit_type_for_node(cur_tp, cur_node);
1529                         if (cur_tp_idx < 0)
1530                                 continue;
1531
1532                         /* check all time_steps at which the current node can be scheduled */
1533                         for (t = cur_na->asap - 1; t <= cur_na->alap - 1; ++t) {
1534                                 int     cst, y_idx;
1535                                 ir_node *irn;
1536                                 int     *tmp_var_idx = NEW_ARR_F(int, 0);
1537                                 ilp_livein_node_t *livein;
1538
1539                                 snprintf(buf, sizeof(buf), "pressure_cst_n%u_%u_%s", cur_idx, t, cur_tp->name);
1540                                 cst = lpp_add_cst_uniq(lpp, buf, lpp_less, (double)(cur_tp->n_units - 1));
1541                                 DBG((env->dbg, LEVEL_2, "added constraint %s\n", buf));
1542                                 num_cst++;
1543
1544                                 /* - accumulate all nodes alive at point t on unit type k */
1545                                 foreach_linked_irns(ba->head_ilp_nodes, irn) {
1546                                         be_ilpsched_irn_t    *node = get_ilpsched_irn(env, irn);
1547                                         ilpsched_node_attr_t *na   = get_ilpsched_node_attr(node);
1548                                         int                  a_idx, tp_idx;
1549
1550                                         /* check if node can be alive here */
1551                                         if (t < na->asap - 1)
1552                                                 continue;
1553
1554                                         tp_idx = is_valid_unit_type_for_node(cur_tp, node);
1555
1556                                         /* current type is not suitable */
1557                                         if (tp_idx < 0)
1558                                                 continue;
1559
1560                                         a_idx = ILPVAR_IDX_DEAD(ba, na, tp_idx, t);
1561                                         ARR_APP1(int, tmp_var_idx, na->ilp_vars.a[a_idx]);
1562                                 }
1563                                 /* do the same for livein nodes */
1564                                 foreach_pset(ba->livein_nodes, livein) {
1565                                         ir_node              *irn  = livein->irn;
1566                                         be_ilpsched_irn_t    *node = get_ilpsched_irn(env, irn);
1567                                         int                  a_idx, tp_idx;
1568
1569                                         /* check if node can be alive here */
1570                                         if (t >= livein->max_alive_steps)
1571                                                 continue;
1572
1573                                         tp_idx = is_valid_unit_type_for_node(cur_tp, node);
1574
1575                                         /* current type is not suitable */
1576                                         if (tp_idx < 0)
1577                                                 continue;
1578
1579                                         a_idx = tp_idx * livein->max_alive_steps + t;
1580                                         ARR_APP1(int, tmp_var_idx, livein->a[a_idx]);
1581                                 }
1582
1583                                 if (ARR_LEN(tmp_var_idx) > 0)
1584                                         lpp_set_factor_fast_bulk(lpp, cst, tmp_var_idx, ARR_LEN(tmp_var_idx), 1.0);
1585                                 DEL_ARR_F(tmp_var_idx);
1586
1587                                 /* - num_nodes * y_{nt}^k */
1588                                 y_idx = ILPVAR_IDX(cur_na, cur_tp_idx, t);
1589                                 lpp_set_factor_fast(lpp, cst, cur_na->ilp_vars.y[y_idx], -1.0);
1590                         }
1591                 }
1592         }
1593         ilp_timer_pop();
1594         DBG((env->dbg, LEVEL_1, "\t%u pressure constraints (%g sec)\n",
1595                 num_cst, ilp_timer_elapsed_usec(t_cst) / 1000000.0));
1596 }
1597
1598 /**
1599  * Create ILP branch constraints:
1600  * Assure, alle nodes are scheduled prior to cfg op.
1601  */
1602 static void create_branch_constraint(be_ilpsched_env_t *env, lpp_t *lpp, be_ilpsched_irn_t *block_node) {
1603         char                  buf[1024];
1604         ir_node               *cur_irn, *cfop;
1605         unsigned              num_cst          = 0;
1606         unsigned              num_non_branches = 0;
1607         ilpsched_block_attr_t *ba     = get_ilpsched_block_attr(block_node);
1608         lc_timer_t            *t_cst  = lc_timer_register("beilpsched_cst_branch", "create branch constraints");
1609
1610         ilp_timer_push(t_cst);
1611         cfop = NULL;
1612         /* determine number of non-branch nodes and the one and only branch node */
1613         foreach_linked_irns(ba->head_ilp_nodes, cur_irn) {
1614                 switch (get_irn_opcode(cur_irn)) {
1615                         case iro_Phi:
1616                         case iro_Start:
1617                         case iro_End:
1618                         case iro_Proj:
1619                         case iro_Bad:
1620                         case iro_Unknown:
1621                                 num_non_branches++;
1622                                 break;
1623                         default:
1624                                 if (is_cfop(cur_irn)) {
1625                                         assert(cfop == NULL && "Highlander - there can be only one to be constrained");
1626                                         cfop = cur_irn;
1627                                 }
1628                                 else {
1629                                         num_non_branches++;
1630                                 }
1631                                 break;
1632                 }
1633         }
1634
1635         if (cfop) {
1636                 be_ilpsched_irn_t    *cf_node = get_ilpsched_irn(env, cfop);
1637                 ilpsched_node_attr_t *cf_na   = get_ilpsched_node_attr(cf_node);
1638                 unsigned t;
1639
1640                 /* for each time step */
1641                 for (t = cf_na->asap - 1; t <= cf_na->alap - 1; ++t) {
1642                         int *non_branch_vars, *branch_vars;
1643                         int cst;
1644
1645                         snprintf(buf, sizeof(buf), "branch_cst_%u_n%u", t, get_irn_idx(cfop));
1646                         cst = lpp_add_cst_uniq(lpp, buf, lpp_greater, 0.0);
1647                         DBG((env->dbg, LEVEL_2, "added constraint %s\n", buf));
1648                         num_cst++;
1649
1650                         /* sum(overall non branches: n)x_{nt}^k - sum(overall branches: b)(num_non_branches * x_{bt}^k >= 0) */
1651                         non_branch_vars = NEW_ARR_F(int, 0);
1652                         branch_vars     = NEW_ARR_F(int, 0);
1653                         foreach_linked_irns(ba->head_ilp_nodes, cur_irn) {
1654                                 be_ilpsched_irn_t    *node = get_ilpsched_irn(env, cur_irn);
1655                                 ilpsched_node_attr_t *na   = get_ilpsched_node_attr(node);
1656                                 int                  tp_idx;
1657
1658                                 if (cur_irn == cfop) {
1659                                         /* for all unit types available for this node */
1660                                         for (tp_idx = na->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1661                                                 unsigned idx = ILPVAR_IDX(na, tp_idx, t);
1662                                                 ARR_APP1(int, branch_vars, na->ilp_vars.x[idx]);
1663                                         }
1664                                 }
1665                                 else {
1666                                         /* sum up all possible schedule points for this node upto current timestep */
1667                                         for (tp_idx = na->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1668                                                 unsigned tn;
1669                                                 unsigned tmax = MIN(t, na->alap - 1);
1670
1671                                                 for (tn = na->asap - 1; tn <= tmax; ++tn) {
1672                                                         unsigned idx = ILPVAR_IDX(na, tp_idx, tn);
1673                                                         ARR_APP1(int, non_branch_vars, na->ilp_vars.x[idx]);
1674                                                 }
1675                                         }
1676                                 }
1677
1678                         }
1679
1680                         if (ARR_LEN(non_branch_vars) > 0)
1681                                 lpp_set_factor_fast_bulk(lpp, cst, non_branch_vars, ARR_LEN(non_branch_vars), 1.0);
1682                         if (ARR_LEN(branch_vars) > 0)
1683                                 lpp_set_factor_fast_bulk(lpp, cst, branch_vars, ARR_LEN(branch_vars), 0.0 - (double)num_non_branches);
1684
1685                         DEL_ARR_F(branch_vars);
1686                         DEL_ARR_F(non_branch_vars);
1687                 }
1688         }
1689         ilp_timer_pop();
1690         DBG((env->dbg, LEVEL_1, "\t%u branch constraints (%g sec)\n",
1691                 num_cst, ilp_timer_elapsed_usec(t_cst) / 1000000.0));
1692 }
1693
1694 #if 0
1695 static void create_proj_keep_constraints(be_ilpsched_env_t *env, lpp_t *lpp, be_ilpsched_irn_t *block_node) {
1696         char                  buf[1024];
1697         ir_node               *irn;
1698         unsigned              num_cst = 0;
1699         ilpsched_block_attr_t *ba     = get_ilpsched_block_attr(block_node);
1700         lc_timer_t            *t_cst  = lc_timer_register("beilpsched_cst_projkeep", "create proj and keep constraints");
1701
1702         ilp_timer_push(t_cst);
1703         /* check all nodes */
1704         foreach_linked_irns(ba->head_ilp_nodes, irn) {
1705                 be_ilpsched_irn_t    *node;
1706                 ilpsched_node_attr_t *na;
1707                 unsigned             t;
1708                 ir_node              **pk;
1709
1710                 /* only mode_T nodes can have Projs and Keeps assigned */
1711                 if (get_irn_mode(irn) != mode_T)
1712                         continue;
1713
1714                 node = get_ilpsched_irn(env, irn);
1715                 na   = get_ilpsched_node_attr(node);
1716
1717                 /* check if has some Projs and Keeps assigned */
1718                 if (! na->projkeeps)
1719                         continue;
1720
1721                 /* we can run only once over the queue, so preserve the nodes */
1722                 pk = NEW_ARR_F(ir_node *, 0);
1723                 while (! waitq_empty(na->projkeeps))
1724                         ARR_APP1(ir_node *, pk, waitq_get(na->projkeeps));
1725                 del_waitq(na->projkeeps);
1726                 na->projkeeps = NULL;
1727
1728                 /* for all time steps at which this node can be scheduled */
1729                 for (t = na->asap - 1; t <= na->alap - 1; ++t) {
1730                         int cst, tp_idx, i;
1731                         int *tmp_var_idx_n = NEW_ARR_F(int, 0);
1732
1733                         /* add the constraint, assure, that a node is always scheduled along with it's Projs and Keeps */
1734                         snprintf(buf, sizeof(buf), "projkeep_cst_n%u_%u", get_irn_idx(irn), t);
1735                         cst = lpp_add_cst_uniq(lpp, buf, lpp_equal, 0.0);
1736                         DBG((env->dbg, LEVEL_2, "added constraint %s\n", buf));
1737                         num_cst++;
1738
1739                         /* sum up scheduling variables for this time step */
1740                         for (tp_idx = na->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1741                                 int idx = ILPVAR_IDX(na, tp_idx, t);
1742                                 ARR_APP1(int, tmp_var_idx_n, na->ilp_vars.x[idx]);
1743                         }
1744
1745                         if (ARR_LEN(tmp_var_idx_n) > 0)
1746                                 lpp_set_factor_fast_bulk(lpp, cst, tmp_var_idx_n, ARR_LEN(tmp_var_idx_n), (double)(ARR_LEN(pk)));
1747                         DEL_ARR_F(tmp_var_idx_n);
1748
1749                         /* subtract all Proj and Keep variables for this step */
1750                         for (i = ARR_LEN(pk) - 1; i >= 0; --i) {
1751                                 be_ilpsched_irn_t    *pk_node = get_ilpsched_irn(env, pk[i]);
1752                                 ilpsched_node_attr_t *pk_na   = get_ilpsched_node_attr(pk_node);
1753                                 int                  pk_tp_idx;
1754
1755                                 for (pk_tp_idx = pk_na->n_unit_types - 1; pk_tp_idx >= 0; --pk_tp_idx) {
1756                                         int idx = ILPVAR_IDX(pk_na, pk_tp_idx, t);
1757                                         lpp_set_factor_fast(lpp, cst, pk_na->ilp_vars.x[idx], -1.0);
1758                                 }
1759                         }
1760                 }
1761         }
1762         ilp_timer_pop();
1763         DBG((env->dbg, LEVEL_1, "\t%u Proj and Keep constraints (%g sec)\n",
1764                 num_cst, ilp_timer_elapsed_usec(t_cst) / 1000000.0));
1765 }
1766 #endif /* if 0 */
1767
1768 /***************************************************
1769  *  _____ _      _____                    _
1770  * |_   _| |    |  __ \                  (_)
1771  *   | | | |    | |__) |  _ __ ___   __ _ _ _ __
1772  *   | | | |    |  ___/  | '_ ` _ \ / _` | | '_ \
1773  *  _| |_| |____| |      | | | | | | (_| | | | | |
1774  * |_____|______|_|      |_| |_| |_|\__,_|_|_| |_|
1775  *
1776  ***************************************************/
1777
1778 /**
1779  * Create the ilp (add variables, build constraints, solve, build schedule from solution).
1780  */
1781 static void create_ilp(ir_node *block, void *walk_env) {
1782         be_ilpsched_env_t     *env           = walk_env;
1783         be_ilpsched_irn_t     *block_node    = get_ilpsched_irn(env, block);
1784         ilpsched_block_attr_t *ba            = get_ilpsched_block_attr(block_node);
1785         FILE                  *logfile       = NULL;
1786         lpp_t                 *lpp           = NULL;
1787         struct obstack        var_obst;
1788         char                  name[1024];
1789
1790         DBG((env->dbg, 255, "\n\n\n=========================================\n"));
1791         DBG((env->dbg, 255, "  ILP Scheduling for %+F\n", block));
1792         DBG((env->dbg, 255, "=========================================\n\n"));
1793
1794         DBG((env->dbg, LEVEL_1, "Creating ILP Variables for nodes in %+F (%u interesting nodes, %u max steps)\n",
1795                 block, ba->n_interesting_nodes, ba->max_steps));
1796
1797         /* notify backend and get block environment */
1798         env->block_env = be_ilp_sched_init_block_ilp_schedule(env->sel, block);
1799
1800         /* if we have less than two interesting nodes, there is no need to create the ILP */
1801         if (ba->n_interesting_nodes > 1) {
1802                 double fact_var        = ba->n_interesting_nodes > 25 ? 2.3 : 3;
1803                 double fact_cst        = ba->n_interesting_nodes > 25 ? 3   : 4.5;
1804                 int    base_num        = ba->n_interesting_nodes * ba->n_interesting_nodes;
1805                 int    estimated_n_var = (int)((double)base_num * fact_var);
1806                 int    estimated_n_cst = (int)((double)base_num * fact_cst);
1807
1808                 DBG((env->dbg, LEVEL_1, "Creating LPP with estimated numbers: %d vars, %d cst\n",
1809                         estimated_n_var, estimated_n_cst));
1810
1811                 /* set up the LPP object */
1812                 snprintf(name, sizeof(name), "ilp scheduling IRG %s", get_entity_ld_name(get_irg_entity(env->irg)));
1813
1814                 lpp = new_lpp_userdef(
1815                         (const char *)name,
1816                         lpp_minimize,
1817                         estimated_n_cst,     /* num vars */
1818                         estimated_n_cst + 1, /* num cst */
1819                         1.3);                /* grow factor */
1820                 obstack_init(&var_obst);
1821
1822                 /* create ILP variables */
1823                 create_variables(env, lpp, block_node, &var_obst);
1824
1825                 /* create ILP constraints */
1826                 DBG((env->dbg, LEVEL_1, "Creating constraints for nodes in %+F:\n", block));
1827                 create_assignment_and_precedence_constraints(env, lpp, block_node);
1828                 create_ressource_constraints(env, lpp, block_node);
1829                 create_bundle_constraints(env, lpp, block_node);
1830                 create_branch_constraint(env, lpp, block_node);
1831                 //create_proj_keep_constraints(env, lpp, block_node);
1832
1833                 if (env->opts->regpress) {
1834                         create_alive_nodes_constraint(env, lpp, block_node);
1835                         create_alive_livein_nodes_constraint(env, lpp, block_node);
1836                         create_pressure_alive_constraint(env, lpp, block_node);
1837                 }
1838
1839                 DBG((env->dbg, LEVEL_1, "ILP to solve: %u variables, %u constraints\n", lpp->var_next, lpp->cst_next));
1840
1841                 /* debug stuff, dump lpp when debugging is on  */
1842                 DEBUG_ONLY(
1843                         if (firm_dbg_get_mask(env->dbg) > 1) {
1844                                 char buf[1024];
1845                                 FILE *f;
1846
1847                                 snprintf(buf, sizeof(buf), "lpp_block_%lu.txt", get_irn_node_nr(block));
1848                                 f = fopen(buf, "w");
1849                                 lpp_dump_plain(lpp, f);
1850                                 fclose(f);
1851                                 snprintf(buf, sizeof(buf), "lpp_block_%lu.mps", get_irn_node_nr(block));
1852                                 lpp_dump(lpp, buf);
1853                         }
1854                 );
1855
1856                 /* set solve time limit */
1857                 lpp_set_time_limit(lpp, env->opts->time_limit);
1858
1859                 /* set logfile if requested */
1860                 if (strlen(env->opts->log_file) > 0) {
1861                         if (strcasecmp(env->opts->log_file, "stdout") == 0)
1862                                 lpp_set_log(lpp, stdout);
1863                         else if (strcasecmp(env->opts->log_file, "stderr") == 0)
1864                                 lpp_set_log(lpp, stderr);
1865                         else {
1866                                 logfile = fopen(env->opts->log_file, "w");
1867                                 if (! logfile)
1868                                         fprintf(stderr, "Could not open logfile '%s'! Logging disabled.\n", env->opts->log_file);
1869                                 else
1870                                         lpp_set_log(lpp, logfile);
1871                         }
1872                 }
1873
1874                 /* solve the ILP */
1875                 lpp_solve_net(lpp, env->main_env->options->ilp_server, env->main_env->options->ilp_solver);
1876
1877                 if (logfile)
1878                         fclose(logfile);
1879
1880                 /* check for valid solution */
1881                 if (! lpp_is_sol_valid(lpp)) {
1882                         char buf[1024];
1883                         FILE *f;
1884
1885                         snprintf(buf, sizeof(buf), "lpp_block_%lu.assert.txt", get_irn_node_nr(block));
1886                         f = fopen(buf, "w");
1887                         lpp_dump_plain(lpp, f);
1888                         fclose(f);
1889                         snprintf(buf, sizeof(buf), "lpp_block_%lu.assert.mps", get_irn_node_nr(block));
1890                         lpp_dump(lpp, buf);
1891                         dump_ir_block_graph(env->irg, "-assert");
1892
1893                         assert(0 && "ILP solution is not feasible!");
1894                 }
1895
1896                 DBG((env->dbg, LEVEL_1, "\nSolution:\n"));
1897                 DBG((env->dbg, LEVEL_1, "\tsend time: %g sec\n", lpp->send_time / 1000000.0));
1898                 DBG((env->dbg, LEVEL_1, "\treceive time: %g sec\n", lpp->recv_time / 1000000.0));
1899                 DBG((env->dbg, LEVEL_1, "\tmatrix: %u elements, density %.2f%%, size %.2fMB\n", lpp->n_elems, lpp->density, (double)lpp->matrix_mem / 1024.0 / 1024.0));
1900                 DBG((env->dbg, LEVEL_1, "\titerations: %d\n", lpp->iterations));
1901                 DBG((env->dbg, LEVEL_1, "\tsolution time: %g\n", lpp->sol_time));
1902                 DBG((env->dbg, LEVEL_1, "\tobjective function: %g\n", LPP_VALUE_IS_0(lpp->objval) ? 0.0 : lpp->objval));
1903                 DBG((env->dbg, LEVEL_1, "\tbest bound: %g\n", LPP_VALUE_IS_0(lpp->best_bound) ? 0.0 : lpp->best_bound));
1904
1905                 DBG((env->dbg, LEVEL_1, "variables used %u bytes\n", obstack_memory_used(&var_obst)));
1906         }
1907
1908         /* apply solution */
1909         apply_solution(env, lpp, block);
1910
1911         if (lpp)
1912                 free_lpp(lpp);
1913
1914         /* notify backend */
1915         be_ilp_sched_finish_block_ilp_schedule(env->sel, block, env->block_env);
1916 }
1917
1918 /**
1919  * Perform ILP scheduling on the given irg.
1920  */
1921 void be_ilp_sched(const be_irg_t *birg) {
1922         be_ilpsched_env_t          env;
1923         const char                 *name = "be ilp scheduling";
1924         arch_isa_t                 *isa  = birg->main_env->arch_env->isa;
1925         const ilp_sched_selector_t *sel  = isa->impl->get_ilp_sched_selector(isa);
1926
1927         FIRM_DBG_REGISTER(env.dbg, "firm.be.sched.ilp");
1928
1929 //      firm_dbg_set_mask(env.dbg, 1);
1930
1931         env.irg_env    = be_ilp_sched_init_irg_ilp_schedule(sel, birg->irg);
1932         env.sel        = sel;
1933         env.irg        = birg->irg;
1934         env.height     = heights_new(birg->irg);
1935         env.main_env   = birg->main_env;
1936         env.arch_env   = birg->main_env->arch_env;
1937         env.cpu        = arch_isa_get_machine(birg->main_env->arch_env->isa);
1938         env.opts       = &ilp_opts;
1939         phase_init(&env.ph, name, env.irg, PHASE_DEFAULT_GROWTH, init_ilpsched_irn);
1940
1941         /* assign a unique per block number to all interesting nodes */
1942         irg_walk_in_or_dep_graph(env.irg, NULL, build_block_idx, &env);
1943
1944         /*
1945                 The block indices are completely build after the walk,
1946                 now we can allocate the bitsets (size depends on block indices)
1947                 for all nodes.
1948         */
1949         phase_reinit_irn_data(&env.ph);
1950
1951         /* Collect all root nodes (having no user in their block) and calculate ASAP. */
1952         irg_walk_in_or_dep_blkwise_graph(env.irg, collect_alap_root_nodes, calculate_irn_asap, &env);
1953
1954         /* Calculate ALAP of all irns */
1955         irg_block_walk_graph(env.irg, NULL, calculate_block_alap, &env);
1956
1957         /* We refine the {ASAP(n), ALAP(n)} interval and fix the time steps for Projs and Keeps */
1958         irg_walk_in_or_dep_blkwise_graph(env.irg, NULL, refine_asap_alap_times, &env);
1959
1960         /* perform ILP scheduling */
1961         irg_block_walk_graph(env.irg, NULL, create_ilp, &env);
1962
1963         DEBUG_ONLY(
1964                 if (firm_dbg_get_mask(env.dbg)) {
1965                         phase_stat_t stat;
1966                         phase_stat_t *stat_ptr = phase_stat(&env.ph, &stat);
1967
1968                         fprintf(stderr, "Phase used: %u bytes\n", stat_ptr->overall_bytes);
1969                 }
1970         );
1971
1972         /* free data allocated dynamically */
1973         irg_block_walk_graph(env.irg, NULL, clear_unwanted_data, &env);
1974
1975         /* free all allocated object */
1976         phase_free(&env.ph);
1977         heights_free(env.height);
1978
1979         /* notify backend */
1980         be_ilp_sched_finish_irg_ilp_schedule(sel, birg->irg, env.irg_env);
1981 }
1982
1983 /**
1984  * Register ILP scheduler options.
1985  */
1986 void be_init_ilpsched(void)
1987 {
1988         lc_opt_entry_t *be_grp = lc_opt_get_grp(firm_opt_get_root(), "be");
1989         lc_opt_entry_t *sched_grp = lc_opt_get_grp(be_grp, "ilpsched");
1990
1991         lc_opt_add_table(sched_grp, ilpsched_option_table);
1992 }
1993
1994 #else /* WITH_ILP */
1995
1996 static INLINE void some_picky_compiler_do_not_allow_empty_files(void)
1997 {}
1998
1999 #endif /* WITH_ILP */