source: src/GenPoly/SpecializeNew.cpp@ a01faa98

ast-experimental
Last change on this file since a01faa98 was bccd70a, checked in by Andrew Beach <ajbeach@…>, 2 years ago

Removed internal code from TypeSubstitution header. It caused a chain of include problems, which have been corrected.

  • Property mode set to 100644
File size: 16.1 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// SpecializeNew.cpp -- Generate thunks to specialize polymorphic functions.
8//
9// Author : Andrew Beach
10// Created On : Tue Jun 7 13:37:00 2022
11// Last Modified By : Andrew Beach
12// Last Modified On : Tue Jun 7 13:37:00 2022
13// Update Count : 0
14//
15
16#include "Specialize.h"
17
18#include "AST/Copy.hpp" // for deepCopy
19#include "AST/Inspect.hpp" // for isIntrinsicCallExpr
20#include "AST/Pass.hpp" // for Pass
21#include "AST/TypeEnvironment.hpp" // for OpenVarSet, AssertionSet
22#include "Common/UniqueName.h" // for UniqueName
23#include "GenPoly/GenPoly.h" // for getFunctionType
24#include "ResolvExpr/FindOpenVars.h" // for findOpenVars
25#include "ResolvExpr/TypeEnvironment.h" // for FirstOpen, FirstClosed
26
27namespace GenPoly {
28
29namespace {
30
31struct SpecializeCore final :
32 public ast::WithConstTypeSubstitution,
33 public ast::WithDeclsToAdd<>,
34 public ast::WithVisitorRef<SpecializeCore> {
35 std::string paramPrefix = "_p";
36
37 ast::ApplicationExpr * handleExplicitParams(
38 const ast::ApplicationExpr * expr );
39 const ast::Expr * createThunkFunction(
40 const CodeLocation & location,
41 const ast::FunctionType * funType,
42 const ast::Expr * actual,
43 const ast::InferredParams * inferParams );
44 const ast::Expr * doSpecialization(
45 const CodeLocation & location,
46 const ast::Type * formalType,
47 const ast::Expr * actual,
48 const ast::InferredParams * inferParams );
49
50 const ast::Expr * postvisit( const ast::ApplicationExpr * expr );
51 const ast::Expr * postvisit( const ast::CastExpr * expr );
52};
53
54const ast::InferredParams * getInferredParams( const ast::Expr * expr ) {
55 const ast::Expr::InferUnion & inferred = expr->inferred;
56 if ( inferred.hasParams() ) {
57 return &inferred.inferParams();
58 } else {
59 return nullptr;
60 }
61}
62
63// Check if both types have the same structure. The leaf (non-tuple) types
64// don't have to match but the tuples must match.
65bool isTupleStructureMatching( const ast::Type * t0, const ast::Type * t1 ) {
66 const ast::TupleType * tt0 = dynamic_cast<const ast::TupleType *>( t0 );
67 const ast::TupleType * tt1 = dynamic_cast<const ast::TupleType *>( t1 );
68 if ( tt0 && tt1 ) {
69 if ( tt0->size() != tt1->size() ) {
70 return false;
71 }
72 for ( auto types : group_iterate( tt0->types, tt1->types ) ) {
73 if ( !isTupleStructureMatching(
74 std::get<0>( types ), std::get<1>( types ) ) ) {
75 return false;
76 }
77 }
78 return true;
79 }
80 return (!tt0 && !tt1);
81}
82
83// The number of elements in a type if it is a flattened tuple.
84size_t flatTupleSize( const ast::Type * type ) {
85 if ( auto tuple = dynamic_cast<const ast::TupleType *>( type ) ) {
86 size_t sum = 0;
87 for ( auto t : *tuple ) {
88 sum += flatTupleSize( t );
89 }
90 return sum;
91 } else {
92 return 1;
93 }
94}
95
96// Find the total number of components in a parameter list.
97size_t functionParameterSize( const ast::FunctionType * type ) {
98 size_t sum = 0;
99 for ( auto param : type->params ) {
100 sum += flatTupleSize( param );
101 }
102 return sum;
103}
104
105bool needsPolySpecialization(
106 const ast::Type * formalType,
107 const ast::Type * actualType,
108 const ast::TypeSubstitution * subs ) {
109 if ( !subs ) {
110 return false;
111 }
112
113 using namespace ResolvExpr;
114 ast::OpenVarSet openVars, closedVars;
115 ast::AssertionSet need, have;
116 findOpenVars( formalType, openVars, closedVars, need, have, FirstClosed );
117 findOpenVars( actualType, openVars, closedVars, need, have, FirstOpen );
118 for ( const ast::OpenVarSet::value_type & openVar : openVars ) {
119 const ast::Type * boundType = subs->lookup( openVar.first );
120 // If the variable is not bound, move onto the next variable.
121 if ( !boundType ) continue;
122
123 // Is the variable cound to another type variable?
124 if ( auto inst = dynamic_cast<const ast::TypeInstType *>( boundType ) ) {
125 if ( closedVars.find( *inst ) == closedVars.end() ) {
126 return true;
127 }
128 // Otherwise, the variable is bound to a concrete type.
129 } else {
130 return true;
131 }
132 }
133 // None of the type variables are bound.
134 return false;
135}
136
137bool needsTupleSpecialization(
138 const ast::Type * formalType, const ast::Type * actualType ) {
139 // Needs tuple specialization if the structure of the formal type and
140 // actual type do not match.
141
142 // This is the case if the formal type has ttype polymorphism, or if the structure of tuple types
143 // between the function do not match exactly.
144 if ( const ast::FunctionType * ftype = getFunctionType( formalType ) ) {
145 // A pack in the parameter or return type requires specialization.
146 if ( ftype->isTtype() ) {
147 return true;
148 }
149 // Conversion of 0 to a function type does not require specialization.
150 if ( dynamic_cast<const ast::ZeroType *>( actualType ) ) {
151 return false;
152 }
153 const ast::FunctionType * atype =
154 getFunctionType( actualType->stripReferences() );
155 assertf( atype,
156 "formal type is a function type, but actual type is not: %s",
157 toString( actualType ).c_str() );
158 // Can't tuple specialize if parameter sizes deeply-differ.
159 if ( functionParameterSize( ftype ) != functionParameterSize( atype ) ) {
160 return false;
161 }
162 // If tuple parameter size matches but actual parameter sizes differ
163 // then there needs to be specialization.
164 if ( ftype->params.size() != atype->params.size() ) {
165 return true;
166 }
167 // Total parameter size can be the same, while individual parameters
168 // can have different structure.
169 for ( auto pairs : group_iterate( ftype->params, atype->params ) ) {
170 if ( !isTupleStructureMatching(
171 std::get<0>( pairs ), std::get<1>( pairs ) ) ) {
172 return true;
173 }
174 }
175 }
176 return false;
177}
178
179bool needsSpecialization(
180 const ast::Type * formalType, const ast::Type * actualType,
181 const ast::TypeSubstitution * subs ) {
182 return needsPolySpecialization( formalType, actualType, subs )
183 || needsTupleSpecialization( formalType, actualType );
184}
185
186ast::ApplicationExpr * SpecializeCore::handleExplicitParams(
187 const ast::ApplicationExpr * expr ) {
188 assert( expr->func->result );
189 const ast::FunctionType * func = getFunctionType( expr->func->result );
190 assert( func );
191
192 ast::ApplicationExpr * mut = ast::mutate( expr );
193
194 std::vector<ast::ptr<ast::Type>>::const_iterator formal;
195 std::vector<ast::ptr<ast::Expr>>::iterator actual;
196 for ( formal = func->params.begin(), actual = mut->args.begin() ;
197 formal != func->params.end() && actual != mut->args.end() ;
198 ++formal, ++actual ) {
199 *actual = doSpecialization( (*actual)->location,
200 *formal, *actual, getInferredParams( expr ) );
201 }
202 return mut;
203}
204
205// Explode assuming simple cases: either type is pure tuple (but not tuple
206// expr) or type is non-tuple.
207template<typename OutputIterator>
208void explodeSimple( const CodeLocation & location,
209 const ast::Expr * expr, OutputIterator out ) {
210 // Recurse on tuple types using index expressions on each component.
211 if ( auto tuple = expr->result.as<ast::TupleType>() ) {
212 ast::ptr<ast::Expr> cleanup = expr;
213 for ( unsigned int i = 0 ; i < tuple->size() ; ++i ) {
214 explodeSimple( location,
215 new ast::TupleIndexExpr( location, expr, i ), out );
216 }
217 // For a non-tuple type, output a clone of the expression.
218 } else {
219 *out++ = expr;
220 }
221}
222
223// Restructures arguments to match the structure of the formal parameters
224// of the actual function. Returns the next structured argument.
225template<typename Iterator>
226const ast::Expr * structureArg(
227 const CodeLocation& location, const ast::ptr<ast::Type> & type,
228 Iterator & begin, const Iterator & end ) {
229 if ( auto tuple = type.as<ast::TupleType>() ) {
230 std::vector<ast::ptr<ast::Expr>> exprs;
231 for ( const ast::ptr<ast::Type> & t : *tuple ) {
232 exprs.push_back( structureArg( location, t, begin, end ) );
233 }
234 return new ast::TupleExpr( location, std::move( exprs ) );
235 } else {
236 assertf( begin != end, "reached the end of the arguments while structuring" );
237 return *begin++;
238 }
239}
240
241struct TypeInstFixer final : public ast::WithShortCircuiting {
242 std::map<const ast::TypeDecl *, std::pair<int, int>> typeMap;
243
244 void previsit(const ast::TypeDecl *) { visit_children = false; }
245 const ast::TypeInstType * postvisit(const ast::TypeInstType * typeInst) {
246 if (typeMap.count(typeInst->base)) {
247 ast::TypeInstType * newInst = mutate(typeInst);
248 auto const & pair = typeMap[typeInst->base];
249 newInst->expr_id = pair.first;
250 newInst->formal_usage = pair.second;
251 return newInst;
252 }
253 return typeInst;
254 }
255};
256
257const ast::Expr * SpecializeCore::createThunkFunction(
258 const CodeLocation & location,
259 const ast::FunctionType * funType,
260 const ast::Expr * actual,
261 const ast::InferredParams * inferParams ) {
262 // One set of unique names per program.
263 static UniqueName thunkNamer("_thunk");
264
265 const ast::FunctionType * newType = ast::deepCopy( funType );
266 if ( typeSubs ) {
267 // Must replace only occurrences of type variables
268 // that occure free in the thunk's type.
269 auto result = typeSubs->applyFree( newType );
270 newType = result.node.release();
271 }
272
273 using DWTVector = std::vector<ast::ptr<ast::DeclWithType>>;
274 using DeclVector = std::vector<ast::ptr<ast::TypeDecl>>;
275
276 UniqueName paramNamer( paramPrefix );
277
278 // Create new thunk with same signature as formal type.
279 ast::Pass<TypeInstFixer> fixer;
280 for (const auto & kv : newType->forall) {
281 if (fixer.core.typeMap.count(kv->base)) {
282 std::cerr << location << ' ' << kv->base->name
283 << ' ' << kv->expr_id << '_' << kv->formal_usage
284 << ',' << fixer.core.typeMap[kv->base].first
285 << '_' << fixer.core.typeMap[kv->base].second << std::endl;
286 assertf(false, "multiple formals in specialize");
287 }
288 else {
289 fixer.core.typeMap[kv->base] = std::make_pair(kv->expr_id, kv->formal_usage);
290 }
291 }
292
293 ast::CompoundStmt * thunkBody = new ast::CompoundStmt( location );
294 ast::FunctionDecl * thunkFunc = new ast::FunctionDecl(
295 location,
296 thunkNamer.newName(),
297 map_range<DeclVector>( newType->forall, []( const ast::TypeInstType * inst ) {
298 return ast::deepCopy( inst->base );
299 } ),
300 map_range<DWTVector>( newType->assertions, []( const ast::VariableExpr * expr ) {
301 return ast::deepCopy( expr->var );
302 } ),
303 map_range<DWTVector>( newType->params, [&location, &paramNamer]( const ast::Type * type ) {
304 return new ast::ObjectDecl( location, paramNamer.newName(), ast::deepCopy( type ) );
305 } ),
306 map_range<DWTVector>( newType->returns, [&location, &paramNamer]( const ast::Type * type ) {
307 return new ast::ObjectDecl( location, paramNamer.newName(), ast::deepCopy( type ) );
308 } ),
309 thunkBody,
310 ast::Storage::Classes(),
311 ast::Linkage::C
312 );
313
314 thunkFunc->fixUniqueId();
315
316 // Thunks may be generated and not used, avoid them.
317 thunkFunc->attributes.push_back( new ast::Attribute( "unused" ) );
318
319 // Global thunks must be static to avoid collitions.
320 // Nested thunks must not be unique and hence, not static.
321 thunkFunc->storage.is_static = !isInFunction();
322
323 // Weave thunk parameters into call to actual function,
324 // naming thunk parameters as we go.
325 ast::ApplicationExpr * app = new ast::ApplicationExpr( location, actual );
326
327 const ast::FunctionType * actualType = ast::deepCopy( getFunctionType( actual->result ) );
328 if ( typeSubs ) {
329 // Need to apply the environment to the actual function's type,
330 // since it may itself be polymorphic.
331 auto result = typeSubs->apply( actualType );
332 actualType = result.node.release();
333 }
334
335 ast::ptr<ast::FunctionType> actualTypeManager = actualType;
336
337 std::vector<ast::ptr<ast::Expr>> args;
338 for ( ast::ptr<ast::DeclWithType> & param : thunkFunc->params ) {
339 // Name each thunk parameter and explode it.
340 // These are then threaded back into the actual function call.
341 ast::DeclWithType * mutParam = ast::mutate( param.get() );
342 explodeSimple( location, new ast::VariableExpr( location, mutParam ),
343 std::back_inserter( args ) );
344 }
345
346 // Walk parameters to the actual function alongside the exploded thunk
347 // parameters and restructure the arguments to match the actual parameters.
348 std::vector<ast::ptr<ast::Expr>>::iterator
349 argBegin = args.begin(), argEnd = args.end();
350 for ( const auto & actualArg : actualType->params ) {
351 app->args.push_back(
352 structureArg( location, actualArg.get(), argBegin, argEnd ) );
353 }
354 assertf( argBegin == argEnd, "Did not structure all arguments." );
355
356 app->accept(fixer); // this should modify in place
357
358 app->env = ast::TypeSubstitution::newFromExpr( app, typeSubs );
359 if ( inferParams ) {
360 app->inferred.inferParams() = *inferParams;
361 }
362
363 // Handle any specializations that may still be present.
364 {
365 std::string oldParamPrefix = paramPrefix;
366 paramPrefix += "p";
367 std::list<ast::ptr<ast::Decl>> oldDecls;
368 oldDecls.splice( oldDecls.end(), declsToAddBefore );
369
370 app->accept( *visitor );
371 // Write recursive specializations into the thunk body.
372 for ( const ast::ptr<ast::Decl> & decl : declsToAddBefore ) {
373 thunkBody->push_back( new ast::DeclStmt( decl->location, decl ) );
374 }
375
376 declsToAddBefore = std::move( oldDecls );
377 paramPrefix = std::move( oldParamPrefix );
378 }
379
380 // Add return (or valueless expression) to the thunk.
381 ast::Stmt * appStmt;
382 if ( funType->returns.empty() ) {
383 appStmt = new ast::ExprStmt( app->location, app );
384 } else {
385 appStmt = new ast::ReturnStmt( app->location, app );
386 }
387 thunkBody->push_back( appStmt );
388
389 // Add the thunk definition:
390 declsToAddBefore.push_back( thunkFunc );
391
392 // Return address of thunk function as replacement expression.
393 return new ast::AddressExpr( location,
394 new ast::VariableExpr( location, thunkFunc ) );
395}
396
397const ast::Expr * SpecializeCore::doSpecialization(
398 const CodeLocation & location,
399 const ast::Type * formalType,
400 const ast::Expr * actual,
401 const ast::InferredParams * inferParams ) {
402 assertf( actual->result, "attempting to specialize an untyped expression" );
403 if ( needsSpecialization( formalType, actual->result, typeSubs ) ) {
404 if ( const ast::FunctionType * type = getFunctionType( formalType ) ) {
405 if ( const ast::ApplicationExpr * expr =
406 dynamic_cast<const ast::ApplicationExpr *>( actual ) ) {
407 return createThunkFunction( location, type, expr->func, inferParams );
408 } else if ( auto expr =
409 dynamic_cast<const ast::VariableExpr *>( actual ) ) {
410 return createThunkFunction( location, type, expr, inferParams );
411 } else {
412 // (I don't even know what that comment means.)
413 // This likely won't work, as anything that could build an ApplicationExpr probably hit one of the previous two branches
414 return createThunkFunction( location, type, actual, inferParams );
415 }
416 } else {
417 return actual;
418 }
419 } else {
420 return actual;
421 }
422}
423
424const ast::Expr * SpecializeCore::postvisit(
425 const ast::ApplicationExpr * expr ) {
426 if ( ast::isIntrinsicCallExpr( expr ) ) {
427 return expr;
428 }
429
430 // Create thunks for the inferred parameters.
431 // This is not needed for intrinsic calls, because they aren't
432 // actually passed to the function. It needs to handle explicit params
433 // before inferred params so that explicit params do not recieve a
434 // changed set of inferParams (and change them again).
435 // Alternatively, if order starts to matter then copy expr's inferParams
436 // and pass them to handleExplicitParams.
437 ast::ApplicationExpr * mut = handleExplicitParams( expr );
438 if ( !mut->inferred.hasParams() ) {
439 return mut;
440 }
441 ast::InferredParams & inferParams = mut->inferred.inferParams();
442 for ( ast::InferredParams::value_type & inferParam : inferParams ) {
443 inferParam.second.expr = doSpecialization(
444 inferParam.second.expr->location,
445 inferParam.second.formalType,
446 inferParam.second.expr,
447 getInferredParams( inferParam.second.expr )
448 );
449 }
450 return mut;
451}
452
453const ast::Expr * SpecializeCore::postvisit( const ast::CastExpr * expr ) {
454 if ( expr->result->isVoid() ) {
455 // No specialization if there is no return value.
456 return expr;
457 }
458 const ast::Expr * specialized = doSpecialization(
459 expr->location, expr->result, expr->arg, getInferredParams( expr ) );
460 if ( specialized != expr->arg ) {
461 // Assume that the specialization incorporates the cast.
462 return specialized;
463 } else {
464 return expr;
465 }
466}
467
468} // namespace
469
470void convertSpecializations( ast::TranslationUnit & translationUnit ) {
471 ast::Pass<SpecializeCore>::run( translationUnit );
472}
473
474} // namespace GenPoly
475
476// Local Variables: //
477// tab-width: 4 //
478// mode: c++ //
479// compile-command: "make install" //
480// End: //
Note: See TracBrowser for help on using the repository browser.