source: src/GenPoly/Specialize.cc @ 322b97e

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 322b97e was ae4038d, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Fix tuple specialize check to more precisely determine where tuple specialization is necessary [fixes #35]

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