source: src/GenPoly/InstantiateGeneric.cc @ acd7c5dd

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

Removed several new warnings

  • Property mode set to 100644
File size: 16.4 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
16#include <cassert>
17#include <list>
[5a3ac84]18#include <unordered_map>
[ea5daeb]19#include <utility>
20#include <vector>
21
22#include "InstantiateGeneric.h"
23
24#include "GenPoly.h"
[3bb195cb]25#include "ScopedSet.h"
[5a3ac84]26#include "ScrubTyVars.h"
[2a7b3ca]27
28#include "Common/PassVisitor.h"
29#include "Common/ScopedMap.h"
30#include "Common/UniqueName.h"
31#include "Common/utility.h"
[ea5daeb]32
33#include "ResolvExpr/typeops.h"
34
35#include "SynTree/Declaration.h"
36#include "SynTree/Expression.h"
37#include "SynTree/Type.h"
38
[2a7b3ca]39
40#include "InitTweak/InitTweak.h"
41
[ea5daeb]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 ) {
[5a3ac84]84                                if ( ! typesPolyCompatible( *it, *jt ) ) return false;
[ea5daeb]85                        }
86                        return true;
87                }
88
89                std::list< Type* > params;  ///< Instantiation parameters
90        };
[e491159]91
[ea5daeb]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 ) {
[e58dfb9]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                        }
[ea5daeb]133                }
134        };
[3bb195cb]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        }
[e491159]157
[ea5daeb]158        /// Mutator pass that replaces concrete instantiations of generic types with actual struct declarations, scoped appropriately
[2a7b3ca]159        struct GenericInstantiator final : public WithTypeSubstitution, public WithDeclsToAdd, public WithVisitorRef<GenericInstantiator>, public WithGuards {
[ea5daeb]160                /// Map of (generic type, parameter list) pairs to concrete type instantiations
161                InstantiationMap< AggregateDecl, AggregateDecl > instantiations;
[3bb195cb]162                /// Set of types which are dtype-only generic (and therefore have static layout)
163                ScopedSet< AggregateDecl* > dtypeStatics;
[ea5daeb]164                /// Namer for concrete types
165                UniqueName typeNamer;
[2a7b3ca]166                /// Should not make use of type environment to replace types of function parameter and return values.
167                bool inFunctionType = false;
168                GenericInstantiator() : instantiations(), dtypeStatics(), typeNamer("_conc_") {}
169
170                Type* postmutate( StructInstType *inst );
171                Type* postmutate( UnionInstType *inst );
[ea5daeb]172
[9ff56e7]173                void premutate( __attribute__((unused)) FunctionType * ftype ) {
[2a7b3ca]174                        GuardValue( inFunctionType );
175                        inFunctionType = true;
176                }
[ea5daeb]177
[2a7b3ca]178                void beginScope();
179                void endScope();
[ea5daeb]180        private:
181                /// Wrap instantiation lookup for structs
182                StructDecl* lookup( StructInstType *inst, const std::list< TypeExpr* > &typeSubs ) { return (StructDecl*)instantiations.lookup( inst->get_baseStruct(), typeSubs ); }
183                /// Wrap instantiation lookup for unions
184                UnionDecl* lookup( UnionInstType *inst, const std::list< TypeExpr* > &typeSubs ) { return (UnionDecl*)instantiations.lookup( inst->get_baseUnion(), typeSubs ); }
185                /// Wrap instantiation insertion for structs
186                void insert( StructInstType *inst, const std::list< TypeExpr* > &typeSubs, StructDecl *decl ) { instantiations.insert( inst->get_baseStruct(), typeSubs, decl ); }
187                /// Wrap instantiation insertion for unions
188                void insert( UnionInstType *inst, const std::list< TypeExpr* > &typeSubs, UnionDecl *decl ) { instantiations.insert( inst->get_baseUnion(), typeSubs, decl ); }
[3bb195cb]189
[b940dc71]190                void replaceParametersWithConcrete( std::list< Expression* >& params );
191                Type *replaceWithConcrete( Type *type, bool doClone );
192
[3bb195cb]193                /// Strips a dtype-static aggregate decl of its type parameters, marks it as stripped
194                void stripDtypeParams( AggregateDecl *base, std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs );
[ea5daeb]195        };
196
197        void instantiateGeneric( std::list< Declaration* > &translationUnit ) {
[2a7b3ca]198                PassVisitor<GenericInstantiator> instantiator;
199                mutateAll( translationUnit, instantiator );
[ea5daeb]200        }
201
[3bb195cb]202        /// Makes substitutions of params into baseParams; returns dtypeStatic if there is a concrete instantiation based only on {d,f}type-to-void conversions,
203        /// concrete if there is a concrete instantiation requiring at least one parameter type, and dynamic if there is no concrete instantiation
[ea5daeb]204        genericType makeSubstitutions( const std::list< TypeDecl* >& baseParams, const std::list< Expression* >& params, std::list< TypeExpr* >& out ) {
205                genericType gt = genericType::dtypeStatic;
206
207                // substitute concrete types for given parameters, and incomplete types for placeholders
208                std::list< TypeDecl* >::const_iterator baseParam = baseParams.begin();
209                std::list< Expression* >::const_iterator param = params.begin();
210                for ( ; baseParam != baseParams.end() && param != params.end(); ++baseParam, ++param ) {
211                        TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
212                        assert(paramType && "Aggregate parameters should be type expressions");
[e491159]213
[0bfaf80]214                        if ( (*baseParam)->isComplete() ) {
[87c3bef]215                                // substitute parameter for complete (otype or sized dtype) type
[5a3ac84]216                                if ( isPolyType( paramType->get_type() ) ) {
217                                        // substitute polymorphic parameter type in to generic type
[87c3bef]218                                        out.push_back( paramType->clone() );
[5a3ac84]219                                        gt = genericType::dynamic;
220                                } else {
221                                        // normalize possibly dtype-static parameter type
[6db9dab]222                                        out.push_back( new TypeExpr{
[5a3ac84]223                                                ScrubTyVars::scrubAll( paramType->get_type()->clone() ) } );
224                                        gt |= genericType::concrete;
[87c3bef]225                                }
[0bfaf80]226                        } else switch ( (*baseParam)->get_kind() ) {
227                                case TypeDecl::Dtype:
228                                        // can pretend that any incomplete dtype is `void`
229                                        out.push_back( new TypeExpr( new VoidType( Type::Qualifiers() ) ) );
230                                        break;
231                                case TypeDecl::Ftype:
232                                        // can pretend that any ftype is `void (*)(void)`
233                                        out.push_back( new TypeExpr( new FunctionType( Type::Qualifiers(), false ) ) );
234                                        break;
235                                case TypeDecl::Ttype:
236                                        assertf( false, "Ttype parameters are not currently allowed as parameters to generic types." );
237                                        break;
238                                case TypeDecl::Any:
239                                        assertf( false, "otype parameters handled by baseParam->isComplete()." );
240                                        break;
[ea5daeb]241                        }
242                }
243
[b2daebd4]244                assertf( baseParam == baseParams.end() && param == params.end(), "Type parameters should match type variables" );
[ea5daeb]245                return gt;
246        }
247
248        /// Substitutes types of members of in according to baseParams => typeSubs, appending the result to out
249        void substituteMembers( const std::list< Declaration* >& in, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs,
250                                                        std::list< Declaration* >& out ) {
251                // substitute types into new members
252                TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
253                for ( std::list< Declaration* >::const_iterator member = in.begin(); member != in.end(); ++member ) {
254                        Declaration *newMember = (*member)->clone();
255                        subs.apply(newMember);
256                        out.push_back( newMember );
257                }
258        }
259
[3bb195cb]260        /// Substitutes types of members according to baseParams => typeSubs, working in-place
261        void substituteMembers( std::list< Declaration* >& members, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs ) {
262                // substitute types into new members
263                TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
264                for ( std::list< Declaration* >::iterator member = members.begin(); member != members.end(); ++member ) {
265                        subs.apply(*member);
266                }
267        }
268
[f18a711]269        /// Strips the instances's type parameters
270        void stripInstParams( ReferenceToType *inst ) {
[3bb195cb]271                deleteAll( inst->get_parameters() );
272                inst->get_parameters().clear();
273        }
[e491159]274
[3bb195cb]275        void GenericInstantiator::stripDtypeParams( AggregateDecl *base, std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs ) {
276                substituteMembers( base->get_members(), baseParams, typeSubs );
277
278                deleteAll( baseParams );
279                baseParams.clear();
[e491159]280
[3bb195cb]281                dtypeStatics.insert( base );
282        }
283
[b940dc71]284        /// xxx - more or less copied from box -- these should be merged with those somehow...
285        void GenericInstantiator::replaceParametersWithConcrete( std::list< Expression* >& params ) {
286                for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
287                        TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
288                        assertf(paramType, "Aggregate parameters should be type expressions");
289                        paramType->set_type( replaceWithConcrete( paramType->get_type(), false ) );
290                }
291        }
292
293        Type *GenericInstantiator::replaceWithConcrete( Type *type, bool doClone ) {
294                if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
[2a7b3ca]295                        if ( env && ! inFunctionType ) {
[b940dc71]296                                Type *concrete = env->lookup( typeInst->get_name() );
297                                if ( concrete ) {
298                                        return concrete->clone();
299                                }
300                                else return typeInst->clone();
301                        }
302                } else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
303                        if ( doClone ) {
304                                structType = structType->clone();
305                        }
306                        replaceParametersWithConcrete( structType->get_parameters() );
307                        return structType;
308                } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
309                        if ( doClone ) {
310                                unionType = unionType->clone();
311                        }
312                        replaceParametersWithConcrete( unionType->get_parameters() );
313                        return unionType;
314                }
315                return type;
316        }
317
318
[2a7b3ca]319        Type* GenericInstantiator::postmutate( StructInstType *inst ) {
[ea5daeb]320                // exit early if no need for further mutation
321                if ( inst->get_parameters().empty() ) return inst;
322
[b940dc71]323                // 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).
324                replaceWithConcrete( inst, false );
325
[3bb195cb]326                // check for an already-instantiatiated dtype-static type
[f18a711]327                if ( dtypeStatics.find( inst->get_baseStruct() ) != dtypeStatics.end() ) {
328                        stripInstParams( inst );
329                        return inst;
330                }
[e491159]331
[ea5daeb]332                // check if type can be concretely instantiated; put substitutions into typeSubs
[b940dc71]333                assertf( inst->get_baseParameters(), "Base struct has parameters" );
[ea5daeb]334                std::list< TypeExpr* > typeSubs;
335                genericType gt = makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs );
336                switch ( gt ) {
[3bb195cb]337                case genericType::dtypeStatic:
338                        stripDtypeParams( inst->get_baseStruct(), *inst->get_baseParameters(), typeSubs );
[f18a711]339                        stripInstParams( inst );
[3bb195cb]340                        break;
[e491159]341
[3bb195cb]342                case genericType::concrete: {
[ea5daeb]343                        // make concrete instantiation of generic type
344                        StructDecl *concDecl = lookup( inst, typeSubs );
345                        if ( ! concDecl ) {
346                                // set concDecl to new type, insert type declaration into statements to add
347                                concDecl = new StructDecl( typeNamer.newName( inst->get_name() ) );
[2c57025]348                                concDecl->set_body( inst->get_baseStruct()->has_body() );
[5a3ac84]349                                substituteMembers( inst->get_baseStruct()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
[c7a3081]350                                insert( inst, typeSubs, concDecl ); // must insert before recursion
[2a7b3ca]351                                concDecl->acceptMutator( *visitor ); // recursively instantiate members
352                                declsToAddBefore.push_back( concDecl ); // must occur before declaration is added so that member instantiations appear first
[ea5daeb]353                        }
354                        StructInstType *newInst = new StructInstType( inst->get_qualifiers(), concDecl->get_name() );
355                        newInst->set_baseStruct( concDecl );
356
357                        delete inst;
358                        inst = newInst;
359                        break;
360                }
361
362                case genericType::dynamic:
363                        // do nothing
364                        break;
365                }
366
367                deleteAll( typeSubs );
368                return inst;
369        }
370
[2a7b3ca]371        Type* GenericInstantiator::postmutate( UnionInstType *inst ) {
[ea5daeb]372                // exit early if no need for further mutation
373                if ( inst->get_parameters().empty() ) return inst;
[3bb195cb]374
375                // check for an already-instantiatiated dtype-static type
[f18a711]376                if ( dtypeStatics.find( inst->get_baseUnion() ) != dtypeStatics.end() ) {
377                        stripInstParams( inst );
378                        return inst;
379                }
[ea5daeb]380
381                // check if type can be concretely instantiated; put substitutions into typeSubs
[3bb195cb]382                assert( inst->get_baseParameters() && "Base union has parameters" );
[ea5daeb]383                std::list< TypeExpr* > typeSubs;
384                genericType gt = makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs );
385                switch ( gt ) {
[3bb195cb]386                case genericType::dtypeStatic:
387                        stripDtypeParams( inst->get_baseUnion(), *inst->get_baseParameters(), typeSubs );
[f18a711]388                        stripInstParams( inst );
[3bb195cb]389                        break;
[e491159]390
[ea5daeb]391                case genericType::concrete:
392                {
393                        // make concrete instantiation of generic type
394                        UnionDecl *concDecl = lookup( inst, typeSubs );
395                        if ( ! concDecl ) {
396                                // set concDecl to new type, insert type declaration into statements to add
397                                concDecl = new UnionDecl( typeNamer.newName( inst->get_name() ) );
[2c57025]398                                concDecl->set_body( inst->get_baseUnion()->has_body() );
[ea5daeb]399                                substituteMembers( inst->get_baseUnion()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
[c7a3081]400                                insert( inst, typeSubs, concDecl ); // must insert before recursion
[2a7b3ca]401                                concDecl->acceptMutator( *visitor ); // recursively instantiate members
402                                declsToAddBefore.push_back( concDecl ); // must occur before declaration is added so that member instantiations appear first
[ea5daeb]403                        }
404                        UnionInstType *newInst = new UnionInstType( inst->get_qualifiers(), concDecl->get_name() );
405                        newInst->set_baseUnion( concDecl );
406
407                        delete inst;
408                        inst = newInst;
409                        break;
410                }
411                case genericType::dynamic:
412                        // do nothing
413                        break;
414                }
415
416                deleteAll( typeSubs );
417                return inst;
418        }
419
[2a7b3ca]420        void GenericInstantiator::beginScope() {
[ea5daeb]421                instantiations.beginScope();
[3bb195cb]422                dtypeStatics.beginScope();
[ea5daeb]423        }
424
[2a7b3ca]425        void GenericInstantiator::endScope() {
[ea5daeb]426                instantiations.endScope();
[3bb195cb]427                dtypeStatics.endScope();
[ea5daeb]428        }
429
430} // namespace GenPoly
431
432// Local Variables: //
433// tab-width: 4 //
434// mode: c++ //
435// compile-command: "make install" //
436// End: //
Note: See TracBrowser for help on using the repository browser.