source: src/GenPoly/Box.cc@ 41a2620

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors ctor deferred_resn demangler enum forall-pointer-decay gc_noraii jacob/cs343-translation jenkins-sandbox memory new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new string with_gc
Last change on this file since 41a2620 was 4318107, checked in by Aaron Moss <a3moss@…>, 10 years ago

Fix member expressions for polymorphic generic types where the member has pointer type

  • Property mode set to 100644
File size: 68.3 KB
RevLine 
[51587aa]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//
[ae63a18]7// Box.cc --
[51587aa]8//
9// Author : Richard C. Bilson
10// Created On : Mon May 18 07:44:20 2015
[bd85400]11// Last Modified By : Peter A. Buhr
12// Last Modified On : Fri Feb 5 16:45:07 2016
13// Update Count : 286
[51587aa]14//
[51b73452]15
16#include <set>
[b1a6d6b]17#include <stack>
[51b73452]18#include <string>
19#include <iterator>
20#include <algorithm>
21#include <cassert>
22
23#include "Box.h"
[05d47278]24#include "InstantiateGeneric.h"
[51b73452]25#include "PolyMutator.h"
26#include "FindFunction.h"
[1194734]27#include "ScopedMap.h"
[51b73452]28#include "ScrubTyVars.h"
29
[68cd1ce]30#include "Parser/ParseNode.h"
31
[cdec5af]32#include "SynTree/Constant.h"
[51b73452]33#include "SynTree/Type.h"
34#include "SynTree/Expression.h"
35#include "SynTree/Initializer.h"
36#include "SynTree/Statement.h"
37#include "SynTree/Mutator.h"
[68cd1ce]38
[51b73452]39#include "ResolvExpr/TypeEnvironment.h"
[68cd1ce]40
[51b73452]41#include "SymTab/Mangler.h"
42
[d3b7937]43#include "Common/SemanticError.h"
44#include "Common/UniqueName.h"
45#include "Common/utility.h"
[51b73452]46
47#include <ext/functional> // temporary
48
49namespace GenPoly {
[01aeade]50 namespace {
51 const std::list<Label> noLabels;
52
[e56cfdb0]53 FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars );
54
[f8b961b]55 /// Replaces polymorphic return types with out-parameters, replaces calls to polymorphic functions with adapter calls as needed, and adds appropriate type variables to the function call
[01aeade]56 class Pass1 : public PolyMutator {
57 public:
58 Pass1();
59 virtual Expression *mutate( ApplicationExpr *appExpr );
60 virtual Expression *mutate( AddressExpr *addrExpr );
61 virtual Expression *mutate( UntypedExpr *expr );
62 virtual DeclarationWithType* mutate( FunctionDecl *functionDecl );
63 virtual TypeDecl *mutate( TypeDecl *typeDecl );
64 virtual Expression *mutate( CommaExpr *commaExpr );
65 virtual Expression *mutate( ConditionalExpr *condExpr );
[cf16f94]66 virtual Statement * mutate( ReturnStmt *returnStmt );
[01aeade]67 virtual Type *mutate( PointerType *pointerType );
[cf16f94]68 virtual Type * mutate( FunctionType *functionType );
[ae63a18]69
[01aeade]70 virtual void doBeginScope();
71 virtual void doEndScope();
72 private:
[05d47278]73 /// Makes a new temporary array holding the offsets of the fields of `type`, and returns a new variable expression referencing it
74 Expression *makeOffsetArray( StructInstType *type );
[5c52b06]75 /// Pass the extra type parameters from polymorphic generic arguments or return types into a function application
76 void passArgTypeVars( ApplicationExpr *appExpr, Type *parmType, Type *argBaseType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars, std::set< std::string > &seenTypes );
[05d47278]77 /// passes extra type parameters into a polymorphic function application
[5c52b06]78 void passTypeVars( ApplicationExpr *appExpr, ReferenceToType *polyRetType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
[48ca586]79 /// wraps a function application with a new temporary for the out-parameter return value
[01aeade]80 Expression *addRetParam( ApplicationExpr *appExpr, FunctionType *function, Type *retType, std::list< Expression *>::iterator &arg );
[48ca586]81 /// Replaces all the type parameters of a generic type with their concrete equivalents under the current environment
82 void replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params );
83 /// Replaces a polymorphic type with its concrete equivalant under the current environment (returns itself if concrete).
84 /// If `doClone` is set to false, will not clone interior types
85 Type *replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone = true );
86 /// wraps a function application returning a polymorphic type with a new temporary for the out-parameter return value
87 Expression *addPolyRetParam( ApplicationExpr *appExpr, FunctionType *function, ReferenceToType *polyType, std::list< Expression *>::iterator &arg );
[01aeade]88 Expression *applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
89 void boxParam( Type *formal, Expression *&arg, const TyVarMap &exprTyVars );
90 void boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
91 void addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars );
[1194734]92 /// Stores assignment operators from assertion list in local map of assignment operations
[01aeade]93 void findAssignOps( const std::list< TypeDecl *> &forall );
94 void passAdapters( ApplicationExpr *appExpr, FunctionType *functionType, const TyVarMap &exprTyVars );
95 FunctionDecl *makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars );
[05d47278]96 /// Replaces intrinsic operator functions with their arithmetic desugaring
[01aeade]97 Expression *handleIntrinsics( ApplicationExpr *appExpr );
[05d47278]98 /// Inserts a new temporary variable into the current scope with an auto-generated name
[01aeade]99 ObjectDecl *makeTemporary( Type *type );
[c29d9ce]100
[e56cfdb0]101 typedef std::map< std::string, DeclarationWithType *> AdapterMap;
[c29d9ce]102 std::map< std::string, DeclarationWithType *> assignOps;
[1194734]103 ScopedMap< std::string, DeclarationWithType *> scopedAssignOps;
[01aeade]104 std::stack< AdapterMap > adapters;
105 DeclarationWithType *retval;
106 bool useRetval;
107 UniqueName tempNamer;
108 };
109
[f8b961b]110 /// Moves polymorphic returns in function types to pointer-type parameters, adds type size and assertion parameters to parameter lists as well
[01aeade]111 class Pass2 : public PolyMutator {
112 public:
113 template< typename DeclClass >
114 DeclClass *handleDecl( DeclClass *decl, Type *type );
115 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
116 virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
117 virtual TypeDecl *mutate( TypeDecl *typeDecl );
118 virtual TypedefDecl *mutate( TypedefDecl *typedefDecl );
119 virtual Type *mutate( PointerType *pointerType );
120 virtual Type *mutate( FunctionType *funcType );
121 private:
122 void addAdapters( FunctionType *functionType );
[ae63a18]123
[01aeade]124 std::map< UniqueId, std::string > adapterName;
125 };
126
[2a4b088]127 /// Replaces member expressions for polymorphic types with calculated add-field-offset-and-dereference;
128 /// also fixes offsetof expressions.
[05d47278]129 class MemberExprFixer : public PolyMutator {
130 public:
131 template< typename DeclClass >
132 DeclClass *handleDecl( DeclClass *decl, Type *type );
133 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
134 virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
135 virtual TypedefDecl *mutate( TypedefDecl *objectDecl );
136 virtual TypeDecl *mutate( TypeDecl *objectDecl );
137 virtual Statement *mutate( DeclStmt *declStmt );
138 virtual Type *mutate( PointerType *pointerType );
139 virtual Type *mutate( FunctionType *funcType );
140 virtual Expression *mutate( MemberExpr *memberExpr );
[2a4b088]141 virtual Expression *mutate( OffsetofExpr *offsetofExpr );
[05d47278]142 };
[b4cd03b7]143
[f8b961b]144 /// Replaces initialization of polymorphic values with alloca, declaration of dtype/ftype with appropriate void expression, and sizeof expressions of polymorphic types with the proper variable
[01aeade]145 class Pass3 : public PolyMutator {
146 public:
147 template< typename DeclClass >
148 DeclClass *handleDecl( DeclClass *decl, Type *type );
149 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
150 virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
151 virtual TypedefDecl *mutate( TypedefDecl *objectDecl );
152 virtual TypeDecl *mutate( TypeDecl *objectDecl );
153 virtual Type *mutate( PointerType *pointerType );
154 virtual Type *mutate( FunctionType *funcType );
155 private:
156 };
157
158 } // anonymous namespace
159
160 void printAllNotBuiltin( const std::list< Declaration *>& translationUnit, std::ostream &os ) {
161 for ( std::list< Declaration *>::const_iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
162 if ( ! LinkageSpec::isBuiltin( (*i)->get_linkage() ) ) {
163 (*i)->print( os );
164 os << std::endl;
[6c3744e]165 } // if
[01aeade]166 } // for
[6c3744e]167 }
168
[05d47278]169 /// version of mutateAll with special handling for translation unit so you can check the end of the prelude when debugging
170 template< typename MutatorType >
171 inline void mutateTranslationUnit( std::list< Declaration* > &translationUnit, MutatorType &mutator ) {
172 bool seenIntrinsic = false;
173 SemanticError errors;
174 for ( typename std::list< Declaration* >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
175 try {
176 if ( *i ) {
177 if ( (*i)->get_linkage() == LinkageSpec::Intrinsic ) {
178 seenIntrinsic = true;
179 } else if ( seenIntrinsic ) {
180 seenIntrinsic = false; // break on this line when debugging for end of prelude
181 }
[b4cd03b7]182
[05d47278]183 *i = dynamic_cast< Declaration* >( (*i)->acceptMutator( mutator ) );
184 assert( *i );
185 } // if
186 } catch( SemanticError &e ) {
187 errors.append( e );
188 } // try
189 } // for
190 if ( ! errors.isEmpty() ) {
191 throw errors;
192 } // if
193 }
194
[01aeade]195 void box( std::list< Declaration *>& translationUnit ) {
196 Pass1 pass1;
197 Pass2 pass2;
[05d47278]198 MemberExprFixer memberFixer;
[01aeade]199 Pass3 pass3;
[05d47278]200 mutateTranslationUnit/*All*/( translationUnit, pass1 );
201 mutateTranslationUnit/*All*/( translationUnit, pass2 );
202 instantiateGeneric( translationUnit );
203 mutateTranslationUnit/*All*/( translationUnit, memberFixer );
204 mutateTranslationUnit/*All*/( translationUnit, pass3 );
[6c3744e]205 }
206
[01aeade]207 ////////////////////////////////////////// Pass1 ////////////////////////////////////////////////////
208
209 namespace {
[bdf1954]210 std::string makePolyMonoSuffix( FunctionType * function, const TyVarMap &tyVars ) {
211 std::stringstream name;
212
[ed1065c]213 // NOTE: this function previously used isPolyObj, which failed to produce
214 // the correct thing in some situations. It's not clear to me why this wasn't working.
215
[ae63a18]216 // if the return type or a parameter type involved polymorphic types, then the adapter will need
217 // to take those polymorphic types as pointers. Therefore, there can be two different functions
[bdf1954]218 // with the same mangled name, so we need to further mangle the names.
[ed1065c]219 for ( std::list< DeclarationWithType *>::iterator retval = function->get_returnVals().begin(); retval != function->get_returnVals().end(); ++retval ) {
[ffad73a]220 if ( isPolyType( (*retval)->get_type(), tyVars ) ) {
[ed1065c]221 name << "P";
222 } else {
223 name << "M";
224 }
[bdf1954]225 }
226 name << "_";
227 std::list< DeclarationWithType *> &paramList = function->get_parameters();
228 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
[ffad73a]229 if ( isPolyType( (*arg)->get_type(), tyVars ) ) {
[bdf1954]230 name << "P";
231 } else {
[ae63a18]232 name << "M";
[bdf1954]233 }
234 } // for
235 return name.str();
236 }
237
238 std::string mangleAdapterName( FunctionType * function, const TyVarMap &tyVars ) {
239 return SymTab::Mangler::mangle( function ) + makePolyMonoSuffix( function, tyVars );
240 }
241
[01aeade]242 std::string makeAdapterName( const std::string &mangleName ) {
243 return "_adapter" + mangleName;
244 }
[6c3744e]245
[56fcd77]246 Pass1::Pass1() : useRetval( false ), tempNamer( "_temp" ) {
[e56cfdb0]247 adapters.push(AdapterMap());
[01aeade]248 }
249
[1194734]250 /// returns T if the given declaration is: (*?=?)(T *, T) for some T (return not checked, but maybe should be), NULL otherwise
251 ReferenceToType *isAssignment( DeclarationWithType *decl ) {
[01aeade]252 if ( decl->get_name() == "?=?" ) {
[1194734]253 if ( FunctionType *funType = getFunctionType( decl->get_type() ) ) {
254 if ( funType->get_parameters().size() == 2 ) {
255 if ( PointerType *pointer = dynamic_cast< PointerType *>( funType->get_parameters().front()->get_type() ) ) {
256 if ( ReferenceToType *refType = dynamic_cast< ReferenceToType *>( pointer->get_base() ) ) {
257 if ( ReferenceToType *refType2 = dynamic_cast< ReferenceToType *>( funType->get_parameters().back()->get_type() ) ) {
258 if ( refType->get_name() == refType2->get_name() ) {
259 return refType;
[cf16f94]260 } // if
[01aeade]261 } // if
262 } // if
263 } // if
264 } // if
265 } // if
266 } // if
[1194734]267 return 0;
[01aeade]268 }
269
270 void Pass1::findAssignOps( const std::list< TypeDecl *> &forall ) {
[ed1065c]271 // what if a nested function uses an assignment operator?
272 // assignOps.clear();
[01aeade]273 for ( std::list< TypeDecl *>::const_iterator i = forall.begin(); i != forall.end(); ++i ) {
274 for ( std::list< DeclarationWithType *>::const_iterator assert = (*i)->get_assertions().begin(); assert != (*i)->get_assertions().end(); ++assert ) {
275 std::string typeName;
[1194734]276 if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( isAssignment( *assert ) ) ) {
277 assignOps[ typeInst->get_name() ] = *assert;
[01aeade]278 } // if
279 } // for
280 } // for
281 }
282
[82dd287]283 DeclarationWithType *Pass1::mutate( FunctionDecl *functionDecl ) {
[1194734]284 // if this is a polymorphic assignment function, put it in the map for this scope
285 if ( ReferenceToType *refType = isAssignment( functionDecl ) ) {
286 if ( ! dynamic_cast< TypeInstType* >( refType ) ) {
287 scopedAssignOps.insert( refType->get_name(), functionDecl );
288 }
289 }
[b4cd03b7]290
[e56cfdb0]291 if ( functionDecl->get_statements() ) { // empty routine body ?
292 doBeginScope();
[01aeade]293 TyVarMap oldtyVars = scopeTyVars;
[ed1065c]294 std::map< std::string, DeclarationWithType *> oldassignOps = assignOps;
[01aeade]295 DeclarationWithType *oldRetval = retval;
296 bool oldUseRetval = useRetval;
[e56cfdb0]297
298 // process polymorphic return value
[01aeade]299 retval = 0;
[aadc9a4]300 if ( isPolyRet( functionDecl->get_functionType() ) && functionDecl->get_linkage() == LinkageSpec::Cforall ) {
[01aeade]301 retval = functionDecl->get_functionType()->get_returnVals().front();
[ae63a18]302
[01aeade]303 // give names to unnamed return values
304 if ( retval->get_name() == "" ) {
305 retval->set_name( "_retparm" );
306 retval->set_linkage( LinkageSpec::C );
307 } // if
308 } // if
[ae63a18]309
[e56cfdb0]310 FunctionType *functionType = functionDecl->get_functionType();
[01aeade]311 makeTyVarMap( functionDecl->get_functionType(), scopeTyVars );
312 findAssignOps( functionDecl->get_functionType()->get_forall() );
[e56cfdb0]313
314 std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
315 std::list< FunctionType *> functions;
316 for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
317 for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
318 findFunction( (*assert)->get_type(), functions, scopeTyVars, needsAdapter );
319 } // for
320 } // for
321 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
322 findFunction( (*arg)->get_type(), functions, scopeTyVars, needsAdapter );
323 } // for
[b4cd03b7]324
[e56cfdb0]325 AdapterMap & adapters = Pass1::adapters.top();
326 for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
[bdf1954]327 std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
[e56cfdb0]328 if ( adapters.find( mangleName ) == adapters.end() ) {
329 std::string adapterName = makeAdapterName( mangleName );
330 adapters.insert( std::pair< std::string, DeclarationWithType *>( mangleName, new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) ) );
331 } // if
332 } // for
333
[01aeade]334 functionDecl->set_statements( functionDecl->get_statements()->acceptMutator( *this ) );
[ae63a18]335
[01aeade]336 scopeTyVars = oldtyVars;
[ed1065c]337 assignOps = oldassignOps;
[e56cfdb0]338 // std::cerr << "end FunctionDecl: ";
339 // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
340 // std::cerr << i->first << " ";
341 // }
342 // std::cerr << "\n";
[01aeade]343 retval = oldRetval;
344 useRetval = oldUseRetval;
[e56cfdb0]345 doEndScope();
[01aeade]346 } // if
347 return functionDecl;
348 }
[6c3744e]349
[01aeade]350 TypeDecl *Pass1::mutate( TypeDecl *typeDecl ) {
351 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
352 return Mutator::mutate( typeDecl );
353 }
[6c3744e]354
[01aeade]355 Expression *Pass1::mutate( CommaExpr *commaExpr ) {
356 bool oldUseRetval = useRetval;
357 useRetval = false;
358 commaExpr->set_arg1( maybeMutate( commaExpr->get_arg1(), *this ) );
359 useRetval = oldUseRetval;
360 commaExpr->set_arg2( maybeMutate( commaExpr->get_arg2(), *this ) );
361 return commaExpr;
362 }
[6c3744e]363
[01aeade]364 Expression *Pass1::mutate( ConditionalExpr *condExpr ) {
365 bool oldUseRetval = useRetval;
366 useRetval = false;
367 condExpr->set_arg1( maybeMutate( condExpr->get_arg1(), *this ) );
368 useRetval = oldUseRetval;
369 condExpr->set_arg2( maybeMutate( condExpr->get_arg2(), *this ) );
370 condExpr->set_arg3( maybeMutate( condExpr->get_arg3(), *this ) );
371 return condExpr;
[6c3744e]372
[01aeade]373 }
[6c3744e]374
[05d47278]375 Expression *Pass1::makeOffsetArray( StructInstType *ty ) {
[4a79e3c9]376 std::list< Declaration* > &baseMembers = ty->get_baseStruct()->get_members();
[b4cd03b7]377
[05d47278]378 // make a new temporary array
379 Type *offsetType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
[4a79e3c9]380 std::stringstream lenGen;
381 lenGen << baseMembers.size();
382 ConstantExpr *lenExpr = new ConstantExpr( Constant( offsetType->clone(), lenGen.str() ) );
383 ObjectDecl *arrayTemp = makeTemporary( new ArrayType( Type::Qualifiers(), offsetType, lenExpr, false, false ) );
[05d47278]384
385 // build initializer list for temporary
386 std::list< Initializer* > inits;
[4a79e3c9]387 for ( std::list< Declaration* >::const_iterator member = baseMembers.begin(); member != baseMembers.end(); ++member ) {
[05d47278]388 DeclarationWithType *memberDecl;
389 if ( DeclarationWithType *origMember = dynamic_cast< DeclarationWithType* >( *member ) ) {
390 memberDecl = origMember->clone();
391 } else {
392 memberDecl = new ObjectDecl( (*member)->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, offsetType->clone(), 0 );
393 }
394 inits.push_back( new SingleInit( new OffsetofExpr( ty->clone(), memberDecl ) ) );
395 }
396 arrayTemp->set_init( new ListInit( inits ) );
397
398 // return variable pointing to temporary
399 return new VariableExpr( arrayTemp );
400 }
[b4cd03b7]401
[5c52b06]402 void Pass1::passArgTypeVars( ApplicationExpr *appExpr, Type *parmType, Type *argBaseType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars, std::set< std::string > &seenTypes ) {
403 Type *polyBase = hasPolyBase( parmType, exprTyVars );
404 if ( polyBase && ! dynamic_cast< TypeInstType* >( polyBase ) ) {
405 std::string sizeName = sizeofName( polyBase );
406 if ( seenTypes.count( sizeName ) ) return;
407
408 arg = appExpr->get_args().insert( arg, new SizeofExpr( argBaseType->clone() ) );
409 arg++;
410 arg = appExpr->get_args().insert( arg, new AlignofExpr( argBaseType->clone() ) );
411 arg++;
412 if ( dynamic_cast< StructInstType* >( polyBase ) ) {
413 if ( StructInstType *argBaseStructType = dynamic_cast< StructInstType* >( argBaseType ) ) {
414 arg = appExpr->get_args().insert( arg, makeOffsetArray( argBaseStructType ) );
415 arg++;
416 } else {
417 throw SemanticError( "Cannot pass non-struct type for generic struct" );
418 }
419 }
420
421 seenTypes.insert( sizeName );
422 }
423 }
424
425 void Pass1::passTypeVars( ApplicationExpr *appExpr, ReferenceToType *polyRetType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
[7754cde]426 // pass size/align for type variables
[01aeade]427 for ( TyVarMap::const_iterator tyParm = exprTyVars.begin(); tyParm != exprTyVars.end(); ++tyParm ) {
428 ResolvExpr::EqvClass eqvClass;
429 assert( env );
430 if ( tyParm->second == TypeDecl::Any ) {
431 Type *concrete = env->lookup( tyParm->first );
432 if ( concrete ) {
433 arg = appExpr->get_args().insert( arg, new SizeofExpr( concrete->clone() ) );
434 arg++;
[db0b3ce]435 arg = appExpr->get_args().insert( arg, new AlignofExpr( concrete->clone() ) );
436 arg++;
[01aeade]437 } else {
438 throw SemanticError( "unbound type variable in application ", appExpr );
439 } // if
440 } // if
441 } // for
[7754cde]442
443 // add size/align for generic types to parameter list
444 if ( appExpr->get_function()->get_results().empty() ) return;
445 FunctionType *funcType = getFunctionType( appExpr->get_function()->get_results().front() );
446 assert( funcType );
[ae63a18]447
[7754cde]448 std::list< DeclarationWithType* >::const_iterator fnParm = funcType->get_parameters().begin();
449 std::list< Expression* >::const_iterator fnArg = arg;
[69911c11]450 std::set< std::string > seenTypes; //< names for generic types we've seen
[7754cde]451
[5c52b06]452 // a polymorphic return type may need to be added to the argument list
453 if ( polyRetType ) {
454 Type *concRetType = replaceWithConcrete( appExpr, polyRetType );
455 passArgTypeVars( appExpr, polyRetType, concRetType, arg, exprTyVars, seenTypes );
456 }
457
458 // add type information args for presently unseen types in parameter list
459 for ( ; fnParm != funcType->get_parameters().end() && fnArg != appExpr->get_args().end(); ++fnParm, ++fnArg ) {
460 VariableExpr *fnArgBase = getBaseVar( *fnArg );
461 if ( ! fnArgBase || fnArgBase->get_results().empty() ) continue;
462 passArgTypeVars( appExpr, (*fnParm)->get_type(), fnArgBase->get_results().front(), arg, exprTyVars, seenTypes );
[7754cde]463 }
[01aeade]464 }
[6c3744e]465
[01aeade]466 ObjectDecl *Pass1::makeTemporary( Type *type ) {
[68cd1ce]467 ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, type, 0 );
[01aeade]468 stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
469 return newObj;
470 }
[6c3744e]471
[01aeade]472 Expression *Pass1::addRetParam( ApplicationExpr *appExpr, FunctionType *function, Type *retType, std::list< Expression *>::iterator &arg ) {
[cf16f94]473 // ***** Code Removal ***** After introducing a temporary variable for all return expressions, the following code appears superfluous.
474 // if ( useRetval ) {
475 // assert( retval );
476 // arg = appExpr->get_args().insert( arg, new VariableExpr( retval ) );
477 // arg++;
478 // } else {
479
480 // Create temporary to hold return value of polymorphic function and produce that temporary as a result
481 // using a comma expression. Possibly change comma expression into statement expression "{}" for multiple
482 // return values.
483 ObjectDecl *newObj = makeTemporary( retType->clone() );
484 Expression *paramExpr = new VariableExpr( newObj );
[5c52b06]485
486 // If the type of the temporary is not polymorphic, box temporary by taking its address;
487 // otherwise the temporary is already boxed and can be used directly.
[5f6c42c]488 if ( ! isPolyType( newObj->get_type(), scopeTyVars, env ) ) {
[cf16f94]489 paramExpr = new AddressExpr( paramExpr );
[01aeade]490 } // if
[cf16f94]491 arg = appExpr->get_args().insert( arg, paramExpr ); // add argument to function call
492 arg++;
493 // Build a comma expression to call the function and emulate a normal return.
494 CommaExpr *commaExpr = new CommaExpr( appExpr, new VariableExpr( newObj ) );
495 commaExpr->set_env( appExpr->get_env() );
496 appExpr->set_env( 0 );
497 return commaExpr;
498 // } // if
499 // return appExpr;
[01aeade]500 }
[6c3744e]501
[48ca586]502 void Pass1::replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params ) {
503 for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
504 TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
505 assert(paramType && "Aggregate parameters should be type expressions");
506 paramType->set_type( replaceWithConcrete( appExpr, paramType->get_type(), false ) );
507 }
508 }
[b4cd03b7]509
[48ca586]510 Type *Pass1::replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone ) {
511 if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
512 Type *concrete = env->lookup( typeInst->get_name() );
513 if ( concrete == 0 ) {
514 throw SemanticError( "Unbound type variable " + typeInst->get_name() + " in ", appExpr );
515 } // if
516 return concrete;
517 } else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
518 if ( doClone ) {
519 structType = structType->clone();
520 }
521 replaceParametersWithConcrete( appExpr, structType->get_parameters() );
522 return structType;
523 } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
524 if ( doClone ) {
525 unionType = unionType->clone();
526 }
527 replaceParametersWithConcrete( appExpr, unionType->get_parameters() );
528 return unionType;
529 }
530 return type;
531 }
532
533 Expression *Pass1::addPolyRetParam( ApplicationExpr *appExpr, FunctionType *function, ReferenceToType *polyType, std::list< Expression *>::iterator &arg ) {
[01aeade]534 assert( env );
[48ca586]535 Type *concrete = replaceWithConcrete( appExpr, polyType );
[5c52b06]536 // add out-parameter for return value
[01aeade]537 return addRetParam( appExpr, function, concrete, arg );
538 }
[6c3744e]539
[01aeade]540 Expression *Pass1::applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
541 Expression *ret = appExpr;
[ffad73a]542 if ( ! function->get_returnVals().empty() && isPolyType( function->get_returnVals().front()->get_type(), tyVars ) ) {
[01aeade]543 ret = addRetParam( appExpr, function, function->get_returnVals().front()->get_type(), arg );
544 } // if
[bdf1954]545 std::string mangleName = mangleAdapterName( function, tyVars );
[01aeade]546 std::string adapterName = makeAdapterName( mangleName );
[b1a6d6b]547
[b4cd03b7]548 // cast adaptee to void (*)(), since it may have any type inside a polymorphic function
549 Type * adapteeType = new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) );
550 appExpr->get_args().push_front( new CastExpr( appExpr->get_function(), adapteeType ) );
[01aeade]551 appExpr->set_function( new NameExpr( adapterName ) );
[ae63a18]552
[01aeade]553 return ret;
554 }
[6c3744e]555
[01aeade]556 void Pass1::boxParam( Type *param, Expression *&arg, const TyVarMap &exprTyVars ) {
557 assert( ! arg->get_results().empty() );
[1cced28]558 if ( isPolyType( param, exprTyVars ) ) {
[9407ed8]559 if ( isPolyType( arg->get_results().front() ) ) {
560 // if the argument's type is polymorphic, we don't need to box again!
[01aeade]561 return;
562 } else if ( arg->get_results().front()->get_isLvalue() ) {
563 // VariableExpr and MemberExpr are lvalues
564 arg = new AddressExpr( arg );
565 } else {
[bd85400]566 // use type computed in unification to declare boxed variables
567 Type * newType = param->clone();
568 if ( env ) env->apply( newType );
569 ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, newType, 0 );
[f6d7e0f]570 newObj->get_type()->get_qualifiers() = Type::Qualifiers(); // TODO: is this right???
[01aeade]571 stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
572 UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
573 assign->get_args().push_back( new VariableExpr( newObj ) );
574 assign->get_args().push_back( arg );
575 stmtsToAdd.push_back( new ExprStmt( noLabels, assign ) );
576 arg = new AddressExpr( new VariableExpr( newObj ) );
577 } // if
578 } // if
579 }
[6c3744e]580
[b4cd03b7]581 /// cast parameters to polymorphic functions so that types are replaced with
582 /// void * if they are type parameters in the formal type.
583 /// this gets rid of warnings from gcc.
[01aeade]584 void addCast( Expression *&actual, Type *formal, const TyVarMap &tyVars ) {
[b4cd03b7]585 Type * newType = formal->clone();
586 if ( getFunctionType( newType ) ) {
587 newType = ScrubTyVars::scrub( newType, tyVars );
[01aeade]588 actual = new CastExpr( actual, newType );
589 } // if
590 }
[6c3744e]591
[01aeade]592 void Pass1::boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
593 for ( std::list< DeclarationWithType *>::const_iterator param = function->get_parameters().begin(); param != function->get_parameters().end(); ++param, ++arg ) {
594 assert( arg != appExpr->get_args().end() );
595 addCast( *arg, (*param)->get_type(), exprTyVars );
596 boxParam( (*param)->get_type(), *arg, exprTyVars );
597 } // for
598 }
[6c3744e]599
[01aeade]600 void Pass1::addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
601 std::list< Expression *>::iterator cur = arg;
602 for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
603 for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
604 InferredParams::const_iterator inferParam = appExpr->get_inferParams().find( (*assert)->get_uniqueId() );
[698664b3]605 assert( inferParam != appExpr->get_inferParams().end() && "NOTE: Explicit casts of polymorphic functions to compatible monomorphic functions are currently unsupported" );
[01aeade]606 Expression *newExpr = inferParam->second.expr->clone();
607 addCast( newExpr, (*assert)->get_type(), tyVars );
608 boxParam( (*assert)->get_type(), newExpr, tyVars );
609 appExpr->get_args().insert( cur, newExpr );
610 } // for
611 } // for
612 }
[6c3744e]613
[01aeade]614 void makeRetParm( FunctionType *funcType ) {
615 DeclarationWithType *retParm = funcType->get_returnVals().front();
[6c3744e]616
[01aeade]617 // make a new parameter that is a pointer to the type of the old return value
618 retParm->set_type( new PointerType( Type::Qualifiers(), retParm->get_type() ) );
619 funcType->get_parameters().push_front( retParm );
[6c3744e]620
[01aeade]621 // we don't need the return value any more
622 funcType->get_returnVals().clear();
623 }
[6c3744e]624
[01aeade]625 FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars ) {
626 // actually make the adapter type
627 FunctionType *adapter = adaptee->clone();
[ffad73a]628 if ( ! adapter->get_returnVals().empty() && isPolyType( adapter->get_returnVals().front()->get_type(), tyVars ) ) {
[01aeade]629 makeRetParm( adapter );
630 } // if
[68cd1ce]631 adapter->get_parameters().push_front( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) ), 0 ) );
[01aeade]632 return adapter;
633 }
[6c3744e]634
[01aeade]635 Expression *makeAdapterArg( DeclarationWithType *param, DeclarationWithType *arg, DeclarationWithType *realParam, const TyVarMap &tyVars ) {
636 assert( param );
637 assert( arg );
[ffad73a]638 if ( isPolyType( realParam->get_type(), tyVars ) ) {
[30aeb27]639 if ( ! isPolyType( arg->get_type() ) ) {
[e56cfdb0]640 UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
641 deref->get_args().push_back( new CastExpr( new VariableExpr( param ), new PointerType( Type::Qualifiers(), arg->get_type()->clone() ) ) );
642 deref->get_results().push_back( arg->get_type()->clone() );
643 return deref;
644 } // if
[01aeade]645 } // if
646 return new VariableExpr( param );
647 }
[6c3744e]648
[01aeade]649 void addAdapterParams( ApplicationExpr *adapteeApp, std::list< DeclarationWithType *>::iterator arg, std::list< DeclarationWithType *>::iterator param, std::list< DeclarationWithType *>::iterator paramEnd, std::list< DeclarationWithType *>::iterator realParam, const TyVarMap &tyVars ) {
650 UniqueName paramNamer( "_p" );
651 for ( ; param != paramEnd; ++param, ++arg, ++realParam ) {
652 if ( (*param)->get_name() == "" ) {
653 (*param)->set_name( paramNamer.newName() );
654 (*param)->set_linkage( LinkageSpec::C );
655 } // if
656 adapteeApp->get_args().push_back( makeAdapterArg( *param, *arg, *realParam, tyVars ) );
657 } // for
658 }
[6c3744e]659
[b1a6d6b]660
661
[01aeade]662 FunctionDecl *Pass1::makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars ) {
663 FunctionType *adapterType = makeAdapterType( adaptee, tyVars );
664 adapterType = ScrubTyVars::scrub( adapterType, tyVars );
665 DeclarationWithType *adapteeDecl = adapterType->get_parameters().front();
666 adapteeDecl->set_name( "_adaptee" );
667 ApplicationExpr *adapteeApp = new ApplicationExpr( new CastExpr( new VariableExpr( adapteeDecl ), new PointerType( Type::Qualifiers(), realType ) ) );
668 Statement *bodyStmt;
[ae63a18]669
[01aeade]670 std::list< TypeDecl *>::iterator tyArg = realType->get_forall().begin();
671 std::list< TypeDecl *>::iterator tyParam = adapterType->get_forall().begin();
672 std::list< TypeDecl *>::iterator realTyParam = adaptee->get_forall().begin();
673 for ( ; tyParam != adapterType->get_forall().end(); ++tyArg, ++tyParam, ++realTyParam ) {
674 assert( tyArg != realType->get_forall().end() );
675 std::list< DeclarationWithType *>::iterator assertArg = (*tyArg)->get_assertions().begin();
676 std::list< DeclarationWithType *>::iterator assertParam = (*tyParam)->get_assertions().begin();
677 std::list< DeclarationWithType *>::iterator realAssertParam = (*realTyParam)->get_assertions().begin();
678 for ( ; assertParam != (*tyParam)->get_assertions().end(); ++assertArg, ++assertParam, ++realAssertParam ) {
679 assert( assertArg != (*tyArg)->get_assertions().end() );
680 adapteeApp->get_args().push_back( makeAdapterArg( *assertParam, *assertArg, *realAssertParam, tyVars ) );
681 } // for
682 } // for
[ae63a18]683
[01aeade]684 std::list< DeclarationWithType *>::iterator arg = realType->get_parameters().begin();
685 std::list< DeclarationWithType *>::iterator param = adapterType->get_parameters().begin();
686 std::list< DeclarationWithType *>::iterator realParam = adaptee->get_parameters().begin();
687 param++; // skip adaptee parameter
688 if ( realType->get_returnVals().empty() ) {
689 addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
690 bodyStmt = new ExprStmt( noLabels, adapteeApp );
[ffad73a]691 } else if ( isPolyType( adaptee->get_returnVals().front()->get_type(), tyVars ) ) {
[01aeade]692 if ( (*param)->get_name() == "" ) {
693 (*param)->set_name( "_ret" );
694 (*param)->set_linkage( LinkageSpec::C );
695 } // if
696 UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
697 UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
698 deref->get_args().push_back( new CastExpr( new VariableExpr( *param++ ), new PointerType( Type::Qualifiers(), realType->get_returnVals().front()->get_type()->clone() ) ) );
699 assign->get_args().push_back( deref );
700 addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
701 assign->get_args().push_back( adapteeApp );
702 bodyStmt = new ExprStmt( noLabels, assign );
703 } else {
704 // adapter for a function that returns a monomorphic value
705 addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
706 bodyStmt = new ReturnStmt( noLabels, adapteeApp );
707 } // if
708 CompoundStmt *adapterBody = new CompoundStmt( noLabels );
709 adapterBody->get_kids().push_back( bodyStmt );
710 std::string adapterName = makeAdapterName( mangleName );
[de62360d]711 return new FunctionDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, adapterType, adapterBody, false, false );
[01aeade]712 }
[6c3744e]713
[c29d9ce]714 void Pass1::passAdapters( ApplicationExpr * appExpr, FunctionType * functionType, const TyVarMap & exprTyVars ) {
[e497c1d]715 // collect a list of function types passed as parameters or implicit parameters (assertions)
[01aeade]716 std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
717 std::list< FunctionType *> functions;
718 for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
719 for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
720 findFunction( (*assert)->get_type(), functions, exprTyVars, needsAdapter );
721 } // for
722 } // for
723 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
724 findFunction( (*arg)->get_type(), functions, exprTyVars, needsAdapter );
725 } // for
[e497c1d]726
[e56cfdb0]727 // parameter function types for which an appropriate adapter has been generated. we cannot use the types
728 // after applying substitutions, since two different parameter types may be unified to the same type
[01aeade]729 std::set< std::string > adaptersDone;
[e497c1d]730
[01aeade]731 for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
[c29d9ce]732 FunctionType *originalFunction = (*funType)->clone();
[01aeade]733 FunctionType *realFunction = (*funType)->clone();
734 std::string mangleName = SymTab::Mangler::mangle( realFunction );
[e497c1d]735
[e56cfdb0]736 // only attempt to create an adapter or pass one as a parameter if we haven't already done so for this
737 // pre-substitution parameter function type.
[01aeade]738 if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
[e497c1d]739 adaptersDone.insert( adaptersDone.begin(), mangleName );
[ae63a18]740
[e56cfdb0]741 // apply substitution to type variables to figure out what the adapter's type should look like
[e497c1d]742 assert( env );
743 env->apply( realFunction );
[ae63a18]744 mangleName = SymTab::Mangler::mangle( realFunction );
[bdf1954]745 mangleName += makePolyMonoSuffix( originalFunction, exprTyVars );
[e497c1d]746
[e56cfdb0]747 AdapterMap & adapters = Pass1::adapters.top();
748 AdapterMap::iterator adapter = adapters.find( mangleName );
749 if ( adapter == adapters.end() ) {
750 // adapter has not been created yet in the current scope, so define it
751 FunctionDecl *newAdapter = makeAdapter( *funType, realFunction, mangleName, exprTyVars );
752 adapter = adapters.insert( adapters.begin(), std::pair< std::string, DeclarationWithType *>( mangleName, newAdapter ) );
753 stmtsToAdd.push_back( new DeclStmt( noLabels, newAdapter ) );
[c29d9ce]754 } // if
[e56cfdb0]755 assert( adapter != adapters.end() );
756
757 // add the appropriate adapter as a parameter
758 appExpr->get_args().push_front( new VariableExpr( adapter->second ) );
[01aeade]759 } // if
760 } // for
[e56cfdb0]761 } // passAdapters
[6c3744e]762
[78dd0da]763 Expression *makeIncrDecrExpr( ApplicationExpr *appExpr, Type *polyType, bool isIncr ) {
[01aeade]764 NameExpr *opExpr;
765 if ( isIncr ) {
766 opExpr = new NameExpr( "?+=?" );
767 } else {
768 opExpr = new NameExpr( "?-=?" );
[6c3744e]769 } // if
[01aeade]770 UntypedExpr *addAssign = new UntypedExpr( opExpr );
771 if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
772 addAssign->get_args().push_back( address->get_arg() );
773 } else {
774 addAssign->get_args().push_back( appExpr->get_args().front() );
[6c3744e]775 } // if
[78dd0da]776 addAssign->get_args().push_back( new NameExpr( sizeofName( polyType ) ) );
[01aeade]777 addAssign->get_results().front() = appExpr->get_results().front()->clone();
778 if ( appExpr->get_env() ) {
779 addAssign->set_env( appExpr->get_env() );
[6c3744e]780 appExpr->set_env( 0 );
781 } // if
[01aeade]782 appExpr->get_args().clear();
783 delete appExpr;
784 return addAssign;
785 }
786
787 Expression *Pass1::handleIntrinsics( ApplicationExpr *appExpr ) {
788 if ( VariableExpr *varExpr = dynamic_cast< VariableExpr *>( appExpr->get_function() ) ) {
789 if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
790 if ( varExpr->get_var()->get_name() == "?[?]" ) {
791 assert( ! appExpr->get_results().empty() );
792 assert( appExpr->get_args().size() == 2 );
[ffad73a]793 Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_results().front(), scopeTyVars, env );
794 Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_results().front(), scopeTyVars, env );
[ae63a18]795 assert( ! baseType1 || ! baseType2 ); // the arguments cannot both be polymorphic pointers
[01aeade]796 UntypedExpr *ret = 0;
[ae63a18]797 if ( baseType1 || baseType2 ) { // one of the arguments is a polymorphic pointer
[01aeade]798 ret = new UntypedExpr( new NameExpr( "?+?" ) );
799 } // if
[ffad73a]800 if ( baseType1 ) {
[01aeade]801 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
802 multiply->get_args().push_back( appExpr->get_args().back() );
[ffad73a]803 multiply->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
[01aeade]804 ret->get_args().push_back( appExpr->get_args().front() );
805 ret->get_args().push_back( multiply );
[ffad73a]806 } else if ( baseType2 ) {
[01aeade]807 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
808 multiply->get_args().push_back( appExpr->get_args().front() );
[ffad73a]809 multiply->get_args().push_back( new NameExpr( sizeofName( baseType2 ) ) );
[01aeade]810 ret->get_args().push_back( multiply );
811 ret->get_args().push_back( appExpr->get_args().back() );
812 } // if
[ffad73a]813 if ( baseType1 || baseType2 ) {
[01aeade]814 ret->get_results().push_front( appExpr->get_results().front()->clone() );
815 if ( appExpr->get_env() ) {
816 ret->set_env( appExpr->get_env() );
817 appExpr->set_env( 0 );
818 } // if
819 appExpr->get_args().clear();
820 delete appExpr;
821 return ret;
822 } // if
823 } else if ( varExpr->get_var()->get_name() == "*?" ) {
824 assert( ! appExpr->get_results().empty() );
825 assert( ! appExpr->get_args().empty() );
[ffad73a]826 if ( isPolyType( appExpr->get_results().front(), scopeTyVars, env ) ) {
[01aeade]827 Expression *ret = appExpr->get_args().front();
828 delete ret->get_results().front();
829 ret->get_results().front() = appExpr->get_results().front()->clone();
830 if ( appExpr->get_env() ) {
831 ret->set_env( appExpr->get_env() );
832 appExpr->set_env( 0 );
833 } // if
834 appExpr->get_args().clear();
835 delete appExpr;
836 return ret;
837 } // if
838 } else if ( varExpr->get_var()->get_name() == "?++" || varExpr->get_var()->get_name() == "?--" ) {
839 assert( ! appExpr->get_results().empty() );
840 assert( appExpr->get_args().size() == 1 );
[ffad73a]841 if ( Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env ) ) {
[01aeade]842 Type *tempType = appExpr->get_results().front()->clone();
843 if ( env ) {
844 env->apply( tempType );
845 } // if
846 ObjectDecl *newObj = makeTemporary( tempType );
847 VariableExpr *tempExpr = new VariableExpr( newObj );
848 UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
849 assignExpr->get_args().push_back( tempExpr->clone() );
850 if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
851 assignExpr->get_args().push_back( address->get_arg()->clone() );
852 } else {
853 assignExpr->get_args().push_back( appExpr->get_args().front()->clone() );
854 } // if
[ffad73a]855 CommaExpr *firstComma = new CommaExpr( assignExpr, makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "?++" ) );
[01aeade]856 return new CommaExpr( firstComma, tempExpr );
857 } // if
858 } else if ( varExpr->get_var()->get_name() == "++?" || varExpr->get_var()->get_name() == "--?" ) {
859 assert( ! appExpr->get_results().empty() );
860 assert( appExpr->get_args().size() == 1 );
[ffad73a]861 if ( Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env ) ) {
862 return makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "++?" );
[01aeade]863 } // if
864 } else if ( varExpr->get_var()->get_name() == "?+?" || varExpr->get_var()->get_name() == "?-?" ) {
865 assert( ! appExpr->get_results().empty() );
866 assert( appExpr->get_args().size() == 2 );
[ffad73a]867 Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_results().front(), scopeTyVars, env );
868 Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_results().front(), scopeTyVars, env );
869 if ( baseType1 && baseType2 ) {
[01aeade]870 UntypedExpr *divide = new UntypedExpr( new NameExpr( "?/?" ) );
871 divide->get_args().push_back( appExpr );
[ffad73a]872 divide->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
[01aeade]873 divide->get_results().push_front( appExpr->get_results().front()->clone() );
874 if ( appExpr->get_env() ) {
875 divide->set_env( appExpr->get_env() );
876 appExpr->set_env( 0 );
877 } // if
878 return divide;
[ffad73a]879 } else if ( baseType1 ) {
[01aeade]880 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
881 multiply->get_args().push_back( appExpr->get_args().back() );
[ffad73a]882 multiply->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
[01aeade]883 appExpr->get_args().back() = multiply;
[ffad73a]884 } else if ( baseType2 ) {
[01aeade]885 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
886 multiply->get_args().push_back( appExpr->get_args().front() );
[ffad73a]887 multiply->get_args().push_back( new NameExpr( sizeofName( baseType2 ) ) );
[01aeade]888 appExpr->get_args().front() = multiply;
889 } // if
890 } else if ( varExpr->get_var()->get_name() == "?+=?" || varExpr->get_var()->get_name() == "?-=?" ) {
891 assert( ! appExpr->get_results().empty() );
892 assert( appExpr->get_args().size() == 2 );
[ffad73a]893 Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env );
894 if ( baseType ) {
[01aeade]895 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
896 multiply->get_args().push_back( appExpr->get_args().back() );
[ffad73a]897 multiply->get_args().push_back( new NameExpr( sizeofName( baseType ) ) );
[01aeade]898 appExpr->get_args().back() = multiply;
899 } // if
900 } // if
901 return appExpr;
902 } // if
[6c3744e]903 } // if
[01aeade]904 return 0;
905 }
[6c3744e]906
[01aeade]907 Expression *Pass1::mutate( ApplicationExpr *appExpr ) {
[e56cfdb0]908 // std::cerr << "mutate appExpr: ";
909 // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
910 // std::cerr << i->first << " ";
911 // }
912 // std::cerr << "\n";
[01aeade]913 bool oldUseRetval = useRetval;
914 useRetval = false;
915 appExpr->get_function()->acceptMutator( *this );
916 mutateAll( appExpr->get_args(), *this );
917 useRetval = oldUseRetval;
[ae63a18]918
[01aeade]919 assert( ! appExpr->get_function()->get_results().empty() );
920 PointerType *pointer = dynamic_cast< PointerType *>( appExpr->get_function()->get_results().front() );
921 assert( pointer );
922 FunctionType *function = dynamic_cast< FunctionType *>( pointer->get_base() );
923 assert( function );
[ae63a18]924
[01aeade]925 if ( Expression *newExpr = handleIntrinsics( appExpr ) ) {
926 return newExpr;
927 } // if
[ae63a18]928
[01aeade]929 Expression *ret = appExpr;
[ae63a18]930
[01aeade]931 std::list< Expression *>::iterator arg = appExpr->get_args().begin();
932 std::list< Expression *>::iterator paramBegin = appExpr->get_args().begin();
[ae63a18]933
[5c52b06]934 TyVarMap exprTyVars;
935 makeTyVarMap( function, exprTyVars );
936 ReferenceToType *polyRetType = 0;
937
938 if ( polyRetType = isPolyRet( function ) ) {
939 ret = addPolyRetParam( appExpr, function, polyRetType, arg );
[01aeade]940 } else if ( needsAdapter( function, scopeTyVars ) ) {
[e56cfdb0]941 // std::cerr << "needs adapter: ";
942 // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
943 // std::cerr << i->first << " ";
944 // }
945 // std::cerr << "\n";
[01aeade]946 // change the application so it calls the adapter rather than the passed function
947 ret = applyAdapter( appExpr, function, arg, scopeTyVars );
948 } // if
949 arg = appExpr->get_args().begin();
[ae63a18]950
[5c52b06]951 passTypeVars( appExpr, polyRetType, arg, exprTyVars );
[01aeade]952 addInferredParams( appExpr, function, arg, exprTyVars );
[51b73452]953
[01aeade]954 arg = paramBegin;
[ae63a18]955
[01aeade]956 boxParams( appExpr, function, arg, exprTyVars );
[6c3744e]957
[01aeade]958 passAdapters( appExpr, function, exprTyVars );
[6c3744e]959
[01aeade]960 return ret;
961 }
[6c3744e]962
[01aeade]963 Expression *Pass1::mutate( UntypedExpr *expr ) {
[ffad73a]964 if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), scopeTyVars, env ) ) {
[01aeade]965 if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
966 if ( name->get_name() == "*?" ) {
967 Expression *ret = expr->get_args().front();
968 expr->get_args().clear();
969 delete expr;
970 return ret->acceptMutator( *this );
971 } // if
972 } // if
973 } // if
974 return PolyMutator::mutate( expr );
975 }
[6c3744e]976
[01aeade]977 Expression *Pass1::mutate( AddressExpr *addrExpr ) {
978 assert( ! addrExpr->get_arg()->get_results().empty() );
[cf16f94]979
980 bool needs = false;
981 if ( UntypedExpr *expr = dynamic_cast< UntypedExpr *>( addrExpr->get_arg() ) ) {
[5f6c42c]982 if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), scopeTyVars, env ) ) {
[cf16f94]983 if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
984 if ( name->get_name() == "*?" ) {
985 if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr->get_args().front() ) ) {
986 assert( ! appExpr->get_function()->get_results().empty() );
987 PointerType *pointer = dynamic_cast< PointerType *>( appExpr->get_function()->get_results().front() );
988 assert( pointer );
989 FunctionType *function = dynamic_cast< FunctionType *>( pointer->get_base() );
990 assert( function );
991 needs = needsAdapter( function, scopeTyVars );
992 } // if
993 } // if
994 } // if
995 } // if
996 } // if
[01aeade]997 addrExpr->set_arg( mutateExpression( addrExpr->get_arg() ) );
[5f6c42c]998 if ( isPolyType( addrExpr->get_arg()->get_results().front(), scopeTyVars, env ) || needs ) {
[01aeade]999 Expression *ret = addrExpr->get_arg();
1000 delete ret->get_results().front();
1001 ret->get_results().front() = addrExpr->get_results().front()->clone();
1002 addrExpr->set_arg( 0 );
1003 delete addrExpr;
1004 return ret;
1005 } else {
1006 return addrExpr;
1007 } // if
1008 }
[6c3744e]1009
[b10c9959]1010 /// Wraps a function declaration in a new pointer-to-function variable expression
1011 VariableExpr *wrapFunctionDecl( DeclarationWithType *functionDecl ) {
1012 // line below cloned from FixFunction.cc
1013 ObjectDecl *functionObj = new ObjectDecl( functionDecl->get_name(), functionDecl->get_storageClass(), functionDecl->get_linkage(), 0,
1014 new PointerType( Type::Qualifiers(), functionDecl->get_type()->clone() ), 0 );
1015 functionObj->set_mangleName( functionDecl->get_mangleName() );
1016 return new VariableExpr( functionObj );
1017 }
1018
[cf16f94]1019 Statement * Pass1::mutate( ReturnStmt *returnStmt ) {
1020 if ( retval && returnStmt->get_expr() ) {
1021 assert( ! returnStmt->get_expr()->get_results().empty() );
1022 // ***** Code Removal ***** After introducing a temporary variable for all return expressions, the following code appears superfluous.
1023 // if ( returnStmt->get_expr()->get_results().front()->get_isLvalue() ) {
[ae63a18]1024 // by this point, a cast expr on a polymorphic return value is redundant
[cf16f94]1025 while ( CastExpr *castExpr = dynamic_cast< CastExpr *>( returnStmt->get_expr() ) ) {
1026 returnStmt->set_expr( castExpr->get_arg() );
1027 returnStmt->get_expr()->set_env( castExpr->get_env() );
1028 castExpr->set_env( 0 );
1029 castExpr->set_arg( 0 );
1030 delete castExpr;
[5f6c42c]1031 } //while
[1194734]1032
1033 // find assignment operator for (polymorphic) return type
[b10c9959]1034 ApplicationExpr *assignExpr = 0;
[1194734]1035 if ( TypeInstType *typeInst = dynamic_cast< TypeInstType *>( retval->get_type() ) ) {
[b10c9959]1036 // find assignment operator for type variable
[1194734]1037 std::map< std::string, DeclarationWithType *>::const_iterator assignIter = assignOps.find( typeInst->get_name() );
1038 if ( assignIter == assignOps.end() ) {
1039 throw SemanticError( "Attempt to return dtype or ftype object in ", returnStmt->get_expr() );
1040 } // if
[b10c9959]1041 assignExpr = new ApplicationExpr( new VariableExpr( assignIter->second ) );
[1194734]1042 } else if ( ReferenceToType *refType = dynamic_cast< ReferenceToType *>( retval->get_type() ) ) {
[b10c9959]1043 // find assignment operator for generic type
[1194734]1044 ScopedMap< std::string, DeclarationWithType *>::const_iterator assignIter = scopedAssignOps.find( refType->get_name() );
1045 if ( assignIter == scopedAssignOps.end() ) {
1046 throw SemanticError( "Attempt to return dtype or ftype generic object in ", returnStmt->get_expr() );
1047 }
[b10c9959]1048
1049 // wrap it up in an application expression
[05d47278]1050 DeclarationWithType *functionDecl = assignIter->second;
[b10c9959]1051 assignExpr = new ApplicationExpr( wrapFunctionDecl( functionDecl ) );
1052 assignExpr->set_env( env->clone() );
1053
1054 // find each of its needed secondary assignment operators
1055 std::list< Expression* > &tyParams = refType->get_parameters();
1056 std::list< TypeDecl* > &forallParams = functionDecl->get_type()->get_forall();
1057 std::list< Expression* >::const_iterator tyIt = tyParams.begin();
1058 std::list< TypeDecl* >::const_iterator forallIt = forallParams.begin();
1059 for ( ; tyIt != tyParams.end() && forallIt != forallParams.end(); ++tyIt, ++forallIt ) {
1060 if ( (*forallIt)->get_kind() != TypeDecl::Any ) continue; // skip types with no assign op (ftype/dtype)
1061
1062 std::list< DeclarationWithType* > &asserts = (*forallIt)->get_assertions();
1063 assert( ! asserts.empty() && "Type param needs assignment operator assertion" );
1064 DeclarationWithType *actualDecl = asserts.front();
1065 ReferenceToType *actualType = isAssignment( actualDecl );
1066 assert( actualType && "First assertion of type with assertions should be assignment operator" );
1067 TypeExpr *formalTypeExpr = dynamic_cast< TypeExpr* >( *tyIt );
1068 assert( formalTypeExpr && "type parameters must be type expressions" );
1069 Type *formalType = formalTypeExpr->get_type();
1070 assignExpr->get_env()->add( actualType->get_name(), formalType );
1071
1072 DeclarationWithType *assertAssign = 0;
1073 if ( TypeInstType *formalTypeInstType = dynamic_cast< TypeInstType* >( formalType ) ) {
1074 std::map< std::string, DeclarationWithType *>::const_iterator assertAssignIt = assignOps.find( formalTypeInstType->get_name() );
1075 if ( assertAssignIt == assignOps.end() ) {
1076 throw SemanticError( "No assignment operation found for ", formalTypeInstType );
1077 }
1078 assertAssign = assertAssignIt->second;
1079 //assignExpr->get_env()->add( formalTypeInstType->get_name(), actualType );
1080 } else if ( ReferenceToType *formalReferenceType = dynamic_cast< ReferenceToType* >( formalType ) ) {
1081 ScopedMap< std::string, DeclarationWithType *>::const_iterator assertAssignIt = scopedAssignOps.find( formalReferenceType->get_name() );
1082 if ( assertAssignIt == scopedAssignOps.end() ) {
1083 throw SemanticError( "No assignment operation found for ", formalReferenceType );
1084 }
1085 assertAssign = assertAssignIt->second;
1086 } else assert( false && "returning polymorphic types with non struct/polymorphic parameters not yet supported" );
1087
1088
1089 assignExpr->get_inferParams()[ actualDecl->get_uniqueId() ]
1090 = ParamEntry( assertAssign->get_uniqueId(), assertAssign->get_type()->clone(), actualDecl->get_type()->clone(), wrapFunctionDecl( assertAssign ) );
1091 }
[1194734]1092 }
[b10c9959]1093 assert( assignExpr );
[1194734]1094
1095 // replace return statement with appropriate assignment to out parameter
[cf16f94]1096 Expression *retParm = new NameExpr( retval->get_name() );
1097 retParm->get_results().push_back( new PointerType( Type::Qualifiers(), retval->get_type()->clone() ) );
1098 assignExpr->get_args().push_back( retParm );
1099 assignExpr->get_args().push_back( returnStmt->get_expr() );
1100 stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( assignExpr ) ) );
1101 // } else {
1102 // useRetval = true;
1103 // stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( returnStmt->get_expr() ) ) );
1104 // useRetval = false;
1105 // } // if
1106 returnStmt->set_expr( 0 );
[01aeade]1107 } else {
[cf16f94]1108 returnStmt->set_expr( mutateExpression( returnStmt->get_expr() ) );
[01aeade]1109 } // if
[cf16f94]1110 return returnStmt;
[01aeade]1111 }
[6c3744e]1112
[01aeade]1113 Type * Pass1::mutate( PointerType *pointerType ) {
1114 TyVarMap oldtyVars = scopeTyVars;
1115 makeTyVarMap( pointerType, scopeTyVars );
[ae63a18]1116
[01aeade]1117 Type *ret = Mutator::mutate( pointerType );
[ae63a18]1118
[01aeade]1119 scopeTyVars = oldtyVars;
1120 return ret;
1121 }
[6c3744e]1122
[01aeade]1123 Type * Pass1::mutate( FunctionType *functionType ) {
1124 TyVarMap oldtyVars = scopeTyVars;
1125 makeTyVarMap( functionType, scopeTyVars );
[ae63a18]1126
[01aeade]1127 Type *ret = Mutator::mutate( functionType );
[ae63a18]1128
[01aeade]1129 scopeTyVars = oldtyVars;
1130 return ret;
1131 }
[51b73452]1132
[01aeade]1133 void Pass1::doBeginScope() {
[bdf1954]1134 // push a copy of the current map
[e56cfdb0]1135 adapters.push(adapters.top());
[1194734]1136 scopedAssignOps.beginScope();
[01aeade]1137 }
[b1a6d6b]1138
[01aeade]1139 void Pass1::doEndScope() {
1140 adapters.pop();
[1194734]1141 scopedAssignOps.endScope();
[01aeade]1142 }
[51b73452]1143
1144////////////////////////////////////////// Pass2 ////////////////////////////////////////////////////
1145
[01aeade]1146 void Pass2::addAdapters( FunctionType *functionType ) {
1147 std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
1148 std::list< FunctionType *> functions;
1149 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
1150 Type *orig = (*arg)->get_type();
1151 findAndReplaceFunction( orig, functions, scopeTyVars, needsAdapter );
1152 (*arg)->set_type( orig );
1153 }
1154 std::set< std::string > adaptersDone;
1155 for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
[bdf1954]1156 std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
[01aeade]1157 if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
1158 std::string adapterName = makeAdapterName( mangleName );
[68cd1ce]1159 paramList.push_front( new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) );
[01aeade]1160 adaptersDone.insert( adaptersDone.begin(), mangleName );
1161 }
1162 }
[5f6c42c]1163// deleteAll( functions );
[01aeade]1164 }
[6c3744e]1165
[01aeade]1166 template< typename DeclClass >
1167 DeclClass * Pass2::handleDecl( DeclClass *decl, Type *type ) {
1168 DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
[6c3744e]1169
[01aeade]1170 return ret;
1171 }
[6c3744e]1172
[01aeade]1173 DeclarationWithType * Pass2::mutate( FunctionDecl *functionDecl ) {
1174 return handleDecl( functionDecl, functionDecl->get_functionType() );
1175 }
[6c3744e]1176
[01aeade]1177 ObjectDecl * Pass2::mutate( ObjectDecl *objectDecl ) {
1178 return handleDecl( objectDecl, objectDecl->get_type() );
1179 }
[6c3744e]1180
[01aeade]1181 TypeDecl * Pass2::mutate( TypeDecl *typeDecl ) {
1182 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1183 if ( typeDecl->get_base() ) {
1184 return handleDecl( typeDecl, typeDecl->get_base() );
1185 } else {
1186 return Mutator::mutate( typeDecl );
1187 }
1188 }
[6c3744e]1189
[01aeade]1190 TypedefDecl * Pass2::mutate( TypedefDecl *typedefDecl ) {
1191 return handleDecl( typedefDecl, typedefDecl->get_base() );
1192 }
[6c3744e]1193
[01aeade]1194 Type * Pass2::mutate( PointerType *pointerType ) {
1195 TyVarMap oldtyVars = scopeTyVars;
1196 makeTyVarMap( pointerType, scopeTyVars );
[ae63a18]1197
[01aeade]1198 Type *ret = Mutator::mutate( pointerType );
[ae63a18]1199
[01aeade]1200 scopeTyVars = oldtyVars;
1201 return ret;
1202 }
[6c3744e]1203
[01aeade]1204 Type *Pass2::mutate( FunctionType *funcType ) {
1205 TyVarMap oldtyVars = scopeTyVars;
1206 makeTyVarMap( funcType, scopeTyVars );
[7754cde]1207
1208 // move polymorphic return type to parameter list
[aadc9a4]1209 if ( isPolyRet( funcType ) ) {
[01aeade]1210 DeclarationWithType *ret = funcType->get_returnVals().front();
1211 ret->set_type( new PointerType( Type::Qualifiers(), ret->get_type() ) );
1212 funcType->get_parameters().push_front( ret );
1213 funcType->get_returnVals().pop_front();
1214 }
[7754cde]1215
1216 // add size/align and assertions for type parameters to parameter list
[01aeade]1217 std::list< DeclarationWithType *>::iterator last = funcType->get_parameters().begin();
1218 std::list< DeclarationWithType *> inferredParams;
[78dd0da]1219 ObjectDecl newObj( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), 0 );
[05d47278]1220 ObjectDecl newPtr( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0,
1221 new PointerType( Type::Qualifiers(), new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ) ), 0 );
[f8b961b]1222// ObjectDecl *newFunPtr = new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) ), 0 );
[01aeade]1223 for ( std::list< TypeDecl *>::const_iterator tyParm = funcType->get_forall().begin(); tyParm != funcType->get_forall().end(); ++tyParm ) {
[db0b3ce]1224 ObjectDecl *sizeParm, *alignParm;
1225 // add all size and alignment parameters to parameter list
[01aeade]1226 if ( (*tyParm)->get_kind() == TypeDecl::Any ) {
[78dd0da]1227 TypeInstType parmType( Type::Qualifiers(), (*tyParm)->get_name(), *tyParm );
[ae63a18]1228
[78dd0da]1229 sizeParm = newObj.clone();
1230 sizeParm->set_name( sizeofName( &parmType ) );
[db0b3ce]1231 last = funcType->get_parameters().insert( last, sizeParm );
1232 ++last;
[78dd0da]1233
1234 alignParm = newObj.clone();
1235 alignParm->set_name( alignofName( &parmType ) );
[db0b3ce]1236 last = funcType->get_parameters().insert( last, alignParm );
[01aeade]1237 ++last;
1238 }
[e56cfdb0]1239 // move all assertions into parameter list
[01aeade]1240 for ( std::list< DeclarationWithType *>::iterator assert = (*tyParm)->get_assertions().begin(); assert != (*tyParm)->get_assertions().end(); ++assert ) {
[f8b961b]1241// *assert = (*assert)->acceptMutator( *this );
[01aeade]1242 inferredParams.push_back( *assert );
1243 }
1244 (*tyParm)->get_assertions().clear();
1245 }
[7754cde]1246
[5c52b06]1247 // add size/align for generic parameter types to parameter list
[b18b0b5]1248 std::set< std::string > seenTypes; // sizeofName for generic types we've seen
[7754cde]1249 for ( std::list< DeclarationWithType* >::const_iterator fnParm = last; fnParm != funcType->get_parameters().end(); ++fnParm ) {
[32805db]1250 Type *polyBase = hasPolyBase( (*fnParm)->get_type(), scopeTyVars );
1251 if ( polyBase && ! dynamic_cast< TypeInstType* >( polyBase ) ) {
1252 std::string sizeName = sizeofName( polyBase );
[7754cde]1253 if ( seenTypes.count( sizeName ) ) continue;
[ae63a18]1254
[05d47278]1255 ObjectDecl *sizeParm, *alignParm, *offsetParm;
[7754cde]1256 sizeParm = newObj.clone();
1257 sizeParm->set_name( sizeName );
1258 last = funcType->get_parameters().insert( last, sizeParm );
1259 ++last;
1260
1261 alignParm = newObj.clone();
[32805db]1262 alignParm->set_name( alignofName( polyBase ) );
[7754cde]1263 last = funcType->get_parameters().insert( last, alignParm );
1264 ++last;
1265
[32805db]1266 if ( dynamic_cast< StructInstType* >( polyBase ) ) {
[05d47278]1267 offsetParm = newPtr.clone();
[32805db]1268 offsetParm->set_name( offsetofName( polyBase ) );
[05d47278]1269 last = funcType->get_parameters().insert( last, offsetParm );
1270 ++last;
1271 }
1272
[7754cde]1273 seenTypes.insert( sizeName );
1274 }
1275 }
1276
1277 // splice assertion parameters into parameter list
[01aeade]1278 funcType->get_parameters().splice( last, inferredParams );
1279 addAdapters( funcType );
1280 mutateAll( funcType->get_returnVals(), *this );
1281 mutateAll( funcType->get_parameters(), *this );
[ae63a18]1282
[01aeade]1283 scopeTyVars = oldtyVars;
1284 return funcType;
1285 }
[51b73452]1286
[05d47278]1287////////////////////////////////////////// MemberExprFixer ////////////////////////////////////////////////////
[51b73452]1288
[01aeade]1289 template< typename DeclClass >
[05d47278]1290 DeclClass * MemberExprFixer::handleDecl( DeclClass *decl, Type *type ) {
[01aeade]1291 TyVarMap oldtyVars = scopeTyVars;
1292 makeTyVarMap( type, scopeTyVars );
[ae63a18]1293
[01aeade]1294 DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
[6c3744e]1295
[01aeade]1296 scopeTyVars = oldtyVars;
1297 return ret;
1298 }
[6c3744e]1299
[05d47278]1300 ObjectDecl * MemberExprFixer::mutate( ObjectDecl *objectDecl ) {
[01aeade]1301 return handleDecl( objectDecl, objectDecl->get_type() );
1302 }
[6c3744e]1303
[05d47278]1304 DeclarationWithType * MemberExprFixer::mutate( FunctionDecl *functionDecl ) {
[01aeade]1305 return handleDecl( functionDecl, functionDecl->get_functionType() );
1306 }
[6c3744e]1307
[05d47278]1308 TypedefDecl * MemberExprFixer::mutate( TypedefDecl *typedefDecl ) {
[01aeade]1309 return handleDecl( typedefDecl, typedefDecl->get_base() );
1310 }
[6c3744e]1311
[05d47278]1312 TypeDecl * MemberExprFixer::mutate( TypeDecl *typeDecl ) {
[01aeade]1313 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1314 return Mutator::mutate( typeDecl );
1315 }
[51b73452]1316
[05d47278]1317 Type * MemberExprFixer::mutate( PointerType *pointerType ) {
[01aeade]1318 TyVarMap oldtyVars = scopeTyVars;
1319 makeTyVarMap( pointerType, scopeTyVars );
[ae63a18]1320
[01aeade]1321 Type *ret = Mutator::mutate( pointerType );
[ae63a18]1322
[01aeade]1323 scopeTyVars = oldtyVars;
1324 return ret;
1325 }
[6c3744e]1326
[05d47278]1327 Type * MemberExprFixer::mutate( FunctionType *functionType ) {
[01aeade]1328 TyVarMap oldtyVars = scopeTyVars;
1329 makeTyVarMap( functionType, scopeTyVars );
[ae63a18]1330
[01aeade]1331 Type *ret = Mutator::mutate( functionType );
[ae63a18]1332
[01aeade]1333 scopeTyVars = oldtyVars;
1334 return ret;
[6c3744e]1335 }
[51b73452]1336
[05d47278]1337 Statement *MemberExprFixer::mutate( DeclStmt *declStmt ) {
[01aeade]1338 if ( ObjectDecl *objectDecl = dynamic_cast< ObjectDecl *>( declStmt->get_decl() ) ) {
[ffad73a]1339 if ( isPolyType( objectDecl->get_type(), scopeTyVars ) ) {
[e01559c]1340 // change initialization of a polymorphic value object
1341 // to allocate storage with alloca
[ffad73a]1342 Type *declType = objectDecl->get_type();
[01aeade]1343 UntypedExpr *alloc = new UntypedExpr( new NameExpr( "__builtin_alloca" ) );
[ffad73a]1344 alloc->get_args().push_back( new NameExpr( sizeofName( declType ) ) );
[e01559c]1345
1346 delete objectDecl->get_init();
1347
1348 std::list<Expression*> designators;
1349 objectDecl->set_init( new SingleInit( alloc, designators ) );
[01aeade]1350 }
1351 }
1352 return Mutator::mutate( declStmt );
1353 }
[05d47278]1354
[2a4b088]1355 /// Finds the member in the base list that matches the given declaration; returns its index, or -1 if not present
1356 long findMember( DeclarationWithType *memberDecl, std::list< Declaration* > &baseDecls ) {
1357 long i = 0;
1358 for(std::list< Declaration* >::const_iterator decl = baseDecls.begin(); decl != baseDecls.end(); ++decl, ++i ) {
1359 if ( memberDecl->get_name() != (*decl)->get_name() ) continue;
1360
1361 if ( DeclarationWithType *declWithType = dynamic_cast< DeclarationWithType* >( *decl ) ) {
[bed4d37c]1362 if ( memberDecl->get_mangleName().empty() || declWithType->get_mangleName().empty()
1363 || memberDecl->get_mangleName() == declWithType->get_mangleName() ) return i;
[2a4b088]1364 else continue;
1365 } else return i;
1366 }
1367 return -1;
1368 }
1369
1370 /// Returns an index expression into the offset array for a type
1371 Expression *makeOffsetIndex( Type *objectType, long i ) {
1372 std::stringstream offset_namer;
1373 offset_namer << i;
1374 ConstantExpr *fieldIndex = new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), offset_namer.str() ) );
1375 UntypedExpr *fieldOffset = new UntypedExpr( new NameExpr( "?[?]" ) );
1376 fieldOffset->get_args().push_back( new NameExpr( offsetofName( objectType ) ) );
1377 fieldOffset->get_args().push_back( fieldIndex );
1378 return fieldOffset;
1379 }
1380
1381 /// Returns an expression dereferenced n times
1382 Expression *makeDerefdVar( Expression *derefdVar, long n ) {
1383 for ( int i = 1; i < n; ++i ) {
1384 UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
1385 derefExpr->get_args().push_back( derefdVar );
1386 derefdVar = derefExpr;
1387 }
1388 return derefdVar;
1389 }
1390
[05d47278]1391 Expression *MemberExprFixer::mutate( MemberExpr *memberExpr ) {
1392 // mutate, exiting early if no longer MemberExpr
1393 Expression *expr = Mutator::mutate( memberExpr );
1394 memberExpr = dynamic_cast< MemberExpr* >( expr );
1395 if ( ! memberExpr ) return expr;
1396
1397 // get declaration for base struct, exiting early if not found
[8488c715]1398 int varDepth;
1399 VariableExpr *varExpr = getBaseVar( memberExpr->get_aggregate(), &varDepth );
[05d47278]1400 if ( ! varExpr ) return memberExpr;
1401 ObjectDecl *objectDecl = dynamic_cast< ObjectDecl* >( varExpr->get_var() );
1402 if ( ! objectDecl ) return memberExpr;
1403
1404 // only mutate member expressions for polymorphic types
[8488c715]1405 int tyDepth;
1406 Type *objectType = hasPolyBase( objectDecl->get_type(), scopeTyVars, &tyDepth );
[05d47278]1407 if ( ! objectType ) return memberExpr;
1408
[4318107]1409 Expression *newMemberExpr = 0;
[05d47278]1410 if ( StructInstType *structType = dynamic_cast< StructInstType* >( objectType ) ) {
[2a4b088]1411 // look up offset index
1412 long i = findMember( memberExpr->get_member(), structType->get_baseStruct()->get_members() );
1413 if ( i == -1 ) return memberExpr;
[05d47278]1414
[2a4b088]1415 // replace member expression with pointer to base plus offset
1416 UntypedExpr *fieldLoc = new UntypedExpr( new NameExpr( "?+?" ) );
1417 fieldLoc->get_args().push_back( makeDerefdVar( varExpr->clone(), varDepth ) );
1418 fieldLoc->get_args().push_back( makeOffsetIndex( objectType, i ) );
[4318107]1419 newMemberExpr = fieldLoc;
[98735ef]1420 } else if ( dynamic_cast< UnionInstType* >( objectType ) ) {
[2a4b088]1421 // union members are all at offset zero, so build appropriately-dereferenced variable
[4318107]1422 newMemberExpr = makeDerefdVar( varExpr->clone(), varDepth );
[2a4b088]1423 } else return memberExpr;
[4318107]1424 assert( newMemberExpr );
1425
1426 // wrap pointer members in appropriate cast
1427 if ( dynamic_cast< PointerType* >( memberExpr->get_member()->get_type() ) ) {
1428 CastExpr *ptrCastExpr = new CastExpr( newMemberExpr, new PointerType( Type::Qualifiers(), new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ) ) );
1429 UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
1430 derefExpr->get_args().push_back( ptrCastExpr );
1431 newMemberExpr = derefExpr;
1432 }
1433
1434 delete memberExpr;
1435 return newMemberExpr;
[2a4b088]1436 }
[05d47278]1437
[2a4b088]1438 Expression *MemberExprFixer::mutate( OffsetofExpr *offsetofExpr ) {
1439 // mutate, exiting early if no longer OffsetofExpr
1440 Expression *expr = Mutator::mutate( offsetofExpr );
1441 offsetofExpr = dynamic_cast< OffsetofExpr* >( expr );
1442 if ( ! offsetofExpr ) return expr;
1443
1444 // only mutate expressions for polymorphic structs/unions
1445 Type *ty = isPolyType( offsetofExpr->get_type(), scopeTyVars );
1446 if ( ! ty ) return offsetofExpr;
1447
1448 if ( StructInstType *structType = dynamic_cast< StructInstType* >( ty ) ) {
1449 // replace offsetof expression by index into offset array
1450 long i = findMember( offsetofExpr->get_member(), structType->get_baseStruct()->get_members() );
1451 if ( i == -1 ) return offsetofExpr;
1452
1453 Expression *offsetInd = makeOffsetIndex( ty, i );
1454 delete offsetofExpr;
1455 return offsetInd;
[5c52b06]1456 } else if ( dynamic_cast< UnionInstType* >( ty ) ) {
[2a4b088]1457 // all union members are at offset zero
1458 delete offsetofExpr;
1459 return new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), std::string("0") ) );
1460 } else return offsetofExpr;
[05d47278]1461 }
1462
1463////////////////////////////////////////// Pass3 ////////////////////////////////////////////////////
1464
1465 template< typename DeclClass >
1466 DeclClass * Pass3::handleDecl( DeclClass *decl, Type *type ) {
1467 TyVarMap oldtyVars = scopeTyVars;
1468 makeTyVarMap( type, scopeTyVars );
1469
1470 DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
1471 ScrubTyVars::scrub( decl, scopeTyVars );
1472
1473 scopeTyVars = oldtyVars;
1474 return ret;
1475 }
1476
1477 ObjectDecl * Pass3::mutate( ObjectDecl *objectDecl ) {
1478 return handleDecl( objectDecl, objectDecl->get_type() );
1479 }
1480
1481 DeclarationWithType * Pass3::mutate( FunctionDecl *functionDecl ) {
1482 return handleDecl( functionDecl, functionDecl->get_functionType() );
1483 }
1484
1485 TypedefDecl * Pass3::mutate( TypedefDecl *typedefDecl ) {
1486 return handleDecl( typedefDecl, typedefDecl->get_base() );
1487 }
1488
1489 TypeDecl * Pass3::mutate( TypeDecl *typeDecl ) {
1490// Initializer *init = 0;
1491// std::list< Expression *> designators;
1492// scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1493// if ( typeDecl->get_base() ) {
1494// init = new SimpleInit( new SizeofExpr( handleDecl( typeDecl, typeDecl->get_base() ) ), designators );
1495// }
1496// return new ObjectDecl( typeDecl->get_name(), Declaration::Extern, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::UnsignedInt ), init );
1497
1498 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1499 return Mutator::mutate( typeDecl );
1500 }
1501
1502 Type * Pass3::mutate( PointerType *pointerType ) {
1503 TyVarMap oldtyVars = scopeTyVars;
1504 makeTyVarMap( pointerType, scopeTyVars );
1505
1506 Type *ret = Mutator::mutate( pointerType );
1507
1508 scopeTyVars = oldtyVars;
1509 return ret;
1510 }
1511
1512 Type * Pass3::mutate( FunctionType *functionType ) {
1513 TyVarMap oldtyVars = scopeTyVars;
1514 makeTyVarMap( functionType, scopeTyVars );
1515
1516 Type *ret = Mutator::mutate( functionType );
1517
1518 scopeTyVars = oldtyVars;
1519 return ret;
1520 }
[01aeade]1521 } // anonymous namespace
[51b73452]1522} // namespace GenPoly
[01aeade]1523
[51587aa]1524// Local Variables: //
1525// tab-width: 4 //
1526// mode: c++ //
1527// compile-command: "make install" //
1528// End: //
Note: See TracBrowser for help on using the repository browser.