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