1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2012 Jean Privat <jean@pryen.org>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
18 # Rapid type analysis on the AST
20 # Rapid type analysis is an analyse that aproximates the set of live classes
21 # and the set of live methods starting from the entry point of the program.
22 # These two sets are interdependant and computed together.
23 # It is quite efficient but the type set is global and pollutes each call site.
24 module rapid_type_analysis
29 import auto_super_init
31 import csv
# for live_types_to_csv
32 import ordered_tree
# for live_methods_to_tree
34 redef class ModelBuilder
35 fun do_rapid_type_analysis
(mainmodule
: MModule): RapidTypeAnalysis
37 var analysis
= new RapidTypeAnalysis(self, mainmodule
)
43 # RapidTypeAnalysis looks for alive rapid types in application.
44 # The entry point of the analysis is the mainmodule of the application.
45 class RapidTypeAnalysis
46 # The modelbuilder used to get the AST.
47 var modelbuilder
: ModelBuilder
49 # The main module of the analysis.
50 # Used to perform types operations.
51 var mainmodule
: MModule
53 # The pool to live types.
54 # During the analysis, new types are added and combined with
55 # live_methods to determine new methoddefs to visit
56 var live_types
= new HashSet[MClassType]
58 # The pool of undesolved live types
59 # They are globally resolved at the end of the analaysis
60 var live_open_types
= new HashSet[MClassType]
62 # Live (instantiated) classes.
63 var live_classes
= new HashSet[MClass]
65 # The pool of types used to perform type checks (isa and as).
66 var live_cast_types
= new HashSet[MType]
68 # The pool of undesolved types used to perform type checks (isa and as).
69 # They are globally resolved at the end of the analaysis
70 var live_open_cast_types
= new HashSet[MType]
72 # Live method definitions.
73 var live_methoddefs
= new HashSet[MMethodDef]
76 var live_methods
= new HashSet[MMethod]
79 var live_super_sends
= new HashSet[MMethodDef]
81 # Return a ready-to-save CSV document objet that agregates informations about live types.
82 # Each discovered type is listed in a line, with its status: resolution, liveness, cast-liveness.
83 # Note: types are listed in an alphanumeric order to improve human reading.
84 fun live_types_to_csv
: CSVDocument
86 # Gather all kind of type
87 var typeset
= new HashSet[MType]
88 typeset
.add_all
(live_types
)
89 typeset
.add_all
(live_open_types
)
90 typeset
.add_all
(live_cast_types
)
91 typeset
.add_all
(live_open_cast_types
)
92 var types
= typeset
.to_a
93 (new CachedAlphaComparator).sort
(types
)
94 var res
= new CSVDocument
95 res
.header
= ["Type", "Resolution", "Liveness", "Cast-liveness"]
98 if t
.need_anchor
then reso
= "OPEN " else reso
= "CLOSED"
100 if t
isa MClassType and (live_types
.has
(t
) or live_open_types
.has
(t
)) then live
= "LIVE" else live
= "DEAD"
102 if live_cast_types
.has
(t
) or live_open_cast_types
.has
(t
) then cast
= "CAST LIVE" else cast
= "CAST DEAD"
103 res
.add_line
(t
, reso
, live
, cast
)
108 # Return a ready-to-save OrderedTree object that agregates infomration about live methods.
109 # Note: methods are listed in an alphanumeric order to improve human reading.
110 fun live_methods_to_tree
: OrderedTree[Object]
112 var tree
= new OrderedTree[Object]
113 for x
in live_methods
do
116 for z
in x
.mpropdefs
do
118 if live_methoddefs
.has
(z
) then
120 if live_super_sends
.has
(z
) then
121 tree
.add
(zn
, zn
+ "(super)")
123 else if live_super_sends
.has
(z
) then
124 tree
.add
(xn
, zn
+ "(super)")
128 tree
.sort_with
(alpha_comparator
)
132 # Methods that are are still candidate to the try_send
133 private var totry_methods
= new HashSet[MMethod]
135 # The method definitions that remain to visit
136 private var todo
= new List[MMethodDef]
138 private fun force_alive
(classname
: String)
140 var classes
= self.modelbuilder
.model
.get_mclasses_by_name
(classname
)
141 if classes
!= null then for c
in classes
do self.add_new
(c
.mclass_type
, c
.mclass_type
)
144 # Run the analysis until all visitable method definitions are visited.
147 var maintype
= mainmodule
.sys_type
148 if maintype
== null then return # No entry point
149 add_new
(maintype
, maintype
)
150 var initprop
= mainmodule
.try_get_primitive_method
("init", maintype
.mclass
)
151 if initprop
!= null then
152 add_send
(maintype
, initprop
)
154 var mainprop
= mainmodule
.try_get_primitive_method
("main", maintype
.mclass
)
155 if mainprop
!= null then
156 add_send
(maintype
, mainprop
)
159 # Force primitive types
165 while not todo
.is_empty
do
166 var mmethoddef
= todo
.shift
167 #print "# visit {mmethoddef}"
168 var v
= new RapidTypeVisitor(self, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
)
170 var vararg_rank
= mmethoddef
.msignature
.vararg_rank
171 if vararg_rank
> -1 then
172 var node
= self.modelbuilder
.mpropdef2npropdef
[mmethoddef
]
173 var elttype
= mmethoddef
.msignature
.mparameters
[vararg_rank
].mtype
174 #elttype = elttype.anchor_to(self.mainmodule, v.receiver)
175 var vararg
= self.mainmodule
.get_primitive_class
("Array").get_mtype
([elttype
])
177 var native
= self.mainmodule
.get_primitive_class
("NativeArray").get_mtype
([elttype
])
179 v
.add_monomorphic_send
(vararg
, self.modelbuilder
.force_get_primitive_method
(node
, "with_native", vararg
.mclass
, self.mainmodule
))
183 for i
in [0..mmethoddef
.msignature
.arity
[ do
184 var origtype
= mmethoddef
.mproperty
.intro
.msignature
.mparameters
[i
].mtype
185 if not origtype
.need_anchor
then continue # skip non covariant stuff
186 var paramtype
= mmethoddef
.msignature
.mparameters
[i
].mtype
187 #paramtype = v.cleanup_type(paramtype).as(not null)
191 if not modelbuilder
.mpropdef2npropdef
.has_key
(mmethoddef
) then
192 # It is an init for a class?
193 if mmethoddef
.mproperty
.name
== "init" then
194 var nclassdef
= self.modelbuilder
.mclassdef2nclassdef
[mmethoddef
.mclassdef
]
195 var super_inits
= nclassdef
.super_inits
196 if super_inits
!= null then
197 #assert args.length == 1
198 for su
in super_inits
do
199 v
.add_monomorphic_send
(v
.receiver
, su
)
209 var npropdef
= modelbuilder
.mpropdef2npropdef
[mmethoddef
]
211 if npropdef
isa AConcreteMethPropdef then
212 var auto_super_inits
= npropdef
.auto_super_inits
213 if auto_super_inits
!= null then
214 for auto_super_init
in auto_super_inits
do
215 v
.add_callsite
(auto_super_init
)
218 else if npropdef
isa AInternMethPropdef or
219 (npropdef
isa AExternMethPropdef and npropdef
.n_extern
!= null) then
220 # UGLY: We force the "instantation" of the concrete return type if any
221 var ret
= mmethoddef
.msignature
.return_mtype
222 if ret
!= null and ret
isa MClassType and ret
.mclass
.kind
!= abstract_kind
and ret
.mclass
.kind
!= interface_kind
then
225 else if npropdef
isa AExternMethPropdef then
226 var nclassdef
= npropdef
.parent
.as(AClassdef)
227 v
.enter_visit
(npropdef
)
228 else if npropdef
isa AExternInitPropdef then
229 v
.add_type
(v
.receiver
)
234 v
.enter_visit
(npropdef
)
237 #print "MMethod {live_methods.length}: {live_methods.join(", ")}"
238 #print "MMethodDef {live_methoddefs.length}: {live_methoddefs.join(", ")}"
240 #print "open MType {live_open_types.length}: {live_open_types.join(", ")}"
241 var todo_types
= new List[MClassType]
242 todo_types
.add_all
(live_types
)
243 while not todo_types
.is_empty
do
244 var t
= todo_types
.shift
245 for ot
in live_open_types
do
247 if not ot
.can_resolve_for
(t
, t
, mainmodule
) then continue
248 var rt
= ot
.anchor_to
(mainmodule
, t
)
249 if live_types
.has
(rt
) then continue
250 #print "{ot}/{t} -> {rt}"
256 #print "MType {live_types.length}: {live_types.join(", ")}"
258 #print "open cast MType {live_open_cast_types.length}: {live_open_cast_types.join(", ")}"
259 for ot
in live_open_cast_types
do
260 #print "live_open_cast_type: {ot}"
261 for t
in live_types
do
262 if not ot
.can_resolve_for
(t
, t
, mainmodule
) then continue
263 var rt
= ot
.anchor_to
(mainmodule
, t
)
264 live_cast_types
.add
(rt
)
265 #print " {ot}/{t} -> {rt}"
268 #print "cast MType {live_cast_types.length}: {live_cast_types.join(", ")}"
271 private fun check_depth
(mtype
: MClassType)
275 self.modelbuilder
.toolcontext
.fatal_error
(null, "Fatal error: limitation in the rapidtype analysis engine: a type depth of {d} is too important, the problematic type is {mtype}.")
279 fun add_new
(recv
: MClassType, mtype
: MClassType)
281 assert not recv
.need_anchor
282 if mtype
.need_anchor
then
283 if live_open_types
.has
(mtype
) then return
284 live_open_types
.add
(mtype
)
286 if live_types
.has
(mtype
) then return
287 live_types
.add
(mtype
)
290 var mclass
= mtype
.mclass
291 if live_classes
.has
(mclass
) then return
292 live_classes
.add
(mclass
)
294 for p
in totry_methods
do try_send
(mtype
, p
)
295 for p
in live_super_sends
do try_super_send
(mtype
, p
)
297 var bound_mtype
= mtype
.anchor_to
(mainmodule
, recv
)
298 for cd
in bound_mtype
.collect_mclassdefs
(mainmodule
)
300 if not self.modelbuilder
.mclassdef2nclassdef
.has_key
(cd
) then continue
301 var nclassdef
= self.modelbuilder
.mclassdef2nclassdef
[cd
]
302 for npropdef
in nclassdef
.n_propdefs
do
303 if not npropdef
isa AAttrPropdef then continue
304 var nexpr
= npropdef
.n_expr
305 if nexpr
== null then continue
306 var mpropdef
= npropdef
.mpropdef
.as(not null)
307 var v
= new RapidTypeVisitor(self, bound_mtype
, mpropdef
)
314 fun add_cast
(mtype
: MType)
316 if mtype
.need_anchor
then
317 live_open_cast_types
.add
(mtype
)
319 live_cast_types
.add
(mtype
)
323 fun try_send
(recv
: MClassType, mproperty
: MMethod)
325 recv
= recv
.mclass
.intro
.bound_mtype
326 if not recv
.has_mproperty
(mainmodule
, mproperty
) then return
327 var d
= mproperty
.lookup_first_definition
(mainmodule
, recv
)
331 fun add_call
(mpropdef
: MMethodDef)
333 if live_methoddefs
.has
(mpropdef
) then return
334 live_methoddefs
.add
(mpropdef
)
337 var mproperty
= mpropdef
.mproperty
338 if mproperty
.mpropdefs
.length
<= 1 then return
339 # If all definitions of a method are live, we can remove the definition of the totry set
340 for d
in mproperty
.mpropdefs
do
341 if d
.is_abstract
then continue
342 if not live_methoddefs
.has
(d
) then return
344 #print "full property: {mpropdef.mproperty} for {mpropdef.mproperty.mpropdefs.length} definitions"
345 totry_methods
.remove
(mpropdef
.mproperty
)
348 fun add_send
(recv
: MType, mproperty
: MMethod)
350 if live_methods
.has
(mproperty
) then return
351 #print "new prop: {mproperty}"
352 live_methods
.add
(mproperty
)
353 if mproperty
.mpropdefs
.length
== 1 then
354 # If there is only one definition, just add the definition and do not try again the property
355 var d
= mproperty
.mpropdefs
.first
359 # Else, the property is potentially called with various reciever
360 # So just try the methods with existing receiver and register it for future receiver
361 totry_methods
.add
(mproperty
)
362 for c
in live_classes
do
363 try_send
(c
.intro
.bound_mtype
, mproperty
)
367 fun try_super_send
(recv
: MClassType, mpropdef
: MMethodDef)
369 recv
= recv
.mclass
.intro
.bound_mtype
370 if not recv
.collect_mclassdefs
(mainmodule
).has
(mpropdef
.mclassdef
) then return
371 var d
= mpropdef
.lookup_next_definition
(mainmodule
, recv
)
375 fun add_super_send
(recv
: MType, mpropdef
: MMethodDef)
377 if live_super_sends
.has
(mpropdef
) then return
378 #print "new super prop: {mpropdef}"
379 live_super_sends
.add
(mpropdef
)
380 for t
in live_types
do
381 try_super_send
(t
, mpropdef
)
386 class RapidTypeVisitor
389 var analysis
: RapidTypeAnalysis
390 var receiver
: MClassType
391 var mpropdef
: MPropDef
393 init(analysis
: RapidTypeAnalysis, receiver
: MClassType, mpropdef
: MPropDef)
395 self.analysis
= analysis
396 self.receiver
= receiver
397 self.mpropdef
= mpropdef
398 assert not receiver
.need_anchor
403 n
.accept_rapid_type_visitor
(self)
405 var implicit_cast_to
= n
.implicit_cast_to
406 if implicit_cast_to
!= null then self.add_cast_type
(implicit_cast_to
)
409 # RTA does not enter in AAnnotations
410 if not n
isa AAnnotations then
415 fun cleanup_type
(mtype
: MType): nullable MClassType
417 mtype
= mtype
.anchor_to
(self.analysis
.mainmodule
, self.receiver
)
418 if mtype
isa MNullType then return null
419 if mtype
isa MNullableType then mtype
= mtype
.mtype
420 assert mtype
isa MClassType
421 assert not mtype
.need_anchor
425 fun get_class
(name
: String): MClass
427 return analysis
.mainmodule
.get_primitive_class
(name
)
430 fun get_method
(recv
: MType, name
: String): MMethod
432 var mtype
= cleanup_type
(recv
)
434 return self.analysis
.modelbuilder
.force_get_primitive_method
(self.current_node
.as(not null), name
, mtype
.mclass
, self.analysis
.mainmodule
)
437 fun add_type
(mtype
: MClassType) do analysis
.add_new
(receiver
, mtype
)
439 fun add_monomorphic_send
(mtype
: MType, mproperty
: MMethod) do analysis
.try_send
(mtype
.as(MClassType), mproperty
)
441 fun add_send
(mtype
: MType, mproperty
: MMethod) do analysis
.add_send
(mtype
, mproperty
)
443 fun add_cast_type
(mtype
: MType) do analysis
.add_cast
(mtype
)
445 fun add_callsite
(callsite
: nullable CallSite) do if callsite
!= null then analysis
.add_send
(callsite
.recv
, callsite
.mproperty
)
451 private fun accept_rapid_type_visitor
(v
: RapidTypeVisitor)
457 redef fun accept_rapid_type_visitor
(v
)
459 v
.add_type
(self.mtype
.as(MClassType))
463 redef class AFloatExpr
464 redef fun accept_rapid_type_visitor
(v
)
466 v
.add_type
(self.mtype
.as(MClassType))
470 redef class ACharExpr
471 redef fun accept_rapid_type_visitor
(v
)
473 v
.add_type
(self.mtype
.as(MClassType))
477 redef class AArrayExpr
478 redef fun accept_rapid_type_visitor
(v
)
480 var mtype
= self.mtype
.as(MClassType)
482 var native
= v
.analysis
.mainmodule
.get_primitive_class
("NativeArray").get_mtype
([mtype
.arguments
.first
])
484 mtype
= v
.cleanup_type
(mtype
).as(not null)
485 var prop
= v
.get_method
(mtype
, "with_native")
486 v
.add_monomorphic_send
(mtype
, prop
)
490 redef class AStringFormExpr
491 redef fun accept_rapid_type_visitor
(v
)
493 var native
= v
.get_class
("NativeString").mclass_type
495 var prop
= v
.get_method
(native
, "to_s_with_length")
496 v
.add_monomorphic_send
(native
, prop
)
500 redef class ASuperstringExpr
501 redef fun accept_rapid_type_visitor
(v
)
503 var arraytype
= v
.get_class
("Array").get_mtype
([v
.get_class
("Object").mclass_type
])
504 v
.add_type
(arraytype
)
505 v
.add_type
(v
.get_class
("NativeArray").get_mtype
([v
.get_class
("Object").mclass_type
]))
506 var prop
= v
.get_method
(arraytype
, "join")
507 v
.add_monomorphic_send
(arraytype
, prop
)
508 var prop2
= v
.get_method
(arraytype
, "with_native")
509 v
.add_monomorphic_send
(arraytype
, prop2
)
513 redef class ACrangeExpr
514 redef fun accept_rapid_type_visitor
(v
)
516 var mtype
= self.mtype
.as(MClassType)
518 var prop
= v
.get_method
(mtype
, "init")
519 v
.add_monomorphic_send
(mtype
, prop
)
523 redef class AOrangeExpr
524 redef fun accept_rapid_type_visitor
(v
)
526 var mtype
= self.mtype
.as(MClassType)
528 var prop
= v
.get_method
(mtype
, "without_last")
529 v
.add_monomorphic_send
(mtype
, prop
)
533 redef class ATrueExpr
534 redef fun accept_rapid_type_visitor
(v
)
536 v
.add_type
(self.mtype
.as(MClassType))
540 redef class AFalseExpr
541 redef fun accept_rapid_type_visitor
(v
)
543 v
.add_type
(self.mtype
.as(MClassType))
548 redef fun accept_rapid_type_visitor
(v
)
550 v
.add_cast_type
(self.cast_type
.as(not null))
554 redef class AAsCastExpr
555 redef fun accept_rapid_type_visitor
(v
)
557 v
.add_cast_type
(self.mtype
.as(not null))
561 redef class ASendExpr
562 redef fun accept_rapid_type_visitor
(v
)
564 v
.add_callsite
(callsite
)
569 redef class ASendReassignFormExpr
570 redef fun accept_rapid_type_visitor
(v
)
572 v
.add_callsite
(callsite
)
573 v
.add_callsite
(reassign_callsite
)
574 v
.add_callsite
(write_callsite
)
578 redef class AVarReassignExpr
579 redef fun accept_rapid_type_visitor
(v
)
581 v
.add_callsite
(reassign_callsite
)
585 redef class AAttrReassignExpr
586 redef fun accept_rapid_type_visitor
(v
)
588 v
.add_callsite
(reassign_callsite
)
592 redef class ASuperExpr
593 redef fun accept_rapid_type_visitor
(v
)
595 var callsite
= self.callsite
596 if callsite
!= null then
597 v
.add_callsite
(callsite
)
601 v
.analysis
.add_super_send
(v
.receiver
, mpropdef
.as(not null))
606 redef fun accept_rapid_type_visitor
(v
)
608 v
.add_callsite
(self.method_iterator
)
609 v
.add_callsite
(self.method_is_ok
)
610 if self.variables
.length
== 1 then
611 v
.add_callsite
(self.method_item
)
612 else if self.variables
.length
== 2 then
613 v
.add_callsite
(self.method_key
)
614 v
.add_callsite
(self.method_item
)
618 v
.add_callsite
(self.method_next
)
623 redef fun accept_rapid_type_visitor
(v
)
625 var mtype
= self.mtype
.as(MClassType)
627 v
.add_callsite
(callsite
)