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