Check polymorphic contexts before redirecting calls to clones
Prevents incorrect virtual method calls by ensuring cloned functions match polymorphic contexts.
The inter-procedural analysis (IPA-CP) pass in GCC incorrectly redirected calls to specialized clones when polymorphic contexts were not considered. This could lead to the execution of wrong virtual methods if a clone was specialized for one dynamic type but a later clone assumed a different one. A new function, cgraph_edge_brings_all_contexts_for_node, is introduced to check these polymorphic contexts, ensuring that calls are only redirected to clones for which the context is compatible, thus preventing runtime errors.
In Details
The perhaps_add_new_callers function in ipa-cp.cc redirects calls to existing specialized clones. It previously only compared scalar and aggregate constants, neglecting polymorphic contexts. This commit introduces cgraph_edge_brings_all_contexts_for_node to check if a call's polymorphic context is compatible with the context for which a clone was specialized. This prevents a call to a clone specialized for TypeA from being made when the call's dynamic type is TypeB, thereby avoiding incorrect devirtualization and runtime aborts in self-recursive functions.
- IPA-CP
- Interprocedural Analysis - Clone Propagation. A GCC optimization pass that analyzes code across function boundaries to identify opportunities for specialization and inlining.
- polymorphic context
- In object-oriented programming, refers to the dynamic type of an object or parameter at runtime. IPA-CP uses this to specialize functions for specific types.
- clone
- A specialized version of a function created by the IPA-CP pass to optimize calls with specific constant arguments or known dynamic types.
- devirtualize
- The process of replacing a virtual function call with a direct function call. This is possible when the compiler can determine the exact type of the object at compile time.