[51587aa] | 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 | // |
---|
[f1e012b] | 7 | // Specialize.cc -- |
---|
[51587aa] | 8 | // |
---|
| 9 | // Author : Richard C. Bilson |
---|
| 10 | // Created On : Mon May 18 07:44:20 2015 |
---|
[d5baf0c] | 11 | // Last Modified By : Andrew Beach |
---|
| 12 | // Last Modified On : Thr Jul 2 17:42:00 2020 |
---|
| 13 | // Update Count : 33 |
---|
[51587aa] | 14 | // |
---|
[51b7345] | 15 | |
---|
[08fc48f] | 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 |
---|
[51b7345] | 23 | |
---|
[cf90b88] | 24 | #include "Common/PassVisitor.h" |
---|
[08fc48f] | 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 |
---|
[51b7345] | 31 | #include "Specialize.h" |
---|
[07de76b] | 32 | #include "SynTree/LinkageSpec.h" // for C |
---|
[08fc48f] | 33 | #include "SynTree/Attribute.h" // for Attribute |
---|
| 34 | #include "SynTree/Declaration.h" // for FunctionDecl, DeclarationWit... |
---|
| 35 | #include "SynTree/Expression.h" // for ApplicationExpr, Expression |
---|
[ba3706f] | 36 | #include "SynTree/Label.h" // for Label |
---|
[08fc48f] | 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 |
---|
[51b7345] | 42 | |
---|
| 43 | namespace GenPoly { |
---|
[d5baf0c] | 44 | struct Specialize final : public WithConstTypeSubstitution, |
---|
| 45 | public WithDeclsToAdd, public WithVisitorRef<Specialize> { |
---|
[cf90b88] | 46 | Expression * postmutate( ApplicationExpr *applicationExpr ); |
---|
| 47 | Expression * postmutate( CastExpr *castExpr ); |
---|
[01aeade] | 48 | |
---|
| 49 | void handleExplicitParams( ApplicationExpr *appExpr ); |
---|
[f3b0a07] | 50 | Expression * createThunkFunction( FunctionType *funType, Expression *actual, InferredParams *inferParams ); |
---|
[bb666f64] | 51 | Expression * doSpecialization( Type *formalType, Expression *actual, InferredParams *inferParams ); |
---|
[626dbc10] | 52 | |
---|
| 53 | std::string paramPrefix = "_p"; |
---|
| 54 | }; |
---|
[01aeade] | 55 | |
---|
[698664b3] | 56 | /// Looks up open variables in actual type, returning true if any of them are bound in the environment or formal type. |
---|
[02fdb8e] | 57 | bool needsPolySpecialization( Type *formalType, Type *actualType, const TypeSubstitution *env ) { |
---|
[01aeade] | 58 | if ( env ) { |
---|
| 59 | using namespace ResolvExpr; |
---|
| 60 | OpenVarSet openVars, closedVars; |
---|
| 61 | AssertionSet need, have; |
---|
| 62 | findOpenVars( formalType, openVars, closedVars, need, have, false ); |
---|
| 63 | findOpenVars( actualType, openVars, closedVars, need, have, true ); |
---|
| 64 | for ( OpenVarSet::const_iterator openVar = openVars.begin(); openVar != openVars.end(); ++openVar ) { |
---|
| 65 | Type *boundType = env->lookup( openVar->first ); |
---|
| 66 | if ( ! boundType ) continue; |
---|
| 67 | if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( boundType ) ) { |
---|
[b226721] | 68 | // bound to another type variable |
---|
[01aeade] | 69 | if ( closedVars.find( typeInst->get_name() ) == closedVars.end() ) { |
---|
[b226721] | 70 | // bound to a closed variable => must specialize |
---|
[01aeade] | 71 | return true; |
---|
| 72 | } // if |
---|
| 73 | } else { |
---|
[b226721] | 74 | // variable is bound to a concrete type => must specialize |
---|
[01aeade] | 75 | return true; |
---|
| 76 | } // if |
---|
| 77 | } // for |
---|
[b226721] | 78 | // none of the type variables are bound |
---|
[01aeade] | 79 | return false; |
---|
| 80 | } else { |
---|
[b226721] | 81 | // no env |
---|
[01aeade] | 82 | return false; |
---|
| 83 | } // if |
---|
| 84 | } |
---|
| 85 | |
---|
[dc0557d] | 86 | /// True if both types have the same structure, but not necessarily the same types. |
---|
| 87 | /// That is, either both types are tuple types with the same size (recursively), or |
---|
| 88 | /// both are not tuple types. |
---|
| 89 | bool matchingTupleStructure( Type * t1, Type * t2 ) { |
---|
| 90 | TupleType * tuple1 = dynamic_cast< TupleType * >( t1 ); |
---|
| 91 | TupleType * tuple2 = dynamic_cast< TupleType * >( t2 ); |
---|
| 92 | if ( tuple1 && tuple2 ) { |
---|
| 93 | if ( tuple1->size() != tuple2->size() ) return false; |
---|
| 94 | for ( auto types : group_iterate( tuple1->get_types(), tuple2->get_types() ) ) { |
---|
| 95 | if ( ! matchingTupleStructure( std::get<0>( types ), std::get<1>( types ) ) ) return false; |
---|
| 96 | } |
---|
| 97 | return true; |
---|
| 98 | } else if ( ! tuple1 && ! tuple2 ) return true; |
---|
| 99 | return false; |
---|
| 100 | } |
---|
| 101 | |
---|
[ae4038d] | 102 | // walk into tuple type and find the number of components |
---|
| 103 | size_t singleParameterSize( Type * type ) { |
---|
| 104 | if ( TupleType * tt = dynamic_cast< TupleType * >( type ) ) { |
---|
| 105 | size_t sz = 0; |
---|
| 106 | for ( Type * t : *tt ) { |
---|
| 107 | sz += singleParameterSize( t ); |
---|
| 108 | } |
---|
| 109 | return sz; |
---|
| 110 | } else { |
---|
| 111 | return 1; |
---|
| 112 | } |
---|
| 113 | } |
---|
| 114 | |
---|
| 115 | // find the total number of components in a parameter list |
---|
| 116 | size_t functionParameterSize( FunctionType * ftype ) { |
---|
| 117 | size_t sz = 0; |
---|
| 118 | for ( DeclarationWithType * p : ftype->get_parameters() ) { |
---|
| 119 | sz += singleParameterSize( p->get_type() ); |
---|
| 120 | } |
---|
| 121 | return sz; |
---|
| 122 | } |
---|
| 123 | |
---|
[d7dc824] | 124 | bool needsTupleSpecialization( Type *formalType, Type *actualType ) { |
---|
[dc0557d] | 125 | // Needs tuple specialization if the structure of the formal type and actual type do not match. |
---|
| 126 | // This is the case if the formal type has ttype polymorphism, or if the structure of tuple types |
---|
| 127 | // between the function do not match exactly. |
---|
| 128 | if ( FunctionType * fftype = getFunctionType( formalType ) ) { |
---|
| 129 | if ( fftype->isTtype() ) return true; |
---|
[969ee0df] | 130 | // conversion of 0 (null) to function type does not require tuple specialization |
---|
| 131 | if ( dynamic_cast< ZeroType * >( actualType ) ) return false; |
---|
[1744e6d] | 132 | FunctionType * aftype = getFunctionType( actualType->stripReferences() ); |
---|
| 133 | assertf( aftype, "formal type is a function type, but actual type is not: %s", toString( actualType ).c_str() ); |
---|
[ae4038d] | 134 | // Can't tuple specialize if parameter sizes deeply-differ. |
---|
| 135 | if ( functionParameterSize( fftype ) != functionParameterSize( aftype ) ) return false; |
---|
| 136 | // tuple-parameter sizes are the same, but actual parameter sizes differ - must tuple specialize |
---|
[bb666f64] | 137 | if ( fftype->parameters.size() != aftype->parameters.size() ) return true; |
---|
[ae4038d] | 138 | // total parameter size can be the same, while individual parameters can have different structure |
---|
[bb666f64] | 139 | for ( auto params : group_iterate( fftype->parameters, aftype->parameters ) ) { |
---|
[dc0557d] | 140 | DeclarationWithType * formal = std::get<0>(params); |
---|
| 141 | DeclarationWithType * actual = std::get<1>(params); |
---|
| 142 | if ( ! matchingTupleStructure( formal->get_type(), actual->get_type() ) ) return true; |
---|
| 143 | } |
---|
[f3b0a07] | 144 | } |
---|
| 145 | return false; |
---|
| 146 | } |
---|
[698664b3] | 147 | |
---|
[02fdb8e] | 148 | bool needsSpecialization( Type *formalType, Type *actualType, const TypeSubstitution *env ) { |
---|
[d7dc824] | 149 | return needsPolySpecialization( formalType, actualType, env ) || needsTupleSpecialization( formalType, actualType ); |
---|
[698664b3] | 150 | } |
---|
[f1e012b] | 151 | |
---|
[f3b0a07] | 152 | Expression * Specialize::doSpecialization( Type *formalType, Expression *actual, InferredParams *inferParams ) { |
---|
[d29fa5f] | 153 | assertf( actual->result, "attempting to specialize an untyped expression" ); |
---|
[906e24d] | 154 | if ( needsSpecialization( formalType, actual->get_result(), env ) ) { |
---|
[6c3a988f] | 155 | if ( FunctionType *funType = getFunctionType( formalType ) ) { |
---|
[bb666f64] | 156 | if ( ApplicationExpr * appExpr = dynamic_cast<ApplicationExpr*>( actual ) ) { |
---|
[698664b3] | 157 | return createThunkFunction( funType, appExpr->get_function(), inferParams ); |
---|
[bb666f64] | 158 | } else if ( VariableExpr * varExpr = dynamic_cast<VariableExpr*>( actual ) ) { |
---|
[698664b3] | 159 | return createThunkFunction( funType, varExpr, inferParams ); |
---|
[01aeade] | 160 | } else { |
---|
[698664b3] | 161 | // This likely won't work, as anything that could build an ApplicationExpr probably hit one of the previous two branches |
---|
| 162 | return createThunkFunction( funType, actual, inferParams ); |
---|
| 163 | } |
---|
[01aeade] | 164 | } else { |
---|
| 165 | return actual; |
---|
| 166 | } // if |
---|
| 167 | } else { |
---|
| 168 | return actual; |
---|
| 169 | } // if |
---|
| 170 | } |
---|
| 171 | |
---|
[dc0557d] | 172 | /// restructures the arguments to match the structure of the formal parameters of the actual function. |
---|
| 173 | /// [begin, end) are the exploded arguments. |
---|
| 174 | template< typename Iterator, typename OutIterator > |
---|
| 175 | void structureArg( Type * type, Iterator & begin, Iterator end, OutIterator out ) { |
---|
| 176 | if ( TupleType * tuple = dynamic_cast< TupleType * >( type ) ) { |
---|
[64eae56] | 177 | std::list< Expression * > exprs; |
---|
[dc0557d] | 178 | for ( Type * t : *tuple ) { |
---|
| 179 | structureArg( t, begin, end, back_inserter( exprs ) ); |
---|
[64eae56] | 180 | } |
---|
| 181 | *out++ = new TupleExpr( exprs ); |
---|
| 182 | } else { |
---|
[dc0557d] | 183 | assertf( begin != end, "reached the end of the arguments while structuring" ); |
---|
| 184 | *out++ = *begin++; |
---|
[64eae56] | 185 | } |
---|
| 186 | } |
---|
| 187 | |
---|
[dc0557d] | 188 | /// explode assuming simple cases: either type is pure tuple (but not tuple expr) or type is non-tuple. |
---|
| 189 | template< typename OutputIterator > |
---|
| 190 | void explodeSimple( Expression * expr, OutputIterator out ) { |
---|
| 191 | if ( TupleType * tupleType = dynamic_cast< TupleType * > ( expr->get_result() ) ) { |
---|
| 192 | // tuple type, recursively index into its components |
---|
| 193 | for ( unsigned int i = 0; i < tupleType->size(); i++ ) { |
---|
| 194 | explodeSimple( new TupleIndexExpr( expr->clone(), i ), out ); |
---|
[f3b0a07] | 195 | } |
---|
[dc0557d] | 196 | delete expr; |
---|
| 197 | } else { |
---|
| 198 | // non-tuple type - output a clone of the expression |
---|
| 199 | *out++ = expr; |
---|
[626dbc10] | 200 | } |
---|
| 201 | } |
---|
| 202 | |
---|
[f3b0a07] | 203 | /// Generates a thunk that calls `actual` with type `funType` and returns its address |
---|
| 204 | Expression * Specialize::createThunkFunction( FunctionType *funType, Expression *actual, InferredParams *inferParams ) { |
---|
| 205 | static UniqueName thunkNamer( "_thunk" ); |
---|
[626dbc10] | 206 | |
---|
| 207 | FunctionType *newType = funType->clone(); |
---|
| 208 | if ( env ) { |
---|
| 209 | // it is important to replace only occurrences of type variables that occur free in the |
---|
| 210 | // thunk's type |
---|
[6c3a988f] | 211 | env->applyFree( newType ); |
---|
[626dbc10] | 212 | } // if |
---|
| 213 | // create new thunk with same signature as formal type (C linkage, empty body) |
---|
[ba3706f] | 214 | FunctionDecl *thunkFunc = new FunctionDecl( thunkNamer.newName(), Type::StorageClasses(), LinkageSpec::C, newType, new CompoundStmt() ); |
---|
[626dbc10] | 215 | thunkFunc->fixUniqueId(); |
---|
| 216 | |
---|
| 217 | // thunks may be generated and not used - silence warning with attribute |
---|
| 218 | thunkFunc->get_attributes().push_back( new Attribute( "unused" ) ); |
---|
| 219 | |
---|
[3100754] | 220 | // Thunks at the global level must be static to avoid collisions between files. |
---|
| 221 | // (Conversly thunks inside a function must be unique and not static.) |
---|
| 222 | thunkFunc->storageClasses.is_static = !isInFunction(); |
---|
| 223 | |
---|
[626dbc10] | 224 | // thread thunk parameters into call to actual function, naming thunk parameters as we go |
---|
| 225 | UniqueName paramNamer( paramPrefix ); |
---|
| 226 | ApplicationExpr *appExpr = new ApplicationExpr( actual ); |
---|
| 227 | |
---|
[6c3a988f] | 228 | FunctionType * actualType = getFunctionType( actual->get_result() )->clone(); |
---|
| 229 | if ( env ) { |
---|
| 230 | // need to apply the environment to the actual function's type, since it may itself be polymorphic |
---|
| 231 | env->apply( actualType ); |
---|
| 232 | } |
---|
| 233 | std::unique_ptr< FunctionType > actualTypeManager( actualType ); // for RAII |
---|
[4c8621ac] | 234 | std::list< DeclarationWithType * >::iterator actualBegin = actualType->get_parameters().begin(); |
---|
| 235 | std::list< DeclarationWithType * >::iterator actualEnd = actualType->get_parameters().end(); |
---|
[626dbc10] | 236 | |
---|
[dc0557d] | 237 | std::list< Expression * > args; |
---|
[626dbc10] | 238 | for ( DeclarationWithType* param : thunkFunc->get_functionType()->get_parameters() ) { |
---|
[dc0557d] | 239 | // name each thunk parameter and explode it - these are then threaded back into the actual function call. |
---|
[626dbc10] | 240 | param->set_name( paramNamer.newName() ); |
---|
[dc0557d] | 241 | explodeSimple( new VariableExpr( param ), back_inserter( args ) ); |
---|
| 242 | } |
---|
| 243 | |
---|
| 244 | // walk parameters to the actual function alongside the exploded thunk parameters and restructure the arguments to match the actual parameters. |
---|
| 245 | std::list< Expression * >::iterator argBegin = args.begin(), argEnd = args.end(); |
---|
| 246 | for ( ; actualBegin != actualEnd; ++actualBegin ) { |
---|
| 247 | structureArg( (*actualBegin)->get_type(), argBegin, argEnd, back_inserter( appExpr->get_args() ) ); |
---|
| 248 | } |
---|
[a8b87d3] | 249 | assertf( argBegin == argEnd, "Did not structure all arguments." ); |
---|
[4c8621ac] | 250 | |
---|
[2ec65ad] | 251 | appExpr->env = TypeSubstitution::newFromExpr( appExpr, env ); |
---|
[626dbc10] | 252 | if ( inferParams ) { |
---|
[0b00df0] | 253 | appExpr->inferParams = *inferParams; |
---|
[626dbc10] | 254 | } // if |
---|
| 255 | |
---|
[d5baf0c] | 256 | // Handle any specializations that may still be present. |
---|
| 257 | { |
---|
| 258 | std::string oldParamPrefix = paramPrefix; |
---|
| 259 | paramPrefix += "p"; |
---|
| 260 | std::list< Declaration * > oldDecls; |
---|
| 261 | oldDecls.splice( oldDecls.end(), declsToAddBefore ); |
---|
| 262 | |
---|
| 263 | appExpr->acceptMutator( *visitor ); |
---|
| 264 | // Write recursive specializations into the thunk body. |
---|
| 265 | for ( Declaration * decl : declsToAddBefore ) { |
---|
| 266 | thunkFunc->statements->kids.push_back( new DeclStmt( decl ) ); |
---|
| 267 | } |
---|
| 268 | |
---|
| 269 | declsToAddBefore = std::move( oldDecls ); |
---|
| 270 | paramPrefix = oldParamPrefix; |
---|
| 271 | } |
---|
[626dbc10] | 272 | |
---|
| 273 | // add return (or valueless expression) to the thunk |
---|
| 274 | Statement *appStmt; |
---|
[cf90b88] | 275 | if ( funType->returnVals.empty() ) { |
---|
[ba3706f] | 276 | appStmt = new ExprStmt( appExpr ); |
---|
[626dbc10] | 277 | } else { |
---|
[ba3706f] | 278 | appStmt = new ReturnStmt( appExpr ); |
---|
[626dbc10] | 279 | } // if |
---|
[cf90b88] | 280 | thunkFunc->statements->kids.push_back( appStmt ); |
---|
[626dbc10] | 281 | |
---|
[d5baf0c] | 282 | // Add the thunk definition (converted to DeclStmt if appproprate). |
---|
| 283 | declsToAddBefore.push_back( thunkFunc ); |
---|
[626dbc10] | 284 | // return address of thunk function as replacement expression |
---|
| 285 | return new AddressExpr( new VariableExpr( thunkFunc ) ); |
---|
| 286 | } |
---|
| 287 | |
---|
[01aeade] | 288 | void Specialize::handleExplicitParams( ApplicationExpr *appExpr ) { |
---|
| 289 | // create thunks for the explicit parameters |
---|
[cf90b88] | 290 | assert( appExpr->function->result ); |
---|
| 291 | FunctionType *function = getFunctionType( appExpr->function->result ); |
---|
[698664b3] | 292 | assert( function ); |
---|
[01aeade] | 293 | std::list< DeclarationWithType* >::iterator formal; |
---|
| 294 | std::list< Expression* >::iterator actual; |
---|
| 295 | for ( formal = function->get_parameters().begin(), actual = appExpr->get_args().begin(); formal != function->get_parameters().end() && actual != appExpr->get_args().end(); ++formal, ++actual ) { |
---|
[0b00df0] | 296 | *actual = doSpecialization( (*formal)->get_type(), *actual, &appExpr->inferParams ); |
---|
[01aeade] | 297 | } |
---|
| 298 | } |
---|
| 299 | |
---|
[cf90b88] | 300 | Expression * Specialize::postmutate( ApplicationExpr *appExpr ) { |
---|
[aedfd91] | 301 | if ( ! InitTweak::isIntrinsicCallExpr( appExpr ) ) { |
---|
| 302 | // create thunks for the inferred parameters |
---|
| 303 | // don't need to do this for intrinsic calls, because they aren't actually passed |
---|
[f3b0a07] | 304 | // need to handle explicit params before inferred params so that explicit params do not recieve a changed set of inferParams (and change them again) |
---|
| 305 | // alternatively, if order starts to matter then copy appExpr's inferParams and pass them to handleExplicitParams. |
---|
| 306 | handleExplicitParams( appExpr ); |
---|
[0b00df0] | 307 | for ( InferredParams::iterator inferParam = appExpr->inferParams.begin(); inferParam != appExpr->inferParams.end(); ++inferParam ) { |
---|
| 308 | inferParam->second.expr = doSpecialization( inferParam->second.formalType, inferParam->second.expr, &inferParam->second.expr->inferParams ); |
---|
[aedfd91] | 309 | } |
---|
| 310 | } |
---|
[01aeade] | 311 | return appExpr; |
---|
| 312 | } |
---|
| 313 | |
---|
[cf90b88] | 314 | Expression * Specialize::postmutate( CastExpr *castExpr ) { |
---|
| 315 | if ( castExpr->result->isVoid() ) { |
---|
[803deb1] | 316 | // can't specialize if we don't have a return value |
---|
| 317 | return castExpr; |
---|
| 318 | } |
---|
[bb666f64] | 319 | Expression *specialized = doSpecialization( castExpr->result, castExpr->arg, &castExpr->inferParams ); |
---|
[cf90b88] | 320 | if ( specialized != castExpr->arg ) { |
---|
[698664b3] | 321 | // assume here that the specialization incorporates the cast |
---|
| 322 | return specialized; |
---|
| 323 | } else { |
---|
| 324 | return castExpr; |
---|
| 325 | } |
---|
[01aeade] | 326 | } |
---|
| 327 | |
---|
[626dbc10] | 328 | void convertSpecializations( std::list< Declaration* >& translationUnit ) { |
---|
[cf90b88] | 329 | PassVisitor<Specialize> spec; |
---|
[626dbc10] | 330 | mutateAll( translationUnit, spec ); |
---|
| 331 | } |
---|
[51b7345] | 332 | } // namespace GenPoly |
---|
[01aeade] | 333 | |
---|
[51587aa] | 334 | // Local Variables: // |
---|
| 335 | // tab-width: 4 // |
---|
| 336 | // mode: c++ // |
---|
| 337 | // compile-command: "make install" // |
---|
| 338 | // End: // |
---|