source: src/GenPoly/GenPoly.cpp@ 26ee4b5

Last change on this file since 26ee4b5 was f9ad69d, checked in by Michael Brooks <mlbrooks@…>, 14 months ago

Fix #175

  • Property mode set to 100644
File size: 16.7 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 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// GenPoly.cpp -- General GenPoly utilities.
8//
9// Author : Richard C. Bilson
10// Created On : Mon May 18 07:44:20 2015
11// Last Modified By : Andrew Beach
12// Last Modified On : Mon Oct 24 15:19:00 2022
13// Update Count : 17
14//
15
16#include "GenPoly.hpp"
17
18#include <cassert> // for assertf, assert
19#include <iostream> // for operator<<, ostream, basic_...
20#include <iterator> // for back_insert_iterator, back_...
21#include <list> // for list, _List_iterator, list<...
22#include <typeindex> // for type_index
23#include <utility> // for pair
24#include <vector> // for vector
25
26#include "AST/Expr.hpp"
27#include "AST/Type.hpp"
28#include "AST/TypeSubstitution.hpp"
29#include "Common/Eval.hpp" // for eval
30#include "GenPoly/ErasableScopedMap.hpp" // for ErasableScopedMap<>::const_...
31#include "ResolvExpr/Typeops.hpp" // for flatten
32
33using namespace std;
34
35namespace GenPoly {
36
37namespace {
38 /// Checks a parameter list for polymorphic parameters; will substitute according to env if present.
39 bool hasPolyParams( const std::vector<ast::ptr<ast::Expr>> & params, const ast::TypeSubstitution * env ) {
40 for ( auto & param : params ) {
41 auto paramType = param.as<ast::TypeExpr>();
42 assertf( paramType, "Aggregate parameters should be type expressions" );
43 if ( isPolyType( paramType->type, env ) ) return true;
44 }
45 return false;
46 }
47
48 /// Checks a parameter list for polymorphic parameters from typeVars; will substitute according to env if present.
49 bool hasPolyParams( const std::vector<ast::ptr<ast::Expr>> & params, const TypeVarMap & typeVars, const ast::TypeSubstitution * env ) {
50 for ( auto & param : params ) {
51 auto paramType = param.as<ast::TypeExpr>();
52 assertf( paramType, "Aggregate parameters should be type expressions" );
53 if ( isPolyType( paramType->type, typeVars, env ) ) return true;
54 }
55 return false;
56 }
57
58 /// Checks a parameter list for dynamic-layout parameters from tyVars; will substitute according to env if present.
59 bool hasDynParams(
60 const std::vector<ast::ptr<ast::Expr>> & params,
61 const TypeVarMap & typeVars,
62 const ast::TypeSubstitution * subst ) {
63 for ( ast::ptr<ast::Expr> const & paramExpr : params ) {
64 auto param = paramExpr.as<ast::TypeExpr>();
65 assertf( param, "Aggregate parameters should be type expressions." );
66 if ( isDynType( param->type.get(), typeVars, subst ) ) {
67 return true;
68 }
69 }
70 return false;
71 }
72} // namespace
73
74const ast::Type * replaceTypeInst( const ast::Type * type, const ast::TypeSubstitution * env ) {
75 if ( !env ) return type;
76 if ( auto typeInst = dynamic_cast<const ast::TypeInstType*>( type ) ) {
77 if ( auto newType = env->lookup( typeInst ) ) return newType;
78 }
79 return type;
80}
81
82const ast::Type * isPolyType( const ast::Type * type, const ast::TypeSubstitution * subst ) {
83 type = replaceTypeInst( type, subst );
84
85 if ( dynamic_cast< const ast::TypeInstType * >( type ) ) {
86 // This case is where the two variants of isPolyType differ.
87 return type;
88 } else if ( auto arrayType = dynamic_cast< const ast::ArrayType * >( type ) ) {
89 return isPolyType( arrayType->base, subst );
90 } else if ( auto structType = dynamic_cast< const ast::StructInstType* >( type ) ) {
91 if ( hasPolyParams( structType->params, subst ) ) return type;
92 } else if ( auto unionType = dynamic_cast< const ast::UnionInstType* >( type ) ) {
93 if ( hasPolyParams( unionType->params, subst ) ) return type;
94 }
95 return nullptr;
96}
97
98const ast::Type * isPolyType( const ast::Type * type,
99 const TypeVarMap & typeVars, const ast::TypeSubstitution * subst ) {
100 type = replaceTypeInst( type, subst );
101
102 if ( auto inst = dynamic_cast< const ast::TypeInstType * >( type ) ) {
103 if ( typeVars.contains( *inst ) ) return type;
104 } else if ( auto array = dynamic_cast< const ast::ArrayType * >( type ) ) {
105 return isPolyType( array->base, typeVars, subst );
106 } else if ( auto sue = dynamic_cast< const ast::StructInstType * >( type ) ) {
107 if ( hasPolyParams( sue->params, typeVars, subst ) ) return type;
108 } else if ( auto sue = dynamic_cast< const ast::UnionInstType * >( type ) ) {
109 if ( hasPolyParams( sue->params, typeVars, subst ) ) return type;
110 }
111 return nullptr;
112}
113
114const ast::BaseInstType * isDynType(
115 const ast::Type * type, const TypeVarMap & typeVars,
116 const ast::TypeSubstitution * subst ) {
117 type = replaceTypeInst( type, subst );
118
119 if ( auto inst = dynamic_cast<ast::TypeInstType const *>( type ) ) {
120 auto var = typeVars.find( *inst );
121 if ( var != typeVars.end() && var->second.isComplete ) {
122 return inst;
123 }
124 } else if ( auto inst = dynamic_cast<ast::StructInstType const *>( type ) ) {
125 if ( hasDynParams( inst->params, typeVars, subst ) ) return inst;
126 } else if ( auto inst = dynamic_cast<ast::UnionInstType const *>( type ) ) {
127 if ( hasDynParams( inst->params, typeVars, subst ) ) return inst;
128 }
129 return nullptr;
130}
131
132const ast::BaseInstType *isDynRet(
133 const ast::FunctionType * type, const TypeVarMap & typeVars ) {
134 if ( type->returns.empty() ) return nullptr;
135
136 return isDynType( type->returns.front(), typeVars );
137}
138
139const ast::BaseInstType *isDynRet( const ast::FunctionType * func ) {
140 if ( func->returns.empty() ) return nullptr;
141
142 TypeVarMap forallTypes;
143 makeTypeVarMap( func, forallTypes );
144 return isDynType( func->returns.front(), forallTypes );
145}
146
147bool needsAdapter(
148 ast::FunctionType const * adaptee, const TypeVarMap & typeVars ) {
149 if ( isDynRet( adaptee, typeVars ) ) return true;
150
151 for ( auto param : adaptee->params ) {
152 if ( isDynType( param, typeVars ) ) {
153 return true;
154 }
155 }
156 return false;
157}
158
159const ast::Type * isPolyPtr(
160 const ast::Type * type, const TypeVarMap & typeVars,
161 const ast::TypeSubstitution * typeSubs ) {
162 type = replaceTypeInst( type, typeSubs );
163
164 if ( auto * ptr = dynamic_cast<ast::PointerType const *>( type ) ) {
165 return isPolyType( ptr->base, typeVars, typeSubs );
166 }
167 return nullptr;
168}
169
170ast::Type const * hasPolyBase(
171 ast::Type const * type, const TypeVarMap & typeVars,
172 int * levels, const ast::TypeSubstitution * subst ) {
173 int level_count = 0;
174
175 while ( true ) {
176 type = replaceTypeInst( type, subst );
177
178 if ( auto ptr = dynamic_cast<ast::PointerType const *>( type ) ) {
179 type = ptr->base;
180 ++level_count;
181 } else {
182 break;
183 }
184 }
185
186 if ( nullptr != levels ) { *levels = level_count; }
187 return isPolyType( type, typeVars, subst );
188}
189
190const ast::FunctionType * getFunctionType( const ast::Type * ty ) {
191 if ( auto pty = dynamic_cast< const ast::PointerType * >( ty ) ) {
192 return pty->base.as< ast::FunctionType >();
193 } else {
194 return dynamic_cast< const ast::FunctionType * >( ty );
195 }
196}
197
198namespace {
199 /// Checks if is a pointer to D
200 template<typename D, typename B>
201 bool is( const B* p ) { return type_index{typeid(D)} == type_index{typeid(*p)}; }
202
203 /// Converts to a pointer to D without checking for safety
204 template<typename D, typename B>
205 inline D* as( B* p ) { return reinterpret_cast<D*>(p); }
206
207 template<typename D, typename B>
208 inline D const * as( B const * p ) {
209 return reinterpret_cast<D const *>( p );
210 }
211
212 /// Flattens a list of types.
213 void flattenList( vector<ast::ptr<ast::Type>> const & src,
214 vector<ast::ptr<ast::Type>> & out ) {
215 for ( auto const & type : src ) {
216 ResolvExpr::flatten( type, out );
217 }
218 }
219
220 bool paramListsPolyCompatible(
221 std::vector<ast::ptr<ast::Expr>> const & lparams,
222 std::vector<ast::ptr<ast::Expr>> const & rparams ) {
223 if ( lparams.size() != rparams.size() ) {
224 return false;
225 }
226
227 for ( auto lparam = lparams.begin(), rparam = rparams.begin() ;
228 lparam != lparams.end() ; ++lparam, ++rparam ) {
229 ast::TypeExpr const * lexpr = lparam->as<ast::TypeExpr>();
230 assertf( lexpr, "Aggregate parameters should be type expressions" );
231 ast::TypeExpr const * rexpr = rparam->as<ast::TypeExpr>();
232 assertf( rexpr, "Aggregate parameters should be type expressions" );
233
234 // xxx - might need to let VoidType be a wildcard here too; could have some voids
235 // stuffed in for dtype-statics.
236 // if ( is<VoidType>( lexpr->type() ) || is<VoidType>( bparam->get_type() ) ) continue;
237 if ( !typesPolyCompatible( lexpr->type, rexpr->type ) ) {
238 return false;
239 }
240 }
241
242 return true;
243 }
244} // namespace
245
246// This function, and its helpers following, have logic duplicated from
247// unification. The difference in context is that unification applies where
248// the types "must" match, while this variation applies to arbitrary type
249// pairs, when an optimization could apply if they happen to match. This
250// variation does not bind type variables. The helper functions support
251// the case for matching ArrayType.
252bool typesPolyCompatible( ast::Type const * lhs, ast::Type const * rhs );
253
254static bool exprsPolyCompatibleByStaticValue(
255 const ast::Expr * e1, const ast::Expr * e2 ) {
256 Evaluation r1 = eval(e1);
257 Evaluation r2 = eval(e2);
258
259 if ( !r1.hasKnownValue ) return false;
260 if ( !r2.hasKnownValue ) return false;
261
262 if ( r1.knownValue != r2.knownValue ) return false;
263
264 return true;
265}
266
267static bool exprsPolyCompatible( ast::Expr const * lhs,
268 ast::Expr const * rhs ) {
269 type_index const lid = typeid(*lhs);
270 type_index const rid = typeid(*rhs);
271 if ( lid != rid ) return false;
272
273 if ( exprsPolyCompatibleByStaticValue( lhs, rhs ) ) return true;
274
275 if ( type_index(typeid(ast::CastExpr)) == lid ) {
276 ast::CastExpr const * l = as<ast::CastExpr>(lhs);
277 ast::CastExpr const * r = as<ast::CastExpr>(rhs);
278
279 // inspect casts' target types
280 if ( !typesPolyCompatible(
281 l->result, r->result ) ) return false;
282
283 // inspect casts' inner expressions
284 return exprsPolyCompatible( l->arg, r->arg );
285
286 } else if ( type_index(typeid(ast::VariableExpr)) == lid ) {
287 ast::VariableExpr const * l = as<ast::VariableExpr>(lhs);
288 ast::VariableExpr const * r = as<ast::VariableExpr>(rhs);
289
290 assert(l->var);
291 assert(r->var);
292
293 // conservative: variable exprs match if their declarations are
294 // represented by the same C++ AST object
295 return (l->var == r->var);
296
297 } else if ( type_index(typeid(ast::SizeofExpr)) == lid ) {
298 ast::SizeofExpr const * l = as<ast::SizeofExpr>(lhs);
299 ast::SizeofExpr const * r = as<ast::SizeofExpr>(rhs);
300
301 assert((l->type != nullptr) ^ (l->expr != nullptr));
302 assert((r->type != nullptr) ^ (r->expr != nullptr));
303 if ( !(l->type && r->type) ) return false;
304
305 // mutual recursion with type poly compatibility
306 return typesPolyCompatible( l->type, r->type );
307
308 } else {
309 // All other forms compare on static value only, done earlier
310 return false;
311 }
312}
313
314bool typesPolyCompatible( ast::Type const * lhs, ast::Type const * rhs ) {
315 type_index const lid = typeid(*lhs);
316
317 // Polymorphic types always match:
318 if ( type_index(typeid(ast::TypeInstType)) == lid ) return true;
319
320 type_index const rid = typeid(*rhs);
321 if ( type_index(typeid(ast::TypeInstType)) == rid ) return true;
322
323 // All other types only match if they are the same type:
324 if ( lid != rid ) return false;
325
326 // So remaining types can be examined case by case.
327 // Recurse through type structure (conditions duplicated from Unify.cpp).
328
329 if ( type_index(typeid(ast::BasicType)) == lid ) {
330 return as<ast::BasicType>(lhs)->kind == as<ast::BasicType>(rhs)->kind;
331 } else if ( type_index(typeid(ast::PointerType)) == lid ) {
332 ast::PointerType const * l = as<ast::PointerType>(lhs);
333 ast::PointerType const * r = as<ast::PointerType>(rhs);
334
335 // void pointers should match any other pointer type.
336 return is<ast::VoidType>( l->base.get() )
337 || is<ast::VoidType>( r->base.get() )
338 || typesPolyCompatible( l->base.get(), r->base.get() );
339 } else if ( type_index(typeid(ast::ReferenceType)) == lid ) {
340 ast::ReferenceType const * l = as<ast::ReferenceType>(lhs);
341 ast::ReferenceType const * r = as<ast::ReferenceType>(rhs);
342
343 // void references should match any other reference type.
344 return is<ast::VoidType>( l->base.get() )
345 || is<ast::VoidType>( r->base.get() )
346 || typesPolyCompatible( l->base.get(), r->base.get() );
347 } else if ( type_index(typeid(ast::ArrayType)) == lid ) {
348 ast::ArrayType const * l = as<ast::ArrayType>(lhs);
349 ast::ArrayType const * r = as<ast::ArrayType>(rhs);
350
351 if ( l->isVarLen != r->isVarLen ) return false;
352 if ( (l->dimension != nullptr) != (r->dimension != nullptr) )
353 return false;
354
355 if ( l->dimension ) {
356 assert( r->dimension );
357 // mutual recursion with expression poly compatibility
358 if ( !exprsPolyCompatible(l->dimension, r->dimension) )
359 return false;
360 }
361
362 return typesPolyCompatible( l->base.get(), r->base.get() );
363 } else if ( type_index(typeid(ast::FunctionType)) == lid ) {
364 ast::FunctionType const * l = as<ast::FunctionType>(lhs);
365 ast::FunctionType const * r = as<ast::FunctionType>(rhs);
366
367 std::vector<ast::ptr<ast::Type>> lparams, rparams;
368 flattenList( l->params, lparams );
369 flattenList( r->params, rparams );
370 if ( lparams.size() != rparams.size() ) return false;
371 for ( unsigned i = 0; i < lparams.size(); ++i ) {
372 if ( !typesPolyCompatible( lparams[i], rparams[i] ) ) return false;
373 }
374
375 std::vector<ast::ptr<ast::Type>> lrets, rrets;
376 flattenList( l->returns, lrets );
377 flattenList( r->returns, rrets );
378 if ( lrets.size() != rrets.size() ) return false;
379 for ( unsigned i = 0; i < lrets.size(); ++i ) {
380 if ( !typesPolyCompatible( lrets[i], rrets[i] ) ) return false;
381 }
382 return true;
383 } else if ( type_index(typeid(ast::StructInstType)) == lid ) {
384 ast::StructInstType const * l = as<ast::StructInstType>(lhs);
385 ast::StructInstType const * r = as<ast::StructInstType>(rhs);
386
387 if ( l->name != r->name ) return false;
388 return paramListsPolyCompatible( l->params, r->params );
389 } else if ( type_index(typeid(ast::UnionInstType)) == lid ) {
390 ast::UnionInstType const * l = as<ast::UnionInstType>(lhs);
391 ast::UnionInstType const * r = as<ast::UnionInstType>(rhs);
392
393 if ( l->name != r->name ) return false;
394 return paramListsPolyCompatible( l->params, r->params );
395 } else if ( type_index(typeid(ast::EnumInstType)) == lid ) {
396 ast::EnumInstType const * l = as<ast::EnumInstType>(lhs);
397 ast::EnumInstType const * r = as<ast::EnumInstType>(rhs);
398
399 return l->name == r->name;
400 } else if ( type_index(typeid(ast::TraitInstType)) == lid ) {
401 ast::TraitInstType const * l = as<ast::TraitInstType>(lhs);
402 ast::TraitInstType const * r = as<ast::TraitInstType>(rhs);
403
404 return l->name == r->name;
405 } else if ( type_index(typeid(ast::TupleType)) == lid ) {
406 ast::TupleType const * l = as<ast::TupleType>(lhs);
407 ast::TupleType const * r = as<ast::TupleType>(rhs);
408
409 std::vector<ast::ptr<ast::Type>> ltypes, rtypes;
410 flattenList( l->types, ( ltypes ) );
411 flattenList( r->types, ( rtypes ) );
412 if ( ltypes.size() != rtypes.size() ) return false;
413
414 for ( unsigned i = 0 ; i < ltypes.size() ; ++i ) {
415 if ( !typesPolyCompatible( ltypes[i], rtypes[i] ) ) return false;
416 }
417 return true;
418 // The remaining types (VoidType, VarArgsType, ZeroType & OneType)
419 // have no variation so will always be equal.
420 } else {
421 return true;
422 }
423}
424
425bool needsBoxing( const ast::Type * param, const ast::Type * arg,
426 const TypeVarMap & typeVars, const ast::TypeSubstitution * subst ) {
427 // Don't need to box if the parameter is not polymorphic.
428 if ( !isPolyType( param, typeVars ) ) return false;
429
430 ast::ptr<ast::Type> newType = arg;
431 if ( subst ) {
432 int count = subst->apply( newType );
433 (void)count;
434 }
435 // Only need to box if the argument is not also polymorphic.
436 return !isPolyType( newType );
437}
438
439bool needsBoxing(
440 const ast::Type * param, const ast::Type * arg,
441 const ast::ApplicationExpr * expr,
442 const ast::TypeSubstitution * subst ) {
443 const ast::FunctionType * function = getFunctionType( expr->func->result );
444 assertf( function, "ApplicationExpr has non-function type: %s", toCString( expr->func->result ) );
445 TypeVarMap exprTyVars;
446 makeTypeVarMap( function, exprTyVars );
447 return needsBoxing( param, arg, exprTyVars, subst );
448}
449
450void addToTypeVarMap( const ast::TypeDecl * decl, TypeVarMap & typeVars ) {
451 typeVars.insert( ast::TypeEnvKey( decl, 0, 0 ), ast::TypeData( decl ) );
452}
453
454void addToTypeVarMap( const ast::TypeInstType * type, TypeVarMap & typeVars ) {
455 typeVars.insert( ast::TypeEnvKey( *type ), ast::TypeData( type->base ) );
456}
457
458void makeTypeVarMap( const ast::Type * type, TypeVarMap & typeVars ) {
459 if ( auto func = dynamic_cast<ast::FunctionType const *>( type ) ) {
460 for ( auto & typeVar : func->forall ) {
461 assert( typeVar );
462 addToTypeVarMap( typeVar, typeVars );
463 }
464 }
465 if ( auto pointer = dynamic_cast<ast::PointerType const *>( type ) ) {
466 makeTypeVarMap( pointer->base, typeVars );
467 }
468}
469
470void makeTypeVarMap( const ast::FunctionDecl * decl, TypeVarMap & typeVars ) {
471 for ( auto & typeDecl : decl->type_params ) {
472 addToTypeVarMap( typeDecl, typeVars );
473 }
474}
475
476} // namespace GenPoly
477
478// Local Variables: //
479// tab-width: 4 //
480// mode: c++ //
481// compile-command: "make install" //
482// End: //
Note: See TracBrowser for help on using the repository browser.