source: src/GenPoly/InstantiateGeneric.cc @ 08fc48f

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 08fc48f was 08fc48f, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Big header cleaning pass - commit 1

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