source: src/GenPoly/Specialize.cc @ a8a2b0a

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since a8a2b0a was a16764a6, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

Changed warning system to prepare for toggling warnings

  • Property mode set to 100644
File size: 15.0 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Specialize.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Mon May 18 07:44:20 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Thu Mar 16 07:53:59 2017
13// Update Count     : 31
14//
15
16#include <cassert>                       // for assert, assertf
17#include <iterator>                      // for back_insert_iterator, back_i...
18#include <map>                           // for _Rb_tree_iterator, _Rb_tree_...
19#include <memory>                        // for unique_ptr
20#include <string>                        // for string
21#include <tuple>                         // for get
22#include <utility>                       // for pair
23
24#include "Common/PassVisitor.h"
25#include "Common/UniqueName.h"           // for UniqueName
26#include "Common/utility.h"              // for group_iterate
27#include "GenPoly.h"                     // for getFunctionType
28#include "InitTweak/InitTweak.h"         // for isIntrinsicCallExpr
29#include "Parser/LinkageSpec.h"          // for C
30#include "ResolvExpr/FindOpenVars.h"     // for findOpenVars
31#include "ResolvExpr/TypeEnvironment.h"  // for OpenVarSet, AssertionSet
32#include "Specialize.h"
33#include "SynTree/Attribute.h"           // for Attribute
34#include "SynTree/Declaration.h"         // for FunctionDecl, DeclarationWit...
35#include "SynTree/Expression.h"          // for ApplicationExpr, Expression
36#include "SynTree/Label.h"               // for Label
37#include "SynTree/Mutator.h"             // for mutateAll
38#include "SynTree/Statement.h"           // for CompoundStmt, DeclStmt, Expr...
39#include "SynTree/Type.h"                // for FunctionType, TupleType, Type
40#include "SynTree/TypeSubstitution.h"    // for TypeSubstitution
41#include "SynTree/Visitor.h"             // for Visitor
42
43namespace GenPoly {
44        struct Specialize final : public WithTypeSubstitution, public WithStmtsToAdd, public WithVisitorRef<Specialize> {
45                Expression * postmutate( ApplicationExpr *applicationExpr );
46                Expression * postmutate( CastExpr *castExpr );
47
48                void handleExplicitParams( ApplicationExpr *appExpr );
49                Expression * createThunkFunction( FunctionType *funType, Expression *actual, InferredParams *inferParams );
50                Expression * doSpecialization( Type *formalType, Expression *actual, InferredParams *inferParams );
51
52                std::string paramPrefix = "_p";
53        };
54
55        /// Looks up open variables in actual type, returning true if any of them are bound in the environment or formal type.
56        bool needsPolySpecialization( Type *formalType, Type *actualType, TypeSubstitution *env ) {
57                if ( env ) {
58                        using namespace ResolvExpr;
59                        OpenVarSet openVars, closedVars;
60                        AssertionSet need, have;
61                        findOpenVars( formalType, openVars, closedVars, need, have, false );
62                        findOpenVars( actualType, openVars, closedVars, need, have, true );
63                        for ( OpenVarSet::const_iterator openVar = openVars.begin(); openVar != openVars.end(); ++openVar ) {
64                                Type *boundType = env->lookup( openVar->first );
65                                if ( ! boundType ) continue;
66                                if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( boundType ) ) {
67                                        // bound to another type variable
68                                        if ( closedVars.find( typeInst->get_name() ) == closedVars.end() ) {
69                                                // bound to a closed variable => must specialize
70                                                return true;
71                                        } // if
72                                } else {
73                                        // variable is bound to a concrete type => must specialize
74                                        return true;
75                                } // if
76                        } // for
77                        // none of the type variables are bound
78                        return false;
79                } else {
80                        // no env
81                        return false;
82                } // if
83        }
84
85        /// True if both types have the same structure, but not necessarily the same types.
86        /// That is, either both types are tuple types with the same size (recursively), or
87        /// both are not tuple types.
88        bool matchingTupleStructure( Type * t1, Type * t2 ) {
89                TupleType * tuple1 = dynamic_cast< TupleType * >( t1 );
90                TupleType * tuple2 = dynamic_cast< TupleType * >( t2 );
91                if ( tuple1 && tuple2 ) {
92                        if ( tuple1->size() != tuple2->size() ) return false;
93                        for ( auto types : group_iterate( tuple1->get_types(), tuple2->get_types() ) ) {
94                                if ( ! matchingTupleStructure( std::get<0>( types ), std::get<1>( types ) ) ) return false;
95                        }
96                        return true;
97                } else if ( ! tuple1 && ! tuple2 ) return true;
98                return false;
99        }
100
101        // walk into tuple type and find the number of components
102        size_t singleParameterSize( Type * type ) {
103                if ( TupleType * tt = dynamic_cast< TupleType * >( type ) ) {
104                        size_t sz = 0;
105                        for ( Type * t : *tt ) {
106                                sz += singleParameterSize( t );
107                        }
108                        return sz;
109                } else {
110                        return 1;
111                }
112        }
113
114        // find the total number of components in a parameter list
115        size_t functionParameterSize( FunctionType * ftype ) {
116                size_t sz = 0;
117                for ( DeclarationWithType * p : ftype->get_parameters() ) {
118                        sz += singleParameterSize( p->get_type() );
119                }
120                return sz;
121        }
122
123        bool needsTupleSpecialization( Type *formalType, Type *actualType ) {
124                // Needs tuple specialization if the structure of the formal type and actual type do not match.
125                // This is the case if the formal type has ttype polymorphism, or if the structure  of tuple types
126                // between the function do not match exactly.
127                if ( FunctionType * fftype = getFunctionType( formalType ) ) {
128                        if ( fftype->isTtype() ) return true;
129                        // conversion of 0 (null) to function type does not require tuple specialization
130                        if ( dynamic_cast< ZeroType * >( actualType ) ) return false;
131                        FunctionType * aftype = getFunctionType( actualType->stripReferences() );
132                        assertf( aftype, "formal type is a function type, but actual type is not: %s", toString( actualType ).c_str() );
133                        // Can't tuple specialize if parameter sizes deeply-differ.
134                        if ( functionParameterSize( fftype ) != functionParameterSize( aftype ) ) return false;
135                        // tuple-parameter sizes are the same, but actual parameter sizes differ - must tuple specialize
136                        if ( fftype->parameters.size() != aftype->parameters.size() ) return true;
137                        // total parameter size can be the same, while individual parameters can have different structure
138                        for ( auto params : group_iterate( fftype->parameters, aftype->parameters ) ) {
139                                DeclarationWithType * formal = std::get<0>(params);
140                                DeclarationWithType * actual = std::get<1>(params);
141                                if ( ! matchingTupleStructure( formal->get_type(), actual->get_type() ) ) return true;
142                        }
143                }
144                return false;
145        }
146
147        bool needsSpecialization( Type *formalType, Type *actualType, TypeSubstitution *env ) {
148                return needsPolySpecialization( formalType, actualType, env ) || needsTupleSpecialization( formalType, actualType );
149        }
150
151        Expression * Specialize::doSpecialization( Type *formalType, Expression *actual, InferredParams *inferParams ) {
152                assertf( actual->result, "attempting to specialize an untyped expression" );
153                if ( needsSpecialization( formalType, actual->get_result(), env ) ) {
154                        if ( FunctionType *funType = getFunctionType( formalType ) ) {
155                                if ( ApplicationExpr * appExpr = dynamic_cast<ApplicationExpr*>( actual ) ) {
156                                        return createThunkFunction( funType, appExpr->get_function(), inferParams );
157                                } else if ( VariableExpr * varExpr = dynamic_cast<VariableExpr*>( actual ) ) {
158                                        return createThunkFunction( funType, varExpr, inferParams );
159                                } else {
160                                        // This likely won't work, as anything that could build an ApplicationExpr probably hit one of the previous two branches
161                                        return createThunkFunction( funType, actual, inferParams );
162                                }
163                        } else {
164                                return actual;
165                        } // if
166                } else {
167                        return actual;
168                } // if
169        }
170
171        /// restructures the arguments to match the structure of the formal parameters of the actual function.
172        /// [begin, end) are the exploded arguments.
173        template< typename Iterator, typename OutIterator >
174        void structureArg( Type * type, Iterator & begin, Iterator end, OutIterator out ) {
175                if ( TupleType * tuple = dynamic_cast< TupleType * >( type ) ) {
176                        std::list< Expression * > exprs;
177                        for ( Type * t : *tuple ) {
178                                structureArg( t, begin, end, back_inserter( exprs ) );
179                        }
180                        *out++ = new TupleExpr( exprs );
181                } else {
182                        assertf( begin != end, "reached the end of the arguments while structuring" );
183                        *out++ = *begin++;
184                }
185        }
186
187        /// explode assuming simple cases: either type is pure tuple (but not tuple expr) or type is non-tuple.
188        template< typename OutputIterator >
189        void explodeSimple( Expression * expr, OutputIterator out ) {
190                if ( TupleType * tupleType = dynamic_cast< TupleType * > ( expr->get_result() ) ) {
191                        // tuple type, recursively index into its components
192                        for ( unsigned int i = 0; i < tupleType->size(); i++ ) {
193                                explodeSimple( new TupleIndexExpr( expr->clone(), i ), out );
194                        }
195                        delete expr;
196                } else {
197                        // non-tuple type - output a clone of the expression
198                        *out++ = expr;
199                }
200        }
201
202        struct EnvTrimmer {
203                TypeSubstitution * env, * newEnv;
204                EnvTrimmer( TypeSubstitution * env, TypeSubstitution * newEnv ) : env( env ), newEnv( newEnv ){}
205                void previsit( TypeDecl * tyDecl ) {
206                        // transfer known bindings for seen type variables
207                        if ( Type * t = env->lookup( tyDecl->name ) ) {
208                                newEnv->add( tyDecl->name, t );
209                        }
210                }
211        };
212
213        /// reduce environment to just the parts that are referenced in a given expression
214        TypeSubstitution * trimEnv( ApplicationExpr * expr, TypeSubstitution * env ) {
215                if ( env ) {
216                        TypeSubstitution * newEnv = new TypeSubstitution();
217                        PassVisitor<EnvTrimmer> trimmer( env, newEnv );
218                        expr->accept( trimmer );
219                        return newEnv;
220                }
221                return nullptr;
222        }
223
224        /// Generates a thunk that calls `actual` with type `funType` and returns its address
225        Expression * Specialize::createThunkFunction( FunctionType *funType, Expression *actual, InferredParams *inferParams ) {
226                static UniqueName thunkNamer( "_thunk" );
227
228                FunctionType *newType = funType->clone();
229                if ( env ) {
230                        // it is important to replace only occurrences of type variables that occur free in the
231                        // thunk's type
232                        env->applyFree( newType );
233                } // if
234                // create new thunk with same signature as formal type (C linkage, empty body)
235                FunctionDecl *thunkFunc = new FunctionDecl( thunkNamer.newName(), Type::StorageClasses(), LinkageSpec::C, newType, new CompoundStmt() );
236                thunkFunc->fixUniqueId();
237
238                // thunks may be generated and not used - silence warning with attribute
239                thunkFunc->get_attributes().push_back( new Attribute( "unused" ) );
240
241                // thread thunk parameters into call to actual function, naming thunk parameters as we go
242                UniqueName paramNamer( paramPrefix );
243                ApplicationExpr *appExpr = new ApplicationExpr( actual );
244
245                FunctionType * actualType = getFunctionType( actual->get_result() )->clone();
246                if ( env ) {
247                        // need to apply the environment to the actual function's type, since it may itself be polymorphic
248                        env->apply( actualType );
249                }
250                std::unique_ptr< FunctionType > actualTypeManager( actualType ); // for RAII
251                std::list< DeclarationWithType * >::iterator actualBegin = actualType->get_parameters().begin();
252                std::list< DeclarationWithType * >::iterator actualEnd = actualType->get_parameters().end();
253
254                std::list< Expression * > args;
255                for ( DeclarationWithType* param : thunkFunc->get_functionType()->get_parameters() ) {
256                        // name each thunk parameter and explode it - these are then threaded back into the actual function call.
257                        param->set_name( paramNamer.newName() );
258                        explodeSimple( new VariableExpr( param ), back_inserter( args ) );
259                }
260
261                // walk parameters to the actual function alongside the exploded thunk parameters and restructure the arguments to match the actual parameters.
262                std::list< Expression * >::iterator argBegin = args.begin(), argEnd = args.end();
263                for ( ; actualBegin != actualEnd; ++actualBegin ) {
264                        structureArg( (*actualBegin)->get_type(), argBegin, argEnd, back_inserter( appExpr->get_args() ) );
265                }
266
267                appExpr->set_env( trimEnv( appExpr, env ) );
268                if ( inferParams ) {
269                        appExpr->get_inferParams() = *inferParams;
270                } // if
271
272                // handle any specializations that may still be present
273                std::string oldParamPrefix = paramPrefix;
274                paramPrefix += "p";
275                // save stmtsToAddBefore in oldStmts
276                std::list< Statement* > oldStmts;
277                oldStmts.splice( oldStmts.end(), stmtsToAddBefore );
278                appExpr->acceptMutator( *visitor );
279                paramPrefix = oldParamPrefix;
280                // write any statements added for recursive specializations into the thunk body
281                thunkFunc->statements->kids.splice( thunkFunc->statements->kids.end(), stmtsToAddBefore );
282                // restore oldStmts into stmtsToAddBefore
283                stmtsToAddBefore.splice( stmtsToAddBefore.end(), oldStmts );
284
285                // add return (or valueless expression) to the thunk
286                Statement *appStmt;
287                if ( funType->returnVals.empty() ) {
288                        appStmt = new ExprStmt( appExpr );
289                } else {
290                        appStmt = new ReturnStmt( appExpr );
291                } // if
292                thunkFunc->statements->kids.push_back( appStmt );
293
294                // add thunk definition to queue of statements to add
295                stmtsToAddBefore.push_back( new DeclStmt( thunkFunc ) );
296                // return address of thunk function as replacement expression
297                return new AddressExpr( new VariableExpr( thunkFunc ) );
298        }
299
300        void Specialize::handleExplicitParams( ApplicationExpr *appExpr ) {
301                // create thunks for the explicit parameters
302                assert( appExpr->function->result );
303                FunctionType *function = getFunctionType( appExpr->function->result );
304                assert( function );
305                std::list< DeclarationWithType* >::iterator formal;
306                std::list< Expression* >::iterator actual;
307                for ( formal = function->get_parameters().begin(), actual = appExpr->get_args().begin(); formal != function->get_parameters().end() && actual != appExpr->get_args().end(); ++formal, ++actual ) {
308                        *actual = doSpecialization( (*formal)->get_type(), *actual, &appExpr->get_inferParams() );
309                }
310        }
311
312        Expression * Specialize::postmutate( ApplicationExpr *appExpr ) {
313                if ( ! InitTweak::isIntrinsicCallExpr( appExpr ) ) {
314                        // create thunks for the inferred parameters
315                        // don't need to do this for intrinsic calls, because they aren't actually passed
316                        // need to handle explicit params before inferred params so that explicit params do not recieve a changed set of inferParams (and change them again)
317                        // alternatively, if order starts to matter then copy appExpr's inferParams and pass them to handleExplicitParams.
318                        handleExplicitParams( appExpr );
319                        for ( InferredParams::iterator inferParam = appExpr->get_inferParams().begin(); inferParam != appExpr->get_inferParams().end(); ++inferParam ) {
320                                inferParam->second.expr = doSpecialization( inferParam->second.formalType, inferParam->second.expr, inferParam->second.inferParams.get() );
321                        }
322                }
323                return appExpr;
324        }
325
326        Expression * Specialize::postmutate( CastExpr *castExpr ) {
327                if ( castExpr->result->isVoid() ) {
328                        // can't specialize if we don't have a return value
329                        return castExpr;
330                }
331                Expression *specialized = doSpecialization( castExpr->result, castExpr->arg, &castExpr->inferParams );
332                if ( specialized != castExpr->arg ) {
333                        // assume here that the specialization incorporates the cast
334                        return specialized;
335                } else {
336                        return castExpr;
337                }
338        }
339
340        void convertSpecializations( std::list< Declaration* >& translationUnit ) {
341                PassVisitor<Specialize> spec;
342                mutateAll( translationUnit, spec );
343        }
344} // namespace GenPoly
345
346// Local Variables: //
347// tab-width: 4 //
348// mode: c++ //
349// compile-command: "make install" //
350// End: //
Note: See TracBrowser for help on using the repository browser.