e41e277075303d103a47f4b6ce6205ad5667f6aa
[nit.git] / src / compiling / compiling_icode.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2009 Jean Privat <jean@pryen.org>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Generate C code from intermediate code representation
18 package compiling_icode
19
20 import icode
21 private import analysis
22 import compiling_base
23
24 # Compiler context from ICode to C
25 class I2CCompilerVisitor
26 # Associate things
27 var _ids: HashMap[Object, String] = new HashMap[Object, String]
28 # Associate other things
29 var _ids2: HashMap[Object, String] = new HashMap[Object, String]
30
31 # Return the string associated with a register
32 fun register(e: IRegister): String
33 do
34 if e.stype isa MMTypeNone then return "NIT_NULL"
35 var ids = _ids
36 if closure and not e.is_local then ids = _ids2
37 if ids.has_key(e) then
38 return ids[e]
39 else
40 var i = e.slot_index
41 if i == null then
42 # The register is dead
43 var s = "NIT_NULL"
44 ids[e] = s
45 return s
46 else
47 var s: String
48 var strs: HashMap[Int, String]
49 if e.in_tag_slots then
50 strs = once new HashMap[Int, String]
51 if not strs.has_key(i) then strs[i] = "REGB{i}"
52 else if closure and not e.is_local then
53 strs = once new HashMap[Int, String]
54 if not strs.has_key(i) then strs[i] = "closctx->variable[{i}]"
55 else
56 strs = once new HashMap[Int, String]
57 if not strs.has_key(i) then strs[i] = "REG[{i}]"
58 end
59 s = strs[i]
60 ids[e] = s
61 return s
62 end
63 end
64 end
65
66 # Return the strings associated with registers
67 fun registers(a: Collection[IRegister]): Array[String]
68 do
69 var r = new Array[String].with_capacity(a.length)
70 for e in a do
71 r.add(register(e))
72 end
73 return r
74 end
75
76 var _last_number: Int = 0
77 # Give a new unique number (unique for the visitor)
78 fun new_number: Int
79 do
80 _last_number += 1
81 return _last_number
82 end
83
84 # Return the string associated with a escape label
85 fun lab(e: ISeq): String
86 do
87 if _ids.has_key(e) then
88 return _ids[e]
89 else
90 var s = "label{new_number}"
91 _ids[e] = s
92 return s
93 end
94 end
95
96 # The rank (number) of each closure
97 readable var _closures: HashMap[IClosureDecl, Int] = new HashMap[IClosureDecl, Int]
98
99 # The functionnal type of each closure
100 readable var _clostypes: HashMap[IClosureDecl, String] = new HashMap[IClosureDecl, String]
101
102 # label locally accessibles
103 readable writable var _local_labels: HashSet[ISeq] = new HashSet[ISeq]
104
105 # Not local escaped labels
106 # The integer value is an index identifying the label
107 readable writable var _escaped_labels: HashMap[ISeq, Int] = new HashMap[ISeq, Int]
108
109 # Register a escape to a non local label and return an index identifying the label
110 fun register_escape_label(e: ISeq): Int
111 do
112 if _escaped_labels.has_key(e) then
113 return _escaped_labels[e]
114 else
115 var res = _escaped_labels.length + 1
116 _escaped_labels[e] = res
117 return res
118 end
119 end
120
121 # Add a C label mark (if needed)
122 fun add_label(e: ISeq)
123 do
124 if _ids.has_key(e) then
125 add_instr("{_ids[e]}: while(0);")
126 end
127 end
128
129 # Add a goto to a label (even outside a closure)
130 fun add_goto(seq: ISeq)
131 do
132 if local_labels.has(seq) then
133 add_instr("goto {lab(seq)};")
134 else
135 assert closure
136 var ind = register_escape_label(seq)
137 add_instr("closctx->has_broke = (val_t*){ind};")
138 add_instr("goto {lab(return_label.as(not null))};")
139 end
140 end
141
142 # Are we in a closure ?
143 readable writable var _closure: Bool = false
144
145 # The current compiler visitor
146 readable var _visitor: CompilerVisitor
147
148 # The current compiled iroutine
149 readable var _iroutine: IRoutine
150
151 # The return label of the current compiling C function
152 readable writable var _return_label: nullable ISeq = null
153
154 fun add_decl(s: String)
155 do
156 visitor.add_decl(s)
157 end
158
159 fun add_instr(s: String)
160 do
161 var l = _next_location
162 if l != null then
163 visitor.add_instr("/* ", l.file, ":", l.line_start.to_s, " */")
164 _next_location = null
165 end
166 visitor.add_instr(s)
167 end
168
169 fun indent
170 do
171 visitor.indent
172 end
173
174 fun unindent
175 do
176 visitor.unindent
177 end
178
179 fun add_assignment(to, from: String)
180 do
181 visitor.add_assignment(to, from)
182 end
183
184 var _last_location: nullable Location = null
185 var _next_location: nullable Location = null
186
187 # Add location information in a comment
188 # Do nothing if the last location added is the same
189 fun add_location(l: nullable Location)
190 do
191 var last = _last_location
192 if last == l or l == null then return
193 _last_location = l
194 if last != null and last.file == l.file and last.line_start == l.line_start then
195 return
196 else
197 _next_location = l
198 end
199 end
200
201 # The C fonction name of the iroutine
202 readable var _basecname: String
203
204 init(v: CompilerVisitor, ir: IRoutine, cname: String)
205 do
206 _visitor = v
207 _iroutine = ir
208 _basecname = cname
209 end
210 end
211
212 redef class IRoutine
213 # Declare and start a C function that match the routine
214 # Return what must be given to compile_inside_to_c or to compile_to_c
215 # After the method, an openinig { and and indent is added.
216 # So, do not forget to add a sub_context, to unintent and to add a closing }
217 fun compile_signature_to_c(v: CompilerVisitor, cname: String, human_name: nullable String, before_params, after_params: nullable String): Array[String]
218 do
219 var cargs = new Array[String]
220 var cparams = new Array[String]
221 if before_params != null then cparams.add(before_params)
222 for i in [0..params.length[ do
223 cargs.add("p{i}")
224 cparams.add("val_t p{i}")
225 end
226 if closure_decls != null then
227 for i in [0..closure_decls.length[ do
228 var closcn = "CLOS_{cname}_{i}"
229 var cs = closure_decls[i].closure.signature
230 var subparams = new Array[String] # Parameters of the closure
231 subparams.add("struct WBT_ *")
232 for j in [0..cs.arity[ do
233 subparams.add("val_t")
234 end
235 var rr = "void"
236 if cs.return_type != null then rr = "val_t"
237 v.add_decl("typedef {rr} (*{closcn})({subparams.join(", ")});")
238 cargs.add("wd{i}")
239 cparams.add("struct WBT_ *wd{i}")
240 end
241 end
242 if after_params != null then cparams.add(after_params)
243 var r = "void"
244 if result != null then r = "val_t"
245 var p: String
246 if cparams.is_empty then
247 p = "void"
248 else
249 p = cparams.join(", ")
250 end
251 if human_name != null then v.add_decl("#define LOCATE_", cname, " \"", human_name, "\"")
252 v.add_decl(r, " ", cname, "(", p, ");")
253 v.add_decl("typedef ", r, " (*", cname, "_t)(", p, ");")
254 v.add_instr(r, " ", cname, "(", p, ")\{")
255 v.indent
256 return cargs
257 end
258
259 # Compile the body of the routine, return the result value is any
260 fun compile_inside_to_c(v: I2CCompilerVisitor, args: Array[String]): nullable String
261 do
262 # Add the trace
263 var ll = 0
264 if location != null then
265 ll = location.line_start
266 end
267 v.add_decl("struct trace_t trace = \{NULL, NULL, {ll}, LOCATE_{v.basecname}, {std_slots_nb}\};")
268 v.add_instr("trace.prev = tracehead; tracehead = &trace;")
269 v.add_instr("trace.file = LOCATE_{v.visitor.module.name};")
270 v.add_instr("trace.REG_pointer = (val_t **)&REG;")
271
272 # Add local variables
273 if std_slots_nb == 0 then
274 v.add_decl("val_t *REG = NULL;")
275 else
276 var init_vals = new Buffer
277 init_vals.append "val_t REG[{std_slots_nb}] = \{ NIT_NULL"
278 for i in [1..std_slots_nb[ do init_vals.append(", NIT_NULL")
279 init_vals.append " \};"
280 v.add_decl(init_vals.to_s)
281 end
282 for i in [0..tag_slots_nb[ do
283 v.add_decl("val_t REGB{i};")
284 end
285 var iclosdecls = closure_decls
286 if iclosdecls != null then
287 v.add_decl("struct WBT_ *CREG[{iclosdecls.length}];")
288 else
289 v.add_decl("struct WBT_ **CREG = NULL;")
290 end
291 var k = 0
292 for r in params do
293 if r.slot_index != null then v.add_assignment(v.register(r), args[k])
294 k += 1
295 end
296 if iclosdecls != null then
297 for i in [0..iclosdecls.length[ do
298 var iclosdecl = iclosdecls[i]
299 v.add_instr("CREG[{i}] = {args[params.length+i]};")
300 v.closures[iclosdecl] = i
301 var cs = iclosdecl.closure.signature # Closure signature
302 var subparams = new Array[String] # Parameters of the closure
303 subparams.add("struct WBT_ *")
304 for j in [0..cs.arity[ do
305 var p = "val_t"
306 subparams.add(p)
307 end
308 var r = "void"
309 if cs.return_type != null then r = "val_t"
310 v.clostypes[iclosdecl] = "{r} (*)({subparams.join(", ")})"
311 end
312 end
313 v.add_decl("val_t tmp;")
314
315 # Prepare return
316 var old_rl = v.return_label
317 v.return_label = body
318
319 # Compile body
320 body.compile_to_c(v)
321
322 v.add_instr("tracehead = trace.prev;")
323 v.return_label = old_rl
324 var r = result
325 if r != null then
326 return v.register(r)
327 else
328 return null
329 end
330 end
331
332 # Full compilation of the routine
333 # Including optimization and other stuff.
334 # cv must be in the correct function
335 fun compile_to_c(cv: CompilerVisitor, cname: String, args: Array[String]): nullable String
336 do
337 optimize(cv.module)
338 var v = new I2CCompilerVisitor(cv, self, cname)
339 return compile_inside_to_c(v, args)
340 end
341 end
342
343 redef class ICode
344 # Full compilation of the icode
345 fun compile_to_c(v: I2CCompilerVisitor)
346 do
347 v.add_location(location)
348 store_result(v, inner_compile_to_c(v))
349 end
350
351 # Is a result really needed
352 private fun need_result: Bool
353 do
354 var r = result
355 return r != null and r.slot_index != null
356 end
357
358 # Store s in the result value of self
359 private fun store_result(v: I2CCompilerVisitor, s: nullable String)
360 do
361 var r = result
362 if r != null and r.slot_index != null then
363 assert s != null
364 v.add_assignment(v.register(r), s)
365 else if s != null and not is_pure then
366 # ICode with side effects must be evaluated
367 # even if the result is not wanted
368 v.add_instr(s + ";")
369 end
370 end
371
372 # Compilation of without the result assigment
373 # Return the right value is case of expression
374 # Return the full expression (witout ;) in case of statement
375 private fun inner_compile_to_c(v: I2CCompilerVisitor): nullable String is abstract
376 end
377
378 redef class ISeq
379 redef fun inner_compile_to_c(v)
380 do
381 v.local_labels.add(self)
382 for ic in icodes do
383 ic.compile_to_c(v)
384 end
385 v.add_label(self)
386 return null
387 end
388 end
389
390 redef class IIf
391 redef fun inner_compile_to_c(v)
392 do
393 v.add_instr("if (UNTAG_Bool({v.register(expr)})) \{")
394 if not then_seq.icodes.is_empty then
395 v.indent
396 then_seq.inner_compile_to_c(v)
397 v.unindent
398 end
399 if not else_seq.icodes.is_empty then
400 v.add_instr("} else \{")
401 v.indent
402 else_seq.inner_compile_to_c(v)
403 v.unindent
404 end
405 v.add_instr("}")
406 return null
407 end
408 end
409
410 redef class ILoop
411 redef fun inner_compile_to_c(v)
412 do
413 v.local_labels.add(self)
414 v.add_instr("while(1) \{")
415 v.indent
416 for ic in icodes do
417 ic.compile_to_c(v)
418 end
419 v.unindent
420 v.add_instr("}")
421 v.add_label(self)
422 return null
423 end
424 end
425
426 redef class IEscape
427 redef fun inner_compile_to_c(v)
428 do
429 v.add_goto(seq)
430 return null
431 end
432 end
433
434 redef class IAbsCall
435 redef fun compile_to_c(v)
436 do
437 v.add_location(location)
438 var args = v.registers(exprs)
439
440 # Compile closure definitions
441 var old_el = v.escaped_labels
442 var closdefs = closure_defs
443 var closcns: nullable Array[String] = null
444 if closdefs != null then
445 v.escaped_labels = new HashMap[ISeq, Int]
446 closcns = new Array[String]
447 for cd in closdefs do
448 if cd != null then
449 var cn = cd.compile_closure(v)
450 args.add(cn)
451 closcns.add(cn)
452 else
453 args.add("NULL")
454 end
455 end
456 end
457
458 var s = compile_call_to_c(v, args)
459 var r: nullable String = s
460
461 # Intercept escapes
462 if closcns != null then
463 var els = v.escaped_labels
464 v.escaped_labels = old_el
465 # Is there possible escapes?
466 if not els.is_empty then
467 # Call in a tmp variable to avoid 'break' overwrite
468 if need_result then
469 r = "tmp"
470 v.add_assignment(r, s)
471 else
472 r = null
473 v.add_instr(s + ";")
474 end
475 # What is the escape index (if any?)
476 # It's computed as the union of has_broke
477 var switcha = new Array[String]
478 for cn in closcns do
479 switcha.add("((int)({cn}->has_broke))")
480 end
481 var switch = switcha.join(" | ")
482 # What are the expected escape indexes
483 v.add_instr("switch ({switch}) \{")
484 v.indent
485 # No escape occured, continue as usual
486 v.add_instr("case 0: break;")
487 var lls = v.local_labels
488 var iels = els.iterator
489 var forward_escape = false
490 while iels.is_ok do
491 var seq = iels.key
492 if lls.has(seq) then
493 # Local escape occured
494 v.add_instr("case {iels.item}: goto {v.lab(seq)};")
495 else
496 # Forward escape occured: register the escape label
497 assert v.closure
498 v.register_escape_label(seq)
499 forward_escape = true
500 end
501 iels.next
502 end
503 # Forward escape occured, just pass to the next one
504 if forward_escape then
505 v.add_instr("default: closctx->has_broke = (val_t*)({switch}); goto {v.lab(v.return_label.as(not null))};")
506 end
507 v.unindent
508 v.add_instr("\}")
509 end
510 end
511
512 store_result(v, r)
513 end
514
515 redef fun inner_compile_to_c(v) do abort
516
517 # The single invocation witout fancy stuffs
518 private fun compile_call_to_c(v: I2CCompilerVisitor, args: Array[String]): String is abstract
519 end
520
521 redef class ICall
522 redef fun compile_call_to_c(v, args)
523 do
524 var prop = property
525 if prop.global.is_init then args.add("init_table")
526 if prop.name == (once ("add".to_symbol)) and prop.local_class.name == (once ("Array".to_symbol)) then
527 return "{prop.cname}({args.join(", ")})"
528 else
529 return "{prop.global.meth_call}({args[0]})({args.join(", ")})"
530 end
531 end
532 end
533
534 redef class ISuper
535 redef fun compile_call_to_c(v, args)
536 do
537 var prop = property
538 if prop.global.is_init then args.add("init_table")
539 return "{prop.super_meth_call}({args[0]})({args.join(", ")})"
540 end
541 end
542
543 redef class INew
544 redef fun compile_call_to_c(v, args)
545 do
546 return "NEW_{stype.local_class}_{property.global.intro.cname}({args.join(", ")})"
547 end
548 end
549
550 redef class INative
551 redef fun inner_compile_to_c(v)
552 do
553 if exprs.is_empty then
554 return code
555 else
556 var res = new Buffer
557 var i = 0
558 var c = code.split_with("@@@")
559 for s in c do
560 res.append(s)
561 if i < exprs.length and i < c.length-1 then
562 res.append(v.register(exprs[i]))
563 end
564 i += 1
565 end
566 return res.to_s
567 end
568 end
569 end
570
571 redef class IAbort
572 redef fun inner_compile_to_c(v)
573 do
574 var s = new Buffer.from("fprintf(stderr")
575 for t in texts do
576 s.append(", \"{t}\"")
577 end
578 s.append(");")
579 v.add_instr(s.to_s)
580
581 var ll = location
582 s = new Buffer.from("fprintf(stderr, \" (%s")
583 if ll != null then
584 s.append(":%d")
585 end
586 s.append(")\\n\", LOCATE_{module_location.name}")
587 if ll != null then
588 s.append(", {ll.line_start}")
589 end
590 s.append(");")
591 v.add_instr(s.to_s)
592
593 v.add_instr("nit_exit(1);")
594 return null
595 end
596 end
597
598 redef class IMove
599 redef fun inner_compile_to_c(v)
600 do
601 return v.register(expr)
602 end
603 end
604
605 redef class IAttrRead
606 redef fun inner_compile_to_c(v)
607 do
608 return "{property.global.attr_access}({v.register(expr)})"
609 end
610 end
611
612 redef class IAttrIsset
613 redef fun inner_compile_to_c(v)
614 do
615 return "TAG_Bool({property.global.attr_access}({v.register(expr)})!=NIT_NULL)"
616 end
617 end
618
619 redef class IAttrWrite
620 redef fun inner_compile_to_c(v)
621 do
622 v.add_instr("{property.global.attr_access}({v.register(expr1)}) = {v.register(expr2)};")
623 return null
624 end
625 end
626
627 redef class ITypeCheck
628 redef fun inner_compile_to_c(v)
629 do
630 # FIXME handle formaltypes
631 var g = stype.local_class.global
632 var recv = v.register(expr)
633 var s = ""
634 if expr.stype.is_nullable then
635 if stype.is_nullable then
636 s = "({recv}==NIT_NULL) || "
637 else if stype.as_nullable == expr.stype then
638 return "TAG_Bool({recv}!=NIT_NULL)"
639 else
640 s = "({recv}!=NIT_NULL) && "
641 end
642 end
643 return "TAG_Bool({s}VAL_ISA({recv}, {g.color_id}, {g.id_id})) /*cast {stype}*/"
644 end
645 end
646
647 redef class IIs
648 redef fun inner_compile_to_c(v)
649 do
650 var t1 = expr1.stype
651 var t2 = expr2.stype
652 if t1 isa MMTypeNone then
653 if t2 isa MMTypeNone then
654 return "TAG_Bool(1)"
655 else if t2.is_nullable then
656 return "TAG_Bool({v.register(expr2)}==NIT_NULL)"
657 else
658 return "TAG_Bool(0)"
659 end
660 else if t1.is_nullable then
661 if t2 isa MMTypeNone then
662 return "TAG_Bool({v.register(expr1)}==NIT_NULL)"
663 else if t2.is_nullable then
664 return "TAG_Bool(IS_EQUAL_NN({v.register(expr1)},{v.register(expr2)}))"
665 else
666 return "TAG_Bool(IS_EQUAL_ON({v.register(expr2)},{v.register(expr1)}))"
667 end
668 else
669 if t2 isa MMTypeNone then
670 return "TAG_Bool(0)"
671 else if t2.is_nullable then
672 return "TAG_Bool(IS_EQUAL_ON({v.register(expr1)},{v.register(expr2)}))"
673 else
674 return "TAG_Bool(IS_EQUAL_OO({v.register(expr1)},{v.register(expr2)}))"
675 end
676 end
677 end
678 end
679
680 redef class INot
681 redef fun inner_compile_to_c(v)
682 do
683 return "TAG_Bool(!UNTAG_Bool({v.register(expr)}))"
684 end
685 end
686
687 redef class IOnce
688 redef fun inner_compile_to_c(v)
689 do
690 var i = v.new_number
691 var res = result.as(not null)
692 if res.stype.is_nullable then
693 v.add_decl("static val_t once_value_{i}; static int once_bool_{i}; /* Once value */")
694 v.add_instr("if (!once_bool_{i}) \{")
695 else
696 # Since the value is not nullable, we use the null value to represent the boolean
697 v.add_decl("static val_t once_value_{i}; /* Once value */")
698 v.add_instr("if (!once_value_{i}) \{")
699 end
700 v.indent
701 body.compile_to_c(v)
702 var e = v.register(result.as(not null))
703 v.add_instr("once_value_{i} = {e};")
704 if res.stype.is_nullable then v.add_instr("once_bool_{i} = true;")
705 v.unindent
706 v.add_instr("} else {e} = once_value_{i};")
707 return e
708 end
709 end
710
711 redef class IClosCall
712 redef fun compile_to_c(v: I2CCompilerVisitor)
713 do
714 v.add_location(location)
715 var ivar: String
716 if v.closure then
717 ivar = "closctx->closurevariable[{v.closures[closure_decl]}]"
718 else
719 ivar = "CREG[{v.closures[closure_decl]}]"
720 end
721 var args = [ivar]
722 args.append(v.registers(exprs))
723
724 var s = "(({v.clostypes[closure_decl]})({ivar}->fun))({args.join(", ")})"
725 store_result(v, s)
726
727 v.add_instr("if ({ivar}->has_broke) \{")
728 v.indent
729 var bs = break_seq
730 if bs != null then
731 bs.compile_to_c(v)
732 end
733 v.add_goto(v.iroutine.body)
734 v.unindent
735 v.add_instr("\}")
736 end
737
738 redef fun inner_compile_to_c(v) do abort
739 end
740
741 redef class IHasClos
742 redef fun inner_compile_to_c(v)
743 do
744 var ivar: String
745 if v.closure then
746 ivar = "closctx->closurevariable[{v.closures[closure_decl]}]"
747 else
748 ivar = "CREG[{v.closures[closure_decl]}]"
749 end
750 return "TAG_Bool({ivar} != NULL)"
751 end
752 end
753
754
755 redef class IClosureDef
756 fun compile_closure(v: I2CCompilerVisitor): String
757 do
758 var cfc_old = v.closure
759 v.closure = true
760 var lls_old = v.local_labels
761 v.local_labels = new HashSet[ISeq]
762
763 var cv = v.visitor
764 var ctx_old = cv.ctx
765 cv.ctx = new CContext
766 cv.out_contexts.add(cv.ctx)
767
768 var cname = "OC_{v.basecname}_{v.new_number}"
769 var args = compile_signature_to_c(v.visitor, cname, null, "struct WBT_ *closctx", null)
770 var ctx_old2 = cv.ctx
771 cv.ctx = new CContext
772
773 var s = compile_inside_to_c(v, args)
774 if s == null then
775 v.add_instr("return;")
776 else
777 v.add_instr("return {s};")
778 end
779
780 ctx_old2.append(cv.ctx)
781 cv.ctx = ctx_old2
782 v.unindent
783 v.add_instr("}")
784 cv.ctx = ctx_old
785
786 v.closure = cfc_old
787
788 # Build closure
789 var closcnv = "wbclos{v.new_number}"
790 v.add_decl("struct WBT_ {closcnv};")
791 v.add_instr("{closcnv}.fun = (fun_t){cname};")
792 v.add_instr("{closcnv}.has_broke = NULL;")
793 if cfc_old then
794 v.add_instr("{closcnv}.variable = closctx->variable;")
795 v.add_instr("{closcnv}.closurevariable = closctx->closurevariable;")
796 else
797 v.add_instr("{closcnv}.variable = REG;")
798 v.add_instr("{closcnv}.closurevariable = CREG;")
799 end
800
801 v.local_labels = lls_old
802 return "(&{closcnv})"
803 end
804 end