cleanup: Remove unnecessary #include from besched.[ch].
[libfirm] / ir / be / amd64 / amd64_emitter.c
1 /*
2  * Copyright (C) 1995-2011 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief   emit assembler for a backend graph
23  */
24 #include "config.h"
25
26 #include <limits.h>
27
28 #include "be_t.h"
29 #include "error.h"
30 #include "xmalloc.h"
31 #include "tv.h"
32 #include "iredges.h"
33 #include "debug.h"
34 #include "irgwalk.h"
35 #include "irprintf.h"
36 #include "irop_t.h"
37 #include "irargs_t.h"
38 #include "irprog.h"
39
40 #include "besched.h"
41 #include "begnuas.h"
42 #include "beblocksched.h"
43
44 #include "amd64_emitter.h"
45 #include "gen_amd64_emitter.h"
46 #include "gen_amd64_regalloc_if.h"
47 #include "amd64_nodes_attr.h"
48 #include "amd64_new_nodes.h"
49
50 #include "benode.h"
51
52 /*************************************************************
53  *             _       _    __   _          _
54  *            (_)     | |  / _| | |        | |
55  *  _ __  _ __ _ _ __ | |_| |_  | |__   ___| |_ __   ___ _ __
56  * | '_ \| '__| | '_ \| __|  _| | '_ \ / _ \ | '_ \ / _ \ '__|
57  * | |_) | |  | | | | | |_| |   | | | |  __/ | |_) |  __/ |
58  * | .__/|_|  |_|_| |_|\__|_|   |_| |_|\___|_| .__/ \___|_|
59  * | |                                       | |
60  * |_|                                       |_|
61  *************************************************************/
62
63 /**
64  * Returns the target block for a control flow node.
65  */
66 static ir_node *get_cfop_target_block(const ir_node *irn)
67 {
68         return (ir_node*)get_irn_link(irn);
69 }
70
71 void amd64_emitf(ir_node const *const node, char const *fmt, ...)
72 {
73         va_list ap;
74         va_start(ap, fmt);
75
76         be_emit_char('\t');
77         for (;;) {
78                 char const *start = fmt;
79
80                 while (*fmt != '%' && *fmt != '\n' && *fmt != '\0')
81                         ++fmt;
82                 if (fmt != start) {
83                         be_emit_string_len(start, fmt - start);
84                 }
85
86                 if (*fmt == '\n') {
87                         be_emit_char('\n');
88                         be_emit_write_line();
89                         be_emit_char('\t');
90                         ++fmt;
91                         continue;
92                 }
93
94                 if (*fmt == '\0')
95                         break;
96
97                 ++fmt;
98
99                 switch (*fmt++) {
100                         arch_register_t const *reg;
101
102                         case '%':
103                                 be_emit_char('%');
104                                 break;
105
106                         case 'C': {
107                                 amd64_attr_t const *const attr = get_amd64_attr_const(node);
108                                 be_emit_irprintf("$0x%X", attr->ext.imm_value);
109                                 break;
110                         }
111
112                         case 'D':
113                                 if (*fmt < '0' || '9' <= *fmt)
114                                         goto unknown;
115                                 reg = arch_get_irn_register_out(node, *fmt++ - '0');
116                                 goto emit_R;
117
118                         case 'E': {
119                                 ir_entity const *const ent = va_arg(ap, ir_entity const*);
120                                 be_gas_emit_entity(ent);
121                                 break;
122                         }
123
124                         case 'L': {
125                                 ir_node *const block = get_cfop_target_block(node);
126                                 be_gas_emit_block_name(block);
127                                 break;
128                         }
129
130                         case 'O': {
131                                 amd64_SymConst_attr_t const *const attr = get_amd64_SymConst_attr_const(node);
132                                 if (attr->fp_offset)
133                                         be_emit_irprintf("%d", attr->fp_offset);
134                                 break;
135                         }
136
137                         case 'R':
138                                 reg = va_arg(ap, arch_register_t const*);
139 emit_R:
140                                 be_emit_char('%');
141                                 be_emit_string(reg->name);
142                                 break;
143
144                         case 'S': {
145                                 int pos;
146                                 if ('0' <= *fmt && *fmt <= '9') {
147                                         pos = *fmt++ - '0';
148                                 } else if (*fmt == '*') {
149                                         ++fmt;
150                                         pos = va_arg(ap, int);
151                                 } else {
152                                         goto unknown;
153                                 }
154                                 reg = arch_get_irn_register_in(node, pos);
155                                 goto emit_R;
156                         }
157
158                         case 'd': {
159                                 int const num = va_arg(ap, int);
160                                 be_emit_irprintf("%d", num);
161                                 break;
162                         }
163
164                         case 's': {
165                                 char const *const str = va_arg(ap, char const*);
166                                 be_emit_string(str);
167                                 break;
168                         }
169
170                         case 'u': {
171                                 unsigned const num = va_arg(ap, unsigned);
172                                 be_emit_irprintf("%u", num);
173                                 break;
174                         }
175
176                         default:
177 unknown:
178                                 panic("unknown format conversion");
179                 }
180         }
181
182         be_emit_finish_line_gas(node);
183         va_end(ap);
184 }
185
186 /***********************************************************************************
187  *                  _          __                                             _
188  *                 (_)        / _|                                           | |
189  *  _ __ ___   __ _ _ _ __   | |_ _ __ __ _ _ __ ___   _____      _____  _ __| | __
190  * | '_ ` _ \ / _` | | '_ \  |  _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
191  * | | | | | | (_| | | | | | | | | | | (_| | | | | | |  __/\ V  V / (_) | |  |   <
192  * |_| |_| |_|\__,_|_|_| |_| |_| |_|  \__,_|_| |_| |_|\___| \_/\_/ \___/|_|  |_|\_\
193  *
194  ***********************************************************************************/
195
196 /**
197  * Default emitter for anything that we don't want to generate code for.
198  */
199 static void emit_nothing(const ir_node *node)
200 {
201         (void) node;
202 }
203
204 /**
205  * Emit a SymConst.
206  */
207 static void emit_amd64_SymConst(const ir_node *irn)
208 {
209         const amd64_SymConst_attr_t *attr = get_amd64_SymConst_attr_const(irn);
210 #if 0
211         sym_or_tv_t key, *entry;
212         unsigned label;
213
214         key.u.id     = get_entity_ld_ident(attr->entity);
215         key.is_ident = 1;
216         key.label    = 0;
217         entry = set_insert(sym_or_tv_t, sym_or_tv, &key, sizeof(key), hash_ptr(key.u.generic));
218         if (entry->label == 0) {
219                 /* allocate a label */
220                 entry->label = get_unique_label();
221         }
222         label = entry->label;
223 #endif
224
225         amd64_emitf(irn, "mov $%E, %D0", attr->entity);
226 }
227
228 /**
229  * Emit a Conv.
230  */
231 static void emit_amd64_Conv(const ir_node *irn)
232 {
233         amd64_emitf(irn, "mov %S0, %D0");
234 }
235
236
237 /**
238  * Returns the next block in a block schedule.
239  */
240 static ir_node *sched_next_block(const ir_node *block)
241 {
242     return (ir_node*)get_irn_link(block);
243 }
244
245 /**
246  * Emit a Jmp.
247  */
248 static void emit_amd64_Jmp(const ir_node *node)
249 {
250         ir_node *block, *next_block;
251
252         /* for now, the code works for scheduled and non-schedules blocks */
253         block = get_nodes_block(node);
254
255         /* we have a block schedule */
256         next_block = sched_next_block(block);
257         if (get_cfop_target_block(node) != next_block) {
258                 amd64_emitf(node, "jmp %L");
259         } else if (be_options.verbose_asm) {
260                 amd64_emitf(node, "/* fallthrough to %L */");
261         }
262 }
263
264 /**
265  * Emit a Compare with conditional branch.
266  */
267 static void emit_amd64_Jcc(const ir_node *irn)
268 {
269         const ir_node      *proj_true  = NULL;
270         const ir_node      *proj_false = NULL;
271         const ir_node      *block;
272         const ir_node      *next_block;
273         const char         *suffix;
274         const amd64_attr_t *attr      = get_amd64_attr_const(irn);
275         ir_relation         relation  = attr->ext.relation;
276         ir_node            *op1       = get_irn_n(irn, 0);
277         const amd64_attr_t *cmp_attr  = get_amd64_attr_const(op1);
278         bool                is_signed = !cmp_attr->data.cmp_unsigned;
279
280         assert(is_amd64_Cmp(op1));
281
282         foreach_out_edge(irn, edge) {
283                 ir_node *proj = get_edge_src_irn(edge);
284                 long nr = get_Proj_proj(proj);
285                 if (nr == pn_Cond_true) {
286                         proj_true = proj;
287                 } else {
288                         proj_false = proj;
289                 }
290         }
291
292         if (cmp_attr->data.ins_permuted) {
293                 relation = get_inversed_relation(relation);
294         }
295
296         /* for now, the code works for scheduled and non-schedules blocks */
297         block = get_nodes_block(irn);
298
299         /* we have a block schedule */
300         next_block = sched_next_block(block);
301
302         assert(relation != ir_relation_false);
303         assert(relation != ir_relation_true);
304
305         if (get_cfop_target_block(proj_true) == next_block) {
306                 /* exchange both proj's so the second one can be omitted */
307                 const ir_node *t = proj_true;
308
309                 proj_true  = proj_false;
310                 proj_false = t;
311                 relation   = get_negated_relation(relation);
312         }
313
314         switch (relation & ir_relation_less_equal_greater) {
315                 case ir_relation_equal:              suffix = "e"; break;
316                 case ir_relation_less:               suffix = is_signed ? "l"  : "b"; break;
317                 case ir_relation_less_equal:         suffix = is_signed ? "le" : "be"; break;
318                 case ir_relation_greater:            suffix = is_signed ? "g"  : "a"; break;
319                 case ir_relation_greater_equal:      suffix = is_signed ? "ge" : "ae"; break;
320                 case ir_relation_less_greater:       suffix = "ne"; break;
321                 case ir_relation_less_equal_greater: suffix = "mp"; break;
322                 default: panic("Cmp has unsupported pnc");
323         }
324
325         /* emit the true proj */
326         amd64_emitf(proj_true, "j%s %L", suffix);
327
328         if (get_cfop_target_block(proj_false) != next_block) {
329                 amd64_emitf(proj_false, "jmp %L");
330         } else if (be_options.verbose_asm) {
331                 amd64_emitf(proj_false, "/* fallthrough to %L */");
332         }
333 }
334
335 /**
336  * Emits code for a call.
337  */
338 static void emit_be_Call(const ir_node *node)
339 {
340         ir_entity *entity = be_Call_get_entity(node);
341
342         /* %eax/%rax is used in AMD64 to pass the number of vector parameters for
343          * variable argument counts */
344         if (get_method_variadicity (be_Call_get_type((ir_node *) node))) {
345                 /* But this still is a hack... */
346                 amd64_emitf(node, "xor %%rax, %%rax");
347         }
348
349         if (entity) {
350                 amd64_emitf(node, "call %E", entity);
351         } else {
352                 be_emit_pad_comment();
353                 be_emit_cstring("/* FIXME: call NULL entity?! */\n");
354         }
355 }
356
357 /**
358  * emit copy node
359  */
360 static void emit_be_Copy(const ir_node *irn)
361 {
362         ir_mode *mode = get_irn_mode(irn);
363
364         if (arch_get_irn_register_in(irn, 0) == arch_get_irn_register_out(irn, 0)) {
365                 /* omitted Copy */
366                 return;
367         }
368
369         if (mode_is_float(mode)) {
370                 panic("move not supported for FP");
371         } else if (mode_is_data(mode)) {
372                 amd64_emitf(irn, "mov %S0, %D0");
373         } else {
374                 panic("move not supported for this mode");
375         }
376 }
377
378 static void emit_be_Perm(const ir_node *node)
379 {
380         const arch_register_t *in0, *in1;
381
382         in0 = arch_get_irn_register(get_irn_n(node, 0));
383         in1 = arch_get_irn_register(get_irn_n(node, 1));
384
385         arch_register_class_t const* const cls0 = in0->reg_class;
386         assert(cls0 == in1->reg_class && "Register class mismatch at Perm");
387
388         amd64_emitf(node, "xchg %R, %R", in0, in1);
389
390         if (cls0 != &amd64_reg_classes[CLASS_amd64_gp]) {
391                 panic("unexpected register class in be_Perm (%+F)", node);
392         }
393 }
394
395 static void emit_amd64_FrameAddr(const ir_node *irn)
396 {
397         const amd64_SymConst_attr_t *attr =
398                 (const amd64_SymConst_attr_t*) get_amd64_attr_const(irn);
399
400         amd64_emitf(irn, "mov %S0, %D0");
401         amd64_emitf(irn, "add $%u, %D0", attr->fp_offset);
402 }
403
404 /**
405  * Emits code to increase stack pointer.
406  */
407 static void emit_be_IncSP(const ir_node *node)
408 {
409         int offs = be_get_IncSP_offset(node);
410
411         if (offs == 0)
412                 return;
413
414         if (offs > 0) {
415                 amd64_emitf(node, "sub, $%d, %D0", offs);
416         } else {
417                 amd64_emitf(node, "add, $%d, %D0", -offs);
418         }
419 }
420
421 /**
422  * Emits code for a return.
423  */
424 static void emit_be_Return(const ir_node *node)
425 {
426         be_emit_cstring("\tret");
427         be_emit_finish_line_gas(node);
428 }
429
430
431 static void emit_amd64_binop_op(const ir_node *irn, int second_op)
432 {
433         if (irn->op == op_amd64_Add) {
434                 amd64_emitf(irn, "add %S*, %D0", second_op);
435         } else if (irn->op == op_amd64_Sub) {
436                 amd64_emitf(irn, "neg %S*",      second_op);
437                 amd64_emitf(irn, "add %S*, %D0", second_op);
438                 amd64_emitf(irn, "neg %S*",      second_op);
439         }
440
441 }
442
443 /**
444  * Emits an arithmetic operation that handles arbitraty input registers.
445  */
446 static void emit_amd64_binop(const ir_node *irn)
447 {
448         const arch_register_t *reg_s1 = arch_get_irn_register_in(irn, 0);
449         const arch_register_t *reg_s2 = arch_get_irn_register_in(irn, 1);
450         const arch_register_t *reg_d1 = arch_get_irn_register_out(irn, 0);
451
452         int second_op = 0;
453
454         if (reg_d1 != reg_s1 && reg_d1 != reg_s2) {
455                 amd64_emitf(irn, "mov %R, %R", reg_s1, reg_d1);
456                 second_op = 1;
457         } else if (reg_d1 == reg_s2 && reg_d1 != reg_s1) {
458                 second_op = 0;
459         }
460
461         emit_amd64_binop_op(irn, second_op);
462 }
463
464 /**
465  * The type of a emitter function.
466  */
467 typedef void (emit_func)(const ir_node *irn);
468
469 /**
470  * Set a node emitter. Make it a bit more type safe.
471  */
472 static inline void set_emitter(ir_op *op, emit_func arm_emit_node)
473 {
474         op->ops.generic = (op_func)arm_emit_node;
475 }
476
477 /**
478  * Enters the emitter functions for handled nodes into the generic
479  * pointer of an opcode.
480  */
481 static void amd64_register_emitters(void)
482 {
483         /* first clear the generic function pointer for all ops */
484         ir_clear_opcodes_generic_func();
485
486         /* register all emitter functions defined in spec */
487         amd64_register_spec_emitters();
488
489         set_emitter(op_amd64_SymConst,   emit_amd64_SymConst);
490         set_emitter(op_amd64_Jmp,        emit_amd64_Jmp);
491         set_emitter(op_amd64_Jcc,        emit_amd64_Jcc);
492         set_emitter(op_amd64_Conv,       emit_amd64_Conv);
493         set_emitter(op_amd64_FrameAddr,  emit_amd64_FrameAddr);
494         set_emitter(op_be_Return,        emit_be_Return);
495         set_emitter(op_be_Call,          emit_be_Call);
496         set_emitter(op_be_Copy,          emit_be_Copy);
497         set_emitter(op_be_IncSP,         emit_be_IncSP);
498         set_emitter(op_be_Perm,          emit_be_Perm);
499
500         set_emitter(op_amd64_Add,        emit_amd64_binop);
501         set_emitter(op_amd64_Sub,        emit_amd64_binop);
502
503         set_emitter(op_be_Start,         emit_nothing);
504         set_emitter(op_be_Keep,          emit_nothing);
505         set_emitter(op_Phi,              emit_nothing);
506 }
507
508 typedef void (*emit_func_ptr) (const ir_node *);
509
510 /**
511  * Emits code for a node.
512  */
513 static void amd64_emit_node(const ir_node *node)
514 {
515         ir_op               *op       = get_irn_op(node);
516
517         if (op->ops.generic) {
518                 emit_func_ptr func = (emit_func_ptr) op->ops.generic;
519                 (*func) (node);
520         } else {
521                 ir_fprintf(stderr, "No emitter for node %+F\n", node);
522         }
523 }
524
525 /**
526  * Walks over the nodes in a block connected by scheduling edges
527  * and emits code for each node.
528  */
529 static void amd64_gen_block(ir_node *block, void *data)
530 {
531         (void) data;
532
533         if (! is_Block(block))
534                 return;
535
536         be_gas_begin_block(block, true);
537
538         sched_foreach(block, node) {
539                 amd64_emit_node(node);
540         }
541 }
542
543
544 /**
545  * Sets labels for control flow nodes (jump target)
546  * TODO: Jump optimization
547  */
548 static void amd64_gen_labels(ir_node *block, void *env)
549 {
550         ir_node *pred;
551         int n = get_Block_n_cfgpreds(block);
552         (void) env;
553
554         for (n--; n >= 0; n--) {
555                 pred = get_Block_cfgpred(block, n);
556                 set_irn_link(pred, block);
557         }
558 }
559
560 /**
561  * Main driver
562  */
563 void amd64_gen_routine(ir_graph *irg)
564 {
565         ir_entity *entity = get_irg_entity(irg);
566         ir_node  **blk_sched;
567         size_t i, n;
568
569         /* register all emitter functions */
570         amd64_register_emitters();
571
572         blk_sched = be_create_block_schedule(irg);
573
574         be_gas_emit_function_prolog(entity, 4, NULL);
575
576         irg_block_walk_graph(irg, amd64_gen_labels, NULL, NULL);
577
578         n = ARR_LEN(blk_sched);
579         for (i = 0; i < n; i++) {
580                 ir_node *block = blk_sched[i];
581                 ir_node *next  = (i + 1) < n ? blk_sched[i+1] : NULL;
582
583                 set_irn_link(block, next);
584         }
585
586         for (i = 0; i < n; ++i) {
587                 ir_node *block = blk_sched[i];
588
589                 amd64_gen_block(block, 0);
590         }
591
592         be_gas_emit_function_epilog(entity);
593 }