source: src/GenPoly/InstantiateGeneric.cc@ ee897e4b

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 ee897e4b was 0bfaf80, checked in by Aaron Moss <a3moss@…>, 9 years ago

Generic instantiation accounts for sized dtypes

  • Property mode set to 100644
File size: 16.9 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 using GenPoly::PolyMutator::mutate;
155 virtual Type * mutate( TypeInstType * inst ) override {
156 if ( env ) envMap[inst] = env;
157 return inst;
158 }
159
160 // 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)?
161 virtual Type * mutate( FunctionType * ftype ) override {
162 return ftype;
163 }
164 std::unordered_map< ReferenceToType *, TypeSubstitution * > envMap;
165 };
166
167 /// Mutator pass that replaces concrete instantiations of generic types with actual struct declarations, scoped appropriately
168 class GenericInstantiator final : public DeclMutator {
169 /// Map of (generic type, parameter list) pairs to concrete type instantiations
170 InstantiationMap< AggregateDecl, AggregateDecl > instantiations;
171 /// Set of types which are dtype-only generic (and therefore have static layout)
172 ScopedSet< AggregateDecl* > dtypeStatics;
173 /// Namer for concrete types
174 UniqueName typeNamer;
175 /// Reference to mapping of environments
176 const std::unordered_map< ReferenceToType *, TypeSubstitution * > & envMap;
177 public:
178 GenericInstantiator( const std::unordered_map< ReferenceToType *, TypeSubstitution * > & envMap ) : DeclMutator(), instantiations(), dtypeStatics(), typeNamer("_conc_"), envMap( envMap ) {}
179
180 using DeclMutator::mutate;
181 virtual Type* mutate( StructInstType *inst ) override;
182 virtual Type* mutate( UnionInstType *inst ) override;
183
184 virtual void doBeginScope() override;
185 virtual void doEndScope() override;
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 EnvFinder finder;
205 mutateAll( translationUnit, finder );
206 GenericInstantiator instantiator( finder.envMap );
207 instantiator.mutateDeclarationList( translationUnit );
208 }
209
210 /// Makes substitutions of params into baseParams; returns dtypeStatic if there is a concrete instantiation based only on {d,f}type-to-void conversions,
211 /// concrete if there is a concrete instantiation requiring at least one parameter type, and dynamic if there is no concrete instantiation
212 genericType makeSubstitutions( const std::list< TypeDecl* >& baseParams, const std::list< Expression* >& params, std::list< TypeExpr* >& out ) {
213 genericType gt = genericType::dtypeStatic;
214
215 // substitute concrete types for given parameters, and incomplete types for placeholders
216 std::list< TypeDecl* >::const_iterator baseParam = baseParams.begin();
217 std::list< Expression* >::const_iterator param = params.begin();
218 for ( ; baseParam != baseParams.end() && param != params.end(); ++baseParam, ++param ) {
219 TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
220 assert(paramType && "Aggregate parameters should be type expressions");
221
222 if ( (*baseParam)->isComplete() ) {
223 // substitute parameter for complete (otype or sized dtype) type; makes the struct concrete or dynamic depending on the parameter
224 out.push_back( paramType->clone() );
225 gt |= isPolyType( paramType->get_type() ) ? genericType::dynamic : genericType::concrete;
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;
241 }
242 }
243
244 assert( baseParam == baseParams.end() && param == params.end() && "Type parameters should match type variables" );
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
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
269 /// Strips the instances's type parameters
270 void stripInstParams( ReferenceToType *inst ) {
271 deleteAll( inst->get_parameters() );
272 inst->get_parameters().clear();
273 }
274
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();
280
281 dtypeStatics.insert( base );
282 }
283
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 ) ) {
295 if ( envMap.count( typeInst ) ) {
296 TypeSubstitution * env = envMap.at( typeInst );
297 Type *concrete = env->lookup( typeInst->get_name() );
298 if ( concrete ) {
299 return concrete->clone();
300 }
301 else return typeInst->clone();
302 }
303 } else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
304 if ( doClone ) {
305 structType = structType->clone();
306 }
307 replaceParametersWithConcrete( structType->get_parameters() );
308 return structType;
309 } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
310 if ( doClone ) {
311 unionType = unionType->clone();
312 }
313 replaceParametersWithConcrete( unionType->get_parameters() );
314 return unionType;
315 }
316 return type;
317 }
318
319
320 Type* GenericInstantiator::mutate( StructInstType *inst ) {
321 // mutate subtypes
322 Type *mutated = Mutator::mutate( inst );
323 inst = dynamic_cast< StructInstType* >( mutated );
324 if ( ! inst ) return mutated;
325
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 DeclMutator::addDeclaration( concDecl );
357 insert( inst, typeSubs, concDecl );
358 }
359 StructInstType *newInst = new StructInstType( inst->get_qualifiers(), concDecl->get_name() );
360 newInst->set_baseStruct( concDecl );
361
362 delete inst;
363 inst = newInst;
364 break;
365 }
366
367 case genericType::dynamic:
368 // do nothing
369 break;
370 }
371
372 deleteAll( typeSubs );
373 return inst;
374 }
375
376 Type* GenericInstantiator::mutate( UnionInstType *inst ) {
377 // mutate subtypes
378 Type *mutated = Mutator::mutate( inst );
379 inst = dynamic_cast< UnionInstType* >( mutated );
380 if ( ! inst ) return mutated;
381
382 // exit early if no need for further mutation
383 if ( inst->get_parameters().empty() ) return inst;
384
385 // check for an already-instantiatiated dtype-static type
386 if ( dtypeStatics.find( inst->get_baseUnion() ) != dtypeStatics.end() ) {
387 stripInstParams( inst );
388 return inst;
389 }
390
391 // check if type can be concretely instantiated; put substitutions into typeSubs
392 assert( inst->get_baseParameters() && "Base union has parameters" );
393 std::list< TypeExpr* > typeSubs;
394 genericType gt = makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs );
395 switch ( gt ) {
396 case genericType::dtypeStatic:
397 stripDtypeParams( inst->get_baseUnion(), *inst->get_baseParameters(), typeSubs );
398 stripInstParams( inst );
399 break;
400
401 case genericType::concrete:
402 {
403 // make concrete instantiation of generic type
404 UnionDecl *concDecl = lookup( inst, typeSubs );
405 if ( ! concDecl ) {
406 // set concDecl to new type, insert type declaration into statements to add
407 concDecl = new UnionDecl( typeNamer.newName( inst->get_name() ) );
408 concDecl->set_body( inst->get_baseUnion()->has_body() );
409 substituteMembers( inst->get_baseUnion()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
410 DeclMutator::addDeclaration( concDecl );
411 insert( inst, typeSubs, concDecl );
412 }
413 UnionInstType *newInst = new UnionInstType( inst->get_qualifiers(), concDecl->get_name() );
414 newInst->set_baseUnion( concDecl );
415
416 delete inst;
417 inst = newInst;
418 break;
419 }
420 case genericType::dynamic:
421 // do nothing
422 break;
423 }
424
425 deleteAll( typeSubs );
426 return inst;
427 }
428
429 void GenericInstantiator::doBeginScope() {
430 DeclMutator::doBeginScope();
431 instantiations.beginScope();
432 dtypeStatics.beginScope();
433 }
434
435 void GenericInstantiator::doEndScope() {
436 DeclMutator::doEndScope();
437 instantiations.endScope();
438 dtypeStatics.endScope();
439 }
440
441} // namespace GenPoly
442
443// Local Variables: //
444// tab-width: 4 //
445// mode: c++ //
446// compile-command: "make install" //
447// End: //
Note: See TracBrowser for help on using the repository browser.