source: src/GenPoly/InstantiateGeneric.cc @ 490db327

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 490db327 was 760ba67, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Temporarily remove type parameter delete for dtype-static generics [fixes #55]

  • Property mode set to 100644
File size: 19.7 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2016 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// InstantiateGeneric.cc --
8//
9// Author           : Aaron B. Moss
10// Created On       : Thu Aug 04 18:33:00 2016
11// Last Modified By : Aaron B. Moss
12// Last Modified On : Thu Aug 04 18:33:00 2016
13// Update Count     : 1
14//
15#include "InstantiateGeneric.h"
16
17#include <cassert>                     // for assertf, assert
18#include <iterator>                    // for back_inserter, inserter
19#include <list>                        // for list, _List_const_iterator
20#include <utility>                     // for move, pair
21#include <vector>                      // for vector
22
23#include "Common/PassVisitor.h"        // for PassVisitor, WithDeclsToAdd
24#include "Common/ScopedMap.h"          // for ScopedMap
25#include "Common/SemanticError.h"      // for SemanticError
26#include "Common/UniqueName.h"         // for UniqueName
27#include "Common/utility.h"            // for deleteAll, cloneAll
28#include "GenPoly.h"                   // for isPolyType, typesPolyCompatible
29#include "ScopedSet.h"                 // for ScopedSet, ScopedSet<>::iterator
30#include "ScrubTyVars.h"               // for ScrubTyVars
31#include "SynTree/Declaration.h"       // for StructDecl, UnionDecl, TypeDecl
32#include "SynTree/Expression.h"        // for TypeExpr, Expression
33#include "SynTree/Mutator.h"           // for mutateAll
34#include "SynTree/Type.h"              // for StructInstType, UnionInstType
35#include "SynTree/TypeSubstitution.h"  // for TypeSubstitution
36#include "SynTree/Visitor.h"           // for acceptAll
37
38
39namespace GenPoly {
40
41        /// Abstracts type equality for a list of parameter types
42        struct TypeList {
43                TypeList() : params() {}
44                TypeList( const std::list< Type* > &_params ) : params() { cloneAll(_params, params); }
45                TypeList( std::list< Type* > &&_params ) : params( _params ) {}
46
47                TypeList( const TypeList &that ) : params() { cloneAll(that.params, params); }
48                TypeList( TypeList &&that ) : params( std::move( that.params ) ) {}
49
50                /// Extracts types from a list of TypeExpr*
51                TypeList( const std::list< TypeExpr* >& _params ) : params() {
52                        for ( std::list< TypeExpr* >::const_iterator param = _params.begin(); param != _params.end(); ++param ) {
53                                params.push_back( (*param)->get_type()->clone() );
54                        }
55                }
56
57                TypeList& operator= ( const TypeList &that ) {
58                        deleteAll( params );
59
60                        params.clear();
61                        cloneAll( that.params, params );
62
63                        return *this;
64                }
65
66                TypeList& operator= ( TypeList &&that ) {
67                        deleteAll( params );
68
69                        params = std::move( that.params );
70
71                        return *this;
72                }
73
74                ~TypeList() { deleteAll( params ); }
75
76                bool operator== ( const TypeList& that ) const {
77                        if ( params.size() != that.params.size() ) return false;
78
79                        for ( std::list< Type* >::const_iterator it = params.begin(), jt = that.params.begin(); it != params.end(); ++it, ++jt ) {
80                                if ( ! typesPolyCompatible( *it, *jt ) ) return false;
81                        }
82                        return true;
83                }
84
85                std::list< Type* > params;  ///< Instantiation parameters
86        };
87
88        /// Maps a key and a TypeList to the some value, accounting for scope
89        template< typename Key, typename Value >
90        class InstantiationMap {
91                /// Wraps value for a specific (Key, TypeList) combination
92                typedef std::pair< TypeList, Value* > Instantiation;
93                /// List of TypeLists paired with their appropriate values
94                typedef std::vector< Instantiation > ValueList;
95                /// Underlying map type; maps keys to a linear list of corresponding TypeLists and values
96                typedef ScopedMap< Key*, ValueList > InnerMap;
97
98                InnerMap instantiations;  ///< instantiations
99
100        public:
101                /// Starts a new scope
102                void beginScope() { instantiations.beginScope(); }
103
104                /// Ends a scope
105                void endScope() { instantiations.endScope(); }
106
107                /// Gets the value for the (key, typeList) pair, returns NULL on none such.
108                Value *lookup( Key *key, const std::list< TypeExpr* >& params ) const {
109                        TypeList typeList( params );
110
111                        // scan scopes for matches to the key
112                        for ( typename InnerMap::const_iterator insts = instantiations.find( key ); insts != instantiations.end(); insts = instantiations.findNext( insts, key ) ) {
113                                for ( typename ValueList::const_reverse_iterator inst = insts->second.rbegin(); inst != insts->second.rend(); ++inst ) {
114                                        if ( inst->first == typeList ) return inst->second;
115                                }
116                        }
117                        // no matching instantiations found
118                        return 0;
119                }
120
121                /// Adds a value for a (key, typeList) pair to the current scope
122                void insert( Key *key, const std::list< TypeExpr* > &params, Value *value ) {
123                        auto it = instantiations.findAt( instantiations.currentScope(), key );
124                        if ( it == instantiations.end() ) {
125                                instantiations.insert( key, ValueList{ Instantiation{ TypeList( params ), value } } );
126                        } else {
127                                it->second.push_back( Instantiation{ TypeList( params ), value } );
128                        }
129                }
130        };
131
132        /// Possible options for a given specialization of a generic type
133        enum class genericType {
134                dtypeStatic,  ///< Concrete instantiation based solely on {d,f}type-to-void conversions
135                concrete,     ///< Concrete instantiation requiring at least one parameter type
136                dynamic       ///< No concrete instantiation
137        };
138
139        genericType& operator |= ( genericType& gt, const genericType& ht ) {
140                switch ( gt ) {
141                case genericType::dtypeStatic:
142                        gt = ht;
143                        break;
144                case genericType::concrete:
145                        if ( ht == genericType::dynamic ) { gt = genericType::dynamic; }
146                        break;
147                case genericType::dynamic:
148                        // nothing possible
149                        break;
150                }
151                return gt;
152        }
153
154        /// Mutator pass that replaces concrete instantiations of generic types with actual struct declarations, scoped appropriately
155        struct GenericInstantiator final : public WithTypeSubstitution, public WithDeclsToAdd, public WithVisitorRef<GenericInstantiator>, public WithGuards {
156                /// Map of (generic type, parameter list) pairs to concrete type instantiations
157                InstantiationMap< AggregateDecl, AggregateDecl > instantiations;
158                /// Set of types which are dtype-only generic (and therefore have static layout)
159                ScopedSet< AggregateDecl* > dtypeStatics;
160                /// Namer for concrete types
161                UniqueName typeNamer;
162                /// Should not make use of type environment to replace types of function parameter and return values.
163                bool inFunctionType = false;
164                /// Index of current member, used to recreate MemberExprs with the member from an instantiation
165                int memberIndex = -1;
166                GenericInstantiator() : instantiations(), dtypeStatics(), typeNamer("_conc_") {}
167
168                Type* postmutate( StructInstType *inst );
169                Type* postmutate( UnionInstType *inst );
170
171                // fix MemberExprs to use the member from the instantiation
172                void premutate( MemberExpr * memberExpr );
173                Expression * postmutate( MemberExpr * memberExpr );
174
175                void premutate( FunctionType * ) {
176                        GuardValue( inFunctionType );
177                        inFunctionType = true;
178                }
179
180                void beginScope();
181                void endScope();
182        private:
183                /// Wrap instantiation lookup for structs
184                StructDecl* lookup( StructInstType *inst, const std::list< TypeExpr* > &typeSubs ) { return (StructDecl*)instantiations.lookup( inst->get_baseStruct(), typeSubs ); }
185                /// Wrap instantiation lookup for unions
186                UnionDecl* lookup( UnionInstType *inst, const std::list< TypeExpr* > &typeSubs ) { return (UnionDecl*)instantiations.lookup( inst->get_baseUnion(), typeSubs ); }
187                /// Wrap instantiation insertion for structs
188                void insert( StructInstType *inst, const std::list< TypeExpr* > &typeSubs, StructDecl *decl ) { instantiations.insert( inst->get_baseStruct(), typeSubs, decl ); }
189                /// Wrap instantiation insertion for unions
190                void insert( UnionInstType *inst, const std::list< TypeExpr* > &typeSubs, UnionDecl *decl ) { instantiations.insert( inst->get_baseUnion(), typeSubs, decl ); }
191
192                void replaceParametersWithConcrete( std::list< Expression* >& params );
193                Type *replaceWithConcrete( Type *type, bool doClone );
194
195                /// Strips a dtype-static aggregate decl of its type parameters, marks it as stripped
196                void stripDtypeParams( AggregateDecl *base, std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs );
197        };
198
199        void instantiateGeneric( std::list< Declaration* > &translationUnit ) {
200                PassVisitor<GenericInstantiator> instantiator;
201                mutateAll( translationUnit, instantiator );
202        }
203
204        /// Makes substitutions of params into baseParams; returns dtypeStatic if there is a concrete instantiation based only on {d,f}type-to-void conversions,
205        /// concrete if there is a concrete instantiation requiring at least one parameter type, and dynamic if there is no concrete instantiation
206        genericType makeSubstitutions( const std::list< TypeDecl* >& baseParams, const std::list< Expression* >& params, std::list< TypeExpr* >& out ) {
207                genericType gt = genericType::dtypeStatic;
208
209                // substitute concrete types for given parameters, and incomplete types for placeholders
210                std::list< TypeDecl* >::const_iterator baseParam = baseParams.begin();
211                std::list< Expression* >::const_iterator param = params.begin();
212                for ( ; baseParam != baseParams.end() && param != params.end(); ++baseParam, ++param ) {
213                        TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
214                        assert(paramType && "Aggregate parameters should be type expressions");
215
216                        if ( (*baseParam)->isComplete() ) {
217                                // substitute parameter for complete (otype or sized dtype) type
218                                if ( isPolyType( paramType->get_type() ) ) {
219                                        // substitute polymorphic parameter type in to generic type
220                                        out.push_back( paramType->clone() );
221                                        gt = genericType::dynamic;
222                                } else {
223                                        // normalize possibly dtype-static parameter type
224                                        out.push_back( new TypeExpr{
225                                                ScrubTyVars::scrubAll( paramType->get_type()->clone() ) } );
226                                        gt |= genericType::concrete;
227                                }
228                        } else switch ( (*baseParam)->get_kind() ) {
229                                case TypeDecl::Dtype:
230                                        // can pretend that any incomplete dtype is `void`
231                                        out.push_back( new TypeExpr( new VoidType( Type::Qualifiers() ) ) );
232                                        break;
233                                case TypeDecl::Ftype:
234                                        // can pretend that any ftype is `void (*)(void)`
235                                        out.push_back( new TypeExpr( new FunctionType( Type::Qualifiers(), false ) ) );
236                                        break;
237                                case TypeDecl::Ttype:
238                                        assertf( false, "Ttype parameters are not currently allowed as parameters to generic types." );
239                                        break;
240                                default:
241                                        assertf( false, "Unhandled type parameter kind" );
242                                        break;
243                        }
244                }
245
246                assertf( baseParam == baseParams.end() && param == params.end(), "Type parameters should match type variables" );
247                return gt;
248        }
249
250        /// Substitutes types of members of in according to baseParams => typeSubs, appending the result to out
251        void substituteMembers( const std::list< Declaration* >& in, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs,
252                                                        std::list< Declaration* >& out ) {
253                // substitute types into new members
254                TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
255                for ( std::list< Declaration* >::const_iterator member = in.begin(); member != in.end(); ++member ) {
256                        Declaration *newMember = (*member)->clone();
257                        subs.apply(newMember);
258                        out.push_back( newMember );
259                }
260        }
261
262        /// Substitutes types of members according to baseParams => typeSubs, working in-place
263        void substituteMembers( std::list< Declaration* >& members, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs ) {
264                // substitute types into new members
265                TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
266                for ( std::list< Declaration* >::iterator member = members.begin(); member != members.end(); ++member ) {
267                        subs.apply(*member);
268                }
269        }
270
271        /// Strips the instances's type parameters
272        void stripInstParams( ReferenceToType *inst ) {
273                deleteAll( inst->get_parameters() );
274                inst->get_parameters().clear();
275        }
276
277        void GenericInstantiator::stripDtypeParams( AggregateDecl *base, std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs ) {
278                substituteMembers( base->get_members(), baseParams, typeSubs );
279
280                // xxx - can't delete type parameters because they may have assertions that are used
281                // deleteAll( baseParams );
282                baseParams.clear();
283
284                dtypeStatics.insert( base );
285        }
286
287        /// xxx - more or less copied from box -- these should be merged with those somehow...
288        void GenericInstantiator::replaceParametersWithConcrete( std::list< Expression* >& params ) {
289                for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
290                        TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
291                        assertf(paramType, "Aggregate parameters should be type expressions");
292                        paramType->set_type( replaceWithConcrete( paramType->get_type(), false ) );
293                }
294        }
295
296        Type *GenericInstantiator::replaceWithConcrete( Type *type, bool doClone ) {
297                if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
298                        if ( env && ! inFunctionType ) {
299                                Type *concrete = env->lookup( typeInst->get_name() );
300                                if ( concrete ) {
301                                        return concrete->clone();
302                                }
303                                else return typeInst->clone();
304                        }
305                } else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
306                        if ( doClone ) {
307                                structType = structType->clone();
308                        }
309                        replaceParametersWithConcrete( structType->get_parameters() );
310                        return structType;
311                } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
312                        if ( doClone ) {
313                                unionType = unionType->clone();
314                        }
315                        replaceParametersWithConcrete( unionType->get_parameters() );
316                        return unionType;
317                }
318                return type;
319        }
320
321
322        Type* GenericInstantiator::postmutate( StructInstType *inst ) {
323                // exit early if no need for further mutation
324                if ( inst->get_parameters().empty() ) return inst;
325
326                // need to replace type variables to ensure that generic types are instantiated for the return values of polymorphic functions (in particular, for thunks, because they are not [currently] copy constructed).
327                replaceWithConcrete( inst, false );
328
329                // check for an already-instantiatiated dtype-static type
330                if ( dtypeStatics.find( inst->get_baseStruct() ) != dtypeStatics.end() ) {
331                        stripInstParams( inst );
332                        return inst;
333                }
334
335                // check if type can be concretely instantiated; put substitutions into typeSubs
336                assertf( inst->get_baseParameters(), "Base struct has parameters" );
337                std::list< TypeExpr* > typeSubs;
338                genericType gt = makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs );
339                switch ( gt ) {
340                case genericType::dtypeStatic:
341                        stripDtypeParams( inst->get_baseStruct(), *inst->get_baseParameters(), typeSubs );
342                        stripInstParams( inst );
343                        break;
344
345                case genericType::concrete: {
346                        // make concrete instantiation of generic type
347                        StructDecl *concDecl = lookup( inst, typeSubs );
348                        if ( ! concDecl ) {
349                                // set concDecl to new type, insert type declaration into statements to add
350                                concDecl = new StructDecl( typeNamer.newName( inst->get_name() ) );
351                                concDecl->set_body( inst->get_baseStruct()->has_body() );
352                                substituteMembers( inst->get_baseStruct()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
353                                insert( inst, typeSubs, concDecl ); // must insert before recursion
354                                concDecl->acceptMutator( *visitor ); // recursively instantiate members
355                                declsToAddBefore.push_back( concDecl ); // must occur before declaration is added so that member instantiations appear first
356                        }
357                        StructInstType *newInst = new StructInstType( inst->get_qualifiers(), concDecl->get_name() );
358                        newInst->set_baseStruct( concDecl );
359
360                        delete inst;
361                        inst = newInst;
362                        break;
363                }
364
365                case genericType::dynamic:
366                        // do nothing
367                        break;
368                }
369
370                deleteAll( typeSubs );
371                return inst;
372        }
373
374        Type* GenericInstantiator::postmutate( UnionInstType *inst ) {
375                // exit early if no need for further mutation
376                if ( inst->get_parameters().empty() ) return inst;
377
378                // check for an already-instantiatiated dtype-static type
379                if ( dtypeStatics.find( inst->get_baseUnion() ) != dtypeStatics.end() ) {
380                        stripInstParams( inst );
381                        return inst;
382                }
383
384                // check if type can be concretely instantiated; put substitutions into typeSubs
385                assert( inst->get_baseParameters() && "Base union has parameters" );
386                std::list< TypeExpr* > typeSubs;
387                genericType gt = makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs );
388                switch ( gt ) {
389                case genericType::dtypeStatic:
390                        stripDtypeParams( inst->get_baseUnion(), *inst->get_baseParameters(), typeSubs );
391                        stripInstParams( inst );
392                        break;
393
394                case genericType::concrete:
395                {
396                        // make concrete instantiation of generic type
397                        UnionDecl *concDecl = lookup( inst, typeSubs );
398                        if ( ! concDecl ) {
399                                // set concDecl to new type, insert type declaration into statements to add
400                                concDecl = new UnionDecl( typeNamer.newName( inst->get_name() ) );
401                                concDecl->set_body( inst->get_baseUnion()->has_body() );
402                                substituteMembers( inst->get_baseUnion()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
403                                insert( inst, typeSubs, concDecl ); // must insert before recursion
404                                concDecl->acceptMutator( *visitor ); // recursively instantiate members
405                                declsToAddBefore.push_back( concDecl ); // must occur before declaration is added so that member instantiations appear first
406                        }
407                        UnionInstType *newInst = new UnionInstType( inst->get_qualifiers(), concDecl->get_name() );
408                        newInst->set_baseUnion( concDecl );
409
410                        delete inst;
411                        inst = newInst;
412                        break;
413                }
414                case genericType::dynamic:
415                        // do nothing
416                        break;
417                }
418
419                deleteAll( typeSubs );
420                return inst;
421        }
422
423        namespace {
424                bool isGenericType( Type * t ) {
425                        if ( StructInstType * inst = dynamic_cast< StructInstType * >( t ) ) {
426                                return ! inst->parameters.empty();
427                        } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( t ) ) {
428                                return ! inst->parameters.empty();
429                        }
430                        return false;
431                }
432
433                AggregateDecl * getAggr( Type * t ) {
434                        if ( StructInstType * inst = dynamic_cast< StructInstType * >( t ) ) {
435                                return inst->baseStruct;
436                        } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( t ) ) {
437                                return inst->baseUnion;
438                        }
439                        assertf( false, "Non-aggregate type: %s", toString( t ).c_str() );
440                }
441        }
442
443        void GenericInstantiator::premutate( MemberExpr * memberExpr ) {
444                GuardValue( memberIndex );
445                memberIndex = -1;
446                if ( isGenericType( memberExpr->aggregate->result ) ) {
447                        // find the location of the member
448                        AggregateDecl * aggr = getAggr( memberExpr->aggregate->result );
449                        std::list< Declaration * > & members = aggr->members;
450                        memberIndex = std::distance( members.begin(), std::find( members.begin(), members.end(), memberExpr->member ) );
451                        assertf( memberIndex < (int)members.size(), "Could not find member %s in generic type %s", toString( memberExpr->member ).c_str(), toString( memberExpr->aggregate ).c_str() );
452                }
453        }
454
455        Expression * GenericInstantiator::postmutate( MemberExpr * memberExpr ) {
456                if ( memberIndex != -1 ) {
457                        // using the location from the generic type, find the member in the instantiation and rebuild the member expression
458                        AggregateDecl * aggr = getAggr( memberExpr->aggregate->result );
459                        assertf( memberIndex < (int)aggr->members.size(), "Instantiation somehow has fewer members than the generic type." );
460                        Declaration * member = *std::next( aggr->members.begin(), memberIndex );
461                        assertf( member->name == memberExpr->member->name, "Instantiation has different member order than the generic type. %s / %s", toString( member ).c_str(), toString( memberExpr->member ).c_str() );
462                        DeclarationWithType * field = strict_dynamic_cast< DeclarationWithType * >( member );
463                        MemberExpr * ret = new MemberExpr( field, memberExpr->aggregate->clone() );
464                        std::swap( ret->env, memberExpr->env );
465                        delete memberExpr;
466                        return ret;
467                }
468                return memberExpr;
469        }
470
471        void GenericInstantiator::beginScope() {
472                instantiations.beginScope();
473                dtypeStatics.beginScope();
474        }
475
476        void GenericInstantiator::endScope() {
477                instantiations.endScope();
478                dtypeStatics.endScope();
479        }
480
481} // namespace GenPoly
482
483// Local Variables: //
484// tab-width: 4 //
485// mode: c++ //
486// compile-command: "make install" //
487// End: //
Note: See TracBrowser for help on using the repository browser.