source: src/GenPoly/Box.cc @ f8b961b

aaron-thesisarm-ehcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decaygc_noraiijacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newstringwith_gc
Last change on this file since f8b961b was f8b961b, checked in by Aaron Moss <a3moss@…>, 7 years ago

Documentation improvements

  • Property mode set to 100644
File size: 47.9 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// Box.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Mon May 18 07:44:20 2015
11// Last Modified By : Rob Schluntz
12// Last Modified On : Thu Nov 26 17:01:55 2015
13// Update Count     : 191
14//
15
16#include <set>
17#include <stack>
18#include <string>
19#include <iterator>
20#include <algorithm>
21#include <cassert>
22
23#include "Box.h"
24#include "PolyMutator.h"
25#include "FindFunction.h"
26#include "ScrubTyVars.h"
27
28#include "Parser/ParseNode.h"
29
30#include "SynTree/Type.h"
31#include "SynTree/Expression.h"
32#include "SynTree/Initializer.h"
33#include "SynTree/Statement.h"
34#include "SynTree/Mutator.h"
35
36#include "ResolvExpr/TypeEnvironment.h"
37
38#include "SymTab/Mangler.h"
39
40#include "SemanticError.h"
41#include "UniqueName.h"
42#include "utility.h"
43
44#include <ext/functional> // temporary
45
46namespace GenPoly {
47        namespace {
48                const std::list<Label> noLabels;
49
50                FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars );
51
52                /// 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
53                class Pass1 : public PolyMutator {
54                  public:
55                        Pass1();
56                        virtual Expression *mutate( ApplicationExpr *appExpr );
57                        virtual Expression *mutate( AddressExpr *addrExpr );
58                        virtual Expression *mutate( UntypedExpr *expr );
59                        virtual DeclarationWithType* mutate( FunctionDecl *functionDecl );
60                        virtual TypeDecl *mutate( TypeDecl *typeDecl );
61                        virtual Expression *mutate( CommaExpr *commaExpr );
62                        virtual Expression *mutate( ConditionalExpr *condExpr );
63                        virtual Statement *mutate(ReturnStmt *catchStmt);
64                        virtual Type *mutate( PointerType *pointerType );
65                        virtual Type *mutate( FunctionType *pointerType );
66 
67                        virtual void doBeginScope();
68                        virtual void doEndScope();
69                  private:
70                        void passTypeVars( ApplicationExpr *appExpr, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
71                        Expression *addRetParam( ApplicationExpr *appExpr, FunctionType *function, Type *retType, std::list< Expression *>::iterator &arg );
72                        Expression *addPolyRetParam( ApplicationExpr *appExpr, FunctionType *function, std::string typeName, std::list< Expression *>::iterator &arg );
73                        Expression *applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
74                        void boxParam( Type *formal, Expression *&arg, const TyVarMap &exprTyVars );
75                        void boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
76                        void addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars );
77                        void findAssignOps( const std::list< TypeDecl *> &forall );
78                        void passAdapters( ApplicationExpr *appExpr, FunctionType *functionType, const TyVarMap &exprTyVars );
79                        FunctionDecl *makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars );
80                        Expression *handleIntrinsics( ApplicationExpr *appExpr );
81                        ObjectDecl *makeTemporary( Type *type );
82
83                        typedef std::map< std::string, DeclarationWithType *> AdapterMap;
84                        std::map< std::string, DeclarationWithType *> assignOps;
85                        std::stack< AdapterMap > adapters;
86                        DeclarationWithType *retval;
87                        bool useRetval;
88                        UniqueName tempNamer;
89                };
90
91                /// Moves polymorphic returns in function types to pointer-type parameters, adds type size and assertion parameters to parameter lists as well
92                class Pass2 : public PolyMutator {
93                  public:
94                        Pass2();
95                        template< typename DeclClass >
96                        DeclClass *handleDecl( DeclClass *decl, Type *type );
97                        virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
98                        virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
99                        virtual TypeDecl *mutate( TypeDecl *typeDecl );
100                        virtual TypedefDecl *mutate( TypedefDecl *typedefDecl );
101                        virtual Type *mutate( PointerType *pointerType );
102                        virtual Type *mutate( FunctionType *funcType );
103                  private:
104                        void addAdapters( FunctionType *functionType );
105 
106                        std::map< UniqueId, std::string > adapterName;
107                };
108
109                /// 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
110                class Pass3 : public PolyMutator {
111                  public:
112                        template< typename DeclClass >
113                        DeclClass *handleDecl( DeclClass *decl, Type *type );
114                        virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
115                        virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
116                        virtual TypedefDecl *mutate( TypedefDecl *objectDecl );
117                        virtual TypeDecl *mutate( TypeDecl *objectDecl );
118                        virtual Statement *mutate( DeclStmt *declStmt );
119                        virtual Type *mutate( PointerType *pointerType );
120                        virtual Type *mutate( FunctionType *funcType );
121                  private:
122                };
123
124        } // anonymous namespace
125
126        void printAllNotBuiltin( const std::list< Declaration *>& translationUnit, std::ostream &os ) {
127                for ( std::list< Declaration *>::const_iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
128                        if ( ! LinkageSpec::isBuiltin( (*i)->get_linkage() ) ) {
129                                (*i)->print( os );
130                                os << std::endl;
131                        } // if
132                } // for
133        }
134
135        void box( std::list< Declaration *>& translationUnit ) {
136                Pass1 pass1;
137                Pass2 pass2;
138                Pass3 pass3;
139                mutateAll( translationUnit, pass1 );
140                mutateAll( translationUnit, pass2 );
141                mutateAll( translationUnit, pass3 );
142        }
143
144        ////////////////////////////////////////// Pass1 ////////////////////////////////////////////////////
145
146        namespace {
147                std::string makePolyMonoSuffix( FunctionType * function, const TyVarMap &tyVars ) {
148                        std::stringstream name;
149
150                        // NOTE: this function previously used isPolyObj, which failed to produce
151                        // the correct thing in some situations. It's not clear to me why this wasn't working.
152
153                        // if the return type or a parameter type involved polymorphic types, then the adapter will need
154                        // to take those polymorphic types as pointers. Therefore, there can be two different functions
155                        // with the same mangled name, so we need to further mangle the names.
156                        for ( std::list< DeclarationWithType *>::iterator retval = function->get_returnVals().begin(); retval != function->get_returnVals().end(); ++retval ) {
157                                if ( isPolyVal( (*retval)->get_type(), tyVars ) ) {
158                                        name << "P";
159                                } else {
160                                        name << "M";
161                                }
162                        }
163                        name << "_";
164                        std::list< DeclarationWithType *> &paramList = function->get_parameters();
165                        for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
166                                if ( isPolyVal( (*arg)->get_type(), tyVars ) ) {
167                                        name << "P";
168                                } else {
169                                        name << "M";                           
170                                }
171                        } // for
172                        return name.str();
173                }
174
175                std::string mangleAdapterName( FunctionType * function, const TyVarMap &tyVars ) {
176                        return SymTab::Mangler::mangle( function ) + makePolyMonoSuffix( function, tyVars );
177                }
178
179                std::string makeAdapterName( const std::string &mangleName ) {
180                        return "_adapter" + mangleName;
181                }
182
183                Pass1::Pass1()
184                        : useRetval( false ), tempNamer( "_temp" ) {
185                        adapters.push(AdapterMap());
186                }
187
188                bool checkAssignment( DeclarationWithType *decl, std::string &name ) {
189                        if ( decl->get_name() == "?=?" ) {
190                                if ( PointerType *ptrType = dynamic_cast< PointerType *>( decl->get_type() ) ) {
191                                        if ( FunctionType *funType = dynamic_cast< FunctionType *>( ptrType->get_base() ) ) {
192                                                if ( funType->get_parameters().size() == 2 ) {
193                                                        if ( PointerType *pointer = dynamic_cast< PointerType *>( funType->get_parameters().front()->get_type() ) ) {
194                                                                if ( TypeInstType *typeInst = dynamic_cast< TypeInstType *>( pointer->get_base() ) ) {
195                                                                        name = typeInst->get_name();
196                                                                        return true;
197                                                                } // if
198                                                        } // if
199                                                } // if
200                                        } // if
201                                } // if
202                        } // if
203                        return false;
204                }
205
206                void Pass1::findAssignOps( const std::list< TypeDecl *> &forall ) {
207                        // what if a nested function uses an assignment operator?
208                        // assignOps.clear();
209                        for ( std::list< TypeDecl *>::const_iterator i = forall.begin(); i != forall.end(); ++i ) {
210                                for ( std::list< DeclarationWithType *>::const_iterator assert = (*i)->get_assertions().begin(); assert != (*i)->get_assertions().end(); ++assert ) {
211                                        std::string typeName;
212                                        if ( checkAssignment( *assert, typeName ) ) {
213                                                assignOps[ typeName ] = *assert;
214                                        } // if
215                                } // for
216                        } // for
217                }
218
219                DeclarationWithType *Pass1::mutate( FunctionDecl *functionDecl ) {
220                        if ( functionDecl->get_statements() ) {         // empty routine body ?
221                                doBeginScope();
222                                TyVarMap oldtyVars = scopeTyVars;
223                                std::map< std::string, DeclarationWithType *> oldassignOps = assignOps;
224                                DeclarationWithType *oldRetval = retval;
225                                bool oldUseRetval = useRetval;
226
227                                // process polymorphic return value
228                                retval = 0;
229                                std::string typeName;
230                                if ( isPolyRet( functionDecl->get_functionType(), typeName ) && functionDecl->get_linkage() == LinkageSpec::Cforall ) {
231                                        retval = functionDecl->get_functionType()->get_returnVals().front();
232 
233                                        // give names to unnamed return values
234                                        if ( retval->get_name() == "" ) {
235                                                retval->set_name( "_retparm" );
236                                                retval->set_linkage( LinkageSpec::C );
237                                        } // if
238                                } // if
239       
240                                FunctionType *functionType = functionDecl->get_functionType();
241                                makeTyVarMap( functionDecl->get_functionType(), scopeTyVars );
242                                findAssignOps( functionDecl->get_functionType()->get_forall() );
243
244                                std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
245                                std::list< FunctionType *> functions;
246                                for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
247                                        for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
248                                                findFunction( (*assert)->get_type(), functions, scopeTyVars, needsAdapter );
249                                        } // for
250                                } // for
251                                for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
252                                        findFunction( (*arg)->get_type(), functions, scopeTyVars, needsAdapter );
253                                } // for
254                                AdapterMap & adapters = Pass1::adapters.top();
255                                for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
256                                        std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
257                                        if ( adapters.find( mangleName ) == adapters.end() ) {
258                                                std::string adapterName = makeAdapterName( mangleName );
259                                                adapters.insert( std::pair< std::string, DeclarationWithType *>( mangleName, new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) ) );
260                                        } // if
261                                } // for
262
263                                functionDecl->set_statements( functionDecl->get_statements()->acceptMutator( *this ) );
264 
265                                scopeTyVars = oldtyVars;
266                                assignOps = oldassignOps;
267                                // std::cerr << "end FunctionDecl: ";
268                                // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
269                                //      std::cerr << i->first << " ";
270                                // }
271                                // std::cerr << "\n";
272                                retval = oldRetval;
273                                useRetval = oldUseRetval;
274                                doEndScope();
275                        } // if
276                        return functionDecl;
277                }
278
279                TypeDecl *Pass1::mutate( TypeDecl *typeDecl ) {
280///     std::cerr << "add " << typeDecl->get_name() << "\n";
281                        scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
282                        return Mutator::mutate( typeDecl );
283                }
284
285                Expression *Pass1::mutate( CommaExpr *commaExpr ) {
286                        bool oldUseRetval = useRetval;
287                        useRetval = false;
288                        commaExpr->set_arg1( maybeMutate( commaExpr->get_arg1(), *this ) );
289                        useRetval = oldUseRetval;
290                        commaExpr->set_arg2( maybeMutate( commaExpr->get_arg2(), *this ) );
291                        return commaExpr;
292                }
293
294                Expression *Pass1::mutate( ConditionalExpr *condExpr ) {
295                        bool oldUseRetval = useRetval;
296                        useRetval = false;
297                        condExpr->set_arg1( maybeMutate( condExpr->get_arg1(), *this ) );
298                        useRetval = oldUseRetval;
299                        condExpr->set_arg2( maybeMutate( condExpr->get_arg2(), *this ) );
300                        condExpr->set_arg3( maybeMutate( condExpr->get_arg3(), *this ) );
301                        return condExpr;
302
303                }
304
305                void Pass1::passTypeVars( ApplicationExpr *appExpr, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
306                        for ( TyVarMap::const_iterator tyParm = exprTyVars.begin(); tyParm != exprTyVars.end(); ++tyParm ) {
307                                ResolvExpr::EqvClass eqvClass;
308                                assert( env );
309                                if ( tyParm->second == TypeDecl::Any ) {
310                                        Type *concrete = env->lookup( tyParm->first );
311                                        if ( concrete ) {
312                                                arg = appExpr->get_args().insert( arg, new SizeofExpr( concrete->clone() ) );
313                                                arg++;
314                                        } else {
315                                                throw SemanticError( "unbound type variable in application ", appExpr );
316                                        } // if
317                                } // if
318                        } // for
319                }
320
321                ObjectDecl *Pass1::makeTemporary( Type *type ) {
322                        ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, type, 0 );
323                        stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
324                        return newObj;
325                }
326
327                TypeInstType *isPolyType( Type *type, const TypeSubstitution *env, const TyVarMap &tyVars ) {
328                        if ( TypeInstType *typeInst = dynamic_cast< TypeInstType *>( type ) ) {
329                                if ( env ) {
330                                        if ( Type *newType = env->lookup( typeInst->get_name() ) ) {
331                                                return isPolyType( newType, env, tyVars );
332                                        } // if
333                                } // if
334                                if ( tyVars.find( typeInst->get_name() ) != tyVars.end() ) {
335                                        return typeInst;
336                                } else {
337                                        return 0;
338                                } // if
339                        } else {
340                                return 0;
341                        } // if
342                }
343
344                Expression *Pass1::addRetParam( ApplicationExpr *appExpr, FunctionType *function, Type *retType, std::list< Expression *>::iterator &arg ) {
345                        if ( useRetval ) {
346                                assert( retval );
347                                arg = appExpr->get_args().insert( arg, new VariableExpr( retval ) );
348                                arg++;
349                        } else {
350                                ObjectDecl *newObj = makeTemporary( retType->clone() );
351                                Expression *paramExpr = new VariableExpr( newObj );
352                                if ( ! isPolyType( newObj->get_type(), env, scopeTyVars ) ) {
353                                        paramExpr = new AddressExpr( paramExpr );
354                                } // if
355                                arg = appExpr->get_args().insert( arg, paramExpr );
356                                arg++;
357///     stmtsToAdd.push_back( new ExprStmt( noLabels, appExpr ) );
358                                CommaExpr *commaExpr = new CommaExpr( appExpr, new VariableExpr( newObj ) );
359                                commaExpr->set_env( appExpr->get_env() );
360                                appExpr->set_env( 0 );
361                                return commaExpr;
362                        } // if
363                        return appExpr;
364                }
365
366                Expression *Pass1::addPolyRetParam( ApplicationExpr *appExpr, FunctionType *function, std::string typeName, std::list< Expression *>::iterator &arg ) {
367                        ResolvExpr::EqvClass eqvClass;
368                        assert( env );
369                        Type *concrete = env->lookup( typeName );
370                        if ( concrete == 0 ) {
371                                throw SemanticError( "Unbound type variable " + typeName + " in ", appExpr );
372                        } // if
373                        return addRetParam( appExpr, function, concrete, arg );
374                }
375
376                Expression *Pass1::applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
377                        Expression *ret = appExpr;
378                        if ( ! function->get_returnVals().empty() && isPolyVal( function->get_returnVals().front()->get_type(), tyVars ) ) {
379                                ret = addRetParam( appExpr, function, function->get_returnVals().front()->get_type(), arg );
380                        } // if
381                        std::string mangleName = mangleAdapterName( function, tyVars );
382                        std::string adapterName = makeAdapterName( mangleName );
383
384                        appExpr->get_args().push_front( appExpr->get_function() );
385                        appExpr->set_function( new NameExpr( adapterName ) );
386 
387                        return ret;
388                }
389
390                void Pass1::boxParam( Type *param, Expression *&arg, const TyVarMap &exprTyVars ) {
391                        assert( ! arg->get_results().empty() );
392///   if ( ! dynamic_cast< PointerType *>( arg->get_results().front() ) ) {
393                        TypeInstType *typeInst = dynamic_cast< TypeInstType *>( param );
394                        if ( typeInst && exprTyVars.find( typeInst->get_name() ) != exprTyVars.end() ) {
395                                if ( dynamic_cast< TypeInstType *>( arg->get_results().front() ) ) {
396                                        // if the argument's type is a type parameter, we don't need to box again!
397                                        return;
398                                } else if ( arg->get_results().front()->get_isLvalue() ) {
399                                        // VariableExpr and MemberExpr are lvalues
400                                        arg = new AddressExpr( arg );
401                                } else {
402                                        ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, arg->get_results().front()->clone(), 0 );
403                                        newObj->get_type()->get_qualifiers() = Type::Qualifiers(); // TODO: is this right???
404                                        stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
405                                        UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
406                                        assign->get_args().push_back( new VariableExpr( newObj ) );
407                                        assign->get_args().push_back( arg );
408                                        stmtsToAdd.push_back( new ExprStmt( noLabels, assign ) );
409                                        arg = new AddressExpr( new VariableExpr( newObj ) );
410                                } // if
411                        } // if
412///   }
413                }
414
415                void addCast( Expression *&actual, Type *formal, const TyVarMap &tyVars ) {
416                        Type *newType = formal->clone();
417                        std::list< FunctionType *> functions;
418                        // instead of functions needing adapters, this really ought to look for
419                        // any function mentioning a polymorphic type
420                        findAndReplaceFunction( newType, functions, tyVars, needsAdapter );
421                        if ( ! functions.empty() ) {
422                                actual = new CastExpr( actual, newType );
423                        } else {
424                                delete newType;
425                        } // if
426                }
427
428                void Pass1::boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
429///   std::cout << "function is ";
430///   function->print( std::cout );
431                        for ( std::list< DeclarationWithType *>::const_iterator param = function->get_parameters().begin(); param != function->get_parameters().end(); ++param, ++arg ) {
432///     std::cout << "parameter is ";
433///     (*param)->print( std::fcout );
434///     std::cout << std::endl << "argument is ";
435///     (*arg)->print( std::cout );
436                                assert( arg != appExpr->get_args().end() );
437                                addCast( *arg, (*param)->get_type(), exprTyVars );
438                                boxParam( (*param)->get_type(), *arg, exprTyVars );
439                        } // for
440                }
441
442                void Pass1::addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
443                        std::list< Expression *>::iterator cur = arg;
444                        for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
445                                for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
446                                        InferredParams::const_iterator inferParam = appExpr->get_inferParams().find( (*assert)->get_uniqueId() );
447                                        assert( inferParam != appExpr->get_inferParams().end() && "NOTE: Explicit casts of polymorphic functions to compatible monomorphic functions are currently unsupported" );
448                                        Expression *newExpr = inferParam->second.expr->clone();
449                                        addCast( newExpr, (*assert)->get_type(), tyVars );
450                                        boxParam( (*assert)->get_type(), newExpr, tyVars );
451                                        appExpr->get_args().insert( cur, newExpr );
452                                } // for
453                        } // for
454                }
455
456                void makeRetParm( FunctionType *funcType ) {
457                        DeclarationWithType *retParm = funcType->get_returnVals().front();
458
459                        // make a new parameter that is a pointer to the type of the old return value
460                        retParm->set_type( new PointerType( Type::Qualifiers(), retParm->get_type() ) );
461                        funcType->get_parameters().push_front( retParm );
462
463                        // we don't need the return value any more
464                        funcType->get_returnVals().clear();
465                }
466
467                FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars ) {
468                        // actually make the adapter type
469                        FunctionType *adapter = adaptee->clone();
470                        if ( ! adapter->get_returnVals().empty() && isPolyVal( adapter->get_returnVals().front()->get_type(), tyVars ) ) {
471                                makeRetParm( adapter );
472                        } // if
473                        adapter->get_parameters().push_front( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) ), 0 ) );
474                        return adapter;
475                }
476
477                Expression *makeAdapterArg( DeclarationWithType *param, DeclarationWithType *arg, DeclarationWithType *realParam, const TyVarMap &tyVars ) {
478                        assert( param );
479                        assert( arg );
480///   std::cout << "arg type is ";
481///   arg->get_type()->print( std::cout );
482///   std::cout << "param type is ";
483///   param->get_type()->print( std::cout );
484///   std::cout << " tyVars are: ";
485///   printTyVarMap( std::cout, tyVars );
486                        if ( isPolyVal( realParam->get_type(), tyVars ) ) {
487///     if ( dynamic_cast< PointerType *>( arg->get_type() ) ) {
488///       return new CastExpr( new VariableExpr( param ), arg->get_type()->clone() );
489///     } else {
490                                if ( dynamic_cast<TypeInstType *>(arg->get_type()) == NULL ) {
491                                        UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
492                                        deref->get_args().push_back( new CastExpr( new VariableExpr( param ), new PointerType( Type::Qualifiers(), arg->get_type()->clone() ) ) );
493                                        deref->get_results().push_back( arg->get_type()->clone() );
494                                        return deref;
495                                } // if
496///     }
497                        } // if
498                        return new VariableExpr( param );
499                }
500
501                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 ) {
502                        UniqueName paramNamer( "_p" );
503                        for ( ; param != paramEnd; ++param, ++arg, ++realParam ) {
504                                if ( (*param)->get_name() == "" ) {
505                                        (*param)->set_name( paramNamer.newName() );
506                                        (*param)->set_linkage( LinkageSpec::C );
507                                } // if
508                                adapteeApp->get_args().push_back( makeAdapterArg( *param, *arg, *realParam, tyVars ) );
509                        } // for
510                }
511
512
513
514                FunctionDecl *Pass1::makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars ) {
515                        FunctionType *adapterType = makeAdapterType( adaptee, tyVars );
516                        adapterType = ScrubTyVars::scrub( adapterType, tyVars );
517                        DeclarationWithType *adapteeDecl = adapterType->get_parameters().front();
518                        adapteeDecl->set_name( "_adaptee" );
519                        ApplicationExpr *adapteeApp = new ApplicationExpr( new CastExpr( new VariableExpr( adapteeDecl ), new PointerType( Type::Qualifiers(), realType ) ) );
520                        Statement *bodyStmt;
521 
522                        std::list< TypeDecl *>::iterator tyArg = realType->get_forall().begin();
523                        std::list< TypeDecl *>::iterator tyParam = adapterType->get_forall().begin();
524                        std::list< TypeDecl *>::iterator realTyParam = adaptee->get_forall().begin();
525                        for ( ; tyParam != adapterType->get_forall().end(); ++tyArg, ++tyParam, ++realTyParam ) {
526                                assert( tyArg != realType->get_forall().end() );
527                                std::list< DeclarationWithType *>::iterator assertArg = (*tyArg)->get_assertions().begin();
528                                std::list< DeclarationWithType *>::iterator assertParam = (*tyParam)->get_assertions().begin();
529                                std::list< DeclarationWithType *>::iterator realAssertParam = (*realTyParam)->get_assertions().begin();
530                                for ( ; assertParam != (*tyParam)->get_assertions().end(); ++assertArg, ++assertParam, ++realAssertParam ) {
531                                        assert( assertArg != (*tyArg)->get_assertions().end() );
532                                        adapteeApp->get_args().push_back( makeAdapterArg( *assertParam, *assertArg, *realAssertParam, tyVars ) );
533                                } // for
534                        } // for
535 
536                        std::list< DeclarationWithType *>::iterator arg = realType->get_parameters().begin();
537                        std::list< DeclarationWithType *>::iterator param = adapterType->get_parameters().begin();
538                        std::list< DeclarationWithType *>::iterator realParam = adaptee->get_parameters().begin();
539                        param++;                // skip adaptee parameter
540                        if ( realType->get_returnVals().empty() ) {
541                                addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
542                                bodyStmt = new ExprStmt( noLabels, adapteeApp );
543                        } else if ( isPolyVal( adaptee->get_returnVals().front()->get_type(), tyVars ) ) {
544                                if ( (*param)->get_name() == "" ) {
545                                        (*param)->set_name( "_ret" );
546                                        (*param)->set_linkage( LinkageSpec::C );
547                                } // if
548                                UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
549                                UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
550                                deref->get_args().push_back( new CastExpr( new VariableExpr( *param++ ), new PointerType( Type::Qualifiers(), realType->get_returnVals().front()->get_type()->clone() ) ) );
551                                assign->get_args().push_back( deref );
552                                addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
553                                assign->get_args().push_back( adapteeApp );
554                                bodyStmt = new ExprStmt( noLabels, assign );
555                        } else {
556                                // adapter for a function that returns a monomorphic value
557                                addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
558                                bodyStmt = new ReturnStmt( noLabels, adapteeApp );
559                        } // if
560                        CompoundStmt *adapterBody = new CompoundStmt( noLabels );
561                        adapterBody->get_kids().push_back( bodyStmt );
562                        std::string adapterName = makeAdapterName( mangleName );
563                        return new FunctionDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, adapterType, adapterBody, false, false );
564                }
565
566                void Pass1::passAdapters( ApplicationExpr * appExpr, FunctionType * functionType, const TyVarMap & exprTyVars ) {
567                        // collect a list of function types passed as parameters or implicit parameters (assertions)
568                        std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
569                        std::list< FunctionType *> functions;
570                        for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
571                                for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
572                                        findFunction( (*assert)->get_type(), functions, exprTyVars, needsAdapter );
573                                } // for
574                        } // for
575                        for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
576                                findFunction( (*arg)->get_type(), functions, exprTyVars, needsAdapter );
577                        } // for
578
579                        // parameter function types for which an appropriate adapter has been generated.  we cannot use the types
580                        // after applying substitutions, since two different parameter types may be unified to the same type
581                        std::set< std::string > adaptersDone;
582
583                        for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
584                                FunctionType *originalFunction = (*funType)->clone();
585                                FunctionType *realFunction = (*funType)->clone();
586                                std::string mangleName = SymTab::Mangler::mangle( realFunction );
587
588                                // only attempt to create an adapter or pass one as a parameter if we haven't already done so for this
589                                // pre-substitution parameter function type.
590                                if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
591                                        adaptersDone.insert( adaptersDone.begin(), mangleName );
592                                       
593                                        // apply substitution to type variables to figure out what the adapter's type should look like
594                                        assert( env );
595                                        env->apply( realFunction );
596                                        mangleName = SymTab::Mangler::mangle( realFunction ); 
597                                        mangleName += makePolyMonoSuffix( originalFunction, exprTyVars );
598
599                                        AdapterMap & adapters = Pass1::adapters.top();
600                                        AdapterMap::iterator adapter = adapters.find( mangleName );
601                                        if ( adapter == adapters.end() ) {
602                                                // adapter has not been created yet in the current scope, so define it
603                                                FunctionDecl *newAdapter = makeAdapter( *funType, realFunction, mangleName, exprTyVars );
604                                                adapter = adapters.insert( adapters.begin(), std::pair< std::string, DeclarationWithType *>( mangleName, newAdapter ) );
605                                                stmtsToAdd.push_back( new DeclStmt( noLabels, newAdapter ) );
606                                        } // if
607                                        assert( adapter != adapters.end() );
608
609                                        // add the appropriate adapter as a parameter
610                                        appExpr->get_args().push_front( new VariableExpr( adapter->second ) );
611                                } // if
612                        } // for
613                } // passAdapters
614
615                TypeInstType *isPolyPtr( Type *type, const TypeSubstitution *env, const TyVarMap &tyVars ) {
616                        if ( PointerType *ptr = dynamic_cast< PointerType *>( type ) ) {
617                                return isPolyType( ptr->get_base(), env, tyVars );
618                        } else if ( env ) {
619                                if ( TypeInstType *typeInst = dynamic_cast< TypeInstType *>( type ) ) {
620                                        if ( Type *newType = env->lookup( typeInst->get_name() ) ) {
621                                                return isPolyPtr( newType, env, tyVars );
622                                        } // if
623                                } // if
624                        } // if
625                        return 0;
626                }
627
628                TypeInstType *isPolyPtrPtr( Type *type, const TypeSubstitution *env, const TyVarMap &tyVars ) {
629                        if ( PointerType *ptr = dynamic_cast< PointerType *>( type ) ) {
630                                return isPolyPtr( ptr->get_base(), env, tyVars );
631                        } else if ( env ) {
632                                if ( TypeInstType *typeInst = dynamic_cast< TypeInstType *>( type ) ) {
633                                        if ( Type *newType = env->lookup( typeInst->get_name() ) ) {
634                                                return isPolyPtrPtr( newType, env, tyVars );
635                                        } // if
636                                } // if
637                        } // if
638                        return 0;
639                }
640
641                Expression *makeIncrDecrExpr( ApplicationExpr *appExpr, std::string polyName, bool isIncr ) {
642                        NameExpr *opExpr;
643                        if ( isIncr ) {
644                                opExpr = new NameExpr( "?+=?" );
645                        } else {
646                                opExpr = new NameExpr( "?-=?" );
647                        } // if
648                        UntypedExpr *addAssign = new UntypedExpr( opExpr );
649                        if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
650                                addAssign->get_args().push_back( address->get_arg() );
651                        } else {
652                                addAssign->get_args().push_back( appExpr->get_args().front() );
653                        } // if
654                        addAssign->get_args().push_back( new NameExpr( polyName ) );
655                        addAssign->get_results().front() = appExpr->get_results().front()->clone();
656                        if ( appExpr->get_env() ) {
657                                addAssign->set_env( appExpr->get_env() );
658                                appExpr->set_env( 0 );
659                        } // if
660                        appExpr->get_args().clear();
661                        delete appExpr;
662                        return addAssign;
663                }
664
665                Expression *Pass1::handleIntrinsics( ApplicationExpr *appExpr ) {
666                        if ( VariableExpr *varExpr = dynamic_cast< VariableExpr *>( appExpr->get_function() ) ) {
667                                if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
668                                        if ( varExpr->get_var()->get_name() == "?[?]" ) {
669                                                assert( ! appExpr->get_results().empty() );
670                                                assert( appExpr->get_args().size() == 2 );
671                                                TypeInstType *typeInst1 = isPolyPtr( appExpr->get_args().front()->get_results().front(), env, scopeTyVars );
672                                                TypeInstType *typeInst2 = isPolyPtr( appExpr->get_args().back()->get_results().front(), env, scopeTyVars );
673                                                assert( ! typeInst1 || ! typeInst2 );
674                                                UntypedExpr *ret = 0;
675                                                if ( typeInst1 || typeInst2 ) {
676                                                        ret = new UntypedExpr( new NameExpr( "?+?" ) );
677                                                } // if
678                                                if ( typeInst1 ) {
679                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
680                                                        multiply->get_args().push_back( appExpr->get_args().back() );
681                                                        multiply->get_args().push_back( new NameExpr( typeInst1->get_name() ) );
682                                                        ret->get_args().push_back( appExpr->get_args().front() );
683                                                        ret->get_args().push_back( multiply );
684                                                } else if ( typeInst2 ) {
685                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
686                                                        multiply->get_args().push_back( appExpr->get_args().front() );
687                                                        multiply->get_args().push_back( new NameExpr( typeInst2->get_name() ) );
688                                                        ret->get_args().push_back( multiply );
689                                                        ret->get_args().push_back( appExpr->get_args().back() );
690                                                } // if
691                                                if ( typeInst1 || typeInst2 ) {
692                                                        ret->get_results().push_front( appExpr->get_results().front()->clone() );
693                                                        if ( appExpr->get_env() ) {
694                                                                ret->set_env( appExpr->get_env() );
695                                                                appExpr->set_env( 0 );
696                                                        } // if
697                                                        appExpr->get_args().clear();
698                                                        delete appExpr;
699                                                        return ret;
700                                                } // if
701                                        } else if ( varExpr->get_var()->get_name() == "*?" ) {
702                                                assert( ! appExpr->get_results().empty() );
703                                                assert( ! appExpr->get_args().empty() );
704                                                if ( isPolyType( appExpr->get_results().front(), env, scopeTyVars ) ) {
705                                                        Expression *ret = appExpr->get_args().front();
706                                                        delete ret->get_results().front();
707                                                        ret->get_results().front() = appExpr->get_results().front()->clone();
708                                                        if ( appExpr->get_env() ) {
709                                                                ret->set_env( appExpr->get_env() );
710                                                                appExpr->set_env( 0 );
711                                                        } // if
712                                                        appExpr->get_args().clear();
713                                                        delete appExpr;
714                                                        return ret;
715                                                } // if
716                                        } else if ( varExpr->get_var()->get_name() == "?++" || varExpr->get_var()->get_name() == "?--" ) {
717                                                assert( ! appExpr->get_results().empty() );
718                                                assert( appExpr->get_args().size() == 1 );
719                                                if ( TypeInstType *typeInst = isPolyPtr( appExpr->get_results().front(), env, scopeTyVars ) ) {
720                                                        Type *tempType = appExpr->get_results().front()->clone();
721                                                        if ( env ) {
722                                                                env->apply( tempType );
723                                                        } // if
724                                                        ObjectDecl *newObj = makeTemporary( tempType );
725                                                        VariableExpr *tempExpr = new VariableExpr( newObj );
726                                                        UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
727                                                        assignExpr->get_args().push_back( tempExpr->clone() );
728                                                        if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
729                                                                assignExpr->get_args().push_back( address->get_arg()->clone() );
730                                                        } else {
731                                                                assignExpr->get_args().push_back( appExpr->get_args().front()->clone() );
732                                                        } // if
733                                                        CommaExpr *firstComma = new CommaExpr( assignExpr, makeIncrDecrExpr( appExpr, typeInst->get_name(), varExpr->get_var()->get_name() == "?++" ) );
734                                                        return new CommaExpr( firstComma, tempExpr );
735                                                } // if
736                                        } else if ( varExpr->get_var()->get_name() == "++?" || varExpr->get_var()->get_name() == "--?" ) {
737                                                assert( ! appExpr->get_results().empty() );
738                                                assert( appExpr->get_args().size() == 1 );
739                                                if ( TypeInstType *typeInst = isPolyPtr( appExpr->get_results().front(), env, scopeTyVars ) ) {
740                                                        return makeIncrDecrExpr( appExpr, typeInst->get_name(), varExpr->get_var()->get_name() == "++?" );
741                                                } // if
742                                        } else if ( varExpr->get_var()->get_name() == "?+?" || varExpr->get_var()->get_name() == "?-?" ) {
743                                                assert( ! appExpr->get_results().empty() );
744                                                assert( appExpr->get_args().size() == 2 );
745                                                TypeInstType *typeInst1 = isPolyPtr( appExpr->get_args().front()->get_results().front(), env, scopeTyVars );
746                                                TypeInstType *typeInst2 = isPolyPtr( appExpr->get_args().back()->get_results().front(), env, scopeTyVars );
747                                                if ( typeInst1 && typeInst2 ) {
748                                                        UntypedExpr *divide = new UntypedExpr( new NameExpr( "?/?" ) );
749                                                        divide->get_args().push_back( appExpr );
750                                                        divide->get_args().push_back( new NameExpr( typeInst1->get_name() ) );
751                                                        divide->get_results().push_front( appExpr->get_results().front()->clone() );
752                                                        if ( appExpr->get_env() ) {
753                                                                divide->set_env( appExpr->get_env() );
754                                                                appExpr->set_env( 0 );
755                                                        } // if
756                                                        return divide;
757                                                } else if ( typeInst1 ) {
758                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
759                                                        multiply->get_args().push_back( appExpr->get_args().back() );
760                                                        multiply->get_args().push_back( new NameExpr( typeInst1->get_name() ) );
761                                                        appExpr->get_args().back() = multiply;
762                                                } else if ( typeInst2 ) {
763                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
764                                                        multiply->get_args().push_back( appExpr->get_args().front() );
765                                                        multiply->get_args().push_back( new NameExpr( typeInst2->get_name() ) );
766                                                        appExpr->get_args().front() = multiply;
767                                                } // if
768                                        } else if ( varExpr->get_var()->get_name() == "?+=?" || varExpr->get_var()->get_name() == "?-=?" ) {
769                                                assert( ! appExpr->get_results().empty() );
770                                                assert( appExpr->get_args().size() == 2 );
771                                                TypeInstType *typeInst = isPolyPtr( appExpr->get_results().front(), env, scopeTyVars );
772                                                if ( typeInst ) {
773                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
774                                                        multiply->get_args().push_back( appExpr->get_args().back() );
775                                                        multiply->get_args().push_back( new NameExpr( typeInst->get_name() ) );
776                                                        appExpr->get_args().back() = multiply;
777                                                } // if
778                                        } // if
779                                        return appExpr;
780                                } // if
781                        } // if
782                        return 0;
783                }
784
785                Expression *Pass1::mutate( ApplicationExpr *appExpr ) {
786                        // std::cerr << "mutate appExpr: ";
787                        // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
788                        //      std::cerr << i->first << " ";
789                        // }
790                        // std::cerr << "\n";
791                        bool oldUseRetval = useRetval;
792                        useRetval = false;
793                        appExpr->get_function()->acceptMutator( *this );
794                        mutateAll( appExpr->get_args(), *this );
795                        useRetval = oldUseRetval;
796 
797                        assert( ! appExpr->get_function()->get_results().empty() );
798                        PointerType *pointer = dynamic_cast< PointerType *>( appExpr->get_function()->get_results().front() );
799                        assert( pointer );
800                        FunctionType *function = dynamic_cast< FunctionType *>( pointer->get_base() );
801                        assert( function );
802 
803                        if ( Expression *newExpr = handleIntrinsics( appExpr ) ) {
804                                return newExpr;
805                        } // if
806 
807                        Expression *ret = appExpr;
808 
809                        std::list< Expression *>::iterator arg = appExpr->get_args().begin();
810                        std::list< Expression *>::iterator paramBegin = appExpr->get_args().begin();
811 
812                        std::string typeName;
813                        if ( isPolyRet( function, typeName ) ) {
814                                ret = addPolyRetParam( appExpr, function, typeName, arg );
815                        } else if ( needsAdapter( function, scopeTyVars ) ) {
816                                // std::cerr << "needs adapter: ";
817                                // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
818                                //      std::cerr << i->first << " ";
819                                // }
820                                // std::cerr << "\n";
821                                // change the application so it calls the adapter rather than the passed function
822                                ret = applyAdapter( appExpr, function, arg, scopeTyVars );
823                        } // if
824                        arg = appExpr->get_args().begin();
825 
826                        TyVarMap exprTyVars;
827                        makeTyVarMap( function, exprTyVars );
828 
829                        passTypeVars( appExpr, arg, exprTyVars );
830                        addInferredParams( appExpr, function, arg, exprTyVars );
831
832                        arg = paramBegin;
833 
834                        boxParams( appExpr, function, arg, exprTyVars );
835
836                        passAdapters( appExpr, function, exprTyVars );
837
838                        return ret;
839                }
840
841                Expression *Pass1::mutate( UntypedExpr *expr ) {
842                        if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), env, scopeTyVars ) ) {
843                                if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
844                                        if ( name->get_name() == "*?" ) {
845                                                Expression *ret = expr->get_args().front();
846                                                expr->get_args().clear();
847                                                delete expr;
848                                                return ret->acceptMutator( *this );
849                                        } // if
850                                } // if
851                        } // if
852                        return PolyMutator::mutate( expr );
853                }
854
855                Expression *Pass1::mutate( AddressExpr *addrExpr ) {
856                        assert( ! addrExpr->get_arg()->get_results().empty() );
857                        addrExpr->set_arg( mutateExpression( addrExpr->get_arg() ) );
858                        if ( isPolyType( addrExpr->get_arg()->get_results().front(), env, scopeTyVars ) ) {
859                                Expression *ret = addrExpr->get_arg();
860                                delete ret->get_results().front();
861                                ret->get_results().front() = addrExpr->get_results().front()->clone();
862                                addrExpr->set_arg( 0 );
863                                delete addrExpr;
864                                return ret;
865                        } else {
866                                return addrExpr;
867                        } // if
868                }
869
870                Statement * Pass1::mutate(ReturnStmt *retStmt) {
871                        // a cast expr on a polymorphic return value is either redundant or invalid
872                        while ( CastExpr *castExpr = dynamic_cast< CastExpr *>( retStmt->get_expr() ) ) {
873                                retStmt->set_expr( castExpr->get_arg() );
874                                retStmt->get_expr()->set_env( castExpr->get_env() );
875                                castExpr->set_env( 0 );
876                                castExpr->set_arg( 0 );
877                                delete castExpr;
878                        }
879                        if ( retval && retStmt->get_expr() ) {
880                                assert( ! retStmt->get_expr()->get_results().empty() );
881                                if ( retStmt->get_expr()->get_results().front()->get_isLvalue() ) {
882///       retStmt->set_expr( mutateExpression( retStmt->get_expr() ) );
883                                        TypeInstType *typeInst = dynamic_cast< TypeInstType *>( retval->get_type() );
884                                        assert( typeInst );
885                                        std::map< std::string, DeclarationWithType *>::const_iterator assignIter = assignOps.find( typeInst->get_name() );
886                                        if ( assignIter == assignOps.end() ) {
887                                                throw SemanticError( "Attempt to return dtype or ftype object in ", retStmt->get_expr() );
888                                        } // if
889                                        ApplicationExpr *assignExpr = new ApplicationExpr( new VariableExpr( assignIter->second ) );
890                                        Expression *retParm = new NameExpr( retval->get_name() );
891                                        retParm->get_results().push_back( new PointerType( Type::Qualifiers(), retval->get_type()->clone() ) );
892                                        assignExpr->get_args().push_back( retParm );
893                                        assignExpr->get_args().push_back( retStmt->get_expr() );
894                                        stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( assignExpr ) ) );
895                                } else {
896                                        useRetval = true;
897                                        stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( retStmt->get_expr() ) ) );
898                                        useRetval = false;
899                                } // if
900                                retStmt->set_expr( 0 );
901                        } else {
902                                retStmt->set_expr( mutateExpression( retStmt->get_expr() ) );
903                        } // if
904                        return retStmt;
905                }
906
907                Type * Pass1::mutate( PointerType *pointerType ) {
908                        TyVarMap oldtyVars = scopeTyVars;
909                        makeTyVarMap( pointerType, scopeTyVars );
910 
911                        Type *ret = Mutator::mutate( pointerType );
912 
913                        scopeTyVars = oldtyVars;
914                        return ret;
915                }
916
917                Type * Pass1::mutate( FunctionType *functionType ) {
918                        TyVarMap oldtyVars = scopeTyVars;
919                        makeTyVarMap( functionType, scopeTyVars );
920 
921                        Type *ret = Mutator::mutate( functionType );
922 
923                        scopeTyVars = oldtyVars;
924                        return ret;
925                }
926
927                void Pass1::doBeginScope() {
928                        // push a copy of the current map
929                        adapters.push(adapters.top());
930                }
931
932                void Pass1::doEndScope() {
933                        adapters.pop();
934                }
935
936////////////////////////////////////////// Pass2 ////////////////////////////////////////////////////
937
938                Pass2::Pass2() {}
939
940                void Pass2::addAdapters( FunctionType *functionType ) {
941                        std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
942                        std::list< FunctionType *> functions;
943                        for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
944                                Type *orig = (*arg)->get_type();
945                                findAndReplaceFunction( orig, functions, scopeTyVars, needsAdapter );
946                                (*arg)->set_type( orig );
947                        }
948                        std::set< std::string > adaptersDone;
949                        for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
950                                std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
951                                if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
952                                        std::string adapterName = makeAdapterName( mangleName );
953                                        paramList.push_front( new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) );
954                                        adaptersDone.insert( adaptersDone.begin(), mangleName );
955                                }
956                        }
957///  deleteAll( functions );
958                }
959
960                template< typename DeclClass >
961                DeclClass * Pass2::handleDecl( DeclClass *decl, Type *type ) {
962                        DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
963
964                        return ret;
965                }
966
967                DeclarationWithType * Pass2::mutate( FunctionDecl *functionDecl ) {
968                        return handleDecl( functionDecl, functionDecl->get_functionType() );
969                }
970
971                ObjectDecl * Pass2::mutate( ObjectDecl *objectDecl ) {
972                        return handleDecl( objectDecl, objectDecl->get_type() );
973                }
974
975                TypeDecl * Pass2::mutate( TypeDecl *typeDecl ) {
976                        scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
977                        if ( typeDecl->get_base() ) {
978                                return handleDecl( typeDecl, typeDecl->get_base() );
979                        } else {
980                                return Mutator::mutate( typeDecl );
981                        }
982                }
983
984                TypedefDecl * Pass2::mutate( TypedefDecl *typedefDecl ) {
985                        return handleDecl( typedefDecl, typedefDecl->get_base() );
986                }
987
988                Type * Pass2::mutate( PointerType *pointerType ) {
989                        TyVarMap oldtyVars = scopeTyVars;
990                        makeTyVarMap( pointerType, scopeTyVars );
991 
992                        Type *ret = Mutator::mutate( pointerType );
993 
994                        scopeTyVars = oldtyVars;
995                        return ret;
996                }
997
998                Type *Pass2::mutate( FunctionType *funcType ) {
999                        TyVarMap oldtyVars = scopeTyVars;
1000                        makeTyVarMap( funcType, scopeTyVars );
1001 
1002                        std::string typeName;
1003                        if ( isPolyRet( funcType, typeName ) ) {
1004                                DeclarationWithType *ret = funcType->get_returnVals().front();
1005                                ret->set_type( new PointerType( Type::Qualifiers(), ret->get_type() ) );
1006                                funcType->get_parameters().push_front( ret );
1007                                funcType->get_returnVals().pop_front();
1008                        }
1009 
1010                        std::list< DeclarationWithType *>::iterator last = funcType->get_parameters().begin();
1011                        std::list< DeclarationWithType *> inferredParams;
1012                        ObjectDecl *newObj = new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), 0 );
1013//   ObjectDecl *newFunPtr = new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) ), 0 );
1014                        for ( std::list< TypeDecl *>::const_iterator tyParm = funcType->get_forall().begin(); tyParm != funcType->get_forall().end(); ++tyParm ) {
1015                                ObjectDecl *thisParm;
1016                                // add all size parameters to parameter list
1017                                if ( (*tyParm)->get_kind() == TypeDecl::Any ) {
1018                                        thisParm = newObj->clone();
1019                                        thisParm->set_name( (*tyParm)->get_name() );
1020                                        last = funcType->get_parameters().insert( last, thisParm );
1021                                        ++last;
1022                                }
1023                                // move all assertions into parameter list
1024                                for ( std::list< DeclarationWithType *>::iterator assert = (*tyParm)->get_assertions().begin(); assert != (*tyParm)->get_assertions().end(); ++assert ) {
1025//      *assert = (*assert)->acceptMutator( *this );
1026                                        inferredParams.push_back( *assert );
1027                                }
1028                                (*tyParm)->get_assertions().clear();
1029                        }
1030                        delete newObj;
1031                        funcType->get_parameters().splice( last, inferredParams );
1032                        addAdapters( funcType );
1033                        mutateAll( funcType->get_returnVals(), *this );
1034                        mutateAll( funcType->get_parameters(), *this );
1035 
1036                        scopeTyVars = oldtyVars;
1037                        return funcType;
1038                }
1039
1040////////////////////////////////////////// Pass3 ////////////////////////////////////////////////////
1041
1042                template< typename DeclClass >
1043                DeclClass * Pass3::handleDecl( DeclClass *decl, Type *type ) {
1044                        TyVarMap oldtyVars = scopeTyVars;
1045                        makeTyVarMap( type, scopeTyVars );
1046 
1047                        DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
1048                        ScrubTyVars::scrub( decl, scopeTyVars );
1049
1050                        scopeTyVars = oldtyVars;
1051                        return ret;
1052                }
1053
1054                ObjectDecl * Pass3::mutate( ObjectDecl *objectDecl ) {
1055                        return handleDecl( objectDecl, objectDecl->get_type() );
1056                }
1057
1058                DeclarationWithType * Pass3::mutate( FunctionDecl *functionDecl ) {
1059                        return handleDecl( functionDecl, functionDecl->get_functionType() );
1060                }
1061
1062                TypedefDecl * Pass3::mutate( TypedefDecl *typedefDecl ) {
1063                        return handleDecl( typedefDecl, typedefDecl->get_base() );
1064                }
1065
1066                TypeDecl * Pass3::mutate( TypeDecl *typeDecl ) {
1067//   Initializer *init = 0;
1068//   std::list< Expression *> designators;
1069//   scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1070//   if ( typeDecl->get_base() ) {
1071//     init = new SimpleInit( new SizeofExpr( handleDecl( typeDecl, typeDecl->get_base() ) ), designators );
1072//   }
1073//   return new ObjectDecl( typeDecl->get_name(), Declaration::Extern, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::UnsignedInt ), init );
1074
1075                        scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1076                        return Mutator::mutate( typeDecl );
1077                }
1078
1079                Type * Pass3::mutate( PointerType *pointerType ) {
1080                        TyVarMap oldtyVars = scopeTyVars;
1081                        makeTyVarMap( pointerType, scopeTyVars );
1082 
1083                        Type *ret = Mutator::mutate( pointerType );
1084 
1085                        scopeTyVars = oldtyVars;
1086                        return ret;
1087                }
1088
1089                Type * Pass3::mutate( FunctionType *functionType ) {
1090                        TyVarMap oldtyVars = scopeTyVars;
1091                        makeTyVarMap( functionType, scopeTyVars );
1092 
1093                        Type *ret = Mutator::mutate( functionType );
1094 
1095                        scopeTyVars = oldtyVars;
1096                        return ret;
1097                }
1098
1099                Statement *Pass3::mutate( DeclStmt *declStmt ) {
1100                        if ( ObjectDecl *objectDecl = dynamic_cast< ObjectDecl *>( declStmt->get_decl() ) ) {
1101                                if ( isPolyVal( objectDecl->get_type(), scopeTyVars ) ) {
1102                                        // change initialization of a polymorphic value object
1103                                        // to allocate storage with alloca
1104                                        TypeInstType *typeInst = dynamic_cast< TypeInstType *>( objectDecl->get_type() );
1105                                        assert( typeInst );
1106                                        UntypedExpr *alloc = new UntypedExpr( new NameExpr( "__builtin_alloca" ) );
1107                                        alloc->get_args().push_back( new NameExpr( typeInst->get_name() ) );
1108
1109                                        delete objectDecl->get_init();
1110
1111                                        std::list<Expression*> designators;
1112                                        objectDecl->set_init( new SingleInit( alloc, designators ) );
1113                                }
1114                        }
1115                        return Mutator::mutate( declStmt );
1116                }
1117        } // anonymous namespace
1118} // namespace GenPoly
1119
1120// Local Variables: //
1121// tab-width: 4 //
1122// mode: c++ //
1123// compile-command: "make install" //
1124// End: //
Note: See TracBrowser for help on using the repository browser.