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