source: src/GenPoly/InstantiateGeneric.cc @ 1ae06fa

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 1ae06fa was f6582243, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Fix member expressions in the InstantiateGeneric? pass so that they correctly refer to the member from the instantiation

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