source: src/GenPoly/Box.cc @ 000b914

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decaygc_noraiijacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newstringwith_gc
Last change on this file since 000b914 was 000b914, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Merge branch 'master' of plg.uwaterloo.ca:/u/cforall/software/cfa/cfa-cc

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