icode: method inlining moves from IRoutine to ICodeBuilder
[nit.git] / src / analysis / inline_methods.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 # Detect inlinable methods and inline them
18 package inline_methods
19
20 import icode
21
22 private class InlineMethodVisitor
23 special ICodeVisitor
24 var _pass: Int = 0
25 var _icb: ICodeBuilder
26
27 redef fun visit_icode(ic)
28 do
29 if ic isa ICall then
30 var m = ic.property
31 if m.iroutine != null and ic.is_inlinable then
32 var icb = _icb
33 var ir = m.iroutine.as(not null)
34 var seq = new ISeq
35 var old_seq = icb.seq
36 icb.seq = seq
37 current_icode.insert_before(seq)
38 var e = icb.inline_routine(ir, ic.exprs)
39 var r = ic.result
40 if r != null then
41 assert e != null
42 current_icode.insert_before(new IMove(r, e))
43 end
44 current_icode.delete
45 icb.seq = old_seq
46 visit_icode(seq)
47 end
48 end
49 super
50 end
51
52 init(m: MMModule, r: IRoutine)
53 do
54 _icb = new ICodeBuilder(m, r)
55 end
56 end
57
58 redef class ICall
59 fun is_inlinable: Bool
60 do
61 var m = property
62 var mn = m.name
63 var cn = m.local_class.name
64 return (m.is_intern and cn != once ("Object".to_symbol)) or
65 (cn == (once ("Array".to_symbol)) and (mn == (once ("length".to_symbol)) or mn == (once ("[]".to_symbol)))) or
66 (cn == (once ("AbstractArrayRead".to_symbol)) and (mn == (once ("length".to_symbol)) or mn == (once ("[]".to_symbol))))
67 end
68 end
69
70 redef class IRoutine
71 fun inline_methods(m: MMModule)
72 do
73 var v = new InlineMethodVisitor(m, self)
74 v.visit_iroutine(self)
75 end
76 end