source: src/GenPoly/InstantiateGeneric.cc@ dd0c97b

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new with_gc
Last change on this file since dd0c97b was b940dc71, checked in by Rob Schluntz <rschlunt@…>, 9 years ago

replace type variables in InstantiateGeneric, fix call passTypeVars so that the correct type is passed

  • Property mode set to 100644
File size: 16.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
16#include <cassert>
17#include <list>
18#include <utility>
19#include <vector>
20#include <unordered_map>
21
22#include "InstantiateGeneric.h"
23
24#include "DeclMutator.h"
25#include "GenPoly.h"
26#include "ScopedSet.h"
27#include "PolyMutator.h"
28
29#include "ResolvExpr/typeops.h"
30
31#include "SynTree/Declaration.h"
32#include "SynTree/Expression.h"
33#include "SynTree/Type.h"
34
35#include "Common/ScopedMap.h"
36#include "Common/UniqueName.h"
37#include "Common/utility.h"
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 SymTab::Indexer dummy;
80 for ( std::list< Type* >::const_iterator it = params.begin(), jt = that.params.begin(); it != params.end(); ++it, ++jt ) {
81 if ( ! ResolvExpr::typesCompatible( *it, *jt, dummy ) ) return false;
82 }
83 return true;
84 }
85
86 std::list< Type* > params; ///< Instantiation parameters
87 };
88
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 ) {
124 instantiations[ key ].push_back( Instantiation( TypeList( params ), value ) );
125 }
126 };
127
128 /// Possible options for a given specialization of a generic type
129 enum class genericType {
130 dtypeStatic, ///< Concrete instantiation based solely on {d,f}type-to-void conversions
131 concrete, ///< Concrete instantiation requiring at least one parameter type
132 dynamic ///< No concrete instantiation
133 };
134
135 genericType& operator |= ( genericType& gt, const genericType& ht ) {
136 switch ( gt ) {
137 case genericType::dtypeStatic:
138 gt = ht;
139 break;
140 case genericType::concrete:
141 if ( ht == genericType::dynamic ) { gt = genericType::dynamic; }
142 break;
143 case genericType::dynamic:
144 // nothing possible
145 break;
146 }
147 return gt;
148 }
149
150 // collect the environments of each TypeInstType so that type variables can be replaced
151 // xxx - possibly temporary solution. Access to type environments is required in GenericInstantiator, but it needs to be a DeclMutator which does not provide easy access to the type environments.
152 class EnvFinder final : public GenPoly::PolyMutator {
153 public:
154 virtual Type * mutate( TypeInstType * inst ) override {
155 if ( env ) envMap[inst] = env;
156 return inst;
157 }
158
159 // don't want to associate an environment with TypeInstTypes that occur in function types - this may actually only apply to function types belonging to DeclarationWithTypes (or even just FunctionDecl)?
160 virtual Type * mutate( FunctionType * ftype ) override {
161 return ftype;
162 }
163 std::unordered_map< ReferenceToType *, TypeSubstitution * > envMap;
164 };
165
166 /// Mutator pass that replaces concrete instantiations of generic types with actual struct declarations, scoped appropriately
167 class GenericInstantiator final : public DeclMutator {
168 /// Map of (generic type, parameter list) pairs to concrete type instantiations
169 InstantiationMap< AggregateDecl, AggregateDecl > instantiations;
170 /// Set of types which are dtype-only generic (and therefore have static layout)
171 ScopedSet< AggregateDecl* > dtypeStatics;
172 /// Namer for concrete types
173 UniqueName typeNamer;
174 /// Reference to mapping of environments
175 const std::unordered_map< ReferenceToType *, TypeSubstitution * > & envMap;
176 public:
177 GenericInstantiator( const std::unordered_map< ReferenceToType *, TypeSubstitution * > & envMap ) : DeclMutator(), instantiations(), dtypeStatics(), typeNamer("_conc_"), envMap( envMap ) {}
178
179 using DeclMutator::mutate;
180 virtual Type* mutate( StructInstType *inst ) override;
181 virtual Type* mutate( UnionInstType *inst ) override;
182
183 virtual void doBeginScope() override;
184 virtual void doEndScope() override;
185 private:
186 /// Wrap instantiation lookup for structs
187 StructDecl* lookup( StructInstType *inst, const std::list< TypeExpr* > &typeSubs ) { return (StructDecl*)instantiations.lookup( inst->get_baseStruct(), typeSubs ); }
188 /// Wrap instantiation lookup for unions
189 UnionDecl* lookup( UnionInstType *inst, const std::list< TypeExpr* > &typeSubs ) { return (UnionDecl*)instantiations.lookup( inst->get_baseUnion(), typeSubs ); }
190 /// Wrap instantiation insertion for structs
191 void insert( StructInstType *inst, const std::list< TypeExpr* > &typeSubs, StructDecl *decl ) { instantiations.insert( inst->get_baseStruct(), typeSubs, decl ); }
192 /// Wrap instantiation insertion for unions
193 void insert( UnionInstType *inst, const std::list< TypeExpr* > &typeSubs, UnionDecl *decl ) { instantiations.insert( inst->get_baseUnion(), typeSubs, decl ); }
194
195 void replaceParametersWithConcrete( std::list< Expression* >& params );
196 Type *replaceWithConcrete( Type *type, bool doClone );
197
198 /// Strips a dtype-static aggregate decl of its type parameters, marks it as stripped
199 void stripDtypeParams( AggregateDecl *base, std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs );
200 };
201
202 void instantiateGeneric( std::list< Declaration* > &translationUnit ) {
203 EnvFinder finder;
204 mutateAll( translationUnit, finder );
205 GenericInstantiator instantiator( finder.envMap );
206 instantiator.mutateDeclarationList( translationUnit );
207 }
208
209 /// Makes substitutions of params into baseParams; returns dtypeStatic if there is a concrete instantiation based only on {d,f}type-to-void conversions,
210 /// concrete if there is a concrete instantiation requiring at least one parameter type, and dynamic if there is no concrete instantiation
211 genericType makeSubstitutions( const std::list< TypeDecl* >& baseParams, const std::list< Expression* >& params, std::list< TypeExpr* >& out ) {
212 genericType gt = genericType::dtypeStatic;
213
214 // substitute concrete types for given parameters, and incomplete types for placeholders
215 std::list< TypeDecl* >::const_iterator baseParam = baseParams.begin();
216 std::list< Expression* >::const_iterator param = params.begin();
217 for ( ; baseParam != baseParams.end() && param != params.end(); ++baseParam, ++param ) {
218 TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
219 assert(paramType && "Aggregate parameters should be type expressions");
220
221 switch ( (*baseParam)->get_kind() ) {
222 case TypeDecl::Any: {
223 // substitute parameter for otype; makes the type concrete or dynamic depending on the parameter
224 out.push_back( paramType->clone() );
225 gt |= isPolyType( paramType->get_type() ) ? genericType::dynamic : genericType::concrete;
226 break;
227 }
228 case TypeDecl::Dtype:
229 // can pretend that any dtype is `void`
230 out.push_back( new TypeExpr( new VoidType( Type::Qualifiers() ) ) );
231 break;
232 case TypeDecl::Ftype:
233 // can pretend that any ftype is `void (*)(void)`
234 out.push_back( new TypeExpr( new FunctionType( Type::Qualifiers(), false ) ) );
235 break;
236 case TypeDecl::Ttype:
237 assertf( false, "Ttype parameters are not currently allowed as parameters to generic types." );
238 break;
239 }
240 }
241
242 assert( baseParam == baseParams.end() && param == params.end() && "Type parameters should match type variables" );
243 return gt;
244 }
245
246 /// Substitutes types of members of in according to baseParams => typeSubs, appending the result to out
247 void substituteMembers( const std::list< Declaration* >& in, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs,
248 std::list< Declaration* >& out ) {
249 // substitute types into new members
250 TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
251 for ( std::list< Declaration* >::const_iterator member = in.begin(); member != in.end(); ++member ) {
252 Declaration *newMember = (*member)->clone();
253 subs.apply(newMember);
254 out.push_back( newMember );
255 }
256 }
257
258 /// Substitutes types of members according to baseParams => typeSubs, working in-place
259 void substituteMembers( std::list< Declaration* >& members, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs ) {
260 // substitute types into new members
261 TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
262 for ( std::list< Declaration* >::iterator member = members.begin(); member != members.end(); ++member ) {
263 subs.apply(*member);
264 }
265 }
266
267 /// Strips the instances's type parameters
268 void stripInstParams( ReferenceToType *inst ) {
269 deleteAll( inst->get_parameters() );
270 inst->get_parameters().clear();
271 }
272
273 void GenericInstantiator::stripDtypeParams( AggregateDecl *base, std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs ) {
274 substituteMembers( base->get_members(), baseParams, typeSubs );
275
276 deleteAll( baseParams );
277 baseParams.clear();
278
279 dtypeStatics.insert( base );
280 }
281
282 /// xxx - more or less copied from box -- these should be merged with those somehow...
283 void GenericInstantiator::replaceParametersWithConcrete( std::list< Expression* >& params ) {
284 for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
285 TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
286 assertf(paramType, "Aggregate parameters should be type expressions");
287 paramType->set_type( replaceWithConcrete( paramType->get_type(), false ) );
288 }
289 }
290
291 Type *GenericInstantiator::replaceWithConcrete( Type *type, bool doClone ) {
292 if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
293 if ( envMap.count( typeInst ) ) {
294 TypeSubstitution * env = envMap.at( typeInst );
295 Type *concrete = env->lookup( typeInst->get_name() );
296 if ( concrete ) {
297 return concrete->clone();
298 }
299 else return typeInst->clone();
300 }
301 } else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
302 if ( doClone ) {
303 structType = structType->clone();
304 }
305 replaceParametersWithConcrete( structType->get_parameters() );
306 return structType;
307 } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
308 if ( doClone ) {
309 unionType = unionType->clone();
310 }
311 replaceParametersWithConcrete( unionType->get_parameters() );
312 return unionType;
313 }
314 return type;
315 }
316
317
318 Type* GenericInstantiator::mutate( StructInstType *inst ) {
319 // mutate subtypes
320 Type *mutated = Mutator::mutate( inst );
321 inst = dynamic_cast< StructInstType* >( mutated );
322 if ( ! inst ) return mutated;
323
324 // exit early if no need for further mutation
325 if ( inst->get_parameters().empty() ) return inst;
326
327 // 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).
328 replaceWithConcrete( inst, false );
329
330 // check for an already-instantiatiated dtype-static type
331 if ( dtypeStatics.find( inst->get_baseStruct() ) != dtypeStatics.end() ) {
332 stripInstParams( inst );
333 return inst;
334 }
335
336 // check if type can be concretely instantiated; put substitutions into typeSubs
337 assertf( inst->get_baseParameters(), "Base struct has parameters" );
338 std::list< TypeExpr* > typeSubs;
339 genericType gt = makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs );
340 switch ( gt ) {
341 case genericType::dtypeStatic:
342 stripDtypeParams( inst->get_baseStruct(), *inst->get_baseParameters(), typeSubs );
343 stripInstParams( inst );
344 break;
345
346 case genericType::concrete: {
347 // make concrete instantiation of generic type
348 StructDecl *concDecl = lookup( inst, typeSubs );
349 if ( ! concDecl ) {
350 // set concDecl to new type, insert type declaration into statements to add
351 concDecl = new StructDecl( typeNamer.newName( inst->get_name() ) );
352 concDecl->set_body( inst->get_baseStruct()->has_body() );
353 substituteMembers( inst->get_baseStruct()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
354 DeclMutator::addDeclaration( concDecl );
355 insert( inst, typeSubs, concDecl );
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::mutate( UnionInstType *inst ) {
375 // mutate subtypes
376 Type *mutated = Mutator::mutate( inst );
377 inst = dynamic_cast< UnionInstType* >( mutated );
378 if ( ! inst ) return mutated;
379
380 // exit early if no need for further mutation
381 if ( inst->get_parameters().empty() ) return inst;
382
383 // check for an already-instantiatiated dtype-static type
384 if ( dtypeStatics.find( inst->get_baseUnion() ) != dtypeStatics.end() ) {
385 stripInstParams( inst );
386 return inst;
387 }
388
389 // check if type can be concretely instantiated; put substitutions into typeSubs
390 assert( inst->get_baseParameters() && "Base union has parameters" );
391 std::list< TypeExpr* > typeSubs;
392 genericType gt = makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs );
393 switch ( gt ) {
394 case genericType::dtypeStatic:
395 stripDtypeParams( inst->get_baseUnion(), *inst->get_baseParameters(), typeSubs );
396 stripInstParams( inst );
397 break;
398
399 case genericType::concrete:
400 {
401 // make concrete instantiation of generic type
402 UnionDecl *concDecl = lookup( inst, typeSubs );
403 if ( ! concDecl ) {
404 // set concDecl to new type, insert type declaration into statements to add
405 concDecl = new UnionDecl( typeNamer.newName( inst->get_name() ) );
406 concDecl->set_body( inst->get_baseUnion()->has_body() );
407 substituteMembers( inst->get_baseUnion()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
408 DeclMutator::addDeclaration( concDecl );
409 insert( inst, typeSubs, concDecl );
410 }
411 UnionInstType *newInst = new UnionInstType( inst->get_qualifiers(), concDecl->get_name() );
412 newInst->set_baseUnion( concDecl );
413
414 delete inst;
415 inst = newInst;
416 break;
417 }
418 case genericType::dynamic:
419 // do nothing
420 break;
421 }
422
423 deleteAll( typeSubs );
424 return inst;
425 }
426
427 void GenericInstantiator::doBeginScope() {
428 DeclMutator::doBeginScope();
429 instantiations.beginScope();
430 dtypeStatics.beginScope();
431 }
432
433 void GenericInstantiator::doEndScope() {
434 DeclMutator::doEndScope();
435 instantiations.endScope();
436 dtypeStatics.endScope();
437 }
438
439} // namespace GenPoly
440
441// Local Variables: //
442// tab-width: 4 //
443// mode: c++ //
444// compile-command: "make install" //
445// End: //
Note: See TracBrowser for help on using the repository browser.