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