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 : Fri Dec 13 23:40:49 2019 |
---|
13 | // Update Count : 32 |
---|
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 "ResolvExpr/FindOpenVars.h" // for findOpenVars |
---|
30 | #include "ResolvExpr/TypeEnvironment.h" // for OpenVarSet, AssertionSet |
---|
31 | #include "Specialize.h" |
---|
32 | #include "SynTree/LinkageSpec.h" // for C |
---|
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 | |
---|
43 | namespace GenPoly { |
---|
44 | struct Specialize final : public WithConstTypeSubstitution, 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, const 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, const 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 | /// Generates a thunk that calls `actual` with type `funType` and returns its address |
---|
203 | Expression * Specialize::createThunkFunction( FunctionType *funType, Expression *actual, InferredParams *inferParams ) { |
---|
204 | static UniqueName thunkNamer( "_thunk" ); |
---|
205 | |
---|
206 | FunctionType *newType = funType->clone(); |
---|
207 | if ( env ) { |
---|
208 | // it is important to replace only occurrences of type variables that occur free in the |
---|
209 | // thunk's type |
---|
210 | env->applyFree( newType ); |
---|
211 | } // if |
---|
212 | // create new thunk with same signature as formal type (C linkage, empty body) |
---|
213 | FunctionDecl *thunkFunc = new FunctionDecl( thunkNamer.newName(), Type::StorageClasses(), LinkageSpec::C, newType, new CompoundStmt() ); |
---|
214 | thunkFunc->fixUniqueId(); |
---|
215 | |
---|
216 | // thunks may be generated and not used - silence warning with attribute |
---|
217 | thunkFunc->get_attributes().push_back( new Attribute( "unused" ) ); |
---|
218 | |
---|
219 | // thread thunk parameters into call to actual function, naming thunk parameters as we go |
---|
220 | UniqueName paramNamer( paramPrefix ); |
---|
221 | ApplicationExpr *appExpr = new ApplicationExpr( actual ); |
---|
222 | |
---|
223 | FunctionType * actualType = getFunctionType( actual->get_result() )->clone(); |
---|
224 | if ( env ) { |
---|
225 | // need to apply the environment to the actual function's type, since it may itself be polymorphic |
---|
226 | env->apply( actualType ); |
---|
227 | } |
---|
228 | std::unique_ptr< FunctionType > actualTypeManager( actualType ); // for RAII |
---|
229 | std::list< DeclarationWithType * >::iterator actualBegin = actualType->get_parameters().begin(); |
---|
230 | std::list< DeclarationWithType * >::iterator actualEnd = actualType->get_parameters().end(); |
---|
231 | |
---|
232 | std::list< Expression * > args; |
---|
233 | for ( DeclarationWithType* param : thunkFunc->get_functionType()->get_parameters() ) { |
---|
234 | // name each thunk parameter and explode it - these are then threaded back into the actual function call. |
---|
235 | param->set_name( paramNamer.newName() ); |
---|
236 | explodeSimple( new VariableExpr( param ), back_inserter( args ) ); |
---|
237 | } |
---|
238 | |
---|
239 | // walk parameters to the actual function alongside the exploded thunk parameters and restructure the arguments to match the actual parameters. |
---|
240 | std::list< Expression * >::iterator argBegin = args.begin(), argEnd = args.end(); |
---|
241 | for ( ; actualBegin != actualEnd; ++actualBegin ) { |
---|
242 | structureArg( (*actualBegin)->get_type(), argBegin, argEnd, back_inserter( appExpr->get_args() ) ); |
---|
243 | } |
---|
244 | |
---|
245 | appExpr->env = TypeSubstitution::newFromExpr( appExpr, env ); |
---|
246 | if ( inferParams ) { |
---|
247 | appExpr->inferParams = *inferParams; |
---|
248 | } // if |
---|
249 | |
---|
250 | // handle any specializations that may still be present |
---|
251 | std::string oldParamPrefix = paramPrefix; |
---|
252 | paramPrefix += "p"; |
---|
253 | // save stmtsToAddBefore in oldStmts |
---|
254 | std::list< Statement* > oldStmts; |
---|
255 | oldStmts.splice( oldStmts.end(), stmtsToAddBefore ); |
---|
256 | appExpr->acceptMutator( *visitor ); |
---|
257 | paramPrefix = oldParamPrefix; |
---|
258 | // write any statements added for recursive specializations into the thunk body |
---|
259 | thunkFunc->statements->kids.splice( thunkFunc->statements->kids.end(), stmtsToAddBefore ); |
---|
260 | // restore oldStmts into stmtsToAddBefore |
---|
261 | stmtsToAddBefore.splice( stmtsToAddBefore.end(), oldStmts ); |
---|
262 | |
---|
263 | // add return (or valueless expression) to the thunk |
---|
264 | Statement *appStmt; |
---|
265 | if ( funType->returnVals.empty() ) { |
---|
266 | appStmt = new ExprStmt( appExpr ); |
---|
267 | } else { |
---|
268 | appStmt = new ReturnStmt( appExpr ); |
---|
269 | } // if |
---|
270 | thunkFunc->statements->kids.push_back( appStmt ); |
---|
271 | |
---|
272 | // add thunk definition to queue of statements to add |
---|
273 | stmtsToAddBefore.push_back( new DeclStmt( thunkFunc ) ); |
---|
274 | // return address of thunk function as replacement expression |
---|
275 | return new AddressExpr( new VariableExpr( thunkFunc ) ); |
---|
276 | } |
---|
277 | |
---|
278 | void Specialize::handleExplicitParams( ApplicationExpr *appExpr ) { |
---|
279 | // create thunks for the explicit parameters |
---|
280 | assert( appExpr->function->result ); |
---|
281 | FunctionType *function = getFunctionType( appExpr->function->result ); |
---|
282 | assert( function ); |
---|
283 | std::list< DeclarationWithType* >::iterator formal; |
---|
284 | std::list< Expression* >::iterator actual; |
---|
285 | for ( formal = function->get_parameters().begin(), actual = appExpr->get_args().begin(); formal != function->get_parameters().end() && actual != appExpr->get_args().end(); ++formal, ++actual ) { |
---|
286 | *actual = doSpecialization( (*formal)->get_type(), *actual, &appExpr->inferParams ); |
---|
287 | } |
---|
288 | } |
---|
289 | |
---|
290 | Expression * Specialize::postmutate( ApplicationExpr *appExpr ) { |
---|
291 | if ( ! InitTweak::isIntrinsicCallExpr( appExpr ) ) { |
---|
292 | // create thunks for the inferred parameters |
---|
293 | // don't need to do this for intrinsic calls, because they aren't actually passed |
---|
294 | // need to handle explicit params before inferred params so that explicit params do not recieve a changed set of inferParams (and change them again) |
---|
295 | // alternatively, if order starts to matter then copy appExpr's inferParams and pass them to handleExplicitParams. |
---|
296 | handleExplicitParams( appExpr ); |
---|
297 | for ( InferredParams::iterator inferParam = appExpr->inferParams.begin(); inferParam != appExpr->inferParams.end(); ++inferParam ) { |
---|
298 | inferParam->second.expr = doSpecialization( inferParam->second.formalType, inferParam->second.expr, &inferParam->second.expr->inferParams ); |
---|
299 | } |
---|
300 | } |
---|
301 | return appExpr; |
---|
302 | } |
---|
303 | |
---|
304 | Expression * Specialize::postmutate( CastExpr *castExpr ) { |
---|
305 | if ( castExpr->result->isVoid() ) { |
---|
306 | // can't specialize if we don't have a return value |
---|
307 | return castExpr; |
---|
308 | } |
---|
309 | Expression *specialized = doSpecialization( castExpr->result, castExpr->arg, &castExpr->inferParams ); |
---|
310 | if ( specialized != castExpr->arg ) { |
---|
311 | // assume here that the specialization incorporates the cast |
---|
312 | return specialized; |
---|
313 | } else { |
---|
314 | return castExpr; |
---|
315 | } |
---|
316 | } |
---|
317 | |
---|
318 | void convertSpecializations( std::list< Declaration* >& translationUnit ) { |
---|
319 | PassVisitor<Specialize> spec; |
---|
320 | mutateAll( translationUnit, spec ); |
---|
321 | } |
---|
322 | } // namespace GenPoly |
---|
323 | |
---|
324 | // Local Variables: // |
---|
325 | // tab-width: 4 // |
---|
326 | // mode: c++ // |
---|
327 | // compile-command: "make install" // |
---|
328 | // End: // |
---|