8db2cb423aefb6b3fcd5576c3839e595dee3216d
[nit.git] / src / analysis / remove_out_of_init_get_test.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2009 Jean-Sebastien Gelinas <calestar@gmail.com>
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 # This package introduces an optimization that removes 'get' tests when
18 # not reachable from an initializer
19 package remove_out_of_init_get_test
20
21 import reachable_from_init_method_analysis
22
23 redef class Program
24 readable var _nb_optimized_isset: Int = 0
25
26 # Calling this method will remove all 'isset' that were generated automaticaly
27 # before a attribute read if this attribute read is done in a method that
28 # cannot be reached by a initializer
29 fun optimize_out_of_init_getters do
30 with_each_iroutines !action(i,m) do
31 if not rfima.is_iroutine_reachable_from_init(i) then
32 var remover = new GetterTestRemover
33 remover.visit_iroutine(i)
34 _nb_optimized_isset = nb_optimized_isset + remover.nb_optimized_isset
35 end
36 end
37 end
38
39 # This method will create a file and output informations about this optimization
40 fun dump_out_of_init_information(directory_name: String) do
41 var f = new OFStream.open("{directory_name}/{main_module.name}.out_of_init_opt.log")
42 var nb_not_optimized = 0
43
44 with_each_iroutines !action(i,m) do
45 var counter = new IssetCounter
46 counter.visit_iroutine(i)
47 nb_not_optimized = nb_not_optimized + counter.nb_isset
48 end
49
50 f.write("Nb. optimized isset: {nb_optimized_isset}\n")
51 f.write("Nb. not optimized: {nb_not_optimized}\n")
52
53 f.close
54 end
55 end
56
57 class IssetCounter
58 special ICodeVisitor
59 readable var _nb_isset: Int = 0
60
61 redef fun visit_icode(ic)
62 do
63 if ic isa IAttrIsset then
64 _nb_isset = nb_isset + 1
65 end
66
67 super
68 end
69 end
70
71 class GetterTestRemover
72 special ICodeVisitor
73 readable var _nb_optimized_isset: Int = 0
74
75 redef fun visit_icode(ic)
76 do
77 # Replace 'x = isset(y)' by 'x = true'
78 if ic isa IAttrIsset then
79 var result = ic.result
80 assert result != null
81 var e = new IBoolValue(true)
82 e.result = result
83 current_icode.insert_before(e)
84 current_icode.delete
85 _nb_optimized_isset = nb_optimized_isset + 1
86 end
87
88 super
89 end
90 end