source: src/GenPoly/Box.cc @ bd85400

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 bd85400 was bd85400, checked in by Peter A. Buhr <pabuhr@…>, 8 years ago

remove offsetof keyword, parser 0/1 names as structure fields, update examples to new stdlib, rename algorithms to stdlib, extend stdlib, use correct type for box parameters

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